diff --git "a/2238.jsonl" "b/2238.jsonl" new file mode 100644--- /dev/null +++ "b/2238.jsonl" @@ -0,0 +1,638 @@ +{"seq_id":"177374542","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfracs = [30, 15, 45, 10]\ncolors = ['b', 'g', 'r', 'w']\n\nplt.pie(fracs, colors = colors, labels=['A', 'B', 'C', 'D'])\n\nplt.savefig(\"Pie.png\")\nplt.show()","sub_path":"Python/2_Matplotlib/Examples/13_Pie.py","file_name":"13_Pie.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"300861052","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\ndef exchange(currency_from,currency_to,amount_from): \n '''return the amount of money in currenct_to based on currency_from,the given amount of money in currency_from\n and the real time exchange rate.'''\n from urllib.request import urlopen\n doc = urlopen('http://cs1110.cs.cornell.edu/2016fa/a1server.php?from=%s&to=%s&amt=%.2f'%(currency_from,currency_to,amount_from))\n docstr = doc.read()\n doc.close()\n jstr = docstr.decode('ascii')#transfer the result into string\n if \"true\" in jstr:\n start=jstr.find('\"to\" : ')+8\n end=start+1\n while ord(jstr[end])==46 or 48<=ord(jstr[end])<=57:\n end=end+1\n answer=jstr[start:end]\n return answer\n else:\n return \"Wrong!\"\n \ndef main():\n currency_from=input(\"\")\n currency_to=input(\"\")\n amount_from=float(input(\"\"))\n amount=exchange(currency_from,currency_to,amount_from)\n if amount==\"Wrong!\":\n print(\"Wrong!\")\n else:\n print(amount)#main body, get input and print out result\n \ndef test_get_from():\n '''testing function'''\n assert exchange(\"USD\",\"EUR\",2.5)==\"2.0952375\"\n \ndef testB():\n '''testing function'''\n assert exchange(\"USD\",\"EUR\",2.7)==\"2.2628565\"\n \ndef testC():\n '''testing function'''\n assert exchange(\"EUR\",\"USD\",2.5)==\"2.9829553928851\"\n \ndef testall():\n '''test a few specific cases.'''\n test_get_from()\n testB()\n testC()\n print(\"All tests passed.\")\n \nif \"__name__\"==\"__main__\":\n main()\n\n","sub_path":"pyassign2/currency.py","file_name":"currency.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"139551125","text":"dogs = ['Rover', 'Max', 'Holly'] \t\nfor dog in dogs:\n\tdog = dog + '\\'s'\n\tprint(dog)\t\t\nprint(dogs)\nfor letter in \"word\":\n\tprint(letter + \"uba\")\n\nages_later = []\t\t\nyears = 10\nages = [12, 15, 17]\nfor age in ages:\n\tage +=years\n\tages_later.append(age)\nprint(ages_later)\n\nlist(range(5))\n\nfor x in range(5):\n\tprint(x**2)\n\nages_later = []\nyears = 10\nfor age in range(12,18):\n\tage +=years\n\tages_later.append(age)\nprint(ages_later)\nprint (range(len(dogs)))\ndogs = ['Rover', 'Holly','Dulcie','Spot'] \t\nfor i in range(len(dogs)):\n\tdogs[i] = dogs[i] + '\\'s'\nprint(dogs)\n\ncards = ['ace', 2,3,4,'queen']\nfor i in range(len(cards)):\n\tcards = cards[i:] + cards[:i]\n\tprint(cards)\n\nevens = []\nfor x in range(100):\n\tif x%2 == 0:\n\t\tevens.append(x)\nprint(evens)\n\nfor i, day in enumerate(['Mon', 'Tue', 'Wed', 'Thurs', 'Fri']):\n\tprint(i, day)\n\nfood = 0\nwhile food < 5:\n\thungry = input(\"Are you hungry? Type Y or N \")\n\tif hungry == \"Y\":\n\t\tprint(\"Here is a treat for you.\")\n\t\tfood += 1\nprint(\"I feel full\")\n\nfood = 0\nwhile food < 5:\n\thungry = input('Are you hungry? Type Y or N ')\n\tif hungry == 'Y':\n\t\tprint('Here is a treat for you.')\n\t\tfood += 1\n\telif hungry == \"N\":\n\t\tbreak\nprint('I am full')\n\t\n\n\ndogs = ['Holly', 'Max', 'Sadie', 'Joey']\nwhile dogs:\t\t\t\t\t\n\tprint(dogs.pop(0) + \" barks.\")\t\t\n\tprint(dogs)\n\ndogs = ['Holly','Max','Sadie','Joey']\ni = 0\nwhile len(dogs) > 1:\n\tif dogs[i] == 'Sadie':\n\t\ti=1\n\t\tcontinue\n\tprint(dogs.pop(i) + \" barks\")\n\tprint(dogs)\n\nx = 10\nwhile x:\t\t\t\n\tx = x-1\n\tif x % 2 != 0:\n\t\tcontinue\n\tprint(x)\n\nx = 11\nwhile x > 10:\n\tprint(\"uh oh\")\n\nwhile True:\n\tprint(\"uh oh\")\n\ndogs = ['Rover', 'Max', 'Holly']\ntoys = ['bone', 'squirrel']\nfor dog in dogs:\n\tfor toy in toys:\n\t\tprint('That is ' + dog + '\\'s ' + toy + '.')\n\t\n\tprint(\"That is %s\\'s %s.\" % (dog,toy))\n\nitems = [\"aaa\", 111, (4,5), 2.01]\ntests = [(4,5), 3.14]\nfor thing in tests:\n for item in items:\n if item == thing:\n print(str(thing) + \"was found\")\n\n\t\n\n","sub_path":"Loops.py","file_name":"Loops.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"215617967","text":"def solution(name):\n answer = 0\n \n change = []\n for alphabet in name:\n change.append(min(ord(alphabet)-ord('A'), ord('Z')-ord(alphabet)+1))\n \n i = 0\n while True:\n answer += change[i]\n change[i] = 0\n if sum(change) == 0:\n break\n \n left, right = 1, 1\n while change[i-left] == 0:\n left += 1\n while change[i+right] == 0:\n right += 1\n \n answer += min(left, right)\n i += -left if left < right else right\n \n return answer","sub_path":"greedy/42860.py","file_name":"42860.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"538313820","text":"#!/usr/bin/env python\r\n#-*- coding:utf-8 -*-\r\n\r\nimport threading\r\nimport socket\r\nimport struct\r\nfrom enum import Enum\r\nfrom DataConnet import CData\r\n\r\n\r\n# 消息的类型\r\nclass EnumMessageType(Enum):\r\n ANONYMOUS = 1\r\n CHAT = 2\r\n ONE2ONE = 3\r\n REGISTER = 4\r\n LOGIN = 5\r\n ADDFRIEND = 6\r\n SEARCHUSER = 7\r\n FILETRANS = 8\r\n MSGERCORD = 9\r\n UPDATEUSER = 10\r\n\r\nclass CServer():\r\n DB = CData()\r\n def __init__(self,ip,port):\r\n ADDR=(ip,port)\r\n # 初始化服务器端端口开始监听端口\r\n # Create a TCP/IP\r\n self.ServSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.ServSocket.bind(ADDR)\r\n # Listen for incoming connections\r\n self.ServSocket.listen(5)\r\n # 将服务器端套接字加入监听列表\r\n print(\"服务器套接字启动成功\")\r\n\r\n def Run(self):\r\n self.AcceptSelector()\r\n\r\n def AcceptSelector(self):\r\n while True:\r\n socketClient,addrClient= self.ServSocket.accept()\r\n\r\n ##将客户端加入创建字典中\r\n #CServer.dictClient[socketClient]=socketClient\r\n #为新加入的客户端创建线程\r\n t=threading.Thread(target=self.__ClientProc__,args=(socketClient,))\r\n t.start()\r\n print(\"IP:%s 接入服务器\"%addrClient[0])\r\n\r\n def __ClientProc__(self,s):\r\n while True:\r\n try:\r\n #解包对应消息进行对应处理\r\n message=s.recv(CServer.BUFSIZE+10)\r\n message_type,=struct.unpack(\"i\",message[:4])\r\n CServer.dictFun[message_type](s,message)\r\n except Exception as i:\r\n #本线程异常则广播给其他客户端\r\n print(i)\r\n\r\n name = CServer.dictClient.get(s)\r\n if name==None:\r\n return\r\n s.close()\r\n name=CServer.dictClient.pop(s)\r\n print(\"客户端退出:用户名:\"+name)\r\n CServer.__UpdateUser(s,False,name)\r\n return\r\n\r\n def __ChatForAnonymous__(s, msg):\r\n dwLen,=struct.unpack(\"L\",msg[4:8])\r\n buf,=struct.unpack(\"%ds\"%dwLen,msg[8:8+dwLen])\r\n name=buf.decode(\"gb2312\")\r\n print(name+\" 加入聊天室\")\r\n CServer.dictClient[s]=name.rstrip('\\0')\r\n for i in CServer.dictClient:\r\n i.send(msg)\r\n CServer.__UpdateUser(s,True,name)\r\n\r\n def __UpdateUser(s, bAdd, name):\r\n try:\r\n #给其余所有人发送广播消息\r\n message_type=EnumMessageType.UPDATEUSER\r\n data=name.encode(\"gb2312\")\r\n message_len=len(data)\r\n message=struct.pack(\"lll2040s\",message_type.value,bAdd,message_len,data)\r\n\r\n for i in CServer.dictClient:\r\n if i==s:\r\n continue\r\n i.send(message)\r\n\r\n if bAdd==False:\r\n return\r\n #给新用户发送在线的客户名\r\n for i in CServer.dictClient:\r\n if i==s:\r\n continue\r\n data=CServer.dictClient[i].encode(\"gb2312\")\r\n message_len=len(data)\r\n message=struct.pack(\"lll2040s\",message_type.value,bAdd,message_len,data)\r\n s.send(message)\r\n except:\r\n return\r\n\r\n def __ChatForChat__(s, msg):\r\n # dwLen,=struct.unpack(\"L\",msg[4:8])\r\n # buf,=struct.unpack(\"%ds\"%dwLen,msg[8:8+dwLen])\r\n #\r\n # #解密并显示在服务器端\r\n # buf=bytearray(buf)\r\n # for i in range(dwLen):\r\n # buf[i]^=15\r\n # data=buf.decode(\"gb2312\")\r\n # IP,other=s.getpeername()\r\n # print(\"%s : %s\"%(IP,data))\r\n # #\r\n\r\n #给除s以外的客户端发消息\r\n for i in CServer.dictClient:\r\n if i == s:\r\n continue\r\n i.send(msg)\r\n\r\n def __ChatForOne2One__(s, msg):\r\n name,=struct.unpack(\"50s\",msg[4:54])\r\n name=bytes(name).decode(encoding=\"gb2312\").rstrip('\\0')\r\n # name=name.encode(\"gb2312\").rstrip('\\0')\r\n #将A发来的消息进行替换\r\n for i in CServer.dictClient:\r\n if name == CServer.dictClient[i]:\r\n data=struct.pack(\"50s\",CServer.dictClient[s].encode(\"gb2312\"))\r\n i.send(msg[:4]+data+msg[54:])\r\n break\r\n\r\n #将聊天记录保存到数据库\r\n msgFrom=CServer.dictClient[s]\r\n msgFrom = msgFrom.encode(\"utf-8\")\r\n msgTo,=struct.unpack(\"50s\",msg[4:54])\r\n msgTo=msgTo.decode(\"gb2312\").rstrip('\\0')\r\n msgTo = msgTo.encode(\"utf-8\")\r\n #消息内容\r\n msginfo,=struct.unpack(\"1024s\",msg[54:54+1024])\r\n msginfo=msginfo.decode(\"gb2312\").rstrip('\\0')\r\n msginfo=msginfo.encode(\"utf-8\")\r\n\r\n #添加聊天记录\r\n CServer.DB.insert(\"insert into msgInfo(userfrom,userto,msgcontent) values(%s,%s,%s)\",(msgFrom,msgTo,msginfo))\r\n\r\n def __ChatForLogin__(s, msg):\r\n #解包\r\n name,=struct.unpack(\"50s\",msg[4:54])\r\n pwd,=struct.unpack(\"50s\",msg[54:104])\r\n #name=name.decode(\"gb2312\".rstrip('\\0'))\r\n #pwd = pwd.decode(\"gb2312\".rstrip('\\0'))\r\n name=name.decode(\"gb2312\").rstrip('\\0')\r\n pwd = pwd.decode(\"gb2312\").rstrip('\\0')\r\n #构造查询语句\r\n result=CServer.DB.query(\"select * from userinfo where name=%s and pwd=%s\",(name,pwd))\r\n # 返回登录结果\r\n message_type = EnumMessageType.LOGIN\r\n message_len = 50\r\n message = \"\"\r\n if result == None or result[1]==0:\r\n message = \"登录失败!\".encode(\"gb2312\")\r\n else:\r\n message = \"登录成功!\".encode(\"gb2312\")\r\n print(\"客户端登录:用户名:\"+name)\r\n CServer.dictClient[s] =name\r\n data = struct.pack(\"l2048s\", message_type.value, message)\r\n s.send(data)\r\n\r\n def __ChatForRegister__(s, msg):\r\n #解包\r\n name,=struct.unpack(\"50s\",msg[4:54])\r\n pwd,=struct.unpack(\"50s\",msg[54:104])\r\n name=name.decode(\"gb2312\").rstrip('\\0')\r\n pwd=pwd.decode('gb2312').rstrip('\\0')\r\n result =CServer.DB.insert(\"insert into userinfo(name,pwd) VALUES (%s,%s)\",(name,pwd))\r\n\r\n #返回注册结果\r\n message_type=EnumMessageType.REGISTER\r\n message_len=50\r\n message = \"\"\r\n if result==None:\r\n message = \"注册失败!\".encode(\"gb2312\")\r\n else:\r\n message = \"注册成功!\".encode(\"gb2312\")\r\n data=struct.pack(\"l2048s\",message_type.value,message)\r\n s.send(data)\r\n\r\n def __ChatForAddFriend__(s, msg):\r\n #解包\r\n name,=struct.unpack(\"50s\",msg[4:54])\r\n frd,=struct.unpack(\"50s\",msg[54:104])\r\n name=name.decode(\"gb2312\").rstrip('\\0')\r\n frd=frd.decode(\"gb2312\").rstrip('\\0')\r\n result = CServer.DB.insert(\"insert into userfriend (name,friend) VALUES (%s,%s)\", (name, frd))\r\n\r\n # 返回添加结果\r\n message_type = EnumMessageType.ADDFRIEND\r\n message_len = 50\r\n message = \"\"\r\n if result == None:\r\n message = \"添加好友失败!\".encode(\"gb2312\")\r\n else:\r\n message = \"添加好友成功!\".encode(\"gb2312\")\r\n data = struct.pack(\"l2048s\", message_type.value, message)\r\n s.send(data)\r\n\r\n def __ChatForSearchUser__(s, msg):\r\n #解包\r\n try:\r\n name, = struct.unpack(\"50s\", msg[4:54])\r\n name = name.decode(\"gb2312\").rstrip('\\0')\r\n dbname=name.encode(\"utf-8\")\r\n result = CServer.DB.query(\"select name from userinfo where name=%s\", (dbname,))\r\n except Exception as theEx:\r\n print(theEx)\r\n #返回搜索结果\r\n message_type=EnumMessageType.SEARCHUSER\r\n message_len=50\r\n message=\"\"\r\n if result==None or result[1]==0:\r\n message=\"查无此人!\".encode(\"gb2312\")\r\n else:\r\n if name in CServer.dictClient.values():\r\n message=\"用户在线,请双击列表内用户名1V1聊天!\".encode(\"gb2312\")\r\n else:\r\n message=\"用户不在线!\".encode(\"gb2312\")\r\n\r\n data=struct.pack(\"l2048s\",message_type.value,message)\r\n s.send(data)\r\n\r\n def __ChatForGetMsgRecord__(s, msg):\r\n name = CServer.dictClient[s]\r\n #查询所有消息\r\n result=CServer.DB.query(\"select * from msgInfo where userfrom=%s or userto=%s\",(name,name))\r\n if result==None or result[1]==0:\r\n return\r\n\r\n message_type=EnumMessageType.MSGERCORD\r\n for i in range(result[1]):\r\n #可以在服务器端显示,此处不做此操作\r\n #逐个消费发给客户端S\r\n try:\r\n msgFrom=bytes(result[0][i][0]).decode(\"utf-8\").rstrip('\\0')\r\n msgFrom=msgFrom.encode(\"gb2312\")\r\n msgTo = bytes(result[0][i][1]).decode(\"utf-8\").rstrip('\\0')\r\n msgTo = msgTo.encode(\"gb2312\")\r\n msgContent = bytes(result[0][i][2]).decode(\"utf-8\").rstrip('\\0')\r\n msgContent = msgContent.encode(\"gb2312\")\r\n data=struct.pack(\"l50s50s1948s\",message_type.value,msgFrom,msgTo,msgContent)\r\n s.send(data)\r\n except Exception as a:\r\n print(a)\r\n #发送END过去,表示聊天记录已发送完毕\r\n msgContent=\"~~~end~~~\".encode(\"gb2312\")\r\n data=struct.pack(\"l2048s\",message_type.value,msgContent)\r\n s.send(data)\r\n\r\n\r\n #类变量根据客户端传来的消息类型调用对应的函数\r\n dictFun={\r\n 1:__ChatForAnonymous__,\r\n 2:__ChatForChat__,\r\n 3:__ChatForOne2One__,\r\n 4:__ChatForRegister__,\r\n 5:__ChatForLogin__,\r\n 6:__ChatForAddFriend__,\r\n 7:__ChatForSearchUser__,\r\n 9:__ChatForGetMsgRecord__\r\n }\r\n\r\n BUFSIZE=2048+4#最大传输字节数\r\n dictClient={}\r\n\r\n\r\nServ=CServer('',5555)\r\nServ.Run()\r\n","sub_path":"Server/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":10070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"318724209","text":"file=open(\"C:/Users/omiro/OneDrive/Υπολογιστής/file.txt\",\"r\")\nPOL=[]\nTHER=[]\nlines=file.readlines()\nfor i in range(0,20,2):\n x=str(lines[i])\n POL.append(x)\nfor i in range(1,20,2):\n x=int(lines[i])\n THER.append(x)\nmesos=0\nfor i in THER:\n mesos=mesos+i\n temp=i\nmesos=mesos/temp\nfor i in range(0,10):\n for j in range(0,10-i-1):\n if THER[j]>THER[j+1]:\n THER[j],THER[j+1]=THER[j+1],THER[j]\n POL[j],POL[j+1]=POL[j+1],POL[j]\nmeg=0\nfor i in range(0,10):\n if THER[i]>meg:\n meg=THER[i]\nfor i in range(0,10):\n if THER[i]==meg:\n print(POL[i],THER[i])","sub_path":"temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"304193326","text":"import subprocess\r\nimport sys\r\nimport os.path\r\nimport re\r\nimport argparse\r\nimport prepro\r\nimport logging as log\r\n\r\ndef build_parser():\r\n \"\"\"\r\nCreate an argument parser. \r\n\r\nParameters\r\n----------\r\nNone\r\n\r\nReturns\r\n-------\r\nparser: ArgumentParser\r\n An ArgumentParser object, capable of handling any specified\r\n positional and optional arguments for the program, including\r\n print functions for providing usage guidance.\r\n \"\"\"\r\n #Positional arguments\r\n parser = argparse.ArgumentParser(description='Processes and compiles a '\r\n '.xtex file into a finished PDF file.')\r\n parser.add_argument('source_file', \r\n help='A .xtex file ready to be processed.')\r\n\r\n #Optional arguments\r\n parser.add_argument('-t', '--target_file', \r\n help='Desired name of the preprocessed LaTeX file.'\r\n ' Default: Same as input')\r\n parser.add_argument('-v', '--verbose', action='count', \r\n help='Extra output to see what\\'s going on. Default: Off. ')\r\n parser.add_argument('-f', '--fancy', action='count',\r\n help=\"Fancy code and execution formatting. Default: On\")\r\n parser.add_argument('-i', '--interaction', action='count',\r\n help='Allow interaction with pdflatex. Default: Off')\r\n\r\n return parser\r\n\r\ndef prepare_files(input_file, output_file, fancy, compiler_args):\r\n \"\"\"\r\nPrepares files and data to send to the preprocessor.\r\n\r\nParameters\r\n----------\r\ninput_file : str\r\n The path of the raw .xtex file.\r\noutput_file : str\r\n The path of the processed .tex file, if specified.\r\nfancy : boolean\r\n A flag stating wether or not fancy verbatim output should be used.\r\ncompiler_args : str\r\n A string containing flags for the compiler.\r\n\r\n \"\"\"\r\n if output_file is None:\r\n rex = re.match(r'(.+)(\\.xtex)', input_file)\r\n if rex is None:\r\n log.error(\"Input file must be a .xtex file.\")\r\n sys.exit(1)\r\n\r\n path = rex.group(1)\r\n output_file = ''.join((path, '.tex'))\r\n\r\n\r\n prepro.process_file(input_file, output_file, fancy, log)\r\n\r\n log.info(\"Sending finished LaTeX file to compiler.\")\r\n compile_latex_file(output_file, compiler_args)\r\n\r\ndef compile_latex_file(input_file, compiler_args):\r\n \"\"\"\r\nCompiles a LaTeX file and prints errors (if any) returned from the compiler, log location and\r\noutput file location. \r\n\r\nParameters\r\n----------\r\ninput_file : str\r\n The LaTeX file to be compiled\r\noutput_file : str\r\n The name of the PDF file written by the compiler.\r\n\r\n \"\"\"\r\n compiler = \"pdflatex\"\r\n proc = subprocess.Popen(\"{0} {1} {2}\".format(compiler, \r\n compiler_args, input_file), shell=True, stdout=subprocess.PIPE)\r\n out, err = proc.communicate()\r\n\r\n if err is not None:\r\n log.error(err)\r\n sys.exit(1)\r\n else:\r\n latex_errors = re.findall(r'^\\.\\/{0}:\\d+:.*?$'.format(input_file), \r\n out, re.S|re.M)\r\n for error in latex_errors:\r\n log.info(error)\r\n\r\n transcript = re.search(r'^Transcript.*?$', out, re.S|re.M).group(0)\r\n output = re.search(r'^Output.*?$', out, re.S|re.M).group(0)\r\n\r\n log.info(transcript)\r\n log.info(output)\r\n\r\n\r\nif __name__ == '__main__':\r\n args = build_parser().parse_args()\r\n\r\n if not os.path.exists(args.source_file):\r\n log.error(\"File {0} does not exist.\".format(args.source_file))\r\n sys.exit(1)\r\n\r\n\r\n if (args.target_file):\r\n target_file = args.target_file\r\n else:\r\n target_file = None\r\n\r\n if (args.verbose):\r\n log.basicConfig(format=\"%(levelname)s: %(message)s\", level=log.DEBUG)\r\n else:\r\n log.basicConfig(format=\"%(levelname)s: %(message)s\")\r\n\r\n if (args.fancy):\r\n fancy = False\r\n else:\r\n fancy = True\r\n\r\n if (args.interaction):\r\n compiler_args = \"-file-line-error\"\r\n else:\r\n compiler_args = \"-file-line-error -interaction=nonstopmode\"\r\n\r\n\r\n prepare_files(args.source_file, target_file, fancy, compiler_args)","sub_path":"oblig3/docs/raw/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"93964975","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCode to insert data into XML file\r\n\"\"\"\r\n\r\nimport xml.etree.cElementTree as ET\r\n\r\nxml=\"Sample.xml\"\r\ntree= ET.ElementTree(file=xml)\r\nroot = tree.getroot()\r\n\r\ndef main(cond,pg,teeth,topx,topy,botx,boty):\r\n \r\n a = ET.Element(\"img\")\r\n a.set('cond',cond)\r\n a.set('pg',pg)\r\n a.set('teeth',teeth)\r\n \r\n tx = ET.Element(\"topx\")\r\n tx.text = topx\r\n \r\n ty = ET.Element(\"topy\")\r\n ty.text = topy\r\n \r\n bx = ET.Element(\"botx\")\r\n bx.text = botx\r\n \r\n by = ET.Element(\"boty\")\r\n by.text = boty\r\n \r\n root.insert(0, a)\r\n a.insert(0, tx)\r\n a.insert(1, ty)\r\n a.insert(2, bx)\r\n a.insert(3, by)\r\n \r\n tree.write(xml)\r\n#ET.dump(root)\r\n","sub_path":"putData.py","file_name":"putData.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"164791347","text":"from itertools import tee\nfrom collections import namedtuple\n\nimport numpy as np\nfrom skyfield.api import Angle\n\nfrom astro.api import earth, sun\n\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef unit_vector(vector):\n \"\"\" Returns the unit vector of the vector. \"\"\"\n return vector / np.linalg.norm(vector)\n\n\ndef angle_between(v1, v2):\n \"\"\" Returns the angle between vectors 'v1' and 'v2'\n\n Thanks to this stackoverflow answer to help me review my long forgotten math:\n http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python\n \"\"\"\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1, 1))\n return Angle(radians=angle)\n\n\ndef haversine(angle):\n 'Meeus Chapter 17, page 115.'\n return (1 - np.cos(angle.radians)) / 2\n\n\nRADec = namedtuple('RADec', 'ra dec')\n\n\ndef angular_separation(a, b):\n 'Meeus Chapter 17, Angular Separation. Formula 17.1'\n cos_d = np.sin(a.dec.radians) * np.sin(b.dec.radians) + \\\n np.cos(a.dec.radians) * np.cos(b.dec.radians) * np.cos(a.ra.radians - b.ra.radians)\n return Angle(radians=np.arccos(cos_d))\n\n\ndef haversine_separation(a, b):\n 'Meeus, Formula 17.5'\n delta_ra = Angle(radians=a.ra.radians - b.ra.radians)\n delta_dec = Angle(radians=a.dec.radians - b.dec.radians)\n hav_d = haversine(delta_dec) + np.cos(a.dec.radians) * np.cos(b.dec.radians) * haversine(delta_ra)\n return Angle(radians=2 * np.arcsin(np.sqrt(hav_d)))\n\n\ndef illuminated_fraction(body, t):\n 'Meeus, Chapter 41, Formula 41.2'\n r = body.at(t).observe(sun).apparent().distance().au\n delta = earth.at(t).observe(body).apparent().distance().au\n R = earth.at(t).observe(sun).apparent().distance().au\n return (np.power(r + delta, 2) - np.power(R, 2)) / (4 * r * delta)\n","sub_path":"astro/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"351888519","text":"from curva.framework.spreadsheet.group import Group\nfrom curva.framework.spreadsheet.cell import Cell\nfrom curva.spreadsheet.prelude.style import stylesheet\n\nimport copy\n\n\nclass PreludeGroup(Group):\n def __init__(self, parent_section, inputs, title, body, body_class_list, group_id, column_width=None):\n super().__init__(parent_section, inputs, group_id, [2, 0])\n\n self.column_width = column_width\n\n self.add_row()\n\n header_cell = Cell(\n self,\n inputs,\n 'header',\n {\n 'text': title\n },\n set(['prelude_header']),\n column_width,\n stylesheet\n )\n self.add_cell(header_cell)\n\n row_offset = 0\n for i, body_row in enumerate(body):\n if 'format' in body_row:\n body_row_format = body_row['format']\n else:\n body_row_format = body_class_list\n\n if 'repeat' in body_row:\n repeat_by = body_row['repeat']\n\n if type(repeat_by) == int:\n for repeat_i in range(repeat_by):\n content = copy.copy(body_row)\n content['text'] = content['text'].format(\n index=repeat_i\n )\n\n self.create_body_cell(\n row_offset,\n content,\n body_row_format\n )\n row_offset += 1\n elif type(repeat_by) == list:\n for repeat_i, repeat_item in enumerate(repeat_by):\n content = copy.copy(body_row)\n content['text'] = content['text'].format(\n index=repeat_i,\n item=repeat_item\n )\n\n self.create_body_cell(\n row_offset,\n content,\n body_row_format\n )\n row_offset += 1\n else:\n self.create_body_cell(\n row_offset,\n body_row,\n body_row_format\n )\n row_offset += 1\n\n def create_body_cell(self, offset, content, cell_format):\n self.add_row()\n\n content = copy.deepcopy(content)\n if 'references' in content:\n for reference in content['references']:\n path = reference['path']\n if len(path) < 3:\n path.append(offset)\n\n cell = Cell(\n self,\n self.inputs,\n f'body_{offset}',\n content,\n cell_format,\n self.column_width,\n stylesheet\n )\n self.add_cell(cell)\n\n def query(self, row):\n if len(self.cells) > 1:\n row = min(row, len(self.cells) - 2)\n cell_id = f'body_{row}'\n return next(cell for cell in self.cells if cell.id == cell_id)\n return None\n\n","sub_path":"src/atualizacao_package/curva/spreadsheet/prelude/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"384015882","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\n\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\n# Register your models here.\n\n\nfrom legislator import views\n\nurlpatterns = [\n # Examples:\n # url(r'^$', 'legislature_directory.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^$', views.index),\n url(r'^legislator/', include('legislator.urls', namespace=\"legislator\")),\n url(r'^admin/', admin.site.urls),\n url(r'^api/v1/', include('api.urls')),\n\n]\n\nif settings.DEBUG:\n urlpatterns += patterns(\n 'django.views.static',\n (r'media/(?P.*)',\n 'serve',\n {'document_root': settings.MEDIA_ROOT}), )\n","sub_path":"legislature_directory/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"594258184","text":"from fastapi import FastAPI\napp = FastAPI()\n\n# Beware to origins allowed ! In this template by default every IP can reach your API !\nfrom starlette.middleware.cors import CORSMiddleware\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello World\"}\n","sub_path":"{{ cookiecutter.repo_name }}/src/api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"14313351","text":"import io\nimport os\n\n# Imports the Google Cloud client library\nfrom google.cloud import speech\nfrom google.cloud.speech import enums\nfrom google.cloud.speech import types\nfrom google.oauth2 import service_account\n\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"/Users/aatishpandit/PycharmProjects/Hackathon/src/My First Project-ccbd1f5cef81.json\"\ndef transcribe_it(file_name = None, language = None):\n # credentialss = service_account.Credentials.from_service_account_file(\n # 'C:\\\\Users\\\\Ultimate Appy\\\\PycharmProjects\\\\NasscomHackathon\\\\src\\\\My First Project-ccbd1f5cef81.json')\n # client = speech.SpeechClient(credentials=credentials)\n client = speech.SpeechClient()\n # The name of the audio file to transcribe\n if file_name is None:\n file_name = \"/Users/aatishpandit/PycharmProjects/Hackathon/src/resources/myRecording5.wavs\"\n # Loads the audio into memory\n with io.open(file_name, 'rb') as audio_file:\n content = audio_file.read()\n audio = types.RecognitionAudio(content=content)\n\n config = types.RecognitionConfig(\n encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,\n\n language_code=language)\n\n # Detects speech in the audio file\n response = client.recognize(config, audio)\n print(response)\n for result in response.results:\n print('Transcript: {}'.format(result.alternatives[0].transcript))\n\n return result.alternatives[0].transcript\n# transcribe_it(file_name=\"/Users/aatishpandit/PycharmProjects/Hackathon/src/downloads/myRecording1_1.wav\",language=\"hi-IN\")","sub_path":"speechTranscribe.py","file_name":"speechTranscribe.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"221315366","text":"from settings import server_url\nfrom selenium import webdriver\nfrom settings import *\nfrom helpers import *\nfrom pages.main_page import MainPage\nfrom pages.cart_block import CartBlock\nfrom pages.good_page import GoodPage\nfrom pages.cart_page import CartPage\n\n\nclass Application(object):\n def __init__(self):\n if browser.lower() == \"ie\":\n self.driver = webdriver.Ie()\n self.driver.implicitly_wait(5)\n elif browser.lower() == \"firefox\":\n self.driver = webdriver.Firefox()\n elif browser.lower() == \"edge\":\n self.driver = webdriver.Edge()\n self.driver.implicitly_wait(5)\n else:\n opt = webdriver.ChromeOptions()\n opt.add_experimental_option('w3c', False)\n self.driver = webdriver.Chrome(options=opt) # Use Chrome browser by default\n\n self.main_page = MainPage(self.driver)\n self.cart_block = CartBlock(self.driver)\n self.good_page = GoodPage(self.driver)\n self.cart_page = CartPage(self.driver)\n\n def quit(self):\n self.driver.quit()\n\n def add_item_to_cart(self):\n self.main_page.open()\n self.main_page.click_first_item()\n cart_items_before = self.cart_block.get_cart_items()\n self.good_page.add_to_cart()\n\n self.cart_block.wait_quantity_update(cart_items_before, 1)\n\n def open_cart(self):\n self.cart_page.open()\n\n def remove_all_items_from_cart(self):\n self.cart_page.remove_all_items()\n","sub_path":"application/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"64464038","text":"# Copyright 2019-2021 Siemens AG\n# SPDX-License-Identifier: MIT\n\nimport re\nimport time\nimport logging\nfrom typing import Tuple\n\nfrom tenacity import retry, TryAgain, stop_after_attempt, retry_if_exception_type\nfrom fossology.exceptions import FossologyApiError, AuthorizationError\nfrom fossology.obj import ReportFormat, Upload, get_options\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclass Report:\n \"\"\"Class dedicated to all \"report\" related endpoints\"\"\"\n\n @retry(retry=retry_if_exception_type(TryAgain), stop=stop_after_attempt(3))\n def generate_report(\n self, upload: Upload, report_format: ReportFormat = None, group: str = None\n ):\n \"\"\"Generate a report for a given upload\n\n API Endpoint: GET /report\n\n :param upload: the upload which report will be generated\n :param format: the report format (default: ReportFormat.READMEOSS)\n :param group: the group name to choose while generating the report (default: None)\n :type upload: Upload\n :type format: ReportFormat\n :type group: string\n :return: the report id\n :rtype: int\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n \"\"\"\n headers = {\"uploadId\": str(upload.id)}\n if report_format:\n headers[\"reportFormat\"] = report_format.value\n else:\n headers[\"reportFormat\"] = \"readmeoss\"\n if group:\n headers[\"groupName\"] = group\n\n response = self.session.get(f\"{self.api}/report\", headers=headers)\n\n if response.status_code == 201:\n report_id = re.search(\"[0-9]*$\", response.json()[\"message\"])\n return report_id[0]\n\n elif response.status_code == 403:\n description = f\"Generating report for upload {upload.id} {get_options(group)}not authorized\"\n raise AuthorizationError(description, response)\n\n elif response.status_code == 503:\n wait_time = response.headers[\"Retry-After\"]\n logger.debug(f\"Retry generate report after {wait_time} seconds\")\n time.sleep(int(wait_time))\n raise TryAgain\n\n else:\n description = f\"Report generation for upload {upload.uploadname} failed\"\n raise FossologyApiError(description, response)\n\n @retry(retry=retry_if_exception_type(TryAgain), stop=stop_after_attempt(3))\n def download_report(self, report_id: int, group: str = None) -> Tuple[str, str]:\n \"\"\"Download a report\n\n API Endpoint: GET /report/{id}\n\n :Example:\n\n >>> from fossology.api import Fossology\n >>>\n >>> foss = Fossology(FOSS_URL, FOSS_TOKEN, username)\n >>>\n >>> # Generate a report for upload 1\n >>> report_id = foss.generate_report(foss.detail_upload(1))\n >>> report_content, report_name = foss.download_report(report_id)\n >>> with open(report_name, \"w+\") as report_file:\n >>> report_file.write(report_content)\n\n :param report_id: the id of the generated report\n :param group: the group name to choose while downloading a specific report (default: None)\n :type report_id: int\n :type group: string\n :return: the report content and the report name\n :rtype: Tuple[str, str]\n :raises FossologyApiError: if the REST call failed\n :raises AuthorizationError: if the user can't access the group\n :raises TryAgain: if the report generation timed out after 3 retries\n \"\"\"\n headers = dict()\n if group:\n headers[\"groupName\"] = group\n\n response = self.session.get(f\"{self.api}/report/{report_id}\", headers=headers)\n if response.status_code == 200:\n content = response.headers[\"Content-Disposition\"]\n report_name_pattern = '(^attachment; filename=\")(.*)(\"$)'\n report_name = re.match(report_name_pattern, content).group(2)\n return response.text, report_name\n elif response.status_code == 403:\n description = (\n f\"Getting report {report_id} {get_options(group)}not authorized\"\n )\n raise AuthorizationError(description, response)\n elif response.status_code == 503:\n wait_time = response.headers[\"Retry-After\"]\n logger.debug(f\"Retry get report after {wait_time} seconds\")\n time.sleep(int(wait_time))\n raise TryAgain\n else:\n description = f\"Download of report {report_id} failed\"\n raise FossologyApiError(description, response)\n","sub_path":"fossology/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"587368062","text":"\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\n\ndef softmax_meanse(input, target):\n \"\"\" Returns the Mean Squared Error on softmax of both input and output \"\"\"\n\n assert input.size() == target.size()\n input_sm = F.softmax(input, dim=1)\n output_sm = F.softmax(target, dim=1)\n num_classes = input.size()[1]\n return F.mse_loss(input_sm, output_sm, size_average=False) / num_classes\n ","sub_path":"ssl_methods/loss_functions.py","file_name":"loss_functions.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"145807944","text":"import numpy as np\nA = [{'jack': 4098, 'kek': 4139},\n {'jack': 46, 'spe': 49},\n {'jack': 40, 'stttape': 0},\n {'jyack': 8, 'stttape': 39}]\n\ns = []\nfor i in A:\n\n for j in i:\n\n b = j in s\n if b == False:\n s.append(j)\n s.append(i[j])\n print(j)\n print(i[j])\n\nprint(s)\n\ns = np.array(s)\nprint(s)\ns = s.reshape((5,2))\nprint(s)\nD = [{'jack': 4098, 'kek': 4139},\n {'jack': 46, 'spe': 49},\n {'jack': 40, 'stttape': 0},\n {'jyack': 8, 'stttape': 39}]\n\nprint(A+D)\n\n","sub_path":"2015-2016/CompareGeekTimes&Habr/linearsvc.py","file_name":"linearsvc.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"498858992","text":"import os\nimport random\nimport shutil\n\nimport torch\nimport torchvision\nfrom PIL import Image\nfrom torchvision.datasets import ImageFolder\nfrom torchvision.transforms import transforms\n\nimport data\n\nMEAN = (0.485, 0.456, 0.406)\nSTD = (0.229, 0.224, 0.225)\n\n\ndef tensor_loader(path):\n return torch.load(path)\n\n\nclass ImageItem(object):\n def __init__(self, source: ImageFolder, index: int):\n self.source = source\n self.index = index\n\n def load(self):\n return self.source[self.index][0]\n\n\nclass TacoDataset(data.LabeledDataset):\n CLASSES = 38\n\n def __init__(self, root=r\"C:\\datasets\\taco\\tensors\", augment_prob=0.0, reduce=0.0, image_size=84,\n tensors=True,\n random_seed=42, **kwargs):\n self.reduce = reduce\n self.tensors = tensors\n random.seed(random_seed)\n\n resize_train = transforms.Compose(\n [\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n ]\n )\n resize_test = transforms.Compose(\n [\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n ]\n )\n\n augment = transforms.Compose(\n [\n # transforms.RandomRotation(degrees=15),\n transforms.RandomHorizontalFlip(p=0.5),\n # transforms.ColorJitter(),\n # transforms.RandomPerspective(p=0.2, distortion_scale=0.25),\n ]\n )\n\n normalize = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(mean=MEAN, std=STD)\n ]\n )\n\n self.test_transform = transforms.Compose(\n [\n resize_test,\n normalize\n ]\n )\n self.train_transform = transforms.Compose(\n [\n resize_train,\n transforms.RandomApply([augment], p=augment_prob),\n normalize\n ]\n )\n if not tensors:\n self.source_dataset_train = torchvision.datasets.ImageFolder(root=root)\n else:\n self.source_dataset_train = torchvision.datasets.DatasetFolder(root=root, loader=tensor_loader,\n extensions=('pt',))\n\n self.dataset_train_size = len(self.source_dataset_train)\n items = []\n labels = []\n for i in range(self.dataset_train_size):\n items.append(ImageItem(self.source_dataset_train, i))\n labels.append(self.source_dataset_train[i][1])\n is_test = [0] * self.dataset_train_size\n\n super(TacoDataset, self).__init__(items, labels, is_test)\n\n self.train_subdataset, self.test_subdataset = self.subdataset.train_test_split()\n\n if reduce < 1:\n self.train_subdataset = self.train_subdataset.downscale(1 - reduce)\n else:\n self.train_subdataset = self.train_subdataset.balance(reduce)\n\n def __getitem__(self, item):\n image, label, is_test = super(TacoDataset, self).__getitem__(item)\n if self.tensors:\n return image, label, is_test\n\n if is_test:\n image = self.test_transform(image)\n else:\n image = self.train_transform(image)\n\n return image, label, is_test\n\n def label_stat(self):\n pass\n\n def train(self):\n return self.train_subdataset\n\n def test(self):\n return self.test_subdataset\n\n\ndef save_as_tensors(source=r'C:\\datasets\\taco\\images', target=r'C:\\datasets\\taco\\tensors',\n image_size=84):\n resize = transforms.Compose(\n [\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n ]\n )\n\n normalize = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(mean=MEAN, std=STD)\n ]\n )\n\n transform = transforms.Compose(\n [\n resize,\n normalize\n ]\n )\n\n os.makedirs(target, exist_ok=True)\n for i, class_label in enumerate(os.listdir(source)):\n cur_source = os.path.join(source, class_label)\n cur_target = os.path.join(target, class_label)\n os.makedirs(cur_target, exist_ok=True)\n for image in os.listdir(cur_source):\n source_image_file = os.path.join(cur_source, image)\n target_file = os.path.join(cur_target, image.replace('.jpg', '.pt'))\n with open(source_image_file, 'rb') as f:\n img = Image.open(f)\n img = img.convert('RGB')\n image_tensor = transform(img)\n torch.save(image_tensor, target_file)\n print(class_label, i)\n\n\ndef remove_small(threshold, root=r'C:\\datasets\\taco\\tensors'):\n for label in os.listdir(root):\n path = os.path.join(root, label)\n cnt = len(os.listdir(path))\n if cnt < threshold:\n print(label, cnt)\n shutil.rmtree(path)\n print(\"Deleted!\")\n\n# if __name__ == '__main__':\n# # save_as_tensors()\n# remove_small(10)\n","sub_path":"data/taco.py","file_name":"taco.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"88511284","text":"import sys\nfrom pcbnew import *\n\n\"\"\"\nexecfile (\"c:/python_progs/test_pcb/set_text.py\")\n\"\"\"\n\ndef SetText(Filename = None):\n if Filename: \n my_board = pcbnew.LoadBoard (Filename)\n else:\n my_board = pcbnew.GetBoard()\n\n for module in my_board.GetModules():\n print (\"module ref %s %s\" % ( module.GetReference(), my_board.GetLayerName(module.Reference().GetLayer())))\n\n # set size in mm\n module.Reference().SetSize (wxSize (FromMM(2),FromMM(2)))\n \n # set thickness in mm\n module.Reference().SetThickness (FromMM(0.3))\n\nSetText(sys.argv[1])\n","sub_path":"silkscreen-size.py","file_name":"silkscreen-size.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"430336545","text":"\nfrom keras.layers import Dense, Input\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom collections import deque\nimport numpy as np\nimport random\nimport argparse\nimport logging\nimport sys\nimport gym\nfrom gym import wrappers, logger\n\n\nclass DQNAgent(object):\n def __init__(self, state_space, action_space):\n self.action_space = action_space\n self.state_space = state_space\n self.build_model()\n self.memory = deque()\n self.gamma = 0.9 # discount rate\n self.epsilon = 1.0 # exploration rate\n self.epsilon_min = 0.1\n self.epsilon_decay = 0.999\n \n def build_model(self):\n inputs = Input(shape=(self.state_space.shape[0], ), name='state')\n x = Dense(128, activation='relu')(inputs)\n x = Dense(128, activation='relu')(x)\n x = Dense(self.action_space.n, activation='linear', name='action')(x)\n self.model = Model(inputs, x)\n self.model.compile(loss='mse', optimizer=Adam())\n\n def act(self, state):\n if np.random.rand() <= self.epsilon:\n # explore\n act = self.action_space.sample()\n return act\n\n # exploit\n act = self.model.predict(state)\n act = np.argmax(act[0])\n return act\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append([state, action, reward, next_state, done])\n\n def replay(self, batch_size):\n mini_batch = random.sample(self.memory, batch_size)\n x_batch, y_batch = [], []\n for state, action, reward, next_state, done in mini_batch:\n y_target = self.model.predict(state)\n q_value = self.gamma * np.amax(self.model.predict(next_state)[0])\n y_target[0][action] = reward if done else reward + q_value\n x_batch.append(state[0])\n y_batch.append(y_target[0])\n\n self.model.fit(np.array(x_batch),\n np.array(y_batch),\n batch_size=batch_size,\n epochs=1,\n verbose=0)\n self.update_epsilon()\n\n def update_epsilon(self):\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=None)\n parser.add_argument('env_id',\n nargs='?',\n default='CartPole-v0',\n help='Select the environment to run')\n args = parser.parse_args()\n\n win_trials = 100\n win_reward = { 'CartPole-v0' : 195.0 }\n scores = deque(maxlen=win_trials)\n\n # You can set the level to logging.DEBUG or logging.WARN if you\n # want to change the amount of output.\n logger.setLevel(logging.ERROR)\n\n env = gym.make(args.env_id)\n\n outdir = \"/tmp/dqn-%s\" % args.env_id\n env = wrappers.Monitor(env, directory=outdir, force=True)\n env.seed(0)\n agent = DQNAgent(env.observation_space, env.action_space)\n\n episode_count = 3000\n state_size = env.observation_space.shape[0]\n batch_size = 4\n\n for i in range(episode_count):\n state = env.reset()\n state = np.reshape(state, [1, state_size])\n t = 0\n done = False\n while not done:\n # in CartPole, action=0 is left and action=1 is right\n action = agent.act(state)\n next_state, reward, done, _ = env.step(action)\n # in CartPole:\n # state = [pos, vel, theta, angular speed]\n next_state = np.reshape(next_state, [1, state_size])\n agent.remember(state, action, reward, next_state, done)\n state = next_state\n t += 1\n\n scores.append(t)\n mean_score = np.mean(scores)\n if mean_score >= win_reward[args.env_id] and i >= win_trials:\n print(\"Solved after %d episodes\" % i)\n exit(0)\n if i % win_trials == 0:\n print(\"Episode %d: Mean survival in the last %d episodes: %0.2lf\" %\n (i, win_trials, mean_score))\n \n if len(agent.memory) >= batch_size:\n agent.replay(batch_size)\n \n # close the env and write monitor result info to disk\n env.close() \n","sub_path":"chapter9-drl/dqn-cartpole-9.2.1.py","file_name":"dqn-cartpole-9.2.1.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"42595667","text":"from unittest.mock import MagicMock, patch\n\nimport pytest\n\nfrom rotkehlchen.chain.ethereum.uniswap.uniswap import Uniswap\nfrom rotkehlchen.premium.premium import Premium\n\n\n@pytest.fixture\ndef uniswap_module(\n ethereum_manager,\n database,\n start_with_valid_premium,\n rotki_premium_credentials,\n function_scope_messages_aggregator,\n data_dir,\n) -> Uniswap:\n premium = None\n\n if start_with_valid_premium:\n premium = Premium(rotki_premium_credentials)\n\n uniswap = Uniswap(\n ethereum_manager=ethereum_manager,\n database=database,\n premium=premium,\n msg_aggregator=function_scope_messages_aggregator,\n data_directory=data_dir,\n )\n return uniswap\n\n\n@pytest.fixture\ndef patch_graph_query_limit(graph_query_limit):\n with patch(\n 'rotkehlchen.chain.ethereum.uniswap.uniswap.GRAPH_QUERY_LIMIT',\n new_callable=MagicMock(return_value=graph_query_limit),\n ):\n yield\n","sub_path":"rotkehlchen/tests/unit/uniswap/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"46777654","text":"__author__ = 'yanjiajia'\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom horizon import tables\n\n\n\n\nclass LogFilter(tables.FilterAction):\n def filter(self, table, logs, filter_string):\n \"\"\"log filter\"\"\"\n query = filter_string.lower()\n return [log for log in logs\n if query in log.name.lower()]\n\n\nclass LogTable(tables.DataTable):\n domain_name = tables.Column('domain_name', verbose_name=_(\"Domain Name\"))\n log_url = tables.Column('log_url', verbose_name=_(\"Download Url\"))\n log_size = tables.Column('log_size', verbose_name=_(\"Log Size(byte)\"))\n begin = tables.Column('begin', verbose_name=_(\"Begin\"))\n end = tables.Column('end', verbose_name=_(\"End\"))\n\n def get_object_id(self, datum):\n return datum.log_url\n\n class Meta(object):\n name = \"log\"\n hidden_title = True\n verbose_name = _(\"Log\")\n columns = (\"domain_name\", \"log_url\", \"log_size\", \"begin\",\n \"end\")\n table_actions = (LogFilter,)\n multi_select = False\n\n\n\n\n\n","sub_path":"horizon/openstack_dashboard/dashboards/cdn/cdn_log_manager/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"41631802","text":"import os\nimport pdb\nimport ffmpeg\nimport argparse\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input', type=str, help='path to file/stream')\n parser.add_argument('-o', '--output', type=str, help='path to sequence of frames')\n parser.add_argument('-f', '--format', type=str, default='jpg', help='frame image format')\n kwargs = parser.parse_args()\n\n if not kwargs.input:\n exit('Please pass required \"--input\" argument')\n\n output = kwargs.output or os.path.join(\n os.path.dirname(kwargs.input),\n os.path.splitext(kwargs.input)[0] + '_frames',\n )\n\n if not os.path.exists(output):\n os.mkdir(output)\n\n ix = 0\n err = None\n info = ffmpeg.probe(kwargs.input)\n duration = float(info['format']['duration'])\n\n while ix < int(duration):\n name = str(ix).zfill(3) + f'.{kwargs.format.lower()}'\n out, err = (\n ffmpeg\n .input(kwargs.input, ss=ix)\n .output(os.path.join(output, name), vframes=1, vcodec='mjpeg')\n .run(capture_stdout=True) # capture_stderr=True\n )\n\n ix += 1\n","sub_path":"grabber.py","file_name":"grabber.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"458474459","text":"import numpy as np\r\nimport torch\r\nimport gym\r\nimport argparse\r\nimport os\r\nimport time\r\nimport utils\r\nimport TD3\r\n\r\nparser = argparse.ArgumentParser(description='RL SAC LongiControl')\r\n\r\nparser.add_argument(\"--policy\", default=\"TD3\") # Policy name (TD3, DDPG or OurDDPG)\r\nparser.add_argument(\"--env\", default=\"DeterministicTrack-v0\", type=str) # OpenAI gym environment name\r\nparser.add_argument(\"--seed\", default=2, type=int) # Sets Gym, PyTorch and Numpy seeds\r\nparser.add_argument(\"--start_timesteps\", default=25e3, type=int)# Time steps initial random policy is used\r\nparser.add_argument(\"--eval_freq\", default=1e3, type=int) # How often (time steps) we evaluate\r\nparser.add_argument(\"--max_timesteps\", default=3e5, type=int) # Max time steps to run environment\r\nparser.add_argument(\"--expl_noise\", default=0.1) # Std of Gaussian exploration noise\r\nparser.add_argument(\"--batch_size\", default=256, type=int) # Batch size for both actor and critic\r\nparser.add_argument(\"--discount\", default=0.99) # Discount factor\r\nparser.add_argument(\"--tau\", default=0.005) # Target network update rate\r\nparser.add_argument(\"--policy_noise\", default=0.2) # Noise added to target policy during critic update\r\nparser.add_argument(\"--noise_clip\", default=0.5) # Range to clip target policy noise\r\nparser.add_argument(\"--policy_freq\", default=2, type=int) # Frequency of delayed policy updates\r\nparser.add_argument(\"--save_model\", action=\"store_true\") # Save model and optimizer parameters\r\nparser.add_argument(\"--load_model\", default=\"\") # Model load file name, \"\" doesn't load, \"default\" uses file_name\r\nparser.add_argument('--visualize','-vis', action='store_true')\r\nparser.add_argument('--record','-rec',action='store_true') \r\nparser.add_argument('--save_id',metavar='',type=int,default=0)\r\nparser.add_argument('--load_id',metavar='',type=int,default=None)\r\nparser.add_argument('--car_id',metavar='',type=str,default='BMW_electric_i3_2014')\r\nparser.add_argument('--env_id',metavar='',type=str,default='DeterministicTrack-v0')\r\nparser.add_argument('--reward_weights','-rw',metavar='',nargs='+',type=float,default=[1.0, 0.5, 1.0, 1.0])\r\nparser.add_argument('--energy_factor',metavar='',type=float,default=1.0)\r\nparser.add_argument('--speed_limit_positions',metavar='',nargs='+',type=float,default=[0.0, 0.25, 0.5, 0.75])\r\nparser.add_argument('--speed_limits',metavar='',nargs='+',type=int,default=[50, 80, 40, 50])\r\nargs = parser.parse_args()\r\n'''\r\ndef torch_to_numpy(torch_input):\r\n if isinstance(torch_input, tuple):\r\n return tuple(torch_to_numpy(e) for e in torch_input)\r\n return torch_input.data.numpy()\r\ndef numpy_to_torch(numpy_input):\r\n if isinstance(numpy_input, tuple):\r\n return tuple(numpy_to_torch(e) for e in numpy_input)\r\n return torch.from_numpy(numpy_input).float()\r\n''' \r\nenv = gym.make('gym_longicontrol:' + args.env_id,\r\n car_id=args.car_id,\r\n speed_limit_positions=args.speed_limit_positions,\r\n speed_limits=args.speed_limits,\r\n reward_weights=args.reward_weights,\r\n energy_factor=args.energy_factor)\r\n \r\nstate_dim = env.observation_space.shape[0]\r\naction_dim = env.action_space.shape[0] \r\nmax_action = float(env.action_space.high[0])\r\nkwargs = {\r\n\"state_dim\": state_dim,\r\n\"action_dim\": action_dim,\r\n\"max_action\": max_action,\r\n\"discount\": args.discount,\r\n\"tau\": args.tau,\r\n}\r\n\r\npolicy = TD3.TD3(**kwargs)\r\nfile_name = f\"{args.policy}_{args.env}_{args.seed}\"\r\npolicy.load(filename=f\"./models/{file_name}\")\r\n\r\nenv.seed(args.seed)\r\ntorch.manual_seed(args.seed)\r\nnp.random.seed(args.seed)\r\n\r\n\r\n\r\nfrom gym import wrappers\r\nfrom time import time\r\nsave_dname = os.path.join(os.path.dirname(__file__),\r\n f'out/{args.env_id}/SAC_id{args.save_id}')\r\nsave_dname = os.path.join(save_dname,\r\n 'videos/' + str(time()) + '/')\r\nenv = wrappers.Monitor(env, save_dname)\r\nenv.seed(2)\r\n\r\n\r\nstate, done = env.reset(), False\r\nepisode_return = 0\r\nwhile True:\r\n action = policy.select_action(np.array(state))\r\n #action = torch_to_numpy(action).reshape(env.action_space.shape)\r\n state, reward, done, info = env.step(action)\r\n episode_return += reward\r\n\r\n #state = numpy_to_torch(next_state)\r\n env.render()\r\n\r\n if done:\r\n #state = numpy_to_torch(env.reset())\r\n state = env.reset()\r\n print(episode_return)\r\n break\r\nenv.close()\r\n\r\n\r\n","sub_path":"rl/pytorch/TD3/try_visualize.py","file_name":"try_visualize.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"212238404","text":"import types\n\ndef init(w=256,h=100):\n\tglobal pygame\n\timport pygame\n\tpygame.init()\n\tglobal screen\n\tglobal screenw\n\tglobal screenh\n\tscreenw = w\n\tscreenh = h\n\tscreen = pygame.display.set_mode((screenw,screenh))\n\tscreen.fill((255,255,255))\n\ndef plot(data,xmin,xmax,ymin,ymax,color):\n\tscreen.fill((255,255,255))\n\tfor k in range(len(data[0])):\n\t\tx = data[0][k]\n\t\ty = data[1][k]\n\t\txc = int( (x-xmin)/float(xmax-xmin) * screenw )\n\t\tyc = int( (y-ymin)/float(ymax-ymin) * screenh )\n\t\tscreen.set_at([xc,yc],color)\n\tpygame.display.update()\n\ndef plotline(data,xmin,xmax,ymin,ymax,color=(0,255,0),width=1):\n\tscreen.fill((255,255,255))\n\tprevpt = [0,0]\n\tfor k in range(len(data[0])):\n\t\tx = data[0][k]\n\t\ty = data[1][k]\n\t\tif type(y) == types.ComplexType:\n\t\t\ty = y.real\n\t\txc = (x-xmin)/float(xmax-xmin) * screenw\n\t\tif y >= ymax:\n\t\t\tyc = screenh-1\n\t\telse:\n\t\t\tyc = (y-ymin)/float(ymax-ymin) * screenh\n\t\txc = int(xc)\n\t\tyc = int(yc)\n\t\tscreen.set_at([xc,yc],color)\n\t\tif k > 0:\n\t\t\tpygame.draw.line(screen,color,[xc,yc],prevpt,width)\n\t\tprevpt = [xc,yc]\n\tpygame.display.update()\n\n","sub_path":"oldprogs/pitchdetection/plot_interactive.py","file_name":"plot_interactive.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"523950365","text":"# File: QueueConsoleTest.py\n\nfrom consoletest import ConsoleTest\nfrom queue import Queue\n\n# File: BSTConsoleTest.py\n\n\"\"\"\nThis program implements an interactive test of the Queue implementation.\nThe program starts off with an empty Queue and then accepts commands\nfrom the user, which can be any of the following:\n\n enqueue value -- Adds the value to the end of the queue\n dequeue -- Dequeues and displays the first value in the queue\n isEmpty -- Reports whether the queue is empty\n list -- Lists the contents of the queue\n\"\"\"\n\nfrom consoletest import ConsoleTest\nfrom queue import Queue\n\nclass QueueConsoleTest(ConsoleTest):\n\n def __init__(self):\n self.queue = Queue()\n self.run()\n\n def enqueueCommand(self, scanner):\n \"\"\"enqueue value -- Adds the value to the end of the queue\"\"\"\n value = scanner.nextToken()\n self.queue.enqueue(value)\n\n def dequeueCommand(self, scanner):\n \"\"\"dequeue -- Dequeues and displays the first value in the queue\"\"\"\n if self.queue.isEmpty():\n print(\"Queue is empty\")\n else:\n print(self.queue.dequeue())\n\n def isEmpty(self, scanner):\n \"\"\"isEmpty -- Reports whether the queue is empty\"\"\"\n print(self.queue.isEmpty())\n\n def listCommand(self, scanner):\n \"\"\"list -- List the contents of the queue\"\"\"\n if self.queue.isEmpty():\n print(\"Queue is empty\")\n else:\n tempQueue = Queue()\n contents = \"\"\n while not self.queue.isEmpty():\n value = self.queue.dequeue()\n if contents != \"\":\n contents += \", \"\n contents += value\n tempQueue.enqueue(value)\n print(contents)\n while not tempQueue.isEmpty():\n self.queue.enqueue(tempQueue.dequeue())\n\n# Startup code\n\nif __name__ == \"__main__\":\n QueueConsoleTest()\n","sub_path":"LinkedQueue/QueueConsoleTest.py","file_name":"QueueConsoleTest.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"648092914","text":"class Node:\n def __init__(self, key, val):\n self.key = key\n self.val = val\n\n\nclass Heap:\n def __init__(self):\n self.heap = []\n self.size = 0\n self.hash_table = {}\n\n def _update_hash(self, val, idx_update):\n self.hash_table[val] = idx_update\n\n def _swap_node(self, left_idx, right_idx):\n self._update_hash(self.heap[left_idx].val, right_idx)\n self._update_hash(self.heap[right_idx].val, left_idx)\n self.heap[left_idx], self.heap[right_idx] = self.heap[right_idx], self.heap[left_idx]\n\n def _bubble_up(self, current_idx):\n if current_idx == 0:\n return\n parent_idx = (current_idx - 1) // 2\n if self.heap[parent_idx].key >= self.heap[current_idx].key:\n self._swap_node(current_idx, parent_idx)\n self._bubble_up(parent_idx)\n\n def _bubble_down(self, current_idx):\n child_left, child_right = current_idx * 2 + 1, current_idx * 2 + 2\n if child_left >= self.size:\n return\n elif child_right >= self.size:\n child_lower = child_left\n else:\n child_lower = child_left if self.heap[child_left].key <= self.heap[child_right].key else child_right\n\n if self.heap[current_idx].key > self.heap[child_lower].key:\n self._swap_node(current_idx, child_lower)\n self._bubble_down(child_lower)\n\n def _search_idx(self, val):\n if val in self.hash_table:\n return self.hash_table[val]\n return None\n\n def insert(self, key, val):\n node_insert = Node(key, val)\n self.heap.append(node_insert)\n self.size += 1\n self.hash_table[val] = self.size - 1\n self._bubble_up(self.size - 1)\n\n def extract_min(self):\n if self.size <= 0:\n raise ValueError('No value to extract.')\n else:\n self._swap_node(self.size-1, 0)\n node_extracted = self.heap.pop()\n self.size -= 1\n self._bubble_down(0)\n self.hash_table.pop(node_extracted.val)\n return node_extracted\n\n def update_key(self, key_updated, val):\n idx_current = self._search_idx(val)\n assert idx_current is not None\n\n key_original = self.heap[idx_current].key\n self._swap_node(idx_current, self.size - 1)\n self.heap.pop()\n self.size -= 1\n self._bubble_down(idx_current)\n\n key_updated = min(key_original, key_updated)\n self.insert(key_updated, val)\n\n def print_current_status(self):\n print(f'Current Heap status : {[(i.key, i.val) for i in self.heap]}')\n\n\n\na = Heap()\na.insert(5, 'A')\na.insert(1, 'B')\na.insert(2, 'C')\na.insert(4, 'D')\na.insert(0, 'E')\na.print_current_status()\na.extract_min()\na.print_current_status()\na.extract_min()\na.print_current_status()\na.extract_min()\na.print_current_status()\na.extract_min()\na.print_current_status()\na.extract_min()\na.print_current_status()\n","sub_path":"heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"525961614","text":"# STOCKHOUSE\nimport pandas\nimport quandl\nimport time\nimport Adafruit_MCP4725\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)\ndac1 = Adafruit_MCP4725.MCP4725(address=0x60, busnum=1)\ndac2 = Adafruit_MCP4725.MCP4725(address=0x61, busnum=1)\n\nauth = \"SNbqZypqf-CzSt51ZQkL\"\ndf1 = quandl.get(\"WIKI/AAPL\", authtoken=auth)\ndf2 = quandl.get(\"WIKI/MSFT\", authtoken=auth)\n\nstock1 = df1[\"Close\"]\nstock2 = df2[\"Close\"]\n\nscalar1 = 4096 / stock1.max()\nscalar2 = 4096 / stock2.max()\n\ndac1_data = stock1.as_matrix()\ndac2_data = stock2.as_matrix()\n\nif dac1_data.size >= dac2_data.size:\n\tdata_range = dac2_data.size\nelse:\n\tdata_range = dac1_data.size\n\npoint = 0\nstep = 1\n\nwhile True:\n\tinput_state = GPIO.input(18)\n\tdac1.set_voltage(int(dac1_data[point]*scalar1))\n\tdac2.set_voltage(int(dac2_data[point]*scalar2))\n\tprint (point, int(dac1_data[point]), int(dac2_data[point]))\n\t#time.sleep(1)\n\n\tif input_state == False:\n\t\tstep = step + 5\n\t\ttime.sleep(0.2)\n\t\tif step > 100:\n\t\t\tstep = 1\n\t\tprint(step)\n\t\t\n\tpoint = point + step\n\tif point >= data_range:\n\t\tpoint = 0\n\n","sub_path":"stocksound_ctrl.py","file_name":"stocksound_ctrl.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"18116410","text":"\"\"\"\nThis spider is a BuscoJobsXML spider created on top of the XMLSpider\nscrapy crawl buscojobs_xml -a extract=1 -a url=\"http://feeds.buscojobs.com/feeds/bjbo/linkedin.xml\"\n\nsample url:\n http://feeds.buscojobs.com/feeds/bjbo/linkedin.xml\n http://feeds.buscojobs.com/feeds/bjbr/linkedin.xml\n\n\"\"\"\n\nfrom zlib import crc32\nfrom brightcorp.base.xmlspider import XMLSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin, ConvertDateString\n\n\nclass BuscoJobsXML(XMLSpider):\n\n follow_job_url = False\n name = 'buscojobs_xml'\n tag = 'job'\n sub_domain_re = r'feeds\\/(.*?)\\/linkedin\\.xml'\n\n field_xpaths = {\n 'title': '//title/text()',\n 'url': '//apply-url/text()',\n 'company': '//company/text()',\n 'description': '//description/node()'\n }\n\n location_xpaths = ['//location/text()', '//state/text()', '//country/text()']\n date_xpath = ['//publishdate/text()']\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n for field, xpath in self.field_xpaths.iteritems():\n loader.add_xpath(field, xpath)\n\n loader.add_value(\n 'referencenumber', str(crc32(loader.get_output_value('url'))),\n Prefix('%s-' % self.name)\n )\n loader.add_xpath('location', self.location_xpaths, NormalizedJoin(\", \"))\n loader.add_xpath('date', self.date_xpath, ConvertDateString('%d/%m/%Y'))\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/buscojobs_xml.py","file_name":"buscojobs_xml.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"49870851","text":"from django import forms\n\nfrom hknweb.utils import DATETIME_12_HOUR_FORMAT\nfrom .models import Event\nfrom .utils import DATETIME_WIDGET_NO_AUTOCOMPLETE\n\n\nclass EventForm(forms.ModelForm):\n start_time = forms.DateTimeField(\n input_formats=(DATETIME_12_HOUR_FORMAT,), widget=DATETIME_WIDGET_NO_AUTOCOMPLETE\n )\n end_time = forms.DateTimeField(\n input_formats=(DATETIME_12_HOUR_FORMAT,), widget=DATETIME_WIDGET_NO_AUTOCOMPLETE\n )\n recurring_num_times = forms.IntegerField(\n min_value=0, required=False, label=\"Number of occurences\", initial=0\n )\n recurring_period = forms.IntegerField(\n min_value=0,\n required=False,\n label=\"How often this event re-occurs (in weeks)\",\n initial=0,\n )\n\n class Meta:\n model = Event\n fields = (\n \"name\",\n \"slug\",\n \"location\",\n \"description\",\n \"event_type\",\n \"start_time\",\n \"end_time\",\n \"rsvp_limit\",\n \"access_level\",\n )\n\n widgets = {\n \"slug\": forms.TextInput(attrs={\"placeholder\": \"e.g. -\"}),\n }\n\n labels = {\n \"slug\": \"URL-friendly name\",\n \"rsvp_limit\": \"RSVP limit\",\n }\n\n\nclass EventUpdateForm(forms.ModelForm):\n start_time = forms.DateTimeField(input_formats=(DATETIME_12_HOUR_FORMAT,))\n end_time = forms.DateTimeField(input_formats=(DATETIME_12_HOUR_FORMAT,))\n\n class Meta:\n model = Event\n fields = [\n \"name\",\n \"slug\",\n \"start_time\",\n \"end_time\",\n \"location\",\n \"event_type\",\n \"description\",\n \"rsvp_limit\",\n \"access_level\",\n ]\n\n widgets = {\n \"slug\": forms.TextInput(attrs={\"placeholder\": \"e.g. -\"}),\n }\n\n labels = {\n \"slug\": \"URL-friendly name\",\n \"rsvp_limit\": \"RSVP limit\",\n }\n","sub_path":"hknweb/events/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"174456687","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 6 21:19:01 2018\r\n\r\n@author: David Romero Acosta\r\n\"\"\"\r\nfrom gurobipy import *\r\n\r\nm = Model(\"Ejercicio_3.18_Jhonson_Montgomery\")\r\nm.update()\r\n\r\n#Materiales \r\nmateriales=[\"Grano 1\",\"Grano 2\",\"Grano 3\",\"Grano 4\"]\r\n\r\n#Productos \r\nProductos=[\"Marca A\",\"Marca B\",\"Marca C\"]\r\n\r\n#Mínimos por tipo de grano\r\nL=[[0,0.10,0.40,0.0],\r\n [0.2,0.3,0.0,0.0],\r\n [0.4,0.0,0.0,0.0]]\r\n\r\n#Máximo por tipo de grano\r\nU=[[0.0,1.0,0.7,0.8],\r\n [0.4,0.7,0.0,0.1],\r\n [1.0,0.6,0.1,0.0]]\r\n\r\n#Demanda de marca de cafè\r\na=[5000,10000,3000]\r\n\r\n#Disponibilidad de tipo de grano\r\nb=[4000,6000,2500,8000]\r\n\r\n#Costo por tipo de grano i\r\np=[0.23,0.20,0.15,0.10]\r\n\r\n#x[i][j] es la fracción de materiales i en cada producto j\r\nx = {}\r\nfor i in range(len(materiales)):\r\n for j in range(len(Productos)):\r\n x[i,j] = m.addVar(L[j][i],U[j][i],vtype= GRB.CONTINUOUS, name=\"Materia Prima %s %s\" % (materiales[i],Productos[j]))\r\n \r\n#y[i] es la cantidad total de grano i usada en la producción\r\n\r\ny={}\r\nfor i in range(len(materiales)):\r\n y[i]=m.addVar(obj=p[i],vtype= GRB.CONTINUOUS, name=\"Total Grano %s\" % (materiales[i]))\r\n \r\n#Restricción de balance en mezcla, la suma de todas las fracciones de un producto debe sumar 1.\r\n\r\nfor j in range(len(Productos)):\r\n m.addConstr(quicksum(x[i,j] for i in range(len(materiales))) == 1, \"Mezcla %s\" % (Productos[j]))\r\n\r\n#Restricción de disponibilidad de grano\r\n\r\nfor i in range(len(materiales)):\r\n m.addConstr(quicksum(a[j]*x[i,j] for j in range(len(Productos))) <= b[i] , \"Disponibilidad %s\" %materiales[i])\r\n\r\n#Restricción de disponibilidad de grano\r\n\r\nfor i in range(len(materiales)):\r\n m.addConstr(y[i]==quicksum(a[j]*x[i,j] for j in range(len(Productos))), \"Consumo Total de Grano %s\" %materiales[i])\r\n \r\n\r\n#Función Objetivo Minimización\r\n\r\nm.ModelSense = 1\r\n\r\nm.optimize()\r\n\r\n#Impresión de resultados de las variables\r\n\r\nfor i in m.getVars():\r\n print('%s %g' % (i.varname, i.x))\r\n\r\n#imprimir el valor de la función objetivo\r\n \r\nprint('Función Objetivo: %g' % (m.objVal))\r\n\r\n#Impresión de resultados de las variables\r\n\r\n\r\nfor cs in m.getConstrs(): \r\n print ('\\n Restriccion %s ' %cs.ConstrName + ' Holgura : %f' %cs.Slack)\r\n\r\n","sub_path":"Ejercicio_3_18.py","file_name":"Ejercicio_3_18.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"69708666","text":"def twoSum(arr,target):\n dict = {}\n result = [-1,-1]\n for i in range(len(arr)):\n dict[arr[i]] = i\n\n for i in range(len(arr)):\n comp = target - arr[i]\n if comp in dict and i!= dict[comp] :\n result[0] = i\n result[1] = dict[comp]\n\n return result\n\n\ndef main():\n myArr = [2,7,11,15]\n target = 9\n result = twoSum(myArr,target)\n print(result)\n\nmain()","sub_path":"1TwoSum.py","file_name":"1TwoSum.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"277126718","text":"from concurrent import futures\nfrom typing import List, Optional, Sequence, Union\n\nfrom acme import core\nfrom acme.jax import networks as network_types\n\nimport jax\nimport ray\nimport datetime\n\n\nclass RayVariableClient:\n \"\"\"A variable client for updating variables from a remote Ray source.\"\"\"\n\n def __init__(self,\n client: core.VariableSource,\n key: Union[str, Sequence[str]],\n update_period: int = 1,\n device: Optional[str] = None,\n temp_client_key: str = None):\n \"\"\"Initializes the variable client.\n\n Args:\n client: A variable source from which we fetch variables.\n key: Which variables to request. When multiple keys are used, params\n property will return a list of params.\n update_period: Interval between fetches.\n device: The name of a JAX device to put variables on. If None (default),\n don't put to device.\n \"\"\"\n self._temp_client_key = temp_client_key # temporary uuid that enables logging the variable update timing\n\n\n self._num_updates = 0 # the number of times variables have been successfully updated\n self._update_period = update_period\n self._call_counter = 0\n self._client = client\n self._params: Sequence[network_types.Params] = None\n self._device = None\n if device:\n self._device = jax.devices(device)[0]\n\n self._executor = futures.ThreadPoolExecutor(max_workers=1)\n if isinstance(key, str):\n key = [key]\n self._request = lambda k=key: ray.get(client.get_variables.remote(k))\n self._future: Optional[futures.Future] = None\n self._async_request = lambda: self._executor.submit(self._request)\n\n def update(self, wait: bool = False) -> None:\n \"\"\"Periodically updates the variables with the latest copy from the source.\n\n If wait is True, a blocking request is executed. Any active request will be\n cancelled.\n If wait is False, this method makes an asynchronous request for variables.\n\n Args:\n wait: Whether to execute asynchronous (False) or blocking updates (True).\n Defaults to False.\n \"\"\"\n # Track calls (we only update periodically).\n if self._call_counter < self._update_period:\n self._call_counter += 1\n\n # Return if it's not time to fetch another update.\n if self._call_counter < self._update_period:\n return\n\n if wait:\n if self._future is not None:\n if self._future.running():\n self._future.cancel()\n self._future = None\n self._call_counter = 0\n self.update_and_wait()\n return\n\n # Return early if we are still waiting for a previous request to come back.\n if self._future and not self._future.done():\n return\n\n # Get a future and add the copy function as a callback.\n self._call_counter = 0\n self._future = self._async_request()\n self._future.add_done_callback(lambda f: self._callback(f.result(), datetime.datetime.now()))\n\n def update_and_wait(self):\n \"\"\"Immediately update and block until we get the result.\"\"\"\n start_time = datetime.datetime.now()\n self._callback(self._request(), start_time)\n\n def _callback(self, params_list: List[network_types.Params], start_time):\n if self._device:\n # Move variables to a proper device.\n self._params = jax.device_put(params_list, self._device)\n else:\n self._params = params_list\n\n duration = datetime.datetime.now() - start_time\n duration = duration.total_seconds()\n \n if self._temp_client_key:\n # temporary: get it to print only if it takes more than 0.5\n if duration > 0.5:\n print(f\"{self._temp_client_key}: variable updated successfully! Took {duration}\")\n self._num_updates += 1\n self._start_time = None\n\n @property\n def params(self) -> Union[network_types.Params, List[network_types.Params]]:\n \"\"\"Returns the first params for one key, otherwise the whole params list.\"\"\"\n if self._params is None:\n self.update_and_wait()\n\n if len(self._params) == 1:\n return self._params[0]\n else:\n return self._params\n","sub_path":"refactor_test/variable_utils.py","file_name":"variable_utils.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"641177473","text":"import scrapy\n\nclass MainSpider(scrapy.Spider):\n name = \"main\"\n allowed_domains = ['tumorlibrary.com']\n\n def start_requests(self):\n for page in range(0, 7 + 1):\n url = f\"http://www.tumorlibrary.com/case/list.jsp?pager.offset={page * 25}&category_sub_type=&category=Bone+Tumors&image_type=X-ray&treatment=&order=diagnosis+ASC&sub_location=&image_id=&diagnosis=&sex=&filter.y=16&location=Distal+femur&filter.x=113&age=&category_type=&case_id=\"\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n first = True\n for row in response.xpath('/html/body/table/tr[@class=\"vatop\"]/td[2]/div/center/table/tr'):\n if first:\n first = False\n continue\n cells = [cell.css('::text').get() for cell in row.css('td')]\n image_page = f'detail.jsp?image_id={cells[1]}'\n req = response.follow(image_page, callback=self.parse_image)\n req.meta['cells'] = cells\n yield req\n\n def parse_image(self, response):\n cells = response.meta['cells']\n# x = response.xpath('/html/body/table/tr[1]/td/table/tr[1]/td[3]/ul/li[12]/text()[1]').get().strip().split(':')[1].strip().split(',')[0]\n x = response.xpath('/html/body/table/tr[1]/td/table/tr[1]/td[3]/ul/li')[-1].xpath('text()[1]').get().strip().split(':')[1].strip().split(',')[0]\n self.log(f'image: {response.url} x={x}')\n intx = -1\n try:\n intx = int(x)\n except:\n pass\n\n if intx >= 0 and intx == int(cells[1]):\n #image_url = response.xpath('/html/body/table/tr[1]/td/table/tr[1]/td[1]/a[2]/@href').get()\n image_url = f'/case/images/{int(cells[1])}.jpg'\n image_url = response.urljoin(image_url)\n cells.append(image_url)\n cells_dict = {'cells':cells}\n yield(cells_dict)\n\n","sub_path":"slike/test/aleksandra/tumor/tumor/spiders/main_spider.py","file_name":"main_spider.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"184378855","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport pss_entity as entity\n\n\n\n\n\n# ---------- Constants ----------\n\nSTARSYSTEM_DESIGN_BASE_PATH = 'GalaxyService/ListStarSystems?languageKey=en'\nSTARSYSTEM_DESIGN_KEY_NAME = 'StarSystemId'\nSTARSYSTEM_DESIGN_DESCRIPTION_PROPERTY_NAME = 'StarSystemTitle'\n\nSTARSYSTEMLINK_DESIGN_BASE_PATH = 'GalaxyService/ListStarSystems?languageKey=en'\nSTARSYSTEMLINK_DESIGN_KEY_NAME = 'StarSystemId'\nSTARSYSTEMLINK_DESIGN_DESCRIPTION_PROPERTY_NAME = 'StarSystemTitle'\n\n\n\n\n\n\n\n\n\n\n# ---------- Initialization ----------\n\nstar_systems_designs_retriever: entity.EntityDesignsRetriever = entity.EntityDesignsRetriever(\n STARSYSTEM_DESIGN_BASE_PATH,\n STARSYSTEM_DESIGN_KEY_NAME,\n STARSYSTEM_DESIGN_DESCRIPTION_PROPERTY_NAME,\n 'StarSystemDesigns'\n)\n\nstar_system_links_designs_retriever: entity.EntityDesignsRetriever = entity.EntityDesignsRetriever(\n STARSYSTEMLINK_DESIGN_BASE_PATH,\n STARSYSTEMLINK_DESIGN_KEY_NAME,\n STARSYSTEMLINK_DESIGN_DESCRIPTION_PROPERTY_NAME,\n 'StarSystemLinkDesigns'\n)\n","sub_path":"src/pss_gm.py","file_name":"pss_gm.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"134451830","text":"import pymongo\nfrom bson.code import Code\nimport xlwt\nimport json\n# url='mongodb://qfliu:' + '111111' + '@192.168.0.210:27017'\nclient =pymongo.MongoClient(host=\"192.168.0.210\",port=27017)\ndb=client.get_database(\"comment\")\ni=0\nmapfun = Code(\"function () {emit({province:this.data.userProvince,terrace:this.data.userClientShow},1);}\")\nreducefun = Code(\"function (key, values) {\"\n \" var total = 0;\"\n \" for (var i = 0; i < values.length; i++) {\"\n \" total += values[i];\"\n \" }\"\n \" return total;\"\n \"}\")\nresult = db.jd_comment.map_reduce(mapfun, reducefun, \"myresults\")\nworkbook = xlwt.Workbook() #注意Workbook的开头W要大写\nsheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True)\nfor i,doc in enumerate(result.find()):\n sheet1.write(i,0,doc['_id']['province'])\n sheet1.write(i, 1, doc['_id']['terrace'])\n sheet1.write(i, 2, doc['value'])\nworkbook.save('./c.xlt')\n# for i,doc in enumerate(result.find()):\n# print(doc)","sub_path":"mongo_script/test_map_reduce.py","file_name":"test_map_reduce.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"347764437","text":"#!/usr/bin/env python\nimport sys\n\ndata = sys.stdin.readlines()\nT = int(data[0])\n\ndef fsum(a):\n b = a//4-1\n res = 2*b*(b+1)\n res += (a%4)*(b+1)\n return res\n\ndef solve(r, t):\n lo, hi = 1, t\n while ((hi-lo)>1):\n m = (lo+hi)//2\n val = fsum(2*r+4*m+1)-fsum(2*r+1)\n if (val > t):\n hi = m\n else:\n lo = m;\n return lo\n\nindex = 1\nfor line in data[1:]:\n r, t = line.split()\n r, t = int(r), int(t)\n print(\"Case #\" + str(index) + \": \" + str(solve(r, t)))\n index += 1\n","sub_path":"solutions_2464487_1/Python/xulusko/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"180594532","text":"import sys\nclass FastAreader :\n\t\n def __init__ (self, fname=''):\n '''contructor: saves attribute fname '''\n self.fname = fname\n \n def doOpen (self):\n if self.fname is '':\n return sys.stdin\n else:\n return open(self.fname)\n \n def readFasta (self):\n\t\t\n header = ''\n sequence = ''\n \n with self.doOpen() as fileH:\n\t\t\t\n header = ''\n sequence = ''\n \n # skip to first fasta header\n line = fileH.readline()\n while not line.startswith('>') :\n line = fileH.readline()\n header = line[1:].rstrip()\n\n for line in fileH:\n if line.startswith ('>'):\n yield header,sequence\n header = line[1:].rstrip()\n sequence = ''\n else :\n sequence += ''.join(line.rstrip().split()).upper()\n\t\t\t\t\t\t\n yield header,sequence\n\n","sub_path":"identify_the_promoter_motif/fastaReader.py","file_name":"fastaReader.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"405686579","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\ndef read_file(fname):\n dist = np.array([])\n fin = open(fname,'r')\n for line in fin:\n dist = np.append(dist, float(line.split(',')[0]))\n fin.close()\n return dist\n\n# falling20_dist = read_file('falling20_dist.txt')\n# falling50_dist = read_file('falling50_dist.txt')\n# falling80_dist = read_file('falling80_dist.txt')\n# rising20_dist = read_file('rising20_dist.txt')\n# rising50_dist = read_file('rising50_dist.txt')\n# rising80_dist = read_file('rising80_dist.txt')\nrise_times = read_file('rise_time.txt')\nfall_times = read_file('fall_time.txt')\n\nbin_num = 200\nfig = plt.figure(figsize=(6,4))\nplt.hist(rise_times,bins = bin_num)\nplt.hist(fall_times,bins = bin_num)\nplt.title('Histogram of Crossing Times Relative to Rising 50% point')#,fontsize = 18)\nplt.xlabel('Time [s]')#,fontsize = 18)\nplt.ylabel('Count')#,fontsize = 18)\nplt.legend(['rise times','fall times'])\nfig.savefig('C:/Users/Andrew Blount/Desktop/rise&fall_hist.png',dpi = 300)\nplt.show()\n","sub_path":"d1/d1_crossing_histograms.py","file_name":"d1_crossing_histograms.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"50242817","text":"#\n# Copyright 2022 Ocean Protocol Foundation\n# SPDX-License-Identifier: Apache-2.0\n#\nimport os\nfrom unittest.mock import patch\n\nimport pytest\nfrom requests.exceptions import InvalidURL\nfrom web3.main import Web3\n\nfrom ocean_lib.agreements.consumable import AssetNotConsumable, ConsumableCodes\nfrom ocean_lib.agreements.service_types import ServiceTypes\nfrom ocean_lib.assets.ddo import DDO\nfrom ocean_lib.assets.asset_downloader import download_asset_files, is_consumable\nfrom ocean_lib.data_provider.data_service_provider import DataServiceProvider\nfrom ocean_lib.services.service import Service\nfrom tests.resources.ddo_helpers import (\n create_basics,\n get_first_service_by_type,\n get_sample_ddo,\n)\n\n\n@pytest.mark.unit\ndef test_is_consumable():\n ddo_dict = get_sample_ddo()\n ddo = DDO.from_dict(ddo_dict)\n service_dict = ddo_dict[\"services\"][0]\n service = Service.from_dict(service_dict)\n with patch(\n \"ocean_lib.assets.test.test_asset_downloader.DataServiceProvider.check_asset_file_info\",\n return_value=False,\n ):\n assert (\n is_consumable(ddo, service, {}, True) == ConsumableCodes.CONNECTIVITY_FAIL\n )\n\n with patch(\n \"ocean_lib.assets.test.test_asset_downloader.DataServiceProvider.check_asset_file_info\",\n return_value=True,\n ):\n assert (\n is_consumable(ddo, service, {\"type\": \"address\", \"value\": \"0xdddd\"}, True)\n == ConsumableCodes.CREDENTIAL_NOT_IN_ALLOW_LIST\n )\n\n\n@pytest.mark.unit\ndef test_ocean_assets_download_failure(publisher_wallet):\n \"\"\"Tests that downloading from an empty service raises an AssertionError.\"\"\"\n\n ddo_dict = get_sample_ddo()\n ddo = DDO.from_dict(ddo_dict)\n access_service = get_first_service_by_type(ddo, ServiceTypes.ASSET_ACCESS)\n access_service.service_endpoint = None\n ddo.services[0] = access_service\n\n with pytest.raises(AssertionError):\n download_asset_files(\n ddo,\n access_service,\n publisher_wallet,\n \"test_destination\",\n \"test_order_tx_id\",\n )\n\n\n@pytest.mark.unit\ndef test_invalid_provider_uri(publisher_wallet):\n \"\"\"Tests with invalid provider URI that raise AssertionError.\"\"\"\n ddo_dict = get_sample_ddo()\n ddo = DDO.from_dict(ddo_dict)\n\n with pytest.raises(InvalidURL):\n download_asset_files(\n ddo,\n ddo.services[0],\n publisher_wallet,\n \"test_destination\",\n \"test_order_tx_id\",\n )\n\n\n@pytest.mark.unit\ndef test_invalid_state(publisher_wallet):\n \"\"\"Tests different scenarios that raise AssetNotConsumable.\"\"\"\n ddo_dict = get_sample_ddo()\n ddo = DDO.from_dict(ddo_dict)\n ddo.nft[\"state\"] = 1\n\n with pytest.raises(AssetNotConsumable):\n download_asset_files(\n ddo,\n ddo.services[0],\n publisher_wallet,\n \"test_destination\",\n \"test_order_tx_id\",\n )\n\n ddo.metadata = []\n with pytest.raises(AssetNotConsumable):\n download_asset_files(\n ddo,\n ddo.services[0],\n publisher_wallet,\n \"test_destination\",\n \"test_order_tx_id\",\n )\n\n\n@pytest.mark.integration\ndef test_ocean_assets_download_indexes(\n publisher_wallet, publisher_ocean_instance, tmpdir\n):\n \"\"\"Tests different values of indexes that raise AssertionError.\"\"\"\n\n ddo_dict = get_sample_ddo()\n ddo = DDO.from_dict(ddo_dict)\n\n index = range(3)\n with pytest.raises(TypeError):\n download_asset_files(\n ddo,\n ddo.services[0],\n publisher_wallet,\n \"test_destination\",\n \"test_order_tx_id\",\n index=index,\n )\n\n index = -1\n with pytest.raises(AssertionError):\n download_asset_files(\n ddo,\n ddo.services[0],\n publisher_wallet,\n \"test_destination\",\n \"test_order_tx_id\",\n index=index,\n )\n\n\n@pytest.mark.integration\ndef test_ocean_assets_download_destination_file(\n config,\n tmpdir,\n publisher_wallet,\n publisher_ocean_instance,\n data_nft,\n datatoken,\n):\n \"\"\"Convert tmpdir: py._path.local.LocalPath to str, satisfy enforce-typing.\"\"\"\n ocean_assets_download_destination_file_helper(\n config,\n str(tmpdir),\n publisher_wallet,\n publisher_ocean_instance,\n data_nft,\n datatoken,\n )\n\n\ndef ocean_assets_download_destination_file_helper(\n config,\n tmpdir,\n publisher_wallet,\n publisher_ocean_instance,\n data_nft,\n datatoken,\n):\n \"\"\"Downloading to an existing directory.\"\"\"\n data_provider = DataServiceProvider\n\n _, metadata, files = create_basics(config, data_provider)\n ddo = publisher_ocean_instance.assets.create(\n metadata=metadata,\n publisher_wallet=publisher_wallet,\n files=files,\n data_nft_address=data_nft.address,\n deployed_datatokens=[datatoken],\n )\n access_service = get_first_service_by_type(ddo, ServiceTypes.ASSET_ACCESS)\n\n datatoken.mint(\n publisher_wallet.address,\n Web3.toWei(\"50\", \"ether\"),\n {\"from\": publisher_wallet},\n )\n\n initialize_response = data_provider.initialize(\n did=ddo.did,\n service=access_service,\n consumer_address=publisher_wallet.address,\n )\n\n provider_fees = initialize_response.json()[\"providerFee\"]\n\n receipt = datatoken.start_order(\n consumer=publisher_wallet.address,\n service_index=ddo.get_index_of_service(access_service),\n provider_fee_address=provider_fees[\"providerFeeAddress\"],\n provider_fee_token=provider_fees[\"providerFeeToken\"],\n provider_fee_amount=provider_fees[\"providerFeeAmount\"],\n v=provider_fees[\"v\"],\n r=provider_fees[\"r\"],\n s=provider_fees[\"s\"],\n valid_until=provider_fees[\"validUntil\"],\n provider_data=provider_fees[\"providerData\"],\n consume_market_order_fee_address=publisher_wallet.address,\n consume_market_order_fee_token=datatoken.address,\n consume_market_order_fee_amount=0,\n transaction_parameters={\"from\": publisher_wallet},\n )\n\n orders = publisher_ocean_instance.get_user_orders(\n publisher_wallet.address, datatoken.address\n )\n assert datatoken.address in [order.address for order in orders]\n assert receipt.txid in [order.transactionHash.hex() for order in orders]\n\n written_path = download_asset_files(\n ddo, access_service, publisher_wallet, tmpdir, receipt.txid\n )\n\n assert os.path.exists(written_path)\n\n # index not found, even though tx_id exists\n with pytest.raises(AssertionError):\n download_asset_files(\n ddo,\n ddo.services[0],\n publisher_wallet,\n str(tmpdir),\n receipt.txid,\n index=4,\n )\n","sub_path":"ocean_lib/assets/test/test_asset_downloader.py","file_name":"test_asset_downloader.py","file_ext":"py","file_size_in_byte":6892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"211010776","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 06 14:57:49 2016\n\n@author: aaa34169\n\"\"\"\n\nimport unittest\nimport os\nimport sys\nimport numpy as np\nimport scipy as sp\nfrom scipy import signal\nimport btk\nimport pdb\n\nsys.path.append('C:\\\\Users\\\\AAA34169\\\\Documents\\\\Programming\\\\API\\\\pyCGA\\\\')\n\nimport core.tools as ct\nimport core.cycle as cc\n\n\n\nimport core.motion as cmot\n\nimport core.enums as cenum\n\nimport core.cgmModel as cgm\nimport core.modelFilters as cmf\nimport core.modelDecorator as cmd\nimport core.forceplates as cpf\n\nimport core.btkExecubables as cbtkexe\n\nimport matplotlib.pyplot as plt \n\n\n\n\nif __name__ == \"__main__\":\n\n\n readerStatic = btk.btkAcquisitionFileReader()\n \n \n path=\"C:\\\\Users\\\\AAA34169\\\\Documents\\\\Programming\\\\API\\\\pyCGA-DATA\\\\pyCGA-Nexus2 Data\\\\gait-pig\\\\\"\n filename=\"MRI-US-01, 2008-08-08, 3DGA 02.c3d\"\n \n \n readerStatic.SetFilename(path+filename)\n readerStatic.Update()\n acqStatic=readerStatic.GetOutput()\n \n model=cgm.CGM1ModelInf()\n \n \n subjectInfos={'sex' : 'M' }\n \n calibInfos={'leftFootFlat' : 0, 'rightFootFlat' : 0, \n 'BoolCustomHJC': 0, \n 'BoolCustomKJC': 1,\n 'BoolCustomAJC':1,\n \"TibialTorsionAnkleViconCompatible\":0} # il faut que TibialTorsion=0 pour retrouver la cinematique de cheville \n \n markerDiameter=14 \n \n mp={\n 'mass' : 71.0, # ajouter dans le paramtree \n 'height' : 1755.0, # ajouter dans le paramtree \n 'leftLegLength' : 860.0,\n 'rightLegLength' : 865.0 ,\n 'leftKneeWidth' : 102.0,\n 'rightKneeWidth' : 103.4,\n 'leftAnkleWidth' : 75.3,\n 'rightAnkleWidth' : 72.9,\n 'leftThighOffset' : 0.0,\n 'rightThighOffset' : 0.0,\n 'leftShankOffset' : 0.0,\n 'rightShankOffset' : 0.0,\n 'leftTibialTorsion' : 0.0,\n 'rightTibialTorsion' : 0.0 \n } \n \n model.addAnthropoInputParameter(mp)\n inertialModel = \"Dempster\"\n \n \n # First calibration FILTER \n scp=cmf.StaticCalibrationProcedure(model)\n cmf.ModelCalibrationFilter(scp,acqStatic,model).compute() # Initial calibration\n \n \n # update static c3d\n writerStatic = btk.btkAcquisitionFileWriter()\n writerStatic.SetInput(acqStatic)\n writerStatic.SetFilename(\"calibratedStatic.c3d\")\n writerStatic.Update() \n \n readerGait = btk.btkAcquisitionFileReader()\n filename=\"MRI-US-01, 2008-08-08, 3DGA 12.c3d\"\n readerGait.SetFilename(path+filename)\n readerGait.Update()\n acqGait=readerGait.GetOutput() \n \n # cpf.appendForcePlateCornerAsMarker(acqGait) \n mappedForcePlate = cpf.matchingFootSideOnForceplate(acqGait)\n if len(mappedForcePlate)<3:\n mappedForcePlate = mappedForcePlate + \"X\"\n elif len(mappedForcePlate)>3:\n raise Exception(\"[pycga] Warning : the btk cgm pipeline uses 3 force plates max\")\n \n \n # Motion FILTER \n # optimisation segmentaire et calibration fonctionnel\n modMotion=cmf.ModelMotionFilter(scp,acqGait,model,cmf.motionMethod.Native)\n modMotion.compute()\n \n \n # update dynamic c3d\n writerDyn = btk.btkAcquisitionFileWriter()\n writerDyn.SetInput(acqGait)\n writerDyn.SetFilename(\"calibratedMotion.c3d\")\n writerDyn.Update() \n \n \n # LANCEMENT DES BTK EXECUTABLE\n \n # exemple 1 : cgm avec JC deja dans le fichier motion\n exe1 = cbtkexe.CGM1JointCentresBtkExe()\n exe1.setBoolJointCentres(hips = True, knees = False, ankles = True)\n exe1.setMass(mp[\"mass\"])\n exe1.setGeometricParameters( leftLegLength = mp[\"leftLegLength\"], rightLegLength = mp[\"rightLegLength\"] ,\n leftKneeWidth = mp[\"leftKneeWidth\"], rightKneeWidth = mp[\"rightKneeWidth\"] ,\n leftAnkleWidth = mp[\"leftAnkleWidth\"], rightAnkleWidth = mp[\"rightAnkleWidth\"])\n\n exe1.setFilenameStaticTrial(readerStatic.GetFilename())\n exe1.setFilenameDynamicTrial(readerGait.GetFilename())\n exe1.setMatchingForcePlate(mappedForcePlate)\n exe1.setMomentReferentialProjection(cenum.MomentProjection.Proximal)\n exe1.setSuffix(\"Ttest\")\n exe1.run(display = True, execute = False)\n \n \n # exemple 2 : JC dans le fichier motion + Deleva et algo generic \n exe2 = cbtkexe.CGM1AdvancedBtkExe()\n exe2.setBoolJointCentres(hips = True, knees = False, ankles = True)\n exe2.setMass(mp[\"mass\"])\n exe2.setGeometricParameters( leftLegLength = mp[\"leftLegLength\"], rightLegLength = mp[\"rightLegLength\"] ,\n leftKneeWidth = mp[\"leftKneeWidth\"], rightKneeWidth = mp[\"rightKneeWidth\"] ,\n leftAnkleWidth = mp[\"leftAnkleWidth\"], rightAnkleWidth = mp[\"rightAnkleWidth\"])\n\n exe2.setFilenameStaticTrial(readerStatic.GetFilename())\n exe2.setFilenameDynamicTrial(readerGait.GetFilename())\n exe2.setMatchingForcePlate(mappedForcePlate)\n exe2.setMomentReferentialProjection(cenum.MomentProjection.Proximal)\n exe2.setSuffix(\"Ttest\")\n exe2.setSex(cenum.Sex.Male)\n exe2.setBspModel(cenum.BspModel.Deleva)\n exe2.setInverseDynamicsAlgo(cenum.InverseDynamicAlgo.Generic)\n exe2.run(display = True, execute = False)\n \n \n ","sub_path":"sandbox/runBtkExeModel/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"194956983","text":"# -*- coding: utf-8 -*-\n\"\"\"\n scap.targets\n ~~~~~~~~\n Classes and helpers for getting a list of hosts to do things to\n\"\"\"\nimport collections\nimport os\nimport re\nimport string\n\nfrom . import utils\n\n\ndef get(key, cfg, limit_hosts=None, extra_paths=[]):\n \"\"\"\n Factory function to get a TargetList object to fetch a list of targets.\n\n Right now this is only flat files, mostly from dsh.\n\n :param key: str The primary configuration key to look for,\n combined with the server_groups config\n :param cfg: dict Ordered dictionary of configuration\n :param limit_hosts: str A pattern to limit host names by. See\n limit_target_hosts for further information on the format\n :param extra_paths: list of extra paths to search for list files in\n \"\"\"\n return DshTargetList(key, cfg, limit_hosts, extra_paths)\n\n\ndef limit_target_hosts(pattern, hosts):\n \"\"\"\n Return a subset of hosts based on wildcards.\n\n If the pattern can specify a range of the format '[start:end]'.\n\n If the supplied pattern begins with ``~`` then it is treated as a\n regular expression.\n\n If the pattern begins with ``!`` then it is negated.\n\n :param pattern: str pattern to limit by\n :param hosts: list of hosts to search against\n \"\"\"\n # Return early if there's no special pattern\n if pattern == '*' or pattern == 'all':\n return hosts\n\n # If pattern is a regex, handle that and return\n if pattern[0] == '~':\n regex = re.compile(pattern[1:])\n return [target for target in hosts if regex.match(target)]\n\n patterns = []\n rpattern = pattern\n\n # Handle replacements of anything like [*:*] in pattern\n while(0 <= rpattern.find('[') < rpattern.find(':') < rpattern.find(']')):\n head, nrange, tail = rpattern.replace(\n '[', '|', 1).replace(']', '|', 1).split('|')\n\n beg, end = nrange.split(':')\n zfill = len(end) if (len(beg) > 0 and beg.startswith('0')) else 0\n\n if (zfill != 0 and len(beg) != len(end)) or beg > end:\n raise ValueError(\"Host range incorrectly specified\")\n\n try:\n asc = string.ascii_letters\n seq = asc[asc.index(beg):asc.index(end) + 1]\n except ValueError: # numeric range\n seq = range(int(beg), int(end) + 1)\n\n patterns = [''.join([head, str(i).zfill(zfill), tail]) for i in seq]\n rpattern = rpattern[rpattern.find(']') + 1:]\n\n # If there weren't range replacements, make pattern an array\n if len(patterns) == 0:\n patterns = [pattern]\n\n targets = []\n for pattern in patterns:\n # remove any leading '!'\n test_pattern = pattern.lstrip('!')\n\n # change '.' to literal period\n test_pattern = test_pattern.replace('.', '\\.')\n\n # convert '*' to match a-Z, 0-9, _, -, or .\n test_pattern = test_pattern.replace('*', '[\\w\\.-]*')\n\n # Add beginning and end marks\n test_pattern = '^{}$'.format(test_pattern)\n\n regex = re.compile(test_pattern)\n\n targets.extend([host for host in hosts if regex.match(host)])\n\n # handle regation of patterns by inverting\n if pattern.startswith('!'):\n targets = list(set(targets) ^ set(hosts))\n\n return targets\n\n\nclass TargetList():\n \"\"\"An abstract list of targets (lists of hosts).\"\"\"\n\n def __init__(self, key, cfg, limit_hosts=None, extra_paths=[]):\n \"\"\"\n Constructor for target lists.\n\n :param key: str The primary configuration key to look for,\n combined with the server_groups config\n :param cfg: dict Ordered dictionary of configuration\n :param limit_hosts: str A pattern to limit host names by. See\n limit_target_hosts for further information on the format\n :param extra_paths: list of extra paths to search for list files in\n \"\"\"\n self.primary_key = key\n self.config = cfg\n self.limit_hosts = limit_hosts\n self.extra_paths = extra_paths\n self.deploy_groups = {}\n\n def _get_failure_limit(self, group):\n key = '{}_failure_limit'.format(group)\n return self.config.get(key, self.config.get('failure_limit', None))\n\n def _get_group_size(self, group):\n key = '{}_group_size'.format(group)\n size = self.config.get(key, self.config.get('group_size', None))\n\n return int(size) if size is not None else None\n\n def _get_server_groups(self):\n \"\"\"Get the server_groups from configuration.\"\"\"\n server_groups = self.config.get('server_groups', None)\n\n if server_groups is None:\n server_groups = ['default']\n else:\n server_groups = server_groups.split(',')\n\n return server_groups\n\n def _get_targets_for_key(self, key):\n \"\"\"\n Get a list of hosts for a given configuration key.\n\n All child classes must implement this!\n\n :param key: str Combined key generated from a group + primary key\n \"\"\"\n raise NotImplementedError\n\n def get_deploy_groups(self):\n \"\"\"Get the list of targets and groups to deploy to.\"\"\"\n if self.deploy_groups:\n return self.deploy_groups\n\n groups = collections.OrderedDict()\n all_hosts = []\n server_groups = self._get_server_groups()\n\n for group in server_groups:\n group = group.strip()\n cfg_key = group + '_' + self.primary_key\n if group == 'default':\n cfg_key = self.primary_key\n\n key = self.config.get(cfg_key, None)\n\n if key is None:\n raise RuntimeError(\n 'Reading `{0}` file \"{1}\" failed'.format(cfg_key, key))\n\n targets = self._get_targets_for_key(key)\n\n if self.limit_hosts is not None:\n targets = limit_target_hosts(self.limit_hosts, targets)\n\n targets = list(set(targets) - set(all_hosts))\n\n if len(targets) > 0:\n all_hosts += targets\n\n size = self._get_group_size(group)\n failure_limit = self._get_failure_limit(group)\n\n groups[group] = DeployGroup(group, targets,\n size=size,\n failure_limit=failure_limit)\n\n self.deploy_groups = {'all_targets': all_hosts,\n 'deploy_groups': groups}\n return self.deploy_groups\n\n @property\n def groups(self):\n return self.get_deploy_groups()['deploy_groups']\n\n @property\n def all(self):\n return self.get_deploy_groups()['all_targets']\n\n\nclass DshTargetList(TargetList):\n \"\"\"Fetch from list of hostnames. Historically kept in /etc/dsh/group.\"\"\"\n\n def _get_targets_for_key(self, filename):\n \"\"\"\n Get a list of hosts for a given filename.\n\n :param filename: str Combined filename key generated from a\n group + primary key\n \"\"\"\n search_path = self.extra_paths\n # Historical reasons :p\n search_path.append('/etc/dsh/group')\n hosts_file = None\n\n if os.path.isabs(filename):\n hosts_file = filename\n else:\n for path in search_path:\n candidate = os.path.join(path, filename)\n if os.path.exists(candidate):\n hosts_file = os.path.abspath(candidate)\n break\n\n utils.check_file_exists(hosts_file)\n\n try:\n with open(hosts_file) as f:\n return re.findall(r'^[\\w\\.\\-]+', f.read(), re.MULTILINE)\n except IOError as e:\n raise IOError(e.errno, e.strerror, hosts_file)\n\n\nclass DeployGroup():\n def __init__(self, name, targets, size=None, failure_limit=None):\n \"\"\"\n :param str name: Name of group\n :param list targets: Group target hosts\n :param int size: Size of deploy subgroups\n :param int|str failure_limit: String percentage or int number of\n acceptable failures (e.g. '30%' or 3). Defaults to 1\n \"\"\"\n self.name = name\n self.targets = targets\n self.size = len(targets) if size is None else size\n\n if len(self.targets) < 1 or self.size < 1:\n raise ValueError('a deploy group must have at least one target')\n\n if failure_limit is None:\n failure_limit = 1\n elif type(failure_limit) is str:\n # Convert percentage strings (e.g. '30%') to number of targets\n if failure_limit.endswith('%'):\n failure_limit = float(failure_limit[:-1]) / 100\n failure_limit *= self.original_size\n\n failure_limit = int(failure_limit)\n\n self.failure_limit = failure_limit\n self.excludes = []\n\n def __iter__(self):\n return iter(self.targets)\n\n def exclude(self, target):\n \"\"\"\n Excludes the given target from future iterations of `subgroups`.\n \"\"\"\n self.excludes.append(target)\n\n def subgroups(self):\n \"\"\"\n Generates each deployable subgroup and label according to size.\n\n :yields (str, list): Each subgroup label and list of targets\n \"\"\"\n\n label = self.name\n targets = [host for host in self.targets if host not in self.excludes]\n\n for i in xrange(0, len(targets), self.size):\n if len(targets) > self.size:\n label = self.name + str((i / self.size) + 1)\n\n yield label, targets[i:i + self.size]\n\n @property\n def original_size(self):\n return len(self.targets)\n","sub_path":"scap/targets.py","file_name":"targets.py","file_ext":"py","file_size_in_byte":9570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"80787905","text":"import sys\n\ninput = sys.stdin.readline\n\narr = [0]*10001\n\nfor i in range(int(input())):\n arr[int(input())] += 1\n\nfor i, a in enumerate(arr):\n if a == 0: continue\n print(f\"{i}\\n\"*a, end=\"\")","sub_path":"BOJ/10989.py","file_name":"10989.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"219298562","text":"'''\nSplitting all the data into train, test and validation part.\n\n@author: sophia\n@github: https://github.com/sophia-hxw/PythonBase\n@data: 20170525\n'''\n\nglobal trainPer\ntrainPer=0.7\t\t\t#percentage of samples for train\nglobal valiPer\nvaliPer=0.1\t\t\t\t#percentage of samples for validation\nglobal testPer\ntestPer=0.2\t\t\t\t#percentage of samples for test\nglobal classNum\nclassNum=4\n\n'''\nindex=0\t\treturn training label and data;\nindex=1\t\treturn validation label and data;\nindex=2\t\treturn testing label and data.\n'''\ndef splitTrainValTest(dataMat, labelMat, index):\n\tclassAll=[]\n\tclaSamNum=[]\n\tfor ia in range(classNum):\n\t\tnumbers=labelMat.count(ia)\n\t\ttrainNum=int(numbers*trainPer)\n\t\tvalidNum=int(numbers*valiPer)\n\t\ttestNum=int(numbers*testPer)\n\t\tclaSamNum.append(numbers)\n\t\tclassAll.append([trainNum, validNum, testNum])\n\t#print(classAll)\n\t#print(classAll[3][1])\n\t\n\tinLabel=[]\n\tinData=[]\n\tstartN=0\n\tif index==0:\n\t\tfor ib in range(classNum):\n\t\t\tendN=startN+classAll[ib][0]\n\t\t\tinLabel.extend(labelMat[startN:endN])\n\t\t\tinData.extend(dataMat[startN:endN][:])\n\t\t\tstartN=startN+claSamNum[ib]\n\telif index==1:\n\t\tfor ic in range(classNum):\n\t\t\tendN=startN+classAll[ic][1]\n\t\t\tinLabel.extend(labelMat[startN:endN])\n\t\t\tinData.extend(dataMat[startN:endN][:])\n\t\t\tstartN=startN+claSamNum[ic]\n\telse:\n\t\tfor id in range(classNum):\n\t\t\tendN=startN+classAll[id][2]\n\t\t\tinLabel.extend(labelMat[startN:endN])\n\t\t\tinData.extend(dataMat[startN:endN][:])\n\t\t\tstartN=startN+claSamNum[id]\n\t\n\treturn inLabel, inData","sub_path":"trainTestValidation.py","file_name":"trainTestValidation.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"18562480","text":"from django.test import TestCase\nimport unittest\n# Create your tests here.\n# import sys\n# sys.path.append('/admin/sorting')\nfrom models import MySum, Palindrome\n\nclass TestMySum(unittest.TestCase):\n def test_one_to_ten_sum_1(self):\n instance = MySum()\n instance.start_number = 1\n instance.end_number = 11\n res = instance.one_to_ten_sum_1()\n print(f'My Expected Value is {res}')\n self.assertEqual(res, 55)\n\nclass TestPalindrome(unittest.TestCase):\n\n def test_str_to_list(self):\n instance = Palindrome()\n instance.input_string = 'applyyrthE'\n ls = instance.str_to_list()\n print(f'My Expected Value is {ls}')\n res = instance.isPalindrome(ls)\n print(f'My Expected Value is {res}')\n self.assertEqual(res, {False})\n\n def test_reverse_string(self):\n instance = Palindrome()\n instance.input_string = 'applE'\n ls = instance.str_to_list()\n print(f'My Expected Value is {ls}')\n res = instance.reverse_string(ls)\n self.assertEqual(res, ['e', 'l', 'p', 'p', 'a'])\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"backend-old/admin/sorting/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"553174370","text":"class Solution(object):\n def findItinerary(self, tickets):\n \"\"\"\n :type tickets: List[List[str]]\n :rtype: List[str]\n \"\"\"\n tickets.sort(key = lambda i: i[1])\n def visit(airport):\n while dict[airport]:\n visit(dict[airport].pop(0))\n rst.append(airport)\n \n dict = collections.defaultdict(list)\n for start, end in tickets:\n dict[start].append(end)\n rst = []\n visit('JFK')\n return rst[::-1]\n \n ","sub_path":"332-Reconstruct-Itinerary/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"368471181","text":"\"\"\"\nTrading-Technical-Indicators (tti) python library\n\nFile name: _machine_learning_api.py\n Defines the API for the Machine Learning features of the tti library.\n\"\"\"\n\nimport joblib\n\nfrom abc import ABC, abstractmethod\nfrom ..utils.constants import ML_CLASSES\nfrom ..utils.constants import ALL_TI_FEATURES\nfrom ._machine_learning_data import MachineLearningData\n\n\nclass MachineLearningAPI(ABC):\n \"\"\"\n Machine Learning API class implementation.\n\n Args:\n model_type (str): The model type of the trained model (i.e. MLP, DT).\n It is set by the child class.\n\n Attributes:\n _model (object): The trained model object.\n\n _scaler (sklearn.preprocessing.StandardScaler): Scaler used with the\n training data.\n\n _model_details (dict): Dictionary with model details. It contains the\n ``model_type`` see model_type argument, ``training_score`` the\n score of the trained model on the training data, ``test_score`` the\n score of the trained model on the test data,\n ``number_of_training_instances`` the number of instances used to\n train the model, ``classes`` a definition (dict) of the classes,\n ``scaler_used`` whether a scaler used with the training data, and\n ``dump_file`` the file where the model is saved.\n \"\"\"\n \n def __init__(self, model_type):\n\n # Trained model, when None there is not any trained model yet\n self._model = None\n\n # Data scaler, when None there is not any scaler used\n self._scaler = None\n\n # Training score, test score, and number of training instances are set\n # by the child class\n self._model_details = {'model_type': model_type,\n 'training_score': None,\n 'test_score': None,\n 'number_of_training_instances': None,\n 'classes': ML_CLASSES,\n 'scaler_used': False,\n 'dump_file': None}\n\n def mlSaveModel(self, file_name):\n \"\"\"\n Saves the trained model to a file.\n\n Args:\n file_name (str): The file where the serialized trained model should\n be saved.\n \"\"\"\n\n self._model_details['dump_file'] = file_name\n\n self._model_details['scaler_used'] = False if self._scaler is None \\\n else True\n\n with open(file_name, 'wb') as out_file:\n joblib.dump((self._scaler, self._model, self._model_details),\n out_file)\n\n def mlLoadModel(self, file_name):\n \"\"\"\n Loads a trained model from a file.\n\n Args:\n file_name (str): The file from where the trained model should be\n deserialized.\n \"\"\"\n\n with open(file_name, 'rb') as in_file:\n self._scaler, self._model, self._model_details = \\\n joblib.load(in_file)\n\n def mlModelDetails(self):\n \"\"\"\n Returns details about the trained model.\n\n Returns:\n dict: The model details dictionary. See class attributes for\n details.\n \"\"\"\n\n self._model_details['scaler_used'] = False if self._scaler is None \\\n else True\n\n return self._model_details\n\n @abstractmethod\n def mlTrainModel(self, **kwargs):\n \"\"\"\n Trains a machine learning model for prices direction predictions.\n \"\"\"\n\n raise NotImplementedError\n\n def mlPredict(self, input_data):\n \"\"\"\n Returns a prediction.\n\n Args:\n input_data (pandas.DataFrame): The input data. Required input\n columns are ``high``, ``low``, ``open``, ``close`` and\n ``volume``. The index is of type ``pandas.DatetimeIndex``. The\n minimum number of data required for prediction is 60 periods.\n\n Returns:\n (str, int): The class predicted by the trained model. Possible\n return values are ('DOWN', 0) and ('UP', 1).\n \"\"\"\n\n # Calculate input features for the prediction of the next period\n data = MachineLearningData(\n input_data=input_data,\n ti_features=ALL_TI_FEATURES,\n include_close_feature=True,\n include_volume_feature=True,\n verbose=False).createPredictionData().values[-1, :].reshape(1, -1)\n\n if self._scaler is not None:\n data = self._scaler.transform(X=data)\n\n prediction = self._model.predict(X=data)\n\n for k, v in ML_CLASSES.items():\n if v == prediction:\n return k, v\n","sub_path":"tti/ml/_machine_learning_api.py","file_name":"_machine_learning_api.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"528442677","text":"\"\"\"\nGiven an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.\n\nExample:\n Given nums = [-2, 0, 3, -5, 2, -1]\n sumRange(0, 2) -> 1\n sumRange(2, 5) -> -1\n sumRange(0, 5) -> -3\n\nNote:\n You may assume that the array does not change.\n There are many calls to sumRange function.\n\"\"\"\n\n\nclass NumArray(object):\n\n def __init__(self, nums):\n self.sum_list = list()\n sum = 0\n for num in nums:\n sum += num\n self.sum_list.append(sum)\n \"\"\"\n :type nums: List[int]\n \"\"\"\n\n def sumRange(self, i, j):\n if i > 0:\n return self.sum_list[j] - self.sum_list[i - 1]\n else:\n return self.sum_list[j]\n\nnums = [-2, 0, 3, -5, 2, -1]\nobj = NumArray(nums)\nprint(obj.sumRange(0, 5))\n","sub_path":"LeetCode-Python/303 Range Sum Query - Immutable.py","file_name":"303 Range Sum Query - Immutable.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"252287788","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2018-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nimport os\nimport shutil\nimport subprocess\nimport unittest\nfrom pathlib import Path\nfrom typing import Optional, Set\n\nfrom eden.cli.util import poll_until\nfrom eden.thrift import EdenClient, EdenNotRunningError\nfrom facebook.eden.ttypes import (\n EdenError,\n FaultDefinition,\n MountState,\n UnblockFaultArg,\n WorkingDirectoryParents,\n)\nfrom fb303.ttypes import fb_status\nfrom thrift.Thrift import TException\n\nfrom .lib import testcase\n\n\n@testcase.eden_repo_test\nclass MountTest(testcase.EdenRepoTest):\n expected_mount_entries: Set[str]\n enable_fault_injection: bool = True\n\n def populate_repo(self) -> None:\n self.repo.write_file(\"hello\", \"hola\\n\")\n self.repo.write_file(\"adir/file\", \"foo!\\n\")\n self.repo.write_file(\"bdir/test.sh\", \"#!/bin/bash\\necho test\\n\", mode=0o755)\n self.repo.write_file(\"bdir/noexec.sh\", \"#!/bin/bash\\necho test\\n\")\n self.repo.symlink(\"slink\", \"hello\")\n self.repo.commit(\"Initial commit.\")\n\n self.expected_mount_entries = {\".eden\", \"adir\", \"bdir\", \"hello\", \"slink\"}\n\n def test_remove_unmounted_checkout(self) -> None:\n # Clone a second checkout mount point\n mount2 = os.path.join(self.mounts_dir, \"mount2\")\n self.eden.clone(self.repo_name, mount2)\n self.assertEqual(\n {self.mount: \"RUNNING\", mount2: \"RUNNING\"}, self.eden.list_cmd_simple()\n )\n\n # Now unmount it\n self.eden.run_cmd(\"unmount\", mount2)\n self.assertEqual(\n {self.mount: \"RUNNING\", mount2: \"NOT_RUNNING\"}, self.eden.list_cmd_simple()\n )\n # The Eden README telling users what to do if their mount point is not mounted\n # should be present in the original mount point directory.\n self.assertTrue(os.path.exists(os.path.join(mount2, \"README_EDEN.txt\")))\n\n # Now use \"eden remove\" to destroy mount2\n self.eden.remove(mount2)\n self.assertEqual({self.mount: \"RUNNING\"}, self.eden.list_cmd_simple())\n self.assertFalse(os.path.exists(mount2))\n\n def test_unmount_remount(self) -> None:\n # write a file into the overlay to test that it is still visible\n # when we remount.\n filename = os.path.join(self.mount, \"overlayonly\")\n with open(filename, \"w\") as f:\n f.write(\"foo!\\n\")\n\n self.assert_checkout_root_entries(self.expected_mount_entries | {\"overlayonly\"})\n self.assertTrue(self.eden.in_proc_mounts(self.mount))\n\n # do a normal user-facing unmount, preserving state\n self.eden.run_cmd(\"unmount\", self.mount)\n\n self.assertFalse(self.eden.in_proc_mounts(self.mount))\n entries = set(os.listdir(self.mount))\n self.assertEqual({\"README_EDEN.txt\"}, entries)\n\n # Now remount it with the mount command\n self.eden.run_cmd(\"mount\", self.mount)\n\n self.assertTrue(self.eden.in_proc_mounts(self.mount))\n self.assert_checkout_root_entries(self.expected_mount_entries | {\"overlayonly\"})\n\n with open(filename, \"r\") as f:\n self.assertEqual(\"foo!\\n\", f.read(), msg=\"overlay file is correct\")\n\n def test_double_unmount(self) -> None:\n # Test calling \"unmount\" twice. The second should fail, but edenfs\n # should still work normally afterwards\n self.eden.run_cmd(\"unmount\", self.mount)\n self.eden.run_unchecked(\"unmount\", self.mount)\n\n # Now remount it with the mount command\n self.eden.run_cmd(\"mount\", self.mount)\n\n self.assertTrue(self.eden.in_proc_mounts(self.mount))\n self.assert_checkout_root_entries({\".eden\", \"adir\", \"bdir\", \"hello\", \"slink\"})\n\n def test_unmount_succeeds_while_file_handle_is_open(self) -> None:\n fd = os.open(os.path.join(self.mount, \"hello\"), os.O_RDWR)\n # This test will fail or time out if unmounting times out.\n self.eden.run_cmd(\"unmount\", self.mount)\n # Surprisingly, os.close does not return an error when the mount has\n # gone away.\n os.close(fd)\n\n def test_unmount_succeeds_while_dir_handle_is_open(self) -> None:\n fd = os.open(self.mount, 0)\n # This test will fail or time out if unmounting times out.\n self.eden.run_cmd(\"unmount\", self.mount)\n # Surprisingly, os.close does not return an error when the mount has\n # gone away.\n os.close(fd)\n\n def test_mount_init_state(self) -> None:\n self.eden.run_cmd(\"unmount\", self.mount)\n self.assertEqual({self.mount: \"NOT_RUNNING\"}, self.eden.list_cmd_simple())\n\n with self.eden.get_thrift_client() as client:\n fault = FaultDefinition(keyClass=\"mount\", keyValueRegex=\".*\", block=True)\n client.injectFault(fault)\n\n # Run the \"eden mount\" CLI command.\n # This won't succeed until we unblock the mount.\n mount_cmd = self.eden.get_eden_cli_args(\"mount\", self.mount)\n mount_proc = subprocess.Popen(mount_cmd)\n\n # Wait for the new mount to be reported by edenfs\n def mount_started() -> Optional[bool]:\n if self.eden.get_mount_state(Path(self.mount), client) is not None:\n return True\n if mount_proc.poll() is not None:\n raise Exception(\n f\"eden mount command finished (with status \"\n f\"{mount_proc.returncode}) while mounting was \"\n f\"still blocked\"\n )\n return None\n\n poll_until(mount_started, timeout=30)\n self.assertEqual({self.mount: \"INITIALIZING\"}, self.eden.list_cmd_simple())\n\n # Most thrift calls to access the mount should be disallowed while it is\n # still initializing.\n self._assert_thrift_calls_fail_during_mount_init(client)\n\n # Unblock mounting and wait for the mount to transition to running\n client.unblockFault(UnblockFaultArg(keyClass=\"mount\", keyValueRegex=\".*\"))\n\n self._wait_for_mount_running(client)\n self.assertEqual({self.mount: \"RUNNING\"}, self.eden.list_cmd_simple())\n\n def _assert_thrift_calls_fail_during_mount_init(self, client: EdenClient) -> None:\n error_regex = \"mount point .* is still initializing\"\n mount_path = Path(self.mount)\n null_commit = b\"\\00\" * 20\n\n with self.assertRaisesRegex(EdenError, error_regex):\n client.getFileInformation(mountPoint=bytes(mount_path), paths=[b\"\"])\n\n with self.assertRaisesRegex(EdenError, error_regex):\n client.getScmStatus(\n mountPoint=bytes(mount_path), listIgnored=False, commit=null_commit\n )\n\n parents = WorkingDirectoryParents(parent1=null_commit)\n with self.assertRaisesRegex(EdenError, error_regex):\n client.resetParentCommits(mountPoint=bytes(mount_path), parents=parents)\n\n def test_start_blocked_mount_init(self) -> None:\n self.eden.shutdown()\n self.eden.spawn_nowait(\n extra_args=[\"--enable_fault_injection\", \"--fault_injection_block_mounts\"]\n )\n\n # Wait for eden to report the mount point in the listMounts() output\n def is_initializing() -> Optional[bool]:\n try:\n with self.eden.get_thrift_client() as client:\n if self.eden.get_mount_state(Path(self.mount), client) is not None:\n return True\n assert self.eden._process is not None\n if self.eden._process.poll():\n self.fail(\"eden exited before becoming healthy\")\n return None\n except (EdenNotRunningError, TException):\n return None\n\n poll_until(is_initializing, timeout=60)\n with self.eden.get_thrift_client() as client:\n # Since we blocked mount initialization the mount should still\n # report as INITIALIZING, and edenfs should report itself STARTING\n self.assertEqual({self.mount: \"INITIALIZING\"}, self.eden.list_cmd_simple())\n self.assertEqual(fb_status.STARTING, client.getStatus())\n\n # Unblock mounting and wait for the mount to transition to running\n client.unblockFault(UnblockFaultArg(keyClass=\"mount\", keyValueRegex=\".*\"))\n self._wait_for_mount_running(client)\n self.assertEqual(fb_status.ALIVE, client.getStatus())\n\n self.assertEqual({self.mount: \"RUNNING\"}, self.eden.list_cmd_simple())\n\n def test_start_no_mount_wait(self) -> None:\n self.eden.shutdown()\n self.eden.start(\n extra_args=[\n \"--noWaitForMounts\",\n \"--enable_fault_injection\",\n \"--fault_injection_block_mounts\",\n ]\n )\n self.assertEqual({self.mount: \"INITIALIZING\"}, self.eden.list_cmd_simple())\n\n # Unblock mounting and wait for the mount to transition to running\n with self.eden.get_thrift_client() as client:\n self.assertEqual(fb_status.ALIVE, client.getStatus())\n client.unblockFault(UnblockFaultArg(keyClass=\"mount\", keyValueRegex=\".*\"))\n self._wait_for_mount_running(client)\n\n self.assertEqual({self.mount: \"RUNNING\"}, self.eden.list_cmd_simple())\n\n def _wait_for_mount_running(self, client: EdenClient) -> None:\n def mount_running() -> Optional[bool]:\n if (\n self.eden.get_mount_state(Path(self.mount), client)\n == MountState.RUNNING\n ):\n return True\n return None\n\n poll_until(mount_running, timeout=60)\n\n def test_remount_creates_mount_point_dir(self) -> None:\n \"\"\"Test that eden will automatically create the mount point directory if\n needed when it is setting up its mount points.\n \"\"\"\n # Create a second checkout in a directory a couple levels deep so that\n # we can remove some of the parent directories of the checkout.\n checkout_path = Path(self.tmp_dir) / \"checkouts\" / \"stuff\" / \"myproject\"\n self.eden.run_cmd(\"clone\", self.repo.path, str(checkout_path))\n self.assert_checkout_root_entries(self.expected_mount_entries, checkout_path)\n\n self.eden.run_cmd(\"unmount\", str(checkout_path))\n self.assertEqual(\n {self.mount: \"RUNNING\", str(checkout_path): \"NOT_RUNNING\"},\n self.eden.list_cmd_simple(),\n )\n\n # Confirm that \"eden mount\" recreates the mount point directory\n shutil.rmtree(Path(self.tmp_dir) / \"checkouts\")\n self.eden.run_cmd(\"mount\", str(checkout_path))\n self.assert_checkout_root_entries(self.expected_mount_entries, checkout_path)\n self.assertTrue(self.eden.in_proc_mounts(str(checkout_path)))\n self.assertEqual(\n {self.mount: \"RUNNING\", str(checkout_path): \"RUNNING\"},\n self.eden.list_cmd_simple(),\n )\n\n # Also confirm that Eden recreates the mount points on startup as well\n self.eden.shutdown()\n shutil.rmtree(Path(self.tmp_dir) / \"checkouts\")\n shutil.rmtree(self.mount_path)\n self.eden.start()\n self.assertEqual(\n {self.mount: \"RUNNING\", str(checkout_path): \"RUNNING\"},\n self.eden.list_cmd_simple(),\n )\n self.assert_checkout_root_entries(self.expected_mount_entries, checkout_path)\n\n # Check the behavior if Eden fails to create one of the mount point directories.\n # We just confirm that Eden still starts and mounts the other checkout normally\n # in this case.\n self.eden.shutdown()\n checkouts_dir = Path(self.tmp_dir) / \"checkouts\"\n shutil.rmtree(checkouts_dir)\n checkouts_dir.write_text(\"now a file\\n\")\n self.eden.start()\n self.assertEqual(\n {self.mount: \"RUNNING\", str(checkout_path): \"NOT_RUNNING\"},\n self.eden.list_cmd_simple(),\n )\n\n def test_remount_creates_bind_mounts_if_needed(self) -> None:\n # Add a repo definition to the config that includes some bind mounts.\n edenrc = os.path.join(self.home_dir, \".edenrc\")\n project_id = \"myproject\"\n with open(edenrc, \"w\") as f:\n f.write(\n f\"\"\"\\\n[\"repository {project_id}\"]\npath = \"{self.repo.get_canonical_root()}\"\ntype = \"{self.repo.get_type()}\"\n\n[\"bindmounts {project_id}\"]\nbuck-out = \"buck-out\"\nxplat-buck-out = \"xplat/buck-out\"\n\"\"\"\n )\n\n # Clone the repository\n checkout_path = Path(self.tmp_dir) / \"myproject_clone\"\n self.eden.run_cmd(\"clone\", project_id, str(checkout_path))\n checkout_state_dir = self.eden.client_dir_for_mount(checkout_path)\n bind_mounts_src_dir = checkout_state_dir / \"bind-mounts\"\n\n # Check that the bind mounts are set up correctly\n bind_src1 = bind_mounts_src_dir / \"buck-out\"\n bind_dest1 = checkout_path / \"buck-out\"\n bind_src2 = bind_mounts_src_dir / \"xplat-buck-out\"\n bind_dest2 = checkout_path / \"xplat\" / \"buck-out\"\n self._assert_bind_mounted(bind_src1, bind_dest1)\n self._assert_bind_mounted(bind_src2, bind_dest2)\n\n # Unmount this checkout\n self.eden.run_cmd(\"unmount\", str(checkout_path))\n\n # Remove the bind-mount source directories.\n # This shouldn't really happen in normal practice, but in some cases users have\n # manually deleted these directories when trying to clean up disk space to\n # recover from disk full situations.\n shutil.rmtree(bind_mounts_src_dir)\n\n # Remount the checkout and make sure the bind mounts\n # still got recreated correctly\n self.eden.run_cmd(\"mount\", str(checkout_path))\n self._assert_bind_mounted(bind_src1, bind_dest1)\n self._assert_bind_mounted(bind_src2, bind_dest2)\n\n # Also check that the bind mounts are recreated by \"eden start\"\n self.eden.shutdown()\n shutil.rmtree(bind_mounts_src_dir)\n self.eden.start()\n self._assert_bind_mounted(bind_src1, bind_dest1)\n self._assert_bind_mounted(bind_src2, bind_dest2)\n\n def _assert_bind_mounted(self, src: Path, dest: Path) -> None:\n # Both the source and destination paths should exist,\n # and should refer to the same directory\n src_stat = src.lstat()\n dest_stat = dest.lstat()\n self.assertEqual(\n (src_stat.st_dev, src_stat.st_ino), (dest_stat.st_dev, dest_stat.st_ino)\n )\n","sub_path":"eden/integration/mount_test.py","file_name":"mount_test.py","file_ext":"py","file_size_in_byte":14750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"2467486","text":"# цикл while\n\nnumber = int(input(\"Введите целое число от 0 до 9: \"))\n\nwhile number < 10:\n print(number)\n number += 1\n\nprint(\"Программа завершена\")\n\n# зацикливание\n# a = 5\n# while a > 0:\n# print(\"!\", end='')\n\n# инструкции break, continue\ni = 0\nwhile True:\n i += 1\n if i > 7:\n print(\"i > 7! Выходим из цикла\")\n break\n if i % 2 != 0:\n print(\"i нечетное! Начинаем цикл заново\")\n continue\n print(\"Число i равно \", i)\n","sub_path":"1289_lesson1/while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"393653017","text":"from lexer import Lexer\nfrom parser import Parser\nfrom codegen import CodeGen\n\ncode = \"\"\"\nprint(4 + 4-2);\n\"\"\"\n\nlexer = Lexer().get_lexer()\ntokens = lexer.lex(code)\n\ncodegen = CodeGen()\n\npg = Parser(codegen.module, codegen.builder, codegen.printf)\npg.parse()\n\nparser = pg.get_parser()\nparser.parse(tokens).eval()\n\ncodegen.create_ir()\ncodegen.save_ir(\"output.ll\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"522832331","text":"import mwclient, datetime\n\nclass ExtendedSite(mwclient.Site):\n\tdef cargoquery(self, **kwargs):\n\t\tresponse = self.api('cargoquery', **kwargs)\n\t\tret = []\n\t\tfor item in response['cargoquery']:\n\t\t\tret.append(item['title'])\n\t\treturn ret\n\t\n\tdef cargo_pagelist(self, fields=None, limit=\"max\", page_pattern = \"%s\", **kwargs):\n\t\tfield = fields.split('=')[1] if '=' in fields else fields\n\t\tgroup_by = fields.split('=')[0]\n\t\tresponse = self.api('cargoquery',\n\t\t\tfields=fields,\n\t\t\tgroup_by=group_by,\n\t\t\tlimit=limit,\n\t\t\t**kwargs\n\t\t)\n\t\tpages = []\n\t\tfor item in response['cargoquery']:\n\t\t\tpage = page_pattern % item['title'][field]\n\t\t\tif page in pages:\n\t\t\t\tcontinue\n\t\t\tpages.append(page)\n\t\t\tyield(self.pages[page])\n\t\n\tdef recentchanges_by_interval(self, interval, offset=0, prop='title|ids', **kwargs):\n\t\tnow = datetime.datetime.utcnow() - datetime.timedelta(minutes=offset)\n\t\tthen = now - datetime.timedelta(minutes=interval)\n\t\tresult = self.recentchanges(\n\t\t\tstart=now.isoformat(),\n\t\t\tend=then.isoformat(),\n\t\t\tlimit='max',\n\t\t\tprop=prop,\n\t\t\t**kwargs\n\t\t)\n\t\treturn result\n\t\n\tdef patrol_recent(self, interval, f, **kwargs):\n\t\trevisions = self.recentchanges_by_interval(interval, prop='title|ids|patrolled', **kwargs)\n\t\tpatrol_token = self.get_token('patrol')\n\t\tfor revision in revisions:\n\t\t\t# revid == 0 if the page was deleted, so it can't be deleted\n\t\t\tif f(revision) and revision['revid'] != 0 and 'unpatrolled' in revision:\n\t\t\t\tself.api('patrol', revid = revision['revid'], token = patrol_token)\n\nclass GamepediaSite(ExtendedSite):\n\tdef __init__(self, user, wiki):\n\t\tsuper().__init__('%s.gamepedia.com' % wiki, path='/')\n\t\tpwd_file = 'password2.txt' if user == 'bot' else 'password.txt'\n\t\tuser_file = 'username2.txt' if user == 'bot' else 'username.txt'\n\t\tpwd = open(pwd_file).read().strip()\n\t\tusername = open(user_file).read().strip()\n\t\tself.login(username, pwd)\n","sub_path":"extended_site.py","file_name":"extended_site.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"364390900","text":"# ------\n# Robot.py class\n# This runs the robot.\n# Copyright 2015. Pioneers in Engineering.\n# ------\n'''\nThis module contains functions for reading data from the robot, and for\nmanipulating the robot.\n\nTo use this module, you must first import it:\n\n>>> from api import Robot\n>>> from api.Robot import *\n'''\n# Connect to memcache\nimport memcache\nmemcache_port = 12357\nmc = memcache.Client(['127.0.0.1:%d' % memcache_port]) # connect to memcache\n\nmotor = {}\n\n_naming_map_filename = 'student_code/CustomID.txt'\n_name_to_id = {} # Mapping from motor name to device_id, both are strings\ntry:\n with open(_naming_map_filename, \"r\") as f:\n for line in f.readlines():\n line = line.strip()\n device_id, name = line.split(\" \", 1)\n _name_to_id[name] = device_id\nexcept:\n print(\"Could not read naming map\")\n\ndef _lookup(name):\n if name in _name_to_id:\n return _name_to_id[name]\n return name\n\ndef is_autonomous():\n \"\"\"Returns the autonomous state of the game.\n\n :param name: None\n :returns: A boolean.\n\n :Examples:\n\n >>> if is_autonomous():\n set_motor('motor1', 0.5)\n\n \"\"\"\n return mc.get('game')['autonomous']\n\ndef is_enabled():\n \"\"\"Returns whether the robot is enabled.\n\n :param name: None\n :returns: A boolean.\n\n :Examples:\n\n >>> if is_enabled():\n set_motor('motor1', 0.5)\n\n \"\"\"\n return mc.get('game')['enabled']\n\ndef get_motor(name):\n \"\"\"Returns the current power value for a motor.\n\n :param name: A string that identifies the motor\n :returns: A value between -1 and 1, which is the power level of that motor.\n\n :Examples:\n\n >>> motor = get_motor(\"motor1\")\n\n \"\"\"\n device_id = _lookup(name)\n name_to_value = mc.get('motor_values')\n assert type(device_id) is str, \"Type Mismatch: Must pass in a string\"\n try:\n return name_to_value[device_id]/100\n except KeyError:\n raise KeyError(\"Motor name not found.\")\n\ndef set_motor(name, value):\n \"\"\"Sets a motor to the specified power value.\n\n :param name: A string that identifies the motor.\n :param value: A decimal value between -1 and 1, the power level you want to set.\n\n :Examples:\n\n >>> set_motor(\"motor1\", .50)\n\n \"\"\"\n assert type(name) is str, \"Type Mismatch: Must pass in a string to name.\"\n assert type(value) is int or type(value) is float, \"Type Mismatch: Must pass in an integer or float to value.\"\n assert value <= 1 and value >= -1, \"Motor value must be a decimal between -1 and 1 inclusive.\"\n device_id = _lookup(name)\n name_to_value = mc.get('motor_values')\n if device_id not in name_to_value:\n raise KeyError(\"No motor with that name\")\n name_to_value[device_id] = value*100\n mc.set('motor_values', name_to_value)\n\ndef get_sensor(name):\n \"\"\"Returns the value, or reading corresponding to the specified sensor.\n\n WARNING: This is a default get method and should only be used if the sensor in question\n does not have a specific get function.\n You should always use a specific sensor's get function if specified in this doc.\n\n :param name: A string that identifies the sensor.\n :returns: The reading of the sensor at the current point in time.\n\n :Examples:\n\n >>> get_sensor(\"sensor1\")\n\n \"\"\"\n device_id = _lookup(name)\n all_data = mc.get('sensor_values')\n try:\n return all_data[device_id]\n except KeyError:\n raise KeyError(\"No Sensor with that name\")\n\ndef get_all_motors():\n \"\"\"Returns the current power values for every connected motor.\n \"\"\"\n return mc.get('motor_values')\n\ndef set_led(num, value):\n \"\"\"Sets a specific LED on the team flag\n\n :param num: The number of the LED (0, 1, 2, or 3)\n :param value: A boolean value\n\n :Examples:\n\n >>> set_LED(0, False)\n >>> set_LED(1, True)\n \"\"\"\n flag_data = mc.get('flag_values')\n flag_data[num] = value\n mc.set('flag_values', flag_data)\n\ndef set_servo(name,value): #TODO Check with hibike on exact functionality\n \"\"\"Sets a degree for a specific servo to turn.\n\n One servo, as specified by its name, is set to turn to an integer amount of degrees (0-180)\n\n :param name: A string that identifies the servo\n :param value: An integer between 0 and 180 which sets the amount to turn to in degrees\n\n :Examples:\n\n >>> set_servo(\"servo1\",90)\n >>> set_servo(\"servo3\",150)\n\n \"\"\"\n assert 0 <= value <= 180, \"Servo degrees must be between 20 and 160\"\n device_id = _lookup(name)\n _testConnected(device_id)\n servo_values = mc.get('servo_values')\n servo_values[device_id] = value\n mc.set('servo_values', servo_values)\n\ndef get_servo(name):\n \"\"\"Gets the degree that a servo is set to.\n\n Each servo is set to an integer degree value (0-180). This function returns\n what value the servo is currently set to.\n\n :param name: A string that identifies the servo\n\n :Examples:\n\n >>> get_servo(\"servo1\")\n 45\n\n \"\"\"\n device_id = _lookup(name)\n value = _testConnected(device_id)\n return value\n\ndef get_rgb(name):\n \"\"\"Returns a list of rgb values from the specified color sensor.\n\n Each value for red, green, and blue will return a\n number between 0 and 255, where 255 indicates a higher intensity. This function returns\n the result from one specific color sensor.\n\n :param name: A string that identifies the color sensor\n :returns: A list of integers in the order of values for red, green, blue\n\n :Examples:\n\n >>> color = get_color_sensor(\"color1\")\n >>> color\n [100, 240, 150]\n\n \"\"\"\n device_id = _lookup(name)\n data = _testConnected(device_id)\n red = data[0]\n green = data[1]\n blue = data[2]\n return [red, green, blue]\n\ndef get_luminosity(name):\n \"\"\"Returns the luminosity for the specified color sensor.\n\n The color sensor returns the luminosity detected by the color sensor, represnted by\n a decimal where larger numbers indicates higher intensity.\n\n :param name: A string that identifies the color sensor\n :returns: A double where a larger number indicates a higher intensity\n\n :Examples:\n\n >>> lum_berry = get_luminosity(\"color1\")\n\n \"\"\"\n device_id = _lookup(name)\n return _testConnected(device_id)[3]\n\ndef get_hue(name):\n \"\"\"Returns the hue detected at the specified color sensor.\n\n This uses the red, green, and blue sensors on the color sensor to return the\n detected hue, which is represented as a double between 0 and 360. See\n https://en.wikipedia.org/wiki/Hue for more information on hue.\n\n :param name: A string that identifies the color sensor\n :returns: A double between 0 and 360 representing the detected hue\n\n :Examples:\n\n >>> hue = get_hue(\"color1\")\n >>> hue\n 254.01\n\n \"\"\"\n device_id = _lookup(name)\n return _testConnected(device_id)[4]\n\ndef toggle_light(name, status):\n \"\"\"Turns the light on specfied color sensor on or off.\n\n Takes in the name of the specified color sensor and a boolean (True for on, False for off).\n\n :param name: A string that identifies the color sensor.\n :param status: A boolean that determines whether the light should be on (True) or off (False)\n\n >>> toggle_light(\"color1\", True)\n >>> toggle_light(\"color2\", False)\n\n \"\"\"\n device_id = _lookup(name)\n _testConnected(device_id)\n if (status):\n write_value = 1\n else:\n write_value = 0\n mc.set(\"toggle_light\", [device_id, write_value])\n\ndef get_distance_sensor(name):\n \"\"\"Returns the distance away from the sensor an object is, measured in centimeters\n\n :param name: A String that identifies the distance sensor\n :returns: A double representing how many centimeters away the object is from the sensor\n\n :Examples:\n\n >>> distance = get_distance_sensor(\"distance1\")\n >>> distance\n 10.76\n\n \"\"\"\n device_id = _lookup(name)\n return _testConnected(device_id)\n\n\ndef get_limit_switch(name):\n \"\"\"Returns whether a specified limit switch on the identified device is pressed or not\n\n The specified limit switch returns a boolean, either True (pressed) or False (not pressed).\n\n :param name: A String that identifies the limit switch\n :returns: A boolean value, where True is pressed and False is not pressed.\n\n :Examples:\n\n >>> switch = get_limit_switch(\"switch1\")\n >>> switch\n True\n\n \"\"\"\n device_id = _lookup(name)\n return _testConnected(device_id)\n\ndef get_potentiometer(name):\n \"\"\"Returns the sensor reading of a potentiometer\n\n The potentiometer returns a decimal between 0 and 1, indicating the angle detected,\n where 0 and 1 are the two extreme angles.\n\n :param name: A string that identifies the potentiometer smart device (contains four potentiometers)\n :returns: A decimal between 0 and 1 representing the angle.\n\n >>> potentiometer = get_potentiometer(\"potentiometer1\")\n >>> potentiometer\n 0.364\n\n \"\"\"\n device_id = _lookup(name)\n return _testConnected(device_id)\n\ndef get_metal_detector(name): #TODO metal detector Implementation\n \"\"\"Returns the sensor reading of the specified metal detector\n\n Each metal detector returns an integer, which changes based on the prescence of metal.\n After callibration, the value should increase in the presence of steel and decrease in\n the presence of aluminum. There is random drift of around 8 so your code should callibrate\n in air often.\n\n :param name: A String that identifies the metal detector smart device.\n :returns: An integer (large) which represents whether metal is detected or not.\n\n \"\"\"\n device_id = _lookup(name)\n return _testConnected(device_id)\n\ndef calibrate_metal_detector(name): #TODO test calibration\n \"\"\"Calibrates the specified metal sensor\n\n Calibrates to set the current reading of the metal detector to air (0). It is\n recommended that this is called before every reading to avoid misreading values\n due to drift.\n\n :param name: A String that identifies the metal detector smart device.\n\n \"\"\"\n device_id = _lookup(name)\n _testConnected(device_id)\n mc.set(\"metal_detector_calibrate\",[device_id, True])\n\n\ndef get_line_sensor(name):\n \"\"\"Returns a value used to determine whether the selected sensor is over a line or not\n\n If the selected sensor (left, center, or right) is over a line/reflective surface,\n this will return an double close to 0;\n Over the ground or dark material, this will return an double close to 1.\n\n :param name: A String that identifies the reflecting smart device.\n :returns: An double that specifies whether it is over the tape (0 - 1)\n\n >>> line_sensor = get_line_sensor(\"line_sensor_1\")\n >>> line_sensor\n 0.03\n\n \"\"\"\n device_id = _lookup(name)\n return _testConnected(device_id)\n\ndef drive_distance_all(degrees, motors, gear_ratios):\n \"\"\"WARNING: THIS METHOD IS NOT GUARANTEED TO WORK. USE WITH CAUTION.\n\n Drives all motors in the list a set number of degrees set by the corresponding index in the distances list.\n\n The specified motor will run until it reaches the specified degree of rotation and will hold the motor\n there until a grizzly motor method is called again.\n The gear ratio should be indicated on the physical motor itself. Implementation of this method for users in PID mode:\n this method translates degrees into encoder ticks and then sets the target in said encoder ticks. When this method is called again\n on the same motor, current encoder tick position is reset to 0 and the method reruns.\n\n :param degrees: A list of integers corresponding to the number of ticks to be moved. The integer at the index of\n this list should match the motor's index.\n :param motor: A list of strings corresponding to the motor names to be rotated. The index of the motor names\n should match the index of the distance.\n :param gear_ratios: A list of integers corresponding to the gear ratios of the motors. The integer at the\n index of this list should match the motor's index.\n \"\"\"\n assert isinstance(motors, list), \"motors must be a list\"\n assert isinstance(gear_ratios, list), \"gear_ratios must be a list\"\n assert isinstance(degrees, list), \"degrees must be a list\"\n assert len(degrees) == len(motors) and len(degrees) == len(gear_ratios), \"List lengths for all 3 parameters must be equal\"\n motor_list = mc.get(\"motor_values\")\n for motor in motors:\n assert motor in motor_list, motor + \" not found in connected motors\"\n zipped = zip(motors, degrees, gear_ratios)\n mc.set(\"drive_distance\", zipped)\n\n #TODO, need to reset positions each time these two methods are called.\ndef drive_distance_degrees(degrees, motor, gear_ratio):\n \"\"\"WARNING: THIS METHOD IS NOT GUARANTEED TO WORK. USE WITH CAUTION.\n\n Drives the specified motor a set number of degrees and holds the motor there.\n\n The specified motor will run until it reaches the specified degree of rotation and will hold the motor there until a grizzly motor method is called again.\n The gear ratio should be indicated on the physical motor itself. Implementation of this method for users in PID mode:\n this method translates degrees into encoder ticks and then sets the target in said encoder ticks. When this method is called again\n on the same motor, current encoder tick position is reset to 0 and the method reruns.\n\n :param degrees: An integer corresponding to the number of degrees to be moved\n :param motor: A String corresponding to the motor name to be rotated\n :param gear_ratio: An integer corresponding to the gear ratio of the motor (19 or 67)\n \"\"\"\n assert isinstance(motor, str), \"motor must be an String\"\n assert isinstance(gear_ratio, int), \"gear_ratio must be an integer\"\n assert isinstance(degrees, int), \"degrees must be an integer\"\n motor_list = mc.get(\"motor_values\")\n assert motor in motor_list, motor + \" not found in connected motors\"\n assert gear_ratio in [19,67], \"Gear ratio must be 19:1 or 67:1\"\n sent_list = [(motor, degrees, gear_ratio)]\n mc.set(\"drive_distance\", sent_list)\n\n\ndef drive_distance_rotations(rotations, motor, gear_ratio):\n \"\"\"WARNING: THIS METHOD IS NOT GUARANTEED TO WORK. USE WITH CAUTION.\n\n Drives the specified motor a set number of rotations and holds the motor there.\n\n The specified motor will run until it reaches the specified degree of rotation and will hold the motor there until a grizzly motor method is called again.\n The gear ratio should be indicated on the physical motor itself. Implementation of this method for users in PID mode:\n this method translates degrees into encoder ticks and then sets the target in said encoder ticks. When this method is called again\n on the same motor, current encoder tick position is reset to 0 and the method reruns.\n\n :param rotations: An integer corresponding to the number of rotations to be moved\n :param motor: A String corresponding to the motor name to be rotated\n :param gear_ratio: An integer corresponding to the gear ratio of the motor (19 or 67)\n \"\"\"\n assert isinstance(motor, str), \"motor must be a String\"\n assert isinstance(gear_ratio, int), \"gear_ratio must be an integer\"\n assert isinstance(rotations, int), \"degrees must be an integer\"\n motor_list = mc.get(\"motor_values\")\n assert motor in motor_list, motor + \" not found in connected motors\"\n assert gear_ratio in [19,67], \"Gear ratio must be 19:1 or 67:1\"\n sent_list = [(motor, rotations*360, gear_ratio)]\n mc.set(\"drive_distance\", sent_list)\n\n\ndef set_drive_mode(mode):\n \"\"\"Sets the drive mode of all the motors between coasting and full breaking.\n\n Enter a string (\"coast\" or \"brake\") to specify if the motors should fully break after movement or coast to a stop. Default mode is breaking after\n movement\n\n :param mode: A String (\"coast\" or \"brake\") corresponding to the selected drive mode.\n\n >>> set_drive_mode(\"coast\")\n\n \"\"\"\n mode = mode.lower()\n assert mode in [\"coast\", \"brake\"], mode + \" is not a valid drive mode\"\n mc.set(\"drive_mode\", [mode, \"all\"])\n\ndef change_control_mode_all(mode):\n \"\"\"Changes PID mode for all motors connected to the robot\n\n This changes the control mode for inputing values into all of the motors.\n Default mode - No_PID which means one inputs a range of floats from -1 to 1 and the motor runs at a proportion corresponding to that range.\n\n Speed PID - Motors run at encoder ticks per second instead of an integer range. Encoder ticks are a proportion of a rotation, similar to degrees\n to check for encoder ticks for each motor, see this website: https://www.pololu.com/category/116/37d-mm-gearmotors\n\n Position PID - Motors run until at a certain position, using encoder ticks as units. See above website for number of ticks per degree of rotation.\n\n :param mode: A String (\"default\", \"speed\", \"position\") corresponding to the wanted control mode for all motors.\n\n \"\"\"\n mode = mode.lower()\n assert mode in [\"default\", \"speed\", \"position\"], mode + \" is not a valid control mode\"\n mc.set(\"control_mode\", [mode, \"all\"])\n\ndef change_control_mode(mode, motor):\n \"\"\"Changes PID mode for specified motors connected to the robot\n\n This changes the control mode for inputing values into the specified motors.\n\n Default mode - No_PID which means one inputs a range of integers from -1 to 1 and the motor runs at a proportion corresponding to that range.\n\n Speed PID - Motors run at encoder ticks per second instead of an integer range. Encoder ticks are a proportion of a rotation, similar to degrees\n to check for encoder ticks for each motor, see this website: https://www.pololu.com/category/116/37d-mm-gearmotors\n\n Position PID - Motors run until at a certain position, using encoder ticks as units. See above website for number of ticks per degree of rotation.\n\n :param mode: A String ('default', 'speed', 'position') corresponding to the wanted control mode for the specified motor.\n :param motor: A String corresponding to the motor name whose PID mode is to be changed\n\n \"\"\"\n mode = mode.lower()\n assert mode in [\"default\", \"speed\", \"position\"], mode + \" is not a valid control mode\"\n motor_list = mc.get(\"motor_values\")\n assert motor in motor_list, motor + \" not found in connected motors\"\n mc.set(\"control_mode\", [mode, motor])\n\ndef change_PID_constants(value, constant):\n \"\"\"Changes a PID constant which error corrects for motor positions for all motors.\n\n P - Proportion - changes the constant for present error correcting\n I - Integral - changes the constant for past error correcting\n D - Derivative - changes the constant for future errors - decreases response time\n For more information, refer to a mentor or the wiki page: https://en.wikipedia.org/wiki/PID_controller\n\n :param value: A decimal corresponding to the new coefficient of a PID constant.\n :param constant: A String (\"P\", \"I\", \"D\") corresponding to the constant to be changed.\n \"\"\"\n constant = constant.upper()\n assert constant in [\"P\", \"I\", \"D\"], \"invalid constant\" + constant\n mc.set(\"PID_constant\", (constant, value))\n\ndef change_specific_PID(motor, pid_list):\n \"\"\"Sets a PID for a specified motor.\n\n For each constant, look at change_PID_constants method for specifics.\n Call after change_PID_constants to override a specific motors PID for a specific purpose (e.g. an arm).\n\n :param motor: A string that specifies which motor to change PID constants.\n :param pid_list: A list of constants in the order of p, i, and d. Must include all 3.\n \"\"\"\n assert isinstance(motor, str), \"motor_name must be a string\"\n assert isinstance(pid_list, list), \"pid_list must be a list\"\n assert len(pid_list) == 3, \"pid_list must have only 3 values\"\n for item in pid_list:\n assert isinstance(item, int) or isinstance(item, float), \"items in pid_list must be an integer\"\n name_to_value = mc.get('motor_values')\n if device_id not in name_to_value:\n raise KeyError(\"No motor with that name\")\n list_to_send = [motor] + pid_list\n mc.set(\"spec_pid\", list_to_send)\ndef get_PID_constants():\n \"\"\"Returns a dictionary with the key being the constants and the corresponding item as the value of the constant\n\n Returns a list of 3 tuples with the key containing a String (\"P\", \"I\", or \"D\") corresponding to each of the constants. The item\n of the dictionary is that constant's current value.\n\n :returns: a dictionary of tuples which keys are strings and items are integer values\n \"\"\"\n return mc.get(\"get_PID\")\n\ndef get_motor_distance(motor, gear_ratio):\n \"\"\"Returns degrees of a motor.\n\n Returns an integer corresponding the degrees of the encoder of the motor. Requires gear ratio of set motor to get degrees of said motor.\n\n :param motor: String value specifying which motor's distance will be returned.\n\n :returns: An integer corresponding to the degrees at which the motor is at.\n \"\"\"\n assert isinstance(motor, str), \"motor must be a string\"\n name_to_value = mc.get('motor_values')\n if device_id not in name_to_value:\n raise KeyError(\"No motor with that name\")\n assert gear_ratio in [19,67], \"Gear ratio must be 19:1 or 67:1\" \n distance_dict = mc.get(\"encoder_distance\")\n distance = distance_dict[motor]\n if gear_ratio == 19:\n distance = distance * 360.0 / 1200.0\n if gear_ratio == 67:\n distance = distance * 360.0 / 1200.0\n return distance\n\ndef _testConnected(device_id): # Returns value if device_id exists, otherwise throws SensorValueOutOFBounds Exception\n all_data = mc.get('sensor_values')\n try:\n return all_data[device_id]\n except KeyError:\n raise KeyError(\"No sensor with that name\")\n\nclass SensorValueOutOfBounds(Exception):\n pass\n\ndef _get_all():\n return mc.get('sensor_values')\n\n# pololu.com. 19:1 and 67:1 motors 37D motors geared. Be able to change PID constants. Move and stay - set point. once it is called again, reset and redo function.\n","sub_path":"runtime/api/Robot.py","file_name":"Robot.py","file_ext":"py","file_size_in_byte":22024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"190793052","text":"#-*-coding:utf-8-*-\n'''\n @usage: 定时服务\n'''\nimport os\nimport logging\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom datetime import datetime,timedelta\nimport random\n\n################### 自定义logging格式 #######################################\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename='%s/main.log' % '../log',\n filemode='a')\n\n\n\n\n######################### 爬虫 ################################################\n\n#------运行单条爬虫------------------\ndef _crawl(spider_name=None,project=None):\n if spider_name and project:\n #改变当前工作目录到项目下\n os.chdir('../%s' % project)\n isExists=os.path.exists('../log/%s'%project)\n if not isExists:\n os.makedirs('../log/%s'%project)\n\n logging.info('running spider: %s/%s' % (project,spider_name))\n starttime = datetime.now()\n\n # os.system('scrapy crawl %s -a page_max=10 2>&1 |tee -a '\\\n # '../logrrr/%s/%s.log ../logrrr/%s/%s_stderr.log'\\\n # % ('weixin','weixin','weixin','weixin','weixin'))\n os.system('scrapy crawl %s -a page_max=10 2>&1 |tee -a '\\\n '../log/%s/%s.log'\\\n % (spider_name,project,spider_name))\n\n #os.system('scrapy crawl weixin -a page_max=10')\n endtime = datetime.now()\n runtime = (endtime-starttime).seconds\n logging.info('end spider: %s/%s, runtime: %s s' % (project,spider_name,runtime))\n\n return None\n\n\n#------定时任务----------------------\ndef main():\n sched = BlockingScheduler()\n try:\n\n #微信公众号及其功能的爬虫任务\n @sched.scheduled_job('cron', day_of_week='mon-sun', hour=_hour,minute=_minute)\n def timed_job_news():\n logging.info('running cron job for --微信公众号功能搜索-- spider')\n try:\n _crawl(spider_name='weixin',project='weixin')\n except Exception as e:\n logging.error(e)\n\n sched.start()\n\n except Exception as e:\n logging.error(e)\n\n\nif __name__ == \"__main__\":\n\n #设置爬虫运行时间\n _hour = '5-23'\n _minute = '*/30'\n _second = random.randint(2, 50)\n _deltatime = 10\n main()\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"303569542","text":"# imports\nimport main as mn \nimport tkinter\nfrom string import ascii_letters\n\n\n# vigenere cipher\n\nfrom string import ascii_letters\n\n\n\n# -----------------------------------------------------------------------------------------------------\n\n# cipher_combo_box \ncipher_combo_box = mn.ttk.Combobox(values = [\n \"caesar cipher\",\n \"ROT13\",\n \"Vigenere cipher\"\n])\ncipher_combo_box.grid(row = 4, column = 0, padx = 35)\ncipher_combo_box.current(2)\n\ndef get_cipher_combo_box_value():\n cipher_value = cipher_combo_box.get()\n return cipher_value\n\nthe_cipher_value = get_cipher_combo_box_value()\n\n# logical functions\n# move encrypted text\ndef move_text_to_decrypt_box():\n # check which cipher was selected\n \"\"\"\n if combox value == cipher A:\n do function\n elif combox value == cipher B:\n do function\n \"\"\"\n if (the_cipher_value == \"caesar cipher\"):\n empty_message = \"Error! The encryption box or shifter key box is empty\\n\"\n moving_text = encryption_box.get(\"1.0\", mn.tkinter.END)\n shifter_key_number = shifter_key_box.get(\"1.0\", mn.tkinter.END)\n # check if there is a empty error message\n if empty_message in moving_text:\n encryption_box.delete(\"1.0\", mn.tkinter.END)\n \n elif (len(moving_text) < 2) or len(shifter_key_number) < 2:\n # checking if the text box is empty\n decrption_box.insert(\"1.0\", empty_message)\n\n else:\n # encrypting the data and inserting it to the decryption box\n decrption_box.insert(\"1.0\", mn.MainWindow.encryption(moving_text, moving_text, int(shifter_key_number)))\n encryption_box.delete(\"1.0\", mn.tkinter.END)\n elif (the_cipher_value == \"ROT13\"):\n empty_message = \"Error! The encryption box or shifter key box is empty\\n\"\n moving_text = encryption_box.get(\"1.0\", mn.tkinter.END)\n shifter_key_number = shifter_key_box.get(\"1.0\", mn.tkinter.END)\n # check if there is a empty error message\n if empty_message in moving_text:\n encryption_box.delete(\"1.0\", mn.tkinter.END)\n \n elif (len(moving_text) < 2) or len(shifter_key_number) < 2:\n # checking if the text box is empty\n decrption_box.insert(\"1.0\", empty_message)\n\n else:\n # encrypting the data and inserting it to the decryption box\n decrption_box.insert(\"1.0\", mn.MainWindow.encrypt_rot13(moving_text, moving_text, int(shifter_key_number)))\n encryption_box.delete(\"1.0\", mn.tkinter.END) \n\n elif (the_cipher_value == \"Vigenere cipher\"):\n\n pattern = {}\n dictionary = pattern.fromkeys(ascii_letters)\n sorted_dictionary = {}\n\n # assigning values \n counter = 0\n counter2 = 0\n for key, value in dictionary.items():\n if counter <= 25:\n value = counter\n counter += 1\n sorted_dictionary[key] = value\n else:\n value = counter2\n counter2 += 1\n sorted_dictionary[key] = value\n\n # print(sorted_dictionary)\n\n # check the alphabet position\n def check_alphabet_position(letter):\n if letter.isalpha():\n alphabet_postion = sorted_dictionary[letter]\n else:\n alphabet_postion = 0\n return alphabet_postion\n\n # this rotates the letters\n def rotate(letter, rotate_value):\n if letter.isupper():\n shift_value = 65\n if letter.islower():\n shift_value = 97\n \n return chr((ord(letter) + rotate_value - shift_value)%26 + shift_value)\n\n # encryption function\n def vigenere_encryption(message, key):\n encrypted_message = []\n starting_index = 0\n for letter in message:\n # checking if the letter is alpha\n rotation = check_alphabet_position(key[starting_index])\n # check if letter is not alpha\n if letter not in sorted_dictionary:\n encrypted_message.append(letter)\n elif letter.isalpha():\n encrypted_message.append(rotate(letter, rotation))\n \n # checking if keyword has reached the end\n if starting_index == (len(key) -1):\n starting_index = 0\n else:\n starting_index += 1\n \n return \"\".join(encrypted_message)\n\n empty_message = \"Error! The encryption box or shifter key box is empty\\n\"\n moving_text = encryption_box.get(\"1.0\", mn.tkinter.END)\n shifter_key_number = shifter_key_box.get(\"1.0\", mn.tkinter.END[:3])\n # check if there is a empty error message\n if empty_message in moving_text:\n encryption_box.delete(\"1.0\", mn.tkinter.END)\n \n elif (len(moving_text) < 2) or len(shifter_key_number) < 2:\n # checking if the text box is empty\n decrption_box.insert(\"1.0\", empty_message)\n\n else:\n # encrypting the data and inserting it to the decryption box\n decrption_box.insert(\"1.0\", vigenere_encryption(moving_text, str(shifter_key_number)))\n encryption_box.delete(\"1.0\", mn.tkinter.END) \n# -----------------------------------------------------------------------------------------------------------\n\n# move decrypted text\ndef move_text_to_encrypted_box():\n\n if (the_cipher_value == \"caesar cipher\"):\n shifter_key_number = 13\n # check for an empty error message\n empty_message = \"Error! The encryption box or shifter key box is empty\\n\"\n moving_text =decrption_box.get(\"1.0\", mn.tkinter.END)\n shifter_key_number = shifter_key_box.get(\"1.0\", mn.tkinter.END)\n\n # checking if the decryption box has an error message\n if empty_message in moving_text:\n decrption_box.delete(\"1.0\", mn.tkinter.END)\n # check if the decryption box is empty\n elif len(moving_text) < 2 or len(shifter_key_number) < 2:\n encryption_box.insert(\"1.0\", empty_message)\n # decrypt the message and send it to the encryption box\n else:\n encryption_box.insert(\"1.0\", mn.MainWindow.decryption(moving_text, moving_text, int(shifter_key_number)))\n decrption_box.delete(\"1.0\", mn.tkinter.END)\n\n elif (the_cipher_value == \"ROT13\"):\n # check for an empty error message\n empty_message = \"Error! The encryption box or shifter key box is empty\\n\"\n moving_text = decrption_box.get(\"1.0\", mn.tkinter.END)\n shifter_key_number = shifter_key_box.get(\"1.0\", mn.tkinter.END)\n\n # checking if the decryption box has an error message\n if empty_message in moving_text:\n decrption_box.delete(\"1.0\", mn.tkinter.END)\n # check if the decryption box is empty\n elif len(moving_text) < 2 or len(shifter_key_number) < 2:\n encryption_box.insert(\"1.0\", empty_message)\n # decrypt the message and send it to the encryption box\n else:\n encryption_box.insert(\"1.0\", mn.MainWindow.decrypt_rot13(moving_text, moving_text, int(shifter_key_number)))\n decrption_box.delete(\"1.0\", mn.tkinter.END)\n \n\n\n\n\n\n# create a title\nplaceholder_label = mn.tkinter.Label(text = \" \", font = (\"times\", 20), bg = \"light blue\")\nplaceholder_label.grid(row =0 , column =0 )\n\ntitle_label = mn.tkinter.Label(text = \"Cryptographic Ciphers\", font = (\"times\", 20), bg = \"light grey\")\ntitle_label.grid(row =0 , column =1 )\n\nplaceholder_label = mn.tkinter.Label(text = \" \", font = (\"times\", 20), bg = \"light blue\")\nplaceholder_label.grid(row =0 , column =2 )\n\n\n# encryption_message\nencryption_message = mn.tkinter.Label(text = \"Encrypt\", font = (\"times\", 17), pady = 20, bg = \"light blue\")\nencryption_message.grid(row = 1, column = 0, sticky = mn.tkinter.W)\n\n# decryption_message\ndecryption_message = mn.tkinter.Label(text = \"Decrypt\", font = (\"times\", 17), pady = 20, bg = \"light blue\")\ndecryption_message.grid(row = 1, column = 2, sticky = mn.tkinter.E)\n\n# encryption_box\nencryption_box = mn.tkinter.Text(height = 12, width = 50, font = (\"times\", 16))\nencryption_box.grid(row = 2, column = 0, sticky = mn.tkinter.W)\n\n# shifter_key\nshifter_key = mn.tkinter.Label(text = \"Shifter Key / Keyword\", font = (\"times\", 15), bg = \"light blue\")\nshifter_key.grid(row = 1, column = 1)\n\n# shifter_key_box\nshifter_key_box = mn.tkinter.Text(height = 2, width = 8, font = (\"times\", 15))\nshifter_key_box.grid(row = 2, column = 1)\nshifter_key_box.insert(tkinter.END,\"13\")\n# encryption_button\nencryption_button = mn.tkinter.Button(text = \" ENCRYPT \",\n font = (\"times\", 15), pady = 10, command = move_text_to_decrypt_box)\nencryption_button.grid(row = 3, column = 0, sticky = mn.tkinter.W)\n\n# decrption_box\ndecrption_box = mn.tkinter.Text(height = 12, width = 50, font = (\"times\", 16))\ndecrption_box.grid(row = 2, column = 2, sticky = mn.tkinter.E)\n\n# Decrption button \ndecryption_button = mn.tkinter.Button(text = \" DECRYPT \",\n font = (\"times\", 15), pady = 10, command = move_text_to_encrypted_box)\ndecryption_button.grid(row = 3, column = 2, sticky = mn.tkinter.E)\n\n# cipher chooser\ncipher_choose_label = tkinter.Label(text = \"Choose cipher: \", font = (\"text\", 15), bg = \"light blue\")\ncipher_choose_label.grid(row = 4, column = 0, sticky = mn.tkinter.W, pady = 10)\n\n\n\n# loop the program\nif __name__ == \"__main__\":\n mn.root_window.mainloop()\n\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"610621435","text":"# -*- coding: utf-8 -*-\n# 实例19:图的基本操作_获取对象\n\nimport tensorflow as tf\n\n# 新建图\ng = tf.Graph()\nwith g.as_default():\n c = tf.constant(0.0)\n print(\"c name: \" + c.name)\n # ��据对象获取元素\n c_temp = g.as_graph_element(c)\n print(\"c_temp name: \" + c_temp.name)\n","sub_path":"tf04/example19_4.py","file_name":"example19_4.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"39798689","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Nov 14 11:52:37 2020\r\n\r\n@author: Kanav Farishta\r\n\"\"\"\r\n\r\n# K Dimension Representation Graphically \r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n#Scenario 1 \r\n\r\nclass Node:\r\n def __init__(self,data,depth,typ):\r\n self.left = None\r\n self.right = None\r\n self.data = data\r\n self.depth = depth\r\n self.type = typ\r\n \r\n def insert(self,depth):\r\n# print(\"Self Depth\",\":\",self.depth)\r\n# print(\"Depth\",\":\",depth)\r\n if(int(self.depth)==depth):\r\n return\r\n else:\r\n if(self.type==int):\r\n #Meaning divide by X\r\n temp = self.data\r\n median = temp[\"X\"].median()\r\n self.left = Node(temp[temp[\"X\"]<=median],self.depth+0.5,float)\r\n self.right = Node(temp[temp[\"X\"]>median],self.depth+0.5,float)\r\n plt.plot([median,median],[max(self.data[\"Y\"]),min(self.data[\"Y\"])])\r\n self.left.insert(depth)\r\n self.right.insert(depth)\r\n if(self.type==float):\r\n #Meaning divide by Y\r\n temp = self.data\r\n median = temp[\"Y\"].median()\r\n self.left = Node(temp[temp[\"Y\"]<=median],self.depth+0.5,int)\r\n self.right = Node(temp[temp[\"Y\"]>median],self.depth+0.5,int)\r\n plt.plot([max(self.data[\"X\"]),min(self.data[\"X\"])],[median,median])\r\n self.left.insert(depth)\r\n self.right.insert(depth)\r\n \r\n def printTree(self):\r\n if self.left:\r\n self.left.printTree()\r\n print(\"Data\",self.data)\r\n print(\"Depth\",self.depth)\r\n print(\"<===========>\")\r\n if self.right:\r\n self.right.printTree()\r\n \r\n \r\n \r\nclass KDTree:\r\n def TwoDTree(self,depth,x_axis,y_axis):\r\n if(type(depth)!=int):\r\n raise Exception(\"Depth must be a positive Integer\")\r\n else:\r\n if(depth<0):\r\n raise Exception(\"Depth must be positive\")\r\n elif(depth==0):\r\n return\r\n df = pd.DataFrame(list(zip(x_axis,y_axis)),columns=[\"X\",\"Y\"])\r\n root = Node(df,0,int)\r\n plt\r\n root.insert(2)\r\n plt.xlabel(\"x Axis\")\r\n plt.ylabel(\"y Axis\")\r\n plt.show()\r\n #root.printTree()\r\n\r\ndata = pd.read_csv(r'C:\\Users\\Kanav Farishta\\Downloads\\archive\\train.csv')\r\nop = KDTree()\r\nop.TwoDTree(1,data[\"x\"].tolist(),data[\"y\"].tolist())\r\n\r\n\r\n\r\n \r\n \r\n \r\n ","sub_path":"K Dimensional Tree.py","file_name":"K Dimensional Tree.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"496787807","text":"# =============================================================\n# dataset details\n# dataset: Synth90k\n# download: http://www.robots.ox.ac.uk/~vgg/data/text/\n# train: 7224612\n# val: 802734\n# test: 891927\n# max num chars: 23\n# classes: 37 [0-9A-Z](case-insensitive)\n# word accuracy: 88.56 %\n# edit distance: 3.163 %\n# pretrained model: Chars74k classifier\n# max steps: 100000 batch size: 100\n# =============================================================\n\nimport tensorflow as tf\nimport numpy as np\nimport skimage\nimport argparse\nimport functools\nimport itertools\nimport dataset\nimport hooks\nfrom models.hats import HATS\nfrom networks.attention_network import AttentionNetwork\nfrom networks.pyramid_resnet import PyramidResNet\nfrom attrdict import AttrDict as Param\nfrom algorithms import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--model_dir\", type=str, default=\"synth90k_hats_model\", help=\"model directory\")\nparser.add_argument(\"--pretrained_model_dir\", type=str, default=\"chars74k_classifier\", help=\"pretrained model directory\")\nparser.add_argument('--train_filenames', type=str, nargs=\"+\", default=[\"synth90k_train.tfrecord\"], help=\"tfrecords for training\")\nparser.add_argument('--val_filenames', type=str, nargs=\"+\", default=[\"synth90k_val.tfrecord\"], help=\"tfrecords for validation\")\nparser.add_argument('--test_filenames', type=str, nargs=\"+\", default=[\"synth90k_test.tfrecord\"], help=\"tfrecords for test\")\nparser.add_argument(\"--batch_size\", type=int, default=100, help=\"batch size\")\nparser.add_argument(\"--random_seed\", type=int, default=1209, help=\"random seed\")\nparser.add_argument(\"--data_format\", type=str, default=\"channels_first\", help=\"data format\")\nparser.add_argument(\"--max_steps\", type=int, default=100000, help=\"maximum number of training steps\")\nparser.add_argument(\"--steps\", type=int, default=None, help=\"number of test steps\")\nparser.add_argument('--train', action=\"store_true\", help=\"with training\")\nparser.add_argument('--eval', action=\"store_true\", help=\"with evaluation\")\nparser.add_argument('--predict', action=\"store_true\", help=\"with prediction\")\nparser.add_argument(\"--gpu\", type=str, default=\"0\", help=\"gpu id\")\nargs = parser.parse_args()\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\nif __name__ == \"__main__\":\n\n # validation時のbatch normalizationの統計は\n # ミニバッチの統計か移動統計どちらを使用するべき?\n # ミニバッチの統計を使う場合に備えてEstimatorのparams以外を一度固定\n # estimator.train, estimator.evaluateの呼び出し時にparamsとしてtrainingを与える\n Estimator = functools.partial(\n tf.estimator.Estimator,\n model_fn=lambda features, labels, mode, params: HATS(\n # =========================================================================================\n # feature extraction\n backbone_network=PyramidResNet(\n conv_param=Param(filters=64, kernel_size=[7, 7], strides=[2, 2]),\n pool_param=None,\n residual_params=[\n Param(filters=64, strides=[2, 2], blocks=2),\n Param(filters=128, strides=[2, 2], blocks=2),\n Param(filters=256, strides=[2, 2], blocks=2),\n Param(filters=512, strides=[2, 2], blocks=2),\n ],\n data_format=args.data_format\n ),\n # =========================================================================================\n # text detection\n attention_network=AttentionNetwork(\n conv_params=[\n Param(filters=16, kernel_size=[3, 3], strides=[2, 2]),\n Param(filters=16, kernel_size=[3, 3], strides=[2, 2]),\n ],\n rnn_params=[\n Param(sequence_length=24, num_units=256),\n ],\n deconv_params=[\n Param(filters=16, kernel_size=[3, 3], strides=[2, 2]),\n Param(filters=16, kernel_size=[3, 3], strides=[2, 2]),\n ],\n data_format=args.data_format\n ),\n # =========================================================================================\n # text recognition\n num_units=[1024],\n num_classes=37,\n # =========================================================================================\n data_format=args.data_format,\n hyper_params=Param(\n attention_decay=0.0,\n learning_rate_fn=lambda global_step: tf.train.exponential_decay(\n learning_rate=1e-3,\n global_step=global_step,\n decay_steps=25000,\n decay_rate=1e-1,\n staircase=True\n )\n )\n )(features, labels, mode, Param(params)),\n model_dir=args.model_dir,\n config=tf.estimator.RunConfig(\n tf_random_seed=args.random_seed,\n save_summary_steps=100,\n save_checkpoints_steps=100,\n session_config=tf.ConfigProto(\n gpu_options=tf.GPUOptions(\n visible_device_list=args.gpu,\n allow_growth=True\n )\n )\n ),\n # resnetはchars74kで学習させた重みを初期値として用いる\n warm_start_from=tf.estimator.WarmStartSettings(\n ckpt_to_initialize_from=args.pretrained_model_dir,\n vars_to_warm_start=\".*pyramid_resnet.*\"\n )\n )\n\n if args.train:\n\n Estimator(params=dict(training=True)).train(\n input_fn=functools.partial(\n dataset.input_fn,\n filenames=args.train_filenames,\n batch_size=args.batch_size,\n num_epochs=None,\n shuffle=True,\n sequence_lengths=[24],\n encoding=\"jpeg\",\n image_size=[256, 256],\n data_format=args.data_format\n ),\n max_steps=args.max_steps,\n hooks=[\n # logging用のhook\n tf.train.LoggingTensorHook(\n tensors=dict(\n word_accuracy=\"accuracy\",\n edit_distance=\"distance\"\n ),\n every_n_iter=100\n ),\n # validationのためのcustom hook\n # 内部でestimator.evaluateしている\n hooks.ValidationMonitorHook(\n estimator=Estimator(params=dict(training=True)),\n input_fn=functools.partial(\n dataset.input_fn,\n filenames=args.val_filenames,\n batch_size=args.batch_size,\n num_epochs=1,\n shuffle=False,\n sequence_lengths=[24],\n encoding=\"jpeg\",\n image_size=[256, 256],\n data_format=args.data_format\n ),\n every_n_steps=1000,\n steps=1000,\n name=\"validation\"\n )\n ]\n )\n\n if args.eval:\n\n eval_result = Estimator(params=dict(training=True)).evaluate(\n input_fn=functools.partial(\n dataset.input_fn,\n filenames=args.test_filenames,\n batch_size=args.batch_size,\n num_epochs=1,\n shuffle=False,\n sequence_lengths=[24],\n encoding=\"jpeg\",\n image_size=[256, 256],\n data_format=args.data_format\n ),\n steps=args.steps,\n name=\"test\"\n )\n\n print(\"==================================================\")\n tf.logging.info(\"test result\")\n tf.logging.info(eval_result)\n print(\"==================================================\")\n","sub_path":"synth90k_main.py","file_name":"synth90k_main.py","file_ext":"py","file_size_in_byte":8037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"377948627","text":"# coding: utf-8\nfrom netCDF4 import Dataset\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\nfrom matplotlib.patches import Polygon\nfrom wrf import getvar, interplevel, to_np, get_basemap, latlon_coords,ALL_TIMES\nimport time\nfrom datetime import date, timedelta\nimport os\ndef wea(fname,figname,itime):\n ncfile = Dataset(fname)\n # Creating a simple test list with three timesteps\n #ncfile = [ #Dataset(\"wrfout_d01_2017-05-30_00:00:00\")]\n # Dataset(\"wrfout_d01_2017-05-31_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-01_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-02_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-03_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-04_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-05_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-06_00:00:00\"),\n # Dataset(\"wrfout_d02_2017-06-07_00:00:00\")]\n # Dataset(\"wrfout_d01_2017-06-08_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-09_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-10_00:00:00\"),\n # Dataset(\"wrfout_d01_2017-06-11_00:00:00\")]\n \n # Extract the pressure, geopotential height, and wind variables\n #p0 = getvar(ncfile, \"slp\", timeidx=ALL_TIMES, method=\"cat\")\n z0 = getvar(ncfile, \"slp\", units=\"hPa\", timeidx=ALL_TIMES, method=\"cat\")\n ua0 = getvar(ncfile, \"uvmet10\", units=\"m s-1\", timeidx=ALL_TIMES, method=\"cat\")\n rh0 = getvar(ncfile, \"rh2\", timeidx=ALL_TIMES, method=\"cat\")\n print(rh0) \n #wspd0 = getvar(ncfile, \"wspd_wdir\", units=\"m s-1\", timeidx=ALL_TIMES, method=\"cat\")[0,:]\n \n #p = p0[itime,:,:,:] \n ht_500 = z0[itime,:,:]\n u_500 = ua0[0,itime,:,:]\n v_500 = ua0[1,itime,:,:]\n rh = rh0[itime,:,:]\n #wspd = wspd0[itime,:,:,:]\n\n print(ht_500.shape)\n # Get the lat/lon coordinates\n lats, lons = latlon_coords(ht_500)\n\n # Get the basemap object\n\n \n # Create the figure\n fig = plt.figure(figsize=(12,9))\n ax = plt.axes()\n\n bm = get_basemap(ht_500) \n shp_info = bm.readshapefile(\"CHN_adm1\",'states',drawbounds=True) # CHN_adm1的数据是中国各省区域\n \n for info, shp in zip(bm.states_info, bm.states):\n proid = info['NAME_1'] # 可以用notepad打开CHN_adm1.csv文件,可以知道'NAME_1'代表各省的名称\n if proid == 'Shandong':\n poly = Polygon(shp,facecolor='g',edgecolor='c', lw=3) # 绘制广东省区域\n ax.add_patch(poly) \n #proid = info['NAME_2'] # 可以用notepad打开CHN_adm1.csv文件,可以知道'NAME_1'代表各省的名称\n #if proid == 'Qingdao':\n # poly = Polygon(shp,facecolor='r',edgecolor='c', lw=3) # 绘制广东省区域\n # ax.add_patch(poly)\n \n bm.shadedrelief()\n \n # Convert the lat/lon coordinates to x/y coordinates in the projection space\n x, y = bm(to_np(lons), to_np(lats))\n \n # Add the 500 hPa geopotential height contours\n levels = np.arange(960., 1050., 2.5)\n contours = bm.contour(x, y, to_np(ht_500), levels=levels, colors=\"blue\")\n plt.clabel(contours, inline=1, fontsize=10, fmt=\"%i\")\n \n # Add the wind speed contours\n levels = [ 70.,75, 80, 85, 90, 95, 100.]\n wspd_contours = bm.contourf(x, y, to_np(rh), levels=levels,\n cmap=get_cmap(\"rainbow\"))\n bm.colorbar(wspd_contours, ax=ax, pad=.15)\n \n # Add the geographic boundaries\n #bm.drawcoastlines(linewidth=0.25)\n #bm.drawstates(linewidth=0.25)\n #bm.drawcountries(linewidth=0.25)\n\n parallels = np.arange(0.,60,10.)\n bm.drawparallels(parallels, color='k', linewidth=.01,\n zorder=0, dashes=[1, 1], labels=[1,0,0,0], fmt='%g')\n meridians = np.arange(90.,150.,10.)\n bm.drawmeridians(meridians, color='k', linewidth=1.0,\n zorder=0, dashes=[1, 1], labels=[0,0,0,1], fmt='%g')\n\n # Add the 500 hPa wind barbs, only plotting every 125th data point.\n bm.barbs(x[::5,::5], y[::5,::5], to_np(u_500[::5, ::5]),\n to_np(v_500[::5, ::5]), length=6)\n \n\n \n #plt.title(\"500 MB Height (dm), Wind Speed (m s-1), Barbs (m s-1)\")\n \n plt.savefig(figname, dpi=300)\n\ndef listdir(path, list_name):\n for file in os.listdir(path):\n file_path = os.path.join(path, file)\n if os.path.isdir(file_path):\n listdir(file_path, list_name)\n #else:\n elif os.path.splitext(file_path)[0][47:57]=='wrfout_d01':\n #else:\n #print(os.path.splitext(file_path)[0][0:10])\n list_name.append(file_path)\n list_name = list(set(list_name)) #列表去重复\n list_name = sorted(list_name) #列表排序\n return list_name\n\ndef getTomorrow():\n today=date.today()\n oneday=timedelta(days=1)\n tomorrow=today+oneday\n return tomorrow\n\ndef main():\n datetext=getTomorrow().strftime('%Y%m%d')\n print(datetext)\n path = \"/public/product/WrfData/wrf_seven_day/\"+datetext\n print(path)\n list_name=[]\n listdir(path,list_name)\n list_name = list(set(list_name)) #列表去重复\n list_name = sorted(list_name) #列表排序\n for i in range(len(list_name)-1):\n for itime in [0,12]:\n fname=list_name[i]\n print(fname)\n figname = \"sur_wea_day_\"+fname[58:68]+\"_\"+str(itime)\n wea(fname,figname,itime)\n\nif __name__=='__main__':\n sta = time.clock()\n main()\n end = time.clock()\n print(\"finished all in %s seconds\" %str(end-sta)) \n","sub_path":"qingdao/post/surface.py","file_name":"surface.py","file_ext":"py","file_size_in_byte":5539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"402595280","text":"import json\nimport magic\nimport os\nimport shutil\nimport shortuuid\n\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.utils.translation import gettext as _\n\nfrom django_form_builder.utils import get_POST_as_json\nfrom organizational_area.models import (OrganizationalStructure,\n OrganizationalStructureOffice,\n OrganizationalStructureOfficeEmployee)\n\nfrom . settings import *\n\n\ndef custom_message(request, message='', structure_slug=''):\n \"\"\"\n \"\"\"\n return render(request, 'custom_message.html',\n {'avviso': message,\n 'structure_slug': structure_slug})\n\ndef user_manage_something(user):\n \"\"\"\n Tells us if the user is a manager or operator in some structure/office\n \"\"\"\n if not user: return False\n osoe = OrganizationalStructureOfficeEmployee\n employee_offices = osoe.objects.filter(employee=user,\n office__is_active=True)\n if not employee_offices: return False\n structures = []\n for eo in employee_offices:\n structure = eo.office.organizational_structure\n if structure.is_active and structure not in structures:\n structures.append(structure)\n return structures\n\ndef user_is_manager(user, structure):\n \"\"\"\n Returns True if user is a manager for the structure\n \"\"\"\n if not user.is_staff: return False\n if not structure: return False\n return user_is_in_default_office(user, structure)\n\ndef user_is_in_default_office(user, structure):\n \"\"\"\n Returns True is user is assigned to structure default office\n \"\"\"\n if not user or not structure: return False\n osoe = OrganizationalStructureOfficeEmployee\n help_desk_assigned = osoe.objects.filter(employee=user,\n office__organizational_structure=structure,\n office__is_default=True).first()\n if help_desk_assigned: return True\n return False\n\ndef user_is_operator(user, structure):\n \"\"\"\n Returns OrganizationalStructureOfficeEmployee queryset\n if user is a operator of an office for the structure\n \"\"\"\n if not user: return False\n if not structure: return False\n osoe = OrganizationalStructureOfficeEmployee\n oe = osoe.objects.filter(employee=user,\n office__organizational_structure=structure,\n office__is_active=True)\n if oe: return oe\n\ndef user_is_office_operator(user, office):\n \"\"\"\n Returns True if user is a operator of an office for the structure\n \"\"\"\n if not office: return False\n if not office.is_active: return False\n # If user is an operator of structure's default office,\n # than he can manage tickets of other offices too\n if user_is_in_default_office(user, office.organizational_structure):\n return True\n osoe = OrganizationalStructureOfficeEmployee\n oe = osoe.objects.filter(employee=user, office=office).first()\n if oe: return True\n return False\n\ndef get_user_type(user, structure=None):\n \"\"\"\n Returns user-type in ticket system hierarchy\n \"\"\"\n if not structure: return 'user'\n if user_is_manager(user, structure): return 'manager'\n if user_is_operator(user, structure): return 'operator'\n return 'user'\n\ndef get_folder_allegato(ticket):\n \"\"\"\n Returns ticket attachments folder path\n \"\"\"\n folder = '{}/{}/{}'.format(TICKET_FOLDER,\n ticket.get_year(),\n ticket.code)\n return folder\n\ndef get_path_allegato(ticket):\n \"\"\"\n Builds ticket attachments path\n \"\"\"\n folder = get_folder_allegato(ticket=ticket)\n path = '{}/{}'.format(settings.MEDIA_ROOT, folder)\n return path\n\ndef get_path_allegato_task(task):\n \"\"\"\n Builds task attachments path\n \"\"\"\n ticket_folder = get_path_allegato(ticket=task.ticket)\n path = '{}/{}/{}'.format(ticket_folder,\n TICKET_TASK_ATTACHMENT_SUBFOLDER,\n task.code)\n return path\n\ndef get_path_ticket_reply(ticket_reply):\n \"\"\"\n Builds ticket messages attachments path\n \"\"\"\n ticket_folder = get_path_allegato(ticket=ticket_reply.ticket)\n path = '{}/{}'.format(ticket_folder,\n TICKET_REPLY_ATTACHMENT_SUBFOLDER)\n return path\n\ndef elimina_file(file_name, path=settings.MEDIA_ROOT):\n \"\"\"\n Deletes a file from disk\n \"\"\"\n file_path = '{}/{}'.format(path,file_name)\n try:\n os.remove(file_path)\n return path\n except:\n return False\n\ndef elimina_directory(ticket_id):\n \"\"\"\n Deletes a ticket attachments directory from disk\n \"\"\"\n path = '{}/{}/{}'.format(settings.MEDIA_ROOT,\n TICKET_FOLDER,\n ticket_id)\n try:\n shutil.rmtree(path)\n return path\n except:\n return False\n\ndef salva_file(f, path, nome_file):\n \"\"\"\n Saves a file on disk\n \"\"\"\n file_path = '{}/{}'.format(path,nome_file)\n\n if not os.path.exists(os.path.dirname(file_path)):\n os.makedirs(os.path.dirname(file_path))\n with open(file_path,'wb') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\ndef download_file(path, nome_file):\n \"\"\"\n Downloads a file\n \"\"\"\n mime = magic.Magic(mime=True)\n file_path = '{}/{}'.format(path,nome_file)\n content_type = mime.from_file(file_path)\n\n if os.path.exists(file_path):\n with open(file_path, 'rb') as fh:\n response = HttpResponse(fh.read(), content_type=content_type)\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)\n return response\n return None\n\ndef format_slugged_name(field_name, capitalize=True):\n \"\"\"\n Makes a string slugged\n \"\"\"\n f = field_name.replace('_',' ')\n if capitalize: return f.capitalize()\n return f\n\ndef visible_tickets_to_user(user, structure, office_employee):\n \"\"\"\n Returns a list of tickets that are visible to user\n \"\"\"\n model = apps.get_model('uni_ticket', 'TicketAssignment')\n default_office = office_employee.filter(office__is_default=True).first()\n if default_office:\n tickets = model.get_ticket_per_structure(structure)\n return tickets\n offices = []\n for oe in office_employee:\n if oe.office not in offices:\n offices.append(oe.office)\n tickets = model.get_ticket_in_office_list(offices)\n return tickets\n\ndef office_is_eliminabile(office):\n \"\"\"\n Returns True if office can be deleted\n \"\"\"\n if not office: return False\n if office.is_default: return False\n model = apps.get_model('uni_ticket', 'TicketAssignment')\n ticket_assegnati = model.objects.filter(office=office)\n if ticket_assegnati: return False\n return True\n\ndef uuid_code():\n \"\"\"\n Returns a short uuid code\n \"\"\"\n return shortuuid.uuid()\n\ndef ticket_summary_dict():\n \"\"\"\n send_mail to operators with a summary of open ticket\n \"\"\"\n model = apps.get_model('uni_ticket', 'Ticket')\n tickets = model.objects.exclude(is_closed=True)\n assign_model = apps.get_model('uni_ticket', 'TicketAssignment')\n\n # per ogni struttura\n # ticket_not_handled = tickets.filter(is_taken=[False, None])\n\n summary_dict = dict()\n offices = OrganizationalStructureOffice.objects.filter(is_active=True)\n for office in offices:\n # employees = office.organizationalstructureofficeemployee_set.filter(is_active=True)\n assignments = assign_model.objects.filter(office=office,\n follow=True,\n ticket__is_closed=False)\n if not summary_dict.get(office):\n summary_dict[office] = []\n\n for ticket in assignments:\n summary_dict[office].append({'subject': ticket.ticket.subject,\n 'url': ticket.ticket.get_url(structure=office.organizational_structure)})\n return summary_dict\n\ndef ticket_user_summary_dict(user):\n assign_model = apps.get_model('uni_ticket', 'TicketAssignment')\n structures = OrganizationalStructure.objects.filter(is_active=True)\n d = dict()\n oso = OrganizationalStructureOffice\n osoe = OrganizationalStructureOfficeEmployee\n office_employee = osoe.objects.filter(employee=user)\n for structure in structures:\n d[structure] = {}\n user_type = get_user_type(user, structure)\n offices = oso.objects.filter(organizational_structure=structure,\n is_active=True)\n for office in offices:\n if user_type == 'operator' and not office in office_employee:\n continue\n assignments = assign_model.objects.filter(office=office,\n follow=True,\n ticket__is_closed=False)\n if not d.get(office):\n d[structure][office] = []\n\n for ticket in assignments:\n d[structure][office].append({'subject': ticket.ticket.subject,\n 'url': ticket.ticket.get_url(structure=structure)})\n return d\n\ndef send_summary_email(users=[]):\n failed = []\n success = []\n for user in users:\n if not user.email:\n failed.append(user)\n continue\n msg = []\n ticket_sum = 0\n tick_sum = ticket_user_summary_dict(user)\n for structure in tick_sum:\n if not tick_sum[structure]: continue\n msg.append('{}:\\n'.format(structure))\n for office in tick_sum[structure]:\n if not tick_sum[structure][office]: continue\n msg.append('{} tickets in {}:\\n'.format(len(tick_sum[structure][office]),\n office.name))\n for ticket in tick_sum[structure][office]:\n ticket_sum += 1\n msg.append(' - {} (http://{}{})\\n'.format(ticket['subject'],\n settings.HOSTNAME,\n ticket['url']))\n msg.append('\\n')\n\n d = {'open_ticket_number': ticket_sum,\n 'tickets_per_office': ''.join(msg),\n 'hostname': settings.HOSTNAME,\n 'user': user}\n m_subject = _('{} - ticket summary'.format(settings.HOSTNAME))\n sent = send_custom_mail(subject=m_subject,\n body=SUMMARY_EMPLOYEE_EMAIL.format(**d),\n recipient=user)\n if not sent:\n failed.append(user)\n else:\n success.append(user)\n\n return {'success': success,\n 'failed': failed}\n\ndef user_offices_list(office_employee_queryset):\n if not office_employee_queryset: return []\n offices = []\n for oe in office_employee_queryset:\n if oe.office not in offices:\n offices.append(oe.office)\n return offices\n\n# Custom email sender\ndef send_custom_mail(subject, body, recipient):\n if not recipient: return False\n if not recipient.email_notify: return False\n result = send_mail(subject,\n body,\n settings.EMAIL_SENDER,\n [recipient.email,],\n fail_silently=True,\n auth_user=None,\n auth_password=None,\n connection=None,\n html_message=None)\n return result\n\n# START Roles 'get' methods\ndef user_is_employee(user):\n if not user: return False\n if getattr(settings, 'EMPLOYEE_ATTRIBUTE_NAME', False):\n attr = getattr(user, settings.EMPLOYEE_ATTRIBUTE_NAME)\n if callable(attr): return attr()\n else: return attr\n # If operator in the same Structure\n # is_operator = user_is_operator(request.user, struttura)\n # If manage something. For alla structures\n return user_manage_something(user)\n\ndef user_is_in_organization(user):\n \"\"\"\n \"\"\"\n if not user: return False\n if getattr(settings, 'USER_ATTRIBUTE_NAME', False):\n attr = getattr(user, settings.USER_ATTRIBUTE_NAME)\n if callable(attr): return attr()\n else: return attr\n return False\n# END Roles 'get' methods\n","sub_path":"uni_ticket/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"157552732","text":"import time\nimport machine\nimport utime\n\n\ndef web_page():\n \n \n \n\n TRIG = machine.Pin(12, machine.Pin.OUT)\n TRIG.off()\n utime.sleep_us(2)\n TRIG.on()\n utime.sleep_us(10)\n TRIG.off()\n ECHO = machine.Pin(13, machine.Pin.IN)\n while ECHO.value() == 0:\n pass\n t1 = utime.ticks_us()\n while ECHO.value() == 1:\n pass\n t2 = utime.ticks_us()\n cm = (t2 - t1) / 58.0\n print(cm)\n utime.sleep(2)\n \n\n\n \n html = \"\"\"\n\n\n\nText To Speech\n\n\n\n\n\n

Dystans: \"\"\" + str(cm) + \"\"\"

\n\n\n\n\n\n\n\n\n\"\"\"\n return html\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('', 80))\ns.listen(5)\n\nwhile True:\n conn, addr = s.accept()\n print('Got a connection from %s' % str(addr))\n request = conn.recv(1024)\n request = str(request)\n print('Content = %s' % request)\n response = web_page()\n conn.send('HTTP/1.1 200 OK\\n')\n conn.send('Content-Type: text/html\\n')\n conn.send('Connection: close\\n\\n')\n conn.sendall(response)\n conn.close()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"25628321","text":"import requests\nimport json\nimport pytest\n\nimport wordpress_orm\nfrom wordpress_orm import wp_session\n\nfrom ..wordpress_orm_extensions.job import Job, JobRequest\n\nurl = 'https://content.sorghumbase.org/wordpress/index.php/wp-json/wp/v2/job'\n\ndef test_wordpress_connection(wp_api):\n\t'''\n\tTest that the WordPress server is running and returns jobs.\n\t'''\n\tr = requests.get(url)\n\tassert r.status_code == 200\n\ndef test_event_schema(wp_api):\n\t'''\n\tTest that the api returns the same schema for jobs as is defined in the ORM.\n\t'''\n\tr = requests.get(url)\n\tjob_request = JobRequest(api=wp_api)\n\tjob_request.per_page = 1\n\tjobs = job_request.get()\n\tif len(jobs) == 0:\n\t\tpytest.skip('No jobs in the CMS')\n\tormSchema = list(jobs[0].s.__dict__)\n\tapiSchema = list(r.json()[0])\n\tapiSchema.pop() # Removes \"_links\" property\n\n\tassert ormSchema == apiSchema\n","sub_path":"sorghum_webapp/sorghum_webapp/tests/test_jobs.py","file_name":"test_jobs.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"472542539","text":"# -*- coding: utf-8 -*-\n# ------------------------------------------------------------------------------\n#\n# Copyright 2018-2019 Fetch.AI Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ------------------------------------------------------------------------------\n\n\"\"\"This package contains a scaffold of a behaviour.\"\"\"\nimport datetime\nimport logging\nfrom typing import Optional, cast, TYPE_CHECKING\n\nfrom aea.skills.base import Behaviour\nfrom aea.protocols.oef.message import OEFMessage\nfrom aea.protocols.oef.models import Description\nfrom aea.protocols.oef.serialization import OEFSerializer, DEFAULT_OEF\n\nif TYPE_CHECKING:\n from packages.skills.fipa_negotiation.search import Search\n from packages.skills.fipa_negotiation.strategy import Strategy\n from packages.skills.fipa_negotiation.transactions import Transactions\nelse:\n from fipa_negotiation_skill.search import Search\n from fipa_negotiation_skill.strategy import Strategy\n from fipa_negotiation_skill.transactions import Transactions\n\nDEFAULT_MSG_ID = 1\n\nlogger = logging.getLogger(\"aea.fipa_negotiation_skill\")\n\n\nclass GoodsRegisterAndSearchBehaviour(Behaviour):\n \"\"\"This class implements the goods register and search behaviour.\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Initialize the behaviour.\"\"\"\n self._services_interval = kwargs.pop('services_interval', 5) # type: int\n super().__init__(**kwargs)\n self._last_update_time = datetime.datetime.now() # type: datetime.datetime\n self._last_search_time = datetime.datetime.now() # type: datetime.datetime\n self._registered_goods_demanded_description = None # type: Optional[Description]\n self._registered_goods_supplied_description = None # type: Optional[Description]\n\n def setup(self) -> None:\n \"\"\"\n Implement the setup.\n\n :return: None\n \"\"\"\n pass\n\n def act(self) -> None:\n \"\"\"\n Implement the act.\n\n :return: None\n \"\"\"\n if self.context.agent_is_ready_to_pursuit_goals:\n if self._is_time_to_update_services():\n self._unregister_service()\n self._register_service()\n if self._is_time_to_search_services():\n self._search_services()\n\n def teardown(self) -> None:\n \"\"\"\n Implement the task teardown.\n\n :return: None\n \"\"\"\n self._unregister_service()\n\n def _unregister_service(self) -> None:\n \"\"\"\n Unregister service from OEF Service Directory.\n\n :return: None\n \"\"\"\n if self._registered_goods_demanded_description is not None:\n msg = OEFMessage(oef_type=OEFMessage.Type.UNREGISTER_SERVICE, id=DEFAULT_MSG_ID, service_description=self._registered_goods_demanded_description, service_id=\"\")\n msg_bytes = OEFSerializer().encode(msg)\n self.context.outbox.put_message(to=DEFAULT_OEF, sender=self.context.agent_public_key, protocol_id=OEFMessage.protocol_id, message=msg_bytes)\n self._registered_goods_demanded_description = None\n if self._registered_goods_supplied_description is not None:\n msg = OEFMessage(oef_type=OEFMessage.Type.UNREGISTER_SERVICE, id=DEFAULT_MSG_ID, service_description=self._registered_goods_supplied_description, service_id=\"\")\n msg_bytes = OEFSerializer().encode(msg)\n self.context.outbox.put_message(to=DEFAULT_OEF, sender=self.context.agent_public_key, protocol_id=OEFMessage.protocol_id, message=msg_bytes)\n self._registered_goods_supplied_description = None\n\n def _register_service(self) -> None:\n \"\"\"\n Register to the OEF Service Directory.\n\n In particular, register\n - as a seller, listing the goods supplied, or\n - as a buyer, listing the goods demanded, or\n - as both.\n\n :return: None\n \"\"\"\n strategy = cast(Strategy, self.context.strategy)\n transactions = cast(Transactions, self.context.transactions)\n if strategy.is_registering_as_seller:\n logger.debug(\"[{}]: Updating service directory as seller with goods supplied.\".format(self.context.agent_name))\n ownership_state_after_locks = transactions.ownership_state_after_locks(self.context.ownership_state, is_seller=True)\n goods_supplied_description = strategy.get_own_service_description(ownership_state_after_locks, is_supply=True)\n self._registered_goods_supplied_description = goods_supplied_description\n msg = OEFMessage(oef_type=OEFMessage.Type.REGISTER_SERVICE, id=DEFAULT_MSG_ID, service_description=goods_supplied_description, service_id=\"\")\n msg_bytes = OEFSerializer().encode(msg)\n self.context.outbox.put_message(to=DEFAULT_OEF, sender=self.context.agent_public_key, protocol_id=OEFMessage.protocol_id, message=msg_bytes)\n if strategy.is_registering_as_buyer:\n logger.debug(\"[{}]: Updating service directory as buyer with goods demanded.\".format(self.context.agent_name))\n ownership_state_after_locks = transactions.ownership_state_after_locks(self.context.ownership_state, is_seller=False)\n goods_demanded_description = strategy.get_own_service_description(ownership_state_after_locks, is_supply=False)\n self._registered_goods_demanded_description = goods_demanded_description\n msg = OEFMessage(oef_type=OEFMessage.Type.REGISTER_SERVICE, id=DEFAULT_MSG_ID, service_description=goods_demanded_description, service_id=\"\")\n msg_bytes = OEFSerializer().encode(msg)\n self.context.outbox.put_message(to=DEFAULT_OEF, sender=self.context.agent_public_key, protocol_id=OEFMessage.protocol_id, message=msg_bytes)\n\n def _search_services(self) -> None:\n \"\"\"\n Search on OEF Service Directory.\n\n In particular, search\n - for sellers and their supply, or\n - for buyers and their demand, or\n - for both.\n\n :return: None\n \"\"\"\n strategy = cast(Strategy, self.context.strategy)\n transactions = cast(Transactions, self.context.transactions)\n if strategy.is_searching_for_sellers:\n ownership_state_after_locks = transactions.ownership_state_after_locks(self.context.ownership_state, is_seller=False)\n query = strategy.get_own_services_query(ownership_state_after_locks, is_searching_for_sellers=True)\n if query is None:\n logger.warning(\"[{}]: Not searching the OEF for sellers because the agent demands no goods.\".format(self.context.agent_name))\n return None\n else:\n logger.debug(\"[{}]: Searching for sellers which match the demand of the agent.\".format(self.context.agent_name))\n search = cast(Search, self.context.search)\n search_id = search.get_next_id(is_searching_for_sellers=True)\n\n msg = OEFMessage(oef_type=OEFMessage.Type.SEARCH_SERVICES, id=search_id, query=query)\n msg_bytes = OEFSerializer().encode(msg)\n self.context.outbox.put_message(to=DEFAULT_OEF, sender=self.context.agent_public_key, protocol_id=OEFMessage.protocol_id, message=msg_bytes)\n if strategy.is_searching_for_buyers:\n ownership_state_after_locks = transactions.ownership_state_after_locks(self.context.ownership_state, is_seller=True)\n query = strategy.get_own_services_query(ownership_state_after_locks, is_searching_for_sellers=False)\n if query is None:\n logger.warning(\"[{}]: Not searching the OEF for buyers because the agent supplies no goods.\".format(self.context.agent_name))\n return None\n else:\n logger.debug(\"[{}]: Searching for buyers which match the supply of the agent.\".format(self.context.agent_name))\n search = cast(Search, self.context.search)\n search_id = search.get_next_id(is_searching_for_sellers=False)\n\n msg = OEFMessage(oef_type=OEFMessage.Type.SEARCH_SERVICES, id=search_id, query=query)\n msg_bytes = OEFSerializer().encode(msg)\n self.context.outbox.put_message(to=DEFAULT_OEF, sender=self.context.agent_public_key, protocol_id=OEFMessage.protocol_id, message=msg_bytes)\n\n def _is_time_to_update_services(self) -> bool:\n \"\"\"\n Check if the agent should update the service directory.\n\n :return: bool indicating the action\n \"\"\"\n now = datetime.datetime.now()\n diff = now - self._last_update_time\n result = diff.total_seconds() > self._services_interval\n if result:\n self._last_update_time = now\n return result\n\n def _is_time_to_search_services(self) -> bool:\n \"\"\"\n Check if the agent should search the service directory.\n\n :return: bool indicating the action\n \"\"\"\n now = datetime.datetime.now()\n diff = now - self._last_search_time\n result = diff.total_seconds() > self._services_interval\n if result:\n self._last_search_time = now\n return result\n","sub_path":"packages/skills/fipa_negotiation/behaviours.py","file_name":"behaviours.py","file_ext":"py","file_size_in_byte":9676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"330247383","text":"from RPi import GPIO\nfrom time import sleep\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(23, GPIO.OUT)\nlimit = 0.1\ncommandstop=\"stop\"\ncommandplus=1\ncomstr='1'\nledpin=23\ni=0\n#function on-off led \ndef blink():\n GPIO.output(ledpin,GPIO.HIGH)\n sleep(limit)\n GPIO.output(ledpin,GPIO.LOW)\n sleep(limit)\n \n#Osnovnaya programma\ntry:\n while True:\n GPIO.output(ledpin, True)\n sleep(limit)\n GPIO.output(ledpin, False)\n sleep(limit)\n command=input('Command for Stoping process :')\n command=str(command)\n \n if command.isdigit():\n print('Vvedeno chislo?_')\n print(command.isdigit())\n print('Kakoe_')\n print(command)\n #print(command.isdigit())\n while i R\n# m = msrc.recv();\n# mdst.write(m);\n# # R -> L\n# m2 = mdst.recv();\n# msrc.write(m2);\n\n\n# similar to the above, but with human-readable display of packets on stdout. \n# in this use case we abuse the self.logfile_raw() function to allow \n# us to use the recv_match function ( whch is then calling recv_msg ) , to still get the raw data stream\n# which we pass off to the other mavlink connection without any interference. \n# because internally it will call logfile_raw.write() for us.\n\n# here we hook raw output of one to the raw input of the other, and vice versa: \nmsrc.logfile_raw = mdst\nmdst.logfile_raw = msrc\n\nwhile True:\n # L -> R\n l = msrc.recv_match();\n if l is not None:\n l_last_timestamp = 0\n if l.get_type() != 'BAD_DATA':\n l_timestamp = getattr(l, '_timestamp', None)\n if not l_timestamp:\n l_timestamp = l_last_timestamp\n l_last_timestamp = l_timestamp\n \n print(\"--> %s.%02u: %s\\n\" % (\n time.strftime(\"%Y-%m-%d %H:%M:%S\",\n time.localtime(l._timestamp)),\n int(l._timestamp*100.0)%100, l))\n \n # R -> L\n r = mdst.recv_match();\n if r is not None:\n r_last_timestamp = 0\n if r.get_type() != 'BAD_DATA':\n r_timestamp = getattr(r, '_timestamp', None)\n if not r_timestamp:\n r_timestamp = r_last_timestamp\n r_last_timestamp = r_timestamp\n \n print(\"<-- %s.%02u: %s\\n\" % (\n time.strftime(\"%Y-%m-%d %H:%M:%S\",\n time.localtime(r._timestamp)),\n int(r._timestamp*100.0)%100, r))\n\n\n ","sub_path":"Utilities/MavLink_custom/pymavlink/examples/mavtcpsniff.py","file_name":"mavtcpsniff.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"117078771","text":"'''\nTask Coach - Your friendly task manager\nCopyright (C) 2004-2008 Frank Niessink \n\nTask Coach is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nTask Coach 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. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n'''\n\nimport test, wx, sys\nfrom taskcoachlib import meta, application\n\n\nclass AppTests(test.TestCase):\n def testAppProperties(self):\n # Normally I prefer one assert per test, but creating the app is\n # expensive, so we do all the queries in one test method.\n app = application.Application(loadSettings=False, loadTaskFile=False)\n wxApp = wx.GetApp()\n self.assertEqual(meta.name, wxApp.GetAppName())\n self.assertEqual(meta.author, wxApp.GetVendorName())\n","sub_path":"branches/Feature_SyncML/taskcoach/tests/unittests/AppTest.py","file_name":"AppTest.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"402916965","text":"import sys\n#sys.stdin=open(\"input.txt\", \"r\")\n\ndef DFS(i):\n global sum1, sum2, flag\n if i == n:\n for j in range(n):\n if res[j][1]==1:\n sum1+=res[j][0]\n else :\n sum2+=res[j][0]\n if sum1==sum2:\n flag=1\n else:\n sum1=0\n sum2=0\n else:\n res[i][1]=1 # O - 부분 집합 포함\n DFS(i+1)\n res[i][1]=0 # X - 부분 집합 제외\n DFS(i+1)\n\n\nif __name__==\"__main__\":\n n= int(input())\n a=list(map(int, input().split()))\n res=[]\n for i in range(n):\n res.append([])\n res[i].append(a[i])\n res[i].append(0)\n flag=0\n sum1=0\n sum2=0\n DFS(0)\n if flag==0:\n print(\"NO\")\n else:\n print(\"YES\")\n\n# res=[(1,0), (3,0),(5,0),(7,0),(9,0)] -> tuple자료구조는 immutable\n# print(res[1]) -> (3,0)\n# print(res[1][0])","sub_path":"section6/4. 합이 같은 부분 집합.py","file_name":"4. 합이 같은 부분 집합.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"570365997","text":"from oandapyV20 import API\r\nimport oandapyV20.endpoints.instruments as instruments\r\nfrom oandapyV20.contrib.factories import InstrumentsCandlesFactory\r\nimport pandas as pd\r\n\r\naccountID = \"101-009-11764804-001\"\r\naccess_token = \"2826adb0783333f6150483c0aa5f1a59-79127121efa78112f7578530295a5e38\"\r\nclient = API(access_token=access_token)\r\n\r\ndef cnv(r, h):\r\n for candle in r.get('candles'):\r\n ctime = candle.get('time')[0:19]\r\n try:\r\n rec = \"{time},{complete},{o},{h},{l},{v},{c}\".format(\r\n time=ctime,\r\n complete=candle['complete'],\r\n o=candle['mid']['o'],\r\n h=candle['mid']['h'],\r\n l=candle['mid']['l'],\r\n v=candle['volume'],\r\n c=candle['mid']['c'],\r\n )\r\n except Exception as e:\r\n print(e, r)\r\n else:\r\n h.write(rec+\"\\n\")\r\n\r\n_from = '2005-05-01T00:00:00Z' \r\n_to = '2019-07-17T00:00:00Z'\r\ngran = 'D'\r\ninstr = 'USD_CAD' \r\n\r\nparams = {\r\n \"granularity\": gran,\r\n \"from\": _from,\r\n \"to\": _to\r\n}\r\n\r\nwith open(\"./{}.{}.csv\".format(instr, gran), \"w\") as O:\r\n for r in InstrumentsCandlesFactory(instrument=instr, params=params):\r\n print(\"REQUEST: {} {} {}\".format(r, r.__class__.__name__, r.params))\r\n rv = client.request(r)\r\n cnv(r.response, O)\r\n\r\ndf = pd.read_csv(\"./USD_CAD.D.csv\" ,header=None,usecols=[0,2,3,4,5,6])\r\ndf.columns = ['time','open', 'high', 'low', 'volume','close']\r\n#df.index = 'time'\r\ndf = df.set_index('time')\r\ndf.head()\r\n","sub_path":"three_class_sequence_with_tech/get_historical_data.py","file_name":"get_historical_data.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"116187559","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 4 14:06:10 2019\n\n@author: talavera\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 20 10:15:34 2018\n\n@author: sujania\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\n\ninv = []\nhome = '/Users/sujania/Documents/'\nresults = '%s/PhD/NotesUU/RadialModes/results_AD/l2shift.txt' % home\nwith open(results,'rb') as source:\n for line in source:\n lines = line.split('\\t')\n inv.append(lines)\n\n# ----------------------------------------------------\nmnum = 6\nl2modes = [4,7,9,10,13,27]\ncolor = ['gray', 'gray', 'gray', 'gray', 'r','b'];\nwidth = [-0.25, -0.15, -0.05, 0.05, 0.15, 0.25, 0.35]\nmarker = ['v', 'o', 's', 'D'];\nmodelname = [r'Masters & Widmer, 1995',\n r'He & Tromp, 1996', \n r'Masters & Widmer (REM)',\n r'Deuss et al, 2013',\n r'My Inversion CC: ellip',\n r'My Inversion CC',\n ]\n\ni=0\nfig = plt.figure(figsize=(12,7))\nax = fig.add_subplot(2,1,1)\nfor model in ['MW95', 'HT', 'REM', 'AD', 'SCC', 'CC']:\n mode = [m for m in inv if m[3]==model]\n for m in mode:\n index = l2modes.index(int(m[0]))+1\n if model not in ['SCC', 'CC']: \n ax.errorbar(index+width[i], float(m[7]), yerr=float(m[6]), \n marker=marker[i], markersize=9, color=color[i], \n capsize=5, elinewidth=2.5)\n else:\n ax.errorbar(index+width[i], float(m[7]), marker='*',\n markersize=15, color=color[i], capsize=5, \n elinewidth=2.5)\n i=i+1\n \nmodename = ['${}_{%s}S_2$'%int(ll) for ll in l2modes]\n\nfor j in np.linspace(1, len(modename), len(modename)):\n plt.axvline(x=j+0.5, color='lightgray', \n linestyle='--', linewidth=1, zorder=0)\nplt.axhline(y=0, color='lightgray', linestyle='-', linewidth=5, zorder=0)\nplt.text(3.5, 0, 'PREM', fontsize=19, backgroundcolor='w', \n va='center', ha='center', zorder=1)\nax.tick_params(axis = 'both', which = 'major', labelsize=18, zorder=0)\nax.set_xticks(np.linspace(1, len(modename), len(modename)))\nax.set_xticklabels(modename, rotation='horizontal', fontsize=25)\nxlim = ax.get_xlim()\nax.yaxis.set_major_locator(plt.MaxNLocator(4))\nax.set_ylabel('$\\delta$f ($\\mu$Hz)', fontsize=25)\n#ax.set_ylim(-2,6)\nax.set_xlim(0.5,mnum+0.5)\n\ni = 0\nax = fig.add_subplot(2,1,2)\nax.set_xticks(np.linspace(1, len(modename), len(modename)))\n\nfor model in ['MW95', 'HT', 'REM', 'AD', 'SCC', 'CC']:\n mode = [m for m in inv if m[3]==model]\n for m in mode:\n index = l2modes.index(int(m[0]))+1\n if model not in ['SCC', 'CC']: \n ax.errorbar(index+width[i], float(m[11]), yerr=float(m[10]), \n marker=marker[i], markersize=9, color=color[i], \n capsize=5, elinewidth=2.5)\n else:\n ax.errorbar(index+width[i], float(m[11]), marker='*',\n markersize=15, color=color[i], \n capsize=5, elinewidth=2.5)\n i=i+1\nfor j in np.linspace(1, len(modename), len(modename)):\n plt.axvline(x=j+0.5, color='lightgray', \n linestyle='--', linewidth=1, zorder=0)\nplt.axhline(y=0, color='lightgray', linestyle='-', linewidth=5, zorder=0)\nplt.text(3.5, 0, 'PREM', fontsize=19, backgroundcolor='w', \n va='center', ha='center', zorder=1)\nax.tick_params(axis = 'both', which = 'major', labelsize = 18, zorder=0)\nax.set_xticklabels(modename, rotation='horizontal', fontsize=25)\nax.set_xlim(xlim)\nax.yaxis.set_major_locator(plt.MaxNLocator(7))\nax.set_ylabel('$\\delta$$Q$',fontsize=25)\n#ax.set_ylim(-100,180)\nax.set_xlim(0.5,mnum+0.5)\n\nlegend=[]; i=0\nfor model in modelname: \n if model not in ['My Inversion CC: ellip','My Inversion CC']: \n legend.append(Line2D([0],[0], color='w', marker=marker[i], \n markersize=15, mfc=color[i], label=modelname[i]))\n else:\n legend.append(Line2D([0],[0], color='w', marker='*', markersize=20, \n mfc=color[i], label=modelname[i]))\n i = i + 1\nlgd = ax.legend(handles=legend, loc='lower center', \n fontsize=14, frameon=False, ncol=2, \n bbox_to_anchor=(0.5, -0.75))\n\nplt.show()\nplt.tight_layout()\n#fig.savefig('df_dQ_results', bbox_extra_artists=(lgd,), \n# bbox_inches='tight', dpi=350) \n","sub_path":"frospy/tests/todo/Su/plot_l=2_measurements.py","file_name":"plot_l=2_measurements.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"273889272","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nfrom scipy import integrate\n\n\ndef f(x):\n return np.sin(x) + 0.5 * x\n\n\na = 0.5\nb = 9.5\nx = np.linspace(0, 10)\ny = f(x)\n# 求积分方法\nintegrate.fixed_quad(f, a, b) # 固定高斯求积\n\nintegrate.quad(f, a, b) # 自适应求积\n\nxi = np.linspace(0.5, 9.5, 100)\nintegrate.trapz(f(xi), xi) # 梯形法则\n\nintegrate.simps(f(xi), xi) # 辛普森法则\nnp.random.normal(size=20)\n\n# 正态随机范例\nx = sorted(np.random.normal(loc=5, scale=10, size=2000))\nplt.hist(x, bins=100)\n\n# 通过模拟求积分\nnp.random.seed(1000) # 设置种子数\nx = np.random.random(2000) * (b - a) + a # 将x的值设置为区间范围内的一个随机数\nnp.sum(f(x)) / len(x) * (b - a) # 先求出积分区间的平均函数值,再乘以区间长度得出积分值\n","sub_path":"积分.py","file_name":"积分.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"639705089","text":"\n\n#calss header\nclass _SAILOR():\n\tdef __init__(self,): \n\t\tself.name = \"SAILOR\"\n\t\tself.definitions = [u'a person who works on a ship, especially one who is not an officer', u'a person who often takes part in the sport of using boats with sails', u'someone who is not/often ill when travelling by boat']\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/_sailor.py","file_name":"_sailor.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"289748853","text":"#import BeautifulSoup\nfrom bs4 import BeautifulSoup as bs\nimport requests\nfrom selenium import webdriver\nfrom splinter import Browser\nimport pandas as pd\n\ndef init_browser():\n # @NOTE: Replace the path with your actual path to the chromedriver\n executable_path = {'executable_path': 'chromedriver.exe'}\n return Browser('chrome', **executable_path, headless=False)\n\ndef scrape_info():\n browser = init_browser()\n #Mars.nasa.gov scrape\n #import webpage to be scraped, use requests module to obtain webpage URL and parse with beautifulsoup\n url = 'https://mars.nasa.gov/news/'\n\n #visit url and get html from new browser (bypass Javascript), use BeautifulSoup parser\n browser.visit(url)\n html = browser.html\n soup = bs(html, 'html.parser')\n\n #find all results with content-title within div\n results = soup.find_all('div', class_=\"content_title\")\n\n #find first title\n news_title = results[0].text\n print(news_title)\n\n #first first paragraph body associated with title\n p_results = soup.find_all('div', class_=\"article_teaser_body\")\n news_p = p_results[0].text\n print(news_p)\n browser.quit()\n\n #jpl.nasa.gov scrape\n #assign url and visit\n browser = init_browser()\n jp_url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(jp_url)\n\n #click through to full image\n browser.click_link_by_partial_text('FULL IMAGE')\n\n #define img site url from open browser after clicking on full image\n img_html = browser.html\n img_soup = bs(img_html, 'html.parser')\n\n #find all articles\n result_1 = img_soup.find_all(\"article\")\n # print(result_1[0].prettify())\n\n #img link is attribute withing article within data-fancybox-href\n img_link = result_1[0].a[\"data-fancybox-href\"] \n\n #define base url\n base_img_url = \"https://www.jpl.nasa.gov\"\n\n #combined base url with specific image url\n featured_img_url = base_img_url + img_link\n print(featured_img_url)\n browser.quit()\n\n #mars weather scrape\n #assign url and visit\n browser = init_browser()\n t_url = 'https://twitter.com/marswxreport?lang=en'\n browser.visit(t_url)\n t_html = browser.html\n t_soup = bs(t_html, 'html.parser')\n\n #find results that contain tweet stream\n t_results = t_soup.find_all('div', class_=\"js-tweet-text-container\")\n # print(t_results[0].prettify())\n\n #look through results to find first paragraph entry that contains 'Insight sol' as key for weather data, if found then break the loop and store string\n for result in t_results:\n p_text = result.p.text\n key_string = \"InSight sol\"\n if key_string not in p_text:\n continue\n else: mars_weather = p_text\n break\n\n print(mars_weather)\n browser.quit()\n\n #mars facts scrape\n fact_url = \"http://space-facts.com/mars/\"\n\n #read in tables as html via PANDAS\n tables = pd.read_html(fact_url)\n\n #mars facts is only table on page, so 0th dataframe element is table list\n mars_facts_df = tables[0]\n\n #rename columns to parameter and value to clean up dataframe\n mars_facts_df = mars_facts_df.rename(columns={0:\"Paramter\", 1:\"Value\"})\n\n #convert dataframe to html string\n mars_html_table = mars_facts_df.to_html()\n mars_html_table = mars_html_table.replace('\\n', '')\n print(mars_html_table)\n\n #ASGS scrape\n #assign url and visit\n browser = init_browser()\n\n #visit main page\n usgs_url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(usgs_url)\n\n #define html from main page and parse\n usgs_html = browser.html\n usgs_soup = bs(usgs_html, 'html.parser')\n\n #find results for each item\n usgs_results = usgs_soup.find_all('div', class_=\"item\")\n # len(usgs_results)\n\n hemisphere_image_urls = []\n\n for i in range(0, len(usgs_results)):\n #find title via h3 header\n title = usgs_results[i].find('h3').text\n \n #find image url - locate enhanced image url and open new browser\n image_url = usgs_results[i].a[\"href\"]\n base_url = \"https://astrogeology.usgs.gov\"\n enhanced_url = base_url + image_url\n browser.visit(enhanced_url)\n \n #create new base line html from new enhanced image in browser\n sample_html = browser.html\n sample_soup = bs(sample_html, 'html.parser')\n \n #find link within class of downloads - sample results will only return one item\n sample_results = sample_soup.find_all('div', class_=\"downloads\")\n img_url = sample_results[0].a[\"href\"]\n\n #add title and image url to dictionary\n dict_img = {\"title\": title, \"img_url\": img_url}\n hemisphere_image_urls.append(dict_img)\n \n print(hemisphere_image_urls)\n \n #store mars data in a dictionary\n mars_data = {\n \"news_title\" : news_title,\n \"news_p\" : news_p,\n \"featured_img_url\" : featured_img_url,\n \"mars_weather\" : mars_weather,\n \"mars_html_table\" : mars_html_table,\n \"hemisphere_img_list\" : hemisphere_image_urls\n }\n \n browser.quit()\n\n return mars_data\n\n \n","sub_path":"scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":5169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"240907894","text":"# https://leetcode-cn.com/problems/reverse-string/\r\n\r\n\r\nclass Solution:\r\n def reverseString(self, s) -> None:\r\n \"\"\"\r\n Do not return anything, modify s in-place instead.\r\n \"\"\"\r\n def rever(start, end, li):\r\n if start >= end:\r\n return li\r\n li[start], li[end] = li[end], li[start]\r\n return rever(start + 1, end - 1, li)\r\n\r\n rever(0, len(s) - 1, s)\r\n print(s)\r\n\r\n\r\ns = [\"h\", \"e\", \"l\", \"l\", \"o\"]\r\n# s = []\r\nprint(Solution().reverseString(s))\r\n","sub_path":"344-3-Reverse String-recursive.py","file_name":"344-3-Reverse String-recursive.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"297737067","text":"# For description of classes refer ClassesExplanation.txt file\r\nclass Point:\r\n def move(self):\r\n print(\"Move\")\r\n\r\n def draw(self):\r\n print(\"Draw\")\r\n\r\n\r\npoint1 = Point() # here point1 is a object or instance of the class point\r\npoint1.draw()\r\n# as we defined the draw method/function earlier it can be accessed by the object created\r\n# within the class 'Point'\r\n\r\npoint1.x = 10 # Here x is an attribute\r\npoint1.y = 20 # Here y is an attribute\r\nprint(point1.x)\r\n\r\npoint2 = Point()\r\n# print(point2.x) # Try this by removing Hash\r\n\r\n# As point2 is a completely new object of the class 'Point', Attributes of point1\r\n# cannot be implemented in point2.\r\n","sub_path":"Beginners/Classes.py","file_name":"Classes.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"433496773","text":"import pyfits \nimport numpy\nimport math\nimport matplotlib\nimport matplotlib.pyplot as p\nimport scipy.interpolate as inter\nimport scipy\nfrom scipy.signal import argrelextrema\n\n#import prediction\n#import noise\n\ndef gaussian(x, xo, a, b):\n return a*numpy.exp(-(x-xo)**2/(2*b**2)) \n \ndef SN(prob, flux):\n #F_av=numpy.sum(prob*flux)\n F_peak=flux[numpy.argmax(prob)]\n \n sigma_1=scipy.special.erf(1*2**-.5)\n \n aux=numpy.argsort(prob)\n acum=numpy.cumsum(prob[aux][::-1]) \n index=numpy.where(abs(acum-sigma_1)==min(abs(acum-sigma_1)))[0]\n F_min, F_max= numpy.nanmin(flux[aux][::-1][0:index+1]), numpy.nanmax(flux[aux][::-1][0:index+1]) \n\n\n if(F_max==F_peak or F_min==F_peak):\n sn=0 \n else:\n if(F_peak>0):\n sn=F_peak/(F_peak-F_min)\n else:\n sn=F_peak/(F_max-F_peak)\n \n return F_peak, sn\n\ndef calculo(onda, value, errores, centro, u, sigma, F, largo):\n f=numpy.zeros(len(F)) \n L=numpy.zeros((len(sigma), len(F))) \n \n longitudes=numpy.zeros(largo) \n longitudes= onda[u-(len(longitudes)-1)/2:u+(len(longitudes)-1)/2+1]\n err=errores[u-(len(longitudes)-1)/2:u+(len(longitudes)-1)/2+1] \n aux=value[u-(len(longitudes)-1)/2:u+(len(longitudes)-1)/2+1]\n \n for i in range(len(F)): \n for j in range(len(sigma)): \n chi=numpy.nansum(((aux-gaussian(longitudes, centro, F[i]/sigma[j], sigma[j]))/err)**2)\n L[j, i]=numpy.exp(-1.0*chi/2) \n \n #getting most probable f, sigma pair \n indices=numpy.where(L==numpy.amax(L)) \n f_peak= F[indices[1]]/sigma[indices[0]]\n sigma_peak= sigma[indices[0]]\n \n #getting Flux pdf\n for i in range(len(F)):\n f[i]= sum(L[:, i]/sigma)\n f=f/sum(f)\n F=F*(math.pi*2)**0.5 \n aux=SN(f,F) \n \"\"\"\n if(abs(aux[1])>5):\n print longitudes\n fig1=p.figure()\n p.plot(F, f, color='black', linewidth=2.5) \n p.title(str(onda[u])) \n p.ylabel('$Probability$', fontsize=60) \n p.xlabel('$Line$ $Flux$ $[erg/s/cm^{2}]$', fontsize=60) \n p.show() \n \"\"\"\n return aux[0], aux[1], f_peak[0], sigma_peak[0] #FPEAK DOES NOT NECESSARILY MATCH f_peak, sigma_peak \n\ndef main(onda, value, onda_i, value_i, errores):\n\n #n=numpy.round(len(value)/2048.)\n\n specres=2.\n disper= (onda[-1]-onda[0])/len(onda) #one frame*number of frames\n \n cut= 3. #sigma cut in flux density for peak search \n longlen= int(numpy.round(15./disper)) #11 #width of fitting gaussian \n dwave= .5 #gaussian center spacing \n order= int(numpy.round(specres/disper)) #max likelihood peak search order\n\n sigma_i= 2 # min sigma value \n sigma_f= 7 #1216*(1+z)*400/3e5 # max sigma value\n \n sig1=scipy.stats.sigmaclip(value_i, low=3., high=3.)[0]\n av=numpy.std(sig1) \n \n lambdas=numpy.arange(onda[longlen], onda[-longlen], dwave) \n sigma=numpy.linspace(sigma_i, sigma_f, 10)\n \n fluxes1=numpy.arange(cut*av, 1.2*max(value), 2e-19)\n fluxes2=numpy.arange(1.2*min(value), -cut*av, 2e-19)\n fluxes=numpy.append(fluxes2, fluxes1)\n \n #fluxes=numpy.zeros(100)\n #fluxes[0:len(fluxes)/2]= numpy.linspace(1.2*min(value), -av, len(fluxes)/2)\n #fluxes[len(fluxes)/2:]= numpy.linspace(av, 1.2*max(value), len(fluxes)/2)\n \n mask1=numpy.where(abs(value_i)>cut*av)[0]\n mask2=argrelextrema(abs(value_i), numpy.greater, order=order)[0] \n mask=numpy.intersect1d(mask1, mask2)\n \n \n fig1=p.figure()\n p.plot(onda_i, value_i, '.')\n p.plot(onda_i[mask1], value_i[mask1], '.')\n p.plot(onda_i[mask], value_i[mask], '.')\n p.show() \n \n \n longitudes=numpy.zeros(longlen) \n L=numpy.zeros((len(lambdas), len(sigma), len(fluxes)))\n \n for i in range(len(lambdas)):\n aux_i=abs(onda_i-lambdas[i])\n index_i=numpy.where(aux_i==min(aux_i))[0][0] \n aux=abs(onda-lambdas[i])\n index=numpy.where(aux==min(aux))[0][0] \n \n if(abs(value_i[index_i])>cut*av):\n longitudes= onda[index-(longlen-1)/2:index+(longlen-1)/2+1] \n err= errores[index-(longlen-1)/2:index+(longlen-1)/2+1] \n aux= value[index-(longlen-1)/2:index+(longlen-1)/2+1] \n for j in range(len(sigma)):\n for k in range(len(fluxes)): \n chi=numpy.nansum(((aux-gaussian(longitudes, lambdas[i], fluxes[k], sigma[j]))/err)**2)\n L[i, j, k]=numpy.exp(-1.0*chi/2) \n \n L[:,:,:]=L[:,:,:]/numpy.sum(L) \n \n p_lambdas=numpy.zeros(len(lambdas)) \n p_aux=numpy.zeros(len(lambdas)) \n for i in range(len(p_lambdas)):\n p_lambdas[i]= numpy.nanmax(L[i,:,:]) #numpy.sum(L[i,:,:]) \n p_aux[i]=numpy.sum(L[i,:,:]) \n \n p_lambdas=p_lambdas/sum(p_lambdas) \n p_aux=p_aux/sum(p_aux)\n \n indices=argrelextrema(p_aux, numpy.greater, order=order)[0] \n #indices=numpy.where(p_aux>0.)[0] \n \"\"\"\n fig1=p.figure()\n p.plot(lambdas, p_lambdas)\n p.show()\n \"\"\"\n \"\"\"\n matplotlib.rc('xtick', labelsize=30) \n matplotlib.rc('ytick', labelsize=30) \n fig1=p.figure()\n p.plot(onda, value, color='black', linewidth=2) \n p.plot(x, gaussian(x, lambdas[maximos[0][0]], fluxes[maximos[2][0]], sigma[maximos[1][0]]), color='red', linewidth=3) \n p.title(r'$Max$ $Likelihood$', fontsize=60) \n p.gca().set_ylabel(r'$f_{\\lambda}$ $[erg/s/cm^{2}/ \\AA]$', fontsize=60)\n p.gca().set_xlabel('$\\lambda$ $[\\AA]$', fontsize=60)\n #p.xlim(5420, 5540) \n p.show() \n \"\"\"\n \n F=numpy.linspace(sigma[0]*fluxes[0], sigma[len(sigma)-1]*fluxes[len(fluxes)-1], 800) \n sigma_array=numpy.linspace(sigma_i, sigma_f, 10)\n \n detections=numpy.zeros((len(indices), 6))\n for k,i in enumerate(indices):\n #waves=numpy.linspace(lambdas[i]-dwave, lambdas[i]+dwave, 10)\n #auxsn=numpy.zeros(len(waves))\n \n aux=abs(onda-lambdas[i])\n index=numpy.where(aux==min(aux))[0][0] \n #for w in range(len(waves)):\n #aux= abs(onda-waves[w])\n #index= numpy.where(aux==min(aux))[0] \n #auxsn[w]= calculo(onda, value, errores, waves[w], index, sigma_array, F, len(longitudes))[1]\n \n wavecenter= lambdas[i]#waves[numpy.where(auxsn==numpy.nanmax(auxsn))[0]][0] \n detections[k,0]= wavecenter\n detections[k,1:5]= calculo(onda, value, errores, wavecenter, index, sigma_array, F, len(longitudes)) \n detections[k, 5]= detections[k,3]/av\n return detections\n \n \n","sub_path":"Bayesian/Codes/Old/detection_old.py","file_name":"detection_old.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"37068448","text":"import talib\nimport pandas as pd\nimport numpy as np\nimport quandl\nimport math\nfrom sklearn import preprocessing, cross_validation, linear_model, neighbors\n\n\ndef get_candle_funcs():\n funcs = {}\n for name in talib.abstract.__FUNCTION_NAMES:\n if name.startswith('CDL'):\n funcs[name] = getattr(talib, name)\n return funcs\n\n# Quandl requires API key to fetch the stock data\nquandl.ApiConfig.api_key = '4_oX5z6kBUsPsQgkZgXn'\n\n# Disable the ignorance of print list [0 0 0 0 ... 0 0 0 0] = > [0 0 0 0 0 100 0 100 -100 0 0]\nnp.set_printoptions(threshold=np.nan)\npd.set_option('display.max_rows', None)\n\n\ndef train(ticker):\n data = quandl.get(\"WIKI/\" + ticker)\n original_closing_price = data.copy()\n data['UpDown'] = data['Adj. Volume'].pct_change()\n data.fillna(0, inplace=True)\n processed_UpDown = [1 if v > 0 else -1 for v in data['UpDown']]\n # Insert a column to indicate if the stock goes up or down in that day\n data['Label'] = processed_UpDown\n data[\"Date\"] = pd.to_datetime(data.index)\n\n O = np.array(data['Open'])\n H = np.array(data['High'])\n L = np.array(data['Low'])\n C = np.array(data['Close'])\n\n funcs = get_candle_funcs()\n\n results = {}\n for f in funcs:\n results[f] = funcs[f](O, H, L, C)\n\n candlestick_pattern_names = list(results.keys())\n results['Label'] = data['Label'].as_matrix()\n results['Date'] = data['Date'].as_matrix()\n\n\n # Create a Pandas dataframe from some data.\n # df = pd.DataFrame(data, columns=candlestick_pattern_names)\n\n pd.DataFrame.from_dict(results, orient='columns').to_csv('candle_pattern.csv', index=False)\n # index_col=61 means using 61th column as index (Date)\n edited_data = pd.read_csv('candle_pattern.csv', index_col=61)\n\n\n n_samples = len(edited_data)\n\n # we want to forecast out 10% of the stock price\n forecast_out = int(math.ceil(0.01 * n_samples))\n\n X = np.array(edited_data.drop(['Label'], 1))\n X = preprocessing.scale(X)\n\n edited_data.dropna(inplace=True)\n y = np.array(edited_data['Label'])\n X_lately = X[-forecast_out:]\n # X = X[:-forecast_out]\n # y= y[:-forecast_out]\n # print(X)\n # print(y)\n\n # Training\n X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)\n\n # logistic_classifier = linear_model.LogisticRegression(C=1e5, n_jobs=-1)\n # logistic_classifier.fit(X_train, y_train)\n # logis_confidence = logistic_classifier.score(X_test, y_test)\n # logis_forecast_set = logistic_classifier.predict(X_lately)\n\n # print('Confidence Score(Logistic Regression): ' + str(logis_confidence))\n # print(' logis_forecast_set (Logistic Regression): ' + str(logis_forecast_set))\n\n knn = neighbors.KNeighborsClassifier()\n knn.fit(X_train, y_train)\n knn_confidence = knn.score(X_test, y_test)\n knn_forecast_set = knn.predict(X_lately)\n\n\n # Confidence Score\n # print('Confidence Score(Logistic Regression): ' + str(logis_confidence))\n # print('Confidence Score(knn): ' + str(knn_confidence))\n # print(forecast_set)\n\n return original_closing_price, knn_forecast_set, knn_confidence\n\n# X = np.array(edited_data.drop(['Label'], 1))\n# X = preprocessing.scale(X)\n","sub_path":"knn_model.py","file_name":"knn_model.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"248221749","text":"import os\nimport types\nimport numpy as np\n\nimport KratosMultiphysics\nimport KratosMultiphysics.KratosUnittest as KratosUnittest\nimport KratosMultiphysics.kratos_utilities as kratos_utilities\nimport KratosMultiphysics.RomApplication.rom_testing_utilities as rom_testing_utilities\nif kratos_utilities.CheckIfApplicationsAvailable(\"FluidDynamicsApplication\"):\n import KratosMultiphysics.FluidDynamicsApplication\n\n@KratosUnittest.skipIfApplicationsNotAvailable(\"FluidDynamicsApplication\")\nclass TestFluidRom(KratosUnittest.TestCase):\n\n def setUp(self):\n self.relative_tolerance = 1.0e-12\n\n def testFluidRom2D(self):\n self.work_folder = \"fluid_dynamics_test_files/ROM/\"\n parameters_filename = \"../ProjectParameters.json\"\n expected_output_filename = \"ExpectedOutputROM.npy\"\n\n with KratosUnittest.WorkFolderScope(self.work_folder, __file__):\n # Set up simulation\n with open(parameters_filename,'r') as parameter_file:\n parameters = KratosMultiphysics.Parameters(parameter_file.read())\n model = KratosMultiphysics.Model()\n self.simulation = rom_testing_utilities.SetUpSimulationInstance(model, parameters)\n\n # Patch the RomAnalysis class to save the selected time steps results\n def Initialize(cls):\n super(type(self.simulation), cls).Initialize()\n cls.selected_time_step_solution_container = []\n\n def FinalizeSolutionStep(cls):\n super(type(self.simulation), cls).FinalizeSolutionStep()\n\n variables_array = [KratosMultiphysics.VELOCITY_X, KratosMultiphysics.VELOCITY_Y, KratosMultiphysics.PRESSURE]\n array_of_results = rom_testing_utilities.GetNodalResults(cls._solver.GetComputingModelPart(), variables_array)\n cls.selected_time_step_solution_container.append(array_of_results)\n\n self.simulation.Initialize = types.MethodType(Initialize, self.simulation)\n self.simulation.FinalizeSolutionStep = types.MethodType(FinalizeSolutionStep, self.simulation)\n\n # Run test case\n self.simulation.Run()\n\n # Check results\n expected_output = np.load(expected_output_filename)\n n_values = len(self.simulation.selected_time_step_solution_container[0])\n n_snapshots = len(self.simulation.selected_time_step_solution_container)\n obtained_snapshot_matrix = np.zeros((n_values, n_snapshots))\n for i in range(n_snapshots):\n snapshot_i= np.array(self.simulation.selected_time_step_solution_container[i])\n obtained_snapshot_matrix[:,i] = snapshot_i.transpose()\n\n for i in range (n_snapshots):\n up = sum((expected_output[:,i] - obtained_snapshot_matrix[:,i])**2)\n down = sum((expected_output[:,i])**2)\n l2 = np.sqrt(up/down)\n self.assertLess(l2, self.relative_tolerance)\n\n def tearDown(self):\n with KratosUnittest.WorkFolderScope(self.work_folder, __file__):\n # Cleaning\n for file_name in os.listdir():\n if file_name.endswith(\".time\"):\n kratos_utilities.DeleteFileIfExisting(file_name)\n\n##########################################################################################\n\nif __name__ == '__main__':\n KratosMultiphysics.Logger.GetDefaultOutput().SetSeverity(KratosMultiphysics.Logger.Severity.WARNING)\n KratosUnittest.main()\n","sub_path":"applications/RomApplication/tests/test_fluid_rom.py","file_name":"test_fluid_rom.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"350999048","text":"import gzip\nimport os\nimport warnings\nimport pandas as pd\nfrom io import TextIOWrapper\n\ntry:\n import fastavro as avro\n\n avro_imported = True\nexcept ImportError:\n avro_imported = False\n\n\ndef read_df(datafile, **read_args):\n \"\"\"Read a dataframe from file based on the file extension\n\n The following formats are supported:\n parquet, avro, csv, pickle\n\n Parameters\n ----------\n datafile : DataFile\n DataFile instance with the path and handle\n read_args : optional\n All keyword args are passed to the read function\n\n Returns\n -------\n data : pd.DataFrame\n\n Notes\n -----\n The read functions are taken from pandas, e.g. pd.read_csv\n Check the pandas doc for more information on the supported arguments\n\n \"\"\"\n filetype, compression = _get_extension(datafile.path)\n reader = _readers[filetype]\n if (\n reader in (pd.read_csv, pd.read_pickle, pd.read_json)\n and compression is not None\n ):\n read_args[\"compression\"] = compression\n elif reader in (pd.read_csv, pd.read_pickle, pd.read_json):\n read_args[\n \"compression\"\n ] = None # default \"infer\" incompatible with handles as of 0.24\n if reader == pd.read_json:\n # Default json file is newline delimited json records, but can be overwritten\n defaults = {\"lines\": True, \"orient\": \"records\"}\n defaults.update(read_args)\n read_args = defaults\n\n with datafile.handle(\"rb\") as f:\n return reader(f, **read_args)\n\n\ndef write_df(df, datafile, **write_args):\n \"\"\"Write a dataframe to file based on the file extension\n\n The following formats are supported:\n parquet, avro, csv, pickle\n\n Parameters\n ----------\n df : pd.DataFrame\n The dataframe to write to disk\n datafile : DataFile\n Datafile instance with the path and file handle\n write_args : optional\n All keyword args are passed to the write function\n\n Notes\n -----\n The write functions are taken from pandas, e.g. pd.to_csv\n Check the pandas doc for more information on the supported arguments\n\n \"\"\"\n extension, compression = _get_extension(datafile.path)\n write_name = _writers[extension]\n # infer compression from filepath or from explicit arg\n compression = compression or write_args.get(\"compression\")\n with datafile.handle(\"wb\") as buf:\n # Some customizations for different file types\n if write_name == \"to_avro\":\n return _write_avro(df, buf, **write_args)\n\n if (\n write_name == \"to_parquet\"\n and not pd.Series(df.columns).map(type).eq(str).all()\n ):\n warnings.warn(\n \"Dataframe contains non-string column names, which cannot be saved in parquet.\\n\"\n \"Blocks will attempt to convert them to strings.\"\n )\n df.columns = df.columns.astype(\"str\")\n\n if write_name == \"to_json\":\n defaults = {\"lines\": True, \"orient\": \"records\"}\n defaults.update(write_args)\n write_args = defaults\n\n if write_name == \"to_csv\":\n # make index=False the default for similar behaviour to other formats\n write_args[\"index\"] = write_args.get(\"index\", False)\n\n # For csv and pickle we have to manually compress\n manual_compress = write_name in (\"to_csv\", \"to_pickle\", \"to_json\")\n if manual_compress:\n write_args[\n \"compression\"\n ] = None # default \"infer\" incompatible with handles as of 0.24\n\n if manual_compress and compression is not None:\n raise ValueError(\n \"Compression {} is not supported for CSV/Pickle/JSON\".format(\n compression\n )\n )\n\n if write_name in (\"to_csv\", \"to_json\"):\n buf = TextIOWrapper(buf, write_through=True)\n\n write_fn = getattr(df, write_name)\n write_fn(buf, **write_args)\n\n\ndef _read_avro(handle, **read_args):\n if not avro_imported:\n raise ImportError(\n \"Avro support requires fastavro.\\n\"\n \"Install blocks with the [avro] option or `pip install fastavro`\"\n )\n records = []\n avro_reader = avro.reader(handle)\n for record in avro_reader:\n records.append(record)\n return pd.DataFrame.from_dict(records)\n\n\ndef _write_avro(df, handle, **write_args):\n if not avro_imported:\n raise ImportError(\n \"Avro support requires fastavro.\\n\"\n \"Install blocks with the [avro] option or `pip install fastavro`\"\n )\n schema = None\n schema_path = None\n try:\n schema = write_args[\"schema\"]\n except KeyError:\n try:\n schema_path = write_args[\"schema_path\"]\n except KeyError:\n raise Exception(\n \"You must provide a schema or schema path when writing to Avro\"\n )\n if schema is None:\n schema = avro.schema.load_schema(schema_path)\n records = df.to_dict(\"records\")\n avro.writer(handle, schema, records)\n\n\ndef _get_extension(path):\n name, ext = os.path.splitext(path)\n # Support compression extensions, eg part.csv.gz\n comp = None\n if ext in _compressions and \".\" in name:\n comp = ext\n name, ext = os.path.splitext(name)\n return ext, _compressions.get(comp)\n\n\n_readers = {\n \".pq\": pd.read_parquet,\n \".parquet\": pd.read_parquet,\n \".csv\": pd.read_csv,\n \".pkl\": pd.read_pickle,\n \".avro\": _read_avro,\n \".json\": pd.read_json,\n}\n\n\n_writers = {\n \".pq\": \"to_parquet\",\n \".parquet\": \"to_parquet\",\n \".csv\": \"to_csv\",\n \".pkl\": \"to_pickle\",\n \".avro\": \"to_avro\",\n \".json\": \"to_json\",\n}\n\n_compressions = {\".gz\": \"gzip\", \".bz2\": \"bz2\", \".zip\": \"zip\", \".xz\": \"xz\"}\n","sub_path":"blocks/dfio.py","file_name":"dfio.py","file_ext":"py","file_size_in_byte":5770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"121999601","text":"from todolist import views\nfrom django.urls import path\n\nurlpatterns = [\n\n path('',views.todolist,name=\"todolist\"),\n path('contact/',views.contact,name=\"contact_us\"),\n path('delete/',views.delete_task,name=\"delete_task\"),\n path('edit/',views.edit_task,name=\"edit_task\"),\n path('completed/',views.completed_task,name=\"completed_task\"),\n path('pending/',views.pending_task,name=\"pending_task\")\n \n\n\n]\n","sub_path":"todolist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"646953866","text":"\"\"\"Tests for the System module\"\"\"\nfrom src.system import System\n\ndef test_system_init():\n success = True\n try:\n _ = System()\n except: # pylint: disable=bare-except\n success = False\n assert success, \"Failed to initialize System()\"\n\ndef test_system_data():\n success = True\n json = {}\n try:\n sys = System()\n sys.FillSystemInfo(json)\n for k, v in json.items():\n if isinstance(v, str) and str in (None, \"unknown\"):\n print(f\"Value [{v}] for '{k}' is not expected, expected str.\")\n success = False\n else:\n print(f\"{k}:{v}, type:{type(v)}\")\n except: # pylint: disable=bare-except\n success = False\n assert success, \"Failed to collect system info\"\n\ndef test_system_metrics():\n success = True\n json = {}\n try:\n sys = System()\n sys.FillSystemMetrics(json)\n for k, v in json.items():\n if isinstance(v, int) and v < 0:\n print(f\"Value [{v}] for '{k}' is not expected, expected int.\")\n success = False\n elif isinstance(v, float) and v == 0.0:\n print(f\"Value [{v}] for '{k}' is not expected, expected float.\")\n success = False\n else:\n print(f\"{k}:{v}, type:{type(v)}\")\n except: # pylint: disable=bare-except\n success = False\n assert success, \"Failed to collect system metrics\"\n","sub_path":"tests/test_system.py","file_name":"test_system.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"40361024","text":"#-*- coding: utf-8 -*-\nfrom transformers import MBartForConditionalGeneration, MBart50Tokenizer, MBart50TokenizerFast\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom transformers import (\n AutoTokenizer,\n EvalPrediction,\n TrainingArguments,\n AutoModelForQuestionAnswering,\n default_data_collator,\n)\nfrom datasets import load_dataset, load_metric, DatasetDict\nfrom tqdm import tqdm\nimport math\n\n# def load_dataset(path)\n# copied = Dataset.load_from_disk('data/copied.json/')\n\ndef translate(origin_examples, train_examples=None, src_lang =\"ko_KR\", target_lang=['en_XX',],output_name='translated') :\n if not train_examples:\n train_examples = deepcopy(origin_examples)\n \n check_i = math.floor(len(train_examples)/len(origin_examples))-1\n check_j = math.floor(len(train_examples)%len(origin_examples))\n checkpoint = 500\n\n print(f'start translate: {target_lang[check_i:]}, checkpoint {check_j}')\n\n model = MBartForConditionalGeneration.from_pretrained(\"facebook/mbart-large-50-many-to-many-mmt\")\n tokenizer = AutoTokenizer.from_pretrained(\"facebook/mbart-large-50-many-to-many-mmt\")\n\n for target in target_lang[check_i:] :\n translate_examples = deepcopy(origin_examples)\n for trans_data in tqdm(origin_examples.select(range(check_j, len(origin_examples)))) :\n # kor -> target lang\n tokenizer.src_lang = src_lang\n encoded_ko = tokenizer(trans_data['question'], return_tensors=\"pt\")\n generated_tokens = model.generate(**encoded_ko, forced_bos_token_id=tokenizer.lang_code_to_id[target])\n tar_sent = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)\n\n # target -> korean\n tokenizer.src_lang = target\n encoded_tar = tokenizer(tar_sent, return_tensors=\"pt\")\n generated_tokens = model.generate(**encoded_tar, forced_bos_token_id=tokenizer.lang_code_to_id[src_lang])\n trans_data['question'] = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)[0]\n train_examples = train_examples.add_item(trans_data)\n\n if (len(train_examples)/len(origin_examples)) % checkpoint == 0:\n print(f'save checkpoint: {len(train_examples)}')\n train_examples.save_to_disk(f\"checkpoint/{output_name}-{'-'.join(target_lang)}\")\n\n check_j = 0\n\n now = datetime.now()\n now_str = f'{now.day:02}{now.hour:02}{now.minute:02}'\n train_examples.save_to_disk(f\"checkpoint/{output_name}-{'-'.join(target_lang)}-{now_str}\")\n print('end translate')\n\n return train_examples","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"157002910","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass LeNet(nn.Module): # ! 定义一个类,继承于nn.Module;并实现两个方法:初始化、前向传播\n def __init__(self): # ^ 初始化方法\n super(LeNet, self).__init__() # 多继承都要用super函数\n self.conv1 = nn.Conv2d(3, 16, 5) \n # ~ 使用nn.Conv2d定义卷积层: 传入的参数分别为 in_channel,out_channel(等于卷积核的个数),kernel_size, stride=1, padding =0, \n self.pool1 = nn.MaxPool2d(2, 2) # ~ 使用nn.MaxPool2d:kernel_size, stride\n self.conv2 = nn.Conv2d(16, 32, 5) # 输入的深度和上一层的输出一样16,使用32个5*5的卷积核\n self.pool2 = nn.MaxPool2d(2, 2)\n self.fc1 = nn.Linear(32*5*5, 120) # ~ 使用nn.Linear:in_channel,out_channel\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10) # 最后的输出要根据类别进行修改\n\n def forward(self, x): # ^ 定义正向传播的过程\n x = F.relu(self.conv1(x)) # input(3, 32, 32) output(16, 28, 28),有16个卷积核所以输出的channel是16; 计算(32-5+2*0)/1+1=28\n x = self.pool1(x) # output(16, 14, 14),channel深度不变,w和h各缩小一半\n x = F.relu(self.conv2(x)) # output(32, 10, 10); (14-5+2*0)/1+1=10\n x = self.pool2(x) # output(32, 5, 5)\n x = x.view(-1, 32*5*5) # output(32*5*5) # ! .view展开\n x = F.relu(self.fc1(x)) # output(120)\n x = F.relu(self.fc2(x)) # output(84)\n x = self.fc3(x) # output(10) # 内部已经实现了softmax(softmax转变为概率)\n return x\n\n\n\nimport torch\n\nif __name__ == '__main__':\n input1 = torch.rand([32,3,32,32]) # ! tensor的维度都是 batch, channel, H, W\n model = LeNet() # ^ 开始实例化模型\n print(model)\n output = model(input1) \n","sub_path":"pytorch_classification/Test1_official_demo/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"363451365","text":"import discord\nfrom discord.ext import commands\n\nimport glob, os\n\nclass Essential(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n\n @commands.command()\n async def ping(self, ctx):\n '''\n Pong!\n '''\n await ctx.send(\"Pong!\")\n \n\n @commands.command()\n @commands.is_owner()\n async def cog(self, ctx, action, *, cog=None):\n '''\n Controll cogs of the bot.\n '''\n if action == \"load\" or action == \"start\":\n await self.load(ctx, cog)\n elif action == \"reload\":\n await self.reload(ctx, cog)\n elif action == \"unload\":\n await self.unload(ctx, cog)\n elif action == \"show\":\n try:\n await self.show(ctx, cog)\n except commands.errors.ExtensionNotFound as e:\n reply = await ctx.send(\"The cog specified was not found!\")\n print(e)\n await ctx.message.delete(delay=5)\n await reply.delete(delay=10)\n\n async def load(self, ctx, cog):\n '''\n Loads a cog\n '''\n try:\n self.bot.load_extension(f'bot.cogs.{cog}')\n await ctx.send(f\"⚙️ Successfully loaded {cog}\")\n\n except commands.errors.ExtensionAlreadyLoaded:\n reply = await ctx.send(f\"{cog} is already loaded!\")\n await ctx.message.delete(delay=5)\n await reply.delete(delay=10)\n\n except commands.errors.ExtensionNotFound:\n reply = await ctx.send(f\"Could not find {cog}\")\n await ctx.message.delete(delay=5)\n await reply.delete(delay=10)\n\n\n async def reload(self, ctx, cog):\n '''\n Reloads a cog\n '''\n try:\n self.bot.reload_extension(f'bot.cogs.{cog}')\n await ctx.send(f\"⚙️ Successfully reloaded {cog}\")\n\n except commands.errors.ExtensionNotFound:\n reply = await ctx.send(f\"Could not find {cog}\")\n await ctx.message.delete(delay=5)\n await reply.delete(delay=10)\n\n\n async def unload(self, ctx, cog):\n '''\n Unloads a cog\n '''\n try:\n self.bot.unload_extension(f'bot.cogs.{cog}')\n await ctx.send(f\"⚙️ Successfully unloaded {cog}\")\n\n except commands.errors.ExtensionNotLoaded:\n reply = await ctx.send(f\"{cog} is already unloaded!\")\n await ctx.message.delete(delay=5)\n await reply.delete(delay=10)\n\n except commands.errors.ExtensionNotFound:\n reply = await ctx.send(f\"Could not find {cog}\")\n await ctx.message.delete(delay=5)\n await reply.delete(delay=10)\n\n async def show(self, ctx, cog):\n '''\n Shows if a cog is running or all running cogs\n '''\n # All cogs\n if not cog or cog == \"all\":\n embed = discord.Embed(title=\"Running cogs\", description=\"-\", colour=0x02e8fb)\n running_cogs = self.bot.cogs\n all_cogs = self.bot.cog_names\n for cog in all_cogs:\n if cog in running_cogs:\n embed.add_field(name=cog, value=\"Running\", inline=True)\n else:\n embed.add_field(name=cog, value=\"Not running...\", inline=True)\n\n # Specific cog\n elif cog in [cog.split(\"\\\\\")[-1][:-3] for cog in glob.glob(os.path.abspath(os.path.sep.join([os.getcwd(), \"bot\", \"cogs\", \"*.py\"])))]:\n running_cogs = self.bot.cogs\n\n if cog in running_cogs:\n embed = discord.Embed(title=cog, description=\"Running\", colour=0x00ff00) \n else: \n embed = discord.Embed(title=cog, description=\"Not running...\", colour=0xff0000)\n \n # If no cog with that name was found\n else:\n raise commands.errors.ExtensionNotFound\n\n # This is outside of the if statement and will be run unless the function is returned earlier\n # or raises an error (which it will if no cog is found)\n embed.set_thumbnail(url=\"https://images.emojiterra.com/google/android-nougat/512px/2699.png\")\n await ctx.send(embed=embed)\n\n\n async def add(self, ctx, cog):\n '''\n Add new, unregistered cogs to the bot.\n '''\n pass\n\n\ndef setup(bot):\n bot.add_cog(Essential(bot))\n print(\"[COG] Essential was added to the bot.\")","sub_path":"bot/cogs/Essential.py","file_name":"Essential.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"388674097","text":"import random\nimport numpy as np\n\n\ndef get_raw_data(file_dir = r\"tang.npz\"):\n data = np.load(file_dir)\n data, word2idx, idx2word = data['data'], data['word2ix'].item(), data['ix2word'].item()\n #把每个整理成,的格式\n out_data = []\n for val in data:\n val = list(val)\n out_data.append(val)\n return out_data, word2idx, idx2word\n\nclass Poem_DataSet():\n def __init__(self):\n self.data, self.word2idx, self.idx2word = get_raw_data()\n self.len = len(self.data)\n\n def fetch_data(self, batch_size, mode=\"train\"):\n random.shuffle(self.data)\n cnt = 0\n out_X = []\n out_Y = []\n for k in range(len(self.data)):\n out_X.append(self.data[k][0 : -1])\n out_Y.append(self.data[k][1 : len(self.data[k])])\n cnt += 1\n if cnt == batch_size:\n cnt = 0\n yield out_X, out_Y\n out_X = []\n out_Y = []\n\nclass Seq_Dataset():\n def __init__(self, self_embedding = None):\n self.rawdata, self.word2idx, self.idx2word = get_raw_data()\n self.len = len(self.rawdata)\n start_sign = self.word2idx[\"\"]\n break_sign = [self.word2idx[\",\"], self.word2idx[\"。\"], self.word2idx[\"\"]]\n self.data = []\n self.embedding = self_embedding\n #f = open(\"data.txt\", \"w\", encoding=\"utf8\")\n for poem in self.rawdata:\n temp_data = []\n pos = poem.index(start_sign)\n t1 = pos\n for move in range(pos+1, len(poem)):\n if poem[move] in break_sign and move - t1 >= 3:\n temp_data.append(poem[t1+1 : move])\n t1 = move\n for seq_num in range(len(temp_data) - 1):\n if len(temp_data[seq_num]) != 5 or len(temp_data[seq_num + 1]) != 5:\n break\n #out_data = []\n #for a in temp_data[seq_num]:\n # out_data.append(self.idx2word[a])\n # out_data.append(\" \")\n #f.writelines(out_data)\n #f.write(\"\\n\")\n self.data.append([temp_data[seq_num], temp_data[seq_num + 1]])\n '''out_data = []\n try:\n for a in temp_data[-1]:\n out_data.append(self.idx2word[a])\n out_data.append(\" \")\n f.writelines(out_data)\n f.write(\"\\n\")\n except:\n print(temp_data)'''\n\n #f.close()\n\n def fetch_data(self, batch_size, self_embedding=None):\n random.shuffle(self.data)\n cnt = 0\n out_X = []\n out_Y = []\n for k in range(len(self.data)):\n out_X.append(self.data[k][0])\n out_Y.append(self.data[k][1])\n cnt += 1\n if cnt == batch_size:\n cnt = 0\n if self_embedding == None:\n yield out_X, out_Y\n else:\n yield self.embeded(out_X, self_embedding), self.embeded(out_Y, self_embedding)\n out_X = []\n out_Y = []\n\n def embeded(self, x, self_embedding):\n len_x = len(x)\n len_batch = len(x[0]) \n out = []\n for batch in range(len_x):\n out.append([])\n for idx in range(len_batch):\n try: \n out[-1].append(self_embedding[self.idx2word[x[batch][idx]]])\n except:\n out[-1].append(np.random.rand(128))\n return out\n\nif __name__ == \"__main__\":\n '''\n DS = Poem_DataSet()\n for idx, (X,Y) in enumerate(DS.fetch_data(batch_size=1)):\n print(X)\n print(Y)\n break\n data, word2idx, idx2word = get_raw_data()\n sum = 0\n calc_word = {}\n for poem in data:\n for word in poem:\n if word == 8292:\n continue\n sum += 1\n if word not in calc_word.keys():\n calc_word[word] = 0\n calc_word[word] += 1\n\n sorted_word = sorted(calc_word.items(), key = lambda x: x[1], reverse=True)\n cnt = 0\n for a in range(len(sorted_word)):\n cnt += sorted_word[a][1]\n if cnt >= 0.99 * sum:\n print(a)\n break\n print(idx2word[sorted_word[a][0]], sorted_word[a][1])\n '''\n gg = Seq_Dataset()\n for idx, val in enumerate(gg.fetch_data(batch_size=1)):\n print(val[0])\n print(val[1])\n break\n","sub_path":"Poem_Writing/DataSet.py","file_name":"DataSet.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"208136498","text":"from django.shortcuts import render, HttpResponse\n\nfrom .forms import *\nfrom .models import *\nfrom .update import *\n# Create your views here.\n\n\n\ndef add_rss(request):\n\n form_add_rss = add_rss_form(request.POST or None)\n\n if form_add_rss.is_valid():\n form_add_rss.save()\n return render(request, \"add_rss.html\", locals())\n\ndef update_rss(request):\n print(request.GET.get(\"token\",\"pas de token\"))\n if request.GET.get(\"token\",\"pas de token\") == '0Y.h8DwNExvvwpiivn':\n for i in Rss_a_suivre.objects.values('lien') : \n print(i['lien'])\n recup(i['lien'])\n return HttpResponse(\"update_rss\")\n else:\n return HttpResponse(\"wrong token\")\n\ndef lecture(request):\n titre = \"Lecture\"\n star= request.GET.get(\"id_star\", None)\n unstar= request.GET.get(\"id_unstar\", None)\n lu = request.GET.get(\"id_lu\", None)\n\n if star != None:\n obj = Articles.objects.get(lien = star)\n obj.starred = True\n obj.save()\n\n if unstar != None:\n obj = Articles.objects.get(lien = unstar)\n obj.starred = False\n obj.save()\n \n if lu != None:\n obj = Articles.objects.get(lien = lu)\n obj.lu = True\n obj.save()\n\n articles = Articles.objects.filter(lu = False).order_by('origine', 'pubDate')\n return render(request, 'lecture.html', locals())\n\ndef favoris(request):\n titre = \"Favoris\"\n articles = Articles.objects.filter(starred = True).order_by('origine', 'pubDate')\n return render(request, 'lecture.html', locals())","sub_path":"rss/reader/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"389154755","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : login.py\n# @Author: wangyalei\n# @Date : 18/8/9\n# @Desc :\n\nfrom pyqrcode import QRCode\nfrom tools import utils\nfrom contact import update_local_chatrooms,update_local_friends\nfrom bean.returnvalues import ReturnValue\nfrom bean import templates\n\nimport logging,config,io,re,time,xml.dom.minidom,random,json\n\nlogger = logging.getLogger(config.TAG_WECHAT)\n\ndef push_login(core):\n cookiesDict = core.s.cookies.get_dict()\n logger.info('push_login cookiesDict:')\n logger.info(cookiesDict)\n if 'wxuin' in cookiesDict:\n url = '%s/cgi-bin/mmwebwx-bin/webwxpushloginurl?uin=%s' % (\n config.BASE_URL, cookiesDict['wxuin'])\n logger.info(\"push_login url: \" + url)\n headers = {'User-Agent': config.USER_AGENT}\n r = core.s.get(url, headers=headers).json()\n logger.info(\"push_login result: \")\n logger.info(r)\n if 'uuid' in r and r.get('ret') in (0, '0'):\n core.uuid = r['uuid']\n logger.info(\"push_login core.uuid: \" + core.uuid)\n return r['uuid']\n return False\n\ndef get_QRuuid(core):\n url = '%s/jslogin' % config.BASE_URL\n logger.info('get_QRuuid url: ' + url)\n params = {\n 'appid': 'wx782c26e4c19acffb',\n 'fun': 'new', }\n headers = {'User-Agent': config.USER_AGENT}\n r = core.s.get(url, params=params, headers=headers)\n logger.info('get_QRuuid r: ')\n logger.info(r)\n logger.info('get_QRuuid r.text:')\n logger.info(r.text)\n regx = r'window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";'\n data = re.search(regx, r.text)\n if data and data.group(1) == '200':\n core.uuid = data.group(2)\n logger.info('get_QRuuid self.uuid: ' + core.uuid)\n return core.uuid\n\n\ndef get_QR(core, uuid=None, enableCmdQR=False, picDir=None, qrCallback=None):\n uuid = uuid or core.uuid\n picDir = picDir or config.DEFAULT_QR\n qrStorage = io.BytesIO()\n logger.info(\"get_QR qrStorage:\")\n logger.info(qrStorage)\n url = 'https://login.weixin.qq.com/l/' + uuid\n logger.info(\"get_QR url: \" + url)\n logger.info(\"get_QR picDir: \" + picDir)\n qrCode = QRCode('https://login.weixin.qq.com/l/' + uuid)\n qrCode.png(qrStorage, scale=10)\n if hasattr(qrCallback, '__call__'):\n qrCallback(uuid=uuid, status='0', qrcode=qrStorage.getvalue())\n else:\n with open(picDir, 'wb') as f:\n f.write(qrStorage.getvalue())\n if enableCmdQR:\n utils.print_cmd_qr(qrCode.text(1), enableCmdQR=enableCmdQR)\n else:\n utils.print_qr(picDir)\n return qrStorage\n\n'''\n检查是否扫码登录\n'''\ndef check_login(core, uuid=None):\n uuid = uuid or core.uuid\n url = '%s/cgi-bin/mmwebwx-bin/login' % config.BASE_URL\n logger.info('check_login url: ' + url)\n localTime = int(time.time())\n params = 'loginicon=true&uuid=%s&tip=1&r=%s&_=%s' % (\n uuid, int(-localTime / 1579), localTime)\n logger.info('check_login params: ' + params)\n headers = {'User-Agent': config.USER_AGENT}\n r = core.s.get(url, params=params, headers=headers)\n regx = r'window.code=(\\d+)'\n data = re.search(regx, r.text)\n logger.info('check_login r.text: ' + r.text)\n if data and data.group(1) == '200':\n if process_login_info(core, r.text):\n return '200'\n else:\n return '400'\n elif data:\n return data.group(1)\n else:\n return '400'\n\n'''\n1.根据redirect_uri匹配fileUrl,syncUrl\n2.根据edirect_uri获取skey,wxsid,wxuin,pass_ticket\n'''\ndef process_login_info(core, loginContent):\n regx = r'window.redirect_uri=\"(\\S+)\";'\n core.loginInfo['url'] = re.search(regx, loginContent).group(1)\n headers = {'User-Agent': config.USER_AGENT}\n logger.info('process_login_info url: ' + core.loginInfo['url'])\n r = core.s.get(core.loginInfo['url'], headers=headers, allow_redirects=False)\n core.loginInfo['url'] = core.loginInfo['url'][:core.loginInfo['url'].rfind('/')]\n logger.info('process_login_info url------: ' + core.loginInfo['url'])\n for indexUrl, detailedUrl in (\n (\"wx2.qq.com\", (\"file.wx2.qq.com\", \"webpush.wx2.qq.com\")),\n (\"wx8.qq.com\", (\"file.wx8.qq.com\", \"webpush.wx8.qq.com\")),\n (\"qq.com\", (\"file.wx.qq.com\", \"webpush.wx.qq.com\")),\n (\"web2.wechat.com\", (\"file.web2.wechat.com\", \"webpush.web2.wechat.com\")),\n (\"wechat.com\", (\"file.web.wechat.com\", \"webpush.web.wechat.com\"))):\n fileUrl, syncUrl = ['https://%s/cgi-bin/mmwebwx-bin' % url for url in detailedUrl]\n logger.info('process_login_info fileUrl: ' + fileUrl)\n logger.info('process_login_info syncUrl: ' + syncUrl)\n logger.info('process_login_info -------------------------')\n if indexUrl in core.loginInfo['url']:\n core.loginInfo['fileUrl'], core.loginInfo['syncUrl'] = \\\n fileUrl, syncUrl\n break\n else:\n logger.info('process_login_info here url: ' + core.loginInfo['url'])\n core.loginInfo['fileUrl'] = core.loginInfo['syncUrl'] = core.loginInfo['url']\n core.loginInfo['deviceid'] = 'e' + repr(random.random())[2:17]\n core.loginInfo['logintime'] = int(time.time() * 1e3)\n core.loginInfo['BaseRequest'] = {}\n logger.info('process_login_info r.text:')\n logger.info(r.text)\n for node in xml.dom.minidom.parseString(r.text).documentElement.childNodes:\n if node.nodeName == 'skey':\n core.loginInfo['skey'] = core.loginInfo['BaseRequest']['Skey'] = node.childNodes[0].data\n elif node.nodeName == 'wxsid':\n core.loginInfo['wxsid'] = core.loginInfo['BaseRequest']['Sid'] = node.childNodes[0].data\n elif node.nodeName == 'wxuin':\n core.loginInfo['wxuin'] = core.loginInfo['BaseRequest']['Uin'] = node.childNodes[0].data\n elif node.nodeName == 'pass_ticket':\n core.loginInfo['pass_ticket'] = core.loginInfo['BaseRequest']['DeviceID'] = node.childNodes[0].data\n if not all([key in core.loginInfo for key in ('skey', 'wxsid', 'wxuin', 'pass_ticket')]):\n logger.error('Your wechat account may be LIMITED to log in WEB wechat, error info:\\n%s' % r.text)\n core.isLogging = False\n return False\n return True\n\n'''\n1.获取最近的联系人和公众号\n2.将好友和群的数据更新到本地\n'''\ndef web_init(core):\n url = '%s/webwxinit' % core.loginInfo['url']\n logger.info('web_init url: ' + url)\n params = {\n 'r': int(-time.time() / 1579),\n 'pass_ticket': core.loginInfo['pass_ticket'], }\n data = {'BaseRequest': core.loginInfo['BaseRequest'], }\n headers = {\n 'ContentType': 'application/json; charset=UTF-8',\n 'User-Agent': config.USER_AGENT, }\n r = core.s.post(url, params=params, data=json.dumps(data), headers=headers)\n logger.info('web_init r.content: ' + r.content)\n dic = json.loads(r.content.decode('utf-8', 'replace'))\n # deal with login info\n utils.emoji_formatter(dic['User'], 'NickName')\n core.loginInfo['InviteStartCount'] = int(dic['InviteStartCount'])\n core.loginInfo['User'] = templates.wrap_user_dict(utils.struct_friend_info(dic['User']))\n core.memberList.append(core.loginInfo['User'])\n core.loginInfo['SyncKey'] = dic['SyncKey']\n core.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val'])\n for item in dic['SyncKey']['List']])\n core.storageClass.userName = dic['User']['UserName']\n core.storageClass.nickName = dic['User']['NickName']\n logger.info('web_init userName: ' + core.storageClass.userName)\n logger.info('web_init nickName: ' + core.storageClass.nickName)\n # deal with contact list returned when init\n contactList = dic.get('ContactList', [])\n chatroomList, otherList = [], []\n for m in contactList:\n if m['Sex'] != 0:\n otherList.append(m)\n elif '@@' in m['UserName']:\n m['MemberList'] = [] # don't let dirty info pollute the list\n chatroomList.append(m)\n elif '@' in m['UserName']:\n # mp will be dealt in update_local_friends as well\n otherList.append(m)\n if chatroomList:\n update_local_chatrooms(core, chatroomList)\n if otherList:\n update_local_friends(core, otherList)\n return dic\n\n\ndef show_mobile_login(core):\n url = '%s/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % (\n core.loginInfo['url'], core.loginInfo['pass_ticket'])\n logger.info('show_mobile_login url: ' + url)\n data = {\n 'BaseRequest': core.loginInfo['BaseRequest'],\n 'Code': 3,\n 'FromUserName': core.storageClass.userName,\n 'ToUserName': core.storageClass.userName,\n 'ClientMsgId': int(time.time()), }\n headers = {\n 'ContentType': 'application/json; charset=UTF-8',\n 'User-Agent': config.USER_AGENT, }\n r = core.s.post(url, data=json.dumps(data), headers=headers)\n logger.info(\"show_mobile_login r:\")\n logger.info(r)\n return ReturnValue(rawResponse=r)\n\n'''\n1.获取通信录信息\n2.更新到本地\n'''\ndef get_contact(core, update=False):\n if not update:\n return utils.contact_deep_copy(core, core.chatroomList)\n\n def _get_contact(seq=0):\n url = '%s/webwxgetcontact?r=%s&seq=%s&skey=%s' % (core.loginInfo['url'],\n int(time.time()), seq, core.loginInfo['skey'])\n logger.info('_get_contact url:')\n logger.info(url)\n headers = {\n 'ContentType': 'application/json; charset=UTF-8',\n 'User-Agent': config.USER_AGENT, }\n try:\n r = core.s.get(url, headers=headers)\n except:\n logger.info('Failed to fetch contact, that may because of the amount of your chatrooms')\n # for chatroom in core.get_chatrooms():\n # core.update_chatroom(chatroom['UserName'], detailedMember=True)\n return 0, []\n contact_str = r.content.decode('utf-8', 'replace')\n logger.info('get_contact contact_str: ' + contact_str)\n j = json.loads(contact_str)\n return j.get('Seq', 0), j.get('MemberList')\n\n seq, memberList = 0, []\n while 1:\n seq, batchMemberList = _get_contact(seq)\n # append:将对象加到list, extend:将对象的内容添加到list\n memberList.extend(batchMemberList)\n if seq == 0:\n break\n chatroomList, otherList = [], []\n for m in memberList:\n if m['Sex'] != 0:\n otherList.append(m)\n elif '@@' in m['UserName']:\n chatroomList.append(m)\n elif '@' in m['UserName']:\n # mp will be dealt in update_local_friends as well\n otherList.append(m)\n if chatroomList:\n update_local_chatrooms(core, chatroomList)\n if otherList:\n update_local_friends(core, otherList)\n return utils.contact_deep_copy(core, chatroomList)\n\n\n\n\n\n","sub_path":"wechat/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":10943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"541772575","text":"import os\nimport csv\nimport cv2\nimport numpy as np\n\nbrand = \"logitech\"\nmode = \"image\"\nhome_base = os.environ['HOME']\nmedia_base = \"/media/nvidia/6139-38632\"\ntraining_datapath = media_base + \"/csdv/data/input/\" + \"racetrack/\" + mode + \"/\" \n\ndef get_image(basepath, filepath):\n # read in images from center, left and right cameras\n source_path = filepath\n # an easy way to update the path is to split the path on it's\n # slashes and then extract the final token, which is the filename\n filename = source_path.split('/')[-1]\n # then I can add that filename to the end of the path to the IMG\n # directory here on the AWS instance\n img_path_on_fs = basepath + filename\n # once I have the current path, I can use opencv to load the image\n image = cv2.imread(img_path_on_fs)\n return image\n\n# read and store multiple cameras and steering angles from driving_log.csv\n# all three camera images will be used to train the model\nimages = []\nsteering_measurements = []\nwith open(training_datapath + \"driving_log.csv\", \"r\") as csvfile:\n reader = csv.reader(csvfile)\n # for each line, extract the path to the camera image\n # but remember that path was recorded on the local machine\n # since I am on the AWS instance\n for row in reader:\n steering_center = float(row[3]) # row, column 3 = steering center angle\n \n # create adjusted steering measurements for the side camera images\n correction = 0.2 # parameter to tune\n # steering left of center, recover back to center\n steering_left = steering_center - correction\n # steering right of center, recover back to center\n steering_right = steering_center + correction\n\n # read in images from center, left and right cameras\n basepath = training_datapath + brand + \"/\"\n image_center = get_image(basepath, row[0])\n image_left = get_image(basepath, row[1])\n image_right = get_image(basepath, row[2])\n\n # insert multiple elements into list\n images.extend([image_center, image_left, image_right])\n steering_measurements.extend([steering_center, steering_left, steering_right])\n \n# Data Augmentation.\n# There's Problem where the model sometimes pulls too hard to the right. \n# This does/nt make sense since the training track is a loop and the car \n# drives counterclockwise. So, most of the time the model should learn to steer \n# to the left. Then in autonomous mode, the model does steer to the left\n# even in situations when staying straight might be best. One approach to mitigate\n# this problem is data augmentation. There are many ways to augment data to expand\n# the training set and help the model generalize better. I could change the brightness\n# on the images or I could shift them horizontally or vertically. In this case,\n# I'll keep things simple and flip the images horizontally like a mirror, then invert\n# the steering angles and I should end up with a balanced dataset that teaches the\n# car to steer clockwise as well as counterclockwise. Just like using side camera data,\n# using data augmentation carries 2 benefits: 1. we have more data to use for training \n# the network and 2. the data we use for the training the network is more comprehensive.\naugmented_images, augmented_steering_measurements = [], []\nfor image, measurement in zip(images, steering_measurements):\n augmented_images.append(image)\n augmented_steering_measurements.append(measurement)\n augmented_images.append(cv2.flip(image,1)) # flip img horizontally\n augmented_steering_measurements.append(measurement*-1.0) # invert steering\n\n# now that I've loaded the images and steering measurements,\n# I am going to convert them to numpy arrays since that is the format\n# keras requires\nX_train = np.array(augmented_images)\ny_train = np.array(augmented_steering_measurements)\n\n# next I am going to build the most basic network possible just to make sure everything is working\n# this single output node will predict my steering angle, which makes this\n# a regression network, so I don't have to apply an activation function\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Activation, Lambda, Cropping2D\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.pooling import MaxPooling2D\n\n# Building Net Architecture based on Nvidia Self Driving Car Neural Network \nmodel = Sequential()\n# Layer 1: Normalization\n# Data preprocessing to normalize input images\nmodel.add(Lambda(lambda x: (x/255.0) - 0.5, input_shape = (180, 320, 3)))\n# Crop2D layer used to remove top 40 pixels, bottom 30 pixels of image\nmodel.add(Cropping2D(cropping = ((40,30), (0,0))))\n# Layer 2: Convolutional. 24 filters, 5 kernel, 5 stride, relu activation function\nmodel.add(Conv2D(24,5,5, subsample = (2,2), activation = \"relu\"))\n# Layer 3: Convolutional. 36 filters\nmodel.add(Conv2D(36,5,5, subsample = (2,2), activation = \"relu\"))\n# Layer 4: Convolutional. 48 filters\nmodel.add(Conv2D(48,5,5, subsample = (2,2), activation = \"relu\"))\n# Layer 5: Convolutional. 64 filters\nmodel.add(Conv2D(64,5,5, activation = \"relu\"))\n# Layer 6: Convolutional. 64 filters\nmodel.add(Conv2D(64,5,5, activation = \"relu\"))\n### Flatten output into a vector\nmodel.add(Flatten())\n# Layer 7: Fully Connected\nmodel.add(Dense(100))\n# Layer 8: Fully Connected\nmodel.add(Dense(50))\n# Layer 9: Fully Connected\nmodel.add(Dense(10))\n# Layer 10: Fully Connected\nmodel.add(Dense(1))\n\n# with the network constructed, I will compile the model\n# for the loss function, I will use mean squared error (mse)\n# What I want to do is minimize the error between the steering\n# measurement that the network predicts and the ground truth steering\n# measurement. mse is a good loss function for this\nmodel.compile(loss='mse', optimizer='adam')\n\n# once the model is compiled, I will train it with the feature and label\n# arrays I just built. I'll also shuffle the data and split off 20% of\n# the data to use for a validation set. I set epochs to 7 since I saw\n# with 10 epochs (keras default) that validation loss decreases with just 7,\n# then increases. Thus, at 10 epochs, I may have been overfitting training data.\n# Hence, at 7 epochs, the validation loss decreases for almost all the epochs.\n# Change 7 epochs to 5 since we are training over more powerful neural net architecture\n# update with data augmentation: training is going fine and is training on twice as\n# many images as before. That makes sense since I copied each image and then flipped\n# the copy\nmodel.fit(X_train, y_train, validation_split=0.2, shuffle=True, epochs=7)\n\n# finally I'll save the trained model, so later I can download it onto my \n# local machine and see how well it works for driving the simulator\nmodel.save('model.h5')\n","sub_path":"cdh/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"70065519","text":"#!/usr/bin/env python3\n\"\"\"\nShows how to toss a capsule to a container.\n\"\"\"\nfrom mujoco_py import load_model_from_path, MjSim, MjViewer\nimport os\nimport numpy as np\n\nnp.set_printoptions(precision=3)\ndef print_state(state):\n time, qpos, qvel, act, udd_state = state.time, state.qpos, state.qvel, state.act, state.udd_state\n print(\"t: %5.3f\" %time)\n print(\"qpos: \", qpos)\n print(\"qvel: \", qvel)\n print(\"tosser (slide,hinge): \", qpos[:2])\n print(\"object (z,y,pitch): \", qpos[-3:])\n\n\nmodel = load_model_from_path(\"../../xmls/tosser.xml\")\nsim = MjSim(model)\n\nviewer = MjViewer(sim)\n\n\nsim_state = sim.get_state()\n\nwhile True:\n sim.set_state(sim_state)\n\n for i in range(1000):\n state = sim.get_state()\n # time, qpos, qvel, act, udd_state = state.time, state.qpos, state.qvel, state.act, state.udd_state\n # print(time, qpos, qvel)\n print_state(state)\n if i < 150:\n sim.data.ctrl[0] = -0.0\n sim.data.ctrl[1] = -0.0\n else:\n sim.data.ctrl[0] = -1.0\n sim.data.ctrl[1] = -1.0\n sim.step()\n viewer.render()\n\n if os.getenv('TESTING') is not None:\n break\n","sub_path":"examples/custom_examples/tosser.py","file_name":"tosser.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"290517756","text":"\"\"\"empty message\n\nRevision ID: e3c5d7ba9169\nRevises: 1a02ad1f5854\nCreate Date: 2019-11-29 12:54:45.225294\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e3c5d7ba9169'\ndown_revision = '1a02ad1f5854'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('zabbix_host',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('host', sa.String(length=255), nullable=True),\n sa.Column('name', sa.String(length=255), nullable=True),\n sa.Column('hostid', sa.String(length=255), nullable=True),\n sa.Column('available', sa.Integer(), nullable=True),\n sa.Column('groups', sa.String(length=255), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('zabbix_host')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/e3c5d7ba9169_.py","file_name":"e3c5d7ba9169_.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"263335529","text":"def anagram(a,b):\n a1=a.lower() #перевод в нижний регистр\n b1=b.lower()\n if (a1==b1):\n print(\"Введено одно и то же слово: \", a)\n elif (sorted(a1)==sorted(b1)): #сортировка букв в слове по алфавиту\n print (\"\\\"\", a1, \"\\\" и \", \"\\\"\", b1, \" \\\" являются анаграммами\")\n\nanagram(\"кот\", \"ток\")\nanagram(\"ток\", \"ток\")\n","sub_path":"Anagram.py","file_name":"Anagram.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"261000172","text":"#!/usr/bin/env python\nimport gi; gi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk\nfrom functools import reduce\nimport sys, os, re\n\n\n\n\nColors = {\n\t'AB' : { 'Name' : 'Accent Back' },\n\t'AF' : { 'Name' : 'Accent Fore' },\n\t'NB' : { 'Name' : 'Normal Back' },\n\t'NF' : { 'Name' : 'Normal Fore' },\n}\n\n\n\n\nDir = os.path.dirname(os.path.realpath(sys.argv[0]))\n\n\n\n\nSrc = []\nCur = []\n\n\n\n\nwith open(Dir + '/themerc.in') as f: Src = f.readlines()\nwith open(Dir + '/themerc') as f: Cur = f.readlines()\n\n\n\n\ndef LoadColors (ls, keys):\n\tfor l in ls:\n\t\tif l.startswith('#'):\n\t\t\tss = l.strip().split(' ')\n\t\t\tfor k in keys:\n\t\t\t\tColors[ss[0].lstrip('#')][k] = ss[len(ss) - 1]\n\n\n\n\nLoadColors(Src, ('Color', 'Initial', 'Default'))\nLoadColors(Cur, ('Color', 'Initial'))\n\n\n\n\ndef Rgb8 (c):\n\treturn [int(c[i:i+2], 16) for i in (1, 3, 5)]\n\ndef Hex8FromRgb8 (c):\n\treturn '#%02x%02x%02x' % tuple(c)\n\ndef Hex8FromRgb (c):\n\treturn Hex8FromRgb8 (\n\t\tmap(lambda f: int(f * 0xFF), c)\n\t)\n\n\n\n\ndef Parse (s):\n\t\n\tdef pone (c):\n\t\tif (c.startswith('#')): return Rgb8(c)\n\t\telse: return Rgb8(Colors[c]['Color'])\n\t\n\tdef addc (a, b):\n\t\treturn map(lambda c0, c1: c0 + c1, a, b)\n\t\n\tdef divc (c, d):\n\t\treturn map(lambda c: c / d, c)\n\t\n\tcs = [pone(c) for c in s.split(' ')];\n\treturn Hex8FromRgb8(divc(reduce(addc, cs), len(cs)))\n\n\ndef Go ():\n\t\n\tout = []\n\t\n\tfor ck in Colors:\n\t\tout.append('#' + ck + ' ' + Colors[ck]['Color'])\n\t\n\tfor l in Src:\n\t\t\n\t\tl = l.strip()\n\t\t\n\t\tif not len(l): continue\n\t\tif l.startswith('#'): continue\n\t\telif '{' in l:\n\t\t\ts = re.split('{|}', l)\n\t\t\tout.append(s[0] + Parse(s[1]))\n\t\telse: out.append(l)\n\t\n\tout = '\\n'.join(out)\n\twith open(Dir + '/themerc', 'w') as of: of.write(out)\n\tos.system('openbox --reconfigure')\n\n\ndef Reveal ():\n\tfor c in Colors.values():\n\t\tc['Button'].set_color(Gdk.color_parse(c['Color']))\n\n\ndef Reset (key):\n\tfor c in Colors.values():\n\t\tc['Color'] = c[key]\n\tReveal()\n\ndef FromGtk ():\n\t\n\tm = Gtk.Menu()\n\ti = Gtk.MenuItem()\n\tw = Gtk.Window()\n\tm.add(i)\n\t\n\tms = i.get_style_context()\n\tws = w.get_style_context()\n\t\n\tdef ccc (key, gc):\n\t\tColors[key]['Color'] = Hex8FromRgb([gc.red, gc.green, gc.blue])\n\t\n\tccc('AB', ms.get_background_color(Gtk.StateFlags.PRELIGHT))\n\tccc('AF', ms.get_color(Gtk.StateFlags.PRELIGHT))\n\tccc('NB', ws.get_background_color(Gtk.StateFlags.NORMAL))\n\tccc('NF', ws.get_color(Gtk.StateFlags.NORMAL))\n\t\n\tReveal()\n\n\n\n\nW = Gtk.Window(title = \"Lean\")\nW.connect(\"destroy\", lambda e: Gtk.main_quit())\n\t\t\nW.set_position(Gtk.WindowPosition.CENTER)\nW.set_resizable(False)\nW.set_border_width(8)\n\nCList = Gtk.Grid()\nCList.set_row_spacing(4)\nCList.set_column_spacing(4)\nCList.Rows = 0\n\ndef SetC (ck, gc):\n\tColors[ck]['Color'] = Hex8FromRgb(gc.to_floats())\n\nfor ck in sorted(Colors):\n\t\n\tc = Colors[ck]\n\t\n\tclbl = Gtk.Label(c['Name'] + ':')\n\tcbtn = c['Button'] = Gtk.ColorButton(color = Gdk.color_parse(c['Color']))\n\tcbtn.connect('color-set', lambda b, k: SetC(k, b.get_color()), ck)\n\t\n\tCList.attach(clbl, 0, CList.Rows, 1, 1)\n\tCList.attach(cbtn, 1, CList.Rows, 1, 1)\n\t\n\tCList.Rows = CList.Rows + 1;\n\nDefBtn = Gtk.Button(\"Default\")\nRevertBtn = Gtk.Button(\"Revert\")\nGtkBtn = Gtk.Button(\"From GTK\")\nGoBtn = Gtk.Button(\"Apply\")\n\nDefBtn.connect('clicked', lambda e: Reset('Default'))\nRevertBtn.connect('clicked', lambda e: Reset('Initial'))\nGtkBtn.connect('clicked', lambda e: FromGtk())\nGoBtn.connect('clicked', lambda e: Go())\n\nRootBox = Gtk.VBox(spacing = 8)\nRootBox.pack_start(DefBtn, True, True, 0)\nRootBox.pack_start(GtkBtn, True, True, 0)\nRootBox.pack_start(CList, True, True, 0)\nRootBox.pack_start(RevertBtn, True, True, 0)\nRootBox.pack_start(GoBtn, True, True, 0)\nW.add(RootBox)\n\t\t\nW.show_all()\nGtk.main()\n","sub_path":"Lean/openbox-3/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"281200486","text":"L = int(input())\nB = [int(input()) for _ in range(L)]\n\nA = []\nfor b in B:\n if b % 2:\n A.append(1)\n else:\n A.append(0 if b == 0 else 2)\n\ndpLBack = [10**10] * (L + 1)\ndpLBack[0] = 0\ncnt = 0\nfor i, a in enumerate(A, start=1):\n cnt += B[i - 1]\n dpLBack[i] = min(dpLBack[i - 1] + 2 - a, cnt)\n\ndpL = [10**10] * (L + 1)\ndpL[0] = 0\ncnt = 0\nfor i, a in enumerate(A, start=1):\n cnt += B[i - 1]\n dpL[i] = min(dpL[i - 1] + (a != 1), dpLBack[i - 1] + (a == 0), cnt)\n\ndpRBack = [10**10] * (L + 1)\ndpRBack[0] = 0\ncnt = 0\nfor i, a in enumerate(A[:: -1], start=1):\n cnt += B[-i]\n dpRBack[i] = min(dpRBack[i - 1] + 2 - a, cnt)\n\ndpR = [10**10] * (L + 1)\ndpR[0] = 0\ncnt = 0\nfor i, a in enumerate(A[:: -1], start=1):\n cnt += B[-i]\n dpR[i] = min(dpR[i - 1] + (a != 1), dpRBack[i - 1] + (a == 0), cnt)\n\ndpR = dpR[:: -1]\ndpRBack = dpRBack[:: -1]\n\nans = min(dpL[L], dpR[0])\nfor mid in range(L + 1):\n ans = min(ans, dpL[mid] + dpRBack[mid], dpLBack[mid] + dpR[mid], dpLBack[mid] + dpRBack[mid])\n\nprint(ans)\n","sub_path":"AtCoder/other/みんなのプロコン_2019/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"463184379","text":"\"\"\"\r\nFormulas for density calculation.\r\n\"\"\"\r\nfrom math import log10, log\r\nfrom colormath.density_standards import *\r\n\r\ndef ansi_density(color, std_array):\r\n \"\"\"\r\n Calculates density for the given SpectralColor using the spectral weighting\r\n function provided. For example, ANSI_STATUS_T_RED. These may be found in\r\n density_standards.py.\r\n \r\n color: (SpectralColor) The SpectralColor object to calculate density for.\r\n std_array: (ndarray) NumPy array of filter of choice from density_standards.py.\r\n \"\"\" \r\n # Load the spec_XXXnm attributes into a Numpy array.\r\n sample = color.get_numpy_array()\r\n # Matrix multiplication\r\n intermediate = sample * std_array\r\n \r\n # Sum the products.\r\n numerator = intermediate.sum()\r\n # This is the denominator in the density equation.\r\n sum_of_standard_wavelengths = std_array.sum()\r\n \r\n # This is the top level of the density formula.\r\n return -1.0 * log10(numerator / sum_of_standard_wavelengths)\r\n\r\ndef auto_density(color):\r\n \"\"\"\r\n Given a SpectralColor, automatically choose the correct ANSIT filter. Returns\r\n a tuple with a string representation of the filter the calculated density.\r\n \"\"\"\r\n color_array = color.get_numpy_array()\r\n blue_density = ansi_density(color, ANSI_STATUS_T_BLUE)\r\n green_density = ansi_density(color, ANSI_STATUS_T_GREEN)\r\n red_density = ansi_density(color, ANSI_STATUS_T_RED)\r\n \r\n densities = [blue_density, green_density, red_density]\r\n min_density = min(densities)\r\n max_density = max(densities)\r\n density_range = max_density - min_density\r\n #print \"DIFF\", density_range\r\n \r\n # See comments in density_standards.py for VISUAL_DENSITY_THRESH to\r\n # understand what this is doing.\r\n if density_range <= VISUAL_DENSITY_THRESH:\r\n #print \"visual\"\r\n return ansi_density(color, ISO_VISUAL)\r\n elif blue_density > green_density and blue_density > red_density:\r\n #print \"blue\"\r\n return blue_density\r\n elif green_density > blue_density and green_density > red_density:\r\n #print \"green\"\r\n return green_density\r\n else:\r\n #print \"red\"\r\n return red_density","sub_path":"Hue Lights.indigoPlugin/Contents/Server Plugin/colormath/density.py","file_name":"density.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"312250848","text":"\"\"\"\nencoding=utf-8\n_author = youzipi\ndate = 17/11/21\n\"\"\"\n\"\"\"\nQ:\n题目描述\n我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?\n\"\"\"\n\"\"\"\nA:\n基本结构只有两种:\n1:\n————\n————\n2:\n|\n|\n\n=>\nf(n) = f(n-1)+f(n-2) # 斐波拉契数列的形式\n\nf(1) = 1\nf(2) = 2\n\n动态规划\n缩小问题规模\n数学归纳法\n分形\n\"\"\"\n\n\nclass Solution:\n def rectCover(self, number):\n if number == 0:\n return 0\n if number == 1:\n return 1\n elif number == 2:\n return 2\n else:\n a = 1\n b = 2\n for i in range(number - 2):\n print(i)\n a, b = b, a + b\n return b\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.rectCover(3))\n","sub_path":"python/rect_cover.py","file_name":"rect_cover.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"535436159","text":"import os\nfrom google.oauth2 import service_account\n# from DB_Manager import insert_intents_into_db\nfrom Similarity_engine import find_similar_intent\n\ncredentials_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')\ncredentials = service_account.Credentials.from_service_account_file(credentials_path)\nPROJECT_ID = os.getenv('GCLOUD_PROJECT')\n\nprint('Credendtials from environ: {}'.format(credentials))\n\n\ndef detect_intent_texts(project_id, session_id, texts, language_code):\n \"\"\"Returns the result of detect intent with texts as inputs.\n Using the same `session_id` between requests allows continuation\n of the conversation.\"\"\"\n import dialogflow_v2 as dialogflow\n session_client = dialogflow.SessionsClient(credentials=credentials)\n\n session = session_client.session_path(project_id, session_id)\n # print('Session path: {}\\n'.format(session))\n\n for text in texts:\n text_input = dialogflow.types.TextInput(\n text=text, language_code=language_code)\n\n query_input = dialogflow.types.QueryInput(text=text_input)\n\n response = session_client.detect_intent(\n session=session, query_input=query_input)\n\n query_text = response.query_result.query_text\n intent = response.query_result.intent.display_name\n confidence = response.query_result.intent_detection_confidence\n fulfillment = response.query_result.fulfillment_text\n parameters = response.query_result.parameters\n\n # print('=' * 40)\n # print('Query text: {}'.format(query_text))\n # print('Detected intent: {} (confidence: {})\\n'.format(intent, confidence))\n # print('Fulfillment text: {}\\n'.format(fulfillment))\n # print('Parameter Entity : {}'.format(parameters))\n\n if fulfillment == 'unknown':\n fulfillment = find_similar_intent([str(query_text)])\n # print('Fulfillment text (by SE): {}\\n'.format(fulfillment))\n\n # record = response.query_result\n # record = {\"Query Text\": query_text, \"Intent\": intent, \"Confidence\": confidence, \"Fulfillment\": fulfillment, \"Parameters\": parameters}\n # print(record)\n # insert_intents_into_db(record)\n return intent\n\n\n","sub_path":"UserSpecs2PseudoCode/PC_Interface/test_detect_intent.py","file_name":"test_detect_intent.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"447460167","text":"# syracuse.py\n# Recursive program to calculate the 3x+1 problem.\n#\n# Michael Kemp\n# 2013-10-29\n# I affirm that I have adhered to the Honor Code in this assignment.\n\ndef main() :\n\n\tn = eval(input(\"Please input a positive length value: \"))\n\n\tstarting_num = 1\n\n\twhile rec(starting_num) <= n :\n\t\tstarting_num = starting_num + 1\n\tprint(starting_num)\n\ndef rec(x) :\n\n\tif x == 1 :\n\t\treturn 1\n\n\telse :\n\t\tif x % 2 == 0 :\n\t\t\treturn 1 + rec(x // 2)\n\t\telse :\n\t\t\treturn 1 + rec(x * 3 + 1)\nmain()\n","sub_path":"lab08/syracuse.py","file_name":"syracuse.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"470796280","text":"from sklearn.model_selection import train_test_split\nimport pandas as pd, numpy as np \n\nif __name__ == \"__main__\":\n data_dir = \"./data/\"\n data_path = data_dir + \"final_dataset.csv\"\n\n # Read data\n df = pd.read_csv(data_path)\n\n # Split into train and test sets\n X_train, X_test, y_train, y_test = train_test_split(df.drop(columns=['user_id', 'great_customer_class']), df['great_customer_class'], test_size=0.2, random_state=0)\n \n # Save onto disk\n X_train.to_csv(data_dir + \"X_train.csv\", index=False)\n X_test.to_csv(data_dir + \"X_test.csv\", index=False)\n y_test.to_csv(data_dir + \"y_test.csv\", index=False)\n y_train.to_csv(data_dir + \"y_train.csv\", index=False)\n","sub_path":"scripts/train_test_split.py","file_name":"train_test_split.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"273686395","text":"import asyncio\nimport websockets\nimport io\nimport servo\nclass WebSockets_Server:\n\n def __init__(self, loop, address , port):\n self.loop = loop\n self.address = address\n self.port = port\n\n async def _handler(self, websocket, path):\n while True:\n recv_data = await websocket.recv()\n print(recv_data)\n print(type(recv_data))\n if recv_data == \"0\":\n # Lock\n servo.setFinishServo(0)\n #servo.setTempServo(0)\n elif recv_data == \"1\":\n # UnLock\n servo.setFinishServo(1)\n #servo.setTempServo(1)\n #elif recv_data == \"2\":\n # servo.setFinishServo(0)\n #elif recv_data == \"3\":\n # servo.setFinishServo(1)\n\n def run(self):\n self._server = websockets.serve(self._handler, self.address, self.port)\n self.loop.run_until_complete(self._server)\n self.loop.run_forever()\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n wss = WebSockets_Server(loop, '0.0.0.0', 8080)\n wss.run()\n","sub_path":"raspi/socket_server.py","file_name":"socket_server.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"155003466","text":"import logging\nimport datetime\nimport flask\n\nfrom server.auth import user_has_auth_role, ROLE_MEDIA_EDIT\n\nSOURCES_TEMPLATE_PROPS_VIEW = ['media_id', 'url','name', 'pub_country', 'public_notes', 'is_monitored']\nSOURCES_TEMPLATE_PROPS_EDIT = ['media_id', 'url','name', 'pub_country', 'public_notes', 'is_monitored', 'editor_notes']\n\nlogger = logging.getLogger(__name__)\n\ndef stream_response(data, dict_keys, filename, column_names=None, as_attachment=True):\n \"\"\"Stream a fully ready dict to the user as a csv.\n Keyword arguments:\n data -- an array of dicts\n dict_keys -- the keys in each dict to build the csv out of (order is preserved)\n filename -- a string to append to the automatically generated filename for identifaction\n column_names -- (optional) column names to use, defaults to dict_keys if not specified\n \"\"\"\n if (len(data) == 0):\n logger.debug(\"data is empty, must be asking for template\")\n else:\n logger.debug(\"csv.stream_response with \"+str(len(data))+\" rows of data\")\n if column_names is None:\n column_names = dict_keys\n logger.debug(\" cols: \"+' '.join(column_names))\n logger.debug(\" props: \"+' '.join(dict_keys))\n # stream back a csv\n def stream_as_csv(dataset, props, names):\n yield ','.join(names) + '\\n'\n for row in dataset:\n try:\n attributes = []\n for p in props:\n value = row[p]\n cleaned_value = value\n if isinstance(value, (int, long, float)):\n cleaned_value = str(row[p])\n elif value in ['', None]:\n # trying to handle endode/decode problem on the other end\n cleaned_value = ''\n else:\n cleaned_value = '\"'+value.encode('utf-8').replace('\"', '\"\"')+'\"'\n attributes.append(cleaned_value)\n #attributes = [ csv_escape(str(row[p])) for p in props]\n yield ','.join(attributes) + '\\n'\n except Exception as e:\n logger.error(\"Couldn't process a CSV row: \"+str(e))\n logger.exception(e)\n logger.debug(row)\n download_filename = str(filename)+'_'+datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'.csv'\n headers = {}\n if as_attachment:\n headers[\"Content-Disposition\"] = \"attachment;filename=\"+download_filename\n\n if (not len(data) == 0):\n return flask.Response(stream_as_csv(data, dict_keys, column_names),\n mimetype='text/csv; charset=utf-8', headers=headers)\n else:\n dict_keys = ','.join(dict_keys) + '\\n'\n return flask.Response(dict_keys,\n mimetype='text/csv; charset=utf-8', headers=headers)\n\n\ndef api_download_sources_csv(all_media, file_prefix):\n\n # info = user_mc.tag(int(collection_id))\n for src in all_media:\n\n # handle nulls\n if 'pub_country' not in src:\n src['pub_country'] = ''\n if 'editor_notes' not in src:\n src['editor_notes'] = ''\n if 'is_monitored' not in src:\n src['is_monitored'] = ''\n if 'public_notes' not in src:\n src['public_notes'] = ''\n\n what_type_download = SOURCES_TEMPLATE_PROPS_EDIT\n\n if user_has_auth_role(ROLE_MEDIA_EDIT):\n what_type_download = SOURCES_TEMPLATE_PROPS_EDIT\n else:\n what_type_download = SOURCES_TEMPLATE_PROPS_VIEW # no editor_notes\n\n return stream_response(all_media, what_type_download, file_prefix, what_type_download)","sub_path":"server/util/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"123248040","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom datetime import datetime\nimport os.path\nimport sys\nimport traceback\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom stn import STN\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string('dataset', 'MNIST',\n \"\"\"Currently only support MNIST dataset.\"\"\")\ntf.app.flags.DEFINE_string('data_path', '', \"\"\"Root directory of data\"\"\")\ntf.app.flags.DEFINE_string('train_dir', '/tmp/zehao/logs/STN/train',\n \"\"\"Directory where to write event logs \"\"\"\n \"\"\"and checkpoint.\"\"\")\ntf.app.flags.DEFINE_integer('max_steps', 1000000,\n \"\"\"Maximum number of batches to run.\"\"\")\ntf.app.flags.DEFINE_integer('summary_step', 10,\n \"\"\"Number of steps to save summary.\"\"\")\ntf.app.flags.DEFINE_integer('checkpoint_step', 1000,\n \"\"\"Number of steps to save summary.\"\"\")\ntf.app.flags.DEFINE_string('gpu', '0', \"\"\"gpu id.\"\"\")\n\n#TODO: remove hard code\n\n# load MNIST data\ndef loadMNIST(fname):\n if not os.path.exists(fname):\n # download and preprocess MNIST dataset\n from tensorflow.examples.tutorials.mnist import input_data\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n trainData, validData, testData = {}, {}, {}\n trainData[\"image\"] = mnist.train.images.reshape([-1, 28, 28]).astype(np.float32)\n validData[\"image\"] = mnist.validation.images.reshape([-1, 28, 28]).astype(np.float32)\n testData[\"image\"] = mnist.test.images.reshape([-1, 28, 28]).astype(np.float32)\n trainData[\"label\"] = mnist.train.labels.astype(np.float32)\n validData[\"label\"] = mnist.validation.labels.astype(np.float32)\n testData[\"label\"] = mnist.test.labels.astype(np.float32)\n os.makedirs(os.path.dirname(fname))\n np.savez(fname, train=trainData, valid=validData, test=testData)\n MNIST = np.load(fname)\n trainData = MNIST[\"train\"].item()\n validData = MNIST[\"valid\"].item()\n testData = MNIST[\"test\"].item()\n return trainData, validData, testData\n\n\n# generate training batch\ndef genPerturbations(params):\n with tf.variable_scope(\"genPerturbations\"):\n X = np.tile(params.canon4pts[:, 0], [params.batchSize, 1])\n Y = np.tile(params.canon4pts[:, 1], [params.batchSize, 1])\n dX = tf.random_normal([params.batchSize, 4]) * params.warpScale[\"pert\"] \\\n + tf.random_normal([params.batchSize, 1]) * params.warpScale[\"trans\"]\n dY = tf.random_normal([params.batchSize, 4]) * params.warpScale[\"pert\"] \\\n + tf.random_normal([params.batchSize, 1]) * params.warpScale[\"trans\"]\n O = np.zeros([params.batchSize, 4], dtype=np.float32)\n I = np.ones([params.batchSize, 4], dtype=np.float32)\n # fit warp parameters to generated displacements\n A = tf.concat([tf.stack([X, Y, I, O, O, O, -X * (X + dX), -Y * (X + dX)], axis=-1),\n tf.stack([O, O, O, X, Y, I, -X * (Y + dY), -Y * (Y + dY)], axis=-1)], 1)\n b = tf.expand_dims(tf.concat([X + dX, Y + dY], 1), -1)\n dpBatch = tf.matrix_solve_ls(A, b)\n dpBatch -= tf.to_float(tf.reshape([1, 0, 0, 0, 1, 0, 0, 0], [1, 8, 1]))\n dpBatch = tf.reduce_sum(dpBatch, reduction_indices=-1)\n return dpBatch\n\n\ndef train():\n \"\"\"Train STN\"\"\"\n # load data\n print(\"loading MNIST dataset...\")\n trainData, validData, testData = loadMNIST(\"data/MNIST.npz\")\n batch_size = 50\n with tf.Graph().as_default():\n model = STN(FLAGS.gpu)\n\n saver = tf.train.Saver(tf.global_variables())\n tfConfig = tf.ConfigProto(allow_soft_placement=True)\n tfConfig.gpu_options.allow_growth = True\n init = tf.global_variables_initializer()\n sess = tf.Session(config=tfConfig)\n sess.run(init)\n\n initial_step = 0\n global_step = model.global_step\n\n ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n initial_step = global_step.eval(session=sess)\n\n tf.train.start_queue_runners(sess=sess)\n\n summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)\n summary_op = tf.summary.merge_all()\n\n for step in xrange(initial_step, FLAGS.max_steps):\n start_time = time.time()\n\n # generate training data\n rand_idx = np.random.randint(len(trainData[\"image\"]), size=batch_size)\n image_per_batch = trainData[\"image\"][rand_idx]\n label_per_batch = trainData[\"label\"][rand_idx]\n image_per_batch = np.reshape(image_per_batch, [batch_size, 28, 28, 1])\n feed_dict = {\n model.image_input: image_per_batch,\n model.labels: label_per_batch,\n }\n\n if step % FLAGS.summary_step == 0:\n op_list = [\n model.train_op, model.loss, summary_op\n ]\n _, loss_value, summary_str = sess.run(op_list, feed_dict=feed_dict)\n summary_writer.add_summary(summary_str, step)\n print('loss: {}'.format(loss_value))\n else:\n _, loss_value = sess.run([model.train_op, model.loss],\n feed_dict=feed_dict)\n\n duration = time.time() - start_time\n\n if step % 10 == 0:\n num_images_per_step = batch_size\n images_per_sec = num_images_per_step / duration\n sec_per_batch = float(duration)\n format_str = ('%s: step %d, loss = %.2f (%.1f images/sec; %.3f '\n 'sec/batch)')\n print(format_str % (datetime.now(), step, loss_value,\n images_per_sec, sec_per_batch))\n sys.stdout.flush()\n\n # Save the model checkpoint periodically.\n if step % FLAGS.checkpoint_step == 0 or (step + 1) == FLAGS.max_steps:\n checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n if tf.gfile.Exists(FLAGS.train_dir):\n # tf.gfile.DeleteRecursively(FLAGS.train_dir)\n pass\n else:\n tf.gfile.MakeDirs(FLAGS.train_dir)\n try:\n train()\n except:\n print\n \"Exception in user code:\"\n print\n '-' * 60\n traceback.print_exc(file=sys.stdout)\n print\n '-' * 60\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"219362848","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2019-04-23 10:43\n# @Author : Pan Xuelei\n# @FileName: socket_exceptions0.py\n# @Eamil : 317118173pxl@gmail.com\n# @Description:Handling network socket exceptions\n\nimport socket\n\nhost = \"192.168.10.155\"\nport = 12345\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ntry:\n s.bind((host, port))\n s.settimeout(3)\n data, addr = s.recvfrom(1024)\n print(\"recevied form \", addr)\n print(\"obtained \", data)\n s.close()\nexcept socket.timeout:\n print(\"No connection between client and server.\")\n s.close()\n","sub_path":"Modules/socket/socket_exceptions0.py","file_name":"socket_exceptions0.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"491923356","text":"import unittest\n'''\n1。给一个singly linked list,去处重复数字的节点,只保留最后一个出现的相同节点\n输入: 5->3->2->2->3->1\n输出: 5->2->3->1.\n然后写test case\n'''\nclass Node:\n def __init__(self, v = None, next = None):\n self.next = next\n self.val = v\n\n def print(self):\n print(self.val)\n if self.next:\n self.next.print()\n\ndef remove(root):\n exist = {root.val}\n trav = root\n while trav.next:\n if trav.next.val in exist:\n trav.next = trav.next.next\n\n else:\n trav = trav.next\n exist.add(trav.val)\n\n return root\n\nroot = Node(1, Node(1, Node(2)))\nroot.print()\nremove(root)\nprint('----')\nroot.print()\nprint('----')\ntrav = dummy = Node()\nfor i in [1]:\n trav.next = Node(i)\n trav = trav.next\nremove(dummy.next)\n\ndummy.print()\n\nclass Test(unittest.TestCase):\n def test1(self):\n trav = dummy = Node()\n for i in [1,1,2,3,2,1]:\n trav.next = Node(i)\n trav = trav.next\n dummy.print()\n","sub_path":"BB/remove_duplicated_LL.py","file_name":"remove_duplicated_LL.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"532420307","text":"#\n# [205] Isomorphic Strings\n#\n# https://leetcode.com/problems/isomorphic-strings/description/\n#\n# algorithms\n# Easy (35.39%)\n# Total Accepted: 154.5K\n# Total Submissions: 436.5K\n# Testcase Example: '\"egg\"\\n\"add\"'\n#\n# Given two strings s and t, determine if they are isomorphic.\n# \n# Two strings are isomorphic if the characters in s can be replaced to get t.\n# \n# All occurrences of a character must be replaced with another character while\n# preserving the order of characters. No two characters may map to the same\n# character but a character may map to itself.\n# \n# Example 1:\n# \n# \n# Input: s = \"egg\", t = \"add\"\n# Output: true\n# \n# \n# Example 2:\n# \n# \n# Input: s = \"foo\", t = \"bar\"\n# Output: false\n# \n# Example 3:\n# \n# \n# Input: s = \"paper\", t = \"title\"\n# Output: true\n# \n# Note:\n# You may assume both s and t have the same length.\n# \n#\nclass Solution:\n def isIsomorphic(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) != len(t):\n \treturn False\n hash_set = {}\n hash_set_reverse = {}\n for i in range(len(s)):\n \tif s[i] not in hash_set.keys():\n \t\thash_set[s[i]] = t[i]\n \telse:\n \t\tif hash_set[s[i]] != t[i]:\n \t\t\treturn False\n\n \tif t[i] not in hash_set_reverse.keys():\n \t\thash_set_reverse[t[i]] = s[i]\n \telse:\n \t\tif hash_set_reverse[t[i]] != s[i]:\n \t\t\treturn False\n return True\n \n\n \n","sub_path":"205/205.isomorphic-strings.python3.py","file_name":"205.isomorphic-strings.python3.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"275680036","text":"\nimport requests\n\nfrom rest_framework.renderers import JSONRenderer\n\n\nclass MoipAPP(object):\n def __init__(self, token, key):\n self.base_url = 'https://sandbox.moip.com.br'\n self.token = token\n self.key = key\n\n def get(self, url, parameters=None):\n response = requests.get(\n '{0}/{1}'.format(self.base_url, url),\n params=parameters,\n auth=(self.token, self.key)\n )\n return response.text\n\n def post(self, url, parameters=None):\n headers = {\n 'Content-type': 'application/json; charset=\"UTF-8\"',\n }\n\n response = requests.post(\n '{0}/{1}'.format(self.base_url, url),\n data=JSONRenderer().render(parameters),\n headers=headers,\n auth=(self.token, self.key)\n )\n return response.text\n\n def create_app(self, parameters):\n response = self.post('v2/channels', parameters=parameters)\n return response\n\n\nclass Moip(object):\n\n STATUS_IN_ANALYSIS = 'IN_ANALYSIS'\n STATUS_AUTHORIZED = 'AUTHORIZED'\n STATUS_CANCELLED = 'CANCELLED'\n\n def __init__(self, access_token):\n self.base_url = 'https://sandbox.moip.com.br'\n self.access_token = access_token\n\n def get(self, url, parameters=None):\n headers = {\n 'Content-type': 'application/json; charset=\"UTF-8\"',\n 'Authorization': 'Bearer ' + self.access_token\n }\n\n response = requests.get('{0}/{1}'.format(self.base_url, url),\n params=parameters, headers=headers)\n return response.text\n\n def post(self, url, parameters=None):\n headers = {\n 'Content-type': 'application/json; charset=\"UTF-8\"',\n 'Authorization': 'Bearer ' + self.access_token\n }\n\n response = requests.post(\n '{0}/{1}'.format(self.base_url, url),\n data=JSONRenderer().render(parameters),\n headers=headers\n )\n return response.text\n\n def create_wirecard(self, parameters):\n response = self.post('v2/accounts', parameters=parameters)\n return response\n\n def post_customer(self, parameters):\n response = self.post('v2/customers', parameters=parameters)\n return response\n\n def get_customer(self, customer_id):\n response = self.get('v2/customers/{0}'.format(customer_id))\n return response\n\n def post_credit_card(self, customer_id, parameters):\n response = self.post(\n 'v2/customers/{0}/fundinginstruments'.format(customer_id),\n parameters=parameters)\n return response\n\n def delete_creditcard(self, creditcard_id):\n headers = {\n 'Content-type': 'application/json; charset=\"UTF-8\"',\n 'Authorization': 'Bearer ' + self.access_token\n }\n response = requests.delete(\n '{0}/v2/fundinginstruments/{1}'.format(self.base_url,\n creditcard_id), headers=headers)\n return response.status_code\n\n def post_order(self, parameters):\n response = self.post('v2/orders', parameters=parameters)\n return response\n\n def get_order(self, order_id):\n response = self.get('v2/orders/{0}'.format(order_id))\n return response\n\n def post_payment(self, order_id, parameters):\n response = self.post(\n 'v2/orders/{0}/payments'.format(order_id), parameters)\n return response\n\n def get_payment(self, payment_id):\n response = self.get('v2/payments/{0}'.format(payment_id))\n return response\n\n def capture_payment(self, payment_id):\n response = self.post('v2/payments/{0}/capture'.format(payment_id))\n return response\n\n def cancel_pre_authorized_payment(self, payment_id):\n response = self.post('v2/payments/{0}/void'.format(payment_id))\n return response\n\n def verify_account(self, account_id):\n response = self.get('v2/accounts/{0}'.format(account_id))\n return response\n","sub_path":"register/payment/moip.py","file_name":"moip.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"360317253","text":"# settings/production.py\n\"\"\"\nDjango production settings. How do I deal with this file and settings?\n\"\"\"\n\nfrom .base import *\n\n\n\"\"\"\nThe secret key and database info should come from the same file, and it\nshould probably be a JSON file (per two scoops of django's suggestion).\n\"\"\"\n\nwith open('/etc/secret_key.txt') as f:\n SECRET_KEY = f.read().strip()\n\nDEBUG = False\n\n#ALLOWED_HOSTS = ['https://map.leibniz-zmt.de/']\nALLOWED_HOSTS = ['map.leibniz-zmt.de/', '127.0.0.1', 'localhost'] # for the time being\n\n# I am not sure why these are important.\nCSRF_COOKIE_SECURE = True\nSESSION_COOKIE_SECURE = True\n","sub_path":"main/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"296614223","text":"#\n# Copyright (C) 2016 David Brookshire \n#\nimport time\n\nimport RPi.GPIO as GPIO\n\nBUTTON_GPIO = 4\nLED1_GPIO = 17\nLED2_GPIO = 18\n\n\nclass Lamp():\n state = False # True==On, False==Off\n gpio = None\n\n def __init__(self, gpio):\n self.gpio = gpio\n GPIO.setup(self.gpio, GPIO.OUT)\n\n def __repr__(self):\n return \"LAMP-%d\" % self.gpio\n\n def on(self):\n GPIO.output(self.gpio, True)\n\n def off(self):\n GPIO.output(self.gpio, False)\n\n\nclass Button():\n gpio = None\n\n def __init__(self, gpio):\n self.gpio = gpio\n GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n def __repr__(self):\n return \"BUTTON-%d\" % self.gpio\n\n def get_state(self):\n return GPIO.input(self.gpio)\n\n\ndef do_blink(lamp, count=1, delay=0.5):\n while count:\n lamp.on()\n time.sleep(delay)\n lamp.off()\n time.sleep(0.2)\n count -= 1\n\n\ndef do_shutdown(*leds):\n if len(leds) >= 2:\n do_blink(leds[0], 4)\n do_blink(leds[1], 1)\n else:\n do_blink(leds[0], 4)\n do_blink(leds[0], 1, 5)\n\n for l in leds:\n l.off()\n\nif __name__ == '__main__':\n\n # GPIO.cleanup()\n GPIO.setmode(GPIO.BCM)\n\n lamp1 = Lamp(LED1_GPIO)\n lamp2 = Lamp(LED2_GPIO)\n trigger = Button(BUTTON_GPIO)\n\n try:\n while True:\n input_state = trigger.get_state()\n\n if not input_state:\n print(\"Button pressed\")\n i = 0\n while not input_state:\n if i % 2:\n lamp1.on()\n lamp2.off()\n else:\n lamp1.off()\n lamp2.on()\n\n i += 1\n time.sleep(0.2)\n input_state = trigger.get_state()\n\n print(\"Button released\")\n lamp1.off()\n lamp2.off()\n\n except KeyboardInterrupt:\n print(\"Shutting down\")\n do_shutdown(lamp1, lamp2)\n GPIO.cleanup()\n print(\"Exiting\")\n","sub_path":"led_press2.py","file_name":"led_press2.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"604686709","text":"# Lab 6, CS104 Moving function definitions\n# Student 1. Shurjo Maitra (sm47), Student 2. Oshomah Agbugui (ota2)\n# <10.15.15>\n\nfrom __future__ import division, print_function\ninput = raw_input\nfrom myro import *\n\n\n#File contains functions to enhance scribbler movement\n\n# constants defined here\nCENTS_PER_SEC = 19 # the distance traveled by the scribbler in 1s\nDEGS_PER_SEC = 130\n\n# functions defined here\ndef travelForw(dist): #function definition for going forward dist cm\n secsPerCent = dist / CENTS_PER_SEC\n forward(1, secsPerCent)\n \ndef travelBack(dist):\n secsPerCent = dist / CENTS_PER_SEC #function definition for going backward dist cm\n backward(1, secsPerCent)\n \ndef turnLeftDegrees(degrees):\n secsPerDeg = degrees / DEGS_PER_SEC #function definition for turning left \"degrees\" \n turnLeft(1, secsPerDeg)\n\ndef turnRightDegrees(degrees):\n secsPerDeg = degrees / DEGS_PER_SEC #function definition for turning right \"degrees\"\n turnRight(1, secsPerDeg)\n\ndef turnDegrees(degs): #function definition for turning \"degrees\"\n degs = degs % 360\n if degs == 0:\n return()\n elif degs <= 180:\n turnLeftDegrees(degs)\n elif degs > 180:\n turnRightDegrees(360-degs)\n\n\n# --------- main program -------------\n","sub_path":"lab6/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"492044423","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 23 14:40:12 2018\n\n@author: Admin\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata= pd.read_csv(\"D:/Udemy_ML/Logistic_Regression/Logistic_Regression/Social_Network_Ads.csv\")\nX = data.iloc[:,[2,3]].values\ny= data.iloc[:,-1].values\n\n#splitting\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=1/4, random_state=0)\n\n#Encoding\n\"\"\"from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n\nle_train= LabelEncoder()\nX_train[:,0]=le_train.fit_transform(X_train[:,0])\noh_train= OneHotEncoder(categorical_features=[0])\nX_train=oh_train.fit_transform(X_train).toarray()\n\nle_test= LabelEncoder()\nX_test[:,0]=le_test.fit_transform(X_test[:,0])\noh_test= OneHotEncoder(categorical_features=[0])\nX_test=oh_test.fit_transform(X_test).toarray()\"\"\"\n\n#Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\n\n#Logistic Regression\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(random_state=0)\nclassifier.fit(X_train, y_train)\n\n#predict test results\ny_pred= classifier.predict(X_test)\n\n#Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n#visualizing\n\ndef plot(X, y):\n from matplotlib.colors import ListedColormap\n X_set, y_set= X, y\n X1, X2= np.meshgrid(np.arange(start = X_set[:,0].min()-1, stop= X_set[:,0].max()+1,step=0.01),\n np.arange(start = X_set[:,1].min()-1, stop= X_set[:,1].max()+1,step=0.01)\n )\n plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha=0.75, cmap= ListedColormap('red','green'))\n plt.xlim(X1.min(), X1.max())\n plt.ylim(X2.min(), X2.max())\n for i,j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set==j,0], X_set[y_set==j,1], c= ListedColormap(('red','green'))(i), label=j)\n plt.title('Logistic Regression')\n plt.xlabel('Age')\n plt.ylabel('Salary')\n plt.legend()\n plt.show()\n \nplot(X_train, y_train)\nplot(X_test, y_test)\n\n\n\n","sub_path":"Python/Code/logistic_reg.py","file_name":"logistic_reg.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"553047105","text":"# -*- coding: utf-8 -*-\nimport time\nimport re\nimport MySQLdb as mdb\nimport scrapy\nfrom ..utils import AmazonSpiderUtil\nfrom ..items import LSpiderCommentInfo, LSpiderBookInfo\n\nclass AmazonCommentSpider(scrapy.Spider):\n name = \"amazon_comment\"\n allowed_domains = [\"www.amazon.cn\"]\n start_urls = ['http://www.amazon.cn/']\n domain = \"amazon\"\n\n def start_requests(self):\n config = AmazonSpiderUtil.get_config()\n self.client = mdb.connect(\n host=config[\"host\"],\n port=config[\"port\"],\n user=config[\"user\"],\n passwd=config[\"passwd\"],\n db='spider_rough_base',\n charset=config[\"charset\"]\n )\n self.client.autocommit(True)\n\n url = \"https://www.amazon.cn/b/ref=s9_acss_bw_cg_editor_2a1_cta_w?ie=UTF8&node=1535039071&pf_rd_m=A1U5RCOVU0NYF2&pf_rd_s=merchandised-search-3&pf_rd_r=ZX5XAG4S895ZY95B85R7&pf_rd_t=101&pf_rd_p=6337e79b-a404-4994-9a54-e522f5870b08&pf_rd_i=116169071\"\n\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n containers = response.css('.bxc-grid__row')\n now = int(time.time())\n\n for container in containers:\n cover = container.css('.bxc-grid__column--4-of-12')\n comment = container.css('.bxc-grid__column--8-of-12')\n\n if len(cover) > 0 and len(comment) > 0:\n url = cover[0].css('a::attr(href)').extract_first()\n item_id = AmazonSpiderUtil.get_item_id(url)\n\n sentences = comment[0].css('h4::text').extract()\n recommend = ''\n username = ''\n for index, sen in enumerate(sentences):\n if index < len(sentences) - 1:\n recommend = recommend + sen\n else:\n username = sen\n username = username.replace(u'——读者', '')\n username = username.replace(u'——编辑', '')\n username = username.strip()\n\n item_id = AmazonSpiderUtil.get_item_id(url)\n custom_item_id = self.domain + '_' + item_id\n\n yield LSpiderCommentInfo(\n user_name=username,\n user_icon=None,\n rate=5,\n content=recommend,\n published_time=now,\n custom_item_id=custom_item_id\n )\n\n yield scrapy.Request(url=url, callback=self.parse_detail)\n\n def parse_detail(self, response):\n now = int(time.time())\n\n item_id = AmazonSpiderUtil.get_item_id(response.url)\n custom_item_id = self.domain + '_' + item_id\n\n author = ''\n author_arr = response.css('div#byline span.author a::text').extract()\n for author_item in author_arr:\n author = author + author_item\n\n title = response.css('h1#title span#ebooksProductTitle::text').extract_first()\n\n price_str = response.css('tr.kindle-price td.a-color-price::text').extract_first()\n price = AmazonSpiderUtil.process_price(price_str)\n\n recommend_pattern = re.compile(r'bookDescEncodedData = \"(.+)\",')\n found = recommend_pattern.findall(response.body)\n recommend = None\n if found is not None and len(found) > 0:\n recommend = found[0]\n\n if title is not None:\n # 组装book信息\n yield LSpiderBookInfo(\n title=title,\n custom_item_id=custom_item_id,\n channel=self.domain,\n cover_image_url=response.css(\n 'div#ebooks-img-canvas img#ebooksImgBlkFront::attr(src)').extract_first(),\n author=author,\n abstract=response.css('div#ps-content').extract_first(),\n detail_url=response.url,\n created_time=now,\n update_time=now,\n price=price,\n recommend=recommend\n )\n","sub_path":"spider_amazon_ebook/spiders/amazon_comment.py","file_name":"amazon_comment.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"169189515","text":"from __future__ import annotations\n\nimport math\nfrom pathlib import Path\n\nimport numpy as np\n\nimport skimage.transform\nimport skimage.io\n\nfrom PySide2.QtCore import QObject, Signal\n\nimport keras\n\nfrom bsmu.vision_core.image import FlatImage\nfrom bsmu.vision.app.plugin import Plugin\n\n# import bsmu.bone_age.plugins.Stn_Oarriaga\nfrom bsmu.bone_age.plugins import stn_layer\n\n\nclass BoneAgeAnalyzerPlugin(Plugin):\n def __init__(self, app: App):\n super().__init__(app)\n\n self.data_storage = app.enable_plugin('bsmu.vision.plugins.storages.data.DataStoragePlugin').data_storage\n\n self.united_config = self.config()\n stn_model_path = (Path(__file__).parent / self.united_config.data['stn_model_path']).resolve()\n self.bone_age_analyzer = BoneAgeAnalyzer(stn_model_path)\n\n def _enable(self):\n self.data_storage.data_added.connect(self.bone_age_analyzer.analyze_bone_age)\n # TODO: add action on self.data_storage.data_removed\n\n def _disable(self):\n self.data_storage.data_added.disconnect(self.bone_age_analyzer.analyze_bone_age)\n\n\nclass BoneAgeAnalyzer(QObject):\n bone_age_analyzed = Signal()\n\n def __init__(self, stn_model_path: Path):\n super().__init__()\n\n self.stn_model_path = stn_model_path\n print('STN model path:', self.stn_model_path.absolute().resolve())\n\n self._stn_model = None\n self._stn_model_output_function = None\n\n def analyze_bone_age(self, data: Data):\n if not isinstance(data, FlatImage):\n return\n\n if self._stn_model is None:\n assert self.stn_model_path.exists(), 'There is no STN model file'\n\n self._stn_model = keras.models.load_model(str(self.stn_model_path),\n custom_objects={'BilinearInterpolation': stn_layer.BilinearInterpolation},\n compile=False)\n print('MODEL LOADED')\n\n image_input_layer = self._stn_model.get_layer('input_1').input\n male_input_layer = self._stn_model.get_layer('input_male').input\n age_layer_output = self._stn_model.layers[-1].output\n stn_layer_output = self._stn_model.get_layer('stn_interpolation').output\n final_conv_layer_output = self._stn_model.get_layer('xception').get_output_at(\n -1) # Take last node from layer\n final_pooling_layer_output = self._stn_model.get_layer('encoder_pooling').output\n\n self._stn_model_output_function = keras.backend.function(\n [image_input_layer, male_input_layer],\n [age_layer_output, stn_layer_output, final_conv_layer_output, final_pooling_layer_output])\n\n image = data.array\n print('image_info:', image.shape, image.min(), image.max(), image.dtype)\n\n BATCH_SIZE = 1\n INPUT_SIZE = (768, 768)\n INPUT_CHANNELS = 3\n\n input_batch_images = np.zeros(shape=(BATCH_SIZE, *INPUT_SIZE, INPUT_CHANNELS), dtype=np.float32)\n input_batch_images[0, ...] = preprocessed_image(image, INPUT_SIZE, INPUT_CHANNELS)\n input_batch_images = keras.applications.xception.preprocess_input(input_batch_images)\n print('preprocessed image', input_batch_images[0].shape, input_batch_images[0].min(),\n input_batch_images[0].max(), input_batch_images[0].dtype, np.mean(input_batch_images[0]))\n skimage.io.imsave('test_image2.png', input_batch_images[0])\n\n input_batch_males = np.zeros(shape=(BATCH_SIZE, 1), dtype=np.uint8)\n input_batch_males[0, ...] = 1 # We do not know the gender at first, so use male\n\n input_batch = [input_batch_images, input_batch_males]\n [age_output_batch, stn_output_batch, final_conv_output_batch, final_pooling_output_batch] = \\\n self._stn_model_output_function(input_batch)\n\n age_in_months = (age_output_batch[0] + 1) * 120\n age_in_years_fractional_part, age_in_years_integer_part = math.modf(age_in_months / 12)\n age_str = f'{age_in_years_integer_part} лет {age_in_years_fractional_part * 12} месяцев'\n\n print('Age_output', data.path, age_output_batch[0], '\\t\\t', age_str)\n skimage.io.imsave('test_stn.png', stn_output_batch[0])\n\n self.bone_age_analyzed.emit()\n\n\ndef preprocessed_image(image, size, channels):\n image = add_pads(image)[0]\n image = skimage.transform.resize(image, size, anti_aliasing=True, order=1).astype(np.float32)\n\n image = normalized_image(image)\n image = image * 255 # xception.preprocess_input needs RGB values within [0, 255].\n\n # augmented_image = augmented_image * 255\n\n if image.ndim == 2:\n image = np.stack((image,) * channels, axis=-1)\n # augmented_image = np.stack((augmented_image,) * MODEL_INPUT_CHANNELS, axis=-1)\n\n skimage.io.imsave('test_image.png', image)\n\n return image\n\n\ndef add_pads(image, dims=2):\n \"\"\"Add zero-padding to make square image (original image will be in the center of paddings)\"\"\"\n image_shape = image.shape[:dims]\n pads = np.array(image_shape).max() - image_shape\n print('pads', pads)\n # Add no pads for channel axis\n pads = np.append(pads, [0] * (len(image.shape) - dims)).astype(pads.dtype)\n print('pads', pads)\n\n # pads[pads < 0] = 0\n before_pads = np.ceil(pads / 2).astype(np.int)\n after_pads = pads - before_pads\n pads = tuple(zip(before_pads, after_pads))\n image = np.pad(image, pads, mode='constant', constant_values=np.mean(image))\n return image, pads\n\n\ndef normalized_image(image):\n image_min = image.min()\n if image_min != 0:\n image = image - image_min\n image_max = image.max()\n if image_max != 0 and image_max != 1:\n image = image / image_max\n return image\n","sub_path":"src/bsmu/bone_age/plugins/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":5773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"296763269","text":"# -*- coding: utf-8 -*-\n# pylint: skip-file\n\n\n# -*- coding: utf-8 -*-\n# pylint: skip-file\n\n# -*- coding: utf-8 -*-\n\nfrom rest_framework import serializers\n\nfrom bsint_django.ect import models\n\nfrom bsint_django.ect.serializers import EnvClassSerializer\n\nfrom bsint_django.ect.serializers.decimal_field import DecimalField\n\nclass EnvParamSerializer(serializers.HyperlinkedModelSerializer):\n\n env_param_id = DecimalField(coerce_to_string=True, source='env_param_id')\n\n env_macro_event_count = serializers.Field()\n\n x_env_class_list = EnvClassSerializer()\n\n class Meta:\n model = models.EnvParam\n fields = (\n 'env_param_id',\n 'name',\n 'category_name',\n 'sub_category_name',\n 'env_macro_event_count',\n 'description',\n 'create_time',\n 'update_time',\n 'x_env_class_list',\n )\n","sub_path":"serializers/env_param_serializer.py","file_name":"env_param_serializer.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"496032744","text":"from zipfile import ZipFile\nfrom glob import glob\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import StructType\nfrom pyspark.sql.functions import lit\nimport shutil\nimport os\nimport pandas as pd\n\ndef extract_all(src, dest, metadata_dir):\n zipfiles = glob(f'{src}/*.zip')\n for zipfile in zipfiles:\n year = zipfile.split('_')[-1].split('.')[0]\n with ZipFile(zipfile) as f:\n f.extractall(src)\n\n _dirs = glob(os.path.join(src, \"*\"))\n for d in _dirs:\n if 'Dados' in d:\n data = os.path.join(d, '*.csv')\n data_file = glob(data)[0]\n if not os.path.exists(dest):\n os.mkdir(dest)\n shutil.move(data_file, os.path.join(dest, f'dados_{year}.csv'))\n \n elif 'Document' in d:\n metadata = os.path.join(d, '*.xlsx')\n metadata_file = glob(metadata)[0]\n if not os.path.exists(metadata_dir):\n os.mkdir(metadata_dir)\n shutil.move(metadata_file, os.path.join(metadata_dir, f'dicionario_dados_{year}.xlsx'))\n\n\nclass Dataset:\n def __init__(self, path, catalog, year, merge_mapping=None):\n '''Returns a Censo Ensino Superior dataset.\n \n :param path: path of dataset\n :param catalog: path of data catalog following the pattern path#sheet_name\n :param year: year of the census.\n '''\n self.path = path\n self.catalog = catalog\n self.year = year\n self.merge_mappinng = merge_mapping\n #self.schema = self._schema()\n self.data = self._build_spark_df()\n \n def __str__(self):\n return self.data.show()\n \n def __repr__(self):\n return self.data.show()\n \n def _extract_metadata_from_excel(self):\n '''Returns dataset metadata from an excel file.\n '''\n path, sheet = self.catalog.split('#')\n print(path)\n print(sheet)\n current_names = ['NOME DA VARIÁVEL', 'TIPO']\n new_names = ['nome_variavel', 'tipo']\n columns = dict(zip(current_names, new_names))\n \n df = pd.read_excel(path, header=1)#, sheet_name=sheet)\n df = df.rename(columns=columns)\n df = df[['nome_variavel', 'tipo']].apply(lambda val: val.str.upper())\n df = df.dropna()\n return df\n\n def _schema_from_pandas(self, metadata):\n '''Returns a spark dataframe schema from pandas dataframe\n '''\n schema_draft = {'type': 'struct'}\n \n fields = []\n for _, row in metadata.iterrows():\n field = {}\n field['name'] = row['nome_variavel']\n field['type'] = 'integer' if row['tipo'] == 'NUM' else 'string'\n field['nullable'] = True\n field['metadata'] = {}\n fields.append(field)\n \n schema_draft['fields'] = fields\n schema = StructType.fromJson(schema_draft)\n return schema\n \n def _schema(self):\n '''Returns the schema of dataset.\n '''\n metadata = self._extract_metadata_from_excel()\n schema = self._schema_from_pandas(metadata)\n return schema\n\n def _get_spark_session(self):\n '''Returns a spark session.\n '''\n spark = SparkSession.builder.getOrCreate()\n return spark\n \n def _build_spark_df(self):\n '''Build the dataset as a spark dataframe.\n '''\n spark = self._get_spark_session()\n df = spark.read.csv(self.path, header=True, sep=';', encoding='ISO-8859-1')#, schema=self.schema)\n return df\n \n def _rename_columns(self):\n if self.year != 2010:\n if self.merge_mapping:\n pass\n else:\n print('')\n \n def _create_columns(self):\n if 'NU_ANO' not in self.data.columns:\n self.data = self.data.withColumn('nu_ano', lit(self.year))\n \n def _normalize(self):\n self._create_columns()\n #self._rename_columns()\n \n def _to_parquet(self, path, partition_by, mode):\n '''Write dataset as parquet.\n '''\n if partition_by:\n self.data.write.partitionBy(partition_by).mode(mode).parquet(path)\n else:\n self.data.write.mode(mode).parquet(path)\n \n def save(self, path, partition_by=None, mode='append', _format='parquet'):\n '''Save dataset.\n '''\n formats = {\n 'parquet': self._to_parquet,\n }\n save_as = formats[_format]\n \n self._normalize()\n save_as(path, partition_by, mode)\n\n\ndef parse(path, catalog, year, dest):\n dataset = Dataset(path, catalog, year)\n dataset.save(os.path.join(dest, 'idd/2006'), 'nu_ano')","sub_path":"eng_dados/galera/funcoes_idd.py","file_name":"funcoes_idd.py","file_ext":"py","file_size_in_byte":4761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"404223063","text":"import numpy as np\nimport os\nimport models\nimport cv2\nimport dlib\nfrom PIL import Image\nimport requests\n\nimport torch\nimport torch.nn.functional as F\nfrom torchvision import transforms\n\ndef correct_ilumination(img):\n \"https://stackoverflow.com/questions/24341114/simple-illumination-correction-in-images-opencv-c\"\n lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n #cv2.imshow(\"lab\",lab)\n #-----Splitting the LAB image to different channels-------------------------\n l, a, b = cv2.split(lab)\n #-----Applying CLAHE to L-channel-------------------------------------------\n clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))\n cl = clahe.apply(l)\n #-----Merge the CLAHE enhanced L-channel with the a and b channel-----------\n limg = cv2.merge((cl,a,b))\n #-----Converting image from LAB Color model to RGB model--------------------\n final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n return final\n\ndef crop_image(img, landmarks):\n # get face's landmarks and crop it\n img = Image.fromarray(img).convert('RGB')\n width, height = img.size\n left = max(int(min(landmarks[:, 0])) - 10, 0)\n right = min(width, int(max(landmarks[:, 0] + 10)))\n top = max(int(min(landmarks[:, 1])) - 30, 0)\n bottom = min(height, int(max(landmarks[:, 1])))\n img = img.crop((left, top, right, bottom))\n return img\n\nLEFT_EYE_INDICES = [36, 37, 38, 39, 40, 41]\nRIGHT_EYE_INDICES = [42, 43, 44, 45, 46, 47]\n\ndef rect_to_tuple(rect):\n left = rect.left()\n right = rect.right()\n top = rect.top()\n bottom = rect.bottom()\n return left, top, right, bottom\n\ndef extract_eye(shape, eye_indices):\n points = map(lambda i: shape.part(i), eye_indices)\n return list(points)\n\ndef extract_eye_center(shape, eye_indices):\n points = extract_eye(shape, eye_indices)\n xs = map(lambda p: p.x, points)\n ys = map(lambda p: p.y, points)\n return sum(xs) // 6, sum(ys) // 6\n\ndef extract_left_eye_center(shape):\n return extract_eye_center(shape, LEFT_EYE_INDICES)\n\ndef extract_right_eye_center(shape):\n return extract_eye_center(shape, RIGHT_EYE_INDICES)\n\ndef angle_between_2_points(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n tan = (y2 - y1) / (x2 - x1)\n return np.degrees(np.arctan(tan))\n\ndef get_rotation_matrix(p1, p2):\n angle = angle_between_2_points(p1, p2)\n x1, y1 = p1\n x2, y2 = p2\n xc = (x1 + x2) // 2\n yc = (y1 + y2) // 2\n M = cv2.getRotationMatrix2D((xc, yc), angle, 1)\n return M\n\nsize = 224\ntransform = transforms.Compose([\n transforms.Grayscale(num_output_channels=3),\n transforms.Resize((size, size)),\n transforms.ToTensor(),\n])\n\nindex_to_string = ['anger', 'contempt', 'disgust', 'fear', 'happiness', 'sadness', 'surprise', 'neutral']\n\nface_detector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor('/home/luiza/Qiron/demographic_survey/scripts/shape_predictor_68_face_landmarks.dat')\n\n# Get a reference to webcam #0 (the default one)\nvideo_capture = cv2.VideoCapture(0)\n\n# Initialize some variables\nprocess_this_frame = True\n\nwhile True:\n cropped = None\n # Grab a single frame of video\n ret, frame = video_capture.read()\n\n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.3, fy=0.3)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n rgb_small_frame = correct_ilumination(rgb_small_frame)\n\n # Only process every other frame of video to save time\n if process_this_frame:\n faces = face_detector(rgb_small_frame, 1)\n\n dets = dlib.full_object_detections()\n for k, d in enumerate(faces):\n # Get the landmarks/parts for the face in box d.\n shape = predictor(rgb_small_frame, d)\n\n left_eye = extract_left_eye_center(shape)\n right_eye = extract_right_eye_center(shape)\n\n img = rgb_small_frame\n\n M = get_rotation_matrix(left_eye, right_eye)\n rotated = cv2.warpAffine(img, M, (img.shape[0], img.shape[1]), flags=cv2.INTER_CUBIC)\n\n landmarks = [[shape.part(i).x, shape.part(i).y] for i in range(68)]\n landmarks = np.array(landmarks)\n\n cropped = crop_image(rotated, landmarks)\n #correct_img = cropped.squeeze(0).numpy().transpose(1, 2, 0)\n\n _, img_encoded = cv2.imencode('.jpg', np.array(cropped))\n\n res = requests.post('http://localhost:5000/predict', data=img_encoded.tostring(), headers={'content-type': 'image/jpeg'})\n if res.ok:\n print('response: ', res.json())\n #correct_img = (correct_img - correct_img.min())/(correct_img.max() - correct_img.min())\n\n process_this_frame = not process_this_frame\n\n # Display the resulting image\n #cv2.imshow('Video', rgb_small_frame)\n\n # Hit 'q' on the keyboard to quit!\n #if cv2.waitKey(1) & 0xFF == ord('q'):\n #break\n\n# Release handle to the webcam\nvideo_capture.release()\ncv2.destroyAllWindows()\n\n","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"651022720","text":"#!/bin/bash/env python\r\n#-*-coding:utf-8-*-\r\n\r\ndict1 = {\r\n \"北京\" : {\r\n \"海淀\" : {\r\n \"清华大学\": [\"数学\", \"物理学\", \"计算机科学与技术\", \"生物学\", \"光学工程\", \"药学\"],\r\n \"北京大学\": [\"经济学\", \"考古学\", \"口腔医学\", \"临床医学\", \"新闻学\"],\r\n \"北京航空航天大学\": [\"计算机\", \"自动化\", \"理科实验班\"]\r\n },\r\n \"东城\" : {\r\n \"中央戏剧学院\": [\"表演\", \"导演\", \"戏剧影视文学\", \"舞台美术\"],\r\n \"北京长江商学院\": [\"MBA\", \"EMBA\"]\r\n },\r\n \"西城\" : {\r\n \"北京教育学院\": [\"文物鉴定与修复\", \"行政管理\", \"工商企业管理\"],\r\n \"北京建筑工程学院\": [\"建筑\", \"城规\", \"土木\"],\r\n },\r\n },\r\n \"上海\" : {\r\n \"悯行\" : {\r\n \"上海交通大学\": [\" 电子信息工程\", \"机械工程\", \"计算机科学与技术\", \"金融学\", \"药学\"],\r\n },\r\n \"徐汇\" : {\r\n \"复旦大学\": [\"新闻学\", \"微电子学\", \"软件工程\"],\r\n },\r\n \"杨浦\" : {\r\n \"同济大学\": [\"土木工程\", \"风景园林学\", \"建筑\"],\r\n },\r\n },\r\n \"广州\" : {\r\n \"海珠\" : {\r\n \"中山大学\": [\" 生态学\", \"工商管理\", \"哲学\", \"金融学\", \"临床医学\"],\r\n },\r\n \"天河\" : {\r\n \"华南理工大学\": [\"网络工程 \", \"食品科学与工程\", \"信息工程\"],\r\n },\r\n \"番禺\" : {\r\n \"华南师范大学\": [\"心理学\", \"汉语言文学\", \"教育学\"],\r\n },\r\n }\r\n}\r\n\r\nwith open('./dict.txt', 'a+') as file:\r\n for key, value in dict1.items():\r\n file.write(\"\\\"%s\\\":\\\"%s\\\"\" % (key, value))\r\n file.newlines\r\n file.flush()\r\n\r\nwhile True:\r\n for city in dict1:\r\n print (city)\r\n\r\n city_choice = input(\"选择城市>>\")\r\n if city_choice in dict1:\r\n while True:\r\n for area in dict1[city_choice]:\r\n print ('\\t', area)\r\n area_choice = input(\"选择区域>>\")\r\n if area_choice in dict1[city_choice]:\r\n while True:\r\n for univercity in dict1[city_choice][area_choice]:\r\n print ('\\t\\t', univercity)\r\n univercity_choice = input(\"选择学校>>\")\r\n if univercity_choice in dict1[city_choice][area_choice]:\r\n while True:\r\n for major in dict1[city_choice][area_choice][univercity_choice]:\r\n print ('\\t\\t\\t', major)\r\n major_choice = input(\"选择专业>>\")\r\n if major_choice in dict1[city_choice][area_choice][univercity_choice]:\r\n print (\"您选择的是 %s 市 %s 区 %s %s 专业\" % (city_choice, area_choice, univercity_choice, major_choice))\r\n else:\r\n print (\"您选择的专业%s没有\" % univercity_choice)\r\n\r\n choice = input(\"是否退出?>>\")\r\n if choice == 'Y':\r\n exit()\r\n else:\r\n print (\"您选择的学校%s没有\" % univercity_choice)\r\n\r\n else:\r\n print (\"您选择的区域不在%s城市\" % city_choice)\r\n continue\r\n else:\r\n print (\"不存在此城市\")\r\n","sub_path":"zuoye11/zuoye_2.py","file_name":"zuoye_2.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"265978584","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport json\n\nimport urllib2\nfrom lxml.html import parse\n\nfrom django.shortcuts import render\n\nfrom django.http import HttpResponse\n\nfrom django.http import JsonResponse\n\nfrom .models import Summary\nfrom pyteaser import SummarizeUrl\nfrom .forms import SummaryForm\n# Create your views here.\ndef summary(request):\n\ttitle = 'Summary'\n\tform = SummaryForm(request.POST or None)\n\tresponse_data = {}\n\tcontext = {\n\t\t\"title\": title,\n\t\t\"form\": form,\n\t}\n\tif request.method == 'POST':\t\t\n\t\tinstance = form.save(commit=False)\n\t\turl = instance.url\n\t\tif form.is_valid():\n\t\t\tsummary = SummarizeUrl(url)\n\t\t\tinstance.summarize_url = summary\n\t\t\thdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n\t\t\t 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n\t\t\t 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n\t\t\t 'Accept-Encoding': 'none',\n\t\t\t 'Accept-Language': 'en-US,en;q=0.8',\n\t\t\t 'Connection': 'keep-alive'\n\t\t\t } \n\t\t\treq = urllib2.Request(url, headers=hdr)\n\t\t\tpage = urllib2.urlopen(req)\n\t\t\tp = parse(page)\n\t\t\ttitle = p.find(\".//title\").text\n\t\t\tinstance.title = title\n\t\t\t# instance.save()\n\t\t\tresponse_data['url'] = instance.url\n\t\t\tresponse_data['title'] = title\n\t\t\tresponse_data['summary'] = instance.summarize_url \n\t\t\tcontext = {\n\t\t\t\t\"title\": title,\n\t\t\t\t\"url\": url,\n\t\t\t\t\"summary\": summary,\n\t\t\t}\n\t\t\treturn JsonResponse(response_data)\n\t\telse:\n\t\t\treturn JsonResponse({\"nothing to see\": \"this isn't happening\"})\n\t\t\t\n\telse:\n\t\tform = SummaryForm()\t\t\n\t\n\n\n\treturn render(request, \"website/index.html\", context)\n\n\n\n","sub_path":"TLDR/summarize/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"136703482","text":"import os\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nimport math\nimport traceback\n\nabs_path = os.path.dirname(os.path.abspath(__file__))\n\n\ndef cal_tradeline(code):\n \"\"\"\n see: https://www.jianshu.com/p/e55a8c9e4b56\n \"\"\"\n print(f\"calculating {code}\")\n df = pd.read_csv(f\"{abs_path}/../navs/{code}.csv\", header=None,\n usecols=[3, 5, 6],\n names=['date', 'net_value', 'accumulative_value']\n )\n df = df.loc[df['accumulative_value'].notnull()]\n df = df.reset_index(drop=True)\n df.head()\n df['new_index'] = df.index\n y = df.accumulative_value\n x = df.new_index\n x = sm.add_constant(x)\n est = sm.OLS(y, x)\n est = est.fit()\n #print(df)\n #print(est.summary())\n #print(est.params)\n indexes = df.index.values\n indexes_values = sm.add_constant(indexes)\n avg_line = est.predict(indexes_values)\n\n # y = ax + b\n # ax - y + b =0\n # distance = a*x0 - y0 + b / sqrt(a*a + 1)\n pos_count = 0\n pos_x_sum = 0.0\n pos_y_sum = 0.0\n neg_count = 0\n neg_x_sum = 0.0\n neg_y_sum = 0.0\n\n for index, row in df.iterrows():\n distance = (est.params.new_index * row['new_index'] - row['accumulative_value']\n + est.params.const)\n if distance >= 0:\n pos_count += 1\n pos_x_sum += row['new_index']\n pos_y_sum += row['accumulative_value']\n else:\n neg_count += 1\n neg_x_sum += row['new_index']\n neg_y_sum += row['accumulative_value']\n\n # ax_pct + b2 = y_pct\n print(f\"a: {est.params.new_index}\")\n print(f\"b: {est.params.const}\")\n print(f\"pos_count: {pos_count}\")\n print(f\"neg_count: {neg_count}\")\n pct_80_x = pos_x_sum / pos_count\n pct_80_y = pos_y_sum / pos_count\n pct_20_x = neg_x_sum / neg_count\n pct_20_y = neg_y_sum / neg_count\n print(f\"pct_80_x: {pct_80_x}\")\n print(f\"pct_80_y: {pct_80_y}\")\n print(f\"pct_20_x: {pct_20_x}\")\n print(f\"pct_20_y: {pct_20_y}\")\n\n b_80 = pct_80_y - pct_80_x * est.params.new_index\n b_80_delta = b_80 - est.params.const\n b_20 = pct_20_y - pct_20_x * est.params.new_index\n b_20_delta = b_20 - est.params.const\n\n pct_80_line = [(v + b_80_delta) for v in avg_line]\n pct_20_line = [(v + b_20_delta) for v in avg_line]\n\n with open(f\"{abs_path}/../anav_stats/{code}.csv\", 'w') as fp:\n for index, row in df.iterrows():\n date = row['date']\n write_row = \"%s,%.6f,%.6f,%.6f\" % (date,\n avg_line[index],\n pct_80_line[index],\n pct_20_line[index])\n fp.write(write_row + \"\\n\")\n\n\ndef main():\n print(\"hahah\")\n with open(f\"{abs_path}/watch_funds.txt\", \"r\") as fp:\n for line in fp:\n line = line.strip()\n if not line:\n continue\n try:\n cal_tradeline(line)\n except:\n traceback.print_exc()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"fund/tools/tradeline.py","file_name":"tradeline.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"587472476","text":"from PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--image', default=\"\")\nparser.add_argument('--out', default=\"./\")\nparser.add_argument('--num', default=\"3\")\nargs = parser.parse_args()\n\n\ndef crop_thumbnails_16_by_9(img, output):\n w, h = img.size\n new_w = h * 9 // 16\n if new_w * 3 == w:\n pass\n elif new_w * 3 < w:\n x1 = (w - (new_w * 3)) // 2\n y1 = 0\n x2 = x1 + (new_w * 3)\n y2 = h\n img = img.crop((x1, y1, x2, y2))\n else:\n new_h = h * new_w * 3 // w\n img = img.resize((new_w * 3, new_h))\n x1 = 0\n y1 = (new_h - h) // 2\n x2 = x1 + new_w * 3\n y2 = y1 + h\n img = img.crop((x1, y1, x2, y2))\n\n img.save(\"{0}/cropped.png\".format(output))\n \n tw, th = img.width // 3, img.height\n out = []\n for idx in range(3):\n x1 = idx * tw\n y1 = 0\n x2 = x1 + tw\n y2 = y1 + th\n im = img.crop((x1, y1, x2, y2))\n out.append(im)\n\n return out\n\n\ndef main():\n path = args.image\n output = args.out\n img = Image.open(path)\n width, height = img.size\n print(\"image: (w:{0}, h: {1})\".format(width, height))\n out = crop_thumbnails_16_by_9(img, output) \n # font = ImageFont.truetype('./arial.ttf', 80)\n for idx, img in enumerate(out):\n img.save(\"{0}/img_{1}.png\".format(output, idx + 1))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/tools/tiktok/thumbnails.py","file_name":"thumbnails.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"271431066","text":"#!/usr/bin/env python3.6\n\n## Read sam file (R1 and R2)\n# count mutations in sam files\n# output mutation counts\n\nimport pandas as pd\nimport re\nimport os\nimport math\nimport logging\nimport argparse\n# import datetime\nfrom collections import deque\n\n# modules in package\nimport help_functions\nimport locate_mut\n\nclass readSam(object):\n\n def __init__(self, sam_r1, sam_r2, param, args, output_dir):\n \"\"\"\n sam_R1: read one of the sample\n sam_R2: read two of the sample\n\n output_dir: main output directory\n\n log_level: settings for logging\n log_dir: directory to save all the logging for each sample\n \"\"\"\n self._r1 = sam_r1\n self._r2 = sam_r2\n self._project, self._seq, self._cds_seq, self._tile_map, self._region_map, self._samples, self._var = help_functions.parse_json(param)\n\n self._qual = self._var[\"posteriorThreshold\"]\n min_cover = self._var[\"minCover\"]\n self._mutrate = self._var[\"mutRate\"]\n self._output_counts_dir = output_dir\n\n # sample information\n self._sample_id = os.path.basename(sam_r1).split(\"_\")[0]\n self._sample_info = self._samples[self._samples[\"Sample ID\"] == self._sample_id]\n\n # tile information\n # if one sample is with two tiles \n self._sample_tile = self._sample_info[\"Tile ID\"].values[0]\n self._tile_begins = (self._tile_map[self._tile_map[\"Tile Number\"] == self._sample_tile][\"Start AA\"].values[0] *3)-2 # beginning position of this tile (cds position)\n self._tile_ends = self._tile_map[self._tile_map[\"Tile Number\"] == self._sample_tile][\"End AA\"].values[0] *3 # ending position of this tile (cds position)\n self._tile_len = self._tile_ends - self._tile_begins\n self._cds_start = self._seq.cds_start\n self._min_map_len = math.ceil(self._tile_len * float(min_cover))\n\n self._sample_condition = self._sample_info[\"Condition\"].values[0]\n self._sample_tp = self._sample_info[\"Time point\"].values[0]\n self._sample_rep = self._sample_info[\"Replicate\"].values[0]\n\n self._seq_lookup = help_functions.build_lookup(self._cds_start.values.item(), self._seq.cds_end.values.item(), self._cds_seq)\n\n log_f = os.path.join(output_dir, f\"sample_{str(self._sample_id)}_mut_count.log\")\n\n logging.basicConfig(filename=log_f,\n filemode=\"w\",\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n datefmt=\"%m/%d/%Y %I:%M:%S %p\",\n level = args.log_level)\n\n # define a Handler which writes INFO messages or higher to the sys.stderr\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n # set a format which is simpler for console use\n formatter = logging.Formatter('%(name)-8s: %(levelname)-4s %(message)s')\n # tell the handler to use this format\n console.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger('').addHandler(console)\n\n self._sample_counts_f = os.path.join(self._output_counts_dir,f\"counts_sample_{self._sample_id}.csv\")\n\n self._mut_log = logging.getLogger(\"count.mut\")\n self._locate_log = logging.getLogger(\"locate.mut\")\n\n self._mut_log.info(f\"Counting mutations in sample-{self._sample_id}\")\n self._mut_log.info(f\"Sam file input R1:{sam_r1}\")\n self._mut_log.info(f\"Sam file input R2:{sam_r2}\")\n\n output_csv = open(self._sample_counts_f, \"w\")\n # write log information to counts output\n output_csv.write(f\"#Sample:{self._sample_id}\\n#Tile:{self._sample_tile}\\n#Tile Starts:{self._tile_begins}\\n#Tile Ends:{self._tile_ends}\\n#Condition:{self._sample_condition}\\n#Replicate:{self._sample_rep}\\n#Timepoint:{self._sample_tp}\\n#Posterior cutoff:{self._qual}\\n#min cover %:{min_cover}\\n\")\n output_csv.close()\n\n def _merged_main(self):\n \"\"\"\n Read two sam files at the same time, store mutations that passed filter\n \"\"\"\n read_pair = 0 # total pairs\n un_map = 0 # total number of unmapped reads\n read_nomut = 0 # read pairs that have no mutations\n\n hgvs_output = {} # save all the hgvs in this pair of sam files\n off_mut = {} # save all the positions that were mapped but outside of the tile\n row = {} # create a dictionary to save all the reads information to pass on to locate_mut.py\n\n final_pairs = 0\n off_read = 0\n chunkSize = 1500000 # number of characters in each chunk (you will need to adjust this)\n chunk1 = deque([\"\"]) #buffered lines from 1st file\n chunk2 = deque([\"\"]) #buffered lines from 2nd file\n with open(self._r1, \"r\") as r1_f, open(self._r2, \"r\") as r2_f:\n while chunk1 and chunk2:\n line_r1 = chunk1.popleft()\n if not chunk1:\n line_r1,*more = (line_r1+r1_f.read(chunkSize)).split(\"\\n\")\n chunk1.extend(more)\n line_r2 = chunk2.popleft()\n if not chunk2:\n line_r2,*more = (line_r2+r2_f.read(chunkSize)).split(\"\\n\")\n chunk2.extend(more)\n\n if line_r1.startswith(\"@\") or line_r2.startswith(\"@\"): # skip header lines\n continue\n\n line_r1 = line_r1.split()\n line_r2 = line_r2.split()\n if len(line_r1) <= 1:\n continue\n\n read_pair += 1 # count how many read pairs in this pair of sam files\n mapped_name_r1 = line_r1[2]\n mapped_name_r2 = line_r2[2]\n if mapped_name_r1 == \"*\" or mapped_name_r2 == \"*\": # if one of the read didn't map to ref\n un_map +=1\n continue\n\n # check if read ID mapped\n read_name_r1 = line_r1[0]\n read_name_r2 = line_r2[0]\n if read_name_r1 != read_name_r2:\n self._mut_log.error(\"Read pair IDs did not map, please check fastq files\")\n exit(1)\n\n # get starting position for r1 and r2\n pos_start_r1 = line_r1[3]\n pos_start_r2 = line_r2[3]\n # record reads that are not mapped to this tile\n # this is defined as if the read covers at least min_map percent of the tile\n # the default min_map is 70%\n # we also assume that the read len is ALWAYS 150\n r1_end = int(pos_start_r1) + 150\n # r1_end must cover from start of the tile to 70% of the tile\n if (r1_end - int(self._cds_start)) < (int(self._tile_begins) + int(self._min_map_len)):\n off_read += 1\n continue\n if (int(pos_start_r2) - int(self._cds_start)) > (int(self._tile_ends) - int(self._min_map_len)):\n off_read += 1\n continue\n # get CIGAR string\n CIGAR_r1 = line_r1[5]\n seq_r1 = line_r1[9]\n quality_r1 = line_r1[10]\n\n CIGAR_r2 = line_r2[5]\n seq_r2 = line_r2[9]\n quality_r2 = line_r2[10]\n\n mdz_r1 = [i for i in line_r1 if \"MD:Z:\" in i]\n mdz_r2 = [i for i in line_r2 if \"MD:Z:\" in i]\n\n if len(mdz_r1) != 0:\n mdz_r1 = mdz_r1[0].split(\":\")[-1]\n else:\n mdz_r1 = \"\"\n\n if len(mdz_r2) != 0:\n mdz_r2 = mdz_r2[0].split(\":\")[-1]\n else:\n mdz_r2 = \"\"\n\n if ((not re.search('[a-zA-Z]', mdz_r1)) and (\"I\" not in CIGAR_r1)) and ((not re.search('[a-zA-Z]', mdz_r2)) and (\"I\" not in CIGAR_r2)):\n # if MDZ string only contains numbers\n # and no insertions shown in CIGAR string\n # means there is no mutation in this read\n # if both reads have no mutations in them, skip this pair\n read_nomut +=1\n # remove reads that have no mutations in MDZ\n continue\n\n # make the reads in the format of a dictionary\n # columns=[\"mapped_name\", \"pos_start\", \"qual\", \"CIGAR\", \"mdz\",\"seq\"])\n\n #row[\"mapped_name_r1\"] = mapped_name_r1\n row[\"pos_start_r1\"] = pos_start_r1\n row[\"qual_r1\"] = quality_r1\n row[\"cigar_r1\"] = CIGAR_r1\n row[\"mdz_r1\"] = mdz_r1\n row[\"seq_r1\"] = seq_r1\n\n #row[\"mapped_name_r2\"] = mapped_name_r2\n row[\"pos_start_r2\"] = pos_start_r2\n row[\"qual_r2\"] = quality_r2\n row[\"cigar_r2\"] = CIGAR_r2\n row[\"mdz_r2\"] = mdz_r2\n row[\"seq_r2\"] = seq_r2\n\n # pass this dictionary to locate mut\n # mut = locate_mut_main()\n # add mutation to mut list\n mut_parser = locate_mut.MutParser(row, self._seq, self._cds_seq, self._seq_lookup, self._tile_begins, self._tile_ends, self._qual, self._locate_log, self._mutrate)\n hgvs, outside_mut= mut_parser._main()\n if len(hgvs) !=0:\n final_pairs +=1\n if hgvs in hgvs_output:\n hgvs_output[hgvs] += 1\n else:\n hgvs_output[hgvs] = 1\n #hgvs_output.append(hgvs)\n if outside_mut != []:\n outside_mut = list(set(outside_mut))\n for i in outside_mut:\n if not (i in off_mut):\n off_mut[i] = 1\n\n # track mutations that are not within the same tile\n # track sequencing depth for each sample\n # write this information to a tmp file\n # merge the tmp file (in main.py)\n tmp_f = os.path.join(self._output_counts_dir,f\"{self._sample_id}_tmp.csv\")\n off_mut = list(set(off_mut))\n off_mut.sort()\n f = open(tmp_f, \"w\")\n f.write(f\"sample,{self._sample_id},tile,{self._tile_begins}-{self._tile_ends},sequencing_depth,{read_pair},off_tile_reads,{off_read},off_tile_perc,{off_read/read_pair}\\n\")\n f.close()\n\n output_csv = open(self._sample_counts_f, \"a\")\n output_csv.write(f\"#Raw read depth:{read_pair}\\n\")\n output_csv.write(f\"#Number of read pairs without mutations:{read_nomut}\\n#Number of read pairs did not map to gene:{un_map}\\n#Mutation positions outside of the tile:{off_mut}\\n#Number of reads outside of the tile:{off_read}\\n\")\n output_csv.write(f\"#Final read-depth:{read_pair - un_map - off_read}\\n\")\n output_csv.write(f\"#Total read pairs with mutations:{final_pairs}\\n\")\n output_csv.write(f\"#Comment: Total read pairs with mutations = Read pairs with mutations that passed the posterior threshold\\n#Comment: Final read-depth = raw read depth - reads didn't map to gene - reads mapped outside of the tile\\n\")\n\n output_csv.close()\n\n self._mut_log.info(f\"Raw sequencing depth: {read_pair}\")\n self._mut_log.info(f\"Number of reads without mutations:{read_nomut}\")\n self._mut_log.info(f\"Final read-depth: {read_pair - un_map - off_read}\")\n # convert list to df with one col\n hgvs_df = pd.DataFrame.from_dict(hgvs_output, orient=\"index\")\n hgvs_df = hgvs_df.reset_index()\n hgvs_df.columns = [\"HGVS\", \"count\"]\n hgvs_df.to_csv(self._sample_counts_f, mode=\"a\", index=False)\n\n# if __name__ == \"__main__\":\n#\n# parser = argparse.ArgumentParser(description='TileSeq mutation counts (for sam files)')\n# parser.add_argument(\"-r1\", \"--read_1\", help=\"sam file for R1\", required=True)\n# parser.add_argument(\"-r2\", \"--read_2\", help=\"sam file for R2\", required=True)\n# parser.add_argument(\"-qual\", \"--quality\", help=\"quality filter using posterior probability\", default=0.99)\n# parser.add_argument(\"-o\", \"--output\", help=\"Output folder that contains the directory: ./sam_files\", required = True)\n# parser.add_argument(\"-log\", \"--log_level\", help=\"Set log level: debug, info, warning, error, critical.\", default = \"debug\")\n# parser.add_argument(\"-mutlog\", \"--log_dir\", help=\"Directory to save all the log files for each sample\")\n# parser.add_argument(\"-p\", \"--param\", help=\"csv paramter file\", required = True)\n# parser.add_argument(\"-min\", \"--min_cover\", help=\"Minimum percentage required to be covered by reads\", default = 0.4)\n#\n# args = parser.parse_args()\n#\n# sam_r1 = args.read_1\n# sam_r2 = args.read_2\n# qual_filter = float(args.quality)\n# log_dir = args.log_dir\n# min_map = float(args.min_cover)\n#\n# out = args.output\n# param = args.param\n#\n# # conver the csv file to json\n# # csv2json = os.path.abspath(\"src/csv2json.R\")\n# param_json = param.replace(\".csv\", \".json\")\n# #convert = f\"Rscript {csv2json} {param} -o {param_json} -l stdout\"\n# #os.system(convert)\n#\n# # process the json file\n# project, seq, cds_seq, tile_map, region_map, samples = help_functions.parse_json(param_json)\n# # build lookup table\n# lookup_df = help_functions.build_lookup(seq.cds_start.values.item(), seq.cds_end.values.item(), cds_seq)\n#\n# # initialize the object\n# MutCounts = readSam(sam_r1, sam_r2, seq, lookup_df, tile_map, region_map, samples, out, qual_filter, min_map, args.log_level, log_dir)\n#\n# MutCounts._merged_main(seq, cds_seq)\n","sub_path":"build/lib/src/count_mut.py","file_name":"count_mut.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"327433372","text":"# -*- coding: UTF-8 -*-\nimport os\nfrom django.conf import settings\nfrom PIL import Image, ImageEnhance\nfrom cStringIO import StringIO\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\ndef reduce_opacity(img, opacity): \n \"\"\"Returns an image with reduced opacity.\"\"\"\n \n assert opacity >= 0 and opacity <= 1\n if img.mode != 'RGBA':\n img = img.convert('RGBA')\n else:\n img = img.copy()\n alpha = img.split()[3]\n alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n img.putalpha(alpha)\n \n return img\n\ndef watermark(img, mark, size, position='bottom-right', opacity=0.25):\n \n \"\"\"Adds a watermark to an image.\"\"\"\n if opacity < 1:\n mark = reduce_opacity(mark, opacity)\n \n if img.mode != 'RGBA':\n img = img.convert('RGBA')\n \n # create a transparent layer the size of the image and draw the watermark in that layer.\n layer = Image.new('RGBA', img.size, (0, 0, 0, 0))\n if position == 'over':\n for y in xrange(0, img.size[1], mark.size[1]):\n for x in xrange(0, img.size[0], mark.size[0]):\n layer.paste(mark, (x, y))\n elif position == 'title':\n # title, but preserve the aspect ratio\n ratio = min(float(img.size[0]) / mark.size[0], float(img.size[1]) / mark.size[1])\n w = int(mark.size[0] * ratio)\n h = int(mark.size[1] * ratio)\n mark = mark.resize((w, h))\n # layer.paste(mark, ((img.size[0] - w) / 2, (img.size[1] - h) / 2))\n layer.paste(mark, ((img.size[0] - w) / 2, 0))\n elif position == 'center':\n position = ((img.size[0] - mark.size[0]) / 2, (img.size[1] - mark.size[1]) / 2)\n layer.paste(mark, position)\n else: # 'bottom-right' (default)\n margin=0.1\n imgsize=0.4\n resize_ratio = min(min((img.size[i] * (1 - margin * 2)) / mark.size[i] for i in (0,1)) * imgsize, 1)\n wm_size = [int(round(mark.size[i] * resize_ratio)) for i in (0,1)]\n box_end = [int(round(img.size[i] * (1 - margin))) for i in (0,1)]\n box = [(box_end[i] - wm_size[i]) for i in (0,1)]\n box.extend(box_end)\n mark = mark.resize(wm_size, Image.ANTIALIAS)\n img.paste(mark, box, mark)\n return img\n\n \n return Image.composite(layer, img, layer)\n\ndef resizeImage(originalImage, size, imageField, outputField, addwatermark=True):\n if addwatermark == True:\n mark = Image.open(os.path.join(settings.STATIC_ROOT, 'watermark1.png'))\n originalImage = watermark(originalImage, mark, size)\n originalImage.thumbnail(size, Image.ANTIALIAS)\n temp_handle = StringIO()\n originalImage.save(temp_handle, 'png')\n temp_handle.seek(0)\n suf = SimpleUploadedFile(os.path.split(imageField.name)[-1],\n temp_handle.read(),\n content_type='image/png')\n outputField.save(suf.name + '.png', suf, save=False)\n\ndef Imprint(im, watermark, opacity=0.3, margin=0.1, size=0.4):\n \"\"\"\n imprints a PIL image with the indicated image in lower-right corner\n \"\"\"\n if im.mode != \"RGBA\":\n im = im.convert(\"RGBA\")\n wm = Image.open(watermark)\n resize_ratio = min(min((im.size[i] * (1 - margin * 2)) / wm.size[i] for i in (0,1)) * size, 1)\n wm_size = [int(round(wm.size[i] * resize_ratio)) for i in (0,1)]\n box_end = [int(round(im.size[i] * (1 - margin))) for i in (0,1)]\n box = [(box_end[i] - wm_size[i]) for i in (0,1)]\n box.extend(box_end)\n wm = wm.resize(wm_size, Image.ANTIALIAS)\n if opacity != 1:\n wm = reduce_opacity(wm, opacity)\n im.paste(wm, box, wm)\n return im","sub_path":"reproductions/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"477716113","text":"# usr/env/bin Python3.4\r\n# coding:utf-8\r\n\r\n\"\"\"\r\nImport these modules for a good use of the program\r\nArgparse to create a choice for the user\r\nAll the other modules below are used to create a main file\r\n\"\"\"\r\n# Import Lib\r\nimport argparse\r\n\r\n# Import file\r\nfrom Gamemanager import GameManager\r\nfrom Maze import Maze\r\nfrom Gui import Game_GUI\r\n\r\n\r\ndef parser_game():\r\n \"\"\"Create a pars for user choice\"\"\"\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-t\", \"--Terminal\",\r\n action='store_true', help=\"Game in The terminal\")\r\n parser.add_argument(\"-g\", \"--GUI\",\r\n action='store_true', help=\"Game in The GUI\")\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \"\"\"Create a main for run this applications\"\"\"\r\n maze = Maze(\"maze_1.txt\")\r\n args = parser_game()\r\n gamemanager = GameManager(maze)\r\n if args.Terminal:\r\n gamemanager.start_game()\r\n else:\r\n gui = Game_GUI(maze, gamemanager.list_item_class)\r\n gui.on_loop_game()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"218891152","text":"# cnn model\nimport numpy as np\nfrom numpy import mean\nfrom numpy import std\nfrom numpy import dstack\nfrom pandas import read_csv\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Flatten, Convolution1D, Dropout,MaxPooling1D\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\nfrom keras.utils import to_categorical\nfrom matplotlib import pyplot\nimport os\n\n\n\n'''\n一个cnn的模型,未完成\n'''\n\n# load a single file as a numpy array\ndef load_file(filepath):\n print(\"Start load_file\")\n dataframe = read_csv(filepath, header=None)\n print(\"Finish load_file\")\n return dataframe.values\n\n\ndata_max = -1\ndata_min = -1\n\n\n# 用于三个维度的归一化\ndef normalization(data):\n global data_min\n global data_max\n if data_max == -1:\n data_min = np.min(data)\n data_max = np.max(data)\n _range = data_max - data_min\n return (data - data_min) / _range\n\n\n# load a list of files and return as a 3d numpy array\ndef load_group(filenames, filepath):\n print(\"Start load_group\")\n loaded = list()\n for name in filenames:\n data = load_file(filepath + name)\n loaded.append(data)\n # stack group so that features are the 3rd dimension\n loaded = dstack(loaded)\n print(\"Finish load_group\")\n return loaded\n\n\n# load a dataset group, such as train or test\ndef load_dataset_group(filepath):\n print(\"Start load_dataset_group\")\n # load all 9 files as a single array\n filenames = os.listdir(filepath)\n del filenames[filenames.index('y.csv')]\n X = load_group(filenames, filepath)\n # load class output\n y = load_file(filepath + 'y.csv')\n print(\"Finish load_dataset_group\")\n return X, y\n\n\n# load the dataset, returns train and test X and y elements\ndef load_dataset(filepath):\n print(\"Start load_dataset\")\n # load all train\n trainX, trainy = load_dataset_group(filepath + 'train/')\n\n testX, testy = load_dataset_group(filepath + 'test/')\n\n trainy = to_categorical(trainy)\n testy = to_categorical(testy)\n return trainX, trainy, testX, testy\n\n\n# fit and evaluate a cnn model\ndef evaluate_model(trainX, trainy, testX, testy,i):\n print(\"Start evaluate_model\")\n verbose, epochs, batch_size = 1, 30, 64\n n_timesteps, n_features, n_outputs = trainX.shape[1], trainX.shape[2], trainy.shape[1]\n model = Sequential()\n\n # 后续在输入格式\n model = Sequential()\n model.add(Convolution1D(nb_filter=50, kernel_size=(1,5),activation='linear',filter_length=1, input_shape=(n_timesteps, n_features)))\n model.add(Convolution1D(nb_filter=20, kernel_size=(1,3),activation='linear',filter_length=1, input_shape=(n_timesteps, n_features)))\n model.add(MaxPooling1D(pool_size=(2, 1)))\n model.add(Activation('relu'))\n model.add(Dense(96))\n model.add(Dense(96))\n model.add(Activation('sigmod'))\n\n model.add(Dense(3))\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n # fit network\n model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=verbose)\n # evaluate model\n _, accuracy = model.evaluate(testX, testy, batch_size=batch_size, verbose=verbose)\n print()\n print(i)\n model.save('model/model_'+str(i)+'.h5')\n print(\"Finish evaluate_model\")\n return accuracy\n\n\n# summarize scores\ndef summarize_results(scores):\n print(\"Start summarize_results\")\n print(scores)\n m, s = mean(scores), std(scores)\n print('Accuracy: %.3f%% (+/-%.3f)' % (m, s))\n print(\"Finish summarize_results\")\n\n\n# run an experiment\ndef run_experiment(filepath, repeats=8):\n # load data\n print(\"Start run_experiment\")\n trainX, trainy, testX, testy = load_dataset(filepath)\n # repeat experiment\n scores = list()\n i=0\n for r in range(repeats):\n score = evaluate_model(trainX, trainy, testX, testy,i)\n i+=1\n score = score * 100.0\n print('>#%d: %.3f' % (r + 1, score))\n scores.append(score)\n # summarize results\n summarize_results(scores)\n print(\"Finish run_experiment\")\n\n\n# run the experiment\nfilepath = '/home/rbai/eeg_lstm_0706/data/'\nrun_experiment(filepath)\n","sub_path":"cnn&&lstm_old/eeg_cnn.py","file_name":"eeg_cnn.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"473787458","text":"from setuptools import setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nexec(open('tubedreams/version.py').read())\n\nsetup(\n name='tubedreams',\n version=__version__,\n description='create dream-sequences from your video browsing history',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/hdbhdb/tubedreams\",\n author='Hudson Bailey',\n author_email='hudsondiggsbailey@gmail.com',\n license='MIT',\n packages=['tubedreams'],\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ),\n install_requires=[\n 'sox>=1.3.3',\n 'youtube_dl>=2018.5.18',\n 'ez_setup>=0.9',\n 'moviepy>=0.2.3.5',\n ],\n scripts=['bin/tubedreams'],\n zip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"456596947","text":"from django.views.generic import ListView\nfrom django.core import serializers\nfrom django.http import HttpResponse\nfrom utils.models import StateList\nfrom utils.log_helper import init_logger\n\nlogger = init_logger(__file__)\n\n# Get country ID, fetch state list for that country. if no state is found, for a company return blank.\n# ON JS page, then we will change the field type to be a text field. This is called dynamically via Ajax\nclass GetStateList(ListView):\n def get(self, request, *args, **kwargs):\n try:\n country_id = request.GET['country_id']\n if country_id:\n state_list = serializers.serialize('json',\n StateList.objects.filter(state_country=country_id).order_by('id'))\n else:\n state_list = \"\"\n return HttpResponse(state_list)\n except Exception as e:\n logger.error(\"Exception while fetching state list: \" + str(e))\n","sub_path":"utils/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"406915367","text":"# working_file\n\nfrom heospy import ssdp\nimport re\nimport telnetlib\nimport logging\nimport json\n\nURN_SCHEMA = \"urn:schemas-denon-com:device:ACT-Denon:1\"\nplayer_name = 'HEOS'\nheosurl = 'heos://'\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef telnet_request(command, wait=True):\n \"\"\"Execute a `command` and return the response(s).\"\"\"\n command = heosurl + command\n logging.debug(\"telnet request {}\".format(command))\n telnet.write(command.encode('ascii') + b'\\n')\n response = b''\n logging.debug(\"starting response loop\")\n while True:\n response += telnet.read_some()\n try:\n response = json.loads(response.decode(\"utf-8\"))\n logging.debug(\"found valid JSON: {}\".format(json.dumps(response)))\n if not wait:\n logging.debug(\n \"I accept the first response: {}\".format(response))\n break\n # sometimes, I get a response with the message \"under\n # process\". I might want to wait here\n message = response.get(\"heos\", {}).get(\"message\", \"\")\n if \"command under process\" not in message:\n logging.debug(\n \"I assume this is the final response: {}\".format(response))\n break\n logging.debug(\"Wait for the final response\")\n response = b'' # forget this message\n except ValueError:\n logging.debug(\"... unfinished response: {}\".format(response))\n # response is not a complete JSON object\n pass\n except TypeError:\n logging.debug(\"... unfinished response: {}\".format(response))\n # response is not a complete JSON object\n pass\n\n if response.get(\"result\") == \"fail\":\n logging.warn(response)\n return None\n\n logging.debug(\"found valid response: {}\".format(json.dumps(response)))\n return response\n\n\ndef _get_player(name):\n response = telnet_request(\"player/get_players\")\n if response.get(\"payload\") is None:\n return None\n for player in response.get(\"payload\"):\n logging.debug(u\"found '{}', looking for '{}'\".format(\n player.get(\"name\"), name))\n if player.get(\"name\") == name:\n return player.get(\"pid\")\n return None\n\n\nssdp_list = ssdp.discover(URN_SCHEMA)\nresponse = ssdp_list[0]\n\nif (response.st == URN_SCHEMA):\n host = re.match(r\"http:..([^\\:]+):\", response.location).group(1)\n telnet = telnetlib.Telnet(host, 1255)\n pid = _get_player(player_name)\n print(host, telnet, pid)\n# logging.debug(host, telnet, pid)\n\ntelnet_request(\"heos://player/get_players\")\ntelnet_request(\"system/heart_beat\")\n","sub_path":"heospy/working_file.py","file_name":"working_file.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"38584978","text":"__author__ = 'thiagocastroferreira'\n\n\"\"\"\nAuthor: Thiago Castro Ferreira\nDate: 28/02/2019\nDescription:\n This script aims to extract the gold-standard structured triple sets for the Text Structuring step.\n\n ARGS:\n [1] Path to the folder where WebNLG corpus is available (versions/v1.0/en)\n [2] Path to the folder where the data will be saved (Folder will be created in case it does not exist)\n [3] Path to the StanfordCoreNLP software (https://stanfordnlp.github.io/CoreNLP/)\n\n EXAMPLE:\n python3 preprocess_acl_webnlg.py ../webnlg/v1.0/en/\n\"\"\"\n\nimport copy\nimport json\nimport os\nimport re\nimport sys\nimport pickle\nimport xml.etree.ElementTree as ET\nfrom deepnlg import parsing as parser\nfrom deepnlg.lexicalization.preprocess import TemplateExtraction\nfrom stanfordcorenlp import StanfordCoreNLP\n\nsys.path.append('./')\nsys.path.append('../')\nre_date = '([0-9]{4})-([0-9]{2})-([0-9]{2})'\nre_tag = re.compile(r\"((AGENT|PATIENT|BRIDGE)\\-\\d{1})\")\n\n\ndef extract_entity_type(entity):\n aux = entity.split('^^')\n if len(aux) > 1:\n return aux[-1]\n\n aux = entity.split('@')\n if len(aux) > 1:\n return aux[-1]\n\n return 'wiki'\n\n\ndef classify(references):\n references = sorted(references, key=lambda x: (x['entity'], x['sentence'], x['pos']))\n\n sentence_statuses = {}\n for i, reference in enumerate(references):\n # text status\n if i == 0 or (reference['entity'] != references[i - 1]['entity']):\n reference['text_status'] = 'new'\n else:\n reference['text_status'] = 'given'\n\n if reference['sentence'] not in sentence_statuses:\n sentence_statuses[reference['sentence']] = []\n\n # sentence status\n if reference['entity'] not in sentence_statuses[reference['sentence']]:\n reference['sentence_status'] = 'new'\n else:\n reference['sentence_status'] = 'given'\n\n sentence_statuses[reference['sentence']].append(reference['entity'])\n\n # referential form\n reg = reference['refex'].replace('eos', '').strip()\n reference['reftype'] = 'name'\n if reg.lower().strip() in ['he', 'his', 'him', 'she', 'hers', 'her', 'it', 'its', 'we', 'our', 'ours',\n 'they', 'theirs', 'them']:\n reference['reftype'] = 'pronoun'\n elif reg.lower().strip().split()[0] in ['the', 'a', 'an']:\n reference['reftype'] = 'description'\n elif reg.lower().strip().split()[0] in ['this', 'these', 'that', 'those']:\n reference['reftype'] = 'demonstrative'\n\n return references\n\n\ndef load(pre_context_file, pos_context_file, entity_file, refex_file, size_file, info_file, data_file,\n original_file=''):\n original_data = []\n with open(pre_context_file) as f:\n pre_context = map(lambda x: x.split(), f.read().split('\\n'))\n\n with open(pos_context_file) as f:\n pos_context = map(lambda x: x.split(), f.read().split('\\n'))\n\n with open(entity_file) as f:\n entity = f.read().split('\\n')\n\n with open(refex_file) as f:\n refex = map(lambda x: x.split(), f.read().split('\\n'))\n\n with open(size_file) as f:\n size = f.read().split('\\n')\n\n with open(info_file) as f:\n info = f.read().split('\\n')\n\n if original_file != '':\n original_data = json.load(open(original_file, encoding='utf-8'))\n\n with open(data_file, 'rb') as file:\n data = pickle.load(file)\n\n data = extend_data(data, info, original_data)\n\n return {\n 'pre_context': list(pre_context),\n 'pos_context': list(pos_context),\n 'entity': list(entity),\n 'refex': list(refex),\n 'size': list(size),\n 'data': list(data),\n 'original': list(original_data)\n }\n\n\ndef extend_data(data_set, data_info, original_data):\n # Get ordered entities\n text_ids = sorted(list(set(map(lambda x: x['text_id'], data_set))))\n new_set = []\n for i, text_id in enumerate(text_ids):\n references = filter(lambda x: x['text_id'] == text_id, data_set)\n references = sorted(references, key=lambda x: x['text_id'])\n\n for r, reference in enumerate(references):\n idx_info = len(reference.keys()) * (r + 1)\n reference['eid'] = 'Id' + str(text_id)\n _, xml_file = data_info[idx_info].split(' ')\n reference['info_category'] = xml_file.replace('.xml', '')\n reference['category'] = ''\n\n # find reference in train\n if len(original_data) > 0:\n original_entries = list(filter(lambda o: o['entity'] == reference['entity'] and\n o['syntax'] == reference['syntax'] and\n o['size'] == reference['size'] and\n (o['text'] == reference['text'] or\n o['pre_context'] == reference['pre_context'] or\n o['pos_context'] == reference['pos_context'] or\n o['refex'] == reference['refex'] or\n o['text_status'] == reference['text_status'] or\n o['sentence_status'] == reference['sentence_status']),\n original_data))\n if len(original_entries) == 0:\n original_entries = list(filter(lambda o: o['entity'] == reference['entity'], original_data))\n if len(original_entries) == 0:\n print('Category not found for Entity :', reference['entity'])\n\n if len(original_entries) > 0:\n categories = list(set([e['category'] for e in original_entries]))\n if len(categories) > 1:\n print('More than one category to entity: ', reference['entity'])\n reference['category'] = categories[0]\n\n new_set.append(reference)\n\n return new_set\n\n\ndef load_data(entry_path, original_path):\n fprecontext = os.path.join(entry_path, 'pre_context.txt')\n fposcontext = os.path.join(entry_path, 'pos_context.txt')\n fentity = os.path.join(entry_path, 'entity.txt')\n frefex = os.path.join(entry_path, 'refex.txt')\n fsize = os.path.join(entry_path, 'size.txt')\n finfo = os.path.join(entry_path, 'info.txt')\n fdata = os.path.join(entry_path, 'data.cPickle')\n if original_path != '':\n foriginal = os.path.join(original_path, 'data.json')\n data_set = load(fprecontext, fposcontext, fentity, frefex, fsize, finfo, fdata, foriginal)\n return data_set\n\n\nclass REGPrecACL:\n def __init__(self, data_path, write_path, stanford_path):\n self.data_path = data_path\n self.write_path = write_path\n\n self.temp_extractor = TemplateExtraction(stanford_path)\n self.corenlp = StanfordCoreNLP(stanford_path)\n\n self.traindata, self.vocab = self.process(entry_path=os.path.join(data_path, 'train'))\n self.testdata, _ = self.process(entry_path=os.path.join(data_path, 'test'))\n\n self.corenlp.close()\n self.temp_extractor.close()\n\n json.dump(self.traindata, open(os.path.join(write_path, 'train.json'), 'w'))\n json.dump(self.vocab, open(os.path.join(write_path, 'vocab.json'), 'w'))\n json.dump(self.testdata, open(os.path.join(write_path, 'test.json'), 'w'))\n\n def process(self, entry_path):\n data, in_vocab, out_vocab = self.run_parser(entry_path)\n\n in_vocab.add('unk')\n out_vocab.add('unk')\n in_vocab.add('eos')\n out_vocab.add('eos')\n\n in_vocab = list(set(in_vocab))\n out_vocab = list(set(out_vocab))\n vocab = {'input': in_vocab, 'output': out_vocab}\n\n print('Path:', entry_path, 'Size: ', len(data))\n return data, vocab\n\n def run_parser(self, set_path):\n entryset, input_vocab, output_vocab = [], set(), set()\n dirtriples = filter(lambda item: not str(item).startswith('.'), os.listdir(set_path))\n for dirtriple in dirtriples:\n fcategories = filter(lambda item: not str(item).startswith('.'),\n os.listdir(os.path.join(set_path, dirtriple)))\n for fcategory in fcategories:\n references, ref_in_vocab, ref_out_vocab = self.parse(os.path.join(set_path, dirtriple, fcategory))\n entryset.extend(references)\n input_vocab = input_vocab.union(ref_in_vocab)\n output_vocab = output_vocab.union(ref_out_vocab)\n\n return entryset, input_vocab, output_vocab\n\n def parse(self, in_file):\n tree = ET.parse(in_file)\n root = tree.getroot()\n\n data = []\n input_vocab, output_vocab = set(), set()\n\n entries = root.find('entries')\n\n for entry in entries:\n eid = entry.attrib['eid']\n size = entry.attrib['size']\n category = entry.attrib['category']\n\n # get entity map\n entitymap_xml = entry.find('entitymap')\n entity_map = {}\n for entitytag in entitymap_xml:\n tag, entity = entitytag.text.split(' | ')\n entity_map[tag] = entity\n\n # Reading original triples to extract the entities type\n types = []\n originaltripleset = entry.find('originaltripleset')\n for otriple in originaltripleset:\n e1, pred, e2 = otriple.text.split(' | ')\n entity1_type = extract_entity_type(e1.strip())\n entity2_type = extract_entity_type(e2.strip())\n types.append({'e1_type': entity1_type, 'e2_type': entity2_type})\n\n entity_type = {}\n modifiedtripleset = entry.find('modifiedtripleset')\n for i, mtriple in enumerate(modifiedtripleset):\n e1, pred, e2 = mtriple.text.split(' | ')\n entity_type[e1.replace('\\'', '')] = types[i]['e1_type']\n entity_type[e2.replace('\\'', '')] = types[i]['e2_type']\n\n lexList = []\n lexEntries = entry.findall('lex')\n for lex in lexEntries:\n try:\n text = lex.find('text').text\n template = lex.find('template').text\n\n if template:\n # print('{}\\r'.format(template))\n\n text = self.tokenize(text)\n text = ' '.join(text).strip()\n\n template = self.tokenize(template)\n template = ' '.join(template).strip()\n\n references, in_vocab, out_vocab = self.get_references(text, template,\n entity_map, entity_type,\n category, in_file)\n\n data.extend(references)\n input_vocab = input_vocab.union(in_vocab)\n output_vocab = output_vocab.union(out_vocab)\n except:\n print(\"Parsing error: \", sys.exc_info()[0])\n\n return data, input_vocab, output_vocab\n\n def get_references(self, text, template, entity_map, entity_type, category, filename):\n context = copy.copy(template)\n references, input_vocab, output_vocab = [], set(), set()\n\n isOver = False\n while not isOver:\n pre_tag, tag, pos_tag = self.process_template(template)\n pre_context, pos_context = self.process_context(context, entity_map)\n\n if tag == '':\n isOver = True\n else:\n # Look for reference from 5-gram to 2-gram\n i, f = 5, []\n try:\n while i > 1:\n begin = ' '.join(i * ['BEGIN'])\n text = begin + ' ' + text\n template = begin + ' ' + template\n pre_tag, tag, pos_tag = self.process_template(template)\n\n regex = re.escape(' '.join(pre_tag[-i:]).strip()) + ' (.+?) ' + re.escape(\n ' '.join(pos_tag[:i]).strip())\n f = re.findall(regex, text)\n\n template = template.replace('BEGIN', '').strip()\n text = text.replace('BEGIN', '').strip()\n i -= 1\n\n if len(f) == 1:\n break\n\n if len(f) > 0:\n # DO NOT LOWER CASE HERE!!!!!!\n template = template.replace(tag, f[0], 1)\n refex = self.tokenize(f[0])\n refex = ' '.join(refex).strip()\n\n # Do not include literals\n entity = entity_map[tag]\n\n if entity_type[entity] == 'wiki':\n refex = refex.replace('eos', '').split()\n\n normalized = '_'.join(entity.replace('\\\"', '').replace('\\'', '').lower().split())\n # aux = context.replace(tag, 'ENTITY', 1)\n # reference_info = self.process_reference_info(aux, 'ENTITY')\n\n if normalized != '':\n isDigit = normalized.replace('.', '').strip().isdigit()\n isDate = len(re.findall(re_date, normalized)) > 0\n if normalized[0] not in ['\\'', '\\\"'] and not isDigit and not isDate:\n mapped_reference = {\n 'entity': normalized,\n 'category': category,\n 'pre_context': pre_context.replace('@', '').replace('eos', '').split(),\n 'pos_context': pos_context.replace('@', '').replace('eos', '').split(),\n 'refex': refex\n # 'size': len(entity_map.keys()),\n # 'syntax': reference_info['syntax'],\n # 'general_pos': reference_info['general_pos'],\n # 'sentence': reference_info['sentence'],\n # 'pos': reference_info['pos'],\n # 'text': text,\n # 'filename': filename,\n }\n references.append(mapped_reference)\n\n output_vocab = output_vocab.union(set(refex))\n input_vocab = input_vocab.union(set(pre_context.split()))\n input_vocab = input_vocab.union(set(pos_context.split()))\n input_vocab = input_vocab.union(set([normalized]))\n\n context = context.replace(tag, normalized, 1)\n else:\n print('Not normalized entity: ', normalized)\n else:\n context = context.replace(tag, '_'.join(\n entity_map[tag].replace('\\\"', '').replace('\\'', '').lower().split()), 1)\n else:\n template = template.replace(tag, ' ', 1)\n context = context.replace(tag, '_'.join(\n entity_map[tag].replace('\\\"', '').replace('\\'', '').lower().split()), 1)\n except:\n print(\"Parsing error (Processing template): \", sys.exc_info()[0])\n\n # references = classify(references)\n\n return references, input_vocab, output_vocab\n\n def process_template(self, text):\n template = text.split()\n\n tag = ''\n pre_tag, pos_tag, i = [], [], 0\n try:\n for token in template:\n i += 1\n token_tag = re.search(re_tag, token)\n\n if token_tag:\n if token != token_tag.group():\n print('Token error: ', token)\n\n tag = token_tag.group()\n for pos_token in template[i:]:\n pos_token_tag = re.search(re_tag, pos_token)\n\n if pos_token_tag:\n break\n else:\n pos_tag.append(pos_token)\n break\n else:\n pre_tag.append(token)\n except:\n print(\"Parsing error (processing template): \", sys.exc_info()[0])\n\n return pre_tag, tag, pos_tag\n\n def process_context(self, text, entity_map):\n context = text.split()\n pre_context, pos_context, i = [], [], 0\n try:\n for token in context:\n i += 1\n\n token_tag = re.search(re_tag, token)\n if token_tag:\n pos_context = context[i:]\n break\n else:\n pre_context.append(token)\n\n pre_context = ' '.join(['eos'] + pre_context)\n pos_context = ' '.join(pos_context + ['eos'])\n for tag in entity_map:\n pre_context = pre_context.replace(tag, '_'.join(\n entity_map[tag].replace('\\\"', '').replace('\\'', '').lower().split()))\n pos_context = pos_context.replace(tag, '_'.join(\n entity_map[tag].replace('\\\"', '').replace('\\'', '').lower().split()))\n except:\n print(\"Parsing error (processing context): \", sys.exc_info()[0])\n\n return pre_context.lower(), pos_context.lower()\n\n def process_reference_info(self, template, tag):\n props = {'annotators': 'tokenize,ssplit,pos,depparse', 'pipelineLanguage': 'en', 'outputFormat': 'json'}\n\n out = self.corenlp.annotate(template.strip(), properties=props)\n out = json.loads(out)\n\n reference = {'syntax': '', 'sentence': -1, 'pos': -1, 'general_pos': -1, 'tag': tag}\n general_pos = 0\n for i, snt in enumerate(out['sentences']):\n for token in snt['enhancedDependencies']:\n # get syntax\n if token['dependentGloss'] == tag:\n reference = {'syntax': '', 'sentence': i, 'pos': int(token['dependent']),\n 'general_pos': general_pos + int(token['dependent']), 'tag': tag}\n if 'nsubj' in token['dep'] or 'nsubjpass' in token['dep']:\n reference['syntax'] = 'np-subj'\n elif 'nmod:poss' in token['dep'] or 'compound' in token['dep']:\n reference['syntax'] = 'subj-det'\n else:\n reference['syntax'] = 'np-obj'\n break\n general_pos += len(snt['tokens'])\n return reference\n\n def tokenize(self, text):\n props = {'annotators': 'tokenize,ssplit', 'pipelineLanguage': 'en', 'outputFormat': 'json'}\n text = text.replace('@', ' ')\n tokens = []\n # tokenizing text\n try:\n out = self.corenlp.annotate(text.strip(), properties=props)\n out = json.loads(out)\n\n for snt in out['sentences']:\n sentence = list(map(lambda w: w['originalText'], snt['tokens']))\n tokens.extend(sentence)\n except:\n print('Parsing error (tokenize):', sys.exc_info()[0])\n\n return tokens\n\n\nif __name__ == '__main__':\n # data_path = '/webnlg/data/v1.0/en'\n # write_path = '/data/v1.0'\n # stanford_path = r'/stanford/stanford-corenlp-full-2018-10-05'\n\n data_path = sys.argv[1]\n write_path = sys.argv[2]\n stanford_path = sys.argv[3]\n s = REGPrecACL(data_path=data_path, write_path=write_path, stanford_path=stanford_path)\n","sub_path":"deepnlg/preprocess_acl_webnlg.py","file_name":"preprocess_acl_webnlg.py","file_ext":"py","file_size_in_byte":20231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"314462631","text":"from kaggle_environments import make\nfrom geese.heuristic_agents import GreedyAgent, SuperGreedyAgent\nfrom geese.dqn import dqnAgent\nfrom geese.dqn_embeddings import dqnEmbeddings\nimport pickle, os\nfrom tensorflow import keras\nfrom copy import deepcopy\nfrom geese.StateTranslator import StateTranslator_TerminalRewards\n\nimport tensorflow as tf\nsess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))\n\nsteps_per_ep = 200\nnum_episodes = 10000\n\nenv = make(\"hungry_geese\", debug=True)\nconfig = env.configuration\nmodel_dir = 'Models'\ntrain_name = 'emb_test_cpu2'\ndirectory = os.sep.join([model_dir, train_name])\n\nmod_num = 0 # Which trial to load\n# state_translator = StateTranslator_TerminalRewards()\nepsilon = .98\nepsilon_min = 0.05\n\nif mod_num > 0:\n model = keras.models.load_model(f'{directory}/trial-{mod_num}')\n dqn_emb = dqnEmbeddings(model=model,\n epsilon=epsilon,\n epsilon_min=epsilon_min)\n\n dqn_emb.target_model = model\n\nelse:\n dqn_emb = dqnEmbeddings(epsilon=epsilon,\n epsilon_min=epsilon_min)\n\nmodel_competitor = keras.models.load_model(f'Models/terminal_transfer_learning/trial-12000')\n\n# Want a little epsilon to add some variablitity to actions so we don't overfit on this opponent\ndqn_competitor = dqnAgent(model=model_competitor,\n epsilon=0,\n epsilon_min=0)\n\nagent3 = SuperGreedyAgent()\nagent4 = GreedyAgent()\n\nagents = [dqn_emb, dqn_competitor, agent3, agent4]\n\nresults_dic = {}\nwins = 0\nfor ep in range(num_episodes):\n print('episode number: ', ep+mod_num)\n state_dict = env.reset(num_agents=4)[0]\n observation = state_dict['observation']\n my_goose_ind = observation['index']\n\n dqn_emb.StateTrans.set_last_action(None)\n dqn_emb.StateTrans.last_goose_length = 1\n cur_state = dqn_emb.StateTrans.get_state(observation, config)\n\n done = False\n for step in range(steps_per_ep):\n actions = []\n for ind, agent in enumerate(agents):\n obs_copy = deepcopy(observation)\n obs_copy['index'] = ind\n action = agent(obs_copy, config)\n actions.append(action)\n\n state_dict = env.step(actions)[0]\n observation = state_dict['observation']\n\n action = state_dict['action']\n status = state_dict['status']\n\n action_for_model = dqn_emb.StateTrans.translate_text_to_int(action)\n new_state = dqn_emb.StateTrans.get_state(observation, config)\n\n # Set rewards based on if value was gained or lost\n reward = dqn_emb.StateTrans.calculate_reward(observation)\n if reward > 100:\n wins += 1\n # Update our goose length based on prev state\n dqn_emb.StateTrans.update_length()\n\n if status != \"ACTIVE\":\n done = True\n\n dqn_emb.remember(cur_state, action_for_model, reward, new_state, done)\n\n cur_state = new_state\n\n # Check if my goose died\n\n if done:\n print('Done, Step: ', step)\n print('status, ', status)\n print('Reward: ', reward)\n print('Trial: ', ep)\n results_dic[ep] = reward\n\n if ep % 50 == 0:\n dqn_emb.save_model(directory + f\"/trial-{ep + mod_num}\")\n with open(directory + \"/results_dic.pkl\", 'wb') as f:\n pickle.dump(results_dic, f)\n\n # Have we won at least 22 of our last 50 games? Then we update the competitor model\n print('win percentage: ', wins/50)\n if wins > 22:\n print('Updating competitor model')\n # I'm scared of using the same instance of the model in two seperate classes... deepcopy didn't work so\n # I'll just use this fix for now\n model1 = keras.models.load_model(f'{directory}/trial-{ep + mod_num}')\n dqn_competitor.model = model1\n wins = 0\n break\n\n\n if step % 5 == 0:\n dqn_emb.replay()\n dqn_emb.target_train()\n\n # Every 250 steps, we update the competitor model to not overfit to one agents strats\n","sub_path":"train-gpu.py","file_name":"train-gpu.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"353221441","text":"import datetime\r\nimport json\r\nimport platform\r\nimport sys\r\nimport discord\r\nimport traceback\r\nfrom discord.ext import commands\r\nimport logging\r\nfrom pathlib import Path\r\nimport youtube_dl\r\n\r\n\r\ndef get_prefix(client, message):\r\n with open('Json_Files/prefixes.json', 'r') as f:\r\n prefixes = json.load(f)\r\n return prefixes[str(message.guild.id)]\r\n\r\n\r\nclient = commands.Bot(command_prefix=get_prefix)\r\n\r\n# Removing a Cog from here will leave it unloaded!\r\ninitial_extensions = 'Cogs.Snipe', 'Cogs.Evaluation', 'Cogs.OwnerCog', 'Cogs.HelpCog', 'Cogs.ErrorCog', 'Cogs.ModCog', \\\r\n 'Cogs.FunCog', 'Cogs.Invites', 'Cogs.PublicCog', 'Cogs.Leveling', 'Cogs.Youtube'\r\n\r\nclient.blacklisted_users = []\r\nplayers = {}\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=\"youtube\"))\r\n data = read_json(\"blacklist\")\r\n client.blacklisted_users = data[\"blacklistedUsers\"]\r\n print(f'Bot has connected.\\nLogged in as {client.user.name} : {client.user.id}. Prefix is d!')\r\n\r\n\r\nclient.help_command = None\r\n\r\nif __name__ == '__main__':\r\n for extension in initial_extensions:\r\n try:\r\n client.load_extension(extension)\r\n except Exception as e:\r\n print(f'Failed to load extension {extension}', file=sys.stderr)\r\n traceback.print_exc()\r\n\r\ncwd = Path(__file__).parents[0]\r\ncwd = str(cwd)\r\n\r\n\r\n@client.command(aliases=['changestatus', 'renamestatus'])\r\nasync def status(ctx, *, message):\r\n if ctx.message.author.id == 356472972657295390:\r\n await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=message))\r\n embed = discord.Embed(title=\"**Status**\",\r\n description=('{}'.format(\"Status was changed to `{}`\".format(message))),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n else:\r\n errormsg = 'You are not a developer!'\r\n embed = discord.Embed(title=\"**Error**\",\r\n description=('{}'.format(errormsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\ncommands.version = '`v2.4`'\r\n\r\n\r\n@client.command(aliases=['bi', 'botinfo', 'botstats', 'bot'])\r\nasync def stats(ctx):\r\n pythonVersion = platform.python_version()\r\n dpyVersion = discord.__version__\r\n serverCount = len(client.guilds)\r\n memberCount = len(set(client.get_all_members()))\r\n\r\n embed = discord.Embed(title=f'{client.user.name} Stats', description='\\uFEFF', color=discord.Colour.blue(),\r\n timestamp=ctx.message.created_at)\r\n embed.add_field(name='Bot Version:', value=commands.version)\r\n embed.add_field(name='Python Version:', value=f'`{pythonVersion}`')\r\n embed.add_field(name='Library:', value='`Discord.py`')\r\n embed.add_field(name='Discord.py Version', value=f'`{dpyVersion}`')\r\n embed.add_field(name='Total Server:', value=f'`{serverCount}`')\r\n embed.add_field(name='Total Users:', value=f'`{memberCount}`')\r\n embed.add_field(name='Bot Developer:', value=\"<@356472972657295390>\")\r\n\r\n embed.set_footer(text=f\"Created by xIntensity#4217 | {client.user.name}\")\r\n embed.set_author(name=client.user.name, icon_url=client.user.avatar_url)\r\n embed.timestamp = datetime.datetime.utcnow()\r\n\r\n await ctx.send(embed=embed)\r\n\r\n\r\n# Music\r\n\r\n@client.command(pass_context=True)\r\nasync def join(ctx):\r\n channel = ctx.message.author.voice.voice_channel\r\n await client.join_voice_channel(channel)\r\n\r\n\r\n@client.command(pass_context=True)\r\nasync def leave(ctx):\r\n server = ctx.message.server\r\n voice_client = client.voice_client_in(server)\r\n await voice_client.disconnect()\r\n\r\n\r\n@client.command(pass_contect=True)\r\nasync def play(ctx, url):\r\n server = ctx.message.server\r\n voice_client = client.voice_client_in(server)\r\n player = await voice_client.create_ytdl_player(url)\r\n players[server.id] = player\r\n player.start()\r\n\r\n\r\n# blacklist\r\n\r\n@client.event\r\nasync def on_message(message):\r\n # ignore ourselves\r\n if message.author.id == client.user.id:\r\n return\r\n\r\n # blacklist system\r\n if message.author.id in client.blacklisted_users:\r\n return\r\n\r\n if message.content.lower().startswith(\"help\"):\r\n embed = discord.Embed(title=\"**Help**\",\r\n description=(\"You can run the help command with d!help!\"),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await message.channel.send(embed=embed)\r\n\r\n await client.process_commands(message)\r\n\r\n\r\n@client.command()\r\nasync def blacklist(ctx, user: discord.Member):\r\n if ctx.message.author.id == user.id:\r\n embed = discord.Embed(title=\"**Error**\",\r\n description=('{}'.format(\"You can't blacklist yourself.\")),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n return\r\n\r\n if ctx.message.author.id == 356472972657295390:\r\n client.blacklisted_users.append(user.id)\r\n data = read_json(\"blacklist\")\r\n data[\"blacklistedUsers\"].append(user.id)\r\n write_json(data, \"blacklist\")\r\n message = f\"{user.name} has been blacklisted from using Ice's commands!\"\r\n embed = discord.Embed(title=\"**Blacklist**\",\r\n description=('{}'.format(message)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n else:\r\n errormsg = 'You are not the owner...'\r\n embed = discord.Embed(title=\"**Error**\",\r\n description=('{}'.format(errormsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@client.command()\r\nasync def unblacklist(ctx, user: discord.Member):\r\n if ctx.message.author.id == 356472972657295390:\r\n client.blacklisted_users.remove(user.id)\r\n data = read_json(\"blacklist\")\r\n data[\"blacklistedUsers\"].remove(user.id)\r\n write_json(data, \"blacklist\")\r\n message = f\"{user.name} is allowed to use Ice's commands again!\"\r\n embed = discord.Embed(title=\"**Unblacklist**\",\r\n description=('{}'.format(message)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n else:\r\n errormsg = 'You are not the owner...'\r\n embed = discord.Embed(title=\"**Error**\",\r\n description=('{}'.format(errormsg)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\n# prefix change\r\n@client.event\r\nasync def on_guild_join(guild):\r\n with open('Json_Files/prefixes.json', 'r') as f:\r\n prefixes = json.load(f)\r\n\r\n prefixes[str(guild.id)] = 'd!'\r\n\r\n with open('Json_Files/prefixes.json', 'w') as f:\r\n json.dump(prefixes, f, indent=4)\r\n\r\n\r\n@client.event\r\nasync def on_guild_remove(guild):\r\n with open('Json_Files/prefixes.json', 'r') as f:\r\n prefixes = json.load(f)\r\n\r\n prefixes.pop(str(guild.id))\r\n\r\n with open('Json_Files/prefixes.json', 'w') as f:\r\n json.dump(prefixes, f, indent=4)\r\n\r\n\r\n@client.command(aliases=['prefix', 'prefixchange', 'setprefix'])\r\n@commands.has_permissions(manage_guild=True)\r\nasync def changeprefix(ctx, prefix):\r\n with open('Json_Files/prefixes.json', 'r') as f:\r\n prefixes = json.load(f)\r\n\r\n prefixes[str(ctx.guild.id)] = prefix\r\n\r\n with open('Json_Files/prefixes.json', 'w') as f:\r\n json.dump(prefixes, f, indent=4)\r\n embed = discord.Embed(title=\"**Change Prefix**\",\r\n description=f'Changed prefix to: {prefix}',\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\n# Ping, checks the latency of the user to the API\r\n@client.command(pass_context=True)\r\nasync def ping(ctx):\r\n ping = (\r\n f'Pong! Your ping is: `{round(client.latency * 1000)}ms`, *Please note this is not your actual '\r\n f'ping, this is '\r\n f'the latency of your connection to the API*')\r\n embed = discord.Embed(title=\"**Ping**\",\r\n description=('{}'.format(ping)),\r\n color=discord.Color.blue())\r\n embed.set_footer(text='Bot made by '\r\n 'xIntensity#4217')\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\n\r\ndef read_json(filename):\r\n with open(f\"{cwd}/Json_Files/{filename}.json\", \"r\") as file:\r\n data = json.load(file)\r\n return data\r\n\r\n\r\ndef write_json(data, filename):\r\n with open(f\"{cwd}/Json_Files/{filename}.json\", \"w\") as file:\r\n json.dump(data, file, indent=4)\r\n\r\n\r\nwith open(\"Json_Files/Token.json\", \"r\") as token_file:\r\n data = json.load(token_file)\r\n token = data['token']\r\n\r\nclient.run(token)\r\n","sub_path":"Ice/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":10269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"597266841","text":"# https://www.urionlinejudge.com.br/judge/pt/problems/view/1244\n\n# -*- coding: utf-8 -*-\n\nN = int(input())\n\nfor casoTeste in range(N):\n entrada = str(input()).split(\" \")\n palavras = [[palavra, len(palavra)] for palavra in entrada]\n listaParaOrdenar = list()\n\n for palavra in palavras:\n tamanho = palavra[1]\n refTamanhos = [item[0] for item in listaParaOrdenar]\n if tamanho not in refTamanhos:\n listaParaOrdenar.append([tamanho, palavra[0]])\n else:\n indice = refTamanhos.index(tamanho)\n listaParaOrdenar[indice].append(palavra[0])\n\n listaParaOrdenar.sort(key = lambda item: item[0], reverse = True)\n\n frase = str()\n\n for item in listaParaOrdenar:\n for palavra in item[1:]:\n if len(frase) == 0:\n frase = palavra\n else:\n frase += \" \" + palavra\n\n print(frase)","sub_path":"Python3/Estruturas e bibliotecas/1244 - Ordenação por Tamanho.py","file_name":"1244 - Ordenação por Tamanho.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"532614542","text":"import os\nimport json\n\nimport misli\nfrom misli.gui.actions_lib import ACTIONS, Action\n\nlog = misli.get_logger(__name__)\n\n\nclass MisliGuiReplay:\n def __init__(self, actions_meta_path):\n self.last_action_dispatched = None\n self._ended = False\n self.speed = 1\n\n if not os.path.exists(actions_meta_path):\n raise Exception('Bad path given for the actions recording: \"%s\"' %\n actions_meta_path)\n\n with open(actions_meta_path) as mf:\n action_states = json.load(mf)\n\n self.actions = [Action(**a) for a in action_states]\n self.actions_left = [Action(**a) for a in action_states]\n\n def end(self):\n self._ended = True\n\n def ended(self):\n return self._ended\n\n def queue_next_action(self, action_states=None):\n if self.ended():\n return\n\n if not self.actions_left:\n log.info('Reached the end of the recording.')\n self.end()\n return\n\n action_to_dispatch = self.actions_left[0]\n timeout = action_to_dispatch.start_time\n\n if self.last_action_dispatched:\n event_action = Action(**action_states[-1])\n # ^^ This event has bad timestamps while replaying\n\n a0 = self.last_action_dispatched\n a1 = event_action\n if a0.type != a1.type or \\\n a0.args != a1.args or \\\n a0.kwargs != a1.kwargs:\n raise Exception('Action properties mismatch.')\n\n timeout -= self.last_action_dispatched.start_time\n\n actions_count = len(self.actions)\n action_idx = 1 + actions_count - len(self.actions_left)\n\n log.info('(%s/%s) Dispatching with timeout %s: %s' %\n (action_idx, actions_count, timeout, action_to_dispatch))\n misli.call_delayed(\n ACTIONS[action_to_dispatch.type],\n self.speed * timeout,\n action_to_dispatch.args,\n action_to_dispatch.kwargs)\n\n self.last_action_dispatched = action_to_dispatch\n self.actions_left = self.actions_left[1:]\n","sub_path":"tests/visual/gui_replay.py","file_name":"gui_replay.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"526294187","text":"start = int(input(\"Choose where the semiprimes will start: \"))\r\nfinal = int(input(\"Choose where the semiprimes will go up to: \"))\r\n\r\nprime = True\r\n\r\nprimeNum = []\r\n\r\nsemiPrimeNum = []\r\n\r\nstartVal = 0\r\n\r\nendVal = 0\r\n\r\n\r\n#Finds all the primes within the range of the input 'where will it go up to' and it excludes 1 and the last number\r\nfor x in range(2, final):\r\n for y in range(2, x):\r\n # if the x value divided by the y value is the same as the rounded answer of it, it means that x is NOT prime\r\n if x/ y == round(x/y):\r\n prime = False\r\n #if x is prime, it is added to an array of all the prime numbers\r\n if prime == True:\r\n primeNum += [x]\r\n #This resets the prime evaluator\r\n prime = True\r\n\r\n#This finds all the semi prime numbers by multiplying all the prime numbers together\r\nfor x in primeNum:\r\n for y in primeNum:\r\n z = x * y\r\n semiPrimeNum += [z]\r\n\r\n#The set method gets rid of any duplicate numbers and the sorted method puts the array in numerical order \r\nsemiPrimeNum = sorted(set(semiPrimeNum))\r\n\r\n#This finds where in the array it should start\r\nfor x in range(len(semiPrimeNum)):\r\n if semiPrimeNum[x] > start:\r\n startVal = x\r\n break\r\n#This finds where in the array it should end\r\nfor x in range(len(semiPrimeNum)):\r\n if semiPrimeNum[x] > final:\r\n endVal = x - 1\r\n break\r\n\r\n#It prints off all the semiprime numbers from the desired range of the user\r\nprint(semiPrimeNum[startVal:endVal + 1])\r\n","sub_path":"semiprime.py","file_name":"semiprime.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"8235482","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 29 10:25:37 2018\r\n\r\n@author: nittin pc\r\n\"\"\"\r\n\r\nimport pickle\r\nimport random\r\n\r\nimport msvcrt\r\nf = open(r'frank_whole.pkl','rb')\r\ndict1 = pickle.load(f)\r\nf.close()\r\ndictionary = {}\r\nfor items in dict1.items():\r\n dictionary[tuple(set(items[0].split(' AND ')))] = items[1]\r\n#### K means for the dictionary\r\n# no of clusters\r\nN = 30\r\nqueries = []\r\nfor item in dictionary.items():\r\n queries = queries + list(item[0])\r\n \r\nqueries = list(set(queries))\r\n\r\n# choosing initial N random centers\r\n\r\ninitial_centers = [queries[x] for x in random.sample(range(0,len(queries)),N)]\r\nclusters_with_center = {}\r\nfor x in initial_centers:\r\n clusters_with_center[x] = [] \r\n\r\nprint('Clusters Initiated')\r\n# no of iterations for k means\r\nmax_iterations = 100 \r\ncenters = initial_centers\r\ncounter = 0\r\nwhile(True):\r\n counter = counter + 1\r\n \r\n #queries = list(set(queries)-set(centers))\r\n while (True):\r\n for factoid in queries:\r\n distance = []\r\n flag = False\r\n for cents in centers:\r\n if ((tuple(set([factoid,cents]))) in [x[0] for x in dictionary.items()]):\r\n distance.append(dictionary[tuple(set([factoid,cents]))])\r\n flag = True\r\n if(not distance):\r\n print('Empty Neighbourhood')\r\n if flag :\r\n clusters_with_center[centers[distance.index(min(distance))]].append(factoid)\r\n \r\n# for n in centers:\r\n# print('Center*****',n, clusters_with_center[n] ) \r\n p = 0 \r\n for n in clusters_with_center:\r\n if n[1]:\r\n p+=1\r\n print('No of groups ',p) \r\n break\r\n# if p == N:\r\n# break\r\n# else: # for recentering the new centers\r\n# print('Recentering!!')\r\n# centers = [queries[x] for x in random.sample(range(0,len(queries)),N)]\r\n# clusters_with_center = {}\r\n# for x in centers:\r\n# clusters_with_center[x] = [] \r\n \r\n \r\n clusters = []\r\n #ch = input()\r\n #type(ch)\r\n for items in clusters_with_center.items():\r\n clusters.append(list(set([items[0]]).union(set(items[1]))))\r\n new_centers = []\r\n for items in clusters:\r\n arr =[]\r\n for x in items:\r\n summ = 0\r\n for y in items:\r\n if ((tuple(set([x,y]))) in [it[0] for it in dictionary.items()]):\r\n summ += abs(dictionary[tuple(set([x,y]))])\r\n arr.append(summ) \r\n new_centers.append(items[arr.index(min(arr))])\r\n #new_centers.append(items[arr.index(min([sum([abs(dictionary[tuple(set([x,y]))]) for y in items]) for x in items]))])\r\n if (centers == new_centers or counter >= max_iterations ):\r\n print('Current Centers', new_centers)\r\n if (counter == max_iterations):\r\n print('Unable to converge')\r\n break\r\n print('After ',counter,' iterations, clusters converged!')\r\n break\r\n else :\r\n clusters_with_center = {}\r\n for x in new_centers:\r\n clusters_with_center[x] = [] \r\n centers = new_centers\r\n","sub_path":"kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"174743330","text":"# Ben Ma\n# Python 3.x\n\nfrom utils import load_data, split_data\nfrom baseline import run_baseline\nfrom autoregression import run_ar\nfrom lasso import run_lasso\nfrom ridge import run_ridge\nimport numpy as np\nimport csv\nimport pickle\nimport argparse\n\nOUTPUT_BASENAME = \"./results/new_compress\"\nATTENTION_LEN = 40\nDATASETS = [\"happy_enjoyment.csv\", \"sad_long_enjoyment.csv\", \"sad_short_enjoyment.csv\"]\nHORIZONS = [\"40\", \"80\"]\nCV_FOLDS = [\"Beg\", \"End\", \"Avg\"]\nSCRIPTS = [\"baseline\", \"ar\", \"lasso\", \"ridge\"]\nW_ENJOY_OR_NOT = [\"w/enjoy\", \"audio only\"]\nNUM_FEATURES = 75\n# for FEATURE_GROUPS, include all columns you want besides 0 (0 being the previous enjoyment values)\n\nFEATURE_GROUPS = {\n \"All\" : [i for i in range(1, NUM_FEATURES)],\n \"MFCCs\" : [i for i in range(1, 1 + 3*13)],\n \"Spectrogram\": [41, 44, 45, 46, 47, 62, 63],\n \"Harmony\": [i for i in range(48, 60)] + [42, 60],\n \"Dynamics\": [1, 43, 61],\n \"Rhythm\": [40],\n \"LPCs\" : [i for i in range(64, 75)]\n}\n\nFEATURE_GROUPS = {\n \"All\" : [i for i in range(1, NUM_FEATURES)],\n \"Dynamics (new compress)\" : [1, 43, 61]\n}\n\nDynamics = [1, 40, 43, 61]\nChroma = [i for i in range(48, 60)]\nSpectrogram = [44, 45, 46, 47, 62, 63]\n\n# FEATURE_GROUPS = {\n# \"Dynamics\": [1, 43, 61],\n# \"Rhythm\": [40]\n# }\n\ndef main():\n # receive data_set\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_set', type=str, default='none')\n para = parser.parse_args()\n assert para.data_set != \"none\", \"You must specify a data_set in the arguments! (Should be a path to a .csv file)\"\n dataset = para.data_set\n\n print(\"Dataset \"+dataset+\"...\")\n (X_full, y) = load_data(dataset)\n results = {}\n for feature_group in FEATURE_GROUPS.keys():\n results[feature_group] = {}\n for horizon in HORIZONS:\n results[feature_group][horizon] = {}\n for script in SCRIPTS:\n results[feature_group][horizon][script] = {}\n for enjoy_or_not in W_ENJOY_OR_NOT:\n results[feature_group][horizon][script][enjoy_or_not] = {}\n for cv_fold in CV_FOLDS:\n results[feature_group][horizon][script][enjoy_or_not][cv_fold] = {}\n # results will be an x-level dict with the following arguments\n # results[feature_group][horizon][script][w_enjoy_or_not][cv_fold][RMSE_or_alpha]\n # e.g. results[\"MFCCs\"][\"40\"][baseline][\"audio only\"][\"Beg\"][\"RMSE\"]\n\n for feature_group in FEATURE_GROUPS.keys():\n print(\"Feature Group \"+feature_group+\"...\")\n # add selected columns in feature_group to X\n num_timesteps = X_full.shape[0]\n X_group = X_full[:, 0] # col 0 included by default\n try:\n FEATURE_GROUPS[feature_group].remove(0)\n except ValueError:\n pass\n for col in FEATURE_GROUPS[feature_group]: # include 0 and every column in feature groups\n X_group = np.hstack( (\n np.reshape(X_group, (num_timesteps, -1)),\n np.reshape(X_full[:, col], (num_timesteps, 1))\n ) )\n for script in SCRIPTS:\n for horizon in HORIZONS:\n X1 = X_group # X starts as the full X_group (will remove columns if necessary)\n if(script==\"baseline\" or script==\"ar\"):\n X2 = np.reshape(X1[:, 0], (num_timesteps, 1)) # X is only first column\n else:\n X2 = X1\n for enjoy_or_not in W_ENJOY_OR_NOT:\n if (enjoy_or_not==\"audio only\" and (script==\"lasso\" or script==\"ridge\")):\n X3 = X2[:, 1:] # exclude column 0\n else:\n X3 = X2\n for cv_fold in CV_FOLDS:\n # RUN EXPERIMENT AS LONG AS IT'S NOT \"AUDIO ONLY\" FOR BASELINE OR AR\n # OR IF CV_FOLD IS AVG\n if( (script==\"baseline\" or script==\"ar\") and (enjoy_or_not==\"audio only\") ):\n results[feature_group][horizon][script][enjoy_or_not][cv_fold][\"RMSE\"] = \\\n results[feature_group][horizon][script][\"w/enjoy\"][cv_fold][\"RMSE\"]\n elif( cv_fold==\"Avg\" ):\n results[feature_group][horizon][script][enjoy_or_not][cv_fold][\"RMSE\"] = \\\n (results[feature_group][horizon][script][enjoy_or_not][\"Beg\"][\"RMSE\"] + \\\n results[feature_group][horizon][script][enjoy_or_not][\"End\"][\"RMSE\"]) / 2\n else:\n (X_train, y_train, X_test, y_test) = split_data(\n X3, y, int(horizon), ATTENTION_LEN, cv_fold)\n RMSE = -1\n if script == \"baseline\":\n RMSE = run_baseline( X_train, y_train, X_test, y_test )\n elif script == \"ar\":\n RMSE = run_ar(X_train, y_train, X_test, y_test)\n elif script == \"lasso\":\n (RMSE, Alpha, Coefs) = run_lasso(X_train, y_train, X_test, y_test)\n results[feature_group][horizon][script][enjoy_or_not][cv_fold][\"Alpha\"] = Alpha\n results[feature_group][horizon][script][enjoy_or_not][cv_fold][\"Coefs\"] = Coefs\n elif script == \"ridge\":\n (RMSE, Alpha, Coefs) = run_ridge(X_train, y_train, X_test, y_test)\n results[feature_group][horizon][script][enjoy_or_not][cv_fold][\"Alpha\"] = Alpha\n results[feature_group][horizon][script][enjoy_or_not][cv_fold][\"Coefs\"] = Coefs\n results[feature_group][horizon][script][enjoy_or_not][cv_fold][\"RMSE\"] = RMSE\n # WRITE TO RESULTS TO FILE\n output_fname = OUTPUT_BASENAME+\"_\"+dataset\n pickle_fname = output_fname[:-3]+\"p\"\n # Write Pickle --------------------\n with open(pickle_fname, \"wb\") as f:\n pickle.dump(results, f)\n # Write CSV --------------------\n with open(output_fname, \"w\", newline='') as f:\n col_names = [\"\", \"Beg w/enjoy\", \"End w/enjoy\", \"Avg w/enjoy\", \"Beg audio only\", \"End audio only\", \"Avg audio only\"]\n row_names = [\"baseline\", \"ar\", \"lasso\", \"lasso Alpha\", \"ridge\", \"ridge Alpha\"]\n writer = csv.writer(f)\n for horizon in HORIZONS:\n for feature_group in FEATURE_GROUPS.keys():\n writer.writerow([feature_group+\" - Horizon \"+horizon])\n writer.writerow(col_names)\n for row in row_names:\n my_row = [row]\n for enjoy_or_not in W_ENJOY_OR_NOT:\n for cv_fold in CV_FOLDS:\n if (row.find(\"Alpha\") != -1): # alpha case\n if (cv_fold != \"Avg\"):\n my_row.append(\n results[feature_group][horizon][row[0:5]][enjoy_or_not][cv_fold][\"Alpha\"]\n )\n else:\n my_row.append(\"\")\n else: # RMSE case\n my_row.append(\n results[feature_group][horizon][row][enjoy_or_not][cv_fold][\"RMSE\"]\n )\n writer.writerow(my_row)\n writer.writerow([]) # put an empty line here\n print(\"Results written to \"+output_fname+\"\\n\")\n\nif (__name__==\"__main__\"):\n main()","sub_path":"AR-VAR/run_experiments.py","file_name":"run_experiments.py","file_ext":"py","file_size_in_byte":7750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"95171378","text":"#if something is not clear after reading comments corresponding to code related to Google Custom Search Engine then do watch this video\"https://www.youtube.com/watch?v=IBhdLRheKyM&t=612s\"\nimport nltk\n#nltk.download()\nimport requests\nfrom bs4 import BeautifulSoup\nfrom nltk.tokenize import word_tokenize\n#we are now going to write code so that our python application can interact with \"Google custom search engine\".Therefore for that we are going to use \"Custom Search\n#JSON API\"\n#The Custom Search JSON API lets you develop websites and applications to retrieve and display search results from Google Custom Search programmatically. With this API,\n#you can use RESTful requests(restful requests are nothing but HTTP requests because REST API uses HTTP requests) to get either web search or image search results in\n#JSON format. \nfrom apiclient.discovery import build#this statement is used to check whether the library is installed or not and whether other things like enabling of\n#\"Custom Search JSON API\" service has been done or not.In short it will prompt a error if any step is not followed properly.\nfrom nltk.tokenize import sent_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.text import Text\nimport string, re\n# import SentimentIntensityAnalyzer class \n# from vaderSentiment.vaderSentiment module. \nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\nlink=[]#storing a list of links\nAPI_key=\"AIzaSyAkyDSWq4bqQkicsjwBy-0sIBBs1lsRSpg\"#this will be the credentials which will be used to use the \"Custom Search JSON API\" service\n#we have also installed an important library \"google-api-python-client\" so that we can interact with \"Custom Search JSON API\" \nresource=build(\"customsearch\",'v1',developerKey=API_key).cse()#now we will create a resource object which using \"build\" module where we have passed 3 things\n#1)Service name 2)Version number 3)API Key and after that we have created a custom search engine object by calling \".cse()\" at the end. We have created this object in\n#order to send requests to Google's Custom Search Engine API .\nfor i in range(1,10):\n result=resource.list(q='Fadnavis',cx='008883652953486625000:fgs4ef2yo4b',start=i).execute()#list() will return me the search results here 'q' is the query and 'cx'\n#search engine ID which has already created by you while enabling the service of \"Custom Search JSON API\" and finally we need to execute this request hence we have\n#called \"execute()\" \nprint(\"the title and links of a search are:\")\n#now we will see the response recieved using the \"result[items]\" and the response send is in JSON format. BY default we get 10 results \nfor item in result['items']:\n print(item['title'],item['link'])#as there may be \"10\" results therefore we are trying we have used for loop for it.\n link.append(item['link'])\n#print(link)\nj=0\nfor i in link:\n #print(i)\n url=i\n j=j+1\n \n response = requests.get(url)#here we are storing the response given by the server for the request given\n data = response.text#here we are trying to store the source code of the webpage or we are storing the raw html code of the webpage\n soup = BeautifulSoup(data, 'lxml')#now we are creating the \"beutiful soup\" object which will be used to create a \"parse tree\" by using parser \"lxml\"\n text = soup.find_all(text=True)#BeautifulSoup provides a simple way to find text content (i.e. non-HTML) from the HTML: \"Plz read from \"https://matix.io/extract-text-from-webpage-using-beautifulsoup-and-python/\"\"\n output = ''\n\n blacklist = [\n '[document]',\n 'noscript',\n 'style',\n 'header',\n 'html',\n 'meta',\n 'head',\n 'input',\n 'script',\n ',',\n ':',\n '.'\n '?'\n # there may be more elements you don't want, such as \"style\", etc.\n ]\n\n for t in text:\n if t.parent.name not in blacklist:\n output += t\n\n \n sentences=sent_tokenize(output)#sentence tokenizing from strings\n\n # function to print sentiments \n # of the sentence. \n def sentiment_scores(sentence): \n \n # Create a SentimentIntensityAnalyzer object. \n sid_obj = SentimentIntensityAnalyzer() \n \n # polarity_scores method of SentimentIntensityAnalyzer \n # oject gives a sentiment dictionary. \n # which contains pos, neg, neu, and compound scores. \n return sid_obj.polarity_scores(sentence) \n \n\n # Driver code\n COMPOUNDSCORE=0#for adding the compound scores of each sentence.\n POSITIVE=0\n NEGATIVE=0\n NEUTRAL=0\n for x in sentences:\n sentiment_dict=sentiment_scores(x)\n COMPOUNDSCORE=COMPOUNDSCORE+sentiment_dict['compound']\n POSITIVE=POSITIVE+sentiment_dict['pos']\n NEGATIVE=NEGATIVE+sentiment_dict['neg']\n NEUTRAL=NEUTRAL+sentiment_dict['neu']\n\n AVGcompoundscore=(COMPOUNDSCORE/len(sentences))*100\n AVGpositivescore=(POSITIVE/len(sentences))*100\n AVGnegativescore=(NEGATIVE/len(sentences))*100\n AVGneutralscore=(NEUTRAL/len(sentences))*100\n\n# decide sentiment as positive, negative and neutral \n if AVGcompoundscore >= 0.05 : \n print(url,\"Content is Positive ,the Compound Score is\",AVGcompoundscore) \n \n elif AVGcompoundscore <= - 0.05 : \n print(url,\"Content is Negative and the Compound Score is\",AVGcompoundscore) \n \n else : \n print(url,\"Content is Neutral and the Compound Score is\",AVGcompoundscore)\n \n\n\n \n \n \n \n","sub_path":"Information_Retrieval/IR_Project/IR Test Project.py","file_name":"IR Test Project.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"291290452","text":"import io\nimport os\nimport sys\nimport json\nimport base64\nimport pytest\nimport logging\nimport zipfile\nimport requests\n\n#Web imports \n\n\nfrom SAF.misc import saf_misc\nfrom SAF.driver import driver_factory\nfrom MobileApps.libs.ma_misc import ma_misc\nfrom MobileApps.libs.app_package.app_class_factory import app_module_factory\n\n#Appium platform consts\nimport MobileApps.resources.const.ios.const as i_const\nimport MobileApps.resources.const.mac.const as m_const\nimport MobileApps.resources.const.android.const as a_const\nimport MobileApps.resources.const.windows.const as w_const\n\n\nclass BadLocaleStrException(Exception):\n pass\n\nclass UnknownDefaultLocaleException(Exception):\n pass\n\nclass MissingWifiInfo(Exception):\n pass\n\n#Default locales please reference this webpage \n#http://www.apps4android.org/?p=3695\n\ndefault_locale= {\"ar\": \"SA\",\n \"en\": \"US\",\n \"cs\": \"CZ\",\n \"da\": \"DK\",\n \"de\": \"DE\",\n \"el\": \"GR\",\n \"es\": \"ES\",\n \"fi\": \"FI\",\n \"he\": \"IL\",\n \"hu\": \"HU\",\n \"ja\": \"JP\",\n \"ko\": \"KR\",\n \"nb\": \"NO\",\n \"pl\": \"PL\",\n \"pt\": \"PT\",\n \"ru\": \"RU\",\n \"sv\": \"SE\",\n \"tr\": \"TR\",\n \"zh\": \"CN\",\n \"nl\": \"NL\",\n \"fr\": \"FR\",\n \"it\": \"IT\"}\n\ndef get_locale(request):\n locale_parts = request.config.getoption(\"--locale\").split(\"_\")\n if len(locale_parts) == 2:\n return locale_parts\n elif len(locale_parts) == 1:\n if default_locale.get(locale_parts[0], None) is None:\n raise UnknownDefaultLocaleException(\"Cannot find a default locale for the language: \" + locale_parts[0] + \" please append it to the default_locale dictionary in conftest_misc.py\")\n return locale_parts[0], default_locale[locale_parts[0]]\n else:\n raise BadLocaleStrException(\"The locale format needs to be [language]_[region]. What was passed in is: \" + request.config.getoption(\"--locale\"))\n\ndef build_info_dict(request, _os=None):\n const = None\n system_config = ma_misc.load_system_config_file()\n try:\n project_name = pytest.app_info\n except AttributeError:\n logging.error(\"Please mark your class with the app you are testing ['SMART', 'HPPS', etc]\")\n sys.exit()\n\n try:\n _os = _os if _os else pytest.platform\n except AttributeError:\n logging.error(\"Please mark test with a platform ['ANDROID', 'IOS', etc]\")\n sys.exit() \n\n lang, locale = get_locale(request)\n executor_url = system_config[\"executor_url\"] if not request.config.getoption(\"--executor-url\") else request.config.getoption(\"--executor-url\")\n executor_port = system_config[\"executor_port\"] if not request.config.getoption(\"--executor-port\") else request.config.getoption(\"--executor-port\")\n\n info_dict = {\"server\": {\"url\": executor_url,\n \"port\": executor_port},\n \"dc\":{\"platformName\": _os.upper(),\n \"platform\": _os.upper(),\n \"clearSystemFiles\": True, \n \"language\": lang\n }}\n\n info_dict[\"ga\"] =request.config.getoption(\"--ga\")\n\n if _os.upper() == \"ANDROID\":\n const = a_const\n info_dict[\"dc\"][\"locale\"] = locale\n info_dict[\"dc\"][\"remoteAppsCacheLimit\"] = 0\n info_dict[\"dc\"][\"automationName\"] = \"uiautomator2\"\n info_dict[\"dc\"][\"androidInstallPath\"] = \"/sdcard/Download/\"\n info_dict[\"dc\"][\"androidScreenshotPath\"] = \"/sdcard/Screenshot/\"\n info_dict[\"dc\"][\"uiautomator2ServerInstallTimeout\"] = 60000\n info_dict[\"dc\"][\"androidInstallTimeout\"] = 180000\n info_dict[\"dc\"][\"unicodeKeyboard\"] = True\n info_dict[\"dc\"][\"recreateChromeDriverSessions\"] = True\n\n if getattr(const.OPTIONAL_INTENT_ARGUMENTS, project_name.upper(), False):\n info_dict[\"dc\"][\"optionalIntentArguments\"] = getattr(const.OPTIONAL_INTENT_ARGUMENTS,\n project_name.upper())\n info_dict[\"dc\"][\"resetKeyboard\"] = True\n\n if getattr(const.ANDROID_PROCESS, project_name.upper(), False):\n info_dict[\"dc\"][\"chromeOptions\"] = {}\n info_dict[\"dc\"][\"chromeOptions\"][\"androidProcess\"] = getattr(const.ANDROID_PROCESS, project_name.upper())\n\n if getattr(const.CUSTOM_CHROME_DRIVER, project_name.upper(), False):\n info_dict[\"dc\"][\"chromedriverExecutable\"] = getattr(const.CUSTOM_CHROME_DRIVER, project_name.upper())\n\n elif _os.upper() == \"IOS\":\n const = i_const\n info_dict[\"dc\"][\"locale\"] = lang + \"_\" +locale\n info_dict[\"dc\"][\"automationName\"] = \"XCUITest\"\n info_dict[\"dc\"][\"useNewWDA\"] = False\n info_dict[\"dc\"][\"waitForQuiescence\"] = True\n info_dict[\"dc\"][\"showXcodeLog\"] = True\n # info_dict[\"dc\"][\"webviewConnectTimeout\"] = 30000\n # info_dict[\"dc\"][\"safariLogAllCommunication\"] = True\n\n elif _os.upper() == 'MAC':\n const = m_const\n info_dict[\"dc\"][\"deviceName\"] = \"mac device\"\n if request.config.getoption(\"--afm2\"):\n info_dict[\"dc\"][\"automationName\"] = \"Mac2\"\n info_dict[\"dc\"][\"showServerLogs\"] = True\n else:\n info_dict[\"dc\"][\"automationName\"] = \"Mac\"\n\n elif _os.upper() == \"WINDOWS\":\n const = w_const\n info_dict[\"dc\"][\"ms:experimental-webdriver\"] = True\n\n if project_name.upper() not in const.NONE_THIRD_PARTY_APP.APP_LIST:\n if _os.upper() == \"IOS\":\n info_dict[\"dc\"][\"bundleId\"] = eval(\"const.BUNDLE_ID.\" + project_name.upper())\n elif _os.upper() == \"ANDROID\":\n try:\n info_dict[\"dc\"][\"appWaitActivity\"] = getattr(const.WAIT_ACTIVITY, project_name.upper())\n except AttributeError:\n logging.debug(\"Does not have a wait activity\")\n info_dict[\"dc\"][\"noReset\"] = True\n else:\n info_dict[\"dc\"][\"fullReset\"] = True\n if _os.upper() not in [\"WINDOWS\", \"MAC\"]:\n #Adding for android and mac the ability to have package name/wait activty in a dictionary\n info_dict[\"dc\"][\"app\"] = get_package_url(request, _os=_os)\n if _os.upper() == \"ANDROID\":\n pkg_name, act_name = get_pkg_activity_name_from_const(request, const, project_name)\n if pkg_name is not None:\n info_dict[\"dc\"][\"appPackage\"] = pkg_name\n if act_name is not None:\n info_dict[\"dc\"][\"appActivity\"] = act_name\n else:\n info_dict[\"dc\"][\"app\"] = eval(\"const.APP_NAME.\" + project_name.upper())\n \n if request.config.getoption(\"--mobile-device\") is not None:\n info_dict[\"dc\"][\"applicationName\"] = request.config.getoption(\"--mobile-device\")\n if request.config.getoption(\"--platform-version\") is not None:\n info_dict[\"dc\"]['platformVersion'] = request.config.getoption(\"--platform-version\")\n\n info_dict[\"language\"], info_dict[\"locale\"] = get_locale(request)\n if request.config.getoption(\"--imagebank-path\") is not None:\n info_dict[\"image_bank_root\"] = request.config.getoption(\"--imagebank-path\")\n else:\n info_dict[\"image_bank_root\"] = system_config.get(\"image_bank_root\")\n info_dict[\"bulk_image_root\"]=system_config.get(\"bulk_image_root\")\n info_dict[\"start_up_project\"] = project_name\n info_dict[\"request\"] = request\n\n return info_dict\n\ndef build_web_info_dict(request, browser_type):\n system_config = ma_misc.load_system_config_file() \n executor_url = system_config[\"executor_url\"] if not request.config.getoption(\"--executor-url\") else request.config.getoption(\"--executor-url\")\n executor_port = system_config[\"executor_port\"] if not request.config.getoption(\"--executor-port\") else request.config.getoption(\"--executor-port\")\n\n try:\n project_name = pytest.app_info\n except AttributeError:\n logging.error(\"Please mark your class with the app you are testing ['SMART', 'HPPS', etc]\")\n sys.exit()\n info_dict = {\"server\": {\"url\": executor_url,\n \"port\": executor_port},\n \"dc\":{\"platform\": request.config.getoption(\"--platform\") ,\n }}\n info_dict[\"language\"], info_dict[\"locale\"] = get_locale(request)\n if request.config.getoption(\"--imagebank-path\") is not None:\n info_dict[\"image_bank_root\"] = request.config.getoption(\"--imagebank-path\")\n else:\n info_dict[\"image_bank_root\"] = system_config.get(\"image_bank_root\")\n info_dict[\"bulk_image_root\"]=system_config.get(\"bulk_image_root\")\n info_dict[\"request\"] = request\n if pytest.app_info == \"ECP\":\n info_dict[\"proxy\"] = \"web-proxy.austin.hpicorp.net:8080\"\n return info_dict\n\ndef create_driver(request, _os):\n info_dict = build_info_dict(request, _os)\n return driver_factory.web_driver_factory(_os, info_dict)\n\ndef utility_web_driver(browser_type=\"chrome\"):\n system_config = ma_misc.load_system_config_file()\n info_dict = {\"server\": {\"url\": system_config[\"web_executor_url\"], \"port\": system_config[\"web_executor_port\"]},\n \"dc\": {\"platform\": \"ANY\"}}\n return driver_factory.web_driver_factory(browser_type, info_dict)\n\ndef create_web_driver(request):\n browser_type = request.config.getoption(\"--browser-type\")\n info_dict = build_web_info_dict(request, browser_type)\n return driver_factory.web_driver_factory(browser_type, info_dict)\n\ndef get_package_url(request, _os=None, project=None, app_type=None, app_build=None, app_release=None):\n system_config = ma_misc.load_system_config_file()\n custom_location = request.config.getoption(\"--app-location\")\n if custom_location is not None:\n if ma_misc.validate_url(custom_location) or os.path.isfile(custom_location):\n if system_config.get(\"database_info\", None) is not None:\n #If database then cache it\n app_obj = app_module_factory(\"ANY\", \"ANY\", system_config[\"database_info\"])\n return app_obj.get_build_url(custom_location)\n #If the build is local and there is no database_info then return the location\n return custom_location\n else:\n raise RuntimeError(\"App Location: \" + custom_location + \" is not a valid location\")\n\n actual_os = _os if _os is not None else pytest.platform\n actual_project = project if project is not None else pytest.app_info\n app_obj = app_module_factory(actual_os, actual_project, system_config.get(\"database_info\", None))\n\n if _os.lower() == \"ANDROID\".lower():\n app_type = app_type if app_type is not None else request.config.getoption(\"--app-type\")\n app_version = request.config.getoption(\"--app-version\")\n app_build = app_build if app_build is not None else request.config.getoption(\"--app-build\")\n app_release = app_release if app_release is not None else request.config.getoption(\"--app-release\")\n return app_obj.get_build_url(build_type=app_type, build_version=app_version, build_number=app_build, release_type=app_release)\n\n\n elif _os.lower() == \"IOS\".lower():\n app_type = request.config.getoption(\"--app-type\")\n app_version = request.config.getoption(\"--app-version\")\n app_build = app_build if app_build is not None else request.config.getoption(\"--app-build\")\n return app_obj.get_build_url(build_type=app_type, build_version=app_version, build_number=app_build)\n\n elif _os.lower() == \"WINDOWS\".lower():\n app_version = request.config.getoption(\"--app-version\")\n return app_obj.get_build_url(build_version=app_version)\n\ndef get_session_result_folder_path(driver):\n info = driver.driver_info\n root_path = ma_misc.get_abs_path(\"/results\", False)\n if info.get(\"desired\", False):\n device_name = info[\"desired\"][\"deviceName\"].replace(\" \", \"_\")\n else:\n device_name = info[\"deviceName\"].replace(\" \", \"_\")\n dir_path = str(\"{}/{}/{}_{}/\".format(root_path, info[\"platformName\"].lower(),\n device_name, info.get(\"CONFIG_UUID\", info.get(\"udid\"))))\n if not os.path.isdir(dir_path):\n os.makedirs(dir_path)\n return dir_path \n\ndef get_web_session_result_folder_path(request):\n root_path = ma_misc.get_abs_path(\"/results\", False)\n return \"{}/{}/{}/{}/\".format(root_path, \"web\", request.config.getoption(\"--browser-type\"), request.config.getoption(\"--uuid\"))\n\n\ndef get_test_result_folder_path(session_result_folder, test_class_name):\n dir_path = session_result_folder + test_class_name + \"/\"\n if not os.path.isdir(dir_path):\n os.makedirs(dir_path)\n return dir_path\n\ndef get_attachment_folder():\n #This function only works after the class scope\n path = pytest.test_result_folder + \"attachment/\"\n if not os.path.isdir(path):\n os.makedirs(path)\n return path\n\ndef save_printer_fp_and_publish(p, file_path):\n try:\n p.printer_screen_shot(file_path)\n except: \n logging.warning(\"Could not take screenshot of printer: \" + file_path)\n return False\n ma_misc.publish_to_junit(file_path) \n\ndef save_mem_stat_and_publish(driver, root_path, file_name=None):\n data = driver.wdvr.execute_script(\"mobile: shell\", {\"command\": \"cat\", \"args\":[\"/proc/meminfo\"]})\n if file_name is None:\n file_name = \"mem_stat.txt\"\n file_path = root_path + file_name\n with open(file_path, \"w+\", encoding=\"utf-8\") as f:\n f.write(data)\n ma_misc.publish_to_junit(file_path)\n\ndef save_screenshot_and_publish(driver, file_path):\n \"\"\"\n Get screen-shot of mobile device\n :param driver:\n :param file_path:\n :return:\n \"\"\"\n # This is currently not proper location need to fix later\n driver.wdvr.get_screenshot_as_file(file_path)\n ma_misc.publish_to_junit(file_path)\n\ndef save_source_and_publish(driver, root_path, file_name=None):\n if file_name is None:\n file_name = \"page_source.txt\"\n file_path = root_path + file_name\n with open(file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(driver.wdvr.page_source)\n ma_misc.publish_to_junit(file_path)\n\n\ndef save_log_and_publish(driver, root_path, node_name):\n \"\"\"\n Get logcat of device and save to file_path\n :param driver:\n :param root_path:\n :param node_name:\n :return:\n \"\"\"\n save_file_path = \"{}{}_log.txt\".format(root_path, node_name)\n driver.return_device_log(save_file_path)\n ma_misc.publish_to_junit(save_file_path)\n\ndef save_app_log_and_publish(project, driver, root_path, node_name):\n try:\n zipfile = base64.b64decode(driver.wdvr.pull_folder(eval(\"a_const.TEST_DATA.\" + project + \"_APP_LOG_PATH\")))\n fh = open(root_path + node_name + \"_app_log\" + \".zip\", \"wb\")\n fh.write(zipfile)\n fh.close()\n #Publish to junit\n ma_misc.publish_to_junit(os.path.realpath(fh.name))\n except:\n logging.warning(\"Unable to capture app log\")\n\ndef save_ios_app_log_and_publish(fc, driver, root_path, node_name):\n try:\n zipfile = base64.b64decode(driver.wdvr.pull_folder(\"@com.hp.printer.control.dev:documents/\" + \"Logs\"))\n fh = open(root_path + node_name + \"_app_log\" + \".zip\", \"wb\")\n fh.write(zipfile)\n fh.close()\n ma_misc.publish_to_junit(os.path.realpath(fh.name))\n except:\n logging.warning(\"Unable to capture app log\")\n\ndef save_video_and_publish(driver, root_path, file_name):\n file_path = root_path + file_name + \".mp4\"\n fh = open(file_path, \"wb+\")\n data = driver.wdvr.stop_recording_screen()\n fh.write(base64.b64decode(data))\n fh.close()\n ma_misc.publish_to_junit(file_path)\n\ndef save_cms_results_and_publish(driver, root_path, file_name):\n file_path = root_path + file_name + \".json\"\n if driver.session_data[\"context_manager_mode\"] != \"verify\":\n logging.info(\"Context manager verify not activated nothing to save\")\n return True\n with open(file_path, \"w+\", encoding=\"utf-8\") as fh:\n json.dump(driver.session_data[\"context_manager_results\"], fh)\n ma_misc.publish_to_junit(file_path)\n\ndef save_cms_failed_images_and_publish(driver, root_path, file_name):\n file_path = root_path + file_name + \".zip\"\n file_list = []\n for key, value in driver.session_data[\"context_manager_failed_images\"].items():\n img_file = key.replace(\"/\", \"_\") + \".png\"\n content = base64.b64decode(value)\n file_list.append(tuple([img_file, content]))\n if file_list == []:\n #If no failures don't post a zip file\n return True\n in_memory_zip(file_path, file_list)\n ma_misc.publish_to_junit(file_path)\n\ndef in_memory_zip(zip_file_path, content):\n zip_buffer = io.BytesIO()\n with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) as zip_file:\n for file_name, data in content:\n zip_file.writestr(file_name, io.BytesIO(data).getvalue())\n with open(zip_file_path, \"wb\") as f:\n f.write(zip_buffer.getvalue())\n\ndef get_wifi_info(request, raise_e=True):\n system_cfg = ma_misc.load_system_config_file()\n if not system_cfg.get(\"default_wifi\", False):\n ssid = request.config.getoption(\"--wifi-ssid\")\n password = request.config.getoption(\"--wifi-pass\")\n else:\n ssid = request.config.getoption(\"--wifi-ssid\") if request.config.getoption(\"--wifi-ssid\") else system_cfg[\"default_wifi\"][\"ssid\"]\n password = request.config.getoption(\"--wifi-pass\") if request.config.getoption(\"--wifi-pass\") else system_cfg[\"default_wifi\"][\"passwd\"]\n\n if ssid is None or password is None:\n if raise_e:\n raise MissingWifiInfo(\"System config file is missing 'default_wifi' info and it's not passed in\")\n else:\n return None, None\n\n return ssid, password\n\ndef get_pkg_activity_name_from_const(request,const, project_name):\n pkg_name = getattr(const.PACKAGE, project_name.upper())\n act_name = getattr(const.LAUNCH_ACTIVITY, project_name.upper())\n pkg_type = request.config.getoption(\"--app-build\")\n if type(pkg_name) == dict:\n pkg_name= pkg_name.get(pkg_type, pkg_name[\"default\"])\n if type(act_name) == dict:\n act_name= act_name.get(pkg_type, act_name[\"default\"])\n return pkg_name, act_name\n\nif __name__ == \"__main__\":\n pass","sub_path":"MobileApps/libs/ma_misc/conftest_misc.py","file_name":"conftest_misc.py","file_ext":"py","file_size_in_byte":18420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"338669534","text":"import os\r\nimport json\r\nfrom config import config_path\r\nfrom comment import excel_handler,log_handler,random_handler,request_handler,yaml_handler,sql_handler\r\nfrom pymysql.cursors import DictCursor\r\n\r\n\r\nclass MiddleHandler:\r\n # 给添加项目的id和project_name一个空值,以便添加接口的时候不会重复调用\r\n project_data=None\r\n interfaces_data=None\r\n # 把配置文件赋值给变量\r\n config=config_path\r\n\r\n # 获取yaml配置文件\r\n yaml=yaml_handler.read_yaml(os.path.join(config.CONFIG_PATH,\"config.yaml\"))\r\n\r\n # 获取测试用例的路径\r\n case_file=yaml[\"case\"][\"case_file\"]\r\n case_path=excel_handler.ExcelHandler(os.path.join(config.CASE_PATH,case_file))\r\n\r\n # 获取log\r\n log=log_handler.log_handler(\r\n file_name=os.path.join(config.LOG_PATH,yaml[\"log\"][\"file_name\"]),\r\n log_name=\"my_log\",\r\n log_level=\"DEBUG\",\r\n stream_level=\"DEBUG\",\r\n file_level=\"DEBUG\",\r\n fmt=\"%(asctime)s--%(filename)s--line:%(lineno)d--%(levelname)s:%(message)s\"\r\n )\r\n\r\n # 封装注册函数\r\n def register(self):\r\n username=(random_handler.RandomHandler().username())[0]\r\n email=random_handler.RandomHandler().email()\r\n data={\r\n \"username\":username,\r\n \"email\":email,\r\n \"password\":\"123456\",\r\n \"password_confirm\":\"123456\"\r\n }\r\n res=request_handler.request_handler(\r\n url=MiddleHandler.yaml[\"url\"] + \"/user/register/\",\r\n method=\"post\",\r\n json=data\r\n ).text\r\n return json.loads(res)[\"username\"]\r\n\r\n # 封装登录函数\r\n def login(self):\r\n username=self.register()\r\n data = {\r\n \"username\": username,\r\n \"password\": \"123456\",\r\n }\r\n res=request_handler.request_handler(\r\n url=MiddleHandler.yaml[\"url\"] + \"/user/login/\",\r\n method=\"post\",\r\n json=data\r\n ).text\r\n username=json.loads(res)[\"username\"]\r\n token_data=json.loads(res)[\"token\"]\r\n token=\" \".join([\"JWT\",token_data])\r\n return [username,token]\r\n\r\n # 封装添加项目函数\r\n def projects(self):\r\n name = (random_handler.RandomHandler().project_name())[0]\r\n data={\r\n \"name\": name,\r\n \"leader\": \"天空\",\r\n \"tester\": \"sky\",\r\n \"programmer\": \"haha\",\r\n \"publish_app\": \"天空是富婆\",\r\n \"desc\": \"当我的笑灿烂像阳光\"\r\n }\r\n res=request_handler.request_handler(\r\n url=MiddleHandler.yaml[\"url\"] + \"/projects/\",\r\n method=\"post\",\r\n headers={\"Authorization\":self.login()[1]},\r\n json=data\r\n ).text\r\n project_id=json.loads(res)[\"id\"]\r\n project_name=json.loads(res)[\"name\"]\r\n return [project_id,project_name]\r\n\r\n def interfaces(self):\r\n interfaces_name = (random_handler.RandomHandler().interfaces_name())[0]\r\n project=self.projects()\r\n project_id=project[0]\r\n project_name=project[1]\r\n interfaces_data = {\r\n \"name\":interfaces_name,\r\n \"tester\":\"天空\",\r\n \"project_id\":project_id,\r\n \"desc\":\"这是一个接口\"\r\n }\r\n interfaces_res = request_handler.request_handler(\r\n url=MiddleHandler.yaml[\"url\"] + \"/interfaces/\",\r\n method=\"post\",\r\n headers={\"Authorization\": self.login()[1]},\r\n json=interfaces_data\r\n ).text\r\n interfaces_id = json.loads(interfaces_res)[\"id\"]\r\n interfaces_name = json.loads(interfaces_res)[\"name\"]\r\n return [interfaces_id,interfaces_name,project_id,project_name]\r\n\r\n def replace_data(self,data):\r\n import re\r\n patten=r\"#(.+?)#\"\r\n while re.search(patten,data):\r\n key=re.search(patten,data,1).group(1)\r\n value=getattr(self,key,\"\")\r\n data=re.sub(patten,str(value),data,1)\r\n return data\r\n\r\n\r\nclass MySqlHandler(sql_handler.MySqlHandler):\r\n # 连接数据库\r\n def __init__(self):\r\n # 从yaml文件中读取到数据库db的配置项\r\n db_config = MiddleHandler.yaml[\"db\"]\r\n # 子类继承父类的方法\r\n super().__init__(\r\n host=db_config[\"host\"],\r\n port=db_config[\"port\"],\r\n user=db_config[\"user\"],\r\n password=db_config[\"password\"],\r\n charset=db_config[\"charset\"],\r\n database=db_config[\"database\"],\r\n cursorclass=DictCursor\r\n )\r\n\r\n\r\nif __name__ == '__main__':\r\n a=MiddleHandler().interfaces()\r\n print(a)\r\n pass\r\n","sub_path":"middle_ware/middle_handler.py","file_name":"middle_handler.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"30429446","text":"import traceback, pdb\nfrom typing import Dict\nfrom uuid import uuid4\n\nimport aiohttp\nimport asyncio\nimport json\nimport random\n\nfrom config import config\n\nimport sys\nsys.path.append(\"..\")\n\n\nclass RPCException(Exception):\n def __init__(self, message):\n super(RPCException, self).__init__(message)\n\nasync def call_aiohttp_wallet_original(method_name: str, coin: str, payload: Dict = None) -> Dict:\n full_payload = {\n 'params': payload or {},\n 'jsonrpc': '2.0',\n 'id': str(uuid4()),\n 'method': f'{method_name}'\n }\n url = get_wallet_rpc_url(coin)\n async with aiohttp.ClientSession() as session:\n async with session.post(url, json=full_payload, timeout=60) as response:\n if response.status == 200:\n res_data = await response.read()\n res_data = res_data.decode('utf-8')\n await session.close()\n decoded_data = json.loads(res_data)\n result = decoded_data['result']\n if random.randint(1,101) > 99: # only random log\n print(coin+\" \"+method_name+\" RPC Result Original : \"+json.dumps(result))\n return result\n else:\n print(\" RPC Original Error status : \"+response.status);\n return None\n \nasync def call_aiohttp_wallet(method_name: str, coin: str, payload: Dict = None) -> Dict:\n coin_family = getattr(getattr(config,\"daemon\"+coin,\"daemonWRKZ\"),\"coin_family\",\"TRTL\")\n indexMajor = 0\n if payload is None:\n payload = {}\n\n if coin_family == \"XMR\" and method_name == \"getBalance\":\n method_name = \"get_balance\"\n payload[\"account_index\"] = 0\n payload[\"address_indices\"] = [0]\n if 'address' in payload:\n indices = await call_aiohttp_wallet_original('get_address_index', coin, payload=payload)\n indexMajor = indices['index']['major']\n if int(indexMajor) != 0:\n print(coin+\" - Error user with majorindex: \")\n payload[\"account_index\"] = indexMajor\n payload[\"address_indices\"] = [indices['index']['minor']]\n\n if coin_family == \"XMR\" and method_name == \"getAddresses\":\n method_name = \"get_address\"\n payload[\"account_index\"] = 0\n\n if coin_family == \"XMR\" and method_name == \"sendTransaction\":\n method_name = \"transfer\"\n indices = await call_aiohttp_wallet_original('get_address_index', coin, {\"address\":payload[\"addresses\"][0]})\n indexMajor = indices['index']['major']\n if int(indexMajor) != 0:\n print(coin+\" - Error user with majorindex: \")\n # payload[\"account_index\"] = indexMajor\n # payload[\"subaddr_indices\"] = [indices['index']['minor']]\n payload[\"destinations\"] = payload[\"transfers\"]\n payload[\"priority\"] = 0\n payload[\"mixin\"] = payload[\"anonymity\"]\n payload[\"get_tx_key\"] = True\n payload[\"unlock_time\"] = 0\n if hasattr(payload,\"paymentId\"):\n payload[\"payment_id\"] = payload[\"paymentId\"]\n\n full_payload = {\n 'params': payload or {},\n 'jsonrpc': '2.0',\n 'id': str(uuid4()),\n 'method': f'{method_name}'\n }\n\n url = get_wallet_rpc_url(coin)\n async with aiohttp.ClientSession() as session:\n async with session.post(url, json=full_payload, timeout=60) as response:\n if response.status == 200:\n res_data = await response.read()\n res_data = res_data.decode('utf-8')\n await session.close()\n decoded_data = json.loads(res_data)\n if 'result' in decoded_data:\n result = decoded_data['result']\n else:\n print(coin+\" \"+method_name+\" RPC Error: \"+json.dumps(decoded_data))\n return None\n # print(coin +\" \"+method_name+ \" RPC finished : \"+res_data);\n if coin_family == \"XMR\" and method_name == \"get_balance\":\n result['availableBalance'] = result[\"per_subaddress\"][0]['unlocked_balance']\n result['lockedAmount'] = result[\"per_subaddress\"][0]['balance']-result[\"per_subaddress\"][0]['unlocked_balance']\n if 'address' not in payload: # global\n result['availableBalance'] = result[\"unlocked_balance\"]\n result['lockedAmount'] = result[\"balance\"]-result[\"unlocked_balance\"]\n if coin_family == \"XMR\" and method_name == \"get_address\":\n resultReformat = {'addresses' : []}\n for address in result[\"addresses\"]:\n resultReformat['addresses'].append(address[\"address\"])\n result = resultReformat\n if coin_family == \"XMR\" and method_name == \"transfer\":\n if hasattr(config,\"daemon\"+coin):\n newCoinConfig = getattr(config,\"daemon\"+coin)\n newCoinConfig.fee = result[\"fee\"]\n setattr(config,\"daemon\"+coin,newCoinConfig)\n result[\"transactionHash\"] = result[\"tx_hash\"]\n if coin_family == \"TRTL\" and method_name == \"sendTransaction\":\n result[\"fee\"] = payload[\"fee\"]\n if coin_family == \"XMR\" and random.randint(1,101) > 99: # only random log:\n print(coin+\" \"+method_name+\" RPC Result from XMR family: \"+json.dumps(result))\n return result\n else:\n print(coin + \" RPC Error status : \"+response.status);\n return None\n\nasync def call_doge_ltc(method_name: str, coin: str, payload: str = None) -> Dict:\n headers = {\n 'content-type': 'text/plain;',\n }\n if payload is None:\n data = '{\"jsonrpc\": \"1.0\", \"id\":\"'+str(uuid4())+'\", \"method\": \"'+method_name+'\", \"params\": [] }'\n else:\n data = '{\"jsonrpc\": \"1.0\", \"id\":\"'+str(uuid4())+'\", \"method\": \"'+method_name+'\", \"params\": ['+payload+'] }'\n url = None\n if coin.upper() == \"DOGE\":\n url = f'http://{config.daemonDOGE.username}:{config.daemonDOGE.password}@{config.daemonDOGE.host}:{config.daemonDOGE.rpcport}/'\n elif coin.upper() == \"LTC\":\n url = f'http://{config.daemonLTC.username}:{config.daemonLTC.password}@{config.daemonLTC.host}:{config.daemonLTC.rpcport}/'\n async with aiohttp.ClientSession() as session:\n async with session.post(url, data=data, timeout=60) as response:\n if response.status == 200:\n res_data = await response.read()\n res_data = res_data.decode('utf-8')\n await session.close()\n decoded_data = json.loads(res_data)\n return decoded_data['result']\n\n\ndef get_wallet_rpc_url(coin: str = None):\n return \"http://\"+getattr(config,\"daemon\"+coin,config.daemonWRKZ).wallethost+\":\"+str(getattr(config,\"daemon\"+coin,config.daemonWRKZ).walletport)\\\n + '/json_rpc'\n\n","sub_path":"wrkzcoin_tipbot/rpc_client.py","file_name":"rpc_client.py","file_ext":"py","file_size_in_byte":6977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"398158118","text":"'''\r\n@author: https://www.youtube.com/watch?v=FxSsnHeWQBY\r\n- Revision 2: use self.assertEqual()\r\n'''\r\nimport unittest\r\nfrom NedBatchelder.UnitTest.portfolio import Portfolio\r\n\r\nclass PortfiolioTest(unittest.TestCase):\r\n def test_empty(self):\r\n ''' test empty portfolio '''\r\n p = Portfolio()\r\n# assert p.cost() == 0\r\n self.assertEqual(p.cost(), 0)\r\n \r\n def test_buy_one_stock(self):\r\n ''' test buy one stock '''\r\n p = Portfolio()\r\n p.buy(\"IBM\", 100, 176.48)\r\n# assert p.cost() == 17648\r\n self.assertEqual(p.cost(), 17648)\r\n \r\n def test_buy_two_stocks(self):\r\n ''' test buy two stocks '''\r\n p = Portfolio()\r\n p.buy(\"IBM\", 100, 176.48)\r\n p.buy(\"HQP\", 101, 36.15)\r\n# assert p.cost() == 21263.0\r\n self.assertEqual(p.cost(), 21263.0)\r\n","sub_path":"Python2/NedBatchelder/UnitTest/portfolio_test2.py","file_name":"portfolio_test2.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"141146321","text":"from django.conf.urls import patterns, url\n\nfrom syncfolder import views\n\nurlpatterns = patterns('',\n\n\turl(r'^$', views.index, name='index'),\n\turl(r'^send$', views.send, name='send'),\n\turl(r'^remove$', views.remove, name='remove'),\n\turl(r'^update$', views.update, name='update'),\n)","sub_path":"syncfolder/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"618041595","text":"import os\nimport pickle\nimport time\n \nimport click\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom sklearn.metrics import roc_auc_score\nfrom torch import optim\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom models.nrms import NRMS\nfrom utils.config import prepare_config\nfrom utils.dataloader import DataSetTrn, DataSetTest\nfrom utils.evaluation import ndcg_score, mrr_score\nfrom utils.selector import NewsSelector\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef set_data_paths(path):\n paths = {'behaviors': os.path.join(path, 'behaviors.tsv'),\n 'news': os.path.join(path, 'news.tsv'),\n 'entity': os.path.join(path, 'entity_embedding.vec'),\n 'relation': os.path.join(path, 'relation_embedding.vec')}\n return paths\n\n\ndef set_util_paths(path):\n paths = {'embedding': os.path.join(path, 'embedding.npy'),\n 'uid2index': os.path.join(path, 'uid2index.pkl'),\n 'word_dict': os.path.join(path, 'word_dict.pkl')}\n return paths\n\n\ndef load_dict(file_path):\n with open(file_path, \"rb\") as f:\n return pickle.load(f)\n\n\ndef set_seed(seed):\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n\n@click.command()\n@click.option('--data_path', type=str, default='/data/mind')\n@click.option('--data', type=str, default='large')\n@click.option('--out_path', type=str, default='../out')\n@click.option('--config_path', type=str, default='./config.yaml')\n@click.option('--eval_every', type=int, default=3)\ndef main(data_path, data, out_path, config_path, eval_every):\n start_time = time.time()\n\n # read paths\n trn_data = os.path.join(data_path, f'MIND{data}_train')\n vld_data = os.path.join(data_path, f'MIND{data}_dev')\n util_data = os.path.join(data_path, 'utils')\n\n trn_paths = set_data_paths(trn_data)\n vld_paths = set_data_paths(vld_data)\n util_paths = set_util_paths(util_data)\n\n trn_pickle_path = os.path.join(trn_data, 'dataset.pickle')\n vld_pickle_path = os.path.join(vld_data, 'dataset.pickle')\n\n # read configuration file\n config = prepare_config(config_path,\n wordEmb_file=util_paths['embedding'],\n wordDict_file=util_paths['word_dict'],\n userDict_file=util_paths['uid2index'])\n\n # out path\n num_global = config['pop'] # 7\n num_fresh = config['fresh'] # 1 \n out_path = os.path.join(out_path, f'MIND{data}_dev_pop{num_global}_fresh{num_fresh}')\n os.makedirs(out_path, exist_ok=True)\n\n # set\n seed = config['seed']\n set_seed(seed)\n epochs = config['epochs']\n metrics = {metric: 0. for metric in config['metrics']}\n\n # load dictionaries\n word2idx = load_dict(config['wordDict_file'])\n uid2idx = load_dict(config['userDict_file'])\n\n # load datasets and define dataloaders\n if os.path.exists(trn_pickle_path):\n with open(trn_pickle_path, 'rb') as f:\n trn_set = pickle.load(f)\n else:\n trn_selector = NewsSelector(data_type1=data, data_type2='train',\n num_pop=20,\n num_fresh=20)\n trn_set = DataSetTrn(trn_paths['news'], trn_paths['behaviors'],\n word2idx=word2idx, uid2idx=uid2idx,\n selector=trn_selector, config=config)\n with open(trn_pickle_path, 'wb') as f:\n pickle.dump(trn_set, f)\n\n if os.path.exists(vld_pickle_path):\n with open(vld_pickle_path, 'rb') as f:\n vld_set = pickle.load(f)\n else:\n vld_selector = NewsSelector(data_type1=data, data_type2='dev',\n num_pop=20,\n num_fresh=20)\n vld_set = DataSetTest(vld_paths['news'], vld_paths['behaviors'],\n word2idx=word2idx, uid2idx=uid2idx,\n selector=vld_selector, config=config,\n label_known=True)\n with open(vld_pickle_path, 'wb') as f:\n pickle.dump(vld_set, f)\n\n trn_loader = DataLoader(trn_set, batch_size=config['batch_size'],\n shuffle=True, num_workers=8)\n vld_impr_idx, vld_his, vld_impr, vld_label, vld_pop, vld_fresh =\\\n vld_set.raw_impr_idxs, vld_set.histories_words, vld_set.imprs_words,\\\n vld_set.labels, vld_set.pops_words, vld_set.freshs_words\n\n # define models, optimizer, loss\n # TODO: w2v --> BERT model\n word2vec_emb = np.load(config['wordEmb_file'])\n model = NRMS(config, word2vec_emb).to(DEVICE)\n optimizer = optim.Adam(model.parameters(), lr=float(config['learning_rate']),\n weight_decay=float(config['weight_decay']))\n criterion = nn.CrossEntropyLoss()\n\n print(f'[{time.time()-start_time:5.2f} Sec] Ready for training...')\n\n # train and evaluate\n for epoch in range(1, epochs+1):\n start_time = time.time()\n batch_loss = 0.\n '''\n training\n '''\n for i, (trn_his, trn_pos, trn_neg, trn_pop, trn_fresh) \\\n in tqdm(enumerate(trn_loader), desc='Training', total=len(trn_loader)):\n # ready for training\n model.train()\n optimizer.zero_grad()\n\n # prepare data\n trn_his, trn_pos, trn_neg, trn_pop, trn_fresh = \\\n trn_his.to(DEVICE), trn_pos.to(DEVICE), trn_neg.to(DEVICE),\\\n trn_pop.to(DEVICE), trn_fresh.to(DEVICE)\n trn_pop = trn_pop[:, :config['pop'], :]\n trn_fresh = trn_fresh[:, :config['fresh'], :]\n trn_cand = torch.cat((trn_pos, trn_neg), dim=1)\n trn_global = torch.cat((trn_pop, trn_fresh), dim=1)\n trn_gt = torch.zeros(size=(trn_cand.shape[0],)).long().to(DEVICE)\n\n # inference\n if config['global']:\n trn_user_out = model((trn_his, trn_global), source='pgt')\n else:\n trn_user_out = model(trn_his, source='history')\n trn_cand_out = model(trn_cand, source='candidate')\n prob = torch.matmul(trn_cand_out, trn_user_out.unsqueeze(2)).squeeze()\n\n # training\n loss = criterion(prob, trn_gt)\n loss.backward()\n optimizer.step()\n batch_loss += loss.item()\n\n inter_time = time.time()\n epoch_loss = batch_loss/(i+1)\n\n if epoch % eval_every != 0:\n result = f'Epoch {epoch:3d} [{inter_time - start_time:5.2f}Sec]' \\\n f', TrnLoss:{epoch_loss:.4f}'\n print(result)\n continue\n\n '''\n evaluation\n '''\n with open(os.path.join(out_path, f'prediction-{epoch}.txt'), 'w') as f:\n for j in tqdm(range(len(vld_impr)), desc='Evaluation', total=len(vld_impr)):\n impr_idx_j = vld_impr_idx[j]\n vld_his_j = torch.tensor(vld_his[j]).long().to(DEVICE).unsqueeze(0)\n vld_pop_j = torch.tensor(vld_pop[j]).long().to(DEVICE).unsqueeze(0)\n vld_fresh_j = torch.tensor(vld_fresh[j]).long().to(DEVICE).unsqueeze(0)\n vld_pop_j = vld_pop_j[:, :config['pop'], :]\n vld_fresh_j = vld_fresh_j[:, :config['fresh'], :]\n vld_global_j = torch.cat((vld_pop_j, vld_fresh_j), dim=1)\n if config['global']:\n vld_user_out_j = model((vld_his_j, vld_global_j), source='pgt')\n else:\n vld_user_out_j = model(vld_his_j, source='history')\n vld_cand_j = torch.tensor(vld_impr[j]).long().to(DEVICE).unsqueeze(0)\n vld_cand_out_j = model(vld_cand_j, source='candidate')\n\n scores_j = torch.matmul(vld_cand_out_j, vld_user_out_j.unsqueeze(2)).squeeze()\n scores_j = scores_j.detach().cpu().numpy()\n argmax_idx = (-scores_j).argsort()\n ranks = np.empty_like(argmax_idx)\n ranks[argmax_idx] = np.arange(1, scores_j.shape[0]+1)\n ranks_str = ','.join([str(r) for r in list(ranks)])\n f.write(f'{impr_idx_j} [{ranks_str}]\\n')\n\n vld_gt_j = np.array(vld_label[j])\n\n for metric, _ in metrics.items():\n if metric == 'auc':\n score = roc_auc_score(vld_gt_j, scores_j)\n metrics[metric] += score\n elif metric == 'mrr':\n score = mrr_score(vld_gt_j, scores_j)\n metrics[metric] += score\n elif metric.startswith('ndcg'): # format like: ndcg@5;10\n k = int(metric.split('@')[1])\n score = ndcg_score(vld_gt_j, scores_j, k=k)\n metrics[metric] += score\n\n for metric, _ in metrics.items():\n metrics[metric] /= len(vld_impr)\n\n end_time = time.time()\n\n result = f'Epoch {epoch:3d} [{inter_time - start_time:5.2f} / {end_time - inter_time:5.2f} Sec]' \\\n f', TrnLoss:{epoch_loss:.4f}, '\n for enum, (metric, _) in enumerate(metrics.items(), start=1):\n result += f'{metric}:{metrics[metric]:.4f}'\n if enum < len(metrics):\n result += ', '\n print(result)\n\n\nif __name__ == '__main__':\n main()","sub_path":"NRMS/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"556410219","text":"\"\"\"******************************************************************************\n* Purpose: Simulate Banking Cash Counter Using Queue .\n*\n* @author: Nikhil Lad\n* @version: 3.7\n* @since: 02-01-2019\n*\n******************************************************************************\"\"\"\n\n\nclass Queue:\n def __init__(self): # Creating list of items\n self.items = ['Nikhil','Pushkar','Sagar','Shahazad','Jahnvi']\n self.Total_cash=1000\n\n def push(self, data): # Method to append the data in queue.\n self.items.append(data)\n\n def pop(self): # Method to delete the data from beginning.\n return self.items.pop(0)\n\n def show(self): # Method to print the data .\n print(self.items)\n return self.items\n\n def isEmpty(self): # returns true if queue is empty\n return self.items == []\n\n def peek(self): # Returns the top item form queue but does not removes it.\n if not self.isEmpty():\n return self.items[-1]\n\n def __sizeof__(self): # Calculate size of queue.\n # return self.items\n print(len(self.items))\n\n\n def deposit(self,depo_amt): # Method to add deposit amount.\n self.Total_cash=self.Total_cash+depo_amt\n q.pop()\n print(self.Total_cash)\n q.show()\n\n def withdraw(self,withdraw_amt): # Method to withdraw amount.\n if self.Total_cash - withdraw_amt>0: # if withdraw balance is greater than total cash in bank the users request if refused .\n self.Total_cash=self.Total_cash - withdraw_amt\n q.pop()\n print(self.Total_cash)\n q.show()\n else:\n print(\"Not enough balance\")\n q.pop()\n\n\nq=Queue()\n\nq.show() # prints whole queue.\ntry:\n for i in range(0,len(q.items)):\n print('Welcome : ',q.items[0])\n c = int(input(\"please select choice 1: Deposit 2: Withdraw money \"))\n if c==1:\n depo_amt=int(input(\"Enter amount to deposit \"))\n q.deposit(depo_amt)\n else:\n withdraw_amt=int(input(\"Enter amount to withdraw \"))\n q.withdraw(withdraw_amt)\nexcept Exception as e:\n print(e)\n\n\n","sub_path":"Data Structure/Queue.py","file_name":"Queue.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"14746770","text":"###############################################################################\n##\n## Filename: caesar_cipher.py\n## Date: 1 March 2019\n## Author: Robert A. Bridges\n##\n## Description:\n## A simple caesar cipher program made as a demonstration for my daughter.\n##\n###############################################################################\n\nletter_codes = {\n 'A': 1,\n 'B': 2,\n 'C': 3,\n 'D': 4,\n 'E': 5,\n 'F': 6,\n 'G': 7,\n 'H': 8,\n 'I': 9,\n 'J': 10,\n 'K': 11,\n 'L': 12,\n 'M': 13,\n 'N': 14,\n 'O': 15,\n 'P': 16,\n 'Q': 17,\n 'R': 18,\n 'S': 19,\n 'T': 20,\n 'U': 21,\n 'V': 22,\n 'W': 23,\n 'X': 24,\n 'Y': 25,\n 'Z': 26\n}\n\nnumber_codes = {\n 1: 'A',\n 2: 'B',\n 3: 'C',\n 4: 'D',\n 5: 'E',\n 6: 'F',\n 7: 'G',\n 8: 'H',\n 9: 'I',\n 10: 'J',\n 11: 'K',\n 12: 'L',\n 13: 'M',\n 14: 'N',\n 15: 'O',\n 16: 'P',\n 17: 'Q',\n 18: 'R',\n 19: 'S',\n 20: 'T',\n 21: 'U',\n 22: 'V',\n 23: 'W',\n 24: 'X',\n 25: 'Y',\n 26: 'Z'\n}\n\ndef encrypt_or_decrypt(crypt_option, message, encryption_key):\n crypt_message = \"\"\n for letter in message:\n if letter != ' ':\n letter_key = letter_codes[letter]\n if crypt_option == 'encrypt':\n letter_key += encryption_key\n elif crypt_option == 'decrypt':\n letter_key -= encryption_key\n if letter_key > 26:\n letter_key -= 26\n elif letter_key < 1:\n letter_key += 26\n crypt_message += number_codes[letter_key]\n return crypt_message\n\nif __name__ == \"__main__\":\n option = \"\"\n key = 0\n initial_message = \"\"\n final_message = \"\"\n\n while (True):\n print(\"Do you want to encrypt or decrypt a message?\")\n print(\"(enter 'encrypt' or 'decrypt')\")\n option = input(\"> \").lower()\n if option == 'encrypt' or option == 'decrypt':\n break\n\n print(\"What is the message?\")\n initial_message = input(\"> \").upper()\n print(\"What is the encryption key?\")\n print(\"(enter a number between 1 and 26)\")\n key = int(input(\"> \"))\n final_message = encrypt_or_decrypt(option, initial_message, key)\n print(\"Here is your final message:\")\n print(final_message)","sub_path":"caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"272635473","text":"#!/bin/env/python\n# coding=utf-8\nimport sys\nimport requests\nimport time\nimport os\nimport json\nimport copy\nfrom threading import Thread\nfrom functools import wraps\n\nfrom util.sign_maker import sign_params\nfrom util.config_parser import load_config\nfrom util.json_parser import load_json\nfrom util.api_parser import format_api, handle_source, exec_time\n\n\ndef threads(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n # print(\"start:%s\" % time.ctime())\n # print(args)\n # print(kwargs)\n concurrency = args[1].get('concurrency')\n times = args[1].get('times')\n \n if not concurrency:\n concurrency = 1\n else:\n concurrency = int(concurrency)\n if not times:\n times = 1\n else:\n times = int(times)\n\n # if not concurrency:\n # concurrency = 1\n # else:\n # try:\n # concurrency = int(concurrency)\n # except TypeError:\n # print(\"concurrency数据格式错误\")\n # if not times:\n # times = 1\n # else:\n # try:\n # times = int(times)\n # except TypeError:\n # print(\"times数据格式错误\")\n\n for i in range(0, times//concurrency):\n threads = []\n for i in range(concurrency):\n if not args or kwargs:\n t = Thread(target=func)\n elif args:\n t = Thread(target=func, args=args)\n elif kwargs:\n t = Thread(target=func, args=kwargs)\n threads.append(t)\n for i in range(concurrency):\n threads[i].start()\n for i in range(concurrency):\n threads[i].join()\n # print(\"end:%s\" % time.ctime())\n return func\n return wrapper\n\n\nclass PostBoy(object):\n @exec_time\n def __init__(self, api_file, config_file='default.conf'):\n self.api_file = api_file\n self.config = load_config(config_file)\n apis = load_json(api_file)\n self.apis = apis if isinstance(apis, list) else [apis]\n self.apis = self.mix_apis()\n self.sources = handle_source(self.apis)\n if os.path.basename(api_file)[0:4].lower() == 'test':\n self.mode = 'Test'\n else:\n self.mode = 'Debug'\n print(self.mode)\n\n @exec_time\n def mix_apis(self):\n config = copy.deepcopy(self.config)\n func = lambda x:config if config.update(x) else config\n return list(map(func, self.apis))\n\n @exec_time\n def update_data(self, api):\n return format_api(api, self.sources)\n\n\n\n @threads\n def post(self, api):\n\n method = api.get('method')\n if not method or method.upper() == 'POST':\n start_time = time.time()\n\n session = api.get('session')\n url = api.get('url')\n headers = api.get('headers')\n cookies = api.get('cookies')\n data = api.get('data')\n @exec_time\n def _post():\n res = session.post(url, headers=headers, cookies=cookies, data=data)\n return res\n\n res = _post()\n if self.mode == 'Debug':\n print(data)\n print(json.dumps(res.json(), ensure_ascii=False))\n print(\"--- %.3fs\" % (time.time()-start_time))\n else:\n print(res.text)\n if '\"code\":100000' in res.text:\n print(\"%s ------ PASS\" % self.api_file)\n else:\n print(\"%s ------ FAIL\" % self.api_file)\n # print(json.dumps(res.json(), ensure_ascii=False, indent=2)) # to handle ISO-8895-1\n\n\n def send_request(self):\n for api in self.apis:\n self.post(self.update_data(api))\n \n\n# def main():\n# if len(sys.argv) > 1:\n# # print(sys.argv[1]) \n\n# postboy.post(sys.argv[1])\n \n\nif __name__ == '__main__':\n # main()\n # post('api/user/getInfoById') \n # post('api/getGoodsCode.json', 'http://detail.spicespirit.com') \n\n pb = PostBoy(\"api/shop/test_matchStation.json\")\n pb.send_request()\n","sub_path":"v0.3.1/postboy.py","file_name":"postboy.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"401868910","text":"from datetime import datetime, timedelta\n\nfrom area.serializers import AreaSerializer\nfrom core.models import (\n Area,\n Boec,\n Brigade,\n Conference,\n Position,\n Season,\n SeasonReport,\n Shtab,\n UserApply,\n)\nfrom core.serializers import DynamicFieldsModelSerializer\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\nfrom shtab.serializers import ShtabSerializer\n\n\nclass FilteredListSerializer(serializers.ListSerializer):\n def to_representation(self, data):\n request = self.context.get(\"request\")\n if request:\n shtab_id = request.query_params.get(\"shtab\")\n if shtab_id is not None:\n data = data.filter(shtab=shtab_id)\n\n return super(FilteredListSerializer, self).to_representation(data)\n\n\nclass BrigadeShortSerializer(DynamicFieldsModelSerializer):\n \"\"\"serializer with only id and title\"\"\"\n\n full_title = serializers.SerializerMethodField(\"get_model_title\")\n can_edit = serializers.BooleanField(read_only=True)\n apply_status = serializers.CharField()\n\n shtab = ShtabSerializer(read_only=True, fields=(\"id\", \"title\"))\n\n def get_model_title(self, obj):\n return str(obj)\n\n class Meta:\n list_serializer_class = FilteredListSerializer\n model = Brigade\n fields = (\n \"id\",\n \"full_title\",\n \"title\",\n \"area\",\n \"can_edit\",\n \"shtab\",\n \"apply_status\",\n )\n\n read_only_fields = (\"id\", \"can_edit\", \"shtab\", \"apply_status\")\n\n\nclass BoecViewerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Boec\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"middle_name\",\n \"full_name\",\n \"vk_id\",\n )\n\n\nclass BoecInfoSerializer(DynamicFieldsModelSerializer):\n \"\"\"serializer for boec objects\"\"\"\n\n brigades = serializers.SerializerMethodField(\"get_boec_brigades\")\n\n def get_boec_brigades(self, obj):\n\n brigades = dict()\n # 500ms\n qs = (\n Brigade.objects.filter(season_reports__seasons__boec=obj)\n .exclude(area__id=10)\n .distinct()\n .values_list(\"id\", \"title\", \"custom_area_prefix\", \"area__short_title\")\n )\n for brigade in qs:\n area_prefix = brigade[2] if brigade[2] else brigade[3]\n full_title = f\"{area_prefix} «{brigade[1]}»\"\n brigades[brigade[0]] = {\n \"id\": brigade[0],\n \"title\": brigade[1],\n \"full_title\": full_title,\n }\n\n # 330ms\n # reports = (\n # SeasonReport.objects\n # .filter(seasons__boec=obj)\n # .values_list(\n # \"brigade__id\",\n # \"brigade__title\",\n # \"brigade__custom_area_prefix\",\n # \"brigade__area__short_title\",\n # )\n # )\n # for brigade in reports:\n # area_prefix = brigade[2] if brigade[2] else brigade[3]\n # full_title = f\"{area_prefix} «{brigade[1]}»\"\n # brigades[brigade[0]] = {\n # \"id\": brigade[0],\n # \"title\": brigade[1],\n # \"full_title\": full_title,\n # }\n\n return brigades.values()\n\n class Meta:\n model = Boec\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"middle_name\",\n \"full_name\",\n \"vk_id\",\n \"brigades\",\n )\n read_only_fields = (\"id\", \"full_name\", \"brigades\")\n\n\nclass BoecTelegramSerializer(serializers.ModelSerializer):\n \"Serializer for boec objects for Telegram interaction\"\n\n class Meta:\n model = Boec\n fields = (\n \"id\",\n \"full_name\",\n \"vk_id\",\n )\n read_only_fields = (\"id\", \"full_name\")\n\n\nclass BoecSerializer(serializers.ModelSerializer):\n \"\"\"serializer for boec objects\"\"\"\n\n can_edit = serializers.BooleanField(read_only=True)\n\n class Meta:\n model = Boec\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"middle_name\",\n \"date_of_birth\",\n \"full_name\",\n \"vk_id\",\n \"telegram\",\n \"can_edit\",\n \"university\",\n \"phone\",\n )\n read_only_fields = (\"id\", \"full_name\")\n\n\nclass BrigadeMemberSerializer(serializers.ModelSerializer):\n \"\"\"serializer for boec objects\"\"\"\n\n season_years = serializers.SerializerMethodField(\"get_season_years\", read_only=True)\n\n def get_season_years(self, obj):\n view = self.context.get(\"view\", None)\n\n if view:\n pk = view.kwargs.get(\"brigade_pk\")\n years = [\n season.season_reports.only(\"year\").first().year\n for season in obj.seasons.filter(season_reports__brigade=pk)\n ]\n return sorted(years)\n\n return []\n\n class Meta:\n model = Boec\n fields = (\n \"id\",\n \"first_name\",\n \"last_name\",\n \"middle_name\",\n \"full_name\",\n \"vk_id\",\n \"season_years\",\n )\n\n\nclass BrigadeSerializer(DynamicFieldsModelSerializer):\n \"\"\"serializer for brigade objects\"\"\"\n\n shtab = ShtabSerializer(read_only=True, fields=(\"id\", \"title\"))\n area = AreaSerializer(read_only=True)\n\n full_title = serializers.SerializerMethodField(\"get_model_title\")\n season_request_count = serializers.SerializerMethodField(\"get_season_request_count\")\n candidates_count = serializers.SerializerMethodField(\"get_candidates_count\")\n can_edit = serializers.BooleanField(read_only=True)\n apply_status = serializers.CharField()\n can_generate = serializers.SerializerMethodField(\"get_can_generate\")\n\n def get_model_title(self, obj):\n return str(obj)\n\n def get_season_request_count(self, obj):\n return obj.season_reports.filter(\n state=SeasonReport.SeasonReportState.REQUEST\n ).count()\n\n def get_candidates_count(self, obj):\n return obj.applies.filter(state=UserApply.ApplyState.INITIAL).count()\n\n def get_can_generate(self, obj):\n if not obj.last_sheets_trigger or (\n timezone.now() - obj.last_sheets_trigger\n ) > timedelta(hours=24):\n return True\n return False\n\n class Meta:\n model = Brigade\n fields = (\n \"id\",\n \"title\",\n \"shtab\",\n \"area\",\n \"date_of_birth\",\n \"full_title\",\n \"title\",\n \"state\",\n \"can_edit\",\n \"members\",\n \"apply_status\",\n \"season_request_count\",\n \"candidates_count\",\n \"sheets_link\",\n \"can_generate\",\n \"last_sheets_trigger\",\n \"readyForApplication\",\n )\n read_only_fields = (\n \"id\",\n \"can_edit\",\n \"season_request_count\",\n \"apply_status\",\n \"candidates_count\",\n \"sheets_link\",\n \"can_generate\",\n )\n\n\nclass PositionSerializer(serializers.ModelSerializer):\n \"\"\"serializer for the position objects\"\"\"\n\n boec = BoecInfoSerializer(required=False)\n brigade = BrigadeShortSerializer(\n required=False,\n read_only=True,\n exclude=(\n \"can_edit\",\n \"apply_status\",\n ),\n )\n shtab = ShtabSerializer(required=False, read_only=True, exclude=(\"can_edit\",))\n boec_id = serializers.PrimaryKeyRelatedField(\n queryset=Boec.objects.all(), source=\"boec\"\n )\n shtab_id = serializers.PrimaryKeyRelatedField(\n required=False, queryset=Shtab.objects.all(), source=\"shtab\"\n )\n brigade_id = serializers.PrimaryKeyRelatedField(\n required=False, queryset=Brigade.objects.all(), source=\"brigade\"\n )\n\n def check_duplicates(\n self, boec: Boec, position: int, brigade: Brigade = None, shtab: Shtab = None\n ):\n # is_boec_exists = Position.objects.filter(\n # boec=boec, to_date__isnull=True, brigade=brigade, shtab=shtab\n # ).exists()\n\n # if is_boec_exists:\n # raise ValidationError(\n # {\"error\": _(\"Один человек не может совмещать две должности\")},\n # code=\"validation\",\n # )\n\n is_position_exists = (\n Position.objects.filter(\n position=position, to_date__isnull=True, brigade=brigade, shtab=shtab\n )\n .exclude(position=Position.PositionEnum.WORKER)\n .exists()\n )\n\n if is_position_exists:\n raise ValidationError(\n {\"error\": _(\"Два человека не могут находиться в одной должности\")},\n code=\"validation\",\n )\n\n def is_valid(self, raise_exception=False, **kwrgs):\n pk_values = {}\n brigade_pk = self.context.get(\"brigade_pk\", None)\n shtab_pk = self.context.get(\"shtab_pk\", None)\n if brigade_pk:\n pk_values[\"brigade_id\"] = brigade_pk\n if shtab_pk:\n pk_values[\"shtab_id\"] = shtab_pk\n\n self.initial_data = {**self.initial_data, **pk_values}\n return super().is_valid(raise_exception=raise_exception, **kwrgs)\n\n def create(self, validated_data):\n if \"to_date\" not in validated_data or validated_data[\"to_date\"] == None:\n self.check_duplicates(\n boec=validated_data[\"boec\"],\n position=validated_data[\"position\"],\n brigade=validated_data.get(\"brigade\", None),\n shtab=validated_data.get(\"shtab\", None),\n )\n return super().create(validated_data)\n\n def update(self, instance, validated_data):\n if (\n \"to_date\" in validated_data\n and validated_data[\"to_date\"] == None\n and not instance.to_date == None\n ):\n self.check_duplicates(\n boec=instance.boec,\n position=validated_data[\"position\"],\n brigade=instance.brigade,\n shtab=instance.shtab,\n )\n return super().update(instance, validated_data)\n\n # def save(self, **kwargs):\n # return super().save(**kwargs)\n\n class Meta:\n model = Position\n fields = (\n \"id\",\n \"position\",\n \"boec\",\n \"brigade\",\n \"brigade_id\",\n \"shtab\",\n \"shtab_id\",\n \"from_date\",\n \"to_date\",\n \"boec_id\",\n )\n read_only_fields = (\"id\", \"boec\", \"shtab\", \"brigade\")\n\n\nclass ConferenceSerializer(serializers.ModelSerializer):\n \"\"\"serializer for conference objects\"\"\"\n\n class Meta:\n model = Conference\n fields = (\"id\", \"brigades\", \"date\", \"shtabs\")\n read_only_fields = (\"id\",)\n\n\nclass BoecMergeSerializer(serializers.Serializer):\n \"\"\"serializer for merge objects\"\"\"\n\n target_id = serializers.IntegerField()\n donor_id = serializers.IntegerField()\n","sub_path":"app/so/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":11305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"575687239","text":"from CRABClient.UserUtilities import config\nconfig = config()\n\nconfig.General.requestName = 'B2GDAS_SingleMuon'\nconfig.General.workArea = 'crab_projects'\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = True\n\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'PSet.py'\n\nconfig.Data.inputDataset = '/SingleMuon/Run2017B-17Nov2017-v1/MINIAOD'\nconfig.Data.inputDBS = 'global'\n#config.Data.splitting = 'LumiBased'\nconfig.Data.splitting = 'Automatic'\n#config.Data.unitsPerJob = 200\nconfig.Data.lumiMask = 'https://cms-service-dqm.web.cern.ch/cms-service-dqm/CAF/certification/Collisions17/13TeV/ReReco/Cert_294927-306462_13TeV_EOY2017ReReco_Collisions17_JSON_v1.txt'\n#config.Data.runRange = '273403-273404'\n\nconfig.Site.storageSite = 'T2_DE_DESY'\n\nconfig.JobType.scriptExe = 'execute_for_crab_data.sh'\n\nconfig.JobType.outputFiles = ['output.root']\nconfig.JobType.inputFiles = ['FrameworkJobReport.xml', 'execute_for_crab.py', 'b2gdas_fwlite.py', 'leptonic_nu_z_component.py', 'JECs', 'purw.root', 'MuonID_Sys.root', 'MuonIso_Sys.root', 'MuonTrigger_SF.root' , 'rootlogon.C']\n","sub_path":"test/crab_submit_data.py","file_name":"crab_submit_data.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"294723465","text":"# read input from standard i/p\nprint(\"Enter the string\")\np_str = input()\n#p_str = \"()(())()\"\np_dict = {'opening': 0, 'closing': 0}\n\ndef total_no_of_paranthesis_are_even():\n\n if len(p_str) % 2 != 0:\n print(\"NO\")\n exit(0)\n print(\"Length is even, let's verify if they are in equal numbers.\")\n\ndef equal_number_of_paranthesis():\n \n for p in p_str:\n if p == '(':\n p_dict['opening'] += 1\n else:\n p_dict['closing'] += 1\n\n if p_dict['opening'] != p_dict['closing']:\n print(\"NO\")\n exit(0)\n\n print(\"Both the opening and paranthesis are in equal numbers. We will finally \\\n check if an open is enclosed with a close.\")\n\ndef validate_paranthesis():\n\n p_stack = []\n for p in p_str:\n if p == '(':\n p_stack.append('(')\n else:\n if p_stack:\n if p_stack[-1] == '(':\n p_stack.pop()\n else:\n p_stack.append(p)\n\n if len(p_stack) != 0:\n print(\"\\nNO\\n\")\n exit(0)\n\n print('\\nYES\\n')\n\ndef main():\n \n # first check if the total number of paranthesis is even, else it is unbalanced\n total_no_of_paranthesis_are_even()\n\n # now loop over and update the dictionary such and verify if the opening\n # and closing paranthesis are in equal numbers,\n # else it is unbalanced\n equal_number_of_paranthesis()\n \n # final check, an opening paranthesis should have a corresponding closing one\n validate_paranthesis()\n\nif __name__ == '__main__':\n main()","sub_path":"code/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"271534826","text":"# Dataloader from PASCAL VOC dataset directory\n\nimport torch\nfrom torchvision.transforms import transforms\nimport os\nimport numpy as np\nimport albumentations as A\nimport xml.etree.ElementTree as Et\nfrom PIL import Image\n\nfrom datonlib.utils import general, plot\n\n\nDEFAULT_ROOT = \"../../open_dataset/VOCtrainval_11-May-2012/VOCdevkit/VOC2012\"\nDEFAULT_TARGET_CLS = \"PERSON\"\nDEFAULT_MODE = \"detection\"\nDEFAULT_SIZE = (224, 224)\nDEFAULT_TRANSFORM = A.Compose([\n A.ColorJitter(),\n A.HueSaturationValue(),\n A.RandomBrightnessContrast(),\n])\nDEFAULT_TARGET_TRANSFORM = A.Compose([\n])\nTOTENSOR = transforms.ToTensor()\n\nclass VOCDataset(torch.utils.data.Dataset):\n def __init__(self,\n root: str,\n target_cls: str=None,\n trainval: str=\"train\",\n mode: str=\"detection\",\n transform: A.core.composition.Compose=None,\n ):\n if trainval not in [\"train\", \"val\", \"trainval\", \"test\"]:\n raise Exception(f\"'trainval' should be selected along ['train', 'val', 'trainval', 'test']\")\n if \"test\" in root:\n trainval = \"test\"\n\n cls_dir = os.path.join(root, \"ImageSets\", \"main\")\n self.cls_list = sorted(list(set([x.split(\"_\")[0] for x in os.listdir(cls_dir)\n if (not x.split(\"_\")[0].endswith(\"txt\"))])))\n\n if target_cls is None or trainval == \"test\":\n target_file = \"{}.txt\".format(trainval)\n print(target_file)\n target_path = os.path.join(cls_dir, target_file)\n if os.path.isfile(target_path):\n with open(target_path, \"r\") as f:\n self.target_imgs = [x.strip().split()[0] for x in f.readlines()]\n else:\n raise Exception(f\"'{target_file}' is not found in VOC '{trainval}' dataset\")\n else:\n target_file = \"{}_{}.txt\".format(target_cls, trainval)\n target_path = os.path.join(cls_dir, target_file)\n if os.path.isfile(target_path):\n with open(target_path, \"r\") as f:\n self.target_imgs = [x.strip().split()[0] for x in f.readlines()\n if x.strip().split()[1] == \"1\"]\n else:\n raise Exception(f\"class '{target_cls}' is not found in VOC '{trainval}' dataset\")\n\n if mode not in [\"detection\", \"semantic_seg\", \"instance_seg\"]:\n raise Exception(f\"'mode' should be selected along ['detection', 'semantic_seg', 'instance_seg']\")\n self.mode = mode\n self.transform = transform\n\n self.img_dir = os.path.join(root, \"JPEGImages\")\n self.det_dir = os.path.join(root, \"Annotations\")\n self.semantic_seg_dir = os.path.join(root, \"SegmentationClass\")\n self.instance_seg_dir = os.path.join(root, \"SegmentationObject\")\n\n def __len__(self):\n return len(self.target_imgs)\n\n def __getitem__(self, idx):\n if self.mode == \"detection\":\n return self.get_det_item(idx)\n elif self.mode == \"semantic_seg\":\n return self.get_semantic_seg_item(idx)\n elif self.mode == \"instance_seg\":\n return self.get_instance_seg_item(idx)\n else:\n raise Exception(f\"'{self.mode}' is invalid mode!\")\n\n def get_det_item(self, idx):\n # Get image and bounding box(x_min, y_min, x_max, y_max, str: name, int: cls)\n img_path = os.path.join(self.img_dir, self.target_imgs[idx]+\".jpg\")\n img = np.array(Image.open(img_path))\n annot_path = os.path.join(self.det_dir, self.target_imgs[idx]+\".xml\")\n bboxes = []\n if os.path.isfile(annot_path):\n with open(annot_path, \"r\") as f:\n tree = Et.parse(f)\n root = tree.getroot()\n objects = root.findall(\"object\")\n for obj in objects:\n name = obj.find(\"name\").text\n cls = self.cls_list.index(name)\n bbox = obj.find(\"bndbox\")\n x_min = int(bbox.find(\"xmin\").text)\n y_min = int(bbox.find(\"ymin\").text)\n x_max = int(bbox.find(\"xmax\").text)\n y_max = int(bbox.find(\"ymax\").text)\n bboxes.append([x_min, y_min, x_max, y_max, name, cls])\n\n if self.transform is not None:\n transformed = self.transform(image=img, bboxes=bboxes)\n img = transformed[\"image\"]\n bboxes = transformed[\"bboxes\"]\n return img, bboxes\n\n def get_semantic_seg_item(self, idx):\n raise Exception(\"Not implemented yet\")\n\n def get_instance_seg_item(self, idx):\n raise Exception(\"Not implemented yet\")\n\n\ndef detection_collate_fn(data):\n img_batch, bbox_batch = [], []\n imgs, bboxes = zip(*data)\n for img, bbox in zip(imgs, bboxes):\n img, ratio, (dw, dh) = plot.letterbox(img, new_shape=DEFAULT_SIZE, auto=False)\n bbox = general.normalize_bboxes(bbox, ratio, dw, dh)\n img_batch.append(TOTENSOR(img).unsqueeze(dim=0))\n bbox_batch.append(bbox)\n img_batch = torch.cat(img_batch)\n return img_batch, bbox_batch\n\n\ncollate_fn_dict = {\n \"detection\": detection_collate_fn,\n}\n\ndef get_VOCDataloader(root: str=DEFAULT_ROOT,\n target_cls: str=DEFAULT_TARGET_CLS,\n mode: str=DEFAULT_MODE,\n transform: A.core.composition.Compose=DEFAULT_TRANSFORM,\n target_transform : A.core.composition.Compose=DEFAULT_TARGET_TRANSFORM,\n train_batch: int=32,\n valid_batch: int=8):\n train_dataset = VOCDataset(root, target_cls, \"train\", mode, transform)\n valid_dataset = VOCDataset(root, target_cls, \"val\", mode, target_transform)\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=train_batch,\n shuffle=True,\n collate_fn=collate_fn_dict[mode]\n )\n valid_dataloader = torch.utils.data.DataLoader(\n valid_dataset,\n batch_size=valid_batch,\n shuffle=False,\n collate_fn=collate_fn_dict[mode]\n )\n return train_dataloader, valid_dataloader\n\n\nif __name__ == \"__main__\":\n import cv2\n\n train_dataloader, valid_dataloder = get_VOCDataloader()\n for imgs, bboxes in train_dataloader:\n print(imgs.shape)\n for img, bbox in zip(imgs, bboxes):\n img_np = img.permute(1, 2, 0).numpy()\n img_np = plot.draw_bboxes(img_np, bbox, color_norm=True)\n cv2.imshow(\"img\", img_np)\n cv2.waitKey(0)\n break\n\n for img, bboxes in valid_dataloder:\n print(img.shape)\n break","sub_path":"data/pascalvoc_dataset.py","file_name":"pascalvoc_dataset.py","file_ext":"py","file_size_in_byte":6676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"578298336","text":"from django.template.loader import render_to_string\nfrom django.utils import timezone, simplejson\n\nfrom trueKarta.apps.posts.models import Post\nfrom trueKarta.apps.users.models import Profile\nfrom trueKarta.siteFunctions import detectMobile\n \ndef base(request):\n \"\"\" can use these as variables in any template \"\"\"\n user = request.user\n authent = user.is_authenticated()\n\n #user info\n if authent:\n \"\"\" render profile \"\"\"\n votes = user.votehistory_set.all()\n upVotes = simplejson.dumps(list(votes.filter(voteUp=True)[:60].values_list('post')))\n downVotes = simplejson.dumps(list(votes.filter(voteDown=True)[:60].values_list('post')))\n\n \"\"\" notifications for new messages and comments \"\"\"\n cPrefs = user.conversationpreference_set.filter(visible=True)\n newMessages = 0\n newComments = 0\n for cPref in cPrefs.filter(newMessages__gt = 0):\n newMessages += cPref.newMessages\n for post in user.post_set.filter(newComments__gt=0):\n newComments += post.newComments\n\n notifications = newMessages + newComments\n \n try:\n user.profile\n except:\n Profile.objects.create(user=user, signature=user.username, resetKey='')\n else: #default\n\n notifications,upVotes,downVotes = None,None,None\n #age of site in hours for slider filter value\n try:\n daysOld = Post.objects.order_by('created')[0]\n daysOld = timezone.now()-daysOld.created\n daysOld = daysOld.days\n except:\n daysOld = 0\n\n return {\n 'user':user,\n 'upVotes':upVotes,\n 'downVotes':downVotes,\n 'authent':authent,\n 'daysOld':daysOld,\n 'notifications':notifications,\n 'mobile':#True\n detectMobile(request)#switch for testing\n }\n\n \n \n ","sub_path":"trueKarta/siteVariables.py","file_name":"siteVariables.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"316553232","text":"#!/usr/bin/python3\n\nimport yaml\n\ndef main():\n hitchhikers = [{\"name\":\"Zaphod Beeblebrox\", \"species\":\"Betelgeusian\"}, {\"name\":\"Authur Dent\",\"species\":\"Human\"}]\n\n print(hitchhikers)\n\n zfile = open(\"galaxyguide.yaml\",\"w\")\n\n yaml.dump(hitchhikers, zfile)\n\n zfile.close()\n\nmain()\n","sub_path":"yamlintro/makeyaml01.py","file_name":"makeyaml01.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"579809557","text":"# Write a main for the function called compare ( x, y ) shown below.\n\ndef compare (x,y):\n if x < y:\n print (f'{x} is less than {y}')\n\n elif x > y:\n print (f'{x} is greater than {y}')\n\n else:\n print (f' {x} and {y} are equal')\n\nnumber1 = int(input(\"Please enter the first number \"))\nnumber2 = int(input(\"Please enter the second number \"))\n\ncompare(number1, number2)","sub_path":"Practice Exercise 2.py","file_name":"Practice Exercise 2.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"513489422","text":"from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D\nfrom keras.models import Model\n\n\ndef basic_convolutional_autoencoder(input_shape=(256, 256, 3)):\n input_img = Input(shape=input_shape)\n\n x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\n encoded = MaxPooling2D((2, 2), padding='same')(x)\n\n x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)\n x = UpSampling2D((2, 2))(x)\n x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)\n x = UpSampling2D((2, 2))(x)\n x = Conv2D(16, (3, 3), activation='relu', padding='same')(x)\n x = UpSampling2D((2, 2))(x)\n decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)\n\n autoencoder = Model(input_img, decoded)\n autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\n\n return autoencoder\n","sub_path":"training/autoencodermodels.py","file_name":"autoencodermodels.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"574358249","text":"n = int(input(\"From : \"))\nm = int(input(\"Where : \"))\n\nprint(\"All perfect numbers are: \")\nfor j in range(n,m+1):\n sum = 0\n for i in range(1,(j//2) + 1):\n if j % i == 0:\n sum += i\n if j == sum:\n print(j)","sub_path":"perfect_num_function.py","file_name":"perfect_num_function.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"577879219","text":"\"\"\"\n:authors: Anastasiia-Khab, Anna Bretsko, Partsey, Ihor Soroka\n:chapter: 7\n: tasks: 323, 325, 331, 329\n\"\"\"\n\n\ndef task_323(num):\n \"\"\"\n Дано натуральное число n. Получить все натуральные числа, меньшие n и взаимно простые с ним.\n :param num: natural\n :return: list of natural numbers n, n 0:\n amount = 0\n for dig in str(nnumber):\n amount += int(dig)\n if (amount ** 2) == mnumber:\n res.append(nnumber)\n nnumber -= 1\n return res\n","sub_path":"tasks/chapter10.py","file_name":"chapter10.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"382336394","text":"from rest_framework import routers\r\nfrom api.views import RegistrationViewSet, EvaluatorViewSet, CandidateViewSet, EventViewSet, GetAuthToken\r\nfrom django.urls import path\r\n\r\nrouter = routers.SimpleRouter()\r\n\r\nurlpatterns = [\r\n path(\"login/\", GetAuthToken.as_view())\r\n]\r\n\r\nrouter.register(\"candidates\", CandidateViewSet)\r\nrouter.register(\"evaluators\", EvaluatorViewSet)\r\nrouter.register(\"registration\", RegistrationViewSet)\r\nrouter.register(\"event\", EventViewSet)\r\n\r\nurlpatterns = urlpatterns + router.urls","sub_path":"outreach/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"302172951","text":"#!/usr/bin/env python2\nimport argparse\nfrom string import Template\nimport subprocess as sp\n\n\ndef run_process(command):\n p = sp.Popen(command)\n p.wait()\n return p.returncode\n\n\ndef make_shell_script(templatePath, scriptPath, substitutions):\n with open(templatePath, \"r\") as templateFile:\n scriptTemplate = Template(templateFile.read())\n # Define each variable required by the template\n # Substitute into the string\n scriptString = scriptTemplate.substitute(substitutions)\n # Write to an output file\n with open(scriptPath, \"w\") as scriptFile:\n scriptFile.write(scriptString)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-p',\n '--path',\n type=str,\n help='Path to where results should be stored',\n required=True)\n parser.add_argument(\n '-t',\n '--n_toys',\n type=int,\n help='Number of toys per job',\n required=True)\n parser.add_argument(\n '-j',\n '--n_jobs',\n type=int,\n help='Number of jobs to submit',\n required=True)\n args = parser.parse_args()\n\n path = args.path\n n_toys = args.n_toys\n n_jobs = args.n_jobs\n\n templatePath = \"/home/rollings/Bu2Dst0h_2d/FittingProgramme/toys_test/shell_scripts/generate_2d.sh.tmpl\"\n for i in range(0, n_jobs):\n scriptPath = \"/home/rollings/Bu2Dst0h_2d/FittingProgramme/toys_test/tmp/generate_2d_\" + str(\n i) + \".sh\"\n substitutions = {\n \"PATH\":\n path,\n \"nToys\":\n n_toys,\n \"nJob\":\n i,\n \"GCCROOT\":\n \"/cvmfs/lhcb.cern.ch/lib/lcg/releases/LCG_88/gcc/4.9.3/x86_64-slc6\",\n \"LD_LIBRARY_PATH\":\n \"/home/rollings/Software/install/lib64:/home/rollings/Software/install/lib:/cvmfs/lhcb.cern.ch/lib/lcg/releases/gcc/4.9.3/x86_64-slc6/lib64:/cvmfs/lhcb.cern.ch/lib/lcg/releases/gcc/4.9.3/x86_64-slc6/lib:/home/rollings/Software/install/lib:64:/cvmfs/lhcb.cern.ch/lib/lcg/releases/gcc/4.9.3/x86_64-slc6/lib64:/cvmfs/lhcb.cern.ch/lib/lcg/releases/gcc/4.9.3/x86_64-slc6/lib::/cvmfs/lhcb.cern.ch/lib/lcg/releases/LCG_88/gcc/4.9.3/x86_64-slc6/lib:/cvmfs/lhcb.cern.ch/lib/lcg/releases/LCG_88/gcc/4.9.3/x86_64-slc6/lib64:/cvmfs/lhcb.cern.ch/lib/lcg/releases/LCG_88/GSL/2.1/x86_64-slc6-gcc49-opt/lib/:/cvmfs/lhcb.cern.ch/lib/lcg/releases/LCG_88/gcc/4.9.3/x86_64-slc6/lib:/cvmfs/lhcb.cern.ch/lib/lcg/releases/LCG_88/gcc/4.9.3/x86_64-slc6/lib64:/cvmfs/lhcb.cern.ch/lib/lcg/releases/LCG_88/GSL/2.1/x86_64-slc6-gcc49-opt/lib/\"\n }\n make_shell_script(templatePath, scriptPath, substitutions)\n # run_process([\"qsub\", scriptPath])\n run_process([\"qsub\", \"-q\", \"testing\", scriptPath])\n","sub_path":"toys_test/shell_scripts/generate_2d.py","file_name":"generate_2d.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"149427461","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 22 12:02:48 2017\n@author: jamezcua\n\"\"\"\n\nimport numpy as np\n\n#############################################################################\ndef createH(obsgrid):\n Nx = 3 \n if obsgrid=='x':\n observed_vars = [0]\n if obsgrid=='y':\n observed_vars = [1]\n if obsgrid=='z':\n observed_vars = [2]\n if obsgrid=='xy':\n observed_vars = [0,1]\n if obsgrid=='xz':\n observed_vars = [0,2]\n if obsgrid=='yz':\n observed_vars = [1,2]\n if obsgrid=='xyz':\n observed_vars = [0,1,2]\n Ny = np.size(observed_vars)\n H = np.mat(np.zeros((Ny,Nx)))\n for i in range(Ny):\n H[i,observed_vars[i]] = 1.0\n del i\n return H, observed_vars\n\n\n#############################################################################\ndef gen_obs(t,x_t,period_obs,H,var_obs):\n \"\"\"This function generates [linear] observations from a nature run.\n Inputs: - t, the time array of the truth [Nsteps]\n - x_t, the true run [Nsteps, N variables]\n - period_obs, observation period (in model t steps)\n - H, the observation matrix\n - var_obs, the observational error variance (diagonal R)\n Outputs: - tobs, the time array of the observations\n - y, the observations\n - R, the observational error covariance matrix\"\"\"\n # The size of the observation operator (matrix) gives us the number of\n # observations and state variables\n L,N = np.shape(H)\n\n # The time array for obs (and coincides with the assimilation window time)\n tobs = t[::period_obs]\n\n # Initialize observations array\n y = np.empty((len(tobs),L))\n y.fill(np.nan)\n\n # The covariance matrix (remember it is diagonal)\n R = var_obs*np.mat(np.eye(L))\n\n # The cycle that generates the observations\n for j in range(1,len(tobs)): # at time 0 there are no obs\n x_aux = np.mat(x_t[period_obs*j,:]).T\n eps_aux = np.sqrt(R)*np.random.randn(L,1)\n y_aux = H*x_aux + eps_aux\n y[j,:] = y_aux.T\n\n return tobs,y,R\n\n\n##############################################################################\ndef rmse_spread(xt,xmean,Xens,anawin):\n \"\"\"Compute RMSE and spread.\n\n This function computes the RMSE of the background (or analysis) mean with\n respect to the true run, as well as the spread of the background (or\n analysis) ensemble.\n\n Inputs: - xt, the true run of the model [length time, N variables]\n - xmean, the background or analysis mean\n [length time, N variables]\n - Xens, the background or analysis ensemble\n [length time, N variables, M ensemble members] or None if\n no ensemble\n - anawin, the analysis window length. When assimilation\n occurs every time we observe then anawin = period_obs.\n Outputs: - rmse, root mean square error of xmean relative to xt\n - spread, spread of Xens. Only returned if Xens != None.\"\"\"\n\n la,N = np.shape(xt)\n\n # Select only the values at the time of assimilation\n ind = range(0,la,anawin)\n mse = np.mean((xt[ind,:]-xmean[ind,:])**2,axis=1)\n rmse = np.sqrt(mse)\n\n if Xens != None:\n spread = np.var(Xens[ind,:,:],ddof=1,axis=2)\n spread = np.mean(spread,axis=1)\n spread = np.sqrt(spread)\n return rmse,spread\n else:\n return rmse\n\n\n##############################################################################\nfrom L63_model import lorenz63\n\ndef getBsimple(model,N):\n \"\"\"A very simple method to obtain the background error covariance.\n\n Obtained from a long run of a model.\n\n Inputs: - model, the name of the model 'lor63' or 'lor96'\n - N, the number of variables\n Outputs: - B, the covariance matrix\n - Bcorr, the correlation matrix\"\"\"\n\n if model=='lor63':\n total_steps = 10000\n tstep = 0.01\n tmax = tstep*total_steps\n x0 = np.array([-10,-10,25])\n t,xt = lorenz63(x0,tmax)\n samfreq = 16\n err2 = 2\n# elif model=='lor96':\n# total_steps = 5000\n# tstep = 0.025\n# tmax = tstep*total_steps\n# x0 = None\n# t,xt = lorenz96(tmax,x0,N)\n# samfreq = 2\n# err2 = 2\n\n # Precreate the matrix\n ind_sample = range(0,total_steps,samfreq)\n x_sample = xt[ind_sample,:]\n Bcorr = np.mat(np.corrcoef(x_sample,rowvar=0))\n\n B = np.mat(np.cov(x_sample,rowvar=0))\n alpha = err2/np.amax(np.diag(B))\n B = alpha*B\n\n return B,Bcorr\n","sub_path":"var/L63_misc.py","file_name":"L63_misc.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"129903687","text":"\n\nfrom xai.brain.wordbase.verbs._underexpose import _UNDEREXPOSE\n\n#calss header\nclass _UNDEREXPOSED(_UNDEREXPOSE, ):\n\tdef __init__(self,): \n\t\t_UNDEREXPOSE.__init__(self)\n\t\tself.name = \"UNDEREXPOSED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"underexpose\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_underexposed.py","file_name":"_underexposed.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"576716257","text":"# myAgents.py\n# ---------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n#\n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\nfrom game import Agent\nfrom searchProblems import PositionSearchProblem, mazeDistance\n\nimport util\nimport time\nimport search\n\n\"\"\"\nIMPORTANT\n`agent` defines which agent you will use. By default, it is set to ClosestDotAgent,\nbut when you're ready to test your own agent, replace it with MyAgent\n\"\"\"\ndef createAgents(num_pacmen, agent='MyAgent'):\n return [eval(agent)(index=i) for i in range(num_pacmen)]\n\nclass MyAgent(Agent):\n \"\"\"\n Implementation of your agent.\n \"\"\"\n\n def myHeuristic(self, exploring_position, problem):\n foodList = problem.food.asList()\n distance = 0.0\n\n if len(foodList) == 0:\n return distance\n\n for food in foodList:\n\n tmpDistance = ((exploring_position[0] - food[0]) ** 2 + (exploring_position[1] - food[1]) ** 2) ** 0.5\n\n if tmpDistance > distance:\n distance = tmpDistance\n\n return distance\n\n\n\n\n\n def getAction(self, state):\n \"\"\"\n Returns the next action the agent will take\n \"\"\"\n\n \"*** YOUR CODE HERE ***\"\n\n if len(self.actions) != 0:\n next_action = self.actions[0]\n self.actions = self.actions[1:]\n else:\n startPosition = state.getPacmanPosition(self.index)\n # food = state.getFood()\n # walls = state.getWalls()\n problem = AnyFoodSearchProblem(state, self.index)\n pacman_states = state.getPacmanStates()\n action_list, goal_coords = search.ucs(problem)\n\n numOfActions = len(action_list)\n\n for pacman_state in pacman_states:\n if startPosition == pacman_state.configuration.pos:\n continue\n else:\n if pacman_state.configuration.direction == 'Stop' and self.actionsTaken != 0:\n continue\n else:\n mazeDist = mazeDistance(pacman_state.configuration.pos, goal_coords, state)\n\n if mazeDist <= numOfActions:\n action_list = ['Stop'] * numOfActions\n break\n self.actionsTaken += 1\n self.actions = action_list[1:]\n next_action = action_list[0]\n\n return next_action\n\n\n def initialize(self):\n \"\"\"\n Intialize anything you want to here. This function is called\n when the agent is first created. If you don't need to use it, then\n leave it blank\n \"\"\"\n\n \"*** YOUR CODE HERE\"\n self.actions = []\n self.actionsTaken = 0\n\n\n\"\"\"\nPut any other SearchProblems or search methods below. You may also import classes/methods in\nsearch.py and searchProblems.py. (ClosestDotAgent as an example below)\n\"\"\"\n\nclass ClosestDotAgent(Agent):\n\n def findPathToClosestDot(self, gameState):\n \"\"\"\n Returns a path (a list of actions) to the closest dot, starting from\n gameState.\n \"\"\"\n # Here are some useful elements of the startState\n startPosition = gameState.getPacmanPosition(self.index)\n food = gameState.getFood()\n walls = gameState.getWalls()\n problem = AnyFoodSearchProblem(gameState, self.index)\n\n \"*** YOUR CODE HERE ***\"\n\n actionList, goalCoords = search.bfs(problem)\n return actionList\n\n def getAction(self, state):\n return self.findPathToClosestDot(state)[0]\n\nclass AnyFoodSearchProblem(PositionSearchProblem):\n \"\"\"\n A search problem for finding a path to any food.\n\n This search problem is just like the PositionSearchProblem, but has a\n different goal test, which you need to fill in below. The state space and\n successor function do not need to be changed.\n\n The class definition above, AnyFoodSearchProblem(PositionSearchProblem),\n inherits the methods of the PositionSearchProblem.\n\n You can use this search problem to help you fill in the findPathToClosestDot\n method.\n \"\"\"\n\n def __init__(self, gameState, agentIndex):\n \"Stores information from the gameState. You don't need to change this.\"\n # Store the food for later reference\n self.food = gameState.getFood()\n\n # Store info for the PositionSearchProblem (no need to change this)\n self.walls = gameState.getWalls()\n self.startState = gameState.getPacmanPosition(agentIndex)\n self.costFn = lambda x: 1\n self._visited, self._visitedlist, self._expanded = {}, [], 0 # DO NOT CHANGE\n\n def isGoalState(self, state):\n \"\"\"\n The state is Pacman's position. Fill this in with a goal test that will\n complete the problem definition.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n x, y = state\n food = self.food\n return food[x][y]\n\n","sub_path":"pacman_project1/myAgents.py","file_name":"myAgents.py","file_ext":"py","file_size_in_byte":5421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"644801748","text":"import unittest\nfrom unittest import TestCase\n\nfrom xn2v import WeightedTriple\nfrom xn2v import StringInteraction\n\nimport os.path\n\n\n# files used by many tests\ngene2ensembl = os.path.join(os.path.dirname(\n __file__), 'data', 'small_gene2ensem.txt.gz')\nstring_ppi = os.path.join(os.path.dirname(\n __file__), 'data', 'small_protein_actions_v11.txt.gz')\n\nhpo_path = os.path.join(os.path.dirname(__file__),\n 'data', 'small_disease_disease.txt')\ngtex_path = os.path.join(os.path.dirname(\n __file__), 'data', 'small_gtex.txt.gz')\ngene_disease_train_path = os.path.join(\n os.path.dirname(__file__), 'data', 'small_gene_disease.txt')\ngene_disease_test_path = os.path.join(\n os.path.dirname(__file__), 'data', 'small_g2d_test.txt')\n\nparams = {'gtex_path': gtex_path, 'gene2ensembl_path': gene2ensembl, 'string_path': string_ppi,\n 'g2d_train_path': gene_disease_train_path, 'g2d_test_path': gene_disease_test_path, 'd2d_path': hpo_path}\n\n\nclass TestWeightedTriple(TestCase):\n\n def test_input_types(self):\n with self.assertRaises(TypeError):\n WeightedTriple(42, 84, \"bad-weight\", \"madeup-edgetype\")\n\n def test_get_subject(self):\n wt = WeightedTriple(42, 84, 0.7, \"madeup-edgetype\")\n self.assertEqual(42, wt.get_subject())\n\n def test_get_object(self):\n wt = WeightedTriple(42, 84, 0.7, \"madeup-edgetype\")\n self.assertEqual(wt.get_triple(), \"42\\t84\\tmadeup-edgetype\")\n\n def test_create_gene_disease_weighted_triple(self):\n wt1 = WeightedTriple(42, 84, 0.7, \"gene_dis\")\n wt2 = WeightedTriple.create_gene_disease_weighted_triple(\n 42, 84, 0.7\n )\n self.assertEqual(str(wt1), str(wt2))\n\n def test_create_gtex(self):\n wt1 = WeightedTriple(42, 84, 0.7, \"gtex\")\n wt2 = WeightedTriple.create_gtex(\n 42, 84, 0.7\n )\n self.assertEqual(str(wt1), str(wt2))\n\n def test_map_string_exception(self):\n with self.assertRaises(TypeError):\n WeightedTriple.map_string(\"Totally not a StringInteraction\")\n\n def test_map_string_to_gene_id_exception(self):\n with self.assertRaises(TypeError):\n WeightedTriple.map_string_to_gene_id(\n \"Totally not a StringInteraction\", None)\n\n def test_get_triple(self):\n wt = WeightedTriple(42, 84, 0.7, \"madeup-edgetype\")\n self.assertEqual(84, wt.get_object())\n\n def test_get_edgetype(self):\n wt = WeightedTriple(42, 84, 0.7, \"madeup-edgetype\")\n self.assertEqual(\"madeup-edgetype\", wt.get_edgetype())\n\n def test_get_weight(self):\n wt = WeightedTriple(42, 84, 0.7, \"madeup-edgetype\")\n self.assertAlmostEqual(0.7, wt.get_weight(), places=6)\n\n def test_set_weight(self):\n wt = WeightedTriple(42, 84, 0.7, \"madeup-edgetype\")\n self.assertAlmostEqual(0.7, wt.get_weight(), places=6)\n wt.set_weight(0.9)\n self.assertAlmostEqual(0.9, wt.get_weight(), places=6)\n\n def test_create_hpo_weighted_triple(self):\n wt = WeightedTriple.create_hpo_weighted_triple(42, 84, 0.7)\n self.assertEqual(42, wt.get_subject())\n self.assertEqual(84, wt.get_object())\n self.assertEqual(\"hpo\", wt.get_edgetype())\n self.assertAlmostEqual(0.7, wt.get_weight(), places=6)\n\n\nclass TestStringInteraction(TestCase):\n # Display this test line as an array and then combine it with tabs\n # because otherwise the formating will not be the same as in the\n # original STRING file. Note that the fourth column can be empty\n # 0) item_id_a\t1) item_id_b 2) mode 3) action\n # 4) a_is_acting 5)score\n threshold = 700\n array1 = [\"9606.ENSP00000000233\",\n \"9606.ENSP00000248901\",\n \"catalysis\",\n \"\",\n \"\",\n \"f\",\n \"277\"]\n line1 = '\\t'.join(array1)\n array2 = [\"9606.ENSP00000000233\",\n \"9606.ENSP00000248901\",\n \"activation\",\n \"\",\n \"\",\n \"f\",\n \"277\"]\n line2 = '\\t'.join(array2)\n array3 = [\"9606.ENSP00000000233\",\n \"9606.ENSP00000248901\",\n \"activation\",\n \"activation\",\n \"\",\n \"f\",\n \"309\"]\n\n line3 = '\\t'.join(array3)\n array4 = [\"9606.ENSP00000000233\",\n \"9606.ENSP00000248901\",\n \"activation\",\n \"\",\n \"random\",\n \"f\",\n \"309\"]\n\n # a line with non-valid triple. \"action\" = \"random\" is not valid\n line4 = '\\t'.join(array4)\n\n array5 = [\"9606.ENSP00000000233\",\n \"9606.ENSP00000223369\",\n \"reaction\",\n \"\",\n \"\",\n \"t\",\n \"913\"]\n # a line with non-valid triple. \"action\" = \"random\" is not valid\n line5 = '\\t'.join(array5)\n\n def test1(self):\n self.assertTrue(True)\n\n # get item_id_a (protein A) from a line\n def test_get_protein_A(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(\"ENSP00000000233\", si1.get_protein_a())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertEqual(\"ENSP00000000233\", si2.get_protein_a())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(\"ENSP00000000233\", si3.get_protein_a())\n si4 = StringInteraction(TestStringInteraction.line4)\n self.assertEqual(\"ENSP00000000233\", si4.get_protein_a())\n\n # get item_id_b (protein B) from a line\n def test_get_protein_B(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(\"ENSP00000248901\", si1.get_protein_b())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertEqual(\"ENSP00000248901\", si2.get_protein_b())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(\"ENSP00000248901\", si3.get_protein_b())\n\n # get the mode of the interaction\n def test_get_mode(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(\"catalysis\", si1.get_mode())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertEqual(\"activation\", si2.get_mode())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(\"activation\", si3.get_mode())\n\n # get the action of the interaction. Action can be \"activation\", \"inhibition\" or \"\".\n def test_get_action(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(\"\", si1.get_action())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertEqual(\"\", si2.get_action())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(\"activation\", si3.get_action())\n\n # if protein A is acting, it returns True. If not, it returns False. But False does not mean that protein B is acting\n def test_get_a_acting(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(False, si1.get_a_is_acting())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertEqual(False, si2.get_a_is_acting())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(False, si3.get_a_is_acting())\n\n # get the score of the interaction. scores have been multiplied by 1000.\n def test_get_score(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(277, si1.get_score())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertEqual(277, si2.get_score())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(309, si3.get_score())\n\n # We will have a category of \"activation\" interactions where\n # protein A activates protein B\n\n def test_is_activation(self):\n si = StringInteraction(TestStringInteraction.line1)\n self.assertFalse(si.is_activation())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertFalse(si2.is_activation())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertTrue(si3.is_activation())\n\n # We will have a category of \"inhibition\" interactions where\n # protein A inhibits protein B\n def test_is_inhibition(self):\n si = StringInteraction(TestStringInteraction.line1)\n self.assertFalse(si.is_inhibition())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertFalse(si2.is_inhibition())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertFalse(si3.is_inhibition())\n\n # We will have a category of \"\" interactions where\n # action is missing\n def test_is_missing_action(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertTrue(si1.is_missing_action())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertTrue(si2.is_missing_action())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertFalse(si3.is_missing_action())\n\n def test_is_a_acting(self):\n si1 = StringInteraction(TestStringInteraction.line1)\n self.assertFalse(si1.is_a_acting())\n si2 = StringInteraction(TestStringInteraction.line2)\n self.assertFalse(si2.is_a_acting())\n si3 = StringInteraction(TestStringInteraction.line3)\n self.assertFalse(si3.is_a_acting())\n\n # We split the name of protein A and get the second part only to write in the output file.\n def test_get_prot_A_pure_name(self):\n si = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(\"ENSP00000000233\", si.get_protein_a_name())\n\n # We split the name of protein A and get the second part only to write in the output file.\n def test_get_prot_B_pure_name(self):\n si = StringInteraction(TestStringInteraction.line1)\n self.assertEqual(\"ENSP00000248901\", si.get_protein_b_name())\n\n # We split the name of protein A and get the second part only to write in the output file.\n def test_get_prot_A_pure_name_1(self):\n si = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(\"ENSP00000000233\", si.get_protein_a_name())\n\n # We split the name of protein A and get the second part only to write in the output file.\n def test_get_prot_B_pure_name_1(self):\n si = StringInteraction(TestStringInteraction.line3)\n self.assertEqual(\"ENSP00000248901\", si.get_protein_b_name())\n\n # We check if the line has a valid triple (protA, action, protB)\n def test_has_valid_triple(self):\n si = StringInteraction(TestStringInteraction.line3)\n self.assertFalse(si.has_valid_triple(TestStringInteraction.threshold))\n\n # We check if the line has a valid triple (protA, action, protB)\n def test_has_valid_triple2(self):\n si = StringInteraction(TestStringInteraction.line4)\n self.assertFalse(si.has_valid_triple(TestStringInteraction.threshold))\n\n def test_has_valid_triple3(self):\n si = StringInteraction(TestStringInteraction.line5)\n self.assertTrue(si.has_valid_triple(TestStringInteraction.threshold))\n\n # get the triple \"[\"protA\", \"action\", \"protB\"]\"\n def test_get_list_triple1(self):\n si = StringInteraction(TestStringInteraction.line1)\n expected = \"['ENSP00000000233', '', 'ENSP00000248901']\"\n self.assertEqual(expected, str(si.get_edge_type()))\n\n # get the triple \"[\"protA\", \"action\", \"protB\"]\"\n def test_get_list_triple2(self):\n si = StringInteraction(TestStringInteraction.line2)\n expected = \"['ENSP00000000233', '', 'ENSP00000248901']\"\n self.assertEqual(expected, str(si.get_edge_type()))\n\n # get the triple \"[\"protA\", \"action\", \"protB\"]\"\n def test_get_list_triple3(self):\n si = StringInteraction(TestStringInteraction.line3)\n expected = \"['ENSP00000000233', 'activation', 'ENSP00000248901']\"\n self.assertEqual(expected, str(si.get_edge_type()))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_n2v.py","file_name":"test_n2v.py","file_ext":"py","file_size_in_byte":12070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"226958278","text":"\nimport numpy as np\nimport pandas as pd\nimport pickle\n\nfilename = '/data/cdiscount/test152/result.hdf'\nprint(filename)\nX = pd.read_hdf(filename, \"result\").values\npk_path = '/data/cdiscount/test152/pk.11'\npk_out = open(pk_path, 'wb')\nfor ii in range(X.shape[0]):\n score = X[ii]\n pickle.dump(score, pk_out, pickle.HIGHEST_PROTOCOL)\npk_out.close()\n\n","sub_path":"Cdiscount/infer/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"342776965","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n# https://socionet.ru/find.htm\n\nimport parsers.parser_engine.config_parsers as config\nfrom .download import download_file\n\nbase_url = 'https://socionet.ru/search/runsearch.cgi'\n\n\ndef author_and_title_problem(author, title, element):\n head = element.text.strip()\n try:\n author_list = author.split()\n author1 = author_list[0] + ' ' + author_list[1] + ' ' + author_list[2]\n author2 = author_list[0] + ' ' + author_list[1] + author_list[2]\n author3 = author_list[1] + author_list[2] + ' ' + author_list[0]\n author4 = author_list[1] + ' ' + author_list[2] + ' ' + author_list[0]\n if ((author1 == author1 in head)\n or (author2 == author2 in head)\n or (author3 == author3 in head)\n or (author4 == author4 in head))\\\n and (title.lower() == title.lower() in head.lower()):\n return True\n except IndexError:\n if (author == author in head) and (title.lower() == title.lower() in head.lower()):\n return True\n return False\n\n\ndef get_urls(html, author='', title=''):\n urls = []\n soup = BeautifulSoup(html, 'lxml')\n tags = soup.find_all('a')\n for tag in tags:\n if author_and_title_problem(author, title, tag):\n url = tag.get('href')\n urls.append(url)\n result_urls = []\n for url in urls:\n if 'cyberleninka' not in url:\n sleep(1)\n html_page = requests.get(url).text\n soup = BeautifulSoup(html_page, 'lxml')\n url_new = soup.find('table', id='m_content_tbl').find('td', class_='ar-on', bgcolor='gray')\n url_new = url_new.find('a').get('title')\n name = soup.find('table', id='m_content_tbl').find('table', class_='com_tbl').find('td', class_='ar-on')\n name = name.text.strip()\n name = name.split('//')[0][:-1].lower()\n result_urls.append((name, url_new))\n return result_urls\n\n\ndef socionet(author='', title='', keywords='', year1='', year2=''):\n\n config.debug('Socionet')\n config.write_log('Socionet: начал работу')\n\n if title:\n keywords = title + ' ' + keywords\n\n try:\n r = requests.post(base_url, data={\n 'author-name': author,\n 'justtext': keywords, # ключевые слова\n 'fulltext': 'fulltext', # fulltext\n 'tr1': year1,\n 'tr2': year2, # 14 марта 1971\n 'accept-charset': 'utf-8',\n })\n except requests.exceptions.ConnectionError:\n config.write_log('Socionet: ошибка при выполнении запроса')\n return 0\n\n config.write_log('Socionet: запрос:' + str(r.url))\n config.to_json({\n 'BaseUrlParser': {\n 'url_socio': r.url\n }\n })\n html = r.text\n\n names_urls = get_urls(html, author, title)\n if names_urls:\n for name, url in names_urls:\n download_file(name, url, 'Socionet')\n config.write_log('Socionet: работа завершена')\n else:\n config.write_log('Socionet: материалы не найдены')\n\n\nif __name__ == '__main__':\n socionet(author='Жуков В. Т.', title='метод', year1='2011', year2='2012')\n","sub_path":"parsers/parser_engine/socionet.py","file_name":"socionet.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"403282009","text":"import asyncio\nimport hashlib\nimport importlib\nimport logging\nfrom copy import copy\nfrom typing import Dict, cast\n\nfrom tortoise import Tortoise\nfrom tortoise.exceptions import OperationalError\nfrom tortoise.utils import get_schema_sql\n\nimport dipdup.codegen as codegen\nimport dipdup.utils as utils\nfrom dipdup import __version__\nfrom dipdup.config import (\n ROLLBACK_HANDLER,\n ContractConfig,\n DipDupConfig,\n DynamicTemplateConfig,\n PostgresDatabaseConfig,\n SqliteDatabaseConfig,\n StaticTemplateConfig,\n TzktDatasourceConfig,\n)\nfrom dipdup.datasources.tzkt.datasource import TzktDatasource\nfrom dipdup.exceptions import ConfigurationError\nfrom dipdup.hasura import configure_hasura\nfrom dipdup.models import IndexType, State\n\n\nclass DipDup:\n def __init__(self, config: DipDupConfig) -> None:\n self._logger = logging.getLogger(__name__)\n self._config = config\n\n async def init(self) -> None:\n await codegen.create_package(self._config)\n await codegen.resolve_dynamic_templates(self._config)\n await codegen.fetch_schemas(self._config)\n await codegen.generate_types(self._config)\n await codegen.generate_handlers(self._config)\n await codegen.cleanup(self._config)\n\n async def run(self, reindex: bool) -> None:\n url = self._config.database.connection_string\n cache = isinstance(self._config.database, SqliteDatabaseConfig)\n models = f'{self._config.package}.models'\n\n try:\n rollback_fn = getattr(importlib.import_module(f'{self._config.package}.handlers.{ROLLBACK_HANDLER}'), ROLLBACK_HANDLER)\n except ModuleNotFoundError as e:\n raise ConfigurationError(f'Package `{self._config.package}` not found. Have you forgot to call `init`?') from e\n\n async with utils.tortoise_wrapper(url, models):\n await self.initialize_database(reindex)\n\n await self._config.initialize()\n\n datasources: Dict[TzktDatasourceConfig, TzktDatasource] = {}\n\n self._logger.info('Processing dynamic templates')\n has_dynamic_templates = False\n for index_name, index_config in copy(self._config.indexes).items():\n if isinstance(index_config, DynamicTemplateConfig):\n if not self._config.templates:\n raise ConfigurationError('`templates` section is missing')\n has_dynamic_templates = True\n template = self._config.templates[index_config.template]\n # NOTE: Datasource and other fields are str as we haven't initialized DynamicTemplateConfigs yet\n datasource_config = self._config.datasources[cast(str, template.datasource)]\n if datasource_config not in datasources:\n datasources[datasource_config] = TzktDatasource(datasource_config.url, cache)\n datasources[datasource_config].set_rollback_fn(rollback_fn)\n datasources[datasource_config].set_package(self._config.package)\n\n contract_config = self._config.contracts[cast(str, index_config.similar_to)]\n await datasources[datasource_config].add_contract_subscription(\n contract_config, index_name, template, index_config.strict\n )\n similar_contracts = await datasources[datasource_config].get_similar_contracts(contract_config.address)\n for contract_address in similar_contracts:\n self._config.contracts[contract_address] = ContractConfig(\n address=contract_address,\n typename=contract_config.typename,\n )\n\n generated_index_name = f'{index_name}_{contract_address}'\n template_config = StaticTemplateConfig(template=index_config.template, values=dict(contract=contract_address))\n self._config.indexes[generated_index_name] = template_config\n\n del self._config.indexes[index_name]\n\n # NOTE: We need to initialize config one more time to process generated indexes\n if has_dynamic_templates:\n self._config.pre_initialize()\n await self._config.initialize()\n\n for index_name, index_config in self._config.indexes.items():\n if isinstance(index_config, StaticTemplateConfig):\n raise RuntimeError('Config is not initialized')\n if isinstance(index_config, DynamicTemplateConfig):\n raise RuntimeError('Dynamic templates must be resolved before this step')\n\n self._logger.info('Processing index `%s`', index_name)\n if isinstance(index_config.datasource, TzktDatasourceConfig):\n if index_config.datasource_config not in datasources:\n datasources[index_config.datasource_config] = TzktDatasource(index_config.datasource_config.url, cache)\n datasources[index_config.datasource_config].set_rollback_fn(rollback_fn)\n datasources[index_config.datasource_config].set_package(self._config.package)\n await datasources[index_config.datasource_config].add_index(index_name, index_config)\n else:\n raise NotImplementedError(f'Datasource `{index_config.datasource}` is not supported')\n\n self._logger.info('Starting datasources')\n run_tasks = [asyncio.create_task(d.start()) for d in datasources.values()]\n\n if self._config.hasura:\n hasura_task = asyncio.create_task(configure_hasura(self._config))\n run_tasks.append(hasura_task)\n\n await asyncio.gather(*run_tasks)\n\n async def initialize_database(self, reindex: bool = False) -> None:\n self._logger.info('Initializing database')\n\n if isinstance(self._config.database, PostgresDatabaseConfig) and self._config.database.schema_name:\n await Tortoise._connections['default'].execute_script(f\"CREATE SCHEMA IF NOT EXISTS {self._config.database.schema_name}\")\n await Tortoise._connections['default'].execute_script(f\"SET search_path TO {self._config.database.schema_name}\")\n\n connection_name, connection = next(iter(Tortoise._connections.items()))\n schema_sql = get_schema_sql(connection, False)\n\n # NOTE: Column order could differ in two generated schemas for the same models, drop commas and sort strings to eliminate this\n processed_schema_sql = '\\n'.join(sorted(schema_sql.replace(',', '').split('\\n'))).encode()\n schema_hash = hashlib.sha256(processed_schema_sql).hexdigest()\n\n if reindex:\n self._logger.warning('Started with `--reindex` argument, reindexing')\n await utils.reindex()\n\n try:\n schema_state = await State.get_or_none(index_type=IndexType.schema, index_name=connection_name)\n except OperationalError:\n schema_state = None\n\n if schema_state is None:\n await Tortoise.generate_schemas()\n schema_state = State(index_type=IndexType.schema, index_name=connection_name, hash=schema_hash)\n await schema_state.save()\n elif schema_state.hash != schema_hash:\n self._logger.warning('Schema hash mismatch, reindexing')\n await utils.reindex()\n","sub_path":"src/dipdup/dipdup.py","file_name":"dipdup.py","file_ext":"py","file_size_in_byte":7505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"543869214","text":"#Kod açıklanmıştır\n\n'''\nHOMEWORK-2:\nBir okuldaki 5 öğrencinin notları hakkında bilgi içeren bir program yazın\nBu öğrencilerin notlarını bir listede tutun. (Ara sınav, final, ödev)\nÖğrenci isimlerini bir listede tutun. (Ad Soyad)\nBir sözlükte öğrencilerin tüm bilgilerini içeren bir sözlük oluşturun.\nBurada öğrencinin notlarını azalan sırayla sıralayın ve listeleyin ve en yüksek puanı alan öğrenciyi tebrik edin.'''\n\nnameSurnameList=[] #name ve surname değerlerini tutmak için oluşturulan liste\nscoreList=[] #midterm, final ve homework değerlerini tutmak için oluşturulan liste\n\nfor i in range(0,5): # for döngüsü ile 0-5'e kadar (5 dahil değil) gidilerek 5 öğrencinin bilgileri alınacaktır. \n\t#name, surname, midterm,final ve homework değerleri kullanıcıdan alınır.\n\tname = str(input(\"name: \")) \n\tsurname = str(input(\"surname: \"))\n\tmidterm = float(input(\"midterm: \"))\n\tfinal = float(input(\"final: \"))\n\thomework = float(input(\"homework: \"))\n\n\t#append metodu ile nameSurnameList ve scoreList listelerine kullanıcıdan alınan \n\t#name, surname, midterm, final ve homework değerleri eklenir\n\tnameSurnameList.append(name+\" \"+surname) \n\tscoreList.append(midterm)\n\tscoreList.append(final)\n\tscoreList.append(homework)\n\t\n\n#information adında dictionary oluşturulur. Bu sözlük 5 öğrencinin name_surname, midterm, final ve homework\n#değerlerini tutarak key ve valeus olarak saklar.\ninformation={\"name\": [nameSurnameList[0],nameSurnameList[1],nameSurnameList[2],nameSurnameList[3],nameSurnameList[4]],\n\t\t\t\"midterm\":[scoreList[0],scoreList[3],scoreList[6],scoreList[9],scoreList[12]],\n\t\t\t\"final\":[scoreList[1],scoreList[4],scoreList[7],scoreList[10],scoreList[13]],\n\t\t\t\"homework\":[scoreList[2],scoreList[5],scoreList[8],scoreList[11],scoreList[14]]\n}\nprint(\"\\ninformation:\")\nprint(information) #kontrol amaçlı information ekrana yazdırılır\n\naverage=[] #average listesi ile en başarılı öğrenciyi belirlemek için vize, final ve ödevlerin ortalamaları hesaplanacaktır \nfor i in range(5): \n\taverage.append((information[\"midterm\"][i]+information[\"final\"][i]+information[\"homework\"][i])/3)# information'da \n\t#ilgili alanlardaki (midterm, final, homework) değerler (i'ler) alınır. Her öğrenci için (5 öğrenci) average hesaplanır.\n\nprint(\"\\naverage:\")\nprint(average) #kontrol amaçlı average listesi ekrana yazdırılır\n\n\n'''En başarılı öğrencilerin notlarını azalan sırayla sıralama işlemi için Bubble Sort algoritması kullanıldı.\nEn yüksek ortalamayı bulurken temp değişkeninde average[j] değeri tutuldu, daha sonra average[i]'deki değer \naverage[j]'ye atandı ve temp değişkeninde tutulan average[j] değeri average[i]'ye atandı.\nDaha sonra information'da kullanıcıya ait bulunan bilgiler (name, midterm, final ve homework değerlerinin) yerlerini \ndeğiştirmek, sıralamak içinde aynı işlemler uygulandı.'''\nfor i in range(5): \n\tfor j in range(4): \n\t\tif average[i] > average[j]: \n\t\t\ttemp = average[j]\n\t\t\taverage[j] = average[i]\n\t\t\taverage[i] = temp\n\n\t\t\ttemp = information[\"name\"][j]\n\t\t\tinformation[\"name\"][j] = information[\"name\"][i]\n\t\t\tinformation[\"name\"][i] = temp\n\n\t\t\ttemp = information[\"midterm\"][j]\n\t\t\tinformation[\"midterm\"][j] = information[\"midterm\"][i]\n\t\t\tinformation[\"midterm\"][i] = temp\n\n\t\t\ttemp = information[\"final\"][j]\n\t\t\tinformation[\"final\"][j] = information[\"final\"][i]\n\t\t\tinformation[\"final\"][i] = temp\n\n\t\t\ttemp = information[\"homework\"][j]\n\t\t\tinformation[\"homework\"][j] = information[\"homework\"][i]\n\t\t\tinformation[\"homework\"][i] = temp\n\n#Bubble Sort algoritması ile sıralanan information yazdırıldı\nprint(\"\\nSıralı information:\\nname - midterm - final - homework - average\") \nfor i in range(5): \n\tprint(information[\"name\"][i], information[\"midterm\"][i], information[\"final\"][i], information[\"homework\"][i], average[i],sep=\" \")\n\n#En yüksek puanı alan öğrencye tebrik mesajı yazdırıldı\nprint(\"\\nTebrikler \",information[\"name\"][0], \"En Yüksek Puanı Aldınız\",sep=\" \")\n","sub_path":"Homeworks/HW2.py","file_name":"HW2.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"476068343","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nAlexander May Thu Jun 11 2020\r\n_______________________________________________________________________________\r\nGeneralLSFR.py\r\n(Least Squares Fitting Routine)\r\n_______________________________________________________________________________\r\nCreates Graphical User Interface Which Allows User to:\r\n -Input Data\r\n -Enter an Equation With Fitting Parameters\r\n -Press a Button to Perform a Fit and Plot a Graph (With Residuals)\r\n_______________________________________________________________________________\r\n\"\"\"\r\nimport tkinter as tk\r\nfrom tkinter.filedialog import askopenfilename\r\nfrom sympy import symbols, sympify, solve, lambdify\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport re\r\nfrom scipy.optimize import curve_fit\r\n\r\nclass Gui():\r\n \"\"\"\r\n GUI class which is called to configure and run the graphical user interface\r\n Handles any user feedback using functions defined below\r\n \"\"\"\r\n def __init__(self, window):\r\n \"\"\"\r\n creates instance of GUI class and configures it.\r\n \"\"\"\r\n self.window = window\r\n \r\n def setup(self):\r\n \"\"\"\r\n Adds Widgets to GUI\r\n \"\"\"\r\n #Gets window's frame\r\n frame = tk.Frame(self.window).grid()\r\n \r\n #Create a Frame for LabelFrames to be placed Into\r\n tFrame = tk.Frame(frame,width=650)\r\n tFrame.place(x=800,y=60)\r\n \r\n #Fit-Tolerence Frame\r\n self.tolFrame = tk.LabelFrame(tFrame,text=\"Input the Fit Tolerence:\",\r\n width=650,height=300)\r\n self.tolFrame.grid()\r\n \r\n #Create Entry Box for Tolerence Input\r\n negFloatVal = self.window.register(self.checkNegFloat)\r\n self.tolEntry = tk.Entry(self.tolFrame,width=50, validate=\"all\",\r\n validatecommand=(negFloatVal, '%P'))\r\n self.tolEntry.grid()\r\n self.tolEntry.insert(0,\"0.00000001\")\r\n \r\n #Fit-Parameters Frame\r\n self.fitParamFrame = tk.LabelFrame(tFrame,text=\"Input Initial Guesses\"\r\n +\" for Fit Parameters:\",width=650,height=300)\r\n self.fitParamFrame.grid()\r\n \r\n #Constant-Parameters Frame\r\n self.constParamFrame=tk.LabelFrame(tFrame,text=\"Input Constant Values:\"\r\n ,width=650,height=50)\r\n self.constParamFrame.grid()\r\n \r\n # Creates \"How to Use\" Button\r\n self.infoButton = tk.Button(frame,text=\"How To Use\",\r\n command=self.getInfo).place(x=20, y=20)\r\n \r\n #Graph-Title Entry\r\n tk.Label(frame, text=\"Graph Title:\").place(x=20, y=100)\r\n self.graphTitleEntry = tk.Entry(frame,width=40)\r\n self.graphTitleEntry.place(x=200,y=100)\r\n self.graphTitleEntry.insert(0,\"Graph Title\")\r\n \r\n #x-Axis Labels Entry\r\n tk.Label(frame, text=\"x-Axis Label:\").place(x=20, y=150)\r\n self.xAxEntry = tk.Entry(frame,width=40)\r\n self.xAxEntry.place(x=200,y=150)\r\n self.xAxEntry.insert(0,\"x-Axis Label\")\r\n \r\n #y-Axis Label Entry \r\n tk.Label(frame, text=\"y-Axis Label:\").place(x=20, y=200)\r\n self.yAxEntry = tk.Entry(frame,width=40)\r\n self.yAxEntry.place(x=200,y=200)\r\n self.yAxEntry.insert(0,\"y-Axis Label\")\r\n \r\n #Searches Text for Parameters. Updates/Destroys Entry Boxes\r\n eqnCheck = self.window.register(self.findParams)\r\n \r\n #Equation Entry Label and Text\r\n tk.Label(frame, text=\"Enter Equation:\"\r\n +\" (Include x and y Terms)\").place(x=20, y=275)\r\n tk.Label(frame, text=\"0 = \").place(x=20, y=325)\r\n \r\n self.eqEntry = tk.Entry(frame,width=50, validate=\"all\",\r\n validatecommand=(eqnCheck,'%P'))\r\n self.eqEntry.place(x=70,y=325)\r\n self.eqEntry.insert(0,\"f1*x+f2-y\") #Insert Linear Eqn as Default \r\n \r\n #Creates Text Widget to Display Data\r\n self.dataText = tk.Text(frame)\r\n self.dataText.place(x=20,y=400, width = 700,height = 300)\r\n self.dataText.insert(tk.INSERT,\"No Data Selected\")\r\n self.dataText.configure(state=tk.DISABLED)\r\n \r\n #Read Data Button\r\n self.readDataButton = tk.Button(frame,text=\"Read Data\",\r\n command=self.dataFromFile).place(x=20, y=710)\r\n self.plotDataButton = tk.Button(frame,text=\"Plot Data\",\r\n command=self.fitData).place(x=600, y=710)\r\n \r\n #Create Label to Show the User any StatusProblems\r\n self.errorText = tk.Label(frame, text=\"Status:\")\r\n self.errorText.place(x=20, y=800)\r\n \r\n def getInfo(self):\r\n \"\"\"\r\n Display Window Which Tells User How to Use the Program\r\n \"\"\"\r\n try:\r\n self.infoWindow #check if window already open\r\n self.infoWindow.attributes(\"-topmost\", True) #bring to front\r\n except:\r\n #create new window to place widgets onto\r\n self.infoWindow = tk.Toplevel(self.window)\r\n self.infoWindow.title(\"Help Page\")\r\n infoGui = Gui(self.infoWindow)\r\n infoGui.window.minsize(width=1250, height=750)\r\n infoGui.window.attributes(\"-topmost\", True) #bring to front\r\n \r\n #Info Text String\r\n infoString = \"\"\"######################################################\r\nGENERAL LSFR - HELP:\r\n######################################################\r\n\r\nAlexander May\t2020\r\nalexander.may-2@student.manchester.ac.uk\r\nThe University Of Manchester\r\nGeneral Equation - Least Squares Fitting Routine\r\nVersion 1.0\r\n\r\n######################################################\r\nABOUT:\r\n######################################################\r\nThis Program Uses the scipi.optimise Function curve_fit(...),\r\nAvailable at:\r\nhttps://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html\r\n\r\nThis Returns the Best Fit Parameters for a General Equation\r\nAs Well as the Covariance Matrix From Which the Uncertainties\r\nCan be Calculated\r\n\r\n######################################################\r\nENTERING EQUATION:\r\n######################################################\r\nWhen Entering an Equation many common functions can be used\r\nFor Example:\r\n\t-exp()\r\n\t-sin()\r\n\t-cos()...etc\r\nTo Raise Something to a power, use \"**\". E.g. \"x**2\" for x\r\nSquared.\r\n\r\nIn Order To Perform the Fit, There Must be Fitting Parameters\r\nTo Insert a Fitting Parameter Into Your Equation type 'f'\r\nFollowed By a positive Integer. e.g. \"f1\",\"f45\"...etc.After\r\nTyping These Into Your Equation, Make Sure Their Initial Values\r\nare Inputted on the Right Hand Side of The Screen\r\n\r\nConstants Can Also Be Defined Using 'k' Followed by a Positive\r\nInteger. E.g. \"k1\", \"k2\"...etc. After Typing These Into Your\r\nEquation, Make Sure They are Defined on the Right Hand Side Of\r\nThe Screen\r\n\r\nMake Sure That Both x and y Appear in Your Equation\r\ne.g. The Default Linear Equation:\r\n\t\"0 = f1*x + f2 - y\"\r\n\r\n######################################################\r\nSELECTING DATA:\r\n######################################################\r\nData Can be Selected Using The \"Read Data\" Button.\r\n\r\nData Should be a .csv File or .txt File (Separated by Tabs)\r\n\r\nThe File Should Have Three Columns of Data:\r\n1. The Left Column Should Contain the x-Data\r\n2. The Central Column Should Contain the y-Data\r\n3. The Right Column Should Contain the y-Errors\r\n\r\nThe Data Should Have Enough Points Depending On The Number Of\r\nFitting Parameters\r\n\r\n######################################################\r\nPLOTTING DATA:\r\n######################################################\r\nBefore Pressing the \"Plot Data\" Button, Make Sure:\r\n- Data has Been Selected\r\n- The Equation has Been Entered\r\n- Constant Parameters Have Been Inputted\r\n- The Fitting Parameters' Initial Values Have Been Inputted.\r\n\r\nWhen Pressing the Button, If No Problems Occur, a Graph Will Be\r\nPlotted and the Fitting Parameter Values Will Be Shown\r\n\"\"\"\r\n #Creates Data Text\r\n infoGui.infoText = tk.Text(infoGui.window)\r\n infoGui.infoText.place(x=0,y=0, width = 1250,height = 750)\r\n infoGui.infoText.insert(tk.INSERT,infoString)\r\n infoGui.infoText.configure(state=tk.DISABLED)\r\n infoGui.window.mainloop() #runs GUI's main loop\r\n \r\n def showFitParams(self, results):\r\n \"\"\"\r\n Creates New Window Displaying The Reduced Chi-Squared, and the Values\r\n of Any Fitting Parameters Used\r\n Results is an Array containing the Reduced Chi-Squared,\r\n The Fitting Parameters and their Uncertainties\r\n \"\"\"\r\n try:\r\n self.fitParamsWindow #check if window already open\r\n self.fitParamsWindow.deiconify() #If Hidden, Reopen it\r\n fitParamsGui = Gui(self.fitParamsWindow) #Create New Gui Instance\r\n\r\n except:\r\n #Create New Window to Place Widgets Onto\r\n self.fitParamsWindow = tk.Toplevel(self.window)\r\n self.fitParamsWindow.title(\"Fitting Parameters\")\r\n fitParamsGui = Gui(self.fitParamsWindow) #Create New Gui Instance\r\n \r\n fitParamsGui.window.minsize(width=750, height=750) #Set Size\r\n fitParamsGui.window.attributes(\"-topmost\", True) #Bring to Front\r\n \r\n #Creates Text Widget to Display the Text\r\n fitParamsGui.fitParamText = tk.Text(fitParamsGui.window)\r\n fitParamsGui.fitParamText.grid(row=0, column=0)\r\n \r\n #Creates String to Show Fit Results To The User \r\n guiString = \"Reduced Chi-Squared: \"+str(results[1])+\"\\n\"\r\n \r\n #For Each Parameter Add Data to String\r\n for i in range(len(self.fitParams)):\r\n key = list(self.fitParams.keys())[i]\r\n strUncert = str(np.sqrt(results[2][i][i]))\r\n guiString = guiString+key+\": \"+str(results[0][i])+\"±\"+strUncert+\"\\n\"\r\n \r\n fitParamsGui.fitParamText.insert(tk.INSERT,guiString) #Show guiString\r\n fitParamsGui.fitParamText.configure(state=tk.DISABLED)#No Text Editting\r\n fitParamsGui.window.mainloop() #runs GUI's main loop\r\n\r\n \r\n def findParams(self,string):\r\n \"\"\"\r\n Searches Equation for Fitting Parameters(f#) & Constant Parameters (k#)\r\n Creates Dictionaries to Be Used To Create Text Entry Boxes for Each\r\n Param\r\n string is a String Passed in by Equation Entry to Be Validated\r\n \"\"\"\r\n fArray = re.findall(r'\\bf\\d+\\b', string)#Instances of f Followed by int\r\n kArray = re.findall(r'\\bk\\d+\\b', string)#Instances of k Followed by int\r\n \r\n #Make Dictionaries of Fit and Const Params With Their Values\r\n try:\r\n #If New Fit Param, Add String Value as Key in Dictionary\r\n for key in fArray:\r\n if not key in self.fitParams:\r\n self.fitParams[key]=None\r\n \r\n #If Fit Param Has Been Removed From Equation, Remove it From Dict\r\n keys = list(self.fitParams.keys())\r\n for key in keys:\r\n if not key in fArray:\r\n self.fitParams[key][1].destroy() #Removes Param's Entry\r\n self.fitParams[key][2].destroy() #Removes Param's Label\r\n self.fitParams.pop(key) #Removes Item From Dict\r\n except:\r\n #If No fitParams Dict, Make One From fArray \r\n self.fitParams=dict.fromkeys(fArray)\r\n try:\r\n #If New Const Param, Add String Value as Key in Dictionary\r\n for key in kArray:\r\n if not key in self.constParams:\r\n self.constParams[key]=None\r\n \r\n #If Const Param Has Been Removed From Equation, Remove it From Dict\r\n keys = list(self.constParams.keys())\r\n for key in keys:\r\n if not key in kArray:\r\n self.constParams[key][1].destroy() #Removes Param's Entry\r\n self.constParams[key][2].destroy() #Removes Param's Label\r\n self.constParams.pop(key) #Removes Item From Dict\r\n except:\r\n #If No constParams Dict, Make One From fArray\r\n self.constParams=dict.fromkeys(kArray)\r\n \r\n #Make Entry Boxes From Dictionaries\r\n self.makeParamEntries(self.fitParams,self.fitParamFrame)\r\n self.makeParamEntries(self.constParams,self.constParamFrame)\r\n \r\n return True #Allow Text To be Editted\r\n \r\n def makeParamEntries(self,params,frame):\r\n \"\"\"\r\n Create Entry Boxes in a Given Frame for Each Member of the Params Dict\r\n With a Key But No Item Inside\r\n Params is a Dict\r\n Frame is a TKinter Frame\r\n \"\"\"\r\n #only allow negative floats to be entered\r\n negFloatVal = self.window.register(self.checkNegFloat)\r\n \r\n #Search for Empty Members of params\r\n for key in params.keys():\r\n if params[key] == None:\r\n #Create Text With the Name of the Fitting Parameter\r\n text1 = tk.Label(frame, text=key+\":\")\r\n text1.grid(sticky = \"W\")\r\n \r\n #Create Entry Which Only allows Negative Floats\r\n entry1 = tk.Entry(frame,width=50, validate=\"all\",\r\n validatecommand=(negFloatVal, '%P'))\r\n entry1.grid()\r\n entry1.insert(0,\"0.0\") #Set Default Value to 0.0\r\n \r\n #Set Dict Value to Array Containing Default Entry Value\r\n #and the Two Widgets\r\n params[key] = [0.0,entry1,text1]\r\n \r\n def checkNegFloat(self, string):\r\n \"\"\"\r\n Returns True if String Can Be Cast as a Float\r\n string is a String Passed in by an Entry Widget to Be Validated\r\n \"\"\"\r\n try:\r\n if string == \"\" or string == \"-\": #Allows the Empty String or Minus\r\n return True\r\n float(string) #Checks if String Can Be Converted to a Float\r\n return True\r\n except: #Raised If String Cannot Be Converted to a Float\r\n return False #Do Not Allow Non-Floats \r\n \r\n def fitData(self):\r\n \"\"\"\r\n Function Called When \"Plot Data\" Button is Pressed\r\n Retrieves Equation, Parameter Symbols and Initial Values, the Tolerence\r\n And Performs a Fit Using these Values\r\n Scales the Reduced Chi-Squared and the Covariance Matrix\r\n Plots the Data With the Best Fit Line\r\n Shows User The Best Fit Parameters and Reduced Chi-Squared\r\n \"\"\"\r\n #Check That There are Fit Params\r\n if self.fitParams == {}:\r\n self.errorText.config(text=\"Status: No Fitting Parameters\")\r\n else:\r\n #Attempt to Retreive Equation from Equation Entry\r\n try:\r\n equation = getEquation(self.eqEntry.get())[0] #Get Equation\r\n except:\r\n self.errorText.config(text=\"Status: Equation Invalid.\"+\r\n \" Check equation contains only x,y,Known\"\r\n +\" Functions,Fitting Parameters and\"\r\n +\"Defined Constants\")\r\n return #Do Not Attempt Fit\r\n \r\n #Get Keys and Symbols From Param Dictionaries\r\n fkeys,fSymbols = self.symbolsFromParams(self.fitParams)\r\n kkeys,kSymbols = self.symbolsFromParams(self.constParams)\r\n \r\n #For Each Fit Parameter, Update Dictionary If Entry not Empty \r\n for fkey in fkeys:\r\n if self.fitParams[fkey][1].get() != \"\":\r\n self.fitParams[fkey][0]=float(self.fitParams[fkey][1].get())\r\n else:\r\n #Otherwise Update Entry With Last Known Value\r\n self.fitParams[fkey][1].insert(tk.END,\r\n str(self.fitParams[fkey][0]))\r\n \r\n #For Each Const Parameter, Update Dictionary If Entry not Empty,\r\n #Substitute That Value Into the Equation\r\n for kkey,kSymbol in zip(kkeys,kSymbols):\r\n if self.constParams[kkey][1].get() != \"\":\r\n self.constParams[kkey][0]=float(self.constParams[kkey][1].get())\r\n else:\r\n #Otherwise Update Entry With Last Known Value\r\n self.constParams[kkey][1].insert(tk.END,\r\n str(self.constParams[kkey][0]))\r\n \r\n #Sub Constant Into Equation\r\n equation = equation.subs(kSymbol,self.constParams[kkey][0])\r\n \r\n #Get Initial Guesses For Fitting Parameters\r\n initialGuesses = [self.fitParams[i][0] for i in fkeys]\r\n \r\n #Check Data File Exists\r\n try:\r\n self.dataFile\r\n except:\r\n #Tell User That No Data Was Loaded\r\n self.errorText.config(text=\"Status: No Data Loaded\")\r\n \r\n return #Do Not Attempt Fit\r\n try:\r\n #Get Tolerence\r\n if self.tolEntry.get() != \"\":\r\n ftol=abs(float(self.tolEntry.get()))\r\n else:\r\n ftol=0.00000001\r\n self.fitParams[fkey][1].insert(tk.END,str(self.fitParams[fkey][0]))\r\n \r\n #Perform the Fit\r\n fitResults, cov = curve_fit(returnFunction1(fSymbols,equation),\r\n self.dataFile[:,0],self.dataFile[:,1]\r\n ,p0=initialGuesses,absolute_sigma=True\r\n ,ftol=ftol,sigma =self.dataFile[:,2])\r\n \r\n #Define a Scaling Factor to Scale the Cov Matrix & Chi-Squared\r\n scalingFactor = (len(self.dataFile)-len(self.fitParams))\r\n \r\n #Get Chi-Squared and Reduced Chi-Squared\r\n chiSqrd = chiSquared(fitResults,self.dataFile,equation,fSymbols) \r\n redChiSqrd = chiSqrd/scalingFactor\r\n \r\n #Scale Cov Matrix to Extract Uncertainties\r\n cov = cov*scalingFactor/(scalingFactor+2)\r\n \r\n #Tell User that Fit Occured\r\n self.errorText.config(text=\"Status: Fit Done\")\r\n except:\r\n #Tell User that Fit Failed\r\n self.errorText.config(text=\"Status: Could Not Perform Fit.\"+\r\n \" Check Fit Parameters and Make sure \"+\r\n \"Equation Contains Only Valid Symbols\")\r\n \r\n return #Do Not Attempt Plot\r\n try:\r\n #Substitute in the Fit Parameters\r\n for i in range(len(fSymbols)):\r\n equation = equation.subs(fSymbols[i],fitResults[i])\r\n \r\n #Choose Graph's Line Colour Based on Reduced Chi-Squared\r\n if 0.5<=redChiSqrd<=2.0:\r\n col = \"b\" #Blue Line\r\n else:\r\n col = \"r\" #Red Line\r\n \r\n #Convert Equation into Function\r\n x = symbols(\"x\")\r\n f = lambdify(x, equation)\r\n \r\n #Plot Equation and Show Fit Params\r\n plotEquation(f,self,col)\r\n self.showFitParams([fitResults,redChiSqrd,cov])\r\n \r\n except:\r\n #Tell User that Plot Failed \r\n self.errorText.config(text=\"Status: Plot Failed\")\r\n \r\n return #Go back to Previous Function\r\n \r\n def symbolsFromParams(self,params):\r\n \"\"\"\r\n Extracts the Keys From the params Dictionary\r\n Creates Sympy Symbols from those Keys\r\n Returns the Keys and the Symbols\r\n \"\"\"\r\n \r\n keys = list(params.keys()) #Get Keys From params Dict\r\n try:\r\n symb = symbols(\" \".join(keys)) #Try to Extract Symbols\r\n \r\n if not isinstance(symb,tuple): #If single Symbol, make tuple\r\n symb = (symb,)\r\n \r\n return keys, symb #Return Keys and Symbols\r\n \r\n except:\r\n symb = () #If 'try:' Failed Return Empty Tuple\r\n self.errorText.config(text=\"Status: No Fitting Parameters\")\r\n \r\n return keys, symb #Return Keys and Symbols\r\n \r\n def dataFromFile(self):\r\n \"\"\"\r\n Opens File Select Window to Select a File\r\n Loads File if it is a .CSV or .TXT and Has More Than 1 Data Point\r\n \"\"\" \r\n filename, delim = getFileName() #Get Filename and Delimiter\r\n \r\n if filename != \"\":\r\n \r\n #reads in data file\r\n self.dataFile = np.genfromtxt(filename, comments='%',\r\n delimiter = delim) \r\n \r\n self.dataText.configure(state=tk.NORMAL) #Make Editable\r\n \r\n if len(self.dataFile) <= 1: #Not Enough Useable Data \r\n \r\n #Edit text\r\n self.dataText.delete('1.0', tk.END)\r\n self.dataText.insert(tk.END,\"File contained no useable data\")\r\n else: #Enough Data to load (Not Necessarily Enough to Fit)\r\n \r\n #Edit text\r\n self.dataText.delete('1.0', tk.END)\r\n self.dataText.insert(tk.END,self.dataFile)\r\n \r\n self.dataText.configure(state=tk.DISABLED) #Make Uneditable\r\n self.errorText.config(text=\"Status: Selected \"+filename.split(\"/\")[-1])\r\n else:\r\n self.errorText.config(text=\"Status: Invalid Input, Please Select\"+\r\n \" a .csv or .txt File\")\r\n\r\ndef chiSquared(guesses, data, equation, fitParams):\r\n \"\"\"\r\n Calculates and Returns the Chi-Squared\r\n Requires the Data File (Array), the Equation Being Fit (Sympy Expression),\r\n The Fit Params (Sympy Symbols) and their Guess Values (array)\r\n \"\"\"\r\n #Define x Symbol\r\n x = symbols(\"x\")\r\n \r\n #Extract x,y and y_err Data from inputted Data Array\r\n x_data = data[:,0]\r\n y_data = data[:,1]\r\n y_err = data[:,2]\r\n\r\n #y-value given by inputted equation\r\n expr = equation\r\n for param,guess in zip(fitParams,guesses):\r\n #Substitute in Guesses\r\n expr = expr.subs(param, guess)\r\n \r\n try: \r\n #Try to Create Function from Sympy Expression\r\n f = lambdify([x], expr) \r\n \r\n #Get y-values Predicted by Expression\r\n yEquationValues = f(x_data)\r\n except:\r\n print(\"Error\")\r\n raise SystemExit\r\n \r\n #Calculate and Return the Chi-Squared \r\n chiSquared = np.sum(((y_data-yEquationValues)/y_err)**2)\r\n return chiSquared \r\n \r\ndef plotEquation(func,gui,col):\r\n \"\"\"\r\n Plots the Data Stored in gui (Member of Gui() Class)\r\n Plots func(x) (The Fitted Data Function)\r\n Plots Residuals\r\n col is a String Determining the Colour of the Fit Line\r\n \"\"\"\r\n #Define Data\r\n data = gui.dataFile\r\n \r\n #Extract x,y and y_err Data from inputted Data Array\r\n x_data = data[:,0]\r\n y_data = data[:,1]\r\n y_err = data[:,2]\r\n \r\n plt.close(1) #Close Figure 1 if One is Already Open\r\n fig = plt.figure(1) #Open New Figure 1\r\n \r\n #Define two Axes\r\n ax1 = fig.add_subplot(211)\r\n ax2 = fig.add_subplot(212)\r\n \r\n #Set Grid to On\r\n ax1.grid(b=True)\r\n ax2.grid(b=True)\r\n \r\n #Set Labels For Each of the Axes\r\n ax1.set_title(gui.graphTitleEntry.get())\r\n ax1.set_ylabel(gui.yAxEntry.get())\r\n ax2.set_ylabel(\"Residuals\")\r\n ax2.set_xlabel(gui.xAxEntry.get())\r\n\r\n #Plot Main Axes\r\n ax1.errorbar(x_data,y_data,y_err, linestyle='none', color='k') #plot data\r\n ax1.plot(x_data,func(x_data), color=col) #plot fit\r\n \r\n #Plot Residual Axes\r\n ax2.errorbar(x_data,y_data-func(x_data),y_err,linestyle='none', color='k')\r\n ax2.plot(x_data,np.zeros(len(x_data)), color=col) #plot fit\r\n \r\n plt.show() #Show Plot\r\n \r\ndef getEquation(string):\r\n \"\"\"\r\n Given a String Value, Convert Into a SymPy Expression and Solve for y\r\n Returns the SymPy Expression\r\n \"\"\" \r\n #Define y Symbol\r\n y = symbols(\"y\")\r\n \r\n #Convert to SymPy Expression\r\n expression = sympify(string)\r\n \r\n #Solve for y\r\n expression = solve(expression,y)\r\n return expression\r\n\r\ndef returnFunction1(*args):\r\n \"\"\"\r\n Nested Function so That Extra Variables Can be Passed Into Curve_Fit\r\n Extra Variables are fitSymbols (Array of SymPy Symbols) and equation\r\n (SymPy Expression)\r\n Returns the Equation Inputted With the Curve_Fit Trial Guesses Substituted\r\n Into the Equation\r\n \"\"\"\r\n #Define fitSymbols and Equation\r\n fitSymbols,equation = args\r\n \r\n #Define Nested Function\r\n def returnFunction2(x,*param):\r\n \r\n #Define fitSymbols and Equation\r\n fitSymbols,equation = args\r\n \r\n #Define x Symbol\r\n xSymb = symbols(\"x\")\r\n \r\n #For Each Fit Symbol, Substitute its Respective Trial Value into\r\n #the Equation\r\n for i in range(len(fitSymbols)):\r\n equation = equation.subs(fitSymbols[i],param[i]) #Sub in Symbol\r\n \r\n #Convert SymPy Expression to Function of x\r\n f = lambdify(xSymb, equation)\r\n \r\n #Returns the Value of the Function Applied to the x Values\r\n return f(x)\r\n \r\n #Call Nested Function\r\n return returnFunction2\r\n\r\ndef getFileName():\r\n \"\"\"\r\n Opens File Selection Window and if Selected File is a .csv or .txt\r\n Returns the Filename and the Delimeter\r\n \"\"\"\r\n #Opens File Selector and Brings it to Front\r\n fileName = askopenfilename()\r\n \r\n #If Cancel Pressed, Exit Program\r\n if fileName == \"\":\r\n print(\"No File Selected\")\r\n \r\n #Check ends in \".csv\" or \".txt\"\r\n split = fileName.split(\".\")\r\n \r\n if split[1] != \"csv\" and split[1] != \"txt\": #Neither .csv or .txt\r\n #Return Empty Strings\r\n return \"\",\"\"\r\n \r\n elif split[1] == \"csv\": #File is a .csv\r\n #Return File Name and \",\" as the Delimeter\r\n return fileName, \",\"\r\n \r\n elif split[1] == \"txt\": #File is a .txt\r\n #Return File Name and a Tab as the Delimeter\r\n return fileName, \"\\t\"\r\n \r\ndef main():\r\n \"\"\"\r\n Main Function, Opens Gui, Sets it Up and Runs It's Main Loop\r\n \"\"\"\r\n try:\r\n #Create New Window to Place Widgets Onto\r\n window = tk.Tk() \r\n \r\n #Initialise and Set-Up Graphical User Interface\r\n gui = Gui(window) \r\n gui.window.title(\"General LSFR\")\r\n gui.window.minsize(width=1500, height=850)\r\n gui.setup() #adds widgets to window\r\n \r\n #window bring to front\r\n window.attributes(\"-topmost\", True) \r\n \r\n #runs GUI's main loop\r\n gui.window.mainloop() \r\n window.withdraw()\r\n \r\n except SystemExit: #catch any attempt to end program\r\n print(\"Terminating program\")\r\n \r\n #Close Any Open Windows By Closing Main Gui (Does Not Close Graphs)\r\n gui.window.destroy() #closes window\r\n \r\n except tk.TclError: #catch any attempt to close GUI\r\n print(\"Terminating program\")\r\n\r\n#Run Main Function \r\nif __name__ == \"__main__\":\r\n main()\r\n ","sub_path":"GeneralLSFR.py","file_name":"GeneralLSFR.py","file_ext":"py","file_size_in_byte":28088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"73751660","text":"#-*- coding:utf-8 -*-\n\nimport datetime\nimport RPG.MoneyBot.MySQL as sql\nimport pandas as pd\nimport RPG.MoneyBot.MakeDecision as decision\nimport RPG.MoneyBot.SelctStocks as select\n\ndef Simulation(stockCode=None, stockName=None, seedMoney=1000000, fromDate='2017-01-01', toDate='2018-12-31', algorithmNumber=0):\n fromSimulDate = datetime.datetime.strptime(str(fromDate), \"%Y-%m-%d\").date()\n toSimulDate = datetime.datetime.strptime((str(toDate)), \"%Y-%m-%d\").date()\n cashValue = seedMoney\n stockCnt = 0\n # 가격데이터 가져오기(나중에 DB select로 변경 예정)\n # stockPriceDF = pd.read_csv(stockDirectory + stock + '_' + kospiList[stock] + '.csv').sort_values(['datetime'])\n\n stockPriceDF = GetStockPrice(stockCode)\n\n for i in range(0, len(stockPriceDF)):\n # date = datetime.datetime.strptime(stockPriceDF[i:i + 1]['datetime'].values[0], \"%Y-%m-%d\").date()\n date = stockPriceDF[i:i + 1]['datetime'].values[0]\n volume = int(stockPriceDF[i:i + 1]['volume'])\n if date >= fromSimulDate and (int(stockPriceDF[i - 1:i]['volume']) * volume) > 0 and date <= toSimulDate:\n\n '''#########################################################################################'''\n '''일자별 의사결정: 매수/매도/Holding'''\n descisionCode, tradeRate = decision.GetAbrilAluScore(stockCode, stockName, date, 0) # 이부분을 코딩한 알고리즘으로 교체하면 됨(거래유형과 거래비율 결정) 0 : AVG, 1 : SUM\n '''#########################################################################################'''\n\n # open = int(stockPriceDF[i:i + 1]['open'])\n close = int(stockPriceDF[i:i + 1]['close'])\n # low = int(stockPriceDF[i:i + 1]['low'])\n # high = int(stockPriceDF[i:i + 1]['high'])\n\n tradeCnt = 0 # 0 ~ 1 사이여야함(거래 비율) : 0이면 거래 안함 1이면 보유현금의 100% 한도까지 거래\n\n if descisionCode > 0:\n # 매수\n tradeCnt = int(cashValue / close * min(tradeRate, 1))\n elif descisionCode < 0 and stockCnt > 0:\n # 매도\n tradeCnt = stockCnt * descisionCode\n\n stockCnt += tradeCnt\n cashValue -= close * tradeCnt\n stockValue = close * stockCnt\n\n # 4. 거래 이력 output\n # wr.writerow([date, descisionCode, stock, kospiList[stock], close, tradeCnt, stockValue, cashValue, (stockValue + cashValue)])\n print('날짜:', date,\n 'tradeRate:', tradeRate,\n '거래유형:', descisionCode,\n '종목코드:', stockCode,\n '종목명:', stockName,\n '거래가격:', close,\n '거래수량:', tradeCnt,\n '주식가치:', stockValue,\n '현금자산:', cashValue,\n '총자산:', stockValue + cashValue)\n\ndef Simulation2(seedMoney=10000000, fromDate='2017-01-01', toDate='2017-12-31'):\n fromSimulDate = datetime.datetime.strptime(str(fromDate), \"%Y-%m-%d\").date()\n toSimulDate = datetime.datetime.strptime((str(toDate)), \"%Y-%m-%d\").date()\n cashValue = seedMoney\n portfolio = dict()\n\n for d in perdelta(fromSimulDate, toSimulDate + datetime.timedelta(days=1), datetime.timedelta(days=1)):\n if(portfolio.__len__() > 0):\n for stock in list(portfolio):\n query = \"SELECT STOCK_CODE, (AVG(sentiment_targets) + AVG(sentiment_document)) / 2 \" \\\n \" FROM aibril_alu \" \\\n \" WHERE issueDatetime >= '%s' \" \\\n \" AND issueDatetime < '%s' \" \\\n \" AND STOCK_CODE = '%s'\t\" \\\n \" GROUP BY STOCK_CODE\" %(pd.to_datetime(str(d + datetime.timedelta(days=-1)) + ' 15:30:00'), pd.to_datetime(str(d) + ' 15:30:00'), stock)\n result = sql.selectStmt(query)\n\n if len(result) > 0:\n tradeRate = result[0][1]\n if tradeRate < 0:\n stockPrice = GetStockPriceByDate(stock, d)\n if len(stockPrice) > 0: # 가격이 있을 때만\n print('매도 :', stock, stockPrice[0][5], portfolio[stock])\n cashValue += stockPrice[0][5] * portfolio[stock]\n portfolio.pop(stock)\n\n else:\n buyStock = select.GetStockByAibrilScore(datetime.datetime.strptime(str(d), \"%Y-%m-%d\").date())[0]\n stockCode = buyStock[0]\n tradeRate = buyStock[1]\n stockPrice = GetStockPriceByDate(stockCode, d)\n if len(stockPrice) > 0: # 가격이 있을 때만\n if tradeRate > 0:\n close = stockPrice[0][5]\n # tradeCnt = int(min(cashValue, 1000000) / close * min(tradeRate, 1))\n tradeCnt = int(min(cashValue, cashValue) / close)\n if tradeCnt > 0:\n if portfolio.__contains__(stockCode):\n portfolio[stockCode] += tradeCnt\n else:\n portfolio[stockCode] = tradeCnt\n cashValue -= close * tradeCnt\n print('매수 :', stockCode, close, tradeCnt)\n\n stockValue = 0\n for stock in portfolio:\n stockValue += portfolio[stock] * GetStockLastPrice(stock, d)[0][0]\n print(d, portfolio, cashValue, stockValue, cashValue+stockValue)\n\ndef perdelta(start, end, delta):\n curr = start\n while curr < end:\n yield curr\n curr += delta\n\ndef GetStockPrice(stockCode=None):\n query = \"SELECT CODE, DATE, PRICE_START, PRICE_HIGH, PRICE_LOW, PRICE_END, TRADE_AMOUNT FROM stock_price WHERE CODE = '%s' ORDER BY DATE\" % stockCode\n df = pd.DataFrame(sql.selectStmt(query))\n df.columns = ['stockcode', 'datetime', 'close', 'high', 'low', 'open', 'volume']\n\n return df\n\ndef GetStockPriceByDate(stockCode=None, date=None):\n query = \"SELECT CODE, DATE, PRICE_START, PRICE_HIGH, PRICE_LOW, PRICE_END, TRADE_AMOUNT FROM stock_price WHERE CODE = '%s' and DATE = '%s' \" % (stockCode, date)\n return sql.selectStmt(query)\n\ndef GetStockLastPrice(stockCode=None, date=None):\n query = \"SELECT PRICE_END FROM stock_price WHERE CODE = '%s' and DATE <= '%s' ORDER BY DATE DESC LIMIT 0, 1 \" % (stockCode, date)\n return sql.selectStmt(query)\n\nSimulation2()","sub_path":"RPG/MoneyBot/Trade.py","file_name":"Trade.py","file_ext":"py","file_size_in_byte":6664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"271710396","text":"class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n self.res = root\n def dfs(node):\n if not node:\n return False\n left, right = dfs(node.left), dfs(node.right)\n porq = (node.val==p.val or node.val==q.val)\n if left+right+porq > 1:\n self.res = node\n return left or right or porq\n dfs(root)\n return self.res\n def lowestCommonAncestor2(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n # iterative\n parent = {root : None}\n stack = [root]\n while not (p in parent and q in parent):\n node = stack.pop(0)\n if node.left:\n parent[node.left] = node\n stack.append(node.left)\n if node.right:\n parent[node.right] = node\n stack.append(node.right)\n p_parents = []\n while p:\n p_parents.append(p)\n p = parent[p]\n while q:\n if q in p_parents:\n return q\n q = parent[q]\n","sub_path":"231/236.py","file_name":"236.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"528502554","text":"import cv2\nimport numpy as np\n\nf1=open(\"C:/object_counting/file.txt\",'w')\n\ncap = cv2.VideoCapture(0)\nret,frame = cap.read()\nframe = cv2.resize(frame,(600,400))\nnum=0\n# mouse callback function\ndef draw_circle(event,x,y,flags,param):\n global num\n if event == cv2.EVENT_LBUTTONDBLCLK:\n cv2.circle(frame,(x,y),2,(255,0,0),-1)\n num+=1\n f1.write(str(x)+\"\\n\")\n f1.write(str(y)+\"\\n\")\n \n# Create a black image, a window and bind the function to window\n\ncv2.namedWindow('image')\n\ncv2.setMouseCallback('image',draw_circle)\n\nwhile(1):\n cv2.imshow('image',frame)\n if cv2.waitKey(20) & 0xFF == 27:\n break\n\nf1.close()\ncv2.destroyAllWindows()","sub_path":"code/point.py","file_name":"point.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"164550509","text":"from flask_login import LoginManager, login_user\nfrom flask import redirect\nimport requests\nfrom TodoUser import TodoUser\nfrom oauthlib.oauth2 import WebApplicationClient\nimport random, string\nimport os\n\nOAUTH_ID = os.environ.get('OAUTH_ID')\nOAUTH_SECRET = os.environ.get('OAUTH_SECRET')\nSECRET_KEY = os.environ.get('secret_key')\n\n\ndef init_auth(app):\n login_mgr = LoginManager()\n\n app.secret_key = SECRET_KEY\n\n @login_mgr.unauthorized_handler\n def unauthorised():\n state = ''.join(random.choices(string.ascii_lowercase, k=16))\n auth_client = WebApplicationClient(OAUTH_ID)\n auth_uri = auth_client.prepare_request_uri(\n 'https://github.com/login/oauth/authorize',\n state=state\n )\n return redirect(auth_uri)\n\n @login_mgr.user_loader\n def load_user(user_id):\n return TodoUser(user_id)\n\n login_mgr.init_app(app)\n\n\ndef get_access_token(code, state):\n auth_client = WebApplicationClient(OAUTH_ID)\n token_request = auth_client.prepare_token_request(\n 'https://github.com/login/oauth/access_token',\n client_id=OAUTH_ID,\n client_secret=OAUTH_SECRET,\n code=code,\n state=state\n )\n print(token_request)\n token_request[1]['Accept'] = 'application/json'\n access_token_response = requests.post(token_request[0], data=token_request[2], headers=token_request[1]).content\n token_params = auth_client.parse_request_body_response(access_token_response)\n return token_params['access_token']\n\n\ndef github_login(code, state):\n access_token = get_access_token(code, state)\n user_request_headers = {'Authorization': 'bearer ' + access_token}\n user_id = requests.get('https://api.github.com/user', headers=user_request_headers).json()['id']\n user = TodoUser(user_id)\n login_user(user)\n","sub_path":"auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"377003096","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom logistic_regression import LogisticRegression\nfrom decision_tree import DecisionTree\nfrom random_forest import RandomForest\n\ndef accuracy_score(Y_true, Y_predict):\n tp_plus_tn = 0\n N = len(Y_true)\n for index in range(N):\n if Y_true[index] == Y_predict[index]:\n tp_plus_tn += 1\n return tp_plus_tn / N\n\n\ndef evaluate_performance():\n '''\n Evaluate the performance of decision trees and logistic regression,\n average over 1,000 trials of 10-fold cross validation\n\n Return:\n a matrix giving the performance that will contain the following entries:\n stats[0,0] = mean accuracy of decision tree\n stats[0,1] = std deviation of decision tree accuracy\n stats[1,0] = mean accuracy of logistic regression\n stats[1,1] = std deviation of logistic regression accuracy\n\n ** Note that your implementation must follow this API**\n '''\n\n # Load Data\n filename = 'data/SPECTF.dat'\n data = np.loadtxt(filename, delimiter=',')\n X = data[:, 1:]\n y = np.array(data[:, 0])\n n, d = X.shape\n\n all_accuracies_dt = []\n all_accuracies_lr = []\n all_accuracies_rf = []\n for trial in range(1):\n idx = np.arange(n)\n np.random.shuffle(idx)\n X = X[idx]\n y = y[idx]\n \n ind = np.arange(X.shape[0])\n classifier_dt = DecisionTree(9)\n classifier_lr = LogisticRegression(max_steps=10000, epsilon=1e-6, step_size = 1, l=3)\n classifier_rf = RandomForest(ratio_per_tree=0.5, num_trees = 100, max_tree_depth=8)\n scores_dt = []\n scores_lr = []\n scores_rf = []\n for i in range(10):\n test_ind = np.random.choice(ind, int(X.shape[0]/10), replace=False)\n ind = np.setdiff1d(np.arange(X.shape[0]), test_ind)\n X_train, Y_train, X_test, Y_test = X[ind], y[ind], X[test_ind], y[test_ind]\n # train the decision tree\n classifier_dt.fit(X_train, Y_train)\n accuracy_dt = accuracy_score(Y_true=Y_test, Y_predict=classifier_dt.predict(X_test))\n scores_dt.append(accuracy_dt)\n # train the logistic regression\n classifier_lr.fit(np.hstack((np.ones(len(X_train)).reshape(len(X_train), 1), X_train)), Y_train)\n accuracy_lr = accuracy_score(Y_true=Y_test, Y_predict=classifier_lr.predict( np.hstack((np.ones(len(X_test)).reshape(len(X_test), 1), X_test))))\n scores_lr.append(accuracy_lr)\n # train the random forest\n classifier_rf.fit(X_train, Y_train)\n accuracy_rf = accuracy_score(Y_true=Y_test, Y_predict=classifier_rf.predict(X_test)[0])\n scores_rf.append(accuracy_rf)\n all_accuracies_dt.append(np.mean(scores_dt))\n all_accuracies_lr.append(np.mean(scores_lr))\n all_accuracies_rf.append(np.mean(scores_rf))\n \n\n\n # compute the training accuracy of the model\n meanDecisionTreeAccuracy = np.mean(all_accuracies_dt)\n stddevDecisionTreeAccuracy = np.std(all_accuracies_dt)\n meanLogisticRegressionAccuracy = np.mean(all_accuracies_lr)\n stddevLogisticRegressionAccuracy = np.std(all_accuracies_lr)\n meanRandomForestAccuracy = np.mean(all_accuracies_rf)\n stddevRandomForestAccuracy = np.std(all_accuracies_rf)\n\n # make certain that the return value matches the API specification\n stats = np.zeros((3, 2))\n stats[0, 0] = meanDecisionTreeAccuracy\n stats[0, 1] = stddevDecisionTreeAccuracy\n stats[1, 0] = meanRandomForestAccuracy\n stats[1, 1] = stddevRandomForestAccuracy\n stats[2, 0] = meanLogisticRegressionAccuracy\n stats[2, 1] = stddevLogisticRegressionAccuracy\n return stats\n\n\n# Do not modify from HERE...\nif __name__ == \"__main__\":\n stats = evaluate_performance()\n print(\"Decision Tree Accuracy = \", stats[0, 0], \" (\", stats[0, 1], \")\")\n print(\"Random Forest Tree Accuracy = \", stats[1, 0], \" (\", stats[1, 1], \")\")\n print(\"Logistic Reg. Accuracy = \", stats[2, 0], \" (\", stats[2, 1], \")\")\n# ...to HERE.\n","sub_path":"Practical-3/part-1/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"442718105","text":"import os\nimport numpy as np\nimport requests\nfrom bs4 import BeautifulSoup as banger\nfrom collections import Counter\nfrom sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB\nfrom sklearn.svm import SVC, NuSVC, LinearSVC\nfrom sklearn.metrics import confusion_matrix\n\nBLACKLISTED = ['the','be','and','of','a','in','to','it','or','an','its','that','is','for','was','on']\n\ndef make_Dictionary():\n all_words = []\n paths = ['./Fake/','./Real/']\n for pizza in paths:\n fs = os.listdir(pizza)\n for i in fs:\n f = open(pizza+i)\n fc = f.read()\n f.close()\n words = fc.split();\n for word in words:\n if word not in BLACKLISTED:\n all_words.append(word)\n\n dictionary = Counter(all_words)\n # removal of nonwords\n list_to_remove = dictionary.keys()\n for item in list_to_remove:\n if item.isalpha() == False:\n del dictionary[item]\n elif len(item) == 1:\n del dictionary[item]\n dictionary = dictionary.most_common(3000)\n return dictionary\n\ndef extract_features():\n pathFake = './Fake/'\n pathReal = './Real/'\n fs = os.listdir(pathReal)\n fx = os.listdir(pathFake)\n features_matrix = np.zeros((len(fx)+len(fs),3000))\n docID = 0\n for i in (fs + fx):\n try:\n f = open(pathFake + i)\n except:\n f = open(pathReal + i)\n q = f.read()\n f.close()\n #recapture q\n words = q.split()\n for word in words:\n for i,d in enumerate(dictionary):\n if d[0] == word:\n wordID = i\n features_matrix[docID,wordID] = words.count(word)\n docID = docID + 1\n return features_matrix\n\n\n\ndef GetWebsiteFromUrl(url):\n html = requests.get(url)\n if(html.status_code >= 300):\n raise Exception(\"URL Returned an invalid response (\", html.status_code, \").\")\n return \"\"\n style = banger(html.text, 'html.parser')\n # kill all script and style elements\n for script in style([\"script\", \"style\"]):\n script.extract()\n text = style.get_text()\n lines = (line.strip() for line in text.splitlines())\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n text = ' '.join(chunk for chunk in chunks if chunk)\n #creating form for neural network to test\n words = text.split()\n web_matrix = np.zeros(3000)\n for word in words:\n for i,d in enumerate(dictionary):\n if d[0] == word:\n wordID = i\n web_matrix[wordID] = words.count(word)\n return web_matrix.reshape(1, -1)\n\n\ntrain_dir = 'train-data'\ndictionary = make_Dictionary()\ntrain_labels = np.zeros(326)\ntrain_labels[198:325] = 1\ntrain_matrix = extract_features()\n#seperate sh** stuff here\n\n#0 is fake 1 is real\n#multinomial Naive Bayes\nmodel1 = MultinomialNB()\n#Linear Support Vector Classifier\nmodel2 = LinearSVC()\nmodel1.fit(train_matrix,train_labels)\nmodel2.fit(train_matrix,train_labels)\n\n\n#test time : )\ntest_matrix = extract_features()\ntest_labels = np.zeros(326)\ntest_labels[198:325] = 1\nresult1 = model1.predict(test_matrix)\nresult2 = model2.predict(test_matrix)\n\nprint(confusion_matrix(test_labels,result1))\nprint(confusion_matrix(test_labels,result2))\n\n\ndef main():\n\tprint(\"Neural Networks trained ready for input!\\n\")\n\tsubmit = ' ';\n\twhile(submit!='quit'):\n\t\tsubmit = raw_input(\"Enter url of website to check if it is fake/bias news or type quit to quit: \")\n\t\tprint(\"Multinomial Naive Bayes result for webpage:\")\n\t\ttry:\n\t\t\tm1 = model1.predict(GetWebsiteFromUrl(submit))\n\t\t\tif(m1==[0.]):\n\t\t\t\tprint(\"Fake/Biased\")\n\t\t\telse:\n\t\t\t\tprint(\"Real/Unbiased\")\n\t\t\tprint(\"Linear Suport Vector Classifier result for webpage:\")\n\t\t\tm2 = model2.predict(GetWebsiteFromUrl(submit))\n\t\t\tif(m2==[0.]):\n\t\t\t\tprint(\"Fake/Biased\")\n\t\t\telse:\n\t\t\t\tprint(\"Real/Unbiased\")\n\t\t\tprint(\"---------------------------------------------------\")\n\t\texcept e:\n \tprint(e)\n\nmain()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"423042269","text":"from flask import Blueprint, render_template\r\n\r\nfrom jakisfilm.db import get_db\r\n\r\nbp = Blueprint('home', __name__, url_prefix='/')\r\n\r\n\r\n@bp.route('/')\r\ndef home():\r\n\r\n db = get_db()\r\n movie_count = db.execute(\r\n 'SELECT COUNT(*)'\r\n ' FROM movie'\r\n ).fetchone()\r\n\r\n return render_template(\r\n 'home/home.html',\r\n movie_count=movie_count[0])\r\n","sub_path":"jakisfilm/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"324737010","text":"#\n# @lc app=leetcode.cn id=1 lang=python\n#\n# [1] 两数之和\n#\n\n# @lc code=start\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n n = len(nums)\n for x in range(n):\n for y in range(x+1 , n):\n if nums[x] + nums[y] == target:\n return x , y\n break\n else:\n continue\n \n# @lc code=end\n\n","sub_path":"Week01/1.两数之和.py","file_name":"1.两数之和.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"273999511","text":"from django.views import View\nfrom onlineapp.models import *\nfrom onlineapp.forms import *\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nimport logging\n\nclass CollegeView(LoginRequiredMixin, View):\n login_url = '/login/'\n def get(self, request, *args, **kwargs):\n if kwargs:\n college = get_object_or_404(College, id=kwargs.get('college_id'))\n studentDetails = Student.objects.values('id', 'name', 'email', 'mocktest1__total').filter(college__id=kwargs.get('college_id')).order_by(\"-mocktest1__total\")\n user_permissions = request.user.get_all_permissions()\n return render(\n request,\n template_name='college_details.html',\n context={\n 'college': college,\n 'studentDetails': studentDetails,\n 'title': 'Students of {} | class project'.format(college.name),\n 'user_permissions': user_permissions,\n 'logged_in': request.user.is_authenticated\n }\n )\n\n colleges=College.objects.all()\n user_permissions = request.user.get_all_permissions()\n logging.error('Error')\n return render(\n request,\n template_name=\"colleges.html\",\n context={\n 'colleges': colleges,\n 'title': 'All colleges | Class Project',\n 'user_permissions': user_permissions,\n 'logged_in': request.user.is_authenticated\n }\n )\n\n\nclass AddCollegeView(LoginRequiredMixin, View):\n login_url = '/login/'\n\n def get(self, request, *args, **kwargs):\n form = AddCollege()\n if kwargs:\n college = College.objects.get(id=kwargs.get('id'))\n form = AddCollege(instance=college)\n\n return render(request, 'add_college.html', {'form': form, 'title': 'Add college', 'logged_in': request.user.is_authenticated})\n\n def post(self, request, *args, **kwargs):\n form = AddCollege(request.POST)\n if kwargs:\n college = College.objects.get(id=kwargs.get('id'))\n form = AddCollege(request.POST, instance=college)\n if form.is_valid():\n form.save()\n return redirect('colleges_html')\n form = AddCollege(request.POST)\n if form.is_valid():\n form.save()\n return redirect('colleges_html')\n\n\nclass DeleteCollegeView(LoginRequiredMixin, View):\n login_url = '/login/'\n def get(self, request, *args, **kwargs):\n if kwargs:\n college = get_object_or_404(College, id=kwargs.get('college_id'))\n college.delete()\n return redirect('colleges_html')\n\n\n\n","sub_path":"classproject/onlineapp/views/college.py","file_name":"college.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"310505073","text":"from distutils.core import setup, Extension\nfrom distutils.extension import Extension\n\n\n# define the extension module\nhelium = Extension('helium', \n\tsources=['helium.c'],\n\t include_dirs=['/usr/include/'], #change this if your environment is different\n\textra_link_args=['-lhe','-lpthread'],\n\textra_compile_args=['-lhe','-lpthread']\n)\n\n# run the setup\nsetup(\n ext_modules=[helium]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"17828251","text":"import urllib\nimport urllib.request\nfrom time import sleep\nfrom dataclasses import dataclass\nfrom abc import ABC, abstractmethod\n\ndef fetch_url(url):\n \"\"\"\n The function is responsible for fetching a url and getting the response\n if we encouter a URL error or an HTTP error, it waits for some time\n and retries the request until several attempts have failed\n \"\"\"\n current_delay=.1 #set the initial retry delay to 100 ms\n max_delay=10 #set maximum retry delay to 10 seconds\n while True:\n try:\n response = urllib.request.urlopen(url)\n except urllib.error.URLError:\n print(\"URL error. Falling to the retry loop with: \"+url)\n pass\n except urllib.error.HTTPError:\n print(\"HTTP error. Falling to the retry loop with: \"+url)\n pass \n else:\n #if there is no error, we can return the response\n return response\n\n #skip this result after mutliple fails:\n if current_delay > max_delay:\n print(\"Too many fails, going to the next one after 60 seconds\")\n sleep(60)\n return None\n\n #add some wait time after the recent fail\n print(\"Waiting\", current_delay, \"seconds before retrying url: \",url)\n sleep(current_delay)\n current_delay *=2\n\n\nclass abstract_param(ABC):\n base_url:str=\"https://www.wikidata.org/w/api.php\"\n \n def encode(self):\n return f\"{self.base_url}?{urllib.parse.urlencode(self._get_param())}\"\n\n @abstractmethod\n def _get_param(self) -> dict:\n pass\n\n@dataclass\nclass TitleRequestParam(abstract_param):\n \"\"\"The class that is responsible for generation of an url for wikidata using a title\"\"\"\n site:str\n title:str\n\n def _get_param(self):\n return {\n \"action\":\"wbgetentities\",\n \"sites\":self.site,\n \"titles\":self.title,\n \"format\":\"json\",\n \"props\":\"info|claims|labels\",\n \"normalize\":1,\n }\n\n@dataclass\nclass IdRequestParam(abstract_param):\n site:str\n id:str\n\n def _get_param(self):\n return {\n \"action\":\"wbgetentities\",\n \"sites\":self.site,\n \"ids\":self.id,\n \"format\":\"json\",\n \"props\":\"info|claims|labels\",\n }\n\n\nif __name__==\"__main__\":\n title_param = TitleRequestParam(\"enwiki\",\"Julia\")\n print(title_param.encode())\n id_param = IdRequestParam(\"enwiki\",\"Q2737173\")\n print(id_param.encode())","sub_path":"synonym_finder/synonym_finder_utils.py","file_name":"synonym_finder_utils.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"480925068","text":"from unet_parts import *\n\n\nclass UNet(nn.Module):\n def __init__(self, n_channels, n_classes):\n super(UNet, self).__init__()\n self.inc = Inconv(n_channels, 64)\n self.down1 = Down(64, 128)\n self.down2 = Down(128, 256)\n self.down3 = Down(256, 512)\n self.down4 = Down(512, 512)\n self.up1_a3up = Up1(512, 256)\n self.up1_b3up = Up1(512, 256)\n self.up2_a3up = Up2(256, 128)\n self.up2_b3up = Up2(256, 128)\n self.up3_a3up = Up3(128, 64)\n self.up3_b3up = Up3(128, 64)\n self.up4_a3up = Up4(64, 64)\n self.up4_b3up = Up4(64, 64)\n self.outc_a3up = Outconv(64, n_classes)\n self.outc_b3up = Outconv(64, n_classes)\n self.lightUnet = LightUNet(n_channels=1, n_classes=1)\n\n def forward(self, x):\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n\n x6 = self.up1_a3up(x5, x4)\n x6_b = self.up1_b3up(x5, x4)\n\n x7 = self.up2_a3up(x6, x3, x4)\n x7_b = self.up2_b3up(x6_b, x3, x4)\n\n x8 = self.up3_a3up(x7, x3, x2)\n x8_b = self.up3_b3up(x7_b, x3, x2)\n\n x9 = self.up4_a3up(x8, x1, x2)\n x9_b = self.up4_b3up(x8_b, x1, x2)\n\n x10 = self.outc_a3up(x9)\n x10_b = self.outc_b3up(x9_b)\n\n x10_ab = self.lightUnet(x10)\n return x10, x10_b, x10_ab\n\n\nclass LightUNet(nn.Module):\n def __init__(self, n_channels, n_classes):\n super(LightUNet, self).__init__()\n self.inc = Inconv(n_channels, 64)\n self.down1 = Down(64, 128)\n self.down2 = Down(128, 128)\n self.up1_a3up = Up1(128, 64)\n self.up2_a3up = Up1(64, 64)\n self.outc_a3up = Outconv(64, n_classes)\n\n\n def forward(self, x):\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n\n x4 = self.up1_a3up(x3, x2)\n x5 = self.up2_a3up(x4, x1)\n x6 = self.outc_a3up(x5)\n\n return x6\n\nif __name__ == '__main__':\n input = torch.rand(4, 3, 512, 512)\n unet = UNet(n_channels=3, n_classes=1)\n output_area, output_bd = unet(input)\n\n for name, param in unet.named_parameters():\n if param.requires_grad:\n print(name)","sub_path":"step3_combine_area_bd/unet/unet_model.py","file_name":"unet_model.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"323911874","text":"import numpy as np\nimport pandas as pd\nfrom time import time\nfrom sklearn import metrics\nfrom sample_encoding_keras import *\nfrom utility import Options, ctr_batch_generator, read_feat_index, eval_auc\nimport tensorflow as tf\n\n\nopts = Options()\nprint('Loading data...')\n\n#############################\n# Settings for ipinyou\n#############################\nopts.sequence_length = 22\nopts.total_training_sample = 127127\n# change here for different camp\n# 1458 2261 2997 3386 3476 2259 2821 3358 3427 all\nBASE_PATH = './data/make-ipinyou-data/all/'\nopts.field_indices_path = BASE_PATH + 'field_indices.txt'\nopts.train_path = BASE_PATH + 'train.yzx.10.txt'\nopts.test_path = BASE_PATH + 'test.yzx.txt'\nopts.featindex = BASE_PATH + 'featindex.txt'\nopts.model_name = 'ipinyou_lr'\n\n### Paramerters for tuning\nopts.batch_size = 512\nopts.dropout = 0.2\n\n\n#############################\n# Settings for criteo\n#############################\n'''\nopts.sequence_length = 35\nopts.total_training_sample = 39799999\n\nBASE_PATH = './data/criteo/'\nopts.field_indices_path = BASE_PATH + 'field_indices.txt'\nopts.train_path = BASE_PATH + 'train.index.txt'\nopts.test_path = BASE_PATH + 'test.index.txt'\nopts.featindex = BASE_PATH + 'featindex.txt'\nopts.model_name = 'criteo_lr'\n\n### Paramerters for tuning\nopts.batch_size = 4096\nopts.dropout = 0.2\n'''\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.33)\nsess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\nK.set_session(sess)\n\nid2cate, cate2id, opts.vocabulary_size = read_feat_index(opts)\n\n#############################\n# Model\n#############################\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Dense, Embedding, Dropout, Activation, Flatten, Merge, merge\n\nmodel = Sequential()\nmodel.add(LR(opts.vocabulary_size, input_length=opts.sequence_length, dropout=0.1, name='prob'))\nmodel.compile(optimizer='nadam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\nprint(model.summary())\n\nopts.current_epoch = 1\n\n#############################\n# Model Training\n#############################\nfor i in range(opts.epochs_to_train):\n print(\"Current Global Epoch: \", opts.current_epoch)\n training_batch_generator = ctr_batch_generator(opts)\n history = model.fit_generator(training_batch_generator, opts.total_training_sample, 1)\n if i % 1 == 0:\n model.save('model_'+opts.model_name+'_' + str(opts.current_epoch) + '.h5')\n eval_auc(model, opts)\n opts.current_epoch += 1\n","sub_path":"ctr_lr.py","file_name":"ctr_lr.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"478261730","text":"# x should be sorted in front of y if int(x+y)-int(y+x) > 0\nclass Solution(object):\n def largestNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: str\n \"\"\"\n nums = map(str, nums)\n nums.sort(cmp=lambda x, y: -(int(x+y)-int(y+x)))\n res = \"\".join(nums)\n return res.lstrip(\"0\") or \"0\" # edge case: \"001\"\n\n\n\n\"\"\"\nGiven a list of non negative integers, arrange them such that they form the largest number.\n\nExample 1:\n\nInput: [10,2]\nOutput: \"210\"\nExample 2:\n\nInput: [3,30,34,5,9]\nOutput: \"9534330\"\n\"\"\"\n","sub_path":"0179. Largest Number.py","file_name":"0179. Largest Number.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"247043806","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden\nfrom django.template.loader import render_to_string\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response, redirect\nfrom django.contrib.contenttypes.models import ContentType\nfrom flag.models import *\nfrom django.contrib.auth.models import User\nfrom django.utils import simplejson\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.http import require_POST\nfrom django.contrib.auth.decorators import login_required\nfrom django.forms.models import model_to_dict\nfrom django.template.loader import render_to_string\nfrom django.views.generic import ListView\nfrom django.views.decorators.cache import never_cache\nfrom flag.utils import generate_unflag_url, generate_flag_url\nimport hashlib\n\n@login_required\n@never_cache\ndef flag(request, ftype, ct, pk, token, action=None):\n success = False\n\n if request.method == 'POST':\n data = request.POST.copy()\n else:\n data = request.GET.copy()\n \n # Security check\n token_check = hashlib.md5(settings.SECRET_KEY + str(ct) + str(pk)).hexdigest()\n \n response = data.get('response', 'json')\n\n if token_check != token:\n return HttpResponseForbidden()\n \n # Load type\n ctype = ContentType.objects.get(id=ct)\n \n # Get Flag Type\n ftype = FlagType.objects.get(slug=ftype)\n ftype.set = False\n \n # Build our query filter\n kwargs = {\n 'content_type': ctype,\n 'object_pk': pk,\n 'ftype': ftype,\n }\n \n kwargs['user'] = request.user\n \n # Execute, either set a flag or remove it\n if action == \"flag\":\n try:\n flag = Flag.objects.get_or_create(**kwargs)\n success = True\n state = 'flagged'\n ftype.set = True\n except Flag.DoesNotExist:\n success = False\n \n elif action == \"unflag\":\n try:\n flag = Flag.objects.get(**kwargs)\n flag.delete()\n success = True\n state = 'unflagged'\n except Flag.DoesNotExist:\n state = 'unflagged'\n \n # Add some extra info\n obj = ctype.get_object_for_this_type(pk=pk)\n ftype.unflag_url = generate_unflag_url(user=request.user, obj=obj, ftype=ftype.slug)\n ftype.flag_url = generate_flag_url(user=request.user, obj=obj, ftype=ftype.slug)\n \n if(request.is_ajax()):\n if response == 'html':\n output = render_to_string('flag/flag.html', {'user': request.user, 'flag': ftype}, context_instance=RequestContext(request))\n return HttpResponse(output)\n else: \n data = {}\n data['success'] = str(success)\n data['state'] = str(state)\n data['ftype'] = model_to_dict(ftype)\n return HttpResponse(simplejson.dumps(data), content_type=\"text/javascript\")\n else:\n next = data.get(\"next\", request.META.get('HTTP_REFERER'))\n return HttpResponseRedirect(next)\n","sub_path":"flag/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"67652155","text":"import re\nimport requests\nfrom requests.exceptions import RequestException\n\n\ndef get_page(list_page):\n url = 'https://blog.csdn.net/sxhelijian/article/list/' + str(list_page)\n headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) '\n + 'Chrome/67.0.3396.99 Safari/537.36'\n }\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n print('请求出错!')\n return None\n\ndef parse_page(html):\n pattern = re.compile(r'(.*?).*?date\">(.*?).*?'\n + r'阅读数:(.*?).*?评论数:(.*?)', re.S)\n items = re.findall(pattern, html)\n for item in items:\n yield {\n '标题': item[1].strip(),\n '发表时间': item[2],\n '阅读数': item[3],\n '评论数': item[4],\n '原文地址': item[0]\n }\n\n\ndef get_classhtml(url):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) '\n + 'Chrome/67.0.3396.99 Safari/537.36'\n }\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n return response.text\n except RequestException:\n print('请求出错!')\n return None\n\n\ndef get_class(html):\n pattern1 = re.compile(r'
(.*?)
', re.S)\n pattern2 = re.compile(r'个人分类:.*?target=\"_blank\">(.*?)<', re.S)\n pattern3 = re.compile(r'<[^>]+>', re.S)\n context = re.findall(pattern1, html)\n item1 = pattern3.sub('', context[0].strip())\n item2 = re.findall(pattern2, html)\n if item2:\n for item in item2:\n yield {\n '文章内容': item1,\n '个人分类': item.strip()\n }\n else:\n yield {\n '文章内容': item1,\n '个人分类': '未分类'\n }\n\n\ndef main(list_page):\n for item in parse_page(get_page(list_page)):\n dict1 = item\n for i in get_class(get_classhtml(item['原文地址'])):\n dict2 = i\n info = dict(dict1, **dict2)\n yield info\n\n\nif __name__ == '__main__':\n for i in range(1, 10):\n main(i)\n\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"10897436","text":"import math\nimport os\nimport pickle\nimport sys\nfrom collections import Counter\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nvector_model_data = {}\nthe_matrix = {}\nflattening_map = []\n\n\n# returns list of vector files based on vector model\ndef get_list_of_files(dir, vector_model):\n current_folder = os.path.dirname(os.path.abspath(__file__))\n data_dir = os.path.join(current_folder, dir)\n list_of_files = os.listdir(data_dir)\n return [file for file in list_of_files if file.__contains__(vector_model + '_vectors')]\n\n\n# stores vector model data globally\ndef read_file_data(list_of_files, dir):\n current_folder = os.path.dirname(os.path.abspath(__file__))\n for each_file in list_of_files:\n # file_path = dir + \"/\" + each_file\n data_dir = os.path.join(current_folder, dir)\n file_path = os.path.join(data_dir, each_file)\n file_handler = open(file_path, 'rb')\n if each_file.count(\"_\") == 3:\n keys = each_file.split('.')[0].split('_')\n key = keys[-2] + \"_\" + keys[-1]\n else:\n key = each_file.split('.')[0].split('_')[-1]\n vector_model_data[key] = pickle.load(file_handler)\n\n\n# return list of features across dimensions\ndef get_list_of_features():\n list_of_features = []\n for each_file in vector_model_data:\n for each_dimension in vector_model_data[each_file]:\n for each_sensor in vector_model_data[each_file][each_dimension]:\n for each_word in vector_model_data[each_file][each_dimension][each_sensor]:\n list_of_features.append((each_dimension, each_sensor, each_word[0]))\n return list_of_features\n\n\n# returns list of unique features\ndef get_unique_features(list_of_features):\n return list(Counter(list_of_features).keys())\n\n\n# globally stores the feature matrix and creates a name map for each file\ndef form_the_matrix(set_of_features):\n for each_file in vector_model_data:\n word_list = []\n value_list = []\n for each_dimension in vector_model_data[each_file]:\n for each_sensor in vector_model_data[each_file][each_dimension]:\n for each_word in vector_model_data[each_file][each_dimension][each_sensor]:\n word_list.append((each_dimension, each_sensor, each_word[0]))\n value_list.append(each_word[1])\n\n temp_list = []\n for each_feature in set_of_features:\n if (each_feature in word_list):\n index = word_list.index(each_feature)\n temp_list.append(value_list[index])\n else:\n temp_list.append(0)\n\n the_matrix[each_file] = temp_list\n\n\n# returns similarity based on dot product of vectors\ndef get_distance_similarity(gesture_vector):\n list_of_similarities = []\n for each_file in the_matrix:\n # compute the similarity for only the main vectors\n if each_file.count(\"_\") == 0:\n distance = 0\n # computing Eucledian distance here\n for i in range(len(the_matrix[each_file])):\n distance = distance + (gesture_vector[i] * the_matrix[each_file][i])\n\n distance = math.sqrt(distance)\n list_of_similarities.append((each_file, distance))\n\n if not list_of_similarities:\n return list_of_similarities\n\n return sorted(list_of_similarities, key=lambda x: x[1], reverse=True)[:k + 1]\n\n\n# returns cosine similarity between two vectors\ndef get_cosine_similarity(transformed_matrix, gesture_vector):\n list_of_similarities = []\n for i in range(len(transformed_matrix)):\n score = 0\n gesture_score = 0\n vector_score = 0\n for j in range(len(transformed_matrix[i])):\n score = score + (gesture_vector[j] * transformed_matrix[i][j])\n gesture_score += gesture_vector[j] ** 2\n vector_score += transformed_matrix[i][j] ** 2\n final_score = score / (math.sqrt(gesture_score) * math.sqrt(vector_score))\n list_of_similarities.append((flattening_map[i], final_score))\n\n return sorted(list_of_similarities, key=lambda x: x[1], reverse=True)\n\n\n# flattens matrix for decompositions and creates a map for indices to file names\ndef flatten_the_matrix():\n temp_matrix = []\n for each_file in the_matrix:\n flattening_map.append(each_file)\n temp_matrix.append(the_matrix[each_file])\n return np.array(temp_matrix)\n\n\n# returns the edit distance cost between two files\ndef editdist(s, t): # for wrd files\n rows = len(s) + 1\n cols = len(t) + 1\n\n dist = [[0 for x in range(cols)] for x in range(rows)]\n\n for row in range(1, rows):\n dist[row][0] = row * 3\n\n for col in range(1, cols):\n dist[0][col] = col * 3\n\n for row in range(1, rows):\n for col in range(1, cols):\n if s[row - 1] == t[col - 1]:\n cost = 0\n else:\n cost = 0\n for i in range(len(s[row - 1])):\n if s[row - 1][i] != t[col - 1][i]:\n cost += 1\n\n dist[row][col] = min(dist[row - 1][col] + 3, # deletes\n dist[row][col - 1] + 3, # inserts\n dist[row - 1][col - 1] + cost) # substitution\n return dist[row][col]\n\n\n# prints output in legible format\ndef print_results(result):\n for r in result:\n print(r)\n\n\ndef perform_knn(similarity_matrix, k, test_key):\n gesture_1 = 'vattene'\n gesture_2 = 'Combinato'\n gesture_3 = \"D'Accordo\"\n config_map = {gesture_1: [1, 31], gesture_2: [249, 279], gesture_3: [559, 589]}\n result_map = {}\n for key in config_map:\n config_range = config_map[key]\n for i in range(config_range[0], config_range[1] + 1):\n result_map[str(i)] = key\n\n count_map = {}\n max_count = 0\n max_key = ''\n for i in range(0, k):\n top_result = similarity_matrix[i]\n if top_result[0] in result_map:\n key = result_map[top_result[0]]\n else:\n key = 'U'\n\n if key in count_map:\n count_map[key] += 1\n else:\n count_map[key] = 1\n\n if count_map[key] > max_count:\n max_count = count_map[key]\n max_key = key\n\n print('According to KNN the best group the key falls into: ' + max_key)\n print('Correct value of the key: ' + str(result_map[test_key]))\n print('Keys in group are in range: ' + str(config_map[max_key]))\n if result_map[test_key] == max_key:\n return 1\n return 0\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) < 3:\n print('Run python phase3_task2_knn.py ')\n sys.exit(0)\n\n directory = sys.argv[1]\n vector_model = sys.argv[2]\n k = int(sys.argv[3])\n\n print(\"Directory: {}\\nVector Model: {}\\nk: {}\".format(directory, vector_model, k))\n\n # function calls to initialize all global variables\n list_of_files = get_list_of_files(directory, vector_model)\n read_file_data(list_of_files, directory)\n list_of_features = get_list_of_features()\n set_of_features = get_unique_features(list_of_features)\n form_the_matrix(set_of_features)\n\n print(type(the_matrix))\n keys = list(the_matrix.keys())\n train, test = train_test_split(keys, test_size=0.2)\n total_count = 0\n correct_count = 0\n # for test_key in test:\n for test_key in keys:\n if test_key.count(\"_\") == 1:\n total_count += 1\n gesture_vector = the_matrix[test_key]\n similarity_matrix = get_distance_similarity(gesture_vector)\n # ignoring the first key\n if similarity_matrix:\n similarity_matrix = similarity_matrix[1:]\n print(\"Printing the similarity results based on dot product\")\n print_results(similarity_matrix)\n correct_count += perform_knn(similarity_matrix, k, test_key.split(\"_\")[0])\n\n print(\"Total count: \" + str(total_count))\n print(\"Count: \" + str(correct_count))\n print(\"Accuracy: \" + str(correct_count / total_count))\n","sub_path":"Phase 3/phase3_task2_knn.py","file_name":"phase3_task2_knn.py","file_ext":"py","file_size_in_byte":8087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"331202599","text":"# Copyright (c) 2023 CNES\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\nimport numpy\nimport pytest\n\nfrom ...core import GeoHash, geohash\n\ntestcases = [['77mkh2hcj7mz', -26.015434642, -26.173663656],\n ['wthnssq3w00x', 29.291182895, 118.331595326],\n ['z3jsmt1sde4r', 51.400326027, 154.228244707],\n ['18ecpnqdg4s1', -86.976900779, -106.90988479],\n ['u90suzhjqv2s', 51.49934315, 23.417648894],\n ['k940p3ewmmyq', -39.365655496, 25.636144008],\n ['6g4wv2sze6ms', -26.934429639, -52.496991862],\n ['jhfyx4dqnczq', -62.123898484, 49.178194037],\n ['j80g4mkqz3z9', -89.442648795, 68.659722351],\n ['hq9z7cjwrcw4', -52.156511416, 13.883626414]]\n\n\ndef test_string_numpy():\n strs = numpy.array([item[0] for item in testcases], dtype='S')\n lons, lats = geohash.decode(strs, round=True)\n assert numpy.all(\n numpy.abs( # type: ignore\n lons - numpy.array([item[2] for item in testcases])) < 1e-6)\n assert numpy.all(\n numpy.abs( # type: ignore\n lats - numpy.array([item[1] for item in testcases])) < 1e-6)\n\n strs = numpy.array([item[0] for item in testcases], dtype='U')\n with pytest.raises(ValueError):\n geohash.decode(strs, round=True)\n strs = numpy.array([item[0] for item in testcases],\n dtype='S').reshape(5, 2)\n with pytest.raises(ValueError):\n geohash.decode(strs, round=True)\n strs = numpy.array([b'0' * 24], dtype='S')\n with pytest.raises(ValueError):\n geohash.decode(strs, round=True)\n strs = numpy.array([item[0] for item in testcases], dtype='S')\n strs = numpy.vstack((strs[:5], strs[5:]))\n indexes = geohash.where(strs)\n assert isinstance(indexes, dict)\n\n with pytest.raises(ValueError):\n indexes = geohash.where(strs.astype('U'))\n\n strs = numpy.array([item[0] for item in testcases], dtype='S')\n strs.reshape(1, 2, 5)\n with pytest.raises(ValueError):\n indexes = geohash.where(strs)\n\n\ndef test_bounding_boxes():\n bboxes = geohash.bounding_boxes(precision=1)\n assert len(bboxes) == 32\n for bbox in bboxes:\n code = GeoHash.from_string(bbox.decode())\n case = geohash.bounding_boxes(code.bounding_box(), precision=1)\n assert len(case) == 1\n assert case[0] == bbox\n\n case = geohash.bounding_boxes(code.bounding_box(), precision=3)\n assert len(case) == 2**10\n assert all(item.startswith(bbox) for item in case)\n\n with pytest.raises(MemoryError):\n geohash.bounding_boxes(precision=12)\n\n\ndef test_bounding_zoom():\n bboxes = geohash.bounding_boxes(precision=1)\n assert len(bboxes) == 32\n\n zoom_in = geohash.transform(bboxes, precision=3)\n assert len(zoom_in) == 2**10 * 32\n assert numpy.all(\n numpy.sort(geohash.transform(zoom_in, precision=1)) == numpy.sort(\n bboxes))\n\n\ndef test_class():\n for code, lat, lon in testcases:\n instance = GeoHash.from_string(code)\n assert str(instance) == code\n point = instance.center()\n assert lat == pytest.approx(point.lat, abs=1e-6)\n assert lon == pytest.approx(point.lon, abs=1e-6)\n","sub_path":"src/pyinterp/tests/core/test_geohash.py","file_name":"test_geohash.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"583538145","text":"\"\"\"Nexus URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\nfrom core import views\r\nfrom django.views.generic import RedirectView\r\n\r\nurlpatterns = [\r\n path('admin/', admin.site.urls),\r\n path('albuns/', views.lista_album),\r\n path('albuns/criar/', views.albuns),\r\n path('albuns/criar/submit', views.submit_album),\r\n path('albuns/criar/delete//', views.delete_album),\r\n path('', RedirectView.as_view(url='/albuns/')),\r\n path('login/', views.login_user),\r\n path('login/submit', views.submit_login),\r\n path('logout/', views.logout_user)\r\n]\r\n","sub_path":"Nexus/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"88150033","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\"\"\"\nCreated on Mon Sep 25 23:16:54 2017\n\n@author: josef\n\"\"\"\n\nimport turtle, datetime, time\n\nmyPen = turtle.Turtle()\nmyPen.shape(\"arrow\")\nmyPen.tracer(0)\nmyPen.speed(0)\nmyPen.shapesize(.5,1)\nturtle.delay(0)\n\nmyPen.penup()\nmyPen.goto(0,-180)\nmyPen.pendown()\nmyPen.pensize(3)\nmyPen.color(\"blue\")\nmyPen.circle(180)\n\nfor wi in range(6,361,6): # 360/60 = 6 -- Sekundenstriche\n myPen.penup()\n myPen.goto(0,0)\n myPen.setheading(wi)\n myPen.fd(160)\n myPen.pendown()\n myPen.fd(10)\n\nmyPen.pensize(6)\nfor wi in range(30,361,30): # 360/60 = 6 -- Minutenstriche\n myPen.penup() # bei 3,6,9,12 länger\n myPen.goto(0,0)\n myPen.setheading(wi)\n if wi % 90 == 0:\n myPen.fd(155)\n myPen.down()\n myPen.fd(15)\n else:\n myPen.fd(160)\n myPen.pendown()\n myPen.fd(10)\n\nmyPen.pensize(3)\n\nwhile True:\n myPen.color(\"red\")\n currentSecond = datetime.datetime.now().second\n currentMinute = datetime.datetime.now().minute\n currentHour = datetime.datetime.now().hour\n myPen.penup()\n myPen.goto(0,0)\n myPen.setheading(90) # Point to the top - 12 o'clock\n myPen.right(currentHour*360/12+currentMinute*360/12/60+currentSecond*360/12/60/60)\n myPen.pendown()\n myPen.pensize(7)\n myPen.forward(100)\n myPen.stamp()\n\n myPen.penup()\n myPen.goto(0,0)\n myPen.setheading(90) # Point to the top - 0 minute\n myPen.right(currentMinute*360/60+currentSecond*360/60/60)\n myPen.pendown()\n myPen.pensize(5)\n myPen.forward(130)\n myPen.stamp()\n \n myPen.color(\"green\") \n myPen.penup()\n myPen.goto(0,0)\n \n myPen.pensize(7)\n myPen.dot()\n myPen.pensize(3)\n \n myPen.setheading(90) # Point to the top - 0 minute\n myPen.right(currentSecond*360/60)\n myPen.pendown()\n myPen.forward(140)\n \n myPen.getscreen().update()\n\n time.sleep(.99)\n for _ in range(20):\n myPen.undo()\n\n# myPen.getscreen().update()\n\n#turtle.done()\n","sub_path":"2017/turtle_grafik/101computing.net/turtle_clock.py","file_name":"turtle_clock.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"189267316","text":"#!/usr/bin/python3.6\r\n# -*- coding: utf-8 -*-\r\n\r\nimport re\r\nimport ftplib\r\nimport calendar\r\nimport time\r\nimport sys\r\nimport os\r\nimport json\r\nfrom pprint import pprint\r\nfrom datetime import datetime\r\nfrom datetime import date, timedelta\r\nfrom bson import ObjectId\r\nfrom helper.ftp import Ftp\r\nfrom helper.mongod import Mongodb\r\nfrom helper.excel import Excel\r\nfrom helper.jaccs import Config\r\nfrom helper.common import Common\r\nfrom helper.mongodbaggregate import Mongodbaggregate\r\nfrom math import floor\r\nimport traceback\r\n\r\ncommon = Common()\r\nbase_url = common.base_url()\r\nwff_env = common.wff_env(base_url)\r\nmongodb = Mongodb(MONGODB=\"worldfone4xs\", WFF_ENV=wff_env)\r\n_mongodb = Mongodb(MONGODB=\"_worldfone4xs\", WFF_ENV=wff_env)\r\n\r\nsubUserType = 'LO'\r\ncollection = common.getSubUser(subUserType, 'Loan_group_report')\r\nlog = open(base_url + \"cronjob/python/Loan/log/cardLoanGroup_log.txt\",\"a\")\r\nnow = datetime.now()\r\nlog.write(now.strftime(\"%d/%m/%Y, %H:%M:%S\") + ': Start Import' + '\\n')\r\ntry:\r\n insertData = []\r\n updateData = []\r\n listDebtGroup = []\r\n zaccfData = []\r\n today = date.today()\r\n # today = datetime.strptime('05/01/2020', \"%d/%m/%Y\").date()\r\n yesterday = today - timedelta(days=1)\r\n\r\n day = yesterday.day\r\n month = yesterday.month\r\n year = yesterday.year\r\n weekday = yesterday.weekday()\r\n lastDayOfMonth = calendar.monthrange(year, month)[1]\r\n\r\n first_day = yesterday.replace(day=1)\r\n\r\n weekdayMonth = first_day.weekday()\r\n if weekdayMonth == 6:\r\n weekdayMonth = 0\r\n else:\r\n weekdayMonth += 1\r\n adjusted_dom = day + weekdayMonth\r\n weekOfMonth = (floor((adjusted_dom - 1)/7) + 1)\r\n\r\n todayString = today.strftime(\"%d/%m/%Y\")\r\n todayTimeStamp = int(time.mktime(time.strptime(str(todayString + \" 00:00:00\"), \"%d/%m/%Y %H:%M:%S\")))\r\n endTodayTimeStamp = int(time.mktime(time.strptime(str(todayString + \" 23:59:59\"), \"%d/%m/%Y %H:%M:%S\")))\r\n\r\n startMonth = int(time.mktime(time.strptime(str('01/' + str(month) + '/' + str(year) + \" 00:00:00\"), \"%d/%m/%Y %H:%M:%S\")))\r\n endMonth = int(time.mktime(time.strptime(str(str(lastDayOfMonth) + '/' + str(month) + '/' + str(year) + \" 23:59:59\"), \"%d/%m/%Y %H:%M:%S\")))\r\n\r\n # holidayOfMonth = mongodb.getOne(MONGO_COLLECTION=common.getSubUser(subUserType, 'Report_off_sys'), WHERE={'off_date': todayTimeStamp})\r\n # if holidayOfMonth != None:\r\n # sys.exit()\r\n # listHoliday = map(lambda offDateRow: {offDateRow['off_date']}, holidayOfMonth)\r\n\r\n # if todayTimeStamp in listHoliday:\r\n # sys.exit()\r\n mongodb.remove_document(MONGO_COLLECTION=collection, WHERE={'createdAt': {'$gte': todayTimeStamp, '$lte': endTodayTimeStamp} })\r\n\r\n yesterdayString = yesterday.strftime(\"%d/%m/%Y\")\r\n \r\n\r\n mainProduct = {}\r\n mainProductRaw = mongodb.get(MONGO_COLLECTION=common.getSubUser(subUserType, 'Product'))\r\n for prod in mainProductRaw:\r\n mainProduct[prod['code']] = prod['name']\r\n\r\n \r\n month = yesterday.strftime(\"%B\")\r\n weekday = yesterday.strftime(\"%A\")\r\n\r\n # ZACCF\r\n aggregate_zaccf = [\r\n {\r\n \"$match\":\r\n {\r\n '$or' : [ { 'createdAt' : {'$gte': todayTimeStamp}}, {'updatedAt' : {'$gte': todayTimeStamp}}],\r\n \"W_ORG_1\": {'$gt': 0},\r\n }\r\n },{\r\n \"$group\":\r\n {\r\n \"_id\": '$ODIND_FG',\r\n \"total_org\": {'$sum': '$W_ORG_1'},\r\n 'W_ORG_arr': {'$push': '$W_ORG_1'},\r\n \"count_data\": {'$sum': 1},\r\n }\r\n }\r\n ]\r\n zaccfInfo = mongodb.aggregate_pipeline(MONGO_COLLECTION=common.getSubUser(subUserType, 'ZACCF_report'),aggregate_pipeline=aggregate_zaccf)\r\n zaccfInfo1 = zaccfInfo\r\n sum_org = 0\r\n sum_acc = 0\r\n sum_org_g2 = 0\r\n sum_acc_g2 = 0\r\n sum_org_g3 = 0\r\n sum_acc_g3 = 0\r\n sum_org_B = 0\r\n sum_acc_B = 0\r\n if zaccfInfo is not None:\r\n for zaccf in zaccfInfo:\r\n if zaccf['_id'] != None:\r\n temp = zaccf\r\n # temp['total_org'] = 0\r\n # for orgInfo in zaccf['W_ORG_arr']:\r\n # org = float(orgInfo)\r\n # temp['total_org'] += org\r\n # # print(zaccf['total_org'])\r\n zaccfData.append(temp)\r\n\r\n for zaccf in zaccfData:\r\n if zaccf['_id'] != None:\r\n sum_org += zaccf['total_org']\r\n sum_acc += zaccf['count_data']\r\n if zaccf['_id'] != 'A':\r\n sum_org_g2 += zaccf['total_org']\r\n sum_acc_g2 += zaccf['count_data']\r\n if zaccf['_id'] == 'B':\r\n sum_org_B += zaccf['total_org']\r\n sum_acc_B += zaccf['count_data']\r\n\r\n sum_org_g3 = sum_org_g2 - sum_org_B\r\n sum_acc_g3 = sum_acc_g2 - sum_acc_B\r\n\r\n for zaccf in zaccfData:\r\n if zaccf['_id'] != None:\r\n temp = {}\r\n if zaccf['_id'] == 'A':\r\n temp['group'] = '1'\r\n if zaccf['_id'] == 'B':\r\n temp['group'] = '2'\r\n if zaccf['_id'] == 'C':\r\n temp['group'] = '3'\r\n if zaccf['_id'] == 'D':\r\n temp['group'] = '4'\r\n if zaccf['_id'] == 'E':\r\n temp['group'] = '5'\r\n\r\n temp['count_data'] = zaccf['count_data']\r\n temp['total_org'] = zaccf['total_org']\r\n temp['ratio'] = temp['total_org']/sum_org if sum_org != 0 else 0\r\n temp['year'] = str(year)\r\n temp['month'] = month\r\n temp['weekday'] = weekday\r\n temp['day'] = yesterdayString\r\n temp['weekOfMonth'] = weekOfMonth\r\n temp['type'] = 'sibs'\r\n temp['createdBy'] = 'system'\r\n temp['createdAt'] = todayTimeStamp\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=temp)\r\n\r\n insertTotal = {\r\n 'year' : str(year),\r\n 'month' : month,\r\n 'weekday' : weekday,\r\n 'day' : yesterdayString,\r\n 'weekOfMonth' : weekOfMonth,\r\n 'type' : 'sibs',\r\n 'createdBy' : 'system',\r\n 'createdAt' : todayTimeStamp\r\n }\r\n insertTotalG2 = {\r\n 'year' : str(year),\r\n 'month' : month,\r\n 'weekday' : weekday,\r\n 'day' : yesterdayString,\r\n 'weekOfMonth' : weekOfMonth,\r\n 'type' : 'sibs',\r\n 'createdBy' : 'system',\r\n 'createdAt' : todayTimeStamp\r\n }\r\n insertTotalG3 = {\r\n 'year' : str(year),\r\n 'month' : month,\r\n 'weekday' : weekday,\r\n 'day' : yesterdayString,\r\n 'weekOfMonth' : weekOfMonth,\r\n 'type' : 'sibs',\r\n 'createdBy' : 'system',\r\n 'createdAt' : todayTimeStamp\r\n }\r\n insertTotal['group'] = 'Total'\r\n insertTotal['total_org'] = sum_org\r\n insertTotal['count_data'] = sum_acc\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=insertTotal)\r\n insertTotalG2['group'] = 'G2'\r\n insertTotalG2['total_org'] = sum_org_g2\r\n insertTotalG2['count_data'] = sum_acc_g2\r\n insertTotalG2['ratio'] = insertTotalG2['total_org']/sum_org if sum_org != 0 else 0\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=insertTotalG2)\r\n insertTotalG3['group'] = 'G3'\r\n insertTotalG3['total_org'] = sum_org_g3\r\n insertTotalG3['count_data'] = sum_acc_g3\r\n insertTotalG3['ratio'] = insertTotalG3['total_org']/sum_org if sum_org != 0 else 0\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=insertTotalG3)\r\n\r\n\r\n\r\n\r\n # Card\r\n sbvData = []\r\n \r\n aggregate_sbv_1 = [\r\n {\r\n \"$project\":\r\n {\r\n 'pay': {'$sum' : [ '$ob_principal_sale', '$ob_principal_cash']},\r\n 'delinquency_group': 1\r\n }\r\n },\r\n {\r\n \"$match\":\r\n {\r\n 'pay': {'$gt' : 0}\r\n }\r\n },\r\n {\r\n \"$group\":\r\n {\r\n \"_id\": '$delinquency_group',\r\n \"total_ob_principal\": {'$sum': '$pay'},\r\n \"count_data\": {'$sum': 1},\r\n }\r\n }\r\n ]\r\n dataSBV = list(mongodb.aggregate_pipeline(MONGO_COLLECTION=common.getSubUser(subUserType, 'SBV'),aggregate_pipeline=aggregate_sbv_1))\r\n \r\n sum_org = 0\r\n sum_acc = 0\r\n sum_org_g2 = 0\r\n sum_acc_g2 = 0\r\n sum_org_g3 = 0\r\n sum_acc_g3 = 0\r\n sum_org_B = 0\r\n sum_acc_B = 0\r\n if dataSBV is not None:\r\n for sbv in dataSBV:\r\n temp = sbv\r\n total_org = sbv['total_ob_principal']\r\n\r\n temp['total_org'] = total_org\r\n sum_org += total_org\r\n sum_acc += sbv['count_data']\r\n if sbv['_id'] != '01':\r\n sum_org_g2 += total_org\r\n sum_acc_g2 += sbv['count_data']\r\n if sbv['_id'] == '02':\r\n sum_org_B += total_org\r\n sum_acc_B += sbv['count_data']\r\n\r\n sbvData.append(temp)\r\n\r\n sum_org_g3 = sum_org_g2 - sum_org_B\r\n sum_acc_g3 = sum_acc_g2 - sum_acc_B\r\n\r\n # print(sum_acc_g2)\r\n # print(sum_acc_g3)\r\n\r\n if sbvData is not None:\r\n for sbv in sbvData:\r\n temp = {}\r\n temp['group'] = sbv['_id']\r\n temp['count_data'] = sbv['count_data']\r\n temp['total_org'] = sbv['total_org']\r\n temp['ratio'] = temp['total_org']/sum_org if sum_org != 0 else 0\r\n temp['year'] = str(year)\r\n temp['month'] = month\r\n temp['weekday'] = weekday\r\n temp['day'] = yesterdayString\r\n temp['weekOfMonth'] = weekOfMonth\r\n temp['type'] = 'card'\r\n temp['createdBy'] = 'system'\r\n temp['createdAt'] = todayTimeStamp\r\n # print(temp)\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=temp)\r\n\r\n insertTotal = {\r\n 'year' : str(year),\r\n 'month' : month,\r\n 'weekday' : weekday,\r\n 'day' : yesterdayString,\r\n 'weekOfMonth' : weekOfMonth,\r\n 'type' : 'card',\r\n 'createdBy' : 'system',\r\n 'createdAt' : todayTimeStamp\r\n }\r\n insertTotalG2 = {\r\n 'year' : str(year),\r\n 'month' : month,\r\n 'weekday' : weekday,\r\n 'day' : yesterdayString,\r\n 'weekOfMonth' : weekOfMonth,\r\n 'type' : 'card',\r\n 'createdBy' : 'system',\r\n 'createdAt' : todayTimeStamp\r\n }\r\n insertTotalG3 = {\r\n 'year' : str(year),\r\n 'month' : month,\r\n 'weekday' : weekday,\r\n 'day' : yesterdayString,\r\n 'weekOfMonth' : weekOfMonth,\r\n 'type' : 'card',\r\n 'createdBy' : 'system',\r\n 'createdAt' : todayTimeStamp\r\n }\r\n insertTotal['group'] = 'Total'\r\n insertTotal['total_org'] = sum_org\r\n insertTotal['count_data'] = sum_acc\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=insertTotal)\r\n insertTotalG2['group'] = 'G2'\r\n insertTotalG2['total_org'] = sum_org_g2\r\n insertTotalG2['count_data'] = sum_acc_g2\r\n insertTotalG2['ratio'] = insertTotalG2['total_org']/sum_org if sum_org != 0 else 0\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=insertTotalG2)\r\n insertTotalG3['group'] = 'G3'\r\n insertTotalG3['total_org'] = sum_org_g3\r\n insertTotalG3['count_data'] = sum_acc_g3\r\n insertTotalG3['ratio'] = insertTotalG3['total_org']/sum_org if sum_org != 0 else 0\r\n mongodb.insert(MONGO_COLLECTION=collection, insert_data=insertTotalG3)\r\n\r\n\r\n\r\n now_end = datetime.now()\r\n log.write(now_end.strftime(\"%d/%m/%Y, %H:%M:%S\") + ': End Log' + '\\n')\r\n print('DONE')\r\nexcept Exception as e:\r\n log.write(now.strftime(\"%d/%m/%Y, %H:%M:%S\") + ': ' + str(e) + '\\n')\r\n print(traceback.format_exc())\r\n","sub_path":"cronjob/python/Loan/saveCardLoanGroupReport.py","file_name":"saveCardLoanGroupReport.py","file_ext":"py","file_size_in_byte":12321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"451626600","text":"from src.main.matrixelements import Matrix\nimport numpy as np\n\n\nclass TDHFMatrix(Matrix):\n\n def __init__(self, molecular_integrals, orbital_energies, electrons):\n super().__init__()\n self.molecular_integrals = molecular_integrals\n self.orbital_energies = np.matrix(np.diag(orbital_energies))\n self.electrons = electrons\n self.matrix_size = orbital_energies.shape[0] // 2\n self.key = self.create_index_key()\n\n def create_index_key(self):\n orbitals = self.orbital_energies.shape[0]\n key = {}\n i = -1\n for a in range(0, self.electrons // 2):\n for b in range(self.electrons // 2, orbitals):\n i += 1\n key[i] = (a, b)\n return key\n\n def a_matrix(self):\n return self.create_matrix(self.calculate_a)\n\n def b_matrix(self):\n return self.create_matrix(self.calculate_b)\n\n def calculate_a(self, r, s):\n i, a = self.key[r]\n j, b = self.key[s]\n out1 = self.orbital_energies.item(i, j) - self.orbital_energies.item(a, b)\n out2 = self.molecular_integrals.item(i, a, j, b) - self.molecular_integrals.item(i, j, a, b)\n return out1 + out2\n\n def calculate_b(self, r, s):\n i, a = self.key[r]\n j, b = self.key[s]\n return self.molecular_integrals.item(i, a, j, b) - self.molecular_integrals.item(i, b, j, a)\n","sub_path":"src/main/matrixelements/tdhf_matrix.py","file_name":"tdhf_matrix.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"337275043","text":"\"\"\" URLs \"\"\"\nfrom django.conf.urls import url\nfrom transactions import views\n\napp_name = 'transactions'\n\nurlpatterns = [\n url(r'^my_operations/$', views.TransactList.as_view(), name='transact_list'),\n url(r'^new_transaction/$', views.NewTransaction.as_view(), name='new_transaction'),\n url(r'^bank_info/$', views.EditData.as_view(), name='bank_info'),\n url(r'^personal_info/$', views.EditPersonalData.as_view(), name='personal_info'),\n url(r'^transact_data/$', views.TransactionData.as_view(), name='transact_data'),\n url(r'^go_edit_data/$', views.go_edit_data, name='go_edit_data'),\n url(r'^image_api/$', views.ImageDetailsViewSet.as_view(\n {'get': 'list','post': 'create'}), name='image_api')\n]","sub_path":"transactions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"247863560","text":"def front_back(str):\n if len(str)<=1:\n return str\n \n else:\n return (str[len(str)-1] + str[1:len(str)-1] + str[0])\n \n \nprint(front_back(\"a\"))\nprint(front_back(\"riya\"))\n\n\n\n# Given a string, return a new string where the first and last chars have been exchanged.","sub_path":"warmup-1/front_back.py","file_name":"front_back.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"31708329","text":"#'datetime_received': 'datetime_received': EWSDateTime(2021, 7, 27, 17, 57, 35, tzinfo=EWSTimeZone(key='UTC'))\n#str1 = \"EWSDateTime(2021, 7, 27, 17, 57, 35, tzinfo=EWSTimeZone(key='UTC'))\"\n#2021-08-10 22:25:48+00:00\n\ndef parse_date(str):\n substr = str[0:-13]\n dt_list = substr.split('-')\n date = f\"{dt_list[2]}.{dt_list[1]}.{dt_list[0]}\"\n return date\n\n\n","sub_path":"parse_date.py","file_name":"parse_date.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"342713035","text":"#coding:utf-8\n__author__ = 'GunMade'\n\n\"\"\"\n使用 Python 生成类似于下图中的字母验证码图片\n\"\"\"\n\nimport random\nimport string\nfrom PIL import Image, ImageDraw, ImageFont, ImageFilter\n\n\ndef range_string(n):\n \"\"\"\n 随机生成n个字符\n :param n:\n :return:\n \"\"\"\n return ''.join(random.choice(string.ascii_letters) for x in range(n))\n\n\ndef create_verfied_img(input_str,\n size=(120, 30),\n img_type='JPG',\n mode='RGB',\n bg_color=(255, 255, 255),\n fg_color=(255, 0, 0),\n font_size=18,\n font_type='msyh.ttc',\n draw_lines=True,\n lines=(1, 2),\n draw_points=True,\n point_chance=3):\n width, height = size\n img = Image.new(mode, size, bg_color)\n draw = ImageDraw.Draw(img)\n if draw_lines:\n line_num = random.randint(*lines)\n for i in range(line_num):\n begin = (random.randint(0, width), random.randint(0, height))\n end = (random.randint(0, width), random.randint(0, height))\n draw.line([begin, end], fill=(0, 0, 0))\n\n if draw_points:\n chance = min(100, max(0, int(point_chance)))\n for w in range(width):\n for h in range(height):\n tmp = random.randint(0, 100)\n if tmp > 100 - chance:\n draw.point([w, h], fill=(0, 0, 0))\n\n font = ImageFont.truetype(font_type, font_size)\n font_width, font_height = font.getsize(input_str)\n draw.text(((width-font_width) / 3, (height-font_height) / 3), input_str, font=font, fill=fg_color)\n params = [1 - float(random.randint(1, 2)) / 100, 0, 0, 0, 1 - float(random.randint(1, 10)) / 100,\n float(random.randint(1, 2)) / 500,\n 0.001,\n float(random.randint(1, 2)) / 500]\n img = img.transform(size, Image.PERSPECTIVE, params)\n img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)\n return img\n\n\nif __name__ == '__main__':\n strs = range_string(4)\n code_img = create_verfied_img(strs)\n code_img.show()\n\n\n","sub_path":"activation_code/0010.py","file_name":"0010.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"38909397","text":"# Calvin Li\n# cli78@jhu.edu\n# 601.465 Natural Language Processing Assignment 3\n# Smoothing\n\n# CS465 at Johns Hopkins University.\n# Module to estimate n-gram probabilities.\n\n# Updated by Jason Baldridge for use in NLP\n# course at UT Austin. (9/9/2008)\n\n# Modified by Mozhi Zhang to add the new log linear model\n# with word embeddings. (2/17/2016)\n\n\nimport math\nimport random\nimport re\nimport sys\nimport numpy as np\n\nBOS = 'BOS' # special word type for context at Beginning Of Sequence\nEOS = 'EOS' # special word type for observed token at End Of Sequence\nOOV = 'OOV' # special word type for all Out-Of-Vocabulary words\nOOL = 'OOL' # special word type for all Out-Of-Lexicon words\nDEFAULT_TRAINING_DIR = \"/usr/local/data/cs465/hw-lm/All_Training/\"\nOOV_THRESHOLD = 3 # minimum number of occurrence for a word to be considered in-vocabulary\n\n\n# TODO for TA: Maybe we should use inheritance instead of condition on the\n# smoother (similar to the Java code).\nclass LanguageModel:\n def __init__(self):\n # The variables below all correspond to quantities discussed in the assignment.\n # For log-linear or Witten-Bell smoothing, you will need to define some \n # additional global variables.\n self.smoother = None # type of smoother we're using\n self.lambdap = None # lambda or C parameter used by some smoothers\n\n # The word vector for w can be found at self.vectors[w].\n # You can check if a word is contained in the lexicon using\n # if w in self.vectors:\n self.vectors = None # loaded using read_vectors()\n\n self.vocab = None # set of words included in the vocabulary\n self.vocab_size = None # V: the total vocab size including OOV.\n\n self.tokens = None # the c(...) function\n self.types_after = None # the T(...) function\n\n self.progress = 0 # for the progress bar\n\n self.bigrams = None\n self.trigrams = None\n \n self.Z_xy = None\n self.dict = None\n\n # the two weight matrices X and Y used in log linear model\n # They are initialized in train() function and represented as two\n # dimensional lists.\n self.X, self.Y = None, None \n\n # self.tokens[(x, y, z)] = # of times that xyz was observed during training.\n # self.tokens[(y, z)] = # of times that yz was observed during training.\n # self.tokens[z] = # of times that z was observed during training.\n # self.tokens[\"\"] = # of tokens observed during training.\n #\n # self.types_after[(x, y)] = # of distinct word types that were\n # observed to follow xy during training.\n # self.types_after[y] = # of distinct word types that were\n # observed to follow y during training.\n # self.types_after[\"\"] = # of distinct word types observed during training.\n\n def prob(self, x, y, z):\n \"\"\"Computes a smoothed estimate of the trigram probability p(z | x,y)\n according to the language model.\n \"\"\"\n\n if self.smoother == \"UNIFORM\":\n return float(1) / self.vocab_size\n elif self.smoother == \"ADDL\":\n if x not in self.vocab:\n x = OOV\n if y not in self.vocab:\n y = OOV\n if z not in self.vocab:\n z = OOV\n return ((self.tokens.get((x, y, z), 0) + self.lambdap) /\n (self.tokens.get((x, y), 0) + self.lambdap * self.vocab_size))\n\n # Notice that summing the numerator over all values of typeZ\n # will give the denominator. Therefore, summing up the quotient\n # over all values of typeZ will give 1, so sum_z p(z | ...) = 1\n # as is required for any probability function.\n\n elif self.smoother == \"BACKOFF_ADDL\":\n if x not in self.vocab:\n x = OOV\n if y not in self.vocab:\n y = OOV\n if z not in self.vocab:\n z = OOV\n\n #p(z)\n p_z = (self.tokens.get(z, 0) + self.lambdap) / (self.tokens[\"\"] + self.lambdap * self.vocab_size)\n #p(z|y)\n p_zy = (self.tokens.get((y,z), 0) + (self.lambdap * self.vocab_size * p_z)) / (self.tokens.get(y, 0) + self.lambdap * self.vocab_size)\n #p(z|xy)\n p_zxy = ((self.tokens.get((x, y, z), 0) + (self.lambdap * self.vocab_size * p_zy)) / (self.tokens.get((x, y), 0) + self.lambdap * self.vocab_size))\n return p_zxy\n elif self.smoother == \"BACKOFF_WB\":\n sys.exit(\"BACKOFF_WB is not implemented yet (that's your job!)\")\n elif self.smoother == \"LOGLINEAR\":\n x_v = np.matrix(self.word_vector(x))\n y_v = np.matrix(self.word_vector(y))\n z_v = np.matrix(self.word_vector(z))\n\n if self.Z_xy:\n Z_xy = self.Z_xy\n else:\n m = (x_v * self.X * self.E) + (y_v * self.Y * self.E)\n self.norm = np.max(m)\n Z_xy = math.log(np.sum(np.exp(m - self.norm)))\n\n U_xyz = ((x_v * self.X * z_v.transpose()) + (y_v * self.Y * z_v.transpose()))[0,0] - self.norm\n\n return pow(math.e, U_xyz - Z_xy)\n elif self.smoother == 'IMPROVED':\n x_v = np.matrix(self.word_vector(x))\n y_v = np.matrix(self.word_vector(y))\n z_v = np.matrix(self.word_vector(z))\n\n if self.Z_xy:\n Z_xy = self.Z_xy\n else:\n m = np.concatenate(((x_v * self.X * self.E) + (y_v * self.Y * self.E) + \\\n self.uni_weights.transpose() * self.uni_hot, \\\n self.bi_weights.transpose() * self.bi_hot, \\\n self.tri_weights.transpose() * self.tri_hot), axis = 1)\n\n self.norm = np.max(m)\n Z_xy = math.log(np.sum(np.exp(m - self.norm)))\n\n U_xyz = ((x_v * self.X * z_v.transpose()) + (y_v * self.Y * z_v.transpose()) + \\\n self.uni_weights.transpose() * self.uni_hot[:, self.get_id(z)] +\\\n self.bi_weights.transpose() * self.bi_hot[:, self.get_id(z,y)] +\\\n self.tri_weights.transpose() * self.tri_hot[:, self.get_id(z,y,x)]\\\n )[0,0] - self.norm\n\n return pow(math.e, U_xyz - Z_xy)\n else:\n sys.exit(\"%s has some weird value\" % self.smoother)\n\n def word_vector(self, word):\n if word not in self.vectors:\n return self.vectors['OOL']\n else:\n return self.vectors[word]\n\n def filelogprob(self, filename):\n \"\"\"Compute the log probability of the sequence of tokens in file.\n NOTE: we use natural log for our internal computation. You will want to\n divide this number by log(2) when reporting log probabilities.\n \"\"\"\n logprob = 0.0\n x, y = BOS, BOS\n corpus = self.open_corpus(filename)\n for line in corpus:\n for z in line.split():\n prob = self.prob(x, y, z)\n logprob += math.log(prob)\n x = y\n y = z\n logprob += math.log(self.prob(x, y, EOS))\n corpus.close()\n return logprob\n\n def read_vectors(self, filename):\n \"\"\"Read word vectors from an external file. The vectors are saved as\n arrays in a dictionary self.vectors.\n \"\"\"\n with open(filename) as infile:\n header = infile.readline()\n self.dim = int(header.split()[-1])\n self.vectors = {}\n for line in infile:\n arr = line.split()\n word = arr.pop(0)\n self.vectors[word] = [float(x) for x in arr]\n\n def train (self, filename):\n \"\"\"Read the training corpus and collect any information that will be needed\n by the prob function later on. Tokens are whitespace-delimited.\n\n Note: In a real system, you wouldn't do this work every time you ran the\n testing program. You'd do it only once and save the trained model to disk\n in some format.\n \"\"\"\n sys.stderr.write(\"Training from corpus %s\\n\" % filename)\n\n # Clear out any previous training\n self.tokens = { }\n self.types_after = { }\n self.bigrams = []\n self.trigrams = [];\n\n # While training, we'll keep track of all the trigram and bigram types\n # we observe. You'll need these lists only for Witten-Bell backoff.\n # The real work:\n # accumulate the type and token counts into the global hash tables.\n\n # If vocab size has not been set, build the vocabulary from training corpus\n if self.vocab_size is None:\n self.set_vocab_size(filename)\n\n # We save the corpus in memory to a list tokens_list. Notice that we\n # appended two BOS at the front of the list and a EOS at the end. You\n # will need to add more BOS tokens if you want to use a longer context than\n # trigram.\n x, y = BOS, BOS # Previous two words. Initialized as \"beginning of sequence\"\n # count the BOS context\n self.tokens[(x, y)] = 1\n self.tokens[y] = 1\n\n tokens_list = [x, y] # the corpus saved as a list\n corpus = self.open_corpus(filename)\n for line in corpus:\n for z in line.split():\n # substitute out-of-vocabulary words with OOV symbol\n if z not in self.vocab:\n z = OOV\n # substitute out-of-lexicon words with OOL symbol (only for log-linear models)\n if self.smoother == 'LOGLINEAR' and z not in self.vectors:\n z = OOL\n self.count(x, y, z)\n self.show_progress()\n x=y; y=z\n tokens_list.append(z)\n tokens_list.append(EOS) # append a end-of-sequence symbol \n sys.stderr.write('\\n') # done printing progress dots \"....\"\n self.count(x, y, EOS) # count EOS \"end of sequence\" token after the final context\n corpus.close()\n if self.smoother == 'LOGLINEAR': \n # Train the log-linear model using SGD.\n\n # Initialize parameters\n self.X = [[0.0 for _ in range(self.dim)] for _ in range(self.dim)]\n self.Y = [[0.0 for _ in range(self.dim)] for _ in range(self.dim)]\n self.E = np.matrix([self.word_vector(word) for word in self.vocab]).transpose()\n\n # Optimization parameters\n gamma0 = 0.1 # initial learning rate, used to compute actual learning rate\n epochs = 10 # number of passes\n epoch = 0 # iteration number\n self.N = len(tokens_list) - 2 # number of training instances\n\n # ******** COMMENT *********\n # In log-linear model, you will have to do some additional computation at\n # this point. You can enumerate over all training trigrams as following.\n #\n # for i in range(2, len(tokens_list)):\n # x, y, z = tokens_list[i - 2], tokens_list[i - 1], tokens_list[i]\n #\n # Note1: self.lambdap is the regularizer constant C\n # Note2: You can use self.show_progress() to log progress.\n #\n # **************************\n # include comment so autograder skips this line of output\n sys.stderr.write(\"#Start optimizing.\\n\")\n\n #####################\n # TODO: Implement your SGD here\n #####################\n def compute_grad(x, y, z, x_v, y_v, z_v, X, Y):\n # change lists to np array for computation\n X = np.asarray(X)\n Y = np.asarray(Y)\n gradX = x_v.transpose() * z_v - ((2*C / self.N) * X)\n gradY = y_v.transpose() * z_v - ((2*C / self.N) * Y)\n\n m = (x_v * self.X * self.E) + (y_v * self.Y * self.E)\n self.norm = np.max(m)\n self.Z_xy = math.log(np.sum(np.exp(m - self.norm)))\n\n for z_prime in self.vocab:\n z_prime_v = np.matrix(self.word_vector(z_prime))\n prob = self.prob(x, y, z_prime)\n gradX -= prob * (x_v.transpose() * z_prime_v)\n gradY -= prob * (y_v.transpose() * z_prime_v)\n\n #reset self.Z_xy\n self.Z_xy = None\n return (gradX, gradY)\n\n if self.lambdap:\n C = self.lambdap\n else:\n C = 0.1\n\n #number of updates so far\n t = 0\n\n # do E passes over training data\n for i in range(epochs):\n epoch += 1\n reg = (C) * (np.sum(np.power(self.X, 2)) + np.sum(np.power(self.Y, 2)))\n\n log_likelihood = 0\n # loop over summands of (25)\n for i in range(2, len(tokens_list)):\n x, y, z = tokens_list[i - 2], tokens_list[i - 1], tokens_list[i]\n log_likelihood += math.log(self.prob(x, y, z))\n F = (log_likelihood - reg) / self.N\n print(\"epoch {}: F={}\".format(epoch, F))\n\n # move in slight direction that increases gradient\n for i in range(2, len(tokens_list)):\n x, y, z = tokens_list[i - 2], tokens_list[i - 1], tokens_list[i]\n x_v = np.matrix(self.word_vector(x))\n y_v = np.matrix(self.word_vector(y))\n z_v = np.matrix(self.word_vector(z))\n\n gamma = gamma0 / (1 + gamma0 * (C/self.N) * t)\n gradX, gradY = compute_grad(x, y, z, x_v, y_v, z_v, self.X, self.Y)\n self.X += gamma * gradX \n self.Y += gamma * gradY\n t += 1\n\n sys.stderr.write(\"Finished training on %d tokens\\n\" % self.tokens[\"\"])\n\n #improved log linear\n # use one hot vectors for n-grams (1,2,3) to help our model\n # idea from https://cs224d.stanford.edu/lecture_notes/notes1.pdf\n if self.smoother == 'IMPROVED':\n C = 8\n # Train the log-linear model using SGD.\n self.bigrams_thresh = [bi for bi in self.bigrams if self.tokens[bi] >= OOV_THRESHOLD]\n self.trigrams_thresh = [tri for tri in self.trigrams if self.tokens[tri] >= OOV_THRESHOLD]\n\n # Initialize parameters\n self.X = np.matrix(np.zeros((self.dim, self.dim)))\n self.Y = np.matrix(np.zeros((self.dim, self.dim)))\n self.E = np.matrix([self.word_vector(word) for word in self.vocab]).transpose()\n epoch = 0 # iteration number\n\n # create one hot matrices\n # unigram\n self.uni_hot = np.matrix(np.zeros((len(self.vocab), len(self.vocab))))\n np.fill_diagonal(self.uni_hot, 1)\n\n # bigram\n self.bi_hot = np.matrix(np.zeros((len(self.bigrams_thresh), len(self.bigrams_thresh))))\n np.fill_diagonal(self.bi_hot, 1)\n self.bi_hot = np.concatenate((self.bi_hot, np.matrix(np.zeros((len(self.bigrams_thresh), 1)))), axis=1)\n\n # trigram\n self.tri_hot = np.matrix(np.zeros((len(self.trigrams_thresh), len(self.trigrams_thresh))))\n np.fill_diagonal(self.tri_hot, 1)\n self.tri_hot = np.concatenate((self.tri_hot, np.matrix(np.zeros((len(self.trigrams_thresh), 1)))), axis=1)\n\n # n-gram model weights matrices\n self.uni_weights = np.matrix(np.zeros((len(self.vocab), 1)))\n self.bi_weights = np.matrix(np.zeros((len(self.bigrams_thresh), 1)))\n self.tri_weights = np.matrix(np.zeros((len(self.trigrams_thresh), 1)))\n\n gamma0 = 0.1 # initial learning rate, used to compute actual learning rate\n epochs = 10 # number of passes\n self.N = len(tokens_list) - 2 # number of training instances\n\n def compute_grad_improved(x, y, z, x_v, y_v, z_v, X, Y):\n gradX = x_v.transpose() * z_v - ((2*C / self.N) * X)\n gradY = y_v.transpose() * z_v - ((2*C / self.N) * Y)\n grad_uni = self.uni_hot[:,self.get_id(z)] - ((2*C / self.N) * self.uni_weights)\n grad_bi = self.bi_hot[:,self.get_id(z, y)] - ((2*C / self.N) * self.bi_weights)\n grad_tri = self.tri_hot[:,self.get_id(z, y, z)] - ((2*C / self.N) * self.tri_weights)\n\n m = np.concatenate(((x_v * self.X * self.E) + (y_v * self.Y * self.E) + \\\n self.uni_weights.transpose() * self.uni_hot, \\\n self.bi_weights.transpose() * self.bi_hot, \\\n self.tri_weights.transpose() * self.tri_hot), axis = 1)\n\n self.norm = np.max(m)\n self.Z_xy = math.log(np.sum(np.exp(m - self.norm)))\n\n for z_prime in self.vocab:\n z_prime_v = np.matrix(self.word_vector(z_prime))\n prob = self.prob(x, y, z_prime)\n gradX -= prob * (x_v.transpose() * z_prime_v)\n gradY -= prob * (y_v.transpose() * z_prime_v)\n grad_uni -= prob * self.uni_hot[:, self.get_id(z_prime)]\n grad_bi -= prob * self.bi_hot[:, self.get_id(z_prime, y)]\n grad_tri -= prob * self.tri_hot[:, self.get_id(z_prime, y, z)]\n\n #reset self.Z_xy\n self.Z_xy = None\n return (gradX, gradY, grad_uni, grad_bi, grad_tri)\n\n sys.stderr.write(\"#Start optimizing.\\n\")\n\n t = 0\n for i in range(epochs):\n epoch += 1\n reg = (C) * (np.sum(np.power(self.X, 2)) + np.sum(np.power(self.Y, 2)))\n\n log_likelihood = 0\n for i in range(2, len(tokens_list)):\n x, y, z = tokens_list[i-2], tokens_list[i-1], tokens_list[i]\n log_likelihood += math.log(self.prob(x, y, z))\n F = (log_likelihood - reg) / self.N\n print(\"epoch {}: F={}\".format(epoch, F))\n\n for i in range(2, len(tokens_list)):\n x, y, z = tokens_list[i-2], tokens_list[i-1], tokens_list[i]\n x_v = np.matrix(self.word_vector(x))\n y_v = np.matrix(self.word_vector(y))\n z_v = np.matrix(self.word_vector(z))\n\n gamma = gamma0 / (1 + gamma0 * (C/self.N) * t)\n gradX, gradY, grad_uni, grad_bi, grad_tri =\\\n compute_grad_improved(x, y, z, x_v, y_v, z_v, self.X, self.Y)\n\n #update parameters\n self.X += gamma * gradX \n self.Y += gamma * gradY\n self.uni_weights += gamma * grad_uni\n self.bi_weights += gamma * grad_bi\n self.tri_weights += gamma * grad_tri\n t += 1\n\n sys.stderr.write(\"Finished training on %d tokens\\n\" % self.tokens[\"\"])\n\n def get_id(self, z, y = None, x = None):\n #build dictionary and set appropriate labels for unknown words\n if z not in self.vocab:\n z = OOV\n if y and y not in self.vocab:\n y = OOV\n if x and x not in self.vocab:\n x = OOV\n if not self.dict:\n self.dict = {}\n for i, v in enumerate(self.vocab):\n self.dict[v] = i\n for i, bi in enumerate(self.bigrams_thresh):\n self.dict[bi] = i \n for i, tri in enumerate(self.trigrams_thresh):\n self.dict[tri] = i\n if not y and not x:\n return self.dict[z]\n elif not x:\n if (y, z) in self.dict:\n return self.dict[(y, z)]\n else:\n return -1\n else:\n if (x, y, z) in self.dict:\n return self.dict[(x, y, z)]\n else:\n return -1\n\n def count(self, x, y, z):\n \"\"\"Count the n-grams. In the perl version, this was an inner function.\n For now, I am just using a class variable to store the found tri-\n and bi- grams.\n \"\"\"\n self.tokens[(x, y, z)] = self.tokens.get((x, y, z), 0) + 1\n if self.tokens[(x, y, z)] == 1: # first time we've seen trigram xyz\n self.trigrams.append((x, y, z))\n self.types_after[(x, y)] = self.types_after.get((x, y), 0) + 1\n\n self.tokens[(y, z)] = self.tokens.get((y, z), 0) + 1\n if self.tokens[(y, z)] == 1: # first time we've seen bigram yz\n self.bigrams.append((y, z))\n self.types_after[y] = self.types_after.get(y, 0) + 1\n\n self.tokens[z] = self.tokens.get(z, 0) + 1\n if self.tokens[z] == 1: # first time we've seen unigram z\n self.types_after[''] = self.types_after.get('', 0) + 1\n # self.vocab_size += 1\n\n self.tokens[''] = self.tokens.get('', 0) + 1 # the zero-gram\n\n\n def set_vocab_size(self, *files):\n \"\"\"When you do text categorization, call this function on the two\n corpora in order to set the global vocab_size to the size\n of the single common vocabulary.\n\n \"\"\"\n count = {} # count of each word\n\n for filename in files:\n corpus = self.open_corpus(filename)\n for line in corpus:\n for z in line.split():\n count[z] = count.get(z, 0) + 1\n self.show_progress();\n corpus.close()\n self.vocab = set(w for w in count if count[w] >= OOV_THRESHOLD)\n\n self.vocab.add(OOV) # add OOV to vocab\n self.vocab.add(EOS) # add EOS to vocab (but not BOS, which is never a possible outcome but only a context)\n sys.stderr.write('\\n') # done printing progress dots \"....\"\n\n if self.vocab_size is not None:\n sys.stderr.write(\"Warning: vocab_size already set; set_vocab_size changing it\\n\")\n self.vocab_size = len(self.vocab)\n sys.stderr.write(\"Vocabulary size is %d types including OOV and EOS\\n\"\n % self.vocab_size)\n\n def set_smoother(self, arg):\n \"\"\"Sets smoother type and lambda from a string passed in by the user on the\n command line.\n \"\"\"\n r = re.compile('^(.*?)-?([0-9.]*)$')\n m = r.match(arg)\n \n if not m.lastindex:\n sys.exit(\"Smoother regular expression failed for %s\" % arg)\n else:\n smoother_name = m.group(1)\n if m.lastindex >= 2 and len(m.group(2)):\n lambda_arg = m.group(2)\n self.lambdap = float(lambda_arg)\n else:\n self.lambdap = None\n\n if smoother_name.lower() == 'uniform':\n self.smoother = \"UNIFORM\"\n elif smoother_name.lower() == 'add':\n self.smoother = \"ADDL\"\n elif smoother_name.lower() == 'backoff_add':\n self.smoother = \"BACKOFF_ADDL\"\n elif smoother_name.lower() == 'backoff_wb':\n self.smoother = \"BACKOFF_WB\"\n elif smoother_name.lower() == 'loglinear':\n self.smoother = \"LOGLINEAR\"\n elif smoother_name.lower() == 'loglin':\n self.smoother = \"LOGLINEAR\"\n elif smoother_name.lower() == 'improved':\n self.smoother = \"IMPROVED\"\n else:\n sys.exit(\"Don't recognize smoother name '%s'\" % smoother_name)\n \n if self.lambdap is None and self.smoother.find('ADDL') != -1:\n sys.exit('You must include a non-negative lambda value in smoother name \"%s\"' % arg)\n\n def open_corpus(self, filename):\n \"\"\"Associates handle CORPUS with the training corpus named by filename.\"\"\"\n try:\n corpus = open(filename, \"r\")\n except IOError as err:\n try:\n corpus = open(DEFAULT_TRAINING_DIR + filename, \"r\")\n except IOError as err:\n sys.exit(\"Couldn't open corpus at %s or %s\" % (filename,\n DEFAULT_TRAINING_DIR + filename))\n return corpus\n\n def num_tokens(self, filename):\n corpus = self.open_corpus(filename)\n num_tokens = sum([len(l.split()) for l in corpus]) + 1\n\n return num_tokens\n\n def show_progress(self, freq=5000):\n \"\"\"Print a dot to stderr every 5000 calls (frequency can be changed).\"\"\"\n self.progress += 1\n if self.progress % freq == 1:\n sys.stderr.write('.')\n\n @classmethod\n def load(cls, fname):\n try:\n import cPickle as pickle\n except:\n import pickle\n fh = open(fname, mode='rb')\n loaded = pickle.load(fh)\n fh.close()\n return loaded\n\n def save(self, fname):\n try:\n import cPickle as pickle\n except:\n import pickle\n with open(fname, mode='wb') as fh:\n pickle.dump(self, fh, protocol=pickle.HIGHEST_PROTOCOL)","sub_path":"More Language Models/Probs.py","file_name":"Probs.py","file_ext":"py","file_size_in_byte":22883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"356653436","text":"import Queue\n\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if root is None:\n return []\n queue = Queue.Queue()\n queue.put(root)\n queue.put('#')\n result = []\n current = []\n while not queue.empty():\n node = queue.get()\n if node is '#':\n result.append(current)\n current = []\n if not queue.empty():\n queue.put('#')\n continue\n\n current.append(node.val)\n if node.left is not None:\n queue.put(node.left)\n if node.right is not None:\n queue.put(node.right)\n return result\n\n\nif __name__ == \"__main__\":\n tree = TreeNode(4)\n tree.left = TreeNode(2)\n tree.right = TreeNode(5)\n tree.left.left = TreeNode(1)\n tree.left.right = TreeNode(1)\n tree.left.right.left = TreeNode(1)\n print(Solution().levelOrder(tree))\n tree = TreeNode(4)\n tree.left = TreeNode(2)\n tree.left.left = TreeNode(1)\n tree.left.right = TreeNode(1)\n print(Solution().levelOrder(tree))\n print(Solution().levelOrder(None))","sub_path":"python/102_binary_tree_level_order_traversal.py","file_name":"102_binary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"168740790","text":"from __future__ import unicode_literals\nfrom decimal import Decimal\nfrom uuid import uuid4\n\nfrom django.forms.models import model_to_dict\nfrom django.shortcuts import get_list_or_404\nimport emailit.api\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.core.validators import MinValueValidator, MaxValueValidator\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import models\nfrom django.db.models import Sum\nfrom django.utils.encoding import smart_text\nfrom django.utils.timezone import now\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.translation import pgettext_lazy\n\nfrom django_prices.models import PriceField\nfrom payments import PurchasedItem\nfrom payments.models import BasePayment\nfrom prices import Price, LinearTax\nfrom satchless.item import ItemSet, ItemLine\nfrom taxrates.models import TaxRate\n\nfrom ..core.utils import build_absolute_uri\nfrom ..product.models import Product, ProductVariant\nfrom saleor.cart import CartLine\nfrom ..userprofile.models import Address, User\nfrom ..delivery import get_delivery\nfrom ..core.models import BaseModelMixin, HistoryModelMixin\n\n\n@python_2_unicode_compatible\nclass Order(models.Model, ItemSet):\n STATUS_CHOICES = (\n ('new', pgettext_lazy('Order status field value', 'Processing')),\n ('cancelled', pgettext_lazy('Order status field value',\n 'Cancelled')),\n ('payment-pending', pgettext_lazy('Order status field value',\n 'Waiting for payment')),\n ('fully-paid', pgettext_lazy('Order status field value',\n 'Fully paid')),\n ('shipped', pgettext_lazy('Order status field value',\n 'Shipped')),\n ('delivered', pgettext_lazy('Order status field value',\n 'Delivered')))\n status = models.CharField(\n pgettext_lazy('Order field', 'order status'),\n max_length=32, choices=STATUS_CHOICES, default='new')\n created = models.DateTimeField(\n pgettext_lazy('Order field', 'created'),\n default=now)\n last_status_change = models.DateTimeField(\n pgettext_lazy('Order field', 'last status change'),\n default=now, editable=False)\n user = models.ForeignKey(\n User, blank=True, null=True, related_name='orders',\n verbose_name=pgettext_lazy('Order field', 'customer'))\n tracking_client_id = models.CharField(max_length=36, blank=True,\n editable=False)\n billing_address = models.ForeignKey(Address, related_name='+')\n shipping_address = models.ForeignKey(Address, related_name='+', null=True)\n shipping_method = models.CharField(\n pgettext_lazy('Order field', 'Delivery method'),\n max_length=255, blank=True)\n anonymous_user_email = models.EmailField(blank=True, default='',\n editable=False)\n token = models.CharField(\n pgettext_lazy('Order field', 'token'), max_length=36, unique=True)\n location = models.ForeignKey('inventory.Location', null=True, blank=True, related_name=\"orders\")\n sold_by = models.ForeignKey(User, blank=True, null=True, related_name='sales',)\n discount = PriceField(\n pgettext_lazy('Order field', 'discount'),\n default=Decimal('0.00'),\n currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2)\n\n class Meta:\n app_label = 'order'\n ordering = ('-last_status_change',)\n\n def save(self, *args, **kwargs):\n if not self.token:\n self.token = str(uuid4())\n return super(Order, self).save(*args, **kwargs)\n\n def change_status(self, status, user=None):\n if status != self.status:\n self.status = status\n self.save()\n self.history.create(status=status)\n\n def get_items(self):\n return OrderedItem.objects.filter(delivery_group__order=self)\n\n def get_refundable_items(self):\n output = []\n for item in self.get_items():\n return_quantity = item.get_returned_quantity()\n if item.quantity > return_quantity:\n item.quantity = item.quantity - return_quantity\n output.append(item)\n return output\n\n def get_returns(self):\n from returns.models import Return\n return Return.objects.filter(lines__item__delivery_group__order=self).distinct()\n\n def is_fully_paid(self):\n total_paid = sum([payment.total for payment in\n self.payments.filter(status__in=('confirmed', 'refunded'))], Decimal())\n total = self.get_total()\n return total_paid >= total.gross\n\n def get_user_email(self):\n if self.user:\n return self.user.email\n return self.anonymous_user_email\n\n def __iter__(self):\n return iter(self.groups.all())\n\n def __repr__(self):\n return '' % (self.id,)\n\n def __str__(self):\n return '#%d' % (self.id, )\n\n def get_total(self):\n try:\n return super(Order, self).get_total() - self.discount\n except AttributeError:\n return Price(0, currency=settings.DEFAULT_CURRENCY)\n\n @property\n def billing_full_name(self):\n return '%s %s' % (self.billing_first_name, self.billing_last_name)\n\n def get_absolute_url(self):\n return reverse('order:details', kwargs={'token': self.token})\n\n def get_delivery_total(self):\n return sum([group.shipping_price for group in self.groups.all()],\n Price(0, currency=settings.DEFAULT_CURRENCY))\n\n def send_confirmation_email(self):\n email = self.get_user_email()\n payment_url = reverse('order:details', kwargs={'token': self.token})\n context = {'object': self}\n emailit.api.send_mail(email, context, 'order/emails/confirm_email')\n\n def get_last_payment_status(self):\n last_payment = self.payments.last()\n if last_payment:\n return last_payment.status\n\n def get_last_payment_status_display(self):\n last_payment = self.payments.last()\n if last_payment:\n return last_payment.get_status_display()\n\n def is_pre_authorized(self):\n return self.payments.filter(status='preauth').exists()\n\n def create_history_entry(self, comment='', status=None):\n if not status:\n status = self.status\n self.history.create(status=status, comment=comment)\n\n def is_shipping_required(self):\n return any(group.is_shipping_required() for group in self.groups.all())\n\n def is_delivery_scheduled(self):\n return not self.groups.filter(delivery__isnull=True).exists()\n\n def is_delivered(self):\n return all(group.status == 'shipped' for group in self.groups.all())\n\n def get_delivery_status(self):\n if self.is_delivery_scheduled():\n return 'complete'\n elif self.is_fully_paid():\n return 'active'\n else:\n return 'disabled'\n\n def get_progress(self):\n output = [\n {\n 'title': 'Order Received',\n 'description': 'Order was made in %s.' % self.location.code,\n 'status': 'complete',\n 'url': reverse('dashboard:order-detail', args=[self.pk])\n },\n {\n 'title': 'Payment',\n 'description': 'Full payment was made.' if self.is_fully_paid() else 'Awaiting Payment',\n 'status': 'complete' if self.is_fully_paid() else 'active',\n 'url': reverse('dashboard:payment-details', args=[self.payments.last().pk]) \\\n if self.is_fully_paid() else reverse('order:payment', args=[self.token]),\n },\n {\n 'title': 'Schedule Delivery',\n 'description': 'Delivery Scheduled.' if self.is_delivery_scheduled() else 'Please schedule a delivery',\n 'status': self.get_delivery_status(),\n 'url': reverse('dashboard:schedule-delivery', args=[self.pk, self.groups.first().pk])\n },\n {\n 'title': 'Delivered',\n 'description': '',\n 'status': 'complete' if self.is_delivered() else 'disabled',\n },\n ]\n return output\n\n\nclass OrderedItemManager(models.Manager):\n\n def move_to_group(self, item, target_group, quantity):\n source_group = item.delivery_group\n order = target_group.order\n try:\n target_item = target_group.items.get(\n product=item.product, product_name=item.product_name,\n product_sku=item.product_sku)\n except ObjectDoesNotExist:\n target_group.items.create(\n delivery_group=target_group, product=item.product,\n product_name=item.product_name, product_sku=item.product_sku,\n quantity=quantity, unit_price_net=item.unit_price_net,\n unit_price_gross=item.unit_price_gross)\n else:\n target_item.quantity += quantity\n target_item.save()\n item.quantity -= quantity\n if item.quantity:\n item.save()\n else:\n item.delete()\n if source_group.get_total_quantity():\n source_group.update_delivery_cost()\n else:\n source_group.delete()\n target_group.update_delivery_cost()\n if not order.get_items():\n order.change_status('cancelled')\n\n def create_po(self):\n pass\n\n\n@python_2_unicode_compatible\nclass OrderedItem(models.Model, ItemLine):\n delivery_group = models.ForeignKey(\n 'delivery.DeliveryGroup', related_name='items', editable=False)\n variant = models.ForeignKey(\n ProductVariant, blank=True, null=True, related_name='items',\n on_delete=models.SET_NULL,\n verbose_name=pgettext_lazy('OrderedItem field', 'variant'))\n product_name = models.CharField(\n pgettext_lazy('OrderedItem field', 'product name'), max_length=128)\n product_sku = models.CharField(pgettext_lazy('OrderedItem field', 'sku'),\n max_length=32)\n quantity = models.IntegerField(\n pgettext_lazy('OrderedItem field', 'quantity'),\n validators=[MinValueValidator(0), MaxValueValidator(999)])\n unit_price_net = models.DecimalField(\n pgettext_lazy('OrderedItem field', 'unit price (net)'),\n max_digits=12, decimal_places=2)\n unit_price_gross = models.DecimalField(\n pgettext_lazy('OrderedItem field', 'unit price (gross)'),\n max_digits=12, decimal_places=2)\n\n objects = OrderedItemManager()\n\n class Meta:\n app_label = 'order'\n\n def get_price_per_item(self, **kwargs):\n return Price(net=self.unit_price_net, gross=self.unit_price_gross,\n currency=settings.DEFAULT_CURRENCY)\n\n def __str__(self):\n return self.product_name\n\n def get_quantity(self):\n return self.quantity\n\n def change_quantity(self, new_quantity):\n order = self.delivery_group.order\n self.quantity = new_quantity\n self.save()\n self.delivery_group.update_delivery_cost()\n if not self.delivery_group.get_total_quantity():\n self.delivery_group.delete()\n if not order.get_items():\n order.change_status('cancelled')\n\n def get_returned_quantity(self):\n return self.returns.aggregate(qty=Sum('quantity'))['qty'] or 0\n\n\nclass PaymentManager(models.Manager):\n\n def last(self):\n # using .all() here reuses data fetched by prefetch_related\n objects = list(self.all()[:1])\n if objects:\n return objects[0]\n\n\nclass Payment(BasePayment):\n order = models.ForeignKey(Order, related_name='payments')\n\n objects = PaymentManager()\n\n def get_failure_url(self):\n return reverse('order:details', kwargs={'token': self.order.token})\n\n def get_success_url(self):\n return reverse('order:details', kwargs={'token': self.order.token})\n\n def get_purchased_items(self):\n items = [PurchasedItem(\n name=item.product_name, sku=item.product_sku,\n quantity=item.quantity,\n price=item.unit_price_gross.quantize(Decimal('0.01')),\n currency=settings.DEFAULT_CURRENCY)\n for item in self.order.get_items()]\n return items\n\n def get_total_price(self):\n net = self.total - self.tax\n return Price(net, gross=self.total, currency=self.currency)\n\n def get_captured_price(self):\n return Price(self.captured_amount, currency=self.currency)\n\n class Meta:\n ordering = ('-pk',)\n app_label = 'order'\n\n\n@python_2_unicode_compatible\nclass OrderHistoryEntry(HistoryModelMixin):\n ORDER_HISTORY_STATUS = Order.STATUS_CHOICES + (\n ('refund', 'Refund was processed'),\n ('scheduled', 'A delivery was scheduled'),\n ('rescheduled', 'A delivery was rescheduled'),\n ('unscheduled', 'Delivery was cancelled'),\n )\n order = models.ForeignKey(Order, related_name='history')\n status = models.CharField(\n pgettext_lazy('Order field', 'order status'),\n max_length=32, choices=ORDER_HISTORY_STATUS)\n comment = models.CharField(max_length=100, default='', blank=True)\n\n class Meta(HistoryModelMixin.Meta):\n app_label = 'order'\n\n def __str__(self):\n return 'OrderHistoryEntry for Order #%d' % self.order.pk\n\n\n@python_2_unicode_compatible\nclass OrderNote(models.Model):\n user = models.ForeignKey(User)\n date = models.DateTimeField(auto_now_add=True)\n order = models.ForeignKey(Order, related_name='notes')\n content = models.CharField(max_length=250)\n\n class Meta:\n app_label = 'order'\n\n def __str__(self):\n return 'OrderNote for Order #%d' % self.order.pk\n","sub_path":"saleor/order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"528207170","text":"from flask import Flask\nimport pandas as pd\nimport sqlite3\nfrom flask import jsonify\nfrom flask import request, render_template\nimport io\nfrom flask import Response\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\n\n# TODO: give editors per project\n## Config\napp = Flask(__name__)\npathToDB = '/home/dsaez/real-time-wiki-covid-tracker/AllWikidataItems.sqlite'\n\n@app.route('/')\ndef index():\n\tconn = sqlite3.connect(pathToDB)\n\ttotalEdits = totalEditsNoHumans() #removing duplicates, should be done in sqlite query, but I'm failing on this, so using this work around. TODO:\n\t \n\teditors = getEditors(humans=False)\n\tpages = pd.read_sql(''' SELECT COUNT(*) as cnt FROM pagesPerProjectTable ''', con=conn).iloc[0].cnt \n\tprojects = numProjects()\n\tupdated = pd.to_datetime(pd.read_sql(''' SELECT max(revisions_update) as cnt FROM updated ''', con=conn).iloc[0].cnt)\n\n\tdata = {'pages':pages,'totalEdits':totalEdits,'editors':editors,'projects':projects,'updated':updated}\n\treturn \"\"\"\n\t\t

General statistics about COVID-19 related pages across Wikipedia projects

\n\t\tThere are {totalEdits} edits done by {editors} editors in {projects} Wikipedia projects.
\n\t\t \n\n\t\tThis data was updated at {updated} UTC
\n\t\tTo know more about the methodology to build the list of pages, \n\t\tplease go this notebook.
All these results are based on public data. Find the code here. \n\t\t\n\t\t\"\"\".format(**data)\n\n\n\n\n@app.route('/perProject')\ndef perProject():\n\tdump = request.args.get('data',False)\n\tconn = sqlite3.connect(pathToDB)\n\trevisions = pd.read_sql(''' SELECT project,COUNT(*) as cnt FROM revisions GROUP BY project''', con=conn)\n\tif dump:\n\t\treturn jsonify(dict(zip(revisions['project'],revisions['cnt'])))\t\n\treturn revisions.to_html(index=False)\n\n\n@app.route('/pagesNoHumans')\ndef pagesNoHumans():\n\tdump = request.args.get('data',False)\n\tconn = sqlite3.connect(pathToDB)\n\tpages = pagesNoHumans()\n\tif dump:\n\t\toutput = {}\n\t\tfor project, data in pages.groupby('project'):\n\t\t\toutput[project] = [row.to_json() for index,row in data.iterrows() ]\n\t\treturn jsonify(output)\n\tpages['url'] =pages.url.apply(lambda x: ' %s ' % (x,x))\n\treturn pages.to_html(index=False,escape=False)\n\n\n@app.route('/pages')\ndef pages():\n\tdump = request.args.get('data',False)\n\tconn = sqlite3.connect(pathToDB)\n\tpages = pd.read_sql('''SELECT DISTINCT pagesPerProjectTable.page, pagesPerProjectTable.wikidataItem, pagesPerProjectTable.project,pagesPerProjectTable.wikilink, itemsInfoTable.Instace_Of_Label, pagesPerProjectTable.url, itemsInfoTable.connector_Label FROM \n itemsInfoTable INNER JOIN pagesPerProjectTable ON pagesPerProjectTable.wikidataItem = itemsInfoTable.item_id\n ''',con=conn).sort_values(by=['project','page'])\n\tif dump:\n\t\toutput = {}\n\t\tfor project, data in pages.groupby('project'):\n\t\t\toutput[project] = [row.to_json() for index,row in data.iterrows() ]\n\t\treturn jsonify(output)\n\tpages['url'] =pages.url.apply(lambda x: ' %s ' % (x,x))\n\treturn pages.to_html(index=False,escape=False)\n\n@app.route('/perDay')\ndef perDay():\n\tdump = request.args.get('data',False)\n\tdays = getEditsPerDay()\n\tif dump:\n\t\treturn jsonify(days)\n\treturn days.to_html()\n\n@app.route('/perDayNoHumans')\ndef perDayNoHumans():\n\tdump = request.args.get('data',False)\n\tproject = request.args.get('project',False)\n\tdays = getEditsPerDay(humans=False,project=project)\n\tif dump:\n\t\treturn jsonify(days)\n\treturn days.to_html()\n\n@app.route('/perProjectNoHumans')\ndef perProjectNoHumans():\n\tdump = request.args.get('data',False)\n\tif dump:\n\t\treturn jsonify(getEditsPerProject())\n\treturn getEditsPerProject().to_html()\n\n\n### Functions\n\ndef getEditsPerDay(project=False,humans=False):\n\tconn = sqlite3.connect(pathToDB)\n\tif not project:\n\t\trevisions = pd.read_sql(''' SELECT timestamp,page,project FROM revisions''', con=conn)\n\telse:\n\t\trevisions = pd.read_sql(''' SELECT timestamp,page,project FROM revisions WHERE project = '%s' ''' % project, con=conn)\n\tif not humans:\t\n\t\tpages = pagesNoHumans()\n\t\trevisions = pd.merge(revisions,pages,on=['page','project'])[['timestamp','project','page']].drop_duplicates() \t\t\n\trevisions['day'] = pd.to_datetime(revisions['timestamp']).dt.strftime('%Y-%m-%d')\n\tdays = revisions[['day','timestamp']].groupby('day').agg('count')\n\tdays.sort_index(inplace=True)\n\treturn days\n\t\n\t\ndef pagesNoHumans():\n\tconn = sqlite3.connect(pathToDB)\n\tpages = pd.read_sql('''SELECT DISTINCT pagesPerProjectTable.page , pagesPerProjectTable.project,pagesPerProjectTable.wikilink, itemsInfoTable.Instace_Of_Label,\n pagesPerProjectTable.url FROM \n itemsInfoTable INNER JOIN pagesPerProjectTable ON pagesPerProjectTable.wikidataItem = itemsInfoTable.item_id\n WHERE itemsInfoTable.Instace_Of != 'Q5' \n ''',con=conn).sort_values(by=['project','page'])\n\treturn pages\n\ndef totalEditsNoHumans(project=False):\n\treturn getEditsPerDay(project=project,humans=False).timestamp.sum()\n\n\ndef getEditors(project=False,humans=True):\n\tconn = sqlite3.connect(pathToDB)\n\tif not project:\n\t\trevisions = pd.read_sql(''' SELECT timestamp,page,project,user FROM revisions''', con=conn)\t\t\n\telse:\n\t\trevisions = pd.read_sql(''' SELECT timestamp,page,project,user FROM revisions WHERE project = '%s' ''' % project, con=conn)\n\tif not humans:\t\n\t\tpages = pagesNoHumans()\n\t\trevisions = pd.merge(revisions,pages,on=['page','project'])[['timestamp','project','page','user']]\t\n\treturn revisions.user.unique().size\n\ndef numProjects(humans=True):\n\tconn = sqlite3.connect(pathToDB)\n\trevisions = pd.read_sql(''' SELECT timestamp,page,project,user FROM revisions''', con=conn)\t\t\n\tif not humans:\t\n\t\tpages = pagesNoHumans()\n\t\trevisions = pd.merge(revisions,pages,on=['page','project'])[['timestamp','project','page','user']]\n\t\t\n\treturn revisions.project.unique().size\n\ndef getEditsPerProject(humans=False):\n\tconn = sqlite3.connect(pathToDB)\n\trevisions = pd.read_sql(''' SELECT timestamp,page,project FROM revisions ''' , con=conn)\n\tif not humans:\t\n\t\tpages = pagesNoHumans()\n\t\trevisions = pd.merge(revisions,pages,on=['page','project'])[['timestamp','project','page']].drop_duplicates() \t\t\n\trevisions['day'] = pd.to_datetime(revisions['timestamp']).dt.strftime('%Y-%m-%d')\n\tprojects = revisions[['project','timestamp']].groupby('project').agg('count')\n\tprojects.sort_index(inplace=True)\n\treturn projects\n\n\n@app.route('/downloadSqlite')\ndef sqliteDownload():\n return app.send_static_file('AllWikidataItems.sqlite')\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"186304511","text":"####################################################################\n# Computational Physics, 2017-18 Sem1\n# HW-1 Ex-8\n#\n# (c) 2017 Haipeng Lin \n# All Rights Reserved.\n#\n# This program is written as Homework for the Computational Physics\n# Course in Peking University, School of Physics.\n# NO WARRANTIES, EXPRESS OR IMPLIED, ARE OFFERED FOR THIS PRODUCT.\n# Copying is strictly prohibited and its usage is solely restricted\n# to uses permitted by the author and homework grading.\n#\n# This program is Python 3 (3.6.2 on darwin)\n# compatible, and does not support Python 2.\n#\n# Now Playing: Remember the Name - Fort Minor\n#\n# Reticulating Splines requires the solving of a tri-diagonal matrix\n# using whatever method of our choice. I have chosen Thomas' Algorithm,\n# which is similar to 追赶法 because its easier and more lightweight\n# to implement.\n# The implementation here is similar to a previous\n# masterpiece of mine written in Haskell,\n# https://github.com/jimmielin/HW-Numerical-Analysis-Spring-2016/\n# blob/master/20160305-extrapolation/splines.hs\n# but re-implemented in Python.\n####################################################################\n\nfrom functools import partial\n\n# Include my own lightweight matrix library & its prototype\nfrom pylitematrix.pylitematrix import Matrix, mp\n\n\n####################################################################\n# The Tridiagonal Matrix Algorithm \"Thomas Algorithm\"\n# https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm\n#\n# An algorithm stable for solving tri-diagonal, positive semi-definite\n# or diagonally dominant matrices\n# in O(n) instead of O(n^2) as Gauss.\n\n# solveTri(M, b) = x solves Mx=b\n# when M is tri-diagonal, positive semi-definite || diagonal dominant\n#\n# Notes of the author (10/05/2017):\n# 1. This implementation IS space-optimal as the matrix is decomposed in\n# the first step and stored in an internal representation similar to the\n# course description (but since we are not symmetric, we use arrays)\n# 2. Watch out for the indexes. Some have been padded for mathematical\n# understanding, but some have not for implementation reasons.\n# \ndef solveTri(M, b):\n # Extract the {c_i}, {b_i} and {a_i} in the NxN matrix\n n = M.nrows()\n if(M.ncols() != n):\n raise ValueError(\"Tridiagonal Matrix to-solve must be square.\")\n\n # The arrays below have been padded so the indeces are mathematically sound.\n # One doesn't have to do this, but it makes for more coding convenience.\n A = [0, 0] # lower diagonal A, i=2,3..n\n B = [0] # diagonal B, i=1,2,..n\n C = [0] # upper diagonal C, i=1,2,..n-1\n D = b.toList() # right-b vector d1, d2, ... n\n D.insert(0, 0) # left-padd, * minor performance concern\n\n # The solution array is *NOT* padded, as it'll be used for\n # fromList_ by the Matrix prototype\n # It's even reversed as part of back-substitution\n # so watch out for the index.\n X = [None] * n\n\n # .elem is now O(1) so you can use that for safety,\n # but I'll tap into .internal represenation for speed and less overhead\n # since we already checked the indexes above\n for i in range(1, n+1):\n if(i != 1): # make sure i=1 case does not run for A\n A.append(M.internal[i-1][i-2])\n if(i != n): # make sure i=n case does not run for C\n C.append(M.internal[i-1][i])\n B.append(M.internal[i-1][i-1])\n\n # Now perform the Thomas Algorithm Forward Sweep\n C[1] = C[1] / B[1]\n D[1] = D[1] / B[1]\n for i in range(2, n+1):\n if(i != n): # make sure i=n case does not run for C=..n-1\n C[i] = C[i] / (B[i] - A[i] * C[i-1])\n D[i] = (D[i] - A[i] * D[i-1]) / (B[i] - A[i] * C[i-1])\n\n # Now do a back-subsitution...\n X[0] = D[n]\n for i in range(2, n+1):\n j = n+1-i # back indexes\n X[i-1] = D[j] - C[j] * X[i-2]\n\n X.reverse()\n\n return mp.fromList_(n, 1, X)\n\n# Some testing data.\n#testtrim = mp.fromList_(4, 4, [1,5,0,0,8,2,6,0,0,9,3,7,0,0,10,4])\n#testtrib = mp.fromList_(4, 1, [1,1,1,1])\n#print(solveTri(testtrim, testtrib))\n\n####################################################################\n# Reticulator of Splines\n# “三次样条差值是一种分段三次多项式插值, 在每个插值节点处比分段三次Hermite更光滑,\n# 具有二阶连续导数, 而且不需要节点导数信息.”\n# 据王鸣老师所述,在早期工程学上三次样条插值的实现方法就是在坐标纸上画点, 然后用\n# 一个铁条固定在节点处弯曲,从而获得自然边界条件。\n#\n# 王教授于2016年夏因病逝世, 我们成为最后一批《计算方法B》的学生.\n# R.I.P.\n#\n\n# Base Hermite Functions alpha, beta\n# \"分段三次Hermite插值的基函数\"\n#\n# for partial applications we may need functools->partial, but this implementation\n# is so much lamer than Haskell...\naL = lambda a, b, x: (1 + 2*(x-a)/(b-a)) * ((x-b)/(a-b))**2\naR = lambda a, b, x: (1 + 2*(x-b)/(a-b)) * ((x-a)/(a-b))**2\nbL = lambda a, b, x: (x-a)*((x-b)/(a-b))**2\nbR = lambda a, b, x: (x-b)*((x-a)/(a-b))**2\n\n# Hermite Functions alpha_i, beta_i\n# Generated Functions (Partially Applied Lambdas) that use aLRbLR to\n# generate the respective alpha/beta functions for extrapolation\n# According to 《计算方法》Page 40, Tsinghua University\n#\n# The Haskell Implementation is as follows:\n#\n# ah' :: (RealFloat a) => Int -> Int -> [a] -> a -> a\n# ah' i n xs x\n# | i == 0 = if x < xs !! 0 then 0 else (if x <= xs !! 1 then aleft (xs !! 0) (xs !! 1) x else 0)\n# | i == n = if x < xs !! (n - 1) then 0 else (if x <= xs !! n then aright (xs !! (n-1)) (xs !! n) x else 0)\n# | otherwise = if x < (xs !! (i - 1)) then 0 else (if x <= (xs !! i) then aright (xs !! (i - 1)) (xs !! i) x else (if x <= (xs !! i + 1) then aleft (xs !! i) (xs !! (i + 1)) x else 0))\n#\n# i = 0, 1, ... n (for a total of n+1 nodes)\n# Indexes are mathematical since the mathematical definition starts with zero.\ndef aI(x, i, nodes):\n n = len(nodes) - 1\n if(n < 1):\n raise ValueError(\"There must be at least 2 nodes for Hermite Extrapolation (or any, actually.)\")\n\n if(i == 0):\n return 0 if x < nodes[0] else (aL(a=nodes[0],b=nodes[1],x=x) if x < nodes[1] else 0)\n elif(i == n):\n return 0 if x < nodes[n-1] else (aR(a=nodes[n-1],b=nodes[n],x=x) if x <= nodes[n] else 0)\n else:\n return 0 if x < nodes[i-1] else (aR(a=nodes[i-1],b=nodes[i],x=x) if x < nodes[i] else (aL(a=nodes[i],b=nodes[i+1],x=x) if x < nodes[i+1] else 0)) \n\ndef bI(x, i, nodes):\n n = len(nodes) - 1\n if(n < 1):\n raise ValueError(\"There must be at least 2 nodes for Hermite Extrapolation (or any, actually.)\")\n\n if(i == 0):\n return 0 if x < nodes[0] else (bL(a=nodes[0],b=nodes[1],x=x) if x < nodes[1] else 0)\n elif(i == n):\n return 0 if x < nodes[n-1] else (bR(a=nodes[n-1],b=nodes[n],x=x) if x <= nodes[n] else 0)\n else:\n return 0 if x < nodes[i-1] else (bR(a=nodes[i-1],b=nodes[i],x=x) if x < nodes[i] else (bL(a=nodes[i],b=nodes[i+1],x=x) if x < nodes[i+1] else 0))\n\n# Generate Equations\n# Given xs, ys, generate the matrices to be solved in order to get the appropriate m-factors\n# in the Splined Hermite representation Sh(x).\n#\n# Note: This is *not* very efficient as it stores a whole matrix.\n# But it is generalized enough so we can abstract a solver out of the equation generator,\n# so its for the greater good.\n#\n# Arrays xs and ys are mathematical indexes i=0..n\ndef genSplineMatrix(xs, ys):\n n = len(xs) - 1\n if(n != len(ys) - 1):\n raise ValueError(\"You must provide as many y-points as x-points to genSplineMatrix\")\n\n M = mp.diag_(n+1, [2] * (n+1))\n\n # arrays lambdas & mus are mathematical indexes i=0..n\n lambdas = [None] * (n+1)\n lambdas[0] = 1\n lambdas[n] = 0\n M.setElem_(1, 2, lambdas[0])\n M.setElem_(n+1, n, 1)\n # h_i = x_i+1 - x_i\n\n mus = [None] * (n+1)\n mus[0] = 3 * (ys[1] - ys[0]) / (xs[1] - xs[0])\n mus[n] = 3 * (ys[n] - ys[n-1]) / (xs[n] - xs[n-1])\n\n for i in range(1, n):\n lambdas[i] = (xs[i] - xs[i-1]) / (xs[i+1] - xs[i-1])\n mus[i] = 3 * ((ys[i] - ys[i-1]) * (1 - lambdas[i]) / (xs[i] - xs[i-1]) + (ys[i+1] - ys[i]) * lambdas[i] / (xs[i+1] - xs[i]))\n # and commit using the side-effect setElem_ function\n M.setElem_(i+1,i+2,lambdas[i])\n M.setElem_(i+1,i,1-lambdas[i])\n\n B = mp.fromList_(n+1,1,mus)\n\n return (M, B)\n\n# Reticulate Splines (Actual Code)\n# Generate Equations, Solve Equations, Construct Functions, and returns a Lambda\n# representing the splined function.\n#\n# Luckily, Python does not do lazy evaluation, meaning that this lambda will be speedy\n# instead of being tri-solved every call. :)\ndef spline_(xs, ys, x):\n gendMatrix = genSplineMatrix(xs, ys)\n mSolution = solveTri(gendMatrix[0], gendMatrix[1]).toList() # ms...\n\n # To do a sum, we need parrying & foldl which Python does not do very well.\n # Hence we use functools.partial to do this in a tricky way,\n # making this spline_ function do the dirty work and wrapping it in a cleaner\n # spline function.\n # def aI(x, i, nodes) / bI\n res = 0\n for i, y in enumerate(ys):\n res += y * aI(x, i, xs) + mSolution[i] * bI(x, i, xs)\n\n return res\n\ndef spline(xs, ys):\n spp = partial(spline_, xs=xs, ys=ys)\n return lambda x: spp(x=x)\n\nex8 = spline([0,3,5,7,9,11,12,13,14,15], [0,1.2,1.7,2.0,2.1,2.0,1.8,1.2,1.0,1.6])\n\n# For plotting the result\nimport matplotlib.pyplot as plt \nfig, ax = plt.subplots()\nxs = [x/100 for x in range(1,1500)]\nys = [ex8(x) for x in xs]\nax.plot(xs, ys)\nplt.show()\n\n# For 0.1x variances\nxs = [0,3,5,7,9,11,12,13,14,15]\nfor i in range(len(xs)):\n print(\"x =\", xs[i] - 0.1, \" y =\", ex8(xs[i] - 0.1))\n print(\"x =\", xs[i], \" y =\", ex8(xs[i]))\n print(\"x =\", xs[i] + 0.1, \" y =\", ex8(xs[i] + 0.1))","sub_path":"ex8-spline.py","file_name":"ex8-spline.py","file_ext":"py","file_size_in_byte":9830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"150315760","text":"#wallpaper\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nimport csv\nimport pandas as pd\n\nindex = 0\npage = 0\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}\n\ndef get_images(name, no):\n\tglobal index\n\tglobal page\n\t\n\tprint(\"第\"+str(page+1)+\"页\")\n\tif not os.path.exists(\"./images/\" + name + '/wallpaper'):\n\t\tos.mkdir(\"./images/\" + name + '/wallpaper')\n\n\turl = 'https://movie.douban.com/celebrity/'+no+'/photos/?type=C&start='+str(page*30)+'&sortby=like&size=a&subtype=a' \n\thtml = BeautifulSoup(requests.get(url, headers=headers).text, features=\"html.parser\")\n\tcover = html.find_all('div',{'class', 'cover'})\n\tfor img in cover:\n\t\tsrc = img.find('img').get('src').replace('/m/','/l/')\n\t\ttime.sleep(0.1)\n\t\ttry:\n\t\t\tr = requests.get(src, timeout=5)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tcontinue\n\t\t\n\t\twith open('./images/' + name + '/wallpaper/p_' + str(index) + \".jpg\", 'wb') as jpg:\n\t\t\tprint(\"正在抓取第%s条数据\" % index)\n\t\t\tindex += 1\n\tpage += 1\n\n\n\ndef iter_page(name, no, total):\n\tglobal page\n\tglobal index\n\twhile page < total:\n\t\tget_images(name, no)\n\n\tdata = pd.read_csv('star.csv', encoding='utf-8')\n\tdata.tail(1)[u'wallpaper'] = str(index)\n\tprint(data.tail(1)[u'wallpaper'])\n\tdata.to_csv('star.csv', header=True, index=False, encoding='utf-8')\n\n#iter_page('Leonardo DiCaprio', '1041029', 3)\niter_page('Catherine Zeta Jones', '1056058', 3)\n","sub_path":"pw.py","file_name":"pw.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"75002306","text":"import numpy as np\n\n# define lattice vectors\nlat = [[2.4912500000, 1.4383238581, 4.4776666667], \n [-2.4912500000, 1.4383238581, 4.4776666667], \n [0.0000000000, -2.8766477162, 4.4776666667]]\n\n# define coordinate of sites under lattice vectors \norb = [[0.1446000000, 0.1446000000, 0.1446000000], [0.6446000000, 0.6446000000, -0.3554000000],\n [0.8554000000,-0.1446000000,-0.1446000000], [0.3554000000,0.3554000000,-0.6446000000]]\n# a class containing all information about a site\n# and a method to calculate distance\nclass site:\n def __init__(self, lat_vec, lat_trans):\n \"\"\"\n construct a site\n parameters:\n lat_vec: the coordinate of sites under lattice vectors.\n This can be obtained from orb\n lat_trans: lattice vector to cell containing this site\n \"\"\"\n self.lat_vec = lat_vec\n self.lat_trans = lat_trans\n\n def findDist(self, target_site):\n \"\"\"\n calclate the distance between this site and another site\n parameters:\n target_site: the second site to find distance to.\n return: the euclidian distance in the unit of A\n \"\"\"\n lat_trans_diff = np.subtract(target_site.lat_trans, self.lat_trans) # difference in lattice translaiton\n site_diff = np.subtract(target_site.lat_vec, self.lat_vec) # difference in site\n diff = lat_trans_diff + site_diff # sum then up\n diff = np.multiply(diff[0], lat[0]) + np.multiply(diff[1], lat[1]) + np.multiply(diff[2], lat[2]) # convert to angstrom\n return np.linalg.norm(diff)\n\n\n\nstart_cell = [] \n\nstart_cell.append(site(orb[0], [0, 0, 0]))\nstart_cell.append(site(orb[1], [0, 0, 0]))\nstart_cell.append(site(orb[2], [0, 0, 0]))\nstart_cell.append(site(orb[3], [0, 0, 0]))\n\n# set the threshold distance\nthreshold = 5\n# range of the translation\ntrans_range = 2\n# a dict to store pairs within threshold\ndist_dict = {}\n\nfor x in range(-trans_range, trans_range+1):\n for y in range(-trans_range, trans_range+1):\n for z in range(-trans_range, trans_range+1):\n # define target cell\n target_cell = [] \n target_cell.append(site(orb[0], [x, y, z]))\n target_cell.append(site(orb[1], [x, y, z]))\n target_cell.append(site(orb[2], [x, y, z]))\n target_cell.append(site(orb[3], [x, y, z]))\n \n # compute all orbits in the cell\n for i in range(4):\n for j in range(i, 4):\n dist = start_cell[i].findDist(target_cell[j])\n # if they are within threshold and two orbits aren't the same\n if(dist < threshold) and (x != 0 or y != 0 or z != 0 or i != j):\n # is equivalent to \n if (i, j, -x, -y, -z) not in dist_dict:\n dist_dict[(i, j, x, y, z)] = dist # add to the dict\n\ndist_dict_sorted = {k: v for k, v in sorted(dist_dict.items(), key=lambda item: item[1])}\n\n# set a counter\ncnt = 0\nfor k, v in dist_dict_sorted.items():\n print('my_model.set_hop(hopping[%d],%d,%d,[%d,%d,%d])' %(cnt, k[0], k[1], k[2], k[3], k[4]))\n cnt = cnt + 1\n\nprint('\\n\\n\\n\\n\\n')\n\n \nfor k, v in dist_dict_sorted.items():\n print('%f' %(v), end=', ')\n","sub_path":"Alpha/alpha/neighborhood_finder.py","file_name":"neighborhood_finder.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"30897118","text":"import itertools\nfrom random import randint\nimport numpy\nfrom copy import deepcopy\nimport collections\n\nclass ParamGener:\n '''参数生成方式'''\n def __init__(self,*args):\n '''参数列表,2维数组'''\n self.inputParam=args\n def allConbine(self):\n '''对列表进行笛卡儿积,并按照一个列表返回'''\n all = []\n for i in itertools.product(*self.inputParam):\n all.append(i)\n return all\n\n # def eachChoice(self):\n # all=self.allConbine()\n #\n # for one in all:\n # print(one)\n # print('######################')\n #\n # retList=[]\n # retList.append(all[0])\n # for one in all:\n # for index,item in enumerate(one):\n # if retList[index]==item:\n # break\n # else:\n # retList.append(one)\n # retList=set(retList)\n # print(len(retList))\n # return retList\n\n def pairWiseMore(self):\n #获取正交参数对\n all=self.allConbine()\n pairList=[]\n\n #根据正交参数对,获取配对算法全部的配对参数对\n for one in all:\n temp=[]\n for item in itertools.combinations(one,2):\n temp.append(item)\n pairList.append(temp)\n\n compareList=deepcopy(pairList)\n # for one in pairList:\n # print(one)\n #配对参数对筛选\n remainsList=[]\n returnList=[]\n\n for line, pairGroups in enumerate(pairList):\n flag=[0]*len(pairGroups)\n for col in range(0, len(pairGroups)):\n for row in range(0,len(compareList)):\n if pairList[line]!=compareList[row] and pairGroups[col]==compareList[row][col]:\n flag[col]=1\n break\n else:\n flag[col]=0\n\n # print(flag)\n if 0 not in flag:\n # deleteList.append(pairGroups)\n # count=collections.Counter(flag)[1]\n # flag=[]\n # if count>=5:\n compareList.remove(pairGroups)\n else:\n remainsList.append(pairGroups)\n\n #合并配对参数的列表\n temp=[]\n for items in remainsList:\n for one in items:\n for item in one:\n if item not in temp:\n temp.append(item)\n # returnList.append(sorted(list(set(temp.lstrip(\",\").split(\",\")))))\n returnList.append(temp)\n temp=[]\n return returnList\n\n def pairWiseLess(self):\n #获取正交参数对\n all=self.allConbine()\n pairList=[]\n\n #根据正交参数对,获取配对算法全部的配对参数对\n for one in all:\n temp=[]\n for item in itertools.combinations(one,2):\n temp.append(item)\n pairList.append(temp)\n compareList=deepcopy(pairList)\n # for one in compareList:\n # print(one)\n #配对参数对筛选\n remainsList=[]\n returnList=[]\n\n for line, pairGroups in enumerate(pairList):\n flag=[0]*len(pairGroups)\n for col in range(0, len(pairGroups)):\n for row in range(0,len(compareList)):\n if pairList[line]!=compareList[row] and pairGroups[col]==compareList[row][col]:\n flag[col]=1\n break\n else:\n flag[col]=0\n print(flag)\n if flag.count(1)>=len(pairGroups)-1:\n # deleteList.append(pairGroups)\n compareList.remove(pairGroups)\n else:\n remainsList.append(pairGroups)\n\n #合并配对参数的列表\n temp=[]\n for items in remainsList:\n for one in items:\n for item in one:\n if item not in temp:\n temp.append(item)\n # returnList.append(sorted(list(set(temp.lstrip(\",\").split(\",\")))))\n returnList.append(temp)\n temp=[]\n return returnList\n\n def antiRandom(self,n):\n '''反随机,找边界'''\n all = self.allConbine()\n start=0\n end=len(all)-1\n resList=[]\n resList.append(all[0])\n resList.append(all[end])\n\n middle = (start + end) // 2\n while len(resList)= 0.0) and (x < 0.2)] # interval[0,0.2)\ninterval2 = [x for x in flist if (x >= 0.2) and (x < 0.4)] # interval[0.2,0.4)\ninterval3 = [x for x in flist if (x >= 0.4) and (x < 0.6)] # interval[0.4,0.6)\ninterval4 = [x for x in flist if (x >= 0.6) and (x < 0.8)] # interval[0.6,0.8)\ninterval5 = [x for x in flist if (x >= 0.8) and (x < 1.0)] # interval[0.8,1.0)\n\n# Getting minimum value for set\nlen_interval = [len(interval1), len(interval2), len(\n interval3), len(interval4), len(interval5)]\nmin_len = min(len_interval)\n\noutlist = [] # Empty list and append the values inside list based on minimum set for each intervals\nfor x in range(min_len):\n outlist.append(interval1[x])\n outlist.append(interval2[x])\n outlist.append(interval3[x])\n outlist.append(interval4[x])\n outlist.append(interval5[x])\n\noutput = ','.join(map(str, outlist)) # Getting output in strings\n\nprint(output)\n","sub_path":"filter_data.py","file_name":"filter_data.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"268265849","text":"import pygame\n\nfrom .raw_color import compute_raw_color\n\nclass Theme:\n def __init__(self,**kwargs):\n self.__dict__ = kwargs\n\n def __getitem__(self,item):\n return self.__dict__[item]\n\nclass TwoColorThematics:\n def __init__(self,bg_color,fg_color):\n self.set_bg(bg_color)\n self.set_fg(fg_color)\n\n def set_bg(self,color):\n self.bg = color\n if self.application:\n self.rebuild_colors()\n\n def set_fg(self,color):\n self.fg = color\n if self.application:\n self.rebuild_colors()\n\n def rebuild_colors(self):\n #NOTE: Call only after calling connect_application.\n self.bg_raw = compute_raw_color(self.application,self.bg)\n self.fg_raw = compute_raw_color(self.application,self.fg)\n\n #NOTE: Always call rebuild_colors in connect_application\n\ndefault_theme = Theme(\n default_bg = (240,240,240),\n default_fg = (0,0,0),\n\n default_button_bg = (160,160,160),\n default_button_fg = (0,0,0),\n default_button_border = (0,0,0),\n\n default_button_hi_bg = (96,96,96),\n default_button_hi_fg = (240,240,240),\n default_button_hi_border = (0,0,0),\n)","sub_path":"themes.py","file_name":"themes.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"127039759","text":"from django.conf.urls import url\nfrom GitQuid import views\n\n\napp_name = 'GitQuid'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^about/', views.about, name='about'),\n\n # Account related urls\n url(r'^register/$', views.register, name='register'),\n url(r'^account/(?P[-\\w]+)/$', views.account, name='account'),\n url(r'^account/(?P[-\\w]+)/editProfile/$', views.editProfile, name='editProfile'),\n url(r'^logout/$', views.user_logout, name='logout'),\n url(r'^ajax/validate_username/$', views.validate_username, name='validate_username'),\n\n # Projects related urls\n url(r'^projects/(?P[a-z]+)$', views.browseProjects, name='browseProjects'),\n #url(r'^projects/$', views.browseProjects, name='browseProjects'),\n url(r'^projects/addProject/$', views.addProject, name='addProject'),\n url(r'^projects/(?P[-\\w]+)/editProject$', views.editProject, name='editProject'),\n url(r'^projects/(?P[-\\w]+)/viewProject$', views.viewProject, name='viewProject'),\n]\n","sub_path":"GitQuid/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"237026059","text":"#BEGIN HEADER\n\n#IsDebugged False\n#IsLocked True\n#RealName InstanceWithNameGetterFunctorScript\n\n#/*##################################/\n# Here are the functions making easier\n# to call any Instance og one of\n# the defined class in the sys\n# framework\n#/##################################*/\n\n#END HEADER\n\n#BEGIN BODY\n\n#/###################################/\n#/#### Define Python Modules ########/\n#/###################################/\n\nimport re\n\n#/###################################/\n#/###### Define Variables ###########/\n#/###################################/\n\n\n#/###################################/\n#/###### Define Functions ##########/\n#/###################################/\n\ndef getDefaultInstancerDictWithIsBased(_IsBased):\n\t'''\n\t\tGet the Default InstancerDict\n\t'''\n\t\"\"\"\n\t\t#Get the Default InstancerDict\n\t\tDefaultDict=_.getDefaultInstancerDict(True);\n\t\t\n\t\t#Print the Default InstancerDict\n\t\tprint(\"\\nDefaulInstancertDict is :\");\n\t\tprint(DefaultInstancerDict);\n\t\"\"\"\n\t\n\tif _IsBased:\n\t\t#Init the DefaultDict\n\t\tDefaultInstancerDict={};\n\t\tfor BaseName in InstancerBaseNamesOrderedSet:\n\t\t\tDefaultInstancerDict.update(getattr(sys.modules['SysPyModule'],'getDefault'+BaseName+'DictWithIsBased')(False));\n\t\n\t#Add Specific Attributes\n\tDefaultInstancerDict.update({\n\t\t\t\t'DefaultInstanceType':\"Sys\"\n\t\t\t});\n\n\t#Return the Dict\n\treturn DefaultInstancerDict;\n\ndef getInstanceWithInstancerAndName(_Instancer,_Name=None):\n\t'''\n\t\tUniversal Getter that returns an instance if an associated class exists in the lib\n\t'''\n\t\"\"\"\n\t\t\n\t\tprint(_.getInstanceWithName('Thing',**{'DefaultInstanceName':'Dict'}))\n\t\n\t\"\"\"\n\t\n\t##Debug\n\t#_.printDebug('Start _Key : '+_Name);\n\t\t\n\t#If it is a StringKey\n\tif type(_Name) in [str,unicode]:\n\t\n\t\t#Init the Instance as a dict\n\t\tInstance=None;\n\t\t\t\n\t\t#UpperCase for the first letter means something knew...\n\t\tif _Name[0]==_Name[0].upper():\n\t\t\n\t\t\t#Instancify\n\t\t\tif _Name!=None:\n\t\t\t\tInstance=getattr(_.getModuleWithName(_Name),_.getClassNameWithName(_Name))();\n\t\t\t\n\t\t\t#Other 'smart' methods for finding maybe a Class for this\n\t\t\tif hasattr(Instance,'__dict__')==False:\n\t\t\t\t\n\t\t\t\t#If it is not defined look at splittedNames\n\t\t\t\tSplittedNames=getWordsListWithName(_Name);\n\t\t\t\tSplittedNames=filter(lambda Element:Element!='',SplittedNames);\n\t\t\t\t\n\t\t\t\t#Do the chunks\n\t\t\t\tfor ChunksNumber in xrange(len(SplittedNames)-1,0,-1):\n\t\t\t\t\t\n\t\t\t\t\t#Build the BaseName\n\t\t\t\t\tBaseName=''.join(SplittedNames[len(SplittedNames)-ChunksNumber:]);\n\t\t\t\t\t\n\t\t\t\t\t#Check that this BaseName exists\n\t\t\t\t\tif _.getFolderPathStringWithName(BaseName)!=None:\n\t\t\n\t\t\t\t\t\t#Get the Instance\n\t\t\t\t\t\tInstance=getattr(_.getModuleWithName(BaseName),_.getClassNameWithName(BaseName))();\n\t\t\t\t\t\t\n\t\t\t\t\t\t#Specify the Type\n\t\t\t\t\t\tInstance.Type=_Name;\n\t\t\t\t\t\t\n\t\t\t\t\t\t#Leave the loop\n\t\t\t\t\t\t\n\t\t\t\n\t\t#If not... Build a Default Sys Class with the name as the ClassName\n\t\tif hasattr(Instance,'__dict__')==False:\n\t\t\n\t\t\t#Import the Default Class\n\t\t\t_.importModulesWithFolderNamesList([_Instancer['DefaultInstanceType']]);\n\t\t\t\n\t\t\t#Define a Default Instance given by the _Instancer\n\t\t\tInstance=getattr(_.getModuleWithNameString(_Instancer['DefaultInstanceTypeString']),_.getClassNameStringWithNameString(_Instancer['DefaultInstanceTypeString']))();\n\t\t\tInstance.TypeString=_Instancer['DefaultInstanceTypeString'];\n\t\t\tInstance.NodeString=_NameString;\n\n\t#Return\n\treturn Instance;\n\ndef getInstancifiedDict(_Dict,**Kwargs):\n\t\n\t#Set DefaultItems\n\tLocalDict=getLocalDictWithKwargsAndDefaultItemsDict(Kwargs,\n\t\t\t\t{\n\t\t\t\t\t'DefaultInstanceName':\"Sys\"\n\t\t\t\t}\n\t\t\t\t);\n\t\t\t\t\n\t#Instancify a Dict if it has a Type Key or not to specify the Type\n\tif _Dict.has_key('Type'):\n\t\treturn addDict(getInstanceWithName(_Dict['Type']),_Dict,**LocalDict);\n\telse:\n\t\treturn addDict(getInstanceWithName(LocalDict['DefaultInstanceName']),_Dict,**LocalDict);\n\n#END BODY","sub_path":"Modules/_drafts/Functor/Modules/Getter/Modules/drafts/Instancer/Scripts/1_InstanceGetterFunctions/InstanceGetterFunctionsScript.py","file_name":"InstanceGetterFunctionsScript.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"520771607","text":"#encoding=utf-8\n#author: walker\n#date: 2015-09-25\n#function: 打印指定access文件、指定表的所有字段\n\n\nimport xlrd\nimport xlwt\nfrom xlutils.copy import copy\n\ndef read_excel():\n # 打开文件\n workbook = xlrd.open_workbook(r'D:\\workspace\\Python\\bom_edit\\cnu_c8811_v1.xlsx')\n # 获取所有sheet\n # 获取所有sheet\n print (workbook.sheet_names()) # [u'sheet1', u'sheet2']\n\n\n # 根据sheet索引或者名称获取sheet内容\n sheet = workbook.sheet_by_index(0)\n\n # sheet的名称,行数,列数\n print (sheet.name)\n print (sheet.name,sheet.nrows,sheet.ncols)\n nrows = sheet.nrows\n ncols = sheet.ncols\n print(range(nrows))\n for i in range(nrows):\n print (sheet.row_values(i))\n print ()\n\n\n\n print()\n print()\n print()\n\ndef get_coord(n,excel_file): #坐标索引 返回字符串在EXCEL中的的坐标位置\n # n---> 'string'\n # excel_file----> r'D:\\*\\*.xlsx'\n #\n # workbook = xlrd.open_workbook(r'D:\\workspace\\Python\\bom_edit\\cnu_c8811_v1.xlsx')\n workbook = xlrd.open_workbook(excel_file)\n # 获取所有sheet\n # 获取所有sheet\n number_row=0\n number_col=0\n\n # 根据sheet索引或者名称获取sheet内容\n sheet = workbook.sheet_by_index(0)\n nrows = sheet.nrows\n ncols = sheet.ncols\n #索引“线路板”cell 坐标点 \n for i in range(nrows):\n for j in range(ncols):\n if sheet.cell_value(i,j) ==n:\n number_row=i\n number_col=j\n break\n\n return number_row,number_col \n\n\ndef write_excel(lib_q,coord,excel_file):\n w = xlrd.open_workbook(excel_file)\n # a = w.sheet_names()\n # print(a)\n sh = w.sheet_by_index(0)\n wb = copy(w)\n #通过get_sheet()获取的sheet有write()方法\n ws = wb.get_sheet(0)\n ws.write(coord[0],coord[1], lib_q)\n \n wb.save(excel_file)\n","sub_path":"bom_edit/excel_lib.py","file_name":"excel_lib.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"5965274","text":"# 14-Longest_Common_Prefix_EASY.py\n\n# https://leetcode.com/problems/longest-common-prefix/\n\n# Write a function to find the longest common prefix string amongst an array of strings.\n\n# If there is no common prefix, return an empty string \"\".\n\n# Example 1:\n\n# Input: [\"flower\",\"flow\",\"flight\"]\n# Output: \"fl\"\n# Example 2:\n\n# Input: [\"dog\",\"racecar\",\"car\"]\n# Output: \"\"\n# Explanation: There is no common prefix among the input strings.\n# Note:\n\n# All given inputs are in lowercase letters a-z.\n\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n\n prefix = []\n\n if strs == []:\n return ''\n\n i = 0\n while True:\n curr_char = None\n for s in strs:\n if i >= len(s):\n return \"\".join(prefix)\n else:\n if curr_char == None:\n curr_char = s[i]\n elif s[i] != curr_char:\n return \"\".join(prefix)\n\n i += 1\n prefix.append(curr_char)\n\n\n","sub_path":"leetcode/14-Longest_Common_Prefix_EASY.py","file_name":"14-Longest_Common_Prefix_EASY.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"535898853","text":"from random import *\nfrom pico2d import *\n\nKPU_WIDTH, KPU_HEIGHT = 1280, 1024\n\n\ndef handle_events():\n global running\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n running = False\n elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:\n running = False\n\n\ndef move_character():\n global character_x, character_y\n global hand_x, hand_y\n\n if character_x < hand_x:\n character_x += 1\n elif character_x > hand_x:\n character_x -= 1\n\n if character_y < hand_y:\n character_y += 1\n elif character_y > hand_y:\n character_y -= 1\n\n\nopen_canvas(KPU_WIDTH, KPU_HEIGHT)\n\nkpu_ground = load_image('KPU_GROUND.png')\ncharacter = load_image('animation_sheet.png')\nhand = load_image('hand_arrow.png')\n\nrunning = True\ncharacter_x, character_y = KPU_WIDTH // 2, KPU_HEIGHT // 2\nhand_x, hand_y = randint(0, KPU_WIDTH), randint(0, KPU_HEIGHT)\ndirection = 0 # 0: right / 1: left\nframe = 0\n\nwhile running:\n clear_canvas()\n kpu_ground.draw(KPU_WIDTH // 2, KPU_HEIGHT // 2)\n hand.draw(hand_x, hand_y)\n\n if hand_x == character_x and hand_y == character_y:\n hand_x = randint(0, KPU_WIDTH)\n hand_y = randint(0, KPU_HEIGHT)\n\n if character_x <= hand_x:\n direction = 0\n else:\n direction = 1\n\n if direction == 0:\n character.clip_draw(frame * 100, 100 * 1, 100, 100, character_x, character_y)\n elif direction == 1:\n character.clip_draw(frame * 100, 0, 100, 100, character_x, character_y)\n\n update_canvas()\n frame = (frame + 1) % 8\n\n handle_events()\n move_character()\n\nclose_canvas()\n\n\n\n\n","sub_path":"move_character_with_hand.py","file_name":"move_character_with_hand.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"165979816","text":"#!/usr/bin/python3\nimport unittest\nfrom python.common.baseunittest import BaseUnitTest\nfrom python.eapi.methods.teams.team import Team\n\n\nclass TestTeams(BaseUnitTest):\n \"\"\"Runs Team test scenarios.\"\"\"\n\n @BaseUnitTest.log_try_except\n def test_01_get(self):\n \"\"\"\n 1. Get multiple.\n \"\"\"\n\n the_team = Team()\n the_team.get_multi()\n\n @BaseUnitTest.log_try_except\n def test_02_get_one(self):\n \"\"\"\n 1. Choose random, existing.\n 2. Get only that one.\n \"\"\"\n\n the_team = Team()\n random_team = the_team.choose_random()\n the_team.get_one(random_team)\n\n @BaseUnitTest.log_try_except\n def test_03_post(self):\n \"\"\"\n 1. Create new.\n 2. Get the newly created.\n \"\"\"\n\n the_team = Team()\n json_team = the_team.post_one()\n the_team.get_one(json_team)\n\n @BaseUnitTest.log_try_except\n def test_04_patch(self):\n \"\"\"\n 1. Create new.\n 2. Get the newly created.\n 3. Update the created.\n 4. Get the updates.\n \"\"\"\n\n the_team = Team()\n json_team = the_team.post_one()\n json_team = the_team.get_one(json_team)\n the_team.patch_one(json_team)\n the_team.get_one(json_team)\n\n @BaseUnitTest.log_try_except\n def test_05_delete(self):\n \"\"\"\n 1. Create new.\n 2. Get the newly created.\n 3. Delete the created.\n 4. Get the freshly deleted, and expect a 404 response.\n \"\"\"\n\n the_team = Team()\n json_team = the_team.post_one()\n the_team.get_one(json_team)\n the_team.delete_one(json_team)\n the_team.get_one(json_team, expected_code=404)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"python/eapi/tests/test_teams.py","file_name":"test_teams.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"463738248","text":"from django.shortcuts import render,redirect\nfrom rest_framework.views import APIView\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\nfrom .utils import *\n\nfrom requests import Request,post\n\nfrom music.models import Room\n\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\n#Create the .env file including CLIENT_ID, CLIENT_SECRET, REDIRECT_URI\n#CLIENT_ID and CLIENT_SECRET are obtained from Spotify Developer Dashboard\nCLIENT_ID = os.getenv(\"CLIENT_ID\")\nCLIENT_SECRET = os.getenv(\"CLIENT_SECRET\")\nREDIRECT_URI = os.getenv(\"REDIRECT_URI\")\n\nclass AuthURL(APIView):\n def get(self,request,format=None):\n scope = 'user-read-playback-state user-modify-playback-state user-read-currently-playing'\n url = Request(\"GET\",\"https://accounts.spotify.com/authorize\",params={\n 'scope':scope,\n 'response_type':'code',\n 'redirect_uri':REDIRECT_URI,\n 'client_id':CLIENT_ID\n }).prepare().url\n\n return Response({'url':url},status=status.HTTP_200_OK)\n\n\n\ndef spotify_callback(request,format=None):\n code = request.GET.get(\"code\")\n error = request.GET.get(\"error\",None)\n\n response = post('https://accounts.spotify.com/api/token',data={\n 'grant_type':'authorization_code',\n 'code':code,\n 'redirect_uri':REDIRECT_URI,\n 'client_id':CLIENT_ID,\n 'client_secret':CLIENT_SECRET\n }).json()\n\n access_token = response.get(\"access_token\")\n token_type = response.get(\"token_type\")\n refresh_token = response.get(\"refresh_token\")\n expires_in = response.get(\"expires_in\")\n error = response.get(\"error\")\n\n if not request.session.exists(request.session.session_key):\n request.session.create()\n\n update_or_create_user_tokens(request.session.session_key,access_token,token_type,expires_in,refresh_token)\n\n return redirect('/')\n\n\n\nclass IsAuthenticated(APIView):\n def get(self,request,format=None):\n is_authenticated = is_spotify_authenticated(self.request.session.session_key)\n\n return Response({\"status\":is_authenticated},status=status.HTTP_200_OK)\n\n\nclass CurrentSong(APIView):\n def get(self,request,format=None):\n room_code = self.request.session.get(\"room_code\")\n room = Room.objects.filter(code=room_code)\n if room.exists():\n room = room.first()\n else:\n return Response({\"404\":\"No Room Found\"},status=status.HTTP_404_NOT_FOUND)\n host = room.host\n endpoint = \"player/currently-playing\"\n response = execute_spotify_api_request(host,endpoint)\n if 'error' in response or 'item' not in response:\n return Response({\"Error\":\"No Content\"},status=status.HTTP_204_NO_CONTENT)\n \n item = response.get('item')\n duration = item.get('duration_ms')\n progress = response.get('progress_ms')\n album_cover = item.get('album').get('images')[0].get(\"url\")\n is_playing = response.get('is_playing')\n song_id = item.get('id')\n\n artist_string = \"\"\n\n for i,artist in enumerate(item.get('artists')):\n if i>0:\n artist_string += ', '\n name = artist.get(\"name\")\n artist_string += name\n \n song = {\n 'title':item.get('name'),\n 'artist':artist_string,\n 'duration':duration,\n 'time':progress,\n 'image_url':album_cover,\n 'is_playing':is_playing,\n 'votes':0,\n 'id':song_id\n }\n\n return Response(song,status=status.HTTP_200_OK)\n\n\nclass PauseSong(APIView):\n def put(self,request,format=None):\n room_code = self.request.session.get('room_code')\n room = Room.objects.filter(code=room_code).first()\n if self.request.session.session_key == room.host or room.guest_can_pause:\n pause_song(room.host)\n return Response({},status=status.HTTP_204_NO_CONTENT)\n \n return Response({\"Access Denied\":\"No Permissions\"},status=status.HTTP_403_FORBIDDEN)\n\nclass PlaySong(APIView):\n def put(self,request,format=None):\n room_code = self.request.session.get('room_code')\n room = Room.objects.filter(code=room_code).first()\n if self.request.session.session_key == room.host or room.guest_can_pause:\n play_song(room.host)\n return Response({},status=status.HTTP_204_NO_CONTENT)\n \n return Response({\"Access Denied\":\"No Permissions\"},status=status.HTTP_403_FORBIDDEN)\n\n\n\n\n\n\n\n","sub_path":"spotify/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"170623436","text":"import numpy as np\nfrom timeflux.core.node import Node\n\n\nclass Discretize(Node):\n \"\"\"Discretize data based on defined ranges\n Attributes:\n i (Port): Default input, expects DataFrame.\n o (Port): Default output, provides DataFrame.\n\n Args:\n range (dict): dictionary with keys corresponding to the discrete labels and values\n are lists of tuple with boundaries.\n default (float|str|None):\n \"\"\"\n\n def __init__(self, range, default=None):\n super().__init__()\n\n if default is None:\n default = np.NaN\n default = default\n self._default = default\n self._range = range\n for k, range_values in self._range.items():\n for v in range_values:\n if v[0] is None:\n v[0] = -np.inf\n if v[1] is None:\n v[1] = np.inf\n\n def _discretize(self, x):\n for k, range_values in self._range.items():\n for v in range_values:\n if (x >= v[0]) & (x <= v[1]):\n return k\n return self._default\n\n def update(self):\n if self.i.ready():\n self.o = self.i\n if self.o.data is not None:\n self.o.data = self.o.data.applymap(lambda x: self._discretize(x))\n","sub_path":"timeflux_dsp/nodes/squashing.py","file_name":"squashing.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"32750468","text":"#!/usr/bin/python\n\n\nimport argparse\nimport random\nimport ipaddr\nimport sqlite3\nfrom collections import namedtuple\nfrom datetime import timedelta, datetime\n\n\nCLIENTS = \"10.10.10.0/24\" # CIDR\nINTERVAL = 24*7 # hours\nSTEP = 10 # minutes\n\n\n\nclass TimeInterval(object):\n _epoch = datetime(1970,1,1)\n\n def __init__(self, interval, step):\n if not isinstance(interval, timedelta):\n interval = timedelta(hours=interval)\n if not isinstance(step, timedelta):\n step = timedelta(minutes=step)\n\n self.interval = interval\n self.step = step\n self.now = datetime.now()\n\n def __iter__(self):\n stop = self.now - self.interval\n while stop < self.now:\n yield int((stop - self._epoch).total_seconds())\n stop += self.step\n\nclass ClientBytes(object):\n def __init__(self):\n self.lastbytes = random.randint(0, 1024*1024*1024*3)\n\n def nextbytes(self):\n newbytes = max(0, self.lastbytes + random.randint(-1024*1024*500, 1024*1024*500))\n self.lastbytes = newbytes\n return newbytes\n \n\nRecord = namedtuple(\"Record\", [\"ip\", \"input\", \"output\", \"timestamp\"])\nClient = namedtuple(\"Client\", [\"input\", \"output\", \"ip\"])\n\n\ndef create_data(clients, times):\n data = []\n\n for timestamp in times:\n data.extend([Record(ip=c.ip, input=c.input.nextbytes(), output=c.output.nextbytes(), timestamp=timestamp) for c in clients])\n\n return data\n\n\ndef write_data(connection, data):\n input = \"INSERT INTO inbound (ip_dst, bytes, stamp_inserted, stamp_updated) VALUES (?, ?, ?, ?)\"\n output = \"INSERT INTO outbound (ip_src, bytes, stamp_inserted, stamp_updated) VALUES (?, ?, ?, ?)\"\n\n connection.executemany(input, [(r.ip, r.input, r.timestamp, r.timestamp) for r in data])\n connection.executemany(output, [(r.ip, r.output, r.timestamp, r.timestamp) for r in data])\n\n connection.commit()\n\n\nparser = argparse.ArgumentParser(description='Insert example data.')\n\nparser.add_argument('clients', metavar='C', type=str,\n help='CIDR describing the clients')\nparser.add_argument(\"--interval\", type=int, help=\"Interval to generate data for in HOURS\")\nparser.add_argument(\"--step\", type=int, help=\"Step within the interval in MINUTES\")\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n clients = [Client(ip=str(ip), input=ClientBytes(), output=ClientBytes()) for ip in ipaddr.IPNetwork(args.clients).iterhosts()]\n\n connection = sqlite3.connect('example.db')\n data = create_data(clients, TimeInterval(args.interval, args.step))\n write_data(connection, data)\n","sub_path":"test/example_db/fill_data.py","file_name":"fill_data.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"278179486","text":"from __future__ import print_function\nimport os\nimport sys\n\nimport torch\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torch.nn.init as init\n\nfrom tensorboardX import SummaryWriter\n\nfrom detector.common.utils.timer import Timer\nfrom detector.common.functions.detection import Detect\nfrom detector.common.models.model_builder import create_model\nfrom detector.train.dataset.dataset_factory import load_data\nfrom detector.train.losses import FocalLoss\n\n\nclass Solver(object):\n \"\"\"\n A wrapper class for the training process\n \"\"\"\n def __init__(self, cfg):\n self.cfg = cfg\n\n # Load data\n print('===> Loading data')\n self.train_loader = load_data(cfg.DATASET, 'train') if 'train' in cfg.PHASE else None\n self.eval_loader = load_data(cfg.DATASET, 'eval') if 'eval' in cfg.PHASE else None\n self.test_loader = load_data(cfg.DATASET, 'test') if 'test' in cfg.PHASE else None\n self.visualize_loader = load_data(cfg.DATASET, 'visualize') if 'visualize' in cfg.PHASE else None\n\n # Build model\n print('===> Building model')\n self.model, self.priorbox = create_model(cfg.MODEL)\n self.priors = self.priorbox.forward()\n self.detector = Detect(cfg.POST_PROCESS, self.priors)\n\n # Print the model architecture and parameters\n #print('Model architectures:\\n{}\\n'.format(self.model))\n #print('Trainable scope: {}'.format(cfg.TRAIN.TRAINABLE_SCOPE))\n print(cfg)\n trainable_param = self.model.parameters() # self.trainable_param(cfg.TRAIN.TRAINABLE_SCOPE)\n\n # Utilize GPUs for computation\n self.use_gpu = torch.cuda.is_available()\n if self.use_gpu:\n print('Utilize GPUs for computation')\n print('Number of GPU available', self.use_gpu)\n self.priors.cuda()\n self.model = torch.nn.DataParallel(self.model.cuda(), device_ids=list(range(cfg.NGPU)))\n #self.model = self.model.cuda()\n\n self.optimizer = self.configure_optimizer(trainable_param)\n self.exp_lr_scheduler = self.configure_lr_scheduler(self.optimizer)\n self.max_epochs = cfg.TRAIN.MAX_EPOCHS\n\n # metric\n self.criterion = FocalLoss(cfg.MATCHER, self.priors, self.use_gpu)\n\n # Set the logger\n self.writer = SummaryWriter(log_dir=cfg.LOG_DIR)\n self.test_writer = SummaryWriter(log_dir=os.path.join(cfg.LOG_DIR, \"test\"))\n self.output_dir = cfg.EXP_DIR\n self.checkpoint = cfg.RESUME_CHECKPOINT\n self.checkpoint_prefix = cfg.CHECKPOINTS_PREFIX\n\n def save_checkpoints(self, epochs, iters=None):\n if not os.path.exists(self.output_dir):\n os.makedirs(self.output_dir)\n if iters:\n filename = self.checkpoint_prefix + '_epoch_{:d}_iter_{:d}'.format(epochs, iters) + '.pth'\n else:\n filename = self.checkpoint_prefix + '_epoch_{:d}'.format(epochs) + '.pth'\n filename = os.path.join(self.output_dir, filename)\n torch.save(self.model.module.state_dict(), filename)\n with open(os.path.join(self.output_dir, 'checkpoint_list.txt'), 'a') as f:\n f.write('epoch {epoch:d}: {filename}\\n'.format(epoch=epochs, filename=filename))\n print('Wrote snapshot to: {:s}'.format(filename))\n\n # TODO: write relative cfg under the same page\n\n def resume_checkpoint(self, resume_checkpoint):\n if resume_checkpoint == '' or not os.path.isfile(resume_checkpoint):\n print((\"=> no checkpoint found at '{}'\".format(resume_checkpoint)))\n return False\n print((\"=> loading checkpoint '{:s}'\".format(resume_checkpoint)))\n checkpoint = torch.load(resume_checkpoint)\n\n # remove the module in the parrallel model\n if 'module.' in list(checkpoint.items())[0][0]:\n pretrained_dict = {'.'.join(k.split('.')[1:]): v for k, v in list(checkpoint.items())}\n checkpoint = pretrained_dict\n\n resume_scope = self.cfg.TRAIN.RESUME_SCOPE\n # extract the weights based on the resume scope\n if resume_scope != '':\n pretrained_dict = {}\n for k, v in list(checkpoint.items()):\n for resume_key in resume_scope.split(','):\n if resume_key in k:\n pretrained_dict[k] = v\n break\n checkpoint = pretrained_dict\n\n pretrained_dict = {k: v for k, v in checkpoint.items() if k in self.model.state_dict()}\n\n checkpoint = self.model.state_dict()\n\n unresume_dict = set(checkpoint)-set(pretrained_dict)\n if len(unresume_dict) != 0:\n print(\"=> UNResume weigths:\")\n print(unresume_dict)\n\n checkpoint.update(pretrained_dict)\n\n return self.model.load_state_dict(checkpoint)\n\n def find_previous(self):\n if not os.path.exists(os.path.join(self.output_dir, 'checkpoint_list.txt')):\n return False\n with open(os.path.join(self.output_dir, 'checkpoint_list.txt'), 'r') as f:\n lineList = f.readlines()\n epoches, resume_checkpoints = [list() for _ in range(2)]\n for line in lineList:\n epoch = int(line[line.find('epoch ') + len('epoch '): line.find(':')])\n checkpoint = line[line.find(':') + 2:-1]\n epoches.append(epoch)\n resume_checkpoints.append(checkpoint)\n return epoches, resume_checkpoints\n\n def weights_init(self, m):\n for key in m.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key:\n init.kaiming_normal(m.state_dict()[key], mode='fan_out')\n if 'bn' in key:\n m.state_dict()[key][...] = 1\n elif key.split('.')[-1] == 'bias':\n m.state_dict()[key][...] = 0\n\n def initialize(self):\n if self.checkpoint:\n print('Loading initial model weights from {:s}'.format(self.checkpoint))\n self.resume_checkpoint(self.checkpoint)\n\n start_epoch = 0\n return start_epoch\n\n def trainable_param(self, trainable_scope):\n for param in self.model.parameters():\n param.requires_grad = False\n\n trainable_param = []\n for module in trainable_scope.split(','):\n if hasattr(self.model, module):\n # print(getattr(self.model, module))\n for param in getattr(self.model, module).parameters():\n param.requires_grad = True\n trainable_param.extend(getattr(self.model, module).parameters())\n\n return trainable_param\n\n def train_model(self):\n previous = self.find_previous()\n if previous:\n start_epoch = previous[0][-1]\n self.resume_checkpoint(previous[1][-1])\n else:\n start_epoch = self.initialize()\n\n # export graph for the model, onnx always not works\n # self.export_graph()\n\n # warm_up epoch\n warm_up = self.cfg.TRAIN.LR_SCHEDULER.WARM_UP_EPOCHS\n for epoch in iter(range(start_epoch+1, self.max_epochs+1)):\n #learning rate\n sys.stdout.write('\\rEpoch {epoch:d}/{max_epochs:d}:\\n'.format(epoch=epoch, max_epochs=self.max_epochs))\n if epoch > warm_up:\n self.exp_lr_scheduler.step(epoch-warm_up)\n if 'train' in self.cfg.PHASE:\n self.train_epoch(self.model, self.train_loader, self.optimizer, self.criterion, self.writer, epoch, self.use_gpu)\n if 'test' in self.cfg.PHASE:\n self.test_epoch(self.model, self.test_loader, self.criterion, self.test_writer, epoch, self.use_gpu)\n\n if epoch % self.cfg.TRAIN.CHECKPOINTS_EPOCHS == 0:\n self.save_checkpoints(epoch)\n\n\n def train_epoch(self, model, data_loader, optimizer, criterion, writer, epoch, use_gpu):\n model.train()\n\n epoch_size = len(data_loader)\n batch_iterator = iter(data_loader)\n\n loc_loss = 0\n conf_loss = 0\n _t = Timer()\n\n for iteration in iter(range((epoch_size))):\n images, targets = next(batch_iterator)\n if use_gpu:\n images = images.cuda()\n targets = [anno.cuda() for anno in targets]\n _t.tic()\n # forward\n out = model(images, phase='train')\n\n # backprop\n optimizer.zero_grad()\n try:\n loss_l, loss_c = criterion(out, targets)\n except RuntimeError:\n continue\n\n # some bugs in coco train2017. maybe the annonation bug.\n if loss_l.item() == float(\"Inf\"):\n continue\n\n loss = loss_l + loss_c\n loss.backward()\n optimizer.step()\n time = _t.toc()\n loc_loss += loss_l.item()\n conf_loss += loss_c.item()\n\n # log per iter\n log = '\\r==>Train: || {iters:d}/{epoch_size:d} in {time:.3f}s [{prograss}] || loc_loss: {loc_loss:.4f} cls_loss: {cls_loss:.4f}\\r'.format(\n prograss='#'*int(round(10*iteration/epoch_size)) + '-'*int(round(10*(1-iteration/epoch_size))), iters=iteration, epoch_size=epoch_size,\n time=time, loc_loss=loss_l.item(), cls_loss=loss_c.item())\n\n sys.stdout.write(log)\n sys.stdout.flush()\n\n # log per epoch\n sys.stdout.write('\\r')\n sys.stdout.flush()\n lr = optimizer.param_groups[0]['lr']\n log = '\\r==>Train: || Total_time: {time:.3f}s || loc_loss: {loc_loss:.4f} conf_loss: {conf_loss:.4f} || lr: {lr:.6f}\\n'.format(lr=lr,\n time=_t.total_time, loc_loss=loc_loss/epoch_size, conf_loss=conf_loss/epoch_size)\n sys.stdout.write(log)\n sys.stdout.flush()\n\n # log for tensorboard\n writer.add_scalar('Train/loc_loss', loc_loss/epoch_size, epoch)\n writer.add_scalar('Train/conf_loss', conf_loss/epoch_size, epoch)\n writer.add_scalar('Train/lr', lr, epoch)\n\n\n def test_epoch(self, model, data_loader, criterion, writer, epoch, use_gpu):\n model.eval()\n\n epoch_size = len(data_loader)\n batch_iterator = iter(data_loader)\n\n loc_loss = 0\n conf_loss = 0\n _t = Timer()\n\n with torch.no_grad():\n for iteration in iter(range((epoch_size))):\n images, targets = next(batch_iterator)\n if use_gpu:\n images = images.cuda()\n targets = [anno.cuda() for anno in targets]\n _t.tic()\n # forward\n out = model(images, phase='train')\n\n try:\n loss_l, loss_c = criterion(out, targets)\n except RuntimeError:\n continue\n\n # some bugs in coco train2017. maybe the annonation bug.\n if loss_l.item() == float(\"Inf\"):\n continue\n\n time = _t.toc()\n loc_loss += loss_l.item()\n conf_loss += loss_c.item()\n\n # log per iter\n log = '\\r==>Test: || {iters:d}/{epoch_size:d} in {time:.3f}s [{prograss}] || loc_loss: {loc_loss:.4f} cls_loss: {cls_loss:.4f}\\r'.format(\n prograss='#' * int(round(10 * iteration / epoch_size)) + '-' * int(\n round(10 * (1 - iteration / epoch_size))), iters=iteration, epoch_size=epoch_size,\n time=time, loc_loss=loss_l.item(), cls_loss=loss_c.item())\n\n sys.stdout.write(log)\n sys.stdout.flush()\n\n # log per epoch\n sys.stdout.write('\\r')\n sys.stdout.flush()\n log = '\\r==>Train: || Total_time: {time:.3f}s || loc_loss: {loc_loss:.4f} conf_loss: {conf_loss:.4f}\\n'.format(\n time=_t.total_time, loc_loss=loc_loss / epoch_size, conf_loss=conf_loss / epoch_size)\n sys.stdout.write(log)\n sys.stdout.flush()\n\n # log for tensorboard\n writer.add_scalar('Train/loc_loss', loc_loss / epoch_size, epoch)\n writer.add_scalar('Train/conf_loss', conf_loss / epoch_size, epoch)\n\n\n def configure_optimizer(self, trainable_param):\n cfg = self.cfg.TRAIN.OPTIMIZER\n if cfg.OPTIMIZER == 'sgd':\n optimizer = optim.SGD(trainable_param,\n lr=cfg.LEARNING_RATE,\n momentum=cfg.MOMENTUM,\n weight_decay=cfg.WEIGHT_DECAY)\n elif cfg.OPTIMIZER == 'rmsprop':\n optimizer = optim.RMSprop(trainable_param,\n lr=cfg.LEARNING_RATE,\n momentum=cfg.MOMENTUM,\n alpha=cfg.MOMENTUM_2,\n eps=cfg.EPS,\n weight_decay=cfg.WEIGHT_DECAY)\n elif cfg.OPTIMIZER == 'adam':\n optimizer = optim.Adam(trainable_param,\n lr=cfg.LEARNING_RATE,\n betas=(cfg.MOMENTUM, cfg.MOMENTUM_2),\n eps=cfg.EPS,\n weight_decay=cfg.WEIGHT_DECAY)\n else:\n AssertionError('optimizer can not be recognized.')\n return optimizer\n\n\n def configure_lr_scheduler(self, optimizer):\n cfg = self.cfg.TRAIN.LR_SCHEDULER\n if cfg.SCHEDULER == 'step':\n scheduler = lr_scheduler.StepLR(optimizer, step_size=cfg.STEPS[0], gamma=cfg.GAMMA)\n elif cfg.SCHEDULER == 'multi_step':\n scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=cfg.STEPS, gamma=cfg.GAMMA)\n elif cfg.SCHEDULER == 'exponential':\n scheduler = lr_scheduler.ExponentialLR(optimizer, gamma=cfg.GAMMA)\n elif cfg.SCHEDULER == 'SGDR':\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=cfg.MAX_EPOCHS)\n else:\n AssertionError('scheduler can not be recognized.')\n return scheduler\n\n\ndef train_model(cfg):\n s = Solver(cfg)\n s.train_model()\n return True\n","sub_path":"detector_back/worker/detector/detector/train/ssds_train.py","file_name":"ssds_train.py","file_ext":"py","file_size_in_byte":14130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"421877026","text":"\"\"\"\nmyauth.view\n\"\"\"\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django import forms\n\nfrom django.http import HttpResponse, HttpResponseRedirect\n\nfrom django.template import RequestContext, loader\nfrom django.template.response import TemplateResponse\n\nfrom django.contrib.auth import login, REDIRECT_FIELD_NAME\nfrom django.contrib.auth.views import logout\n\nfrom django.views.generic.base import View\nfrom wkhtmltopdf.views import PDFTemplateResponse\n\n#from django.contrib.sites.shortcuts import get_current_site\n#from django.core.exceptions import ValidationError\n\nfrom problems.models import Subject, Category, Problem, Solve\n\nfrom myauth.forms import LoginForm\n\ndef index(request):\n #로그인되어있으면 바로 /probs/lists 로 보내기\n if request.user.is_authenticated() :\n return HttpResponseRedirect('/probs/')\n \n #임시로 문제 한게 긁어서 보내기..\n p = Problem.objects.filter(id=1)\n \n template = loader.get_template('myauth/index.html')\n context = RequestContext(request, {\n 'foo': 'bar',\n 'p' : p,\n })\n return HttpResponse(template.render(context))\n\n\"\"\"\n\n\"\"\"\ndef login_page(request):\n \n if request.method == \"POST\" :\n \n #form = LoginForm(request.POST) forms.Form 을 상속받은 폼클래스는 이렇게 하나 \n #AuthenticationForm을 상속받은 폼클래스는 이렇게 하면 안됨.\n #생성자가 전달 받는 인자의 순서가 다름\n #http://stackoverflow.com/questions/7297980/django-login-failing\n form = LoginForm(request, data=request.POST) \n \n #이 함수는 AuthenticationForm 의 is_valid함수로 내부적으로 유저가 있고 패스워드가 맞으면 True \n if form.is_valid() : \n #is_valid를 통과했으면 유저가 있고 패스워드도 맞다는 뜻 그러므로 로그인시키고\n #리다이렉트 시키면됨. \n login(request, form.get_user())\n redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME, '')) \n # Redirect to a success page.\n return HttpResponseRedirect(redirect_to)\n \n \n else : #GET\n form = LoginForm()\n \n context = {\n 'form':form\n }\n \n return TemplateResponse(request, 'myauth/login.html', context) \n\n \ndef logout_page(request):\n logout(request)\n return HttpResponseRedirect('/')\n \n\nclass MyPDFView(View):\n template='myauth/index.html'\n \n #임시로 문제 한게 긁어서 보내기..\n p = Problem.objects.filter(id=1)\n \n #template = loader.get_template('myauth/index.html')\n \n context = {\n 'foo': 'bar',\n 'p' : p,\n }\n #--javascript-delay 10000 --print-media-type --page-size A4 --dpi 300 -T 10mm -B 10mm -L 10mm -R 10mm\n def get(self, request):\n response = PDFTemplateResponse(request=request,\n template=self.template,\n filename=\"rp.pdf\",\n context= self.context,\n show_content_in_browser=False,\n cmd_options={'javascript-delay':15000, 'page-size':'A4', 'dpi': 300, 'print-media-type':True},\n )\n return response \n\n \n\n","sub_path":"myauth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"329173771","text":"# *_*coding:utf-8 *_*\nimport json\nfrom time import sleep\nfrom tkinter import Tk, ttk\nimport socket\nimport pandas as pd\n\nDICT_TRANS = {\"libere\": ('1', '2',0), \"nettoyage\": ('2', '0',1), \"checkin\": ('0', '1',-1), }\n\n\ndef print_str(input_str):\n print('called function : ' + input_str)\n return True\n\n\ndef trans(commande, num_room=0, num_bed=0, file_path='rec.csv'):\n try:\n assert commande in DICT_TRANS, 'commande not recgnized'\n\n state = DICT_TRANS[commande]\n rec = pd.read_csv(file_path)\n ls = rec[rec['num_room'] == num_room].values\n res = ls[0][3].split(' ')\n assert res[num_bed] == state[0], 'no bed available {} {}'.format(res[num_bed], state[0])\n ls[0][2] += state[2]\n res[num_bed] = state[1]\n ls[0][3] = ' '.join(res)\n rec[rec['num_room'] == num_room] = ls\n rec.to_csv(file_path, index=False)\n return 'True'\n except Exception as e:\n print(e)\n return 'False'\n\n\ndef occupe_bed(num_bed=0, num_room=0, file_path='rec.csv'):\n try:\n rec = pd.read_csv(file_path)\n ls = rec[rec['num_room'] == num_room].values\n res = ls[0][3].split(' ')\n assert ls[0][2] > 0 and res[num_bed] == '0', 'no bed available'\n ls[0][2] -= 1\n res[num_bed] = '1'\n ls[0][3] = ' '.join(res)\n rec[rec['num_room'] == num_room] = ls\n rec.to_csv(file_path, index=False)\n return 'True'\n except Exception as e:\n return 'False'\n\n\ndef libere_bed(num_room=0, num_bed=0, file_path='rec.csv'):\n try:\n rec = pd.read_csv(file_path)\n ls = rec[rec['num_room'] == num_room].values\n res = ls[0][3].split(' ')\n assert ls[0][2] < ls[0][1] and res[num_bed] == '1', 'bed available'\n ls[0][2] += 1\n res[num_bed] = '0'\n ls[0][3] = ' '.join(res)\n rec[rec['num_room'] == num_room] = ls\n rec.to_csv(file_path, index=False)\n return 'True'\n except Exception as e:\n print(e)\n return 'False'\n\n\ndef check_fun(input_str):\n return input_str in FUN_DICT\n\n\ndef load_table(file_path='rec.csv'):\n try:\n rec = pd.read_csv(file_path).to_json(orient='split', force_ascii=False)\n return rec\n except Exception as e:\n print(e)\n return 'False'\n\n\ndef display(string):\n res = json.loads(string)\n return res\n\n\ndef show_table(js):\n win = Tk()\n win.title('real-time situation')\n tree = ttk.Treeview(win) # 表格\n tree[\"columns\"] = js['columns']\n for head in js['columns']:\n tree.heading(head, text=head)\n for index in js['index']:\n tree.insert(\"\", index, text=str(index).zfill(3), values=js['data'][index]) # 插入数据,\n tree.pack()\n win.mainloop()\n\ndef ouvrir(a='1',HOST=\"192.168.1.21\",PORT=8090):\n BUFSIZE = 1024\n ADDR = (HOST, PORT)\n sock = socket.socket()\n try:\n sock.connect(ADDR)\n sock.sendall(a.encode('utf-8')) # 不要用send()\n recv_data = sock.recv(BUFSIZE)\n print(recv_data.decode('utf-8'))\n sock.close()\n except Exception as e:\n sock.close()\n\nFUN_DICT = {'print_str': print_str, 'occupe_bed': occupe_bed, 'libere_bed': libere_bed, 'info': load_table}\nif __name__==\"__main__\":\n ouvrir('1')\n quit()\n for i in range(10):\n print(\"the {} th connection\".format(i))\n ouvrir(str(i))\n# show_table(display(load_table()))\n# print(occupe_bed(int('0')))\n# print(libere_bed(1))\n\n# for terms in FUN_DICT:\n# print(terms)\n# print(check_fun('print_str'))\n","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"457093538","text":"#!/usr/bin/env python\n\nimport contextlib\nimport json\nimport os\nimport sys\nimport urllib.request\n\nURL = \"https://www.archlinux.org/mirrors/status/json/\"\n\n\ndef main():\n DATA = load_data(URL)\n\n synced_urls = set()\n for encapsulated_data in DATA[\"urls\"]:\n if is_valid(encapsulated_data):\n synced_urls.add(f\"Server = {encapsulated_data['url']}$repo/os/$arch\\n\")\n\n with open(\"/etc/pacman.d/mirrorlist\", \"w\") as mirror_file:\n for mirror_url in synced_urls:\n mirror_file.write(mirror_url)\n\n\ndef is_platform_linux() -> bool:\n \"\"\"\n Check if the running platform is linux.\n\n Returns\n -------\n bool\n True if the running platform is linux.\n \"\"\"\n return \"linux\" in sys.platform\n\n\ndef is_valid(url_info: dict) -> bool:\n \"\"\"\n Check if the tested dict is up to standarts.\n\n Which means that the values for the specific keys are:\n\n protocol: 'https'\n completion_pct: 1\n active: True\n\n Parameters\n ----------\n url_info : dict\n Dict mapping:\n - url : str\n - protocol : {'http', 'https', 'rsync'}\n - last_sync : datetime\n - completion_pct : float\n - delay : int\n - duration_avg : float\n - duration_stddev : float\n - score : float\n - active : bool\n - country : str\n - country_code : str\n - isos : bool\n - ipv4 : bool\n - ipv6 : bool\n - details : str\n\n Returns\n -------\n bool\n True if all the checks are passed.\n \"\"\"\n if url_info[\"protocol\"] != \"https\":\n return False\n if url_info[\"completion_pct\"] != 1:\n return False\n if not url_info[\"active\"]:\n return False\n return True\n\n\ndef load_data(url: str) -> dict:\n \"\"\"\n Load json data from a given URL.\n\n Parameters\n ----------\n url : str\n URL to fetch data from.\n\n Returns\n -------\n dict\n \"\"\"\n with contextlib.closing(urllib.request.urlopen(url)) as url_data:\n data = json.loads(url_data.read().decode())\n return data\n\n\nif __name__ == \"__main__\":\n if is_platform_linux():\n assert os.geteuid() == 0, \"Must run as root\"\n sys.exit(main())\n","sub_path":"updater.py","file_name":"updater.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"186672933","text":"\"\"\"\nFunctions about linked lists where the nodes are of the form\n\nclass ListNode(object):\n def __init__(self, val):\n self.val = val\n self.next = None\n\"\"\"\n\ndef reverse_list_iteratively(head):\n \"\"\"Reverse a linked list in an iterative manner\n\n The idea here is simple: for the current element, we want to change\n its 'next' pointer to point to the previous element. However, once\n we change this pointer, we lose track of the (old/original) next element,\n hence we need to store the original next element in a temporary variable.\n Likewise, we need to keep track of what is the previous element as we go,\n so we will use another variable for that as well\n \"\"\"\n\n # base case\n if not head:\n return None\n\n # both previous and next elements are initially None\n prev_node = None\n next_node = None\n\n # iterate through all the elements until the list is done\n while head:\n # save the pointer to the next node\n next_node = head.next\n # change the 'next' pointer of the current\n # element to point to the previous element\n head.next = prev_node\n # we no longer need the previous node! Make the\n # current node the previous node, as we will move forward\n prev_node = head\n # we updated the head element, move it to wherever the next_node points\n head = next_node\n\n # In our reversed list, prev_node holds the reversed head!\n # We stopped the iteration once head was None, thus prev_node\n # holds the last non-None element (aka the last element\n # of the original list)\n return prev_node\n\n\ndef reverse_list_recursively(head):\n \"\"\" Reverse a linked list recursively.\n\n At each point, he have two components, the current head, and then the\n rest of the list (pointed to by head.next). We call reverse_list_recursively\n for the rest of the list and we get back the pointer to the\n head or the reversed list. Now all we have to do is connect this reversed\n list to the head.\n\n |\n [head]-> | | REVERSED_SUBLIST | <-rev_head\n |\n\n if head.next is None, we don't need to revert anything, we are at the\n end of the list! So we should simply return head (base case).\n\n\n Notice that once we retrieve the (reversed) list, the last element should\n have a next pointer to None. This element was (originally) pointed to by\n head.next. We want to switch the last element to point to head. Thus we\n set head.next.next to head!!\n \"\"\"\n\n # base cases\n if not head: return None\n\n if not head.next:\n # we are at the end of the list! return 'head' as the\n # head of the reversed list!!\n return head\n\n # recursively reverse the list\n rev_head = reverse_list_recursively(head.next)\n # make the last element of the reversed list (originally pointed to by\n # head.next) to point to the current head!\n head.next.next = head\n # now head is the last element! make its 'next' None\n head.next = None\n\n # return the head for the reversed list\n return rev_head\n\ndef cycle_start(head):\n \"\"\"Given a linked list, return the node where the cycle begins. If there is\n no cycle, return None.\n\n This uses a very well known trick. We use a fast pointer and a slow pointer\n and if there is a cycle, the two will meet. Here, we use a hack and catch\n an Exception if None is accessed as a node, in which case there is no cycle\n \"\"\"\n\n try:\n slow_ptr = head.next\n fast_ptr = head.next.next\n while slow_ptr is not fast_ptr:\n slow_ptr = slow_ptr.next\n fast_ptr = fast_ptr.next.next\n except Exception:\n # definitely not a cycle! We dereferenced smth we shouldn't\n return None\n\n # slow_ptr is fast_ptr, slow_ptr.next is where the cycle begins\n return slow_ptr.next\n","sub_path":"basics/linked_lists.py","file_name":"linked_lists.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"371188606","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pymongo\nfrom configure import *\n\ndef plotSource(sourceNum):\n\n source= configure.SOURCES[sourceNum]\n\n print(\"Plotting %s\" % source[\"name\"])\n fig, ax = plt.subplots()\n fig.canvas.set_window_title(source[\"name\"])\n plt.title(source[\"name\"])\n\n fig.set_size_inches(20, 15)\n plt.xlabel('Time')\n plt.ylabel('Distance (meters)')\n\n df = merger.RTL_DATA[merger.RTL_DATA.Source == sourceNum]\n droneLog = merger.DRONE_LOGS[merger.DRONE_LOGS.Source == sourceNum]\n\n xs = [time for time, row in df.iterrows()]\n\n\n # Plot Altitude\n df.plot(ax=ax, use_index=True, y=\"Altitude\", color=\"blue\", label='Drone Altitude')\n\n ax.hlines(7.62, min(xs), max(xs), colors='k', linestyles='dashed' )\n ax.text(x=min(xs), y=8, s=\"25ft\", fontsize=20)\n\n\n def onclick(event):\n print('DATA Time:%i, Dist:%fm or %fft' %(mdates.num2epoch(event.xdata), event.ydata, event.ydata * 3.28084))\n\n fig.canvas.mpl_connect('button_press_event', onclick)\n\n plt.legend()\n\n graphbounds = min(0,df[\"Altitude\"].min()), max(df[\"Altitude\"].max(),60)\n\n print(\"Sugested offset min:%f\"%(-(df[\"Altitude\"].min()+source[\"altitude-adjust\"])))\n plt.ylim(graphbounds)\n plt.xlim(droneLog.iloc[0].name,droneLog.iloc[-1].name)\n plt.show()\n\n print()\n #plt.savefig(\"CAL_\"+sourceName+\".png\")\n fig.clf()\n\n\ndef loadDroneLog(file):\n print(\"Reading Drone Log %s\"%file)\n\n data = pd.read_csv(file)\n\n #Remove missing data on location\n listOfCols = ['Lat', 'Lon', 'Altitude']\n data[listOfCols] = data[listOfCols].replace(0, np.nan)\n data.dropna(subset=listOfCols, inplace=True)\n\n if len(data) == 0:\n print(\"Error: No drone data\")\n exit()\n\n #Set time as index\n data['Time'] = pd.to_datetime(data['Time']/1000.0, unit='s')\n data.set_index('Time', inplace=True)\n\n #Convert radians to degrees\n data[\"Lat\"] = np.degrees(data[\"Lat\"])\n data[\"Lon\"] = np.degrees(data[\"Lon\"])\n\n return data\n\n\ndef loadRtlLog(file):\n print(\"Reading RTL Log %s\"%file)\n\n data = pd.read_csv(file)\n\n #Remove missing data on location\n listOfCols = ['Frequency','Signal_Strength']\n data[listOfCols] = data[listOfCols].replace(0, np.nan)\n data.dropna(subset=listOfCols, inplace=True)\n\n if len(data) == 0:\n print(\"Error: No RTL data\")\n exit()\n\n #Set time as index\n data['Time'] = pd.to_datetime(data['Time'], unit='s')\n data.set_index('Time', inplace=True)\n\n return data\n\ndef merge():\n global RTL_DATA, DRONE_LOGS\n print(\"* Reading & Merging\")\n for index,source in enumerate(SOURCES):\n\n print(\"\\n[ %s ]\"%source['name'])\n\n folder = \"data/%s/\"%source[\"name\"]\n if not os.path.exists(folder):\n print(\">< Folder '%s' does not exist\"%folder)\n continue\n\n #Load Drone Log\n droneLog = loadDroneLog(folder+\"drone.log\")\n\n # Offset Altitude to real\n altOffset = droneLog[\"Altitude\"].min()\n print(\"Altitude Offset %f\" % altOffset)\n droneLog[\"Altitude\"] -= altOffset\n\n\n #Load RTL-SDR Data\n rtlLog = loadRtlLog(folder +\"channels.csv\")\n\n\n # Label Source\n droneLog[\"Source\"] = index\n droneLog[\"Location\"] = source[\"location\"]\n droneLog[\"Vehicle\"] = source[\"vehicle\"]\n droneLog[\"Device\"] = source[\"device\"]\n\n #Merge Logs\n dlCopy = droneLog.reindex(rtlLog.index, method='nearest')\n trialData = pd.concat([dlCopy, rtlLog], axis=1)\n\n\n #Set Global constants\n RTL_DATA = RTL_DATA.append(trialData)\n DRONE_LOGS = DRONE_LOGS.append(droneLog)\n\n\n\n print(\"\\nSorting\")\n RTL_DATA.sort_index(inplace=True)\n DRONE_LOGS.sort_index(inplace=True)\n\n print(\"* Merge Complete!\")\n\ndef save():\n print(\"Saving Result...\")\n merger.RTL_DATA.to_csv(\"results.csv\")","sub_path":"plugins/RSSI Loader/merger.py","file_name":"merger.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"399595798","text":"from fastapi import APIRouter\nfrom database import Global\n\nrouter = APIRouter(\n prefix=\"/vendor\",\n tags=[\"vendor\"],\n responses={404: {\"description\": \"Not found\"}}\n)\n\ncur = Global.cur\n\n\n@router.get('/')\ndef get_vendors():\n res = []\n cur.execute(\"select * from Vendor\")\n for ID, name, phone, address, email in cur:\n res.append({\n 'id': ID,\n 'name': name,\n 'phone': phone,\n 'email': email,\n 'address': address\n })\n return {\n 'data': res,\n 'key': ['ID', 'Name', 'Phone', 'Email', 'Address']\n }\n\n\n@router.get('/dashboard/{pk}')\ndef get_doctor_info(pk):\n cur.execute(f\"select * from VendorDrugInfo where vendorID={pk}\")\n res = []\n for venID, price, orderTime, supplyTime, drugName, category in cur:\n res.append({\n 'id': venID,\n 'price': price,\n 'orderTime': orderTime,\n 'supplyTime': supplyTime,\n 'drugName': drugName,\n 'category': category,\n })\n return {\n 'data': res,\n 'key': ['ID', 'Price', 'Order Time', 'Supply Time', 'Drug Name', 'Category']\n }\n\n\n@router.get('/{pk}')\ndef vendor_profile(pk):\n cur.execute(f\"select name from Vendor where vendorID={pk}\")\n for name in cur:\n return {\n 'id': pk,\n 'name': name\n }\n","sub_path":"hyacinthBE/routers/vendor.py","file_name":"vendor.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"198037947","text":"#!/usr/bin/env python3\n\"\"\"\nthe code is designed for collecting and sending data of pizoelectric vibration sensor using RPi\nand thingspeak cloud, ADS1115 adc is used. Data is update in my channel\n\"\"\"\nimport http.client as http \nimport urllib\nimport board\nimport busio\nimport adafruit_ads1x15.ads1115 as ADS\nfrom adafruit_ads1x15.analog_in import AnalogIn\n\ni2c = busio.I2C(board.SCL, board.SDA)\nads = ADS.ADS1115(i2c)\nchan = AnalogIn(ads, ADS.P0) # sensor input connected in pin0\nvibration = chan.value # reading the value of senosr\nkey = \"ABCD\" # API Key here\n\ndef pizo_sensor():\n while True:\n params = urllib.parse.urlencode({'field1': vibration, 'key':key }) \n headers = {\"Content-typZZe\": \"application/x-www-form-urlencoded\",\"Accept\": \"text/plain\"}\n conn = http.HTTPConnection(\"api.thingspeak.com:80\")\n try:\n conn.request(\"POST\", \"/update\", params, headers)\n response = conn.getresponse()\n print(vibration)\n print(response.status, response.reason)\n data = response.read()\n conn.close()\n except:\n print(\"connection failed\")\n break\nif __name__ == \"__main__\":\n while True:\n pizo_sensor()","sub_path":"pizoelectric_sensor.py","file_name":"pizoelectric_sensor.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"555190205","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\r\nfrom __future__ import print_function\r\nimport torch\r\nimport copy\r\nimport torch.nn.functional as F\r\nfrom torch import nn\r\nfrom .gradient_scalar_layer import GradientScalarLayer\r\nfrom pod.utils.registry_factory import MODULE_ZOO_REGISTRY\r\nfrom .loss import make_ins_heads_loss_evaluator\r\nfrom .loss import consistency_loss\r\nfrom.loss import gcn_adaptive_loss\r\nimport pdb\r\nfrom pod.plugins.da_faster.models.heads.gcn.models import GCN\r\nfrom pod.plugins.da_faster.models.heads.gcn.utils import get_adj\r\n\r\n__all__ = ['insDomainAdaptationModule']\r\nclass DAInsHead(nn.Module):\r\n \"\"\"\r\n Adds a simple Instance-level Domain Classifier head\r\n \"\"\"\r\n\r\n def __init__(self, in_channels):\r\n \"\"\"\r\n Arguments:\r\n in_channels (int): number of channels of the input feature\r\n \"\"\"\r\n super(DAInsHead, self).__init__()\r\n\r\n self.fc1_da = nn.Linear(in_channels, 1024)\r\n self.fc2_da = nn.Linear(1024, 1024)\r\n self.fc3_da = nn.Linear(1024, 1)\r\n for l in [self.fc1_da, self.fc2_da]:\r\n nn.init.normal_(l.weight, std=0.01)\r\n nn.init.constant_(l.bias, 0)\r\n nn.init.normal_(self.fc3_da.weight, std=0.05)\r\n nn.init.constant_(self.fc3_da.bias, 0)\r\n\r\n def forward(self, x):\r\n\r\n x = F.relu(self.fc1_da(x))\r\n x = F.dropout(x, p=0.5, training=self.training)\r\n\r\n x = F.relu(self.fc2_da(x))\r\n x = F.dropout(x, p=0.5, training=self.training)\r\n\r\n x = self.fc3_da(x)\r\n return x\r\n\r\n\r\n@MODULE_ZOO_REGISTRY.register('da_ins_head')\r\n\r\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\r\nclass insDomainAdaptationModule(torch.nn.Module):\r\n \"\"\"\r\n Module for Domain Adaptation Component. Takes feature maps from the backbone and instance\r\n feature vectors, domain labels and proposals. Works for both FPN and non-FPN.\r\n \"\"\"\r\n\r\n def __init__(self,inplanes, cfg):\r\n super(insDomainAdaptationModule, self).__init__()\r\n\r\n self.cfg = copy.deepcopy(cfg)\r\n self.prefix = 'InsHead'\r\n # stage_index = 4\r\n # stage2_relative_factor = 2 ** (stage_index - 1)\r\n # res2_out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS\r\n # num_ins_inputs = cfg.MODEL.ROI_BOX_HEAD.MLP_HEAD_DIM if cfg.MODEL.BACKBONE.CONV_BODY.startswith('V') else res2_out_channels * stage2_relative_factor\r\n \r\n # self.resnet_backbone = cfg.MODEL.BACKBONE.CONV_BODY.startswith('R')\r\n # self.avgpool = nn.AvgPool2d(kernel_size=7, stride=7)\r\n self.ins_weight = cfg['ins_head_weight']\r\n if self.ins_weight>0:\r\n self.consist_weight=cfg['da_consist_weight']\r\n self.grl_ins = GradientScalarLayer(-1.0*cfg['ins_grl_weight'])\r\n self.inshead = DAInsHead(inplanes)\r\n self.grl_ins_consist = GradientScalarLayer(1.0 * cfg['ins_grl_weight'])\r\n self.loss_evaluator = make_ins_heads_loss_evaluator(cfg)\r\n self.consistency_loss=consistency_loss\r\n self.domain_on = cfg['domain_on']\r\n if self.domain_on:\r\n self.RCNN_adapt_feat = nn.Linear(inplanes, 64)\r\n nn.init.normal_(self.RCNN_adapt_feat.weight, std=0.01)\r\n nn.init.constant_(self.RCNN_adapt_feat.bias, 0)\r\n\r\n # self.resnet_backbone=cfg['res_no_fpn']\r\n self.gcn_adaptive_loss=gcn_adaptive_loss\r\n\r\n def forward(self, input):\r\n \"\"\"\r\n Arguments:\r\n img_features (list[Tensor]): features computed from the images that are\r\n used for computing the predictions.\r\n da_ins_feature (Tensor): instance-level feature vectors\r\n da_ins_labels (Tensor): domain labels for instance-level feature vectors\r\n targets (list[BoxList): ground-truth boxes present in the image (optional)\r\n\r\n Returns:\r\n losses (dict[Tensor]): the losses for the model during training. During\r\n testing, it is an empty dict.\r\n \"\"\"\r\n if self.training:\r\n batch_size=1\r\n pooled_feature=input['ins_feature'] #1024 2048\r\n source_feature=input['source_ins_feature'] #256 2048\r\n target_feature=input['target_ins_feature'] #256 2048\r\n # rois=input['dt_bboxes']\r\n # print(rois.shape) #2097 7\r\n source_cls_prob = input['source_cls_pred'] #256 2\r\n tgt_cls_prob = input['target_cls_pred'] #256 2\r\n source_rois=input['source_roi']\r\n tgt_rois=input['target_roi']\r\n num_proposal=source_rois.size(0)\r\n num_proposal2=tgt_rois.size(0)\r\n # if self.resnet_backbone:\r\n # da_ins_feature = self.avgpool(da_ins_feature)\r\n\r\n # pdb.set_trace()\r\n if self.ins_weight > 0:\r\n da_ins_feature = pooled_feature.view(pooled_feature.size(0), -1)\r\n da_ins_labels=input['ins_domain_label']\r\n\r\n ins_grl_consist_fea = self.grl_ins_consist(da_ins_feature)\r\n ins_grl_fea = self.grl_ins(da_ins_feature)\r\n\r\n da_ins_consist_features = self.inshead(ins_grl_consist_fea)\r\n da_ins_features = self.inshead(ins_grl_fea) #[N,1]\r\n da_ins_loss = self.loss_evaluator(\r\n da_ins_features, da_ins_labels\r\n )\r\n da_ins_loss = self.ins_weight * da_ins_loss\r\n if self.consist_weight>0:\r\n da_ins_consist_features = da_ins_consist_features.sigmoid()\r\n da_img_feature = input['img_grl_feature']\r\n\r\n consistency_loss = self.consistency_loss(da_img_feature, da_ins_consist_features, da_ins_labels,\r\n size_average=True)\r\n consistency_loss=self.consist_weight*consistency_loss\r\n return {\r\n self.prefix + '.da_loss': da_ins_loss,\r\n self.prefix+'.consist_loss':consistency_loss}\r\n else:\r\n return {self.prefix + '.da_loss': da_ins_loss}\r\n\r\n else:\r\n if self.domain_on:\r\n\r\n source_output = source_rois.new(batch_size, num_proposal, 5).zero_()\r\n source_output[0]=source_rois\r\n # source_output[0, :num_proposal, 1:] = source_rois\r\n target_output = tgt_rois.new(batch_size, num_proposal2, 5).zero_()\r\n target_output[0] =tgt_rois\r\n source_feature=self.RCNN_adapt_feat(source_feature)\r\n target_feature=self.RCNN_adapt_feat(target_feature)\r\n RCNN_loss_intra, RCNN_loss_inter = self.gcn_adaptive_loss(source_feature, source_cls_prob, source_output,target_feature,\r\n tgt_cls_prob, target_output, batch_size)\r\n\r\n # pdb.set_trace()\r\n return {self.prefix+'.intra_loss':RCNN_loss_intra,\r\n self.prefix + '.inter_loss': RCNN_loss_inter,\r\n }\r\n else:\r\n return {}","sub_path":"ubteacher/modeling/da_ins_heads.py","file_name":"da_ins_heads.py","file_ext":"py","file_size_in_byte":7227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"262632036","text":"import psycopg2\nimport psycopg2.extras\n\n\nclass Connection:\n\n def __init__(self, database, user):\n connection = psycopg2.connect(database=database, user=user)\n self.__cursor = connection.cursor(\n cursor_factory=psycopg2.extras.RealDictCursor)\n\n def query(self, query):\n self.__cursor.execute(query)\n return self\n\n def fetch_all(self):\n return self.__cursor.fetchall()\n\n def fetch_one(self):\n return self.__cursor.fetchone()\n\n\nif __name__ == '__main__':\n db = Connection('dvdrental', 'rodgers')\n results = db.query(\"\"\"\n SELECT name, COUNT(DISTINCT f.film_id ) FROM rental r\n JOIN inventory i ON (r.inventory_id=i.inventory_id)\n JOIN film f ON (f.film_id=i.film_id)\n JOIN film_category fc ON (fc.film_id=f.film_id)\n JOIN category c ON (c.category_id=fc.category_id)\n GROUP BY name ORDER BY COUNT DESC\"\"\").fetch_all()\n for result in results:\n print(\"Category: {name}\\nMovies: {count}\".format(**result))\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"481955915","text":"\"\"\"Functions that create and load NFC classification datasets.\"\"\"\n\n\nfrom __future__ import print_function\n\nfrom collections import defaultdict\nimport itertools\nimport os.path\nimport random\n\nimport numpy as np\n\nfrom vesper.archive.archive import Archive\n\n\n_CSV_FILE_NAME = 'clips.csv'\n\n\ndef create_clip_dataset(\n archive_dir_path, dataset_dir_path, dataset_size, clip_class_names,\n clip_class_fractions=None):\n \n # TODO: Balance counts from different stations.\n # TODO: Filter by station and date.\n # TODO: Raise an exception if dataset directory does not exist or\n # is not empty.\n \n if clip_class_fractions is None:\n n = len(clip_class_names)\n clip_class_fractions = np.ones(n) / n\n \n counts = np.array(np.round(clip_class_fractions * dataset_size),\n dtype='int')\n \n archive = Archive.open(archive_dir_path)\n file_name_lists = []\n \n for name, count in zip(clip_class_names, counts):\n \n print('getting clips of class \"{:s}\"...'.format(name))\n clips = _get_clips(archive, name, count)\n \n print('creating clip files for class \"{:s}\"...'.format(name))\n file_names = _create_clip_files(clips, dataset_dir_path)\n \n file_name_lists.append(file_names)\n \n print('creating csv file...')\n _create_csv_file(file_name_lists, dataset_dir_path)\n \n \ndef _create_csv_file(file_name_lists, dataset_dir_path):\n \n line_lists = [_create_csv_line_list(l, i)\n for i, l in enumerate(file_name_lists)]\n \n lines = list(itertools.chain(*line_lists))\n lines.sort()\n \n file_path = os.path.join(dataset_dir_path, _CSV_FILE_NAME)\n with open(file_path, 'w') as file_:\n file_.writelines(lines)\n \n \ndef _create_csv_line_list(file_names, class_num):\n class_num = ',' + str(class_num) + '\\n'\n return [name + class_num for name in file_names]\n\n\ndef _get_clips(archive, clip_class_name, num_clips):\n \n clips = archive.get_clips(clip_class_name=clip_class_name)\n \n # TODO: Issue a warning here rather than raising an exception?\n if num_clips > len(clips):\n raise ValueError(\n ('Cannot create dataset with {:d} \"{:s}\" clips, since archive '\n 'contains only {:d}.').format(\n num_clips, clip_class_name, len(clips)))\n \n _show_station_counts(clips)\n \n return random.sample(clips, num_clips)\n\n\ndef _show_station_counts(clips):\n counts = defaultdict(int)\n for clip in clips:\n counts[clip.station_name] += 1\n keys = counts.keys()\n keys.sort()\n threshold = 0\n keys = [key for key in keys if counts[key] >= threshold]\n for i, key in enumerate(keys):\n print(i, key, counts[key])\n print()\n \n \ndef _create_clip_files(clips, dataset_dir_path):\n return [_create_clip_file(clip, dataset_dir_path) for clip in clips]\n\n\ndef _create_clip_file(clip, dataset_dir_path):\n file_name = _create_clip_file_name(\n clip.station_name, clip.detector_name, clip.time)\n# file_path = os.path.join(dataset_dir_path, file_name)\n # TODO: Create the file.\n return file_name\n\n\n_CLIP_FILE_NAME_EXTENSION = '.wav'\n\n\n# TODO: This is redundant with function of same name in `Archive`. Fix this.\ndef _create_clip_file_name(station_name, detector_name, clip_time):\n millisecond = int(round(clip_time.microsecond / 1000.))\n time = clip_time.strftime('%Y-%m-%d_%H.%M.%S') + \\\n '.{:03d}'.format(millisecond)\n return '{:s}_{:s}_{:s}{:s}'.format(\n station_name, detector_name, time, _CLIP_FILE_NAME_EXTENSION)\n\n\ndef load_dataset(dir_path):\n pass\n","sub_path":"src/vesper/classification/clip_dataset.py","file_name":"clip_dataset.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"461523058","text":"# Eksempel på grensesnitt fra Python rammeverket: Iterator.\n#\n# Objekter av en klasse som implementerer Iterator grensesnittet kan brukes i en for-løkke for å behandle alle\n# elementene i den.\n#\n# Eksempel: En klasse som representerer en geometrisk rekke. tall_nummer_n = start*base^n\nclass Rekke:\n def __init__(self, start, base, antall):\n self.start = start\n self.base = base\n self.antall = antall\n self.k = 0\n\n # Implementerer metode fra Iterator grensesnittet. Denne skal lage og returnere en iterator over rekka.\n def __iter__(self):\n return RekkeIterator(self)\n\n\n# Iterator klasse for rekke. Tar inn en referanse til rekka den skal iterere over i konstruktøren\nclass RekkeIterator:\n def __init__(self, rekke):\n self.rekke = rekke\n self.k = 0\n\n # Implementerer metode fra Iterator grensesnittet. For iteratoren skal denne alltid returnere objektet selv.\n def __iter__(self):\n return self\n\n # Implementerer metode fra Iterator grensesnittet. Denne skal returnere neste element, eller lage\n # StopIteration exception når det ikke er flere elementer igjen.\n def __next__(self):\n if self.k >= self.rekke.antall:\n raise StopIteration\n verdi = self.rekke.start*(self.rekke.base**self.k)\n self.k += 1\n return verdi\n\n\n# Demonstrerer bruken av rekka og iteratoren.\nif __name__ == \"__main__\":\n rekka = Rekke(1, 0.5, 15)\n for tall in rekka:\n print(tall)\n for tall in rekka:\n print(tall)\n","sub_path":"polymorfisme/rekke.py","file_name":"rekke.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"633022968","text":"# Data structures & algorithms: Ex. 1.21\n'''\nWrite a Python program that repeatedly reads lines\nfrom standard input until an EOFError is raised,\nand then outputs those lines in reverse order\n(a user can indicate end of input by typing ctrl-D).\n'''\n\n\ndef get_input():\n data = []\n print('Enter any number of lines. End with ctrl-D: ')\n while True:\n try:\n data.append(input())\n except EOFError:\n return data\n\n\ndef print_data(data):\n for e in data:\n print(e)\n\n\ndata = get_input()\ndata.reverse()\nprint('Your reversed input:')\nprint_data(data)\n","sub_path":"Ch. 1 - Python Primer/1.21.py","file_name":"1.21.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"513923999","text":"# Storing Data\nimport json\n\n# saves numbers list to a new file!\nnumbers = [2, 3, 5, 7, 11, 13]\nfilename = '10_numbers.json'\nwith open(filename, 'w') as file_obj:\n json.dump(numbers, file_obj)\n\n# load the file and read the list!\nwith open(filename, 'r') as saved_file:\n saved_numbers = json.load(saved_file)\nprint(saved_numbers)\n\n\n# Saving and Reading User-Generated Data\n\n# save\nusername = input('What is your name m8? ')\nuser_file = '10_username.json'\nwith open(user_file, 'w') as user_obj:\n json.dump(username, user_obj)\n\n# load\nwith open(user_file, 'r') as saved_user_obj:\n saved_user = json.load(saved_user_obj)\n print('Welcome back, ' + saved_user)\n","sub_path":"imgurex/crash_course/9_exceptions_cont.py","file_name":"9_exceptions_cont.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"310276781","text":"import numpy as np\r\n\r\n# Z-Score Normalization\r\ndef normalize_data(dataList, mu, std):\r\n\r\n\timageList = list(dataList)\r\n\r\n\tfor index in range(len(imageList)):\r\n\t\timageList[index] = ( imageList[index] - mu ) / std\r\n\r\n\treturn np.array(imageList)","sub_path":"normalize.py","file_name":"normalize.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"647965596","text":"\"\"\"\n从文件中加载 IP 列表\n\"\"\"\nimport asyncio\nimport os\nimport sys\n\nfrom src.app.ip_get import IPGet\nfrom src.app.main import Logger\n\n\nasync def main():\n res = os.listdir('.')\n ip_file_lists = [name for name in res if name.find('.ip.txt') > 0]\n if len(sys.argv) > 1:\n custom_file = sys.argv[1]\n if custom_file not in ip_file_lists:\n Logger.error('file %s doesn\\'t exists' % custom_file)\n return\n else:\n ip_file_lists = [custom_file]\n for fn in ip_file_lists:\n await load_file(fn)\n\n\nasync def load_file(f_path):\n with open(f_path) as f:\n ips = []\n for ip in f.readlines():\n if ip and ip.find(':') and ip.find('#') < 0:\n ip = ip.strip()\n ips.append(ip)\n if ips:\n Logger.info('Find ip count %d' % len(ips))\n await IPGet.push_to_pool(ips)\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n tasks = [main()]\n loop.run_until_complete(asyncio.wait(tasks))\n","sub_path":"load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"590629897","text":"from django.conf.urls import include, url\n\nfrom hello.api import ApiKqcBlog, information_detail, information_list, kqctimes_list, kqctimes_detail\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\n# Examples:\n# url(r'^$', 'gettingstarted.views.home', name='home'),\n# url(r'^blog/', include('blog.urls')),\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^information/$', information_list),\n url(r'^information/(?P[0-9]+)$', information_detail),\n url(r'^kqc-times/$',kqctimes_list),\n url(r'^kqc-times/(?P[0-9]+)$',kqctimes_detail),\n url(r'^kqc-blogs', ApiKqcBlog.as_view())\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"gettingstarted/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"170501668","text":"# Copyright (c) 2014-2015 Sine Nomine Associates\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n\"\"\"System utilities for setting up AFS.\"\"\"\n\nimport logging\nimport os\nimport re\nimport subprocess\nimport time\n\nlogger = logging.getLogger(__name__)\n\nclass CommandFailed(Exception):\n \"\"\"Command exited with a non-zero exit code.\"\"\"\n def __init__(self, cmd, args, code, out, err):\n self.cmd = cmd\n self.args = args\n self.code = code\n self.out = out\n self.err = err\n\n def __str__(self):\n msg = \"Command failed! %s; code=%d, stderr='%s'\" % \\\n (\" \".join(self.args), self.code, self.err.strip())\n return repr(msg)\n\ndef run(cmd, args=None, quiet=False, retry=0, wait=1, cleanup=None):\n \"\"\"Run a command and return the output.\n\n Raises a CommandFailed exception if the command exits with an\n a non zero exit code.\"\"\"\n if args is None:\n args = []\n else:\n args = list(args)\n args.insert(0, cmd)\n for attempt in xrange(0, (retry + 1)):\n if attempt > 0:\n c = os.path.basename(cmd)\n logger.info(\"Retrying %s command in %d seconds; retry %d of %d.\", c, wait, attempt, retry)\n time.sleep(wait)\n if cleanup:\n cleanup() # Try to cleanup the mess from the last failure.\n logger.debug(\"Running: %s\", subprocess.list2cmdline(args))\n proc = subprocess.Popen(\n args,\n executable=cmd,\n shell=False,\n bufsize=-1,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n output,error = proc.communicate()\n rc = proc.returncode\n logger.debug(\"Result of %s; rc=%d, output=%s, error=%s\", cmd, rc, output, error)\n if rc == 0:\n return output\n raise CommandFailed(cmd, args, rc, output, error);\n\ndef which(program, extra_paths=None, raise_errors=False):\n \"\"\"Find a program in the PATH.\"\"\"\n dirname, basename = os.path.split(program)\n if dirname:\n # Full path was given; verify it is an executable file.\n if os.path.isfile(program) and os.access(program, os.X_OK):\n return program\n if raise_errors:\n raise AssertionError(\"Program '%s' is not an executable file.\" % (program))\n else:\n # Just the basename was given; search the paths.\n paths = os.environ['PATH'].split(os.pathsep)\n if extra_paths:\n paths = paths + extra_paths\n for path in paths:\n path = path.strip('\"')\n fpath = os.path.join(path, program)\n if os.path.isfile(fpath) and os.access(fpath, os.X_OK):\n return fpath\n if raise_errors:\n raise AssertionError(\"Could not find '%s' in paths %s\" % (program, \",\".join(paths)))\n return None\n\ndef file_should_exist(path, description=None):\n \"\"\"Fails if the given file does not exist.\"\"\"\n if not os.path.isfile(path):\n if description is None:\n description = \"File '%s' does not exist.\" % (path)\n raise AssertionError(description)\n return True\n\ndef directory_should_exist(path, description=None):\n \"\"\"Fails if the given directory does not exist.\"\"\"\n if not os.path.isdir(path):\n if description is None:\n description = \"Directory '%s' does not exist.\" % (path)\n raise AssertionError(description)\n return True\n\ndef directory_should_not_exist(path, description=None):\n \"\"\"Fails if the given directory does exist.\"\"\"\n if os.path.exists(path):\n if description is None:\n description = \"Directory '%s' already exists.\" % (path)\n raise AssertionError(description)\n return True\n\ndef get_running():\n \"\"\"Get a set of running processes.\"\"\"\n ps = which(\"ps\")\n out = run(ps, args=[\"ax\"])\n lines = out.splitlines()\n # The first line of the `ps ax' output is a header line which is\n # used to find the data field columns.\n column = lines[0].index('COMMAND')\n procs = set()\n for line in lines[1:]:\n cmd_line = line[column:]\n if cmd_line[0] == '[': # skip linux threads\n continue\n command = cmd_line.split()[0]\n procs.add(os.path.basename(command))\n return procs\n\ndef is_running(program):\n \"\"\"Returns true if program is running.\"\"\"\n return program in get_running()\n\ndef afs_mountpoint():\n uname = os.uname()[0]\n if uname == 'Linux':\n pattern = r'^AFS on (/.\\S+)'\n elif uname == 'SunOS':\n pattern = r'(/.\\S+) on AFS'\n else:\n raise AssertionError(\"Unsupported operating system: %s\" % (uname))\n output = run('mount')\n found = re.search(pattern, output, re.M)\n if found:\n mountpoint = found.group(1)\n else:\n mountpoint = None\n return mountpoint\n\ndef _linux_network_interfaces():\n \"\"\"Return list of non-loopback network interfaces.\"\"\"\n addrs = []\n out = run(\"/sbin/ip\", args=[\"-oneline\", \"-family\", \"inet\", \"addr\", \"show\"])\n for line in out.splitlines():\n match = re.search(r'inet (\\d+\\.\\d+\\.\\d+\\.\\d+)', line)\n if match:\n addr = match.group(1)\n if not addr.startswith(\"127.\"):\n addrs.append(addr)\n logger.debug(\"Found network interfaces: %s\", \",\".join(addrs))\n return addrs\n\ndef _linux_is_loaded(kmod):\n with open(\"/proc/modules\", \"r\") as f:\n for line in f.readlines():\n if kmod == line.split()[0]:\n return True\n return False\n\ndef _linux_configure_dynamic_linker(path):\n \"\"\"Configure the dynamic linker with ldconfig.\n\n Add a path to the ld configuration file for the OpenAFS shared\n libraries and run ldconfig to update the dynamic linker.\"\"\"\n conf = '/etc/ld.so.conf.d/openafs.conf'\n paths = set()\n paths.add(path)\n if os.path.exists(conf):\n with open(conf, 'r') as f:\n for line in f.readlines():\n line = line.strip()\n if line.startswith(\"#\") or line == \"\":\n continue\n paths.add(line)\n with open(conf, 'w') as f:\n logger.debug(\"Writing %s\", conf)\n for path in paths:\n f.write(\"%s\\n\" % path)\n run(\"/sbin/ldconfig\")\n\ndef _linux_unload_module():\n output = run('/sbin/lsmod')\n kmods = re.findall(r'^(libafs|openafs)\\s', output, re.M)\n for kmod in kmods:\n run('rmmod', args=[kmod])\n\ndef _solaris_network_interfaces():\n \"\"\"Return list of non-loopback network interfaces.\"\"\"\n addrs = []\n out = run(\"ipadm\", args=[\"show-addr\", \"-p\", \"-o\", \"STATE,ADDR\"])\n for line in out.splitlines():\n match = re.match(r'ok:(\\d+\\.\\d+\\.\\d+\\.\\d+)', line)\n if match:\n addr = match.group(1)\n if not addr.startswith(\"127.\"):\n addrs.append(addr)\n return addrs\n\ndef _solaris_is_loaded(kmod):\n \"\"\"Returns the list of currently loaded kernel modules.\"\"\"\n out = run(\"/usr/sbin/modinfo\", args=[\"-w\"])\n for line in out.splitlines()[1:]: # skip header line\n # Fields are: Id Loadaddr Size Info Rev Module (Name)\n m = re.match(r'\\s*(\\d+)\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\d+\\s+(\\S+)', line)\n if not m:\n raise AssertionError(\"Unexpected modinfo output: %s\" % (line))\n mid = m.group(1) # We will need the id to remove the module.\n mname = m.group(2)\n if kmod == mname:\n return mid\n return 0\n\ndef mkdirp(path):\n \"\"\"Make a directory with parents.\"\"\"\n # Do not raise an execption if the directory already exists.\n if not os.path.isdir(path):\n os.makedirs(path)\n\ndef cat(files, path):\n \"\"\"Combine one or more files.\"\"\"\n dst = open(path, 'w')\n for f in files:\n with open(f, 'r') as src:\n dst.write(src.read())\n dst.close()\n\ndef touch(path):\n \"\"\"Touch a file; create a empty file if not already existing.\"\"\"\n with open(path, 'a') as f:\n os.utime(path, None)\n\ndef symlink(src, dst):\n \"\"\"Create a symlink dst to src.\"\"\"\n logger.debug(\"Creating symlink %s -> %s\", dst, src)\n if not os.path.isfile(src):\n raise AssertionError(\"Failed to make symlink: src %s not found\" % (src))\n if os.path.exists(dst) and not os.path.islink(dst):\n raise AssertionError(\"Failed to make symlink: dst %s exists\" % (dst))\n if os.path.islink(dst):\n os.remove(dst)\n os.symlink(src, dst)\n\ndef _so_symlinks(path):\n \"\"\"Create shared lib symlinks.\"\"\"\n if not os.path.isdir(path):\n assert AssertionError(\"Failed to make so symlinks: path '%s' is not a directory.\", path)\n for dirent in os.listdir(path):\n fname = os.path.join(path, dirent)\n if os.path.isdir(fname) or os.path.islink(fname):\n continue\n m = re.match(r'(.+\\.so)\\.(\\d+)\\.(\\d+)\\.(\\d+)$', fname)\n if m:\n so,x,y,z = m.groups()\n symlink(fname, \"%s.%s.%s\" % (so, x, y))\n symlink(fname, \"%s.%s\" % (so, x))\n symlink(fname, so)\n\ndef _solaris_configure_dynamic_linker(path):\n if not os.path.isdir(path):\n raise AssertionError(\"Failed to configure dynamic linker: path %s not found.\" % (path))\n _so_symlinks(path)\n run(\"/usr/bin/crle\", args=[\"-u\", \"-l\", path])\n\ndef _solaris_unload_module():\n module_id = _solaris_is_loaded('afs')\n if module_id != 0:\n run('modunload', args=[\"-i\", module_id])\n\n_uname = os.uname()[0]\nif _uname == \"Linux\":\n network_interfaces = _linux_network_interfaces\n is_loaded = _linux_is_loaded\n configure_dynamic_linker = _linux_configure_dynamic_linker\n unload_module = _linux_unload_module\nelif _uname == \"SunOS\":\n network_interfaces = _solaris_network_interfaces\n is_loaded = _solaris_is_loaded\n configure_dynamic_linker = _solaris_configure_dynamic_linker\n unload_module = _solaris_unload_module\nelse:\n raise AssertionError(\"Unsupported operating system: %s\" % (uname))\n\n","sub_path":"libraries/afsutil/afsutil/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":10852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"371388962","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n runserver\r\n ~~~~~~~~~\r\n\r\n Initializaztion script for the Flask application. To run the server,\r\n execute `python runserver.py`\r\n\r\n :copyright: (c) 2010 by Mike Chambliss\r\n\"\"\"\r\nfrom flask import g\r\nfrom logging import Formatter\r\nfrom webapp import create_app\r\nfrom webapp.database.connection import init_db, get_session\r\n\r\n# Create the Flask app object\r\napp = create_app()\r\napp.debug_log_format = '%(levelname)s - %(asctime)s [in %(funcName)s:%(pathname)s:%(lineno)d]: %(message)s'\r\n\r\n# Initialize the database. See the database package for more details.\r\ninit_db(app.config['DATABASE'])\r\n\r\n@app.before_request\r\ndef start_session():\r\n \"\"\"Flask will invoke this at the beginning of every request.\r\n Initialize variables or do other important things before the application\r\n handles the request.\r\n \"\"\"\r\n \r\n app.logger.debug(\"Starting a request...\")\r\n g.session = get_session()\r\n\r\n@app.after_request\r\ndef shutdown_session(response):\r\n \"\"\"Flask will invoke this at the end of every request.\r\n Destroy variables or do other important things after the application\r\n handles the request.\r\n \"\"\"\r\n g.session.close()\r\n app.logger.debug(\"Finishing a request...\")\r\n return response\r\n \r\n@app.errorhandler(404)\r\ndef page_not_found(error):\r\n return 'This page does not exist', 200\r\n\r\n# Invoke the application\r\napp.run(debug=app.config['DEBUG'],host='0.0.0.0')\r\n","sub_path":"webapp/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"310142733","text":"#coding=utf-8\n\nfrom digg import model\n\nNAME=\"stat\"\n\nclass Stat(model.MongoModel):\n doc_name = NAME\n db_name = NAME\n #sort: asc | desc | none\n props = {\n \"today_news_num\": {'sort': None, \"default\": 0},\n \"today_news_timestamp\": {'sort': None, \"default\": 0},\n }\n\n @classmethod\n def current(cls):\n objs = cls.query({})\n obj = None\n if not objs:\n obj = cls.new_obj()\n cls.put_data(obj)\n else:\n obj = objs[0]\n return obj","sub_path":"source/www.51zhi.com/app/digg/model/stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"32308051","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom chat.models import Chat, MessageImage, MessageSmile\n\n\n@login_required(login_url='login')\ndef chat(request):\n chats = Chat.objects.filter(user_list=request.user)\n smiles = MessageSmile.objects.all()\n return render(request, 'chat/chat.html', {\n 'chats': chats, 'smiles': smiles\n })\n\n\n@login_required(login_url='login')\ndef upload_image(request):\n if request.method == 'POST' and request.FILES['img']:\n image = MessageImage(img=request.FILES['img'])\n image.save()\n return JsonResponse({'success': True, 'id': image.id})\n return JsonResponse({'success': False, 'message': 'no file'})\n","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"9713849","text":"import torch\nimport syft as sy\nfrom pandas import read_csv\n\n\ndef start_webserver(id: int, port: str):\n hook = sy.TorchHook(torch)\n server = sy.workers.websocket_server.WebsocketServerWorker(\n id=id, host=None, port=port, hook=hook, verbose=False\n )\n server.start()\n return server\n\n\ndef read_websocket_config(path: str):\n df = read_csv(path, header=None, index_col=0)\n return df.to_dict()\n\n\n\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument(\"--id\", type=str, required=True, help=\"id of worker\")\n parser.add_argument(\"--port\", type=int, required=True)\n args = parser.parse_args()\n\n start_webserver(args.id, args.port)\n","sub_path":"torchlib/websocket_utils.py","file_name":"websocket_utils.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"96108530","text":"import requests\nimport uuid\nimport time\n\nfrom django.shortcuts import render, HttpResponseRedirect, reverse, redirect\nfrom django.http import JsonResponse\nfrom django.conf import settings\nfrom django.utils.text import slugify\nfrom django.db.models import Q\nfrom django.template import engines\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth.models import User\n\nimport modules.keycloak_lib as kc\n\nfrom apps.models import Apps, AppInstance\nfrom projects.models import Project\n\ndef index(request,id=0):\n try:\n projects = Project.objects.filter(Q(owner=request.user) | Q(authorized=request.user), status='active')\n except Exception as err:\n print(\"User not logged in.\")\n base_template = 'base.html'\n if 'project' in request.session:\n project_slug = request.session['project']\n is_authorized = kc.keycloak_verify_user_role(request, project_slug, ['member'])\n if is_authorized:\n try:\n project = Project.objects.filter(Q(owner=request.user) | Q(authorized=request.user), status='active', slug=project_slug).first()\n base_template = 'baseproject.html'\n except TypeError as err:\n project = []\n print(err)\n if not project:\n base_template = 'base.html'\n # if project_selected:\n # print(\"Project is selected\")\n # print(project)\n # print(base_template)\n media_url = settings.MEDIA_URL\n \n # create session object to store info about app and their tag counts\n if \"app_tags\" not in request.session:\n request.session['app_tags'] = {}\n # tag_count from the get request helps set num_tags which helps set the number of tags to show in the template\n if \"tag_count\" in request.GET:\n # add app id to app_tags object\n if \"app_id_add\" in request.GET:\n num_tags = int(request.GET['tag_count'])\n id=int(request.GET['app_id_add'])\n request.session['app_tags'][str(id)]=num_tags\n # remove app id from app_tags object\n if \"app_id_remove\" in request.GET:\n num_tags = int(request.GET['tag_count'])\n id=int(request.GET['app_id_remove'])\n if str(id) in request.session['app_tags']:\n request.session['app_tags'].pop(str(id))\n \n # reset app_tags if Apps Tab on Sidebar pressed\n if id==0:\n if 'tf_add' not in request.GET and 'tf_remove' not in request.GET:\n request.session['app_tags'] = {}\n \n published_apps = AppInstance.objects.filter(~Q(state='Deleted'), access='public')\n\n # create session object to store ids for tag seacrh if it does not exist\n if \"app_tag_filters\" not in request.session:\n request.session['app_tag_filters'] = []\n if 'tf_add' in request.GET:\n tag = request.GET['tf_add']\n if tag not in request.session['app_tag_filters']:\n request.session['app_tag_filters'].append(tag)\n elif 'tf_remove' in request.GET:\n tag = request.GET['tf_remove']\n if tag in request.session['app_tag_filters']:\n request.session['app_tag_filters'].remove(tag)\n elif \"tag_count\" not in request.GET:\n tag=\"\"\n request.session['app_tag_filters'] = []\n print(\"app_tag_filters: \", request.session['app_tag_filters'])\n\n # changed list of published model only if tag filters are present\n if request.session['app_tag_filters']:\n tagged_published_apps = []\n for app in published_apps:\n for t in app.tags.all():\n if t in request.session['app_tag_filters']:\n tagged_published_apps.append(app)\n break\n published_apps = tagged_published_apps\n \n request.session.modified = True\n\n template = 'index_portal.html'\n return render(request, template, locals())\n","sub_path":"components/studio/portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"150996496","text":"import pdb\nimport os\nimport cv2\nimport multiprocessing\n\nimport logging\nimport time\nimport importlib\nimport numpy as np\nfrom tensorboardX import SummaryWriter\n\nimport mxnet as mx\nimport core.metrics as metrics\nfrom collections import namedtuple\nfrom core.module import MutableModule\nfrom utils.evl_seg import load_params, calculate, get_data, fasttrainID2labels\n\nBatchEndParam = namedtuple('BatchEndParams', ['epoch', 'nbatch', 'eval_metric'])\n\ndef resize_wrapper(i):\n if result_list[i] is None:\n return cv2.resize(unresized_result_list[i],\n tuple(val.output_size), interpolation=cv2.INTER_LINEAR)\n return result_list[i] + cv2.resize(unresized_result_list[i],\n tuple(val.output_size), interpolation=cv2.INTER_LINEAR)\n\ndef eval_IOU(epoch, val, args_params, auxs_params, mpool, logger, writer, visualize=False):\n bind_shape = 0\n tp = [0.0] * 21\n denom = [0.0] * 21\n\n num_class = val.num_class\n root_dir = val.root_dir\n epoch = epoch\n ctx = mx.gpu(val.test_gpus)\n scales = val.scales\n enet_args = args_params\n enet_auxs = auxs_params\n enet = importlib.import_module(\n 'symbols.' + val.network).get_symbol(val.num_class,\n val.output_stride,\n val.use_refine_decoder,\n val.use_aspp_with_separable_conv,\n non_local=val.non_local, \n oc_context=val.oc_context)\n enet = mx.symbol.contrib.BilinearResize2D(enet, \n height=val.output_size[0], width=val.output_size[1])\n lines = open(os.path.join(val.root_dir, val.val_list)).read().splitlines()\n num_image = len(lines)\n outlist = []\n result_list = [None] * num_image\n unresized_result_list = [None] * num_image\n for scale in scales:\n for idx, line in enumerate(lines):\n data_img_name, label_img_name = line.strip('\\n').split(\"\\t\")\n label_name = os.path.join(root_dir, label_img_name)\n filename = os.path.join(root_dir, data_img_name)\n index = 0\n for flip in range(val.flip+1):\n img_data, img_label, nh, nw = get_data(filename, label_name, scale, flip, val.output_size)\n if bind_shape != img_data.shape[1]:\n exector = enet.simple_bind(ctx, data=(1, 3, img_data.shape[1], \n img_data.shape[2]), grad_req=\"null\")\n bind_shape = img_data.shape[1]\n exector.copy_params_from(enet_args, enet_auxs, False)\n img_data = np.expand_dims(img_data, 0)\n data = mx.nd.array(img_data, ctx)\n exector.forward(is_train=False, data=data)\n if flip == 1:\t\t\t# CxHxW\n output = exector.outputs[0].flip(axis=2).asnumpy()\n else:\n output = exector.outputs[0].asnumpy()\n output = np.squeeze(output)\n if flip == 1:\n labels += output\n labels /= 2.0\n else:\n labels = output\n unresized_result_list[idx] = labels.transpose([1,2,0])\t# HxWxC\n\n if result_list[idx] is None:\n result_list[idx] = labels\n else:\n result_list[idx] += labels\n\n print(idx)\n\n \"\"\"\n for idx, i in enumerate(unresized_result_list):\n unresized_result_list[idx]=[i, tuple(val.output_size), cv2.INTER_LINEAR, result_list[idx]]\n result_list = mpool.map(resize_wrapper, range(len(unresized_result_list)))\n\n for idx, labels in enumerate(unresized_result_list):\t\t# HxWxC\n if result_list[idx] is None:\n result_list[idx] = labels\n else:\n result_list[idx] += labels\n \"\"\"\n\n\n for idx, line in enumerate(lines):\n if result_list[idx] is None:\n continue\n output = result_list[idx]/float(len(scales))\n #if np.isnan(np.mean(output)):\n # print(np.mean(output))\n # sys.exit(0)\n pre_label = np.argmax(output, axis=-1)\t\t\t\t# HxWxC\n iou = calculate(pre_label, img_label, num_class, tp, denom)\n #print(iou)\n\n if visualize:\n heat = np.max(output, axis=0)\n heat *= 255\n heat_map = cv2.applyColorMap(heat.astype(np.uint8), cv2.COLORMAP_JET)\n\n pre_label, result = fasttrainID2labels(pre_label, num_class)\n img = cv2.imread(filename)\n gt_label = cv2.imread(label_name)\n gt_label = np.transpose(gt_label, [2, 0, 1])\n _label = np.zeros((3, 512, 512), np.single)\n _label[:, :gt_label.shape[1], :gt_label.shape[2]] = gt_label\n _label = np.transpose(_label, [1, 2, 0])\n img = np.transpose(img, [2, 0, 1])\n _img_data = np.zeros((3, 512, 512), np.single)\n _img_data[:, :img.shape[1], :img.shape[2]] = img\n _img_data = np.transpose(_img_data, [1, 2, 0])\n \n visual = np.zeros((result.shape[0] * 2, result.shape[1] * 2, 3))\n visual[result.shape[0]:, :result.shape[1], :] = result\n visual[result.shape[0]:, result.shape[1]:, :] = _label\n visual[:result.shape[0], result.shape[1]:, :] = heat_map\n visual[:result.shape[0], :result.shape[1], :] = _img_data\n\n if not os.path.exists('./visual'):\n os.makedirs('./visual')\n\n name = label_img_name.split('/')[-1]\n #cv2.imwrite('./visual/'+name,visual)\n\n id2name = ['road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic_light', 'traffic_sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle']\n\n for c in range(num_class):\n temp = tp[c] / (denom[c] + 1e-6)\n writer.add_scalar(id2name[c], temp, epoch)\n writer.add_scalar('Aug-Validation', iou, epoch)\n logger.info('Epoch[%d] Aug-Validation-%s=%f', epoch, miou, iou)\n\n\nclass Solver(object):\n def __init__(self, symbol, ctx=None,\n begin_epoch=0, end_epoch=None,\n arg_params=None, aux_params=None, opt_states=None, num_class=21):\n self.symbol = symbol\n self.ctx = ctx\n if self.ctx is None:\n self.ctx = [mx.cpu()]\n self.begin_epoch = begin_epoch\n self.end_epoch = end_epoch\n self.arg_params = arg_params\n self.aux_params = aux_params\n self.opt_states = opt_states\n self.num_class = num_class\n\n self.mpool = multiprocessing.Pool(50)\n\n def _reset_bind(self):\n \"\"\"Internal function to reset binded state.\"\"\"\n self.binded = False\n self._exec_group = None\n self._data_shapes = None\n self._label_shapes = None\n\n def fit(self, prefix=\"\",start_evl=100,train_data=None, eval_data=None, eval_metric='acc',\n validate_metric=None, work_load_list=None,\n max_data_shapes=None, max_label_shapes=None,\n epoch_end_callback=None, batch_end_callback=None,\n fixed_param_regex=None, initializer=None, optimizer=None,\n optimizer_params=None, logger=None, kvstore='local', p=None):\n writer = SummaryWriter(os.path.join('/',*prefix.split('/')[:-1]))\n\n if logger is None:\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n\n if validate_metric is None:\n validate_metric = eval_metric\n\n # set module\n mod = MutableModule(symbol=self.symbol,\n data_names=[x[0] for x in train_data.provide_data],\n label_names=[x[0] for x in train_data.provide_label],\n logger=logger,\n context=self.ctx,\n preload_opt_states=self.opt_states,\n work_load_list=work_load_list,\n max_data_shapes=max_data_shapes,\n max_label_shapes=max_label_shapes,\n fixed_param_regex=fixed_param_regex\n )\n\n mod.bind(data_shapes=max_data_shapes, label_shapes=max_label_shapes)\n self.arg_params['oc_W_weight'] = mx.nd.zeros([256,256,1,1])\n #self.arg_params['nonlocal_conv44'] = mx.nd.zeros([1024,1024,1,1])\n mod.init_params(initializer=initializer,\n arg_params=self.arg_params,\n aux_params=self.aux_params,\n allow_missing=True)\n mod.init_optimizer(kvstore=kvstore,\n optimizer=optimizer,\n optimizer_params=optimizer_params)\n\n metric_tra = []\n metric_lst = []\n eval_metric1 = metrics.AccWithIgnoreMetric(ignore_label=255)\n metric_tra.append(eval_metric1)\n metric_lst.append(metrics.IoUMetric(ignore_label=255, label_num=self.num_class, name='IOU'))\n validate_metric = mx.metric.CompositeEvalMetric(metrics=metric_lst)\n eval_metric = mx.metric.CompositeEvalMetric(metrics=metric_tra)\n\n # training loop\n for epoch in range(self.begin_epoch, self.end_epoch):\n tic = time.time()\n eval_metric.reset()\n\n\n # evaluation\n print('score')\n if eval_data and (epoch>=start_evl) and (epoch%2==0):\n if (p.test_gpus is not None) and epoch%10==0:\n arg_params, aux_params = mod.get_params()\n eval_IOU(epoch, p, arg_params, aux_params, self.mpool,\n \tlogger, writer, visualize=False)\n else:\n res = mod.score(eval_data, validate_metric)\n for name, val in res:\n logger.info('Epoch[%d] Validation-%s=%f', epoch, name, val)\n writer.add_scalar(name, val, epoch)\n validate_metric.reset()\n\n\n for nbatch, data in enumerate(train_data, 1):\n mod.forward(data_batch=data, is_train=True)\n mod.backward()\n mod.update_metric(eval_metric, data.label)\n mod.update()\n\n if batch_end_callback is not None:\n batch_end_params = BatchEndParam(epoch=epoch, nbatch=nbatch, eval_metric=eval_metric)\n batch_end_callback(batch_end_params)\n\n # one epoch training is finished\n for name, val in eval_metric.get_name_value():\n logger.info('Epoch[%d] Train-%s=%f', epoch, name, val)\n toc = time.time()\n logger.info('Epoch[%d] Time cost=%.3f', epoch, (toc - tic))\n if epoch_end_callback is not None:\n arg_params, aux_params = mod.get_params()\n if epoch > 100 and (epoch%20)==0:\n mod.save_checkpoint(prefix, epoch+1, True)\n mod.set_params(arg_params, aux_params)\n\n # one epoch training is finished, reset train set\n train_data.reset()\n eval_data.reset()\n","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":11304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"388991468","text":"#!/usr/bin/python3\n\nfrom utils.utils_constants import API_KEY_ABS_PATH\n\nfrom backoff import on_exception, expo\nimport requests\nfrom requests import ConnectionError, Timeout, HTTPError\nfrom ratelimit import limits, sleep_and_retry\nfrom typing import Union\n\n\nKEY = open(API_KEY_ABS_PATH).read().strip()\n\nFIVE_MINUTES = 300 # Number of seconds in five minutes.\n\nAPI_BASE_URL = \"https://api.companieshouse.gov.uk\"\n\n\n@sleep_and_retry # if we exceed the rate limit imposed by @limits, it forces sleep until we can start again.\n@on_exception(expo, (ConnectionError, Timeout, HTTPError), max_tries=10)\n@limits(calls=1000, period=FIVE_MINUTES) # CH enforces a 600 queries per 5 minutes limit.\ndef call_api(url: str, api_key: str) -> Union[None, dict]:\n\t\"\"\"\n\tfunc to generate a query for an API with auth=(key, \"\"). Decorators handle rate limit calls and exceptions.\n\t:param url: string, url of the query.\n\t:param api_key: string, apy_key.\n\t:return: if status_code is 200 func returns a JSON object.\n\t\t\t if status_code is http error func returns {\"error\":\"error_string\"}\n\t\t\t if status_code is not 200/404 func re-runs up to 10 times if exceptions in @on_exception tuple\n\t\t\t argument are raised. If 11th attempt fails, return None and print 'API response: {}'.format(r.status_code).\n\t\"\"\"\n\tr = requests.get(url, auth=(api_key, \"\"))\n\n\tif not (r.status_code == 200 or r.status_code == 404 or r.status_code == 401 or r.status_code == 400):\n\t\tr.raise_for_status()\n\n\telif r.status_code == 404:\n\t\treturn dict({\"error\": \"not found\"})\n\n\telif r.status_code == 401:\n\t\treturn dict({\"error\": \"not authorised\"})\n\n\telif r.status_code == 400:\n\t\treturn dict({\"error\": \"bad request\"})\n\n\telse:\n\t\treturn r.json()\n\n\ndef get_companyprofile(url_id: str, **kwargs) -> callable:\n\t\"\"\"\n\tfunc to extract companyprofile¹ resource from the API given a company number.\n\t:param url_id: uniquely identified code of the company.\n\t:param kwargs: it ensures that in the factory function Getter.extract(root_uid, start_index) we are\n\t\t\t\t able to call get_companyprofile with the (unnecessary for this func) start_index argument (which is\n\t\t\t\t otherwise necessary for all other functions).\n\t:return: call_api(), with url formatted to search company whose code is \"comp_code\".\n\t\"\"\"\n\turl = API_BASE_URL + \"/company/\" + url_id\n\treturn call_api(url=url, api_key=KEY)\n\n\ndef get_company_resource(url_id: str, res_type: str, items_per_page: int, start_index: int) -> callable:\n\t\"\"\"\n\tfunc to customise the API request for a given company, used to create other functions for all possible \"res_type\".\n\t:param start_index: index used by the url for the pagination.\n\t:param url_id: uniquely identified code of the company.\n\t:param res_type: resource type, can chose from:\n\t\t\t\t\t \"officers\", will return all officers of the company (no UID attributed by CH)²\n\t\t\t\t\t \"filing-history\", will return all filings³.\n\t\t\t\t\t \"insolvency\", will return insolvency information⁴.\n\t\t\t\t\t \"charges\", will return charges⁵.\n\t\t\t\t\t \"persons-with-significant-control\", will return all psc (no UID attributed by CH)⁶.\n\t:param items_per_page: max items per page to be returned (we could set it to any number, but want the max).\n\t:return: call_api(), with url formatted to search company whose code is root_uid and res_type is chosen from list.\n\t\"\"\"\n\n\turl = (API_BASE_URL \n\t + f\"/company/{url_id}/{res_type}?items_per_page={items_per_page}&start_index={str(start_index)}\")\n\treturn call_api(url=url, api_key=KEY)\n\n\ndef get_appointmentlist(url_id: str, items_per_page: int, start_index: int) -> callable:\n\t\"\"\"\n\tfunc to query the API for appointmentList⁸ resource (being all appointments of one officer).\n\t:param items_per_page: max items per page to be returned (we could set it to any number, but want the max).\n\t:param start_index: index used by the url for the pagination.\n\t:param url_id: string, needed to create url to get all appointments from API.\n\t:return: call_api(), with url formatted to search officers appointments whose link is param appointments_link.\n\t\"\"\"\n\t# what we are building to:\n\t# https://api.companieshouse.gov.uk/{root_uid}/?items_per_page=1&start_index=1\n\t# where a root_uid here is: \"/officers/LsKBd0tzif0mocK0gTSiK5WXmuA/appointments\"\n\n\turl = (API_BASE_URL\n\t + f\"{url_id}?items_per_page={str(items_per_page)}&start_index={str(start_index)}\")\n\treturn call_api(url=url, api_key=KEY)\n\n\ndef get_officersearch(url_id: str, items_per_page: int, start_index: int) -> callable:\n\t\"\"\"\n\tfunc to get total results returned in the officerSearch resource⁹.\n\t:param url_id: string for the officer search query.\n\t:param items_per_page: max items per page to be returned (we could set it to any number, but want the max).\n\t:param start_index: index used by the url for the pagination.\n\t\t\t\t\t\tBe aware that if you try to extract more than the first 900 matches, you will get HTTP 416⁷.\n\t:return: call_api with URL customised to search for a certain officer.\n\t\"\"\"\n\turl = (API_BASE_URL\n\t + f\"/search/officers?q={url_id}&items_per_page={str(items_per_page)}&start_index={str(start_index)}\")\n\treturn call_api(url=url, api_key=KEY)\n\n\n# Resources JSON examples and discussion from the CH developer forum\n\n\n# ¹ https://developer.companieshouse.gov.uk/api/docs/company/company_number/companyProfile-resource.html\n# ² https://developer.companieshouse.gov.uk/api/docs/company/company_number/officers/officerList-resource.html\n# ³ https://developer.companieshouse.gov.uk/api/docs/company/company_number/filing-history/filingHistoryList-resource.html\n# ⁴ https://developer.companieshouse.gov.uk/api/docs/company/company_number/insolvency/companyInsolvency-resource.html\n# ⁵ https://developer.companieshouse.gov.uk/api/docs/company/company_number/charges/chargeList-resource.html\n# ⁶ https://developer.companieshouse.gov.uk/api/docs/company/company_number/persons-with-significant-control/listPersonsWithSignificantControl.html\n# ⁷ https://forum.aws.chdev.org/t/search-company-officers-returns-http-416-when-start-index-over-300/897/4\n# ⁸ https://developer.companieshouse.gov.uk/api/docs/officers/officer_id/appointments/appointmentList-resource.html\n# ⁹ https://developer.companieshouse.gov.uk/api/docs/search-overview/OfficerSearch-resource.html\n","sub_path":"ch_api/utils/api_functions.py","file_name":"api_functions.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"399611935","text":"from io import BytesIO\nimport unittest\nimport time\nfrom random import randint\nfrom helper import (\n hash256,\n encode_varint,\n int_to_little_endian,\n little_endian_to_int,\n read_varint,\n)\nNETWORK_MAGIC = b'\\xf9\\xbe\\xb4\\xd9'\nTESTNET_NETWORK_MAGIC = b'\\x0b\\x11\\x09\\x07'\n\nclass NetworkEnvelope:\n \"\"\"Class docstrings go here.\"\"\"\n def __init__(self, command, payload, testnet = False):\n self.command = command\n self.payload = payload\n self.magic = TESTNET_NETWORK_MAGIC if testnet else NETWORK_MAGIC\n\n def __repr__(self):\n return '{}:{}:{}'.format(self.magic, self.command.decode('ascii'), self.payload.hex())\n \n def serialize(self):\n '''Returns the byte serialization of the entire network message'''\n # add the network magic\n result = self.magic\n # command 12 bytes\n # fill with 0's\n result += self.command + b'\\x00' * (12 - len(self.command))\n # payload length 4 bytes, little endian\n result += int_to_little_endian(len(self.payload), 4)\n # checksum 4 bytes, first four of hash256 of payload\n result += hash256(self.payload)[:4]\n # payload\n result += self.payload\n return result\n \n @classmethod\n def parse(cls, stream, testnet = False):\n magic = stream.read(4) # \n #print('Magic: {}'.format(magic))\n if magic == b'': # if magic is empty\n raise IOError('Connection reset!') # network problem\n expected_magic = TESTNET_NETWORK_MAGIC if testnet else NETWORK_MAGIC\n if magic != expected_magic:\n raise SyntaxError('magic is not right {} vs {}'.format(magic.hex(), expected_magic.hex()))\n \n command = stream.read(12) # 12 bytes, human-readable\n command = command.strip(b'\\x00')\n \n payload_length = little_endian_to_int(stream.read(4)) # 4 payload length, 4 bytes, little endian\n \n checksum = stream.read(4) # payload checksum, first 4 bytes of hash of the payload\n payload = stream.read(payload_length) # read payload\n calculated_checksum = hash256(payload)[:4]\n if calculated_checksum != checksum:\n raise IOError('checksum does not match')\n return cls(command, payload, testnet=testnet)\n\n\nclass VersionMessage:\n \"\"\"Class docstrings go here.\"\"\"\n command = b'version'\n def __init__(self, \n version = 70015, \n services = 0, \n timestamp = None, \n receiver_services = 0,\n receiver_ip = b'\\x00\\x00\\x00\\x00', \n receiver_port = 8333,\n sender_services = 0,\n sender_ip=b'\\x00\\x00\\x00\\x00',\n sender_port = 8333,\n nonce = None,\n user_agent = b'/programmingbitcoin:0.1/',\n latest_block = 0,\n relay = False):\n self.version = version\n self.services = services\n if timestamp is None:\n self.timestamp = int(time.time())\n else:\n self.timestamp = timestamp\n self.receiver_ip = receiver_ip\n self.receiver_port = receiver_port\n self.receiver_services = receiver_services\n self.sender_services = sender_services\n self.sender_ip = sender_ip\n self.sender_port = sender_port\n if nonce is None:\n self.nonce = int_to_little_endian(randint(0, 2**64), 8)\n else:\n self.nonce = nonce\n self.user_agent = user_agent\n self.latest_block = latest_block\n self.relay = relay\n\n def serialize(self):\n '''Serialize this message to send over the network'''\n # version is 4 bytes little endian\n result = int_to_little_endian(self.version, 4)\n # services is 8 bytes little endian\n result += int_to_little_endian(self.services, 8)\n # timestamp is 8 bytes little endian\n result += int_to_little_endian(self.timestamp, 8)\n # receiver services is 8 bytes little endian\n result += int_to_little_endian(self.receiver_services, 8)\n # IPV4 is 10 00 bytes and 2 ff bytes then receiver ip\n result += b'\\x00' * 10 + b'\\xff\\xff' + self.receiver_ip\n # receiver port is 2 bytes, big endian\n result += self.receiver_port.to_bytes(2, 'big')\n # sender services is 8 bytes little endian\n result += int_to_little_endian(self.sender_services, 8)\n # IPV4 is 10 00 bytes and 2 ff bytes then sender ip\n result += b'\\x00' * 10 + b'\\xff\\xff' + self.sender_ip\n # sender port is 2 bytes, big endian\n result += self.sender_port.to_bytes(2, 'big')\n # nonce should be 8 bytes\n result += self.nonce\n # useragent is a variable string, so varint first\n result += encode_varint(len(self.user_agent))\n # latest block is 4 bytes little endian\n result += self.user_agent\n # relay is 00 if false, 01 if true\n result += int_to_little_endian(self.latest_block, 4)\n\n result += b'\\x01' if self.relay else b'\\x00'\n return result\n \nimport socket\n\nclass NetworkEnvelopeTest(unittest.TestCase):\n\n def _test_parse(self):\n\n version = VersionMessage()\n\n envelope = NetworkEnvelope(version.command, version.serialize())\n msg = envelope.serialize()#bytes.fromhex('f9beb4d976657273696f6e0000000000650000005f1a69d2721101000100000000000000bc8f5e5400000000010000000000000000000000000000000000ffffc61b6409208d010000000000000000000000000000000000ffffcb0071c0208d128035cbc97953f80f2f5361746f7368693a302e392e332fcf05050001')\n stream = BytesIO(msg)\n envelope = NetworkEnvelope.parse(stream)\n self.assertEqual(envelope.command, b'version')\n self.assertEqual(envelope.payload, msg[24:])\n\n msg = bytes.fromhex('f9beb4d976657261636b000000000000000000005df6e0e2')\n stream = BytesIO(msg)\n envelope = NetworkEnvelope.parse(stream)\n self.assertEqual(envelope.command, b'verack')\n self.assertEqual(envelope.payload, b'')\n\n msg = bytes.fromhex('f9beb4d976657273696f6e0000000000650000005f1a69d2721101000100000000000000bc8f5e5400000000010000000000000000000000000000000000ffffc61b6409208d010000000000000000000000000000000000ffffcb0071c0208d128035cbc97953f80f2f5361746f7368693a302e392e332fcf05050001')\n stream = BytesIO(msg)\n envelope = NetworkEnvelope.parse(stream)\n self.assertEqual(envelope.command, b'version')\n self.assertEqual(envelope.payload, msg[24:])\n\n def test1(self):\n print('Testing network envelop')\n host = 'testnet.programmingbitcoin.com'\n port = 18333\n skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n skt.connect((host, port))\n stream = skt.makefile('rb', None)\n version = VersionMessage()\n envelope = NetworkEnvelope(version.command, version.serialize())\n #print(envelope.serialize() )\n #print(envelope)\n #print(envelope.serialize().decode(\"ascii\") )\n skt.sendall(envelope.serialize())\n while(True): # emulate a assync transfer of messages\n new_message = NetworkEnvelope.parse(stream)\n print(new_message)\n\n def _test_serialize(self):\n msg = bytes.fromhex('f9beb4d976657261636b000000000000000000005df6e0e2')\n stream = BytesIO(msg)\n envelope = NetworkEnvelope.parse(stream)\n self.assertEqual(envelope.serialize(), msg)\n msg = bytes.fromhex('f9beb4d976657273696f6e0000000000650000005f1a69d2721101000100000000000000bc8f5e5400000000010000000000000000000000000000000000ffffc61b6409208d010000000000000000000000000000000000ffffcb0071c0208d128035cbc97953f80f2f5361746f7368693a302e392e332fcf05050001')\n stream = BytesIO(msg)\n envelope = NetworkEnvelope.parse(stream)\n self.assertEqual(envelope.serialize(), msg) \n \nif __name__ == '__main__':\n unittest.main()\n\n\n","sub_path":"Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":7835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"372917940","text":"class Solution(object):\n def maxSubArray(self, nums):\n \"\"\"\n dynamic programming\n iterate the array, for the current cell i, if nums[i-1] is negative, it has no contribution to the max sum, thus\n directly ignore the first i-1 items. Otherwise, add nums[i-1] + nums[i] for a new local maximum.\n runtime: 12 ms beats 99.83%\n \"\"\"\n for i in range(1, len(nums)):\n nums[i] = nums[i] if nums[i - 1] < 0 else nums[i - 1] + nums[i]\n\n return max(nums)\n # res[1] = nums[1] if nums[0] + nums[1] < nums[1] else nums[0] + nums[1]\n # for i in range(2, len(nums)):\n # if nums[i] < 0:\n # res[i] = res[i - 1]\n # else:\n # res[i] = max(res[i - 1] + nums[i], nums[i])\n # max_sum = nums[0]\n # for i in res:\n # if i > max_sum:\n # max_sum = i\n # return max_sum\n\n\nif __name__ == \"__main__\":\n s = Solution()\n nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n # nums = [1, 2, 3, 4, 5, 6]\n print(s.maxSubArray(nums))\n","sub_path":"Array/53. MaximumSubarray.py","file_name":"53. MaximumSubarray.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"193697708","text":"# External imports\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Set plot params\nplt.rc('font', size=14) # controls default text sizes\nplt.rc('axes', titlesize=14) # fontsize of the axes title\nplt.rc('axes', labelsize=14) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=14) # fontsize of the tick labels\nplt.rc('ytick', labelsize=14) # fontsize of the tick labels\nplt.rc('legend', fontsize=14) # legend fontsize\n\n\n'''\n This script calculates the elastic constant from stress-energy relation \n to files from a LAMMPS calculation.\n\n Devloped by Eric Lindgren, SNUID: 2020-81634\n April 2020\n'''\n\n\ndef extract(f):\n ''' Extracts the quantity of interest from the .fe file f and returns it in a Numoy array '''\n a = []\n with open(f, 'r') as file:\n for row in file:\n if '=' in row:\n a.append( float(row.split('=')[1].rstrip()) )\n a = np.array( a )\n return a\n\n\n# Setup\neV = 1.602177e-19\nT = 0\nd_file = 'd.mgo'\ne_file = 'e.mgo'\na0 = 4.21079\nV = a0**3\n\n# Extract strain and E values\nd = extract(d_file)\nE = extract(e_file)\n\n# Extract strain\ne = (d-a0)/a0\n\n# Convert to numpy arrays and normalize\nE = np.array(E) - E[2]\nd = np.array(d)\n\n# Perform linefit\ndE2dd2 = np.polyfit( d, E, deg=2 )[2] # eV - strain is dimensionless\n# Calculate elastic constant\ndE2dd2 *= eV*1e-9 # Convert to GJ\nV *= 1e-30 # m3\nC11 = 2/V * dE2dd2\nprint(f'Obtained elastic constant at T={T} K: \\t C11 = {C11:.3f} GPa')\n\n\n# Plot stress-strain\nfig, ax = plt.subplots(figsize=(8,6))\nax.plot( e, E, label=r'$T=$'+f'{T:.2f} K' )\nax.set_xlabel(r'Strain $e$')\nax.set_ylabel(r'Energy $E$, (eV)')\nax.grid()\nax.legend(loc='best')\nplt.tight_layout()\nplt.savefig('energy_strain.png')\nplt.show()\n","sub_path":"SNU/introduction_to_atomistic_simulations_of_nuclear_materials/example04-mgo_elastic_constant_energy_strain/calc_elastic_constant.py","file_name":"calc_elastic_constant.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"382777095","text":"\"\"\"\nModule that handles all email notifications\n\"\"\"\nimport smtplib\nimport logging\nimport json\nfrom email import encoders\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email.mime.text import MIMEText\n\n\nclass EmailSender():\n \"\"\"\n Email Sender allows to send emails to users using CERN SMTP server\n \"\"\"\n\n def __init__(self, config):\n self.logger = logging.getLogger('logger')\n self.credentials = config['ssh_credentials']\n self.smtp = None\n\n def __setup_smtp(self):\n \"\"\"\n Read credentials and connect to SMTP file\n \"\"\"\n if ':' not in self.credentials:\n with open(self.credentials) as json_file:\n credentials = json.load(json_file)\n else:\n credentials = {}\n credentials['username'] = self.credentials.split(':')[0]\n credentials['password'] = self.credentials.split(':')[1]\n\n self.logger.info('Credentials loaded successfully: %s', credentials['username'])\n self.smtp = smtplib.SMTP(host='smtp.cern.ch', port=587)\n # self.smtp.connect()\n self.smtp.ehlo()\n self.smtp.starttls()\n self.smtp.ehlo()\n self.smtp.login(credentials['username'], credentials['password'])\n\n def __close_smtp(self):\n \"\"\"\n Close connection to SMTP server\n \"\"\"\n self.smtp.quit()\n self.smtp = None\n\n def send(self, subject, body, recipients, files=None):\n \"\"\"\n Send email\n \"\"\"\n body = body.strip()\n body += '\\n\\nSincerely,\\nRelMon Service'\n ccs = ['PdmV Service Account ']\n # Create a fancy email message\n message = MIMEMultipart()\n message['Subject'] = '[RelMon] %s' % (subject)\n message['From'] = 'PdmV Service Account '\n message['To'] = ', '.join(recipients)\n message['Cc'] = ', '.join(ccs)\n # Set body text\n message.attach(MIMEText(body))\n if files:\n for path in files:\n attachment = MIMEBase('application', 'octet-stream')\n with open(path, 'rb') as attachment_file:\n attachment.set_payload(attachment_file.read())\n\n file_name = path.split('/')[-1]\n encoders.encode_base64(attachment)\n attachment.add_header('Content-Disposition',\n 'attachment; filename=\"%s\"' % (file_name))\n message.attach(attachment)\n\n self.logger.info('Will send \"%s\" to %s', message['Subject'], message['To'])\n self.__setup_smtp()\n self.smtp.sendmail(message['From'], recipients + ccs, message.as_string())\n self.__close_smtp()\n","sub_path":"local/email_sender.py","file_name":"email_sender.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"565536773","text":"import time\n\nimport grpc\n\nimport example_pb2\nimport example_pb2_grpc\n\ndef run():\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = example_pb2_grpc.ExampleStub(channel)\n print(time.time())\n msg = example_pb2.Req(id=0, query=\"Do you ack?\", req_value=131)\n print(time.time())\n response1 = stub.RunExample2(msg)\n print(f'Example client received response, id: {response1.id}, message: {response1.res_string}')\n #response1 = stub.RunExample2.future(msg)\n #res1 = response1.result()\n #response2 = stub.RunExample(msg)\n #print(f'Example client received response, id: {response2.id}, message: {response2.res_string}')\n\n #if res1:\n #print(f'Unsolicited(fake) response received {res}')\n print('connection terminated')\n\nif __name__ == '__main__':\n run()\n","sub_path":"grpc/client_bi_directional.py","file_name":"client_bi_directional.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"94338660","text":"\r\n# This allows us to use the type Individual within the Individual class.\r\nfrom __future__ import annotations\r\n\r\nfrom random import choice, randint, sample\r\nfrom typing import Any, List, NewType, Sequence, Tuple\r\n\r\nimport core.gui as gui\r\nfrom core.gui import GOSTOP, GO_ONCE\r\nfrom core.sim_engine import SimEngine\r\nfrom core.world_patch_block import World\r\n\r\n# Create a Gene type for pre-execution type checking.\r\n# This will be \"overridden\" in ga_segregation.\r\nGene = NewType('Gene', Any)\r\n\r\n\r\nclass Chromosome(tuple):\r\n \"\"\"\r\n An individual consists primarily of a sequence of Genes, called\r\n a chromosome. We create a class for it simply because it's a\r\n convenient place to store methods.\r\n\r\n \"\"\"\r\n\r\n def chromosome_fitness(self) -> float:\r\n pass\r\n\r\n # len_chrom = len(self)\r\n # # A chromosome is a tuple of Genes, each of which is a Pixel_xy. We use mod (%)\r\n # # so that we can include the distance from chromosome[len_chrom - 1] to chromosome[0]\r\n # distances = [self[i].distance_to(self[(i+1) % len_chrom]) for i in range(len_chrom)]\r\n # fitness = sum(distances)\r\n # return fitness\r\n\r\n def cx_all_diff_chromosome(self: Chromosome, other_chromosome: Chromosome) -> Chromosome:\r\n \"\"\"\r\n chromosome_1 and other_chromosome are the same length.\r\n chromosome_1 is self\r\n\r\n Returns: a selection from chromosome_1 and other_chromosome preserving all_different\r\n \"\"\"\r\n # This ensures that the rotations are non-trivial.\r\n inner_indices = range(1, len(self) - 1) if len(self) > 2 else range(len(self))\r\n self_rotated: Chromosome = self.rotate_by(choice(inner_indices))\r\n other_chromosome_rotated: Chromosome = other_chromosome.rotate_by(choice(inner_indices))\r\n indx = choice(inner_indices)\r\n\r\n child_chromosome_start: Chromosome = self_rotated[:indx]\r\n child_chromosome_end = tuple(gene for gene in other_chromosome_rotated\r\n if gene not in child_chromosome_start)\r\n\r\n child_chromosome: Chromosome = GA_World.chromosome_class(child_chromosome_start + child_chromosome_end)\r\n return child_chromosome[:len(self)]\r\n\r\n def move_gene(self) -> Sequence:\r\n \"\"\"\r\n This mutation operator moves a gene from one place to another.\r\n \"\"\"\r\n (from_index, to_index) = sorted(sample(list(range(len(self))), 2))\r\n list_chromosome: List[Gene] = list(self)\r\n gene_to_move: Gene = list_chromosome[from_index]\r\n revised_list: List[Gene] = list_chromosome[:from_index] + list_chromosome[from_index+1:]\r\n revised_list.insert(to_index, gene_to_move)\r\n # return GA_World.chromosome_class(revised_list)\r\n return revised_list\r\n\r\n def reverse_subseq(self: Chromosome) -> Sequence:\r\n \"\"\" Reverse a subsequence of this chromosome. \"\"\"\r\n # Ensure that the two index positions are different.\r\n (indx_1, indx_2) = sorted(sample(list(range(len(self))), 2))\r\n list_chromosome = list(self)\r\n list_chromosome[indx_1:indx_2] = reversed(list_chromosome[indx_1:indx_2])\r\n # return GA_World.chromosome_class(list_chromosome)\r\n return list_chromosome\r\n\r\n def rotate_by(self, amt: int) -> Chromosome:\r\n return GA_World.chromosome_class(self[amt:] + self[:amt])\r\n\r\n\r\nclass Individual:\r\n \"\"\"\r\n Note: An Individual is NOT an agent. Individual is a separate, stand-alone class.\r\n\r\n An Individual consists of a chromosome and a fitness. \r\n The chromosome is a sequence of Genes. (See type definitions above.) \r\n A chromosomes is stored as a tuple (reather than a list) to ensure that it is immutable.\r\n \"\"\"\r\n def __init__(self, chromosome: Sequence[Gene] = None):\r\n self.chromosome: Chromosome = GA_World.chromosome_class(chromosome)\r\n self.fitness = self.compute_fitness()\r\n\r\n def compute_fitness(self) -> float:\r\n pass\r\n\r\n @staticmethod\r\n def cx_all_diff(ind_1, ind_2) -> Tuple[Individual, Individual]:\r\n \"\"\"\r\n Perform crossover between self and other while preserving all_different.\r\n \"\"\"\r\n child_1 = GA_World.individual_class((ind_1.chromosome).cx_all_diff_chromosome(ind_2.chromosome))\r\n child_2 = GA_World.individual_class((ind_2.chromosome).cx_all_diff_chromosome(ind_1.chromosome))\r\n return (child_1, child_2)\r\n\r\n @property\r\n def discrepancy(self) -> float:\r\n discr = abs(self.fitness - GA_World.fitness_target)\r\n return discr\r\n\r\n def mate_with(self, other) -> Tuple[Individual, Individual]:\r\n pass\r\n\r\n def mutate(self) -> Individual:\r\n pass\r\n\r\n\r\nclass GA_World(World):\r\n \"\"\"\r\n The Population holds the collection of Individuals that will undergo evolution.\r\n \"\"\"\r\n fitness_target = None\r\n individual_class = Individual\r\n chromosome_class = Chromosome\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n # noinspection PyTypeChecker\r\n self.best_ind: Individual = None\r\n self.generations = None\r\n self.pop_size = None\r\n # noinspection PyTypeChecker\r\n self.population: List[Individual] = None\r\n\r\n self.mating_op = None\r\n self.tournament_size = None\r\n\r\n self.BEST = 'best'\r\n self.WORST = 'worst'\r\n\r\n # noinspection PyNoneFunctionAssignment\r\n def generate_2_children(self):\r\n \"\"\" Generate two children and put them into the population. \"\"\"\r\n parent_1 = self.get_parent()\r\n parent_2 = self.get_parent()\r\n (child_1, child_2) = parent_1.mate_with(parent_2)\r\n child_1_mutated: Individual = child_1.mutate()\r\n child_2_mutated: Individual = child_2.mutate()\r\n\r\n child_1_mutated.compute_fitness()\r\n child_2_mutated.compute_fitness()\r\n\r\n dest_1_indx: int = self.select_gene_index(self.WORST, self.tournament_size)\r\n dest_2_indx: int = self.select_gene_index(self.WORST, self.tournament_size)\r\n # noinspection PyTypeChecker\r\n self.population[dest_1_indx] = min([child_1, child_1_mutated], key=lambda c: c.discrepancy)\r\n # noinspection PyTypeChecker\r\n self.population[dest_2_indx] = min([child_2, child_2_mutated], key=lambda c: c.discrepancy)\r\n\r\n def gen_individual(self) -> Individual:\r\n pass\r\n\r\n def get_best_individual(self) -> Individual:\r\n best_index = self.select_gene_index(self.BEST, len(self.population))\r\n best_individual = self.population[best_index]\r\n return best_individual\r\n\r\n def get_parent(self) -> Individual:\r\n if randint(0, 99) < SimEngine.gui_get('prob_random_parent'):\r\n parent = self.gen_individual()\r\n else:\r\n parent_indx = self.select_gene_index(self.BEST, self.tournament_size)\r\n parent = self.population[parent_indx]\r\n # noinspection PyTypeChecker\r\n return parent\r\n\r\n def handle_event(self, event):\r\n if event == 'fitness_target':\r\n GA_World.fitness_target = SimEngine.gui_get('fitness_target')\r\n self.resume_ga()\r\n return\r\n super().handle_event(event)\r\n\r\n def initial_population(self) -> List[Individual]:\r\n \"\"\"\r\n Generate the initial population. Use gen_individual from the subclass.\r\n \"\"\"\r\n population = [self.gen_individual() for _ in range(self.pop_size)]\r\n return population\r\n\r\n def resume_ga(self):\r\n \"\"\" \r\n This is used when one of the parameters changes dynamically. \r\n It is called from handle_event. (See above.)\r\n \"\"\"\r\n if self.done:\r\n self.done = False\r\n self.best_ind = None\r\n SimEngine.gui_set('best_fitness', value=None)\r\n go_stop_button = gui.WINDOW[GOSTOP]\r\n SimEngine.gui_set(GOSTOP, enabled=True)\r\n SimEngine.gui_set(GO_ONCE, enabled=True)\r\n go_stop_button.click()\r\n self.set_results()\r\n\r\n def select_gene_index(self, best_or_worst, tournament_size) -> int:\r\n \"\"\" Run a tournament to select the index of a best or worst individual in a sample. \"\"\"\r\n min_or_max = min if best_or_worst == self.BEST else max\r\n candidate_indices = sample(range(self.pop_size), min(tournament_size, self.pop_size))\r\n selected_index = min_or_max(candidate_indices, key=lambda i: self.population[i].discrepancy)\r\n return selected_index\r\n\r\n @staticmethod\r\n def seq_to_chromosome(sequence: Sequence[Gene]): # -> Chromosome:\r\n \"\"\" Converts a list to a Chromosome. \"\"\"\r\n return sequence\r\n # return GA_World.chromosome_class(tuple(sequence))\r\n\r\n def set_results(self):\r\n \"\"\" Find and display the best individual. \"\"\"\r\n # noinspection PyNoneFunctionAssignment\r\n current_best_ind = self.get_best_individual()\r\n if self.best_ind is None or current_best_ind.discrepancy < self.best_ind.discrepancy:\r\n self.best_ind = current_best_ind\r\n SimEngine.gui_set('best_fitness', value=round(self.best_ind.fitness, 1))\r\n SimEngine.gui_set('discrepancy', value=round(self.best_ind.discrepancy, 1))\r\n SimEngine.gui_set('generations', value=self.generations)\r\n\r\n def setup(self):\r\n # Create a list of Individuals as the initial population.\r\n # self.pop_size must be even since we generate children two at a time.\r\n self.pop_size = (SimEngine.gui_get('pop_size')//2)*2\r\n self.tournament_size = SimEngine.gui_get('tourn_size')\r\n GA_World.fitness_target = SimEngine.gui_get('fitness_target')\r\n self.population = self.initial_population()\r\n self.best_ind = None\r\n self.generations = 0\r\n self.set_results()\r\n\r\n def step(self):\r\n if self.best_ind and self.best_ind.discrepancy < 0.05:\r\n self.done = True\r\n return\r\n\r\n for i in range(self.pop_size//2):\r\n self.generate_2_children()\r\n\r\n self.generations += 1\r\n self.set_results()\r\n\r\n\r\n# ############################################## Define GUI ############################################## #\r\nimport PySimpleGUI as sg\r\ngui_left_upper = [\r\n\r\n [sg.Text('Best:', pad=(None, (0, 0))),\r\n sg.Text(' 0.0', key='best_fitness', pad=(None, (0, 0))),\r\n sg.Text('Discrepancy:', pad=((20, 0), (0, 0))),\r\n sg.Text(' .0', key='discrepancy', pad=(None, (0, 0)))],\r\n\r\n [sg.Text('Generations:', pad=((0, 0), (0, 0))),\r\n sg.Text('000000000', key='generations', pad=(None, (0, 0))),\r\n ],\r\n\r\n [sg.Text('Population size\\n(must be even)', pad=((0, 5), (20, 0))),\r\n sg.Slider(key='pop_size', range=(4, 100), resolution=2, default_value=10,\r\n orientation='horizontal', size=(10, 20))\r\n ],\r\n\r\n [sg.Text('Tournament size', pad=((0, 5), (10, 0))),\r\n sg.Slider(key='tourn_size', range=(3, 15), resolution=1, default_value=7,\r\n orientation='horizontal', size=(10, 20))\r\n ],\r\n\r\n [sg.Text('Prob move gene', pad=((0, 5), (20, 0))),\r\n sg.Slider(key='move_gene', range=(0, 100), default_value=5,\r\n orientation='horizontal', size=(10, 20))\r\n ],\r\n\r\n [sg.Text('Prob reverse subsequence', pad=((0, 5), (20, 0))),\r\n sg.Slider(key='reverse_subseq', range=(0, 100), default_value=5,\r\n orientation='horizontal', size=(10, 20))\r\n ],\r\n\r\n [sg.Text('Prob random parent', pad=((0, 5), (20, 0))),\r\n sg.Slider(key='prob_random_parent', range=(0, 100), default_value=5,\r\n orientation='horizontal', size=(10, 20))\r\n ],\r\n\r\n ]\r\n","sub_path":"core/ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":12048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"58444383","text":"#!/usr/bin/env python3\n\"\"\"\nInitial IAGOS data testing file\n===================================================================\n-------------------------------------------------------------------\n---v1.0---Initial_File---------------------------------------------\n----------[DEPRECATED]-There_is_a_newer_version_of_this_file-------\n-------------------------------------------------------------------\n===================================================================\nReads netCDF files and produces plots of aircraft temperature and\naltitude.\n===================================================================\n\"\"\"\nimport netCDF4 as nc\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# /mnt/Data/Bath/Temp._IAGOS_data/iagos_banyard_20191003124813\n\n# Change current working directory appropriately\nos.chdir('..')\n\n\"\"\"Find directory and read netCDF data\"\"\"\ninfile = '/mnt/Data/Bath/Temp._IAGOS_data'\ninfile += '/iagos_banyard_20191003124813'\ninfile += '/IAGOS_timeseries_1994080122151749.nc'\nprint(infile)\ndata = nc.Dataset(infile)\n\n\"\"\"Download variables\"\"\"\n# UTC time in seconds since 1994-08-01 00:00:00\ndata_UTC_time = data.variables['UTC_time'][:]\n# Longitude\ndata_lon = data.variables['lon'][:]\n# Latitude\ndata_lat = data.variables['lat'][:]\n# (NOTE: Many of the below parameters have associated validity flags)\n# Barometric altitude measured by aircraft\ndata_baro_alt_AC = data.variables['baro_alt_AC'][:]\n# Air pressure mesaured by aircraft\ndata_air_press_AC = data.variables['air_press_AC'][:]\n# Aircraft air speed\ndata_air_speed_AC = data.variables['air_speed_AC'][:]\n# Aircraft ground speed\ndata_ground_speed_AC = data.variables['ground_speed_AC'][:]\n# Air temperature\ndata_air_temp_AC = data.variables['air_temp_AC'][:]\n# Stagnation Air temperature\ndata_air_stag_temp_AC = data.variables['air_stag_temp_AC'][:]\n# Wind direction\ndata_wind_dir_AC = data.variables['wind_dir_AC'][:]\n# Wind speed\ndata_wind_speed_AC = data.variables['wind_speed_AC'][:]\n# Zonal wind\ndata_zon_wind_AC = data.variables['zon_wind_AC'][:]\n# Meridional wind\ndata_mer_wind_AC = data.variables['mer_wind_AC'][:]\n# Air temperature (measured by MOZAIC package)\ndata_air_temp_PM = data.variables['air_temp_PM'][:]\n# Stagnation Air temperature (MOZAIC)\ndata_air_stag_temp_PM = data.variables['air_stag_temp_PM'][:]\n\n# Converted time\ndata_time = nc.num2date(data.variables['UTC_time'][:],\\\ncalendar = 'standard', units = data.variables['UTC_time'].units)\n\nprint(len(data_time))\nprint(len(data_air_temp_AC))\n\nfor i in range(1):\n\tprint(data_time[i])\n\tprint(data_air_temp_AC[i])\ndata.close()\n\n\"\"\"Plotting\"\"\"\nX = data_time\nY1 = data_air_temp_AC\nY2 = data_baro_alt_AC\nfig = plt.figure()\nax1 = fig.add_subplot(111)\nax1.plot(X,Y1, 'black')\nax2 = ax1.twinx()\nax2.plot(X,Y2, 'red')\nplt.title('Single Flight')\nplt.savefig(\"test.png\", dpi=300)\n","sub_path":"Programs/IAGOS_plots_.py/IAGOS_plots_v1.0.py","file_name":"IAGOS_plots_v1.0.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"242816430","text":"# Experiment without fault tolerance class, six classes.\n\nimport csv\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport scikitplot as sklpt\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_score\n\nx = pickle.load(open('../../datasets/x-no-1', 'rb'))\ny = pickle.load(open('../../datasets/y-no-1', 'rb'))\n\nY = []\nfor o in y:\n if o == 0:\n Y.append([1, 0, 0, 0, 0, 0, 0])\n if o == 1:\n Y.append([0, 1, 0, 0, 0, 0, 0])\n if o == 2:\n Y.append([0, 0, 1, 0, 0, 0, 0])\n if o == 3:\n Y.append([0, 0, 0, 1, 0, 0, 0])\n if o == 4:\n Y.append([0, 0, 0, 0, 1, 0, 0])\n if o == 5:\n Y.append([0, 0, 0, 0, 0, 1, 0])\n if o == 6:\n Y.append([0, 0, 0, 0, 0, 0, 1])\n\nx = torch.from_numpy(x)\nY = np.array(Y)\nY = torch.from_numpy(Y)\n\ncriterion = nn.MSELoss()\nepochs = 5000\n\n# Device configuration\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nx = x.to(device)\nY = Y.to(device)\n\n# Defining folds\nkf = StratifiedKFold(n_splits=10)\nlrate = 0.0006\n\naccuracies_train = []\naccuracies_test = []\nprecisions = []\nrecalls = []\nf1_scores = []\n\nn_fold = 1\n\nfor train_index, test_index in kf.split(x, y):\n model = nn.Sequential(nn.Linear(148, 25), nn.Tanh(), nn.Linear(25, 7), nn.Tanh())\n model.to(device)\n\n optimizer = optim.SGD(model.parameters(), lr=lrate)\n\n accuracy_train_epochs = []\n accuracy_test_epochs = []\n precision_epochs = []\n recall_epochs = []\n f1_epochs = []\n\n for e in range(epochs):\n\n y_true_train = []\n y_clas_train = []\n\n for xi, yo in zip(x[train_index], Y[train_index]):\n optimizer.zero_grad()\n output = model(xi.float())\n y_true_train.append(torch.argmax(yo).cpu().detach().numpy())\n y_clas_train.append(torch.argmax(output).cpu().detach().numpy())\n loss = criterion(output, yo.float())\n loss.backward()\n optimizer.step()\n \n y_true = []\n y_clas = []\n \n for xi, yo in zip(x[test_index], Y[test_index]):\n output = model(xi.float())\n y_true.append(torch.argmax(yo).cpu().detach().numpy())\n y_clas.append(torch.argmax(output).cpu().detach().numpy())\n \n if (e == epochs-1):\n sklpt.metrics.plot_confusion_matrix(y_true, y_clas, \n title= \"Six Classes Confusion Matrix: Fold \" + str(n_fold), \n normalize=True, text_fontsize='small')\n plt.savefig('cf-6-classes-' + str(n_fold) + '.png')\n plt.clf()\n plt.close()\n \n # Metrics in this fold\n\n accuracy_train_epochs.append(accuracy_score(y_true_train, y_clas_train))\n accuracy_test_epochs.append(accuracy_score(y_true, y_clas))\n precision_epochs.append(precision_score(y_true, y_clas, average='macro', zero_division=0))\n recall_epochs.append(recall_score(y_true, y_clas, average='macro', zero_division=0))\n f1_epochs.append(f1_score(y_true, y_clas, average='macro', zero_division=0))\n\n print(\"Fold {}, Epoch {}, Accuracy train {}, Accuracy test {}, Precision {}, Recall {}, F1 {}\".format(\n n_fold,\n e, \n accuracy_train_epochs[-1], \n accuracy_test_epochs[-1], \n precision_epochs[-1], \n recall_epochs[-1],\n f1_epochs[-1]))\n\n\n plt.title('Convergence Plot in fold ' + str(n_fold))\n plt.xlabel('Epochs')\n plt.ylabel('Values')\n plt.plot(range(epochs), accuracy_train_epochs, label='Train Accuracy')\n plt.plot(range(epochs), accuracy_test_epochs, label=\" Test Accuracy\")\n plt.plot(range(epochs), precision_epochs, label=\"Test Precision\")\n plt.plot(range(epochs), recall_epochs, label='Test Recall')\n plt.plot(range(epochs), f1_epochs, label='Test F1-score')\n plt.legend(title='Metrics')\n plt.savefig(\"convergence-\" + str(n_fold))\n plt.clf()\n plt.close()\n\n accuracies_train.append(accuracy_train_epochs[-1])\n accuracies_test.append(accuracy_test_epochs[-1])\n precisions.append(precision_epochs[-1])\n recalls.append(recall_epochs[-1])\n f1_scores.append(f1_epochs[-1])\n\n n_fold = n_fold + 1\n\nwith open(\"results-6-classes.csv\", 'w', encoding='UTF8', newline='') as csvfile:\n writer = csv.writer(csvfile)\n fold = 1\n header = ['fold', 'accuracy train', 'accuracy test', 'precision', 'recall', 'f1_score']\n writer.writerow(header)\n for atrain, atest, p, r, f1 in zip(accuracies_train,\n accuracies_test, \n precisions,\n recalls,\n f1_scores):\n row = [fold, atrain, atest, p, r, f1]\n writer.writerow(row)\n fold += 1\n\n avgs = [\"Average\",\n np.mean(np.array(accuracies_train)),\n np.mean(np.array(accuracies_test)),\n np.mean(np.array(precisions)),\n np.mean(np.array(recalls)),\n np.mean(np.array(f1_scores)) ]\n writer.writerow(avgs)","sub_path":"balanced-experiments/nn/experiment-6-classes/experiment-6-classes.py","file_name":"experiment-6-classes.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"229532024","text":"\"\"\"\nRobertHalfBE subspider created on the top of RobertHalfDE\n\nscrapy crawl roberthalf_be -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.roberthalf.be/jobs?izjobsearch.keywords=&izjobsearch.searchTitleOnly=Y&locations=-1&izjobsearch.submittedJobTypes1=Temp&izjobsearch.submittedJobTypes2=Perm&izjobsearch.submittedJobTypes3=Contracting&izjobsearch.performSearch=true\"\n\nSample URL:\n http://www.roberthalf.be/jobs?izjobsearch.keywords=&izjobsearch.searchTitleOnly=Y&locations=-1&izjobsearch.submittedJobTypes1=Temp&izjobsearch.submittedJobTypes2=Perm&izjobsearch.submittedJobTypes3=Contracting&izjobsearch.performSearch=true\n\"\"\"\n\nfrom brightcorp.spiders.roberthalf_de import RobertHalfDE\nfrom brightcorp.items import BrightcorpItemLoader\n\n\nclass RobertHalfBE(RobertHalfDE):\n\n name = 'roberthalf_be'\n # Taking table header and map to english headers\n mapping_table_headers = {\n 'Job Title': 'title',\n 'Location': 'location',\n 'Ref.': 'ref_id',\n 'Division': 'jobcategory',\n 'Post Date': 'date',\n }\n","sub_path":"brightcorp/brightcorp/spiders/roberthalf_be.py","file_name":"roberthalf_be.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"61932172","text":"import gym\nimport pytest\n\n\n@pytest.fixture(scope='module')\ndef env():\n env = gym.make('ma_gym:PongDuel-v0')\n yield env\n env.close()\n\n\ndef test_init(env):\n assert env.n_agents == 2\n\n\ndef test_reset(env):\n env.reset()\n assert env._step_count == 0\n assert env._total_episode_reward == [0 for _ in range(env.n_agents)]\n assert env._agent_dones == [False for _ in range(env.n_agents)]\n\n\ndef test_reset_after_episode_end(env):\n env.reset()\n done = [False for _ in range(env.n_agents)]\n step_i = 0\n ep_reward = [0 for _ in range(env.n_agents)]\n while not all(done):\n step_i += 1\n _, reward_n, done, _ = env.step(env.action_space.sample())\n for i in range(env.n_agents):\n ep_reward[i] += reward_n[i]\n\n assert step_i == env._step_count\n assert env._total_episode_reward == ep_reward\n test_reset(env)\n\n\ndef test_observation_space(env):\n obs = env.reset()\n assert env.observation_space.contains(obs)\n done = [False for _ in range(env.n_agents)]\n while not all(done):\n _, reward_n, done, _ = env.step(env.action_space.sample())\n assert env.observation_space.contains(obs)\n assert env.observation_space.contains(env.observation_space.sample())\n","sub_path":"tests/envs/test_pong_duel.py","file_name":"test_pong_duel.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"26154541","text":"from past.builtins import basestring\n\n# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration\n\ndef hitColls2SimulatedDetectors(inputlist):\n \"\"\"Build a dictionary from the list of containers in the metadata\"\"\"\n simulatedDetectors = []\n simulatedDictionary = {'PixelHits': 'pixel', 'SCT_Hits': 'SCT', 'TRTUncompressedHits': 'TRT',\n 'BCMHits': 'BCM', 'LucidSimHitsVector': 'Lucid', 'LArHitEMB': 'LAr',\n 'LArHitEMEC': 'LAr', 'LArHitFCAL': 'LAr', 'LArHitHEC': 'LAr', 'LArHitHGTD': 'HGTD',\n 'MBTSHits': 'Tile', 'TileHitVec': 'Tile', 'MDT_Hits': 'MDT',\n 'MicromegasSensitiveDetector': 'Micromegas',\n 'sTGCSensitiveDetector': 'sTGC',\n 'CSC_Hits': 'CSC', 'TGC_Hits': 'TGC', 'RPC_Hits': 'RPC',\n 'TruthEvent': 'Truth'} #'': 'ALFA', '': 'ZDC',\n for entry in inputlist:\n if entry[1] in simulatedDictionary:\n if simulatedDictionary[entry[1]] not in simulatedDetectors:\n simulatedDetectors += [simulatedDictionary[entry[1]]]\n return simulatedDetectors\n\ndef getHITSFile(runArgs):\n from AthenaCommon.AthenaCommonFlags import athenaCommonFlags\n if hasattr(runArgs,\"inputHITSFile\"):\n athenaCommonFlags.FilesInput.set_Value_and_Lock( runArgs.inputHITSFile )\n return runArgs.inputHITSFile[0]\n elif hasattr(runArgs,\"inputHitsFile\"):\n athenaCommonFlags.FilesInput.set_Value_and_Lock( runArgs.inputHitsFile )\n return runArgs.inputHitsFile[0]\n else:\n raise SystemExit(\"No HITS file in runArgs!!\")\n\ndef HitsFilePeeker(runArgs, skeletonLog):\n from PyUtils.MetaReader import read_metadata\n try:\n input_file = getHITSFile(runArgs)\n metadata_peeker = read_metadata(input_file, mode = 'peeker')\n metadata_peeker = metadata_peeker[input_file] # promote all keys one level up\n\n metadata_full = read_metadata(input_file, mode = 'full')\n metadata_full = metadata_full[input_file] # promote all keys one level up\n except AssertionError:\n skeletonLog.error(\"Failed to open input file: %s\", getHITSFile(runArgs))\n # check eventTypes of input file\n if 'eventTypes' in metadata_peeker:\n import re\n if 'IS_SIMULATION' not in metadata_peeker['eventTypes']:\n skeletonLog.error('This input file has incorrect evt_type: %s', metadata_peeker['eventTypes'])\n skeletonLog.info('Please make sure you have set input file metadata correctly.')\n skeletonLog.info('Consider using the job transforms for earlier steps if you aren\\'t already.')\n #then exit gracefully\n raise SystemExit(\"Input file eventTypes is incorrect, please check your g4sim and evgen jobs.\")\n else :\n skeletonLog.warning('Could not find \\'eventTypes\\' key in metadata. Unable to that check eventTypes is correct.')\n\n metadatadict = dict()\n\n if metadata_full:\n if '/Simulation/Parameters' in metadata_full:\n metadatadict = metadata_full['/Simulation/Parameters']\n\n ##Get IOVDbGlobalTag\n if 'IOVDbGlobalTag' not in metadatadict:\n try:\n assert metadata_full['/TagInfo']['IOVDbGlobalTag'] is not None\n metadatadict['IOVDbGlobalTag'] = metadata_full['/TagInfo']['IOVDbGlobalTag']\n except:\n try:\n assert metadata_full['/Digitization/Parameters']['IOVDbGlobalTag'] is not None\n metadatadict['IOVDbGlobalTag'] = metadata_full['/Digitization/Parameters']['IOVDbGlobalTag']\n except:\n skeletonLog.warning(\"Failed to find IOVDbGlobalTag.\")\n else:\n ##Patch for older hit files\n if 'SimulatedDetectors' not in metadatadict:\n if 'itemList' in metadata_peeker:\n metadatadict['SimulatedDetectors'] = hitColls2SimulatedDetectors(metadata_peeker['itemList'])\n else :\n metadatadict['SimulatedDetectors'] = ['pixel','SCT','TRT','BCM','Lucid','LAr','Tile','MDT','CSC','TGC','RPC','Truth']\n\n import re\n from AthenaCommon.GlobalFlags import globalflags\n globalflags.DataSource=\"geant4\"\n ## Configure DetDescrVersion\n if hasattr(runArgs,\"geometryVersion\"):\n inputGeometryVersion = runArgs.geometryVersion\n if isinstance(inputGeometryVersion, basestring) and inputGeometryVersion.endswith(\"_VALIDATION\"):\n inputGeometryVersion = inputGeometryVersion.replace(\"_VALIDATION\", \"\")\n if 'SimLayout' in metadatadict:\n if not re.match(metadatadict['SimLayout'], inputGeometryVersion):\n skeletonLog.warning(\"command-line geometryVersion (%s) does not match the value used in the Simulation step (%s) !\",\n inputGeometryVersion, metadatadict['SimLayout'])\n globalflags.DetDescrVersion.set_Value_and_Lock( inputGeometryVersion )\n skeletonLog.info(\"Using geometryVersion from command-line: %s\", globalflags.DetDescrVersion.get_Value())\n elif 'SimLayout' in metadatadict:\n globalflags.DetDescrVersion.set_Value_and_Lock( metadatadict['SimLayout'] )\n skeletonLog.info(\"Using geometryVersion from HITS file metadata %s\", globalflags.DetDescrVersion.get_Value())\n else:\n raise SystemExit(\"geometryVersion not found in HITS file metadata or on transform command-line!\")\n\n ## Configure ConditionsTag\n if hasattr(runArgs,\"conditionsTag\"):\n if 'IOVDbGlobalTag' in metadatadict:\n if not re.match(metadatadict['IOVDbGlobalTag'], runArgs.conditionsTag):\n skeletonLog.warning(\"command-line conditionsTag (%s) does not match the value used in the Simulation step (%s) !\",\n runArgs.conditionsTag, metadatadict['IOVDbGlobalTag'])\n if not globalflags.ConditionsTag.is_locked():\n globalflags.ConditionsTag.set_Value_and_Lock( runArgs.conditionsTag )\n skeletonLog.info(\"Using conditionsTag from command-line: %s\", globalflags.ConditionsTag.get_Value())\n else:\n skeletonLog.info(\"globalflags.ConditionsTag already locked to %s - will not alter it.\", globalflags.ConditionsTag.get_Value())\n elif 'IOVDbGlobalTag' in metadatadict:\n globalflags.ConditionsTag.set_Value_and_Lock( metadatadict['IOVDbGlobalTag'] )\n skeletonLog.info(\"Using conditionsTag from HITS file metadata %s\", globalflags.ConditionsTag.get_Value())\n else:\n skeletonLog.fatal(\"conditionsTag not found in HITS file metadata or on transform command-line!\")\n raise SystemExit(\"conditionsTag not found in HITS file metadata or on transform command-line!\")\n\n ## Configure DetFlags\n if 'SimulatedDetectors' in metadatadict:\n from AthenaCommon.DetFlags import DetFlags\n # by default everything is off\n DetFlags.all_setOff()\n skeletonLog.debug(\"Switching on DetFlags for subdetectors which were simulated\")\n simulatedDetectors = eval(metadatadict['SimulatedDetectors'])\n for subdet in simulatedDetectors:\n cmd='DetFlags.%s_setOn()' % subdet\n skeletonLog.debug(cmd)\n try:\n exec(cmd)\n except:\n skeletonLog.warning('Failed to switch on subdetector %s',subdet)\n DetFlags.simulateLVL1.all_setOff()\n DetFlags.digitize.all_setOff()\n if hasattr(DetFlags, 'overlay'): DetFlags.overlay.all_setOff()\n DetFlags.pileup.all_setOff()\n DetFlags.readRDOBS.all_setOff()\n DetFlags.readRDOPool.all_setOff()\n DetFlags.readRIOBS.all_setOff()\n DetFlags.readRIOPool.all_setOff()\n DetFlags.makeRIO.all_setOff()\n DetFlags.writeBS.all_setOff()\n DetFlags.writeRDOPool.all_setOff()\n DetFlags.writeRIOPool.all_setOff()\n print('{} -> __Test__001__:\\n{}'.format(__file__, metadatadict))\n return\n","sub_path":"Simulation/SimuJobTransforms/python/HitsFilePeeker.py","file_name":"HitsFilePeeker.py","file_ext":"py","file_size_in_byte":8000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"430502621","text":"import datetime\nimport discord\nimport json\nimport re\n\nfrom discord.ext import commands, tasks\n\nfrom utils.functions import func\nfrom utils import sql\n\nclass Cards(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n self.network_chat_id = 626749195318984704\n self.shoob_id = 673362753489993749\n self.most_recent_card_name = None\n self.most_recent_tier = None\n self.card_id = None\n\n # Event\n\n self.event = {\"Started\": False, \"TotalDuration\": None, \"Remaining\": None, \"Reward\": None}\n self.event_message = None\n self.leaderboard_message = None\n self.channel = None\n\n self.update.start()\n\n with open(\"./modules/data/cards/MentionRoles.json\") as f:\n self.roles = json.load(f)\n\n\n def ReloadJSON(self):\n with open(\"./modules/data/cards/MentionRoles.json\") as f:\n self.roles = json.load(f)\n return self.roles\n\n @commands.Cog.listener()\n async def on_message(self, message):\n\n if message.channel.id != self.network_chat_id:\n return\n\n if message.author.id != self.shoob_id:\n return\n\n # Claiming -------------------------------------\n\n for embed in message.embeds:\n embed = embed.to_dict()\n\n try:\n if \"To claim, use:\" in embed[\"description\"]:\n self.card_id = message.id\n self.most_recent_card_name = embed['title'][:embed['title'].index(\"Tier\")]\n tier = embed['title'].split(\":\")\n self.most_recent_tier = tier[1].replace(\" \", \"\")\n sql.AddCard(self.card_id, self.most_recent_card_name, tier[1], datetime.datetime.utcnow(), embed['image']['url'])\n if int(tier[1]) > 4:\n await self.MentionRoles(message, self.most_recent_card_name, tier[1])\n\n if f\"got the card! `{self.most_recent_card_name[:-1]}`\" in embed[\"description\"]:\n version = embed['description'].split(\":\")\n ver = version[3].split(\".\")\n v = ver[0].replace(\"`\", \"\")\n numbers = re.findall(r'[0-9]+', embed['description'])\n\n if self.event[\"Started\"]:\n sql.CardClaimed(self.card_id, numbers[1], v, datetime.datetime.utcnow(), True)\n else:\n sql.CardClaimed(self.card_id, numbers[1], v, datetime.datetime.utcnow())\n\n user = await self.bot.fetch_user(numbers[1])\n\n if not sql.accountExists(user.id):\n return await user.send(embed=func.ErrorEmbed(f\"Hey! You claimed a card but dont have a sCoin account? What are you doing!? Join now by typing h.sCoin in MAL.\"))\n\n useracc = sql.getAccount(user.id)\n amount = 0.02 * float(self.most_recent_tier)\n sql.setCoins(user.id, float(useracc[2]) + amount)\n\n sql.sLog(message.author.id, 3, f\"Added {amount} to {message.author.name}s eCoin balance\", datetime.datetime.utcnow())\n await message.channel.send(embed=func.Embed(f\"{user.mention} Gained {amount} sCoin for claiming {self.most_recent_card_name}: Tier {self.most_recent_tier}!\"))\n\n except Exception as e:\n print(e)\n\n # ----------------------------------------------\n\n @commands.group(invoke_without_command=True)\n async def card(self, ctx):\n await ctx.send(embed=func.Embed(f\"`{ctx.prefix}card stats @user` - Get a users cards stats\\n`{ctx.prefix}card history` - View card history\"))\n\n @card.group(invoke_without_command=True)\n async def stats(self, ctx, user: discord.User=None):\n if not user:\n return\n\n Stats = [sql.TotalCardCount(user.id), sql.LastClaimedCard(user.id), sql.RarestCard(user.id)]\n\n if Stats:\n embed = discord.Embed(colour=0xcf53ee)\n embed.set_author(name=f\"{user.name} - Card Stats\", icon_url=user.avatar_url)\n embed.add_field(name=\"Total Cards\", value=Stats[0], inline=True)\n embed.add_field(name=\"Last Claimed\", value=Stats[1], inline=True)\n embed.add_field(name=\"Rarest Card\", value=Stats[2], inline=True)\n await ctx.send(embed=embed)\n else:\n await ctx.send(\"That user has not claimed any cards!\")\n\n @card.group(invoke_without_command=True)\n async def history(self, ctx):\n sorted_cards = []\n\n cards = sql.CardsHistory()\n\n i = 0\n for row in cards:\n i += 1\n if row[1] == 0:\n sorted_cards.append(f\"{row[0]}- Tier {row[2]} is __unclaimed__\")\n if i == 20:\n last_time = row[3]\n if row[1] == 1:\n sorted_cards.append(f\"{row[0]}- Tier {row[2]} is __claimed__\")\n if i == 20:\n last_time = row[3]\n\n embed = discord.Embed(\n description=\"\\n\".join(sorted_cards),\n colour=0xcf53ee,\n )\n embed.set_footer(text=f\"Last Card Sent: {last_time}\")\n\n await ctx.send(embed=embed)\n\n async def MentionRoles(self, message, name, tier):\n self.roles = self.ReloadJSON()\n\n if int(tier) == 5:\n channel = self.bot.get_channel(self.network_chat_id)\n role = discord.utils.get(message.guild.roles, id=self.roles[\"Tier5\"])\n await channel.send(f\"{role.mention} {name}- Tier 5 has spawned!\")\n\n if int(tier) == 6:\n channel = self.bot.get_channel(self.network_chat_id)\n role = discord.utils.get(message.guild.roles, id=self.roles[\"Tier6\"])\n await channel.send(f\"{role.mention} {name}- Tier 6 has spawned!\")\n\n @commands.command()\n async def mentions(self, ctx, tier:int=None, role:int=None):\n if not role or not tier:\n await ctx.send(embed=func.Embed(f\"Use the command like this:\\n\\n{ctx.prefix}mentions [5 / 6] [roleid]\"))\n\n if tier < 5:\n return\n\n check = discord.utils.get(ctx.guild.roles, id=role)\n\n if not check:\n return await ctx.send(embed=func.ErrorEmbed(\"I couldnt find that role\"))\n\n self.roles[f\"Tier{tier}\"] = role\n with open(\"./modules/data/cards/MentionRoles.json\", \"w\") as f:\n json.dump(self.roles, f)\n\n await ctx.send(\"Updated\")\n\n # Event --------------------------------------------------------\n\n @tasks.loop(seconds=5)\n async def update(self):\n\n if not self.event_message or not self.event[\"Started\"]:\n return\n\n try:\n if self.event[\"Remaining\"] < 0:\n endembed = await self.leaderboardsMessage(True)\n await self.leaderboard_message.edit(embed=endembed)\n self.ResetEvent()\n\n embed = await self.EventMessage()\n self.event[\"Remaining\"] -= 5\n await self.event_message.edit(embed=embed)\n\n embed1 = await self.leaderboardsMessage()\n await self.leaderboard_message.edit(embed=embed1)\n except Exception as e:\n print(e)\n\n @commands.group()\n async def shoob(self, ctx, event = None, duration = None, *args):\n\n if not await sql.isStaff(ctx.author):\n return await ctx.send(embed=func.NoPerm())\n\n if not event or not duration or not args:\n return await ctx.send(embed=func.Embed(f\"If you want to start an event use the command like this:\\n\\n{ctx.prefix}shoob event [duration] [card]\\n\\nDurations: m, h, d, w\"))\n\n self.event[\"Reward\"] = ' '.join(args)\n self.event[\"TotalDuration\"] = self.timeformat(duration)\n self.event[\"Remaining\"] = self.event[\"TotalDuration\"]\n self.channel = ctx.channel\n\n embed = await self.EventMessage()\n self.event_message = await ctx.send(embed=embed)\n self.event[\"Started\"] = True\n\n embed = await self.leaderboardsMessage()\n self.leaderboard_message = await ctx.send(embed=embed)\n\n @shoob.group()\n async def cancel(self, ctx):\n if not await sql.isStaff(ctx.author):\n return ctx.send(embed=func.NoPerm())\n\n async def leaderboardsMessage(self, end=False):\n\n rows = sql.GetLeaderboard()\n rows_sorted = []\n i = 1\n\n if rows and not end:\n for card in rows:\n user = await self.bot.fetch_user(card[1])\n rows_sorted.append(f\"👤 {i}. {user.mention} {card[2]}\")\n i += 1\n\n desc = \"\\n\".join(rows_sorted)\n\n if end:\n self.event[\"Started\"] = False\n for card in rows:\n if i == 1:\n user = await self.bot.fetch_user(card[1])\n rows_sorted.append(f\"Congratulations {user.mention}, you've won {self.event['Reward']}\")\n rows_sorted.append(\"\")\n rows_sorted.append(f\"🏆 {user.mention} {card[2]}\")\n if i == 2 or i == 3:\n user = await self.bot.fetch_user(card[1])\n rows_sorted.append(f\"🏅 {user.mention} {card[2]}\")\n\n i += 1\n\n desc = \"\\n\".join(rows_sorted)\n\n if not rows:\n desc = \"No cards have been claimed yet.\"\n\n embed = discord.Embed(\n description=desc,\n colour=0xcf53ee\n )\n\n rows_sorted.clear()\n return embed\n\n def ResetEvent(self):\n self.event = {\"Started\": False, \"TotalDuration\": None, \"Remaining\": None, \"Reward\": None}\n self.event_message = None\n self.leaderboard_message = None\n self.channel = None\n\n async def EventMessage(self):\n\n Duration = str(datetime.timedelta(seconds=int(self.event[\"TotalDuration\"])))\n\n embed = discord.Embed(\n description=f\"Ok! Starting an event with a duration of {Duration} with a reward of **{self.event['Reward']}**.\",\n colour=0xcf53ee,\n )\n embed.set_footer(text=\"Duration Remaining: {}\".format(str(datetime.timedelta(seconds=int(self.event[\"Remaining\"])))))\n\n return embed\n\n def timeformat(self, st): # Get Seconds\n\n available_times = ['m', 'h', 'd', 'w']\n multiplier = [60, 3600, 86400, 604800]\n time = ''\n\n try:\n for i in st:\n try:\n time += str(int(i))\n except:\n if i in available_times:\n time += i\n break\n except:\n return False\n\n if time == '':\n return False\n\n for i, v in enumerate(available_times):\n if v in time:\n return int(time[:-1]) * multiplier[i]\n\n try:\n return int(time)\n except:\n pass\n\n return False\n\ndef setup(bot):\n bot.add_cog(Cards(bot))","sub_path":"modules/Cards.py","file_name":"Cards.py","file_ext":"py","file_size_in_byte":11006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"252674715","text":"#-*- coding:utf-8 -*-\r\n\r\nimport requests\r\nimport re,os\r\nimport threading\r\nimport time\r\n\r\ndef store_path(path):\r\n path = path.strip()\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n return True\r\n else:\r\n return False\r\n\r\ndef get_image(url):\r\n req = requests.get(url, timeout=30)\r\n return req.text\r\n\r\ndef save_images(req, name):\r\n reg = r'src=\"(.+?\\.jpg)\"'\r\n imgre = re.compile(reg)\r\n imglist = imgre.findall(req)\r\n for imageURL in imglist:\r\n splitPath = imageURL.split('/')\r\n fileName = splitPath[-1]\r\n print(fileName, 'Download Completes')\r\n dirName = name + \"/\" + fileName\r\n try:\r\n if \"http:\" in imageURL:\r\n rr = requests.get(imageURL)\r\n else:\r\n rr = requests.get('http:' + imageURL)\r\n data = rr.content\r\n f = open(dirName, 'wb+')\r\n f.write(data)\r\n f.close()\r\n except :\r\n continue\r\n\r\nif __name__ == '__main__':\r\n Initial_page = input('The initial page: ')\r\n Final_page = input('The final page: ')\r\n print('Start Download')\r\n path = 'Imagines'\r\n store_path(path)\r\n\r\n for i in range(int(Initial_page),int(Final_page)+1):\r\n req = get_image(\" https://www.qiushibaike.com/imgrank/page-%d#comments\" % i)\r\n threading._start_new_thread(save_images, (req, path))\r\n input('press Enter to exit...\\n')\r\n\r\n\r\n\r\n","sub_path":"12 爬取煎蛋妹子图.py","file_name":"12 爬取煎蛋妹子图.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"373782942","text":"from decimal import Decimal\n\nfrom django.core.cache import cache\nfrom django.core import exceptions\n\nfrom nose.tools import eq_\nfrom test_utils import ExtraAppTestCase\n\nfrom amo.fields import DecimalCharField\n\nfrom fieldtestapp.models import DecimalCharFieldModel\n\n\nclass DecimalCharFieldTestCase(ExtraAppTestCase):\n fixtures = ['fieldtestapp/test_models.json']\n extra_apps = ['amo.tests.fieldtestapp']\n\n def setUp(self):\n cache.clear()\n\n def test_fetch(self):\n o = DecimalCharFieldModel.objects.get(id=1)\n eq_(o.strict, Decimal('1.23'))\n eq_(o.loose, None)\n\n def test_nullify_invalid_false(self):\n val = Decimal('1.5')\n o = DecimalCharFieldModel()\n o.strict = val\n try:\n o.strict = 'not a decimal'\n except exceptions.ValidationError:\n pass\n else:\n assert False, 'invalid value did not raise an exception'\n eq_(o.strict, val, 'unexpected Decimal value')\n\n def test_nullify_invalid_true(self):\n val = Decimal('1.5')\n o = DecimalCharFieldModel()\n o.loose = val\n eq_(o.loose, val, 'unexpected Decimal value')\n\n o.loose = 'not a decimal'\n eq_(o.loose, None, 'expected None')\n\n def test_save(self):\n a = DecimalCharFieldModel()\n a.strict = '1.23'\n a.loose = 'this had better be NULL'\n a.save()\n\n b = DecimalCharFieldModel.objects.get(pk=a.id)\n eq_(b.strict, Decimal('1.23'))\n eq_(b.loose, None)\n","sub_path":"apps/amo/tests/test_fields.py","file_name":"test_fields.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"374131254","text":"from django.test import TestCase\nfrom django.urls import reverse\n\nfrom .models import Mineral\n\n# Create your tests here.\nclass MineralModelTests(TestCase):\n \"\"\"Test for Mineral model.\"\"\"\n\n def setUp(self):\n \"\"\"Set up method to use for model test.\"\"\"\n self.mineral = Mineral.objects.create(\n name='Test Mineral',\n image_filename='testfilename.jpg',\n image_caption='test caption',\n category='test category',\n formula='test formula',\n strunz_classification='test strunz_classification',\n color='test color',\n crystal_system='test crystal system',\n unit_cell='test unit cell',\n crystal_symmetry='test crystal symmetry',\n cleavage='test cleavage',\n mohs_scale_hardness='test mohs scale hardness',\n luster='test luster',\n streak='test streak',\n diaphaneity='test diaphaneity',\n optical_properties='test optical properties',\n refractive_index='test refractive index',\n crystal_habit='test crystal habit',\n specific_gravity='test spacific gravity',\n group='test group')\n\n def test_mineral_creation(self):\n \"\"\"Model that tests a Mineral objects creations.\"\"\"\n self.assertIn(self.mineral, Mineral.objects.all())\n\n\nclass MineralViewsTests(TestCase):\n \"\"\"Test for Mineral views.\"\"\"\n\n def setUp(self):\n \"\"\"Set up method to use for model test.\"\"\"\n self.mineral = Mineral.objects.create(\n name='A Test Mineral',\n image_filename='testfilename.jpg',\n image_caption='test caption',\n category='test category',\n formula='test formula',\n strunz_classification='test strunz_classification',\n color='test color',\n crystal_system='test crystal system',\n unit_cell='test unit cell',\n crystal_symmetry='test crystal symmetry',\n cleavage='test cleavage',\n mohs_scale_hardness='test mohs scale hardness',\n luster='test luster',\n streak='test streak',\n diaphaneity='test diaphaneity',\n optical_properties='test optical properties',\n refractive_index='test refractive index',\n crystal_habit='test crystal habit',\n specific_gravity='test spacific gravity',\n group='test group')\n\n self.mineral2 = Mineral.objects.create(\n name='A Test Mineral2',\n image_filename='testfilename2.jpg',\n image_caption='test caption2',\n category='test category2',\n formula='test formula2',\n strunz_classification='test strunz_classification2',\n color='test color2',\n crystal_system='test crystal system2',\n unit_cell='test unit cell2',\n crystal_symmetry='test crystal symmetry2',\n cleavage='test cleavage2',\n mohs_scale_hardness='test mohs scale hardness2',\n luster='test luster2',\n streak='test streak2',\n diaphaneity='test diaphaneity2',\n optical_properties='test optical properties2',\n refractive_index='test refractive index2',\n crystal_habit='test crystal habit2',\n specific_gravity='test spacific gravity2',\n group='test group')\n\n def test_mineral_list_view(self):\n \"\"\"Testing Mineral home view.\"\"\"\n resp = self.client.get(reverse('minerals:home'))\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertIn(self.mineral2, resp.context['minerals'])\n self.assertTemplateUsed(resp, 'minerals/mineral_list.html')\n self.assertContains(resp, self.mineral.name)\n\n def test_mineral_detail_view(self):\n \"\"\"Testing Mineral detail view.\"\"\"\n resp = self.client.get(reverse('minerals:detail',\n kwargs={'pk':self.mineral.pk}))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(self.mineral, resp.context['mineral'])\n self.assertTemplateUsed(resp, 'minerals/mineral_detail.html')\n self.assertContains(resp, self.mineral.name)\n\n\n def test_letter_search_view(self):\n \"\"\"Testing Mineral letter search view.\"\"\"\n resp = self.client.get(reverse('minerals:letter_search',\n kwargs={'letter': self.mineral.name[0]}\n ))\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertIn(self.mineral2, resp.context['minerals'])\n self.assertTemplateUsed(resp, 'minerals/mineral_list.html')\n self.assertContains(resp, self.mineral.name)\n\n \n def test_search_view(self):\n \"\"\"Testing Mineral search view.\"\"\"\n resp = self.client.get('/search/?q=A Test Mineral')\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertTemplateUsed(resp, 'minerals/mineral_list.html')\n self.assertContains(resp, self.mineral.name)\n\n\n def test_group_search_view(self):\n \"\"\"Testing Mineral group search view.\"\"\"\n resp = self.client.get(reverse('minerals:group_search',\n kwargs={'group': self.mineral.group}\n ))\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertIn(self.mineral2, resp.context['minerals'])\n self.assertTemplateUsed(resp, 'minerals/mineral_list.html')\n self.assertContains(resp, self.mineral.name)\n","sub_path":"mineral_site/minerals/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"554082408","text":"\"\"\"Runs A* for all depths and heuristics.\n\nAuthor: Ryan Strauss\nAuthor: Niall Williams\n\"\"\"\nimport json\nimport multiprocessing\nimport os\n\nimport click\n\nfrom a_star import AStarSolver\nfrom sliding_tile_puzzle import SlidingTilePuzzle\n\n\ndef process_depth(depth, data_dir):\n results = {\n 'misplaced': {\n 'nodes_generated': [],\n 'ebf': []\n },\n 'manhattan': {\n 'nodes_generated': [],\n 'ebf': []\n },\n 'linear_conflict': {\n 'nodes_generated': [],\n 'ebf': []\n }\n }\n with open(os.path.join(data_dir, 'puzzles_depth{}_100.txt'.format(depth)), 'r') as fp:\n for start, goal in [line.split() for line in fp.readlines()]:\n for heuristic in ['misplaced', 'manhattan', 'linear_conflict']:\n puzzle = SlidingTilePuzzle(start, goal, heuristic)\n solver = AStarSolver(puzzle)\n solver.solve()\n results[heuristic]['nodes_generated'].append(solver.nodes_generated)\n results[heuristic]['ebf'].append(solver.effective_branching_factor())\n\n print('Depth {} finished...'.format(depth))\n return results\n\n\n@click.command()\n@click.argument('data_dir', type=click.Path(file_okay=False, dir_okay=True, exists=False), nargs=1)\n@click.argument('save_dir', type=click.Path(file_okay=False, dir_okay=True, exists=False), nargs=1)\n@click.option('--workers', type=click.INT, default=1, nargs=1)\ndef main(data_dir, save_dir, workers):\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n with multiprocessing.Pool(processes=workers) as p:\n results = [p.apply(process_depth, args=(d, data_dir)) for d in range(2, 25, 2)]\n\n output_dict = {}\n for i, data in enumerate(results):\n output_dict[(i + 1) * 2] = data\n\n with open(os.path.join(save_dir, 'results_no_tiebreak.json'), 'w') as fp:\n json.dump(output_dict, fp)\n\n with open(os.path.join(save_dir, 'results_no_tiebreak.json'), 'r') as f:\n results = json.load(f)\n for depth in range(2, 25, 2):\n misplaced = results[str(depth)]['misplaced']\n manhattan = results[str(depth)]['manhattan']\n linear_conflict = results[str(depth)]['linear_conflict']\n\n misplaced_avg_node_gen = sum(misplaced['nodes_generated']) / len(misplaced['nodes_generated'])\n misplaced_ebf = sum(misplaced['ebf']) / len(misplaced['ebf'])\n misplaced_penetrance = depth / misplaced_avg_node_gen\n\n manhattan_avg_node_gen = sum(manhattan['nodes_generated']) / len(manhattan['nodes_generated'])\n manhattan_ebf = sum(manhattan['ebf']) / len(manhattan['ebf'])\n manhattan_penetrance = depth / manhattan_avg_node_gen\n\n linear_conflict_avg_node_gen = sum(linear_conflict['nodes_generated']) / len(\n linear_conflict['nodes_generated'])\n linear_conflict_ebf = sum(linear_conflict['ebf']) / len(linear_conflict['ebf'])\n linear_conflict_penetrance = depth / linear_conflict_avg_node_gen\n\n with open(os.path.join(save_dir, 'results_no_tiebreak.txt'), 'a') as fp:\n fp.write(\n '===MISPLACED DEPTH {}===\\nAvg. nodes generated: {}\\nAvg. EBF: {}\\nAvg. penetrance: {}\\n\\n'.format(\n depth, misplaced_avg_node_gen, misplaced_ebf, misplaced_penetrance))\n\n fp.write(\n '===MANHATTAN DEPTH {}===\\nAvg. nodes generated: {}\\nAvg. EBF: {}\\nAvg. penetrance: {}\\n\\n'.format(\n depth, manhattan_avg_node_gen, manhattan_ebf, manhattan_penetrance))\n\n fp.write(\n '===LINEAR CONFLICT DEPTH {}===\\nAvg. nodes generated: {}\\nAvg. EBF: {}\\nAvg. penetrance: {}\\n\\n'.format(\n depth, linear_conflict_avg_node_gen, linear_conflict_ebf, linear_conflict_penetrance))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run_experiment.py","file_name":"run_experiment.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"587589040","text":"\"\"\"\nlsh.py\n\nAlgorithms based on 'Mining of Massive Datasets'\n\"\"\"\n\n\nclass LSH:\n \"\"\"Locality sensitive hashing. Uses a banding approach to hash\n similar signatures to the same buckets.\"\"\"\n\n def __init__(self, length, threshold):\n self.length = length\n self.threshold = threshold\n self.bandwidth = self.get_bandwidth(length, threshold)\n\n def hash(self, sig):\n \"\"\"Generate hashvals for this signature\"\"\"\n for band in zip(*(iter(sig),) * self.bandwidth):\n yield hash(\"salt\" + str(band) + \"tlas\")\n\n def get_bandwidth(self, n, t):\n \"\"\"Approximates the bandwidth (number of rows in each band)\n needed to get threshold.\n\n Threshold t = (1/b) ** (1/r) where\n b = #bands\n r = #rows per band\n n = b * r = #elements in signature\n \"\"\"\n\n best = n, 1\n minerr = float(\"inf\")\n for r in range(1, n + 1):\n try:\n b = 1. / (t ** r)\n except: # Divide by zero, your signature is huge\n return best\n err = abs(n - b * r)\n if err < minerr:\n best = r\n minerr = err\n return best\n\n def get_threshold(self):\n r = self.bandwidth\n b = self.length / r\n return (1. / b) ** (1. / r)\n","sub_path":"lshhdc/lsh.py","file_name":"lsh.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"65332992","text":"from typing import Any, Type\n\nss = 10\n\n\nclass Person:\n\n def __init__(self, a, b, c, d):\n self.a = a\n self.b = b\n self.c = c\n self.__d = d\n\n def greeting(self):\n print(\"당신은 {} 입니다\".format(self.a))\n\n def greeting2(self):\n print(\"체력:{} 마나:{}\".format(self.b, self.c))\n\n\nclass Person2:\n\n def __init__(self, a, b, c, d):\n self.__a = a\n self.__b = b\n self.__c = c\n self.__d = d\n\n def __setattr__(self, name: str, value: Any) -> None:\n super().__setattr__(name, value)\n\n def __getattribute__(self, name: str) -> Any:\n return super().__getattribute__(name)\n\n\nif __name__ == \"__main__\":\n p = Person(\"전사\", 100, 0, 0)\n c = Person(\"마법사\", 50, 100000000000, 10232313)\n p.greeting()\n p.greeting2()\n c.greeting()\n c.greeting2()\n c.__d -= 1000\n","sub_path":"34.클래스/1.클래스.py","file_name":"1.클래스.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"29857153","text":"import os\n\ndef judge(s):\n\tm = 0\n\tfor i in s:\n\t\tif i !='_' and i !='R':\n\t\t\tm += 1\n\t\telse:\n\t\t\tbreak\n\treturn m\n\ndef main():\n\tfile_list = os.listdir()\n\tfor i in file_list:\n\t\tremain = 3-judge(i)\n\t\tos.rename(i, '0'*remain+i)\n\t\nif __name__ == \"__main__\":\n\tmain()","sub_path":"Leetcode/000Rename.py","file_name":"000Rename.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"272187316","text":"def blackjack_hand_greater_than(hand_1, hand_2):\n \"\"\"\n Return True if hand_1 beats hand_2, and False otherwise.\n\n In order for hand_1 to beat hand_2 the following must be true:\n - The total of hand_1 must not exceed 21\n - The total of hand_1 must exceed the total of hand_2 OR hand_2's total must exceed 21\n\n Hands are represented as a list of cards. Each card is represented by a string.\n\n When adding up a hand's total, cards with numbers count for that many points. Face\n cards ('J', 'Q', and 'K') are worth 10 points. 'A' can count for 1 or 11.\n\n When determining a hand's total, you should try to count aces in the way that\n maximizes the hand's total without going over 21. e.g. the total of ['A', 'A', '9'] is 21,\n the total of ['A', 'A', '9', '3'] is 14.\n\n Examples:\n >>> blackjack_hand_greater_than(['K'], ['3', '4'])\n True\n >>> blackjack_hand_greater_than(['K'], ['10'])\n False\n >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3'])\n False\n \"\"\"\n hv1 = hand_value(hand_1)\n hv2 = hand_value(hand_2)\n return hv1 <= 21 and (hv1 > hv2 or hv2>=21)\n\n\ndef hand_value(hand):\n num_aces = hand.count('A')\n if num_aces:\n hand = list(filter(lambda x: x!='A', hand))\n fixed_value = sum([10 if x in ['J','K','Q'] else int(x) for x in hand])\n while num_aces:\n if (fixed_value + 11) < 21:\n fixed_value += 11\n else:\n fixed_value += 1\n num_aces -= 1\n return fixed_value\n\n\nprint(hand_value(['1','6']))\nprint(hand_value(['1','A']))\nprint(hand_value(['K', '10', '4']))\nprint(hand_value(['A', 'A', '9']))\nprint(hand_value(['9']))\nprint(hand_value(['9', 'Q', '8', 'A']))","sub_path":"Python/blackjack_hand_value.py","file_name":"blackjack_hand_value.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"290117549","text":"\"\"\"\nProvides a basic layer to ICanHazDadJoke-API;\ndoesn't require any API keys...\nReference: https://icanhazdadjoke.com/api\n\"\"\"\nfrom random import randrange\nfrom typing import Optional\n\nfrom requests import get, HTTPError, ConnectionError\n\nfrom agents.jokes.constants import JOKES_AGENT_NAME, ICHDJ_API_URL, ICHDJ_DEFAULT_HEADERS, \\\n ICHDJ_DEFAULT_NUM_JOKES_PER_PAGE\nfrom utils import logger as logger\n\nTERM_KEY = 'term'\nPAGE_KEY = 'page'\nLIMIT_KEY = 'limit'\nJOKE_DATA_KEY = 'joke'\n\n\ndef get_random_joke() -> Optional[str]:\n \"\"\"\n Retrieves a random joke...\n :return: Retrieved joke if request was successful, otherwise None...\n \"\"\"\n url = ICHDJ_API_URL\n request_params = {}\n try:\n response = get(url=url, headers=ICHDJ_DEFAULT_HEADERS, params=request_params)\n response.raise_for_status()\n except HTTPError as http_error:\n logger.exception(JOKES_AGENT_NAME,\n f'Could not retrieve data from server: {http_error}')\n return None\n except ConnectionError as con_error:\n logger.exception(JOKES_AGENT_NAME,\n f'Connection lost while getting a joke: {con_error}')\n return None\n\n data = response.json()\n joke = data.get(JOKE_DATA_KEY, None)\n return joke\n\n\ndef get_search_joke(term: Optional[str] = None,\n page: Optional[int] = None,\n limit: Optional[int] = None) -> Optional[str]:\n \"\"\"\n Retrieves a joke on the given query...\n :param term: A query/category/keyword to look upon...\n :param page: A page number to retrieve from; think of a pagination.\n Example: 100 jokes, 20 jokes/per --> 5 pages; to get 21-th joke, get 2-nd page...\n :param limit: Maximum number of jokes to retrieve, server's default is 20...\n\n :return: Retrieved joke if the request was successful, otherwise None...\n \"\"\"\n # Compose URL out of the given parameters...\n data = {\n TERM_KEY: term,\n PAGE_KEY: page,\n LIMIT_KEY: limit\n }\n url = f'{ICHDJ_API_URL}/search'\n if data.values():\n url_query = '&'.join([\n f'{key}={val}' for key, val in data.items()\n if val\n ])\n url += f'?{url_query}'\n\n request_params = None\n try:\n response = get(url=url, headers=ICHDJ_DEFAULT_HEADERS, params=request_params)\n response.raise_for_status()\n except HTTPError as http_error:\n logger.exception(JOKES_AGENT_NAME,\n f'Could not retrieve data from server: {http_error}')\n return None\n except ConnectionError as con_error:\n logger.exception(JOKES_AGENT_NAME,\n f'Connection lost while getting a joke: {con_error}')\n return None\n\n # Get the retrieved jokes...\n data = response.json()\n jokes = data.get('results', [])\n if not jokes:\n return None\n\n # Randomly choose one of them...\n max_ind = len(jokes) or ICHDJ_DEFAULT_NUM_JOKES_PER_PAGE\n rand_ind = randrange(max_ind - 1)\n joke = jokes[rand_ind].get(JOKE_DATA_KEY, None)\n\n return joke\n","sub_path":"agents/jokes/apis/icanhazdadjoke.py","file_name":"icanhazdadjoke.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"513681144","text":"# 1.文件过滤,显示一个文件的所有行,忽略以#开始的行\ndef iter_mode():\n # 打开文件\n with open('test', 'r') as f:\n # 读取文件里面的内容,以列表形式存储\n read_lines = f.readlines()\n # print(read_lines)\n # 循环整个列表,去除以空格开头的空格,然后出去以#开头的行\n for i in read_lines:\n new_i = i.strip() # 去除每行内容前的空格\n if new_i[0] == '#': # 如果每行的第一个字符为#则跳出\n continue\n else:\n print(new_i)\n\n\n# 2.比较文件,写一个比较文件的程序,如果不同,给出第一个不同处的行号和列号\n\n\n# 3.统计一个文本中每个单词出现个数\ndef count_str():\n with open('test', 'r') as f:\n list1 = f.read().split() # 将文本以空格分割,结果为一个列表\n print(list1)\n set1 = set(list1) # 将列表转换为集合,去除重复\n # print(set1)\n list2 = list(set1) # 再将集合转换为列表\n # print(list2)\n dict1 = {} # 创建一个空的字典\n for x in range(len(list2)):\n dict1[list2[x]] = 0\n for y in range(len(list1)):\n if list2[x] == list1[y]:\n dict1[list2[x]] += 1\n print(dict1)\n\n\nif __name__ == '__main__':\n iter_mode()\n count_str()\n","sub_path":"zhangna/file_exercise.py","file_name":"file_exercise.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"596718869","text":"\n\nfrom xai.brain.wordbase.adjectives._saucy import _SAUCY\n\n#calss header\nclass _SAUCIEST(_SAUCY, ):\n\tdef __init__(self,): \n\t\t_SAUCY.__init__(self)\n\t\tself.name = \"SAUCIEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"saucy\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_sauciest.py","file_name":"_sauciest.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"271200667","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nメイン関数\n\"\"\"\n\n__author__ = \"Hidemasa Kondo (C.A.C.)\"\n__date__ = \"updated at 2021/08/30 (created at 2021/08/12)\"\n__version__ = \"1.0.0\"\n\nimport sys\n\nfrom window_2d import Window2D\n\n\ndef main():\n \"\"\"メイン関数やでー\"\"\"\n app = Window2D()\n app.learn()\n app.display_at_tk()\n app.mainloop()\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"codes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"644541737","text":"#!/usr/bin/env python3\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom PIL import Image\nimport scipy.io as io\nimport subprocess\nimport multiprocessing.pool as mpp\n\nDATA_ROOT = subprocess.check_output(\n ['bash', '-c', \"source config.profile; echo $DATA_ROOT\"]\n).decode().strip()\n\nimport os\nimport sys\nimport argparse\nimport os.path as osp\n\nscript_path = osp.abspath(osp.join(osp.dirname(__file__)))\nos.chdir(osp.join(script_path, '..', '..'))\nsys.path.insert(0, os.getcwd())\nos.environ['PYTHONPATH'] = os.getcwd() + ':' + os.environ.get('PYTHONPATH', '')\n\nclass LabelTransformer:\n\n label_list = list(range(1, 151))\n\n @staticmethod\n def encode(labelmap):\n labelmap = np.array(labelmap)\n\n shape = labelmap.shape\n encoded_labelmap = np.ones(\n shape=(shape[0], shape[1]), dtype=np.int) * 255\n for i in range(len(LabelTransformer.label_list)):\n class_id = LabelTransformer.label_list[i]\n encoded_labelmap[labelmap == class_id] = i\n\n return encoded_labelmap\n\n @staticmethod\n def decode(labelmap):\n labelmap = np.array(labelmap)\n\n shape = labelmap.shape\n encoded_labelmap = np.ones(\n shape=(shape[0], shape[1]), dtype=np.uint8) * 255\n for i in range(len(LabelTransformer.label_list)):\n class_id = i\n encoded_labelmap[labelmap ==\n class_id] = LabelTransformer.label_list[i]\n\n return encoded_labelmap\n\n\ndef gen_coord_map(H, W):\n coord_vecs = [torch.arange(length, dtype=torch.float) for length in (H, W)]\n coord_h, coord_w = torch.meshgrid(coord_vecs)\n return coord_h, coord_w\n\ndef shift(x, offset):\n \"\"\"\n x: h x w\n offset: 2 x h x w\n \"\"\"\n h, w = x.shape\n x = torch.from_numpy(x).unsqueeze(0)\n offset = torch.from_numpy(offset).unsqueeze(0)\n coord_map = gen_coord_map(h, w)\n norm_factor = torch.FloatTensor([(w-1)/2, (h-1)/2])\n grid_h = offset[:, 0]+coord_map[0]\n grid_w = offset[:, 1]+coord_map[1]\n grid = torch.stack([grid_w, grid_h], dim=-1) / norm_factor - 1\n x = F.grid_sample(x.unsqueeze(1).float(), grid, padding_mode='border', mode='bilinear').squeeze().numpy()\n x = np.round(x)\n return x.astype(np.uint8)\n\ndef get_offset(basename):\n return io.loadmat(osp.join(offset_dir, basename+'.mat'))['mat']\\\n .astype(np.float32).transpose(2, 0, 1) * args.scale\n\ndef process(basename):\n infile = osp.join(in_label_dir, basename + '.png')\n outfile = osp.join(out_label_dir, basename + '.png')\n\n input_label_map = np.array(Image.open(infile).convert('P'))\n input_label_map = LabelTransformer.encode(input_label_map)\n\n offset_map = get_offset(basename)\n output_label_map = shift(input_label_map, offset_map)\n output_label_map = LabelTransformer.decode(output_label_map)\n Image.fromarray(output_label_map).save(outfile)\n print('Writing', outfile)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--input')\n parser.add_argument('--offset')\n parser.add_argument('--out')\n parser.add_argument('--split', choices=['val'], default='val')\n parser.add_argument('--scale', type=float, default=2)\n args = parser.parse_args()\n\n if args.offset is None:\n offset_dir = osp.join(DATA_ROOT, 'ade20k', 'val', 'offset_pred', 'semantic', 'offset_hrnext')\n else:\n offset_dir = args.offset\n\n in_label_dir = args.input\n if args.out is None:\n if '/label' in in_label_dir:\n out_label_dir = in_label_dir.replace('/label', '/label_w_segfix')\n else:\n out_label_dir = osp.join(in_label_dir, 'label_w_segfix')\n else:\n out_label_dir = args.out\n print('Saving to', out_label_dir)\n\n os.makedirs(out_label_dir, exist_ok=True)\n input_args = [fn.rpartition('.')[0] for fn in os.listdir(in_label_dir)]\n print(len(input_args), 'files in total.')\n mpp.Pool().map(process, input_args)\n\n if args.split == 'val':\n os.system('{} lib/metrics/ade20k_evaluator.py --gt_dir {}/ade20k/val/label --pred_dir {}'.format(sys.executable, DATA_ROOT, out_label_dir))","sub_path":"scripts/cityscapes/segfix_ade20k.py","file_name":"segfix_ade20k.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"7068663","text":"import matplotlib\nmatplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv(\"/home/matilda/PycharmProjects/RCA_metrics /data_paper_attention_traces\")\n# plt.hist(data.iloc[:, [3]])\n# plt.show()\nlista_lstm = np.array([0.5, 2, 3.5, 7, 8.5, 10, 13.5, 15, 16.5])\nlista_attention = lista_lstm+ 0.5\n\nplt.bar(lista_lstm, data.iloc[:, 4], width=0.5, label=\"LSTM\", color=\"red\")\nplt.bar(lista_attention, data.iloc[:, 5], width=0.5, label=\"ATTENTION\", color=\"blue\")\n#plt.xticks(lista_lstm, [\"long_prec\", \"long_rec\", \"long_f1\", \"short_prec\", \"short_rec\", \"short_f1\", \"long_short_prec\", \"long_short_rec\", \"long_short_f1\"], rotation=90)\nplt.xticks(lista_lstm, [\"precision\", \"recall\", \"F1\", \"precision\", \"recall\", \"F1\", \"precision\", \"recall\", \"F1\"], rotation=90, fontsize=12)\nplt.text(2.25, 1, s=\"LONG\" )\nplt.text(8.25, 1, s=\"SHORT\" )\nplt.text(14.25, 1, s=\"LONG_SHORT\")\nplt.legend()\nplt.savefig(\"/home/matilda/PycharmProjects/RCA_metrics /2nd.pdf\", bbox_inches=\"tight\")\n","sub_path":"script_.py","file_name":"script_.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"41721205","text":"from files_n_vars import *\nfrom lat_lon_grid import *\nimport numpy as np\nfrom netCDF4 import Dataset as ds\nfrom glob import glob\n\ndef getPlanAlbFromSol(col, filetype = 'aijpc', num_files = 10):\n filedir = col['filedir']\n results = glob('{0}/*{1}*'.format(filedir, filetype))\n arr_tot = 0\n for filename in results:\n nc_i = ds(filename, 'r+', format='NETCDF4')\n net_i = nc_i['srnf_toa'][:]\n inc_i = nc_i['incsw_toa'][:]\n out_i = inc_i - net_i\n albedo_i = (out_i / inc_i) * 100\n arr_tot = arr_tot + albedo_i\n\n area_arr = nc_i['axyp'][:]\n area_arr[albedo_i.mask] = 0\n print(np.where(area_arr == 0)[0].size)\n arr_avg = arr_tot / num_files\n if 'aqua' in filedir:\n arr_avg = np.roll(arr_avg, (arr_avg.shape[1]) // 2, axis=1)\n area_arr = np.roll(area_arr, (area_arr.shape[1]) // 2, axis=1)\n # Rolling the area so that masked values (i.e. for albedo) are rolled according to their coordinate\n # Rollling is necessary for determining side and substell averages\n\n plot_row = {'var':'plan_alb_calc',\n 'ylabel':'Calculated \\n Planetary \\n Albedo \\n [%]',\n 'title':'Calculated Planetary Albedo',\n 'units':'[%]',\n 'lat':lat,\n 'lon':lon}\n title = col['title']\n return arr_avg, area_arr, plot_row, title\n\n\n","sub_path":"plot_scripts/calculatedQuantities.py","file_name":"calculatedQuantities.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"609679781","text":"from __future__ import division\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\n\n\nclass QLearn(object):\n\n def __init__(self):\n tf.reset_default_graph()\n self.session = tf.Session()\n\n # Environment\n self.env = gym.make('FrozenLake-v0')\n self.observation_space_size = self.env.observation_space.n\n self.action_space_size = self.env.action_space.n\n\n # Q-table parameters\n self.Q = np.zeros([self.observation_space_size, self.action_space_size]) # Zero initialized Q-table\n self.learning_rate = .8 # learning rate\n self.discount = .95 # discount rate\n self.num_epochs = 2000\n self.rewardList = [] # lists of total rewards and steps per epoch\n self.max_steps = 99\n\n # Network parameters\n self.inputs1 = tf.placeholder(shape=[1, self.observation_space_size], dtype=tf.float32, name='inputs1')\n self.w = tf.Variable(tf.random_uniform([self.observation_space_size, self.action_space_size], 0, 0.01), name='W')\n self.nextQ = tf.placeholder(shape=[1, 4], dtype=tf.float32, name='next_q')\n self.jList = []\n self.e = 0.1\n\n self._build_q_network()\n self._build_q_network()\n self._build_loss_function()\n self._build_optimizer()\n\n def train_q_table(self):\n for i in range(self.num_epochs):\n # Reset environment and get first new observation\n s = self.env.reset()\n rewards = 0\n j = 0\n\n # The Q-Table learning algorithm\n while j < self.max_steps:\n j += 1\n\n # Choose an action by greedily (with noise) picking from Q table\n a = np.argmax(self.Q[s, :] + np.random.randn(1, self.env.action_space.n) * (1. / (i + 1)))\n\n # Get new state and reward from environment\n s1, r, d, _ = self.env.step(a)\n\n # Update Q-Table with new knowledge\n self.Q[s, a] = self.Q[s, a] + self.learning_rate * (r + self.discount * np.max(self.Q[s1, :]) - self.Q[s, a])\n rewards += r\n s = s1\n\n if d:\n break\n self.rewardList.append(rewards)\n\n def _build_q_network(self):\n # feed-forward network\n q_out = tf.matmul(self.inputs1, self.w, name='output')\n action = tf.argmax(q_out, 1)\n self.Q_out = q_out\n return action, q_out\n\n def _build_loss_function(self):\n # loss is sum of squared differences between the target and prediction Q values\n self.loss = tf.reduce_sum(tf.square(self.nextQ - self.Q_out))\n tf.summary.scalar('loss', self.loss)\n\n def _build_optimizer(self):\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)\n self.optimizer = optimizer.minimize(self.loss)\n\n def train(self):\n self.session.run(tf.global_variables_initializer())\n\n for i in range(self.num_epochs):\n\n # Reset environment and get first new observation\n s = self.env.reset()\n rewards = 0\n j = 0\n\n while j < 99:\n j += 1\n # Choose an action by greedily (with e chance of random action) from the Q-network\n action, q_out = self.session.run([self.optimizer, self._build_q_network], feed_dict={self.inputs1: np.identity(self.observation_space_size)[s:s + 1]})\n\n # wind blows, changes game if probability ...\n if np.random.rand(1) < self.e:\n action[0] = self.env.action_space.sample()\n\n # Get new state and reward from environment\n s1, r, d, _ = self.env.step(action[0])\n\n # Obtain the Q' values by feeding the new state through our network\n q1 = self.session.run(self._build_q_network, feed_dict={self.inputs1: np.identity(self.observation_space_size)[s1:s1 + 1]})\n\n # Obtain maxQ' and set our target value for chosen action.\n max_q1 = np.max(q1)\n target_q = q_out\n target_q[0, action[0]] = r + self.discount * max_q1\n\n # Train our network using target and predicted Q values\n _, w1 = self.session.run([self.optimizer, self.w], feed_dict={self.inputs1: np.identity(self.observation_space_size)[s:s + 1], self.nextQ: target_q})\n rewards += r\n s = s1\n if d is True:\n # Reduce chance of random action as we train the model.\n self.e = 1. / ((i / 50) + 10)\n break\n self.jList.append(j)\n self.rewardList.append(rewards)\n print(\"Percent of succesful episodes: \" + str(sum(self.rewardList) / self.num_epochs) + \"%\")\n\n\ndef main():\n model = QLearn()\n model.train()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"reinforcement_learning.py","file_name":"reinforcement_learning.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"146515667","text":"from rest_framework.exceptions import ValidationError\nfrom rest_framework.fields import CharField\nfrom rest_framework.serializers import ModelSerializer\n\nfrom apps.users.models import User\n\n\nclass UserModelSerializer(ModelSerializer): # 内部已经实现了 create update的方法,直接使用即可,更加方便\n token = CharField(read_only=True)\n\n class Meta:\n model = User # 指定生成字段的模型类,反序列化限制对应的信息通过model层来限制,不在序列化层限制\n fields = ('id', 'nick', 'token')\n\n\n def create(self, validated_data):\n '''\n 用户注册\n '''\n user = User(**validated_data)\n\n # 把token保存到user对象中,随着返回值返回给前端,Restful风格自动会返回\n user.token = user.gen_jwt_token()\n return user\n\n\nclass UserLoginSerializer(ModelSerializer):\n token = CharField(read_only=True)\n code = CharField(write_only=True, required=True)\n\n class Meta:\n model = User # 指定生成字段的模型类,反序列化限制对应的信息通过model层来限制,不在序列化层限制\n fields = ('mobile', 'token', 'code')\n extra_kwargs = { # 可以通过这种方式对序列化器内部的字段属性进行更改\n 'password': {'write_only': True},\n }\n\n def validate(self, attrs):\n '''\n 用户登录行为验证\n '''\n\n user = User.objects.filter(mobile=attrs[\"mobile\"]).first()\n if not user:\n user = User(username=attrs[\"mobile\"],mobile = attrs[\"mobile\"],nick=\"用户{}\".format(attrs[\"mobile\"])).save()\n if attrs['code'] != \"111\": #redis里面获取值,然后判断是否相等\n raise ValidationError(\"验证码不正确\")\n\n # 把token保存到user对象中,随着返回值返回给前端,Restful风格自动会返回\n attrs[\"token\"] = user.gen_jwt_token()\n attrs[\"id\"] = user.id\n return attrs\n","sub_path":"apps/users/serializers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"178409684","text":"import websocket\nfrom ._utils.rate_limiter import RateLimiter\nimport time\nfrom ._utils.frame_model import get_frame_data, FrameType\nimport logging\nfrom threading import Thread\nfrom ._utils import ws_utils\nfrom ._utils.consts import MESG_regular, MESG_snoo, TPST, TPEN, MOBILE_USERAGENT\n\n\nlogging.basicConfig(level=logging.INFO, datefmt='%H:%M', format='%(asctime)s, %(levelname)s: %(message)s')\n\n\ndef _print_chat_(resp, channelid_sub_pairs):\n if resp.type_f == FrameType.MESG:\n print(f\"{resp.user.name}@{channelid_sub_pairs.get(resp.channel_url)}: {resp.message}\")\n\n\nclass WebSockClient:\n def __init__(self, access_token, user_id, enable_trace=False, print_chat=True, log_websocket_frames=False,\n other_logging=True, global_blacklist_users=None, global_blacklist_words=None):\n self._user_id = user_id\n if global_blacklist_words is None:\n global_blacklist_words = set()\n if global_blacklist_users is None:\n global_blacklist_users = set()\n assert isinstance(global_blacklist_words, set), \"blacklists must be set()s\"\n assert isinstance(global_blacklist_users, set), \"blacklists must be set()s\"\n self.global_blacklist_words = global_blacklist_words\n self.global_blacklist_users = global_blacklist_users\n\n self.channelid_sub_pairs = {}\n self.RateLimiter = RateLimiter\n\n self.logger = logging.getLogger(__name__)\n self.logger.disabled = not other_logging\n websocket.enableTrace(enable_trace)\n\n ws_url = ws_utils.get_ws_url(self._user_id, access_token)\n self.ws = self._get_ws_app(ws_url)\n\n self.req_id = int(time.time() * 1000)\n self.own_name = None\n self.print_chat = print_chat\n self.log_websocket_frames = log_websocket_frames\n self.last_err = None\n self.is_logi_err = False\n self.session_key = None\n\n self._get_current_channels = None\n\n self.after_message_hooks = []\n\n def _get_ws_app(self, ws_url):\n ws = websocket.WebSocketApp(ws_url,\n on_message=self.on_message,\n on_error=self.on_error,\n on_close=self.on_close,\n on_open=self.on_open,\n header={'User-Agent': MOBILE_USERAGENT}\n )\n return ws\n\n def ws_run_forever(self, skip_utf8_validation):\n self.ws.run_forever(ping_interval=15, ping_timeout=5, skip_utf8_validation=skip_utf8_validation)\n\n def update_ws_app_urls_access_token(self, access_token):\n self.ws.url = ws_utils.get_ws_url(self._user_id, access_token)\n\n def on_open(self, _):\n self.logger.info(\"### successfully connected to the websocket ###\")\n\n def on_message(self, _, message):\n resp = get_frame_data(message)\n if self.print_chat:\n _print_chat_(resp, self.channelid_sub_pairs)\n if self.log_websocket_frames:\n self.logger.info(message)\n if resp.type_f == FrameType.LOGI:\n self.logger.info(message)\n self._logi(resp)\n\n if resp.type_f == FrameType.MESG and resp.user.name in self.global_blacklist_users:\n return\n\n Thread(target=self._response_loop, args=(resp,), daemon=True).start()\n\n def _logi(self, resp):\n try:\n logi_err = resp.error\n except AttributeError:\n logi_err = None\n if logi_err is None:\n self.session_key = resp.key\n self.current_channels = self._get_current_channels(limit=100, order='latest_last_message', show_member=True,\n show_read_receipt=True, show_empty=True,\n member_state_filter='joined_only', super_mode='all',\n public_mode='all', unread_filter='all',\n hidden_mode='all', show_frozen=True,\n session_key=self.session_key)\n self.update_channelid_sub_pair()\n self.own_name = resp.nickname\n else:\n self.logger.error(f\"err: {resp.message}\")\n self.is_logi_err = True\n\n def update_channelid_sub_pair(self):\n self.channelid_sub_pairs = ws_utils.pair_channel_and_names(channels=self.current_channels,\n own_user_id=self._user_id)\n\n def _response_loop(self, resp):\n for func in self.after_message_hooks:\n if func(resp):\n break\n\n def ws_send_message(self, text, channel_url):\n if self.RateLimiter.is_enabled and self.RateLimiter.check():\n return\n if any(blacklist_word in text.lower() for blacklist_word in self.global_blacklist_words):\n return\n payload = MESG_regular.format(channel_url=channel_url, text=text, req_id=self.req_id)\n self.ws.send(payload)\n self.req_id += 1\n\n def ws_send_snoomoji(self, snoomoji, channel_url):\n if self.RateLimiter.is_enabled and self.RateLimiter.check():\n return\n payload = MESG_snoo.format(channel_url=channel_url, snoomoji=snoomoji, req_id=self.req_id)\n self.ws.send(payload)\n self.req_id += 1\n\n def ws_send_typing_indicator(self, channel_url):\n payload = TPST.format(channel_url=channel_url, time=int(time.time() * 1000))\n self.ws.send(payload)\n\n def ws_stop_typing_indicator(self, channel_url):\n payload = TPEN.format(channel_url=channel_url, time=int(time.time() * 1000))\n self.ws.send(payload)\n\n def on_error(self, _, error):\n self.logger.error(error)\n self.last_err = error\n\n def on_close(self, _):\n self.logger.warning(\"### websocket closed ###\")\n","sub_path":"Reddit_ChatBot_Python/ws_client.py","file_name":"ws_client.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"524190594","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n\n\"\"\"\nExample from python101 course\n\"\"\"\n\nimport os, random\nfrom sqlalchemy import Column, ForeignKey, Integer, String, create_engine, func\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, sessionmaker\n\nif os.path.exists('test.db'):\n os.remove('test.db')\n\n# tworzymy instancję klasy Engine do obsługi bazy\nbaza = create_engine('sqlite:///test.db', echo=False)\n\n# klasa bazowa\nBazaModel = declarative_base()\n\n# klasy Klasa i Uczen opisują rekordy tabel \"klasa\" i \"uczen\"\n# oraz relacje między nimi\n\nclass Klasa(BazaModel):\n __tablename__ = 'klasa'\n id = Column(Integer, primary_key = True)\n nazwa = Column(String(100), nullable=False)\n profil = Column(String(100), default='')\n uczniowie = relationship('Uczen', backref='klasa')\n\nclass Uczen(BazaModel):\n __tablename__ = 'uczen'\n id = Column(Integer, primary_key=True)\n imie = Column(String(100), nullable=False)\n nazwisko = Column(String(100), nullable=False)\n klasa_id = Column(Integer, ForeignKey('klasa.id'))\n\n# tworzymy tabelę\nBazaModel.metadata.create_all(baza)\n\n# tworzymy sesję, która przechowuje obiekty i umozliwia \"rozmowę\" z bazą\nBDSesja = sessionmaker(bind=baza)\nsesja = BDSesja()\n\n# dodajemy dwie klasy, jeżeli tabela jest pusta\nif not sesja.query(Klasa).count():\n sesja.add(Klasa(nazwa='1A', profil='matematyczny'))\n sesja.add(Klasa(nazwa='1B', profil='humanistyczny'))\n\n# tworzymy instancję klasy Klasa reprezentującą klasę '1A'\ninst_klasa = sesja.query(Klasa).filter_by(nazwa='1A').one()\n\n# dodajemy dane wielu uczniów\nsesja.add_all([\n Uczen(imie='Tomasz', nazwisko='Nowak', klasa_id=inst_klasa.id),\n Uczen(imie='Jan', nazwisko='Kos', klasa_id=inst_klasa.id),\n Uczen(imie='Piotr', nazwisko='Kowalski', klasa_id=inst_klasa.id),\n Uczen(imie='Rak', nazwisko='Piotrowski', klasa_id=\"2\")\n ])\n\nnames = \"Ahmed Farid Jack Jesus Jahve Ewelina Julka Grażyna Janusz Seba Pioter Dick\".split()\nsurnames = \"Mohamed Black White Master Slave Goatfucker Rughead Pink Jude Ass Turd Bush\".split()\nrandom.shuffle(names)\nrandom.shuffle(surnames)\nfor a in range(len(names)-1):\n a+=1\n i = random.randint(1,2)\n name=names[a]\n surname=surnames[a]\n sesja.add(Uczen(imie=name, nazwisko=surname, klasa_id = i))\n\ndef czytajdane():\n for uczen in sesja.query(Uczen).join(Klasa).all():\n print(uczen.id, uczen.imie, uczen.nazwisko, uczen.klasa.nazwa)\n print()\n\n# zmiana klasy ucznia o identyfikatorze 2\ninst_uczen = sesja.query(Uczen).filter(Uczen.id == 2).one()\ninst_uczen.klasa_id = sesja.query(Klasa.id).filter(\n Klasa.nazwa == '1B').scalar()\n\n# usunięcie ucznia o identyfikatorze 3\nsesja.delete(sesja.query(Uczen).get(3))\n\n\n# zapisanie zmian w bazie i zamknięcie sesji\n\ndef main():\n while True:\n hello = \"\\n\"\n hello += \"1. Create \\n\"\n hello += \"2. Read \\n\"\n hello += \"3. Update \\n\"\n hello += \"4. Delete \\n\"\n hello += \"0. Quit \\n\"\n hello += \"Pick one: \"\n choice = input(hello)\n if choice == \"0\":\n exit()\n elif choice == \"1\":\n \"\"\" Create A\"\"\"\n while choice !=\"0\":\n hello = \"\\n\"\n hello += \"What do you want to create? \\n\"\n hello += \"1. Class \\n\"\n hello += \"2. Student \\n\"\n hello += \"0. Get back \\n\"\n hello += \"Choice: \"\n choice = input(hello)\n if choice == \"1\":\n \"\"\" Create Class A\"\"\"\n hello = \"\\n\"\n hello += \"Type in name and profile seperated by coma: \"\n data = input(hello).split(sep=\",\")\n if len(data) == 2:\n sesja.add(Klasa(nazwa=data[0].upper(), profil=data[1]))\n elif choice == \"2\":\n \"\"\" Create Student A\"\"\"\n hello = \"\\n\"\n hello += \"Type in class name, name and surname seperated by coma: \"\n data = \"\"\n while data.count(\",\") != 2:\n data = input(hello)\n data = data.split(\",\")\n try:\n inst_klasa = sesja.query(Klasa).filter(Klasa.nazwa == data[0].upper()).one()\n sesja.add(Uczen(imie=data[1].capitalize(), nazwisko = data[2].capitalize(), klasa = inst_klasa))\n except:\n print(\"No class with the name {}.\".format(data[0].upper()))\n\n\n elif choice == \"2\":\n \"\"\" Read A\"\"\"\n while choice !=\"0\":\n hello = \"\\n\"\n hello += \"What do you want to read? \\n\"\n hello += \"1. Classes \\n\"\n hello += \"2. Student \\n\"\n hello += \"3. All students \\n\"\n hello += \"0. Get back \\n\"\n hello += \"Choice: \"\n choice = input(hello)\n if choice == \"1\":\n \"\"\" Read Classes A\"\"\"\n classes = sesja.query(Klasa).all()\n for klasa in classes:\n print(klasa.id, klasa.profil, klasa.nazwa)\n elif choice == \"2\":\n \"\"\" Read Student A\"\"\"\n hello = \"\\n\"\n hello += \"What's the surname of the student: \"\n student_surname = input(hello)\n student = sesja.query(Uczen).filter(Uczen.nazwisko == student_surname.capitalize()).all()\n if len(student):\n for uczen in student:\n print(uczen.id, uczen.imie, uczen.nazwisko)\n else:\n print(\"No student with such surname.\")\n elif choice == \"3\":\n \"\"\" Read All Students A\"\"\"\n query = sesja.query(Uczen).join(Klasa).all()\n if len(query):\n print()\n for uczen in query:\n print(uczen.id, uczen.imie, uczen.nazwisko, uczen.klasa.nazwa)\n\n elif choice == \"3\":\n \"\"\" Update A\"\"\"\n while choice != \"0\":\n hello = \"\\n\"\n hello += \"What do you want to update? \\n\"\n hello += \"1. Class` profile \\n\"\n hello += \"2. Student's data \\n\"\n hello += \"0. Get back \\n\"\n hello += \"Choice: \"\n choice = input(hello)\n if choice == \"1\":\n \"\"\" Update Class' Profile A\"\"\"\n hello = \"\\n\"\n hello += \"Type in class name and new profile, seperated by coma: \"\n data = \"\"\n while \",\" not in data:\n data = input(hello)\n data = data.split(\",\")\n klasa = sesja.query(Klasa).filter(Klasa.nazwa == data[0].upper()).first()\n if klasa:\n klasa.profil = data[1]\n else:\n print(\"No class with name {}.\".format(data[0].upper()))\n elif choice == \"2\":\n \"\"\" Update Student's Data A\"\"\"\n hello = \"\\n\"\n hello += \"What's the student id: \"\n data = input(hello)\n uczen = sesja.query(Uczen).filter(Uczen.id == data).first()\n if uczen:\n print(uczen.id, uczen.imie, uczen.nazwisko, uczen.klasa.nazwa)\n hello = \"\\n\"\n hello += \"Type in new name, surname and class name, separated by comas: \"\n new_data = \"\"\n while new_data.count(\",\") != 2:\n new_data = input(hello)\n print(new_data)\n new_data = new_data.split(\",\")\n print(new_data)\n klasa = sesja.query(Klasa).filter(Klasa.nazwa == new_data[2].upper()).first()\n if klasa:\n uczen.imie = new_data[0].capitalize()\n uczen.nazwisko = new_data[1].capitalize()\n uczen.klasa_id = klasa.id\n\n else:\n print(\"No class with given name: \",new_data[2].upper())\n else:\n print(\"No student with given id: \", data)\n\n elif choice == \"4\":\n \"\"\" Delete A\"\"\"\n while choice !=\"0\":\n hello = \"\\n\"\n hello += \"What do you want to delete? \\n\"\n hello += \"1. Empty Class \\n\"\n hello += \"2. Student \\n\"\n hello += \"0. Get back \\n\"\n hello += \"Choice: \"\n choice = input(hello)\n if choice == \"1\":\n \"\"\"Delete Empty Class A\"\"\"\n hello = \"\\n\"\n hello += \"What is the class name: \"\n data = input(hello).upper()\n klasa_count = sesja.query(Klasa).filter(Klasa.nazwa == data).first()\n if klasa_count:\n klasa = sesja.query(Klasa).filter(Klasa.nazwa == data).first()\n uczniowie_count= sesja.query(Uczen).filter(Uczen.klasa_id == klasa.id).count()\n if uczniowie_count:\n print(\"Class {} in not empty, it has {} student(s)\".format(data.upper(), uczniowie_count))\n else:\n sesja.query(Klasa).filter(Klasa.nazwa == data).delete()\n print(\"Class {} deleted\".format(data))\n else:\n print(\"No class with given name: \",data.upper())\n elif choice == \"2\":\n \"\"\" Delete Student by id A\"\"\"\n hello = \"\\n\"\n hello += \"What is the student's id: \"\n data = input(hello)\n uczen = sesja.query(Uczen).filter(Uczen.id == data).first()\n if uczen:\n sesja.query(Uczen).filter(Uczen.id == data).delete()\n print(\"Student with id {} deleted.\".format(data))\n else:\n print(\"No student with id \", data)\nmain()\nsesja.commit()\nsesja.close()\n","sub_path":"python101/orm/ormsa.py","file_name":"ormsa.py","file_ext":"py","file_size_in_byte":10523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"644705340","text":"\r\n#A\r\n\r\nmydict = {}\r\nwith open('text_for_test.txt', encoding='utf8') as f:\r\n f = f.read()\r\n text = f.replace('?', '.').replace('!', '.').replace('...', '.')\r\n for sentence in text.split(\".\"):\r\n mydict[sentence] = len([j for j in sentence.split() if len(j)==1 ])\r\n l = text.split(' ')\r\n c = text.count('.')\r\nprint('а)1.Среднее количество слов в предложении:',len(l)/c)\r\ndp = [(value, key) for key, value in mydict.items()]\r\nprint (\"a)2.Предложение с максимальным количеством односимвольных слов:\", max(dp)[1])\r\n\r\n#Б\r\n\r\nimport re\r\nimport string\r\nfrequency = {}\r\ndocument_text = open('text_for_test.txt', encoding='utf8' )\r\ntext_string = document_text.read().lower()\r\nmatch_pattern = re.findall(r'ответил\\b', text_string)\r\nfor word in match_pattern:\r\n count = frequency.get(word,0)\r\n frequency[word] = count + 1\r\nfrequency_list = frequency.keys()\r\nfor words in frequency_list:\r\n print ('Количество слов \"ответил\" в файле:',frequency[words])\r\nfile = open('text_for_test.txt', encoding='utf8' )\r\ndata = file.read()\r\nw = data.split()\r\nprint('Количество слов в файле:', len(w))\r\nprint('2.tf для слова \"ответил\":',frequency[words]/len(w))\r\n\r\n\r\n\r\n","sub_path":"Тест/тест_комп_лингва.py","file_name":"тест_комп_лингва.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"60735493","text":"# Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.\n# Для решения используйте цикл while и арифметические операции.\n\n\n# Можно решить с помощью FOR-WHILE, но Ребе скажет, что это не кошерно, т.к. откровение гласит:\n# \"Для решения используйте цикл while и арифметические операции.\"\n# user_Number = input(\"Введите целое положительное число состоящее не менее чем из двух цифр: \")\n# most_Bigger_number = 0\n# for i in user_Number:\n# while int(i) > most_Bigger_number:\n# most_Bigger_number = int(i)\n# print(most_Bigger_number)\n\n\n# Поэтому решаем кошернее, но Ребе снова будет недоволен:\n# user_Number = input(\"Введите целое положительное число состоящее не менее чем из двух цифр: \")\n# print(f'В введённом вами числе {user_Number} максимальная цифра таки: {max(user_Number)}')\n\n\n# финальный вариант, но всё равно с опаской косимся на Ребе, потому что про if он не говорил\nuser_Number = int(input(\"Введите целое положительное число состоящее не менее чем из двух цифр: \"))\nmax_Cyfer = 0\nwhile user_Number > 1:\n residue = user_Number % 10\n user_Number = user_Number // 10\n max_Cyfer = residue if residue > max_Cyfer else max_Cyfer\nprint(f\"Максимальная цифра: {max_Cyfer}\")\n","sub_path":"lesson_01/004.py","file_name":"004.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"410358255","text":"Celsius_values = [-2,34,56,-10]\n\n\n#ºF = (ºC · 1,8) + 32\ndef fahrenheit_values(x):\n# the magic go here:\n fah = (x*1.8)+32\n return fah\n \nresult = list(map(fahrenheit_values, Celsius_values))\nprint(result)","sub_path":"exercises/12-Map_a_list/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"500641008","text":"a = [5, 10, 15, 20, 25] # existing list\nnew = list() # creates new list\n\nlist_length = len(a) # gets length of entire list\nlast_item = list_length - 1 # subtracts one for last index value and returns value\n\nfirst = a[0] # gets first value in list\nlast = a[last_item] # gets last value in list\n\nnew.append(first)\nnew.append(last)\n\nprint(new)\n","sub_path":"learn_python/list_ends_12.py","file_name":"list_ends_12.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"292668657","text":"import os, glob\nimport torch\nimport librosa\nimport numpy as np\nimport torch.nn.functional as F\n\nclass DatasetDCUNET(torch.utils.data.Dataset):\n def __init__(self, root,SNRs, num_frame=80):\n\n self.root = root\n self.num_frame = num_frame\n self.SNRs = SNRs\n self.target = root.split('/')[-1]\n\n if type(SNRs) == str : \n self.data_list = [x for x in glob.glob(os.path.join(root,SNRs, 'noisy','*.pt'), recursive=False)]\n elif type(SNRs) == list : \n self.data_list = []\n for i in SNRs : \n self.data_list = self.data_list + [x for x in glob.glob(os.path.join(root, i,'noisy' ,'*.pt'), recursive=False)]\n else : \n raise Exception('Unsupported type for target')\n\n def __getitem__(self, index):\n path = self.data_list[index]\n# print('['+str(index)+'] : ' + path)\n file_name = path.split('/')[-1]\n SNR = path.split('/')[-3]\n\n root = self.root\n\n noisy = torch.load(os.path.join(root,SNR,'noisy')+'/'+file_name)\n estim= torch.load(os.path.join(root,SNR,'estimated_speech')+'/'+file_name)\n noise = torch.load(os.path.join(root,SNR,'estimated_noise')+'/'+file_name)\n if self.target == 'CGMM_RLS_MPDR_norm_2' : \n clean = torch.load(os.path.join(root,SNR,'clean')+'/'+file_name)\n else :\n clean = torch.load(os.path.join(root,'clean')+'/'+file_name)\n\n ## sampling routine ##\n\n # [Freq, Time, complex] \n length = noisy.shape[1]\n need = self.num_frame - length\n\n start_idx = np.random.randint(low=0,high = length)\n\n # padding on head \n if start_idx + self.num_frame > length : \n shortage = (start_idx + self.num_frame) - length\n noisy = noisy[:,start_idx:,:]\n noisy = F.pad(noisy,(0,0,shortage,0,0,0),'constant',value=0)\n estim = estim[:,start_idx:,:]\n estim = F.pad(estim,(0,0,shortage,0,0,0),'constant',value=0)\n noise = noise[:,start_idx:,:]\n noise = F.pad(noise,(0,0,shortage,0,0,0),'constant',value=0)\n clean = clean[:,start_idx:,:]\n clean = F.pad(clean,(0,0,shortage,0,0,0),'constant',value=0)\n #print(str(1) + ' ' + str(start_idx)+ '| '+str(length) + '|'+str(shortage) + '|' + str(noisy.shape))\n # padding on tail\n elif start_idx >= length - self.num_frame : \n shortage = start_idx - length + self.num_frame \n noisy = noisy[:,start_idx:,]\n noisy = F.pad(noisy,(0,0,0,shortage,0,0),'constant',value=0)\n estim = estim[:,start_idx:,]\n estim = F.pad(estim,(0,0,0,shortage,0,0),'constant',value=0)\n noise = noise[:,start_idx:,]\n noise = F.pad(noise,(0,0,0,shortage,0,0),'constant',value=0)\n clean = clean[:,start_idx:,]\n clean = F.pad(clean,(0,0,0,shortage,0,0),'constant',value=0)\n #print(str(2) + ' ' + str(start_idx)+ '| '+str(length) + '|'+str(shortage) + '|' + str(noisy.shape))\n else :\n noisy = noisy[:,start_idx:start_idx+self.num_frame,:]\n estim = estim[:,start_idx:start_idx+self.num_frame,:]\n noise = noise[:,start_idx:start_idx+self.num_frame,:]\n clean = clean[:,start_idx:start_idx+self.num_frame,:]\n #print(str(3) + ' ' + str(start_idx)+ '| '+str(length)+'|'+str(noisy.shape))\n data = {\"input\":torch.stack((noisy,estim,noise),0), \"clean\":clean}\n return data\n\n def __len__(self):\n return len(self.data_list)\n","sub_path":"src/legacy/DatasetDCUNET.py","file_name":"DatasetDCUNET.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"377017684","text":"__author__ = 'sype'\n\nfrom django.conf.urls.defaults import patterns, include, url\n\n\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^backup/', 'backup.views.check_stats', name=\"check_stats\"),\n\n\n # url(r'^cluster_gui/', include('cluster_gui.foo.urls')),\n #url(r'^cluster_gui/', include(status.urls)),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n\n\n # Uncomment the next line to enable the admin:\n\n)\n\n","sub_path":"cluster_gui/backup/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"618452757","text":"class BooleanExpression:\r\n\r\n class BoolExprError(Exception):pass\r\n #operators ordered from highest to lowest priority\r\n #!or is an OR with a higher priority as an AND\r\n #!and has a higher priority as an 1or\r\n #as if it were surrounded by ()\r\n operators_by_priority = [\"!and\", \"!or\", \"and\", \"or\"]\r\n\r\n #------------- INTERNAL CLASS FUNCTIONS ---------------------\r\n def _evaluate_and(bool_array):\r\n \"\"\"\r\n Evaluates the given logical boolean array.\r\n All elements are linked with a logical AND.\r\n\r\n Parameters:\r\n -----------\r\n bool_array: the list of bool values to evaluate\r\n\r\n Returns:\r\n --------\r\n True or False: if bool_array has at least one element\r\n None: if bool_array is empty\r\n \"\"\"\r\n l = len(bool_array)\r\n if l > 1:\r\n if sum(bool_array) == l:\r\n return True\r\n else:\r\n return False\r\n elif l == 1:\r\n return bool_array[0]\r\n else:\r\n return None\r\n \r\n def _evaluate_or(bool_array):\r\n \"\"\"\r\n Evaluates the given logical boolean array.\r\n All elements are linked with a logical OR.\r\n\r\n Parameters:\r\n -----------\r\n bool_array: the list of bool values to evaluate\r\n\r\n Returns:\r\n --------\r\n True or False: if bool_array has at least one element\r\n None: if bool_array is empty\r\n \"\"\"\r\n l = len(bool_array)\r\n if l > 1:\r\n if sum(bool_array) == 0:\r\n return False\r\n else:\r\n return True\r\n elif l == 1:\r\n return bool_array[0]\r\n else:\r\n return None\r\n \r\n def _split_and_eval(bool_array, indices, operator):\r\n \"\"\"\r\n Splits the expression at the given operators and evaluates the sub arrays.\r\n Example:\r\n --------\r\n BooleanExression._split_and_eval([True, False, True], [\"!or\", \"and\"])\r\n True !or False and True is equal to:\r\n (True or False) and True\r\n True and True; after evaluating !or\r\n True; after evaluating and\r\n\r\n Parameters:\r\n -----------\r\n bool_array: a list of bool values\r\n indices: a list of all consecutive operator indices\r\n operator: the operator to evaluate\r\n\r\n Returns:\r\n --------\r\n list: new list of bool values, after operator was evaluated\r\n \"\"\"\r\n new_arr = []\r\n last_index = 0\r\n for i, x in enumerate(indices):\r\n index, length, op = x\r\n if op == operator:\r\n if i > 0:\r\n #add all elements from last index that were before the operator\r\n new_arr += bool_array[last_index:index]\r\n #set last index to after the operators\r\n last_index = index + length + 1\r\n #exclude lowest priority operator(logical OR)\r\n if operator in BooleanExpression.operators_by_priority[0:-1]:\r\n #evaluate the expression\r\n if operator.find(\"or\") != -1:\r\n new_arr.append(BooleanExpression._evaluate_or(bool_array[index:last_index]))\r\n elif operator.find(\"and\") != -1:\r\n new_arr.append(BooleanExpression._evaluate_and(bool_array[index:last_index]))\r\n elif i == len(indices)-1:\r\n #if the last element is not an operator\r\n #add all the elements from last index to the end of the array\r\n new_arr += bool_array[last_index:]\r\n break\r\n return new_arr\r\n\r\n def _split_and_eval2(bool_array, indices, op):\r\n \"\"\"\r\n Splits the expression at the given operators and evaluates the sub arrays.\r\n Example:\r\n --------\r\n BooleanExression._split_and_eval([True, False, True], [\"!or\", \"and\"])\r\n True !or False and True is equal to:\r\n (True or False) and True\r\n True and True; after evaluating !or\r\n True; after evaluating and\r\n\r\n Parameters:\r\n -----------\r\n bool_array: a list of bool values\r\n indices: a list of all consecutive operator indices\r\n operator: the operator to evaluate\r\n\r\n Returns:\r\n --------\r\n list: new list of bool values, after operator was evaluated\r\n \"\"\"\r\n new_arr = []\r\n start_index = 0\r\n for i, x in enumerate(indices):\r\n index, length = x\r\n if index > 0:\r\n #add all elements from last index that were before the operator\r\n new_arr += bool_array[start_index:index]\r\n #set start index to after the operators\r\n start_index = index + length + 1\r\n #evaluate the expression\r\n if op.find(\"or\") != -1:\r\n new_arr.append(BooleanExpression._evaluate_or(bool_array[index:start_index]))\r\n elif op.find(\"and\") != -1:\r\n new_arr.append(BooleanExpression._evaluate_and(bool_array[index:start_index]))\r\n if start_index < len(bool_array):\r\n #if the last element is not an operator\r\n #add all the elements from last index to the end of the array\r\n new_arr += bool_array[start_index:]\r\n return new_arr\r\n\r\n def _create_indices(operator_array):\r\n \"\"\"\r\n Creates an index list for a given operator list.\r\n Each index is the starting index for a sequence of the same operators.\r\n Example: (0, 1, \"or\")\r\n This index starts at 0 and has 1 \"or\" operator(s).\r\n\r\n Parameters:\r\n -----------\r\n operator_array: a list of operators(as strings)\r\n\r\n Returns:\r\n --------\r\n list: a list containing all indices for each operator sequence as a touple\r\n\r\n \"\"\"\r\n indices = []\r\n count_op = 0\r\n count_other = 0\r\n if len(operator_array) > 0:\r\n last_op = operator_array[0]\r\n last_index = 0\r\n for i, x in enumerate(operator_array):\r\n if x != last_op:\r\n indices.append((last_index, i-last_index, last_op))\r\n last_op = x\r\n last_index = i\r\n if last_index <= len(operator_array)-1:\r\n indices.append((last_index, len(operator_array)-last_index, last_op))\r\n return indices\r\n\r\n def _create_indices2(operator_array, operator):\r\n \"\"\"\r\n Creates an index list for a given operator list.\r\n Each index is the starting index for a sequence of the same operators.\r\n Example: (0, 1, \"or\")\r\n This index starts at 0 and has 1 \"or\" operator(s).\r\n\r\n Parameters:\r\n -----------\r\n operator_array: a list of operators(as strings)\r\n\r\n Returns:\r\n --------\r\n list: a list containing all indices for each operator sequence as a touple\r\n\r\n \"\"\"\r\n if len(operator_array) > 0:\r\n indices = []\r\n count_op = 0\r\n last_index = 0\r\n for i, x in enumerate(operator_array):\r\n if x == operator:\r\n count_op += 1\r\n else:\r\n if count_op > 0:\r\n indices.append((i - count_op, count_op))\r\n count_op = 0\r\n last_index = i + 1\r\n if count_op > 0:\r\n indices.append((last_index, count_op))\r\n return indices\r\n\r\n #-------------- INSTANCE FUNCTIONS ---------------\r\n def __init__(self, bool_array, operator_array):\r\n if len(bool_array)-1 != len(operator_array):\r\n raise BooleanExpression.BoolExprError(\"Length mismatch. Expression and operator length don't match.\")\r\n self.bool_array = bool_array\r\n self.operator_array = operator_array\r\n\r\n def _debug_eval(self):\r\n \"\"\"\r\n Evaluates the logical expression without changing the expression.\r\n FOR DEBUGGING PURPOSES, prints the individual steps\r\n\r\n Raises:\r\n -------\r\n BoolExprError: if lowest priority operator could not be resolved\r\n if one step failed to create matching bool and operator lists\r\n \"\"\"\r\n #exclude lowest priority operator\r\n bools = self.bool_array\r\n bools2 = self.bool_array\r\n operators = self.operator_array\r\n print(self)\r\n for operator in BooleanExpression.operators_by_priority[0:-1]:\r\n if operator not in operators:\r\n #if the operator is not found, skip to the next one\r\n continue\r\n print(\"Eliminate: %s\"%operator)\r\n #create indices for all operators\r\n #(index, length of consecutive operators, operator type)\r\n indices = BooleanExpression._create_indices(operators)\r\n print(indices)\r\n indices2 = BooleanExpression._create_indices2(operators, operator)\r\n print(indices2)\r\n #split array at the given operator and evaluate sub arrays\r\n bools = BooleanExpression._split_and_eval(bools, indices, operator)\r\n bools2 = BooleanExpression._split_and_eval2(bools2, indices2, operator)\r\n print(bools)\r\n print(bools2)\r\n #remove the operators that were evaluated above\r\n operators = [op for op in operators if op != operator]\r\n print(BooleanExpression(bools, operators))\r\n if len(operators) == 0:\r\n #print(\"Zero Len:\", bool_array)\r\n print(\"Zero Length: \" + str(bools[0]))\r\n #eval lowest priority operator\r\n print(\"R2:\", BooleanExpression._evaluate_or(bools2))\r\n if BooleanExpression.operators_by_priority[-1].find(\"or\") != -1:\r\n print(\"Result: \" + str(BooleanExpression._evaluate_or(bools)))\r\n elif BooleanExpression.operators_by_priority[-1].find(\"and\") != -1:\r\n print(\"Result: \" + str(BooleanExpression._evaluate_and(bools)))\r\n else:\r\n raise BoolExprError(\"Couldn't evaluate lowest priority operator.\")\r\n \r\n def evaluate(self):\r\n \"\"\"\r\n Evaluates the logical expression without changing the expression.\r\n Example: True and False evaluates to False\r\n\r\n Raises:\r\n -------\r\n BoolExprError: if lowest priority operator could not be resolved\r\n\r\n Returns:\r\n --------\r\n bool: the boolean value the expression evaluates to\r\n \"\"\"\r\n #exclude lowest priority operator\r\n bools = self.bool_array\r\n operators = self.operator_array\r\n for operator in BooleanExpression.operators_by_priority[0:-1]:\r\n if operator not in operators:\r\n #if the operator is not found, skip to the next one\r\n continue\r\n #create indices for all operators\r\n #(index, length of consecutive operators, operator type)\r\n indices = BooleanExpression._create_indices(operators)\r\n #split array at the given operator and evaluate sub arrays\r\n bools = BooleanExpression._split_and_eval(bools, indices, operator)\r\n #remove the operators that were evaluated above\r\n operators = [op for op in operators if op != operator]\r\n if len(operators) == 0:\r\n return bools[0]\r\n #eval lowest priority operator\r\n if BooleanExpression.operators_by_priority[-1].find(\"or\") != -1:\r\n return BooleanExpression._evaluate_or(bools)\r\n elif BooleanExpression.operators_by_priority[-1].find(\"and\") != -1:\r\n return BooleanExpression._evaluate_and(bools)\r\n else:\r\n raise BoolExprError(\"Couldn't evaluate lowest priority operator.\")\r\n\r\n def __str__(self):\r\n \"\"\"\r\n Prints a logical expression.\r\n\r\n Returns:\r\n --------\r\n str: a string representation of the logical expression\r\n\r\n \"\"\"\r\n s = \"\"\r\n for value, operator in zip(self.bool_array, self.operator_array):\r\n s += \" \".join([str(value), operator]) + \" \"\r\n s += str(self.bool_array[-1])\r\n return s.strip()\r\n \r\n\r\ndef bool_expression_from_string(s):\r\n def str2bool(s):\r\n if s == \"True\":\r\n return True\r\n elif s == \"False\":\r\n return False\r\n else:\r\n return None\r\n arr = s.split(\" \")\r\n #all bools\r\n bools = [str2bool(x) for x in arr if x == \"True\" or x == \"False\"]\r\n #all logical operators\r\n operators = [x for x in arr if x.find(\"or\") != -1 or x.find(\"and\") != -1]\r\n return BooleanExpression(bools, operators)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"False and False == \"+str(bool_expression_from_string(\"False and False\").evaluate()))\r\n print(\"False and True == \"+str(bool_expression_from_string(\"False and True\").evaluate()))\r\n print(\"True and False == \"+str(bool_expression_from_string(\"True and False\").evaluate()))\r\n print(\"True and True == \"+str(bool_expression_from_string(\"True and True\").evaluate()))\r\n print(\"False or False == \"+str(bool_expression_from_string(\"False or False\").evaluate()))\r\n print(\"False or True == \"+str(bool_expression_from_string(\"False or True\").evaluate()))\r\n print(\"True or False == \"+str(bool_expression_from_string(\"True or False\").evaluate()))\r\n print(\"True or True == \"+str(bool_expression_from_string(\"True or True\").evaluate()))\r\n import random\r\n def rand_expression(length = 15):\r\n b = []\r\n o = []\r\n for x in range(length):\r\n n = random.randint(-128, 127)\r\n if n%3 == 1:\r\n b.append(True)\r\n else:\r\n b.append(False)\r\n if n%7 == 0:\r\n o.append(\"!or\")\r\n elif n%5 == 2:\r\n o.append(\"!and\")\r\n elif n%2 == 1:\r\n o.append(\"and\")\r\n else:\r\n o.append(\"or\")\r\n return BooleanExpression(b, o[0:-1])\r\n bool_expression_from_string(\"True !and False !or False !and False or False and False or False and True and False !or False or False !or True and True and True and False\")._debug_eval()\r\n\r\n for m in range(0):\r\n print(\"-------- NEW EXPRESSION --------\")\r\n expr = rand_expression()\r\n expr._debug_eval()\r\n","sub_path":"BoolExpression.py","file_name":"BoolExpression.py","file_ext":"py","file_size_in_byte":14527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"553484019","text":"def exercise_1():\n def check_list(list):\n print(\"Max:\", max(list))\n print(\"Min:\", min(list))\n print(\"Average:\", sum(list) / len(list))\n\n list = [1, 2, 3, 4]\n print(\"List:\", list)\n check_list(list)\n\n\ndef exercise_2():\n def copy_list(list):\n return [x for x in list]\n\n list = [1, 2, 3, 4]\n print(\"First list:\", list)\n print(\"Copied list:\", copy_list(list))\n\n\ndef exercise_3():\n def average_list(list):\n return [(list[ind] + list[ind - 1] + list[ind + 1]) / 3 if ind != 0 and ind != len(list) - 1\n else list[ind] for ind, x in enumerate(list)]\n\n list = [1, 2, 3, 4, 5, 6, 7]\n print(\"Original list:\", list)\n print(\"List with averages:\", average_list(list))\n\n\ndef exercise_4():\n def list_add(list_1, list_2):\n if len(list_1) <= len(list_2):\n short = len(list_1)\n else:\n short = len(list_2)\n return [list_1[i] + list_2[i] for i in range(0, short)]\n\n list1 = [1, 2, 3, 3, 8, 1]\n list2 = [2, 1, 3, 3, 6]\n print(\"List 1:\", list1)\n print(\"List 2:\", list2)\n print(\"List addition:\", list_add(list1, list2))\n\n\ndef exercise_5():\n def list_divide(list_1, list_2):\n if len(list_1) <= len(list_2):\n short = len(list_1)\n else:\n short = len(list_2)\n return [list_1[i] if list_2[i] is 0 else list_1[i] / list_2[i] for i in range(0, short)]\n\n list1 = [3, 1, 0, 5]\n list2 = [8, 0, 1, 3]\n print(\"List1:\", list1)\n print(\"List2:\", list2)\n print(\"List division:\", list_divide(list1, list2))\n\n\ndef exercise_6():\n def take_min_and_max(list):\n list_dec = sorted(list, reverse=True)\n new_list = [list_dec[i] for i in range(0, len(list_dec)) if i not in range(3, len(list_dec) - 3)]\n return [new_list[i] for i in (-3, -2, -1, 0, 1, 2)]\n\n list = [0, 1, -5, 8, 14, 9, 6]\n print(\"Original list:\", list)\n print(\"Sorted list:\", take_min_and_max(list))\n\n\ndef exercise_7():\n def delete_elements(list):\n for i in range(len(list) - 1, 0, -1):\n if list[i] < 0 or (i + 1) % 3 is 0:\n del list[i]\n return list\n\n list = [0, 1, 5, 8, 14, 9, 6, -3, -10, 2, 3, 8, 1, -2, 3, -15, 2]\n print(\"Original list:\", list)\n print(\"New list:\", delete_elements(list))\n\n#tu skonczylem\ndef exercise_8():\n def insert(list, space):\n new_list = [x for x in list]\n for i in range(space, len(list) + space, space + 1):\n new_list.insert(i, 0)\n\n return new_list\n\n list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n print(\"Original list:\", list)\n print(\"New list: space = \" + str(2), insert(list, 2))\n print(\"New list: space = \" + str(3), insert(list, 3))\n\n\ndef exercise_9():\n def checkboard(size):\n return [[1 if j % 2 is 0 else 0 for j in range(size)] for i in range(size)]\n\n print(checkboard(4))\n print(checkboard(3))\n\n\ndef exercise_9000():\n def vowels(text):\n vowels_num = 0\n for sign in text:\n if sign.casefold() in \"aiueoy\":\n vowels_num += 1\n\n return vowels_num\n\n def even_vowels_in(texts):\n return [text for text in texts if vowels(text) % 2 is 0]\n\n print(even_vowels_in([\"Robot\", \"Mech\", \"Metal Gear\", \"Android\"]))\n\nprint(\"Zadanie 1\")\nexercise_1()\nprint(\"\\nZadanie 2\")\nexercise_2()\nprint(\"\\nZadanie 3\")\nexercise_3()\nprint(\"\\nZadanie 4\")\nexercise_4()\nprint(\"\\nZadanie 5\")\nexercise_5()\nprint(\"\\nZadanie 6\")\nexercise_6()\nprint(\"\\nZadanie 7\")\nexercise_7()\nprint(\"\\nZadanie 8\")\nexercise_8()\nprint(\"\\nZadanie 9\")\nexercise_9()\nprint(\"\\nZadanie 9000\")\nexercise_9000()\n","sub_path":"lab3/venv/bin/Flis_Kamil_lab3.py","file_name":"Flis_Kamil_lab3.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"590440465","text":"\nfrom KNN.ItemKNNCFRecommender import ItemKNNCFRecommender\nfrom SLIM_BPR.Cython.SLIM_BPR_Cython import SLIM_BPR_Cython\nfrom KNN.UserKNNCFRecommender import UserKNNCFRecommender\nfrom Base.NonPersonalizedRecommender import TopPop\nfrom Base.BaseRecommender import BaseRecommender\nfrom GraphBased.P3alphaRecommender import P3alphaRecommender\nfrom operator import add\nimport numpy as np\nfrom Base.DataIO import DataIO\n\nHybridRecommender_params = {\n 'a': 1.0, # p3alpha\n 'b': 1.0, # userCF\n 'c': 1.0, # SLIM BPR\n 'd': 1.0 # itemCF\n} \n\ndef sumScores(s1,s2,s3,s4):\n s1= list(map(add, s1, s2) )\n s1= list(map(add, s1, s3) )\n s1= list(map(add, s1, s4) )\n return s1\n\ndef sumScoresWeights(s1,s2,s3,s4,ws1,ws2,ws3,ws4):\n s1= list(map(add, ws1*s1, ws2*s2) )\n s1= list(map(add, s1, ws3*s3) )\n s1= list(map(add, s1, ws4*s4) )\n return s1\n\nimport sys, os\n\n# Disable\ndef blockPrint():\n sys.stdout = open(os.devnull, 'w')\n\n# Restore\ndef enablePrint():\n sys.stdout = sys.__stdout__\n\nclass UserItemBPRHybridScoreRecommender(BaseRecommender):\n \n RECOMMENDER_NAME = \"UserItemBPRHybridScoreRecommender\"\n #inzializzo tutti i modelli che uso\n def __init__(self, URM_train):\n\n super(UserItemBPRHybridScoreRecommender, self).__init__(URM_train)\n \n #ci asta ggiungere IALS faceva benino\n \n self.recommenderBPR = SLIM_BPR_Cython(self.URM_train, recompile_cython=False,verbose=False)\n \n #se uso questo devo anche farmi passare icm\n #self.itemCBF = ItemKNNCBFRecommender(data_wrapper.ICM_sub_class, self.URM_train)\n self.itemKNNCF = ItemKNNCFRecommender(self.URM_train)\n self.userRecommender = UserKNNCFRecommender(self.URM_train)\n self.topPop = TopPop(self.URM_train)\n self.p3alpha=P3alphaRecommender(self.URM_train)\n\n #qui a,b,c sono i pesi del mix degli scores\n def fit(self, URM_train=None,ws1=1,ws2=1,ws3=1,ws4=1):\n print(\"--------FITTING IN PROGRESS...-------\")\n #blockPrint()\n\n if URM_train is not None:\n self.URM_train = URM_train\n\n self.ws1 = ws1\n self.ws2 = ws2\n self.ws3 = ws3\n self.ws4 = ws4\n\n self.recommenderBPR.fit(epochs=300, batch_size=1, sgd_mode='sgd', learning_rate=0.001, positive_threshold_BPR=0.8,topK=800)\n self.itemKNNCF.fit(shrink=51, topK=370) #MAP=0.041\n self.userRecommender.fit(shrink=0.5, topK=150)#MAP=0.056 #sbagliato, va sistemato\n self.topPop.fit()\n self.p3alpha.fit(alpha=0.547615508822564,topK=500)#'MAP': 0.058 circa\n\n\n #enablePrint()\n print(\"------FITTING END, SIAMO GROSSISSIMI ------\")\n \n #qui calcolo score per ogni metodo e sommo e tutte quelle belle cose\n #penso basti fare gli scores e basta , poi se chiama reccommend ci pensa lui a dire quali hanno buoni scores \n def _compute_item_score(self, user_id_array, items_to_compute=None):\n item_weights = np.zeros((len(user_id_array), self.URM_train.shape[1]), dtype=np.float32)\n\n i = 0\n\n for user_id in user_id_array:\n user_profile_length = self.URM_train[user_id].getnnz(1)\n\n # recommend cold users\n if user_profile_length == 0:#topPop.compute>Itemscore\n \n item_weights[i]=self.topPop._compute_item_score_single_user()\n \n elif user_profile_length == 1:#silmBPR compute score\n \n item_weights[i]=self.recommenderBPR._compute_item_score(int(user_id), items_to_compute)\n else:#warm users\n scoresUser=self.userRecommender._compute_item_score(int(user_id), items_to_compute)\n scoresItem=self.itemKNNCF._compute_item_score(int(user_id), items_to_compute)\n scoresBPR=self.recommenderBPR._compute_item_score(int(user_id), items_to_compute)\n scoresP3=self.p3alpha._compute_item_score(int(user_id), items_to_compute)\n\n item_weights[i]=np.array(sumScoresWeights(scoresP3,scoresUser,scoresBPR,scoresItem,\n self.ws1,self.ws2,self.ws3,self.ws4)) \n \n #print(item_weights[i]) \n i += 1\n return item_weights\n def save_model(self, folder_path, file_name=None):\n \n if file_name is None:\n file_name = self.RECOMMENDER_NAME\n self._print(\"Saving model in file '{}'\".format(folder_path + file_name))\n data_dict_to_save = HybridRecommender_params\n dataIO = DataIO(folder_path=folder_path)\n dataIO.save_data(file_name=file_name, data_dict_to_save = data_dict_to_save)\n self._print(\"Saving complete\")\n \n #self.itemScoresHybrid.save_model(SAVED_MODELS_PATH, None)\n #self.userScoresHybrid.save_model(SAVED_MODELS_PATH, None)\n\n def load_model(self, folder_path, file_name=None):\n \n if file_name is None:\n file_name = self.RECOMMENDER_NAME\n self._print(\"Loading model from file '{}'\".format(folder_path + file_name))\n dataIO = DataIO(folder_path=folder_path)\n data_dict = dataIO.load_data(file_name=file_name)\n HybridRecommender_params = data_dict\n self._print(\"Loading complete\")\n \n #self.itemScoresHybrid.load_model(SAVED_MODELS_PATH)\n #self.userScoresHybrid.load_model(SAVED_MODELS_PATH)\n ","sub_path":"topAlessandro/myRecommenders/UserItemBPRHybridScoreRecommender.py","file_name":"UserItemBPRHybridScoreRecommender.py","file_ext":"py","file_size_in_byte":5382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"200122901","text":"import random\n\nmoney = 100\nnum = random.randint(1, 10)\n\n#Write your game of chance functions here\ndef coinflip(guess, bet, money):\n\tflip = random.randint(1,2)\n\tg_val = guess.upper()\n\n\twhile not (g_val == \"HEADS\" or g_val == \"TAILS\"):\n\t\tg_val = input(\"Invalid guess. Heads or Tails:\").upper()\n\n\twhile not (bet.isdigit() and int(bet) <= money):\n\t\tbet = input(\"Invalid bet. Enter your bet:\")\n\n\tif ((g_val == \"HEADS\") and (flip == 1)) or ((g_val == \"TAILS\") and (flip == 2)):\n\t\tprint(\"The flip was \" + g_val + \", you won!\\n\")\n\t\tflag = 0\n\telif (g_val == \"HEADS\" and flip == 2):\n\t\tprint(\"The flip was TAILS, you lost.\\n\")\n\t\tflag = 1\n\telif (g_val == \"TAILS\" and flip == 1):\n\t\tprint(\"The flip was HEADS, you lost.\\n\")\n\t\tflag = 1\n\n\tif flag:\n\t\tprint(\"You earned -\" + str(bet) +\".\")\n\t\treturn int(bet) * -1\n\telse:\n\t\tprint(\"You earned \" + str(bet) + \".\")\n\t\treturn int(bet)\n\ndef cho_han(guess, bet, money):\n\tdie1 = random.randint(1,6)\n\tdie2 = random.randint(1,6)\n\tg_val = guess.upper()\n\n\twhile not (g_val == \"ODD\" or g_val == \"EVEN\"):\n\t\tg_val = input(\"Invalid guess. Odd or Even:\").upper()\n\n\twhile not (bet.isdigit() and int(bet) <= money):\n\t\tbet = input(\"Invalid bet. Enter your bet:\")\n\n\tis_even = (die1 + die2) % 2 == 0\n\n\tif (is_even and g_val == \"EVEN\") or (not is_even and g_val == \"ODD\"):\n\t\tprint(\"The sum of the die were \" + g_val + \", you won!\\n\")\n\t\tflag = 0\n\t# elif (not is_even and g_val == \"ODD\"):\n\t# \tprint(\"The sum of the die were \" + g_val + \", you won!\\n\")\n\telif (not is_even and g_val == \"EVEN\"):\n\t\tprint(\"The sum of the die were ODD, you lost!\\n\")\n\t\tflag = 1\n\telif (is_even and g_val == \"ODD\"):\n\t\tprint(\"The sum of the die were EVEN, you lost!\\n\")\n\t\tflag = 1\n\n\tif flag:\n\t\tprint(\"You earned -\" + str(bet) + \".\")\n\t\treturn int(bet) * -1\n\telse:\n\t\tprint(\"You earned \" + str(bet) + \".\")\n\t\treturn int(bet)\n\ndef card_game(p1_bet, p2_bet):\n\tdeck = list(range(1,52))\n\n\twhile not p1_bet.isdigit():\n\t\tp1_bet = input(\"Invalid bet. Player 1 enter your bet:\")\n\n\twhile not p2_bet.isdigit():\n\t\tp2_bet = input(\"Invalid bet. Player 2 enter your bet:\")\n\n\tp1_card = deck[random.randint(0,len(deck))]%13\n\tdeck.remove(p1_card)\n\n\tp2_card = deck[random.randint(0,len(deck))]%13\n\n\tif p1_card == 0 or p1_card == 1:\n\t\tp1_card += 13\n\n\tif p2_card == 0 or p2_card == 1:\n\t\tp2_card += 13\n\n\t#ace 2 3 4 5 6 7 8 9 10 jack queen king\n\t#1 2 3 4 5 6 7 8 9 10 11 12 0\n\n\tprint(\"Player 1 drew: \" + str(p1_card) + \", Player 2 drew: \" + str(p2_card) + \".\")\n\tif p1_card > p2_card:\n\t\tprint(\"Player 1 wins $\" + str(p1_bet) + \".\")\n\telif p1_card < p2_card:\n\t\tprint(\"Player 2 wins $\" + str(p2_bet) + \".\")\n\telse:\n\t\tprint(\"Tie! Both players earn $0.\")\n\n\ndef roulette(guess,bet, money):\n\twhile not (guess.upper() == \"ODD\" or guess.upper() == \"EVEN\" or guess.isdigit()):\n\t\tguess = input(\"Invalid guess. Odd, Even, or Number:\")\n\n\twhile not bet.isdigit():\n\t\tbet = input(\"Invalid bet. Enter your bet:\")\n\n\tanswers = list(range(0,36))\n\tanswers.append(\"00\")\n\n\tball_roll = answers[random.randint(0,len(answers))]\n\n\tif guess.upper() == \"EVEN\":\n\t\tif ball_roll % 2 == 0 and ball_roll != 0 and ball_roll != \"00\":\n\t\t\tflag = (0, 0, 1)\n\t\telse:\n\t\t\tflag = (1, 1, 1)\n\telif guess.upper() == \"ODD\":\n\t\tif ball_roll % 2 == 1 and ball_roll != 0 and ball_roll != \"00\":\n\t\t\tflag = (0, 1, 1)\n\t\telse:\n\t\t\tflag = (1, 0, 1)\n\telif guess.isdigit():\n\t\tif guess == str(ball_roll):\n\t\t\tflag = (1, 2, 35)\n\t\telse:\n\t\t\tflag = (1, 2, 35)\n\n\tprint(\"BALL ROLL:\", ball_roll)\n\tif flag[0] == 0:\n\t\tif flag[1] == 0:\n\t\t\tprint(\"The roll was EVEN, you won $\" + str(flag[2]*int(bet)) + \".\")\n\t\telif flag[1] == 1:\n\t\t\tprint(\"The roll was ODD, you won $\" + str(flag[2]*int(bet)) + \".\")\n\t\telif flag[1] == 2:\n\t\t\tprint(\"The ball landed on your bet. You won $\" + str(flag[2]*int(bet)) + \".\")\n\t\treturn flag[2]*int(bet)\n\telif flag[0] == 1:\n\t\tif flag[1] == 0:\n\t\t\tprint(\"The roll was EVEN, you lost $\" + bet + \".\")\n\t\telif flag[1] == 1:\n\t\t\tprint(\"The roll was ODD, you lost $\" + bet + \".\")\n\t\telif flag[1] == 2:\n\t\t\tprint(\"The roll was not \" + guess + \", you lost $\" + bet + \".\")\n\t\treturn int(bet) * -1\n\n#Call your game of chance functions\nmoney = 10\nprint(\"Current Money = \" + str(money))\n\ndecision = input(\"Play Coin Flip? (Y/N)\").upper()\nwhile decision == \"Y\" and money > 0:\n\tmoney += coinflip(input(\"Heads or Tails:\"), input(\"Enter your bet:\"), money)\n\tprint(\"\\n\")\n\tprint(\"Current Money = \" + str(money))\n\tdecision = input(\"Keep playing? (Y/N)\").upper()\n\tprint(\"\\n\")\n\ndecision = input(\"Play Cho Han? (Y/N)\").upper()\nwhile decision == \"Y\" and money > 0:\n\tmoney += cho_han(input(\"Odd or Even:\"), input(\"Enter your bet:\"), money)\n\tprint(\"\\n\")\n\tprint(\"Current Money = \" + str(money))\n\tdecision = input(\"Keep playing? (Y/N)\").upper()\n\tprint(\"\\n\")\n\ndecision = input(\"Play Card Game? (Y/N)\").upper()\nwhile decision == \"Y\":\n\tcard_game(input(\"Player 1 - Enter your bet:\"),input(\"Player 2 - Enter your bet:\"))\n\tdecision = input(\"Keep playing? (Y/N)\").upper()\n\tprint(\"\\n\")\n\ndecision = input(\"Play Roulette? (Y/N)\").upper()\nwhile decision == \"Y\" and money > 0:\n\tmoney += roulette(input(\"Odd, Even, or Number:\"),input(\"Enter your bet:\"), money)\n\tprint(\"\\n\")\n\tprint(\"Current Money = \" + str(money))\n\tdecision = input(\"Keep playing? (Y/N)\").upper()\n\tprint(\"\\n\")\n\n\nprint(\"\\nYour money after playing:\", money)\nprint(\"Thanks for playing!\")\n\n","sub_path":"beginner/gamesofchance.py","file_name":"gamesofchance.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"200240720","text":"from datetime import datetime,timedelta\ndef broken_clock(starting_time, wrong_time, error_description):\n format = '%H:%M:%S'\n st_time = datetime.strptime(starting_time,format)\n wr_time = datetime.strptime(wrong_time,format)\n mistake_step= int(error_description.split('at ')[1].split(' ')[0])\n mistake_sign = error_description.split('at ')[1].split(' ')[1]\n mistake_value_per_step = abs(int(error_description.split(' ')[0]))\n mistake_value_per_step_sign = error_description.split(' ')[1].split(' ')[0]\n sign = error_description[0]\n\n if mistake_sign in ['seconds','second']:\n mistake_step_delta = timedelta(seconds = mistake_step)\n elif mistake_sign in ['minute','minutes'] :\n mistake_step_delta = timedelta(minutes = mistake_step)\n else:\n mistake_step_delta = timedelta(hours = mistake_step)\n\n if mistake_value_per_step_sign in ['seconds','second']:\n mistake_value_per_step_delta = timedelta(seconds = mistake_value_per_step)\n elif mistake_value_per_step_sign in ['minute','minutes'] :\n mistake_value_per_step_delta = timedelta(minutes = mistake_value_per_step)\n else:\n mistake_value_per_step_delta = timedelta(hours = mistake_value_per_step)\n\n mistake_step_delta_sec = mistake_step_delta.seconds\n mistake_value_per_step_delta_sec = mistake_value_per_step_delta.seconds\n if sign=='+':\n correction_per_second = (mistake_step_delta_sec+mistake_value_per_step_delta_sec)/(mistake_step_delta_sec*1.0)\n else:\n correction_per_second = (mistake_step_delta_sec-mistake_value_per_step_delta_sec)/(mistake_step_delta_sec*1.0)\n\n time_difference = wr_time - st_time\n time_difference_second = time_difference.seconds\n second_result = time_difference_second/correction_per_second\n correction_delta = timedelta(seconds=second_result)\n\n\n return (st_time+correction_delta).strftime(format)\n\n\n#These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == \"__main__\":\n assert broken_clock('00:00:00', '00:00:15', '+5 seconds at 10 seconds') == '00:00:10', \"First example\"\n assert broken_clock('06:10:00', '06:10:15', '-5 seconds at 10 seconds') == '06:10:30', 'Second example'\n assert broken_clock('13:00:00', '14:01:00', '+1 second at 1 minute') == '14:00:00', 'Third example'\n assert broken_clock('01:05:05', '04:05:05', '-1 hour at 2 hours') == '07:05:05', 'Fourth example'\n assert broken_clock('00:00:00', '00:00:30', '+2 seconds at 6 seconds') == '00:00:22', 'Fifth example'\n\n","sub_path":"broken_clock.py","file_name":"broken_clock.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"391948873","text":"from django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.utils.translation import gettext_lazy as _\nfrom django.db.models import Prefetch\nfrom django.template.loader import render_to_string\n\nfrom accounts.models import Profile\nfrom product.models import Product\n\nfrom shopping_cart.extras import generate_order_id\nfrom shopping_cart.models import OrderItem, Order\n\nfrom shopping_cart.forms import OrderContactPhoneForm\n\nfrom django.http import JsonResponse\nfrom django.db import IntegrityError, transaction\nfrom django.core.mail import send_mail, send_mass_mail, BadHeaderError,EmailMultiAlternatives\n\nimport datetime\nimport json\n\n\ndef get_user_pending_order(request):\n # get order for the correct user\n user_profile = get_object_or_404(Profile, user=request.user)\n # order = Order.objects.prefetch_related('items__product__product_imgs').filter(owner=user_profile, is_ordered=False)\n order = Order.objects.prefetch_related(Prefetch('items', queryset=OrderItem.objects.select_related('product'))).filter(owner=user_profile, is_ordered=False)\n if order.exists():\n # get the only order in the list of filtered orders\n return order[0]\n return 0\n\ndef generate_success_order_email_content(items_queryset):\n content = ''\n for item in items_queryset:\n content += f'{item.product.name} ({item.details}) × {item.nmb}\\n'\n return content\n\n\n\n# ajax + login_requiered cooperating\ndef add_to_cart(request, **kwargs):\n return_data = dict()\n\n if request.user.is_authenticated():\n # get the user profile\n user_profile = get_object_or_404(Profile, user=request.user)\n # filter products by id\n\n product = Product.objects.filter(id=kwargs.get('item_id', \"\")).first()\n\n product_quantity = int(request.POST.get('quantity',1)) \n order_item_details_raw = request.POST.get('order_item_details', '')\n\n #spliting data from ajax request, checkout here\n # if order_item_details_raw:\n # try:\n # order_item_details = order_item_details_raw.split(',')\n # order_item_details = ', '.join([item.split(':')[1].strip() for item in order_item_details if item])\n # print (order_item_details)\n # except:\n # order_item_details = order_item_details_raw\n try:\n with transaction.atomic():\n # create orderItem of the selected product\n \n # TODO: have changed to create from get_or_create to fix bug with order items deleting if both users have the same order_item in cart... but this spoil the server db, so optimizations recomended\n order_item = OrderItem.objects.create(product=product, nmb=product_quantity, details=order_item_details_raw)\n if order_item:\n messages.info(request, _(\"item added to cart\"))\n # create order associated with the user\n user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)\n user_order.items.add(order_item)\n if status:\n # generate a reference code\n user_order.ref_code = generate_order_id()\n user_order.save()\n except IntegrityError:\n print('IntegrityError')\n raise\n # print(order_item)\n # print(user_order.owner)\n # print(request.POST)\n # print(request.user.is_authenticated)\n # show confirmation message and redirect back to the same page\n # product_id = kwargs.get('item_id')\n # playing with ajax VVV\n # return redirect(reverse('product:product_detail', kwargs={'product_id': product_id}))\n\n django_messages = dict()\n\n for message in messages.get_messages(request):\n django_messages.update({\n \"level\": message.level,\n \"message\": message.message,\n \"extra_tags\": message.tags,\n })\n\n print('SMS', django_messages)\n\n return_data.update({'amount':request.user.profile.orders.filter(is_ordered=False)[0].items.count() or 0, 'messages':django_messages, 'authenticated': True})\n else:\n return_data.update({ 'authenticated': False })\n return JsonResponse(return_data)\n\n@login_required()\ndef delete_from_cart(request, item_id):\n item_to_delete = OrderItem.objects.filter(pk=item_id)\n if item_to_delete.exists():\n item_to_delete[0].delete()\n messages.info(request, _(\"Item has been deleted\"))\n return redirect(reverse('shopping_cart:order_summary'))\n\n\n@login_required()\ndef order_details(request, **kwargs):\n existing_order = get_user_pending_order(request)\n context = {\n 'order': existing_order\n }\n return render(request, 'shopping_cart/order_summary.html', context)\n\n\n@login_required()\ndef checkout(request):\n existing_order = get_user_pending_order(request)\n if request.method == 'POST':\n form = OrderContactPhoneForm(request.POST, instance=existing_order)\n if form.is_valid():\n with transaction.atomic():\n form.save()\n print(request.POST)\n return redirect(reverse('shopping_cart:update_records')) \n else:\n form = OrderContactPhoneForm()\n context = {\n 'order':existing_order,\n 'form':form\n }\n return render(request, 'shopping_cart/checkout.html', context)\n\n\n@login_required()\ndef update_transaction_records(request):\n # get the order being processed\n order_to_purchase = get_user_pending_order(request)\n\n # update the placed order\n order_to_purchase.customer_email = request.user.email or None\n order_to_purchase.date_ordered = datetime.datetime.now()\n order_to_purchase.is_ordered = True\n order_to_purchase.save()\n \n # get all items in the order - generates a queryset\n order_items = order_to_purchase.items.all()\n\n # update order items\n order_items.update(is_ordered=True, date_ordered=datetime.datetime.now())\n\n # Add products to user profile\n user_profile = get_object_or_404(Profile, user=request.user)\n # get the products from the items\n order_products = [item.product for item in order_items]\n user_profile.purchases.add(*order_products)\n user_profile.save()\n email_content = generate_success_order_email_content(order_items)\n\n\n# datatuple = (\n# (_('PJ | Order accepted!'), \n# _('''\n# Hi, there!\n# Thank you for ordering:\n# {email_content}\n# We'll contact you again soon.\n\n# Now you can check out your order #{order_code} details and follow status of your order fulfillment in your awesome PJ-shop profile :)\n\n# P.S. Have a questions? Contact us, you are always welcome! \n# ''').format(email_content = email_content, order_code=order_to_purchase.ref_code), \n# settings.EMAIL_HOST_USER, [order_to_purchase.owner.user.email, settings.DEV_SUPPORT_EMAIL]),\n\n# (f'New order #{order_to_purchase.ref_code}', \n# f'''\n# Order #{order_to_purchase.ref_code}:\n# {email_content}\n# Customer contacts: email: {order_to_purchase.owner.user.email}, phone: {order_to_purchase.customer_phone_number}\n\n# Have a nice day!\n# Και αυτό θα περάσει..\n# ''', \n# settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER,settings.DEV_SUPPORT_EMAIL]),\n# )\n subject, from_email, to = _('PJ | Order accepted!'), settings.EMAIL_HOST_USER, settings.DEV_SUPPORT_EMAIL\n text_content = _('''\n Hi, there!\n Thank you for ordering:\n {email_content}\n We'll contact you again soon.\n\n Now you can check out your order #{order_code} details and follow status of your order fulfillment in your awesome PJ-shop profile :)\n\n P.S. Have a questions? Contact us, you are always welcome! \n ''').format(email_content = email_content, order_code=order_to_purchase.ref_code)\n # html_content = f'{product_links}'\n html_content = render_to_string('order_accepted_email.html', {'order_items': order_items})\n msg_to_castomer = EmailMultiAlternatives(subject, text_content, from_email, [to])\n msg_to_castomer.attach_alternative(html_content, \"text/html\")\n\n subject, from_email, to = _('PJ | New order!'), settings.EMAIL_HOST_USER, settings.DEV_SUPPORT_EMAIL\n text_content = 'New order, don\\'t see order details? Please, inform your developer'\n html_content = render_to_string('new_order.html', {'order_items': order_items, 'order_to_purchase':order_to_purchase})\n msg_to_shop = EmailMultiAlternatives(subject, text_content, from_email, [to])\n msg_to_shop.attach_alternative(html_content, \"text/html\")\n \n try:\n # send_mass_mail(datatuple, fail_silently=False)\n msg_to_castomer.send(fail_silently=False)\n msg_to_shop.send(fail_silently=False)\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n\n\n \n \n\n messages.info(request, _(\"Thank you! Your order accepted!\"))\n return redirect(reverse('accounts:my_profile'))\n","sub_path":"shopping_cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"549268364","text":"\"\"\"在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,\n但不知道有几个数字是重复的。也不知道每个数字重复几次。\n请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},\n那么对应的输出是第一个重复的数字2。\"\"\"\n\n# -*- coding:utf-8 -*-\nclass Solution:\n # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]\n # 函数返回True/False\n def duplicate(self, numbers, duplication):\n # write code here\n for i in range(len(numbers) - 1):\n for k in range(i + 1, len(numbers) - 1):\n if numbers[i] == numbers[k]:\n duplication[0]=numbers[i]\n return True\n return False\nduplication=[0]\nnumbers=[2,4,3,1,4]\ns=Solution()\nprint(s.duplicate(numbers, duplication))\n","sub_path":"suanfa/chongfu_shuzu.py","file_name":"chongfu_shuzu.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"549939165","text":"def binary_search_recursive(a_list, item):\n first = 0\n last = len(a_list) - 1\n if len(a_list) == 0:\n return -1\n else:\n i = (first + last) // 2\n if item == a_list[i][1]:\n return i\n else:\n if a_list[i][1] < item:\n tmp = binary_search_recursive(a_list[i+1:], item)\n return (i + 1 + tmp) if tmp != -1 else -1\n else:\n return binary_search_recursive(a_list[:i], item)\n\nclass Solution:\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n new_list = []\n for ind, val in enumerate(nums):\n new_list.append((ind, val))\n new_list.sort(key=lambda x: x[1])\n # print(new_list)\n for i, each in enumerate(new_list):\n # print(each[1], target-each[1])\n ind = binary_search_recursive(new_list[i+1:], target-each[1])\n # print(\"Theind: \",ind)\n if ind != -1:\n # print([each[0], new_list[i + 1 + ind][0]])\n return [each[0], new_list[i + 1 + ind][0]]\n","sub_path":"LeetCode (Python 3)/Two Sum.py","file_name":"Two Sum.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"146443180","text":"from unittest import TestCase\n\nfrom itwm_example.mco.scaling_tools.kpi_scaling import sen_scaling_method\nfrom itwm_example.mco.tests.mock_classes import MockOptimizer\n\n\nclass TestSenScaling(TestCase):\n def setUp(self):\n self.optimizer = MockOptimizer(None, None)\n self.scaling_values = self.optimizer.scaling_values.tolist()\n\n def test_sen_scaling(self):\n scaling = sen_scaling_method(\n self.optimizer.dimension, self.optimizer.optimize\n )\n self.assertListEqual(scaling.tolist(), self.scaling_values)\n","sub_path":"itwm_example/mco/scaling_tools/tests/test_kpi_scaling.py","file_name":"test_kpi_scaling.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"22408650","text":"import sqlite3, config\nfrom fastapi import FastAPI, Request, Form \nfrom fastapi.templating import Jinja2Templates\nfrom fastapi.responses import RedirectResponse\nfrom datetime import date, timedelta\nimport alpaca_trade_api as tradeapi\n\n# https://pypi.org/project/alpaca-trade-api/ # Alpaca trading API\n# https://semantic-ui.com/introduction/advanced-usage.html # Easy template html\n# https://www.tradingview.com/widget/advanced-chart/\t\t # Stock charts\n\ncurrent_date = date.today()- timedelta(days =1)\n#If we are on a weekend, go back to Friday\nif date.weekday(current_date) >=5:\n\tcurrent_date = (current_date + timedelta(days = 4 - date.weekday(current_date) )).isoformat()\n\nprint(current_date)\napp = FastAPI()\ntemplates = Jinja2Templates(directory = \"templates\")\n\n@app.get(\"/\")\ndef index(request: Request):\n\tstock_filter = request.query_params.get('filter', False)\n\n\tconnection = sqlite3.connect(config.DB_FILE)\n\tconnection.row_factory = sqlite3.Row #This converts rows to objects\n\n\tcursor = connection.cursor()\n\n\t# Filter stocks to display\n\tif stock_filter == \"new_closing_highs\":\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT * FROM (\n\t\t\t\tSELECT symbol, name, stock_id, max(close), date\n\t\t\t\tFROM stock_price JOIN stock \n\t\t\t\t\tON stock_price.stock_id = stock.id\n\t\t\t\tGROUP BY stock_id\n\t\t\t\tORDER BY symbol\n\t\t\t\t)\n\t\t\tWHERE date = ?\n\t\t\t\"\"\", (current_date,))\n\n\telif stock_filter == \"new_closing_lows\":\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT * FROM (\n\t\t\t\tSELECT symbol, name, stock_id, min(close), date\n\t\t\t\tFROM stock_price JOIN stock \n\t\t\t\t\tON stock_price.stock_id = stock.id\n\t\t\t\tGROUP BY stock_id\n\t\t\t\tORDER BY symbol\n\t\t\t\t)\n\t\t\tWHERE date = ?\n\t\t\t\"\"\", (current_date,))\n\n\telif stock_filter == \"rsi_overbought\":\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT symbol, name, stock_id, date\n\t\t\tFROM stock_price JOIN stock \n\t\t\t\tON stock_price.stock_id = stock.id\n\t\t\tWHERE rsi_14 > 70\n\t\t\tAND date = ?\n\t\t\tORDER BY symbol\n\t\t\t\"\"\", (current_date,))\n\n\telif stock_filter == \"rsi_oversold\":\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT symbol, name, stock_id, date\n\t\t\tFROM stock_price JOIN stock \n\t\t\t\tON stock_price.stock_id = stock.id\n\t\t\tWHERE rsi_14 < 30\n\t\t\tAND date = ?\n\t\t\tORDER BY symbol\n\t\t\t\"\"\", (current_date,))\n\n\telif stock_filter == \"above_sma_20\":\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT symbol, name, stock_id, date\n\t\t\tFROM stock_price JOIN stock \n\t\t\t\tON stock_price.stock_id = stock.id\n\t\t\tWHERE close > sma_20\n\t\t\tAND date = ?\n\t\t\tORDER BY symbol\n\t\t\t\"\"\", (current_date,))\n\n\telif stock_filter == \"below_sma_20\":\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT symbol, name, stock_id, date\n\t\t\tFROM stock_price JOIN stock \n\t\t\t\tON stock_price.stock_id = stock.id\n\t\t\tWHERE close < sma_20\n\t\t\tAND date = ?\n\t\t\tORDER BY symbol\n\t\t\t\"\"\", (current_date,))\n\n\telse:\n\t\tcursor.execute(\"\"\"\n\t\t\tSELECT id, symbol, name FROM stock ORDER BY symbol\n\t\t\t\"\"\")\n\n\trows = cursor.fetchall()\n\n\tcursor.execute(\"\"\"\n\t\tSELECT symbol, close, sma_20, sma_50, rsi_14\n\t\tFROM stock JOIN stock_price\n\t\t\tON stock_price.stock_id = stock.id\n\t\tWHERE date = ?\n\t\t\"\"\", (current_date,))\n\n\tindicator_rows = cursor.fetchall()\n\tindicator_values = dict()\n\tfor row in indicator_rows:\n\t\tindicator_values[row['symbol']] = row\n\n\n\treturn templates.TemplateResponse(\"index.html\", {'request': request, 'stocks': rows, 'indicator_values': indicator_values})\n\t#return{'title': 'Dashboard', 'stocks': rows}\n\n@app.get(\"/stock/{symbol}\")\ndef stock_detail(request: Request, symbol):\n\tconnection = sqlite3.connect(config.DB_FILE)\n\tconnection.row_factory = sqlite3.Row #This converts rows to objects\n\n\tcursor = connection.cursor()\n\n\tcursor.execute(\"\"\"\n\t\tSELECT id, symbol, name FROM stock WHERE symbol = ?\n\t\t\"\"\", (symbol,))\n\n\trow = cursor.fetchone()\n\n\t# cursor.execute(\"\"\"\n\t# \tSELECT 'date', open, high, low, close, volume\n\t# \tFROM stock_price JOIN stock ON stock_price.stock_id = stock.id\n\t# \tWHERE stock.symbol = ?\n\t# \tORDER BY 'date'\n\t# \t\"\"\", (symbol, ))\n\tcursor.execute(\"\"\"\n\t\tSELECT * FROM stock_price\n\t\tWHERE stock_id = ?\n\t\tORDER BY date DESC\n\t\t\"\"\", (row['id'],))\n\n\tprices = cursor.fetchall()\n\n\n\t# Strategies\n\tcursor.execute(\"\"\"\n\t\tSELECT * FROM strategy\n\t\t\"\"\")\n\n\tstrategies = cursor.fetchall()\n\n\treturn templates.TemplateResponse(\"stock_detail.html\", {'request': request, 'stocks': row, 'bars': prices, 'strategies':strategies})\n\n@app.post(\"/apply_strategy\")\ndef apply_strategy(strategy_id: int = Form(...), stock_id: int = Form(...)):\n\tconnection = sqlite3.connect(config.DB_FILE)\n\n\tcursor = connection.cursor()\n\n\tcursor.execute(\"\"\"\n\t\tINSERT INTO stock_strategy (stock_id, strategy_id) VALUES (?, ?)\n\t\t\"\"\", (stock_id, strategy_id))\n\n\tconnection.commit()\n\n\treturn RedirectResponse(url = f\"/strategy/{strategy_id}\", status_code = 303)\n\n\n@app.get(\"/strategies\")\ndef strategies(request: Request):\n\n\tconnection = sqlite3.connect(config.DB_FILE)\n\tconnection.row_factory = sqlite3.Row #This converts rows to objects\n\n\tcursor = connection.cursor()\n\n\tcursor.execute(\"\"\"SELECT * FROM strategy\"\"\")\n\n\tstrategies = cursor.fetchall()\n\treturn templates.TemplateResponse(\"strategies.html\", {'request': request, 'strategies': strategies})\n\n@app.get(\"/strategy/{strategy_id}\")\ndef strategy(request: Request, strategy_id):\n\tconnection = sqlite3.connect(config.DB_FILE)\n\tconnection.row_factory = sqlite3.Row #This converts rows to objects\n\n\tcursor = connection.cursor()\n\n\tcursor.execute(\"\"\"\n\t\tSELECT id, name FROM strategy WHERE id = ?\n\t\t\"\"\", (strategy_id,))\n\n\tstrategy = cursor.fetchone()\n\n\tcursor.execute(\"\"\"\n\t\tSELECT *\n\t\tFROM stock JOIN stock_strategy ON stock_strategy.stock_id = stock.id\n\t\tWHERE stock_strategy.strategy_id = ?\n\t\t\"\"\", (strategy_id,))\n\n\tstocks = cursor.fetchall()\n\n\treturn templates.TemplateResponse(\"strategy.html\", {'request': request, 'stocks': stocks, 'strategy':strategy})\n\n\n@app.get(\"/orders\")\ndef orders(request: Request):\n\t# Contact with the API\n\tapi = tradeapi.REST(config.API_KEY, config.SECRET_KEY, base_url=config.BASE_URL)\n\n\torders = api.list_orders(status='all')\n\n\treturn templates.TemplateResponse(\"orders.html\", {'request': request, 'orders': orders})\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"257417954","text":"#Tile :-creating fuction for reverse integer,sum of primes and matching () pattern in string\n#Author:-Vighnesh Gawad\ndef intreverse(a): \n\tb=int(a)\n\tnew=0\n\twhile b != 0:\n\t\tc=b%10\n\t\tnew=new*10+c\n\t\tb=b//10\n\t\ndef sumprimes(a):\n\tsum=0\n\tfor i in a:\n\t\tflag=0\n\t\tj=2\n\t\twhile j <= i//2:\n\t\t\tif i%j == 0:\n\t\t\t\tflag=1\n\t\t\t\tbreak\n\t\t\tj=j+1\n\t\tif flag == 0:\n\t\t\tsum=sum+i\n\treturn(sum)\n\ndef matched(s):\n\tc=0;b=0\n\tfor i in range(0,len(s)):\n\t\tif s[i] == '(':\n\t\t\tflag=False\n\t\t\tc=c+1\n\t\t\tfor j in s[i:]:\n\t\t\t\tif j == ')':\n\t\t\t\t\tflag=True\n\t\t\t\t\tbreak\n\t\telif s[i] == ')':\n\t\t\tb=b+1\n\tif c == b and flag == True:\n\t\tflag2=True\n\telse:\n\t\tflag2=False\n\treturn(flag2)\n","sub_path":"week2.py","file_name":"week2.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"592879158","text":"################################################################################\n## S T R I P P I N G 21r1p1 ##\n## ##\n## Configuration for RD WG ##\n## Contact persons: Pablo Ruiz Valls pruizval@cern.ch ##\n## Guido Andreassi guido.andreassi@cern.ch ##\n################################################################################\n\nB2KstTauTau = {\n \"BUILDERTYPE\": \"B2KstTauXConf\",\n \"CONFIG\": {\n \"AMAXDOCA_D\": \"0.2\",\n \"APT_D\": \"800\",\n \"B2DDSL_LinePostscale\": 1,\n \"B2DDSL_LinePrescale\": 1,\n \"B2KstMuMu_LinePostscale\": 1,\n \"B2KstMuMu_LinePrescale\": 1,\n \"B2KstMuMu_SameSign_LinePostscale\": 1,\n \"B2KstMuMu_SameSign_LinePrescale\": 1,\n \"B2KstTauMu_LinePostscale\": 1,\n \"B2KstTauMu_LinePrescale\": 1,\n \"B2KstTauMu_SameSign_LinePostscale\": 1,\n \"B2KstTauMu_SameSign_LinePrescale\": 0.5,\n \"B2KstTauTau_LinePostscale\": 1,\n \"B2KstTauTau_LinePrescale\": 1,\n \"B2KstTauTau_SameSign_LinePostscale\": 1,\n \"B2KstTauTau_SameSign_LinePrescale\": 1,\n \"B_COSDIRA_KMM\": \"0.999\",\n \"DIRA_D\": \"0.99\",\n \"DOCAMAX_KST_KMM\": \"0.15\",\n \"FDCHI2OWNPV_KST_KMM\": \"120\",\n \"FDCHI2_B\": \"80\",\n \"FDCHI2_D\": \"16\",\n \"FD_B_Max_KTM\": \"70\",\n \"FD_B_Max_KTT\": \"40\",\n \"FD_B_Mu\": \"3\",\n \"FD_B_Mu_KMM\": \"3\",\n \"FD_Kst_Mu_KMM\": \"3\",\n \"IPCHI2_HAD_ALL_FINAL_STATE\": \"16\",\n \"MASS_HIGH_B\": \"10000\",\n \"MASS_HIGH_B_KMM\": \"10000\",\n \"MASS_HIGH_D\": \"1900\",\n \"MASS_HIGH_Ds\": \"1998\",\n \"MASS_HIGH_Kst\": \"1100\",\n \"MASS_LOW_B\": \"2000\",\n \"MASS_LOW_B_KMM\": \"1500\",\n \"MASS_LOW_D\": \"1840\",\n \"MASS_LOW_Ds\": \"1938\",\n \"MASS_LOW_Kst\": \"700\",\n \"MINIPCHI2_KST_KMM\": \"3\",\n \"MINIPCHI2_K_KMM\": \"4\",\n \"MINIPCHI2_MU_KMM\": \"4\",\n \"MINIPCHI2_PI_KMM\": \"4\",\n \"MaxPT_D\": \"800\",\n \"PT_B_KMM\": \"2000\",\n \"PT_B_KTM\": \"3000\",\n \"PT_B_KTT\": \"3000\",\n \"PT_D\": \"1000\",\n \"PT_HAD_ALL_FINAL_STATE\": \"250\",\n \"PT_Kst\": \"1000\",\n \"PT_MU\": \"1000\",\n \"PT_MU_KMM\": \"800\",\n \"P_HAD_ALL_FINAL_STATE\": \"2000\",\n \"RelatedInfoTools\": [\n {\n \"Location\": \"B2KstTauTau_MuonIsolationBDT\",\n \"Type\": \"RelInfoBKsttautauMuonIsolationBDT\",\n \"Variables\": [\n \"BKSTTAUTAUMUONISOBDTFIRSTVALUETAUP\",\n \"BKSTTAUTAUMUONISOBDTSECONDVALUETAUP\",\n \"BKSTTAUTAUMUONISOBDTTHIRDVALUETAUP\",\n \"BKSTTAUTAUMUONISOBDTFIRSTVALUETAUM\",\n \"BKSTTAUTAUMUONISOBDTSECONDVALUETAUM\",\n \"BKSTTAUTAUMUONISOBDTTHIRDVALUETAUM\"\n ]\n },\n {\n \"Location\": \"B2KstTauTau_TauIsolationBDT\",\n \"Type\": \"RelInfoBKsttautauTauIsolationBDT\",\n \"Variables\": [\n \"BKSTTAUTAUTAUISOBDTFIRSTVALUETAUP\",\n \"BKSTTAUTAUTAUISOBDTSECONDVALUETAUP\",\n \"BKSTTAUTAUTAUISOBDTTHIRDVALUETAUP\",\n \"BKSTTAUTAUTAUISOBDTFIRSTVALUETAUM\",\n \"BKSTTAUTAUTAUISOBDTSECONDVALUETAUM\",\n \"BKSTTAUTAUTAUISOBDTTHIRDVALUETAUM\",\n \"BKSTTAUTAUTAUISOBDTFIRSTVALUEKST\",\n \"BKSTTAUTAUTAUISOBDTSECONDVALUEKST\",\n \"BKSTTAUTAUTAUISOBDTTHIRDVALUEKST\"\n ]\n },\n {\n \"Location\": \"B2KstTauTau_TrackIsolationBDT\",\n \"Type\": \"RelInfoBKsttautauTrackIsolationBDT\",\n \"Variables\": [\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUETAUPPIM\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUETAUPPIM\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUETAUPPIM\",\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUETAUPPIP1\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUETAUPPIP1\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUETAUPPIP1\",\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUETAUPPIP2\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUETAUPPIP2\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUETAUPPIP2\",\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUETAUMPIP\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUETAUMPIP\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUETAUMPIP\",\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUETAUMPIM1\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUETAUMPIM1\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUETAUMPIM1\",\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUETAUMPIM2\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUETAUMPIM2\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUETAUMPIM2\",\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUEKSTK\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUEKSTK\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUEKSTK\",\n \"BKSTTAUTAUTRKISOBDTFIRSTVALUEKSTPI\",\n \"BKSTTAUTAUTRKISOBDTSECONDVALUEKSTPI\",\n \"BKSTTAUTAUTRKISOBDTTHIRDVALUEKSTPI\"\n ]\n },\n {\n \"Location\": \"B2KstTauTau_CDFIso\",\n \"Type\": \"RelInfoBstautauCDFIso\"\n }\n ],\n \"SpdMult\": \"600\",\n \"TRACKCHI2_HAD_ALL_FINAL_STATE\": \"4\",\n \"TRACKCHI2_MU\": \"4\",\n \"TRGHOPROB_HAD_ALL_FINAL_STATE\": \"0.4\",\n \"VCHI2_B\": \"100\",\n \"VCHI2_B_Mu\": \"150\",\n \"VCHI2_B_Mu_KMM\": \"100\",\n \"VCHI2_D\": \"16\",\n \"VCHI2_Kst\": \"15\",\n \"VDRHOmax_D\": \"7.0\",\n \"VDRHOmin_D\": \"0.1\",\n \"VDZ_D\": \"5.0\"\n },\n \"STREAMS\": [ \"Bhadron\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nB2Lambda0Mu = {\n \"BUILDERTYPE\": \"B2Lambda0MuLines\",\n \"CONFIG\": {\n \"BDIRA\": 0.99,\n \"BVCHI2DOF\": 4.0,\n \"GEC_nLongTrk\": 300.0,\n \"Lambda0DaugMIPChi2\": 10.0,\n \"Lambda0DaugP\": 2000.0,\n \"Lambda0DaugPT\": 250.0,\n \"Lambda0DaugTrackChi2\": 4.0,\n \"Lambda0PT\": 700.0,\n \"Lambda0VertexChi2\": 10.0,\n \"LambdaMuMassLowTight\": 1500.0,\n \"LambdaZ\": 0.0,\n \"MajoranaCutFDChi2\": 100.0,\n \"MajoranaCutM\": 1500.0,\n \"MuonGHOSTPROB\": 0.5,\n \"MuonMINIPCHI2\": 12,\n \"MuonP\": 3000.0,\n \"MuonPIDK\": 0.0,\n \"MuonPIDmu\": 0.0,\n \"MuonPIDp\": 0.0,\n \"MuonPT\": 250.0,\n \"MuonTRCHI2\": 4.0,\n \"XMuMassUpperHigh\": 6500.0\n },\n \"STREAMS\": [ \"Dimuon\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nB2XMuMu = {\n \"BUILDERTYPE\": \"B2XMuMuConf\",\n \"CONFIG\": {\n \"A1_Comb_MassHigh\": 5550.0,\n \"A1_Comb_MassLow\": 0.0,\n \"A1_Dau_MaxIPCHI2\": 9.0,\n \"A1_FlightChi2\": 25.0,\n \"A1_MassHigh\": 5500.0,\n \"A1_MassLow\": 0.0,\n \"A1_MinIPCHI2\": 4.0,\n \"A1_VtxChi2\": 10.0,\n \"B_Comb_MassHigh\": 7100.0,\n \"B_Comb_MassLow\": 4600.0,\n \"B_DIRA\": 0.9999,\n \"B_Dau_MaxIPCHI2\": 9.0,\n \"B_FlightCHI2\": 121.0,\n \"B_IPCHI2\": 16.0,\n \"B_MassHigh\": 7000.0,\n \"B_MassLow\": 4700.0,\n \"B_VertexCHI2\": 8.0,\n \"DECAYS\": [\n \"[B0 -> J/psi(1S) K*(892)0]cc\",\n \"[B+ -> J/psi(1S) rho(770)+]cc\",\n \"[B+ -> J/psi(1S) K+]cc\",\n \"[B+ -> J/psi(1S) K*(892)+]cc\",\n \"B0 -> J/psi(1S) pi0\"\n ],\n \"Dau_DIRA\": -0.9,\n \"Dau_VertexCHI2\": 12.0,\n \"Dimu_Dau_MaxIPCHI2\": 9.0,\n \"Dimu_FlightChi2\": 9.0,\n \"DimuonUPPERMASS\": 7100.0,\n \"DimuonWS\": True,\n \"DplusLOWERMASS\": 1600.0,\n \"DplusUPPERMASS\": 2300.0,\n \"HLT1_FILTER\": None,\n \"HLT2_FILTER\": None,\n \"HadronWS\": True,\n \"Hadron_MinIPCHI2\": 6.0,\n \"K12OmegaK_CombMassHigh\": 2000,\n \"K12OmegaK_CombMassLow\": 400,\n \"K12OmegaK_MassHigh\": 2100,\n \"K12OmegaK_MassLow\": 300,\n \"K12OmegaK_VtxChi2\": 10,\n \"KpiVXCHI2NDOF\": 9.0,\n \"KsWINDOW\": 30.0,\n \"Kstar_Comb_MassHigh\": 6200.0,\n \"Kstar_Comb_MassLow\": 0.0,\n \"Kstar_Dau_MaxIPCHI2\": 9.0,\n \"Kstar_FlightChi2\": 9.0,\n \"Kstar_MassHigh\": 6200.0,\n \"Kstar_MassLow\": 0.0,\n \"Kstar_MinIPCHI2\": 0.0,\n \"KstarplusWINDOW\": 300.0,\n \"L0DU_FILTER\": None,\n \"LambdaWINDOW\": 30.0,\n \"LongLivedPT\": 0.0,\n \"LongLivedTau\": 2,\n \"MuonNoPIDs_PIDmu\": 0.0,\n \"MuonPID\": -3.0,\n \"Muon_IsMuon\": True,\n \"Muon_MinIPCHI2\": 9.0,\n \"OmegaChi2Prob\": 1e-05,\n \"Omega_CombMassWin\": 200,\n \"Omega_MassWin\": 100,\n \"Pi0ForOmegaMINPT\": 500.0,\n \"Pi0MINPT\": 700.0,\n \"RelatedInfoTools\": [\n {\n \"Location\": \"ConeIsoInfo\",\n \"Type\": \"RelInfoConeVariables\",\n \"Variables\": [\n \"CONEANGLE\",\n \"CONEMULT\",\n \"CONEPTASYM\",\n \"CONEPT\",\n \"CONEP\",\n \"CONEPASYM\",\n \"CONEDELTAETA\",\n \"CONEDELTAPHI\"\n ]\n },\n {\n \"ConeSize\": 1.0,\n \"Location\": \"ConeIsoInfoCCNC\",\n \"Type\": \"RelInfoConeIsolation\",\n \"Variables\": [\n \"CC_ANGLE\",\n \"CC_MULT\",\n \"CC_SPT\",\n \"CC_VPT\",\n \"CC_PX\",\n \"CC_PY\",\n \"CC_PZ\",\n \"CC_PASYM\",\n \"CC_PTASYM\",\n \"CC_PXASYM\",\n \"CC_PYASYM\",\n \"CC_PZASYM\",\n \"CC_DELTAETA\",\n \"CC_DELTAPHI\",\n \"CC_IT\",\n \"CC_MAXPT_Q\",\n \"CC_MAXPT_PT\",\n \"CC_MAXPT_PX\",\n \"CC_MAXPT_PY\",\n \"CC_MAXPT_PZ\",\n \"CC_MAXPT_PE\",\n \"NC_ANGLE\",\n \"NC_MULT\",\n \"NC_SPT\",\n \"NC_VPT\",\n \"NC_PX\",\n \"NC_PY\",\n \"NC_PZ\",\n \"NC_PASYM\",\n \"NC_PTASYM\",\n \"NC_PXASYM\",\n \"NC_PYASYM\",\n \"NC_PZASYM\",\n \"NC_DELTAETA\",\n \"NC_DELTAPHI\",\n \"NC_IT\",\n \"NC_MAXPT_PT\",\n \"NC_MAXPT_PX\",\n \"NC_MAXPT_PY\",\n \"NC_MAXPT_PZ\"\n ]\n },\n {\n \"Location\": \"VtxIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\",\n \"Variables\": [\n \"VTXISONUMVTX\",\n \"VTXISODCHI2ONETRACK\",\n \"VTXISODCHI2MASSONETRACK\",\n \"VTXISODCHI2TWOTRACK\",\n \"VTXISODCHI2MASSTWOTRACK\"\n ]\n },\n {\n \"Location\": \"VtxIsoBDTInfo\",\n \"Type\": \"RelInfoVertexIsolationBDT\"\n }\n ],\n \"SpdMult\": 600,\n \"Track_GhostProb\": 0.5,\n \"UseNoPIDsHadrons\": True\n },\n \"STREAMS\": [ \"Leptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nB2XTauMu = {\n \"BUILDERTYPE\": \"B2XTauMuConf\",\n \"CONFIG\": {\n \"BDIRA_K\": 0.99,\n \"BDIRA_K_3pi\": 0.999,\n \"BDIRA_kst\": 0.95,\n \"BVCHI2DOF_K\": 15.0,\n \"BVCHI2DOF_K_3pi\": 4.0,\n \"BVCHI2DOF_kst\": 25.0,\n \"BVCHI2DOF_phi\": 10000000000.0,\n \"B_FDCHI2_K\": 400.0,\n \"B_FDCHI2_kst\": 80,\n \"B_MAX_MASS\": 10000,\n \"B_MAX_MASS_K_3pi\": 10000,\n \"B_MIN_MASS\": 2000,\n \"B_MIN_MASS_K_3pi\": 3000,\n \"B_PT_K\": 3000.0,\n \"KMuPT_K\": 1000.0,\n \"KMuSumPT_K\": 2000.0,\n \"KPiPT_K\": 800.0,\n \"KPiPT_kst\": 500.0,\n \"KaonPIDK\": 4.0,\n \"KaonPIDK_K\": 5,\n \"KaonPIDK_K_3pi\": 6,\n \"KaonP_K\": 3.0,\n \"KaonP_K_3pi\": 6.0,\n \"KaonP_kst\": 2.0,\n \"KstAMassWin\": 180.0,\n \"KstMassWin\": 150.0,\n \"KstVCHI2DOF\": 15.0,\n \"MINIPCHI2\": 16.0,\n \"MINIPCHI2_K\": 36.0,\n \"MuTauWS\": True,\n \"MuonPT_K\": 800.0,\n \"MuonPT_kst\": 500.0,\n \"MuonP_K\": 5.0,\n \"MuonP_K_3pi\": 6.0,\n \"MuonP_kst\": 2.0,\n \"PIDmu\": 2.0,\n \"PhiAMassWin\": 30.0,\n \"PhiMassWin\": 25.0,\n \"PhiVCHI2DOF\": 20.0,\n \"PionPIDK\": 0.0,\n \"PionP_kst\": 2.0,\n \"Prescale\": 1,\n \"Prescale_WS\": 0.5,\n \"RelatedInfoTools\": [\n {\n \"Location\": \"VertexIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\"\n },\n {\n \"Location\": \"VertexIsoBDTInfo\",\n \"Type\": \"RelInfoVertexIsolationBDT\"\n },\n {\n \"ConeAngle\": 1.0,\n \"Location\": \"ConeVarsInfo\",\n \"Type\": \"RelInfoConeVariables\"\n },\n {\n \"ConeSize\": 0.5,\n \"DaughterLocations\": {\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l+]CC \": \"ConeIsoInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l-]CC \": \"ConeIsoInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l+]CC \": \"ConeIsoInfoH1\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l-]CC \": \"ConeIsoInfoH1\",\n \"[Beauty -> (X+ -> X+ ^l+) l+]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ ^l+) l-]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ l+) ^l+]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X+ -> X+ l+) ^l-]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X+ -> X0 ^l+) l+]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X0 ^l+) l-]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X0 l+) ^l+]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X+ -> X0 l+) ^l-]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X+ -> ^X+ l+) l+]CC \": \"ConeIsoInfoH\",\n \"[Beauty -> (X+ -> ^X+ l+) l-]CC \": \"ConeIsoInfoH\",\n \"[Beauty -> (X0 -> X+ ^l-) l+]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ ^l-) l-]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ l-) ^l+]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ l-) ^l-]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0 -> ^X+ l-) l+]CC \": \"ConeIsoInfoH\",\n \"[Beauty -> (X0 -> ^X+ l-) l-]CC \": \"ConeIsoInfoH\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l+]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l-]CC \": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l+]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l-]CC \": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l+]CC \": \"ConeIsoInfoH1\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l-]CC \": \"ConeIsoInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l+]CC \": \"ConeIsoInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l-]CC \": \"ConeIsoInfoH1\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"Type\": \"RelInfoConeIsolation\"\n },\n {\n \"ConeAngle\": 0.5,\n \"DaughterLocations\": {\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l+]CC \": \"ConeVarsInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l-]CC \": \"ConeVarsInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l+]CC \": \"ConeVarsInfoH1\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l-]CC \": \"ConeVarsInfoH1\",\n \"[Beauty -> (X+ -> X+ ^l+) l+]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X+ -> X+ ^l+) l-]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X+ -> X+ l+) ^l+]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X+ -> X+ l+) ^l-]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X+ -> X0 ^l+) l+]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X+ -> X0 ^l+) l-]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X+ -> X0 l+) ^l+]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X+ -> X0 l+) ^l-]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X+ -> ^X+ l+) l+]CC \": \"ConeVarsInfoH\",\n \"[Beauty -> (X+ -> ^X+ l+) l-]CC \": \"ConeVarsInfoH\",\n \"[Beauty -> (X0 -> X+ ^l-) l+]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X0 -> X+ ^l-) l-]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X0 -> X+ l-) ^l+]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X0 -> X+ l-) ^l-]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X0 -> ^X+ l-) l+]CC \": \"ConeVarsInfoH\",\n \"[Beauty -> (X0 -> ^X+ l-) l-]CC \": \"ConeVarsInfoH\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l+]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l-]CC \": \"ConeVarsInfoL1\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l+]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l-]CC \": \"ConeVarsInfoL2\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l+]CC \": \"ConeVarsInfoH1\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l-]CC \": \"ConeVarsInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l+]CC \": \"ConeVarsInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l-]CC \": \"ConeVarsInfoH1\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"Type\": \"RelInfoConeVariables\"\n },\n {\n \"DaughterLocations\": {\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l+]CC \": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l-]CC \": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l+]CC \": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l-]CC \": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X+ -> X+ ^l+) l+]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X+ ^l+) l-]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X+ l+) ^l+]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X+ -> X+ l+) ^l-]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X+ -> X0 ^l+) l+]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X0 ^l+) l-]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X0 l+) ^l+]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X+ -> X0 l+) ^l-]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X+ -> ^X+ l+) l+]CC \": \"TrackIsoBDTInfoH\",\n \"[Beauty -> (X+ -> ^X+ l+) l-]CC \": \"TrackIsoBDTInfoH\",\n \"[Beauty -> (X0 -> X+ ^l-) l+]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0 -> X+ ^l-) l-]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0 -> X+ l-) ^l+]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0 -> X+ l-) ^l-]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0 -> ^X+ l-) l+]CC \": \"TrackIsoBDTInfoH\",\n \"[Beauty -> (X0 -> ^X+ l-) l-]CC \": \"TrackIsoBDTInfoH\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l+]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l-]CC \": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l+]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l-]CC \": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l+]CC \": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l-]CC \": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l+]CC \": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l-]CC \": \"TrackIsoBDTInfoH1\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"Type\": \"RelInfoTrackIsolationBDT\"\n },\n {\n \"DaughterLocations\": {\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l+]CC \": \"TrackIsoBsMMInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> X+ ^X-) l+) l-]CC \": \"TrackIsoBsMMInfoH2\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l+]CC \": \"TrackIsoBsMMInfoH1\",\n \"[Beauty -> (X+ -> (X0 -> ^X+ X-) l+) l-]CC \": \"TrackIsoBsMMInfoH1\",\n \"[Beauty -> (X+ -> X+ ^l+) l+]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X+ -> X+ ^l+) l-]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X+ -> X+ l+) ^l+]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X+ -> X+ l+) ^l-]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X+ -> X0 ^l+) l+]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X+ -> X0 ^l+) l-]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X+ -> X0 l+) ^l+]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X+ -> X0 l+) ^l-]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X+ -> ^X+ l+) l+]CC \": \"TrackIsoBsMMInfoH\",\n \"[Beauty -> (X+ -> ^X+ l+) l-]CC \": \"TrackIsoBsMMInfoH\",\n \"[Beauty -> (X0 -> X+ ^l-) l+]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X0 -> X+ ^l-) l-]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X0 -> X+ l-) ^l+]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X0 -> X+ l-) ^l-]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X0 -> ^X+ l-) l+]CC \": \"TrackIsoBsMMInfoH\",\n \"[Beauty -> (X0 -> ^X+ l-) l-]CC \": \"TrackIsoBsMMInfoH\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l+]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X0-> X+ X-) ^l+ l-]CC \": \"TrackIsoBsMMInfoL1\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l+]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X0-> X+ X-) l+ ^l-]CC \": \"TrackIsoBsMMInfoL2\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l+]CC \": \"TrackIsoBsMMInfoH1\",\n \"[Beauty -> (X0-> X+ ^X-) l+ l-]CC \": \"TrackIsoBsMMInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l+]CC \": \"TrackIsoBsMMInfoH1\",\n \"[Beauty -> (X0-> ^X+ X-) l+ l-]CC \": \"TrackIsoBsMMInfoH1\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"IsoTwoBody\": False,\n \"Type\": \"RelInfoBs2MuMuTrackIsolations\",\n \"angle\": 0.27,\n \"doca_iso\": 0.13,\n \"fc\": 0.6,\n \"ips\": 3.0,\n \"makeTrackCuts\": False,\n \"pvdis\": 0.5,\n \"pvdis_h\": 40.0,\n \"svdis\": -0.15,\n \"svdis_h\": 30.0,\n \"tracktype\": 3\n }\n ],\n \"TrackCHI2\": 3,\n \"TrackGhostProb\": 0.5,\n \"XMuVCHI2DOF_K\": 9.0,\n \"XMuVCHI2DOF_kst\": 15.0,\n \"XMuVCHI2DOF_phi\": 20.0\n },\n \"STREAMS\": {\n \"Dimuon\": [\n \"StrippingB2XTauMu_KstLine\",\n \"StrippingB2XTauMu_Kst_WSLine\",\n \"StrippingB2XTauMu_K_3piLine\",\n \"StrippingB2XTauMu_K_3pi_WSLine\"\n ],\n \"Leptonic\": [\n \"StrippingB2XTauMu_PhiLine\",\n \"StrippingB2XTauMu_KLine\",\n \"StrippingB2XTauMu_Phi_3piLine\",\n \"StrippingB2XTauMu_Phi_WSLine\",\n \"StrippingB2XTauMu_K_WSLine\",\n \"StrippingB2XTauMu_Phi_3pi_WSLine\",\n \"StrippingB2XTauMu_K_3pi_looseLine\",\n \"StrippingB2XTauMu_K_3pi_loose_WSLine\"\n ]\n },\n \"WGs\": [ \"RD\" ]\n}\n\nBeauty2XGamma = {\n \"BUILDERTYPE\": \"Beauty2XGammaConf\",\n \"CONFIG\": {\n \"B2PhiOmega2pipipi0MPrescale\": 1.0,\n \"B2PhiOmega2pipipi0RPrescale\": 1.0,\n \"B2XG2pi2KsPrescale\": 0.0,\n \"B2XG2piCNVDDPrescale\": 0.0,\n \"B2XG2piCNVLLPrescale\": 0.0,\n \"B2XG2piGGPrescale\": 1.0,\n \"B2XG2piKsPrescale\": 0.0,\n \"B2XG2piPrescale\": 0.0,\n \"B2XG2pipi0MPrescale\": 0.0,\n \"B2XG2pipi0RPrescale\": 0.0,\n \"B2XG3piCNVDDPrescale\": 0.0,\n \"B2XG3piCNVLLPrescale\": 0.0,\n \"B2XG3piGGPrescale\": 1.0,\n \"B2XG3piKsPrescale\": 0.0,\n \"B2XG3piPrescale\": 0.0,\n \"B2XG3pipi0MPrescale\": 0.0,\n \"B2XG3pipi0RPrescale\": 0.0,\n \"B2XG4piPrescale\": 0.0,\n \"B2XGBMaxCorrM\": 73000.0,\n \"B2XGBMaxM\": 9000.0,\n \"B2XGBMinBPVDIRA\": 0.0,\n \"B2XGBMinM2pi\": 3280.0,\n \"B2XGBMinM3pi\": 2900.0,\n \"B2XGBMinM4pi\": 2560.0,\n \"B2XGBMinMLambda\": 2560.0,\n \"B2XGBMinPT\": 200.0,\n \"B2XGBSumPtMin\": 5000,\n \"B2XGBVtxChi2DOF\": 9.0,\n \"B2XGBVtxMaxIPChi2\": 9.0,\n \"B2XGGammaCL\": 0.0,\n \"B2XGGammaCNVPTMin\": 1000.0,\n \"B2XGGammaPTMin\": 2000.0,\n \"B2XGLambda2piPrescale\": 0.0,\n \"B2XGLambda3piPrescale\": 0.0,\n \"B2XGLambdapiPrescale\": 0.0,\n \"B2XGLbLambdaPrescale\": 0.0,\n \"B2XGPhiOmegaMaxMass\": 1300.0,\n \"B2XGPhiOmegaMinMass\": 700.0,\n \"B2XGResBPVVDCHI2Min\": 0.0,\n \"B2XGResDocaMax\": 100.5,\n \"B2XGResIPCHI2Min\": 0.0,\n \"B2XGResMaxMass\": 7900.0,\n \"B2XGResMinMass\": 0.0,\n \"B2XGResMinPT\": 150.0,\n \"B2XGResSumPtMin\": 1500.0,\n \"B2XGResVtxChi2DOF\": 10.0,\n \"B2XGTrkChi2DOF\": 3.0,\n \"B2XGTrkMinIPChi2\": 16.0,\n \"B2XGTrkMinP\": 1000,\n \"B2XGTrkMinPT\": 300.0,\n \"B2XGpiKsPrescale\": 0.0,\n \"Pi0MPMin\": 4000.0,\n \"Pi0MPTMin\": 700.0,\n \"Pi0MPTReCut\": 1200.0,\n \"Pi0RPMin\": 4000.0,\n \"Pi0RPTMin\": 700.0,\n \"Pi0RPTReCut\": 1700.0,\n \"TISTOSLinesDict\": {\n \"Hlt2IncPhi.*Decision%TIS\": 0,\n \"Hlt2IncPhi.*Decision%TOS\": 0,\n \"Hlt2Radiative.*Decision%TIS\": 0,\n \"Hlt2Radiative.*Decision%TOS\": 0,\n \"Hlt2Topo(2|3|4)Body.*Decision%TIS\": 0,\n \"Hlt2Topo(2|3|4)Body.*Decision%TOS\": 0\n },\n \"TrackGhostProb\": 0.4\n },\n \"STREAMS\": [ \"Leptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nBs2MuMuLines = {\n \"BUILDERTYPE\": \"Bs2MuMuLinesConf\",\n \"CONFIG\": {\n \"BFDChi2_loose\": 100,\n \"BIPChi2_loose\": 64,\n \"BPVVDChi2\": 121,\n \"B_BPVIPChi2\": 25,\n \"B_BPVIPChi2_LTUB\": 25,\n \"B_Pt\": 350,\n \"B_Pt_LTUB\": 500,\n \"B_maximum_decaytime_bsst\": 0.2,\n \"B_minimum_decaytime_LTUB\": 0.6,\n \"B_minimum_decaytime_bsst\": 0.0,\n \"BdPrescale\": 0,\n \"Bs2KKLTUBLinePrescale\": 0,\n \"Bs2mmLTUBLinePrescale\": 0,\n \"Bs2mmWideLinePrescale\": 0,\n \"BsPrescale\": 0,\n \"Bsst2mmLinePrescale\": 1,\n \"BuPrescale\": 0,\n \"DOCA\": 0.3,\n \"DOCA_LTUB\": 0.3,\n \"DOCA_loose\": 0.5,\n \"DefaultLinePrescale\": 0,\n \"DefaultPostscale\": 1,\n \"JPsiLinePrescale\": 0,\n \"JPsiLooseLinePrescale\": 0.,\n \"JPsiPromptLinePrescale\": 0.,\n \"LooseLinePrescale\": 0.0,\n \"MuIPChi2_loose\": 9,\n \"MuTrChi2_loose\": 10,\n \"ProbNN\": 0.4,\n \"SSPrescale\": 0,\n \"SUMPT\": 4500,\n \"TrackGhostProb\": 0.4,\n \"TrackGhostProb_bsst\": 0.3,\n \"VCHI2_VDOF\": 9,\n \"VCHI2_VDOF_LTUB\": 9,\n \"VCHI2_VDOF_loose\": 25,\n \"daughter_IPChi2\": 9,\n \"daughter_TrChi2\": 4,\n \"daughter_TrChi2_LTUB\": 4,\n \"daughter_TrChi2_bsst\": 3,\n \"muon_PT_LTUB\": 40\n },\n \"STREAMS\": {\n \"Dimuon\": [\n \"StrippingBs2MuMuLinesNoMuIDLine\",\n \"StrippingBs2MuMuLinesWideMassLine\",\n \"StrippingBs2MuMuLinesBu2JPsiKLine\",\n \"StrippingBs2MuMuLinesBsstLine\"\n ],\n \"Leptonic\": [\n \"StrippingBs2MuMuLinesWideMassLine\",\n \"StrippingBs2MuMuLinesBs2JPsiPhiLine\",\n \"StrippingBs2MuMuLinesBs2KKLTUBLine\",\n \"StrippingBs2MuMuLinesNoMuIDLine\",\n \"StrippingBs2MuMuLinesSSLine\",\n \"StrippingBs2MuMuLinesBd2JPsiKstLine\",\n \"StrippingBs2MuMuLinesLTUBLine\",\n \"StrippingBs2MuMuLinesBu2JPsiKLine\"\n ]\n },\n \"WGs\": [ \"RD\" ]\n}\n\nBs2st2KKMuX = {\n \"BUILDERTYPE\": \"Bs2st2KKMuXConf\",\n \"CONFIG\": {\n \"Bs2PT\": 50.0,\n \"Bs2st2KKJpsiPrescale\": 1.0,\n \"Bs2st2KKJpsiWSPrescale\": 1.0,\n \"Bs2st2KKMuPrescale\": 1.0,\n \"Bs2st2KKMuWSPrescale\": 1.0,\n \"DMKKJpsi\": 1093.677,\n \"DMKKMu\": 713.677,\n \"DZBPV\": 1.0,\n \"GEC_nLongTrk\": 1000.0,\n \"HLT_FILTER\": \"\",\n \"JpsiMassWindow\": 80.0,\n \"K1MinIPChi2\": 9.0,\n \"K1PIDK\": 16.0,\n \"K1PT\": 500.0,\n \"K1PTLoose\": 250.0,\n \"K2MinIPChi2\": 9.0,\n \"K2P\": 3000.0,\n \"K2PIDK\": 0.0,\n \"K2PT\": 1000.0,\n \"KJpsiFdChi2\": 25.0,\n \"KJpsiMassMax\": 5500.0,\n \"KJpsiMassMin\": 5050.0,\n \"KJpsiVChi2Dof\": 4.0,\n \"KMuFdChi2\": 100.0,\n \"KMuMassMax\": 5500.0,\n \"KMuMassMin\": 1800.0,\n \"KMuVChi2Dof\": 4.0,\n \"MuMinIPChi2\": 9.0,\n \"MuP\": 3000.0,\n \"MuPIDmu\": 0.0,\n \"MuPT\": 1000.0,\n \"RelatedInfoTools\": [\n {\n \"DaughterLocations\": {\n \"[B*_s20 -> (B+ -> K+ [mu-]cc) ^[K-]cc]CC\": \"K1ISO\",\n \"[B*_s20 -> (B+ -> K+ ^[mu-]cc) [K-]cc]CC\": \"MuISO\",\n \"[B*_s20 -> (B+ -> ^K+ [mu-]cc) [K-]cc]CC\": \"K2ISO\"\n },\n \"IsoTwoBody\": True,\n \"Type\": \"RelInfoBs2MuMuTrackIsolations\",\n \"Variables\": [\n \"BSMUMUTRACKPLUSISO\",\n \"BSMUMUTRACKPLUSISOTWO\",\n \"ISOTWOBODYMASSISOPLUS\",\n \"ISOTWOBODYCHI2ISOPLUS\",\n \"ISOTWOBODYISO5PLUS\",\n \"BSMUMUTRACKID\"\n ],\n \"angle\": 0.27,\n \"doca_iso\": 0.13,\n \"fc\": 0.6,\n \"ips\": 3.0,\n \"makeTrackCuts\": False,\n \"pvdis\": 0.5,\n \"pvdis_h\": 40.0,\n \"svdis\": -0.15,\n \"svdis_h\": 30.0,\n \"tracktype\": 3\n }\n ]\n },\n \"STREAMS\": [ \"Semileptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nLFV = {\n \"BUILDERTYPE\": \"LFVLinesConf\",\n \"CONFIG\": {\n \"B2TauMuPrescale\": 0,\n \"B2eMuPrescale\": 1,\n \"JPsi2eMuPrescale\": 1,\n \"B2eePrescale\": 1,\n \"B2hTauMuPrescale\": 0,\n \"B2heMuPrescale\": 1,\n \"B2pMuPrescale\": 0,\n \"Bu2KJPsieePrescale\": 1,\n \"Postscale\": 1,\n \"RelatedInfoTools_B2eMu\": [\n {\n \"Location\": \"BSMUMUVARIABLES\",\n \"Type\": \"RelInfoBs2MuMuBIsolations\",\n \"Variables\": [\n \"BSMUMUCDFISO\",\n \"BSMUMUOTHERBMAG\",\n \"BSMUMUOTHERBANGLE\",\n \"BSMUMUOTHERBBOOSTMAG\",\n \"BSMUMUOTHERBBOOSTANGLE\",\n \"BSMUMUOTHERBTRACKS\"\n ],\n \"makeTrackCuts\": False,\n \"tracktype\": 3\n },\n {\n \"DaughterLocations\": {\n \"[B_s0 -> ^e+ [mu-]cc]CC\": \"Electron_ISO\",\n \"[B_s0 -> e+ ^[mu-]cc]CC\": \"Muon_ISO\"\n },\n \"IsoTwoBody\": True,\n \"Type\": \"RelInfoBs2MuMuTrackIsolations\",\n \"Variables\": [\n \"BSMUMUTRACKPLUSISO\",\n \"BSMUMUTRACKPLUSISOTWO\",\n \"ISOTWOBODYQPLUS\",\n \"ISOTWOBODYMASSISOPLUS\",\n \"ISOTWOBODYCHI2ISOPLUS\",\n \"ISOTWOBODYISO5PLUS\"\n ],\n \"angle\": 0.27,\n \"doca_iso\": 0.13,\n \"fc\": 0.6,\n \"ips\": 3.0,\n \"makeTrackCuts\": False,\n \"pvdis\": 0.5,\n \"pvdis_h\": 40.0,\n \"svdis\": -0.15,\n \"svdis_h\": 30.0,\n \"tracktype\": 3\n },\n {\n \"Location\": \"VtxIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\"\n },\n {\n \"Location\": \"ConeIsoInfo\",\n \"Type\": \"RelInfoConeVariables\"\n },\n {\n \"Location\": \"VtxIsoInfoBDT\",\n \"Type\": \"RelInfoVertexIsolationBDT\"\n },\n {\n \"Location\": \"ConeIsoInfoBDT\",\n \"Type\": \"RelInfoTrackIsolationBDT\"\n }\n ],\n \"RelatedInfoTools_JPsi2eMu\": [\n {\n 'Type': 'RelInfoBs2MuMuBIsolations',\n 'Variables' : ['BSMUMUCDFISO',\n 'BSMUMUOTHERBMAG',\n 'BSMUMUOTHERBANGLE',\n 'BSMUMUOTHERBBOOSTMAG',\n 'BSMUMUOTHERBBOOSTANGLE',\n 'BSMUMUOTHERBTRACKS'],\n 'Location' : 'BSMUMUVARIABLES', ## For the B\n 'tracktype' : 3,\n 'makeTrackCuts' : False\n },\n { \n 'Type' : 'RelInfoBs2MuMuTrackIsolations',\n 'Variables' : ['BSMUMUTRACKPLUSISO',\n 'BSMUMUTRACKPLUSISOTWO',\n 'ISOTWOBODYQPLUS',\n 'ISOTWOBODYMASSISOPLUS',\n 'ISOTWOBODYCHI2ISOPLUS',\n 'ISOTWOBODYISO5PLUS'],\n 'DaughterLocations' : {\n '[J/psi(1S) -> e+ ^[mu-]cc]CC' : 'Muon_ISO',\n '[J/psi(1S) -> ^e+ [mu-]cc]CC' : 'Electron_ISO',\n },\n 'tracktype' : 3,\n 'angle' : 0.27,\n 'fc' : 0.60,\n 'doca_iso' : 0.13,\n 'ips' : 3.0,\n 'svdis' : -0.15,\n 'svdis_h' : 30.,\n 'pvdis' : 0.5,\n 'pvdis_h' : 40.,\n 'makeTrackCuts' : False,\n 'IsoTwoBody' : True\n },\n {\n 'Type': 'RelInfoVertexIsolation',\n 'Location':'VtxIsoInfo',\n },\n {\n 'Type': 'RelInfoConeVariables',\n 'Location':'ConeIsoInfo',\n },\n {\n 'Type': 'RelInfoVertexIsolationBDT',\n 'Location':'VtxIsoInfoBDT',\n },\n {\n 'Type': 'RelInfoTrackIsolationBDT',\n 'Location':'ConeIsoInfoBDT',\n },\n ],\n \"RelatedInfoTools_B2ee\": [\n {\n \"Location\": \"BSMUMUVARIABLES\",\n \"Type\": \"RelInfoBs2MuMuBIsolations\",\n \"Variables\": [\n \"BSMUMUCDFISO\",\n \"BSMUMUOTHERBMAG\",\n \"BSMUMUOTHERBANGLE\",\n \"BSMUMUOTHERBBOOSTMAG\",\n \"BSMUMUOTHERBBOOSTANGLE\",\n \"BSMUMUOTHERBTRACKS\"\n ],\n \"makeTrackCuts\": False,\n \"tracktype\": 3\n },\n {\n \"DaughterLocations\": {\n \"[B_s0 -> ^e+ [e-]cc]CC\": \"Electron1_ISO\",\n \"[B_s0 -> e+ ^[e-]cc]CC\": \"Electron2_ISO\"\n },\n \"IsoTwoBody\": True,\n \"Type\": \"RelInfoBs2MuMuTrackIsolations\",\n \"Variables\": [\n \"BSMUMUTRACKPLUSISO\",\n \"BSMUMUTRACKPLUSISOTWO\",\n \"ISOTWOBODYQPLUS\",\n \"ISOTWOBODYMASSISOPLUS\",\n \"ISOTWOBODYCHI2ISOPLUS\",\n \"ISOTWOBODYISO5PLUS\"\n ],\n \"angle\": 0.27,\n \"doca_iso\": 0.13,\n \"fc\": 0.6,\n \"ips\": 3.0,\n \"makeTrackCuts\": False,\n \"pvdis\": 0.5,\n \"pvdis_h\": 40.0,\n \"svdis\": -0.15,\n \"svdis_h\": 30.0,\n \"tracktype\": 3\n },\n {\n \"Location\": \"VtxIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\"\n },\n {\n \"Location\": \"ConeIsoInfo\",\n \"Type\": \"RelInfoConeVariables\"\n },\n {\n \"Location\": \"VtxIsoInfoBDT\",\n \"Type\": \"RelInfoVertexIsolationBDT\"\n },\n {\n \"Location\": \"ConeIsoInfoBDT\",\n \"Type\": \"RelInfoTrackIsolationBDT\"\n }\n ],\n \"RelatedInfoTools_Bu2KJPsiee\": [\n {\n \"DaughterLocations\": {\n \"[B+ -> ^(J/psi(1S) -> e+ e-) K+]CC\": \"Jpsi_ISO\"\n },\n \"Location\": \"BSMUMUVARIABLES\",\n \"Type\": \"RelInfoBs2MuMuBIsolations\",\n \"Variables\": [\n \"BSMUMUCDFISO\",\n \"BSMUMUOTHERBMAG\",\n \"BSMUMUOTHERBANGLE\",\n \"BSMUMUOTHERBBOOSTMAG\",\n \"BSMUMUOTHERBBOOSTANGLE\",\n \"BSMUMUOTHERBTRACKS\"\n ],\n \"makeTrackCuts\": False,\n \"tracktype\": 3\n },\n {\n \"DaughterLocations\": {\n \"[B+ -> (J/psi(1S) -> ^e+ e-) K+]CC\": \"Electron1_ISO\",\n \"[B+ -> (J/psi(1S) -> e+ ^e-) K+]CC\": \"Electron2_ISO\",\n \"[B+ -> (J/psi(1S) -> e+ e-) ^K+]CC\": \"Kplus_ISO\"\n },\n \"IsoTwoBody\": True,\n \"Type\": \"RelInfoBs2MuMuTrackIsolations\",\n \"Variables\": [\n \"BSMUMUTRACKPLUSISO\",\n \"BSMUMUTRACKPLUSISOTWO\",\n \"ISOTWOBODYQPLUS\",\n \"ISOTWOBODYMASSISOPLUS\",\n \"ISOTWOBODYCHI2ISOPLUS\",\n \"ISOTWOBODYISO5PLUS\"\n ],\n \"angle\": 0.27,\n \"doca_iso\": 0.13,\n \"fc\": 0.6,\n \"ips\": 3.0,\n \"makeTrackCuts\": False,\n \"pvdis\": 0.5,\n \"pvdis_h\": 40.0,\n \"svdis\": -0.15,\n \"svdis_h\": 30.0,\n \"tracktype\": 3\n },\n {\n \"Location\": \"VtxIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\"\n },\n {\n \"Location\": \"ConeIsoInfo\",\n \"Type\": \"RelInfoConeVariables\"\n },\n {\n \"Location\": \"VtxIsoInfoBDT\",\n \"Type\": \"RelInfoVertexIsolationBDT\"\n },\n {\n \"Location\": \"ConeIsoInfoBDT\",\n \"Type\": \"RelInfoTrackIsolationBDT\"\n }\n ],\n \"RelatedInfoTools_Tau2MuEtaPrime\": [\n {\n \"Location\": \"VtxIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\"\n },\n {\n \"Location\": \"VtxIsoInfoBDT\",\n \"Type\": \"RelInfoVertexIsolationBDT\"\n }\n ],\n \"RelatedInfoTools_Tau2PhiMu\": [\n {\n \"ConeAngle\": 0.5,\n \"DaughterLocations\": {\n \"[tau+ -> (phi(1020)->K+ K-) ^mu+]CC\": \"coneInfoMu05\",\n \"[tau+ -> (phi(1020)->K+ ^K-) mu+]CC\": \"coneInfoKminus05\",\n \"[tau+ -> (phi(1020)->^K+ K-) mu+]CC\": \"coneInfoKplus05\",\n \"[tau+ -> ^(phi(1020)->K+ K-) mu+]CC\": \"coneInfoPhi05\"\n },\n \"Location\": \"coneInfoTau05\",\n \"Type\": \"RelInfoConeVariables\",\n \"Variables\": [\n \"CONEANGLE\",\n \"CONEMULT\",\n \"CONEPT\",\n \"CONEPTASYM\"\n ]\n },\n {\n \"ConeAngle\": 0.8,\n \"DaughterLocations\": {\n \"[tau+ -> (phi(1020)->K+ K-) ^mu+]CC\": \"coneInfoMu08\",\n \"[tau+ -> (phi(1020)->K+ ^K-) mu+]CC\": \"coneInfoKminus08\",\n \"[tau+ -> (phi(1020)->^K+ K-) mu+]CC\": \"coneInfoKplus08\",\n \"[tau+ -> ^(phi(1020)->K+ K-) mu+]CC\": \"coneInfoPhi08\"\n },\n \"Location\": \"coneInfoTau08\",\n \"Type\": \"RelInfoConeVariables\",\n \"Variables\": [\n \"CONEANGLE\",\n \"CONEMULT\",\n \"CONEPT\",\n \"CONEPTASYM\"\n ]\n },\n {\n \"ConeAngle\": 1.0,\n \"DaughterLocations\": {\n \"[tau+ -> (phi(1020)->K+ K-) ^mu+]CC\": \"coneInfoMu10\",\n \"[tau+ -> (phi(1020)->K+ ^K-) mu+]CC\": \"coneInfoKminus10\",\n \"[tau+ -> (phi(1020)->^K+ K-) mu+]CC\": \"coneInfoKplus10\",\n \"[tau+ -> ^(phi(1020)->K+ K-) mu+]CC\": \"coneInfoPhi10\"\n },\n \"Location\": \"coneInfoTau10\",\n \"Type\": \"RelInfoConeVariables\",\n \"Variables\": [\n \"CONEANGLE\",\n \"CONEMULT\",\n \"CONEPT\",\n \"CONEPTASYM\"\n ]\n },\n {\n \"ConeAngle\": 1.2,\n \"DaughterLocations\": {\n \"[tau+ -> (phi(1020)->K+ K-) ^mu+]CC\": \"coneInfoMu12\",\n \"[tau+ -> (phi(1020)->K+ ^K-) mu+]CC\": \"coneInfoKminus12\",\n \"[tau+ -> (phi(1020)->^K+ K-) mu+]CC\": \"coneInfoKplus12\",\n \"[tau+ -> ^(phi(1020)->K+ K-) mu+]CC\": \"coneInfoPhi12\"\n },\n \"Location\": \"coneInfoTau12\",\n \"Type\": \"RelInfoConeVariables\",\n \"Variables\": [\n \"CONEANGLE\",\n \"CONEMULT\",\n \"CONEPT\",\n \"CONEPTASYM\"\n ]\n },\n {\n \"Location\": \"VtxIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\",\n \"Variables\": [\n \"VTXISONUMVTX\",\n \"VTXISODCHI2ONETRACK\",\n \"VTXISODCHI2MASSONETRACK\",\n \"VTXISODCHI2TWOTRACK\",\n \"VTXISODCHI2MASSTWOTRACK\"\n ]\n },\n {\n \"DaughterLocations\": {\n \"[tau+ -> (phi(1020)->K+ K-) ^mu+]CC\": \"MuonTrackIsoBDTInfo\",\n \"[tau+ -> (phi(1020)->K+ ^K-) mu+]CC\": \"KminusTrackIsoBDTInfo\",\n \"[tau+ -> (phi(1020)->^K+ K-) mu+]CC\": \"KplusTrackIsoBDTInfo\"\n },\n \"Type\": \"RelInfoTrackIsolationBDT\"\n }\n ],\n \"Tau2MuEtaPrimePrescale\": 1,\n \"Tau2MuMuePrescale\": 0,\n \"TauPrescale\": 0,\n \"config_B2eMu\": {\n \"max_ADAMASS\": 1200.0,\n \"max_AMAXDOCA\": 0.3,\n \"max_BPVIPCHI2\": 25,\n \"max_TRCHI2DV\": 3.0,\n \"max_TRGHOSTPROB\": 0.3,\n \"min_BPVDIRA\": 0,\n \"min_BPVVDCHI2\": 225,\n \"min_MIPCHI2DV\": 25.0\n },\n 'config_JPsi2eMu': {\n 'min_MIPCHI2DV': 36.,\n 'max_ADAMASS' : 1000,\n 'max_TRCHI2DV' : 3.,\n 'max_TRGHOSTPROB' : 0.3,\n 'max_AMAXDOCA' : 0.3,\n 'min_BPVDIRA' : 0,\n 'min_BPVVDCHI2': 256,\n 'max_BPVIPCHI2': 25,\n },\n \"config_Tau2MuEtaPrime\": {\n \"config_EtaPrime2pipigamma\": {\n \"etap_cuts\": \"(PT > 500*MeV) & (VFASPF(VCHI2/VDOF) < 6.0)\",\n \"etap_mass_window\": \"(ADAMASS('eta') < 80*MeV) | (ADAMASS('eta_prime') < 80*MeV)\",\n \"gamma_cuts\": \"(PT > 300*MeV) & (CL > 0.1)\",\n \"piminus_cuts\": \"(PROBNNpi > 0.1) & (PT > 250*MeV) & (TRGHOSTPROB < 0.3) & (TRCHI2DOF < 3.0) & (MIPCHI2DV(PRIMARY) > 9.)\",\n \"piplus_cuts\": \"(PROBNNpi > 0.1) & (PT > 250*MeV) & (TRGHOSTPROB < 0.3) & (TRCHI2DOF < 3.0) & (MIPCHI2DV(PRIMARY) > 9.)\"\n },\n \"config_EtaPrime2pipipi\": {\n \"etap_cuts\": \"(PT > 500*MeV) & (VFASPF(VCHI2/VDOF) < 6.0)\",\n \"etap_mass_window\": \"(ADAMASS('eta') < 80*MeV) | (ADAMASS('eta_prime') < 80*MeV)\",\n \"pi0_cuts\": \"(PT > 250*MeV)\",\n \"piminus_cuts\": \"(PROBNNpi > 0.1) & (PT > 250*MeV) & (TRGHOSTPROB < 0.3) & (TRCHI2DOF < 3.0) & (MIPCHI2DV(PRIMARY) > 9.)\",\n \"piplus_cuts\": \"(PROBNNpi > 0.1) & (PT > 250*MeV) & (TRGHOSTPROB < 0.3) & (TRCHI2DOF < 3.0) & (MIPCHI2DV(PRIMARY) > 9.)\"\n },\n \"muplus_cuts\": \"(ISLONG) & (TRCHI2DOF < 3 ) & (MIPCHI2DV(PRIMARY) > 9.) & (PT > 300*MeV) & (TRGHOSTPROB < 0.3)\",\n \"tau_cuts\": \"(BPVIPCHI2()< 100) & (VFASPF(VCHI2/VDOF)<6.) & (BPVLTIME()*c_light > 50.*micrometer) & (BPVLTIME()*c_light < 400.*micrometer) & (PT>500*MeV) & (D2DVVD(2) < 80*micrometer)\",\n \"tau_mass_window\": \"(ADAMASS('tau+')<150*MeV)\"\n }\n },\n \"STREAMS\": [ \"Leptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nLb2L0Gamma = {\n \"BUILDERTYPE\": \"StrippingLb2L0GammaConf\",\n \"CONFIG\": {\n \"HLT1\": [],\n \"HLT2\": [],\n \"L0\": [\n \"Photon\",\n \"Electron\",\n \"Hadron\"\n ],\n \"L0_Conv\": [],\n \"Lambda0DD_MassWindow\": 30.0,\n \"Lambda0LL_IP_Min\": 0.05,\n \"Lambda0LL_MassWindow\": 20.0,\n \"Lambda0_Pt_Min\": 1000.0,\n \"Lambda0_VtxChi2_Max\": 9.0,\n \"Lambdab_IPChi2_Max\": 25.0,\n \"Lambdab_MTDOCAChi2_Max\": 7.0,\n \"Lambdab_MassWindow\": 1100.0,\n \"Lambdab_Pt_Min\": 1000.0,\n \"Lambdab_SumPt_Min\": 5000.0,\n \"Lambdab_VtxChi2_Max\": 9.0,\n \"Lb2L0GammaConvertedPrescale\": 1.0,\n \"Lb2L0GammaPrescale\": 1.0,\n \"PhotonCnv_MM_Max\": 100.0,\n \"PhotonCnv_PT_Min\": 1000.0,\n \"PhotonCnv_VtxChi2_Max\": 9.0,\n \"Photon_CL_Min\": 0.2,\n \"Photon_PT_Min\": 2500.0,\n \"Pion_P_Min\": 2000.0,\n \"Pion_Pt_Min\": 300.0,\n \"Proton_P_Min\": 7000.0,\n \"Proton_Pt_Min\": 800.0,\n \"TrackLL_IPChi2_Min\": 16.0,\n \"Track_Chi2ndf_Max\": 3.0,\n \"Track_GhostProb_Max\": 0.4,\n \"Track_MinChi2ndf_Max\": 2.0\n },\n \"STREAMS\": [ \"Leptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nRnS = {\n \"BUILDERTYPE\": \"RnSConf\",\n \"CONFIG\": {\n \"DiDOCA\": 0.3,\n \"IP\": 0.5,\n \"IPChi2Max\": 1500,\n \"IPChi2Min\": 1.5,\n \"K0s2mmLinePostscale\": 1,\n \"K0s2mmLinePrescale\": 1,\n \"K0s2mmSBCut\": 465,\n \"K0s2mmSBLinePostscale\": 1,\n \"K0s2mmSBLinePrescale\": 0.1,\n \"KSdira\": 0,\n \"KSip\": 0.9,\n \"KSlife\": 1.610411922,\n \"KSsidebmaxMass\": 1000,\n \"KSsidebminMass\": 600,\n \"KSsignalmaxMass\": 600,\n \"KSsignalminMass\": 300,\n \"L0life\": 4.734283679999999,\n \"MaxIpDistRatio\": 0.016666666666666666,\n \"MaxMass\": 450,\n \"MinBPVDira\": 0,\n \"MinVDZ\": 0,\n \"MultibodyChi2dof\": 9,\n \"MultibodyIPChi2\": 25,\n \"NoMuIDLinePostscale\": 1,\n \"NoMuIDLinePrescale\": 0.001,\n \"Rho\": 4,\n \"SVZ\": 650,\n \"SidebandLinePostscale\": 1,\n \"SidebandLinePrescale\": 0.2,\n \"SignalLinePostscale\": 1,\n \"SignalLinePrescale\": 1,\n \"TRACK_TRGHOSTPROB_MAX\": 0.3,\n \"TTHits\": -1,\n \"VertexChi2\": 9,\n \"cosAngle\": 0.999998,\n \"eIpChi2\": 49,\n \"muIpChi2\": 36,\n \"muTrChi2Dof\": 5,\n \"piIpChi2\": 100,\n \"protonIpChi2\": 16\n },\n \"STREAMS\": [ \"Dimuon\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nBu2LLK = {\n \"BUILDERTYPE\": \"Bu2LLKConf\",\n \"CONFIG\": {\n \"BDIRA\": 0.9995,\n \"BFlightCHI2\": 100,\n \"BIPCHI2\": 25,\n \"BMassWindow\": 1500,\n \"BMassWindowTau\": 5000,\n \"BVertexCHI2\": 9,\n \"Bu2eeLine2Prescale\": 1,\n \"Bu2eeLine3Prescale\": 1,\n \"Bu2eeLinePrescale\": 1,\n \"Bu2meLinePrescale\": 1,\n \"Bu2meSSLinePrescale\": 1,\n \"Bu2mmLinePrescale\": 1,\n \"Bu2mtLinePrescale\": 1,\n \"Bu2mtSSLinePrescale\": 1,\n \"DiHadronMass\": 2600,\n \"DiLeptonFDCHI2\": 16,\n \"DiLeptonIPCHI2\": 0,\n \"DiLeptonPT\": 0,\n \"K1_MassWindow_Hi\": 6000,\n \"K1_MassWindow_Lo\": 0,\n \"K1_SumIPChi2Had\": 48.0,\n \"K1_SumPTHad\": 800,\n \"K1_VtxChi2\": 12,\n \"KaonIPCHI2\": 9,\n \"KaonPT\": 400,\n \"KstarPADOCACHI2\": 30,\n \"KstarPMassWindow\": 300,\n \"KstarPVertexCHI2\": 25,\n \"LeptonIPCHI2\": 9,\n \"LeptonPT\": 300,\n \"PIDe\": 0,\n \"RelatedInfoTools\": [\n {\n \"Location\": \"VertexIsoInfo\",\n \"Type\": \"RelInfoVertexIsolation\"\n },\n {\n \"Location\": \"VertexIsoBDTInfo\",\n \"Type\": \"RelInfoVertexIsolationBDT\"\n },\n {\n \"ConeAngle\": 0.5,\n \"DaughterLocations\": {\n \"[Beauty -> StableCharged (X0 -> l+ ^l+)]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l+)]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> l+ ^l-)]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> ^l+ l-)]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ ^X-) (X0 -> l+ l-)]CC\": \"TrackIsoInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l+)]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l-)]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l+)]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l-)]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l+)]CC\": \"TrackIsoInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l-)]CC\": \"TrackIsoInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l+)]CC\": \"TrackIsoInfoH2\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l-)]CC\": \"TrackIsoInfoH2\",\n \"[Beauty -> (X+ -> X+ ^X+ X-) (X0 -> l+ l-)]CC\": \"TrackIsoInfoH2\",\n \"[Beauty -> (X+ -> ^X+ X+ X-) (X0 -> l+ l-)]CC\": \"TrackIsoInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l+)]CC\": \"TrackIsoInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l-)]CC\": \"TrackIsoInfoH1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ X- ^X+))]CC\": \"TrackIsoInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ ^X- X+))]CC\": \"TrackIsoInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> ^X+ X- X+))]CC\": \"TrackIsoInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- X- ^X+))]CC\": \"TrackIsoInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- ^X- X+))]CC\": \"TrackIsoInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> ^X- X- X+))]CC\": \"TrackIsoInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l+ -> X+ X- X+))]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l- -> X- X- X+))]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^l+)]CC\": \"TrackIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l- -> X- X- X+))]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ l+)]CC\": \"TrackIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\": \"TrackIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"TrackIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ l+)]CC\": \"TrackIsoInfoH2\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\": \"TrackIsoInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"TrackIsoInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ l+)]CC\": \"TrackIsoInfoH1\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l+)]CC\": \"TrackIsoInfoH\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\": \"TrackIsoInfoH\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"Type\": \"RelInfoConeVariables\"\n },\n {\n \"ConeSize\": 0.5,\n \"DaughterLocations\": {\n \"[Beauty -> StableCharged (X0 -> l+ ^l+)]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l+)]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> l+ ^l-)]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> ^l+ l-)]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ ^X-) (X0 -> l+ l-)]CC\": \"ConeIsoInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l+)]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l-)]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l+)]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l-)]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l+)]CC\": \"ConeIsoInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l-)]CC\": \"ConeIsoInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l+)]CC\": \"ConeIsoInfoH2\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l-)]CC\": \"ConeIsoInfoH2\",\n \"[Beauty -> (X+ -> X+ ^X+ X-) (X0 -> l+ l-)]CC\": \"ConeIsoInfoH2\",\n \"[Beauty -> (X+ -> ^X+ X+ X-) (X0 -> l+ l-)]CC\": \"ConeIsoInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l+)]CC\": \"ConeIsoInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l-)]CC\": \"ConeIsoInfoH1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ X- ^X+))]CC\": \"ConeIsoInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ ^X- X+))]CC\": \"ConeIsoInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> ^X+ X- X+))]CC\": \"ConeIsoInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- X- ^X+))]CC\": \"ConeIsoInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- ^X- X+))]CC\": \"ConeIsoInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> ^X- X- X+))]CC\": \"ConeIsoInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l+ -> X+ X- X+))]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l- -> X- X- X+))]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^l+)]CC\": \"ConeIsoInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l+ -> X+ X- X+))]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l- -> X- X- X+))]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ l+)]CC\": \"ConeIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\": \"ConeIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"ConeIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"ConeIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ l+)]CC\": \"ConeIsoInfoH2\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\": \"ConeIsoInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"ConeIsoInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"ConeIsoInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ l+)]CC\": \"ConeIsoInfoH1\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l+)]CC\": \"ConeIsoInfoH\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\": \"ConeIsoInfoH\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"Type\": \"RelInfoConeIsolation\"\n },\n {\n \"DaughterLocations\": {\n \"[Beauty -> StableCharged (X0 -> l+ ^l+)]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l+)]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> l+ ^l-)]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> ^l+ l-)]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ ^X-) (X0 -> l+ l-)]CC\": \"TrackIsoBDTInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l+)]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l-)]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l+)]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l-)]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l+)]CC\": \"TrackIsoBDTInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l-)]CC\": \"TrackIsoBDTInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l+)]CC\": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l-)]CC\": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X+ -> X+ ^X+ X-) (X0 -> l+ l-)]CC\": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X+ -> ^X+ X+ X-) (X0 -> l+ l-)]CC\": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l+)]CC\": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l-)]CC\": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ X- ^X+))]CC\": \"TrackIsoBDTInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ ^X- X+))]CC\": \"TrackIsoBDTInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> ^X+ X- X+))]CC\": \"TrackIsoBDTInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- X- ^X+))]CC\": \"TrackIsoBDTInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- ^X- X+))]CC\": \"TrackIsoBDTInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> ^X- X- X+))]CC\": \"TrackIsoBDTInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l+ -> X+ X- X+))]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l- -> X- X- X+))]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^l+)]CC\": \"TrackIsoBDTInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l- -> X- X- X+))]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ l+)]CC\": \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ l+)]CC\": \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ l+)]CC\": \"TrackIsoBDTInfoH1\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l+)]CC\": \"TrackIsoBDTInfoH\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\": \"TrackIsoBDTInfoH\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"Type\": \"RelInfoTrackIsolationBDT\"\n },\n {\n \"DaughterLocations\": {\n \"[Beauty -> StableCharged (X0 -> l+ ^l+)]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l+)]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> l+ ^l-)]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> (X+ -> X+ X+ X-) (X0 -> ^l+ l-)]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X+ -> X+ X+ ^X-) (X0 -> l+ l-)]CC\": \"TrackIsoBs2MMInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l+)]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> l+ ^l-)]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l+)]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ X-)) (X0 -> ^l+ l-)]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l+)]CC\": \"TrackIsoBs2MMInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> X+ ^X-)) (X0 -> l+ l-)]CC\": \"TrackIsoBs2MMInfoH3\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l+)]CC\": \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X+ -> X+ (X0 -> ^X+ X-)) (X0 -> l+ l-)]CC\": \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X+ -> X+ ^X+ X-) (X0 -> l+ l-)]CC\": \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X+ -> ^X+ X+ X-) (X0 -> l+ l-)]CC\": \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l+)]CC\": \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> (X+ -> ^X+ (X0 -> X+ X-)) (X0 -> l+ l-)]CC\": \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ X- ^X+))]CC\": \"TrackIsoBs2MMInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> X+ ^X- X+))]CC\": \"TrackIsoBs2MMInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l+ -> ^X+ X- X+))]CC\": \"TrackIsoBs2MMInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- X- ^X+))]CC\": \"TrackIsoBs2MMInfoL23\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> X- ^X- X+))]CC\": \"TrackIsoBs2MMInfoL22\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ (l- -> ^X- X- X+))]CC\": \"TrackIsoBs2MMInfoL21\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l+ -> X+ X- X+))]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^(l- -> X- X- X+))]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> l+ ^l+)]CC\": \"TrackIsoBs2MMInfoL2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ (l- -> X- X- X+))]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^l+ l+)]CC\": \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\": \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> l+ l+)]CC\": \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\": \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l+ -> X+ X- X+))]CC\": \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ (l- -> X- X- X+))]CC\": \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> l+ l+)]CC\": \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l+)]CC\": \"TrackIsoBs2MMInfoH\",\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\": \"TrackIsoBs2MMInfoH\"\n },\n \"IgnoreUnmatchedDescriptors\": True,\n \"Type\": \"RelInfoBs2MuMuTrackIsolations\"\n }\n ],\n \"TauPT\": 0,\n \"TauVCHI2DOF\": 150,\n \"Trk_Chi2\": 3,\n \"Trk_GhostProb\": 0.4,\n \"UpperMass\": 5500\n },\n \"STREAMS\": [ \"Leptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nB2XLL = {\n \"BUILDERTYPE\": \"B2XLLConf\",\n \"CONFIG\": {\n \"BDIRA\": 0.9995,\n \"BFlightCHI2\": 100,\n \"BIPCHI2\": 25,\n \"BMassWindow\": 1500,\n \"BVertexCHI2\": 9,\n \"DiHadronMass\": 2600,\n \"DiLeptonFDCHI2\": 16,\n \"DiLeptonIPCHI2\": 0,\n \"DiLeptonPT\": 0,\n \"KaonIPCHI2\": 9,\n \"KaonPT\": 400,\n \"LeptonIPCHI2\": 9,\n \"LeptonPT\": 300,\n \"ProbNNe\": 0.05,\n \"ProbNNk\": 0.05,\n \"ProbNNmu\": 0.05,\n \"ProbNNp\": 0.05,\n \"ProbNNpi\": 0.95,\n \"TrChi2DOF\": 4,\n \"TrGhostProb\": 0.4,\n \"UpperMass\": 5500,\n \"eeXLinePrescale\": 1,\n \"eeXSSLinePrescale\": 1,\n \"meXLinePrescale\": 1,\n \"meXSSLinePrescale\": 1,\n \"mmXLinePrescale\": 1,\n \"mmXSSLinePrescale\": 1\n },\n \"STREAMS\": [ \"Leptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nRareStrange = {\n \"BUILDERTYPE\": \"RareStrangeLinesConf\",\n \"CONFIG\": {\n \"DiElectronMaxMass\": 1000,\n \"DiElectronMinIpChi2\": 9,\n \"DiElectronPIDe\": 2,\n \"DiElectronVtxChi2\": 36,\n \"DiMuonMaxDOCA\": 2,\n \"DiMuonMaxMass\": 700,\n \"DiMuonMinIpChi2\": 9,\n \"DiMuonMinPt\": 0,\n \"DiMuonVtxChi2\": 36,\n \"KDauMinIpChi2\": 9.0,\n \"KDauMinIpChi2Down\": 5.0,\n \"KDauMinIpChi2MassMeas\": 8.0,\n \"KDauMinIpChi2MassMeasDown\": 4.0,\n \"KDauTrChi2\": 3.0,\n \"KMassWin\": 100.0,\n \"KMassWinDown\": 100.0,\n \"KMassWinMassMeas\": 50.0,\n \"KMassWinMassMeasDown\": 100.0,\n \"KMaxDOCA\": 3.0,\n \"KMaxDOCADown\": 10.0,\n \"KMaxDOCAMassMeas\": 2.0,\n \"KMaxDOCAMassMeasDown\": 2.0,\n \"KMaxIpChi2\": 25.0,\n \"KMaxIpChi2MassMeas\": 25.0,\n \"KMinDIRA\": 0.98,\n \"KMinDIRADown\": 0.98,\n \"KMinDIRAMassMeas\": 0.9998,\n \"KMinDIRAMassMeasDown\": 0.999,\n \"KMinPT\": 100.0,\n \"KMinPTDown\": 0.0,\n \"KMinPTMassMeas\": 300.0,\n \"KMinPTMassMeasDown\": 250.0,\n \"KMinVDChi2\": 36.0,\n \"KMinVDChi2Down\": 49.0,\n \"KMinVDChi2MassMeas\": 100.0,\n \"KMinVDChi2MassMeasDown\": 64.0,\n \"KPiMuMuDownPrescale\": 1,\n \"KPiMuMuLFVDownPrescale\": 1,\n \"KPiMuMuLFVPrescale\": 1,\n \"KPiMuMuPrescale\": 1,\n \"KPiPiPiDownPrescale\": 0.1,\n \"KPiPiPiMassMeasDownPrescale\": 1,\n \"KPiPiPiMassMeasPrescale\": 1,\n \"KPiPiPiPrescale\": 0.01,\n \"KVDPVMaxDown\": 2500.0,\n \"KVDPVMaxMassMeasDown\": 2200.0,\n \"KVDPVMinDown\": 500.0,\n \"KVDPVMinMassMeasDown\": 900.0,\n \"KVtxChi2\": 25.0,\n \"KVtxChi2Down\": 25.0,\n \"KVtxChi2MassMeas\": 10.0,\n \"KVtxChi2MassMeasDown\": 20.0,\n \"LambdaMassWin\": 500.0,\n \"LambdaMassWinTight\": 50.0,\n \"LambdaMaxDOCA\": 2.0,\n \"LambdaMaxIpChi2\": 36.0,\n \"LambdaMinDIRA\": 0.9,\n \"LambdaMinPt\": 500.0,\n \"LambdaMinTauPs\": 6.0,\n \"LambdaPPiEEPrescale\": 1.0,\n \"LambdaPPiPrescale\": 0.01,\n \"LambdaVtxChi2\": 25.0,\n \"PhiDauMinPT\": 400.0,\n \"PhiKMuPrescale\": 0.01,\n \"PhiMassMax\": 1200,\n \"PhiMassMin\": 800,\n \"PhiMaxDOCA\": 0.1,\n \"PhiMinDIRA\": 0.5,\n \"PhiMinPT\": 700,\n \"PhiProbNNk\": 0.3,\n \"PhiVtxChi2\": 9,\n \"Postscale\": 1,\n \"Sigma3DauTrChi2Down\": 9.0,\n \"Sigma3MassWin\": 500.0,\n \"Sigma3MassWinDown\": 500.0,\n \"Sigma3MaxDOCA\": 2.0,\n \"Sigma3MaxDOCADown\": 2.0,\n \"Sigma3MaxIpChi2\": 36.0,\n \"Sigma3MaxIpChi2Down\": 100.0,\n \"Sigma3MinDIRA\": 0.9,\n \"Sigma3MinDIRADown\": 0.1,\n \"Sigma3MinPt\": 0.0,\n \"Sigma3MinPtDown\": 0.0,\n \"Sigma3MinTauPs\": 3,\n \"Sigma3MinTauPsDown\": 2,\n \"Sigma3VtxChi2\": 36.0,\n \"Sigma3VtxChi2Down\": 100.0,\n \"SigmaDauTrChi2Down\": 9.0,\n \"SigmaDetVtxChi2\": 25,\n \"SigmaMassWin\": 500.0,\n \"SigmaMassWinDown\": 500.0,\n \"SigmaMaxDOCA\": 2.0,\n \"SigmaMaxDOCADown\": 10.0,\n \"SigmaMaxIpChi2\": 36.0,\n \"SigmaMaxIpChi2Down\": 25.0,\n \"SigmaMinDIRA\": 0.9,\n \"SigmaMinDIRADown\": 0.9,\n \"SigmaMinPt\": 500.0,\n \"SigmaMinPtDown\": 0.0,\n \"SigmaMinTauPs\": 6.0,\n \"SigmaMinTauPsDown\": 7.0,\n \"SigmaMuMuMuDownPrescale\": 1,\n \"SigmaMuMuMuPrescale\": 1,\n \"SigmaPEEDetPrescale\": 1,\n \"SigmaPEEDownPrescale\": 0.1,\n \"SigmaPEEMassWinDown\": 100.0,\n \"SigmaPEEPrescale\": 1,\n \"SigmaPEMuPrescale\": 1,\n \"SigmaPMuMuDetPrescale\": 1,\n \"SigmaPMuMuDownPrescale\": 1,\n \"SigmaPMuMuLFVDownPrescale\": 0.1,\n \"SigmaPMuMuLFVPrescale\": 1,\n \"SigmaPMuMuPrescale\": 1,\n \"SigmaPPi0CalPrescale\": 1.0,\n \"SigmaPPi0MassWin\": 150.0,\n \"SigmaPPi0Prescale\": 1,\n \"SigmaVtxChi2\": 36.0,\n \"SigmaVtxChi2Down\": 25.0,\n \"electronMinIpChi2\": 9.0,\n \"electronMinIpChi2Down\": 4.0,\n \"electronPIDe\": 2.0,\n \"muon3MinIpChi2\": 5.0,\n \"muon3MinIpChi2Down\": 5.0,\n \"muonMinIpChi2\": 9.0,\n \"muonMinIpChi2Down\": 9.0,\n \"pMinPt\": 500.0,\n \"pi0MinPt\": 700.0,\n \"pionMinIpChi2\": 9.0,\n \"protonMinIpChi2\": 9.0,\n \"protonProbNNp\": 0.05,\n \"protonProbNNpTight\": 0.5\n },\n \"STREAMS\": [ \"Leptonic\" ],\n \"WGs\": [ \"RD\" ]\n}\n\nB2LLXBDT = {\n 'BUILDERTYPE' : 'B2LLXBDTConf',\n 'CONFIG' : {\n 'DiElectronCuts': \"\"\"\n (HASVERTEX) & (VFASPF(VCHI2)<16) & (MM<5.0*GeV)\n & (INTREE( (ID=='e+') & (PT>200*MeV) & (MIPCHI2DV(PRIMARY)>1.) & (PIDe>-2) & (TRGHOSTPROB<0.5) ))\n & (INTREE( (ID=='e-') & (PT>200*MeV) & (MIPCHI2DV(PRIMARY)>1.) & (PIDe>-2) & (TRGHOSTPROB<0.5) ))\n \"\"\",\n 'DiMuonCuts' : \"\"\"\n (HASVERTEX) & (VFASPF(VCHI2)<16) & (MM<5.0*GeV)\n & (INTREE( (ID=='mu+') & (PT>200*MeV) & (MIPCHI2DV(PRIMARY)>1.) & (TRGHOSTPROB<0.5) ))\n & (INTREE( (ID=='mu-') & (PT>200*MeV) & (MIPCHI2DV(PRIMARY)>1.) & (TRGHOSTPROB<0.5) ))\n \"\"\",\n 'PionCuts' : \"(PROBNNpi> 0.2) & (PT>250*MeV) & (TRGHOSTPROB<0.4)\",\n 'KaonCuts' : \"(PROBNNk > 0.1) & (PT>300*MeV) & (TRGHOSTPROB<0.4)\",\n 'ProtonCuts' : \"(PROBNNp> 0.05) & (PT>300*MeV) & (TRGHOSTPROB<0.4)\",\n\n 'Pion4LPCuts' : \"(PROBNNpi> 0.2) & (PT>100*MeV) & (TRGHOSTPROB<0.4) & (MIPCHI2DV(PRIMARY)>9.)\",\n\n 'KstarCuts' : \"(VFASPF(VCHI2/VDOF)<16) & (ADMASS('K*(892)0')< 300*MeV)\",\n\n 'KsDDCuts' : \"(ADMASS('KS0') < 30.*MeV) & (BPVVDCHI2>25)\",\n 'KsLLComCuts' : \"(ADAMASS('KS0') < 50.*MeV) & (ADOCACHI2CUT(25, ''))\",\n 'KsLLCuts' : \"(ADMASS('KS0') < 30.*MeV) & (BPVVDCHI2>25) & (VFASPF(VCHI2) < 25.)\",\n\n 'PhiCuts' : \"\"\"\n (HASVERTEX) & (VFASPF(VCHI2)<16) & (MM<1.05*GeV) & (MIPCHI2DV(PRIMARY)>2.)\n & (INTREE( (ID=='K+') & (PT>200*MeV) & (TRGHOSTPROB<0.4) ))\n & (INTREE( (ID=='K-') & (PT>200*MeV) & (TRGHOSTPROB<0.4) ))\n \"\"\" ,\n\n 'LambdaDDCuts' : \"(ADMASS('Lambda0') < 30.*MeV) & (BPVVDCHI2>25)\",\n\n 'LambdaLLComCuts': \"(ADAMASS('Lambda0')<50*MeV) & (ADOCACHI2CUT(30, ''))\",\n 'LambdaLLCuts' : \"(ADMASS('Lambda0') < 30.*MeV) & (BPVVDCHI2>25) & (VFASPF(VCHI2) < 25.)\",\n\n 'LambdastarComCuts' : \"(AM < 5.6*GeV)\",\n 'LambdastarCuts': \"(VFASPF(VCHI2) < 25.)\",\n\n 'BComCuts' : \"(in_range(3.7*GeV, AM, 6.8*GeV))\",\n 'BMomCuts' : \"(in_range(4.0*GeV, M, 6.5*GeV)) & (VFASPF(VCHI2/VDOF) < 25.) & (BPVDIRA> 0.999) & (BPVDLS>0) & (BPVIPCHI2()<400)\",\n\n 'LbComCuts' : \"(in_range(3.7*GeV, AM, 7.1*GeV))\",\n 'LbMomCuts' : \"(in_range(4.0*GeV, M, 6.8*GeV)) & (VFASPF(VCHI2/VDOF) < 25.) & (BPVDIRA> 0.999) & (BPVDLS>0) & (BPVIPCHI2()<400)\",\n\n 'Bu2eeKMVACut' : \"-0.05\",\n 'Bu2mumuKMVACut' : \"-0.05\",\n 'Bu2LLKXmlFile' : '$TMVAWEIGHTSROOT/data/Bu2eeK_BDT_v1r0.xml',\n\n 'Bd2eeKstarMVACut' : \"-0.05\",\n 'Bd2mumuKstarMVACut' : \"-0.05\",\n 'Bd2LLKstarXmlFile' : '$TMVAWEIGHTSROOT/data/Bd2eeKstar_BDT_v1r0.xml',\n\n 'Bd2eeKsMVACut' : \"-0.07\",\n 'Bd2mumuKsMVACut' : \"-0.07\",\n 'Bd2LLKsXmlFile' : '$TMVAWEIGHTSROOT/data/Bd2eeKs_BDT_v1r0.xml',\n\n 'Bs2eePhiMVACut' : \"-0.06\",\n 'Bs2mumuPhiMVACut' : \"-0.08\",\n 'Bs2LLPhiXmlFile' : '$TMVAWEIGHTSROOT/data/Bs2eePhi_BDT_v1r0.xml',\n\n 'Lb2eeLambdaMVACut' : \"-0.11\",\n 'Lb2mumuLambdaMVACut': \"-0.15\",\n 'Lb2LLLambdaXmlFile' : '$TMVAWEIGHTSROOT/data/Lb2eeLambda_BDT_v1r0.xml',\n\n 'Lb2eePKMVACut' : \"-0.09\",\n 'Lb2mumuPKMVACut' : \"-0.11\",\n 'Lb2LLPKXmlFile' : '$TMVAWEIGHTSROOT/data/Lb2eePK_BDT_v1r0.xml',\n\n 'RelatedInfoTools' : [\n {'Type' : 'RelInfoVertexIsolation',\n 'Location' : 'VertexIsoInfo'},\n {'Type' : 'RelInfoVertexIsolationBDT',\n 'Location' : 'VertexIsoBDTInfo'},\n {'Type' : 'RelInfoConeVariables',\n 'ConeAngle' : 0.5,\n 'IgnoreUnmatchedDescriptors': True,\n 'DaughterLocations' : {\n # OPPOSITE SIGN\n # 3-body\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\" : \"TrackIsoInfoH\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\" : \"TrackIsoInfoL1\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\" : \"TrackIsoInfoL2\",\n # 4-body\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\" : \"TrackIsoInfoH1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\" : \"TrackIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\" : \"TrackIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\" : \"TrackIsoInfoL2\"\n }\n },\n {'Type' : 'RelInfoConeIsolation',\n 'ConeSize' : 0.5,\n 'IgnoreUnmatchedDescriptors': True,\n 'DaughterLocations' : {\n # OPPOSITE SIGN\n # 3-body\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\" : \"ConeIsoInfoH\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\" : \"ConeIsoInfoL1\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\" : \"ConeIsoInfoL2\",\n # 4-body\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\" : \"ConeIsoInfoH1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\" : \"ConeIsoInfoH2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\" : \"ConeIsoInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\" : \"ConeIsoInfoL2\",\n }\n },\n {'Type' : 'RelInfoTrackIsolationBDT',\n 'IgnoreUnmatchedDescriptors': True,\n 'DaughterLocations' : {\n # OPPOSITE SIGN\n # 3-body\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\" : \"TrackIsoBDTInfoH\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\" : \"TrackIsoBDTInfoL1\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\" : \"TrackIsoBDTInfoL2\",\n # 4-body\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\" : \"TrackIsoBDTInfoH1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\" : \"TrackIsoBDTInfoH2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\" : \"TrackIsoBDTInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\" : \"TrackIsoBDTInfoL2\"\n }\n },\n {'Type' : 'RelInfoBs2MuMuTrackIsolations',\n 'IgnoreUnmatchedDescriptors': True,\n 'DaughterLocations' : {\n # OPPOSITE SIGN\n # 3-body\n \"[Beauty -> ^StableCharged (X0 -> l+ l-)]CC\" : \"TrackIsoBs2MMInfoH\",\n \"[Beauty -> StableCharged (X0 -> ^l+ l-)]CC\" : \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> StableCharged (X0 -> l+ ^l-)]CC\" : \"TrackIsoBs2MMInfoL2\",\n # 4-body\n \"[Beauty -> (X0 -> ^X+ X-) (X0 -> StableCharged StableCharged)]CC\" : \"TrackIsoBs2MMInfoH1\",\n \"[Beauty -> (X0 -> X+ ^X-) (X0 -> StableCharged StableCharged)]CC\" : \"TrackIsoBs2MMInfoH2\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> ^StableCharged StableCharged)]CC\" : \"TrackIsoBs2MMInfoL1\",\n \"[Beauty -> (X0 -> X+ X-) (X0 -> StableCharged ^StableCharged)]CC\" : \"TrackIsoBs2MMInfoL2\"\n },\n }\n ]\n },\n 'STREAMS' : ['Leptonic' ],\n 'WGs' : ['RD']\n }\n\n","sub_path":"Stripping/Phys/StrippingSettings/python/StrippingSettings/Stripping21r1p1/LineConfigDictionaries_RD.py","file_name":"LineConfigDictionaries_RD.py","file_ext":"py","file_size_in_byte":78869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"627390855","text":"from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\napp_name = 'accounts'\nurlpatterns = [\n path('register/', views.register_view, name=\"register\"),\n path('login/', views.login_view, name=\"login\"),\n path('profile/', views.profile, name='profile'),\n path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),\n]\n","sub_path":"vrook_blog/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"141523704","text":"import hashlib\r\n\r\n\r\ndef calc_hash(filename):\r\n m = hashlib.md5()\r\n with open(filename, 'rb') as f:\r\n while True:\r\n chunk = f.read(1024 * 1024)\r\n if len(chunk) == 0:\r\n break\r\n m.update(chunk)\r\n return m.hexdigest()\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"171951279","text":"import arcpy, shutil\nfrom arcpy import env\n\n# Set the workspace environment\n#\n# List all file geodatabases in the current workspace \n# \n#workspaces = arcpy.ListWorkspaces(\"*\", \"\")\n#for workspace in workspaces:\n#name = arcpy.Describe(workspace).name\n#namepart = name.split(\".\")\n#newname = namepart[0]\n# Set local variables\n#\nfeatureclassin = \"Stations\"\nfeatureclassout = \"Stations\"\ninFC = arcpy.env.ncgmp09 + \"\\\\GeologicMap\\\\\" + featureclassin\noutFC = arcpy.env.gems +\"\\\\GeologicMap\\\\\" + featureclassout\nschemaType = \"NO_TEST\"\nsubtype = \"\"\n\n# Set input field variables\n#\ninfield1 = \"Stations_ID\"\ninfield2 = \"FieldID\"\ninfield3 = \"Label\"\ninfield4 = \"PlotAtScale\"\ninfield5 = \"MapX\"\ninfield6 = \"MapY\"\ninfield7 = \"DataSourceID\"\ninfield8 = \"GPSX\"\ninfield9 = \"GPSY\"\ninfield10 = \"PDOP\"\ninfield11 = \"SignificantDimensionMeters\"\ninfield12 = \"TimeDate\"\ninfield13 = \"MapUnit\"\ninfield14 = \"Observer\"\ninfield15 = \"LocationConfidenceMeters\"\n\n# Set output field variables\n#\noutfield1 = \"Stations_ID\"\noutfield2 = \"FieldID\"\noutfield3 = \"Label\"\noutfield4 = \"PlotAtScale\"\noutfield5 = \"MapX\"\noutfield6 = \"MapY\"\noutfield7 = \"DataSourceID\"\noutfield8 = \"GPSX\"\noutfield9 = \"GPSY\"\noutfield10 = \"PDOP\"\noutfield11 = \"SignificantDimensionMeters\"\noutfield12 = \"TimeDate\"\noutfield13 = \"MapUnit\"\noutfield14 = \"Observer\"\noutfield15 = \"LocationConfidenceMeters\"\n\nprint ((\"Adding \" + featureclassin + \" field map to. . .\"))\n# Create a fieldmappings object and two fieldmap objects\n#\ninput1 = arcpy.FieldMap()\ninput2 = arcpy.FieldMap()\ninput3 = arcpy.FieldMap()\ninput4 = arcpy.FieldMap()\ninput5 = arcpy.FieldMap()\ninput6 = arcpy.FieldMap()\ninput7 = arcpy.FieldMap()\ninput8 = arcpy.FieldMap()\ninput9 = arcpy.FieldMap()\ninput10 = arcpy.FieldMap()\ninput11 = arcpy.FieldMap()\ninput12 = arcpy.FieldMap()\ninput13 = arcpy.FieldMap()\ninput14 = arcpy.FieldMap()\ninput15 = arcpy.FieldMap()\n\n\nfieldmappings = arcpy.FieldMappings()\n\n# Add input fields\n# to fieldmap object.\n#\ninput1.addInputField(inFC,infield1)\ninput2.addInputField(inFC,infield2)\ninput3.addInputField(inFC,infield3)\ninput4.addInputField(inFC,infield4) \ninput5.addInputField(inFC,infield5)\ninput6.addInputField(inFC,infield6)\ninput7.addInputField(inFC,infield7)\ninput8.addInputField(inFC,infield8)\ninput9.addInputField(inFC,infield9)\ninput10.addInputField(inFC,infield10) \ninput11.addInputField(inFC,infield11)\ninput12.addInputField(inFC,infield12)\ninput13.addInputField(inFC,infield13)\ninput14.addInputField(inFC,infield14)\ninput15.addInputField(inFC,infield15)\n\n# Set the Name of the Field output from this field map.\n#\noutput1 = input1.outputField\noutput1.name = (outfield1)\ninput1.outputField = output1\n# Set the Name of the Field output from this field map.\n#\noutput2 = input2.outputField\noutput2.name = (outfield2)\ninput2.outputField = output2\n# Set the Name of the Field output from this field map.\n#\noutput3 = input3.outputField\noutput3.name = (outfield3)\ninput3.outputField = output3\n# Set the Name of the Field output from this field map.\n#\noutput4 = input4.outputField\noutput4.name = (outfield4)\ninput4.outputField = output4\n# Set the Name of the Field output from this field map.\n#\noutput5 = input5.outputField\noutput5.name = (outfield5)\ninput5.outputField = output5\n# Set the Name of the Field output from this field map.\n#\noutput6 = input6.outputField\noutput6.name = (outfield6)\ninput6.outputField = output6\n# Set the Name of the Field output from this field map.\n#\noutput7 = input7.outputField\noutput7.name = (outfield7)\ninput7.outputField = output7 \n # Set the Name of the Field output from this field map.\n#\noutput8 = input8.outputField\noutput8.name = (outfield8)\ninput8.outputField = output8 \n # Set the Name of the Field output from this field map.\n#\noutput9 = input9.outputField\noutput9.name = (outfield9)\ninput9.outputField = output9 \n # Set the Name of the Field output from this field map.\n#\noutput10 = input10.outputField\noutput10.name = (outfield10)\ninput10.outputField = output10 \n # Set the Name of the Field output from this field map.\n#\noutput11 = input11.outputField\noutput11.name = (outfield11)\ninput11.outputField = output11 \n # Set the Name of the Field output from this field map.\n#\noutput12 = input12.outputField\noutput12.name = (outfield12)\ninput12.outputField = output12 \n # Set the Name of the Field output from this field map.\n#\noutput13 = input13.outputField\noutput13.name = (outfield13)\ninput13.outputField = output13 \n # Set the Name of the Field output from this field map.\n#\noutput14 = input14.outputField\noutput14.name = (outfield14)\ninput14.outputField = output14 \n # Set the Name of the Field output from this field map.\n#\noutput15 = input15.outputField\noutput15.name = (outfield15)\ninput15.outputField = output15 \n\n# Add the custom fieldmaps into the fieldmappings object.\n#\nfieldmappings.addFieldMap(input1)\nfieldmappings.addFieldMap(input2)\nfieldmappings.addFieldMap(input3)\nfieldmappings.addFieldMap(input4)\nfieldmappings.addFieldMap(input5)\nfieldmappings.addFieldMap(input6)\nfieldmappings.addFieldMap(input7)\nfieldmappings.addFieldMap(input8)\nfieldmappings.addFieldMap(input9)\nfieldmappings.addFieldMap(input10)\nfieldmappings.addFieldMap(input11)\nfieldmappings.addFieldMap(input12)\nfieldmappings.addFieldMap(input13)\nfieldmappings.addFieldMap(input14)\nfieldmappings.addFieldMap(input15)\n\ntry:\n\tprint (\"Appending data. . .\")\n\t# Process: Append the feature classes into the empty feature class\n\tarcpy.Append_management(inFC, outFC, schemaType, fieldmappings, subtype)\n\nexcept:\n\t# If an error occurred while running a tool print the messages\n\tprint ((arcpy.GetMessages()))\n\nprint ((\"Append data to \" + featureclassout + \" \" + \" complete. . .\"))\n\n","sub_path":"ArcMap/Scripts/Transfer_scripts/AppendStationPointsWithFieldMappings.py","file_name":"AppendStationPointsWithFieldMappings.py","file_ext":"py","file_size_in_byte":5624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"9809626","text":"#2 - Variables and expressions\n\n#Variable deklarieren + initialisieren\nf=0\nprint(f)\n\n#Variable redeklarieren\nf=\"abc\"\nprint(f)\n\n#Fehler: Variablen verschiedener Typen können nicht kombiniert\nprint(\"This is a string \" + str(123) )\n\n#Globale vs. lokale Variablen <- wie bei C/C++\ndef someFunktion():\n #sagen, dass f globale Variable ist:\n global f\n \n f=\"def\"\n print(f)\n\nsomeFunktion()\nprint(f)\n\n#man kann deklarierte Variablen im laufendem Programm löschen\ndel f\n#print(f)\n\n#3 - Python functions:\n\n#einfache Funktionsdefinition\ndef func1():\n print(\"I am a function\")\n\n#Funktion mit Param\ndef func2(arg1, arg2):\n print(arg1, \" \", arg2)\n\n#Funktion mit return:\ndef cube(x):\n return x*x*x\n\n#Funktion mit default-Argumenten\ndef power(num, x=1):\n result = 1\n for i in range(x):\n result = result * num\n return result\n\n#Funktion mit variablen Parameterliste:\ndef multi_add(*args):\n result=0\n for x in args:\n result = result + x\n return result\n\n#Aufrufe:\nfunc1()\nprint(func1()) #gibt None aus, da Funktion kein return hat\nprint(func1) #gibt Adresse der Funktion\n\nfunc2(10,20)\nprint(func2(10,20))\nprint(func2)\n\nprint(cube(3))\nprint(cube)\n\nprint ( power(2) )\nprint( power(2,3) )\n#in Python kann man beim Aufruf die Parameter in belibiger Reihenfolge aufrufen:\nprint( power(x=3, num=2) )\n\nprint(multi_add(4,5,10,4))\n\n# 4 - Conditional structuren:\nx, y = 1000, 1000\nif (x < y):\n st = \"x is less then y\"\nelif (x == y):\n st = \"x is the same as y\"\nelse:\n st = \"x is greater then y\"\nprint (st)\n\n# in Python gibt es kein switch-case\n\n#Conditional statement = if-else in einer Zeile\nst=\"x is less then y \" if (x < y) else \"x is greater than or the same as y\"\nprint(st)\n\n#5 - Loops:\nx=0\nwhile (x < 5):\n print(x)\n x = x + 1\n#for fnktioiert etwas anders:\n# range startet bei 5 und endet wenn x<10\nfor x in range(5, 10):\n print(x)\n\n#for als Loop über Collection:\ndays=[\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\" ]\nfor d in days:\n print(d)\n\n# continuer + break\nx=5\nfor x in range (5, 10):\n if (x == 7):\n #break\n continue\n print(x)\n\n#enumerate() benutzen: enumerate() return Index und Werte des Var[Index]\nfor i,d in enumerate(days):\n print(i,d)\n\n#6 - Classes:\n\n#\nclass myClass(): \n # self = referenziert zum Objekt selbst ~ this-> in C++\n def method1(self): \n print(\"myClass method1\")\n \n def method2(self, someString):\n print(\"myClass method2 \" + someString)\n\n#Vererbung\nclass anotherClass(myClass): \n # self = referenziert zum Objekt selbst ~ this-> in C++\n def method1(self): \n #hier die Funktion der Oberklasse aufrufen + braucht als Param self\n myClass.method1(self)\n print(\"anotherClass method1\")\n \n def method2(self, someString):\n print(\"anotherClass method2 \")\n\nc = myClass()\nc.method1()\nc.method2(\"mein String\")\n\nc2=anotherClass()\nc2.method1()\nc2.method2(\"mein String\")","sub_path":"ONLINE-KURSE/Become a Python Developer/3 - Learning Python/code-training/Code der Kapitel/2 - Python_Basics/python_basics-2.py","file_name":"python_basics-2.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"581318715","text":"import boto3\nimport botocore\nfrom boto3.dynamodb.conditions import Key, Attr\nfrom botocore.client import Config\nfrom botocore.exceptions import ClientError\nimport json\n\nimport configparser\n\n###############################\n### Config ###\n###############################\n\nconfig = configparser.ConfigParser()\nconfig.sections()\nconfig.read('config.ini')\n\n###############################\n### Constants ###\n###############################\n\n# Region\nREGION_NAME = config['AWS']['REGION_NAME']\n\n# S3\nS3_INPUTS_BUCKET = config['AWS']['S3_INPUTS_BUCKET']\nS3_RESULTS_BUCKET = config['AWS']['S3_RESULTS_BUCKET']\nS3_ACL = config['AWS']['S3_ACL']\n\n# DynamoDB\nDYNAMODB_ANNOTATIONS_TABLE = config['AWS']['DYNAMODB_ANNOTATIONS_TABLE']\n\n# Glacier\nGLACIER_VAULT = config['AWS']['GLACIER_VAULT']\nGLACIER_ACCOUNT_ID = config['AWS']['GLACIER_ACCOUNT_ID']\n\n# SQS\nSQS_JOB_REQUESTS_QUEUE = config['AWS']['SQS_JOB_REQUESTS_QUEUE']\nSQS_JOB_RESULTS_QUEUE = config['AWS']['SQS_JOB_RESULTS_QUEUE']\nSQS_ARCHIVE_REQUESTS_QUEUE = config['AWS']['SQS_ARCHIVE_REQUESTS_QUEUE']\nSQS_THAW_REQUESTS_QUEUE = config['AWS']['SQS_THAW_REQUESTS_QUEUE']\nSQS_RESTORE_RESULTS_QUEUE = config['AWS']['SQS_RESTORE_RESULTS_QUEUE']\n\n# SNS\nSNS_JOB_REQUESTS_TOPIC = config['AWS']['SNS_JOB_REQUESTS_TOPIC']\nSNS_JOB_RESULTS_TOPIC = config['AWS']['SNS_JOB_RESULTS_TOPIC']\nSNS_ARCHIVE_REQUESTS_TOPIC = config['AWS']['SNS_ARCHIVE_REQUESTS_TOPIC']\nSNS_THAW_REQUESTS_TOPIC = config['AWS']['SNS_THAW_REQUESTS_TOPIC']\nSNS_RESTORE_RESULTS_TOPIC = config['AWS']['SNS_RESTORE_RESULTS_TOPIC']\n\n# Email (SES)\nMAIL_DEFAULT_SENDER = config['AWS']['MAIL_DEFAULT_SENDER']\n\n# Archive\nFREE_USER_DATA_RETENTION = config['ARCHIVE']['FREE_USER_DATA_RETENTION'] # time before free user results are archived (in seconds)\n\n###############################\n### S3 ###\n###############################\n\n# get an s3 connection\ndef get_s3():\n try:\n s3 = boto3.resource('s3')\n except Exception as e:\n print(\"There was an error connecting to S3:\\n\" + str(e))\n return s3\n\n# download file from s3\ndef download_file_from_s3(s3, bucket, key, file_path):\n try:\n s3.Bucket(bucket).download_file(key, file_path)\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"404\":\n print(\"The requested file could not be found in S3 for processing.\")\n else:\n print(\"There was an error downloading the file for processing:\\n\" + str(e))\n\n# upload files to s3\ndef upload_files_to_s3(s3, bucket, prefix, local_folder, local_files):\n for file in local_files:\n # define file path and AWS key\n file_path = local_folder + file\n key = prefix + file\n # upload\n try:\n s3.meta.client.upload_file(file_path, bucket, key)\n except:\n print(\"There was an error uploading the file: \" + str(key))\n\n# put data in S3\ndef put_data_in_S3(s3, bucket, key, data):\n object = s3.Object(bucket, key)\n object.put(Body=data.read())\n print(\"File placed in S3.\")\n\n# delete s3 file\ndef delete_s3_file(s3, bucket, key):\n s3_object = s3.Object(bucket, key)\n s3_object.delete()\n\n###############################\n### DynamoDB ###\n###############################\n\n# get table by name\ndef get_table(table_name):\n try:\n aws_db = boto3.resource('dynamodb', region_name=REGION_NAME)\n table = aws_db.Table(table_name)\n return table\n except Exception as e:\n print(\"There was an error coneecting to the annotations database:\\n\" + str(e))\n\n# get annotations for a user from annotations db\ndef get_annotations(table, user_id):\n try:\n response = table.query(\n IndexName='user_id_index',\n KeyConditionExpression=Key('user_id').eq(user_id)\n )\n annotations = response['Items']\n return annotations\n except Exception as e:\n print(\"There was an error getting the annotations for user from the annotations database:\\n\" + str(e))\n\n# get details from table by job id\ndef get_annotation_details(table, job_id):\n try:\n response = table.get_item(\n Key={ 'job_id': job_id\n }\n )\n annotation_details = response['Item']\n return annotation_details\n except Exception as e:\n print(\"There was an error getting the annotation details from the annotations database:\\n\" + str(e))\n\n# claim PENDING job: returns True if job status can be updated from PENDING to RUNNING\n# https://stackoverflow.com/questions/37053595/how-do-i-conditionally-insert-an-item-into-a-dynamodb-table-using-boto3?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa\n# http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Table.update_item\ndef claim_annotation_job(table, job_id):\n try:\n response = table.update_item(\n Key={'job_id': job_id},\n UpdateExpression=\"set job_status=:job_status\",\n ConditionExpression=Attr('job_status').eq('PENDING'),\n ReturnValues='UPDATED_NEW',\n ExpressionAttributeValues={\n ':job_status' : 'RUNNING'\n }\n )\n return response['Attributes']['job_status'] == 'RUNNING'\n except botocore.exceptions.ClientError as e:\n # Ignore the ConditionalCheckFailedException, bubble up other exceptions.\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\n print(\"There was an error updating the job status in the annotations database.\")\n else:\n print(\"Job not PENDING.\")\n return False\n\n# set field for a completed job in the annotations database\ndef set_completed_job_details(table, job_id, bucket, key_result_file,\n key_log_file, complete_time, status, result_file_location):\n try:\n table.update_item(\n Key={'job_id': job_id},\n UpdateExpression=\"set s3_results_bucket=:results_bucket, \"\n \"s3_key_result_file=:result_file, \"\n \"s3_key_log_file=:log_file, \"\n \"complete_time=:complete_time, \"\n \"job_status=:job_status, \"\n \"result_file_location=:result_file_location\",\n ExpressionAttributeValues={\n ':results_bucket' : bucket,\n ':result_file' : key_result_file,\n ':log_file' : key_log_file,\n ':complete_time' : complete_time,\n ':job_status' : status,\n ':result_file_location': result_file_location\n }\n )\n except:\n print(\"There was an error updating the job database for job id: \" + str(job_id))\n\n# claim archive job\ndef claim_archive_job(table, job_id):\n try:\n response = table.update_item(\n Key={'job_id': job_id},\n UpdateExpression=\"set result_file_location=:result_file_location\",\n ConditionExpression=Attr('result_file_location').eq('S3'),\n ReturnValues='UPDATED_NEW',\n ExpressionAttributeValues={\n ':result_file_location' : 'archiving...'\n }\n )\n return response['Attributes']['result_file_location'] == 'archiving...'\n except botocore.exceptions.ClientError as e:\n # Ignore the ConditionalCheckFailedException, bubble up other exceptions.\n if e.response['Error']['Code'] != 'ConditionalCheckFailedException':\n print(\"There was an error updating the result file location in the annotations database.\")\n else:\n print(\"Unable to claim archive job. It is possible that result file is not located in S3.\")\n return False\n\n# set user role in annotations db given job id\ndef set_user_role(table, job_id, user_role):\n try:\n table.update_item(\n Key={'job_id': job_id},\n UpdateExpression=\"set user_role=:user_role\",\n ExpressionAttributeValues={\n ':user_role': user_role\n }\n )\n except Exception as e:\n print(\"There was an error setting the user role in the annotations database for job id: \" + str(job_id))\n print(str(e))\n\n# update result file location in annotations database\ndef set_result_file_location(table, job_id, result_file_location):\n try:\n table.update_item(\n Key={'job_id': job_id},\n UpdateExpression=\"set result_file_location=:result_file_location\",\n ExpressionAttributeValues={\n ':result_file_location': result_file_location\n }\n )\n print(\"Updated result file location in annotations db for job: \" + str(job_id))\n except Exception as e:\n print(\"There was an error updating the result file location in the annotations database for job id: \" + str(job_id))\n print(str(e))\n\n# update archive id in annotations database\ndef set_archive_id(table, job_id, archive_id):\n try:\n table.update_item(\n Key={'job_id': job_id},\n UpdateExpression=\"set results_file_archive_id=:archive_id\",\n ExpressionAttributeValues={\n ':archive_id': archive_id\n }\n )\n print(\"Updated archive id in annotations db for job: \" + str(job_id))\n except Exception as e:\n print(\"There was an error updating the archive id in the annotations database for job id: \" + str(job_id))\n print(str(e))\n\n###############################\n### SQS ###\n###############################\n\n# get SQS\ndef get_sqs():\n try:\n sqs = boto3.resource('sqs', region_name=REGION_NAME)\n return sqs\n except Exception as e:\n print(\"There was an error connecting to sqs:\\n\" + str(e))\n\n# get queue by name\ndef get_queue(sqs, queue_name):\n try:\n queue = sqs.get_queue_by_name(\n QueueName=queue_name,\n )\n return queue\n except Exception as e:\n print(\"There was an error getting the queue by name:\\n\" + str(e))\n\n###############################\n### SNS ###\n###############################\n\n# get SNS service\ndef get_sns():\n # connect to SNS\n try:\n region_name = 'us-east-1'\n sns = boto3.client('sns', region_name=REGION_NAME)\n return sns\n except Exception as e:\n print(\"There was an error connecting to AWS SNS:\\n\" + str(e))\n\n# publish message to SNS topic\ndef publish_message(sns, topic, message_data):\n # publish data to SNS\n try:\n message = json.dumps(message_data)\n sns_response = sns.publish(\n TopicArn=topic,\n Message=message\n )\n print(\"Message published to SNS topic \" + str(topic))\n except Exception as e:\n print(\"There was an error publishing a message to SNS topic \" + str(topic))\n print(str(e))\n\n###############################\n### SES ###\n###############################\n\n# get SES connection\ndef get_ses():\n try:\n ses = boto3.client('ses', region_name=REGION_NAME)\n return ses\n except Exception as e:\n print(\"There was an error creating a connection to SES:\\n\" + str(e))\n\n# notify user: send an email\ndef notify_user(ses, annotation_details):\n # set the email details\n user_email = [annotation_details['user_email']]\n user_name = annotation_details['user_name']\n job_id = annotation_details['job_id']\n input_file_name = annotation_details['input_file_name']\n sender = MAIL_DEFAULT_SENDER\n subject = 'GAS Annotation Request Complete'\n body = ('Hi ' + user_name + ',\\n\\n' + 'Your requested annotation job is complete.\\n\\n' +\n 'Request ID: ' + job_id +'\\n' +\n 'Input File: ' + input_file_name + '\\n\\n' +\n 'Annotation details can be viewed at:\\n' + 'https://ramonlrodriguez.ucmpcs.org:4433/annotations/' + job_id\n )\n\n # send the email\n try:\n response = ses.send_email(\n Destination = {'ToAddresses': user_email},\n Message={\n 'Body': {'Text': {'Charset': \"UTF-8\", 'Data': body}},\n 'Subject': {'Charset': \"UTF-8\", 'Data': subject},\n },\n Source=sender)\n print(\"Notification sent to \" + user_name + ' (' + user_email[0] + ') for job id ' + job_id)\n return response['ResponseMetadata']['HTTPStatusCode']\n except Exception as e:\n print(\"There was an error sending the email with SES:\\n\" + str(e))\n\n###############################\n### Glacier ###\n###############################\n\n# get Glacier resource\ndef get_glacier_resource():\n try:\n glacier_resource = boto3.resource('glacier', region_name=REGION_NAME)\n return glacier_resource\n except Exception as e:\n print(\"There was an error connecting to Glacier:\\n\" + str(e))\n\n# get vault for a Glacier resource\ndef get_vault(glacier_resource):\n try:\n vault = glacier_resource.Vault(GLACIER_ACCOUNT_ID, GLACIER_VAULT)\n return vault\n except Exception as e:\n print(\"There was an error getting the Glacier vault:\\n\" + str(e))\n\n# archive annotation result file in s3 to glacier vault\ndef archive_result_file(s3, vault, annotation_details):\n # get s3 object\n s3_key_result_file = annotation_details['s3_key_result_file']\n s3_results_bucket = annotation_details['s3_results_bucket']\n s3_object = s3.Object(s3_results_bucket, s3_key_result_file)\n\n # set the annotation job id as the archive description\n archive_description = annotation_details['job_id']\n\n # archive s3 object as it is read\n try:\n archive_object = vault.upload_archive(\n archiveDescription=archive_description,\n body=s3_object.get()['Body'].read()\n )\n print('Archive response: ' + str(archive_object))\n return archive_object.id\n except Exception as e:\n print(\"There was an error moving result file from S3 to Glacier:\\n\" + str(e))\n\n# get Glacier client\ndef get_glacier_client():\n try:\n glacier_client = boto3.client('glacier', region_name=REGION_NAME)\n return glacier_client\n except Exception as e:\n print(\"There was an error connecting to Glacier:\\n\" + str(e))\n\n# request archive restore from Glacier client\ndef request_restore(glacier_client, archive_id, tier):\n try:\n response = glacier_client.initiate_job(\n vaultName=GLACIER_VAULT,\n jobParameters={\n 'Type': 'archive-retrieval',\n 'ArchiveId': archive_id,\n 'SNSTopic': SNS_RESTORE_RESULTS_TOPIC,\n 'Tier': tier\n }\n )\n print('Thaw succesfully requested: \\n' + str(response))\n except botocore.exceptions.ClientError as e:\n # Handle the InsufficientCapacityException, bubble up other exceptions.\n if e.response['Error']['Code'] == 'InsufficientCapacityException':\n # request restore using Standard processing\n print(\"There was an error requesting an expedited thaw:\\n\" + str(e))\n print(\"Trying again with Standard tier initiate job request.\")\n request_restore(glacier_client, archive_id, 'Standard')\n else:\n print(\"There was an error requesting the file to be restored from Glacier:\\n\" + str(e))\n\n# get archive data from Glacier client\ndef get_archive_data(glacier_client, restore_job_id):\n try:\n archive_data = glacier_client.get_job_output(\n vaultName=GLACIER_VAULT,\n jobId=restore_job_id\n )\n return archive_data\n except Exception as e:\n print(\"There was an error getting the archive data from Glacier:\\n\" + str(e))\n","sub_path":"load_testing/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":14590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"335510520","text":"from __future__ import unicode_literals\nfrom six import with_metaclass\n\nimport os\nimport re\nimport sys\nimport codecs\nimport unittest\n\nsys.path.append('.')\n\nfrom fluent.syntax import ast as ftl, parse\n\n\nsigil = r'^# ~'\nre_directive = re.compile(r'{}(.*)[\\n$]'.format(sigil), re.MULTILINE)\n\n\ndef preprocess(source):\n return [\n re.findall(re_directive, source),\n re.sub(re_directive, '', source)\n ]\n\n\ndef get_code_name(code):\n first = code[0]\n if first == 'E':\n return 'ERROR {}'.format(code)\n if first == 'W':\n return 'ERROR {}'.format(code)\n if first == 'H':\n return 'ERROR {}'.format(code)\n raise Exception('Unknown Annotation code')\n\n\ndef serialize_annotation(annot):\n parts = [get_code_name(annot.code)]\n span = annot.span\n\n if (span.start == span.end):\n parts.append('pos {}'.format(span.start))\n else:\n parts.append(\n 'start {}'.format(span.start),\n 'end {}'.format(span.end)\n )\n\n if len(annot.args):\n pretty_args = ' '.join([\n '\"{}\"'.format(arg)\n for arg in annot.args\n ])\n parts.append('args {}'.format(pretty_args))\n\n return ', '.join(parts)\n\n\ndef read_file(path):\n with codecs.open(path, 'r', encoding='utf-8') as file:\n text = file.read()\n return text\n\n\nfixtures = os.path.join(\n os.path.dirname(__file__), 'fixtures_behavior'\n)\n\n\nclass TestBehaviorMeta(type):\n def __new__(mcs, name, bases, attrs):\n\n def gen_test(file_name):\n def test(self):\n ftl_path = os.path.join(fixtures, file_name + '.ftl')\n ftl_file = read_file(ftl_path)\n\n [expected_directives, source] = preprocess(ftl_file)\n expected = '{}\\n'.format('\\n'.join(expected_directives))\n ast = parse(source)\n actual_directives = [\n serialize_annotation(annot)\n for entry in ast.body\n if isinstance(entry, ftl.Junk)\n for annot in entry.annotations\n ]\n actual = '{}\\n'.format('\\n'.join(actual_directives))\n\n self.assertEqual(actual, expected)\n\n return test\n\n for f in os.listdir(fixtures):\n file_name, ext = os.path.splitext(f)\n\n if ext != '.ftl':\n continue\n\n test_name = 'test_{}'.format(file_name)\n attrs[test_name] = gen_test(file_name)\n\n return type.__new__(mcs, name, bases, attrs)\n\n\nclass TestBehavior(with_metaclass(TestBehaviorMeta, unittest.TestCase)):\n maxDiff = None\n","sub_path":"fluent.syntax/tests/syntax/test_behavior.py","file_name":"test_behavior.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"191920584","text":"#-------------------------------------------------------------------------------\n# Introduction to Programming in Python - Sedgewick and Co.\n#\n# Author: Christopher Martinez\n# Date: 7/16/17\n# Description:\n#\n# Continuously compounded interest. Compose a program that calculates and writes\n# the amount of money you would have if you invested it at a given interest rate\n# compounded continuously, taking the number of years t, the principal P, and\n# the annual interest rate r as command-line arguments. The desired is given by\n# the formula Pe^(rt).\n#-------------------------------------------------------------------------------\n\nimport sys\nimport math\nimport stdio\n\nt = int(sys.argv[1])\nP = float(sys.argv[2])\nr = float(sys.argv[3])\n\nresult = P * math.e ** (r * t)\n\nstdio.writeln('')\nstdio.writeln(result)\nstdio.writeln('')\n","sub_path":"chapter01/exercises/exercise-01.02.21.py","file_name":"exercise-01.02.21.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"364521033","text":"import pytest\nfrom .pages.main_page import MainPage\nfrom .pages.game_page import GameBoard\n\n\ndef test_solver_game(browser):\n link = \"https://meduza.io/games/tsvet-nastroeniya-krasnyy-igra-meduzy\"\n main_page = MainPage(browser, link)\n main_page.open_browser()\n main_page.start_bnt_click()\n main_page.close_cookies()\n game_page = GameBoard(browser, browser.current_url)\n game_page.switch_to_game_frame()\n for i in range(1,1000):\n game_page.solver_game()\n","sub_path":"test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"48422945","text":"import glob\nimport os\nfrom PIL import Image\nimport numpy as np\nimport PIL\n\nfolder_path = \"F:/Datasets/BCSS/safron/train\"\nmasks_input_folder = os.path.join(folder_path, \"masks\")\nimages_input_folder = os.path.join(folder_path, \"images\")\n\noutput_dir = \"F:/Datasets/BCSS/safron/train/728\"\nmasks_output_folder = os.path.join(output_dir, \"masks\")\nimages_output_folder = os.path.join(output_dir, \"images\")\n\nif not os.path.exists(masks_output_folder):\n os.makedirs(masks_output_folder)\nif not os.path.exists(images_output_folder):\n os.makedirs(images_output_folder)\n\npatchsize = 728\nstride = 728\nmax_background_threshold = 0\nPIL.Image.MAX_IMAGE_PIXELS = 933120000\n\ndef CropImage(imgname,mbt_index):\n masks_image_path = os.path.join(masks_input_folder,imgname+\".png\")\n images_image_path = os.path.join(images_input_folder, imgname+\".png\")\n image_initial = imgname\n\n mask_im = Image.open(masks_image_path)\n image_im = Image.open(images_image_path)\n\n width, height = mask_im.size\n #mask_im = mask_im.resize(newsize)\n #image_im = image_im.resize(newsize)\n #Default images are 20X, resize them to half of size to make them 10X\n\n x = 0\n y = 0\n right = 0\n bottom = 0\n\n while (bottom < height):\n while (right < width):\n left = x\n top = y\n right = left + patchsize\n bottom = top + patchsize\n if (right > width):\n offset = right - width\n right -= offset\n left -= offset\n if (bottom > height):\n offset = bottom - height\n bottom -= offset\n top -= offset\n\n im_crop_name = image_initial + \"_\" + str(left) + \"_\" + str(top) + \".png\"\n\n im_crop_mask = mask_im.crop((left, top, right, bottom))\n\n im_crop_image = image_im.crop((left, top, right, bottom))\n\n # im_crop_image_np = np.asarray(im_crop_image)\n\n save_flag = True\n # if (np.mean(im_crop_image_np[:,:,2]) >= 230): #blue background\n # if (mbt_index >= max_background_threshold):\n # save_flag = False\n # else:\n # mbt_index = mbt_index + 1\n\n if (save_flag):\n output_mask_path = os.path.join(masks_output_folder, im_crop_name)\n output_image_path = os.path.join(images_output_folder, im_crop_name)\n im_crop_mask.save(output_mask_path)\n im_crop_image.save(output_image_path)\n\n x += stride\n\n x = 0\n right = 0\n y += stride\n\n return mbt_index\n\navgs = []\nmbt_index = 0\nmasks_image_paths = glob.glob(os.path.join(masks_input_folder,\"*.png\"))\nimage_names = []\nfor path in masks_image_paths:\n image_names.append(os.path.split(path)[1].split('.')[0])\nfor imgname in image_names:\n print(imgname)\n mbt_index = CropImage(imgname,mbt_index)\n\navgs = np.array(avgs)\n#print(np.max(avgs))\n#print(np.mean(avgs))\n","sub_path":"BCSS/ImagesCropper.py","file_name":"ImagesCropper.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"483910535","text":"import os\n\nfrom invoke import task\n\nfrom tasks.environment import check_requirements\nfrom tasks.run import webpack_build\n\n\ndef circleci_running_on_desired_container(target_container):\n \"\"\"\n\n CircleCI supports parallel test running, but they do not have a built in method for running tasks in parallel across\n multiple containers. Their parallelism support is built to run against N versions of Python/Node/etc.\n\n We can get around this by reading the environment variables they set, and bailing out of tasks if the task\n is not running on the desired container.\n\n Docs: https://circleci.com/docs/parallel-manual-setup/#env-splitting\n\n \"\"\"\n\n if os.environ.get('CIRCLECI') == 'true':\n container_index = int(os.environ.get('CIRCLE_NODE_INDEX', '0'))\n container_total = int(os.environ.get('CIRCLE_NODE_TOTAL', '-1'))\n\n if container_index != target_container or container_index >= container_total:\n return True\n\n return False\n\n\n@task(check_requirements)\ndef backend(ctx):\n \"\"\"\n\n Here as a convenience method for CI scripting.\n\n \"\"\"\n\n if circleci_running_on_desired_container(0):\n return\n\n ctx.run('./bin/run-backend-tests')\n\n\n@task(check_requirements)\ndef frontend(ctx):\n if circleci_running_on_desired_container(1):\n return\n\n ctx.run('npm test')\n\n\n@task(check_requirements)\ndef integration(ctx):\n \"\"\"\n\n Here as a convenience method for CI scripting.\n\n \"\"\"\n if circleci_running_on_desired_container(2):\n return\n\n ctx.run('./bin/run-integration-tests')\n\n\n@task(post=[backend, frontend, webpack_build, integration], default=True)\ndef run_all(ctx):\n pass\n","sub_path":"tasks/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"49167392","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 21 18:15:05 2018\r\n\r\n@author: ymamo\r\n\"\"\"\r\n\r\nfrom mesa import Model\r\nfrom mesa.time import RandomActivation\r\nfrom mesa.space import MultiGrid\r\nfrom mesa.datacollection import DataCollector\r\nimport decileagent as da\r\nimport world as world\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\r\nclass InequalityModel(Model):\r\n \r\n '''\r\n Model to create human fractal network formation form first principles\r\n \r\n \r\n '''\r\n\r\n\r\n \r\n def __init__(self):\r\n ###################################\r\n # SET INITIAL NUMBERS\r\n ###################################\r\n self.num_agents = 10000\r\n self.wealth_per = np.loadtxt(\"data_abm/init_wealth_percentile.txt\")\r\n self.num_decs = int(self.num_agents/100)\r\n self.decile = self.create_deciles(self.wealth_per)\r\n ###################################\r\n # Create Income and Top Down World\r\n ######################################\r\n self.schedule = RandomActivation(self)\r\n self.rank_list = []\r\n self.world = world.World(self)\r\n self.time = 1966\r\n #####################################\r\n # Create agent and add to schedule\r\n ########################################\r\n for i in range(self.num_agents):\r\n #get correct decile for agent population\r\n pos = i//100\r\n #print (len(self.decile[pos]))\r\n wealth=self.decile[pos][i%self.num_decs]\r\n a = da.DecileAgent(i, self, wealth,i)\r\n self.schedule.add(a)\r\n self.rank_list.append(a)\r\n self.datacollector = DataCollector(agent_reporters = {\"Wealth\" : \"wealth\", \"Rank\":\"rank\"})\r\n \r\n \r\n ##################################################################\r\n # HELPER FUNCTION FOR INIT\r\n ################################################################# \r\n def create_deciles(self, wealth):\r\n \r\n wealth_map = wealth\r\n #account for upper wealth threshold\r\n wealth_map = np.append(wealth_map, 100000000000.0)\r\n deciles = []\r\n income_dics = []\r\n #income = 0\r\n #wealth = -962.66\r\n #wealth_2 = 0\r\n for i in range(100):\r\n array_w = list(np.random.uniform(wealth_map[i],wealth_map[i+1], self.num_decs))\r\n array_w.sort()\r\n deciles.append(array_w)\r\n \r\n #print (len(deciles[0]))\r\n return deciles\r\n \r\n def rerank(self):\r\n #print (self.rank_list[5000].wealth)\r\n self.rank_list.sort(key=lambda x: x.wealth)\r\n for a in self.rank_list:\r\n a.rank = self.rank_list.index(a)\r\n ###########################################################################\r\n # STEP FUNCTION --- WHAT OCCURS EACH YEAR\r\n ###########################################################################\r\n \r\n def step(self):\r\n self.rerank()\r\n self.schedule.step()\r\n self.time += 1\r\n self.datacollector.collect(self)\r\n \r\n\r\n###############################################################################\r\n#\r\n#\r\n# RUN THE MODEL\r\n#\r\n################################################################################\r\n# Create an instance of the model\r\ntest = InequalityModel()\r\n\r\n#Range indicate number of steps\r\nfor i in range(46):\r\n print (test.time)\r\n test.step()\r\n \r\nresults = test.datacollector.get_agent_vars_dataframe()\r\nresults.to_csv(\"results.csv\")\r\n\r\n","sub_path":"data-inequalitymodel.py","file_name":"data-inequalitymodel.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"584069745","text":"from matplotlib import pyplot as plt\nimport re\nimport argparse\nimport numpy as np\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--file\", \"-f\", type=str, required=False, default = \"log\")\nargument = parser.parse_args()\nlog_file_name = str(argument.file)\n\nlog_list = []\nfile = open(str(log_file_name),\"r\")\n\nEVAL = 0\nAVG = 1\nBEST = 2\n\n\nwhile True:\n #find the next run block\n\n line = file.readline()\n if not line:\n #EOF\n print(\"eof\")\n break\n line = re.split(' |\\t|\\n', line)\n if line[0] == \"Run\":\n run_block = []\n #start adding evals to each line\n while(True):\n line = re.split(' |\\t|\\n',file.readline())\n eval_line = []\n #print(line)\n if line[0] == \"\":\n #if it is the end of a run block, quite current loop\n break\n else:\n for i in [EVAL, AVG, BEST]:\n eval_line.append(eval(line[i]))\n run_block.append(eval_line)\n log_list.append(run_block)\n\nlog_arr = np.array(log_list)\navg_all_runs = np.average(log_arr, axis = 0)\n#print(avg_all_runs)\n\n#Get the best fitness of each run on the last generation fot t-test\nt_test_data = log_arr[:,-1,BEST]\nt_test_list = list(t_test_data)\nt_test_file = open(\"t_test_data\",\"w\")\nfor i in t_test_list:\n t_test_file.write(str(i)+\"\\n\")\n\n#EVAL, AVG, BEST\neval_axis = avg_all_runs[:,EVAL]\navg_axis = avg_all_runs[:,AVG]\nbest_axis = avg_all_runs[:,BEST]\nplt.plot(eval_axis, avg_axis, 'g-', label = \"avg_fitness\")\nplt.plot(eval_axis, best_axis, 'r-', label = \"best_fitness\")\nplt.xlabel(\"Number of Evaluations\")\nplt.ylabel(\"Fitness Score\")\nplt.title(\"Fitness vs Number of Evaluations\")\nplt.legend()\nplt.savefig( log_file_name +\"_plot.png\")\nplt.show()\n","sub_path":"graphs logs results for every experiments/formal_exp_2/plot_tool.py","file_name":"plot_tool.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"46067754","text":"# Binary Search\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n # idx in [0, m*n-1], idx = row*m + col, row = idx//n, col = idx%n\n M = len(matrix)\n N = len(matrix[0])\n l, r = 0, M*N-1\n while l < r:\n mid = (l+r)//2\n row = mid//N\n col = mid%N\n if matrix[row][col] >= target:\n r = mid\n else:\n l = mid + 1\n return target == matrix[l//N][l%N]\n\n\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n M = len(matrix)\n N = len(matrix[0])\n # find the row\n l,r = 0, M-1\n # choose [l][-1] to search, target must be equal or smaller:\n while l < r:\n mid = (l+r)//2\n if matrix[mid][-1] >= target:\n r = mid\n else:\n l = mid+1\n row = l\n # determine col\n l, r = 0, N-1\n while l < r:\n mid = (l+r)//2\n if matrix[row][mid] >= target:\n r = mid\n else:\n l = mid + 1\n col = l\n return target == matrix[row][col]\n# Runtime: 32 ms, faster than 75.34% of Python online submissions for Search a 2D Matrix.\n# Memory Usage: 13.9 MB, less than 50.28% of Python online submissions for Search a 2D Matrix.\n\n","sub_path":"74. Search a 2D Matrix.py","file_name":"74. Search a 2D Matrix.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"448980147","text":"import sqlite3 as sql\nimport csv\nimport os, os.path\n\nfileToLoad = 'GLEIF-concatenated-file.csv'\ndatabaseName = '../LegalEntities.db'\n\nif os.path.isfile(databaseName):\n os.remove(databaseName)\n\nwith open(fileToLoad, encoding=\"utf8\") as country_list:\n reader = csv.reader(country_list, delimiter=\";\")\n header_row = next(reader)\n\n # for index, column in enumerate(header_row):\n # print('Column ' + str(index + 1) + ': ' + column)\n # Column 1 = LEI\n # Column 2 = Name\n # Column 191 = Jurisdiction\n\n con = sql.connect('../LegalEntities.db',isolation_level=None)\n cur = con.cursor()\n cur.execute(\"CREATE TABLE LegalEntities (Id varchar(20) NOT NULL PRIMARY KEY, Name varchar(200) NULL, Country varchar(3) NULL)\")\n\n for row in reader:\n to_db = [row[0], row[1], row[43]]\n cur.execute(\"INSERT INTO LegalEntities (Id, Name, Country) VALUES (?, ?, ?);\", to_db)\n\n con.commit()\n","sub_path":"Utilities/parseCsv.py","file_name":"parseCsv.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"476149000","text":"from selenium.webdriver.common.by import By\nfrom behave import given, when, then\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom time import sleep\n\nSEARCH_FIELD = (By.ID, 'searchval')\nSEARCH_BUTTON = (By.CSS_SELECTOR, '.banner-search-btn')\nPRODUCT_LIST = (By.CSS_SELECTOR, '#product_listing .ag-item')\nBUY_BUTTON = (By.ID, 'buyButton')\nVIEW_CART = (By.CSS_SELECTOR, '.btn.btn-primary')\nEMPTY_CART = (By.CSS_SELECTOR, '.emptyCartButton.btn.btn-mini.btn-ui.pull-right')\nEMPTY_CART_CONFIRM = (By.CSS_SELECTOR, '.modal-footer .btn.btn-primary')\n\n@given('Open Webstaurant store page')\ndef open_webpage(context):\n context.driver.get('https://www.webstaurantstore.com')\n\n@when('Look for {querry}')\ndef looking_for_item(context, querry):\n webst_search = context.driver.find_element(*SEARCH_FIELD)\n webst_search.clear()\n webst_search.send_keys(querry)\n context.driver.find_element(*SEARCH_BUTTON).click()\n\n@when('Check all result ensuring {q} its title')\ndef looking_for_something(context, q):\n context.products = context.driver.find_elements(*PRODUCT_LIST)\n for i in range(len(context.products)):\n assert q in context.products[i].text, f'Expected {q}, but didnt find it in item {i}, with text {context.products[i].text}'\n@then('Add last item to the cart')\ndef add_last_item(context):\n context.driver.find_elements(*PRODUCT_LIST)[len(context.products)-1].click()\n context.wait.until(EC.visibility_of_element_located(BUY_BUTTON))\n context.driver.find_element(*BUY_BUTTON).click()\n@then('Empty cart')\ndef empty_cart(context):\n context.wait.until(EC.element_to_be_clickable(VIEW_CART))\n context.driver.find_element(*VIEW_CART).click()\n context.driver.find_element(By.NAME, 'quantityButtonDown').click()\n context.driver.find_element(By.ID, 'update-cart').click()\n\n sleep(2)\n\n\n","sub_path":"Homework_week_6/features/steps/webstaurant.py","file_name":"webstaurant.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"470166185","text":"from behave import given, then\nfrom selenium.webdriver.common.by import By\n\nTOP_LINKS = (By.CSS_SELECTOR, '#zg_header a')\nHEADER = (By.CSS_SELECTOR, '#zg_banner_text_wrapper')\n\n@given ('Open amazon best sellers')\ndef open_page(context):\n context.driver.get('https://www.amazon.com/Best-Sellers/zgbs')\n\n@then ('Click on each top link and verify new page opens')\ndef click_through(context):\n top_links = context.driver.find_elements(*TOP_LINKS)\n\n for x in range(len(top_links)):\n link = context.driver.find_elements(*TOP_LINKS)[x]\n link_text = link.text\n link.click()\n header_text = context.driver.find_element(*HEADER).text\n assert link_text in header_text, f\"Expected {link_text} not in {header_text}\"\n\n\n\n\n","sub_path":"features/steps/hw6.2 click on best sellers links.py","file_name":"hw6.2 click on best sellers links.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"210121916","text":"import time\nimport hashlib\nimport uuid\nimport json\n\nclass Blockchain(object):\n \"\"\"\n Responsible for managing the chain. This is where transactions (tx)\n will be stored\n \"\"\"\n def __init__(self):\n self.chain = []\n self.current_tx = []\n\n # When the Blockchain() is initiated, we need to seed it with a genesis block.\n # A genesis block is a block with no predecessors.\n self.new_block(previous_hash=1, proof=100)\n\n def new_block(self, proof :int, previous_hash=None) -> dict:\n \"\"\"\n This created a new block in the chain.\n\n :param proof: Proof of work\n :param previous_hash: Hash of the previous block. If it's the\n first block (genesis), then it's none.\n \"\"\"\n block = {\n 'index': len(self.chain) + 1,\n 'timestamp': time.time(),\n 'tx': self.current_tx,\n 'proof': proof,\n 'previous_hash': previous_hash or self.hash(self.chain[-1]),\n }\n\n self.current_tx = [] # reset the list of current tx\n self.chain.append(block)\n return block\n\n def new_tx(self, **kwargs) -> int:\n \"\"\"\n Creates a new transaction (tx)\n Kwargs expects to have:\n\n :param kwargs:\n - sender: address (hash) of the sender\n - receiver: address (hash) of a receiver\n - amount: amount the sender is sending to a receiver\n :return: The index of a block that holds this tx\n \"\"\"\n self.current_tx.append(kwargs)\n return self.last_block['index'] + 1 # return the next block to be mined.\n\n @staticmethod\n def hash(block :dict) -> str:\n \"\"\"\n Creates a SHA-256 of a block.\n\n :param block: a block\n :return: the sha256 of block.\n \"\"\"\n block = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block).hexdigest()\n\n def pow(self, last_p :int) -> int:\n \"\"\"\n Proof of work algorithm.\n\n - find a number p such that hash(pp') contains leading 4 zeroes, where p\n is the previous p'\n - p is the previous proof, and p' is the new one\n\n :param: last_p \n :return \n \"\"\"\n\n proof = 0\n while self.validate_proof(last_p, proof) is False:\n proof += 1\n return proof\n\n @property\n def last_block(self):\n return self.chain[-1]\n\n @staticmethod\n def validate_proof(last_p :int, p :int) -> bool:\n \"\"\"\n Validates the proof by asking: does hash(last_p, p) contain 4 leading 0s?\n\n :param: last_p previous proof\n :param p current proof\n :return True if ok, false if not.\n \"\"\"\n\n # Note: if we want to ajust the difficulty of the algorihm, we could simply\n # modify the number of leading 0s.\n guess = f'{last_p}{p}'.encode()\n guess_hash = hashlib.sha256(guess).hexdigest()\n return guess_hash[:4] == \"0000\"\n","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"593345925","text":"''' Documentation.\r\n\r\nМoдуль мoегo автoрства, oтвечающий за \r\nвoспрoизведения анимирoванных спрайтoв в игре.\r\n\r\n'''\r\n\r\nimport pygame\r\nfrom pygame.sprite import Sprite\r\n\r\nclass AnimatedSprite(Sprite):\r\n\t''' Класс для введения анимирoванных картинoк в игру. '''\r\n\tdef __init__(self, screen, images, duration, x, y):\r\n\t\tsuper().__init__()\r\n\t\t# Кooрдинаты вывoда изoбражения на экране.\r\n\t\tself.x = x\r\n\t\tself.y = y\r\n\t\t# Экран, на кoтoрoм будет вoспрoизвoдиться анимация.\r\n\t\tself.screen = screen\r\n\t\t# Набoр кадрoв для анимации в виде списка.\r\n\t\tself.images = images\r\n\t\t# Картинки будут oдинакoвoгo размера, значит, упрoстим пoлучение прямoугoльника.\r\n\t\tself.rect = self.images[0].get_rect()\r\n\t\t# Счетчик кадрoв игры.\r\n\t\tself.count_frame = 1\r\n\t\t# Счетчик кадрoв анимации, устанoвлен на пocледний кадр.\r\n\t\tself.i = (len(self.images)-1)\r\n\t\t# Длительнoсть oднoгo кадра анимации в кадрах игры.\r\n\t\tself.duration = duration\r\n\t\t# Сooтветственнo скoрoсть либo 1, либo 0.5.\r\n\t\tself.frame = self.images[self.i]\r\n\r\n\tdef update_count_frame(self):\r\n\t\t''' Функция oбнoвляет счетчик кадрoв игры '''\r\n\t\tif self.count_frame <= self.duration:\r\n\t\t\tself.count_frame += 1\r\n\t\telse:\r\n\t\t\tself.count_frame = 1\r\n\r\n\tdef update_i(self):\r\n\t\t''' Функция oбнoвляет счетчик в каждoм игрoвoм цикле = каждый кадр. '''\r\n\t\tif (self.count_frame - self.duration) == 0:\r\n\t\t\t# Нужен непустoй списoк\r\n\t\t\tif self.i < (len(self.images)-1):\r\n\t\t\t\t# Если i не дoшел дo пoследнегo кадра, тo oбнoвляем счетчик.\r\n\t\t\t\tself.i += 1\r\n\t\t\telse:\r\n\t\t\t\t# Если i дoшел дo пoследнегo кадра, oставляем егo на нем.\r\n\t\t\t\tself.i = (len(self.images)-1)\r\n\t\t'''\r\n\t\telse:\r\n\t\t\t# Когда i дошел до последнего кадра, возвращаем анимацию в начало цикла.\r\n\t\t\tself.i = 0\r\n\t\t'''\r\n\t\r\n\tdef blitme(self):\r\n\t\t''' Функция oтрисoвывает текущий кадр '''\r\n\t\tself.screen.blit(self.frame, self.rect)\r\n\r\n\r\nclass FireFX(AnimatedSprite):\r\n\t''' Пoдкласс oбъектoв oгня при выстреле. '''\r\n\tdef update_frame(self, ship):\r\n\t\t''' Функция oбнoвляет текущий кадр в сooтветствии с счетчикoм. '''\r\n\t\tself.frame = self.images[self.i]\r\n\t\t# Изменяем пoлoжение прямoугoльника вывoда кадра.\r\n\t\tself.x = self.x + ship.delta_x\r\n\t\tself.rect.centerx = self.x\r\n\t\tself.rect.bottom = self.y\t\r\n\r\n\r\n\r\nclass ExplosionFX(AnimatedSprite):\r\n\t'''\t Пoдкласс oбъектoв взрывoв при пoпадании. '''\r\n\tdef __init__(self, *args):\r\n\t\tsuper().__init__(*args)\r\n\t\tself.lifetime = len(self.images)*self.duration\r\n\t\tself.i = 0\r\n\t\r\n\tdef update_lifetime(self):\r\n\t\tif self.lifetime > 0:\r\n\t\t\tself.lifetime -= 1\r\n\t\telse:\r\n\t\t\tself.lifetime = 0\r\n\r\n\tdef update_frame(self):\r\n\t\t\t''' Функция oбнoвляет текущий кадр в сooтветствии с счетчикoм. '''\r\n\t\t\tself.frame = self.images[self.i]\r\n\t\t\t# Изменяем пoлoжение прямoугoльника вывoда кадра.\r\n\t\t\tself.rect.centerx = self.x\r\n\t\t\tself.rect.centery = self.y\r\n\r\nif __name__ == '__main__':\r\n\tpass","sub_path":"GAME/animated_sprites.py","file_name":"animated_sprites.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"584027392","text":"import pygame as pg\nimport pickle\nimport random\nimport os\nimport math\nimport hero\nimport npc\nimport enemy\nimport packages\nimport item\n\npg.init()\nclock = pg.time.Clock()\n\n# Display Size\nHEIGHT = 800\nWIDTH = 800\n# Frames per second\nFPS = 30\n# Global item sizes\nITEM_SIZE = round(16*2.5)\n# Save all map collision into array\nrects = packages.rects()\n# Create array of Traps and extract the Traps from package file\ntraps = packages.trap_list()\n# Each rect is made up of a point, two lengths and a key value\nkeyarea = [4611, 4, 2584, 2294, 943876]\n# Global cooldown variable\ncooldown = 0\n# Global talking animation variable\ntalking_animation = 0\ntext_position = 600\ntext_temp = 0\ntext_next_pos = 3\ninfo_text_show = 0\n# Load game icon\ngameIcon = pg.image.load('assets/gui/icon.png')\n# Load map image\nbackground = pg.transform.scale(\n pg.image.load('assets/map/map.png'), (7200, 7200))\n# Load text background image\ntext = pg.transform.scale(pg.image.load('assets/gui/text.png'), (700, 400))\n# Initialise the used fonts\nwon_font = pg.font.Font('assets/font/EnglishTowne.ttf', 65)\nmenu_font = pg.font.Font('assets/font/anirb___.ttf', 20)\ntalking_font = pg.font.Font('assets/font/BLKCHCRY.TTF', 30)\ndmg_font = pg.font.Font('assets/font/BLKCHCRY.TTF', 35)\ninfo_font = pg.font.Font('assets/font/BLKCHCRY.TTF', 25)\n# Load button images\nbutton1 = pg.transform.scale(pg.image.load(\n 'assets/gui/button_not_pressed.png'), (round(800*0.5), round(163*0.5)))\nbutton2 = pg.transform.scale(pg.image.load(\n 'assets/gui/button_pressed.png'), (round(800*0.5), round(163*0.5)))\n# Load the key as an item\nkey = item.Item(pg.transform.scale(pg.image.load(\n 'assets/player/key.png'), (ITEM_SIZE, ITEM_SIZE)), 'assets/player/key.png', 1, \"Final Key\", 943876, None, None, None, 0)\n\n\ndef draw(screen, player, npcs, enemys, loot):\n # print(player.inventory)\n global talking_animation, text_position, text_temp, info_text_show\n # Get coordinates on what the player is currently looking on\n view_cords = [round(player.stats[\"x\"]), round(\n player.stats[\"y\"]), HEIGHT, WIDTH]\n # Set background to black\n screen.fill((0, 0, 0))\n # Draws the whole map on screen\n screen.blit(\n background, (-round(player.stats[\"x\"]), -round(player.stats[\"y\"])))\n '''\n # Draws all traps on screen\n for trap in traps:\n pg.draw.rect(screen, (255, 0, 0),\n (trap[0]-view_cords[0], trap[1]-view_cords[1], trap[2], trap[3]))\n '''\n '''\n # Draw collision rects on screen\n for rect in rects:\n # Only draw rects if it is in view of player\n if packages.collision(rect, view_cords):\n pg.draw.rect(screen, (255, 255, 255),\n (rect[0]-view_cords[0], rect[1]-view_cords[1], rect[2], rect[3]))\n '''\n # Draw enemy's on screen\n for enemy in enemys:\n enemy.draw(screen, view_cords)\n # Draw loot on screen\n for loot_ in loot:\n # Only draw loot if it is in view of player\n if packages.collision(loot_.hitbox, view_cords):\n screen.blit(loot_.img, (round(loot_.hitbox[0]-view_cords[0]),\n round(loot_.hitbox[1]-view_cords[1])))\n # Display the dmg done by the player on screen\n for dmg in player.damage:\n # Draw it red if it was a crit\n # Else yellow\n if dmg[3]:\n dmg_text = dmg_font.render(str(int(dmg[2])), 1, (255, 0, 0))\n else:\n dmg_text = dmg_font.render(str(int(dmg[2])), 1, (255, 255, 0))\n # Draw the damage text on screen\n screen.blit(dmg_text, (dmg[0]-view_cords[0], dmg[1]-view_cords[1]))\n # Subtract 1 from show time and delete it if show time is zero\n dmg[4] -= 1\n if dmg[4] <= 0:\n player.damage.remove(dmg)\n # Moves the current writing position forward by two steps to create a writing illusion\n if player.stats[\"talking\"]:\n talking_animation += 2\n else:\n talking_animation = 0\n # show info stats from the item the player has currently selected\n if player.inventory[player.inventory_pos] is not None and info_text_show > 0:\n if player.inventory[player.inventory_pos].heal is not None:\n info_text = info_font.render(\"Heilung: \"+str(\n player.inventory[player.inventory_pos].heal), 1, (255, 255, 255))\n screen.blit(info_text, (120+(56*player.inventory_pos), 700))\n elif player.inventory[player.inventory_pos].dmg != 1:\n info_text = info_font.render(\"Schaden: \"+str(\n player.inventory[player.inventory_pos].dmg), 1, (255, 255, 255))\n screen.blit(info_text, (120+(56*player.inventory_pos), 700))\n elif player.inventory[player.inventory_pos].defence != 0:\n info_text = info_font.render(\"Verteidigung: \"+str(\n player.inventory[player.inventory_pos].defence), 1, (255, 255, 255))\n screen.blit(info_text, (115+(56*player.inventory_pos), 700))\n info_text_show -= 1\n # Draw npcs on screen\n for npc in npcs:\n npc.draw(screen, view_cords)\n if npc.stats[\"talking\"]:\n if text_temp < len(npc.text):\n if text_temp != text_next_pos:\n screen.blit(text, (50, 550))\n if npc.text_pos >= 1:\n talking_text = talking_font.render(\n npc.text[npc.text_pos+text_temp-1], 1, (0, 0, 0))\n screen.blit(talking_text, (100, text_position-50))\n if npc.text_pos >= 2:\n talking_text = talking_font.render(\n npc.text[npc.text_pos+text_temp-2], 1, (0, 0, 0))\n screen.blit(talking_text, (100, text_position-100))\n\n talking_text = talking_font.render(\n npc.text[npc.text_pos+text_temp][:round(talking_animation)], 1, (0, 0, 0))\n screen.blit(talking_text, (100, text_position))\n if talking_animation >= len(npc.text[npc.text_pos]):\n talking_animation = 0\n npc.text_pos += 1\n text_position += 50\n if npc.text_pos >= 3:\n npc.text_pos = 0\n text_temp += 3\n text_position -= 50\n else:\n player.stats[\"waiting\"] = True\n screen.blit(text, (50, 550))\n talking_text = talking_font.render(\n npc.text[text_temp-3], 1, (0, 0, 0))\n screen.blit(talking_text, (100, text_position-100))\n talking_text = talking_font.render(\n npc.text[text_temp-2], 1, (0, 0, 0))\n screen.blit(talking_text, (100, text_position-50))\n talking_text = talking_font.render(\n npc.text[text_temp-1], 1, (0, 0, 0))\n screen.blit(talking_text, (100, text_position))\n break\n # Draw player\n player.draw(screen, dmg_font)\n pg.display.update()\n\n\ndef save_game(player, npcs, enemys, loot):\n # Create target Directory if don't exist\n if not os.path.exists('saves'):\n os.mkdir('saves')\n if not os.path.exists('saves/'+player.stats[\"name\"]):\n os.mkdir('saves/'+player.stats[\"name\"])\n # Saves all infos from the player, npcs, enemy's and the current loot into a file\n pickle.dump(player.stats, open(\n 'saves/'+player.stats[\"name\"]+'/player_stats.p', 'wb'))\n pickle.dump(player.hitbox, open(\n 'saves/'+player.stats[\"name\"]+'/player_hitbox.p', 'wb'))\n pickle.dump(player.inventory, open(\n 'saves/'+player.stats[\"name\"]+'/player_inventory.p', 'wb'))\n pickle.dump(player.player_animation, open(\n 'saves/'+player.stats[\"name\"]+'/player_animation.p', 'wb'))\n npcs_stats = []\n npcs_hitbox = []\n npcs_animation = []\n for npc in npcs:\n npcs_stats.append(npc.stats)\n npcs_hitbox.append(npc.hitbox)\n npcs_animation.append(npc.animation)\n pickle.dump(npcs_stats, open(\n 'saves/'+player.stats[\"name\"]+'/npcs_stats.p', 'wb'))\n pickle.dump(npcs_hitbox, open(\n 'saves/'+player.stats[\"name\"]+'/npcs_hitbox.p', 'wb'))\n pickle.dump(npcs_animation, open(\n 'saves/'+player.stats[\"name\"]+'/npcs_animation.p', 'wb'))\n enemys_stats = []\n enemys_hitbox = []\n enemys_animation = []\n for enemy in enemys:\n enemys_stats.append(enemy.stats)\n enemys_hitbox.append(enemy.hitbox)\n enemys_animation.append(enemy.animation)\n pickle.dump(enemys_stats, open(\n 'saves/'+player.stats[\"name\"]+'/enemys_stats.p', 'wb'))\n pickle.dump(enemys_hitbox, open(\n 'saves/'+player.stats[\"name\"]+'/enemys_hitbox.p', 'wb'))\n pickle.dump(enemys_animation, open(\n 'saves/'+player.stats[\"name\"]+'/enemys_animation.p', 'wb'))\n temp = []\n for item in loot:\n temp.append([item.id, item.dmg, item.name, item.key,\n item.hitbox[0], item.hitbox[1], item.heal, item.defence])\n pickle.dump(temp, open(\n 'saves/'+player.stats[\"name\"]+'/loot.p', 'wb'))\n\n\ndef load_game(player, npcs, enemys, loot, dirname):\n # NOT FINISHED\n if os.path.exists('saves/'+dirname):\n infile = open('saves/'+dirname+'player_stats.p', 'rb')\n player.stats = pickle.load(infile)\n infile.close()\n infile = open('saves/'+dirname+'player_inventory.p', 'rb')\n player.inventory = pickle.load(infile)\n infile.close()\n infile = open('saves/'+dirname+'player_hitbox.p', 'rb')\n player.hitbox = pickle.load(infile)\n infile.close()\n infile = open('saves/'+dirname+'player_animation.p', 'rb')\n player.player_animation = pickle.load(infile)\n infile.close()\n '''\n npcs_stats = pickle.load('saves/'+dirname+'npcs_stats.p', 'wb')\n npcs_hitbox = pickle.load('saves/'+dirname+'npcs_hitbox.p', 'wb')\n npcs_animation = pickle.load('saves/'+dirname+'npcs_aniamtion.p', 'wb')\n enemys_stats = pickle.load('saves/'+dirname+'enemys_stats.p', 'wb')\n enemys_hitbox = pickle.load('saves/'+dirname+'enemys_hitbox.p', 'wb')\n enemys_animation = pickle.load(\n 'saves/'+dirname+'enemys_aniamtion.p', 'wb')\n loot_pickle = pickle.load('saves/'+dirname+'loot.p', 'wb')'''\n else:\n print(\"Error: Path doesn´t exist\")\n\n\ndef controls(player, npcs, enemys, loot):\n # Tell funktion that it should use global variable and not create a new one\n global cooldown, text_next_pos, talking_animation, text_position, info_text_show, key\n if cooldown != 0:\n cooldown -= 1\n # Get all buttons that where pressed\n mouse = pg.mouse.get_pressed()\n keys = pg.key.get_pressed()\n # Create a copy of all collision rects\n rects_temp = packages.rects()\n # If the player doesn´t posses the key he can´t walk into the key-area\n for item in player.inventory:\n if item != None and item.key == keyarea[4]:\n break\n else:\n rects_temp.append(keyarea[:4])\n if keys[pg.K_d]:\n # Move player right\n cooldown = 1\n player.move(1, rects_temp)\n if keys[pg.K_a]:\n # Move player left\n cooldown = 1\n player.move(2, rects_temp)\n if keys[pg.K_w]:\n # Move player up\n cooldown = 1\n player.move(3, rects_temp)\n if keys[pg.K_s]:\n # Move player down\n cooldown = 1\n player.move(4, rects_temp)\n # No buttons where pressed player should go into idle\n if cooldown == 0:\n player.move(0, rects_temp)\n if mouse[0] and cooldown == 0:\n # Cooldown so spamming the mouse button isn´t possible\n cooldown = 20\n # Get the coordinates of mouse\n mouse_pos = pg.mouse.get_pos()\n '''\n # Print current mouse position\n print(\"[\"+str(round(mouse_pos[0]+player.stats[\"x\"])) +\n \", \"+str(round(mouse_pos[1]+player.stats[\"y\"]))+\"]\")\n '''\n # Test whether player clicked on loot and if it is in range and if he has enough space in his inventory\n for loot_ in loot:\n if packages.collision(loot_.hitbox, [mouse_pos[0]+player.stats[\"x\"]-1, mouse_pos[1]+player.stats[\"y\"]-1, 3, 3]):\n if math.sqrt((player.hitbox[0]+player.hitbox[2]/2-mouse_pos[0]) ** 2+(player.hitbox[1]+player.hitbox[3]/2-mouse_pos[1])**2) < 200:\n if player.pickup(loot_):\n loot.remove(loot_)\n break\n # Test whether player clicked on npc and if he is in range and start talking to him\n for npc in npcs:\n if packages.collision(npc.hitbox, [mouse_pos[0]+player.stats[\"x\"]-1, mouse_pos[1]+player.stats[\"y\"]-1, 3, 3]):\n if math.sqrt((player.hitbox[0]+player.hitbox[2]/2-mouse_pos[0]) ** 2+(player.hitbox[1]+player.hitbox[3]/2-mouse_pos[1])**2) < 200:\n npc.talk()\n break\n # Test whether player clicked on enemy and if he is in range and attack the enemy\n for enemy in enemys:\n if packages.collision(enemy.hitbox, [mouse_pos[0]+player.stats[\"x\"]-1, mouse_pos[1]+player.stats[\"y\"]-1, 3, 3]):\n if math.sqrt((player.hitbox[0]+player.hitbox[2]/2-mouse_pos[0]) ** 2+(player.hitbox[1]+player.hitbox[3]/2-mouse_pos[1])**2) < 200:\n # Get players attack dmg and subtract it from enemy\n dmg = player.attack()\n dmg[0] -= enemy.defence\n if dmg[0] < 0:\n dmg[0] = 0\n player.damage.append(\n [mouse_pos[0]+player.stats[\"x\"], mouse_pos[1]+player.stats[\"y\"], dmg[0], dmg[1], 20])\n alive = enemy.hit(dmg[0], player.stats[\"level\"])\n # If the enemy is dead make him drop some loot, and add experience to player and remove enemy from array\n if not alive:\n loot.append(packages.random_item(player.stats[\"level\"], round(\n enemy.hitbox[0]), round(enemy.hitbox[1])))\n player.stats[\"xp\"] += enemy.stats[\"dead_xp\"]\n if len(enemys) == 2:\n key.hitbox[0] = enemy.hitbox[0]\n key.hitbox[1] = enemy.hitbox[1]\n loot.append(key)\n enemys.remove(enemy)\n break\n if not player.stats[\"talking\"]:\n # If the player isn´t talking he can use items and heal him self with them\n # It also checks that the player can´t have more then 100 hp\n if keys[pg.K_e]:\n if player.inventory[player.inventory_pos] is not None and player.inventory[player.inventory_pos].heal != 0 and player.stats[\"hp\"] < 100:\n player.stats[\"hp\"] += player.inventory[player.inventory_pos].heal\n if player.stats[\"hp\"] > 100:\n player.stats[\"hp\"] = 100\n player.inventory[player.inventory_pos] = None\n # Drop the item which is currently selected\n if keys[pg.K_q]:\n item = player.drop(player.inventory_pos)\n if item is not None:\n loot.append(item)\n # Change the currently selected spot in the inventory\n # Also activates a small timer for how long the Item info is being displayed\n if keys[pg.K_1]:\n player.inventory_pos = 0\n info_text_show = 30\n elif keys[pg.K_2]:\n player.inventory_pos = 1\n info_text_show = 30\n elif keys[pg.K_3]:\n player.inventory_pos = 2\n info_text_show = 30\n elif keys[pg.K_4]:\n player.inventory_pos = 3\n info_text_show = 30\n elif keys[pg.K_5]:\n player.inventory_pos = 4\n info_text_show = 30\n elif keys[pg.K_6]:\n player.inventory_pos = 5\n info_text_show = 30\n elif keys[pg.K_7]:\n player.inventory_pos = 6\n info_text_show = 30\n elif keys[pg.K_8]:\n player.inventory_pos = 7\n info_text_show = 30\n elif keys[pg.K_9]:\n player.inventory_pos = 8\n info_text_show = 30\n else:\n # Allows the player so get to the next 3 lines of text only if he´s at the end of the current 3 lines of text\n if keys[pg.K_SPACE] and cooldown == 0 and player.stats[\"waiting\"]:\n player.stats[\"waiting\"] = False\n text_next_pos += 3\n talking_animation = 0\n text_position = 600\n cooldown = 10\n return loot\n\n\ndef ingame_menu(screen, player, npcs, enemys, loot, cd):\n run = True\n closed = False\n pg.time.delay(100)\n buttons = [\n [200, 330, 400, 40, False, \"Zurück zum Spiel\", 270, 0],\n [200, 400, 400, 40, False, \"Spiel speichern\", 290, 0],\n [200, 470, 400, 40, False, \"Zum Hauptmenü\", 280, 0],\n [200, 540, 400, 40, False, \"Spiel verlassen\", 290, 0],\n ]\n while run and not closed:\n clock.tick(FPS)\n for event in pg.event.get():\n if event.type == pg.QUIT:\n run = False\n pg.quit()\n\n mouse_pos = pg.mouse.get_pos()\n mouse = pg.mouse.get_pressed()\n keys = pg.key.get_pressed()\n\n if mouse[0] and cd <= 0:\n cd = 15\n for i, button in enumerate(buttons):\n if packages.collision(button[:4], [mouse_pos[0], mouse_pos[1], 1, 1]):\n button[4] = True\n button[7] = 10\n if i == 0:\n closed = True\n elif i == 1:\n save_game(player, npcs, enemys, loot)\n elif i == 2:\n packages.start_screen(\n screen, run, clock, FPS, HEIGHT, WIDTH)\n draw(screen, player, npcs, enemys, loot)\n elif i == 3:\n run = False\n pg.quit()\n\n if cd > 0:\n cd -= 1\n\n for button in buttons:\n if packages.collision(button[:4], [mouse_pos[0], mouse_pos[1], 1, 1]) and not button[4]:\n screen.blit(button1, (button[0], button[1]))\n menu_text = menu_font.render(button[5], 1, (61, 61, 61))\n screen.blit(menu_text, (button[6], button[1]))\n else:\n if not button[4]:\n screen.blit(button1, (button[0], button[1]))\n menu_text = menu_font.render(button[5], 1, (0, 0, 0))\n screen.blit(menu_text, (button[6], button[1]))\n else:\n screen.blit(button2, (button[0], button[1]))\n menu_text = menu_font.render(button[5], 1, (255, 255, 255))\n screen.blit(menu_text, (button[6], button[1]))\n button[7] -= 1\n if button[7] <= 0:\n button[4] = False\n\n pg.display.update()\n\n if keys[pg.K_ESCAPE] and cd == 0:\n closed = True\n return run\n\n\ndef main():\n global cooldown, text_next_pos, talking_animation, text_position, text_temp\n # Set screen as display name, Set taskname\n screen = pg.display.set_mode((WIDTH, HEIGHT))\n pg.display.set_caption(\"Legends of Lumania\")\n pg.display.set_icon(gameIcon)\n # Set run loop boolean\n run = True\n # Call program start screen\n input_values = packages.start_screen(screen, run, clock, FPS, HEIGHT, WIDTH)\n # Test whether windows already closed\n run = input_values[0]\n # Create Player object\n player = hero.Player(\n HEIGHT, WIDTH, input_values[1], input_values[2], input_values[3])\n # Create array of npcs and extract the npcs from package file\n npcs = []\n tmp = packages.npc_list()\n for i in tmp:\n npcs.append(npc.NPC(i[0], i[1], i[2], i[3], i[4]))\n # Create array of enemy's and extract the enemy's from package file\n enemys = []\n tmp = packages.enemy_list()\n for i in tmp:\n enemys.append(enemy.Enemy(i[0], i[1], i[2]))\n enemy_hit_cd = 0\n # Create array of loot and extract the loot from package file\n loot = packages.loot_list()\n # How often trap can make the player dmg\n trap_cd = 0\n finished = False\n # Game Loop\n while run and not finished:\n # Funktion that automates loop for set fps\n clock.tick(FPS)\n # Test if windows closed\n for event in pg.event.get():\n if event.type == pg.QUIT:\n run = False\n pg.quit()\n # Get coordinates on what the player is currently looking on\n view_cords = [player.stats[\"x\"], player.stats[\"y\"], HEIGHT, WIDTH]\n # Loop threw enemy array and test if player is hit; move enemy's\n for _enemy in enemys:\n _enemy.move(player.hitbox, view_cords, rects)\n if enemy_hit_cd == 0:\n if packages.collision([player.hitbox[0]+view_cords[0], player.hitbox[1]+view_cords[1], player.hitbox[2], player.hitbox[3]], _enemy.hitbox):\n enemy_hit_cd = 45\n dmg = _enemy.attack(player.stats[\"level\"])\n player.hit(dmg)\n # Cooldown so enemy cant hit player to often\n if enemy_hit_cd > 0:\n enemy_hit_cd -= 1\n if trap_cd > 0:\n trap_cd -= 1\n # Move npcs\n for _npc in npcs:\n _npc.move(player.hitbox, view_cords)\n if _npc.stats[\"talking\"]:\n player.stats[\"talking\"] = True\n elif player.stats[\"talking\"]:\n player.stats[\"talking\"] = False\n player.stats[\"waiting\"] = False\n talking_animation = 0\n text_position = 600\n text_temp = 0\n text_next_pos = 3\n # Test whether player stepped on a trap and if he did subtract him dmg\n for trap in traps:\n if packages.collision([player.hitbox[0]+view_cords[0], player.hitbox[1]+view_cords[1], player.hitbox[2], player.hitbox[3]], trap[:4]) and trap_cd == 0:\n player.stats[\"hp\"] -= trap[4] + random.randint(-2, 2)\n trap_cd = 15\n # Test for all loot if the player is on it and if the player has enough space he should pick it up\n for loot_ in loot:\n if packages.collision(loot_.hitbox, [player.hitbox[0] + player.stats[\"x\"], player.hitbox[1] + player.stats[\"y\"], player.hitbox[2], player.hitbox[3]]):\n if player.pickup(loot_):\n loot.remove(loot_)\n # Makes sure the players hp is never negative so bugs can´t happen\n if player.stats[\"hp\"] < 0:\n player.stats[\"hp\"] = 0\n # Get what actions where performed by player\n loot = controls(player, npcs, enemys, loot)\n # Draw everything on display\n draw(screen, player, npcs, enemys, loot)\n # Get all pressed keys\n keys = pg.key.get_pressed()\n # Test whether the escape key was pressed and open menu if it was pressed\n if keys[pg.K_ESCAPE] and cooldown == 0:\n run = ingame_menu(screen, player, npcs, enemys, loot, 15)\n cooldown = 15\n\n if player.stats[\"hp\"] <= 0:\n finished = True\n elif len(enemys) == 0:\n finished = True\n\n if run and player.stats[\"hp\"] > 0:\n while run:\n # Funktion that automates loop for set fps\n clock.tick(FPS)\n # Test if windows closed\n for event in pg.event.get():\n if event.type == pg.QUIT:\n run = False\n pg.quit()\n screen.blit(pg.transform.scale(text, (500, 100)), (150, 550))\n won_text = won_font.render(\n \"Du hast gewonnen!\", 1, (0, 0, 0))\n screen.blit(won_text, (176, 560))\n pg.display.update()\n if cooldown > 0:\n cooldown -= 1\n keys = pg.key.get_pressed()\n # Test whether the escape key was pressed and open menu if it was pressed\n if keys[pg.K_ESCAPE] and cooldown == 0:\n run = ingame_menu(screen, player, npcs, enemys, loot, 15)\n cooldown = 15\n # Draw everything on display\n draw(screen, player, npcs, enemys, loot)\n while run:\n # If player lost but game isn´t closed yet wait until windows closed\n # Funktion that automates loop for set fps\n clock.tick(FPS)\n # Test if windows closed\n for event in pg.event.get():\n if event.type == pg.QUIT:\n run = False\n pg.quit()\n screen.blit(pg.transform.scale(text, (500, 100)), (150, 550))\n won_text = won_font.render(\n \"Du bist gestorben!\", True, (0, 0, 0))\n screen.blit(won_text, (185, 560))\n pg.display.update()\n if cooldown > 0:\n cooldown -= 1\n keys = pg.key.get_pressed()\n # Test whether the escape key was pressed and open menu if it was pressed\n if keys[pg.K_ESCAPE] and cooldown == 0:\n run = ingame_menu(screen, player, npcs, enemys, loot, 15)\n cooldown = 15\n # Draw everything on display\n draw(screen, player, npcs, enemys, loot)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":25563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"195916100","text":"import argparse\n\nfrom data_source import DataSource\nfrom plot import run_plot\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-i', '--input',\n type=str,\n default=None,\n help='Path to the input file. '\n 'If provided, the data will be replayed '\n 'from this file instead of being acquired from the board. '\n 'Ex: --input \"data/output-2018-08-22.csv\"'\n )\n parser.add_argument(\n '-f', '--filter',\n action='count',\n default=False,\n help='Whether to filter the input data.'\n )\n parser.add_argument(\n '-s', '--save',\n action='count',\n default=False,\n help='Whether to save the data to a CSV file. '\n 'The CSV file will be saved to data/ and its '\n 'name will be timestamped.'\n )\n parser.add_argument(\n '-b', '--buffer',\n type=int,\n default=500,\n help='Size of the data history to display in the charts. This is also '\n 'the window of points used for PSD computation.'\n )\n\n args = parser.parse_args()\n source = DataSource(\n input_file=args.input,\n filter_data=args.filter,\n to_csv=args.save\n )\n source.start()\n\n try:\n run_plot(source)\n except KeyboardInterrupt:\n source.stop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sandbox/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"385689691","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 22 23:01:55 2019\n\n@author: ipekgamzeucal\n\"\"\"\n\nprint(\"\"\"\n ********************\n \n Armstrong Sayısı Bulmaca\n \n ********************\n \"\"\")\n\nsayi = input(\"Gir bi sayı, Armstrong mu bakalım:\")\n\nkuvvet=len(sayi)\n\ntoplam=0\nfor x in range(0,kuvvet):\n deger=int(sayi[x]) ** kuvvet\n toplam+=deger\n \nif int(sayi)==toplam:\n print(\"Armstrong sayısı!\")\nelse:\n print(\"Bu sayıdan Armstrong olmaz dostum...\")\n\n","sub_path":"armstrongSayisi.py","file_name":"armstrongSayisi.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"514560104","text":"\n\nfrom xai.brain.wordbase.nouns._destroyer import _DESTROYER\n\n#calss header\nclass _DESTROYERS(_DESTROYER, ):\n\tdef __init__(self,): \n\t\t_DESTROYER.__init__(self)\n\t\tself.name = \"DESTROYERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"destroyer\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_destroyers.py","file_name":"_destroyers.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"258036645","text":"from queue import Queue\nclass Solution:\n def updateMatrix(self, matrix):\n rows = len(matrix)\n if rows == 0:\n return 0\n cols = len(matrix[0])\n q = Queue()\n dist = matrix\n for i in range(rows):\n for j in range(cols):\n if matrix[i][j] == 0:\n dist[i][j] = 0\n q.put([i,j])\n else:\n dist[i][j] == 999\n dirt = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n while q is not q.empty():\n curr = q.get()\n for k in range(4):\n new_r = curr[0] + dirt[k][0]\n new_c = curr[1] + dirt[k][1]\n if (new_r >= 0 and new_c >= 0 and new_r < rows and new_c < cols):\n if dist[new_r][new_c] > dist[curr[0]][curr[1]] + 1:\n dist[new_r][new_c] == dist[curr[0]][curr[1]] + 1\n q.put([new_r, new_c])\n return dist\n#-------------------------------------------------------------------(Failure)\n\nclass Solution:\n def updateMatrix(self, matrix):\n rows = len(matrix)\n if rows == 0:\n return matrix\n cols = len(matrix[0])\n dist = matrix[0:]\n for i in range(rows):\n for j in range(cols):\n if matrix[i][j] == 0:\n dist[i][j] = 0\n else:\n dist[i][j] = 999\n for i in range(rows):\n for j in range(cols):\n if matrix[i][j] == 0:\n dist[i][j] = 0\n else:\n for k in range(rows):\n for l in range(cols):\n if matrix[k][l] == 0:\n dist[i][j] = min(dist[i][j], abs(k-i) + abs(l-j))\n return dist\n\n\n","sub_path":"leetcode-first_time/01matrix.py","file_name":"01matrix.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"649313449","text":"import matplotlib as ploty\r\nimport numpy as np\r\n\r\n\r\ndef show_number(A):\r\n \"\"\"Plot a matrix to the screen\r\n Expects A to be a sequence or sequence of sequences (of the same size).\r\n A should include only numerical values\r\n Return None\"\"\"\r\n B = np.array(A) \r\n ploty.imshow(B,cmap='gray')\r\n ploty.show()\r\n\r\ndef loadtxt(filename):\r\n \"\"\" Open and read files for ex5.\r\n Assumes the file include only numerical values seperated by tabs.\r\n Each line in filename will be represented as one item in the returned list.\r\n Such that if the 3rd line included 3 values,\r\n returned_list[2] will be a list of size 3.\r\n \"\"\"\r\n temp = np.loadtxt(filename,delimiter = '\\t')\r\n return temp.tolist()\r\n \r\n\r\n\r\ndef show_perceptron(X,Y,w,b):\r\n \"\"\"Present the current state of the perceptron algorithm\r\n where X (sequence of sequences) isthe data\r\n Y - the labels\r\n w - the candidate seperator\r\n b- the seprator bias\r\n Works only for 2D data - X assumed to be sequence of sequences of size 2\r\n \"\"\"\r\n if len(X) != 2 or len(Y) != 2 or len(w) != 2:\r\n print (\"Works only for 2d data!\")\r\n return\r\n \r\n\r\n X = np.array(X)\r\n Y = np.array(Y)\r\n w = np.array(w)\r\n ploty.plot(X[Y==1,0],X[Y==1,1],'bD',markersize=10,linestyle='None',linewidth = 3)\r\n ploty.plot(X[Y==-1,0],X[Y==-1,1],'ro',markersize=10,linestyle='None',linewidth = 3)\r\n \r\n minx = min(X[:,0]) - abs(min(X[:,0]))*0.2\r\n maxx = max(X[:,0]) + abs(max(X[:,0]))*0.2\r\n miny = min(X[:,1]) - abs(min(X[:,1]))*0.2\r\n maxy = max(X[:,1]) + abs(max(X[:,1]))*0.2\r\n ploty.xlim([minx,maxx])\r\n ploty.ylim([miny,maxy])\r\n A = np.arange(minx,maxx,0.01) \r\n if w[0] == 0 and w[1] ==0:\r\n ploty.plot(0,b,'.k',linewidth=2)\r\n ploty.xlim(min(minx,-0.1),max(maxx,0.1))\r\n ploty.ylim(min(miny,b-0.1),max(maxy,b+0.1)) \r\n elif w[1] == 0:\r\n B = np.arange(miny-abs(miny)*0.2,maxy+abs(maxy)*0.2,0.01)\r\n b =b/w[0]\r\n ploty.plot([b]*len(B),B,'k',linewidth=2)\r\n ploty.xlim(min(minx,b-0.1),max(maxx,b+0.1))\r\n else:\r\n l = b/w[1]-(w[0]/w[1])*A\r\n ploty.plot(A,l,'k',linewidth=2)\r\n ploty.ylim(min(miny,min(l)),max(maxy,max(l)))\r\n ploty.show()\r\n\r\n","sub_path":"ex5/intro2cs_ex5.py","file_name":"intro2cs_ex5.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"429532369","text":"import argparse\nimport json\nimport os\nimport types\n\nimport torch\n\nfrom diora.scripts.train import argument_parser, parse_args, configure\nfrom diora.scripts.train import get_validation_dataset, get_validation_iterator\nfrom diora.scripts.train import build_net\n\nfrom diora.logging.configuration import get_logger\n\nfrom diora.analysis.cky import ParsePredictor as CKY\n\n\ndef override_init_with_batch(var):\n init_with_batch = var.init_with_batch\n\n def func(self, *args, **kwargs):\n init_with_batch(*args, **kwargs)\n self.saved_scalars = {i: {} for i in range(self.length)}\n self.saved_scalars_out = {i: {} for i in range(self.length)}\n\n var.init_with_batch = types.MethodType(func, var)\n\n\ndef override_inside_hook(var):\n def func(self, level, h, c, s):\n length = self.length\n B = self.batch_size\n L = length - level\n\n assert s.shape[0] == B\n assert s.shape[1] == L\n # assert s.shape[2] == N\n assert s.shape[3] == 1\n assert len(s.shape) == 4\n smax = s.max(2, keepdim=True)[0]\n s = s - smax\n\n for pos in range(L):\n self.saved_scalars[level][pos] = s[:, pos, :]\n\n var.inside_hook = types.MethodType(func, var)\n\n\ndef replace_leaves(tree, leaves):\n def func(tr, pos=0):\n if not isinstance(tr, (list, tuple)):\n return 1, leaves[pos]\n\n newtree = []\n sofar = 0\n for node in tr:\n size, newnode = func(node, pos+sofar)\n sofar += size\n newtree += [newnode]\n\n return sofar, newtree\n\n _, newtree = func(tree)\n\n return newtree\n\n\ndef run(options):\n logger = get_logger()\n\n validation_dataset = get_validation_dataset(options)\n validation_iterator = get_validation_iterator(options, validation_dataset)\n word2idx = validation_dataset['word2idx']\n embeddings = validation_dataset['embeddings']\n\n idx2word = {v: k for k, v in word2idx.items()}\n\n logger.info('Initializing model.')\n trainer = build_net(options, embeddings, validation_iterator)\n\n # Parse\n\n diora = trainer.net.diora\n\n ## Monkey patch parsing specific methods.\n override_init_with_batch(diora)\n override_inside_hook(diora)\n\n ## Turn off outside pass.\n trainer.net.diora.outside = False\n\n ## Eval mode.\n trainer.net.eval()\n \n return trainer, word2idx\n \n\n\nclass DioraRepresentation(object):\n def __init__(self, corpus_path):\n self.corpus = corpus_path\n lines = [str(i) + ' ' + line for i, line in enumerate(open(self.corpus))]\n options = torch.load(os.path.join(os.path.dirname(__file__), 'options.pt'))\n options.elmo_cache_dir = os.path.join(os.path.dirname(__file__), options.elmo_cache_dir)\n print(options)\n with open(options.validation_path, 'w') as fout:\n for line in lines:\n fout.write(line)\n fout.close()\n self.trainer, self.word2idx = run(options)\n os.system('rm {:s}'.format(options.validation_path))\n\n\n # get fixed-length span representation repr(sent[start:end])\n def span_representation(self, sent, start, end):\n sent_tensor = torch.tensor([self.word2idx[item] for item in sent]).long().view(1, -1)\n sent_length = sent_tensor.shape[1]\n batch_map = {\n 'sentences': sent_tensor,\n 'neg_samples': sent_tensor, # just ignore this\n 'batch_size': 1,\n 'length': sent_length,\n 'example_ids': ['0']\n }\n _ = self.trainer.step(batch_map, train=False, compute_loss=False)\n span_length = end - start\n chart = self.trainer.net.diora.chart.inside_h[0]\n span_index = sent_length * (span_length - 1) - (span_length - 1) * (span_length - 2) // 2 + start \n return chart[span_index]\n\n\n\nif __name__ == '__main__':\n sent = 'hello world !'.split()\n tool = DioraRepresentation('./corpus.txt')\n representation = tool.span_representation(sent, 0, 3)\n print(representation.shape)\n\n","sub_path":"pytorch/diora_span.py","file_name":"diora_span.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"602504383","text":"# coding=utf-8\nfrom __future__ import unicode_literals, absolute_import, print_function, division\n\nimport errno\nimport json\nimport logging\nimport os.path\nimport sys\nimport traceback\n\nfrom sopel.tools import Identifier\n\nfrom sqlalchemy import create_engine, Column, ForeignKey, Integer, String\nfrom sqlalchemy.engine.url import URL\nfrom sqlalchemy.exc import OperationalError, SQLAlchemyError\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nif sys.version_info.major >= 3:\n unicode = str\n basestring = str\n\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef _deserialize(value):\n if value is None:\n return None\n # sqlite likes to return ints for strings that look like ints, even though\n # the column type is string. That's how you do dynamic typing wrong.\n value = unicode(value)\n # Just in case someone's mucking with the DB in a way we can't account for,\n # ignore json parsing errors\n try:\n value = json.loads(value)\n except ValueError:\n pass\n return value\n\n\nBASE = declarative_base()\nMYSQL_TABLE_ARGS = {'mysql_engine': 'InnoDB',\n 'mysql_charset': 'utf8mb4',\n 'mysql_collate': 'utf8mb4_unicode_ci'}\n\n\nclass NickIDs(BASE):\n \"\"\"Nick IDs table SQLAlchemy class.\"\"\"\n __tablename__ = 'nick_ids'\n nick_id = Column(Integer, primary_key=True)\n\n\nclass Nicknames(BASE):\n \"\"\"Nicknames table SQLAlchemy class.\"\"\"\n __tablename__ = 'nicknames'\n __table_args__ = MYSQL_TABLE_ARGS\n nick_id = Column(Integer, ForeignKey('nick_ids.nick_id'), primary_key=True)\n slug = Column(String(255), primary_key=True)\n canonical = Column(String(255))\n\n\nclass NickValues(BASE):\n \"\"\"Nick values table SQLAlchemy class.\"\"\"\n __tablename__ = 'nick_values'\n __table_args__ = MYSQL_TABLE_ARGS\n nick_id = Column(Integer, ForeignKey('nick_ids.nick_id'), primary_key=True)\n key = Column(String(255), primary_key=True)\n value = Column(String(255))\n\n\nclass ChannelValues(BASE):\n \"\"\"Channel values table SQLAlchemy class.\"\"\"\n __tablename__ = 'channel_values'\n __table_args__ = MYSQL_TABLE_ARGS\n channel = Column(String(255), primary_key=True)\n key = Column(String(255), primary_key=True)\n value = Column(String(255))\n\n\nclass PluginValues(BASE):\n \"\"\"Plugin values table SQLAlchemy class.\"\"\"\n __tablename__ = 'plugin_values'\n __table_args__ = MYSQL_TABLE_ARGS\n plugin = Column(String(255), primary_key=True)\n key = Column(String(255), primary_key=True)\n value = Column(String(255))\n\n\nclass SopelDB(object):\n \"\"\"Database object class.\n\n :param config: Sopel's configuration settings\n :type config: :class:`sopel.config.Config`\n\n This defines a simplified interface for basic, common operations on the\n bot's database. Direct access to the database is also available, to serve\n more complex plugins' needs.\n\n When configured to use SQLite with a relative filename, the file is assumed\n to be in the directory named by the core setting ``homedir``.\n\n .. versionadded:: 5.0\n\n .. versionchanged:: 7.0\n\n Switched from direct SQLite access to :ref:`SQLAlchemy\n `, allowing users more flexibility around what type\n of database they use (especially on high-load Sopel instances, which may\n run up against SQLite's concurrent-access limitations).\n\n \"\"\"\n\n def __init__(self, config):\n # MySQL - mysql://username:password@localhost/db\n # SQLite - sqlite:////home/sopel/.sopel/default.db\n self.type = config.core.db_type\n\n # Handle SQLite explicitly as a default\n if self.type == 'sqlite':\n path = config.core.db_filename\n if path is None:\n path = os.path.join(config.core.homedir, config.basename + '.db')\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n path = os.path.normpath(os.path.join(config.core.homedir, path))\n if not os.path.isdir(os.path.dirname(path)):\n raise OSError(\n errno.ENOENT,\n 'Cannot create database file. '\n 'No such directory: \"{}\". Check that configuration setting '\n 'core.db_filename is valid'.format(os.path.dirname(path)),\n path\n )\n self.filename = path\n self.url = 'sqlite:///%s' % path\n # Otherwise, handle all other database engines\n else:\n query = {}\n if self.type == 'mysql':\n drivername = config.core.db_driver or 'mysql'\n query = {'charset': 'utf8mb4'}\n elif self.type == 'postgres':\n drivername = config.core.db_driver or 'postgresql'\n elif self.type == 'oracle':\n drivername = config.core.db_driver or 'oracle'\n elif self.type == 'mssql':\n drivername = config.core.db_driver or 'mssql+pymssql'\n elif self.type == 'firebird':\n drivername = config.core.db_driver or 'firebird+fdb'\n elif self.type == 'sybase':\n drivername = config.core.db_driver or 'sybase+pysybase'\n else:\n raise Exception('Unknown db_type')\n\n db_user = config.core.db_user\n db_pass = config.core.db_pass\n db_host = config.core.db_host\n db_port = config.core.db_port # Optional\n db_name = config.core.db_name # Optional, depending on DB\n\n # Ensure we have all our variables defined\n if db_user is None or db_pass is None or db_host is None:\n raise Exception('Please make sure the following core '\n 'configuration values are defined: '\n 'db_user, db_pass, db_host')\n self.url = URL(drivername=drivername, username=db_user,\n password=db_pass, host=db_host, port=db_port,\n database=db_name, query=query)\n\n self.engine = create_engine(self.url, pool_recycle=3600)\n\n # Catch any errors connecting to database\n try:\n self.engine.connect()\n except OperationalError:\n print(\"OperationalError: Unable to connect to database.\")\n raise\n\n # Create our tables\n BASE.metadata.create_all(self.engine)\n\n self.ssession = scoped_session(sessionmaker(bind=self.engine))\n\n def connect(self):\n \"\"\"Get a direct database connection.\n\n :return: a proxied DBAPI connection object; see\n :meth:`sqlalchemy.engine.Engine.raw_connection()`\n\n .. important::\n\n The :attr:`~sopel.config.core_section.CoreSection.db_type` in use\n can change how the raw connection object behaves. You probably want\n to use :meth:`session` and the SQLAlchemy ORM in new plugins, and\n officially support only Sopel 7.0+.\n\n Note that :meth:`session` is not available in Sopel versions prior\n to 7.0. If your plugin needs to be compatible with older Sopel\n releases, your code *should* use SQLAlchemy via :meth:`session` if\n it is available (Sopel 7.0+) and fall back to direct SQLite access\n via :meth:`connect` if it is not (Sopel 6.x).\n\n We discourage *publishing* plugins that don't work with all\n supported databases, but you're obviously welcome to take shortcuts\n and support only the engine(s) you need in *private* plugins.\n\n \"\"\"\n if self.type != 'sqlite':\n # log non-sqlite uses of raw connections for troubleshooting, since\n # unless the developer had a good reason to use this instead of\n # `session()`, it indicates the plugin was written before Sopel 7.0\n # and might not work right when connected to non-sqlite DBs\n LOGGER.info(\n \"Raw connection requested when 'db_type' is not 'sqlite':\\n\"\n \"Consider using 'db.session()' to get a SQLAlchemy session \"\n \"instead here:\\n%s\",\n traceback.format_list(traceback.extract_stack()[:-1])[-1][:-1])\n return self.engine.raw_connection()\n\n def session(self):\n \"\"\"Get a SQLAlchemy Session object.\n\n :rtype: :class:`sqlalchemy.orm.session.Session`\n\n .. versionadded:: 7.0\n\n .. note::\n\n If your plugin needs to remain compatible with Sopel versions prior\n to 7.0, you can use :meth:`connect` to get a raw connection. See\n its documentation for relevant warnings and compatibility caveats.\n\n \"\"\"\n return self.ssession()\n\n def execute(self, *args, **kwargs):\n \"\"\"Execute an arbitrary SQL query against the database.\n\n :return: the query results\n :rtype: :class:`sqlalchemy.engine.ResultProxy`\n\n The ``ResultProxy`` object returned is a wrapper around a ``Cursor``\n object as specified by PEP 249.\n \"\"\"\n return self.engine.execute(*args, **kwargs)\n\n def get_uri(self):\n \"\"\"Return a direct URL for the database.\n\n :return: the database connection URI\n :rtype: str\n\n This can be used to connect from a plugin using another SQLAlchemy\n instance, for example, without sharing the bot's connection.\n \"\"\"\n return self.url\n\n # NICK FUNCTIONS\n\n def get_nick_id(self, nick, create=True):\n \"\"\"Return the internal identifier for a given nick.\n\n :param nick: the nickname for which to fetch an ID\n :type nick: :class:`~sopel.tools.Identifier`\n :param bool create: whether to create an ID if one does not exist\n :raise ValueError: if no ID exists for the given ``nick`` and ``create``\n is set to ``False``\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n The nick ID is shared across all of a user's aliases, assuming their\n nicks have been grouped together.\n\n .. seealso::\n\n Alias/group management functions: :meth:`alias_nick`,\n :meth:`unalias_nick`, :meth:`merge_nick_groups`, and\n :meth:`delete_nick_group`.\n\n \"\"\"\n session = self.ssession()\n slug = nick.lower()\n try:\n nickname = session.query(Nicknames) \\\n .filter(Nicknames.slug == slug) \\\n .one_or_none()\n\n if nickname is None:\n # see if it needs case-mapping migration\n nickname = session.query(Nicknames) \\\n .filter(Nicknames.slug == Identifier._lower_swapped(nick)) \\\n .one_or_none()\n if nickname is not None:\n # it does!\n nickname.slug = slug\n session.commit()\n\n if nickname is None: # \"is /* still */ None\", if Python had inline comments\n if not create:\n raise ValueError('No ID exists for the given nick')\n # Generate a new ID\n nick_id = NickIDs()\n session.add(nick_id)\n session.commit()\n\n # Create a new Nickname\n nickname = Nicknames(nick_id=nick_id.nick_id, slug=slug, canonical=nick)\n session.add(nickname)\n session.commit()\n return nickname.nick_id\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def alias_nick(self, nick, alias):\n \"\"\"Create an alias for a nick.\n\n :param str nick: an existing nickname\n :param str alias: an alias by which ``nick`` should also be known\n :raise ValueError: if the ``alias`` already exists\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To merge two *existing* nick groups, use :meth:`merge_nick_groups`.\n\n To remove an alias created with this function, use\n :meth:`unalias_nick`.\n\n \"\"\"\n nick = Identifier(nick)\n alias = Identifier(alias)\n nick_id = self.get_nick_id(nick)\n session = self.ssession()\n try:\n result = session.query(Nicknames) \\\n .filter(Nicknames.slug == alias.lower()) \\\n .filter(Nicknames.canonical == alias) \\\n .one_or_none()\n if result:\n raise ValueError('Alias already exists.')\n nickname = Nicknames(nick_id=nick_id, slug=alias.lower(), canonical=alias)\n session.add(nickname)\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def set_nick_value(self, nick, key, value):\n \"\"\"Set or update a value in the key-value store for ``nick``.\n\n :param str nick: the nickname with which to associate the ``value``\n :param str key: the name by which this ``value`` may be accessed later\n :param mixed value: the value to set for this ``key`` under ``nick``\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n The ``value`` can be any of a range of types; it need not be a string.\n It will be serialized to JSON before being stored and decoded\n transparently upon retrieval.\n\n .. seealso::\n\n To retrieve a value set with this method, use\n :meth:`get_nick_value`.\n\n To delete a value set with this method, use\n :meth:`delete_nick_value`.\n\n \"\"\"\n nick = Identifier(nick)\n value = json.dumps(value, ensure_ascii=False)\n nick_id = self.get_nick_id(nick)\n session = self.ssession()\n try:\n result = session.query(NickValues) \\\n .filter(NickValues.nick_id == nick_id) \\\n .filter(NickValues.key == key) \\\n .one_or_none()\n # NickValue exists, update\n if result:\n result.value = value\n session.commit()\n # DNE - Insert\n else:\n new_nickvalue = NickValues(nick_id=nick_id, key=key, value=value)\n session.add(new_nickvalue)\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def delete_nick_value(self, nick, key):\n \"\"\"Delete a value from the key-value store for ``nick``.\n\n :param str nick: the nickname whose values to modify\n :param str key: the name of the value to delete\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To set a value in the first place, use :meth:`set_nick_value`.\n\n To retrieve a value instead of deleting it, use\n :meth:`get_nick_value`.\n\n \"\"\"\n nick = Identifier(nick)\n nick_id = self.get_nick_id(nick)\n session = self.ssession()\n try:\n result = session.query(NickValues) \\\n .filter(NickValues.nick_id == nick_id) \\\n .filter(NickValues.key == key) \\\n .one_or_none()\n # NickValue exists, delete\n if result:\n session.delete(result)\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def get_nick_value(self, nick, key, default=None):\n \"\"\"Get a value from the key-value store for ``nick``.\n\n :param str nick: the nickname whose values to access\n :param str key: the name by which the desired value was saved\n :param mixed default: value to return if ``key`` does not have a value\n set (optional)\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To set a value for later retrieval with this method, use\n :meth:`set_nick_value`.\n\n To delete a value instead of retrieving it, use\n :meth:`delete_nick_value`.\n\n \"\"\"\n nick = Identifier(nick)\n session = self.ssession()\n try:\n result = session.query(NickValues) \\\n .filter(Nicknames.nick_id == NickValues.nick_id) \\\n .filter(Nicknames.slug == nick.lower()) \\\n .filter(NickValues.key == key) \\\n .one_or_none()\n if result is not None:\n result = result.value\n elif default is not None:\n result = default\n return _deserialize(result)\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def unalias_nick(self, alias):\n \"\"\"Remove an alias.\n\n :param str alias: an alias with at least one other nick in its group\n :raise ValueError: if there is not at least one other nick in the group\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To delete an entire group, use :meth:`delete_nick_group`.\n\n To *add* an alias for a nick, use :meth:`alias_nick`.\n\n \"\"\"\n alias = Identifier(alias)\n nick_id = self.get_nick_id(alias, False)\n session = self.ssession()\n try:\n count = session.query(Nicknames) \\\n .filter(Nicknames.nick_id == nick_id) \\\n .count()\n if count <= 1:\n raise ValueError('Given alias is the only entry in its group.')\n session.query(Nicknames).filter(Nicknames.slug == alias.lower()).delete()\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def delete_nick_group(self, nick):\n \"\"\"Remove a nickname, all of its aliases, and all of its stored values.\n\n :param str nick: one of the nicknames in the group to be deleted\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. important::\n\n This is otherwise known as The Nuclear Option. Be *very* sure that\n you want to do this.\n\n \"\"\"\n nick = Identifier(nick)\n nick_id = self.get_nick_id(nick, False)\n session = self.ssession()\n try:\n session.query(Nicknames).filter(Nicknames.nick_id == nick_id).delete()\n session.query(NickValues).filter(NickValues.nick_id == nick_id).delete()\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def merge_nick_groups(self, first_nick, second_nick):\n \"\"\"Merge two nick groups.\n\n :param str first_nick: one nick in the first group to merge\n :param str second_nick: one nick in the second group to merge\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n Takes two nicks, which may or may not be registered. Unregistered nicks\n will be registered. Keys which are set for only one of the given nicks\n will be preserved. Where both nicks have values for a given key, the\n value set for the ``first_nick`` will be used.\n\n A nick group can contain one or many nicknames. Groups containing more\n than one nickname can be created with this function, or by using\n :meth:`alias_nick` to add aliases.\n\n Note that merging of data only applies to the native key-value store.\n Plugins which define their own tables relying on the nick table will\n need to handle their own merging separately.\n \"\"\"\n first_id = self.get_nick_id(Identifier(first_nick))\n second_id = self.get_nick_id(Identifier(second_nick))\n session = self.ssession()\n try:\n # Get second_id's values\n res = session.query(NickValues).filter(NickValues.nick_id == second_id).all()\n # Update first_id with second_id values if first_id doesn't have that key\n for row in res:\n first_res = session.query(NickValues) \\\n .filter(NickValues.nick_id == first_id) \\\n .filter(NickValues.key == row.key) \\\n .one_or_none()\n if not first_res:\n self.set_nick_value(first_nick, row.key, _deserialize(row.value))\n session.query(NickValues).filter(NickValues.nick_id == second_id).delete()\n session.query(Nicknames) \\\n .filter(Nicknames.nick_id == second_id) \\\n .update({'nick_id': first_id})\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n # CHANNEL FUNCTIONS\n\n def get_channel_slug(self, chan):\n \"\"\"Return the case-normalized representation of ``channel``.\n\n :param str channel: the channel name to normalize, with prefix\n (required)\n :return str: the case-normalized channel name (or \"slug\"\n representation)\n\n This is useful to make sure that a channel name is stored consistently\n in both the bot's own database and third-party plugins'\n databases/files, without regard for variation in case between\n different clients and/or servers on the network.\n \"\"\"\n chan = Identifier(chan)\n slug = chan.lower()\n session = self.ssession()\n try:\n count = session.query(ChannelValues) \\\n .filter(ChannelValues.channel == slug) \\\n .count()\n\n if count == 0:\n # see if it needs case-mapping migration\n old_rows = session.query(ChannelValues) \\\n .filter(ChannelValues.channel == Identifier._lower_swapped(chan))\n old_count = old_rows.count()\n if old_count > 0:\n # it does!\n old_rows.update({ChannelValues.channel: slug})\n session.commit()\n\n return slug\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def set_channel_value(self, channel, key, value):\n \"\"\"Set or update a value in the key-value store for ``channel``.\n\n :param str channel: the channel with which to associate the ``value``\n :param str key: the name by which this ``value`` may be accessed later\n :param mixed value: the value to set for this ``key`` under ``channel``\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n The ``value`` can be any of a range of types; it need not be a string.\n It will be serialized to JSON before being stored and decoded\n transparently upon retrieval.\n\n .. seealso::\n\n To retrieve a value set with this method, use\n :meth:`get_channel_value`.\n\n To delete a value set with this method, use\n :meth:`delete_channel_value`.\n\n \"\"\"\n channel = self.get_channel_slug(channel)\n value = json.dumps(value, ensure_ascii=False)\n session = self.ssession()\n try:\n result = session.query(ChannelValues) \\\n .filter(ChannelValues.channel == channel)\\\n .filter(ChannelValues.key == key) \\\n .one_or_none()\n # ChannelValue exists, update\n if result:\n result.value = value\n session.commit()\n # DNE - Insert\n else:\n new_channelvalue = ChannelValues(channel=channel, key=key, value=value)\n session.add(new_channelvalue)\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def delete_channel_value(self, channel, key):\n \"\"\"Delete a value from the key-value store for ``channel``.\n\n :param str channel: the channel whose values to modify\n :param str key: the name of the value to delete\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To set a value in the first place, use :meth:`set_channel_value`.\n\n To retrieve a value instead of deleting it, use\n :meth:`get_channel_value`.\n\n \"\"\"\n channel = self.get_channel_slug(channel)\n session = self.ssession()\n try:\n result = session.query(ChannelValues) \\\n .filter(ChannelValues.channel == channel)\\\n .filter(ChannelValues.key == key) \\\n .one_or_none()\n # ChannelValue exists, delete\n if result:\n session.delete(result)\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def get_channel_value(self, channel, key, default=None):\n \"\"\"Get a value from the key-value store for ``channel``.\n\n :param str channel: the channel whose values to access\n :param str key: the name by which the desired value was saved\n :param mixed default: value to return if ``key`` does not have a value\n set (optional)\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To set a value for later retrieval with this method, use\n :meth:`set_channel_value`.\n\n To delete a value instead of retrieving it, use\n :meth:`delete_channel_value`.\n\n \"\"\"\n channel = self.get_channel_slug(channel)\n session = self.ssession()\n try:\n result = session.query(ChannelValues) \\\n .filter(ChannelValues.channel == channel)\\\n .filter(ChannelValues.key == key) \\\n .one_or_none()\n if result is not None:\n result = result.value\n elif default is not None:\n result = default\n return _deserialize(result)\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n # PLUGIN FUNCTIONS\n\n def set_plugin_value(self, plugin, key, value):\n \"\"\"Set or update a value in the key-value store for ``plugin``.\n\n :param str plugin: the plugin name with which to associate the ``value``\n :param str key: the name by which this ``value`` may be accessed later\n :param mixed value: the value to set for this ``key`` under ``plugin``\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n The ``value`` can be any of a range of types; it need not be a string.\n It will be serialized to JSON before being stored and decoded\n transparently upon retrieval.\n\n .. seealso::\n\n To retrieve a value set with this method, use\n :meth:`get_plugin_value`.\n\n To delete a value set with this method, use\n :meth:`delete_plugin_value`.\n\n \"\"\"\n plugin = plugin.lower()\n value = json.dumps(value, ensure_ascii=False)\n session = self.ssession()\n try:\n result = session.query(PluginValues) \\\n .filter(PluginValues.plugin == plugin)\\\n .filter(PluginValues.key == key) \\\n .one_or_none()\n # PluginValue exists, update\n if result:\n result.value = value\n session.commit()\n # DNE - Insert\n else:\n new_pluginvalue = PluginValues(plugin=plugin, key=key, value=value)\n session.add(new_pluginvalue)\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def delete_plugin_value(self, plugin, key):\n \"\"\"Delete a value from the key-value store for ``plugin``.\n\n :param str plugin: the plugin name whose values to modify\n :param str key: the name of the value to delete\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To set a value in the first place, use :meth:`set_plugin_value`.\n\n To retrieve a value instead of deleting it, use\n :meth:`get_plugin_value`.\n\n \"\"\"\n plugin = plugin.lower()\n session = self.ssession()\n try:\n result = session.query(PluginValues) \\\n .filter(PluginValues.plugin == plugin)\\\n .filter(PluginValues.key == key) \\\n .one_or_none()\n # PluginValue exists, update\n if result:\n session.delete(result)\n session.commit()\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n def get_plugin_value(self, plugin, key, default=None):\n \"\"\"Get a value from the key-value store for ``plugin``.\n\n :param str plugin: the plugin name whose values to access\n :param str key: the name by which the desired value was saved\n :param mixed default: value to return if ``key`` does not have a value\n set (optional)\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n .. seealso::\n\n To set a value for later retrieval with this method, use\n :meth:`set_plugin_value`.\n\n To delete a value instead of retrieving it, use\n :meth:`delete_plugin_value`.\n\n \"\"\"\n plugin = plugin.lower()\n session = self.ssession()\n try:\n result = session.query(PluginValues) \\\n .filter(PluginValues.plugin == plugin)\\\n .filter(PluginValues.key == key) \\\n .one_or_none()\n if result is not None:\n result = result.value\n elif default is not None:\n result = default\n return _deserialize(result)\n except SQLAlchemyError:\n session.rollback()\n raise\n finally:\n self.ssession.remove()\n\n # NICK AND CHANNEL FUNCTIONS\n\n def get_nick_or_channel_value(self, name, key, default=None):\n \"\"\"Get a value from the key-value store for ``name``.\n\n :param str name: nick or channel whose values to access\n :param str key: the name by which the desired value was saved\n :param mixed default: value to return if ``key`` does not have a value\n set (optional)\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n This is useful for common logic that is shared between both users and\n channels, as it will fetch the appropriate value based on what type of\n ``name`` it is given.\n\n .. seealso::\n\n To get a value for a nick specifically, use :meth:`get_nick_value`.\n\n To get a value for a channel specifically, use\n :meth:`get_channel_value`.\n\n \"\"\"\n name = Identifier(name)\n if name.is_nick():\n return self.get_nick_value(name, key, default)\n else:\n return self.get_channel_value(name, key, default)\n\n def get_preferred_value(self, names, key):\n \"\"\"Get a value for the first name which has it set.\n\n :param list names: a list of channel names and/or nicknames\n :param str key: the name by which the desired value was saved\n :return: the value for ``key`` from the first ``name`` which has it set,\n or ``None`` if none of the ``names`` has it set\n :raise ~sqlalchemy.exc.SQLAlchemyError: if there is a database error\n\n This is useful for logic that needs to customize its output based on\n settings stored in the database. For example, it can be used to fall\n back from the triggering user's setting to the current channel's setting\n in case the user has not configured their setting.\n\n .. note::\n\n This is the only ``get_*_value()`` method that does not support\n passing a ``default``. Try to avoid using it on ``key``\\\\s which\n might have ``None`` as a valid value, to avoid ambiguous logic.\n\n \"\"\"\n for name in names:\n value = self.get_nick_or_channel_value(name, key)\n if value is not None:\n return value\n","sub_path":"sopel/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":32975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"147527155","text":"from django.conf.urls import url\n\nfrom usaspending_api.accounts import views\n\n# bind ViewSets to URLs\ntas_list = views.TreasuryAppropriationAccountViewSet.as_view(\n {'get': 'list', 'post': 'list'})\ntas_balances_list = views.TreasuryAppropriationAccountBalancesViewSet.as_view(\n {'get': 'list', 'post': 'list'})\nfinancial_accounts_by_award = views.FinancialAccountsByAwardListViewSet.as_view(\n {'get': 'list', 'post': 'list'})\n\nurlpatterns = [\n url(r'^$', tas_balances_list),\n url(r'^tas/', tas_list),\n url(r'^awards/', financial_accounts_by_award),\n]\n","sub_path":"usaspending_api/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"306497270","text":"import torch.nn as nn\n\nimport DeepSparseCoding.utils.loaders as loaders\n\n\nclass EnsembleModule(nn.Sequential):\n def __init__(self, params, logger=None): # do not do Sequential's init\n super(nn.Sequential, self).__init__()\n self.params = params\n\n def setup_ensemble_module(self):\n for subparams in self.params.ensemble_params:\n submodule = loaders.load_module(subparams.model_type, subparams)\n #submodule.setup_module(subparams)\n self.add_module(subparams.model_type, submodule)\n if subparams.model_type == 'lca':\n self.register_parameter('w', submodule.getW())\n elif subparams.model_type == 'mlp':\n layers = submodule.getLayers()\n\n self.register_parameter('fc0_w', layers[0].weight)\n self.register_parameter('fc0_b', layers[0].bias)\n\n def forward(self, x):\n self.layer_list = [x]\n print(self.layer_list)\n for module in self:\n self.layer_list.append(module.get_encodings(self.layer_list[-1])) # latent encodings\n return self.layer_list[-1]\n\n def get_encodings(self, x):\n return self.forward(x)\n","sub_path":"DeepSparseCoding/modules/ensemble_module.py","file_name":"ensemble_module.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"246691992","text":"\"\"\"\n\nT-S Diagram Module\n\nStep 1 :The Simple Abstraction of The Rankine Cycle 8.1,8.2 with list,dict,function\n\nLicense: this code is in the public domain\n\nCheng Maohua(cmh@seu.edu.cn)\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom seuif97 import *\nimport numpy as np\n\n\ndef PlotPrettyTSDiagram(Nodes):\n # plt.figure()\n plt.figure(figsize=(10.0, 5.0)) # figsize :set figure size\n\n # saturated vapor and liquid entropy lines\n npt = np.linspace(10, 647.096-273.15, 200) # range of temperatures\n # saturated vapor tx2s(t, 1),x=1\n svap = [s for s in [tx2s(t, 1) for t in npt]]\n # saturated liquid tx2s(t, 0),x=0\n sliq = [s for s in [tx2s(t, 0) for t in npt]]\n plt.plot(svap, npt, 'r-')\n plt.plot(sliq, npt, 'b-')\n\n t = [Nodes[i]['t'] for i in range(4)]\n s = [Nodes[i]['s'] for i in range(4)]\n\n # Nodes[3]['t'] is slightly larger than Nodes[2]['t'] ,\n # points Nodes[2] and Nodes[3] are almost overlap if drawing with real values\n # so,adjust the value of Nodes[3]['t'] ,\n # using the virtual values to eliminate drawing overlap\n t[3] = Nodes[3]['t']+8\n\n # point 5 sat water\n t.append(px2t(Nodes[0]['p'], 0))\n s.append(px2s(Nodes[0]['p'], 0))\n\n # point 6 sat steam\n if (Nodes[0]['t'] > px2t(Nodes[0]['p'], 1)):\n t.append(px2t(Nodes[0]['p'], 1))\n s.append(px2s(Nodes[0]['p'], 1))\n\n t.append(Nodes[0]['t'])\n s.append(Nodes[0]['s'])\n\n plt.plot(s, t, 'go-')\n\n plt.annotate('1 ({:.2f},{:.2f})'.format(s[0], t[0]),\n xy=(s[0], t[0]), xycoords='data',\n xytext=(+2, +5), textcoords='offset points', fontsize=12)\n\n plt.annotate('2 ({:.2f},{:.2f})'.format(s[1], t[1]),\n xy=(s[1], t[1]), xycoords='data',\n xytext=(+2, +5), textcoords='offset points', fontsize=12)\n\n plt.annotate('3 ({:.2f},{:.2f})'.format(s[2], t[2]),\n xy=(s[2], t[2]), xycoords='data',\n xytext=(+10, +5), textcoords='offset points', fontsize=12)\n\n plt.annotate('4 ({:.2f},{:.2f})'.format(s[3], t[3]-8),\n xy=(s[3], t[3]), xycoords='data',\n xytext=(+10, +25), textcoords='offset points', fontsize=12)\n\n plt.annotate('5 ({:.2f},{:.2f})'.format(s[4], t[4]),\n xy=(s[4], t[4]), xycoords='data',\n xytext=(-60, +5), textcoords='offset points', fontsize=12)\n\n tist = [t[1], t[1]]\n sist = [s[1], px2s(Nodes[1]['p'], 1)]\n plt.plot(sist, tist, 'y-')\n\n plt.title('T-s: Ideal Rankine Cycle')\n\n plt.xlabel('Entropy(kJ/(kg.K)')\n plt.ylabel('Temperature(°C)')\n plt.grid() # Show Grid\n # The output of a matplotlib plot as an SVG\n # plt.savefig(\"./img/rankine81-TS.svg\")\n plt.show()\n","sub_path":"step1/plotTS.py","file_name":"plotTS.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"382740904","text":"from numpy.testing import assert_almost_equal\nfrom ..lightcurve import KeplerCBVCorrector, KeplerLightCurveFile\n\n\ndef test_kepler_cbv_fit():\n tabby_quarter_8 = (\"https://archive.stsci.edu/missions/kepler/lightcurves\"\n \"/0084/008462852/kplr008462852-2011073133259_llc.fits\")\n cbv = KeplerCBVCorrector(tabby_quarter_8)\n cbv_lc = cbv.correct()\n assert_almost_equal(cbv.coeffs, [0.08534423, 0.10814261], decimal=4)\n\n lcf = KeplerLightCurveFile(tabby_quarter_8)\n cbv_lcf = lcf.compute_cotrended_lightcurve()\n assert_almost_equal(cbv_lc.flux, cbv_lcf.flux)\n","sub_path":"pyke/tests/test_lightcurve.py","file_name":"test_lightcurve.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"591877844","text":"from __future__ import print_function # Python 2/3 compatibility\r\nimport boto3\r\n\r\n#dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url=\"http://localhost:8000\")\r\n\r\n# For running against our AWS instance.\r\ndynamodb = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url=\"http://dynamodb.us-east-1.amazonaws.com\")\r\n\r\n#\r\n# Interesting thing to note is that when you create the tables you only define the keys. Not the other attributes.\r\n#\r\n\r\n\r\n# There is one entry per stock symbol in this table.\r\ncurrent_trend_table = dynamodb.create_table(\r\n TableName='Temp_Current_Trend',\r\n KeySchema=[\r\n {\r\n 'AttributeName': 'stock_symbol',\r\n 'KeyType': 'HASH' #Partition key\r\n },\r\n ],\r\n AttributeDefinitions=[\r\n { \r\n 'AttributeName': 'stock_symbol',\r\n 'AttributeType': 'S'\r\n }\r\n\r\n ],\r\n ProvisionedThroughput={\r\n 'ReadCapacityUnits': 1,\r\n 'WriteCapacityUnits': 1\r\n }\r\n)\r\n\r\nprint(\"Current Trend Table status:\", current_trend_table.table_status)\r\n\r\n# There will be many entries per stock symbol in this table.\r\ntrend_history_table = dynamodb.create_table(\r\n TableName='Temp_Trend_History',\r\n KeySchema=[\r\n {\r\n 'AttributeName': 'stock_symbol',\r\n 'KeyType': 'HASH' #Partition key\r\n },\r\n {\r\n 'AttributeName': 'occurence_date',\r\n 'KeyType': 'RANGE' #Partition key\r\n }, \r\n ],\r\n AttributeDefinitions=[\r\n { \r\n 'AttributeName': 'stock_symbol',\r\n 'AttributeType': 'S'\r\n }, \r\n {\r\n 'AttributeName': 'occurence_date',\r\n 'AttributeType': 'S'\r\n },\r\n ],\r\n ProvisionedThroughput={\r\n 'ReadCapacityUnits': 1,\r\n 'WriteCapacityUnits': 1\r\n }\r\n)\r\n\r\nprint(\"Trend History Table status:\", trend_history_table.table_status)\r\n\r\n","sub_path":"dynamo_db_AWS_table_create_temp.py","file_name":"dynamo_db_AWS_table_create_temp.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"282046104","text":"\"\"\"Server app for DataRobot Prime prediction.\"\"\"\n# -*- coding: utf-8 -*-\n\nfrom bottle import get, post, run, request, response, error, BaseRequest\nimport json\nimport os\nimport pandas\nimport prime3 as prime # DataRobot Prime module\n\n\n@get('/status')\ndef get_status():\n \"\"\"Return 200 reponse.\"\"\"\n response.content_type = 'application/json'\n return json.dumps({'status': 'ok', 'error': None, 'code': 200})\n\n\n@post('/predict')\ndef post_predict():\n \"\"\"Run DataRobot Prime.\n\n @json {Object} - must include all of the columns for prediction\n \"\"\"\n return _run_predict()\n\n\n@post('/predict/')\ndef post_predict_key(key='id'):\n \"\"\"Run DataRobot Prime with key.\n\n @json {Object} - must include all of the columns for prediction\n \"\"\"\n return _run_predict(key)\n\n\ndef _run_predict(key='id'):\n \"\"\"Run DataRobot prime by POST method.\n\n @json {Object} - must include all of the columns for prediction\n \"\"\"\n params = _to_list(request.json)\n ds = pandas.DataFrame.from_dict(params)\n ds = prime.rename_columns(ds)\n ds = prime.convert_bool(ds)\n prime.validate_columns(ds.columns)\n ds = prime.parse_numeric_types(ds)\n ds = prime.add_missing_indicators(ds)\n ds = prime.impute_values(ds)\n ds = prime.combine_small_levels(ds)\n predicts = prime.predict_dataframe(ds)\n\n if key in params[0]:\n result = [{key: params[i][key], 'predict': predicts[i]} for i in range(predicts.size)]\n return {'error': None, 'code': 200, 'data': result}\n else:\n return {'error': None, 'code': 200, 'predicts': predicts.tolist()}\n\n\ndef _to_list(val):\n \"\"\"Return the variable converted to list type.\"\"\"\n if isinstance(val, list):\n return val\n else:\n return [val]\n\n\n@error(404)\ndef error404(e):\n \"\"\"Return 404 error message.\"\"\"\n response.content_type = 'application/json'\n return json.dumps({'status': 'Not Found', 'error': str(e.exception), 'code': 404})\n\n\n@error(500)\ndef error500(e):\n \"\"\"Return 500 error message.\"\"\"\n response.content_type = 'application/json'\n result = {'status': 'Internal Server Error', 'error': str(e.exception), 'code': 500}\n return json.dumps(result)\n\n\nif __name__ == '__main__':\n KB = 1024\n MB = KB * KB\n BaseRequest.MEMFILE_MAX = 2 * MB\n\n port = 8080\n if \"DR_SERVER_PORT\" in os.environ:\n port = os.environ[\"DR_SERVER_PORT\"]\n run(host='0.0.0.0', port=port)\n","sub_path":"datarobot/assets/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"535547883","text":"import psycopg2\nimport os\n\n\ndef run_query(query):\n try:\n # setup connection string\n connect_str = \"dbname='your_database_name' user='your_username' host='localhost' password='yourpwd'\"\n # use our connection values to establish a connection\n conn = psycopg2.connect(connect_str)\n # set autocommit option, to do every query when we call it\n conn.autocommit = True\n # create a psycopg2 cursor that can execute queries\n cursor = conn.cursor()\n cursor.execute(query)\n except Exception as e:\n print(\"Uh oh, can't connect. Invalid dbname, user or password?\")\n print(e)\n return cursor\n\n\ndef print_menu():\n os.system('clear')\n print('MENU: ')\n print('1. Mentor names')\n print('2. Nicknames at Miskolc')\n print('3. Carol\\'s full name')\n print('4. Possible owner of hat')\n print('5. New applicant: Markus')\n print('6. Jemima Foreman\\'s number')\n print('7. Deleting applications')\n print('8. Exit')\n print('')\n\n\ndef user_input():\n choice = input(\"Enter your choice (1-8): \")\n print('')\n return choice\n\n\ndef display_results():\n print_menu()\n display_again = True\n while display_again:\n choice = user_input()\n if choice == '1':\n mentor_names()\n print('')\n if choice == '2':\n nicknames_at_miskolc()\n print('')\n if choice == '3':\n applicant_carol()\n print('')\n if choice == '4':\n owner_of_the_hat()\n print('')\n if choice == '5':\n new_applicant_markus()\n print('')\n if choice == '6':\n update_jemima()\n print('')\n if choice == '7':\n delete_applicants()\n print('')\n if choice == '8':\n quit()\n\n\ndef mentor_names():\n cursor = run_query(\"\"\"SELECT first_name, last_name FROM mentors;\"\"\")\n mentor_names = cursor.fetchall()\n print_menu()\n print('Mentor names: \\n')\n for name in mentor_names:\n name = ', '.join(name)\n print(name)\n return mentor_names\n\n\ndef nicknames_at_miskolc():\n cursor = run_query(\"\"\"SELECT nick_name FROM mentors WHERE city='Miskolc';\"\"\")\n nicknames = cursor.fetchall()\n print_menu()\n print('Nicknames at Miskolc: \\n')\n for name in nicknames:\n name = ', '.join(name)\n print(name)\n\n\ndef applicant_carol():\n cursor = run_query(\"\"\"SELECT first_name, last_name, phone_number FROM applicants WHERE first_name='Carol';\"\"\")\n carol_data = cursor.fetchall()\n print_menu()\n print(\"Carol's full name, and her phone number: \\n\")\n for full_name in carol_data:\n full_name = ', '.join(full_name)\n print(full_name)\n\n\ndef owner_of_the_hat():\n cursor = run_query(\n \"\"\"SELECT first_name, last_name, phone_number FROM applicants WHERE email LIKE '%@adipiscingenimmi.edu';\"\"\")\n unknown_girl_data = cursor.fetchall()\n print_menu()\n print(\"The possible owners of the hat: \\n\")\n for full_name in unknown_girl_data:\n full_name = ', '.join(full_name)\n print(full_name)\n\n\ndef new_applicant_markus():\n cursor = run_query(\"\"\"INSERT INTO applicants (first_name, last_name, phone_number, email, application_code)\n VALUES ('Markus', 'Schaffarzyk', '003620/725-2666', 'djnovus@groovecoverage.com', 54823);\"\"\")\n print(\"New applicant added. \\n\")\n print_menu()\n\n cursor = run_query(\"\"\"SELECT * FROM applicants WHERE application_code=54823;\"\"\")\n new_applicant_markus_data = cursor.fetchall()\n print(\"New applicant's data: \\n\")\n\n new_applicant_markus_data = str(new_applicant_markus_data)\n get_the_code = new_applicant_markus_data.split(',')\n app_code = (get_the_code[5][1:-2])\n\n data_list = []\n data = ''\n for char in new_applicant_markus_data:\n if char in [\",\", \"(\", \")\", \"[\", \"]\", \"'\"]:\n continue\n elif char != ' ' or type(char) == int:\n data += char\n elif char == ' ':\n if len(data) > 0:\n data_list.append(data)\n data = ''\n\n app_id = data_list[0]\n first_name = data_list[1]\n last_name = data_list[2]\n phone = data_list[3]\n email = data_list[4]\n\n print(\"ID: {0} \\nFirst name: {1}\\nLast name: {2}\\nPhone number: {3}\\nE-mail: {4}\\nApplication code: {5}\"\n .format(app_id, first_name, last_name, phone, email, app_code))\n\n\ndef update_jemima():\n cursor = run_query(\"\"\"UPDATE applicants SET phone_number='003670/223-7459'\\\n WHERE first_name='Jemima' AND last_name='Foreman';\"\"\")\n print(\"Data updated. \\n\")\n cursor = run_query(\"\"\"SELECT first_name, last_name, phone_number FROM applicants\\\n WHERE first_name='Jemima' AND last_name='Foreman';\"\"\")\n jemima_number = cursor.fetchall()\n print_menu()\n print(\"Jemima's number: \\n\")\n for number in jemima_number:\n number = ', '.join(number)\n print(number)\n\n\ndef delete_applicants():\n cursor = run_query(\"\"\"DELETE FROM applicants WHERE email LIKE '%mauriseu.net';\"\"\")\n print('Applicant(s) removed from database.')\n\n\nif __name__ == '__main__':\n display_results()\n","sub_path":"queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":5211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"397143809","text":"import os\nimport sys\nfrom flask import Flask, request, jsonify, abort\nfrom sqlalchemy import exc\nimport json\nfrom flask_cors import CORS\n\nfrom .database.models import db_drop_and_create_all, setup_db, Drink\nfrom .auth.auth import AuthError, requires_auth\n\napp = Flask(__name__)\nsetup_db(app)\nCORS(app)\n\n# db_drop_and_create_all()\n\n# ROUTES\n\n\n@app.route('/drinks')\ndef get_drinks():\n try:\n drinks = Drink.query.all()\n drinks = [drink.short() for drink in drinks]\n\n if not drinks:\n abort(404)\n\n return jsonify({\n 'success': True,\n 'drinks': drinks\n })\n except Exception:\n # print('Error:', sys.exc_info())\n abort(422)\n\n\n@app.route('/drinks-detail')\n@requires_auth('get:drinks-detail')\ndef get_drinks_detail(token):\n try:\n drinks = Drink.query.all()\n drinks = [drink.long() for drink in drinks]\n\n if not drinks:\n abort(404)\n\n return jsonify({\n 'success': True,\n 'drinks': drinks\n })\n except Exception:\n # print('Error:', sys.exc_info())\n abort(422)\n\n\n@app.route('/drinks', methods=['POST'])\n@requires_auth('post:drinks')\ndef create_new_drink(token):\n body = request.get_json()\n if not body:\n abort(400)\n title = body.get('title', '')\n recipe = body.get('recipe', None)\n if recipe:\n try:\n new_drink = Drink(title=title, recipe=json.dumps(recipe))\n new_drink.insert()\n return jsonify({\n 'success': True,\n 'drinks': [{'id': new_drink.id,\n 'title': new_drink.title,\n 'recipe': new_drink.recipe\n }]\n })\n except Exception as e:\n # print('error', e.args)\n abort(422)\n else:\n abort(400)\n\n\n@app.route('/drinks/', methods=['PATCH'])\n@requires_auth('patch:drinks')\ndef udpate_drink(token, drink_id):\n drink = Drink.query.get(drink_id)\n if not drink:\n abort(404)\n\n data = request.get_json()\n if not data:\n abort(400)\n drink.title = data.get('title', drink.title)\n recipe = data.get('recipe', drink.recipe)\n drink.recipe = json.dumps(recipe)\n\n try:\n drink.update()\n return jsonify({\n 'success': True,\n 'drinks': [drink.long()]\n })\n except Exception:\n print('Error:', sys.exc_info())\n abort(422)\n\n\n@app.route('/drinks/', methods=['DELETE'])\n@requires_auth('delete:drinks')\ndef delete_drink(token, drink_id):\n try:\n drink = Drink.query.filter(Drink.id == drink_id).one_or_none()\n if drink is None:\n abort(404)\n drink.delete()\n return jsonify({\n 'success': True,\n 'delete': drink_id\n })\n except Exception:\n abort(422)\n\n\n# Error Handling\n'''\nExample error handling for unprocessable entity\n'''\n\n\n@app.errorhandler(422)\ndef unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"resource not found\"\n }), 404\n\n\n@app.errorhandler(400)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"bad request\"\n }), 400\n\n\n@app.errorhandler(AuthError)\ndef auth_error(error):\n return jsonify({\n \"success\": False,\n \"error\": 'Authentication Error',\n \"message\": error.error['description']\n }), 401\n","sub_path":"projects/03_coffee_shop_full_stack/starter_code/backend/src/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"169323930","text":"#!/usr/bin/env python\n\nimport binascii\nfrom os import path, makedirs\nfrom xml.etree.ElementTree import Element, SubElement, tostring, parse\nfrom api import TournamentApi\nfrom config import PadmissConfigManager\n\nfrom api import ScoreBreakdown, Score, Song, ChartUpload, TimingWindows\n\n\nclass SLIni():\n\t__fields__ = {\n\t\t'JudgmentGraphic': \"Love\",\n\t\t'Mini': \"0%\",\n\t\t'BackgroundFilter': \"Off\",\n\t\t'SpeedModType': \"x\",\n\t\t'SpeedMod': \"1.00\",\n\t\t'Vocalization': \"None\",\n\t\t'NoteSkin': \"\",\n\t\t'HideTargets': \"false\",\n\t\t'HideSongBG': \"false\",\n\t\t'HideCombo': \"false\",\n\t\t'HideLifebar': \"false\",\n\t\t'HideScore': \"false\",\n\t\t'HideDanger': \"true\",\n\t\t'ColumnFlashOnMiss': \"false\",\n\t\t'SubtractiveScoring': \"false\",\n\t\t'MeasureCounterPosition': \"Left\",\n\t\t'MeasureCounter': \"None\",\n\t\t'TargetStatus': \"Disabled\",\n\t\t'TargetBar': 11,\n\t\t'TargetScore': \"false\",\n\t\t'ReceptorArrowsPosition': \"StomperZ\",\n\t\t'LifeMeterType': \"Standard\",\n\t}\n\n\tdef write_string(self):\n\t\tret = \"[Simply Love]\\n\"\n\t\tfor k,v in self.__fields__.items():\n\t\t\tret += k + '=' + str(v) + \"\\n\"\n\t\treturn ret\n\t\n\tdef from_score(self, score):\n\t\tif score['speedMod']['type'] == 'MaxBPM':\n\t\t\tself.__fields__['SpeedModType'] = 'M'\n\t\tif score['speedMod']['type'] == 'Multiplier':\n\t\t\tself.__fields__['SpeedModType'] = 'X'\n\t\tif score['speedMod']['type'] == 'ConstantBPM':\n\t\t\tself.__fields__['SpeedModType'] = 'C'\n\n\t\tspeed = float(score['speedMod']['value'])\n\t\tif speed > 0:\n\t\t\tif self.__fields__['SpeedModType'] == 'X':\n\t\t\t\tspeed = int(speed * 100) / 100\n\t\t\telse:\n\t\t\t\tspeed = int(speed)\n\t\t\tself.__fields__['SpeedMod'] = str(speed)\n\n\t\tif score['noteSkin']:\n\t\t\tself.__fields__['NoteSkin'] = score['noteSkin']\n\n\t\tfor mod in score['modsOther']:\n\t\t\tif mod['name'] == 'EFFECT_MINI':\n\t\t\t\tvalue = int(float(mod['value']) * 100)\n\t\t\t\tself.__fields__['Mini'] = str(value) + '%'\n\n\t\tfor mod in score['modsOther']:\n\t\t\tif mod['name'][0:3] == 'SL:':\n\t\t\t\tself.__fields__[mod['name'][3:]] = mod['value']\n\ndef generate_statsxml(player, score):\n\tstats = Element('Stats')\n\tgeneral = SubElement(stats, 'GeneralData')\n\tSubElement(general, 'DisplayName').text = player.nickname\n\tSubElement(general, 'Guid').text = player._id\n\tif score != None:\n\t\tmodifiers = SubElement(general, 'DefaultModifiers')\n\t\tmods = []\n\t\tif score['speedMod']['type'] == 'MaxBPM':\n\t\t\tmods.append('m' + str(score['speedMod']['value']))\n\t\tif score['speedMod']['type'] == 'Multiplier':\n\t\t\tmods.append(str(score['speedMod']['value']) + 'x')\n\t\tmods.append('Overhead')\n\t\tif score['noteSkin']:\n\t\t\tmods.append(score['noteSkin'])\n\t\tSubElement(modifiers, 'dance').text = ', '.join(mods)\n\n\treturn stats\n\n\ndef generate_editableini(player):\n\tini_template = \\\n'''\n[Editable]\nDisplayName={displayname}\nLastUsedHighScoreName={shortname}\n'''[1:]\n\treturn ini_template.format(displayname=player.nickname, shortname=player.shortNickname)\n\ndef generate_sl_ini(score):\n\tif score == None:\n\t\treturn None\n\tini = SLIni()\n\tini.from_score(score)\n\n\treturn ini.write_string()\n\ndef generate_profile(api, dirname, player):\n\tmakedirs(dirname)\n\n\tscore = api.get_last_sore(player._id)\n\n\twith open(path.join(dirname, 'Stats.xml'), 'w') as statsxml:\n\t\tstatsxml.write(tostring(generate_statsxml(player, score), encoding=\"unicode\"))\n\n\twith open(path.join(dirname, 'Editable.ini'), 'w') as editableini:\n\t\teditableini.write(generate_editableini(player))\n\n\twith open(path.join(dirname, 'card0.txt'), 'w') as card:\n\t\thex_player_id = binascii.hexlify(player._id.encode()).decode()\n\t\tcard.write('E004' + hex_player_id.zfill(12)[0:12])\n\n\tini = generate_sl_ini(score)\n\tif ini != None:\n\t\twith open(path.join(dirname, 'Simply Love UserPrefs.ini'), 'w') as slini:\n\t\t\tslini.write(ini)\n\n\ndef parse_profile_scores(dirname):\n\ttree = parse(path.join(dirname, 'Stats.xml'))\n\troot = tree.getroot()\n\tfor song in root.findall('./SongScores/Song'):\n\t\tprint(song.attrib['Dir'])\n\t\tfor steps in song.findall('./Steps'):\n\t\t\tprint(steps.attrib['Difficulty'], steps.attrib['StepsType'])\n\t\t\tfor score in steps.findall('./HighScoreList/HighScore'):\n\t\t\t\tprint('score')\n\t\t\t\tprint(score.find('PercentDP').text)\n\t\t\t\ttns = score.find('TapNoteScores')\n\t\t\t\tprint(tns.find('HitMine').text)\n\n\nif __name__ == '__main__':\n\tconfig = PadmissConfigManager().load_config()\n\tapi = TournamentApi(config.padmiss_api_url, config.api_key)\n\tscore = api.get_last_sore('5ad12d9f07b73e108861bf9b')\n\n\tini = generate_sl_ini(score)\n\tprint(ini)\n","sub_path":"sm5_profile.py","file_name":"sm5_profile.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"547072832","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script creates sites for `google-cloud-clients` and `google-api-grpc`\n# modules and commits (but does not push) them to gh-pages branch of\n# googleapis/google-cloud-java github repository.\n\n# Usage:\n# python utilities/stage_sites.py\n\nimport subprocess\nimport sys\n\n\ndef stage_sites(sites, gh_pages, git_url, top_site_url):\n _run(['git', 'clone', '--branch', 'gh-pages', '--single-branch', git_url,\n gh_pages])\n _run(['mkdir', '-p', gh_pages])\n for site in sites:\n _create_site(site, gh_pages, top_site_url)\n _run(['git', 'add', '.'], gh_pages)\n _run(['git', 'commit', '-m',\n \"Regenerate documentation for %s. [ci skip]\" % ', '.join(sites)],\n gh_pages)\n\n\ndef _create_site(site_name, gh_pages, top_site_url):\n _run(['mvn', 'site'], site_name)\n _run(['mvn', 'site:stage', '-q',\n \"-DtopSiteURL=%s/%s\" % (top_site_url, site_name)],\n site_name)\n _run(['rm', '-rf', site_name], gh_pages)\n _run(['cp', '-r', \"%s/target/staging/site/%s\" % (site_name, site_name),\n gh_pages])\n\n\ndef _run(command, cwd=None):\n print(\"\\033[1;36mExecute command:\\033[0m %s\" % ' '.join(command))\n subprocess.check_call(command, cwd=cwd, stdout=sys.stdout, stderr=sys.stderr)\n\n\nif __name__ == '__main__':\n stage_sites(['google-api-grpc', 'google-cloud-clients'], 'tmp_gh-pages',\n 'git@github.com:googleapis/google-cloud-java.git',\n 'https://googleapis.github.io/google-cloud-java')\n","sub_path":"utilities/stage_sites.py","file_name":"stage_sites.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"202260724","text":"# coding:utf-8\n\"\"\"\nYou can precisely specify dashes with an on/off ink rect sequence in\npoints.\n\"\"\"\nfrom pylab import *\n\ndashes = [5,2,10,5] # 5 points on, 2 off, 3 on, 1 off\n\nl, = plot(arange(20), '--')\nl.set_dashes(dashes)\nsavefig('dash_control')\nshow()\n","sub_path":"fig/fig11.py","file_name":"fig11.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"223608432","text":"import face_recognition\nimport cv2\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport pickle\n\nknown_face_encodings = []\nknown_face_metadata = []\n\n\ndef load_known_faces():\n global known_face_encodings\n global known_face_metadata\n\n try:\n with open(\"faces_file.dat\", \"rb\") as faces_file:\n print('cai aq')\n known_face_encodings, known_face_metadata = pickle.load(\n faces_file)\n print('Known faces lodaded')\n except FileNotFoundError as err:\n print('No file found, creating a new one')\n pass\n\n\ndef lookup_known_faces(face_encoding):\n metadata = None\n\n # If has no faces return\n if len(known_face_encodings) == 0:\n return metadata\n\n # Else, compare using euclidean distance (lower value, higher similarity)\n face_distances = face_recognition.face_distance(\n known_face_encodings, face_encoding)\n best_match_index = np.argmin(face_distances)\n\n # Threshold at 0.65\n if face_distances[best_match_index] < 0.65:\n metadata = known_face_metadata[best_match_index]\n metadata[\"last_seen\"] = datetime.now()\n metadata[\"seen_frames\"] += 1\n\n # If not seen in the last X minutes, is a new visit\n if datetime.now() - metadata[\"first_seen_this_interaction\"] > timedelta(minutes=30):\n metadata[\"first_seen_this_interaction\"] = datetime.now()\n metadata[\"seen_count\"] += 1\n return metadata\n\n\ndef register_new_face(face_encoding, face_image):\n print(\"Recording new face\")\n\n # Add new face to the known face data\n known_face_encodings.append(face_encoding)\n\n known_face_metadata.append({\n \"first_seen\": datetime.now(),\n \"first_seen_this_interaction\": datetime.now(),\n \"last_seen\": datetime.now(),\n \"seen_count\": 1,\n \"seen_frames\": 1,\n \"face_image\": face_image,\n })\n\n\ndef check_have_seen(face_locations, face_encodings, small_frame):\n face_labels = []\n for location, encoding in zip(face_locations, face_encodings):\n metadata = lookup_known_faces(encoding)\n\n if metadata is not None:\n time_at_door = datetime.now(\n ) - metadata['first_seen_this_interaction']\n face_label = f\"Time: {int(time_at_door.total_seconds())}s\"\n else:\n face_label = \"New visitor!\"\n\n top, right, bottom, left = location\n face_image = small_frame[top:bottom, left:right]\n face_image = cv2.resize(face_image, (150, 150))\n register_new_face(encoding, face_image)\n\n face_labels.append(face_label)\n return face_labels\n\n\ndef draw_bbox(face_locations, face_labels, frame):\n\n for(top, right, bottom, left), face_label in zip(face_locations, face_labels):\n # Return to normal size since we divided by 4\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n # Draw bbox on face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n # Draw label\n cv2.rectangle(frame, (left, bottom - 35),\n (right, bottom), (0, 0, 255), cv2.FILLED)\n cv2.putText(frame, face_label, (left + 6, bottom - 6),\n cv2.FONT_HERSHEY_DUPLEX, 0.8, (255, 255, 255), 1)\n\n\ndef draw_visitors_data(frame):\n number_of_recent_visitors = 0\n\n for metadata in known_face_metadata:\n # If we have seen this person in the last minute, draw their image\n if (datetime.now() - metadata['last_seen'] < timedelta(seconds=10)) and (metadata['seen_frames'] > 5):\n # Position offset to display face image\n x_position = number_of_recent_visitors * 150\n frame[30:180, x_position:x_position+150] = metadata['face_image']\n number_of_recent_visitors += 1\n\n visits = metadata['seen_count']\n visit_label = f\"{visits} visits\"\n if visits == 1:\n visit_label = 'First Visit'\n\n cv2.putText(frame, visit_label, (x_position + 10, 170),\n cv2.FONT_HERSHEY_DUPLEX, 0.6, (255, 255, 255), 1)\n\n if number_of_recent_visitors > 0:\n cv2.putText(frame, \"Visitors:\", (5, 18),\n cv2.FONT_HERSHEY_DUPLEX, 0.8, (0, 0, 0), 1)\n\n\ndef save_faces(face_locations, number_of_faces_since_save, quit=False):\n\n if((len(face_locations) > 0 and number_of_faces_since_save > 100) or quit == True):\n print('saving')\n\n with open(\"faces_file.dat\", \"wb\") as faces_file:\n face_data = [known_face_encodings, known_face_metadata]\n pickle.dump(face_data, faces_file)\n print('Known faces saved')\n\n number_of_faces_since_save = 0\n return number_of_faces_since_save\n else:\n number_of_faces_since_save += 1\n return number_of_faces_since_save\n","sub_path":"face_handler.py","file_name":"face_handler.py","file_ext":"py","file_size_in_byte":4828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"454704229","text":"def main():\r\n n = int(input(\"Digite o valor de n: \" ))\r\n\r\n print(fatorial(n))\r\n\r\ndef fatorial(num):\r\n fatorial = 1\r\n\r\n if num <= 1:\r\n if num < 0:\r\n resp = \"Fatorial apenas de números inteiros não negativos\"\r\n else:\r\n resp = \"1\"\r\n else:\r\n while num >= 1:\r\n fatorial = fatorial * num\r\n num -= 1\r\n resp = str(fatorial)\r\n return resp\r\nmain()\r\n","sub_path":"l3-exer01.py","file_name":"l3-exer01.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"545944037","text":"# PyMoBu - Python enhancement for Autodesk's MotionBuilder\r\n# Copyright (C) 2010 Scott Englert\r\n# scott@scottenglert.com\r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see .\r\n'''\r\nPyMoBu\r\n\r\nAn enhancement for Autodesk's MotionBuilder Python implementation.\r\nPyMoBu offers stronger and more user-friendly object classes and\r\nfunctions that wrap around existing MotionBuilder objects.\r\n\r\nIt is easy to convert your existing object to a PyMoBu one by\r\ncalling the 'ConvertToPyMoBu' method on that object. \r\n\r\nGoogle code project page:\r\nhttp://code.google.com/p/pymobu/\r\n\r\nSupported MB versions:\r\n2010\r\n'''\r\nimport sys\r\nfrom cStringIO import StringIO\r\n\r\nfrom pyfbsdk import FBSystem\r\nfrom pythonidelib import GenDoc\r\n\r\nfrom datatypes import insertMathClasses\r\nfrom core import *\r\nfrom components import *\r\n\r\n__version__ = '0.1'\r\n__author__ = \"Scott Englert - scott@scottenglert.com\"\r\n\r\n__MBVersion__ = FBSystem().Version\r\n\r\ninsertMathClasses()\r\n\r\n################################\r\n# set up help #\r\n################################\r\n_stdout = sys.stdout\r\ndef help(topic):\r\n '''Creates a window that displays help information'''\r\n from pyfbsdk import FBAddRegionParam, FBAttachType, FBMemo, ShowTool\r\n from pyfbsdk_additions import CreateUniqueTool\r\n \r\n win = CreateUniqueTool('Help')\r\n win.StartSizeX = 400\r\n win.StartSizeY = 500\r\n \r\n helpText = FBMemo()\r\n \r\n x = FBAddRegionParam(0, FBAttachType.kFBAttachLeft,\"\")\r\n y = FBAddRegionParam(0, FBAttachType.kFBAttachTop,\"\")\r\n w = FBAddRegionParam(0, FBAttachType.kFBAttachRight,\"\")\r\n h = FBAddRegionParam(0, FBAttachType.kFBAttachBottom,\"\")\r\n \r\n win.AddRegion(\"helpText\", \"helpText\", x, y, w, h)\r\n\r\n win.SetControl(\"helpText\", helpText)\r\n \r\n ShowTool(win)\r\n \r\n try:\r\n sys.stdout = StringIO()\r\n GenDoc(topic)\r\n helpText.Text = sys.stdout.getvalue()\r\n finally:\r\n sys.stdout = _stdout\r\n ","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"40498380","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 18 19:12:36 2018\n\n@author: Collin Wilson\n\nContains all functions used by code in lab 5, see docstrings for details\n\"\"\"\n\nfrom numpy.fft import rfft, irfft, rfftfreq\nfrom numpy import zeros, empty, arange, exp, real, pi, loadtxt\n\n\ndef rfft_lpf(data,percent):\n \"\"\" Calculates the real fast fourier transform of the data and only keeps the first \n percent(arg) of the data, setting the remaining coefficients to zero\n INPUT:\n argument data [array] is the data to be analyzed and argument percent \n [float] is percent of the coefficients to be kept\n OUTPUT:\n res [float, array] are the coefficients of the fast fourier transform of\n data, with only a certain percentage kept the rest set to zero\n \"\"\"\n \n # compute the fast fourier transform\n c_k = rfft(data)\n \n # calculate the constants needed to perform zeroing\n data_size = len(c_k) # number of coefficients\n divisor = 100 // percent # number of blocks, size percent\n \n idx = data_size//divisor # get index of last element in first percent of coefficients\n sz_to_zero = data_size - idx # size of the sub-array that will be zeroed\n c_k[idx:] = zeros(sz_to_zero) # zero the remaining percent of the data\n return c_k\n\ndef cst_lpf(data,percent):\n \"\"\" Calculates discrete cosine transform of the data and only keeps the first \n percent(arg) of the data, setting the remaining coefficients to zero\n INPUT:\n argument data [array] is the data to be analyzed and argument percent \n [float] is percent of the coefficients to be kept\n OUTPUT:\n res [float, array] are the coefficients of the dicrete cosine transform\n of data, with only a certain percentage kept the rest set to zero\n \"\"\"\n \n # compute the fast fourier transform\n c_k = dct(data)\n \n # calculate the constants needed to perform zeroing\n data_size = len(c_k) # number of coefficients\n divisor = 100 // percent # number of blocks, size percent\n \n idx = data_size//divisor # get index of last element in first percent of coefficients\n sz_to_zero = data_size - idx # size of the sub-array that will be zeroed\n c_k[idx:] = zeros(sz_to_zero) # zero the remaining percent of the data\n return c_k\n\ndef loadfft(filename, sample_rate):\n \"\"\" Loads data from the given file, calculates fast fourier transform of \n the data, the associated frquencies and returns the results\n INPUT:\n argument filename [string] is the filename to be loaded \n argument sample_rate [float] is the sample rate\n OUTPUT:\n res data [float, array] is the data\n res data_ft[float, array] are the fft coefficients\n res data_freq are the frequencies associated with the fft\n \"\"\"\n # Check that filename is a string\n if type(filename) is not str:\n raise TypeError(\"Filename argument must be a string.\")\n d = 1/sample_rate #sample frequency\n \n data = loadtxt(filename) #load data\n data_ft = rfft(data) # fast Fourier transform the data\n data_freq = rfftfreq(len(data), d)\n \n return data, data_ft, data_freq\n\n# Written by Mark Newman , June 24, 2011\n# You may use, share, or modify this file freely\n#\n######################################################################\n# 1D DCT Type-II\n\ndef dct(y):\n N = len(y)\n y2 = empty(2*N,float)\n y2[:N] = y[:]\n y2[N:] = y[::-1]\n\n c = rfft(y2)\n phi = exp(-1j*pi*arange(N)/(2*N))\n return real(phi*c[:N])\n\n\n######################################################################\n# 1D inverse DCT Type-II\n\ndef idct(a):\n N = len(a)\n c = empty(N+1,complex)\n\n phi = exp(1j*pi*arange(N)/(2*N))\n c[:N] = phi*a\n c[N] = 0.0\n return irfft(c)[:N]\n\nfrom matplotlib.transforms import (\n Bbox, TransformedBbox, blended_transform_factory)\n\nfrom mpl_toolkits.axes_grid1.inset_locator import (\n BboxPatch, BboxConnector, BboxConnectorPatch)\n#####################################################################\n\n# from Matplotlib docs https://matplotlib.org/gallery/subplots_axes_and_figures/axes_zoom_effect.html\ndef connect_bbox(bbox1, bbox2,\n loc1a, loc2a, loc1b, loc2b,\n prop_lines, prop_patches=None):\n if prop_patches is None:\n prop_patches = {\n **prop_lines,\n \"alpha\": prop_lines.get(\"alpha\", 1) * 0.2,\n }\n\n c1 = BboxConnector(bbox1, bbox2, loc1=loc1a, loc2=loc2a, **prop_lines)\n c1.set_clip_on(False)\n c2 = BboxConnector(bbox1, bbox2, loc1=loc1b, loc2=loc2b, **prop_lines)\n c2.set_clip_on(False)\n\n bbox_patch1 = BboxPatch(bbox1, **prop_patches)\n bbox_patch2 = BboxPatch(bbox2, **prop_patches)\n\n p = BboxConnectorPatch(bbox1, bbox2,\n # loc1a=3, loc2a=2, loc1b=4, loc2b=1,\n loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,\n **prop_patches)\n p.set_clip_on(False)\n\n return c1, c2, bbox_patch1, bbox_patch2, p\n\n\ndef zoom_effect01(ax1, ax2, xmin, xmax, **kwargs):\n \"\"\"\n ax1 : the main axes\n ax1 : the zoomed axes\n (xmin,xmax) : the limits of the colored area in both plot axes.\n\n connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will\n be marked. The keywords parameters will be used ti create\n patches.\n\n \"\"\"\n\n trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)\n trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)\n\n bbox = Bbox.from_extents(xmin, 0, xmax, 1)\n\n mybbox1 = TransformedBbox(bbox, trans1)\n mybbox2 = TransformedBbox(bbox, trans2)\n\n prop_patches = {**kwargs, \"ec\": \"none\", \"alpha\": 0.2}\n\n c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(\n mybbox1, mybbox2,\n loc1a=3, loc2a=2, loc1b=4, loc2b=1,\n prop_lines=kwargs, prop_patches=prop_patches)\n\n ax1.add_patch(bbox_patch1)\n ax2.add_patch(bbox_patch2)\n ax2.add_patch(c1)\n ax2.add_patch(c2)\n ax2.add_patch(p)\n\n return c1, c2, bbox_patch1, bbox_patch2, p\n\n\ndef zoom_effect02(ax1, ax2, **kwargs):\n \"\"\"\n ax1 : the main axes\n ax1 : the zoomed axes\n\n Similar to zoom_effect01. The xmin & xmax will be taken from the\n ax1.viewLim.\n \"\"\"\n\n tt = ax1.transScale + (ax1.transLimits + ax2.transAxes)\n trans = blended_transform_factory(ax2.transData, tt)\n\n mybbox1 = ax1.bbox\n mybbox2 = TransformedBbox(ax1.viewLim, trans)\n\n prop_patches = {**kwargs, \"ec\": \"none\", \"alpha\": 0.2}\n\n c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(\n mybbox1, mybbox2,\n loc1a=3, loc2a=2, loc1b=4, loc2b=1,\n prop_lines=kwargs, prop_patches=prop_patches)\n\n ax1.add_patch(bbox_patch1)\n ax2.add_patch(bbox_patch2)\n ax2.add_patch(c1)\n ax2.add_patch(c2)\n ax2.add_patch(p)\n\n return c1, c2, bbox_patch1, bbox_patch2, p\n","sub_path":"Lab05/functions_lab05.py","file_name":"functions_lab05.py","file_ext":"py","file_size_in_byte":6885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"302062359","text":"import store_db\nimport pandas as pd\nimport data_cleansing as dc\n\n\nclass Jobs:\n def __init__(self):\n self.filepath = './data/jobs.csv'\n self.dc = dc.DataPrep(self.filepath)\n self.df = self.load_data_frame()\n self.features = []\n\n def load_data_frame(self):\n if not self.dc.check_clean_file():\n self.prepare_clean_ds(self.dc)\n self.dc = dc.DataPrep(self.filepath)\n\n # Load the clean DS\n df = self.dc.df\n\n # Test the dataset for inconsistencies\n df = self.test_and_prep_df(df)\n\n return df.add_suffix('_jbs')\n\n def prepare_clean_ds(self, dc):\n # Convert datetime columns to date format\n dc.convert_to_datetime('last_published_at')\n dc.convert_to_datetime('closed_at')\n dc.df['last_published_at_wkd'] = dc.df['last_published_at'].dt.dayofweek\n dc.df['closed_at_wkd'] = dc.df['closed_at'].dt.dayofweek\n\n sqlite = store_db.SQLite()\n dc.df.to_sql('jobs', con=sqlite.create_connection(), if_exists='replace', index=False)\n\n dc.generate_clean_csv()\n\n def test_and_prep_df(self, df):\n\n return df\n\n def get_average_offer_open_days(self):\n df = self.df[self.df['closed_at_jbs'].notnull() & self.df['last_published_at_jbs'].notnull()].reset_index()\n\n df['closed_at_jbs'] = pd.to_datetime(df['closed_at_jbs'])\n df['last_published_at_jbs'] = pd.to_datetime(df['last_published_at_jbs'])\n\n df['day_diff_jbs'] = (df['closed_at_jbs'] - df['last_published_at_jbs']).dt.days\n return df['day_diff_jbs'].median()\n","sub_path":"jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"647524767","text":"\nimport csv\nimport matplotlib.pyplot as plt\nng = 0\ngybe = 0\nng_months = {\n \"Jul\": 0, # these should match how the date was outputted by: https://mainstream.ghan.nl/export.html\n \"Aug\": 0,\n \"Sep\": 0,\n \"Oct\": 0,\n \"Nov\": 0,\n \"Dec\": 0,\n \"Jan\": 0,\n}\ng_list = []\nn_list = []\n# csv should have artist in column 1 and date format w/3 letter month in column 5\nwith open('test8.csv', newline='', encoding=\"utf-8\") as f:\n reader = csv.reader(f)\n for row in reader:\n if row.__contains__(\"Godspeed You! Black Emperor\"):\n print(row)\n for i in ng_months:\n if row[4].__contains__(i):\n ng_months[i] += 1\nfor key, value in ng_months.items():\n temp = [key, value]\n g_list.append(temp[1])\n\n\nwith open('test8.csv', newline='', encoding=\"utf-8\") as f:\n reader = csv.reader(f)\n for row in reader:\n if row.__contains__(\"Nana Grizol\"):\n for i in ng_months:\n if row[4].__contains__(i):\n ng_months[i] += 1\nfor key, value in ng_months.items():\n temp = [key, value]\n n_list.append(temp[1])\n\nprint(g_list)\nplt.plot(g_list)\nplt.plot(n_list)\nplt.legend([\"gybe plays\", \"nana grizol plays\"])\nplt.title(\"plays by month\")\nplt.ylabel(\"plays\")\nplt.xlabel(\"months since start of account\")\nplt.show()\n\nimport csv\nimport matplotlib.pyplot as plt\nmonths = [\"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\", \"Jan\"]\nng_months = dict()\ngybe_months = dict()\nfor month in months:\n ng_months[month] = 0\n gybe_months[month] = 0\n# csv should have artist in some columng and date format w/3 letter month in column 2\nwith open('test8.csv', newline='', encoding=\"utf-8\") as f:\n reader = csv.reader(f)\n for row in reader:\n if row.__contains__(\"Godspeed You! Black Emperor\"):\n print(row)\n for i in gybe_months:\n if row[-1].__contains__(i):\n gybe_months[i] += 1\n if row.__contains__(\"Nana Grizol\"):\n for i in ng_months:\n if row[-1].__contains__(i):\n ng_months[i] += 1\n\nplt.title(\"Plays by month\")\nplt.ylabel(\"Plays\")\nplt.xlabel(\"Month\")\nplt.plot(ng_months.keys(), ng_months.values(), label='Nana Grizol')\nplt.plot(gybe_months.keys(), gybe_months.values(), label=\"Godspeed You! Black Emperor\")\nplt.legend()\nplt.show()\n","sub_path":"last3.py","file_name":"last3.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"206370344","text":"#! /usr/bin/env python3\n\n# MODIFIED TO WORK WITH 3.0.0 eDo w/o gripper\n\nimport rospy\nfrom edo_core_msgs.msg import MachineState\nfrom edo_core_msgs.msg import JointInit\nfrom edo_core_msgs.msg import JointReset\nfrom edo_core_msgs.msg import MovementCommand\nfrom edo_core_msgs.msg import JointCalibration\nfrom edo_core_msgs.msg import MovementFeedback\nfrom edo_core_msgs.msg import BrakesCheckAck\n\n# sudo -H pip3 install getkey on 16.04\n# pip install getkey on 18.04\nfrom getkey import getkey, keys\n\n\nclass EdoStates(object):\n NUMBER_OF_JOINTS = 6 # The seventh joint was probably the gripper\n\n JOG_SPEED_MIN = 0.11\n JOG_SPEED_MAX = 0.99\n CS_DISCONNECTED = -2\n CS_UNKNOWN = -1\n CS_INIT = 0 # Initial state\n CS_NOT_CALIBRATED = 1 # uncalibrated machine\n CS_CALIBRATED = 2 # calibrated machine\n CS_MOVE = 3 # machine in execution of a move\n CS_JOG = 4 # machine running a jog\n CS_MACHINE_ERROR = 5 # machine in error status and waiting for a restart\n CS_BRAKED = 6 # brake active, no motor power supply\n BRAKES_CHECK = 7 # check state for the brakes: brakes active and motor on!\n MOVE_TEST = 8 # move test for brakes check\n CS_INIT_DISCOVER = 254 # UI internal state if we are initializing joints\n CS_COMMAND = 255 # state machine busy keep previous state, temporary status when there is a command running\n\n\n def __init__(self, current_state, opcode):\n self.edo_current_state = current_state\n self._edo_opcode_previous = opcode\n self._edo_current_state_previous = current_state\n self.edo_opcode = opcode\n self._edo_jog_speed = 0.5\n self.send_first_step_bool = False # select 6-axis configuration\n self.send_second_step_bool = False # disconnect the brakes\n self.send_third_step_bool = False # calibration process will start\n self._current_joint = 0\n self._sent_next_movement_command_bool = False\n\n self._joint_init_command_pub = None\n self._joint_reset_command_pub = None\n self._jog_command_pub = None\n self._joint_calibration_command_pub = None\n self._movement_command_pub = None\n\n self.reselect_joints_bool = False\n\n self.disengage_brakes_timer = None\n self.disengage_brakes_bool = False\n self.read_input_bool = False\n\n def callback(self, msg):\n self.edo_current_state = msg.current_state\n self.edo_opcode = msg.opcode\n if self.edo_current_state != self._edo_current_state_previous or self.edo_opcode != self._edo_opcode_previous:\n\n rospy.loginfo(\"Current machine state: %s (%d), opcode %d\" % (self.get_current_code_string(),\n self.edo_current_state,\n self.edo_opcode))\n self._edo_current_state_previous = self.edo_current_state\n self._edo_opcode_previous = self.edo_opcode\n\n # hack: input is blocking main while lopp ...\n if self.edo_current_state == self.CS_BRAKED and self.edo_opcode == 64:\n rospy.loginfo(\"Disengage emergency brake and press Enter to continue\")\n\n if self.edo_current_state == self.CS_MACHINE_ERROR:\n rospy.logerr(\"Robot is in error state, terminating this node!\")\n rospy.signal_shutdown(\"edo error\")\n\n def move_ack_callback(self, msg):\n if msg.type == 0:\n pass\n elif msg.type == 1:\n pass\n elif msg.type == 2:\n rospy.loginfo(\"FB: Command executed, send next one if available\")\n self._sent_next_movement_command_bool = True\n elif msg.type == -1:\n rospy.logerr(\"FB Error, msg.data: %d, \" % msg.data)\n else:\n rospy.logerr(\"Feedback from a robot is not specified!!!: msg.type: $d, msg.data: %d\" % msg.type, msg.data)\n # rospy.loginfo(msg)\n\n def get_current_code_string(self):\n if self.edo_current_state == self.CS_DISCONNECTED:\n return \"DISCONNECTED\"\n elif self.edo_current_state == self.CS_UNKNOWN:\n return \"UNKNOWN\"\n elif self.edo_current_state == self.CS_INIT:\n return \"INIT\"\n elif self.edo_current_state == self.CS_NOT_CALIBRATED:\n return \"NOT_CALIBRATED\"\n elif self.edo_current_state == self.CS_CALIBRATED:\n return \"CALIBRATED\"\n elif self.edo_current_state == self.CS_MOVE:\n return \"MOVE\"\n elif self.edo_current_state == self.CS_JOG:\n return \"JOG\"\n elif self.edo_current_state == self.CS_MACHINE_ERROR:\n return \"MACHINE_ERROR\"\n elif self.edo_current_state == self.CS_BRAKED:\n return \"BRAKED\"\n elif self.edo_current_state == self.CS_INIT_DISCOVER:\n return \"INIT_DISCOVER\"\n elif self.edo_current_state == self.CS_COMMAND:\n return \"ROBOT IS BUSY\"\n\n def send_movement_command_init(self, msg):\n self._sent_next_movement_command_bool = False\n self._movement_command_pub.publish(msg)\n\n def send_movement_command(self, msg):\n while not self._sent_next_movement_command_bool and not rospy.is_shutdown():\n rospy.sleep(0.01)\n\n self._sent_next_movement_command_bool = False\n self._movement_command_pub.publish(msg)\n\n def select_6_axis_with_gripper_edo(self):\n rospy.loginfo(\"Trying to select 6-axis robot with a gripper...\")\n # selecting 6 axis robot\n msg_ji = JointInit()\n # this code is from ros.service.ts\n msg_ji.mode = 0\n msg_ji.joints_mask = (1 << self.NUMBER_OF_JOINTS) - 1 # 127\n msg_ji.reduction_factor = 0.0\n # rospy.loginfo(msg_ji)\n\n # TODO before sending the message get number of subscribers?\n\n self._joint_init_command_pub.publish(msg_ji) # /bridge_init\n rospy.loginfo(\"Message sent, 6-axis configuration was selected\")\n\n def disengage_brakes(self):\n rospy.loginfo(\"Trying to disengage brakes\")\n msg_jr = JointReset()\n msg_jr.joints_mask = (1 << self.NUMBER_OF_JOINTS) - 1\n msg_jr.disengage_steps = 2000\n msg_jr.disengage_offset = 3.5\n self._joint_reset_command_pub.publish(msg_jr) # /bridge_jnt_reset\n rospy.loginfo(\"Brakes should be disengaged...\")\n\n def disengage_brakes_callback(self, timer_event):\n # TODO check what I can do with parameter event\n self.disengage_brakes()\n\n def create_jog_joint_command_message(self, sign):\n msg_mc = MovementCommand()\n msg_mc.move_command = 74\n msg_mc.move_type = 74\n msg_mc.ovr = 100\n msg_mc.target.data_type = 74\n msg_mc.target.joints_mask = 127\n msg_mc.target.joints_data = [0.0] * 10\n msg_mc.target.joints_data[self._current_joint] = sign * self._edo_jog_speed\n return msg_mc\n\n def create_jog_cartesian_command_message(self, sign):\n msg_mc = MovementCommand()\n msg_mc.move_command = 74\n msg_mc.move_type = 76\n msg_mc.ovr = 100\n # last joint/gripper has a diffrerent message\n if self._current_joint == 6:\n msg_mc.target.data_type = 88\n msg_mc.target.joints_mask = 127\n msg_mc.target.joints_data = [0.0] * 10\n msg_mc.target.joints_data[self._current_joint] = sign * self._edo_jog_speed\n else:\n msg_mc.target.data_type = 80\n if self._current_joint == 0:\n msg_mc.target.cartesian_data.x = sign * self._edo_jog_speed\n elif self._current_joint == 1:\n msg_mc.target.cartesian_data.a = sign * self._edo_jog_speed\n elif self._current_joint == 2:\n msg_mc.target.cartesian_data.y = sign * self._edo_jog_speed\n elif self._current_joint == 3:\n msg_mc.target.cartesian_data.e = sign * self._edo_jog_speed\n elif self._current_joint == 4:\n msg_mc.target.cartesian_data.z = sign * self._edo_jog_speed\n elif self._current_joint == 5:\n msg_mc.target.cartesian_data.r = sign * self._edo_jog_speed\n msg_mc.target.joints_mask = 127\n return msg_mc\n\n def calibration(self):\n # calibrating just first 6 joints!!!\n self._current_joint = 0 # always start calibration procedure with first joint\n\n rospy.loginfo(\"Entering jog/calibration loop\")\n rospy.loginfo(\" Use up/down arrows to increase/decrease jog speed\")\n rospy.loginfo(\" Use left/right arrows to jog joint\")\n rospy.loginfo(\" Use Enter to calibrate current joint and switch to next one\")\n rospy.loginfo(\"Calibrating joint %d\", self._current_joint + 1)\n\n while not rospy.is_shutdown():\n key = getkey()\n if key == keys.UP:\n if self._edo_jog_speed < self.JOG_SPEED_MAX:\n self._edo_jog_speed += 0.1\n rospy.loginfo(\"Jog speed: %.1f\", self._edo_jog_speed)\n elif key == keys.DOWN:\n if self._edo_jog_speed > self.JOG_SPEED_MIN:\n self._edo_jog_speed -= 0.1\n rospy.loginfo(\"Jog speed: %.1f\", self._edo_jog_speed)\n elif key == keys.RIGHT:\n self._jog_command_pub.publish(self.create_jog_joint_command_message(1))\n elif key == keys.LEFT:\n self._jog_command_pub.publish(self.create_jog_joint_command_message(-1))\n elif key == keys.PLUS:\n self._current_joint = (self._current_joint + 1) % self.NUMBER_OF_JOINTS\n rospy.loginfo(\"Calibrating joint %d\", self._current_joint + 1)\n elif key == keys.MINUS:\n self._current_joint = (self._current_joint - 1) % self.NUMBER_OF_JOINTS\n rospy.loginfo(\"Calibrating joint %d\", self._current_joint + 1)\n elif key == keys.ENTER:\n if self._current_joint < 0 or self._current_joint > self.NUMBER_OF_JOINTS-1:\n rospy.logerr(\"Wrong number of joint %d\", self._current_joint)\n break\n msg_jc = JointCalibration()\n msg_jc.joints_mask = 1 << self._current_joint\n self._joint_calibration_command_pub.publish(msg_jc)\n\n # increase joint number or/and quit the calibration procedure\n self._current_joint += 1\n\n # if self._current_joint >= self.NUMBER_OF_JOINTS-1:\n if self._current_joint >= self.NUMBER_OF_JOINTS - 1: # calibrate sixth joint configuration w/o gripper\n self._current_joint = 0\n rospy.loginfo(\"Calibration completed, exiting jog loop\")\n break\n else:\n rospy.loginfo(\"Calibrating joint %d\", self._current_joint + 1)\n elif key == keys.ESC:\n rospy.loginfo(\"Calibration NOT finished for all joints, exiting jog loop\")\n break\n else:\n rospy.loginfo(\"Wrong button was pressed\")\n\n def jog(self):\n\n rospy.loginfo(\"Entering jog loop\")\n rospy.loginfo(\" Use up/down arrows to increase/decrease jog speed\")\n rospy.loginfo(\" Use left/right arrows to jog joint\")\n rospy.loginfo(\" Use +/- to increase/decrease joint number\")\n rospy.loginfo(\"Jogging joint %d\", self._current_joint + 1)\n\n while not rospy.is_shutdown():\n key = getkey()\n if key == keys.UP:\n if self._edo_jog_speed < self.JOG_SPEED_MAX:\n self._edo_jog_speed += 0.1\n rospy.loginfo(\"Jog speed: %.1f\", self._edo_jog_speed)\n elif key == keys.DOWN:\n if self._edo_jog_speed > self.JOG_SPEED_MIN:\n self._edo_jog_speed -= 0.1\n rospy.loginfo(\"Jog speed: %.1f\", self._edo_jog_speed)\n elif key == keys.RIGHT:\n self._jog_command_pub.publish(self.create_jog_joint_command_message(1))\n elif key == keys.LEFT:\n self._jog_command_pub.publish(self.create_jog_joint_command_message(-1))\n elif key == keys.PLUS:\n self._current_joint = (self._current_joint + 1) % self.NUMBER_OF_JOINTS\n rospy.loginfo(\"Jogging joint %d\", self._current_joint + 1)\n elif key == keys.MINUS:\n self._current_joint = (self._current_joint - 1) % self.NUMBER_OF_JOINTS\n rospy.loginfo(\"Jogging joint %d\", self._current_joint + 1)\n elif key == keys.ESC:\n rospy.loginfo(\"Exiting joint jog loop\")\n break\n else:\n rospy.loginfo(\"Wrong button was presed\")\n\n def jog_cartesian(self):\n\n array_of_cartesian = ['X-axis', 'Roll', 'Y-axis', 'Pitch', 'Z-axis', 'not exactly a Yaw', 'Gripper']\n\n rospy.loginfo(\"Entering jog Cartesian loop\")\n rospy.loginfo(\" Use up/down arrows to increase/decrease jog speed\")\n rospy.loginfo(\" Use left/right arrows to jog cartesian\")\n rospy.loginfo(\" Use +/- to select next/previus cartesian part\")\n rospy.loginfo(\" ['X-axis', 'Roll', 'Y-axis', 'Pitch', 'Z-axis', 'not exactly a Yaw', 'Gripper']\")\n rospy.loginfo(\"Jogging cartesian: %s\", array_of_cartesian[self._current_joint])\n\n while not rospy.is_shutdown():\n key = getkey()\n if key == keys.UP:\n if self._edo_jog_speed < self.JOG_SPEED_MAX:\n self._edo_jog_speed += 0.1\n rospy.loginfo(\"Jog speed: %.1f\", self._edo_jog_speed)\n elif key == keys.DOWN:\n if self._edo_jog_speed > self.JOG_SPEED_MIN:\n self._edo_jog_speed -= 0.1\n rospy.loginfo(\"Jog speed: %.1f\", self._edo_jog_speed)\n elif key == keys.RIGHT:\n pass\n self._jog_command_pub.publish(self.create_jog_cartesian_command_message(1))\n elif key == keys.LEFT:\n pass\n self._jog_command_pub.publish(self.create_jog_cartesian_command_message(-1))\n elif key == keys.PLUS:\n self._current_joint = (self._current_joint + 1) % self.NUMBER_OF_JOINTS\n rospy.loginfo(\"Jogging cartesian: %s\", array_of_cartesian[self._current_joint])\n elif key == keys.MINUS:\n self._current_joint = (self._current_joint - 1) % self.NUMBER_OF_JOINTS\n rospy.loginfo(\"Jogging cartesian: %s\", array_of_cartesian[self._current_joint])\n elif key == keys.ESC:\n rospy.loginfo(\"Exiting cartesian jog loop\")\n break\n else:\n rospy.loginfo(\"Wrong button was presed\")\n\n def move_home(self):\n rospy.loginfo(\"Sending home position\")\n\n # send reset command\n msg_mc = MovementCommand()\n msg_mc.move_command = 67\n self.send_movement_command_init(msg_mc)\n\n msg_mc = MovementCommand()\n msg_mc.move_command = 77\n msg_mc.move_type = 74\n msg_mc.ovr = 50\n msg_mc.target.data_type = 74\n msg_mc.target.joints_mask = (1 << self.NUMBER_OF_JOINTS) - 1\n msg_mc.target.joints_data = [0.0] * 7\n\n self.send_movement_command(msg_mc)\n rospy.loginfo(\"Home position should be soon reached\")\n\n def move_joint(self, joint_values, joint_speed):\n\n msg_mc = MovementCommand()\n msg_mc.move_command = 77\n msg_mc.move_type = 74\n msg_mc.ovr = joint_speed\n msg_mc.delay = 255\n msg_mc.target.data_type = 74\n msg_mc.target.joints_mask = 63\n msg_mc.target.joints_data = [0.0] * 6\n\n # the first six joints are in degress\n msg_mc.target.joints_data[0] = joint_values[0]\n msg_mc.target.joints_data[1] = joint_values[1]\n msg_mc.target.joints_data[2] = joint_values[2]\n msg_mc.target.joints_data[3] = joint_values[3]\n msg_mc.target.joints_data[4] = joint_values[4]\n msg_mc.target.joints_data[5] = joint_values[5]\n # joint 7 is in milimeters\n #msg_mc.target.joints_data[6] = joint_values[6]\n\n self.send_movement_command(msg_mc)\n\n while not self._sent_next_movement_command_bool and not rospy.is_shutdown():\n rospy.sleep(0.01)\n rospy.loginfo(\"Move joint should be completed\")\n\n def execute_move_joint(self):\n rospy.loginfo(\"Setting up a joint movement:\")\n try:\n repeat_number = int(input('Write number of repetions cycles: '))\n except ValueError:\n rospy.loginfo(\"Not a number\")\n rospy.loginfo(\"Exiting to a main loop.\")\n return\n\n try:\n number_of_points = int(input('Write number of different points: '))\n except ValueError:\n rospy.loginfo(\"Not a number\")\n rospy.loginfo(\"Exiting to a main loop.\")\n return\n\n list_of_poses = []\n rospy.loginfo(\"Input: j1 j2 j3 j4 j5 j6\")\n rospy.loginfo(\"Joint data in degrees\")\n\n for i in range(0, number_of_points):\n try:\n j1, j2, j3, j4, j5, j6 = [int(x) for x in raw_input(\"Input: \").split()]\n except ValueError:\n rospy.loginfo(\"Not a valid angle...\")\n rospy.loginfo(\"Exiting to a main loop.\")\n return\n list_of_poses.append([j1, j2, j3, j4, j5, j6])\n\n for item in list_of_poses:\n if len(item) != self.NUMBER_OF_JOINTS:\n rospy.logerr(\"To many or not enough joint values for a robot\")\n rospy.loginfo(\"Exiting to a main loop.\")\n return\n try:\n joint_speed = int(input('Write joint speed [0,..,100]: '))\n except ValueError:\n rospy.loginfo(\"Not a number\")\n rospy.loginfo(\"Exiting to a main loop.\")\n return\n joint_speed %= 100\n\n # send reset message\n msg_mc = MovementCommand()\n msg_mc.move_command = 67\n self.send_movement_command_init(msg_mc)\n\n # send all the data\n for i in range(0, repeat_number):\n for j in range(0, number_of_points):\n if not rospy.is_shutdown():\n self.move_joint(list_of_poses[j], joint_speed)\n rospy.loginfo(list_of_poses[j])\n\n if rospy.is_shutdown():\n rospy.loginfo(\"Terminating an execution loop...\")\n rospy.loginfo(\"Exiting to a main loop.\")\n return\n\n rospy.loginfo(\"Joint movement was successful.\")\n rospy.loginfo(\"Exiting to a main loop.\")\n return\n\n\ndef main():\n rospy.loginfo(\"Main loop has started\")\n\n rospy.init_node('python_configuration_node', anonymous=True)\n # True ensures that your node has a unique name by adding random numbers to the end of NAME\n\n states = EdoStates(-1, -1)\n\n rospy.Subscriber(\"/machine_state\", MachineState, states.callback)\n # ros::spin() will enter a loop, pumping callbacks.\n # rospy.spin() # this is replaced with a loop\n\n joint_init_command_pub = rospy.Publisher('/bridge_init', JointInit, queue_size=10, latch=True)\n states._joint_init_command_pub = joint_init_command_pub\n\n joint_reset_command_pub = rospy.Publisher('/bridge_jnt_reset', JointReset, queue_size=10, latch=True)\n states._joint_reset_command_pub = joint_reset_command_pub\n\n jog_command_pub = rospy.Publisher('/bridge_jog', MovementCommand, queue_size=10, latch=True)\n states._jog_command_pub = jog_command_pub\n\n joint_calibration_command_pub = rospy.Publisher('/bridge_jnt_calib', JointCalibration, queue_size=10, latch=True)\n states._joint_calibration_command_pub = joint_calibration_command_pub\n\n states._movement_command_pub = rospy.Publisher('/bridge_move', MovementCommand, queue_size=10, latch=True)\n\n rospy.Subscriber('/machine_movement_ack', MovementFeedback, states.move_ack_callback)\n\n rospy.Subscriber('/brakes_ckeck_ack', BrakesCheckAck, states.brakes_check_ack_callback)\n\n rate = rospy.Rate(30) # 30hz\n\n while not rospy.is_shutdown():\n\n # TODO move this if statements to callback function\n if states.edo_current_state == states.CS_INIT and states.edo_opcode == 0 and not states.send_first_step_bool:\n # I should not come back to this state\n states.send_first_step_bool = True\n states.select_6_axis_with_gripper_edo()\n\n if states.edo_current_state == states.CS_BRAKED and states.edo_opcode == 72 and not states.send_second_step_bool:\n # disengage brakes to uncalibrated robot\n states.send_second_step_bool = True\n states.disengage_brakes()\n\n if states.edo_current_state == states.CS_INIT and \\\n (states.edo_opcode == 64 or states.edo_opcode == 72) and not states.reselect_joints_bool:\n # according to tablet, select 7 joints again and start from scratch...\n states.reselect_joints_bool = True\n states.select_6_axis_with_gripper_edo()\n\n if states.edo_current_state == states.CS_NOT_CALIBRATED and states.edo_opcode == 8 and not states.send_third_step_bool:\n rospy.loginfo(\"Starting calibration jog loop\")\n states.calibration()\n states.send_third_step_bool = True\n states.read_input_bool = True\n\n if states.edo_current_state == states.CS_BRAKED and states.edo_opcode == 64:\n # disengage brakes to calibrated robot on every two seconds until emergency button is released\n states.read_input_bool = False\n if not states.disengage_brakes_bool:\n rospy.loginfo(\"Setting up release breakes timer\")\n states.disengage_brakes_timer = rospy.Timer(rospy.Duration(2), states.disengage_brakes_callback)\n states.disengage_brakes_bool = True\n\n if states.edo_current_state == states.CS_CALIBRATED and states.edo_opcode == 0:\n if states.disengage_brakes_bool:\n rospy.loginfo(\"Robot is active again, disabling release breakes timer\")\n states.disengage_brakes_timer.shutdown()\n states.disengage_brakes_bool = False\n states.read_input_bool = True\n\n # rospy.loginfo(\"Waiting a key before\")\n if states.read_input_bool:\n rospy.loginfo(\"Press j to start jogging in joint space\")\n rospy.loginfo(\"Press c to start jogging in cartesian space\")\n rospy.loginfo(\"Press h to send robot to home position\")\n rospy.loginfo(\"Press r to restart calibration\")\n rospy.loginfo(\"Press f to start simple joint movement\")\n rospy.loginfo(\"Press ESC to quit the program\")\n key = getkey(blocking=True)\n if key == keys.J:\n states.jog()\n elif key == keys.C:\n states.jog_cartesian()\n elif key == keys.H:\n states.move_home()\n elif key == keys.R:\n states.calibration()\n elif key == keys.F:\n states.execute_move_joint()\n elif key == keys.ESC:\n rospy.loginfo(\"Exiting/Killing the main loop/program\")\n rospy.signal_shutdown(\"setup_edo.py shutdown\")\n\n rate.sleep()\n # rospy.loginfo(\"loop\")\n\n\nif __name__ == '__main__':\n\n # rospy.sleep() and rospy.Rate.sleep() can thrown exception\n try:\n main()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"setup_edo.py","file_name":"setup_edo.py","file_ext":"py","file_size_in_byte":23623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"397521897","text":"import pandas as pd\nimport ggplot as gg\nfrom ggplot import aes\nimport statsmodels.formula.api as smf\nimport statsmodels as sm\n\nfilepath = \"Dropbox/MSBA/CommunicatingData/1.FirstDayAssignment/1_FDA_AdData.csv\"\ndf = pd.read_csv(filepath)\n\n#transformations used for analysis later on\ndf['Sales'] = df['Sales'] * 1000\n\n#not in appendix - shows sums of each column\ndf['AdSpending'] = df[[\"TV\",\"Radio\",\"Newspaper\"]].sum(axis=1)\n\n#Table 2: Summary Statistics\ndf[[\"TV\",\"Radio\",\"Newspaper\",\"AdSpending\"]].describe()\n\n#Table 3: Sums of Advertising Spending\ndf[[\"TV\",\"Radio\",\"Newspaper\",\"AdSpending\",\"Market\"]].groupby([\"Market\"]).sum()\n\n#Figure 1: Histograms of Sales and Advertising Spending\ngg.ggplot(df,aes(x='Sales')) +\\\n geom_histogram() +\\\n facet_grid('Market')\ngg.ggplot(df,aes(x='AdSpending')) +\\\n geom_histogram() +\\\n facet_grid('Market')\n\n#reshape df so each row is a single \ndfMelt = pd.melt(df, id_vars=['Market','Sales'], value_vars=['TV','Radio','Newspaper'])\ndfMelt['Sales'] = dfMelt['Sales']/1000\n\n#plot\ngg.ggplot(dfMelt,gg.aes(x='value',y='Sales',color='Market')) +\\\n gg.geom_point() +\\\n gg.facet_grid('Market','variable',scales=\"free\") +\\\n gg.stat_smooth(color=\"black\",se=False)\n\nmodRural = smf.ols('Sales ~ TV + Radio + Newspaper', data=df[df.Market == \"Rural\"])\nresRural = mod.fit()\nmodSubUrban = smf.ols('Sales ~ TV + Radio + Newspaper', data=df[df.Market == \"SubUrban\"])\nresSubUrban = mod.fit()\nmodUrban = smf.ols('Sales ~ TV + Radio + Newspaper', data=df[df.Market == \"Urban\"])\nresUrban = mod.fit()\n\ndfoutput = sm.summary_col([resRural,resSubUrban,resUrban],stars=True)\nprint(dfoutput)\n","sub_path":"1.FirstDayAssignment/FDA_insights.py","file_name":"FDA_insights.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"122186402","text":"\"\"\" MFI Indicator\n\"\"\"\n\nimport math\n\nimport pandas\nfrom talib import abstract\n\nfrom analyzers.utils import IndicatorUtils\n\n\nclass TD(IndicatorUtils):\n def analyze(self, historical_data, period_count=14,\n signal=['td'], hot_thresh=None, cold_thresh=None):\n \"\"\"Performs MFI analysis on the historical data\n\n Args:\n historical_data (list): A matrix of historical OHCLV data.\n period_count (int, optional): Defaults to 14. The number of data points to consider for\n our MFI.\n signal (list, optional): Defaults to mfi. The indicator line to check hot/cold\n against.\n hot_thresh (float, optional): Defaults to None. The threshold at which this might be\n good to purchase.\n cold_thresh (float, optional): Defaults to None. The threshold at which this might be\n good to sell.\n\n Returns:\n pandas.DataFrame: A dataframe containing the indicators and hot/cold values.\n \"\"\"\n\n dataframe = self.convert_to_dataframe(historical_data)\n td_values = self.td_sequential(dataframe)\n td_values.dropna(how='all', inplace=True)\n td_values.rename(columns={0: 'td'}, inplace=True)\n\n if td_values[signal[0]].shape[0]:\n td_values['is_hot'] = td_values[signal[0]] < hot_thresh\n td_values['is_cold'] = td_values[signal[0]] > cold_thresh\n return td_values\n\n\n def td_sequential(self, dataframe):\n \"\"\"\n TD Sequential\n :param dataframe: dataframe\n :return: TD Sequential:values -9 to +9\n \"\"\"\n \"\"\"\n TD Sequential\n \"\"\"\n\n # Copy DF\n df = dataframe.copy()\n\n condv = (df['volume'] > 0)\n cond1 = (df['close'] > df['close'].shift(4))\n cond2 = (df['close'] < df['close'].shift(4))\n\n df['cond_tdb_a'] = (df.groupby((((cond1)[condv])).cumsum()).cumcount() % 10 == 0).cumsum()\n df['cond_tds_a'] = (df.groupby((((cond2)[condv])).cumsum()).cumcount() % 10 == 0).cumsum()\n df['cond_tdb_b'] = (df.groupby((((cond1)[condv])).cumsum()).cumcount() % 10 != 0).cumsum()\n df['cond_tds_b'] = (df.groupby((((cond2)[condv])).cumsum()).cumcount() % 10 != 0).cumsum()\n\n df['tdb_a'] = df.groupby(\n\n df['cond_tdb_a']\n\n ).cumcount()\n df['tds_a'] = df.groupby(\n\n df['cond_tds_a']\n\n ).cumcount()\n\n df['tdb_b'] = df.groupby(\n\n df['cond_tdb_b']\n\n ).cumcount()\n df['tds_b'] = df.groupby(\n\n df['cond_tds_b']\n\n ).cumcount()\n\n df['td'] = df['tds_a'] - df['tdb_a']\n df['td'] = df.apply((lambda x: x['tdb_b'] % 9 if x['tdb_b'] > 9 else x['td']), axis=1)\n df['td'] = df.apply((lambda x: (x['tds_b'] % 9) * -1 if x['tds_b'] > 9 else x['td']), axis=1)\n\n return df\n","sub_path":"app/analyzers/indicators/td.py","file_name":"td.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"613026803","text":"import timeit\nfrom functools import reduce\n\nkilian_setup = '''\nfrom __main__ import kilian_day13\n'''\n\ndef kilian_day13(arr):\n i = 1\n while i < len(arr):\n if (arr[i] == 'NORTH') and (arr[i - 1] == 'SOUTH'):\n del arr[i-1]\n del arr[i-1]\n elif (arr[i] == 'SOUTH') and (arr[i - 1] == 'NORTH'):\n del arr[i-1]\n del arr[i-1]\n elif (arr[i] == 'WEST') and (arr[i - 1] == 'EAST'):\n del arr[i-1]\n del arr[i-1]\n elif (arr[i] == 'EAST') and (arr[i - 1] == 'WEST'):\n del arr[i-1]\n del arr[i-1]\n elif i == len(arr) - 1:\n break\n elif (arr[i] == 'NORTH') and (arr[i + 1] == 'SOUTH'):\n del arr[i]\n del arr[i]\n elif (arr[i] == 'SOUTH') and (arr[i + 1] == 'NORTH'):\n del arr[i]\n del arr[i]\n elif (arr[i] == 'WEST') and (arr[i + 1] == 'EAST'):\n del arr[i]\n del arr[i]\n elif (arr[i] == 'EAST') and (arr[i + 1] == 'WEST'):\n del arr[i]\n del arr[i]\n else:\n i += 1\n return arr\n\nTEST_CODE_kilian = '''\nresult = kilian_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nakash_karan_setup = '''\nfrom __main__ import akash_karan_day13\n'''\n\ndef akash_karan_day13(arr):\n di={\"NORTH\":1, \"WEST\":-1j, \"SOUTH\":-1, \"EAST\":1j}\n l,t1=[],0\n for i in arr:\n if (t1+di[i]==0):\n l.pop() #if north-south or east-west comes one after another\n if not(len(l)):t1=0 #then pop the prev and dont add the current\n else: t1=di[l[-1]] #update the prev element after pop element\n else:\n l.append(i)\n t1=di[i]\n return l \n\nTEST_CODE_akash_karan = '''\nresult = akash_karan_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\n\n\nakash_agarwal_setup = '''\nfrom __main__ import akash_agarwal_day13\n'''\n\ndef akash_agarwal_day13(arr):\n di={\"NORTH\":1, \"WEST\":-1j, \"SOUTH\":-1, \"EAST\":1j}\n l,t1=[],0\n for i in arr:\n if (t1+di[i]==0):\n l.pop() #if north-south or east-west comes one after another\n if not(len(l)):t1=0 #then pop the prev and dont add the current\n else: t1=di[l[-1]] #update the prev element after pop element\n else:\n l.append(i)\n t1=di[i]\n return l \n\nTEST_CODE_akash_agarwal = '''\nresult = akash_agarwal_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nccquiel_setup = '''\nfrom __main__ import ccquiel_day13\n'''\n\ndef ccquiel_day13(arr):\n dirnum = {\"NORTH\": 1, \"SOUTH\": -1,\n \"EAST\": 2, \"WEST\": -2}\n index = 0\n while index < (len(arr) - 1):\n if dirnum[arr[index]] + dirnum[arr[index+1]] == 0:\n arr = arr[:index] + arr[index+2:]\n index = 0\n else:\n index += 1\n return arr\n\nTEST_CODE_ccquiel = '''\nresult = ccquiel_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\ndiana_henninger_setup = '''\nfrom __main__ import diana_henninger_day13\n'''\n\ndef opposite(x,y):\n return (x==\"NORTH\" and y==\"SOUTH\") or (x==\"SOUTH\" and y==\"NORTH\") or (x==\"WEST\" and y==\"EAST\") or (x==\"EAST\" and y==\"WEST\")\ndef diana_henninger_day13(arr):\n i = 0\n while (i 1:\n multiplication = 1\n for digit in n_to_string:\n multiplication *= int(digit)\n n_to_string = str(multiplication)\n loop_count += 1\n return loop_count\n\nTEST_CODE_ggebre = '''\nresult = ggebre_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nvijaya_lakshmi_setup = '''\nfrom __main__ import vijaya_lakshmi_day13\n'''\n\ndef recursion(arr): \n res = [int(x) for x in str(arr)] \n total = reduce((lambda x, y: x * y), res)\n loopCount = 1\n while total >= 10: \n tot = [int(x) for x in str(total)] \n total = reduce((lambda x, y: x * y), tot)\n loopCount += 1\n \n return loopCount\ndef vijaya_lakshmi_day13(arr):\n # your code\n if(len(str(arr)) < 2):\n return 0\n else:\n return recursion(arr)\n\nTEST_CODE_vijaya_lakshmi = '''\nresult = vijaya_lakshmi_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nPrashanth_Kadimisetty_setup = '''\nfrom __main__ import Prashanth_Kadimisetty_day13\n'''\n\ndef Prashanth_Kadimisetty_day13(arr):\n return min([available[x]//recipe[x] if x in available else 0 for x in recipe])\n\nTEST_CODE_Prashanth_Kadimisetty = '''\nresult = Prashanth_Kadimisetty_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nKrzysztof_Blach_setup = '''\nfrom __main__ import Krzysztof_Blach_day13\n'''\n\ndef Krzysztof_Blach_day13(arr):\n count = 0\n while len(str(arr)) > 1:\n count += 1\n mult = 1\n digits = [int(el) for el in str(arr)]\n for digit in digits:\n mult = mult * digit\n n = mult\n return count\n\nTEST_CODE_Krzysztof_Blach = '''\nresult = Krzysztof_Blach_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nKurt_Hinderer_setup = '''\nfrom __main__ import Kurt_Hinderer_day13\n'''\n\n\ndef Kurt_Hinderer_day13(directions):\n #damn, no vectors, have to fudge it\n dir_dict = {\"NORTH\": -1, \"SOUTH\": 1, \"EAST\": -2, \"WEST\": 2}\n done = False\n while not done:\n i = 0\n deleted = False\n while i < len(directions)-1 and not deleted:\n if dir_dict[directions[i]] + dir_dict[directions[i+1]] == 0:\n del directions[i: i+2]\n deleted = True\n i += 1\n done = not deleted\n return directions\n\n\nTEST_CODE_Kurt_Hinderer = '''\nresult = Kurt_Hinderer_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nJose_Catela_setup = '''\nfrom __main__ import Jose_Catela_day13\n'''\n\ndef Jose_Catela_day13(arr):\n cases = ['NORTHSOUTH', 'SOUTHNORTH', 'EASTWEST', 'WESTEAST']\n position = 0\n while len(arr) != 0 and position != len(arr) - 1:\n to_test = arr[position] + arr[position+1]\n if to_test in cases:\n arr.pop(position)\n arr.pop(position)\n position = 0\n else:\n position += 1\n return arr\n\nTEST_CODE_Jose_Catela = '''\nresult = Jose_Catela_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nYang_setup = '''\nfrom __main__ import Yang_day13\n'''\n\n\ndef Yang_day13(arr):\n count = 0 \n while n>9: \n n = reduce(lambda x,y:int(x)*int(y), str(arr))\n count +=1 \n return count\n\nTEST_CODE_Yang = '''\nresult = Yang_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nVanessa_G_setup = '''\nfrom __main__ import Vanessa_G_day13\n'''\n\n\ndef Vanessa_G_day13(arr):\n count = 0\n while n >= 10:\n n = reduce(lambda x, y: x * y, [int(x) for x in str(arr)])\n count += 1\n return count\n\nTEST_CODE_Vanessa_G = '''\nresult = Vanessa_G_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nMemo_Hurtado_setup = '''\nfrom __main__ import Memo_Hurtado_day13\n'''\n\n\ndef Memo_Hurtado_day13(arr):\n if (n<10):\n return 0;\n string = str(arr)\n a = 1\n p = 0\n while True:\n string = (str(a), string) [p == 0]\n a = 1\n for s in string:\n b = int(s) \n a = a * b\n p += 1\n if (a<9):\n break\n return p \n\nTEST_CODE_Memo_Hurtado = '''\nresult = Memo_Hurtado_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nOleksandra_Chmel_setup = '''\nfrom __main__ import Oleksandra_Chmel_day13\n'''\n\n\ndef Oleksandra_Chmel_day13(arr):\n check = {'WEST':'EAST','EAST':'WEST','NORTH':'SOUTH','SOUTH':'NORTH'}\n count = len(arr)+1\n def smaller(arr):\n for ind,dir in enumerate(arr):\n if dir and check[dir]==arr[ind-1]:\n del arr[ind-1:ind+1]\n return arr\n while len(arr)!=count:\n arr = smaller(arr)\n count -= 1\n return arr\n\n\nTEST_CODE_Oleksandra_Chmel = '''\nresult = Oleksandra_Chmel_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nsjay_setup = '''\nfrom __main__ import sjay_day13\n'''\n\n\ndef sjay_day13(arr):\n index=0\n while index <= len(arr)-2:\n if (str(arr[index]).upper() == \"NORTH\" and str(arr[index+1]).upper()==\"SOUTH\") or (str(arr[index].upper()) == \"SOUTH\" and str(arr[index+1]).upper()==\"NORTH\"):\n del arr[index:index+2]\n index =0\n elif (str(arr[index]).upper() == \"EAST\" and str(arr[index+1]).upper()==\"WEST\") or (str(arr[index]).upper() == \"WEST\" and str(arr[index+1]).upper()==\"EAST\"):\n del arr[index:index+2]\n index=0\n else:\n index = index + 1\n return arr\n\n\nTEST_CODE_sjay = '''\nresult = sjay_day13([\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WEST\", \"NORTH\", \"WEST\"])\n'''\n\nprint(\"Time for akash_karan test code: \" + str(timeit.timeit(stmt=TEST_CODE_akash_karan, setup=akash_karan_setup, number=100000)) + \" seconds\")\nprint(\"Time for akash_agarwal test code: \" + str(timeit.timeit(stmt=TEST_CODE_akash_agarwal, setup=akash_agarwal_setup, number=100000)) + \" seconds\")\nprint(\"Time for kilian test code: \" + str(timeit.timeit(stmt=TEST_CODE_kilian, setup=kilian_setup, number=100000)) + \" seconds\")\nprint(\"Time for ccquiel test code: \" + str(timeit.timeit(stmt=TEST_CODE_ccquiel, setup=ccquiel_setup, number=100000)) + \" seconds\")\n#print(\"Time for vijaya_lakshmi test code: \" + str(timeit.timeit(stmt=TEST_CODE_vijaya_lakshmi, setup=vijaya_lakshmi_setup, number=100000)) + \" seconds\")\nprint(\"Time for diana_henninger test code: \" + str(timeit.timeit(stmt=TEST_CODE_diana_henninger, setup=diana_henninger_setup, number=100000)) + \" seconds\")\n#print(\"Time for ggebre test code: \" + str(timeit.timeit(stmt=TEST_CODE_ggebre, setup=ggebre_setup, number=100000)) + \" seconds\")\n#print(\"Time for Krzysztof_Blach test code: \" + str(timeit.timeit(stmt=TEST_CODE_Krzysztof_Blach, setup=Krzysztof_Blach_setup, number=100000)) + \" seconds\")\n#print(\"Time for Prashanth_Kadimisetty test code: \" + str(timeit.timeit(stmt=TEST_CODE_Prashanth_Kadimisetty, setup=Prashanth_Kadimisetty_setup, number=100000)) + \" seconds\")\nprint(\"Time for Kurt_Hinderer test code: \" + str(timeit.timeit(stmt=TEST_CODE_Kurt_Hinderer, setup=Kurt_Hinderer_setup, number=100000)) + \" seconds\")\nprint(\"Time for Jose_Catela test code: \" + str(timeit.timeit(stmt=TEST_CODE_Jose_Catela, setup=Jose_Catela_setup, number=100000)) + \" seconds\")\n#print(\"Time for Yang test code: \" + str(timeit.timeit(stmt=TEST_CODE_Yang, setup=Yang_setup, number=100000)) + \" seconds\")\n#print(\"Time for Vanessa_G test code: \" + str(timeit.timeit(stmt=TEST_CODE_Vanessa_G, setup=Vanessa_G_setup, number=100000)) + \" seconds\")\n#print(\"Time for Memo_Hurtado test code: \" + str(timeit.timeit(stmt=TEST_CODE_Memo_Hurtado, setup=Memo_Hurtado_setup, number=100000)) + \" seconds\")\nprint(\"Time for Oleksandra_Chmel test code: \" + str(timeit.timeit(stmt=TEST_CODE_Oleksandra_Chmel, setup=Oleksandra_Chmel_setup, number=100000)) + \" seconds\")\nprint(\"Time for sjay test code: \" + str(timeit.timeit(stmt=TEST_CODE_sjay, setup=sjay_setup, number=100000)) + \" seconds\")\n","sub_path":"day13/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":11657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"214724878","text":"#stworzyć funkcję, która po otrzymaniu liczby\n#całkowitej do 1 miliona zwróci wartość True jeśli ta\n#liczba jest pierwsza\n\nimport common_functions\n\ndef check_number(numberek):\n\n check_result = \"\"\n result = True\n\n for x in range(2, numberek):\n if numberek % x == 0:\n check_result = \"F\"\n\n if numberek > 1000000:\n print(\"za duży numberek\")\n elif check_result == \"F\":\n result = False\n else:\n result = True\n print(result)\n\ncheck_number(common_functions.check_input(\"int\", \"numberek: \"))\n\n\n\n","sub_path":"08_10/homework_02.py","file_name":"homework_02.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"513754116","text":"import logging\nimport os\nimport pickle\nfrom tempfile import TemporaryDirectory\n\nfrom funcy import cached_property\n\nfrom dvc.path_info import PathInfo\nfrom dvc.stage import PipelineStage\nfrom dvc.tree.base import BaseTree\nfrom dvc.utils import relpath\nfrom dvc.utils.fs import copy_fobj_to_file, makedirs\n\nlogger = logging.getLogger(__name__)\n\n\nclass ExperimentExecutor:\n \"\"\"Base class for executing experiments in parallel.\n\n Args:\n src_tree: source tree for this experiment.\n baseline_rev: baseline revision that this experiment is derived from.\n\n Optional keyword args:\n repro_args: Args to be passed into reproduce.\n repro_kwargs: Keyword args to be passed into reproduce.\n \"\"\"\n\n def __init__(self, src_tree: BaseTree, baseline_rev: str, **kwargs):\n self.src_tree = src_tree\n self.baseline_rev = baseline_rev\n self.repro_args = kwargs.pop(\"repro_args\", [])\n self.repro_kwargs = kwargs.pop(\"repro_kwargs\", {})\n\n def run(self):\n pass\n\n def cleanup(self):\n pass\n\n # TODO: come up with better way to stash repro arguments\n @staticmethod\n def pack_repro_args(path, *args, tree=None, **kwargs):\n open_func = tree.open if tree else open\n data = {\"args\": args, \"kwargs\": kwargs}\n with open_func(path, \"wb\") as fobj:\n pickle.dump(data, fobj)\n\n @staticmethod\n def unpack_repro_args(path, tree=None):\n open_func = tree.open if tree else open\n with open_func(path, \"rb\") as fobj:\n data = pickle.load(fobj)\n return data[\"args\"], data[\"kwargs\"]\n\n\nclass LocalExecutor(ExperimentExecutor):\n \"\"\"Local machine exepriment executor.\"\"\"\n\n def __init__(self, src_tree: BaseTree, baseline_rev: str, **kwargs):\n dvc_dir = kwargs.pop(\"dvc_dir\")\n cache_dir = kwargs.pop(\"cache_dir\")\n super().__init__(src_tree, baseline_rev, **kwargs)\n self.tmp_dir = TemporaryDirectory()\n logger.debug(\"Init local executor in dir '%s'.\", self.tmp_dir)\n self.dvc_dir = os.path.join(self.tmp_dir.name, dvc_dir)\n try:\n for fname in src_tree.walk_files(src_tree.tree_root):\n dest = self.path_info / relpath(fname, src_tree.tree_root)\n if not os.path.exists(dest.parent):\n makedirs(dest.parent)\n with src_tree.open(fname, \"rb\") as fobj:\n copy_fobj_to_file(fobj, dest)\n except Exception:\n self.tmp_dir.cleanup()\n raise\n self._config(cache_dir)\n\n def _config(self, cache_dir):\n local_config = os.path.join(self.dvc_dir, \"config.local\")\n logger.debug(\"Writing experiments local config '%s'\", local_config)\n with open(local_config, \"w\") as fobj:\n fobj.write(\"[core]\\n no_scm = true\\n\")\n fobj.write(f\"[cache]\\n dir = {cache_dir}\")\n\n @cached_property\n def dvc(self):\n from dvc.repo import Repo\n\n return Repo(self.dvc_dir)\n\n @cached_property\n def path_info(self):\n return PathInfo(self.tmp_dir.name)\n\n @staticmethod\n def reproduce(dvc_dir, cwd=None, **kwargs):\n \"\"\"Run dvc repro and return the result.\"\"\"\n from dvc.repo import Repo\n from dvc.repo.experiments import hash_exp\n\n unchanged = []\n\n def filter_pipeline(stage):\n if isinstance(stage, PipelineStage):\n unchanged.append(stage)\n\n if cwd:\n old_cwd = os.getcwd()\n os.chdir(cwd)\n else:\n old_cwd = None\n cwd = os.getcwd()\n\n try:\n logger.debug(\"Running repro in '%s'\", cwd)\n dvc = Repo(dvc_dir)\n dvc.checkout()\n stages = dvc.reproduce(on_unchanged=filter_pipeline, **kwargs)\n finally:\n if old_cwd is not None:\n os.chdir(old_cwd)\n\n # ideally we would return stages here like a normal repro() call, but\n # stages is not currently picklable and cannot be returned across\n # multiprocessing calls\n return hash_exp(stages + unchanged)\n\n def cleanup(self):\n logger.debug(\"Removing tmpdir '%s'\", self.tmp_dir)\n self.tmp_dir.cleanup()\n super().cleanup()\n","sub_path":"dvc/repo/experiments/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"122650596","text":"NUM_INSTRUMENTS = 64\nNUM_SYNTHS = 16\nNUM_PHRASES = 255\nNUM_TABLES = 32\nWAVES_PER_SYNTH = 16\nFRAMES_PER_WAVE = 32\nSTEPS = 16\nNUM_SONG_CHAINS = 256\nNUM_GROOVES = 32\nNUM_CHAINS = 128\nNUM_WORDS = 42\nWORD_LENGTH = 16\nBITSINBYTE = 8\nNIBBLE = 4\nNUM_CHANNELS = 4\n\nNull = \"\"\nmem_init_flag_1 = 'rb'\nmem_init_flag_2 = 'rb'\nmem_init_flag_3 = 'rb'\n\nfn1 = '../orbitalfrontaldistal.lsdsng'\nfn2 = '../organelle.lsdsng'\nfn3 = '../choral.lsdsng'","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"376180549","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nWalle version 2.0\n\"\"\"\n\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nimport logging\nimport logging.config\nimport sys\nimport sqlite3\n\nlogger = logging.getLogger(__name__)\n\nBANG = \"90057254\"\nCHUI = \"119906841\"\nDB_NAME = \"walle.db\"\n\nwith open(\"token.key\") as f:\n TOKEN = f.readline().strip()\n\n# Define a few command handlers. These usually take the two arguments bot and\n# update. Error handlers also receive the raised TelegramError object in error.\ndef start(bot, update):\n update.message.reply_text('Hi!')\n\n\ndef help(bot, update):\n update.message.reply_text('Help!')\n\n\ndef bookkeeper(bot, update):\n '''\n bookkeeper takes a command from account owner and\n does balance transfer betweent accounts\n\n 'walle! pay 1000 for massage'\n chatid:-161289404 user:90057254 knightelvis\n chatid:-161289404 user:119906841 None\n '''\n\n parsed_cmd = _parse_payment_cmd(update.message.text)\n\n if not parsed_cmd:\n return\n try:\n money = int(parsed_cmd[0])\n except ValueError:\n logger.info(\"money is not a integer:%s\" % parsed_cmd[0])\n update.message.reply_text(\"请输入数字:\" + parsed_cmd[0])\n\n if len(parsed_cmd) > 1:\n reason = parsed_cmd[1]\n else:\n reason = \"n/a\"\n\n from_user = str(update.message.from_user.id)\n txn_date = update.message.date\n\n logger.debug('money:%s reason:%s from:%s date:%s' %\n (money, reason, from_user, txn_date))\n\n if from_user == BANG:\n receiver = CHUI\n elif from_user == CHUI:\n receiver = BANG\n\n from_balance = _get_balance(from_user)\n\n if from_balance >= money:\n _write_balace(from_user, from_balance - money)\n _write_balace(receiver, _get_balance(receiver) + money)\n _log_txn(from_user, receiver, money, reason, txn_date)\n update.message.reply_text(\"大锤: %d 棒棒: %d\" %\n (_get_balance(CHUI), _get_balance(BANG)))\n\n else:\n update.message.reply_text(\"Sorry, 余额不足哦!您现在余额:%s\" % from_balance)\n\n\ndef _log_txn(from_user, to_user, money, reason, date):\n try:\n db = sqlite3.connect(DB_NAME)\n\n cursor = db.cursor()\n cursor.execute(\n \"INSERT INTO Txn VALUES(?, ?, ?, ?, datetime('now'))\",\n (from_user, to_user, money, reason))\n\n db.commit()\n except Exception as e:\n logger.exception(\"Error when saving txn to db.\", e)\n raise e\n finally:\n db.close()\n\n\ndef _get_balance(user):\n '''\n Return an integer\n '''\n try:\n db = sqlite3.connect(DB_NAME)\n\n cursor = db.cursor()\n cursor.execute(\"SELECT balance from Balance where user = ?\", (user,))\n return int(cursor.fetchone()[0]) # always single row returned\n except Exception as e:\n logger.exception(\"Error when getting balance from db.\", e)\n raise e\n finally:\n db.close()\n\n\ndef _write_balace(user, new_balance):\n try:\n db = sqlite3.connect(DB_NAME)\n\n cursor = db.cursor()\n cursor.execute(\"UPDATE Balance SET balance = ? where user = ?\",\n (new_balance, user))\n db.commit()\n except Exception as e:\n logger.exception(\"Error when writing balance to db.\", e)\n raise e\n finally:\n db.close()\n\n\ndef _parse_payment_cmd(msg):\n '''\n If the msg is valid command, the returned array has the money\n nominal value and the reason for payment. If not, return empty array.\n '''\n if msg and msg.lower().startswith(\"walle!\"):\n elements = msg.strip().split()\n # filter == [x for x in elements if func(x)]\n return list(filter(None, elements))[2:] # skip 'walle!' and 'pay'\n else:\n return []\n\n\ndef error(bot, update, error):\n logger.warn('Update \"%s\" caused error \"%s\"' % (update, error))\n\n\ndef main():\n\n kw = {\n 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n 'level': logging.INFO,\n 'filename': 'walle2.log',\n # 'stream': sys.stdout,\n }\n\n logging.basicConfig(**kw)\n\n # Create the EventHandler and pass it your bot's token.\n updater = Updater(TOKEN)\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n\n # on different commands - answer in Telegram\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(CommandHandler(\"help\", help))\n dp.add_handler(MessageHandler(Filters.text, bookkeeper))\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling()\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"walle2.py","file_name":"walle2.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"239952001","text":"\nfrom structure.rule import Rule\nfrom structure.rule_untyped import RuleUntyped\n\n\nclass RuleCyclic(Rule):\n\n def __init__(self, rule_untyped):\n super().__init__()\n super().init_from_rule_untyped(rule_untyped)\n if self.body.literals[0].contains('Y') and self.bodysize() > 1:\n for i in range((self.bodysize() // 2) - 1 ):\n j = (self.bodysize() - i) - 1\n atom_i = self.body.literals[i]\n atom_j = self.body.literals[j]\n self.body.literals[i] = atom_j\n self.body.literals[j] = atom_i\n\n self.body.normalize_variable_names()\n\n def compute_tail_results(self, head, triple_set):\n results = set()\n self.get_cyclic('X', 'Y', head, 0, True, triple_set, set(), results)\n return results\n\n def compute_head_results(self, tail, triple_set):\n results = set()\n self.get_cyclic('Y', 'X', tail, self.bodysize() - 1, False, triple_set, set(), results)\n return results\n\n def compute_scores(triple_set):\n pass\n\n def get_cyclic(self, current_variable, last_variable, value, body_index, direction, triple_set ,previous_values, final_results):\n if self.has_negation():\n if self.negation.left == current_variable:\n tails = triple_set.get_tail_entities(self.negation.relation, value)\n if self.negation.is_variable_right():\n if len(tails) > 0:\n return\n elif self.negation.right == current_variable:\n heads = triple_set.get_head_entities(self.negation.relation, value)\n if Rule.application_mode and len(final_results) >= self.cfg.discrimination_bound:\n final_results.clear()\n return\n # XXX if (!Rule.APPLICATION_MODE && finalResults.size() >= Settings.SAMPLE_SIZE) return;\n\t\t# check if the value has been seen before as grounding of another variable\n atom = self.body.literals[body_index]\n head_not_tail = atom.left == current_variable\n if value in previous_values:\n return\n if (direction == True and self.body.size() - 1 == body_index) and (direction == False and body_index == 0):\n for v in triple_set.get_entities(atom.relation, value, head_not_tail):\n if v not in previous_values and not v == value:\n final_results.add(v)\n return\n # the current atom is not the last\n else:\n results = triples.get_entities(atom.relation, value, head_not_tail)\n next_variable = atom.right if head_not_tail else atom.left\n current_values = set(previous_values)\n current_values.add(value)\n for next_value in results:\n updated_body_index = bodyIndex + 1 if direction else bodyIndex - 1\n self.get_cyclic(next_variable, last_variable, next_value, updated_body_index, direction, triple_set, current_values, final_results)\n return\n\n","sub_path":"source/AnyBURL-Reinforced/structure/rule_cyclic.py","file_name":"rule_cyclic.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"535426674","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport os\nfrom ..visualizations import plot_cst_confusion, plot_latent_mixture_stats, plot_prior_distribution, plot_confusion, plot_compare, plot_latent_stats, plot_samples, plot_reconstructions, plot_encodings, plot_samples_by_class\nfrom ..util.util import joinpath\n\nclass ramp(tf.keras.callbacks.Callback):\n def __init__(self, final_value, ramp_iters=0, warmup_iters=0, init_value=0., by_epoch=False):\n self.final_value = final_value\n self.ramp_iters = ramp_iters\n self.warmup_iters = warmup_iters\n self.init = init_value if ramp_iters > 0 else final_value\n self.by_epoch = by_epoch\n self.current_batch = 0\n\n def setup(self, model, scale=1.):\n self.init = scale * self.init\n self.final_value = scale * self.final_value\n\n model.callbacks.append(self)\n self.var = tf.Variable(self.init, trainable=False)\n return self.var\n\n def on_batch_end(self, epoch, logs=None, override=False):\n self.current_batch += 1\n epoch = self.current_batch\n if self.ramp_iters > 0 and epoch > self.warmup_iters and (not self.by_epoch or override):\n epoch = max(epoch - self.warmup_iters, 0)\n val = min(epoch *(self.final_value / self.ramp_iters) + self.init, self.final_value)\n tf.keras.backend.set_value(self.var, val)\n\n def on_epoch_end(self, epoch, logs=None):\n if self.by_epoch:\n self.on_batch_end(epoch, logs, True)\n\n\nclass VizCallback(tf.keras.callbacks.Callback):\n # Keras callback for annealing Beta at each epoch end\n\n def __init__(self, ca, data):\n self.ca = ca\n self.data = data\n\n def on_batch_end(self, epoch, logs=None):\n if np.random.random() < 0.005:\n try:\n x, y = self.data.valid().numpy()\n x, y, = x[:1000], y[:1000]\n recon = self.ca.predict([x, y])[0]\n x, recon = self.data.norm_inv(x), self.data.norm_inv(recon)\n plot_compare(x, recon, rescale=False)\n except:\n pass\n\nclass AllVizCallback(tf.keras.callbacks.Callback):\n # Keras callback for annealing Beta at each epoch end\n\n def __init__(self, m=None, data=None, save=None):\n self.m = m\n self.data = data\n self.save_path = save\n\n def save(self, name, epoch):\n if self.save_path is None:\n return None\n return joinpath(self.save_path, 'visualizations', 'epoch_%d' % epoch, file='%s.pdf' % name)\n\n def on_epoch_end(self, epoch, logs=None):\n results = dict(model=self.m, dataset=self.data, labels=[str(i) for i in range(10)])\n plot_samples(results, save=self.save('samples', epoch))\n try:\n #plot_samples_by_class(results)\n plot_latent_stats(results, save=self.save('stats', epoch))\n except:\n pass\n try:\n #plot_samples_by_class(results)\n plot_latent_mixture_stats(results, save=self.save('mix_stats', epoch))\n except:\n pass\n try:\n plot_confusion(results, save=self.save('confusion', epoch))\n plot_cst_confusion(results, save=self.save('consistency_confusion', epoch))\n except:\n pass\n plot_encodings(results, save=self.save('encodings', epoch))\n plot_prior_distribution(results, save=self.save('prior', epoch))\n plot_reconstructions(results, save=self.save('reconstructions', epoch))\n plot_reconstructions(results, consistency=True, save=self.save('consistency_reconstructions', epoch))\n plot_reconstructions(results, consistency=True, split='train', save=self.save('training_reconstructions', epoch))\n try:\n pass\n #plot_samples_by_class(results)\n except:\n pass\n\n\nclass ConsisCallback(tf.keras.callbacks.Callback):\n # Keras callback for annealing Beta at each epoch end\n\n def __init__(self, ca, data):\n self.ca = ca\n self.ld, self.ldy = data.labeled().numpy()\n self.uld, self.uldy = data.unlabeled().numpy()\n self.val, self.valy = data.valid().numpy()\n\n self.ldy = self.ldy.argmax(axis=-1)\n self.uldy = self.uldy.argmax(axis=-1)\n self.valy = self.valy.argmax(axis=-1)\n\n print(self.ld.shape)\n print(self.uld.shape)\n print(self.val.shape)\n\n def on_epoch_end(self, epoch, logs=None):\n try:\n\n # TODO: Consistency vs. Accuracy\n\n # LD Split\n loss, pred = self.ca.predict([self.ld])\n lossc = loss[pred.argmax(axis=-1) == self.ldy]\n lossic = loss[pred.argmax(axis=-1) != self.ldy]\n\n plt.figure()\n plt.hist(lossc, density=True, bins='fd')\n plt.title(f'Epoch: {epoch+1} Labeled C Mean:{round(float(lossc.mean()),3)}')\n plt.show()\n\n plt.figure()\n plt.hist(lossic, density=True, bins='fd')\n plt.title(f'Epoch: {epoch+1} Labeled IC Mean:{round(float(lossic.mean()),3)}')\n plt.show()\n\n # ULD Split\n loss, pred = self.ca.predict([self.uld])\n lossc = loss[pred.argmax(axis=-1) == self.uldy]\n lossic = loss[pred.argmax(axis=-1) != self.uldy]\n\n plt.figure()\n plt.hist(lossc, density=True, bins='fd')\n plt.title(f'Epoch: {epoch+1} Unlabeled C Mean:{round(float(lossc.mean()),3)}')\n plt.show()\n\n plt.figure()\n plt.hist(lossic, density=True, bins='fd')\n plt.title(f'Epoch: {epoch+1} Unlabeled IC Mean:{round(float(lossic.mean()),3)}')\n plt.show()\n\n # VAL Split\n loss, pred = self.ca.predict([self.val])\n lossc = loss[pred.argmax(axis=-1) == self.valy]\n lossic = loss[pred.argmax(axis=-1) != self.valy]\n\n plt.figure()\n plt.hist(lossc, density=True, bins='fd')\n plt.title(f'Epoch: {epoch+1} Valid C Mean:{round(float(lossc.mean()),3)}')\n plt.show()\n\n plt.figure()\n plt.hist(lossic, density=True, bins='fd')\n plt.title(f'Epoch: {epoch+1} Valid IC Mean:{round(float(lossic.mean()),3)}')\n plt.show()\n\n\n\n except:\n raise\n\n","sub_path":"src/PC-HMM/tutorial_files/pcvae/util/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":6319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"249896227","text":"import os\r\nimport pickle\r\nimport re\r\nimport shutil\r\n\r\n\r\nclass model_functions:\r\n \"\"\"\r\n This class shall be used to save the model after training\r\n and load the saved model for prediction.\r\n\r\n Written By: richabudhraja8@gmail.com\r\n Version: 1.0\r\n Revisions: None\r\n\r\n \"\"\"\r\n\r\n def __init__(self, logger_object, file_object):\r\n self.file_obj = file_object\r\n self.log_writer = logger_object\r\n self.models_location = 'models/'\r\n\r\n\r\n def save_model(self, model, model_name):\r\n \"\"\"\r\n Method Name: save_model\r\n Description: Save the model file to directory at models_location\r\n Output: File gets saved\r\n On Failure: Raise Exception\r\n\r\n Written By: richabudhraja8@gmail.com\r\n Version: 1.0\r\n Revisions: None\r\n \"\"\"\r\n self.log_writer.log(self.file_obj, \"Entered save_model of model_functions class!!\")\r\n try:\r\n #make models directory\r\n if not os.path.isdir(self.models_location):\r\n os.mkdir(self.models_location)\r\n\r\n model_path = os.path.join(self.models_location, model_name)\r\n if os.path.isdir(model_path):\r\n shutil.rmtree(model_path)\r\n os.mkdir(model_path)\r\n else:\r\n os.mkdir(model_path)\r\n final_model = model_path + '/' + model_name + '.sav'\r\n with open(final_model, 'wb') as f:\r\n pickle.dump(model, f)\r\n self.log_writer.log(self.file_obj,\r\n 'saving the model %s successfully.Exited the save_model of model_functions class!!' % model_name)\r\n\r\n return \"success\"\r\n except Exception as e:\r\n self.log_writer.log(self.file_obj,\r\n 'Exception occurred in save_model of model_functions class!! Exception message:' + str(\r\n e))\r\n self.log_writer.log(self.file_obj,\r\n 'saving the model %s failed. save_model of model_functions class!!' % model_name)\r\n raise e\r\n\r\n def load_model(self, model_name):\r\n \"\"\"\r\n Method Name: load_model\r\n Description: load model for a given model name\r\n Output: the model\r\n On Failure: Raise Exception\r\n\r\n Written By: richabudhraja8@gmail.com\r\n Version: 1.0\r\n Revisions: None\r\n \"\"\"\r\n dest = self.models_location + model_name + '/' + model_name + '.sav'\r\n self.log_writer.log(self.file_obj, \"Entered load_model of model_functions class!!\")\r\n try:\r\n\r\n with open(dest, 'rb') as f: # read the model in binary mode\r\n self.log_writer.log(self.file_obj, \"loaded the model %s Successfully!!\" % model_name)\r\n return pickle.load(f)\r\n except Exception as e:\r\n self.log_writer.log(self.file_obj,\r\n 'Exception occurred in load_model of model_functions class!! Exception message:' + str(\r\n e))\r\n self.log_writer.log(self.file_obj,\r\n 'loading the model %s failed. load_model of model_functions class!!' % model_name)\r\n raise e\r\n\r\n def find_correct_model(self):\r\n \"\"\"\r\n Method Name: find_correct_model_for_cluster\r\n Description: find the correct model for a given cluster number\r\n Output: exact location of the model file\r\n On Failure: Raise Exception\r\n\r\n Written By: richabudhraja8@gmail.com\r\n Version: 1.0\r\n Revisions: None\r\n \"\"\"\r\n\r\n self.log_writer.log(self.file_obj, \"Entered find_correct_model of model_functions class!!\")\r\n\r\n try:\r\n model_name = os.listdir(self.models_location)\r\n self.log_writer.log(self.file_obj, \"returned the model %s \" % model_name[0]+\"Successfully for cluster number \")\r\n return model_name[0]\r\n\r\n\r\n except Exception as e:\r\n self.log_writer.log(self.file_obj,\r\n 'Exception occurred in find_correct_model of model_functions class!! Exception message:' + str(\r\n e))\r\n self.log_writer.log(self.file_obj,\r\n \"Could not return the model .\")\r\n raise e","sub_path":"Model_functions/model_functions_fileops.py","file_name":"model_functions_fileops.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"287344008","text":"#SYMMETRIC POSITIVE DEFINITE MATRIX\nimport numpy as np\nimport torch\nimport numpy as np\nfrom numpy import linalg as LA\nimport matplotlib.pyplot as plt\nimport sys\n\n\n#Compute Adjacency Matrix given Laplacian A\ndef computeAdjancency(A):\n A = -A;\n ind = np.diag_indices(A.shape[0])\n A[ind[0], ind[1]] = 0;\n return A\n\n\n#Compute Laplacian of Adjacency Matrix A\ndef computeLaplacian(A):\n A = - A;\n sum_val = abs(torch.sum(A, dim=1))\n non_null_val = torch.where(sum_val > 0)[0];\n ind = np.diag_indices(A.shape[0])\n A[ind[0], ind[1]] = sum_val;\n A = A[non_null_val,:];\n A = A[:,non_null_val];\n A = A.type(torch.DoubleTensor)\n return A.cuda(), non_null_val;\n\ndef computeStrongConnections(A, param):\n #get the maximum of rows\n N = A.size(1)\n EXCLUDE_DIAG = (torch.eye(N)<1).cuda();\n A_noDiag = A*EXCLUDE_DIAG\n\n MaxAIJ = torch.max(torch.abs(A_noDiag),dim=1).values\n\n MaxAIJ_T = torch.t(MaxAIJ)\n MAX_MATRIX = MaxAIJ_T.repeat(N,1).t()\n\n #Compute which Elements (Diagonals Exluded) satifies the \"Strong\n #Connection Requirement) for each node (row).\n S = torch.logical_and(torch.abs(A) >= (param*MAX_MATRIX), EXCLUDE_DIAG);\n B = torch.abs(A) >= (param*MAX_MATRIX);\n return S\n\ndef computeLambdas(F,U,S):\n\n N = S.size(1);\n #Compute mask for U nodes\n maskU = torch.zeros(N,N).cuda();\n #Get indices of Nodes in U\n\n maskU[torch.where(U==1)[0],:] = 1;\n #Create Mask for F Nodes\n maskF = torch.zeros(N,N).cuda();\n\n maskU[F,:] = 1;\n #Compute intersection\n SintU = (S*maskU).t();\n SintF = (S*maskF).t();\n\n #Compute lambdas according to formula\n lambdas = torch.sum(SintU,1) + 2*torch.sum(SintF,1);\n\n #Get only those elements belonging to U, and return lambdas;\n return lambdas*U.t()\n\n\ndef computePrologator(A, SUBNODES_PG):\n dim = A.size(1)\n SUBNODES = int(dim*SUBNODES_PG);\n S = computeStrongConnections(A, 0.25);\n F = np.array([], dtype='int');\n F = torch.from_numpy(F).cuda()\n C = np.array([], dtype='int');\n C = torch.from_numpy(C).cuda()\n U = torch.ones(dim,1).cuda();\n\n #neighbour matrix\n N = (A != 0).cuda();\n N = N * (torch.eye(dim)<1).cuda();\n #Compute lambdas according formula\n lambdas = computeLambdas(F,U,S);\n\n #SUBSPACE COARSENING\n for iteration in range(0,SUBNODES):\n index = torch.where(lambdas == torch.max(lambdas))[1][0];\n if(iteration ==0):\n C = index.unsqueeze(0);\n else:\n C = torch.cat((C,index.unsqueeze(0)))\n U[C] = 0;\n concatenate1 = torch.where(S[index,:]==1)[0]\n if(iteration == 0):\n F = concatenate1;\n else:\n F = torch.unique(torch.cat((F.unsqueeze(0),concatenate1.unsqueeze(0)),1)).cuda()\n U[F] = 0;\n lambdas = computeLambdas(F,U,S);\n\n #Compute the Prolongation Operator\n Prol = torch.zeros(dim,dim);\n\n #Cnodes Mask\n CNodes = torch.zeros(dim,dim).cuda();\n CNodes[C,:] = 1;\n CNodes[:,C]= 1;\n\n #Compute P (as in paper) as and AND element wise between CNodes and\n #Neighbours Nodes\n P = torch.logical_and(N,CNodes).cuda();\n\n dotProduct1 = A*N;\n secondProduct2 = A*P;\n\n #Compute weights of Prologation Operator for Fine nodes\n for i in F:\n Js = torch.where(P[i,:]==1)[0];\n\n for j in Js:\n firstDot = torch.sum(dotProduct1[i,:]);\n secondDot = torch.sum(secondProduct2[i,:]);\n Prol[i,j] = - (firstDot/secondDot)*(A[i,j]/A[i,i]);\n\n #Compute weights of Prologation Operator for Coarse nodes\n for i in C:\n Prol[i,i] = A[i,i];\n\n #Get only the columns that contain the \"COARSEN NODES\";\n\n Prol = Prol[:,C];\n\n Prol = Prol.type(torch.DoubleTensor)\n return Prol\n","sub_path":"PART_I_APPROACH_3/easyAMG.py","file_name":"easyAMG.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"433061813","text":"import pandas as pd \nimport streamlit as st \nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import linear_model\nfrom sklearn import neighbors\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import KFold\nimport category_encoders as ec\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import StandardScaler\nimport plotly.graph_objects as go\n\n\nst.markdown(\"# DOPP3\")\nst.markdown('## Which characteristics are predictive for countries with large populations living in extreme poverty?')\n\nwith st.echo():\n # READ TRANSFORMED CSV FILE\n raw = pd.read_csv(\"../data/transformed.csv\") \n #st.write(raw.head(100))\n\n feature_descriptions = pd.read_csv(\"../data/feature_descriptions.csv\")\n #st.write(feature_descriptions)\n\n # FEATURES WITH LESS THAN 50% MISSING VALUES\n features = feature_descriptions.where(feature_descriptions['na_percent']<=50.0).dropna(0)\n \n # ONLY DEMOGRAFIC FEATURES!\n cols = features['Unnamed: 0'].tolist()\n #cols_to_drop = 7:13 + 18:25\n cols = cols[0:7]+ cols[13:18] + [cols[25]]\n #st.write(cols)\n\n dataset = raw[cols]\n\nst.write(dataset.head(100)) \n \n\nst.markdown('## Exploratory Data Analysis')\nst.markdown('After selection of only demographic features with less than 50% missing values we are left with the following attributes: ')\n\n# PRINTING DESCRIPTIONS OF FEATURES\nfor col in cols:\n desc = pd.DataFrame(features.where(features['Unnamed: 0'] == col).dropna(0)['descriptions'])\n st.write(col, ':', desc.to_string(header=False, index=False)) \nst.write('All attributes except *Location*(**categorical**) are **numeric**')\n\n# CORRELATION MATRIX\nplt.figure(figsize=(35,30))\nsns.set(font_scale=3.1)\nsns.heatmap(dataset.corr(),annot=True)\nst.pyplot()\n\nst.write('From the correlation matrix, we can see that all *population measures correlate* with each other (as excepted). Moreover, we can notice a strong negative correlation between *fertility rate* and *life expectancy at birth* as well as *life expectancy at birth* and *mortality rate*.')\n\n#st.write(dataset.drop(labels=[cols[0], cols[-1]], axis=1).head(10))\n\n# PLOT DISTRIBUTION OF THE ATTRIBUTES\nfig = dataset.drop(labels=[cols[0], cols[-1]], axis=1).hist(figsize=(14,14), xlabelsize=10, ylabelsize=10, bins=20)\n[x.title.set_size(20) for x in fig.ravel()]\nplt.tight_layout()\nst.pyplot()\n\nst.markdown('## Missing Values')\nst.markdown('The dataset contains a lot of missing values. We did **linear interpolation** for *each attribute* in *each country* separately. The values that were **not handled by the interpolation** were set to the *mean* of the column (probably because they are on the beginning/end of the column). Some attributes of the certain countries were without any values, we set those to 0. ')\n\nwith st.echo():\n by_country = dataset.groupby(by=dataset['LOCATION']) \n dataset_full = pd.DataFrame(columns=cols)\n dataset_full2 = pd.DataFrame(columns=cols)\n\n\n for name, group in by_country :\n tdf = pd.DataFrame(columns=cols)\n tdf2 = pd.DataFrame(columns=cols) \n\n tdf['TIME'] = group['TIME']\n tdf['poverty'] = group['poverty']\n\n # cols with all NaN values\n all_null = group.isna().all() \n null_cols = all_null.where(all_null == 1).dropna(0).index.tolist()\n tdf[null_cols] = 0\n\n # cols for interpolation\n cols_to_int = all_null.where(all_null == 0).dropna(0).index.tolist()[2:]\n cols_to_int.remove('poverty')\n\n #st.write(group[cols_to_int].isnull().values.sum())\n\n tdf[cols_to_int] = group[cols_to_int].interpolate(method='linear', axis=0)\n tdf['LOCATION'] = name \n\n # fill the NaN values that were not interpolated\n tdf.fillna(tdf.mean(), inplace=True)\n\n # Another way to interpolate - take mean for the cols with all NaNs\n tdf2 = group.interpolate(method ='linear', limit_direction ='forward', axis = 0)\n tdf2 = tdf2.interpolate(method ='linear', limit_direction ='backward', axis = 0)\n tdf2['LOCATION'] = name\n tdf2.fillna(dataset.drop(labels=['LOCATION'], axis=1).mean(), inplace=True)\n\n dataset_full2 = pd.concat([dataset_full2,tdf2])\n dataset_full = pd.concat([dataset_full,tdf])\n\n \ndataset_full2.sort_index(inplace=True)\ndataset_full.sort_index(inplace=True)\nst.write(dataset_full2.head(100))\n\n\nst.markdown('## ML Models')\n\nwith st.echo():\n # GROUND TRUTH AS NUMERIC\n y = dataset_full['poverty']\n y = y.apply(lambda x: 1 if x==True else 0)\n #st.write(y.head(100))\n\n # FEATURE MATRIX UNSCALED AND SCALED \n X = dataset_full.drop(labels=['poverty'], axis=1)\n X_2 = dataset_full2.drop(labels=['LOCATION', 'poverty'], axis=1)\n X_noloc = dataset_full.drop(labels=['poverty'], axis=1).drop(labels=['LOCATION'], axis=1)\n st.write(X_2)\n\n sc = StandardScaler()\n X_s = sc.fit_transform(X.drop(labels=['LOCATION'], axis=1))\n X_s = pd.DataFrame(X_s, columns=cols[1:12])\n\n #ATTRIBUTE 'LOCATION' - BINARY ENCODER \n encoder = ec.BinaryEncoder(cols=['LOCATION'])\n L_enc = encoder.fit_transform(X['LOCATION'])\n X = pd.concat([X.drop(labels=['LOCATION'], axis=1),L_enc], axis=1)\n X_s = pd.concat([X_s,L_enc], axis=1)\n \n #st.write(X_s.head(100))\n\n skf = KFold(n_splits=10, random_state = 30)\n\n # FUNCTIONS FOR ML \n def print_performance (classifier, X, y, scores= ['accuracy', 'precision', 'recall'], model=''):\n for score in scores:\n #cv1 = cross_val_score(classifier, X, y, cv=skf.split(X,y), scoring=score).mean()\n cv2 = cross_val_score(classifier, X, y, cv=10, scoring=score)\n cv2_m = cv2.mean()\n cv2_sd = cv2.std()\n st.write(model + ' ' + score +\" : \" + str(round(cv2_m, 5))+ ' +- '+ str(round(cv2_sd, 5)))\n\n def r_classifier (X, y, alpha=1.0, fit_intercept=True, normalize=True, solver='auto', max_iter=1000, tol=0.0001) :\n reg = linear_model.RidgeClassifier(alpha=alpha, fit_intercept=fit_intercept, normalize=normalize, max_iter=max_iter, tol=0.001, solver='auto', random_state=30)\n print_performance(reg, X , y, model='Ridge Calssifier', scores= ['accuracy'])\n reg.fit(X,y)\n return reg \n\n def find_best_parameters (classifier, parameters, X, y):\n clf = GridSearchCV(classifier, parameters, cv=10)\n clf.fit(X, y)\n return clf.best_params_\n\nst.markdown('### L2 normalized data')\nridge = r_classifier(X,y, alpha=0.1)\nst.markdown('### z-scored data')\nridge_s = r_classifier(X,y, alpha=0.1, normalize=False)\nst.markdown('### L2 normalized data no location')\nridge_noloc = r_classifier(X_noloc,y, alpha=0.1)\nst.markdown('### L2 normalized data no location and mean')\nridge_2= r_classifier(X_2,y, alpha=0.1)\n\n# Show ridge_2\nR2_coef = np.array(ridge_2.coef_)\nX2_cols = X_2.columns\nR2_relativ = R2_coef/np.abs(R2_coef).sum()\n\n# Create dict\ntable = {'col':X2_cols, 'absolute':[], 'relative':[]}\nfor i in range(0,len(X2_cols)):\n table['absolute'].append(round(R2_coef[0,i],6))\n table['relative'].append(round(R2_relativ[0,i],6))\nFeatures = ['Fertility', 'Life Expectancy', 'Mortality Rate', 'Population Growth', '%Pop in Rural Areas']\n\nfig = go.Figure(data=[\n go.Bar(name='In Poverty', x=Features, y=table['relative'][1:6]),\n])\nfig.update_layout(barmode='group')\nst.plotly_chart(fig)\n\n# DONE \nst.balloons()","sub_path":"src/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":7434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"261599923","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\n这个是类似生成双色球,并将结果进行排序\n一共59个数,取其中7个\n简单做法 sorted(random.sample(range(1,59),7))\n'''\n\nimport random\n\ndef get_num(total,target):\n '''\n 用于获取中奖的数字\n \n Args:\n total: 一共有多少个数\n target: 取其中多少个数,target一定要小于total\n \n Returns:\n 返回一个不重复的无序数值列表,例如[5,30,27,13],\n 如果target大于等于total则返回[]\n '''\n if target >= total:\n return []\n \n bang = []\n pool = [x for x in range(1,total+1)]\n for i in range(target):\n ran = random.randint(1,total)\n bang.append(pool[ran])\n del pool[ran]\n return bang\n \ndef sort(list):\n '''\n Python 自带的sorted已经很厉害了\n 不过既然练手就自己写一个\n \n Args:\n list: 出入一个字符串,然后排序\n '''\n # 冒泡排序双for循环\n for i in range(len(list)-1):\n for j in range(1,len(list)):\n if list[j-1] > list[j]:\n list[j-1],list[j] = list[j],list[j-1]\n \n return list\n\ndef start():\n list = get_num(59,7)\n win = sort(list)\n print('获奖号码为:',win)\n \nif __name__ == '__main__':\n start()\n input('Please Enter...')\n","sub_path":"Python_basic/2.lottery.py","file_name":"2.lottery.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"641765859","text":"# -*- coding: iso-8859-15 -*-\nimport random\n\nVERTICAL = 0\nHORIZONTAL = 1\n\nclass Room(object):\n def __init__(self, x, y, w, h):\n self.childs = None\n self.sibling = None\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.rx = x + random.randint(1, 4)\n self.ry = y + random.randint(1, 4)\n \n self.rh = h - random.randint(1, 4)\n while self.rh - self.ry < 3:\n self.rh += 1\n \n self.rw = w - random.randint(1, 4)\n while self.rw - self.rx < 3:\n self.rw += 1\n \n self.split = None\n self.parent = None\n self.corridor = False\n \ndef split_room(room, vertical):\n #if room.parent != None:\n # if room.parent.parent != None:\n # if random.randint(0, 100) < 10:\n # return\n \n if vertical:\n split_line = (room.w - room.x) / 2 + random.randint(-3, 3)\n room1 = Room(room.x, room.y, room.x + split_line, room.h)\n room2 = Room(room.x + split_line, room.y, room.w, room.h)\n else:\n split_line = (room.h - room.y) / 2 + random.randint(-3, 3)\n room1 = Room(room.x, room.y, room.w, room.y + split_line)\n room2 = Room(room.x, room.y + split_line, room.w, room.h)\n room.split = vertical\n room1.parent = room\n room2.parent = room\n \n room.childs = [room1, room2]\n room1.sibling = room2\n room2.sibling = room1\n\ndef split(room, count):\n rooms = [room]\n for _ in xrange(count):\n new = []\n for r in rooms:\n if r.parent != None:\n split = not r.parent.split\n else:\n split = random.choice((True, False))\n split_room(r, split)\n if r.childs != None:\n new.extend(r.childs)\n rooms = []\n rooms.extend(new)\n\ndef connect_rooms(rooms, map_array, sy='*'):\n for r in rooms:\n #if r==None: return\n #if r.parent==None:continue\n if r.corridor: continue\n vert = r.parent.split\n\n if vert:\n s = r.sibling\n mm1 = max(r.ry + 1, s.ry + 1)\n mm2 = min(r.rh - 1, s.rh - 1)\n \n if mm1 != mm2:\n y = random.randint(mm1, mm2)\n else:\n y = mm1\n if r.x < s.x: v = r.rx + 1; b = s.rx + 1\n else: v = s.rx + 1 ;b = r.rx + 1\n \n while map_array[y][v] == '.':\n v += 1\n \n while map_array[y][b - 1] == '.':\n b += 1\n \n for x in xrange(v, b - 1):\n map_array[y][x] = sy\n r.corridor = s.corridor = True\n else:\n s = r.sibling\n mm1 = max(r.rx + 1, s.rx + 1)\n mm2 = min(r.rw - 1, s.rw - 1)\n \n if mm1 != mm2:\n x = random.randint(mm1, mm2)\n else:\n x = mm1\n\n if r.y < s.y: v = r.ry; b = s.ry + 1\n else: v = s.ry ;b = r.ry + 1\n \n while map_array[v][x] == '.':\n v += 1\n \n while map_array[b - 1][x] == '.':\n b += 1\n \n for y in xrange(v, b - 1):\n map_array[y][x] = '*'\n r.corridor = s.corridor = True\n\ndef get_all_rooms(room):\n rooms = [room]\n finish = False\n\n while not finish:\n new = []\n finish = True\n for r in rooms:\n if r.childs != None:\n new.extend(r.childs)\n finish = False\n else:\n new.append(r)\n if not finish:\n rooms = []\n rooms.extend(new)\n return rooms\n\ndef create(room):\n rooms = get_all_rooms(room)\n map_array = []\n for _ in xrange(room.h):\n line = []\n for _ in xrange(room.w):\n line.append('.')\n map_array.append(line)\n \n for r in rooms:\n for y in xrange(r.ry, r.rh):\n for x in xrange(r.rx, r.rw):\n map_array[y][x] = '*'\n \n connect_rooms(rooms, map_array)\n parents = set()\n [parents.add(r.parent) for r in rooms]\n# \n while len(parents) > 1:\n connect_rooms(parents, map_array)\n new = set()\n for r in parents:\n if r.parent != None:\n new.add(r.parent)\n parents = new\n return map_array\n# \n# for line in map_array:\n# l = ''\n# for s in line:\n# l = l + str(s)\n# print l \n\n\n \nif __name__ == \"__main__\":\n r1 = Room(0, 0, 100, 50)\n split(r1, 4)\n create(r1)\n \n \n","sub_path":"PDC/PDC_5/PDC/src/dungeon/bsd.py","file_name":"bsd.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"237018983","text":"from datapaths import projectPath, imagePath\nfrom resistics.project.io import loadProject\n\n# load the project and also provide a config file\nprojData = loadProject(projectPath, configFile=\"asciiconfig.ini\")\nprojData.printInfo()\n\nfrom resistics.project.time import viewTime\nfrom resistics.common.plot import plotOptionsTime, getPaperFonts\n\nplotOptions = plotOptionsTime(plotfonts=getPaperFonts())\nfig = viewTime(\n projData,\n \"2018-01-03 00:00:00\",\n \"2018-01-05 00:00:00\",\n polreverse={\"Hy\": True},\n plotoptions=plotOptions,\n save=False,\n)\nfig.savefig(imagePath / \"viewTime_polreverse\")\n\n# calculate spectrum using the new configuration\nfrom resistics.project.spectra import calculateSpectra\n\ncalculateSpectra(projData, calibrate=False, polreverse={\"Hy\": True})\nprojData.refresh()\n\n# plot spectra stack\nfrom resistics.project.spectra import viewSpectraStack\nfrom resistics.common.plot import plotOptionsSpec, getPaperFonts\n\nplotOptions = plotOptionsSpec(plotfonts=getPaperFonts())\nfig = viewSpectraStack(\n projData,\n \"site1\",\n \"meas\",\n coherences=[[\"Ex\", \"Hy\"], [\"Ey\", \"Hx\"]],\n plotoptions=plotOptions,\n save=False,\n show=False,\n)\nfig.savefig(imagePath / \"viewSpectraStack_config_polreverse\")\n\n# calculate impedance tensor\nfrom resistics.project.transfunc import processProject\n\nprocessProject(projData, outchans=[\"Ex\", \"Ey\"])\n\n# plot impedance tensor and save the plot\nfrom resistics.project.transfunc import viewImpedance\nfrom resistics.common.plot import plotOptionsTransferFunction\n\nplotoptions = plotOptionsTransferFunction(plotfonts=getPaperFonts())\nplotoptions[\"xlim\"] = [0.01, 1000000]\nplotoptions[\"phase_ylim\"] = [-10, 100]\nfigs = viewImpedance(\n projData,\n sites=[\"site1\"],\n oneplot=True,\n polarisations=[\"ExHy\", \"EyHx\"],\n plotoptions=plotoptions,\n save=True,\n)\nfigs[0].savefig(imagePath / \"impedance_config\")\n\n# process for the tipper\nprocessProject(projData, outchans=[\"Ex\", \"Ey\", \"Hz\"], postpend=\"withHz\")\n\nfrom resistics.project.transfunc import viewTipper\nfrom resistics.common.plot import plotOptionsTipper\n\nplotoptions = plotOptionsTipper(plotfonts=getPaperFonts())\nplotoptions[\"xlim\"] = [0.01, 1000000]\nfigs = viewTipper(\n projData, sites=[\"site1\"], postpend=\"withHz\", plotoptions=plotoptions, save=True\n)\nfigs[0].savefig(imagePath / \"impedance_config_withHz\")","sub_path":"cookbook/usingAscii/runWithConfig.py","file_name":"runWithConfig.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"360883931","text":"#{************************************}\n# Programa: Conjuntos\n# Autor: Villalobos Valenzuela Jesús Héctor\n# Fecha: 23/02/2020\n#{************************************}\nif __name__ == '__main__':\n conjunto = set()\n conjunto = {1,2,3,4,1,2,3,4,1,2,3,4}\n conjunto.add(\"H\")\n conjunto.add(\"A\")\n print(conjunto)\n\n print('Jesus' in conjunto)\n\n lista = list(conjunto)\n print(lista)","sub_path":"Colecciones de datos/Conjuntos.py","file_name":"Conjuntos.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"522036628","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nfrom argparse import ArgumentParser\n\n############################################################\nclass Function:\n \"\"\"\nan object that describes one occurrence of a function solution\nprovided in the corrections/ package\nit comes with a week number, a sequence number, \na function name, plus the code as a string\n \"\"\"\n def __init__ (self, week, sequence, name):\n self.week=week\n self.sequence=sequence\n self.name=name\n self.code=\"\"\n def add_line (self, line):\n \"convenience for the parser code\"\n self.code += line\n# corriges.py would have the ability to do sorting, but..\n# I turn it off because it is less accurate\n# functions appear in the right week/sequence order, but\n# not necessarily in the order of the sequence..\n# @staticmethod\n# def key (self):\n# return 100*self.week+self.sequence\n\n########################################\n # utiliser les {} comme un marqueur dans du latex ne semble pas\n # être l'idée du siècle -> je prends pour une fois %()s et l'opérateur %\n latex_format=r\"\"\"\n\\addcontentsline{toc}{section}{\n\\texttt{%(name)s} -- {\\small \\footnotesize{Semaine} %(week)s \\footnotesize{Séquence} %(sequence)s}\n%%%(name)s\n}\n\\begin{Verbatim}[frame=single,fontsize=\\%(size)s, samepage=true, numbers=left,\nframesep=3mm, framerule=3px,\nrulecolor=\\color{Gray},\n%%fillcolor=\\color{Plum},\nlabel=%(name)s - {\\small \\footnotesize{Semaine} %(week)s \\footnotesize{Séquence} %(sequence)s}]\n%(code)s\\end{Verbatim}\n\\vspace{1cm}\n\"\"\"\n # on peut tricher un peu si un problème ne rentre pas bien dans les clous\n # \\tiny, \\scriptsize, \\footnotesize, \\small, \\normalsize\n exceptions_size = { 'diff': 'footnotesize',\n# 'decode_zen' : 'small',\n }\n\n def latex (self):\n name = Latex.escape (self.name)\n week = self.week\n sequence = self.sequence\n size = Function.exceptions_size.get(self.name,'small')\n code = self.code\n return self.latex_format % locals()\n\n########################################\n text_format = r\"\"\"\n##################################################\n# %(name)s - Semaine %(week)s Séquence %(sequence)s\n##################################################\n%(code)s\n\"\"\"\n def text (self):\n return self.text_format %self.__dict__\n\n############################################################\n# as of dec. 11 2014 all files are UTF-8 and that's it\nclass Source (object):\n\n def __init__ (self, filename):\n self.filename = filename\n\n def parse (self):\n \"return a list of Function objects\"\n function = None\n functions = []\n with open(self.filename) as input:\n for line in input:\n if '@BEG@' in line:\n index = line.find(\"@BEG@\")\n end_of_line = line[index+5:].strip()\n try:\n week, sequence, name = end_of_line.split(' ')\n function = Function (week, sequence, name)\n except:\n print (\"ERROR - ignored {} in {}\".format(line,self.filename))\n elif '@END@' in line:\n functions.append(function)\n function = None\n elif function:\n function.add_line(line)\n return functions\n\n############################################################\nclass Latex (object):\n\n header=r\"\"\"\\documentclass [12pt]{article}\n\\usepackage[utf8]{inputenc}\n\\usepackage[francais]{babel}\n%% for Verbatim\n\\usepackage{fancyvrb}\n\\usepackage[usenames,dvipsnames]{color}\n\\setlength{\\oddsidemargin}{0cm}\n\\setlength{\\textwidth}{16cm}\n\\setlength{\\topmargin}{0cm}\n\\setlength{\\textheight}{21cm}\n\\setlength{\\headsep}{1.5cm}\n\\setlength{\\parindent}{0.5cm}\n\\begin{document}\n\\centerline{\\huge{%(title)s}}\n\\vspace{2cm}\n\"\"\"\n\n contents=r\"\"\"\n\\tableofcontents\n\\newpage\n\"\"\"\n\n\n footer=r\"\"\"\n\\end{document}\n\"\"\"\n\n def __init__ (self, filename):\n self.filename = filename\n\n def write (self, functions, title, contents):\n with open(self.filename, 'w') as output:\n output.write (Latex.header%(dict(title=title)))\n if contents:\n output.write(Latex.contents)\n for function in functions:\n output.write (function.latex())\n output.write (Latex.footer)\n print (\"{} (over)written\".format(self.filename))\n\n @staticmethod\n def escape (str):\n return str.replace (\"_\",r\"\\_\")\n\n########################################\n\nclass Text (object):\n \n def __init__ (self, filename):\n self.filename = filename\n\n header = \"\"\"# -*- coding: iso-8859-15 -*-\n############################################################ \n#\n# %(title)s\n#\n############################################################\n\"\"\"\n \n\n def write (self, functions, title):\n with open (self.filename, 'w') as output:\n output.write (self.header%dict(title=title))\n for function in functions:\n output.write (function.text())\n print (\"{} (over)written\".format(self.filename))\n\ndef main ():\n parser = ArgumentParser ()\n parser.add_argument (\"-o\",\"--output\", default=None)\n parser.add_argument (\"-t\",\"--title\", default=\"Donnez un titre avec --title\")\n parser.add_argument (\"-c\",\"--contents\", action='store_true', default=False)\n parser.add_argument (\"-L\",\"--latex\", action='store_true', default=False)\n parser.add_argument (\"-T\",\"--text\", action='store_true', default=False)\n parser.add_argument (\"files\", nargs='+')\n args = parser.parse_args()\n\n functions = []\n for filename in args.files:\n functions += Source(filename).parse()\n\n if args.latex:\n do_latex = True; do_text = False\n elif args.text:\n do_latex = False; do_text = True\n else:\n do_latex = True; do_text = True\n\n output = args.output if args.output else \"corriges\"\n texoutput = \"{}.tex\".format(output)\n txtoutput = \"{}.txt\".format(output)\n if do_latex:\n Latex(texoutput).write (functions, title=args.title, contents=args.contents)\n if do_text:\n Text (txtoutput).write (functions, title=args.title)\n\nif __name__ == '__main__':\n main ()\n","sub_path":"tools/corriges.py","file_name":"corriges.py","file_ext":"py","file_size_in_byte":6340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"124873650","text":"import io\nfrom urllib.request import urlopen\nfrom PIL import Image, ImageTk\n\nclass Helper:\n def getImage(show):\n if show.image == \"\": return None\n \n imgBuffer = urlopen(show.image).read()\n imgBytes = io.BytesIO(imgBuffer)\n imgFull = Image.open(imgBytes)\n imgMin = imgFull.resize((150, 150))\n photo = ImageTk.PhotoImage(imgMin)\n \n return photo","sub_path":"Helper.py","file_name":"Helper.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"563761029","text":"import pytest\nfrom inheritance import Car\nfrom random import randint\nfrom inheritance import Star\nfrom inheritance import Planet\n\nclass TestsTesla:\n def test_tesla_popltn1(self):\n tesla = Car('Roadster', 2,3,[], 6)\n tesla.send_peeps_here(1)\n assert tesla.population == 1\n \n @pytest.mark.mark1\n @pytest.mark.mark2\n def test_tesla_popltn2(self):\n tesla = Car('Roadster', 2,3,[], 6)\n tesla.send_peeps_here(2)\n assert tesla.population == 2, 'Wrong population!!!111'\n \n @pytest.mark.mark1\n def test_tesla_popltn_dot5(self):\n tesla = Car('Roadster', 2,3,[], 6)\n tesla.send_peeps_here(.5)\n assert tesla.population == .5\n @pytest.mark.mark2\n def test_tesla_popltn_1000(self):\n tesla = Car('Roadster', 2,3,[], 6)\n tesla.send_peeps_here(1000)\n assert tesla.population == 2\n\n \n@pytest.mark.parametrize('mass', [randint(0,1000) for x in range(5)])\n@pytest.mark.parametrize('density', [randint(0,1000) for y in range(5)])\n@pytest.mark.parametrize('radius', [randint(0,1000) for y in range(5)])\nclass TestsParametrizedCar:\n names = ['Roadster', 'Model S', 'SpaceX'] \n @pytest.mark.parametrize(('name_expected'), names)\n def test_car_name_positive(self, name_expected, mass, density, radius):\n #name_expected = 'Roadster'\n tesla = Car(name_expected, mass, density,[], radius)\n assert tesla.name == name_expected\n \n def test_car_name_whitespace_negative(self, mass, density, radius):\n name_not_alnum = 'Tesla-Roadster'\n with pytest.raises(NameError):\n Car(name_not_alnum, mass, density,[], radius)\n\t\t\t\n@pytest.mark.parametrize('n', [randint(0,1000) for x in range(10)])\nclass TestsStarPopulation:\n def test_star_popltn(self, n):\n stars = Star('Star1', 2,3,[], 6)\n stars.send_peeps_here(n)\n assert stars.population == 0\n\t\t\t\n@pytest.mark.parametrize('mass', [randint(0,9000000) for x in range(5)])\n@pytest.mark.parametrize('density', [randint(0,9000000) for y in range(5)])\n@pytest.mark.parametrize('radius', [randint(0,9000000) for y in range(5)])\nclass TestsParametrizedStar:\n names = ['LHS 2924', 'Проксіма Центавра', 'Альфа Центавра A', 'Альфа Центавра B','Сіріус А', 'Сіріус B', 'Мю Цефея', 'Зірка Барнарда', 'Зірка у Пістолеті', 'HD189733b','М31','NGC 224'] \n @pytest.mark.parametrize(('name_expected'), names)\n def test_star_name_positive(self, name_expected, mass, density, radius):\n stars = Star(name_expected, mass, density,[], radius)\n assert stars.name == name_expected\n \n names_not_alnum = ['','LHS-2924', 'Проксіма.Центавра', 'Альфа/Центавра А', 'Альфа Центавра\\'B','Сіріус,А', 'Сіріус;B', 'Мю\\Цефея', 'Зірка=Барнарда', 'Зірка[уПістолеті', 'HD189733{b','М_31','NG(C224'] \n @pytest.mark.parametrize(('name_not_alnum'), names_not_alnum)\n def test_star_name_negative(self, name_not_alnum, mass, density, radius):\n with pytest.raises(NameError):\n Star(name_not_alnum, mass, density,[], radius)\n\t\t\t\n@pytest.mark.parametrize('mass', [randint(0,100000) for x in range(5)])\n@pytest.mark.parametrize('density', [randint(0,100000) for y in range(5)])\n@pytest.mark.parametrize('radius', [randint(0,100000) for y in range(5)])\nclass TestsParametrizedPlanet:\n names = ['Аврора','Альфа','Анакреонт','Арктур','Асконь','Асперта','Баронн','Бонда','Ванда','Вега','Венкорі','Вінсеторі','Ворег','Гамма Андромеда','Гелікон','Геторин','Гесперос','Гея','Гліпталь IV', 'HD1897332b','М321','NGC 2324'] \n @pytest.mark.parametrize(('name_expected'), names)\n def test_planet_name_positive(self, name_expected, mass, density, radius):\n planets = Planet(name_expected, mass, density,[], radius, 1)\n assert planets.name == name_expected\n \n names_not_alnum = ['','Авр-ора','Аль.фа','Анак\\реонт','А/рктур','Аскон,ь','Ас;перта','Барон=н','Б[онд��','В{анда','В_ега','Венк(орі','Вінс`еторі','Во\\'рег','Гамма\"Андромеда']\n @pytest.mark.parametrize(('name_not_alnum'), names_not_alnum)\n def test_planet_name_negative(self, name_not_alnum, mass, density, radius):\n with pytest.raises(NameError):\n Planet(name_not_alnum, mass, density,[], radius, 1)\n","sub_path":"universe/test_inheritance.py","file_name":"test_inheritance.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"285461627","text":"#!/usr/bin/python3\n\"\"\"Defines a function that adds text to a file after every line where a\ngiven substring is found\"\"\"\n\n\ndef append_after(filename=\"\", search_string=\"\", new_string=\"\"):\n \"\"\"Adds text to a file after every line where a given substring\n is found\"\"\"\n with open(filename, \"r+\") as f:\n text = \"\"\n for line in f:\n if search_string in line:\n line += new_string\n text += line\n f.seek(0)\n f.write(text)\n","sub_path":"0x0B-python-input_output/100-append_after.py","file_name":"100-append_after.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"361434069","text":"import pickle \nimport random\nimport sys\n\nimport veceval as ve\nimport numpy as np\nnp.random.seed(ve.SEED)\n\nfrom trainer import Trainer\nfrom index_datasets import IndexWindowCapsDataset\n\nfrom keras.models import Sequential\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.core import Dense, Dropout, Activation, Reshape\n\nclass ChunkFinetunedTrainer(Trainer):\n def __init__(self, config_path, name):\n # Define constants and paths\n self.TASK = ve.CHUNK\n self.MODE = ve.FINE\n self.name = name\n (self.train_data_path, self.checkpoint_path,\n self.embedding_path) = ve.make_paths(self.TASK, self.MODE, self.name)\n \n # Get embeddings\n self.embeddings = pickle.load(open(self.embedding_path, 'r'))\n self.ds = IndexWindowCapsDataset(self.train_data_path, self.embeddings,\n has_validation=False, is_testing=ve.IS_TESTING)\n\n # Define model \n self.hp = ve.read_hp(config_path)\n self.hp.stop_epochs = ve.STOP_EPOCHS\n self.model = self.build_model()\n\n def build_model(self):\n model = Sequential()\n model.add(Embedding(input_dim=len(self.ds.vocab),\n output_dim=ve.EMBEDDING_SIZE,\n weights=[self.ds.weights],\n input_length=ve.WINDOW_SIZE))\n model.add(Reshape((ve.EMBEDDING_SIZE * ve.WINDOW_SIZE,)))\n model.add(Dense(output_dim=ve.HIDDEN_SIZE))\n model.add(Activation(ve.TANH))\n model.add(Dropout(ve.DROPOUT_PROB))\n model.add(Dense(input_dim=ve.HIDDEN_SIZE, output_dim=ve.CHUNK_CLASSES))\n model.add(Activation(ve.SOFTMAX))\n ve.compile_other_model(model, self.hp.optimizer)\n return model\n\n\ndef main():\n config_path, name = sys.argv[1:3]\n trainer = ChunkFinetunedTrainer(config_path, name)\n trainer.train_and_test()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"training/chunk_finetuned.py","file_name":"chunk_finetuned.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"41017063","text":"\"\"\"\nsentry.quotas.redis\n~~~~~~~~~~~~~~~~~~~\n\n:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.\n:license: BSD, see LICENSE for more details.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport functools\nimport six\n\nfrom time import time\n\nfrom sentry.exceptions import InvalidConfiguration\nfrom sentry.quotas.base import NotRateLimited, Quota, RateLimited\nfrom sentry.utils.redis import get_cluster_from_options, load_script\n\nis_rate_limited = load_script('quotas/is_rate_limited.lua')\n\n\nclass BasicRedisQuota(object):\n __slots__ = ['key', 'limit', 'window', 'reason_code', 'enforce']\n\n def __init__(self, key, limit=0, window=60, reason_code=None, enforce=True):\n self.key = key\n # maximum number of events in the given window, 0 indicates \"no limit\"\n self.limit = limit\n # time in seconds that this quota reflects\n self.window = window\n # a machine readable string\n self.reason_code = reason_code\n # should this quota be hard-enforced (or just tracked)\n self.enforce = enforce\n\n\nclass RedisQuota(Quota):\n #: The ``grace`` period allows accomodating for clock drift in TTL\n #: calculation since the clock on the Redis instance used to store quota\n #: metrics may not be in sync with the computer running this code.\n grace = 60\n\n def __init__(self, **options):\n self.cluster, options = get_cluster_from_options('SENTRY_QUOTA_OPTIONS', options)\n super(RedisQuota, self).__init__(**options)\n self.namespace = 'quota'\n\n def validate(self):\n try:\n with self.cluster.all() as client:\n client.ping()\n except Exception as e:\n raise InvalidConfiguration(six.text_type(e))\n\n def __get_redis_key(self, key, timestamp, interval, shift):\n return '{}:{}:{}'.format(\n self.namespace,\n key,\n int((timestamp - shift) // interval),\n )\n\n def get_quotas(self, project, key=None):\n if key:\n key.project = project\n pquota = self.get_project_quota(project)\n oquota = self.get_organization_quota(project.organization)\n results = [\n BasicRedisQuota(\n key='p:{}'.format(project.id),\n limit=pquota[0],\n window=pquota[1],\n reason_code='project_quota',\n ),\n BasicRedisQuota(\n key='o:{}'.format(project.organization.id),\n limit=oquota[0],\n window=oquota[1],\n reason_code='org_quota',\n ),\n ]\n if key:\n kquota = self.get_key_quota(key)\n results.append(\n BasicRedisQuota(\n key='k:{}'.format(key.id),\n limit=kquota[0],\n window=kquota[1],\n reason_code='key_quota',\n )\n )\n return results\n\n def get_usage(self, organization_id, quotas, timestamp=None):\n if timestamp is None:\n timestamp = time()\n\n def get_usage_for_quota(client, quota):\n if quota.limit == 0:\n return None\n\n return client.get(\n self.__get_redis_key(\n quota.key, timestamp, quota.window, organization_id % quota.window\n ),\n )\n\n def get_value_for_result(result):\n if result is None:\n return None\n\n return int(result.value or 0)\n\n with self.cluster.fanout() as client:\n results = map(\n functools.partial(\n get_usage_for_quota,\n client.target_key(\n six.text_type(organization_id),\n ),\n ),\n quotas,\n )\n\n return map(\n get_value_for_result,\n results,\n )\n\n def is_rate_limited(self, project, key=None, timestamp=None):\n if timestamp is None:\n timestamp = time()\n\n quotas = [\n quota for quota in self.get_quotas(project, key=key)\n # x = (key, limit, interval)\n if quota.limit > 0 # a zero limit means \"no limit\", not \"reject all\"\n ]\n\n # If there are no quotas to actually check, skip the trip to the database.\n if not quotas:\n return NotRateLimited()\n\n def get_next_period_start(interval, shift):\n \"\"\"Return the timestamp when the next rate limit period begins for an interval.\"\"\"\n return (((timestamp - shift) // interval) + 1) * interval + shift\n\n keys = []\n args = []\n for quota in quotas:\n shift = project.organization_id % quota.window\n keys.append(self.__get_redis_key(quota.key, timestamp, quota.window, shift))\n expiry = get_next_period_start(quota.window, shift) + self.grace\n args.extend((quota.limit, int(expiry)))\n\n client = self.cluster.get_local_client_for_key(six.text_type(project.organization.pk))\n rejections = is_rate_limited(client, keys, args)\n if any(rejections):\n enforce = False\n worst_case = (0, None)\n for quota, rejected in zip(quotas, rejections):\n if not rejected:\n continue\n if quota.enforce:\n enforce = True\n shift = project.organization_id % quota.window\n delay = get_next_period_start(quota.window, shift) - timestamp\n if delay > worst_case[0]:\n worst_case = (delay, quota.reason_code)\n if enforce:\n return RateLimited(\n retry_after=worst_case[0],\n reason_code=worst_case[1],\n )\n return NotRateLimited()\n","sub_path":"src/sentry/quotas/redis.py","file_name":"redis.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"144591970","text":"import torch\nimport cv2\nimport torch.nn.functional as F\nfrom dogcat import Net ##重要,虽然显示灰色(即在次代码中没用到),但若没有引入这个模型代码,加载模型时会找不到模型\nfrom torchvision import datasets, transforms\nfrom PIL import Image\nimport os\n \nclasses = ('cat', 'dog')\nif __name__ == '__main__':\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = torch.load('model/Resnet_001.pth') # 加载模型\n model = model.to(device)\n model.eval() # 把模型转为test模式\n\n root = r\"D:\\Windows\\Projects\\Resnet\\test\"\n imgs = [os.path.join(root, img) for img in os.listdir(root)]\n for img_path in imgs:\n origin_img = cv2.imread(img_path) # 读取要预测的图片\n img = Image.fromarray(cv2.cvtColor(origin_img, cv2.COLOR_BGR2RGB))\n trans = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n ])\n\n img = trans(img)\n img = img.to(device)\n img = img.unsqueeze(0) # 图片扩展多一维,因为输入到保存的模型中是4维的[batch_size,通道,长,宽],而普通图片只有三维,[通道,长,宽]\n output = model(img)\n prob = F.softmax(output, dim=1) # prob是2个分类的概率\n print(prob)\n value, predicted = torch.max(output.data, 1)\n print(predicted.item())\n print(value)\n pred_class = classes[predicted.item()]\n print(pred_class)\n cv2.putText(origin_img, pred_class, (54, 80), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 125, 255), 3, cv2.LINE_AA)\n cv2.imshow(\"classify\", origin_img)\n key = cv2.waitKey(3000)\n if key & 0xFF == ord('q'):\n break","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"158093702","text":"#!/usr/bin/env python3\n\"\"\"Nicolas Gampierakis (2019). Derives CT^2.\n\"\"\"\n\nimport re\nimport data_parser as dp\nimport path_weighting as pw\n\n\ndef derive_ct2(data_file):\n \"\"\"Derives the CT^2 structure parameter from measured Cn^2,\n and external weather data.\n\n Args:\n data_file (str): the name of the data file, without the .mnd\n extension, located in ../data/SRun/ folder\n Returns:\n derived (pandas.dataFrame): data frame containing derived CT^2\n alongside weather conditions\n \"\"\"\n scint_data = dp.scintillometer_parse(data_file)\n scint_data[\"Cn2\"] = (scint_data[\"Cn2\"]) / 2032 ** (-3) * 1031.5 ** (-3)\n # scrub extra characters from file name\n day = re.sub(\"[^0-9\\-]\", \"\", data_file)\n # placeholder until we can access acinn data\n # acinn_data = dp.weather_download(day, \"off\")\n acinn_data = dp.weather_download(day)\n\n derived = scint_data.filter([\"Cn2\"], axis=1)\n kelvin = 273.15\n # merge weather and scintillometer data according to datetimes\n # derived = derived.join(acinn_data[[\"temperature\", \"pressure\",\n # \"windspeed\"]])\n derived = derived.join(acinn_data[[\"t\", \"ldred\", \"wg\", \"wr\"]]).rename(\n columns={\n \"t\": \"temperature\",\n \"ldred\": \"pressure\",\n \"wg\": \"windspeed\",\n \"wr\": \"wind_dir\",\n }\n )\n # # adjust values\n derived[\"temperature\"] = derived[\"temperature\"] + kelvin\n derived[\"pressure\"] = derived[\"pressure\"] # convert to Pa\n derived[\"windspeed\"] = derived[\"windspeed\"] / 3.6 # convert to ms^-1\n\n transmit_lambda = 880 * (10 ** -9) # m\n lambda_2 = 7.53 * (10 ** -3) # micron^2\n lambda_2 = lambda_2 / (10 ** 6) ** 2\n alpha_factor_2 = 77.6 * (10 ** -6) # K hPa^-1\n alpha_factor_1 = alpha_factor_2 * (1 + (lambda_2 / transmit_lambda))\n\n # This equation is accurate to 10^-5, but doesn't account for humidity\n # fluctuations - errors should be within 3% of inverse Bowen ratio\n # (Moene 2003)\n\n derived[\"CT2\"] = (\n derived[\"Cn2\"]\n * (derived[\"temperature\"] ** 4)\n * ((alpha_factor_1 * derived[\"pressure\"]) ** -2)\n )\n\n derived = derived.tz_convert(\"CET\")\n\n return derived\n\n\ndef kinematic_shf(dataframe, z_eff):\n k = 0.4 # von Karman constant\n g = 9.81\n dataframe[\"Q_0\"] = (\n 1.165\n * k\n * z_eff\n * (dataframe[\"CT2\"] ** (3 / 4))\n * (g / dataframe[\"temperature\"]) ** (1 / 2)\n )\n return dataframe\n\n\ndef compute_fluxes(file_name, z_eff):\n r_d = 287.05 # J kg^-1 K^-1, specific gas constant for dry air\n cp = 1004 # J kg^-1 K^-1, heat capacity of air\n dataframe = derive_ct2(file_name)\n # Calculate kinematic surface heat flux\n dataframe = kinematic_shf(dataframe, z_eff)\n # Air density\n dataframe[\"rho_air\"] = (\n 100 * dataframe[\"pressure\"] / (r_d * dataframe[\"temperature\"])\n )\n # Surface sensible heat flux under free convection (little wind shear,\n # high instability)\n dataframe[\"H_free\"] = dataframe[\"Q_0\"] * cp * dataframe[\"rho_air\"]\n return dataframe\n\n\ndef data_processor(filename, station):\n # Get effective path height\n z_eff = pw.return_z_effective(station)\n # Derive CT2, merge weather data, calculate free convection fluxes\n dataframe = compute_fluxes(filename, z_eff)\n processed_data = {\"computed\": dataframe, \"effective_height\": z_eff}\n return processed_data\n","sub_path":"Pycode/cn_derivations.py","file_name":"cn_derivations.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"488625256","text":"import requests\nimport json\n# update pass in getPass() \nimport privatepass\nfrom arcgis.gis import GIS\nfrom arcgis.features import Feature\nfrom arcgis.geometry import Point\n\nimport datetime\n\nidArr = []\nmeasuresDict = {}\nmeasuresDict[\"values\"] = []\n\n# function parse the data from netatmo and share the infos in measuresDict\ndef parseData(resultJson):\n # get the body\n body = resultJson['body']\n # for each item flatten the value\n for item in body:\n \n measureFlat = {}\n measureFlat[\"_id\"] = item[\"_id\"]\n # check that the value is unique if multiple request send back the same infos\n if(measureFlat[\"_id\"] in idArr ):\n continue\n else:\n idArr.append(measureFlat[\"_id\"])\n\n measureFlat[\"X\"] = item[\"place\"][\"location\"][0]\n measureFlat[\"Y\"] = item[\"place\"][\"location\"][1]\n measureFlat[\"altitude\"] = item[\"place\"][\"altitude\"]\n #default value empty\n measureFlat[\"temperature\"] = \"\"\n measureFlat[\"humidity\"] =\"\"\n measureFlat[\"pressure\"] =\"\"\n #rain\n measureFlat[\"rain_60min\"] =\"\"\n measureFlat[\"rain_24h\"] =\"\"\n measureFlat[\"rain_live\"] = \"\"\n measureFlat[\"rain_timeutc\"] = \"\"\n #wind\n measureFlat[\"wind_strength\"] =\"\"\n measureFlat[\"wind_angle\"] =\"\"\n measureFlat[\"gust_strength\"] = \"\"\n measureFlat[\"gust_angle\"] = \"\"\n measureFlat[\"wind_timeutc\"] = \"\"\n \n \n \n \n # set values\n for key,val in item[\"measures\"].items():\n if \"type\" in val:\n #pression or temp/hum\n if val[\"type\"] == ['temperature', 'humidity']:\n measureFlat[\"temperature\"] = next(iter(val[\"res\"].values()))[0]\n measureFlat[\"humidity\"] = next(iter(val[\"res\"].values()))[1]\n if val[\"type\"] == ['pressure']:\n measureFlat[\"pressure\"] = next(iter(val[\"res\"].values()))[0]\n #if rain\n if \"rain_60min\" in val:\n measureFlat[\"rain_60min\"] = val[\"rain_60min\"]\n measureFlat[\"rain_24h\"] = val[\"rain_24h\"]\n measureFlat[\"rain_live\"] = val[\"rain_live\"]\n measureFlat[\"rain_timeutc\"] = val[\"rain_timeutc\"]\n #if wind\n if \"wind_strength\" in val:\n measureFlat[\"wind_strength\"] = val[\"wind_strength\"]\n measureFlat[\"wind_angle\"] =val[\"wind_angle\"]\n measureFlat[\"gust_strength\"] = val[\"gust_strength\"]\n measureFlat[\"gust_angle\"] = val[\"gust_angle\"]\n measureFlat[\"wind_timeutc\"] = val[\"wind_timeutc\"]\n measuresDict[\"values\"].append(measureFlat)\n\n\n\n\n\n\n# First we need to authenticate, give back an access_token used by requests\n# https://dev.netatmo.com/resources/technical/guides/authentication/refreshingatoken\n# for initial request of token see https://dev.netatmo.com/resources/technical/guides/authentication/clientcredentials \npayload = {'grant_type': 'refresh_token',\n 'client_id': privatepass.getClientId(),\n 'client_secret': privatepass.getClientSecret(),\n 'refresh_token' : privatepass.getRefreshToken(),\n 'scope': 'read_station'}\ntry:\n response = requests.post(\"https://api.netatmo.com/oauth2/token\", data=payload)\n response.raise_for_status()\n access_token=response.json()[\"access_token\"]\n refresh_token=response.json()[\"refresh_token\"]\n scope=response.json()[\"scope\"]\n \nexcept requests.exceptions.HTTPError as error:\n print(error.response.status_code, error.response.text)\n\n\n\n'''\nnetatmo data is dependent on extent queried, the more you zoom the more you\n\nhttps://dev.netatmo.com/en-US/resources/technical/guides/ratelimits\nPer user limits\n50 requests every 10 seconds\n> One global request, and multiple litle on a specific area, while staying under api limit\n'''\n\n# first global request\n\npayload = {'access_token': access_token,\n 'lat_ne':52.677040100097656,\n 'lon_ne': 13.662185668945312,\n 'lat_sw' : 52.374916076660156,\n 'lon_sw':13.194580078125\n # filter wierd/wrong data \n ,'filter': 'true'\n }\ntry:\n response = requests.post(\"https://api.netatmo.com/api/getpublicdata\", data=payload)\n response.raise_for_status()\n resultJson=response.json()\n parseData(resultJson)\n \nexcept requests.exceptions.HTTPError as error:\n print(error.response.status_code, error.response.text)\n\n\n\nbase_lat_ne = 52.677040100097656\nbase_lon_ne = 13.662185668945312\nbase_lat_sw = 52.374916076660156\nbase_lon_sw = 13.194580078125\n\n\n# calc each subextent size\nlon_step = (base_lon_ne - base_lon_sw)/4\nlat_step = (base_lat_ne - base_lat_sw)/4\n\ncurrentStep=0\n\n# we cut the extent in x/x and go through each sub-extent\nlat_sw = base_lat_sw\nwhile(lat_sw < base_lat_ne):\n lat_ne = lat_sw + lat_step\n #reset the lon_sw\n lon_sw = base_lon_sw\n while(lon_sw < base_lon_ne):\n lon_ne = lon_sw + lon_step\n payload = {'access_token': access_token,\n 'lat_sw' : lat_sw,\n 'lon_sw':lon_sw,\n 'lat_ne':lat_ne,\n 'lon_ne': lon_ne,\n # filter wierd/wrong data \n 'filter': 'true'\n }\n try:\n currentStep=currentStep+1\n #print(str(lat_ne) + \" \" + str(lon_ne))\n response = requests.post(\"https://api.netatmo.com/api/getpublicdata\", data=payload)\n response.raise_for_status()\n resultJson=response.json()\n # parse the data\n parseData(resultJson)\n except requests.exceptions.HTTPError as error:\n print(error.response.status_code, error.response.text)\n lon_sw = lon_ne\n lat_sw = lat_ne\n\n\n\n# last part - json can be dumped in a file for test purpose or geoevent server integration\n#with open('dataNetAtmo.json', 'w') as outfile: \n# json.dump(measuresDict, outfile)\n\n# or we can get each object and push it as a feature !\n\n# connect to to the gis\n# get the feature layer\ngis = GIS(\"https://esrich.maps.arcgis.com\", \"cede_esrich\", privatepass.getPass()) \nnetAtmoFl = gis.content.get('0078c29282174460b57ce7ca72262549').layers[0] \n\nfeaturesToAdd = []\n'''\" sample value\n _id\": \"70:ee:50:3f:4d:26\",\n \"X\": 13.5000311,\n \"Y\": 52.5020974,\n \"altitude\": 37,\n \"temperature\": 10.4,\n \"humidity\": 71,\n \"pressure\": 1018.1,\n \"rain_60min\": \"\",\n \"rain_24h\": \"\",\n \"rain_live\": \"\",\n \"rain_timeutc\": \"\",\n \"wind_strength\": \"\",\n \"wind_angle\": \"\",\n \"gust_strength\": \"\",\n \"gust_angle\": \"\",\n \"wind_timeutc\": \"\"\n '''\n\nfor measure in measuresDict[\"values\"]:\n attr = dict()\n attr[\"id\"] = measure[\"_id\"]\n attr[\"altitude\"] = measure[\"altitude\"]\n attr[\"temperature\"] = measure[\"temperature\"]\n attr[\"humidity\"] = measure[\"humidity\"]\n attr[\"pressure\"] = measure[\"pressure\"]\n attr[\"rain_60min\"] = measure[\"rain_60min\"]\n attr[\"rain_24h\"] = measure[\"rain_24h\"]\n attr[\"rain_live\"] = measure[\"rain_live\"]\n attr[\"rain_timeutc\"] = measure[\"rain_timeutc\"]\n attr[\"wind_strength\"] = measure[\"wind_strength\"]\n attr[\"wind_angle\"] = measure[\"wind_angle\"]\n attr[\"gust_strength\"] = measure[\"gust_strength\"]\n attr[\"gust_angle\"] = measure[\"gust_angle\"]\n attr[\"wind_timeutc\"] = measure[\"wind_timeutc\"]\n lat = measure[\"Y\"]\n lon = measure[\"X\"]\n pt = Point({\"x\" : lon, \"y\" : lat, \"spatialReference\" : {\"wkid\" : 4326}})\n feature = Feature(pt,attr)\n featuresToAdd.append(feature)\n#add all the points \n#test\n#netAtmoFl.manager.truncate()\nnetAtmoFl.edit_features(adds=featuresToAdd)","sub_path":"NetAtmo.py","file_name":"NetAtmo.py","file_ext":"py","file_size_in_byte":7717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"322860608","text":"import unittest\nimport p11\n\nclass IsUniqueTest(unittest.TestCase):\n\n def test_false_cases(self):\n cases = ['a'*257, 'aa', 'aba']\n for c in cases:\n self.assertFalse(p11.is_unique(c))\n\n def test_true_cases(self):\n cases = ['', 'a', 'ab', 'abc']\n for c in cases:\n self.assertTrue(p11.is_unique(c))\n\n","sub_path":"ctci/c1/test_p11.py","file_name":"test_p11.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"167200810","text":"#https://projecteuler.net/problem=2\n\nimport Eulerlib\n\n#We have to start the Fibonacci sequence with two 1's\nx, y = 1, 1\n\n#Start timer to time algorithm\nstart = Eulerlib.getTime()\n\n#This will just add up the even numbers of the Fibonacci sequence less than 4000000\nwhile y < 4000000:\n y += x\n x = y - x\n if y % 2 == 0:\n Eulerlib.answer += y\n\n#Stop timer to time algorithm\nend = Eulerlib.getTime()\n\n#The answer should be 4613732\nprint (\"The answer was found in %f seconds\" % (end - start))\nprint (\"And the answer is: %d\" % Eulerlib.answer)\n","sub_path":"Python/p002.py","file_name":"p002.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"268427522","text":"#!/usr/bin/python3\n\n\nimport pandas as pd \nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom preprocess import text_process\n\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.utils import shuffle\nimport time\n\n\n\n# read SMS.csv file \ndf = pd.read_csv('SMS.csv', encoding = \"ISO-8859-1\")\nprint('\\nReading csv file ....')\n\n\n# shuffle data\nX, Y = shuffle(df['Full_Text'], df['IsSpam'])\n\n\n\n# function to convert into numerical labels\ndef binary_class(x):\n\tif x=='yes':\n\t\treturn 1\n\telse:\n\t\treturn 0\n\n# convert all labels to 0 or 1\nY = Y.apply(binary_class)\n\n\n\n\n# create a pipeline\npipeline = Pipeline([\n\t('bow', CountVectorizer(analyzer=text_process)),\n\t('tfidf', TfidfTransformer(use_idf=True, smooth_idf=True)),\n\t('classifier', MultinomialNB())\n\t])\n\n\n\n\n# define the number for K-fold cross validation\nkfold=10\n\nprint('\\nApplying %d-fold cross-validation using Naïve-Bayes ...' % kfold)\nprint('\\n')\n\n\nstart = time.time()\n# estimate f1-score using kfold cross validation \nf1_scores = cross_val_score(pipeline, X, Y, \n\tcv=kfold, scoring='f1')\n\nprint('F1-score: %.3f (+/- %.3f) time: %.3f sec' % (f1_scores.mean(), \n\t2*f1_scores.std(), (time.time()-start)) )\n\n\n\nstart = time.time()\n# estimate precision using kfold cross validation \nprecisions = cross_val_score(pipeline, X, Y, \n\tcv=kfold, scoring='precision')\n\nprint('Precision: %.3f (+/- %.3f) time: %.3f sec' % (precisions.mean(), \n\t2*precisions.std(), (time.time()-start)) )\n\n\n\nstart = time.time()\n# estimate recall using kfold cross validation \nrecalls = cross_val_score(pipeline, X, Y, \n\tcv=kfold, scoring='recall')\n\nprint('Recall: %.3f (+/- %.3f) time: %.3f sec' % (recalls.mean(), \n\t2*recalls.std(), (time.time()-start)) )\n","sub_path":"naiveBayes.py","file_name":"naiveBayes.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"412319233","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 3/14/18 10:48 PM\n# @Author : Saseny.Zhou\n# @File : path.py\n\n\nimport sys\nimport time\nfrom Logs.log import *\nfrom Functions.json_file import *\nfrom Config.config import *\nimport re\n\n\"\"\"路径定义\"\"\"\nbaseDir = os.path.split(os.path.dirname(sys.argv[0]))[0]\nresources = os.path.join(baseDir, \"Resources\")\ndebugLogPath = os.path.join(resources, \"logs\", \"debug.log\")\nimagePath = os.path.join(resources, \"images\")\nconfigJsonPath = os.path.join(resources, \"config.json\")\nerrorJsonPath = os.path.join(resources, \"error.json\")\nunitJsonPath = os.path.join(resources, \"units.json\")\nhistoryJsonPath = os.path.join(resources, \"history.json\") # 记录上次所使用的功能,当再次打开时自动选择上次\nerrorMessageJsonPath = os.path.join(resources, \"errorInfo.json\")\n\n\"\"\"实例化运行数据收集\"\"\"\ncollectionData = log_collection(log_path=\"/tmp/logs.log\", debug_log=debugLogPath)\ncollectionData.run()\n\n\"\"\"检测配置文件是否存在,不存在则新建默认配置文件\"\"\"\nif not os.path.isfile(configJsonPath):\n collectionData.logger.info(\"配置文件不存在,重新生成默认配置文件: {}\".format(configJsonPath))\n write_json_file(configInfo, configJsonPath)\n\n\ndef match(rule, text):\n tb = re.compile(rule)\n find = tb.findall(str(text))\n return find\n","sub_path":"Desktop/BurninTools/0.1.9/Path/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"341936365","text":"filename = '__tests__/logs/log.log'\n\n\nresult = []\npos = []\nwhile True:\n try:\n with open(filename, 'rb') as f:\n for p, s in pos:\n f.read(p)\n f.read(s)\n a = f.read()\n a.decode('utf-16-be')\n break\n except UnicodeDecodeError as err:\n # print(err)\n msg = err.__str__()\n st = ''\n i = 49\n while True:\n s = msg[i]\n if s == ':':\n break\n st += s\n i += 1\n first, second = map(int, st.split('-'))\n pos.append( (first, second-first) )\n # print(pos)\nprint(pos)\n\n\nwith open(filename, 'rb') as f:\n for p, s in pos:\n result.append(f.read(p))\n f.read(s)\n result.append(f.read())\n\n# result = list(map(lambda x: x.decode('utf-16-be'), result))\nprint(len(result))\nresult = (b''.join(result)).split(b'\\r\\n')\nprint(len(result))\nresult = [i for i in result if b'Mixed Content' not in i]\nprint(len(result))\nresult = b''.join(result)\nprint(len(result))\n\n\nwith open('__tests__/logs/l.log', 'w', encoding='utf-16-be') as f:\n f.write(result.decode('utf-16-be'))\n","sub_path":"__tests__/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"262801004","text":"#!/usr/bin/env python\nimport rospy\nimport tf\nfrom sensor_msgs.msg import PointCloud2, PointField\nimport sensor_msgs.point_cloud2 as pc2\nimport numpy\nimport sys\nimport struct\nimport ctypes\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport numpy as np\nimport matplotlib.image as mpimg\nimport ros_numpy\nimport numpy as np\n \nclass DepthReader:\n def __init__(self):\n rospy.init_node('depth_node', anonymous=True)\n self.hz = 50\n self.depth_points = rospy.Subscriber(\"/camera/depth/color/points\", PointCloud2, self.depth_callback)\n self.ready = False\n fig = plt.figure()\n self.data = np.zeros((300, 300))\n self.im = plt.imshow(self.data, cmap='gray', vmin=0, vmax=255)\n anim = animation.FuncAnimation(fig, self.animate, init_func=self.init, frames=30,\n interval=250)\n plt.show()\n\n def init(self):\n self.im.set_data(np.zeros((1000,1000)))\n \n \n def animate(self,i):\n if self.ready:\n self.im.set_data(self.data)\t\n \n self.data = np.zeros((300, 300))\n self.ready = False\t\n return self.im\n\n \n def depth_callback(self, point_cloud):\n #min_x = 0\n #min_y = 0\n #max_x = 0\n #max_y = 0\n \n #pointcloud2_array = list(pc2.read_points(point_cloud,field_names=(\"x\",\"y\",\"z\"),skip_nans=True))\n\n #print(pointcloud2_array)\n \"\"\"\n for p in pc2.read_points(point_cloud, field_names = (\"x\", \"y\", \"z\", \"rgb\"), skip_nans=True):\n rgb = p[3]\n r = (rgb & 0x00FF0000)>> 16\n g = (rgb & 0x0000FF00)>> 8\n b = (rgb & 0x000000FF)\n gray = (r + b + g)/3\n self.data[int(150+p[1]*100)][int(150+p[0]*100)] = int(gray*100)\n \"\"\"\n sensor = ros_numpy.point_cloud2.pointcloud2_to_xyz_array(point_cloud)\n zs = sensor[:,-1:].squeeze()\n\n xs = sensor[:,0:1].squeeze()\n xs = np.round(xs*100)+150\n xs = xs.astype(int)\n\n ys = sensor[:,1:2].squeeze()\n ys = np.round(ys*100)+150\n ys = ys.astype(int)\n ys[ys>300] = 299\n ys[ys<0] = 0\n\n xs[xs>300] = 299\n xs[xs<0] = 0\n\n self.data[ys,xs] = zs*100\n #print(sensor[:,3])\n print(np.max(self.data))\n \n \n #print \" x : %f y: %f z: %f\" %(p[0],p[1],p[2])\n self.ready = True\n #plt.show()\n #print(min_y)\n #print(max_y)\n \n \n def run(self):\n rate = rospy.Rate(self.hz)\n while not rospy.is_shutdown():\n rate.sleep()\n\n \nif __name__ == '__main__':\n depth = DepthReader()\n depth.run()\n\n\n","sub_path":"src/realsense-ros-2.2.8/realsense2_camera/scripts/depth_reader.py","file_name":"depth_reader.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"406120136","text":"from flask import Flask, render_template, request, jsonify\nimport time\nimport flask\nimport os\nimport json\nfrom functions import prediction\nfrom flask_cors import CORS, cross_origin\n#app = Flask(__name__)\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n\n@app.route(\"/\")\ndef home():\n print(\"Hola mundo\")\n return \"hola mundo version 2\"\n\n@app.route(\"/get_users_products\", methods=['POST','GET'])\ndef get_prods_users():\n if flask.request.method == 'POST':\n data = request.get_json(force=True)\n print(data)\n user = int(data['user'])\n store = data['store']\n modelo = data['model']\n try:\n dic = prediction.predict.user_products(user,store)\n except:\n print(\"error\")\n dic=prediction.predict.get_promociones()\n return json.dumps(dic),200\n \n@app.route(\"/get_promotions\", methods=['POST','GET'])\ndef get_proms():\n if flask.request.method == 'POST':\n dic = prediction.predict.get_promociones()\n return json.dumps(dic),200\n \n@app.route(\"/get_products\", methods=['POST','GET'])\ndef get_products():\n if flask.request.method == 'POST':\n dic = prediction.predict.get_items()\n return json.dumps(dic),200\n\n@app.route(\"/recommended_by_user\",methods=['POST', 'GET'])\ndef get_recomm_by_user():\n if flask.request.method == 'POST':\n data = request.get_json(force=True)\n print(data)\n user = int(data['user'])\n store = data['store']\n modelo = data['model']\n print(modelo)\n if modelo == \"knn\":\n try:\n print (\"Si hay knn\")\n dic = prediction.predict.user_knn(user,store)\n except:\n print(\"no hay knn\")\n dic = prediction.predict.user(user,store)\n else: \n dic = prediction.predict.user(user,store)\n return json.dumps(dic),200\n\n@app.route(\"/recommended_by_item\",methods=['POST', 'GET'])\ndef similar_items():\n if flask.request.method == 'POST':\n print(\"Recomendando por item\")\n data = request.get_json(force=True)\n item = data['item']\n store = data['store']\n dic = prediction.predict.similar_items(item,store)\n return json.dumps(dic),200\n\n@app.route(\"/recommended_by_apriori\",methods=['POST', 'GET'])\ndef apriori():\n if flask.request.method == 'POST':\n print(\"Recomendando por apriori\")\n data = request.get_json(force=True)\n item = data['item']\n store = data['store']\n try:\n print (\"apriori\")\n dic = prediction.predict.apriori_model(item,store)\n except:\n print (\"no apriori\")\n dic = {}\n return json.dumps(dic),200\n \nif __name__ == \"__main__\":\n #app.run(debug=True, port=5050)\n app.run(host='0.0.0.0', port=5050)\n #app.run(host='0.0.0.0')\n \n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"472174755","text":"from scipy import *\nfrom pylab import *\n\n# Thickness of hBN Film\nd = 83.0e-9\n\n# Load Complex Dielectric Function Data\nlambda1, n_r, n_i = loadtxt(\"hBN_RTConstZ32.txt\", usecols=(0,1,2), unpack = True)\n\n# Calculate Complex Refractive Index\nnc = n_r + 1j*n_i\neps = nc**2\n\n\n# Calculate Complex Propagation Constant\nk0 = 2.0*pi/(lambda1*1.0e-6)\nk=k0*nc\n\n# Calculate (Power) Transmision from the result of problem 5.11 \n# from: http://eceweb1.rutgers.edu/~orfanidi/ewa/ch05.pdf\n# Note j --> -i Convention in formula below\nR1= 1.0 - abs(1.0/(cos(k*d)-1j*(nc+1.0/nc)*sin(k*d)/2.0))**2# Load FDTD Transmission Data\n\nlambda2, RFDTD= loadtxt(\"hBN_RTConstZ32.txt\", usecols=(0,2,), unpack = True)\n\n# Formatting and Plotting\nrc('axes', linewidth=2)\ntick_params(width=2, labelsize=20)\n\nxlim(200,2000)\nylabel(\"T\", fontsize = '30')\nxlabel(r'$\\lambda (\\mu m)$', fontsize = '30')\n\n#plot(k0, R1, label=r'$T_{Theory}$', color='red')\nplot(1/(lambda2*1e-4), RFDTD, label=r'$T_{FDTD: getindex Constant Z}$', color='blue' )\n#legend(loc='upper right', fontsize='20')\n\nshow()\n","sub_path":"RefK.py","file_name":"RefK.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"385093123","text":"from flask import Flask, render_template\n\napp = Flask(__name__)\n\n@app.route('/')\n@app.route('/index')\ndef index():\n user = dict(name='Chris', email='wcbeard10@gmail.com')\n return render_template('index.html',\n user=user)\n\n# from flask import Flask, jsonify, render_template, request\n# app = Flask(__name__)\n# app.debug = True\n\n# # @app.route('/_add_numbers')\n# # def add_numbers():\n# # \"\"\"Add two numbers server side, ridiculous but well...\"\"\"\n# # a = request.args.get('a', 0, type=int)\n# # b = request.args.get('b', 0, type=int)\n# # return jsonify(result=a + b)\n\n\n# @app.route('/')\n# def index():\n# return render_template('index.html')\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"513787242","text":"from django.contrib import admin\nfrom markdownx.admin import MarkdownxModelAdmin\n\nfrom app.models import Category, Tag, Post, ContentImage\n\n\nclass ContentImageInline(admin.TabularInline):\n model = ContentImage\n extra = 1\n\n\nclass PostAdmin(admin.ModelAdmin):\n inlines = [\n ContentImageInline,\n ]\n\n\nadmin.site.register(Category)\nadmin.site.register(Tag)\n\nadmin.site.register(Post, MarkdownxModelAdmin)","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"368699192","text":"\n# https://github.com/eternnoir/pyTelegramBotAPI\n\nimport telebot\n\ntoken = \"876288218:AAGwZhJQw38ppbnsZxG5Ik7gSM6_Buf4HHU\"\n\nbot = telebot.TeleBot(token)\n\ndef FefiVocal(a):\n if(a == 'a'): \n return 'i'\n if(a == 'e'): \n return 'i'\n if(a == 'o'): \n return 'i'\n if(a == 'u'): \n return 'i'\n return a\n\n@bot.message_handler(commands=['dictator'])\ndef route_fefify(message):\n print(message)\n print(message.chat.username)\n\n fefiedMsg = message.text\n\n fefiedMsg = fefiedMsg.split(' ')\n\n fefiedMsg.pop(0)\n\n fefiedMsg = ' '.join(fefiedMsg)\n print(fefiedMsg)\n \n fefiedMsg = ''.join([FefiVocal(x) for x in fefiedMsg])\n print(fefiedMsg)\n bot.reply_to(message,fefiedMsg)\n pass\n\n@bot.message_handler(func=lambda message: True)\ndef echo_all(message):\n\tbot.reply_to(message, message.text)\n\nprint(\"bot listening\")\nbot.polling()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"47700612","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport time\nimport json\nimport getpass\nimport argparse\n\nfrom pathlib import Path\nfrom subprocess import Popen, PIPE\n\nhome = str(Path.home())\nif sys.platform == 'win32':\n VBoxManage = ' \"C:\\\\Program Files\\\\Oracle\\\\VirtualBox\\\\VBoxManage.exe\" '\nelse:\n VBoxManage = 'VBoxManage'\n\nparser = argparse.ArgumentParser(description='Create VM, deploy VM')\nparser.add_argument('-n', '--vm_name', help='vm_name', required=True)\nparser.add_argument('-f', '--vm_base_folder', help='vm_base_folder', default='VirtualBox VMs')\nparser.add_argument('-i', '--vm_source_iso_file', help='vm_source_iso_file', required=True)\nparser.add_argument('-c', '--vm_config_file', help='vm_config_file', required=True)\nparser.add_argument('-s', '--vm_disk_size', type=str, help='vm_disk_size', default='20480') # 20gb\nparser.add_argument('-m', '--steps', help='steps to deploy', type=str, nargs='+', required=True, choices=['create', 'install', 'configure'])\nargs = parser.parse_args()\n\nvm_base_folder = os.path.join(home, args.vm_base_folder)\nvm_root = os.path.join(vm_base_folder, args.vm_name)\nvm_disk_filename = os.path.join(vm_base_folder, args.vm_name, \"disc0.vdi\")\n\n# vm_ssh_user = getpass.getuser()\n# vm_ssh_key = home + \"/.ssh/id_rsa.pub\"\n# vm_hostonlyadapter_ip = \"192.168.44.1\"\n# vboxtftp = vm_basefolder + \"/tftp\"\n# PXELINUX = \"./pxelinux.0\"\n\n\nkey_codes = {\n '0': '0b 8b',\n '1': '02 82',\n '2': '03 83',\n '3': '04 84',\n '4': '05 85',\n '5': '06 86',\n '6': '07 87',\n '7': '08 88',\n '8': '09 89',\n '9': '0a 8a',\n\n 'a': '1e 9e', 'A': '2a 1e aa 9e',\n 'b': '30 b0', 'B': '2a 30 aa b0',\n 'c': '2e ae', 'C': '2a 2e aa ae',\n 'd': '20 a0', 'D': '2a 20 aa a0',\n 'e': '12 92', 'E': '2a 12 aa',\n 'f': '21 a1', 'F': '2a 21 aa a1',\n 'g': '22 a2', 'G': '2a 22 aa a2',\n 'h': '23 a3', 'H': '2a 23 aa a3',\n 'i': '17 97', 'I': '2a 17 aa',\n 'j': '24 a4', 'J': '2a 24 aa a4',\n 'k': '25 a5', 'K': '2a 25 aa a5',\n 'l': '26 a6', 'L': '2a 26 aa a6',\n 'm': '32 b2', 'M': '2a 32 aa b2',\n 'n': '31 b1', 'N': '2a 31 aa b1',\n 'o': '18 98', 'O': '2a 18 aa',\n 'p': '19 99', 'P': '2a 19 aa',\n 'q': '10 90', 'Q': '2a 10 aa',\n 'r': '13 93', 'R': '2a 13 aa',\n 's': '1f 9f', 'S': '2a 1f aa 9f',\n 't': '14 94', 'T': '2a 14 aa',\n 'u': '16 96', 'U': '2a 16 aa',\n 'v': '2f af', 'V': '2a 2f aa af',\n 'w': '11 91', 'W': '2a 11 aa',\n 'x': '2d ad', 'X': '2a 2d aa ad',\n 'y': '15 95', 'Y': '2a 15 aa',\n 'z': '2c ac', 'Z': '2a 2c aa ac',\n\n ',': '33 b3',\n '.': '34 b4',\n '/': '35 b5',\n '\\\\': '2b ab',\n ':': '2a 27 aa a7',\n '%': '2a 06 aa 86',\n '_': '2a 0c aa 8c',\n '&': '2a 08 aa 88',\n '(': '2a 0a aa 8a',\n ')': '2a 0b aa 8b',\n ';': '27 a7',\n '\"': '2a 28 aa a8',\n \"'\": '28 a8',\n '|': '2a 2b aa 8b',\n '[': '1a 9a',\n ']': '1b 9b',\n '<': '2a 33 aa b3',\n '>': '2a 34 aa b4',\n '$': '2a 05 aa 85',\n '+': '2a 0d aa 8d',\n '-': '0c 8c',\n '=': '0d 8d',\n '*': '2a 09 aa 89',\n '?': '2a 35 aa b5',\n '^': '07 87'\n}\n\nbutton_codes = {\n 'Enter': '1c 9c',\n 'Backspace': '0e 8e',\n 'Spacebar': '39 b9',\n 'Return': '1c 9c',\n 'Esc': '01 81',\n 'Tab': '0f 8f',\n 'F1': '3B BB',\n 'F2': '3C BC',\n 'F3': '3D BD',\n 'F4': '3E BE',\n 'F5': '3F BF',\n 'F6': '40 C0',\n 'F7': '41 C1',\n 'F8': '42 C2',\n 'F9': '43 C3',\n 'F10': '44 C4',\n 'F11': '57 D7',\n 'F12': '58 D8',\n\n 'UP': '48 C8',\n 'DOWN': '50 D0',\n 'LEFT': '4B CB',\n 'RIGHT': '4D CD',\n\n 'HOME': '47 C7',\n 'END': '4F CF',\n\n 'PGUP': '49 C9',\n 'PGDN': '51 D1'\n}\n\n\ndef chars_to_codes(chars):\n c = []\n for one in chars:\n c.append(key_codes[one])\n return ' '.join(c)\n\n\ndef buttons_to_codes(buttons):\n c = []\n for one in buttons.split(' '):\n c.append(button_codes[one])\n return ' '.join(c)\n\n\ndef call(params):\n print(params)\n with Popen(' '.join(params), shell=True, stdout=PIPE) as proc:\n stdout = proc.stdout.readlines()\n print(stdout)\n return stdout\n\n\ndef press_enter_and_wait(delay):\n call([VBoxManage, \"controlvm\", args.vm_name, \"keyboardputscancode\", buttons_to_codes('Enter')])\n time.sleep(delay)\n\n\ndef type_command(params, delay_after_enter):\n call(params)\n press_enter_and_wait(delay_after_enter)\n\n\nif __name__ == '__main__':\n\n if 'create' in args.steps:\n VBOXINFO = call([VBoxManage, \"showvminfo\", args.vm_name])\n\n VBOXINFO = call([VBoxManage, \"unregistervm\", args.vm_name, \"--delete\"])\n\n VBOXINFO = call(\n [VBoxManage, \"createvm\", \"--name\", args.vm_name, \"--basefolder\", '\"%s\"' % vm_base_folder, \"--ostype\", \"ubuntu_64\",\n \"--register\"])\n\n # base memory\n VBOXINFO = call([VBoxManage, \"modifyvm\", args.vm_name, \"--cpus\", \"1\", \"--memory\", \"1024\", \"--vram\", \"128\"])\n # set boot order\n VBOXINFO = call([VBoxManage, \"modifyvm\", args.vm_name, \"--boot1\", \"dvd\", \"--boot2\", \"disk\", \"--boot3\", \"none\"])\n # set acpi\n VBOXINFO = call([VBoxManage, \"modifyvm\", args.vm_name, \"--acpi\", \"on\"])\n # set pae\n VBOXINFO = call([VBoxManage, \"modifyvm\", args.vm_name, \"--pae\", \"on\"])\n # set hardware virtualization\n VBOXINFO = call([VBoxManage, \"modifyvm\", args.vm_name, \"--hwvirtex\", \"on\"])\n # network interface - nat for the outside world\n VBOXINFO = call([VBoxManage, \"modifyvm\", args.vm_name, \"--nic1\", \"nat\"])\n\n # 'C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe' setextradata kubuntu VBoxInternal2/SharedFoldersEnableSymlinksCreate/arena_streams 1\n\n VBOXINFO = call(\n [VBoxManage, \"createhd\", \"--filename\", '\"%s\"' % vm_disk_filename, \"--size\", args.vm_disk_size, \"--format\", \"VDI\"])\n VBOXINFO = call(\n [VBoxManage, \"storagectl\", args.vm_name, \"--name\", '\"Disk Controller\"', \"--add\", \"sata\", \"--hostiocache\", \"on\"])\n VBOXINFO = call(\n [VBoxManage, \"storageattach\", args.vm_name, \"--storagectl\", '\"Disk Controller\"', \"--port\", \"0\", \"--device\", \"0\", \"--type\",\n \"hdd\", \"--medium\", '\"%s\"' % vm_disk_filename])\n VBOXINFO = call([VBoxManage, \"storagectl\", args.vm_name, \"--name\", '\"DVD IDE Controller\"', \"--add\", \"ide\"])\n VBOXINFO = call(\n [VBoxManage, \"storageattach\", args.vm_name, \"--storagectl\", '\"DVD IDE Controller\"', \"--type\", \"dvddrive\", \"--port\", \"0\",\n \"--device\", \"0\", \"--medium\", args.vm_source_iso_file])\n VBOXINFO = call([VBoxManage, \"startvm\", args.vm_name])\n\n if 'install' in args.steps:\n with open(args.vm_config_file) as f:\n conf = json.loads(f.read())\n\n install_steps = conf['install']\n for one in install_steps:\n if 'comment' in one:\n print(one['comment'])\n if 'type' in one:\n call([VBoxManage, \"controlvm\", args.vm_name, \"keyboardputscancode\", chars_to_codes(one['type'])])\n if 'press' in one:\n call([VBoxManage, \"controlvm\", args.vm_name, \"keyboardputscancode\", buttons_to_codes(one['press'])])\n if 'timeout' in one:\n time.sleep(one['timeout'])\n\n if 'configure' in args.steps:\n VBOXINFO = call([VBoxManage, \"showvminfo\", vm])\n # login\n call([VBoxManage, \"controlvm\", args.vm_name, \"keyboardputscancode\", chars_to_codes('ubuntu')])\n press_enter_and_wait(2)\n # password\n call([VBoxManage, \"controlvm\", args.vm_name, \"keyboardputscancode\", chars_to_codes('ubuntu')])\n press_enter_and_wait(2)\n","sub_path":"vm.py","file_name":"vm.py","file_ext":"py","file_size_in_byte":7559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"307228952","text":"\"\"\"Server for Tweet generator app\"\"\"\n\nfrom jinja2 import StrictUndefined\nfrom flask import Flask, jsonify, render_template, request\nfrom tweet import get_all_tweets, make_chains, make_a_phrase\n\n\napp = Flask(__name__)\n\n# Raises an error if using an undefined variable in Jinja2\napp.jinja_env.undefined = StrictUndefined\n\n\n@app.route(\"/\")\ndef index():\n \"\"\"Shows the homepage.\"\"\"\n\n return render_template(\"index.html\")\n\n\n@app.route(\"/markov-chains.json\")\ndef get_markov_chains():\n \"\"\"Returns generated markov chain tweet\"\"\"\n\n twitter_handle = request.args.get(\"handle\")\n\n # Get Tweets for that user\n tweets = get_all_tweets(twitter_handle)\n\n # Make dictionary of Markov chains (bigrams)\n chains = make_chains(tweets)\n\n # Produce random phrase that is 140 characters or less\n tweet = make_a_phrase(chains)\n\n\n return jsonify({\"tweet\": tweet, \"len\": len(tweet)})\n\n\nif __name__ == \"__main__\":\n app.run(port=5000, host='0.0.0.0')","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"554360419","text":"import tkinter as tk\n\ndef relief_button(row, col):\n Frame1 = tk.Frame(window, borderwidth= 50)\n Frame1.grid(row=row, column=col)\n mymessage=tk.Label (Frame1, relief='raised',anchor='center', text=\"test\", bd=20)\n mymessage.grid(padx= 20, pady= 20)\n\ndef handle_click(event):\n label1[\"text\"] = \"Button Clicked!\"\n\ndef handle_enter(event):\n label1[\"text\"] = \"Mouse Enter!\"\n\ndef handle_leave(event):\n label1[\"text\"] = \"Mouse Leave!\"\n\nwindow = tk.Tk()\nwindow.geometry(\"400x300\")\n\nlabel1 = tk.Label(text=\"\")\nlabel1.grid(row=3, column=3)\nrelief_button(1, 3)\nbutton = tk.Button(text=\"Click me!\")\nbutton.grid(row=1, column=3)\n\nbutton.bind(\"\", handle_click)\nbutton.bind(\"\", handle_leave)\nbutton.bind(\"\", handle_enter)\n\nwindow.mainloop()\n","sub_path":"Gui/button_press.py","file_name":"button_press.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"74611046","text":"from collections import defaultdict\n\n\nclass Controller:\n def __init__(self,base, view):\n self.aim = None\n self.view = view\n self.base = base\n self.T = defaultdict(list)\n self.features = defaultdict(list)\n\n for index in range(len(base)):\n self.T[base[index].conclusion[0]].append(index)\n\n for item in base:\n for k,v in item.condition.items():\n if v not in self.features[k]:\n self.features[k].append(v)\n\n for k in self.features.keys():\n self.features[k].append('не знаю')\n\n self.is_end = False\n self.known = {}\n self.taken_rules = []\n self.stack_aim = []\n self.tresh_rules = []\n\n self.ans = 'есть ответ'\n\n def get_stack_aim(self):\n return 'Стек целей: '+str(self.stack_aim)\n\n def get_known(self):\n return 'Контекстный стек: ' + str(self.known)\n\n def get_list_aims(self):\n return list(self.T.keys())\n\n def run(self, aim):\n find_rule = self.T[aim][0]\n self.stack_aim.append((aim, find_rule))\n self.aim = aim\n while not self.is_end:\n is_any_rule = False\n # print(self.stack_aim)\n # print(self.known)\n\n self.view.set_text(self.get_stack_aim() + '\\n' + self.get_known() +'\\n\\n')\n\n if len(self.stack_aim) > 0 and self.stack_aim[-1][1] >= 0: # надо еще посмотреть правило\n # анализируем последнее правило в стеке правил\n cur_rule = self.stack_aim[-1][1]\n cur_feat = self.stack_aim[-1][0]\n val_rule = '+'\n cur_rule_conditions = self.base[cur_rule].condition\n\n for feat_name in cur_rule_conditions.keys():\n if feat_name not in self.known:\n val_rule = '?'\n elif self.known[feat_name] != cur_rule_conditions[feat_name]:\n val_rule = '-'\n break\n\n if val_rule == '?':\n features = []\n for feat in self.base[cur_rule].condition.keys():\n if feat not in self.known:\n if feat in self.T:\n rule_indexes = [i for i in self.T[feat] if i not in self.tresh_rules]\n rule_index = rule_indexes[0]\n\n else:\n rule_index = -1 # у признака нет правила для анализа\n features.append([feat, rule_index])\n\n if len(features) > 0:\n self.stack_aim.append(features[0]) # первый неизвестный признак\n\n if val_rule == '-':\n self.tresh_rules.append(cur_rule)\n self.stack_aim.pop()\n rule_indexes = [i for i in self.T[cur_feat] if i not in self.tresh_rules]\n if rule_indexes:\n self.stack_aim.append([cur_feat, rule_indexes[0]])\n else:\n # если нет подходящего правила\n self.stack_aim.append([cur_feat, -1])\n\n if val_rule == '+':\n self.taken_rules.append(cur_rule)\n self.stack_aim.pop()\n feat, val = self.base[cur_rule].conclusion\n self.known[feat] = val\n\n else:\n if not is_any_rule:\n if len(self.stack_aim) == 0:\n self.is_end = True\n else:\n if self.stack_aim[-1][0] == self.aim:\n self.ans = 'нет ответа'\n else:\n question = self.stack_aim[-1][0]\n self.known[self.stack_aim[-1][0]] = self.view.get_text(question)\n\n self.stack_aim.pop()\n # print(self.ans)\n self.view.set_text('\\n\\n' + self.ans)\n\n","sub_path":"artificial-intelligence/lab1/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"450249183","text":"import smtplib, ssl\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nfrom configuration import (\n settings,\n logger as setting_logger\n)\n\nlogger = setting_logger.get_logger(__name__)\n\n\ndef send(email_from, email_to, subject, template, variables={}):\n msg = MIMEMultipart('alternative')\n msg['Subject'] = subject\n msg['From'] = email_from\n msg['To'] = email_to\n\n template = settings.jinja_env.get_template(template)\n html = template.render(variables)\n\n text = \"Пожалуйста используйте html версию письма.\"\n mime_text = MIMEText(text, 'plain')\n html_text = MIMEText(html, 'html')\n\n msg.attach(mime_text)\n msg.attach(html_text)\n\n logger.info(f'Send email to {email_to}')\n\n with smtplib.SMTP_SSL(settings.EMAIL_URL, settings.EMAIL_PORT) as server:\n server.ehlo()\n server.login(settings.EMAIL_USERNAME, settings.EMAIL_PASSWORD)\n server.sendmail(email_from, email_to, msg.as_string())\n\n logger.info(f'Email to {email_to} sent')\n","sub_path":"application/utils/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"350549186","text":"'''\nGiven a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.\n\nAn example is the root-to-leaf path 1->2->3 which represents the number 123.\n\nFind the total sum of all root-to-leaf numbers.\n\nNote: A leaf is a node with no children.\n\nExample:\n\nInput: [1,2,3]\n 1\n / \\\n 2 3\nOutput: 25\nExplanation:\nThe root-to-leaf path 1->2 represents the number 12.\nThe root-to-leaf path 1->3 represents the number 13.\nTherefore, sum = 12 + 13 = 25.\nExample 2:\n\nInput: [4,9,0,5,1]\n 4\n / \\\n 9 0\n / \\\n5 1\nOutput: 1026\nExplanation:\nThe root-to-leaf path 4->9->5 represents the number 495.\nThe root-to-leaf path 4->9->1 represents the number 491.\nThe root-to-leaf path 4->0 represents the number 40.\nTherefore, sum = 495 + 491 + 40 = 1026.\n'''\n###############################################################################\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n rep=[root]\n val=[0]\n result=0\n while rep:\n len_rep=len(rep)\n while len_rep>0:\n cur_root=rep.pop(0)\n cur_val=val.pop(0) \n if cur_root.left or cur_root.right:\n if cur_root.left:\n rep.append(cur_root.left)\n val.append(10*cur_val+cur_root.val)\n if cur_root.right:\n rep.append(cur_root.right)\n val.append(10*cur_val+cur_root.val)\n else:\n result=result+10*cur_val+cur_root.val\n len_rep-=1\n return result\n ##############################################################################3\n # Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def sumNumbers(self, root):\n if root is None:\n return 0 \n rep=0\n return self.subsunNumbers(root,rep)\n \n def subsunNumbers(self,root,rep):\n if root is None:\n return 0\n if root.left or root.right:\n return self.subsunNumbers(root.left,10*rep+root.val)+self.subsunNumbers(root.right,10*rep+root.val)\n else:\n return 10*rep+root.val\n","sub_path":"Tree/00129. Sum Root to Leaf Numbers.py","file_name":"00129. Sum Root to Leaf Numbers.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"495971765","text":"#!/bin/python\nimport re\nfrom sys import argv\nfrom gzip import open as gzopen\n\nconsensusTadFile=argv[1]\ncnvResultFiles=argv[2]\n\nchromosomeList=[str(x) for x in range(1,23)]+[\"X\",\"Y\"]\n\ndef natural_sort(l): \n convert = lambda text: int(text) if text.isdigit() else text.lower() \n alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] \n return sorted(l, key = alphanum_key)\n\nvalidChromosomes={str(x) for x in range(1,23)}\nvalidChromosomes.add(\"X\")\nvalidChromosomes.add(\"Y\")\n\nchrToIndex = {str(x):x for x in range(1,23)}\nchrToIndex[\"X\"]=23\nchrToIndex[\"Y\"]=24\n\n\nclass TAD:\n def __init__(self,chromosome,start,end,index,cytoband,genes,cancerGenes):\n self.chromosome=chromosome\n self.start=start\n self.end=end\n self.index=index\n self.donorIndicesGain=set()\n self.donorIndicesLoss=set()\n self.donorIndicesLoh=set()\n def printTad(self,donorConverter):\n if self.chromosome in validChromosomes and (len(self.donorIndicesGain)>0 or len(self.donorIndicesLoss)>0):\n donorsStrGain=','.join(natural_sort([donorConverter[x] for x in self.donorIndicesGain]))\n if donorsStrGain==\"\":\n donorsStrGain=\"NA\"\n donorsStrLoss=','.join(natural_sort([donorConverter[x] for x in self.donorIndicesLoss]))\n if donorsStrLoss==\"\":\n donorsStrLoss=\"NA\"\n donorsStrLoh=','.join(natural_sort([donorConverter[x] for x in self.donorIndicesLoh]))\n if donorsStrLoh==\"\":\n donorsStrLoh=\"NA\"\n print(self.index,donorsStrLoss,donorsStrGain,donorsStrLoh,sep='\\t')\nclass TadIntersector:\n def __init__(self):\n self.tads=[]\n with open(consensusTadFile) as f:\n for line in f:\n lineChunks=line.rstrip().split('\\t')\n self.tads.append(TAD(*lineChunks))\n self.donorIndices=dict()\n self.maxDonorIndex=0\n def processResults(self,tadResults):\n with gzopen(tadResults,'rt') as f:\n for line in f:\n lineChunks=line.rstrip().split('\\t')\n tadIndex=int(lineChunks[0])\n cnvTypes=lineChunks[1].split(',')\n lohTypes=[x for x in lineChunks[2].split(',') if x!=\".\"]\n donor=lineChunks[3]\n if donor not in self.donorIndices:\n self.maxDonorIndex+=1\n self.donorIndices[donor] = self.maxDonorIndex\n if any([\"gain\" in x for x in cnvTypes]):\n self.tads[tadIndex-1].donorIndicesGain.add(self.donorIndices[donor])\n if any([\"loss\" in x for x in cnvTypes]):\n self.tads[tadIndex-1].donorIndicesLoss.add(self.donorIndices[donor])\n if len(lohTypes) > 0:\n self.tads[tadIndex-1].donorIndicesLoh.add(self.donorIndices[donor])\n def printDb(self):\n donorIndicesInverse = {v: k for k, v in self.donorIndices.items()}\n for tad in self.tads:\n tad.printTad(donorIndicesInverse)\n\ntmpObj=TadIntersector()\ntmpObj.processResults(cnvResultFiles)\n \nprint(\"tadIndex\",\"lossDonors\",\"gainDonors\",\"lohDonors\",sep='\\t')\ntmpObj.printDb()\n","sub_path":"06-cohortAnalysisForEPISTEME/WES/recurrenceTools/multiInterCnvs.py","file_name":"multiInterCnvs.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"421252142","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.management import call_command\nfrom django.http import HttpResponse, HttpResponseRedirect\n\nfrom BuildingSpeakApp.models import UserProfile\nfrom BuildingSpeakApp.models import UserSettingsForm\n\n\n@login_required\ndef staff_main(request):\n current_user = request.user\n if not current_user.is_staff: raise PermissionDenied\n email = current_user.email\n \n #---branching for POST vs. GET request\n if request.method == 'POST': # If a form has been submitted...\n if 'get_bldg_ES_xml' in request.POST:\n building_id = request.POST['building_id']\n try:\n call_command('SendEmail', email, 'get_building_energystar_xml', building_id)\n messages.success(request, 'XML has been emailed.')\n except:\n messages.error(request, 'XML delivery failed.')\n return HttpResponseRedirect('/staff/')\n elif 'get_meter_end_dates' in request.POST:\n try:\n call_command('SendEmail', email, 'get_latest_meter_end_dates')\n messages.success(request, 'Meter end dates have been emailed.')\n except:\n messages.error(request, 'Meter end dates delivery failed.')\n return HttpResponseRedirect('/staff/')\n elif 'check_meter_forecasts' in request.POST:\n try:\n call_command('SendEmail', email, 'check_meter_forecasts')\n messages.success(request, 'Latest forecasted months for Meters have been emailed.')\n except:\n messages.error(request, 'Failed to email latest forecasted months for Meters.')\n return HttpResponseRedirect('/staff/')\n elif 'get_financial_summary' in request.POST:\n try:\n call_command('SendEmail', email, 'get_financial_summary')\n messages.success(request, 'Financial summary emailed.')\n except:\n messages.error(request, 'Financial summary delivery failed.')\n return HttpResponseRedirect('/staff/')\n elif 'get_all_stripe_events' in request.POST:\n try:\n call_command('SendEmail', email, 'get_all_stripe_events')\n messages.success(request, 'Stripe events summary emailed.')\n except:\n messages.error(request, 'Stripe events summary delivery failed.')\n return HttpResponseRedirect('/staff/')\n elif 'check_ENERGY_STAR_scores' in request.POST:\n try:\n call_command('SendEmail', email, 'check_ENERGY_STAR_scores')\n messages.success(request, 'ENERGY STAR score checker emailed.')\n except:\n messages.error(request, 'ENERGY STAR score checker email failed.')\n return HttpResponseRedirect('/staff/')\n \n main_page_help_text = ''\n block_01 = 'get XML to paste into REST client to investigate missing scores'\n block_02 = 'get one of the summary tables by email'\n\n context = {\n 'sidebar': 'buildingspeakapp/shared/user_sidebar.html',\n 'main_page_help_text': main_page_help_text,\n 'block_01': block_01,\n 'block_02': block_02,\n 'user': request.user,\n 'accounts': request.user.account_set.order_by('id'),\n 'user_email_address': email,\n }\n\n template_name = 'buildingspeakapp/staff/staff.html'\n return render(request, template_name, RequestContext(request, context))\n","sub_path":"BuildingSpeakApp/views/staff.py","file_name":"staff.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"577498886","text":"from flask import Flask, render_template, request\nfrom werkzeug.utils import secure_filename\nimport os\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport re\nfrom PIL import Image\nfrom konlpy.tag import Okt\nfrom tensorflow import keras\nfrom keras.models import load_model\nfrom keras.applications.vgg16 import VGG16, decode_predictions\n\n\napp = Flask(__name__)\napp.debug = True\n\nvgg = VGG16()\nokt = Okt()\n\ndef tw_tokenizer(text):\n # 입력 인자로 들어온 text 를 형태소 단어로 토큰화 하여 list 객체 반환\n tokens_ko = okt.morphs(text)\n return tokens_ko\n\nmovie_nb = None\ndef load_movie_nb():\n global movie_nb\n movie_nb = joblib.load(os.path.join(app.root_path, 'model/news.h5'))\n\ndef nb_transform(review):\n stopwords=['의','가','이','은','들','는','좀','잘','걍','과','도','를','으로','자','에','와','한','하다']\n review = review.replace(\"[^ㄱ-ㅎㅏ-ㅣ가-힣 ]\",\"\")\n morphs = okt.morphs(review, stem=True)\n temp = ' '.join(morph for morph in morphs if not morph in stopwords)\n return temp\n\nmodel_iris_lr = None\nmodel_iris_svm = None\nmodel_iris_dt = None\nmodel_iris_deep = None\ndef load_iris():\n global model_iris_lr, model_iris_svm, model_iris_dt, model_iris_deep\n model_iris_lr = joblib.load(os.path.join(app.root_path, 'model/iris_lr.pkl'))\n model_iris_svm = joblib.load(os.path.join(app.root_path, 'model/iris_svm.pkl'))\n model_iris_dt = joblib.load(os.path.join(app.root_path, 'model/iris_dt.pkl'))\n model_iris_deep = load_model(os.path.join(app.root_path, 'model/iris_deep.hdf5'))\n\n@app.route('/')\ndef index():\n menu = {'home':True, 'rgrs':False, 'stmt':False, 'clsf':False, 'clst':False, 'user':False}\n return render_template('home.html', menu=menu)\n\n@app.route('/news', methods=['GET', 'POST'])\ndef news():\n menu = {'home':False, 'rgrs':False, 'stmt':True, 'clsf':False, 'clst':False, 'user':False}\n if request.method == 'GET':\n return render_template('news.html', menu=menu)\n # return render_template('sentiment.html', menu=menu)\n else:\n res_str = ['1=진짜', '0=가짜']\n review = request.form['review']\n # Logistic Regression 처리\n review_lr = re.sub(r\"\\d+\", \" \", review)\n review_lr_dtm = movie_nb.transform([review_lr])\n result_lr = res_str[movie_nb.predict(review_lr_dtm)[0]]\n \n # 결과 처리\n movie = {'review':review, 'result_lr':result_lr, 'result_nb':result_nb}\n return render_template('senti_result.html', menu=menu, movie=movie)\ndef load_news():\n global model_news\n \n \n model_news = load_model(os.path.join(app.root_path, 'D:\\workspace\\deep-larning\\4.RNN\\ news.h5'))\n@app.route('/member/')\ndef member(name):\n menu = {'home':False, 'rgrs':False, 'stmt':False, 'clsf':False, 'clst':False, 'user':True}\n nickname = request.args.get('nickname', '별명: 없음')\n return render_template('user.html', menu=menu, name=name, nickname=nickname)\n\nif __name__ == '__main__':\n load_movie_nb()\n load_iris()\n app.run(host='0.0.0.0') # 외부 접속 허용시 host='0.0.0.0' 추가","sub_path":"news/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"641638059","text":"'''\nUtility functions for easy_db.\n'''\nimport os\nimport sqlite3, pyodbc\nfrom typing import List, Dict, Any\n\n\n\ndef check_if_file_is_sqlite(filename: str) -> bool:\n '''\n Check if file is a sqlite database.\n See: https://stackoverflow.com/questions/12932607/how-to-check-if-a-sqlite3-database-exists-in-python\n '''\n if not os.path.isfile(filename):\n return False\n\n if os.path.getsize(filename) < 100: # SQLite db file header is 100 bytes (minimum file size)\n return False\n\n with open(filename, 'rb') as possible_db_file:\n header = possible_db_file.read(100)\n\n if header[:16] == b'SQLite format 3\\x00':\n return True\n else:\n return False\n\n\ndef list_of_dicts_from_query(cursor, sql: str, tablename: str, db_type: str, parameters: list=[]) -> List[Dict[str, Any]]:\n '''\n Query db using cursor, supplied sql, and tablename.\n Return list of dicts for query result.\n '''\n try:\n data = cursor.execute(sql, parameters).fetchall()\n except (sqlite3.OperationalError, pyodbc.ProgrammingError) as error:\n print(f'ERROR querying table {tablename}! Error below:')\n print(error)\n print(f'SQL: {sql}')\n return\n\n if db_type == 'SQLITE3':\n columns = [description[0] for description in cursor.description]\n elif db_type == 'SQL SERVER':\n columns = [column[0] for column in cursor.description]\n else:\n try:\n columns = [row.column_name for row in cursor.columns(table=tablename)]\n except UnicodeDecodeError:\n print('\\nERROR - Unable to read column names.')\n print('This may occur if using Access database with column descriptions populated.')\n print('Try deleting the column descriptions.\\n')\n return [{}]\n table_data = [dict(zip(columns, row)) for row in data]\n return table_data\n\n\n# set for quickly checking possibly malicious characters\nunallowed_characters = {';', '(', ')', '=', '+', \"'\", '\"', '.', '[', ']', ',',\n '{', '}', '\\\\', '/', '`', '~', '!', '@', '#', '$', '%', '^', '&', '*'}\n\ndef name_clean(name: str) -> bool:\n '''\n Check name and return True if it looks clean (not malicious).\n Return False if it name could be attempting sql injection.\n\n Used for table names and column names (as these can't be parameterized).\n '''\n for char in name:\n if char in unallowed_characters:\n print(f'ERROR!!! Prohibited characters detected in:\\n {name}')\n return False\n if 'DROP' in name.upper():\n print(f'ERROR!!! Prohibited characters detected in:\\n {name}')\n return False\n return True\n","sub_path":"easy_db/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"159733429","text":"#!/usr/bin/env python3\n# create the dashboard\n\nimport os\nimport glob\nimport time\nimport json\nimport requests\n\ndef main():\n\n kibana_host = os.environ['KIBANA_HOST']\n kibana_backport = os.environ['KIBANA_BACKPORT']\n kibana_user = os.environ['ELASTIC_USER']\n kibana_pw = os.environ['ELASTIC_PW']\n kibana_url = f'https://{kibana_host}:{kibana_backport}'\n\n headers = {'kbn-xsrf':'true', 'Content-Type':'application/json'}\n\n # import dashboards\n os.chdir(\"/tmp\")\n\n print('SETTING UP DASHBOARD')\n\n for file in glob.glob(\"dashboard_*.json\"):\n\n with open(file, 'r') as f:\n dashboard = f.read()\n\n import_url = f'{kibana_url}/api/kibana/dashboards/import'\n\n r = requests.post(import_url,\n auth=(kibana_user, kibana_pw),\n headers=headers,\n data=dashboard,\n verify='/etc/ssl/certs')\n\n print(r.content)\n\n print(f'{file} created')\n\n time.sleep(2)\n\n with open('default.json' ,'r') as d:\n default_index = d.read()\n\n default_index_url = f'{kibana_url}/api/kibana/settings/defaultIndex'\n\n r = requests.post(default_index_url,\n auth=(kibana_user, kibana_pw),\n headers=headers,\n data=default_index,\n verify='/etc/ssl/certs')\n\n print(r.content)\n print(' ... default Index set.')\n\nif __name__ == '__main__':\n main()\n","sub_path":"engine/setup_dashboard.py","file_name":"setup_dashboard.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"305545937","text":"import sys\nimport os\n\nfn = sys.argv[1]\nfn2 = fn + \".tmp\"\n\nlines = open(fn).readlines()\n\nout = open(fn2, 'w')\n\nfor i in range(len(lines)):\n line = lines[i]\n if i == 0 and lines[0] != '\\001':\n out.write(\"\\001\\r\\r\\n\")\n if line[-3:] != '\\r\\r\\n':\n if line[-2:] == '\\r\\n':\n out.write(line[:-2] + \"\\r\\r\\n\")\n else:\n out.write(line[:-1] + \"\\r\\r\\n\")\n else:\n out.write(line)\n\nout.close()\nos.rename(fn2, fn)","sub_path":"util/make_text_noaaportish.py","file_name":"make_text_noaaportish.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"205178585","text":"#!/usr/bin/env python\nimport rospy\nimport sys\n\nfrom geometry_msgs.msg import PoseStamped, Point, Quaternion\nfrom tf.transformations import quaternion_from_euler\n\nfrom giskardpy.python_interface import GiskardWrapper\nfrom giskardpy.tfwrapper import lookup_transform, lookup_pose\nfrom giskardpy import logging\n\nif __name__ == '__main__':\n rospy.init_node('add_urdf')\n giskard = GiskardWrapper()\n try:\n name = rospy.get_param('~name')\n path = rospy.get_param('~path', None)\n param_name = rospy.get_param('~param', None)\n position = rospy.get_param('~position', None)\n orientation = rospy.get_param('~rpy', None)\n root_frame = rospy.get_param('~root_frame', None)\n map_frame = rospy.get_param('~frame_id', 'map')\n if root_frame is not None:\n pose = lookup_pose(map_frame, root_frame)\n else:\n pose = PoseStamped()\n pose.header.frame_id = map_frame\n if position is not None:\n pose.pose.position = Point(*position)\n if orientation is not None:\n pose.pose.orientation = Quaternion(*quaternion_from_euler(*orientation))\n else:\n pose.pose.orientation.w = 1\n if path is None:\n if param_name is None:\n logging.logwarn('neither _param nor _path specified')\n sys.exit()\n else:\n urdf = rospy.get_param(param_name)\n else:\n with open(path, 'r') as f:\n urdf = f.read()\n result = giskard.add_urdf(name=name, urdf=urdf, pose=pose, js_topic=rospy.get_param('~js', None))\n if result.error_codes == result.SUCCESS:\n logging.loginfo('urdfs \\'{}\\' added'.format(name))\n else:\n logging.logwarn('failed to add urdfs \\'{}\\''.format(name))\n except KeyError:\n logging.loginfo('Example call: rosrun giskardpy add_urdf.py _name:=kitchen _param:=kitchen_description _js:=kitchen/joint_states _root_frame:=iai_kitchen/world _frame_id:=map')\n","sub_path":"scripts/add_urdf.py","file_name":"add_urdf.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"73524853","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n# ionastasi@gmail.com\n\n\nimport argparse\nimport sys\n\nimport log\nimport download\nimport clean\n\n\nHTMLS_INDEX = '../data/html/.index'\n\n\ndef parse_argument(argv):\n parser = argparse.ArgumentParser(\n prog='crawler',\n description='''Download and clean posts from geektimes.ru.\n Because of reforwarding, a few posts from\n habrababr.ru and megamozg.ru too.'''\n )\n parser.add_argument(\n '--log',\n default='error',\n choices=['critical', 'error', 'debug'],\n dest='log_level',\n help=\"changing log level, 'error' for default\"\n )\n\n subparsers = parser.add_subparsers(\n dest='parser_mode'\n )\n\n update = subparsers.add_parser(\n 'update',\n description=\"Downloading pages. You can download last posts or some range of posts.\",\n help='downloading pages'\n )\n update.add_argument(\n '--print-ids',\n action='store_true',\n dest='print_ids',\n help='set this if you want ids printed out'\n )\n update_subs = update.add_subparsers(\n dest='update_mode'\n )\n update_last = update_subs.add_parser(\n 'last',\n description=\"Download last 1000 posts, if they wasn't downloaded earlier.\",\n help='download last 1000 posts'\n )\n update_range = update_subs.add_parser(\n 'range',\n description='''Download posts in some range.\n Stops if starts downloading already downloaded posts.\n Of course, you should set the range by --from and --to.''',\n help='download posts in some range'\n )\n update_range.add_argument(\n '--from',\n required=True,\n type=int,\n dest='start_down',\n help='where range of downloading starts'\n )\n update_range.add_argument(\n '--to',\n required=True,\n type=int,\n dest='end_down',\n help='where range of downloading ends'\n )\n\n\n clean = subparsers.add_parser(\n 'clean',\n help='cleaning pages',\n description='''Clean pages from tags and etc.\n You can clean all pages, or some range of them, or some list.'''\n )\n clean_subs = clean.add_subparsers(\n dest='clean_mode'\n )\n clean_all = clean_subs.add_parser(\n 'all',\n help='parse all htmls',\n description=\"Clean all htmls from tags and etc, if they weren't cleaned earlier.\"\n )\n clean_range = clean_subs.add_parser(\n 'range',\n help='parse htmls in some range',\n description='''Clean htmls in some range, skipping already cleaned htmls.\n Of course you should set the range by --from and --to.'''\n )\n clean_range.add_argument(\n '--from',\n type=int,\n required=True,\n dest='start_clean',\n help='where range of cleaning starts'\n )\n clean_range.add_argument(\n '--to',\n type=int,\n required=True,\n dest='end_clean',\n help='where range of cleaning ends'\n )\n clean_list = clean_subs.add_parser(\n 'list',\n help='parse htmls from some list',\n description='''Clean htmls from some list you give with --file key.'''\n )\n clean_list.add_argument(\n '--file',\n required=True,\n type=str,\n dest='clean_file',\n help='cleaning posts from list in this file'\n )\n\n update.add_argument(\n '--force',\n action='store_true',\n dest='update_force',\n help='downloading pages even if they were downloaded earlier'\n )\n clean.add_argument(\n '--force',\n action='store_true',\n dest='clean_force',\n help='cleaning pages even if they were cleaned earlier'\n )\n\n if 'update' in sys.argv:\n if 'range' not in sys.argv and 'last' not in sys.argv:\n update.print_help()\n sys.exit(1)\n elif 'clean' in sys.argv:\n if 'range' not in sys.argv and 'all' not in sys.argv and 'list' not in sys.argv:\n clean.print_help()\n sys.exit(1)\n else:\n parser.print_help()\n sys.exit(1)\n\n return parser.parse_args()\n\n\ndef main():\n args = parse_argument(sys.argv)\n\n log.config(log.level(args.log_level))\n\n if args.parser_mode == 'update':\n if args.update_mode == 'last':\n download.download_last(args.print_ids, args.update_force)\n if args.update_mode == 'range':\n download.download_range(min(args.start_down, args.end_down),\n max(args.start_down, args.end_down),\n args.print_ids, args.update_force)\n\n if args.parser_mode == 'clean':\n if args.clean_mode == 'list':\n ids = list(map(int, open(args.clean_file).readlines()))\n if args.clean_mode == 'all':\n htmls = list(map(int, open(HTMLS_INDEX).readlines()))\n if not htmls:\n exit()\n ids = [x for x in range(min(htmls), max(htmls) + 1)]\n if args.clean_mode == 'range':\n first = min(args.start_clean, args.end_clean)\n last = max(args.start_clean, args.end_clean)\n ids = [x for x in range(first, last + 1)]\n clean.clean_list(ids, args.clean_force)\n\nif __name__ == '__main__':\n main()\n","sub_path":"crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"39117026","text":"import os\nimport sys\n\nfrom flask import Flask\nfrom flask_webpack import Webpack\nfrom flask_debugtoolbar import DebugToolbarExtension\n\nimport models # noqa\nfrom models.database import init_db\nfrom routes import register_routes\n\n\nclass App:\n @classmethod\n def create(self):\n return self._create_app()\n\n @classmethod\n def _create_app(self):\n app = Flask(__name__)\n\n self._load_config(app)\n self._register_path(app)\n\n # use template pug(jade)\n app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')\n\n # use webpack\n webpack = Webpack()\n webpack.init_app(app)\n\n # routing\n register_routes(app)\n\n # init db\n init_db(app)\n\n toolbar = DebugToolbarExtension()\n toolbar.init_app(app)\n\n return app\n\n @classmethod\n def _load_config(self, app):\n # load configure\n app.config.from_object('config.default')\n\n if os.getenv('FLASK_ENV', 'development') == 'production':\n app.config.from_object('config.production')\n else:\n app.config.from_object('config.development')\n\n app.config.from_pyfile('secrets.py', silent=True)\n\n @classmethod\n def _register_path(self, app):\n for path in ['utils']:\n sys.path.append(\n os.path.join(app.root_path, path)\n )\n\n\napp = App.create()\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"40833323","text":"from django.shortcuts import render\nfrom Memo.models import Group\nfrom Memo.models import Memo\nfrom django.http import HttpResponseServerError, HttpResponse\nfrom django.db.models import Max\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\n\n\nfrom rest_framework import viewsets, permissions, generics\nfrom rest_framework.response import Response\nfrom Memo.serializers import (\n # NoteSerializer,\n # CreateUserSerializer,\n UserSerializer,\n LoginUserSerializer,\n)\nfrom knox.models import AuthToken\n\n\n# https://velog.io/@killi8n/Dnote-5-1.-Django-%EA%B6%8C%ED%95%9C-%EC%84%A4%EC%A0%95-%EB%B0%8F-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%ED%9A%8C%EC%9B%90%EA%B0%80%EC%9E%85-%EA%B5%AC%ED%98%84-tmjmep5tcm\n# https://behonestar.tistory.com/117\n\n\nclass LoginAPI(generics.GenericAPIView):\n serializer_class = LoginUserSerializer\n\n def post(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data\n print(serializer)\n print(user)\n print('-------------------------')\n return Response(\n {\n \"user\": UserSerializer(\n user, context=self.get_serializer_context()\n ).data,\n \"token\": AuthToken.objects.create(user)[1],\n }\n )\n\n\nclass UserAPI(generics.RetrieveAPIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = UserSerializer\n\n def get_object(self):\n return self.request.user\n\n\n@csrf_exempt\ndef sign_in(request):\n username = request.POST['username']\n password = request.POST['password']\n # print(username, password)\n user = authenticate(request, username=username, password=password)\n # print(user)\n if user is not None:\n # 인증 성공\n login(request, user)\n print(f'[Login request: \"{user}\" login success]')\n return HttpResponse(\"login\")\n else:\n # 인증 실패\n print(f'[Login request: login failed..]')\n return HttpResponse(\"failed\")\n\n\n@login_required\n@csrf_exempt\ndef sign_out(request):\n print(f'[Logout request: {request.user}]')\n logout(request)\n return HttpResponse(\"logout\")\n\n\n@login_required\ndef get_all_memo(request):\n user = request.user\n data = []\n print(user)\n \n try:\n for item in Memo.objects.filter(owner=user).order_by('-created_at'):\n data.append({\n 'id': item.id,\n 'index': item.index,\n 'owner': item.owner,\n 'group': item.group,\n 'content': item.content,\n 'created_at': str(item.created_at),\n 'updated_at': str(item.updated_at),\n 'isDo': item.isDo,\n 'isStar': item.isStar,\n 'targetDate': item.targetDate,\n })\n except:\n print(\"[Get request: All Memo] ERROR\")\n return HttpResponseServerError()\n\n print(\"[Get request: All Memo]\")\n data = json.dumps(data, indent=4)\n print(data)\n\n return HttpResponse(data, content_type=\"application/json\")\n\n\n@login_required\ndef get_all_group(request):\n user = request.user\n data = []\n \n try:\n for item in Group.objects.filter(owner=user).order_by('-created_at'):\n data.append({\n 'id': item.id,\n 'index': item.index,\n 'owner': item.owner,\n 'group_name': item.group,\n })\n except:\n print(\"[Get request: All Group] ERROR\")\n return HttpResponseServerError()\n\n print(\"[Get request: All Group]\")\n data = json.dumps(data, indent=4)\n print(data)\n\n return HttpResponse(data, content_type=\"application/json\")\n\n\n@login_required\ndef get_memo_by_group_id(request, group_id):\n user = request.user\n # memo = get_object_or_404(Memo, group=group_id) 이 방식 괜찮은지 후에 검토\n data = []\n\n if not group:\n return HttpResponse(status=400)\n\n try:\n for item in Memo.objects.filter(Q(user=user) & Q(group=group_id)).order_by('-created_at'):\n data.append({\n 'id': item.id,\n 'index': item.index,\n 'owner': item.owner,\n 'group': item.group,\n 'content': item.content,\n 'created_at': str(item.created_at),\n 'updated_at': str(item.updated_at),\n 'isDo': item.isDo,\n 'isStar': item.isStar,\n 'targetDate': item.targetDate,\n })\n except:\n print(\"[Get request: Memo by Group ID] ERROR\")\n return HttpResponseServerError()\n\n print(\"[Get request: Memo by Group ID]\")\n data = json.dumps(data, indent=4)\n print(data)\n\n return HttpResponse(data, content_type=\"application/json\")\n\n\n@login_required\n@csrf_exempt\ndef add_memo(request):\n user = request.user\n memo = json.loads(request.POST['memo'])\n print(json.dumps(memo, indent=4), type(memo))\n\n # group = memo.get('group') if memo.get('group') is not None else ''\n group = None\n content = memo.get('content') if memo.get('content') is not None else ''\n isDo = memo.get('isDo') if memo.get('isDo') is not None else False\n isStar = memo.get('isStar') if memo.get('isStar') is not None else False\n targetDate = memo.get('targetDate') if memo.get('targetDate') is not None else None\n\n print(group, content, isDo, isStar, targetDate)\n\n last_memo_index_obj = Memo.objects.aggregate(\n index=Max('index')).get('index')\n last_memo_index = last_memo_index_obj + 1 if last_memo_index_obj is not None else 0\n print(last_memo_index)\n try:\n memo_obj = Memo(index=last_memo_index, owner=user, group=group, content=content,\n isDo=isDo, isStar=isStar, targetDate=targetDate)\n # memo_obj.save()\n except:\n print(\"[Add request: Memo] ERROR\")\n return HttpResponseServerError()\n return HttpResponse(status=200)\n\n\n@login_required\ndef update_memo_index(request):\n user = request.user\n memo = json.loads(request.POST['memo'])\n print(json.dumps(memo, indent=4), type(memo))\n\n if memo.get('index') is None:\n return HttpResponseServerError()\n\n memo_id = memo.get('id')\n index = memo.get('index')\n\n try:\n memo_obj = Memo.objects.get(id=memo_id)\n except Photo.DoesNotExist:\n print(\n \"[Update request: Index of Memo] Failed!!! No Memo matches the given query.\")\n return HttpResponseServerError()\n\n # filter(Q()|Q())\n\n if memo_obj.index < index:\n # 앞번호에서 뒷번호로 이동한 경우 : 뒷번호를 포함한 두 번호 사이에 있는 모든 항목들의 index--\n between_memo_set = Memo.objects.filter(\n Q(id > memo_obj.index) & Q(id <= index))\n for between_memo in between_memo_set:\n between_memo.index = between_memo.index - 1\n between_memo.save()\n elif memo_obj.index > index:\n # 뒷번호에서 앞번호로 이동한 경우 : 앞번호를 포함한 두 번호 사이에 있는 모든 항목들의 index++\n between_memo_set = Memo.objects.filter(\n Q(id < memo_obj.index) & Q(id >= index))\n for between_memo in between_memo_set:\n between_memo.index = between_memo.index + 1\n between_memo.save()\n\n memo_obj.index = index\n memo_obj.save()\n\n return HttpResponse(status=200)\n\n\n@login_required\ndef update_memo(request):\n user = request.user\n memo = json.loads(request.POST['memo'])\n print(json.dumps(memo, indent=4), type(memo))\n\n memo_id = memo.get('id')\n group = memo.get('group') if memo.get('group') is not None else ''\n content = memo.get('content') if memo.get('content') is not None else ''\n isDo = memo.get('isDo') if memo.get('isDo') is not None else False\n isStar = memo.get('isStar') if memo.get('isStar') is not None else False\n targetDate = memo.get('targetDate') if memo.get('targetDate') is not None else None\n\n print(group, content, isDo, isStar, targetDate)\n\n try:\n memo_obj = Memo.objects.get(id=memo_id)\n except Photo.DoesNotExist:\n print(\"[Update request: Memo] Failed!!! No Memo matches the given query.\")\n return HttpResponseServerError()\n\n # filter(Q()|Q())\n\n # if memo.index is not None:\n # if memo_obj.index < memo.index:\n # # 앞번호에서 뒷번호로 이동한 경우 : 뒷번호를 포함한 두 번호 사이에 있는 모든 항목들의 index--\n # between_memo_set = Memo.objects.filter(\n # Q(id > memo_obj.index) & Q(id <= memo.index))\n # for between_memo in between_memo_set:\n # between_memo.index = between_memo.index - 1\n # between_memo.save()\n # elif memo_obj.index > memo.index:\n # # 뒷번호에서 앞번호로 이동한 경우 : 앞번호를 포함한 두 번호 사이에 있는 모든 항목들의 index++\n # between_memo_set = Memo.objects.filter(\n # Q(id < memo_obj.index) & Q(id >= memo.index))\n # for between_memo in between_memo_set:\n # between_memo.index = between_memo.index + 1\n # between_memo.save()\n # memo_obj.index = memo.index\n\n memo_obj.group = group\n memo_obj.content = content\n memo_obj.isDo = isDo\n memo_obj.isStar = isStar\n memo_obj.targetDate = targetDate\n\n memo_obj.save()\n return HttpResponse(status=200)\n\n\n@login_required\ndef delete_memo(request):\n user = request.user\n memo_id = request.POST['memo_id']\n\n try:\n memo_obj = Memo.objects.get(id=memo_id)\n except Photo.DoesNotExist:\n print(\"[Delete request: Memo] Failed!!! No Memo matches the given query.\")\n return HttpResponseServerError()\n\n\n # 삭제 시 삭제할 항목의 뒷번호들의 index--\n between_memo_set = Group.objects.filter(Q(index > memo_obj.index))\n for between_memo in between_memo_set:\n between_memo.index = between_memo.index - 1\n between_memo.save()\n \n memo_obj.delete()\n\n return HttpResponse(status=200)\n\n\n@login_required\ndef add_group(request):\n user = request.user\n group_name = request.POST['group_name']\n\n last_group_index = Group.objects.aggregate(\n index=Max('index'))['index'] + 1 or 0\n\n try:\n group_obj = Group(index=last_group_index,\n owner=user, group_name=group_name)\n group_obj.save()\n except:\n print(\"[Add request: Group] ERROR\")\n return HttpResponseServerError()\n return HttpResponse(status=200)\n\n\n@login_required\ndef update_group_index(request):\n user = request.user\n group_index = request.POST['group_index']\n\n try:\n group_obj = Group.objects.get(id=group.id)\n except Photo.DoesNotExist:\n print(\n \"[Update request: Index of Group] Failed!!! No Group matches the given query.\")\n return HttpResponseServerError()\n\n # filter(Q()|Q())\n\n if group_obj.index < group_index:\n # 앞번호에서 뒷번호로 이동한 경우 : 뒷번호를 포함한 두 번호 사이에 있는 모든 항목들의 index--\n between_group_set = Group.objects.filter(\n Q(id > group_obj.index) & Q(id <= group_index))\n for between_group in between_group_set:\n between_group.index = between_group.index - 1\n between_group.save()\n elif group_obj.index > group_index:\n # 뒷번호에서 앞번호로 이동한 경우 : 앞번호를 포함한 두 번호 사이에 있는 모든 항목들의 index++\n between_group_set = Group.objects.filter(\n Q(id < group_obj.index) & Q(id >= group_index))\n for between_group in between_group_set:\n between_group.index = between_group.index + 1\n between_group.save()\n\n group_obj.index = group_index\n group_obj.save()\n\n return HttpResponse(status=200)\n\n\n@login_required\ndef update_group(request):\n user = request.user\n group = json.loads(request.POST['group'])\n print(json.dumps(group, indent=4), type(group))\n\n group_id = group.get('id')\n group_name = group.get('name')\n\n try:\n group_obj = Group.objects.get(id=group_id)\n except Group.DoesNotExist:\n print(\"[Update request: Group] Failed!!! No Group matches the given query.\")\n return HttpResponseServerError()\n\n group_obj.group_name = group_name\n\n group_obj.save()\n return HttpResponse(status=200)\n\n\n@login_required\ndef delete_group(request):\n user = request.user\n group_id = request.POST['group_id']\n\n try:\n group_obj = Group.objects.get(id=group_id)\n except Group.DoesNotExist:\n print(\"[Delete request: Group] Failed!!! No Group matches the given query.\")\n return HttpResponseServerError()\n\n # 삭제 시 삭제할 항목의 뒷번호들의 index-- \n between_group_set = Group.objects.filter(Q(index > group_obj.index))\n for between_group in between_group_set:\n between_group.index = between_group.index - 1\n between_group.save()\n\n group_obj.delete()\n\n return HttpResponse(status=200)\n","sub_path":"server/ToDoServer/Memo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"404087163","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A composable gradient processing and optimization library for JAX.\n\nThe ``optix`` module implements a number of composable gradient transformations,\ntypically used in the context of optimizing neural nets.\n\nEach transformation defines:\n\n* ``init_fn``: Params -> OptState, to initialize (possibly empty) sets of statistics (aka ``state``)\n* ``update_fn``: (Updates, OptState, Optional[Params]) -> (Updates, OptState)\n to transform a parameter update or gradient and update the state\n\nAn (optional) ``chain`` utility can be used to build custom optimizers by\nchaining arbitrary sequences of transformations. For any sequence of\ntransformations ``chain`` returns a single ``init_fn`` and ``update_fn``.\n\nAn (optional) ``apply_updates`` function can be used to eventually apply the\ntransformed gradients to the set of parameters of interest.\n\nSeparating gradient transformations from the parameter update allows to flexibly\nchain a sequence of transformations of the same gradients, as well as combine\nmultiple updates to the same parameters (e.g. in multi-task settings where the\ndifferent tasks may benefit from different sets of gradient transformations).\n\nMany popular optimizers can be implemented using ``optix`` as one-liners, and,\nfor convenience, we provide aliases for some of the most popular ones.\n\nExample Usage:\n\n opt = optix.sgd(learning_rate)\n OptData = collections.namedtuple('OptData', 'step state params')\n data = OptData(0, opt.init(params), params)\n\n def step(opt_data):\n step, state, params = opt_data\n value, grads = jax.value_and_grad(loss_fn)(params)\n updates, state = opt.update(grads, state, params)\n params = optix.apply_updates(updates, params)\n return value, OptData(step+1, state, params)\n\n for step in range(steps):\n value, opt_data = step(opt_data)\n\"\"\"\n\n\nfrom typing import Any, Callable, NamedTuple, Optional, Sequence, Tuple, Union\n\nfrom jax import numpy as jnp\nfrom jax import random as jrandom\n\nfrom jax.tree_util import tree_leaves\nfrom jax.tree_util import tree_multimap\nfrom jax.tree_util import tree_structure\nfrom jax.tree_util import tree_unflatten\n\n###\n# Typing\n\n# TODO(jaslanides): Make these more specific.\n# pylint:disable=no-value-for-parameter\n\nOptState = NamedTuple # Transformation states are (possibly empty) namedtuples.\nParams = Any # Parameters are arbitrary nests of `jnp.ndarrays`.\nUpdates = Params # Gradient updates are of the same type as parameters.\n\nInitFn = Callable[[Params], Union[OptState, Sequence[OptState]]]\nUpdateFn = Callable[[Updates, OptState, Optional[Params]],\n Tuple[Updates, Union[OptState, Sequence[OptState]]]]\n\n\n###\n# Composable gradient transformations.\n\n\nclass GradientTransformation(NamedTuple):\n \"\"\"Optix optimizers consists of a pair of functions: (initialiser, update).\"\"\"\n init: InitFn\n update: UpdateFn\n\n\n# TODO(mtthss): Remove alias, once existing references are updated\nInitUpdate = GradientTransformation\n\n\nclass ClipState(OptState):\n \"\"\"The `clip` transformation is stateless.\"\"\"\n\n\ndef clip(max_delta) -> GradientTransformation:\n \"\"\"Clip updates element-wise, to be between -max_delta and +max_delta.\n\n Args:\n max_delta: the maximum absolute value for each element in the update.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(_):\n return ClipState()\n\n def update_fn(updates, state, params=None):\n del params\n updates = tree_multimap(\n lambda g: jnp.clip(g, -max_delta, max_delta), updates)\n return updates, state\n\n return GradientTransformation(init_fn, update_fn)\n\n\ndef global_norm(updates: Updates) -> Updates:\n return jnp.sqrt(\n sum([jnp.sum(jnp.square(x)) for x in tree_leaves(updates)]))\n\n\nclass ClipByGlobalNormState(OptState):\n \"\"\"The `clip_by_global_norm` transformation is stateless.\"\"\"\n\n\ndef clip_by_global_norm(max_norm) -> GradientTransformation:\n \"\"\"Clip updates using their global norm.\n\n References:\n [Pascanu et al, 2012](https://arxiv.org/abs/1211.5063)\n\n Args:\n max_norm: the maximum global norm for an update.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(_):\n return ClipByGlobalNormState()\n\n def update_fn(updates, state, params=None):\n del params\n g_norm = global_norm(updates)\n trigger = g_norm < max_norm\n updates = tree_multimap(\n lambda t: jnp.where(trigger, t, (t / g_norm) * max_norm), updates)\n return updates, state\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass TraceState(OptState):\n \"\"\"Holds an aggregation of past updates.\"\"\"\n trace: Params\n\n\ndef trace(decay: float, nesterov: bool) -> GradientTransformation:\n \"\"\"Compute a trace of past updates.\n\n Args:\n decay: the decay rate for the tracing of past updates.\n nesterov: whether to use Nesterov momentum.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(params):\n return TraceState(trace=tree_multimap(jnp.zeros_like, params))\n\n def update_fn(updates, state, params=None):\n del params\n f = lambda g, t: g + decay * t\n update_trace = tree_multimap(f, updates, state.trace)\n updates = (\n tree_multimap(f, updates, update_trace) if nesterov else update_trace)\n return updates, TraceState(trace=update_trace)\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass ScaleByRmsState(OptState):\n \"\"\"State for exponential root mean-squared (RMS)-normalized updates.\"\"\"\n nu: Updates\n\n\ndef _update_moment(updates, moments, decay, order):\n return tree_multimap(\n lambda g, t: (1 - decay) * (g ** order) + decay * t, updates, moments)\n\n\ndef scale_by_rms(decay: float = 0.9, eps: float = 1e-8):\n \"\"\"Rescale updates by the root of the exp. moving avg of the square.\n\n References:\n [Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)\n\n Args:\n decay: decay rate for the exponentially weighted average of squared grads.\n eps: term added to the denominator to improve numerical stability.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(params):\n nu = tree_multimap(jnp.zeros_like, params) # second moment\n return ScaleByRmsState(nu=nu)\n\n def update_fn(updates, state, params=None):\n del params\n nu = _update_moment(updates, state.nu, decay, 2)\n updates = tree_multimap(lambda g, n: g / (jnp.sqrt(n + eps)), updates, nu)\n return updates, ScaleByRmsState(nu=nu)\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass ScaleByRStdDevState(OptState):\n \"\"\"State for centered exponential moving average of squares of updates.\"\"\"\n mu: Updates\n nu: Updates\n\n\ndef scale_by_stddev(\n decay: float = 0.9, eps: float = 1e-8) -> GradientTransformation:\n \"\"\"Rescale updates by the root of the centered exp. moving average of squares.\n\n References:\n [Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)\n\n Args:\n decay: decay rate for the exponentially weighted average of squared grads.\n eps: term added to the denominator to improve numerical stability.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(params):\n mu = tree_multimap(jnp.zeros_like, params) # First moment\n nu = tree_multimap(jnp.zeros_like, params) # Second moment\n return ScaleByRStdDevState(mu=mu, nu=nu)\n\n def update_fn(updates, state, params=None):\n del params\n mu = _update_moment(updates, state.mu, decay, 1)\n nu = _update_moment(updates, state.nu, decay, 2)\n updates = tree_multimap(\n lambda g, m, n: g / jnp.sqrt(n - jnp.square(m) + eps), updates, mu, nu)\n return updates, ScaleByRStdDevState(mu=mu, nu=nu)\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass ScaleByAdamState(OptState):\n \"\"\"State for the Adam algorithm.\"\"\"\n count: jnp.ndarray # shape=(), dtype=jnp.int32.\n mu: Updates\n nu: Updates\n\n\ndef scale_by_adam(b1: float = 0.9,\n b2: float = 0.999,\n eps: float = 1e-8,\n eps_root: float = 0.0) -> GradientTransformation:\n \"\"\"Rescale updates according to the Adam algorithm.\n\n References:\n [Kingma et al, 2014](https://arxiv.org/abs/1412.6980)\n\n Args:\n b1: decay rate for the exponentially weighted average of grads.\n b2: decay rate for the exponentially weighted average of squared grads.\n eps: term added to the denominator to improve numerical stability.\n eps_root: term added to the denominator inside the square-root to improve\n numerical stability when backpropagating gradients through the rescaling.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(params):\n mu = tree_multimap(jnp.zeros_like, params) # First moment\n nu = tree_multimap(jnp.zeros_like, params) # Second moment\n return ScaleByAdamState(count=jnp.zeros([], jnp.int32), mu=mu, nu=nu)\n\n def update_fn(updates, state, params=None):\n del params\n mu = _update_moment(updates, state.mu, b1, 1)\n nu = _update_moment(updates, state.nu, b2, 2)\n mu_hat = tree_multimap(lambda t: t / (1 - b1 ** (state.count + 1)), mu)\n nu_hat = tree_multimap(lambda t: t / (1 - b2 ** (state.count + 1)), nu)\n updates = tree_multimap(\n lambda m, v: m / (jnp.sqrt(v + eps_root) + eps), mu_hat, nu_hat)\n return updates, ScaleByAdamState(count=state.count + 1, mu=mu, nu=nu)\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass ScaleState(NamedTuple):\n \"\"\"The scale transformation is stateless.\"\"\"\n\n\ndef scale(step_size: float) -> GradientTransformation:\n \"\"\"Scale updates by some fixed scalar `step_size`.\n\n Args:\n step_size: a scalar corresponding to a fixed scaling factor for updates.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(_):\n return ScaleState()\n\n def update_fn(updates, state, params=None):\n del params\n updates = tree_multimap(lambda g: step_size * g, updates)\n return updates, state\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass ScaleByScheduleState(OptState):\n \"\"\"Maintains count for scale scheduling.\"\"\"\n count: jnp.ndarray # shape=(), dtype=jnp.int32\n\n\ndef scale_by_schedule(step_size_fn: Callable[[jnp.ndarray], jnp.ndarray]):\n \"\"\"Scale updates using a custom schedule for the `step_size`.\n\n Args:\n step_size_fn: a function that takes an update count as input and proposes\n the step_size to multiply the updates by.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(_):\n return ScaleByScheduleState(count=jnp.zeros([], jnp.int32))\n\n def update_fn(updates, state, params=None):\n del params\n updates = tree_multimap(lambda g: step_size_fn(state.count) * g, updates)\n return updates, ScaleByScheduleState(count=state.count + 1)\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass AddNoiseState(OptState):\n \"\"\"State for adding gradient noise. Contains a count for annealing.\"\"\"\n count: jnp.ndarray\n rng_key: jnp.ndarray\n\n\ndef add_noise(eta: float, gamma: float, seed: int) -> GradientTransformation:\n \"\"\"Add gradient noise.\n\n References:\n [Neelakantan et al, 2014](https://arxiv.org/abs/1511.06807)\n\n Args:\n eta: base variance of the gaussian noise added to the gradient.\n gamma: decay exponent for annealing of the variance.\n seed: seed for random number generation.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(_):\n return AddNoiseState(\n count=jnp.zeros([], jnp.int32), rng_key=jrandom.PRNGKey(seed))\n\n def update_fn(updates, state, params=None): # pylint: disable=missing-docstring\n del params\n num_vars = len(tree_leaves(updates))\n treedef = tree_structure(updates)\n variance = eta / (1 + state.count) ** gamma\n all_keys = jrandom.split(state.rng_key, num=num_vars + 1)\n noise = tree_multimap(\n lambda g, k: jrandom.normal(k, shape=g.shape),\n updates, tree_unflatten(treedef, all_keys[1:]))\n updates = tree_multimap(\n lambda g, n: g + variance * n, updates, noise)\n return updates, AddNoiseState(count=state.count + 1, rng_key=all_keys[0])\n\n return GradientTransformation(init_fn, update_fn)\n\n\nclass ApplyEvery(OptState):\n \"\"\"Contains a counter and a gradient accumulator.\"\"\"\n count: jnp.ndarray\n grad_acc: Updates\n\n\ndef apply_every(k: int = 1) -> GradientTransformation:\n \"\"\"accumulate gradients and apply them every k steps.\n\n Args:\n k: apply the update every k steps otherwise accumulate the gradients.\n\n Returns:\n An (init_fn, update_fn) tuple.\n \"\"\"\n\n def init_fn(params):\n grad_acc = tree_multimap(jnp.zeros_like, params)\n return ApplyEvery(count=jnp.zeros([], jnp.int32), grad_acc=grad_acc)\n\n def update_fn(updates, state, params=None):\n del params\n c = state.count % k\n acc = c != 0\n grad_acc = tree_multimap(\n lambda g, ga: acc * ga + g, updates, state.grad_acc)\n emit = c == (k - 1)\n updates = tree_multimap(lambda ga: emit * ga, grad_acc)\n return updates, ApplyEvery(count=state.count + 1, grad_acc=grad_acc)\n\n return GradientTransformation(init_fn, update_fn)\n\n\n###\n# Utilities for building and using custom optimizers.\n\n\ndef chain(*args: GradientTransformation) -> GradientTransformation:\n \"\"\"Applies a list of chainable update transformations.\n\n Given a sequence of chainable transforms, `chain` returns an `init_fn`\n that constructs a `state` by concatenating the states of the individual\n transforms, and returns an `update_fn` which chains the update transformations\n feeding the appropriate state to each.\n\n Args:\n *args: a sequence of chainable (init_fn, update_fn) tuples.\n\n Returns:\n A single (init_fn, update_fn) tuple.\n \"\"\"\n\n init_fns, update_fns = zip(*args)\n\n def init_fn(params: Params) -> Sequence[OptState]:\n return [fn(params) for fn in init_fns]\n\n def update_fn(updates: Updates, state: OptState, params: Params = None\n ) -> Tuple[Updates, Sequence[OptState]]:\n new_state = []\n for s, fn in zip(state, update_fns): # pytype: disable=wrong-arg-types\n updates, new_s = fn(updates, s, params)\n new_state.append(new_s)\n return updates, new_state\n\n return GradientTransformation(init_fn, update_fn)\n\n\ndef apply_updates(params: Params, updates: Updates) -> Params:\n \"\"\"Applies an update to the corresponding parameters.\n\n This is an (optional) utility functions that applies an update, and returns\n the updated parameters to the caller. The update itself is typically the\n result of applying any number of `chainable` transformations.\n\n Args:\n params: a tree of parameters.\n updates: a tree of updates, the tree structure and the shape of the leaf\n nodes must match that of `params`.\n\n Returns:\n Updated parameters, with same structure and shape as `params`.\n \"\"\"\n return tree_multimap(lambda p, u: p + u, params, updates)\n\n\n###\n# Aliases for popular optimizers.\n\n\ndef sgd(learning_rate: float,\n momentum: float = 0.,\n nesterov: bool = False) -> GradientTransformation:\n return chain(\n trace(decay=momentum, nesterov=nesterov),\n scale(-learning_rate),\n )\n\n\ndef noisy_sgd(learning_rate: float,\n eta: float = 0.01,\n gamma: float = 0.55,\n seed: int = 0) -> GradientTransformation:\n return chain(\n trace(decay=0., nesterov=False),\n scale(-learning_rate),\n add_noise(eta, gamma, seed),\n )\n\n\ndef adam(learning_rate: float,\n b1: float = 0.9,\n b2: float = 0.999,\n eps: float = 1e-8) -> GradientTransformation:\n return chain(\n scale_by_adam(b1=b1, b2=b2, eps=eps),\n scale(-learning_rate),\n )\n\n\ndef rmsprop(learning_rate: float,\n decay: float = 0.9,\n eps: float = 1e-8,\n centered: bool = False) -> GradientTransformation:\n if centered:\n return chain(\n scale_by_stddev(decay=decay, eps=eps),\n scale(-learning_rate),\n )\n return chain(\n scale_by_rms(decay=decay, eps=eps),\n scale(-learning_rate),\n )\n","sub_path":"jax/experimental/optix.py","file_name":"optix.py","file_ext":"py","file_size_in_byte":16353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"309598738","text":"from firebase import firebase\r\nfrom flask import Flask, jsonify, make_response,request,render_template\r\nimport json\r\nimport os\r\nimport requests\r\nfrom werkzeug.exceptions import NotFound, ServiceUnavailable\r\nfrom datetime import date\r\n\r\napp = Flask(__name__)\r\n\r\nglobal data\r\ndata = { \"CarID\" : \"GJ0000004\",\r\n\t\t\t\"CustID\" : 121,\r\n\t\t\t\"CustName\" : \"HastiB\",\r\n\t\t\t\"EmailID\" : \"hasti@gmail.com\",\r\n\t\t\t\"ContactNo\" : 9997778880,\r\n\t\t\t\"CarName\" : \"Hynudai Verna\",\r\n \"CarType\" : \"Sedan\",\r\n\t\t\t\"CarColour\" : \"White\",\r\n\t\t\t\"InitialDeposit\" : 8000,\r\n\t\t\t\"RatePerKm\" : 15,\r\n\t\t}\t\t\r\n\r\n@app.route(\"/\")\r\ndef hello():\r\n ''' Greet the user '''\r\n \r\n return \"Hey! Test Service is up\"\r\n\r\n\r\n@app.route('/issue_call')\r\ndef issue_call():\r\n\r\n try:\r\n req = requests.post(\"http://127.0.0.1:5001/catalogue2issue/\",data)\r\n except requests.exceptions.ConnectionError:\r\n return \"Services Unavailable\"\r\n return req.text\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(port=5000, debug=True)","sub_path":"Services/TestService.py","file_name":"TestService.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"616078487","text":"from selenium import webdriver\n\n\nclass WindowSize:\n\n def test(self):\n\n # Define base URL and location to Gecko driver\n base_url = \"https://learn.letskodeit.com/\"\n driver = webdriver.Firefox(\n executable_path='C:/Python/Drivers/Gecko/geckodriver-v0.26.0-win32/geckodriver.exe')\n\n # Open base url\n driver.get(base_url)\n driver.implicitly_wait(3)\n\n height = driver.execute_script(\"return window.innerHeight;\")\n width = driver.execute_script(\"return window.innerWidth;\")\n print(\"Height: \" + str(height))\n print(\"Width : \" + str(width))\n driver.close()\n\n\nmy_test = WindowSize()\nmy_test.test()\n","sub_path":"Advanced/WindowSize.py","file_name":"WindowSize.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"592889979","text":"import RL\nimport gym\n# import gym_ple\n\nclass GymFactory (RL.EnvironmentFactory):\n def __init__(self, env_name):\n self.env_name = env_name\n def make(self):\n env = gym.make(self.env_name)\n #if isinstance(env.unwrapped, gym_ple.PLEEnv):\n # s = env.observation_space.shape\n # env.observation_space = gym.spaces.Box(low=0, high=255, shape=(s[1], s[0], 3))\n return env\n#gym_env_name = 'MountainCar-v0'\n#gym_env_name = 'Pendulum-v0'\n#gym_env_name = 'Acrobot-v1'\n#gym_env_name = 'CartPole-v0'\n#gym_env_name = 'FlappyBird-v0'\n#gym_env_name = 'PixelCopter-v0'\n#gym_env_name = 'Snake-v0'\ngym_env_name = 'SpaceInvadersDeterministic-v4'\nenv_factory = GymFactory(gym_env_name)\n\n#env = RL.envs.ContextualBandit(3,4)\nenv = env_factory.make()\n\n#agent = RL.Agents.HumanAgent(\"my agent\", env)\n#agent = RL.Agents.RandomDiscreteActionAgent(\"random agent\", env, window_mode = True)\nagent = RL.Agents.A3C('A3C agent 256 256 ' + gym_env_name, env_factory, is_deterministic = False, use_gpu = False, input_is_image = True, window_mode = False)\nagent.render = False\nagent.run(train = True, restore = False, indefinitely = True)\n#agent.run(train = False, restore = True, indefinitely = True) ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"402661403","text":"from pathlib import Path\n\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nfrom ...api_doc import ApiDoc\nfrom ...helpers import ExampleContainer, HighlightedSource\nfrom ...metadata import get_component_metadata\nfrom .dropdown import button_group as button_group_dropdown\nfrom .simple import button_group as button_group_simple\nfrom .size import button_groups as button_group_size\nfrom .vertical import button_group as button_group_vertical\n\nHERE = Path(__file__).parent\n\nbutton_group_simple_source = (HERE / \"simple.py\").read_text()\nbutton_group_size_source = (HERE / \"size.py\").read_text()\nbutton_group_dropdown_source = (HERE / \"dropdown.py\").read_text()\nbutton_group_vertical_source = (HERE / \"vertical.py\").read_text()\n\ncontent = [\n html.H2(\"Button group\", className=\"display-4\"),\n html.P(\n dcc.Markdown(\n \"Group a series of buttons on a single line with the \"\n \"`ButtonGroup` component.\"\n ),\n className=\"lead\",\n ),\n html.H4(\"Simple example\"),\n html.P(\n dcc.Markdown(\"Wrap a list of `Button` components with `ButtonGroup`.\")\n ),\n ExampleContainer(button_group_simple),\n HighlightedSource(button_group_simple_source),\n html.H4(\"Size\"),\n html.P(\n dcc.Markdown(\n \"Instead of setting the `size` prop of each button in the group, \"\n \"you can set the `size` prop of the `ButtonGroup` to modify the \"\n \"size of all buttons in the group.\"\n )\n ),\n ExampleContainer(button_group_size),\n HighlightedSource(button_group_size_source),\n html.H4(\"Dropdown\"),\n html.P(\n dcc.Markdown(\n \"As well as `Button` you can include `DropdownMenu` in your \"\n \"button groups by setting `group=True`.\"\n )\n ),\n ExampleContainer(button_group_dropdown),\n HighlightedSource(button_group_dropdown_source),\n html.H4(\"Vertical variation\"),\n html.P(\n dcc.Markdown(\n \"Stack buttons in the `ButtonGroup` vertically by setting \"\n \"`vertical=True`.\"\n )\n ),\n ExampleContainer(button_group_vertical),\n HighlightedSource(button_group_vertical_source),\n ApiDoc(get_component_metadata(\"src/components/ButtonGroup.js\")),\n]\n","sub_path":"docs/components_page/components/button_group/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"22693771","text":"class AlgModel:\n def __init__(self, config=None):\n if not config:\n config = cfg.load_config(config_path)\n self.config = config\n self.device = torch.device(0)\n self.load()\n\n def load(self):\n device = self.device\n config = self.config\n\n model = AlgebraicTriangulationNet(config, device=device).to(device)\n state_dict = torch.load(config.model.checkpoint)\n\n for key in list(state_dict.keys()):\n new_key = key.replace(\"module.\", \"\")\n state_dict[new_key] = state_dict.pop(key)\n\n model.load_state_dict(state_dict, strict=True)\n model.eval()\n\n self.model = model\n\n def infer(self, cameras, images):\n keypoints_3d_pred, keypoints_2d_pred, heatmaps_pred, confidences_pred \\\n = self.model(images, cameras, None)\n prediction = edict()\n prediction.d3 = keypoints_3d_pred\n prediction.d2 = keypoints_2d_pred\n return prediction\n","sub_path":"mocap/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"651920060","text":"import sys\ndef RollingHashMatch(text, pattern):\n base = 1007 # 基数 \n h = 10**9+7 #除数\n t_len = len(text)\n p_len = len(pattern)\n t_hash = p_hash = 0\n base_l = 1\n for i in range(p_len):\n base_l *= base\n base_l = base_l%h\n #print('base_l',base_l)\n #patternとtextの最初のp_len文字に関するハッシュ値を計算\n H_p = H_t = 0\n for i in range(p_len):\n #print('pattern[i]',i,ord(pattern[i]))\n #print('text[i]',i,ord(text[i]))\n H_p = (H_p*base + ord(pattern[i]))%h\n H_t = (H_t*base + ord(text[i]))%h\n #print('H_p',H_p,'H_t',H_t)\n for i in range(t_len - p_len+1):\n #print('2nd i',i)\n if H_p == H_t:\n #print('H_p',H_p,'H_t',H_t)\n print(i)\n if i+p_len < t_len:\n H_t = (H_t*base - base_l*ord(text[i]) + ord(text[i+p_len]))%h\n #print('text[i]',text[i],'text[i+p_len]',text[i+p_len])\n #print('2nd elif H_p',H_p,'H_t',H_t)\nS = list(input())\nT = list(input())\n#print(S)\n#print(T)\nRollingHashMatch(S,T)\n","sub_path":"5-b.py","file_name":"5-b.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"34628324","text":"from AnyGUI.xGUI import *\nxGUI(Environment = \"qt\")\n'''\nPackage in AnyGUI\n-------------------\nfrom AnyGUI.fltkGUI import * #FLTK GUI\nfrom AnyGUI.tkGUI import * #Tkinter GUI\nfrom AnyGUI.wxGUI import * #wxPython GUI\nfrom AnyGUI.gtkGUI import * #GTK GUI\nfrom AnyGUI.qtGUI import * #QtPy GUI\n\nArgumented evironment change\n-------------------------\nxGUI(Environment = \"x\")\nEnvironment x will in\n wx : wxPython \n fltk : Fast Light Toolkit \n gtk : GTK Py \n qt : PyQT \n tk : TKinter \n'''\n\n\n#Functions bind to button events\ndef SubmitButtonClick(event=None):\n report = \" Your city is \"+valuelist.getValue()+\"\\n\"\n if(checkbox1.getValue()):\n report = report + \" you have read the code\\n\"\n else:\n report = report + \" you have not read the code\\n\"\n\n if(checkbox2.getValue()):\n report = report + \" you have read the documentation\\n\"\n else:\n report = report + \" you have not read the documentation\\n\"\n\n report = report + \" you are \"+rb1.getValue()+\"\\n\"\n report = report + \" you need \"+rb2.getValue()+\"\\n\"\n\n textarea.appendText(\"_______________________\\n\"+report+\"\\n\\n\")\n return True \n\ndef AboutButtonClick(event=None):\n textarea.setText(\"Created by wxGUI -v1.0\\nAuthor : Arink Verma\\n\\nhttp://10.1.0.140/trac/wiki/ArinkVerma\\n\")\n return True\n\n\n\n#Constructor canvas\ncanvas = Canvas(1, 'wxGUI -v1.0 | ArinkVerma' ,510,300)\n\n\n#Dropdown valuelist\ncities = ['New Delhi', 'Mumbai', 'Ropar', 'Lucknow', 'Chandigrah', 'Wasseypur', 'Jaipur' ]\nvaluelist = ValueList(cities,10,10,200,20,\"